file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
OpenTopicIn.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/navigate/OpenTopicIn.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * */ package org.wandora.application.tools.navigate; import java.util.Iterator; import javax.swing.Icon; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.application.gui.topicpanels.TopicPanel; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.exceptions.OpenTopicNotSupportedException; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; /** * * @author akivela */ public class OpenTopicIn extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; public final static int ASK_USER = 100; public final static int SOLVE_USING_CONTEXT = 102; public int options = SOLVE_USING_CONTEXT; private TopicPanel topicPanel = null; /** Creates a new instance of OpenTopicIn */ public OpenTopicIn(TopicPanel tp) { topicPanel = tp; } public OpenTopicIn(TopicPanel tp, Context preferredContext) { topicPanel = tp; setContext(preferredContext); } public OpenTopicIn(TopicPanel tp, int preferredOptions) { topicPanel = tp; this.options = preferredOptions; } @Override public void execute(Wandora wandora, Context context) throws TopicMapException { Iterator contextTopics = context.getContextObjects(); if(options == SOLVE_USING_CONTEXT && contextTopics != null && contextTopics.hasNext()) { Topic t = (Topic) contextTopics.next(); if(t != null) { if(topicPanel != null) { try { topicPanel.open(t); wandora.addToHistory(t); } catch(OpenTopicNotSupportedException ex) { wandora.handleError(ex); } } else { wandora.openTopic(t); } } else { WandoraOptionPane.showMessageDialog(wandora, "Can't open a topic. Select a valid topic first.", "Can't open a topic", WandoraOptionPane.WARNING_MESSAGE); } } else { if(topicPanel != null) { Topic t = wandora.showTopicFinder(); if(t != null) { try { topicPanel.open(t); wandora.addToHistory(t); } catch (OpenTopicNotSupportedException ex) { wandora.handleError(ex); } } } else { Topic t = wandora.showTopicFinder(); if(t != null) { wandora.openTopic(t); } } } } @Override public String getName() { return "Open topic in"; } @Override public String getDescription() { return "Open selected topic in given topic panel."; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/topic_open.png"); } @Override public boolean requiresRefresh() { return true; } @Override public boolean runInOwnThread() { return false; } }
4,293
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
CollapseTool.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/graph/CollapseTool.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * CollapseTool.java * * Created on 6.6.2007, 15:21 * */ package org.wandora.application.tools.graph; import java.util.HashSet; import java.util.Iterator; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.application.contexts.GraphNodeContext; import org.wandora.application.gui.topicpanels.graphpanel.TopicMapGraphPanel; import org.wandora.application.gui.topicpanels.graphpanel.VEdge; import org.wandora.application.gui.topicpanels.graphpanel.VModel; import org.wandora.application.gui.topicpanels.graphpanel.VNode; import org.wandora.utils.Tuples.T2; /** * * @author olli */ public class CollapseTool extends AbstractGraphTool { private static final long serialVersionUID = 1L; private int depth; public CollapseTool(TopicMapGraphPanel gp) { this(gp, 1); } public CollapseTool(TopicMapGraphPanel gp, int depth) { super(gp); this.setContext(new GraphNodeContext()); this.depth=depth; } @Override public String getName(){ if(depth==1) return "Collapse node"; else return "Collapse nodes "+depth+" links deep"; } public void collapse(VNode vn,VModel model, HashSet<VNode> processed,int depth){ processed.add(vn); if(depth>1){ for(VEdge edge : vn.getEdges()){ T2<VNode,VNode> ns=edge.getNodes(); VNode other=null; if(ns.e1.equals(vn)) other=ns.e2; else if(ns.e2.equals(vn)) other=ns.e1; if(!processed.contains(other)) collapse(other,model,processed,depth-1); } } model.collapseNode(vn); } @Override public void executeSynchronized(Wandora wandora, Context context) { if(context != null) { VNode vn = null; for(Iterator iter=context.getContextObjects(); iter.hasNext(); ) { try { vn = (VNode) iter.next(); //TopicMapGraphPanel panel = vn.getPanel(); VModel model = vn.getModel(); if(vn != null) { if(depth==1) model.collapseNode(vn); else { collapse(vn,model,new HashSet<VNode>(),depth); } } } catch (Exception e) { singleLog(e); } } } } }
3,330
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ConnectNodesTool.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/graph/ConnectNodesTool.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * ConnectNodesTool.java * * Created on 16.7.2007, 14:43 * */ package org.wandora.application.tools.graph; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.application.gui.topicpanels.graphpanel.TopicMapGraphPanel; /** * * @author olli */ public class ConnectNodesTool extends AbstractGraphTool { private static final long serialVersionUID = 1L; /** Creates a new instance of ConnectNodesTool */ public ConnectNodesTool(TopicMapGraphPanel gp) { super(gp); } @Override public String getName(){ return "Connect visible nodes"; } public void executeSynchronized(Wandora admin, Context context) { solveModel(admin,context).connectAllNodes(); } }
1,586
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ChangeNodeMass.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/graph/ChangeNodeMass.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * ChangeNodeMass.java * */ package org.wandora.application.tools.graph; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.GraphNodeContext; import org.wandora.application.gui.topicpanels.graphpanel.AbstractNode; import org.wandora.application.gui.topicpanels.graphpanel.TopicMapGraphPanel; /** * * @author akivela */ public class ChangeNodeMass extends AbstractSliderTool implements WandoraTool { private static final long serialVersionUID = 1L; /** Creates a new instance of ChangeStiffness */ public ChangeNodeMass(TopicMapGraphPanel gp) { super(gp); this.setContext(new GraphNodeContext()); } @Override public String getName(){ return "Change node mass of graph topic panel"; } @Override protected int getMinValue(TopicMapGraphPanel graphPanel) { return 1; } @Override protected int getMaxValue(TopicMapGraphPanel graphPanel) { return 100; } @Override protected int getDefaultValue(TopicMapGraphPanel graphPanel) { return scaleToInteger(AbstractNode.massMultiplier, 0.1, 10.0, 1, 100); } @Override protected void setValue(TopicMapGraphPanel graphPanel, int newValue) { AbstractNode.massMultiplier = scaleToDouble(newValue, 1, 100, 0.1, 10.0); } }
2,175
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ToggleViewFilterInfo.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/graph/ToggleViewFilterInfo.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * ToggleViewFilterInfo.java * * */ package org.wandora.application.tools.graph; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.contexts.GraphNodeContext; import org.wandora.application.gui.topicpanels.graphpanel.TopicMapGraphPanel; /** * * @author akivela */ public class ToggleViewFilterInfo extends AbstractGraphTool implements WandoraTool { private static final long serialVersionUID = 1L; /** Creates a new instance of ToggleViewFilterInfo */ public ToggleViewFilterInfo(TopicMapGraphPanel gp) { super(gp); this.setContext(new GraphNodeContext()); } @Override public String getName(){ return "Toggle visibility of node and edge filter info"; } @Override public String getDescription(){ return "Toggle visibility of node and edge filter info. If selected, "+ "information about node and edge filters is viewed beside the graph."; } public void executeSynchronized(Wandora wandora, Context context) { TopicMapGraphPanel graphPanel = this.solveGraphPanel(wandora, context); if(graphPanel != null) { graphPanel.setViewFilterInfo(!graphPanel.getViewFilterInfo()); } } @Override public boolean requiresRefresh() { return true; } }
2,246
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AbstractSliderTool.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/graph/AbstractSliderTool.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * AbstractSliderTool.java * */ package org.wandora.application.tools.graph; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JPanel; import javax.swing.JWindow; import javax.swing.border.LineBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.gui.UIConstants; import org.wandora.application.gui.simple.SimpleLabel; import org.wandora.application.gui.simple.SimpleSlider; import org.wandora.application.gui.simple.SimpleToggleButton; import org.wandora.application.gui.topicpanels.graphpanel.TopicMapGraphPanel; /** * * @author akivela */ public abstract class AbstractSliderTool extends AbstractGraphTool implements WandoraTool, ChangeListener, MouseListener { private static final long serialVersionUID = 1L; private TopicMapGraphPanel graphPanel = null; private JWindow sliderPopup = null; private SimpleSlider slider = null; private SimpleLabel sliderLabel = null; private Component referenceComponent = null; public AbstractSliderTool(TopicMapGraphPanel gp) { super(gp); graphPanel = gp; } private void initializeSlider(TopicMapGraphPanel gp) { int minValue = getMinValue(gp); int maxValue = getMaxValue(gp); int defaultValue = getDefaultValue(gp); if(defaultValue < minValue) defaultValue = minValue; if(defaultValue > maxValue) defaultValue = maxValue; slider = new SimpleSlider(SimpleSlider.HORIZONTAL, minValue, maxValue, defaultValue); sliderLabel = new SimpleLabel(); sliderPopup = new JWindow(); slider.setPreferredSize(new Dimension(120, 24)); slider.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); sliderLabel.setFont(UIConstants.smallButtonLabelFont); sliderLabel.setPreferredSize(new Dimension(30, 24)); sliderLabel.setHorizontalAlignment(SimpleLabel.CENTER); JPanel panel = new JPanel(); panel.setBorder(new LineBorder(UIConstants.defaultBorderShadow)); panel.setLayout(new BorderLayout(2,2)); panel.add(slider, BorderLayout.CENTER); panel.add(sliderLabel, BorderLayout.EAST); sliderPopup.setLayout(new BorderLayout(2,2)); sliderPopup.add(panel, BorderLayout.CENTER); sliderPopup.setSize(150, 24); // sliderPopup.addMouseListener(this); sliderPopup.setAlwaysOnTop(true); slider.addChangeListener(this); slider.addMouseListener(this); } @Override public void execute(Wandora wandora, Context context) { // graphPanel = this.solveGraphPanel(wandora, context); if(graphPanel != null) { ActionEvent ae = context.getContextEvent(); Object o = ae.getSource(); if(o instanceof Component) { referenceComponent = (Component) o; if(sliderPopup == null) initializeSlider(graphPanel); if(!getSliderVisible()) { setSliderRange(getMinValue(graphPanel),getMaxValue(graphPanel)); setSliderValue(getDefaultValue(graphPanel)); setSliderLocation(referenceComponent); setSliderVisible(true); } else { setSliderVisible(false); } } } } @Override public void executeSynchronized(Wandora wandora, Context context) { // NOTHING HERE! } private void setSliderLocation(Component referenceComponent) { if(referenceComponent != null) { Point loc = referenceComponent.getLocationOnScreen(); loc = new Point(loc.x+32, loc.y); sliderPopup.setLocation(loc); } } private boolean getSliderVisible() { if(sliderPopup != null) { return sliderPopup.isVisible(); } else { return false; } } private void setSliderVisible(boolean v) { if(sliderPopup != null) { sliderPopup.setVisible(v); } } private void setSliderValue(int value) { if(slider != null) { if(value < slider.getMinimum()) value = slider.getMinimum(); if(value > slider.getMaximum()) value = slider.getMaximum(); slider.setValue(value); } if(sliderLabel != null) { sliderLabel.setText(""+value); } } private void setSliderRange(int minValue, int maxValue) { if(slider != null) { slider.setMinimum(minValue); slider.setMaximum(maxValue); } } @Override public void stateChanged(ChangeEvent e) { SimpleSlider source = (SimpleSlider)e.getSource(); int newValue = (int)source.getValue(); if(sliderLabel != null) sliderLabel.setText(""+newValue); if(!source.getValueIsAdjusting()) { setValue(graphPanel, newValue); } } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { sliderPopup.setVisible(false); if(referenceComponent != null && referenceComponent instanceof SimpleToggleButton) { ((SimpleToggleButton) referenceComponent).setSelected(false); } } @Override public void mouseClicked(MouseEvent e) { } protected abstract int getDefaultValue(TopicMapGraphPanel graphPanel); protected abstract void setValue(TopicMapGraphPanel graphPanel, int newValue); protected abstract int getMinValue(TopicMapGraphPanel graphPanel); protected abstract int getMaxValue(TopicMapGraphPanel graphPanel); protected double scaleToDouble(int val, int min, int max, double mind, double maxd) { double vald = mind + (maxd-mind) * ((val-min*1.0) / (max-min*1.0)); return vald; } protected int scaleToInteger(double vald, double mind, double maxd, int min, int max) { int val = (int) Math.round(min + (max-min) * ((vald-mind) / (maxd-mind))); return val; } @Override public boolean requiresRefresh() { return false; } }
7,671
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ExpandNodesRecursivelyTool.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/graph/ExpandNodesRecursivelyTool.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * ExpandNodesRecursivelyTool.java * * Created on 12.6.2007, 11:17 * */ package org.wandora.application.tools.graph; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.application.contexts.GraphNodeContext; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.application.gui.topicpanels.graphpanel.TopicMapGraphPanel; import org.wandora.application.gui.topicpanels.graphpanel.VEdge; import org.wandora.application.gui.topicpanels.graphpanel.VModel; import org.wandora.application.gui.topicpanels.graphpanel.VNode; import org.wandora.topicmap.Topic; import org.wandora.utils.Tuples.T2; /** * * @author olli, akivela */ public class ExpandNodesRecursivelyTool extends AbstractGraphTool { private static final long serialVersionUID = 1L; private int depth; private HashSet<VNode> openNodes = null; /** Creates a new instance of ExpandNodesRecursivelyTool */ public ExpandNodesRecursivelyTool(TopicMapGraphPanel gp) { super(gp); this.setContext(new GraphNodeContext()); depth=-1; } public ExpandNodesRecursivelyTool(TopicMapGraphPanel gp, int depth) { super(gp); this.setContext(new GraphNodeContext()); this.depth=depth; } @Override public String getName(){ return "Recursive expand tool"; } public void expandRecursive(VNode node,VModel model,int depth){ if(!openNodes.contains(node)) { openNodes.add(node); model.openNode(node); if(depth>0){ for(VEdge e : node.getEdges()){ T2<VNode,VNode> ns=e.getNodes(); if(!ns.e1.equals(node)) expandRecursive(ns.e1,model,depth-1); if(!ns.e2.equals(node)) expandRecursive(ns.e2,model,depth-1); } } } } public void executeSynchronized(Wandora wandora, Context context) {} @Override public void execute(Wandora wandora, Context context){ if(context != null) { Iterator contextObjects = context.getContextObjects(); if(!contextObjects.hasNext()) { ArrayList<Topic> adhocContext = new ArrayList<>(); adhocContext.add( wandora.getOpenTopic() ); contextObjects = adhocContext.iterator(); } if(contextObjects.hasNext()) { int d=depth; if(d==-1){ String in=WandoraOptionPane.showInputDialog(wandora,"Enter recursion depth"); try { d=Integer.parseInt(in); } catch(NumberFormatException nfe){} if(d<0) { WandoraOptionPane.showMessageDialog(wandora,"Invalid depth"); return; } } try { synchronized(solveGraphPanel(wandora,context)) { VNode node = null; VModel model = null; openNodes = new LinkedHashSet<>(); while(contextObjects.hasNext()) { node = (VNode) contextObjects.next(); if(node != null) { model = node.getModel(); if(model != null) { expandRecursive(node,node.getModel(),d); } } } } } catch(Exception e) { log(e); } openNodes = null; // Release the node set for garbage collector; } } } }
4,783
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AbstractGraphTool.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/graph/AbstractGraphTool.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * AbstractGraphTool.java * * Created on 13.6.2007, 15:32 * */ package org.wandora.application.tools.graph; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.gui.topicpanels.DockingFramePanel; import org.wandora.application.gui.topicpanels.GraphTopicPanel; import org.wandora.application.gui.topicpanels.TopicPanel; import org.wandora.application.gui.topicpanels.graphpanel.TopicMapGraphPanel; import org.wandora.application.gui.topicpanels.graphpanel.VModel; import org.wandora.application.gui.topicpanels.graphpanel.VNode; import org.wandora.application.tools.AbstractWandoraTool; /** * * @author akivela */ public abstract class AbstractGraphTool extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; private TopicMapGraphPanel graphPanel = null; /** Creates a new instance of AbstractGraphTool */ public AbstractGraphTool(TopicMapGraphPanel gp) { graphPanel = gp; } public AbstractGraphTool() { } @Override public void execute(Wandora wandora, Context context){ try { synchronized(solveGraphPanel(wandora,context)){ executeSynchronized(wandora,context); } } catch(Exception e) { System.out.println("Exception '"+e.toString()+"' captured in abstract graph tool."); singleLog(e); } } public abstract void executeSynchronized(Wandora wandora, Context context); public TopicMapGraphPanel solveGraphPanel(Wandora wandora, Context context) { if(graphPanel != null) { return graphPanel; } if(context != null) { Object contextSource = context.getContextSource(); if(contextSource != null && contextSource instanceof GraphTopicPanel) { return ((GraphTopicPanel)contextSource).getGraphPanel(); } } if(wandora != null) { TopicPanel topicPanel = wandora.getTopicPanel(); if(topicPanel != null && topicPanel instanceof DockingFramePanel) { topicPanel = ((DockingFramePanel) topicPanel).getCurrentTopicPanel(); } if(topicPanel != null && topicPanel instanceof GraphTopicPanel) { return ((GraphTopicPanel)topicPanel).getGraphPanel(); } } return null; } public VModel solveModel(Wandora wandora, Context context){ TopicMapGraphPanel panel=solveGraphPanel(wandora,context); if(panel==null) return null; else return panel.getModel(); } public TopicMapGraphPanel solveGraphPanel(VNode vnode) { if(vnode != null) { return vnode.getPanel(); } return null; } @Override public boolean allowMultipleInvocations() { return false; } }
3,811
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ChangeFramerate.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/graph/ChangeFramerate.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * ChangeFramerate.java * */ package org.wandora.application.tools.graph; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.GraphNodeContext; import org.wandora.application.gui.topicpanels.graphpanel.TopicMapGraphPanel; /** * * @author akivela */ public class ChangeFramerate extends AbstractSliderTool implements WandoraTool { private static final long serialVersionUID = 1L; /** Creates a new instance of ChangeFramerate */ public ChangeFramerate(TopicMapGraphPanel gp) { super(gp); this.setContext(new GraphNodeContext()); } @Override public String getName(){ return "Change framerate for graph topic panel"; } @Override protected int getMinValue(TopicMapGraphPanel graphPanel) { return 5; } @Override protected int getMaxValue(TopicMapGraphPanel graphPanel) { return 100; } @Override protected int getDefaultValue(TopicMapGraphPanel graphPanel) { if(graphPanel != null) { return (int) graphPanel.getFramerate(); } else { return 24; } } @Override protected void setValue(TopicMapGraphPanel graphPanel, int newValue) { if(graphPanel != null) { synchronized(graphPanel) { graphPanel.setFramerate(newValue); } } } }
2,240
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ChangeScale.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/graph/ChangeScale.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * ChangeFramerate.java * */ package org.wandora.application.tools.graph; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.GraphNodeContext; import org.wandora.application.gui.topicpanels.graphpanel.TopicMapGraphPanel; import org.wandora.application.gui.topicpanels.graphpanel.projections.HyperbolicProjection; import org.wandora.application.gui.topicpanels.graphpanel.projections.Projection; /** * * @author akivela */ public class ChangeScale extends AbstractSliderTool implements WandoraTool { private static final long serialVersionUID = 1L; private int key = HyperbolicProjection.SCALE; private int minVal = 1; private int maxVal = 100; /** Creates a new instance of ChangeScale */ public ChangeScale(TopicMapGraphPanel gp) { super(gp); this.setContext(new GraphNodeContext()); } @Override public String getName(){ return "Change scale of a graph topic panel"; } @Override protected int getMinValue(TopicMapGraphPanel graphPanel) { return minVal; } @Override protected int getMaxValue(TopicMapGraphPanel graphPanel) { return maxVal; } @Override protected int getDefaultValue(TopicMapGraphPanel graphPanel) { if(graphPanel != null) { Projection projection = graphPanel.getProjection(); double val = projection.get(key); int defaultValue = scaleToInteger(val, 0.05, 5.0, minVal, maxVal); if(defaultValue < minVal) defaultValue = minVal; if(defaultValue > maxVal) defaultValue = maxVal; return defaultValue; } else { return minVal; } } @Override protected void setValue(TopicMapGraphPanel graphPanel, int newValue) { if(graphPanel != null) { synchronized(graphPanel) { Projection projection = graphPanel.getProjection(); double vald = scaleToDouble(newValue, minVal, maxVal, 0.05, 5.0); projection.set(key, vald); } } } }
2,988
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SetMouseTool.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/graph/SetMouseTool.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * SetMouseTool.java * * Created on 16.7.2007, 14:52 * */ package org.wandora.application.tools.graph; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.contexts.GraphNodeContext; import org.wandora.application.gui.topicpanels.graphpanel.TopicMapGraphPanel; /** * * @author akivela */ public class SetMouseTool extends AbstractGraphTool implements WandoraTool { private static final long serialVersionUID = 1L; private int myMouseTool = -1; /** Creates a new instance of ToggleAntialiasTool */ public SetMouseTool(TopicMapGraphPanel gp, int predefinedMouseTool) { super(gp); this.setContext(new GraphNodeContext()); this.myMouseTool = predefinedMouseTool; } public int getMouseTool(){return myMouseTool;} @Override public String getName() { if(myMouseTool != -1) { return TopicMapGraphPanel.getToolName(myMouseTool); } return "Set mouse tool for graph panel"; } @Override public String getDescription() { if(myMouseTool != -1) { return TopicMapGraphPanel.getToolDescription(myMouseTool); } return super.getDescription(); } public void executeSynchronized(Wandora wandora, Context context) { TopicMapGraphPanel graphPanel = this.solveGraphPanel(wandora, context); if(graphPanel != null) { graphPanel.setMouseTool(myMouseTool); } } }
2,400
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
CenterCurrentTopic.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/graph/CenterCurrentTopic.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * CenterCurrentGraph.java * * Created on 18.7.2007, 16:50 * */ package org.wandora.application.tools.graph; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.contexts.GraphNodeContext; import org.wandora.application.gui.topicpanels.graphpanel.TopicMapGraphPanel; /** * * @author akivela */ public class CenterCurrentTopic extends AbstractGraphTool implements WandoraTool { private static final long serialVersionUID = 1L; /** Creates a new instance of CenterCurrentTopic */ public CenterCurrentTopic(TopicMapGraphPanel gp) { super(gp); this.setContext(new GraphNodeContext()); } @Override public String getName(){ return "Center current topic node"; } @Override public void executeSynchronized(Wandora wandora, Context context) { TopicMapGraphPanel graphPanel = this.solveGraphPanel(wandora, context); if(graphPanel != null) { graphPanel.setMouseFollowNode(graphPanel.getRootNode()); } } }
1,945
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ExpandNodeTool.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/graph/ExpandNodeTool.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * ExpandNodeTool.java * * Created on 6.6.2007, 15:16 * */ package org.wandora.application.tools.graph; import java.util.Iterator; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.application.contexts.GraphNodeContext; import org.wandora.application.gui.topicpanels.graphpanel.TopicMapGraphPanel; import org.wandora.application.gui.topicpanels.graphpanel.VModel; import org.wandora.application.gui.topicpanels.graphpanel.VNode; /** * * @author olli */ public class ExpandNodeTool extends AbstractGraphTool { private static final long serialVersionUID = 1L; public ExpandNodeTool(TopicMapGraphPanel gp) { super(gp); this.setContext(new GraphNodeContext()); } @Override public String getName(){ return "Open graph node"; } public void executeSynchronized(Wandora wandora, Context context) { VModel model = null; VNode node = null; for(Iterator iter = context.getContextObjects(); iter.hasNext(); ) { try { node = (VNode) iter.next(); if(node != null) { model = node.getModel(); if(model != null) { model.openNode(node); } } } catch(Exception e) { singleLog(e); } } } }
2,239
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ChangeCurvature.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/graph/ChangeCurvature.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * ChangeFramerate.java * */ package org.wandora.application.tools.graph; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.GraphNodeContext; import org.wandora.application.gui.topicpanels.graphpanel.TopicMapGraphPanel; import org.wandora.application.gui.topicpanels.graphpanel.projections.HyperbolicProjection; import org.wandora.application.gui.topicpanels.graphpanel.projections.Projection; /** * * @author akivela */ public class ChangeCurvature extends AbstractSliderTool implements WandoraTool { private static final long serialVersionUID = 1L; private int key = HyperbolicProjection.CURVATURE; private int minVal = 1; private int maxVal = 100; /** Creates a new instance of ChangeCurvature */ public ChangeCurvature(TopicMapGraphPanel gp) { super(gp); this.setContext(new GraphNodeContext()); } @Override public String getName(){ return "Change curvature of a graph topic panel"; } @Override protected int getMinValue(TopicMapGraphPanel graphPanel) { return minVal; } @Override protected int getMaxValue(TopicMapGraphPanel graphPanel) { return maxVal; } @Override protected int getDefaultValue(TopicMapGraphPanel graphPanel) { if(graphPanel != null) { Projection projection = graphPanel.getProjection(); double val = projection.get(key); int defaultValue = scaleToInteger(val, 0.5, 10.0, minVal, maxVal); if(defaultValue < minVal) defaultValue = minVal; if(defaultValue > maxVal) defaultValue = maxVal; return defaultValue; } else { return minVal; } } @Override protected void setValue(TopicMapGraphPanel graphPanel, int newValue) { if(graphPanel != null) { synchronized(graphPanel) { Projection projection = graphPanel.getProjection(); double vald = scaleToDouble(newValue, minVal, maxVal, 0.5, 10.0); projection.set(key, vald); } } } }
2,987
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ChangeStiffness.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/graph/ChangeStiffness.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * ChangeStiffness.java * */ package org.wandora.application.tools.graph; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.GraphNodeContext; import org.wandora.application.gui.topicpanels.graphpanel.AbstractEdge; import org.wandora.application.gui.topicpanels.graphpanel.TopicMapGraphPanel; /** * * @author akivela */ public class ChangeStiffness extends AbstractSliderTool implements WandoraTool { private static final long serialVersionUID = 1L; /** Creates a new instance of ChangeStiffness */ public ChangeStiffness(TopicMapGraphPanel gp) { super(gp); this.setContext(new GraphNodeContext()); } @Override public String getName(){ return "Change edge stiffness of graph topic panel"; } @Override protected int getMinValue(TopicMapGraphPanel graphPanel) { return 1; } @Override protected int getMaxValue(TopicMapGraphPanel graphPanel) { return 100; } @Override protected int getDefaultValue(TopicMapGraphPanel graphPanel) { return scaleToInteger(AbstractEdge.defaultEdgeStiffness, 0.001, 0.2, 1, 100); } @Override protected void setValue(TopicMapGraphPanel graphPanel, int newValue) { AbstractEdge.defaultEdgeStiffness = scaleToDouble(newValue, 1, 100, 0.001, 0.2); } }
2,199
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ToggleAntialiasTool.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/graph/ToggleAntialiasTool.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * ToggleAntialiasTool.java * * Created on 11.6.2007, 16:33 * */ package org.wandora.application.tools.graph; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.contexts.GraphNodeContext; import org.wandora.application.gui.topicpanels.graphpanel.TopicMapGraphPanel; /** * * @author olli */ public class ToggleAntialiasTool extends AbstractGraphTool implements WandoraTool { private static final long serialVersionUID = 1L; /** Creates a new instance of ToggleAntialiasTool */ public ToggleAntialiasTool(TopicMapGraphPanel gp) { super(gp); this.setContext(new GraphNodeContext()); } @Override public String getName(){ return "Toggle antialiasing"; } @Override public String getDescription(){ return "Change option for antialising. If selected, "+ "graph is draw smooth. Drawing smooth graphics requires more computing power."; } public void executeSynchronized(Wandora wandora, Context context) { TopicMapGraphPanel graphPanel = this.solveGraphPanel(wandora, context); //System.out.println("GRAPHPANEL: "+graphPanel); if(graphPanel != null) { graphPanel.setAntialized(!graphPanel.getAntialized()); } } @Override public boolean requiresRefresh() { return true; } }
2,280
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ToggleProjectionSettings.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/graph/ToggleProjectionSettings.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * ToggleProjectionSettings.java * * Created on 16.7.2007, 13:34 * */ package org.wandora.application.tools.graph; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.contexts.GraphNodeContext; import org.wandora.application.gui.topicpanels.graphpanel.TopicMapGraphPanel; /** * * @author akivela */ public class ToggleProjectionSettings extends AbstractGraphTool implements WandoraTool { private static final long serialVersionUID = 1L; /** Creates a new instance of ToggleProjectionSettings */ public ToggleProjectionSettings(TopicMapGraphPanel gp) { super(gp); this.setContext(new GraphNodeContext()); } @Override public String getName(){ return "Toggle projection settings"; } @Override public void executeSynchronized(Wandora wandora, Context context) { TopicMapGraphPanel graphPanel = this.solveGraphPanel(wandora, context); if(graphPanel != null) { try { graphPanel.getProjection().useNextProjectionSettings(); } catch(Exception e) { System.out.println("Exception occurred in toggle projection settings."); singleLog(e); } } } }
2,170
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ToggleFilterWindow.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/graph/ToggleFilterWindow.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * ToggleFilterWindow.java * * Created on 17.7.2007, 11:26 * */ package org.wandora.application.tools.graph; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.contexts.GraphNodeContext; import org.wandora.application.gui.topicpanels.graphpanel.TopicMapGraphPanel; /** * * @author akivela */ public class ToggleFilterWindow extends AbstractGraphTool implements WandoraTool { private static final long serialVersionUID = 1L; /** Creates a new instance of ToggleFilterWindow */ public ToggleFilterWindow(TopicMapGraphPanel gp) { super(gp); this.setContext(new GraphNodeContext()); } @Override public String getName(){ return "Toggle filter window visibility"; } public void executeSynchronized(Wandora wandora, Context context) { TopicMapGraphPanel graphPanel = this.solveGraphPanel(wandora, context); if(graphPanel != null) { graphPanel.openFilterManager(); } } }
1,916
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ToggleStaticWidthNodeBoxes.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/graph/ToggleStaticWidthNodeBoxes.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * ToggleStaticWidthNodeBoxes.java * * */ package org.wandora.application.tools.graph; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.contexts.GraphNodeContext; import org.wandora.application.gui.topicpanels.graphpanel.TopicMapGraphPanel; /** * * @author akivela */ public class ToggleStaticWidthNodeBoxes extends AbstractGraphTool implements WandoraTool { private static final long serialVersionUID = 1L; /** Creates a new instance of ToggleStaticWidthNodeBoxes */ public ToggleStaticWidthNodeBoxes(TopicMapGraphPanel gp) { super(gp); this.setContext(new GraphNodeContext()); } @Override public String getName(){ return "Toggle static vs. free width node boxes"; } @Override public String getDescription(){ return "Change option for static width node boxes. If selected, "+ "all node boxes are equal width. Mouse over expands the box to view complete node label."; } public void executeSynchronized(Wandora wandora, Context context) { TopicMapGraphPanel graphPanel = this.solveGraphPanel(wandora, context); if(graphPanel != null) { graphPanel.setCropNodeBoxes(!graphPanel.getCropNodeBoxes()); } } @Override public boolean requiresRefresh() { return true; } }
2,267
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ToggleAnimationTool.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/graph/ToggleAnimationTool.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * ToggleAnimationTool.java * * Created on 7.6.2007, 16:04 * */ package org.wandora.application.tools.graph; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.contexts.GraphNodeContext; import org.wandora.application.gui.topicpanels.graphpanel.TopicMapGraphPanel; /** * * @author olli */ public class ToggleAnimationTool extends AbstractGraphTool implements WandoraTool { private static final long serialVersionUID = 1L; /** Creates a new instance of ToggleAnimationTool */ public ToggleAnimationTool(TopicMapGraphPanel gp) { super(gp); this.setContext(new GraphNodeContext()); } @Override public String getName(){ return "Toggle graph animation"; } @Override public String getDescription(){ return "Change option for animation. If selected, "+ "graph is animated."; } public void executeSynchronized(Wandora wandora, Context context) { TopicMapGraphPanel graphPanel = this.solveGraphPanel(wandora, context); if(graphPanel != null) { graphPanel.setAnimationEnabled(!graphPanel.getAnimationEnabled()); } } @Override public boolean requiresRefresh() { return true; } }
2,166
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
CloseTopicNodesOfType.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/graph/CloseTopicNodesOfType.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * CloseTopicNodesOfType.java * * Created on 7.6.2007, 13:09 * */ package org.wandora.application.tools.graph; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.application.contexts.GraphEdgeContext; import org.wandora.application.gui.topicpanels.graphpanel.GraphFilter; import org.wandora.application.gui.topicpanels.graphpanel.Node; import org.wandora.application.gui.topicpanels.graphpanel.NodeFilter; import org.wandora.application.gui.topicpanels.graphpanel.TopicMapGraphPanel; import org.wandora.application.gui.topicpanels.graphpanel.TopicNode; import org.wandora.application.gui.topicpanels.graphpanel.VModel; import org.wandora.application.gui.topicpanels.graphpanel.VNode; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public class CloseTopicNodesOfType extends AbstractGraphTool { private static final long serialVersionUID = 1L; private Topic type; private GraphFilter filter; public CloseTopicNodesOfType(TopicMapGraphPanel gp, Topic type, NodeFilter filter) { this(gp, type,(GraphFilter)filter); } public CloseTopicNodesOfType(TopicMapGraphPanel gp, Topic type, GraphFilter filter) { super(gp); this.setContext(new GraphEdgeContext()); this.type=type; this.filter=filter; } @Override public String getName(){ try{ return "Hide nodes of type "+type.getBaseName(); }catch(TopicMapException tme){tme.printStackTrace(); return "";} } public static void hideTopicsOfType(Topic type,VModel model){ HashSet<VNode> remove=new HashSet<VNode>(); try{ for(VNode vnode : model.getNodes()){ Node n=vnode.getNode(); if(n instanceof TopicNode){ TopicNode tn=(TopicNode)n; if(tn.getTopic().isOfType(type)) remove.add(vnode); } } }catch(TopicMapException tme){tme.printStackTrace();} for(VNode vnode : remove){ model.removeNode(vnode); } } public void executeSynchronized(Wandora wandora, Context context) { VModel model = null; VNode node = null; for(Iterator iter = context.getContextObjects(); iter.hasNext(); ) { try { node = (VNode) iter.next(); if(node != null) { model = node.getModel(); if(model != null) { hideTopicsOfType(type,model); } } } catch(Exception e) { singleLog(e); } } } // ------------------------------------------------------------------------- public static ArrayList<AbstractGraphTool> makeTools(TopicMapGraphPanel gp, Node n, NodeFilter nodeFilter, ArrayList<AbstractGraphTool> tools){ if(tools==null) tools=new ArrayList<AbstractGraphTool>(); if(n instanceof TopicNode){ TopicNode tn=(TopicNode)n; try{ for(Topic type : tn.getTopic().getTypes()){ tools.add(new CloseTopicNodesOfType(gp,type,nodeFilter)); } }catch(TopicMapException tme){tme.printStackTrace();} } return tools; } }
4,351
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ToggleLabelEdges.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/graph/ToggleLabelEdges.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * ToggleAntialiasTool.java * * Created on 11.6.2007, 16:33 * */ package org.wandora.application.tools.graph; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.contexts.GraphNodeContext; import org.wandora.application.gui.topicpanels.graphpanel.TopicMapGraphPanel; /** * * @author akivela */ public class ToggleLabelEdges extends AbstractGraphTool implements WandoraTool { private static final long serialVersionUID = 1L; /** Creates a new instance of ToggleLabelEdges */ public ToggleLabelEdges(TopicMapGraphPanel gp) { super(gp); this.setContext(new GraphNodeContext()); } @Override public String getName(){ return "Toggle draw egde labels"; } @Override public String getDescription(){ return "Change option for draw egde labels. If selected, "+ "Wandora draws edge labels i.e. association types."; } public void executeSynchronized(Wandora wandora, Context context) { TopicMapGraphPanel graphPanel = this.solveGraphPanel(wandora, context); if(graphPanel != null) { graphPanel.setLabelEdges(!graphPanel.getLabelEdges()); } } @Override public boolean requiresRefresh() { return true; } }
2,198
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ToggleFreezeForMouseOverTool.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/graph/ToggleFreezeForMouseOverTool.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * ToggleFreezeForMouseOverTool.java * * */ package org.wandora.application.tools.graph; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.contexts.GraphNodeContext; import org.wandora.application.gui.topicpanels.graphpanel.TopicMapGraphPanel; /** * * @author akivela */ public class ToggleFreezeForMouseOverTool extends AbstractGraphTool implements WandoraTool { private static final long serialVersionUID = 1L; /** Creates a new instance of ToggleFreezeForMouseOverTool */ public ToggleFreezeForMouseOverTool(TopicMapGraphPanel gp) { super(gp); this.setContext(new GraphNodeContext()); } @Override public String getName(){ return "Toggle freeze while mouse over"; } @Override public String getDescription(){ return "Change option for freeze while mouse over. If selected, "+ "graph animation stops when mouse pointer is over a node or an edge."; } public void executeSynchronized(Wandora wandora, Context context) { TopicMapGraphPanel graphPanel = this.solveGraphPanel(wandora, context); //System.out.println("GRAPHPANEL: "+graphPanel); if(graphPanel != null) { graphPanel.setFreezeForMouseOver(!graphPanel.getFreezeForMouseOver()); } } @Override public boolean requiresRefresh() { return true; } }
2,328
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
CloseTopicNode.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/graph/CloseTopicNode.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * CloseNodeTopic.java * * Created on 7.6.2007, 11:24 * */ package org.wandora.application.tools.graph; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.application.contexts.GraphNodeContext; import org.wandora.application.gui.topicpanels.graphpanel.TopicMapGraphPanel; import org.wandora.application.gui.topicpanels.graphpanel.VModel; import org.wandora.application.gui.topicpanels.graphpanel.VNode; /** * * @author olli, akivela */ public class CloseTopicNode extends AbstractGraphTool { private static final long serialVersionUID = 1L; private boolean allButCurrent; public CloseTopicNode(TopicMapGraphPanel gp) { this(gp, false); } public CloseTopicNode(TopicMapGraphPanel gp, boolean allButCurrent) { super(gp); this.allButCurrent=allButCurrent; this.setContext(new GraphNodeContext(gp)); } @Override public String getName(){ if(allButCurrent) return "Close all topic nodes but this"; else return "Close topic node"; } @Override public void executeSynchronized(Wandora wandora, Context context) { VModel model = null; VNode node = null; if(!allButCurrent){ for(Iterator iter = context.getContextObjects(); iter.hasNext(); ) { try { node = (VNode) iter.next(); if(node != null) { model = node.getModel(); if(model != null) { model.removeNode(node); } } } catch(Exception e) { singleLog(e); } } } else{ HashSet<VNode> selected=new HashSet<VNode>(); for(Iterator iter = context.getContextObjects(); iter.hasNext(); ) { try { node = (VNode) iter.next(); if(node != null) selected.add(node); } catch(Exception e) { singleLog(e); } } model=solveModel(wandora, context); ArrayList<VNode> all=new ArrayList<VNode>(model.getNodes()); for(VNode vn : all){ if(!selected.contains(vn)) model.removeNode(vn); } } } }
3,331
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
GraphGMLExport.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/graph/export/GraphGMLExport.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.wandora.application.tools.graph.export; import java.awt.Color; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import javax.swing.Icon; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.UIConstants; import org.wandora.application.gui.simple.SimpleFileChooser; import org.wandora.application.gui.topicpanels.graphpanel.TopicMapGraphPanel; import org.wandora.application.gui.topicpanels.graphpanel.VEdge; import org.wandora.application.gui.topicpanels.graphpanel.VModel; import org.wandora.application.gui.topicpanels.graphpanel.VNode; import org.wandora.application.tools.graph.AbstractGraphTool; import org.wandora.utils.IObox; import org.wandora.utils.Tuples.T2; /** * * @author akivela */ public class GraphGMLExport extends AbstractGraphTool { private static final long serialVersionUID = 1L; @Override public String getName() { return "Graph view GML export"; } @Override public String getDescription() { return "Export graph in Graph panel as a GML formatted file"; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/export_graph.png"); } @Override public boolean requiresRefresh() { return false; } @Override public void executeSynchronized(Wandora admin, Context context) { // NOTHING HERE! } @Override public void execute(Wandora wandora, Context context) { TopicMapGraphPanel graphPanel = this.solveGraphPanel(wandora, context); if(graphPanel != null) { VModel model = graphPanel.getModel(); if(model != null) { SimpleFileChooser chooser=UIConstants.getFileChooser(); chooser.setDialogTitle("Export graph view..."); if(chooser.open(wandora, "Export")==SimpleFileChooser.APPROVE_OPTION){ setDefaultLogger(); File file = chooser.getSelectedFile(); String fileName = file.getName(); // --- Finally write graph to the file OutputStream out = null; try { file = IObox.addFileExtension(file, "gml"); // Ensure file extension exists! fileName = file.getName(); // Updating filename if file has changed! out = new FileOutputStream(file); log("Exporting graph view to '"+fileName+"'."); exportGraph(out, model); out.close(); log("Ready."); } catch(Exception e) { log(e); try { if(out != null) out.close(); } catch(Exception e2) { log(e2); } } } setState(WAIT); } } } public void exportGraph(OutputStream out, VModel model) { PrintWriter writer = null; try { writer = new PrintWriter(new OutputStreamWriter(out, "ISO-8859-1")); } catch (UnsupportedEncodingException ex) { log("Exception while instantiating PrintWriter with ISO-8859-1 character encoding. Using default encoding."); writer = new PrintWriter(new OutputStreamWriter(out)); } writer.println("Creator \"Wandora\""); writer.println("graph ["); writer.println(" label "+makeString("Wandora graph panel")); writer.println(" directed 0"); for(VNode n : model.getNodes()) { printNode(n, writer); } T2<VNode,VNode> nodes; for(VEdge e : model.getEdges()) { nodes=e.getNodes(); if(!nodes.e1.equals(nodes.e2)) { printEdge(e, writer); } } writer.println("]"); // graph writer.flush(); writer.close(); } protected void printNode(VNode node, PrintWriter writer) { if(node == null) return; println(writer, " node ["); println(writer, " id "+node.getID()); println(writer, " label "+makeString(node.getNode().getLabel())); println(writer, " ]"); } protected void printEdge(VEdge edge, PrintWriter writer) { if(edge == null) return; T2<VNode,VNode> nodes = edge.getNodes(); writer.println(" edge ["); writer.println(" label "+makeString(edge.getEdge().getLabel())); writer.println(" source "+nodes.e1.getID()); writer.println(" target "+nodes.e2.getID()); writer.println(" ]"); } protected void print(PrintWriter writer, String str) { writer.print(str); } protected void println(PrintWriter writer, String str) { writer.println(str); } protected String makeString(String s) { if(s == null) return null; s = s.substring(0,Math.min(s.length(), 240)); s = s.replaceAll("\\\n", " "); s = s.replaceAll("\\\r", ""); s = s.replaceAll("\\&", "&amp;"); s = s.replaceAll("\\\"", "&quot;"); return "\""+s+"\""; } protected String makeString(Color c) { if(c == null) return ""; int red = c.getRed(); int green = c.getGreen(); int blue = c.getBlue(); StringBuilder s = new StringBuilder(""); s.append("#"); s.append(Integer.toHexString(red)); s.append(Integer.toHexString(green)); s.append(Integer.toHexString(blue)); return s.toString(); } }
6,790
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
GraphDOTExport.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/graph/export/GraphDOTExport.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.wandora.application.tools.graph.export; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import javax.swing.Icon; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.UIConstants; import org.wandora.application.gui.simple.SimpleFileChooser; import org.wandora.application.gui.topicpanels.graphpanel.TopicMapGraphPanel; import org.wandora.application.gui.topicpanels.graphpanel.VEdge; import org.wandora.application.gui.topicpanels.graphpanel.VModel; import org.wandora.application.gui.topicpanels.graphpanel.VNode; import org.wandora.application.tools.graph.AbstractGraphTool; import org.wandora.utils.IObox; import org.wandora.utils.Tuples.T2; /** * * @author akivela */ public class GraphDOTExport extends AbstractGraphTool { private static final long serialVersionUID = 1L; @Override public String getName() { return "Graph view DOT export"; } @Override public String getDescription() { return "Export graph in Graph panel as a DOT formatted file"; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/export_graph.png"); } @Override public boolean requiresRefresh() { return false; } @Override public void executeSynchronized(Wandora admin, Context context) { // NOTHING HERE! } @Override public void execute(Wandora wandora, Context context) { TopicMapGraphPanel graphPanel = this.solveGraphPanel(wandora, context); if(graphPanel != null) { VModel model = graphPanel.getModel(); if(model != null) { SimpleFileChooser chooser=UIConstants.getFileChooser(); chooser.setDialogTitle("Export graph view..."); if(chooser.open(wandora, "Export")==SimpleFileChooser.APPROVE_OPTION){ setDefaultLogger(); File file = chooser.getSelectedFile(); String fileName = file.getName(); // --- Finally write graph to the file OutputStream out=null; try { file=IObox.addFileExtension(file, "dot"); // Ensure file extension exists! fileName = file.getName(); // Updating filename if file has changed! out=new FileOutputStream(file); log("Exporting graph view to '"+fileName+"'."); //System.out.println("tm == "+ tm); exportGraph(out, model); out.close(); log("Ready."); } catch(Exception e) { log(e); try { if(out != null) out.close(); } catch(Exception e2) { log(e2); } } } setState(WAIT); } } } public void exportGraph(OutputStream out, VModel model) { PrintWriter writer = null; try { writer = new PrintWriter(new OutputStreamWriter(out, "ISO-8859-1")); } catch (UnsupportedEncodingException ex) { log("Exception while instantiating PrintWriter with ISO-8859-1 character encoding. Using default encoding."); writer = new PrintWriter(new OutputStreamWriter(out)); } println(writer, "graph wandora_export {"); for(VNode n : model.getNodes()) { printNode(n, writer); } T2<VNode,VNode> nodes; for(VEdge e : model.getEdges()) { nodes=e.getNodes(); if(!nodes.e1.equals(nodes.e2)) { printEdge(e, writer); } } println(writer, "}"); writer.flush(); writer.close(); } protected void printNode(VNode node, PrintWriter writer) { if(node == null) return; println(writer, " "+node.getID()+" [label=\""+makeString(node.getNode().getLabel())+"\"]"); } protected void printEdge(VEdge edge, PrintWriter writer) { if(edge == null) return; T2<VNode,VNode> nodes = edge.getNodes(); println(writer, " "+nodes.e1.getID()+" -- "+nodes.e2.getID()+" [label=\""+makeString(edge.getEdge().getLabel())+"\"]"); } protected void print(PrintWriter writer, String str) { writer.print(str); } protected void println(PrintWriter writer, String str) { writer.println(str); } protected String makeString(String s) { if(s == null) return null; //s = s.substring(0,Math.min(s.length(), 240)); s = s.replaceAll("\"", "\\\""); s = s.replaceAll("\n", " "); s = s.replaceAll("\t", " "); s = s.replaceAll("\r", " "); return s; } }
5,984
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
GraphGraphMLExport.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/graph/export/GraphGraphMLExport.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.wandora.application.tools.graph.export; import java.awt.Color; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import javax.swing.Icon; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.UIConstants; import org.wandora.application.gui.simple.SimpleFileChooser; import org.wandora.application.gui.topicpanels.graphpanel.TopicMapGraphPanel; import org.wandora.application.gui.topicpanels.graphpanel.VEdge; import org.wandora.application.gui.topicpanels.graphpanel.VModel; import org.wandora.application.gui.topicpanels.graphpanel.VNode; import org.wandora.application.tools.graph.AbstractGraphTool; import org.wandora.utils.IObox; import org.wandora.utils.Tuples.T2; /** * * @author akivela */ public class GraphGraphMLExport extends AbstractGraphTool { private static final long serialVersionUID = 1L; @Override public String getName() { return "Graph view GraphML export"; } @Override public String getDescription() { return "Export graph in Graph panel as a GraphML formatted file"; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/export_graph.png"); } @Override public boolean requiresRefresh() { return false; } @Override public void executeSynchronized(Wandora admin, Context context) { // NOTHING HERE! } @Override public void execute(Wandora wandora, Context context) { TopicMapGraphPanel graphPanel = this.solveGraphPanel(wandora, context); if(graphPanel != null) { VModel model = graphPanel.getModel(); if(model != null) { SimpleFileChooser chooser=UIConstants.getFileChooser(); chooser.setDialogTitle("Export graph view..."); if(chooser.open(wandora, "Export")==SimpleFileChooser.APPROVE_OPTION){ setDefaultLogger(); File file = chooser.getSelectedFile(); String fileName = file.getName(); // --- Finally write graph to the file OutputStream out=null; try { file = IObox.addFileExtension(file, "graphml"); // Ensure file extension exists! fileName = file.getName(); // Updating filename if file has changed! out = new FileOutputStream(file); log("Exporting graph view to '"+fileName+"'."); exportGraph(out, model); out.close(); log("Done"); } catch(Exception e) { log(e); try { if(out != null) out.close(); } catch(Exception e2) { log(e2); } } } setState(WAIT); } } } public void exportGraph(OutputStream out, VModel model) { PrintWriter writer = null; try { writer = new PrintWriter(new OutputStreamWriter(out, "ISO-8859-1")); } catch (UnsupportedEncodingException ex) { } println(writer, "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>"); println(writer, "<graphml xmlns=\"http://graphml.graphdrawing.org/xmlns\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://graphml.graphdrawing.org/xmlns http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd\">"); println(writer, " <key id=\"d0\" for=\"all\" attr.name=\"label\" attr.type=\"string\"/>"); println(writer, " <key id=\"d1\" for=\"all\" attr.name=\"name\" attr.type=\"string\"/>"); println(writer, " <graph id=\"wandora_graph_panel_view\" edgedefault=\"undirected\">"); for(VNode n : model.getNodes()) { printNode(n, writer); } T2<VNode,VNode> nodes; for(VEdge e : model.getEdges()) { nodes=e.getNodes(); if(!nodes.e1.equals(nodes.e2)) { printEdge(e, writer); } } println(writer, " </graph>"); // graph println(writer, "</graphml>"); // graphml writer.flush(); writer.close(); } protected void printNode(VNode node, PrintWriter writer) { if(node == null) return; println(writer, " <node id=\""+node.getID()+"\">"); println(writer, " <data key=\"d0\">"+makeString(node.getNode().getLabel())+"</data>"); println(writer, " <data key=\"d1\">"+makeString(node.getColor())+"</data>"); println(writer, " </node>"); } protected void printEdge(VEdge edge, PrintWriter writer) { if(edge == null) return; T2<VNode,VNode> nodes = edge.getNodes(); print(writer, " <edge"); print(writer, " source=\""+nodes.e1.getID()+"\""); print(writer, " target=\""+nodes.e2.getID()+"\""); println(writer, ">"); println(writer, " <data key=\"d0\">"+makeString(edge.getEdge().getLabel())+"</data>"); println(writer, " <data key=\"d1\">"+makeString(edge.getColor())+"</data>"); println(writer, " </edge>"); } protected void print(PrintWriter writer, String str) { writer.print(str); } protected void println(PrintWriter writer, String str) { writer.println(str); } protected String makeString(String s) { if(s == null) return null; //s = s.substring(0,Math.min(s.length(), 240)); s = s.replaceAll("<", "&lt;"); s = s.replaceAll(">", "&gt;"); s = s.replaceAll("\\&", "&amp;"); return s; } protected String makeString(Color c) { if(c == null) return ""; int red = c.getRed(); int green = c.getGreen(); int blue = c.getBlue(); StringBuilder s = new StringBuilder(""); s.append("#"); s.append(Integer.toHexString(red)); s.append(Integer.toHexString(green)); s.append(Integer.toHexString(blue)); return s.toString(); } }
7,289
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
GraphGraphXMLExport.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/graph/export/GraphGraphXMLExport.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.wandora.application.tools.graph.export; import java.awt.Color; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import javax.swing.Icon; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.UIConstants; import org.wandora.application.gui.simple.SimpleFileChooser; import org.wandora.application.gui.topicpanels.graphpanel.TopicMapGraphPanel; import org.wandora.application.gui.topicpanels.graphpanel.VEdge; import org.wandora.application.gui.topicpanels.graphpanel.VModel; import org.wandora.application.gui.topicpanels.graphpanel.VNode; import org.wandora.application.tools.graph.AbstractGraphTool; import org.wandora.utils.IObox; import org.wandora.utils.Tuples.T2; /** * * @author akivela */ public class GraphGraphXMLExport extends AbstractGraphTool { private static final long serialVersionUID = 1L; @Override public String getName() { return "Graph view GraphXML export"; } @Override public String getDescription() { return "Export graph in Graph panel as a GraphXML formatted file"; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/export_graph.png"); } @Override public boolean requiresRefresh() { return false; } @Override public void executeSynchronized(Wandora admin, Context context) { // NOTHING HERE! } @Override public void execute(Wandora wandora, Context context) { TopicMapGraphPanel graphPanel = this.solveGraphPanel(wandora, context); if(graphPanel != null) { VModel model = graphPanel.getModel(); if(model != null) { SimpleFileChooser chooser=UIConstants.getFileChooser(); chooser.setDialogTitle("Export graph view..."); if(chooser.open(wandora, "Export")==SimpleFileChooser.APPROVE_OPTION){ setDefaultLogger(); File file = chooser.getSelectedFile(); String fileName = file.getName(); // --- Finally write graph to the file OutputStream out = null; try { file = IObox.addFileExtension(file, "xml"); // Ensure file extension exists! fileName = file.getName(); // Updating filename if file has changed! out = new FileOutputStream(file); log("Exporting graph view to '"+fileName+"'."); exportGraph(out, model); out.close(); log("Ready."); } catch(Exception e) { log(e); try { if(out != null) out.close(); } catch(Exception e2) { log(e2); } } } setState(WAIT); } } } public void exportGraph(OutputStream out, VModel model) { PrintWriter writer = null; try { writer = new PrintWriter(new OutputStreamWriter(out, "UTF-8")); } catch (UnsupportedEncodingException ex) { } println(writer, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); println(writer, "<!DOCTYPE GraphXML SYSTEM \"GraphXML.dtd\">"); println(writer, "<GraphXML>"); println(writer, " <graph id=\"WandoraGraph\" isDirected=\"false\" isForest=\"false\">"); for(VNode n : model.getNodes()) { printNode(n, writer); } T2<VNode,VNode> nodes; for(VEdge e : model.getEdges()) { nodes=e.getNodes(); if(!nodes.e1.equals(nodes.e2)) { printEdge(e, writer); } } println(writer, " </graph>"); // graph println(writer, "</GraphXML>"); // graphml writer.flush(); writer.close(); } protected void printNode(VNode node, PrintWriter writer) { if(node == null) return; println(writer, " <node name=\""+node.getID()+"\">"); println(writer, " <label>"+makeString(node.getNode().getLabel())+"</label>"); println(writer, " <position x=\""+node.getX()+"\" y=\""+node.getY()+"\">"); println(writer, " </node>"); } protected void printEdge(VEdge edge, PrintWriter writer) { if(edge == null) return; T2<VNode,VNode> nodes = edge.getNodes(); print(writer, " <edge"); print(writer, " source=\""+nodes.e1.getID()+"\""); print(writer, " target=\""+nodes.e2.getID()+"\""); println(writer, ">"); writer.println(" <label>"+makeString(edge.getEdge().getLabel())+"</label>"); println(writer, " </edge>"); } protected void print(PrintWriter writer, String str) { writer.print(str); } protected void println(PrintWriter writer, String str) { writer.println(str); } protected String makeString(String s) { if(s == null) return null; //s = s.substring(0,Math.min(s.length(), 240)); s = s.replaceAll("<", "&lt;"); s = s.replaceAll(">", "&gt;"); s = s.replaceAll("\\&", "&amp;"); return s; } protected String makeString(Color c) { if(c == null) return ""; int red = c.getRed(); int green = c.getGreen(); int blue = c.getBlue(); StringBuilder s = new StringBuilder(""); s.append("#"); s.append(Integer.toHexString(red)); s.append(Integer.toHexString(green)); s.append(Integer.toHexString(blue)); return s.toString(); } }
6,819
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ReversePinningTool.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/graph/pinning/ReversePinningTool.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * ReversePinningTool.java * * Created on 7.6.2007, 16:19 * */ package org.wandora.application.tools.graph.pinning; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.application.contexts.GraphNodeContext; import org.wandora.application.gui.topicpanels.graphpanel.TopicMapGraphPanel; /** * * @author olli */ public class ReversePinningTool extends AbstractGraphPinningTool { private static final long serialVersionUID = 1L; /** Creates a new instance of ReversePinningTool */ public ReversePinningTool(TopicMapGraphPanel gp) { super(gp); this.setContext(new GraphNodeContext()); } public ReversePinningTool(TopicMapGraphPanel gp, Context proposedContext) { super(gp); this.setContext(proposedContext); } @Override public String getName(){ return "Toggle node pinning"; } public void executeSynchronized(Wandora wandora, Context context) { if(context != null) { setPinning(context.getContextObjects(), REVERSE_PINNING); } } }
1,937
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SetPinnedTool.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/graph/pinning/SetPinnedTool.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * SetPinnedTool.java * * Created on 14.6.2007, 12:53 * */ package org.wandora.application.tools.graph.pinning; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.application.contexts.GraphNodeContext; import org.wandora.application.gui.topicpanels.graphpanel.TopicMapGraphPanel; /** * * @author akivela */ public class SetPinnedTool extends AbstractGraphPinningTool { private static final long serialVersionUID = 1L; /** Creates a new instance of SetPinnedTool */ public SetPinnedTool(TopicMapGraphPanel gp) { super(gp); this.setContext(new GraphNodeContext()); } public SetPinnedTool(TopicMapGraphPanel gp, Context proposedContext) { super(gp); this.setContext(proposedContext); } @Override public String getName(){ return "Set node pinned"; } public void executeSynchronized(Wandora wandora, Context context) { if(context != null) { setPinning(context.getContextObjects(), SET_PINNED); } } }
1,909
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AbstractGraphPinningTool.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/graph/pinning/AbstractGraphPinningTool.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * AbstractGraphPinningTool.java * * Created on 14.6.2007, 13:04 * */ package org.wandora.application.tools.graph.pinning; import java.util.Iterator; import org.wandora.application.gui.topicpanels.graphpanel.TopicMapGraphPanel; import org.wandora.application.gui.topicpanels.graphpanel.VNode; import org.wandora.application.tools.graph.AbstractGraphTool; /** * * @author akivela */ public abstract class AbstractGraphPinningTool extends AbstractGraphTool { private static final long serialVersionUID = 1L; public static final int SET_PINNED = 10; public static final int SET_UNPINNED = 20; public static final int REVERSE_PINNING = 30; /** Creates a new instance of AbstractGraphPinningTool */ public AbstractGraphPinningTool(TopicMapGraphPanel gp) { super(gp); } public void setPinning(Iterator nodes, int mode) { if(nodes == null) return; VNode vn = null; while(nodes.hasNext()) { try { vn = (VNode) nodes.next(); if(vn != null) { switch(mode) { case SET_PINNED: vn.setPinned(true); break; case SET_UNPINNED: vn.setPinned(false); break; case REVERSE_PINNING: vn.setPinned(!vn.isPinned()); break; } } } catch (Exception e) { singleLog(e); } } } }
2,438
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SetUnpinnedTool.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/graph/pinning/SetUnpinnedTool.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * SetUnpinnedTool.java * * Created on 14.6.2007, 13:13 * */ package org.wandora.application.tools.graph.pinning; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.application.contexts.GraphNodeContext; import org.wandora.application.gui.topicpanels.graphpanel.TopicMapGraphPanel; /** * * @author akivela */ public class SetUnpinnedTool extends AbstractGraphPinningTool { private static final long serialVersionUID = 1L; /** Creates a new instance of SetUnpinnedTool */ public SetUnpinnedTool(TopicMapGraphPanel gp) { super(gp); this.setContext(new GraphNodeContext()); } public SetUnpinnedTool(TopicMapGraphPanel gp, Context proposedContext) { super(gp); this.setContext(proposedContext); } @Override public String getName(){ return "Set node unpinned"; } public void executeSynchronized(Wandora wandora, Context context) { if(context != null) { setPinning(context.getContextObjects(), SET_UNPINNED); } } }
1,920
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ReleaseEdges.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/graph/filters/ReleaseEdges.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * ReleaseEdges.java * * Created on 7.6.2007, 12:06 * */ package org.wandora.application.tools.graph.filters; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.application.contexts.GraphEdgeContext; import org.wandora.application.gui.topicpanels.graphpanel.GraphFilter; import org.wandora.application.gui.topicpanels.graphpanel.NodeFilter; import org.wandora.application.gui.topicpanels.graphpanel.TopicNode; import org.wandora.application.gui.topicpanels.graphpanel.VModel; import org.wandora.application.gui.topicstringify.TopicToString; import org.wandora.application.tools.graph.AbstractGraphTool; import org.wandora.topicmap.Topic; /** * * @author akivela */ public class ReleaseEdges extends AbstractGraphTool { private static final long serialVersionUID = 1L; public static final int FILTER_EDGES_WITH_TYPE = 1; public static final int FILTER_INSTANCE_EDGES = 2; public static final int FILTER_OCCURRENCE_EDGES = 3; private int filterType = FILTER_EDGES_WITH_TYPE; private Topic edgeType; private GraphFilter filter; public ReleaseEdges(int filterType, Topic edgeType, NodeFilter filter) { this(filterType, edgeType, (GraphFilter)filter); } /** */ public ReleaseEdges(int filterType, Topic edgeType, GraphFilter filter) { this.setContext(new GraphEdgeContext()); this.edgeType = edgeType; this.filterType = filterType; this.filter = filter; } @Override public String getName(){ try { switch(filterType) { case FILTER_OCCURRENCE_EDGES: return "Release Occurrence edges"; case FILTER_INSTANCE_EDGES: return "Release Class-Instance edges"; case FILTER_EDGES_WITH_TYPE: { if(edgeType != null) return "Release edges of type "+TopicToString.toString(edgeType); else return "[No filtered edges]"; } } } catch(Exception tme){ tme.printStackTrace(); } return ""; } public void executeSynchronized(Wandora wandora, Context context) { VModel model = solveModel(wandora,context); switch(filterType) { case FILTER_OCCURRENCE_EDGES: { filter.setFilterOccurrences(false); break; } case FILTER_INSTANCE_EDGES: { filter.setFilterInstances(false); break; } default: { if(edgeType != null) filter.releaseEdgeType(edgeType); break; } } } // ------------------------------------------------------------------------- public static List<AbstractGraphTool> makeTools(Collection c, GraphFilter graphFilter, List<AbstractGraphTool> tools){ if(tools==null) tools=new ArrayList<AbstractGraphTool>(); ArrayList<Topic> types = new ArrayList<Topic>(); for(Object o : graphFilter.getFilteredEdgeTypes()) { if(o != null) { if(o instanceof TopicNode) { TopicNode tn=(TopicNode)o; Topic t = tn.getTopic(); try { if(!types.contains(t)) { types.add(t); tools.add(new ReleaseEdges(FILTER_EDGES_WITH_TYPE, t, graphFilter)); } } catch(Exception tme){tme.printStackTrace();} } } } if(graphFilter.getFilterInstances()) { tools.add(new ReleaseEdges(FILTER_INSTANCE_EDGES, null, graphFilter)); } if(graphFilter.getFilterOccurrences()) { tools.add(new ReleaseEdges(FILTER_OCCURRENCE_EDGES, null, graphFilter)); } if(tools.isEmpty()) { tools.add(new ReleaseEdges(FILTER_EDGES_WITH_TYPE, null, graphFilter)); } return tools; } }
4,999
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
FilterNodesOfType.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/graph/filters/FilterNodesOfType.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * FilterNodesOfType.java * * Created on 6.6.2007, 15:40 * */ package org.wandora.application.tools.graph.filters; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.application.contexts.GraphEdgeContext; import org.wandora.application.gui.topicpanels.graphpanel.GraphFilter; import org.wandora.application.gui.topicpanels.graphpanel.Node; import org.wandora.application.gui.topicpanels.graphpanel.NodeFilter; import org.wandora.application.gui.topicpanels.graphpanel.TopicNode; import org.wandora.application.gui.topicpanels.graphpanel.VModel; import org.wandora.application.gui.topicpanels.graphpanel.VNode; import org.wandora.application.gui.topicstringify.TopicToString; import org.wandora.application.tools.graph.AbstractGraphTool; import org.wandora.application.tools.graph.CloseTopicNodesOfType; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public class FilterNodesOfType extends AbstractGraphTool { private static final long serialVersionUID = 1L; private Topic type; private GraphFilter filter; public FilterNodesOfType(Topic type,NodeFilter filter) { this(type,(GraphFilter)filter); } public FilterNodesOfType(Topic type,GraphFilter filter) { this.setContext(new GraphEdgeContext()); this.type=type; this.filter=filter; } @Override public String getName(){ try{ return "Filter nodes of type "+TopicToString.toString(type); } catch(Exception tme){ tme.printStackTrace(); return ""; } } public void executeSynchronized(Wandora wandora, Context context) { VModel model=solveModel(wandora,context); CloseTopicNodesOfType.hideTopicsOfType(type,model); filter.filterNodesOfType(type); } // ------------------------------------------------------------------------- public static ArrayList<AbstractGraphTool> makeTools(VNode n, NodeFilter nodeFilter, ArrayList<AbstractGraphTool> tools){ return makeTools(n==null?null:n.getNode(),nodeFilter,tools); } public static ArrayList<AbstractGraphTool> makeTools(Node n, NodeFilter nodeFilter, ArrayList<AbstractGraphTool> tools){ if(tools==null) tools=new ArrayList<AbstractGraphTool>(); if(n!=null && n instanceof TopicNode){ TopicNode tn=(TopicNode)n; try { for(Topic type : tn.getTopic().getTypes()) { tools.add(new FilterNodesOfType(type,nodeFilter)); } } catch(TopicMapException tme) { tme.printStackTrace(); } } return tools; } public static List<AbstractGraphTool> makeTools(Collection ns, NodeFilter nodeFilter, List<AbstractGraphTool> tools){ if(tools==null) tools=new ArrayList<AbstractGraphTool>(); ArrayList<Topic> oldTypes = new ArrayList<Topic>(); for(Object o : ns) { if(o != null && o instanceof VNode) { o = ((VNode) o).getNode(); } if(o != null && o instanceof TopicNode) { TopicNode tn=(TopicNode)o; try { for(Topic type : tn.getTopic().getTypes()) { if(!oldTypes.contains(type)) { oldTypes.add(type); tools.add(new FilterNodesOfType(type,nodeFilter)); } } } catch(TopicMapException tme){ tme.printStackTrace(); } } } return tools; } }
4,726
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ClearEdgeFilters.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/graph/filters/ClearEdgeFilters.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * ClearEdgeFilters.java * * Created on 21. elokuuta 2007, 16:26 * */ package org.wandora.application.tools.graph.filters; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.application.gui.topicpanels.graphpanel.GraphFilter; import org.wandora.application.tools.graph.AbstractGraphTool; /** * * @author akivela */ public class ClearEdgeFilters extends AbstractGraphTool { private static final long serialVersionUID = 1L; GraphFilter filter = null; @Override public String getName() { return "Clear all edge filters"; } /** Creates a new instance of ClearEdgeFilters */ public ClearEdgeFilters(GraphFilter filter) { this.filter = filter; } public void executeSynchronized(Wandora wandora, Context context) { try { filter.clearEdgeFilters(); } catch (Exception e) { singleLog(e); } } }
1,778
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ClearNodeFilters.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/graph/filters/ClearNodeFilters.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * ClearNodeFilters.java * * Created on 21. elokuuta 2007, 17:01 * */ package org.wandora.application.tools.graph.filters; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.application.gui.topicpanels.graphpanel.GraphFilter; import org.wandora.application.tools.graph.AbstractGraphTool; /** * * @author akivela */ public class ClearNodeFilters extends AbstractGraphTool { private static final long serialVersionUID = 1L; GraphFilter filter = null; @Override public String getName() { return "Clear all node filters"; } @Override public String getDescription() { return "Clear all node filters."; } /** Creates a new instance of ClearNodeFilters */ public ClearNodeFilters(GraphFilter filter) { this.filter = filter; } public void executeSynchronized(Wandora admin, Context context) { try { filter.clearNodeFilters(); filter.clearNodeTypeFilters(); } catch (Exception e) { singleLog(e); } } }
1,943
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
FilterEdges.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/graph/filters/FilterEdges.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * FilterEdges.java * * Created on 7.6.2007, 12:06 * */ package org.wandora.application.tools.graph.filters; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.application.contexts.GraphEdgeContext; import org.wandora.application.gui.topicpanels.graphpanel.AssociationEdge; import org.wandora.application.gui.topicpanels.graphpanel.Edge; import org.wandora.application.gui.topicpanels.graphpanel.GraphFilter; import org.wandora.application.gui.topicpanels.graphpanel.InstanceEdge; import org.wandora.application.gui.topicpanels.graphpanel.NodeFilter; import org.wandora.application.gui.topicpanels.graphpanel.OccurrenceEdge; import org.wandora.application.gui.topicpanels.graphpanel.VEdge; import org.wandora.application.gui.topicpanels.graphpanel.VModel; import org.wandora.application.gui.topicpanels.graphpanel.VNode; import org.wandora.application.gui.topicstringify.TopicToString; import org.wandora.application.tools.graph.AbstractGraphTool; import org.wandora.topicmap.Association; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; import org.wandora.utils.Tuples.T2; /** * * @author olli */ public class FilterEdges extends AbstractGraphTool { private static final long serialVersionUID = 1L; public static final int FILTER_EDGES_WITH_TYPE = 1; public static final int FILTER_INSTANCE_EDGES = 2; public static final int FILTER_OCCURRENCE_EDGES = 3; private int filterType = FILTER_EDGES_WITH_TYPE; private Topic edgeType; private GraphFilter filter; public FilterEdges(int filterType, Topic edgeType, NodeFilter filter) { this(filterType, edgeType, (GraphFilter)filter); } /** */ public FilterEdges(int filterType, Topic edgeType, GraphFilter filter) { this.setContext(new GraphEdgeContext()); this.edgeType = edgeType; this.filterType = filterType; this.filter = filter; } @Override public String getName(){ try { switch(filterType) { case FILTER_OCCURRENCE_EDGES: return "Filter Occurrence edges"; case FILTER_INSTANCE_EDGES: return "Filter Class-Instance edges"; case FILTER_EDGES_WITH_TYPE: return "Filter edges of type "+TopicToString.toString(edgeType); } } catch(Exception tme){ tme.printStackTrace(); } return ""; } public static void hideNodesOfType(int filterType, Topic edgeType, VModel model) { HashSet<VEdge> remove=new HashSet<VEdge>(); try { for(VEdge vedge : model.getEdges()){ Edge e=vedge.getEdge(); if(filterType==FILTER_INSTANCE_EDGES) { if(e instanceof InstanceEdge) { remove.add(vedge); } } if(filterType==FILTER_OCCURRENCE_EDGES) { if(e instanceof OccurrenceEdge) { remove.add(vedge); } } else { if(e instanceof AssociationEdge){ AssociationEdge ae=(AssociationEdge)e; Association a=ae.getAssociation(); if(a.getType().mergesWithTopic(edgeType)) { remove.add(vedge); } } } } } catch(TopicMapException tme) { tme.printStackTrace(); } for(VEdge vedge : remove){ model.removeEdge(vedge); T2<VNode,VNode> ns=vedge.getNodes(); if(ns.e1.getEdges().isEmpty()) model.removeNode(ns.e1); if(ns.e2.getEdges().isEmpty()) model.removeNode(ns.e2); } } public void executeSynchronized(Wandora wandora, Context context) { VModel model = solveModel(wandora,context); hideNodesOfType(filterType, edgeType, model); switch(filterType) { case FILTER_OCCURRENCE_EDGES: { filter.setFilterOccurrences(true); break; } case FILTER_INSTANCE_EDGES: { filter.setFilterInstances(true); break; } default: { filter.filterEdgeType(edgeType); break; } } } // ------------------------------------------------------------------------- public static List<AbstractGraphTool> makeTools(VEdge e,GraphFilter graphFilter,List<AbstractGraphTool> tools){ return makeTools(e==null?null:e.getEdge(),graphFilter,tools); } public static List<AbstractGraphTool> makeTools(Edge e,GraphFilter graphFilter,List<AbstractGraphTool> tools){ if(tools==null) tools=new ArrayList<AbstractGraphTool>(); if(e!=null){ if(e instanceof AssociationEdge){ AssociationEdge ae=(AssociationEdge)e; Association a=ae.getAssociation(); try { tools.add(new FilterEdges(FILTER_EDGES_WITH_TYPE, a.getType(), graphFilter)); } catch(TopicMapException tme) { tme.printStackTrace(); } } else if(e instanceof InstanceEdge){ tools.add(new FilterEdges(FILTER_INSTANCE_EDGES, null, graphFilter)); } else if(e instanceof OccurrenceEdge){ tools.add(new FilterEdges(FILTER_OCCURRENCE_EDGES, null, graphFilter)); } } return tools; } public static List<AbstractGraphTool> makeTools(Collection c,GraphFilter graphFilter,List<AbstractGraphTool> tools){ if(tools==null) tools=new ArrayList<AbstractGraphTool>(); ArrayList<Topic> types = new ArrayList<Topic>(); boolean instanceAdded = false; boolean occurrenceAdded = false; for(Object o : c) { if(o != null) { if(o instanceof VEdge) { o = ((VEdge) o).getEdge(); if(o == null) continue; } if(o instanceof AssociationEdge) { AssociationEdge ae=(AssociationEdge)o; Association a=ae.getAssociation(); try { Topic type = a.getType(); if(!types.contains(type)) { types.add(type); tools.add(new FilterEdges(FILTER_EDGES_WITH_TYPE, type, graphFilter)); } } catch(TopicMapException tme){tme.printStackTrace();} } else if(o instanceof InstanceEdge) { if(!instanceAdded) { instanceAdded = true; tools.add(new FilterEdges(FILTER_INSTANCE_EDGES, null, graphFilter)); } } else if(o instanceof OccurrenceEdge) { if(!occurrenceAdded) { occurrenceAdded = true; tools.add(new FilterEdges(FILTER_OCCURRENCE_EDGES, null, graphFilter)); } } } } return tools; } }
8,301
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ReleaseNodesOfType.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/graph/filters/ReleaseNodesOfType.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * ReleaseNodesOfType.java * * Created on 6.6.2007, 15:40 * */ package org.wandora.application.tools.graph.filters; import java.util.ArrayList; import java.util.List; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.application.contexts.GraphEdgeContext; import org.wandora.application.gui.topicpanels.graphpanel.GraphFilter; import org.wandora.application.gui.topicpanels.graphpanel.NodeFilter; import org.wandora.application.gui.topicpanels.graphpanel.TopicNode; import org.wandora.application.gui.topicstringify.TopicToString; import org.wandora.application.tools.graph.AbstractGraphTool; import org.wandora.topicmap.Topic; /** * * @author akivela */ public class ReleaseNodesOfType extends AbstractGraphTool { private static final long serialVersionUID = 1L; private Topic type; private GraphFilter filter; public ReleaseNodesOfType(Topic type, NodeFilter filter) { this(type,(GraphFilter)filter); } public ReleaseNodesOfType(Topic type, GraphFilter filter) { this.setContext(new GraphEdgeContext()); this.type=type; this.filter=filter; } @Override public String getName() { if(type != null) { return "Release nodes of type "+TopicToString.toString(type); } else { return "[No filtered nodes]"; } } public void executeSynchronized(Wandora wandora, Context context) { if(type != null && filter != null) { filter.releaseNodesOfType(type); } } // ------------------------------------------------------------------------- public static List<AbstractGraphTool> makeTools(GraphFilter graphFilter, List<AbstractGraphTool> tools) { if(tools==null) tools=new ArrayList<AbstractGraphTool>(); for(TopicNode tn : graphFilter.getFilteredNodeTypes()) { if(tn != null) { try { Topic type = tn.getTopic(); if(type != null && !type.isRemoved()) { tools.add(new ReleaseNodesOfType(type, graphFilter)); } } catch(Exception tme){ tme.printStackTrace(); } } } if(tools.isEmpty()) { tools.add(new ReleaseNodesOfType(null, graphFilter)); } return tools; } }
3,316
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
FilterNode.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/graph/filters/FilterNode.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * FilterNode.java * * Created on 6.6.2007, 15:38 * */ package org.wandora.application.tools.graph.filters; import java.util.Iterator; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.application.contexts.GraphNodeContext; import org.wandora.application.gui.topicpanels.graphpanel.GraphFilter; import org.wandora.application.gui.topicpanels.graphpanel.NodeFilter; import org.wandora.application.gui.topicpanels.graphpanel.VModel; import org.wandora.application.gui.topicpanels.graphpanel.VNode; import org.wandora.application.tools.graph.AbstractGraphTool; /** * * @author olli */ public class FilterNode extends AbstractGraphTool { private static final long serialVersionUID = 1L; private GraphFilter filter; public FilterNode(GraphFilter filter) { this.filter=filter; this.setContext(new GraphNodeContext()); } public FilterNode(NodeFilter filter) { this((GraphFilter)filter); } @Override public String getName(){ return "Filter graph node"; } public void executeSynchronized(Wandora wandora, Context context) { VModel model = null; VNode node = null; for(Iterator iter = context.getContextObjects(); iter.hasNext(); ) { try { Object o = iter.next(); if(o instanceof VNode){ node = (VNode) o; if(node != null) { model = node.getModel(); if(model != null) { model.removeNode(node); filter.filterNode(node); } } } } catch(Exception e) { singleLog(e); } } } }
2,660
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicTest.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/testing/TopicTest.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.wandora.application.tools.testing; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Hashtable; import java.util.List; import java.util.Set; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; /** * * @author akivela */ public class TopicTest extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; @Override public String getName() { return "Various topic tests"; } @Override public String getDescription() { return "Various topic tests."; } @Override public void execute(Wandora wandora, Context context) { try { setDefaultLogger(); setLogTitle("Various topic tests"); TopicMap tm = wandora.getTopicMap(); ArrayList<String> sis = new ArrayList(); int numberOfTestTopics = 200; int numberOfFails = 0; int numberOfRepeats = 1; log("Number of test topics is "+numberOfTestTopics+"."); // -------------------------------------------------- CREATION ----- if(!forceStop()) { hlog("Topic creation test."); long startTime = System.currentTimeMillis(); int topicCount = tm.getNumTopics(); setProgress(0); setProgressMax(numberOfTestTopics); for(int i=0; i<numberOfTestTopics; i++) { String si = "http://wandora.org/si/test-topic/"+System.currentTimeMillis()+"/"+i; Topic t = tm.createTopic(); t.addSubjectIdentifier(new Locator(si)); sis.add(si); setProgress(i); if(forceStop()) break; } int newTopicCount = tm.getNumTopics(); long testTime = System.currentTimeMillis() - startTime; if(newTopicCount == topicCount+numberOfTestTopics) { log("Topic creation test passed in "+testTime+"ms."); } else { log("Topic creation test failed in "+testTime+"ms."); numberOfFails++; } } // -------------------------------- FIND BY SUBJECT IDENTIFIER ----- if(!forceStop()) { hlog("Topic find test."); long startTime = System.currentTimeMillis(); boolean success = true; int p=0; setProgress(p); setProgressMax(numberOfTestTopics); for(String si : sis) { Topic t = tm.getTopic(si); if(t == null) { log("Can't find topic for subject identifier "+si); success = false; } setProgress(p++); if(forceStop()) break; } p=0; setProgress(p); setProgressMax(numberOfTestTopics); for(int i=0; i<numberOfTestTopics; i++) { String si = sis.get((int) Math.floor(Math.random()*sis.size())); Topic t = tm.getTopic(si); if(t == null) { log("Can't find topic for subject identifier "+si); success = false; } setProgress(p++); if(forceStop()) break; } long testTime = System.currentTimeMillis() - startTime; if(success) { log("Topic find test passed in "+testTime+"ms."); } else { log("Topic find test failed in "+testTime+"ms."); numberOfFails++; } } // -------------------- SUBJECT IDENTIFIER ADDITION AND REMOVE ----- if(!forceStop()) { hlog("Topic add and remove subject identifier test."); long startTime = System.currentTimeMillis(); boolean success = true; int p=0; setProgress(0); setProgressMax(1); String si = sis.get(0); Topic t = tm.getTopic(si); Locator testsi = new Locator("http://wandora.org/si/test-subject-identifiers/"+System.currentTimeMillis()); t.addSubjectIdentifier(testsi); Collection<Locator> tsis = t.getSubjectIdentifiers(); if(!tsis.contains(testsi)) { log("Topic doesn't contain added subject identifier."); success = false; } if(!tsis.contains(new Locator(si))) { log("Topic doesn't contain original subject identifier after another subject identifier is added."); success = false; } Topic t0 = tm.getTopic(si); Topic t1 = tm.getTopic(testsi.toExternalForm()); if(!t0.mergesWithTopic(t1)) { log("Two subject identifiers added to a topic resolve different topic. Shouldn't."); success = false; } t.removeSubjectIdentifier(testsi); tsis = t.getSubjectIdentifiers(); if(tsis.contains(testsi)) { log("Topic contains a subject identifier even when it is removed."); success = false; } long testTime = System.currentTimeMillis() - startTime; if(success) { log("Topic add and remove subject identifier test passed in "+testTime+"ms."); } else { log("Topic add and remove subject identifier test failed in "+testTime+"ms."); numberOfFails++; } } // ----------------------------------------------- SET BASENAME----- if(!forceStop()) { hlog("Topic set basename test."); long startTime = System.currentTimeMillis(); boolean success = true; int p=0; setProgress(p); setProgressMax(numberOfTestTopics); for(String si : sis) { Topic t = tm.getTopic(si); if(t == null) { log("Can't find topic for subject identifier "+si); success = false; } else { for(int i=0; i<numberOfRepeats; i++) { String basename = getRandomString(); t.setBaseName(basename); String basename2 = t.getBaseName(); if(!basename.equals(basename2)) { success = false; log("Failed to restore basename "+basename); } if(forceStop()) break; } } setProgress(p++); if(forceStop()) break; } long testTime = System.currentTimeMillis() - startTime; if(success) { log("Topic set basename test passed in "+testTime+"ms."); } else { log("Topic set basename test failed in "+testTime+"ms."); numberOfFails++; } } // ------------------------------------------ SET VARIANT NAME ----- if(!forceStop()) { hlog("Topic variant name test."); long startTime = System.currentTimeMillis(); boolean success = true; int p=0; setProgress(p); setProgressMax(numberOfTestTopics); for(String si : sis) { Topic t = tm.getTopic(si); if(t == null) { log("Can't find topic for subject identifier "+si); success = false; } else { String name = getRandomString(); t.setDisplayName("en", name); String name2 = t.getDisplayName("en"); if(!name.equals(name2)) { success = false; log("Failed to restore topic's variant name "+name); } } setProgress(p++); if(forceStop()) break; } long testTime = System.currentTimeMillis() - startTime; if(success) { log("Topic variant name test passed in "+testTime+"ms."); } else { log("Topic variant name test failed in "+testTime+"ms."); numberOfFails++; } } // ------------------------------------------ SET VARIANT NAME ----- if(!forceStop()) { hlog("Topic variant name test 2."); long startTime = System.currentTimeMillis(); boolean success = true; List<String> sis2 = new ArrayList<String>(sis); int p=0; setProgress(p); setProgressMax(numberOfTestTopics); for(String si : sis) { Topic t = tm.getTopic(si); if(t == null) { log("Can't find topic for subject identifier "+si); success = false; } else { for(int j=0; j<numberOfRepeats; j++) { Set<Topic> scope = new HashSet<>(); for(int i=0; i<1+Math.round(Math.random()*Math.min(10, numberOfTestTopics)); i++) { scope.add(tm.getTopic(sis2.get((int) Math.floor(Math.random() * sis2.size())))); } String name = getRandomString(); t.setVariant(scope, name); Set<Topic> scope2 = new HashSet<>(); scope2.addAll(scope); String name2 = t.getVariant(scope2); if(!name.equals(name2)) { success = false; log("Failed to restore topic's variant name "+name); } if(forceStop()) break; } setProgress(p++); if(forceStop()) break; } } long testTime = System.currentTimeMillis() - startTime; if(success) { log("Topic variant name test 2 passed in "+testTime+"ms."); } else { log("Topic variant name test 2 failed in "+testTime+"ms."); numberOfFails++; } } // --------------------------------------- DELETE VARIANT NAME ----- if(!forceStop()) { hlog("Topic delete variant name test."); long startTime = System.currentTimeMillis(); boolean success = true; int p=0; setProgress(p); setProgressMax(numberOfTestTopics); for(String si : sis) { Topic t = tm.getTopic(si); if(t == null) { log("Can't find topic for subject identifier "+si); success = false; } else { Set<Set<Topic>> scopes = t.getVariantScopes(); for(Set<Topic> scope : scopes) { t.removeVariant(scope); } scopes = t.getVariantScopes(); if(!scopes.isEmpty()) { success = false; log("Failed to delete all variant names of a topic."); } setProgress(p++); if(forceStop()) break; } } long testTime = System.currentTimeMillis() - startTime; if(success) { log("Topic delete variant name test passed in "+testTime+"ms."); } else { log("Topic delete variant name test failed in "+testTime+"ms."); numberOfFails++; } } // -------------------------------------------- SET OCCURRENCE ----- if(!forceStop()) { hlog("Topic occurrence test."); long startTime = System.currentTimeMillis(); boolean success = true; List<String> sis2 = new ArrayList<String>(sis); int p=0; setProgress(p); setProgressMax(numberOfTestTopics); for(String si : sis) { Topic t = tm.getTopic(si); if(t == null) { log("Can't find topic for subject identifier "+si); success = false; } else { for(int j=0; j<numberOfRepeats; j++) { Topic type = tm.getTopic(sis2.get((int) Math.floor(Math.random() * sis2.size()))); Topic version = tm.getTopic(sis2.get((int) Math.floor(Math.random() * sis2.size()))); String occurrence = getRandomString(); t.setData(type, version, occurrence); String occurrence2 = t.getData(type, version); if(!occurrence.equals(occurrence2)) { success = false; log("Failed to restore occurrence "+occurrence); } if(forceStop()) break; } setProgress(p++); if(forceStop()) break; } } long testTime = System.currentTimeMillis() - startTime; if(success) { log("Topic occurrence test passed in "+testTime+"ms."); } else { log("Topic occurrence test failed in "+testTime+"ms."); numberOfFails++; } } // ----------------------------------------- DELETE OCCURRENCE ----- if(!forceStop()) { hlog("Topic occurrence delete test."); long startTime = System.currentTimeMillis(); boolean success = true; int p=0; setProgress(p); setProgressMax(numberOfTestTopics); for(String si : sis) { Topic t = tm.getTopic(si); if(t == null) { log("Can't find topic for subject identifier "+si); success = false; } else { Collection<Topic> dataTypes = t.getDataTypes(); for(Topic dataType : dataTypes) { if(Math.random() > 0.5) { t.removeData(dataType); } else { Hashtable<Topic,String> datas = t.getData(dataType); for(Topic version : datas.keySet()) { t.removeData(dataType, version); } } } dataTypes = t.getDataTypes(); if(!dataTypes.isEmpty()) { success = false; log("Failed to delete all occurrences of a topic."); } setProgress(p++); if(forceStop()) break; } } long testTime = System.currentTimeMillis() - startTime; if(success) { log("Topic occurrence delete test passed in "+testTime+"ms."); } else { log("Topic occurrence delete test failed in "+testTime+"ms."); numberOfFails++; } } // ------------------------------------------- DELETE BASENAME ----- if(!forceStop()) { hlog("Topic delete basename test."); long startTime = System.currentTimeMillis(); boolean success = true; int p=0; setProgress(p); setProgressMax(numberOfTestTopics); for(String si : sis) { Topic t = tm.getTopic(si); if(t == null) { log("Can't find topic for subject identifier "+si); success = false; } else { t.setBaseName(null); String basename = t.getBaseName(); if(basename != null) { success = false; log("Failed to delete topic's basename "+basename); } } setProgress(p++); if(forceStop()) break; } long testTime = System.currentTimeMillis() - startTime; if(success) { log("Topic delete basename test passed in "+testTime+"ms."); } else { log("Topic delete basename test failed in "+testTime+"ms."); numberOfFails++; } } // ---------------------------------------------- MERGE TOPICS ----- if(!forceStop()) { hlog("Topic merge test."); boolean success = true; long startTime = System.currentTimeMillis(); int topicCount = tm.getNumTopics(); int p=0; setProgress(p); setProgressMax(1); String si0 = sis.get(0); String si1 = sis.get(1); Topic t0 = tm.getTopic(si0); Topic t1 = tm.getTopic(si1); t0.addSubjectIdentifier(new Locator(si1)); if(!t1.isRemoved()) { log("Merged topic is not marked removed. Should be marked removed."); success = false; } if(t0.isRemoved()) { log("Merging topic is marked removed. Shouldn't be marked removed."); success = false; } t0 = tm.getTopic(si0); t1 = tm.getTopic(si1); if(t0 == null || !t0.mergesWithTopic(t1)) { log("Subject identifiers don't return same topic after merge. Should return."); success = false; } int topicCountAfterMerge = tm.getNumTopics(); if(topicCountAfterMerge >= topicCount) { log("Number of topics hasn't decreased during the merge. Should have decreased by one."); success = false; } long testTime = System.currentTimeMillis() - startTime; if(success) { log("Topic merge test passed in "+testTime+"ms."); } else { log("Topic merge test failed in "+testTime+"ms."); numberOfFails++; } } // -------------------------------------------- MERGE TOPICS 2 ----- if(!forceStop()) { hlog("Topic merge test 2."); boolean success = true; long startTime = System.currentTimeMillis(); int topicCount = tm.getNumTopics(); int p=0; setProgress(p); setProgressMax(1); String si0 = sis.get(2); String si1 = sis.get(3); Topic t0 = tm.getTopic(si0); Topic t1 = tm.getTopic(si1); String randomBasename = getRandomString(); t1.setBaseName(randomBasename); t0.setBaseName(randomBasename); // Merges t1 into t0. if(!t1.isRemoved()) { log("Merged topic is not marked removed. Should be removed."); success = false; } if(t0.isRemoved()) { log("Merging topic is marked removed. Shouldn't be removed."); success = false; } t0 = tm.getTopic(si0); t1 = tm.getTopic(si1); Topic t2 = tm.getTopicWithBaseName(randomBasename); if(t0 == null || !t0.mergesWithTopic(t1)) { log("Subject identifiers don't return same topic after merge. Should return."); success = false; } if(t2 == null || !t2.mergesWithTopic(t0)) { log("Basename doesn't return same topic as the subject identifier. Should return."); success = false; } if(t2 == null || !t2.mergesWithTopic(t1)) { log("Basename doesn't return same topic as the subject identifier. Should return."); success = false; } int topicCountAfterMerge = tm.getNumTopics(); if(topicCountAfterMerge >= topicCount) { log("Number of topics hasn't decreased during the merge. Should have decreased by one."); success = false; } long testTime = System.currentTimeMillis() - startTime; if(success) { log("Topic merge test 2 passed in "+testTime+"ms."); } else { log("Topic merge test 2 failed in "+testTime+"ms."); numberOfFails++; } } // -------------------------------------------- MERGE TOPICS 3 ----- if(!forceStop()) { hlog("Topic merge test 3."); boolean success = true; long startTime = System.currentTimeMillis(); int topicCount = tm.getNumTopics(); int p=0; setProgress(p); setProgressMax(1); String si0 = sis.get(4); String si1 = sis.get(5); Topic t0 = tm.getTopic(si0); Topic t1 = tm.getTopic(si1); String bn0 = getRandomString(); String bn1 = getRandomString(); t1.setBaseName(bn1); t0.setBaseName(bn0); Locator sl = new Locator("http://wandora.org/si/test-subject-locator-merging/"+System.currentTimeMillis()); t1.setSubjectLocator(sl); t0.setSubjectLocator(sl); // Merges t1 into t0. if(!t1.isRemoved()) { log("Merged topic is not marked removed. Should be removed."); success = false; } if(t0.isRemoved()) { log("Merging topic is marked removed. Shouldn't be removed."); success = false; } String bna = t0.getBaseName(); if(bn0.equals(bna)) { log("After merge the basename of the merged topic is the name of the merging topic. Shouldn't be."); success = false; } if(!bn1.equals(bna)) { log("After merge the basename of the merged topic is not the name of the removed topic. Should be."); success = false; } t0 = tm.getTopic(si0); t1 = tm.getTopic(si1); if(!t0.mergesWithTopic(t1)) { log("Subject identifiers don't return same topic after the merge. Should return."); success = false; } int topicCountAfterMerge = tm.getNumTopics(); if(topicCountAfterMerge >= topicCount) { log("Number of topics hasn't decreased during the merge. Should have decreased by one."); success = false; } long testTime = System.currentTimeMillis() - startTime; if(success) { log("Topic merge test 3 passed in "+testTime+"ms."); } else { log("Topic merge test 3 failed in "+testTime+"ms."); numberOfFails++; } } // ------------------------------------------------ TEST TYPES ----- if(!forceStop()) { hlog("Topic type test."); boolean success = true; long startTime = System.currentTimeMillis(); int p=0; setProgress(p); setProgressMax(1); String si0 = sis.get(6); String si1 = sis.get(7); Topic t0 = tm.getTopic(si0); Topic t1 = tm.getTopic(si1); t0.addType(t1); if(!t0.isOfType(t1)) { log("Failed to retrieve type with isOfType."); success = false; } Collection<Topic> types = t0.getTypes(); if(types == null || !types.contains(t1)) { log("Failed to retrieve type with getTypes."); success = false; } t0.removeType(t1); if(t0.isOfType(t1)) { log("IsOfType still gets the type even if removed."); success = false; } types = t0.getTypes(); if(types != null && types.contains(t1)) { log("GetTypes still gets the type even if removed."); success = false; } long testTime = System.currentTimeMillis() - startTime; if(success) { log("Topic type test passed in "+testTime+"ms."); } else { log("Topic type test failed in "+testTime+"ms."); numberOfFails++; } } // ---------------------------------------------- DELETE TOPIC ----- if(!forceStop()) { hlog("Topic delete test."); long startTime = System.currentTimeMillis(); int topicCount = tm.getNumTopics(); int deleteCount = 0; int p=0; setProgress(p); setProgressMax(numberOfTestTopics); for(String si : sis) { Topic t = tm.getTopic(si); if(t != null) { if(!t.isRemoved()) { deleteCount++; } t.remove(); } setProgress(p++); if(forceStop()) break; } int newTopicCount = tm.getNumTopics(); long testTime = System.currentTimeMillis() - startTime; if(deleteCount > 0 && topicCount-deleteCount == newTopicCount) { log("Topic delete test passed in "+testTime+"ms."); } else { log("Topic delete test failed in "+testTime+"ms."); log("Number of topics before delete was "+topicCount); log("Number of topics after delete was "+newTopicCount); numberOfFails++; } } // ---------------------------------------------- END OF TESTS ----- if(numberOfFails > 0) { log("Failed "+numberOfFails+" tests."); } else { log("Passed all tests."); } } catch(Exception e) { log(e); } setState(WAIT); } private String getRandomString() { StringBuilder stringBuilder = new StringBuilder(""); for(long i=Math.round(100+Math.random()*2000); i>0; i--) { stringBuilder.append((char) Math.floor(1+Math.random()*9000)); } return stringBuilder.toString(); } }
31,870
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AssociationTest.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/testing/AssociationTest.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.wandora.application.tools.testing; import java.util.ArrayList; import java.util.Collection; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; /** * * @author akivela */ public class AssociationTest extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; @Override public String getName() { return "Various association tests"; } @Override public String getDescription() { return "Various association tests."; } @Override public void execute(Wandora wandora, Context context) { try { setDefaultLogger(); setLogTitle("Various association tests"); TopicMap tm = wandora.getTopicMap(); ArrayList<String> sis = new ArrayList<>(); int numberOfTestTopics = 30; int numberOfFails = 0; int numberOfRepeats = 1; int maxNumberOfRoles = 15; // --------------------------------------------- CREATE TOPICS ----- if(!forceStop()) { hlog("Topic creation."); long startTime = System.currentTimeMillis(); int topicCount = tm.getNumTopics(); setProgress(0); setProgressMax(numberOfTestTopics); for(int i=0; i<numberOfTestTopics; i++) { String si = "http://wandora.org/si/test-topic/"+System.currentTimeMillis()+"/"+i; Topic t = tm.createTopic(); t.addSubjectIdentifier(new Locator(si)); t.setBaseName("t"+(i<10 ? "0" : "")+i); sis.add(si); setProgress(i); if(forceStop()) break; } int newTopicCount = tm.getNumTopics(); long testTime = System.currentTimeMillis() - startTime; if(newTopicCount != topicCount+numberOfTestTopics) { log("Topic creation failed in "+testTime+"ms."); numberOfFails++; } } // --------------------------------------- CREATE ASSOCIATIONS ----- if(!forceStop()) { hlog("Association creation test."); long startTime = System.currentTimeMillis(); boolean success = true; setProgress(0); setProgressMax(maxNumberOfRoles); int numberOfAssociations = tm.getNumAssociations(); String typesi = sis.get(0); Topic type = tm.getTopic(typesi); ArrayList<Association> associations = new ArrayList<Association>(); for(int k=1; k<maxNumberOfRoles; k++) { setProgress(k); ArrayList<Topic> roles = new ArrayList<Topic>(); for(int j=0; j<k; j++) { String rolesi = sis.get(j); Topic role = tm.getTopic(rolesi); roles.add(role); } for(int i=0; i<numberOfTestTopics-k; i++) { Association a = tm.createAssociation(type); for(int j=0; j<k; j++) { String playersi = sis.get(i+j); Topic player = tm.getTopic(playersi); a.addPlayer(player, roles.get(j)); } associations.add(a); } } int numberOfAssociationsAfterwards = tm.getNumAssociations(); int delta = numberOfAssociationsAfterwards-numberOfAssociations; if(delta != numberOfTestTopics-1) { log("Wrong number of associations created. Associations don't merge properly."); success = false; } long testTime = System.currentTimeMillis() - startTime; if(success) { log("Association creation test passed in "+testTime+"ms."); } else { log("Association creation test failed in "+testTime+"ms."); numberOfFails++; } } // ------------------------------------------ GET ASSOCIATIONS ----- if(!forceStop()) { hlog("Association access test."); long startTime = System.currentTimeMillis(); boolean success = true; Topic t0 = tm.getTopic(sis.get(0)); Collection<Association> assocs = tm.getAssociationsOfType(t0); if(assocs.size() != numberOfTestTopics-1) { log("Number of requested associations is wrong."); success = false; } for(Association a : assocs) { Topic type = a.getType(); if(!t0.mergesWithTopic(type)) { log("Association type is not the expected one."); success = false; } } for(int i=0; i<maxNumberOfRoles; i++) { Topic ti = tm.getTopic(sis.get(i)); Collection<Association> tia = ti.getAssociations(); int n = Math.min(i+1, maxNumberOfRoles-1); if(tia.size() != n) { log("Number of associations is not the expected one ("+n+")."); success = false; } } for(Association a : assocs) { Topic p = a.getPlayer(t0); int n = Integer.parseInt(p.getBaseName().substring(1)); for(int i=1; i<maxNumberOfRoles; i++) { if(n+i < maxNumberOfRoles) { Topic ri = tm.getTopic(sis.get(i)); Topic pi = a.getPlayer(ri); if(pi != null) { Topic px = tm.getTopic(sis.get(n+i)); if(!pi.mergesWithTopic(px)) { log("Association has wrong player."); success = false; } } } } } long testTime = System.currentTimeMillis() - startTime; if(success) { log("Association access test passed in "+testTime+"ms."); } else { log("Association access test failed in "+testTime+"ms."); numberOfFails++; } } // --------------------------------------- DELETE ASSOCIATIONS ----- if(!forceStop()) { hlog("Association delete test."); long startTime = System.currentTimeMillis(); boolean success = true; Topic t0 = tm.getTopic(sis.get(0)); Collection<Association> assocs = tm.getAssociationsOfType(t0); for(Association a : assocs) { a.remove(); } assocs = tm.getAssociationsOfType(t0); if(assocs.size() > 0) { log("Failed to remove all associations"); success = false; } long testTime = System.currentTimeMillis() - startTime; if(success) { log("Association delete test passed in "+testTime+"ms."); } else { log("Association delete test failed in "+testTime+"ms."); numberOfFails++; } } // ---------------------------------------------- END OF TESTS ----- if(numberOfFails > 0) { log("Failed "+numberOfFails+" tests."); } else { log("Passed all tests."); } } catch(Exception e) { log(e); } setState(WAIT); } }
9,765
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AssociateNearByOccurrenceCarriers.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/occurrences/AssociateNearByOccurrenceCarriers.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * */ package org.wandora.application.tools.occurrences; import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.application.tools.GenericOptionsDialog; import org.wandora.application.tools.extractors.ExtractHelper; import org.wandora.topicmap.Association; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author akivela */ public class AssociateNearByOccurrenceCarriers extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; private boolean requiresRefresh = false; private Context preferredContext = null; public static final String NEARBY_TYPE = "http://wandora.org/si/nearby-points/"; public static final String POINT_A_TYPE = "http://wandora.org/si/nearby-points/point-1"; public static final String POINT_B_TYPE = "http://wandora.org/si/nearby-points/point-2"; public AssociateNearByOccurrenceCarriers() { } public AssociateNearByOccurrenceCarriers(Context context) { this.preferredContext = context; } @Override public String getName() { return "Associate near by occurrence carriers"; } @Override public String getDescription() { return "Associate near by occurrence carriers"; } @Override public boolean requiresRefresh() { return requiresRefresh; } @Override public void execute(Wandora admin, Context context) { requiresRefresh = false; // This tool doesn't use context! //Iterator topics = null; //if(preferredContext != null) topics = preferredContext.getContextObjects(); //else topics = context.getContextObjects(); try { int pointAcount = 0; int pointBcount = 0; int acount = 0; TopicMap tm = admin.getTopicMap(); GenericOptionsDialog god=new GenericOptionsDialog(admin, "Find nearby point occurrences and associate occurrence carriers.", "Find nearby point occurrences and associate occurrence carriers.",true,new String[][]{ new String[]{"Occurrence type (A) of points","topic","","Type of occurrences that contain points"}, new String[]{"Occurrence type (B) of points","topic","","Type of occurrences that contain points"}, new String[]{"Scope of occurrences","topic","","Scope i.e. language of changed occurrences"}, new String[]{"Maximum distance (km)","String","","Allowed distance between points in kilometers"}, new String[]{"Reverse point (B) coordinates","boolean","","Swap latitude with longitude"}, },admin); god.setVisible(true); if(god.wasCancelled()) return; Map<String,String> values=god.getValues(); Topic pointAType = tm.getTopic(values.get("Occurrence type (A) of points")); Topic pointBType = tm.getTopic(values.get("Occurrence type (B) of points")); Topic scopeTopic = tm.getTopic(values.get("Scope of occurrences")); String maxDistanceStr = values.get("Maximum distance (km)"); double maxDistance = 1; try { maxDistance = Double.parseDouble(maxDistanceStr); } catch(Exception e) { log("Invalid maximum distance. Using default maximum distance "+maxDistance); e.printStackTrace(); } boolean reversePointCoordinates = "true".equalsIgnoreCase(values.get("Reverse point (B) coordinates")); setDefaultLogger(); setLogTitle("Finding nearby point occurrences..."); Iterator<Topic> allTopics = tm.getTopics(); Map<Topic,GeoLocation> pointAOccurrences = new LinkedHashMap<>(); Map<Topic,GeoLocation> pointBOccurrences = new LinkedHashMap<>(); try { log("Looking for point occurrences..."); while(allTopics.hasNext()) { Topic topic = allTopics.next(); if(topic != null && !topic.isRemoved()) { if(pointAType != null) { Hashtable<Topic,String> scopedOccurrences = topic.getData(pointAType); if(scopedOccurrences != null && scopedOccurrences.size() > 0) { if(scopeTopic != null) { String occurrence = scopedOccurrences.get(scopeTopic); if(occurrence != null) { GeoLocation location = parseGeoLocation(occurrence); if(location != null) { pointAcount++; pointAOccurrences.put(topic, location); } } } else { Enumeration<Topic> scopeTopics = scopedOccurrences.keys(); while(scopeTopics.hasMoreElements()) { Topic oscopeTopic = scopeTopics.nextElement(); String occurrence = scopedOccurrences.get(oscopeTopic); if(occurrence != null && occurrence.length() > 0) { GeoLocation location = parseGeoLocation(occurrence); if(location != null) { pointAcount++; pointAOccurrences.put(topic, location); } break; } } } } } if(pointBType != null) { Hashtable<Topic,String> scopedOccurrences = topic.getData(pointBType); if(scopedOccurrences != null && scopedOccurrences.size() > 0) { if(scopeTopic != null) { String occurrence = scopedOccurrences.get(scopeTopic); if(occurrence != null) { GeoLocation location = parseGeoLocation(occurrence, reversePointCoordinates); if(location != null) { pointBcount++; pointBOccurrences.put(topic, location); } } } else { Enumeration<Topic> scopeTopics = scopedOccurrences.keys(); while(scopeTopics.hasMoreElements()) { Topic oscopeTopic = scopeTopics.nextElement(); String occurrence = scopedOccurrences.get(oscopeTopic); if(occurrence != null && occurrence.length() > 0) { GeoLocation location = parseGeoLocation(occurrence, reversePointCoordinates); if(location != null) { pointBcount++; pointBOccurrences.put(topic, location); } break; } } } } } } } log("Total " + pointAcount + " point (A) occurrences found!"); log("Total " + pointBcount + " point (B) occurrences found!"); log("Looking for nearby points..."); int progress = 0; setProgress(progress); setProgressMax(pointAcount); for(Topic pointAKey : pointAOccurrences.keySet()) { setProgress(progress++); if(forceStop()) break; GeoLocation pointA = pointAOccurrences.get(pointAKey); for(Topic pointBKey : pointBOccurrences.keySet()) { if(forceStop()) break; GeoLocation pointB = pointBOccurrences.get(pointBKey); if(pointB != null) { double distance = pointB.distanceInKM(pointA); if(distance != -1 && distance < maxDistance) { associate(pointAKey, pointBKey, tm); acount++; } } } } } catch (Exception e) { log(e); } if(acount > 0) { requiresRefresh = true; log("Total " + acount + " nearby associations created!"); } else { requiresRefresh = false; log("No nearby associations created!"); } } catch(Exception e) { log(e); } setState(WAIT); } private GeoLocation parseGeoLocation(String p) { return parseGeoLocation(p, false); } private GeoLocation parseGeoLocation(String p, boolean rev) { if(p != null) { String[] ps = p.split("[,; ]"); if(ps.length >= 2) { Double d1 = Double.parseDouble(ps[0]); Double d2 = Double.parseDouble(ps[1]); if(rev) { Double temp = d1; d1 = d2; d2 = temp; } GeoLocation l = new GeoLocation(d1, d2); return l; } } return null; } private void associate(Topic pointTopic, Topic polygonTopic, TopicMap tm) throws TopicMapException { if(tm == null || pointTopic == null || polygonTopic == null) return; Topic associationType = ExtractHelper.getOrCreateTopic(NEARBY_TYPE, "Nearby points", tm); Topic pointRole = ExtractHelper.getOrCreateTopic(POINT_A_TYPE, "Point-1", tm); Topic polygonRole = ExtractHelper.getOrCreateTopic(POINT_B_TYPE, "Point-2", tm); if(associationType != null && pointRole != null && polygonRole != null) { Association a = tm.createAssociation(associationType); a.addPlayer(pointTopic, pointRole); a.addPlayer(polygonTopic, polygonRole); } } // ------------------------------------------------------------------------- private class GeoLocation { double lat = 0; double lon = 0; public GeoLocation(double lat, double lon) { this.lat = lat; this.lon = lon; } private double d2r = Math.PI / 180; public double distanceInKM(GeoLocation o) { if(o == null) return -1; double dlong = (o.lon - lon) * d2r; double dlat = (o.lat - lat) * d2r; double a = Math.pow(Math.sin(dlat/2.0), 2) + Math.cos(lat*d2r) * Math.cos(o.lat*d2r) * Math.pow(Math.sin(dlong/2.0), 2); double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); double d = 6367 * c; return d; } } }
13,190
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
URLOccurrenceChecker.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/occurrences/URLOccurrenceChecker.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * SubjectLocatorChecker.java * * Created on 2009-11-20 */ package org.wandora.application.tools.occurrences; import java.io.File; import java.net.URL; import java.util.Collection; import java.util.Hashtable; import java.util.Iterator; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; import org.wandora.utils.IObox; /** * Performs a test to given occurrences. Test checks if the occurrence is an URL, * if the URL is a valid URL, and if the resource addressed by URL occurrences exists. * * @author akivela */ public class URLOccurrenceChecker extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; String urlExists = "EXISTS\t'<locator/>'"; String urlDoesntExists = "MISSING\t'<locator/>'"; String noURLOccurrences = "NOT URL\t'<topic/>'."; String illegalURLOccurrence = "INVALID URL\t'<topic/>'."; String topicError = "TOPIC ERROR\t'<topic/>'."; /** * <code>reportType</code> contains character set defining tool * generated reports. Possible report characters are: * * m = report missing url occurrences * s = report existing url occurrences (successful) * i = report invalid url occurrences (exception occurred) * n = report when topic has no url occurrences * e = report topic errors (topic == null || exceptions) */ String reportType = "sm"; File currentDirectory = null; Iterator<Topic> topicsToCheck; public URLOccurrenceChecker() {} public URLOccurrenceChecker(Context context) { setContext(context); } public URLOccurrenceChecker(Collection<Topic> topics) { topicsToCheck = topics.iterator(); } public URLOccurrenceChecker(Iterator<Topic> topics) { topicsToCheck = topics; } @Override public void execute(Wandora wandora, Context context) { setDefaultLogger(); if(topicsToCheck == null) { topicsToCheck = context.getContextObjects(); } if(topicsToCheck != null) { try { setLogTitle("Check URL occurrences of topics..."); Topic topic = null; int validURLOccurrences = 0; int invalidURLOccurrences = 0; int totalOccurrences = 0; int totalURLOccurrences = 0; int topicsChecked = 0; CheckResult result = null; while(topicsToCheck.hasNext() && !forceStop()) { try { topicsChecked++; topic = (Topic) topicsToCheck.next(); if(topic != null && !topic.isRemoved()) { result = checkURLOccurrences(topic); validURLOccurrences += result.validURLOccurrences; invalidURLOccurrences += result.invalidURLOccurrences; totalURLOccurrences += result.totalURLOccurrences; totalOccurrences += result.totalOccurrences; } } catch (Exception e) { log(e); } setLogTitle("Check URL occurrences in topics... " + topicsChecked); } log(topicsChecked + " topics checked."); log(totalOccurrences + " occurrences checked."); log(totalURLOccurrences + " URL occurrences checked."); log(validURLOccurrences + " valid and existing url occurrences found."); log(invalidURLOccurrences + " invalid or missing url occurrences found."); } catch (Exception e) { log(e); } setState(WAIT); topicsToCheck = null; } } @Override public String getName() { return "Check URL occurrences"; } @Override public String getDescription() { return "Check if URL occurrences of given topics really resolve existing resource."; } public CheckResult checkURLOccurrences(Topic t) throws TopicMapException { int valid = 0; int invalid = 0; int totalOccurrences = 0; int totalUrls = 0; if(t != null) { Collection<Topic> occurrenceTypes = t.getDataTypes(); for(Topic occurrenceType : occurrenceTypes) { Hashtable<Topic, String> occurrences = t.getData(occurrenceType); for(String occurrence : occurrences.values()) { totalOccurrences++; URL urlOccurrence = getURLOccurrence(occurrence); if(urlOccurrence != null) { totalUrls++; try { if(IObox.urlExists(urlOccurrence)) { if(reportAbout('s')) log(urlExists.replaceAll("<locator/>", urlOccurrence.toExternalForm())); valid++; } else { if(reportAbout('m')) log(urlDoesntExists.replaceAll("<locator/>", urlOccurrence.toExternalForm())); invalid++; } } catch (Exception e) { if(reportAbout('i')) { log(illegalURLOccurrence.replaceAll("<topic/>", t.getBaseName())); log("\t"+e.toString()); invalid++; } } } } } if(valid == 0) { if(reportAbout('i')) { log(noURLOccurrences.replace("<topic/>", t.getBaseName())); } } } else { if(reportAbout('e')) { log(topicError.replaceAll("<topic/>", "TOPIC IS NULL")); } } return new CheckResult(valid, invalid, totalUrls, totalOccurrences); } private boolean reportAbout(char reportCode) { return ( reportType.indexOf(reportCode) != -1 ); } private URL getURLOccurrence(String urlString) { if(urlString != null) { urlString = urlString.trim(); if(urlString.startsWith("http://") || urlString.startsWith("https://") || urlString.startsWith("file://") || urlString.startsWith("ftp://") || urlString.startsWith("ftps://")) { try { URL url = new URL(urlString); return url; } catch(Exception e) { e.printStackTrace(); } } } //System.out.println("NOT A URL: '"+urlString+"'"); return null; } // ------------------------------------------------------------------------- public class CheckResult { int validURLOccurrences = 0; int invalidURLOccurrences = 0; int totalOccurrences = 0; int totalURLOccurrences = 0; public CheckResult(int v, int i, int t, int to) { validURLOccurrences = v; invalidURLOccurrences = i; totalURLOccurrences = t; totalOccurrences = to; } } }
8,380
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
FindPointInPolygonOccurrence.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/occurrences/FindPointInPolygonOccurrence.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * */ package org.wandora.application.tools.occurrences; import java.awt.Point; import java.awt.Polygon; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.application.tools.GenericOptionsDialog; import org.wandora.application.tools.extractors.ExtractHelper; import org.wandora.topicmap.Association; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author akivela */ public class FindPointInPolygonOccurrence extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; private boolean requiresRefresh = false; private Context preferredContext = null; public static final String INCLUSION_TYPE = "http://wandora.org/si/find-point-in-polygon/inclusion"; public static final String POINT_TYPE = "http://wandora.org/si/find-point-in-polygon/point"; public static final String POLYGON_TYPE = "http://wandora.org/si/find-point-in-polygon/polygon"; private boolean reversePointCoordinates = false; public FindPointInPolygonOccurrence() { } public FindPointInPolygonOccurrence(Context context) { this.preferredContext = context; } @Override public String getName() { return "Find point in polygon occurrences"; } @Override public String getDescription() { return "Find point occurrences in polygon occurrences and if inclusion is "+ "detected associate point occurrence carrier topic with the polygon "+ "occurrence carrier topic. Tool can be used to associate geo location "+ "topics, for example."; } @Override public boolean requiresRefresh() { return requiresRefresh; } public void execute(Wandora wandora, Context context) { requiresRefresh = false; Iterator topics = null; if(preferredContext != null) topics = preferredContext.getContextObjects(); else topics = context.getContextObjects(); try { int pointcount = 0; int polygoncount = 0; int acount = 0; TopicMap tm = wandora.getTopicMap(); GenericOptionsDialog god=new GenericOptionsDialog(wandora, "Find point occurrences in polygon occurrence and associate", "Select point and polygon occurrence types.",true,new String[][]{ new String[]{"Type of point carrier topics","topic","","Type of topics carrying the point occurrence"}, new String[]{"Type of polygon carrier topics","topic","","Type of topics carrying the polygon occurrence"}, new String[]{"Occurrence type of points","topic","","Type of occurrences that contain points"}, new String[]{"Occurrence type of polygons","topic","","Type of occurrences that contain polygons"}, new String[]{"Scope of occurrences","topic","","Scope i.e. language of changed occurrences"}, new String[]{"Reverse point coordinates","boolean","","Swap latitude with longitude"}, },wandora); god.setVisible(true); if(god.wasCancelled()) return; Map<String,String> values=god.getValues(); Topic pointType = tm.getTopic(values.get("Type of point carrier topics")); Topic polygonType = tm.getTopic(values.get("Type of polygon carrier topics")); Topic pointOType = tm.getTopic(values.get("Occurrence type of points")); Topic polygonOType = tm.getTopic(values.get("Occurrence type of polygons")); Topic scopeTopic = tm.getTopic(values.get("Scope of occurrences")); reversePointCoordinates = "true".equalsIgnoreCase(values.get("Reverse point coordinates")); setDefaultLogger(); setLogTitle("Finding point in polygons occurrences..."); Collection<Topic> pointTopics = new ArrayList<>(); if(pointType == null) { while(topics.hasNext() && !forceStop()) { pointTopics.add((Topic) topics.next()); } } else { pointTopics = tm.getTopicsOfType(pointType); } Collection<Topic> polygonTopics = new ArrayList<>(); if(polygonType == null) { while(topics.hasNext() && !forceStop()) { polygonTopics.add((Topic) topics.next()); } } else { polygonTopics = tm.getTopicsOfType(polygonType); } HashMap<Topic,String> pointOccurrences = new HashMap<>(); HashMap<Topic,String> polygonOccurrences = new HashMap<>(); try { log("Looking for point occurrences..."); for(Topic topic : pointTopics) { if(topic != null && !topic.isRemoved()) { if(pointOType != null) { Hashtable<Topic,String> scopedOccurrences = topic.getData(pointOType); if(scopedOccurrences != null && scopedOccurrences.size() > 0) { if(scopeTopic != null) { String occurrence = scopedOccurrences.get(scopeTopic); if(occurrence != null) { pointcount++; pointOccurrences.put(topic, occurrence); } } else { Enumeration<Topic> scopeTopics = scopedOccurrences.keys(); while(scopeTopics.hasMoreElements()) { Topic oscopeTopic = scopeTopics.nextElement(); String occurrence = scopedOccurrences.get(oscopeTopic); if(occurrence != null && occurrence.length() > 0) { pointcount++; pointOccurrences.put(topic, occurrence); break; } } } } } } } log("Total " + pointcount + " point occurrences found!"); log("Looking for polygon occurrences..."); for(Topic topic : polygonTopics) { if(topic != null && !topic.isRemoved()) { if(polygonOType != null) { Hashtable<Topic,String> scopedOccurrences = topic.getData(polygonOType); if(scopedOccurrences != null && scopedOccurrences.size() > 0) { if(scopeTopic != null) { String occurrence = scopedOccurrences.get(scopeTopic); if(occurrence != null) { polygoncount++; polygonOccurrences.put(topic, occurrence); } } else { Enumeration<Topic> scopeTopics = scopedOccurrences.keys(); while(scopeTopics.hasMoreElements()) { Topic oscopeTopic = scopeTopics.nextElement(); String occurrence = scopedOccurrences.get(oscopeTopic); if(occurrence != null && occurrence.length() > 0) { polygoncount++; polygonOccurrences.put(topic, occurrence); break; } } } } } } } log("Total " + polygoncount + " polygon occurrences found!"); log("Looking for points in polygons..."); int progress = 0; setProgress(progress); setProgressMax(pointOccurrences.size()); for(Topic pointKey : pointOccurrences.keySet()) { setProgress(progress++); if(forceStop()) break; String point = pointOccurrences.get(pointKey); for(Topic polygonKey : polygonOccurrences.keySet()) { if(forceStop()) break; String polygon = polygonOccurrences.get(polygonKey); if(isInside(point, polygon)) { associate(pointKey, polygonKey, tm); acount++; } } } } catch (Exception e) { log(e); } if(acount > 0) requiresRefresh = true; log("Total " + acount + " associations created!"); } catch(Exception e) { log(e); } setState(WAIT); } private boolean isInside(String point, String polygon) { Point p = parsePoint(point); Polygon pol = parsePolygon(polygon); if(p == null || pol == null) return false; return pol.contains(p); } private Point parsePoint(String p) { String[] ps = p.split("[,; ]"); if(ps.length >= 2) { Double d1 = Double.parseDouble(ps[0]); Double d2 = Double.parseDouble(ps[1]); if(reversePointCoordinates) { Double temp = d1; d1 = d2; d2 = temp; } Point point = new Point(getAsInt(d1), getAsInt(d2)); return point; } return null; } private Polygon parsePolygon(String p) { String[] ps = p.split("[,; ]"); if(ps.length >= 2) { Polygon polygon = new Polygon(); for(int i=0; i+1<ps.length; i=i+2) { Double d1 = Double.parseDouble(ps[i]); Double d2 = Double.parseDouble(ps[i+1]); polygon.addPoint(getAsInt(d1), getAsInt(d2)); } return polygon; } return null; } private int getAsInt(Double d) { return (int) Math.round(d * 1000000); } private void associate(Topic pointTopic, Topic polygonTopic, TopicMap tm) throws TopicMapException { if(tm == null || pointTopic == null || polygonTopic == null) return; Topic associationType = ExtractHelper.getOrCreateTopic(INCLUSION_TYPE, "Point in polygon", tm); Topic pointRole = ExtractHelper.getOrCreateTopic(POINT_TYPE, "Point", tm); Topic polygonRole = ExtractHelper.getOrCreateTopic(POLYGON_TYPE, "Polygon", tm); if(associationType != null && pointRole != null && polygonRole != null) { Association a = tm.createAssociation(associationType); a.addPlayer(pointTopic, pointRole); a.addPlayer(polygonTopic, polygonRole); } } // ------------------------------------------------------------------------- }
12,840
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
OccurrenceRegexReplacerOne.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/occurrences/OccurrenceRegexReplacerOne.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * OccurrenceRegexReplacerOne.java * * Created on 10.7.2007, 13:00 * */ package org.wandora.application.tools.occurrences; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.contexts.TopicContext; import org.wandora.application.gui.RegularExpressionEditor; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.Topic; /** * Applies given regular expression to user addressed occurrences. * User must select the occurrence type and language. Regular expression * may change the occurrence text. * * @author akivela */ public class OccurrenceRegexReplacerOne extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; RegularExpressionEditor editor = null; public OccurrenceRegexReplacerOne() { setContext(new TopicContext()); } public OccurrenceRegexReplacerOne(Context preferredContext) { setContext(preferredContext); } @Override public String getName() { return "Occurrence regular expression replacer"; } @Override public String getDescription() { return "Applies given regular expression to user addressed occurrences. "+ "User must select the occurrence type and language."; } @Override public void execute(Wandora wandora, Context context) { Iterator topics = context.getContextObjects(); if(topics == null || !topics.hasNext()) return; try { Topic otype = wandora.showTopicFinder("Select occurrence type..."); if( otype == null ) return; Topic oscope = wandora.showTopicFinder("Select occurrence language..."); if( oscope == null ) return; editor = RegularExpressionEditor.getReplaceExpressionEditor(wandora); editor.approve = false; editor.setVisible(true); if(editor.approve == true) { setDefaultLogger(); log("Transforming occurrences with regular expression."); Topic topic = null; Topic type = null; Topic scope = null; String occurrence = null; String newOccurrence = null; Iterator typeIterator = null; ArrayList updatedOccurrences = new ArrayList(); Collection<Topic> types = null; Hashtable<Topic, String> occurrences = null; int progress = 0; int count = 0; while(topics.hasNext() && !forceStop()) { try { topic = (Topic) topics.next(); if(topic != null && !topic.isRemoved()) { hlog("Investigating topic '" + getTopicName(topic) + "'."); progress++; setProgress(progress); types = topic.getDataTypes(); if(types != null) { typeIterator = types.iterator(); while(typeIterator.hasNext() && !topic.isRemoved()) { try { type = (Topic) typeIterator.next(); if(type != null && type.mergesWithTopic(otype)) { occurrences = topic.getData(type); if(occurrences != null) { for(Enumeration occurrenceScopes = occurrences.keys(); occurrenceScopes.hasMoreElements();) { scope = (Topic) occurrenceScopes.nextElement(); if(scope != null && scope.mergesWithTopic(oscope)) { occurrence = occurrences.get(scope); newOccurrence = editor.replace(occurrence); if(newOccurrence != null && !occurrence.equals(newOccurrence)) { updatedOccurrences.add(topic); updatedOccurrences.add(type); updatedOccurrences.add(scope); updatedOccurrences.add(newOccurrence); } } } } } } catch(Exception e) { log(e); } } } } } catch(Exception e) { log(e); } } log("Updating changed occurrences."); setProgress(0); setProgressMax(updatedOccurrences.size()); progress = 0; String newo = null; for(Iterator i = updatedOccurrences.iterator(); i.hasNext() && !forceStop();) { try { setProgress(++progress); topic = (Topic) i.next(); type = (Topic) i.next(); scope = (Topic) i.next(); newo = (String) i.next(); if(topic != null && type != null && scope != null && newo != null) { topic.setData(type, scope, newo); count++; } } catch(Exception e) { log(e); } } log("Total "+count+" occurrences changed!"); } } catch (Exception e) { log(e); } setState(WAIT); } }
7,376
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DeleteAllOccurrences.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/occurrences/DeleteAllOccurrences.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * */ package org.wandora.application.tools.occurrences; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; /** * * @author akivela */ public class DeleteAllOccurrences extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; public DeleteAllOccurrences(Context proposedContext) { this.setContext(proposedContext); } @Override public String getName() { return "Delete all occurrences"; } @Override public String getDescription() { return "Delete all occurrences of given topic."; } @Override public void execute(Wandora wandora, Context context) throws TopicMapException { Object contextSource = context.getContextSource(); Iterator topics = getContext().getContextObjects(); Topic topic = null; int count = 0; ArrayList<Topic> allOccurrenceTypes = new ArrayList<Topic>(); if(topics!= null && topics.hasNext()) { while(topics.hasNext() && !forceStop()) { topic = (Topic) topics.next(); if(topic != null && !topic.isRemoved()) { Collection<Topic> types=topic.getDataTypes(); if(types.isEmpty()) continue; for(Topic type : types) { try { Collection<Topic> scopes = new ArrayList<>(topic.getData(type).keySet()); for(Topic scope : scopes) { topic.removeData(type, scope); count++; } count++; } catch(Exception e) { log(e); } } } } } } }
3,033
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
OccurrenceRegexReplacerAll.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/occurrences/OccurrenceRegexReplacerAll.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * OccurrenceRegexReplacer.java * * Created on 10.7.2007, 13:00 * */ package org.wandora.application.tools.occurrences; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.contexts.TopicContext; import org.wandora.application.gui.RegularExpressionEditor; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.Topic; /** * Applies given regular expression to all occurrences. Regular expression * may change the occurrence text. * * @author akivela */ public class OccurrenceRegexReplacerAll extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; RegularExpressionEditor editor = null; public OccurrenceRegexReplacerAll() { setContext(new TopicContext()); } public OccurrenceRegexReplacerAll(Context preferredContext) { setContext(preferredContext); } @Override public String getName() { return "Occurrence regular expression replacer"; } @Override public String getDescription() { return "Applies given regular expression to all occurrences."; } @Override public void execute(Wandora admin, Context context) { Iterator topics = context.getContextObjects(); if(topics == null || !topics.hasNext()) return; try { editor = RegularExpressionEditor.getReplaceExpressionEditor(admin); editor.approve = false; editor.setVisible(true); if(editor.approve == true) { setDefaultLogger(); log("Transforming occurrences with regular expression."); Topic topic = null; String occurrence = null; String newOccurrence = null; Collection scopes = null; Iterator typeIterator = null; Collection<Topic> types = null; Hashtable<Topic, String> occurrences = null; //Iterator occurrenceIterator = null; Topic type = null; Topic scope = null; int progress = 0; int count = 0; List updatedOccurrences = new ArrayList(); while(topics.hasNext() && !forceStop()) { try { topic = (Topic) topics.next(); if(topic != null && !topic.isRemoved()) { hlog("Investigating topic '" + getTopicName(topic) + "'."); progress++; setProgress(progress); types = topic.getDataTypes(); if(types != null) { typeIterator = types.iterator(); while(typeIterator.hasNext() && !topic.isRemoved()) { try { type = (Topic) typeIterator.next(); occurrences = topic.getData(type); if(occurrences != null) { for(Enumeration occurrenceScopes = occurrences.keys(); occurrenceScopes.hasMoreElements();) { scope = (Topic) occurrenceScopes.nextElement(); occurrence = occurrences.get(scope); newOccurrence = editor.replace(occurrence); if(newOccurrence != null && !occurrence.equals(newOccurrence)) { updatedOccurrences.add(topic); updatedOccurrences.add(type); updatedOccurrences.add(scope); updatedOccurrences.add(newOccurrence); } } } } catch(Exception e) { log(e); } } } } } catch(Exception e) { log(e); } } log("Updating changed occurrences."); setProgress(0); setProgressMax(updatedOccurrences.size()); progress = 0; String newo = null; for(Iterator i = updatedOccurrences.iterator(); i.hasNext() && !forceStop();) { try { setProgress(++progress); topic = (Topic) i.next(); type = (Topic) i.next(); scope = (Topic) i.next(); newo = (String) i.next(); if(topic != null && type != null && scope != null && newo != null) { topic.setData(type, scope, newo); count++; } } catch(Exception e) { log(e); } } log("Total "+count+" occurrences changed!"); } } catch (Exception e) { log(e); } setState(WAIT); } }
6,733
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DownloadOccurrence.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/occurrences/DownloadOccurrence.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * DownloadOccurrence.java */ package org.wandora.application.tools.occurrences; import java.io.File; import java.net.URL; import java.util.Iterator; import java.util.Map; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.gui.OccurrenceTable; import org.wandora.application.gui.UIConstants; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.application.gui.simple.SimpleFileChooser; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.application.tools.GenericOptionsDialog; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.utils.DataURL; import org.wandora.utils.IObox; /** * Downloads URL occurrence resource and stores resource data into a file or * an occurrence. * * @author akivela */ public class DownloadOccurrence extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; public static final int TARGET_FILE = 1; public static final int TARGET_OCCURRENCE = 2; private int target = TARGET_FILE; private boolean changeOccurrence = false; private boolean overWriteAll = false; public DownloadOccurrence() { } public DownloadOccurrence(Context preferredContext) { this(preferredContext, false); } public DownloadOccurrence(int t) { target = t; } public DownloadOccurrence(int t, boolean changeOccurrence) { this.target = t; this.changeOccurrence = changeOccurrence; } public DownloadOccurrence(Context preferredContext, boolean changeOccurrence) { setContext(preferredContext); this.changeOccurrence = changeOccurrence; } private Topic typeTopic = null; private Topic langTopic = null; @Override public void execute(Wandora wandora, Context context) { Object contextSource = context.getContextSource(); // ***** TARGET OCCURRENCE ***** if(target == TARGET_OCCURRENCE) { if(contextSource instanceof OccurrenceTable) { OccurrenceTable ot = (OccurrenceTable) contextSource; ot.downloadURLOccurrence(); } } // ***** TARGET FILE ***** else { overWriteAll = false; if(contextSource instanceof OccurrenceTable) { try { File targetPath = null; OccurrenceTable ot = (OccurrenceTable) contextSource; String occurrence = ot.getPointedOccurrence(); Topic topic = ot.getTopic(); typeTopic = ot.getPointedOccurrenceType(); langTopic = ot.getPointedOccurrenceLang(); if(occurrence != null) { if(DataURL.isDataURL(occurrence)) { File targetFile = selectFile("Select target file", wandora); if(targetFile == null) return; DataURL.saveToFile(occurrence, targetFile); } else { String url = extractURLFromOccurrence(occurrence); if(url != null) { if(targetPath == null) { targetPath = selectDirectory("Select download directory", wandora); if(targetPath == null) return; } download(wandora, topic, url, targetPath); } } } } catch(Exception e) { log(e); } } else { Iterator topics = context.getContextObjects(); File targetPath = null; TopicMap tm = wandora.getTopicMap(); if(topics != null && topics.hasNext()) { try { Topic topic = null; int total = 0; int count = 0; boolean cont = true; overWriteAll = false; if(topics.hasNext()) { GenericOptionsDialog god=new GenericOptionsDialog(wandora, "Download occurrences", "To download occurrences please give occurrence type and scope topics.",true,new String[][]{ new String[]{"Type of downloaded occurrences","topic","","Type topic of occurrences"}, new String[]{"Scope of downloaded occurrences","topic","","Scope topic i.e. language of occurrences"}, },wandora); god.setVisible(true); if(god.wasCancelled()) return; Map<String,String> values=god.getValues(); typeTopic = tm.getTopic(values.get("Type of downloaded occurrences")); langTopic = tm.getTopic(values.get("Scope of downloaded occurrences")); } while(cont && topics.hasNext() && !forceStop()) { try { total++; topic = (Topic) topics.next(); if(topic != null && !topic.isRemoved()) { String occurrence = topic.getData(typeTopic, langTopic); String url = extractURLFromOccurrence(occurrence); if(url != null) { if(targetPath == null) { setState(INVISIBLE); targetPath = selectDirectory("Select download directory", wandora); setState(VISIBLE); if(targetPath == null) break; } setDefaultLogger(); setLogTitle("Download URL occurrences..."); cont = download(wandora, topic, url, targetPath); count++; } } } catch (Exception e) { log(e); } } log("Total " + total + " topics browsed!"); log("Total " + count + " occurrences downloaded!"); } catch (Exception e) { log(e); } setState(WAIT); } } } } public String extractURLFromOccurrence(String occurrence) { if(occurrence == null) return null; occurrence = occurrence.trim(); if(occurrence.length() == 0) return null; try { URL u = new URL(occurrence); return occurrence; } catch(Exception e) { // DO NOTHING } return null; } public boolean download(Wandora admin, Topic topic, String url, File target) { try { URL subjectUrl = new URL(url); String filename = subjectUrl.getPath(); String filenameWithoutExtension = filename; String filenameExtension = ""; if(filename.indexOf('/') > -1) filename = filename.substring(filename.lastIndexOf('/')); if(filename.indexOf('.') > 0) { filenameWithoutExtension = filename.substring(0, filename.lastIndexOf('.')-1); filenameExtension = filename.substring(filename.lastIndexOf('.')); } File targetFile = new File(target.getPath() + "/" + filename); if(!overWriteAll && targetFile.exists()) { int c = 1; File newFile = null; do { c++; newFile = new File(target.getPath()+"/"+filenameWithoutExtension+"_"+c+filenameExtension); } while(newFile.exists() && c < 999); int a = WandoraOptionPane.showConfirmDialog(admin, "File '"+filename+"' already exists. Overwrite file? Selecting No renames the file to "+newFile.getPath()+".", "Overwrite existing file?", WandoraOptionPane.YES_TO_ALL_NO_CANCEL_OPTION); if(a == WandoraOptionPane.NO_OPTION) targetFile = newFile; else if(a == WandoraOptionPane.CANCEL_OPTION) return false; else if(a == WandoraOptionPane.YES_TO_ALL_OPTION) overWriteAll = true; } log("Downloading occurrence content from "+subjectUrl.toExternalForm()+" to "+targetFile.getPath()); IObox.moveUrl(subjectUrl, targetFile); if(changeOccurrence) { String newOccurrence = makeFileLocator(targetFile); if(typeTopic != null || langTopic != null) { topic.setData(typeTopic, langTopic, newOccurrence); log("Topic's occurrence has been updated to "+newOccurrence); } } } catch (Exception e) { log(e); } return true; } private File selectDirectory(String directoryDialogTitle, Wandora admin) { File currentDirectory = null; try { SimpleFileChooser chooser=UIConstants.getFileChooser(); chooser.setDialogTitle(directoryDialogTitle); chooser.setApproveButtonText("Select directory"); chooser.setFileSelectionMode(SimpleFileChooser.DIRECTORIES_ONLY); if(chooser.open(admin, SimpleFileChooser.OPEN_DIALOG)==SimpleFileChooser.APPROVE_OPTION) { currentDirectory = chooser.getSelectedFile(); } else { currentDirectory = null; } } catch (Exception e) { e.printStackTrace(); } return currentDirectory; } private File selectFile(String directoryDialogTitle, Wandora admin) { File currentFile = null; try { SimpleFileChooser chooser=UIConstants.getFileChooser(); chooser.setDialogTitle(directoryDialogTitle); chooser.setApproveButtonText("Select file"); chooser.setFileSelectionMode(SimpleFileChooser.FILES_ONLY); if(chooser.open(admin, SimpleFileChooser.OPEN_DIALOG)==SimpleFileChooser.APPROVE_OPTION) { currentFile = chooser.getSelectedFile(); } else { currentFile = null; } } catch (Exception e) { e.printStackTrace(); } return currentFile; } @Override public String getName() { return "Download occurrences"; } @Override public String getDescription() { return "Downloads occurrences to local directory selected by user."; } // ------------------------------------------------------------------------- public String makeFileLocator(File f) { return f.toURI().toString(); // return "file://" + f.getPath().replace('\\', '/'); } // ------------------------------------------------------------------------- }
12,642
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MakeOccurrenceFromSubjectIdentifier.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/occurrences/MakeOccurrenceFromSubjectIdentifier.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * */ package org.wandora.application.tools.occurrences; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.regex.Pattern; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.application.tools.GenericOptionsDialog; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; /** * * @author akivela */ public class MakeOccurrenceFromSubjectIdentifier extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; public static boolean overWrite = false; private int mode = COPY_ONE; public static int COPY_ONE = 0; public static int COPY_ONE_WITH_REGEX = 1; public static int COPY_ALL = 2; /** * Creates a new instance of MakeOccurrenceFromSubjectIdentifier */ public MakeOccurrenceFromSubjectIdentifier() { } public MakeOccurrenceFromSubjectIdentifier(Context preferredContext) { setContext(preferredContext); } @Override public String getName() { return "Make occurrence using topic's subject identifier."; } @Override public String getDescription() { return "Iterates through selected topics and copies topic's subject identifier to occurrence."; } @Override public void execute(Wandora wandora, Context context) { try { setDefaultLogger(); setLogTitle("Copying subject identifier to topic occurrence"); log("Copying subject identifier to topic occurrence"); Iterator topics = context.getContextObjects(); if(topics == null || !topics.hasNext()) return; Topic topic = null; String sistr = null; Locator si = null; Collection<Locator> sis = null; String occurrence = null; Topic type = wandora.showTopicFinder("Select occurrence type..."); if(type == null) return; Topic language = wandora.showTopicFinder("Select occurrence language..."); if(language == null) return; int progress = 0; int count = 0; Pattern siPattern = null; while(topics.hasNext() && !forceStop()) { sistr = null; try { topic = (Topic) topics.next(); if(topic != null && !topic.isRemoved()) { setProgress(progress++); if(mode == COPY_ALL) { sis = topic.getSubjectIdentifiers(); StringBuilder sb = new StringBuilder(""); for(Locator s : sis) { sb.append(s.toExternalForm()); sb.append("\n"); } sistr = sb.toString(); } else if(mode == COPY_ONE_WITH_REGEX) { if(siPattern == null) { String siPatternStr = WandoraOptionPane.showInputDialog(wandora, "Enter regular expression pattern used to regocnize subject identifiers", ".*", "Enter regular expression pattern", WandoraOptionPane.QUESTION_MESSAGE); if(siPatternStr == null) return; siPattern = Pattern.compile(siPatternStr); } if(siPattern != null) { sis = topic.getSubjectIdentifiers(); for(Locator s : sis) { String str = s.toExternalForm(); if(siPattern.matcher(str).find()) { sistr = str; break; } } } } else { si = topic.getOneSubjectIdentifier(); sistr = si.toExternalForm(); } if(sistr != null && sistr.length() > 0) { occurrence = topic.getData(type, language); if(occurrence == null || overWrite) { topic.setData(type, language, sistr); count++; } } } } catch(Exception e) { log(e); } } log("Ready."); setState(WAIT); } catch (Exception e) { log(e); } } // ---------------------------------------------------------- CONFIGURE ---- @Override public boolean isConfigurable() { return true; } @Override public void configure(Wandora wandora, org.wandora.utils.Options options, String prefix) throws TopicMapException { GenericOptionsDialog god=new GenericOptionsDialog(wandora,"Make occurrence out of subject identifier options","Make occurrence out of subject identifier options",true,new String[][]{ new String[]{"Copy one subject identifier regocnized by a regular expression?","boolean",(mode == COPY_ONE_WITH_REGEX ? "true" : "false"),null }, new String[]{"Copy all subject identifiers?","boolean",(mode == COPY_ALL ? "true" : "false"), null }, },wandora); god.setVisible(true); if(god.wasCancelled()) return; Map<String, String> values = god.getValues(); boolean copyOneWithRegex = ("true".equals(values.get("Copy one subject identifier regocnized by a regular expression?")) ? true : false ); boolean copyAll = ("true".equals(values.get("Copy all subject identifiers?")) ? true : false ); if(copyAll) { mode = COPY_ALL; } else if(copyOneWithRegex) { mode = COPY_ONE_WITH_REGEX; } else { mode = COPY_ONE; } } }
7,351
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MakeOccurrencesFromVariants.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/occurrences/MakeOccurrencesFromVariants.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * MakeOccurrencesFromVariants.java * * Created on 2.3.2010, 14:55 * */ package org.wandora.application.tools.occurrences; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.XTMPSI; /** * * @author akivela */ public class MakeOccurrencesFromVariants extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; public static boolean overWrite = false; /** * Creates a new instance of MakeOccurrencesFromVariants */ public MakeOccurrencesFromVariants() { } public MakeOccurrencesFromVariants(Context preferredContext) { setContext(preferredContext); } @Override public String getName() { return "Makes occurrences using topic's variant names."; } @Override public String getDescription() { return "Iterates through selected topics and copies all topic's display variant name to occurrences."; } @Override public void execute(Wandora wandora, Context context) { try { setDefaultLogger(); setLogTitle("Copying variant names to topic occurrences"); log("Copying variant names to topic occurrences"); Iterator topics = context.getContextObjects(); if(topics == null || !topics.hasNext()) return; Topic topic = null; String variant = null; String occurrence = null; Topic type = wandora.showTopicFinder("Select occurrence type..."); if(type == null) return; Collection<Topic> languages = wandora.getTopicMap().getTopicsOfType(TMBox.LANGUAGE_SI); Topic language = null; Iterator<Topic> languageIterator = null; Set<Topic> scope = null; Topic displayScope = wandora.getTopicMap().getTopic(XTMPSI.DISPLAY); int progress = 0; while(topics.hasNext() && !forceStop()) { try { topic = (Topic) topics.next(); if(topic != null && !topic.isRemoved()) { setProgress(progress++); if(languages != null && !languages.isEmpty()) { languageIterator = languages.iterator(); while(languageIterator.hasNext()) { try { language = (Topic) languageIterator.next(); scope = new LinkedHashSet<>(); scope.add(language); scope.add(displayScope); variant = topic.getVariant(scope); occurrence = topic.getData(type, language); if(occurrence == null || overWrite) { topic.setData(type, language, variant); } } catch(Exception e) { log(e); } } } } } catch(Exception e) { log(e); } } log("Ready."); setState(WAIT); } catch (Exception e) { log(e); } } }
4,603
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MakeOccurrenceFromSubjectLocator.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/occurrences/MakeOccurrenceFromSubjectLocator.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * */ package org.wandora.application.tools.occurrences; import java.util.Iterator; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; /** * * @author akivela */ public class MakeOccurrenceFromSubjectLocator extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; public static boolean overWrite = false; /** * Creates a new instance of MakeOccurrenceFromSubjectLocator */ public MakeOccurrenceFromSubjectLocator() { } public MakeOccurrenceFromSubjectLocator(Context preferredContext) { setContext(preferredContext); } @Override public String getName() { return "Make occurrence using topic's subject locator."; } @Override public String getDescription() { return "Iterates through selected topics and copies topic's subject locator to occurrence."; } @Override public void execute(Wandora wandora, Context context) { try { setDefaultLogger(); setLogTitle("Copying subject locator to topic occurrence"); log("Copying subject locator to topic occurrence"); Iterator topics = context.getContextObjects(); if(topics == null || !topics.hasNext()) return; Topic topic = null; String slstr = null; Locator sl = null; String occurrence = null; Topic type = wandora.showTopicFinder("Select occurrence type..."); if(type == null) return; Topic language = wandora.showTopicFinder("Select occurrence language..."); if(language == null) return; int progress = 0; int count = 0; while(topics.hasNext() && !forceStop()) { try { topic = (Topic) topics.next(); if(topic != null && !topic.isRemoved()) { setProgress(progress++); sl = topic.getSubjectLocator(); if(sl != null) { slstr = sl.toExternalForm(); occurrence = topic.getData(type, language); if(occurrence == null || overWrite) { topic.setData(type, language, slstr); count++; } } } } catch(Exception e) { log(e); } } if(count == 0) log("No subject locators copied to occurrences."); else log("Total "+count+" subject locators copied to occurrences."); log("Ready."); setState(WAIT); } catch (Exception e) { log(e); } } }
3,854
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DuplicateOccurrence.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/occurrences/DuplicateOccurrence.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * */ package org.wandora.application.tools.occurrences; import java.util.ArrayList; import java.util.Hashtable; import java.util.Iterator; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.gui.OccurrenceTable; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; /** * * @author akivela */ public class DuplicateOccurrence extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; private Topic occurrenceType = null; private Topic masterTopic = null; /** Creates a new instance of DuplicateOccurrence */ public DuplicateOccurrence() { this.occurrenceType=null; } public DuplicateOccurrence(Context proposedContext) { this.setContext(proposedContext); this.occurrenceType=null; } public DuplicateOccurrence(Context proposedContext, Topic occurrenceType) { this.setContext(proposedContext); this.occurrenceType=occurrenceType; } public DuplicateOccurrence(Topic occurrenceType) { this.occurrenceType=occurrenceType; } public DuplicateOccurrence(Context proposedContext, Topic occurrenceType, Topic masterTopic) { this.setContext(proposedContext); this.occurrenceType=occurrenceType; this.masterTopic=masterTopic; } public DuplicateOccurrence(Topic occurrenceType, Topic masterTopic) { this.occurrenceType=occurrenceType; this.masterTopic=masterTopic; } @Override public String getName() { return "Duplicate occurrence"; } @Override public String getDescription() { return "Copy given occurrences to new occurrence type."; } @Override public void execute(Wandora wandora, Context context) throws TopicMapException { Object contextSource = context.getContextSource(); if(contextSource instanceof OccurrenceTable) { OccurrenceTable ot = (OccurrenceTable) contextSource; ot.duplicateType(); } else { Iterator<Topic> topics = null; if(masterTopic != null) { ArrayList<Topic> topicArray = new ArrayList<>(); topicArray.add(masterTopic); topics = topicArray.iterator(); } else { topics = context.getContextObjects(); } if(topics != null) { Topic type = occurrenceType; if(type == null || type.isRemoved()) { type = wandora.showTopicFinder("Select occurrence type to be duplicated"); } if(type != null && !type.isRemoved()) { Topic newType = wandora.showTopicFinder("Select new occurrence type"); if(newType != null && !newType.isRemoved()) { while(topics.hasNext()) { Topic topic = topics.next(); if(topic != null && !topic.isRemoved()) { Hashtable<Topic,String> os = topic.getData(occurrenceType); if(os != null && !os.isEmpty()) { for(Topic scope : os.keySet()) { if(scope != null && !scope.isRemoved()) { String occurrenceText = os.get(scope); topic.setData(newType, scope, occurrenceText); } } } } } } } } } } }
4,779
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DeleteOccurrence.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/occurrences/DeleteOccurrence.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * DeleteOccurrence.java * * Created on 23. toukokuuta 2006, 11:24 * */ package org.wandora.application.tools.occurrences; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.gui.ComboBoxTopicWrapper; import org.wandora.application.gui.OccurrenceTable; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public class DeleteOccurrence extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; private Topic masterTopic = null; private Topic occurrenceType = null; private boolean deleteAll = false; private boolean forceStop = false; /** Creates a new instance of DeleteOccurrence */ public DeleteOccurrence() { this.occurrenceType=null; } public DeleteOccurrence(Context proposedContext) { this.setContext(proposedContext); this.occurrenceType=null; } public DeleteOccurrence(Context proposedContext, Topic occurrenceType) { this.setContext(proposedContext); this.occurrenceType=occurrenceType; } public DeleteOccurrence(Topic occurrenceType) { this.occurrenceType=occurrenceType; } public DeleteOccurrence(Context proposedContext, Topic occurrenceType, Topic masterTopic) { this.setContext(proposedContext); this.occurrenceType=occurrenceType; this.masterTopic=masterTopic; } public DeleteOccurrence(Topic occurrenceType, Topic masterTopic) { this.occurrenceType=occurrenceType; this.masterTopic=masterTopic; } @Override public String getName() { return "Delete occurrence"; } @Override public String getDescription() { return "Delete occurrence of given type."; } @Override public void execute(Wandora admin, Context context) throws TopicMapException { Object contextSource = context.getContextSource(); deleteAll = false; forceStop = false; if(contextSource instanceof OccurrenceTable) { OccurrenceTable ot = (OccurrenceTable) contextSource; ot.delete(); } else { Iterator topics = null; if(masterTopic != null && !masterTopic.isRemoved()) { ArrayList<Topic> topicArray = new ArrayList<>(); topicArray.add(masterTopic); topics = topicArray.iterator(); deleteAll = true; } else { topics = getContext().getContextObjects(); } Topic topic = null; int count = 0; Topic type = occurrenceType; ArrayList<Topic> allOccurrenceTypes = new ArrayList<Topic>(); if(topics!= null && topics.hasNext()) { if(type == null) { while(topics.hasNext() && !forceStop() && !forceStop) { topic = (Topic) topics.next(); if(topic != null && !topic.isRemoved()) { Collection<Topic> types=topic.getDataTypes(); if(types.isEmpty()) continue; for(Topic t : types) { if(!allOccurrenceTypes.contains(t)) { allOccurrenceTypes.add(t); } } } } if(allOccurrenceTypes.size() > 0) { Object[] values=new Object[allOccurrenceTypes.size()]; int counter=0; for(Topic t : allOccurrenceTypes){ values[counter++]=new ComboBoxTopicWrapper(t); } Object selected=WandoraOptionPane.showOptionDialog(admin, "Which occurrence you want to delete?", "Delete occurrence", WandoraOptionPane.QUESTION_MESSAGE, values, values[0]); if(selected==null) return; type=((ComboBoxTopicWrapper)selected).topic; topics = getContext().getContextObjects(); } else { singleLog("No occurrences found in selected topics!"); } } if(type == null) return; while(topics.hasNext() && !forceStop() && !forceStop) { topic = (Topic) topics.next(); if(topic != null && !topic.isRemoved()) { if(shouldDelete(topic,type,admin)) { try { Iterator<Topic> iter=new ArrayList<>(topic.getData(type).keySet()).iterator(); while(iter.hasNext()){ Topic version=(Topic)iter.next(); topic.removeData(type,version); } count++; } catch(Exception e2) { log(e2); } } } } } } } private boolean shouldDelete(Topic topic,Topic type,Wandora parent){ if(deleteAll) return true; else { int answer = WandoraOptionPane.showConfirmDialog(parent, "Do you want to delete occurrences of type '"+parent.getTopicGUIName(type)+"' from topic '"+parent.getTopicGUIName(topic)+"'?", "Confirm delete", WandoraOptionPane.YES_TO_ALL_NO_CANCEL_OPTION); if(answer == WandoraOptionPane.YES_TO_ALL_OPTION) { deleteAll = true; return true; } else if(answer == WandoraOptionPane.YES_OPTION) { return true; } else { if(answer == WandoraOptionPane.CANCEL_OPTION) { forceStop = true; } return false; } } } }
7,373
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MakeOccurrenceFromAssociation.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/occurrences/MakeOccurrenceFromAssociation.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * MakeOccurrenceFromAssociation.java * * Created on 25. toukokuuta 2006, 10:57 * */ package org.wandora.application.tools.occurrences; import java.util.ArrayList; import java.util.Iterator; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.AssociationContext; import org.wandora.application.contexts.Context; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; /** * <p> * Transforms given associations to occurrences. * </p> * <p> * Occurrence's type will be association's type. Occurrence is constructed from * player's base name. * </p> * <p> * See also <code>MakeAssociationFromOccurrence</code> tool representing * symmetric counterpart to <code>MakeOccurrenceFromAssociation</code>. * </p> * @author akivela */ public class MakeOccurrenceFromAssociation extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; boolean deleteAssociationAndTopic = false; public MakeOccurrenceFromAssociation() { } public MakeOccurrenceFromAssociation(Context preferredContext) { setContext(preferredContext); } @Override public String getName() { return "Make occurrence out of topic's association"; } @Override public String getDescription() { return "Iterates through selected topics or associations and makes occurrences using the associated topic."; } @Override public void execute(Wandora admin, Context context) { try { Iterator associations = null; Topic associationType = null; Locator associationTypeLocator = null; Topic topic = null; Topic topicRole = null; Topic occurrenceTopic = null; Topic occurrenceRole = null; Topic occurrenceScope = null; Locator occurrenceScopeLocator = null; // If context contains associtions iterate them. Otherwise solve associations... if(context instanceof AssociationContext) { associations = context.getContextObjects(); } else { Iterator topics = context.getContextObjects(); if(topics == null || !topics.hasNext()) return; ArrayList<Association> associationArray = new ArrayList<>(); associationType = admin.showTopicFinder("Select association type..."); if(associationType == null) return; associationTypeLocator = associationType.getSubjectIdentifiers().iterator().next(); topic = null; while(topics.hasNext() && !forceStop()) { try { topic = (Topic) topics.next(); if(topic != null && !topic.isRemoved()) { associationArray.addAll(topic.getAssociations(associationType)); } } catch(Exception e) { log(e); } } } if(associations == null || !associations.hasNext()) return; // Now we have associations. Next solve hooks used to pick up the topic // new occurrence is attached and the topic that contains occurrences // text as a base name. Both hooks are roles of our associations. topicRole=admin.showTopicFinder("Select role of topic where new occurrence is attached..."); if(topicRole == null) return; occurrenceRole=admin.showTopicFinder("Select role of topic that is transformed to occurrence..."); if(occurrenceRole == null) return; occurrenceScope=admin.showTopicFinder("Select occurrences scope (language)..."); if(occurrenceScope == null) return; occurrenceScopeLocator = occurrenceScope.getSubjectIdentifiers().iterator().next(); setDefaultLogger(); setLogTitle("Making occurrences from associations"); log("Making occurrences from associations"); int progress = 0; Association a = null; String occurrenceText = null; // Iterate through selected topics... while(associations.hasNext() && !forceStop()) { try { a = (Association) associations.next(); if(a != null && !a.isRemoved()) { progress++; associationType = a.getType(); topic = a.getPlayer(topicRole); occurrenceTopic = a.getPlayer(occurrenceRole); // Check if both hooks have catched a valid topic! if(topic != null || occurrenceTopic != null) { occurrenceText = occurrenceTopic.getBaseName(); topic.setData(associationType, occurrenceScope, occurrenceText); // Finally deleting association and topic if... if(deleteAssociationAndTopic) { a.remove(); occurrenceTopic.remove(); } } } } catch(Exception e) { log(e); } } log("Ready."); setState(WAIT); } catch (Exception e) { log(e); } } }
6,790
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
OccurrenceScopeCopier.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/occurrences/OccurrenceScopeCopier.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * OccurrenceScopeCopier.java * * Created on 2008-07-16, 17:04 * */ package org.wandora.application.tools.occurrences; import java.util.Iterator; import java.util.Map; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.application.tools.GenericOptionsDialog; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; /** * Copies occurrence to other scope. Optionally removes old occurrence. * * @author akivela */ public class OccurrenceScopeCopier extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; private boolean REMOVE_AFTER_COPY = false; private boolean COPY_NULLS = true; private boolean OVERWRITE_OLDIES = true; public OccurrenceScopeCopier() { REMOVE_AFTER_COPY = false; } public OccurrenceScopeCopier(Context preferredContext) { REMOVE_AFTER_COPY = false; setContext(preferredContext); } public OccurrenceScopeCopier(boolean removeAfterCopy) { REMOVE_AFTER_COPY = false; } public OccurrenceScopeCopier(boolean removeAfterCopy, Context preferredContext) { REMOVE_AFTER_COPY = removeAfterCopy; setContext(preferredContext); } @Override public String getName() { return "Occurrence scope copier"; } @Override public String getDescription() { return "Iterates through selected topics and copies or moves user specified occurrences to other scope."; } public void execute(Wandora wandora, Context context) { try { Iterator topics = context.getContextObjects(); if(topics == null || !topics.hasNext()) return; GenericOptionsDialog god=new GenericOptionsDialog(wandora, ( REMOVE_AFTER_COPY ? "Move occurrences to other type and scope" : "Copy occurrences to type and other scope" ), "To change occurrence scopes please address source and target scopes.",true,new String[][]{ new String[]{"Type of source occurrences","topic","","Type of changed occurrences"}, new String[]{"Scope of source occurrences","topic","","Scope i.e. language of changed occurrences"}, new String[]{"Type of target occurrences","topic","","Type of new occurrences"}, new String[]{"Scope of target occurrences","topic","","Scope i.e. language of new occurrences"}, new String[]{"Overwrite existing occurrences?","boolean","false","Save existing target occurrences?"}, new String[]{"Copy also null occurrences?","boolean","false","Set target occurrences although source variant is null?"}, },wandora); god.setVisible(true); if(god.wasCancelled()) return; Map<String,String> values=god.getValues(); COPY_NULLS = "true".equals( values.get("Copy also null occurrences?") ) ? true : false; OVERWRITE_OLDIES = "true".equals( values.get("Overwrite existing occurrences?") ) ? true : false; Topic sourceTypeTopic = null; Topic sourceScopeTopic = null; Topic targetTypeTopic = null; Topic targetScopeTopic = null; TopicMap tm = null; setDefaultLogger(); if( REMOVE_AFTER_COPY ) { setLogTitle("Moving occurrences"); } else { setLogTitle("Copying occurrences"); } if( OVERWRITE_OLDIES ) log("Overwriting existing occurrences."); if( COPY_NULLS ) log("Copying also null occurrences."); int progress = 0; int processed = 0; Topic topic = null; String occurrence = ""; String targetOccurrence = null; while(topics.hasNext() && !forceStop()) { try { topic = (Topic) topics.next(); if(topic != null && !topic.isRemoved()) { tm = topic.getTopicMap(); try { sourceTypeTopic = null; sourceScopeTopic = null; targetTypeTopic = null; targetScopeTopic = null; sourceTypeTopic = tm.getTopic(values.get("Type of source occurrences")); sourceScopeTopic = tm.getTopic(values.get("Scope of source occurrences")); targetTypeTopic = tm.getTopic(values.get("Type of target occurrences")); targetScopeTopic = tm.getTopic(values.get("Scope of target occurrences")); } catch(Exception e) { } if(sourceTypeTopic != null && sourceScopeTopic != null && targetTypeTopic != null && targetScopeTopic != null) { progress++; occurrence = topic.getData(sourceTypeTopic, sourceScopeTopic); targetOccurrence = topic.getData(targetTypeTopic, targetScopeTopic); if(occurrence != null) { if(REMOVE_AFTER_COPY) topic.setData(targetTypeTopic, targetScopeTopic, null); if(targetOccurrence == null || OVERWRITE_OLDIES) { topic.setData(targetTypeTopic, targetScopeTopic, occurrence); processed++; } } else { if(COPY_NULLS) { if(targetOccurrence == null || OVERWRITE_OLDIES) { topic.setData(targetTypeTopic, targetScopeTopic, null); processed++; } } } } else { if(sourceTypeTopic == null) log("Can't find source type for "+getTopicName(topic)+". Skipping topic."); else if(sourceScopeTopic == null) log("Can't find source scope for "+getTopicName(topic)+". Skipping topic."); else if(targetTypeTopic == null) log("Can't find target type for "+getTopicName(topic)+". Skipping topic."); else if(targetScopeTopic == null) log("Can't find target scope for "+getTopicName(topic)+". Skipping topic."); } } } catch(Exception e) { log(e); } } log("Processed total " + processed + " occurrences."); setState(WAIT); } catch (Exception e) { log(e); } } }
7,913
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AddOccurrences.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/occurrences/AddOccurrences.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * AddOccurrences.java * * Created on 24. lokakuuta 2005, 19:57 * */ package org.wandora.application.tools.occurrences; import java.util.Iterator; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.gui.SchemaOccurrencePrompt; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.Topic; /** * * @deprecated * @see AddSchemalessOccurrence * @author akivela */ public class AddOccurrences extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; public AddOccurrences() {} public AddOccurrences(Context preferredContext) { setContext(preferredContext); } @Override public String getName() { return "Add occurrences"; } @Override public String getDescription() { return "Deprecated. Tool opens schema occurrence editor used to add internal occurrences to selected topic. "+ "Only schema defined occurrences can be added with this tool."; } @Override public void execute(Wandora wandora, Context context) { Iterator contextTopics = context.getContextObjects(); if(contextTopics != null && contextTopics.hasNext()) { Topic topic = (Topic) contextTopics.next(); if( !contextTopics.hasNext() && !forceStop() ) { try { if(topic != null && !topic.isRemoved()) { SchemaOccurrencePrompt prompt=new SchemaOccurrencePrompt(wandora, true, topic); prompt.setVisible(true); if(!prompt.wasCancelled()) { } } } catch(Exception e) { log(e); } } else { log("Context contains more than one topic! Unable to decide which topic to add associations to."); } } } }
2,853
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ChangeOccurrenceTableRowHeight.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/occurrences/ChangeOccurrenceTableRowHeight.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.wandora.application.tools.occurrences; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.gui.OccurrenceTable; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.TopicMapException; import org.wandora.utils.Options; /** * * @author akivela */ public class ChangeOccurrenceTableRowHeight extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; private int rowHeight = 1; private Options localOptions = null; /** Creates a new instance of ChangeOccurrenceTableRowHeight */ public ChangeOccurrenceTableRowHeight(int newRowHeight) { this.rowHeight = newRowHeight; } public ChangeOccurrenceTableRowHeight(int newRowHeight, Options options) { this.rowHeight = newRowHeight; this.localOptions = options; } @Override public String getName() { return "Change occurrence table row height"; } @Override public String getDescription() { return "Change occurrence table row height."; } @Override public void execute(Wandora wandora, Context context) throws TopicMapException { if(localOptions != null) { localOptions.put(OccurrenceTable.ROW_HEIGHT_OPTIONS_KEY, ""+rowHeight); } if(wandora != null) { Options ops = wandora.getOptions(); ops.put(OccurrenceTable.ROW_HEIGHT_OPTIONS_KEY, ""+rowHeight); } } }
2,409
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ChangeOccurrenceView.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/occurrences/ChangeOccurrenceView.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * ChangeOccurrenceView.java * * Created on 3. Maaliskuuta 2008 * */ package org.wandora.application.tools.occurrences; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.gui.OccurrenceTable; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.TopicMapException; import org.wandora.utils.Options; /** * Changes Wandora application options to reflect user selected occurrence * view. * * @author akivela */ public class ChangeOccurrenceView extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; private String newView = OccurrenceTable.VIEW_SCHEMA; private Options localOptions = null; /** Creates a new instance of ChangeOccurrenceView */ public ChangeOccurrenceView(String view) { this.newView = view; } public ChangeOccurrenceView(String view, Options options) { this.newView = view; this.localOptions = options; } @Override public String getName() { return "Change occurrence table view"; } @Override public String getDescription() { return "Change occurrence table view."; } @Override public boolean requiresRefresh() { return true; } @Override public void execute(Wandora wandora, Context context) throws TopicMapException { if(localOptions != null) { localOptions.put(OccurrenceTable.VIEW_OPTIONS_KEY, newView); } if(wandora != null) { Options ops = wandora.getOptions(); ops.put(OccurrenceTable.VIEW_OPTIONS_KEY, newView); } } }
2,586
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ChangeOccurrenceType.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/occurrences/ChangeOccurrenceType.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * */ package org.wandora.application.tools.occurrences; import java.util.ArrayList; import java.util.Hashtable; import java.util.Iterator; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.gui.OccurrenceTable; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public class ChangeOccurrenceType extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; private Topic occurrenceType = null; private Topic masterTopic = null; private boolean deleteAll = false; private boolean forceStop = false; /** Creates a new instance of ChangeOccurrenceType */ public ChangeOccurrenceType() { this.occurrenceType=null; } public ChangeOccurrenceType(Context proposedContext) { this.setContext(proposedContext); this.occurrenceType=null; } public ChangeOccurrenceType(Context proposedContext, Topic occurrenceType) { this.setContext(proposedContext); this.occurrenceType = occurrenceType; } public ChangeOccurrenceType(Topic occurrenceType) { this.occurrenceType = occurrenceType; } public ChangeOccurrenceType(Context proposedContext, Topic occurrenceType, Topic masterTopic) { this.setContext(proposedContext); this.occurrenceType = occurrenceType; this.masterTopic = masterTopic; } public ChangeOccurrenceType(Topic occurrenceType, Topic masterTopic) { this.occurrenceType = occurrenceType; this.masterTopic = masterTopic; } @Override public String getName() { return "Change occurrence type"; } @Override public String getDescription() { return "Change occurrence's type topic."; } @Override public void execute(Wandora wandora, Context context) throws TopicMapException { Object contextSource = context.getContextSource(); if(contextSource instanceof OccurrenceTable) { OccurrenceTable ot = (OccurrenceTable) contextSource; ot.changeType(); } else { Iterator<Topic> topics = null; if(masterTopic != null) { ArrayList<Topic> topicArray = new ArrayList(); topicArray.add(masterTopic); topics = topicArray.iterator(); } else { topics = context.getContextObjects(); } if(topics != null) { Topic type = occurrenceType; if(type == null || type.isRemoved()) { type = wandora.showTopicFinder("Select occurrence type to be changed"); } if(type != null && !type.isRemoved()) { Topic newType = wandora.showTopicFinder("Select new occurrence type"); if(newType != null && !newType.isRemoved()) { while(topics.hasNext()) { Topic topic = topics.next(); if(topic != null && !topic.isRemoved()) { Hashtable<Topic,String> os = topic.getData(type); if(os != null && !os.isEmpty()) { for(Topic scope : os.keySet()) { if(scope != null && !scope.isRemoved()) { String occurrenceText = os.get(scope); topic.setData(newType, scope, occurrenceText); } } topic.removeData(type); } } } } } } } } }
4,911
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MakeOccurrenceFromVariant.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/occurrences/MakeOccurrenceFromVariant.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * MakeOccurrenceFromVariant.java * * Created on 2.3.2010, 14:55 * */ package org.wandora.application.tools.occurrences; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.Topic; import org.wandora.topicmap.XTMPSI; /** * * @author akivela */ public class MakeOccurrenceFromVariant extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; public static boolean overWrite = false; /** * Creates a new instance of MakeOccurrenceFromVariant */ public MakeOccurrenceFromVariant() { } public MakeOccurrenceFromVariant(Context preferredContext) { setContext(preferredContext); } @Override public String getName() { return "Makes occurrence using topic's variant name."; } @Override public String getDescription() { return "Iterates through selected topics and copies topic's display variant name to occurrence."; } @Override public void execute(Wandora wandora, Context context) { try { setDefaultLogger(); setLogTitle("Copying variant name to topic occurrence"); log("Copying variant name to topic occurrence"); Iterator topics = context.getContextObjects(); if(topics == null || !topics.hasNext()) return; Topic topic = null; String variant = null; String occurrence = null; Topic type = wandora.showTopicFinder("Select occurrence type..."); if(type == null) return; Topic language = wandora.showTopicFinder("Select language..."); if(language == null) return; Set<Topic> scope = new LinkedHashSet<Topic>(); Topic displayScope = wandora.getTopicMap().getTopic(XTMPSI.DISPLAY); scope.add(language); scope.add(displayScope); while(topics.hasNext() && !forceStop()) { try { topic = (Topic) topics.next(); if(topic != null && !topic.isRemoved()) { variant = topic.getVariant(scope); occurrence = topic.getData(type, language); if(occurrence == null || overWrite) { topic.setData(type, language, variant); } } } catch(Exception e) { log(e); } } log("Ready."); setState(WAIT); } catch (Exception e) { log(e); setState(WAIT); } } }
3,698
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
CopyOccurrence.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/occurrences/CopyOccurrence.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * CopyOccurrence.java * * Created on 3. Maaliskuuta 2008 * */ package org.wandora.application.tools.occurrences; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.gui.OccurrenceTable; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.TopicMapException; /** * * @author akivela */ public class CopyOccurrence extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; /** Creates a new instance of CopyOccurrence */ public CopyOccurrence() { } public CopyOccurrence(Context proposedContext) { this.setContext(proposedContext); } @Override public String getName() { return "Copy occurrence"; } @Override public String getDescription() { return "Copy occurrence text to clipboard."; } @Override public void execute(Wandora wandora, Context context) throws TopicMapException { Object source = getContext().getContextSource(); if(source instanceof OccurrenceTable) { OccurrenceTable ot = (OccurrenceTable) source; ot.copy(); } } }
2,080
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
EditOccurrences.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/occurrences/EditOccurrences.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * */ package org.wandora.application.tools.occurrences; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.application.contexts.LayeredTopicContext; import org.wandora.application.gui.FreeOccurrencePrompt; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; /** * * @author akivela */ public class EditOccurrences extends AbstractWandoraTool { private static final long serialVersionUID = 1L; private Topic masterTopic = null; private Topic occurrenceType = null; /** Creates a new instance of EditOccurrences */ public EditOccurrences(Topic occurrenceType, Topic topic) { this.masterTopic = topic; this.occurrenceType = occurrenceType; setContext(new LayeredTopicContext()); } public EditOccurrences(Context preferredContext, Topic occurrenceType, Topic topic ) { this.masterTopic = topic; this.occurrenceType = occurrenceType; setContext(preferredContext); } @Override public String getName() { return "Edit occurrences"; } @Override public String getDescription() { return "Open occurrence editor for editing context occurrences."; } @Override public void execute(Wandora wandora, Context context) throws TopicMapException { if(masterTopic != null && !masterTopic.isRemoved() && occurrenceType != null && !occurrenceType.isRemoved()) { FreeOccurrencePrompt d=new FreeOccurrencePrompt(wandora, masterTopic, occurrenceType); d.setVisible(true); } } }
2,503
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AppendOccurrence.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/occurrences/AppendOccurrence.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * AppendOccurrence.java * * Created on 3. Maaliskuuta 2008 * */ package org.wandora.application.tools.occurrences; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.gui.OccurrenceTable; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.TopicMapException; /** * * @author akivela */ public class AppendOccurrence extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; public AppendOccurrence() { } public AppendOccurrence(Context proposedContext) { this.setContext(proposedContext); } @Override public String getName() { return "Append occurrence"; } @Override public String getDescription() { return "Appends clipboard text to given occurrence."; } @Override public void execute(Wandora wandora, Context context) throws TopicMapException { Object source = getContext().getContextSource(); if(source instanceof OccurrenceTable) { OccurrenceTable ot = (OccurrenceTable) source; ot.append(); } } }
2,045
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MakeOccurrenceFromBasename.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/occurrences/MakeOccurrenceFromBasename.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * MakeOccurrenceFromBasename.java * * Created on 2.3.2010, 14:55 * */ package org.wandora.application.tools.occurrences; import java.util.Iterator; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.Topic; /** * * @author akivela */ public class MakeOccurrenceFromBasename extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; public static boolean overWrite = false; /** * Creates a new instance of MakeOccurrenceFromBasename */ public MakeOccurrenceFromBasename() { } public MakeOccurrenceFromBasename(Context preferredContext) { setContext(preferredContext); } @Override public String getName() { return "Make occurrence using topic's base name."; } @Override public String getDescription() { return "Iterates through selected topics and copies topic's base name to occurrence."; } @Override public void execute(Wandora wandora, Context context) { try { setDefaultLogger(); setLogTitle("Copying base name to topic occurrence"); log("Copying base name to topic occurrence"); Iterator topics = context.getContextObjects(); if(topics == null || !topics.hasNext()) return; Topic topic = null; String basename = null; String occurrence = null; Topic type = wandora.showTopicFinder("Select occurrence type..."); if(type == null) return; Topic language = wandora.showTopicFinder("Select occurrence language..."); if(language == null) return; int progress = 0; while(topics.hasNext() && !forceStop()) { try { topic = (Topic) topics.next(); if(topic != null && !topic.isRemoved()) { setProgress(progress++); basename = topic.getBaseName(); occurrence = topic.getData(type, language); if(occurrence == null || overWrite) { topic.setData(type, language, basename); } } } catch(Exception e) { log(e); } } log("Ready."); setState(WAIT); } catch (Exception e) { log(e); } } }
3,445
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DownloadAllOccurrences.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/occurrences/DownloadAllOccurrences.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * DownloadAllOccurrences.java * */ package org.wandora.application.tools.occurrences; import java.io.File; import java.net.URL; import java.util.Collection; import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; /** * * @author akivela */ import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.gui.UIConstants; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.application.gui.simple.SimpleFileChooser; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.utils.IObox; /** * <p> * Download resources addressed by occurrences that can be recognized as URLs. * Download folder is asked from the user. * </p> * * @author akivela */ public class DownloadAllOccurrences extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; public boolean changeOccurrence = false; public boolean overWriteAll = false; public DownloadAllOccurrences() { } public DownloadAllOccurrences(Context preferredContext) { this(preferredContext, false); } public DownloadAllOccurrences(boolean changeOccurrence) { this.changeOccurrence = changeOccurrence; } public DownloadAllOccurrences(Context preferredContext, boolean changeOccurrence) { setContext(preferredContext); this.changeOccurrence = changeOccurrence; } private Topic typeTopic = null; private Topic langTopic = null; @Override public void execute(Wandora admin, Context context) { Iterator topics = context.getContextObjects(); File targetPath = null; TopicMap tm = admin.getTopicMap(); if(topics != null && topics.hasNext()) { try { Topic topic = null; int total = 0; int count = 0; boolean cont = true; overWriteAll = false; setDefaultLogger(); setLogTitle("Download URL occurrences..."); while(cont && topics.hasNext() && !forceStop()) { try { total++; topic = (Topic) topics.next(); if(topic != null && !topic.isRemoved()) { Collection<Topic> occurrenceTypes = topic.getDataTypes(); for(Topic type: occurrenceTypes) { typeTopic = type; Hashtable<Topic,String> scopedOccurrences = topic.getData(type); Enumeration<Topic> scopeTopics = scopedOccurrences.keys(); while(scopeTopics.hasMoreElements()) { langTopic = scopeTopics.nextElement(); String occurrence = scopedOccurrences.get(langTopic); String url = extractURLFromOccurrence(occurrence); if(url != null) { if(targetPath == null) { setState(INVISIBLE); targetPath = selectDirectory("Select download directory", admin); setState(VISIBLE); if(targetPath == null) break; } cont = download(admin, topic, url, targetPath); count++; } } } } } catch (Exception e) { log(e); } } log("Total " + total + " topics browsed!"); log("Total " + count + " occurrences downloaded!"); } catch (Exception e) { log(e); } setState(WAIT); } } public String extractURLFromOccurrence(String occurrence) { if(occurrence == null) return null; occurrence = occurrence.trim(); if(occurrence.length() == 0) return null; if(occurrence.startsWith("http://") || occurrence.startsWith("https://") || occurrence.startsWith("ftp://") || occurrence.startsWith("ftps://")) { return occurrence; } return null; } public boolean download(Wandora admin, Topic topic, String url, File target) { try { URL subjectUrl = new URL(url); String filename = subjectUrl.getPath(); String filenameWithoutExtension = filename; String filenameExtension = ""; if(filename.indexOf('/') > -1) filename = filename.substring(filename.lastIndexOf('/')); if(filename.indexOf('.') > 0) { filenameWithoutExtension = filename.substring(0, filename.lastIndexOf('.')-1); filenameExtension = filename.substring(filename.lastIndexOf('.')); } File targetFile = new File(target.getPath() + "/" + filename); if(!overWriteAll && targetFile.exists()) { int c = 1; File newFile = null; do { c++; newFile = new File(target.getPath()+"/"+filenameWithoutExtension+"_"+c+filenameExtension); } while(newFile.exists() && c < 999); int a = WandoraOptionPane.showConfirmDialog(admin, "File '"+filename+"' already exists. Overwrite file? Selecting No renames the file to "+newFile.getPath()+".", "Overwrite existing file?", WandoraOptionPane.YES_TO_ALL_NO_CANCEL_OPTION); if(a == WandoraOptionPane.NO_OPTION) targetFile = newFile; else if(a == WandoraOptionPane.CANCEL_OPTION) return false; else if(a == WandoraOptionPane.YES_TO_ALL_OPTION) overWriteAll = true; } log("Downloading occurrence content from "+subjectUrl.toExternalForm()+" to "+targetFile.getPath()); IObox.moveUrl(subjectUrl, targetFile); if(changeOccurrence) { String newOccurrence = makeFileLocator(targetFile); if(typeTopic != null && langTopic != null) { topic.setSubjectLocator(new Locator(newOccurrence)); log("Topic's occurrence has been updated to "+newOccurrence); } } } catch (Exception e) { log(e); } return true; } private File selectDirectory(String directoryDialogTitle, Wandora admin) { File currentDirectory = null; try { SimpleFileChooser chooser=UIConstants.getFileChooser(); chooser.setDialogTitle(directoryDialogTitle); chooser.setApproveButtonText("Select directory"); chooser.setFileSelectionMode(SimpleFileChooser.DIRECTORIES_ONLY); if(chooser.open(admin, SimpleFileChooser.OPEN_DIALOG)==SimpleFileChooser.APPROVE_OPTION) { currentDirectory = chooser.getSelectedFile(); } else { currentDirectory = null; } } catch (Exception e) { e.printStackTrace(); } return currentDirectory; } @Override public String getName() { return "Download all occurrences"; } @Override public String getDescription() { return "Downloads all occurrences to local directory selected by user."; } // ------------------------------------------------------------------------- public String makeFileLocator(File f) { return f.toURI().toString(); // return "file://" + f.getPath().replace('\\', '/'); } // ------------------------------------------------------------------------- }
9,075
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
CreateTopicWithOccurrenceSelection.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/occurrences/CreateTopicWithOccurrenceSelection.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.wandora.application.tools.occurrences; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.gui.texteditor.OccurrenceTextEditor; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.Association; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicTools; /** * * @author akivela */ public class CreateTopicWithOccurrenceSelection extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; public boolean ASSOCIATE_TO_OCCURRENCE_CARRIER = true; private boolean requiresRefresh = false; /** Creates a new instance of CreateTopicWithOccurrenceSelection */ public CreateTopicWithOccurrenceSelection() { } public CreateTopicWithOccurrenceSelection(boolean associate) { ASSOCIATE_TO_OCCURRENCE_CARRIER = associate; } public CreateTopicWithOccurrenceSelection(Context proposedContext) { this.setContext(proposedContext); } public CreateTopicWithOccurrenceSelection(boolean associate, Context proposedContext) { ASSOCIATE_TO_OCCURRENCE_CARRIER = associate; this.setContext(proposedContext); } @Override public String getName() { return "Create topic with occurrence selection"; } @Override public String getDescription() { return "Create topic with occurrence selection and optionally associate created topic to occurrence carrier."; } @Override public void execute(Wandora wandora, Context context) throws TopicMapException { Object source = getContext().getContextSource(); requiresRefresh = false; if(source instanceof OccurrenceTextEditor) { try { OccurrenceTextEditor oe = (OccurrenceTextEditor) source; String text = oe.getSelectedText(); if(text != null) { text = text.replace("\n", " "); text = text.replace("\r", ""); text = text.replace("\t", " "); text = text.trim(); if(text.length() > 0) { TopicMap tm = wandora.getTopicMap(); Topic topic = tm.getTopicWithBaseName(text); if(topic == null) { topic = tm.createTopic(); topic.addSubjectIdentifier(TopicTools.createDefaultLocator()); topic.setBaseName(text); } else { log("Topic '"+text+"' already exists."); } if(topic != null) { if(ASSOCIATE_TO_OCCURRENCE_CARRIER) { Topic ocarrier = (Topic) context.getContextObjects().next(); if(ocarrier != null) { Topic atype = getOrCreateTopic(tm, "http://wandora.org/si/occurrence-distilled-association", "Occurrence distilled association"); Association a = tm.createAssociation(atype); a.addPlayer(ocarrier, getOrCreateTopic(tm, "http://wandora.org/si/occurrence-carrier", "Occurrence carrier")); a.addPlayer(topic, getOrCreateTopic(tm, "http://wandora.org/si/occurrence-distilled-topic", "Occurrence distilled topic")); requiresRefresh = true; } } } } else { log("No valid occurrence text selection found."); } } else { log("No valid occurrence text selection found."); } } catch(Exception e) { log(e); } } else { log("Invalid context source. This tool requires OccurrenceTextEditor as context source!"); } } protected Topic getOrCreateTopic(TopicMap tm, String si,String bn) throws TopicMapException { if(si!=null){ Topic t=tm.getTopic(si); if(t==null){ t=tm.createTopic(); t.addSubjectIdentifier(tm.createLocator(si)); if(bn!=null) t.setBaseName(bn); } return t; } else{ Topic t=tm.getTopicWithBaseName(bn); if(t==null){ t=tm.createTopic(); if(bn!=null) t.setBaseName(bn); if(si!=null) t.addSubjectIdentifier(tm.createLocator(si)); else t.addSubjectIdentifier(tm.makeSubjectIndicatorAsLocator()); } return t; } } @Override public boolean requiresRefresh() { return requiresRefresh; } }
6,009
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AddSchemalessOccurrence.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/occurrences/AddSchemalessOccurrence.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * AddSchemalessOccurrence.java * * Created on 15.6.2006, 17:10 */ package org.wandora.application.tools.occurrences; import java.util.Iterator; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.application.contexts.LayeredTopicContext; import org.wandora.application.gui.FreeOccurrencePrompt; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public class AddSchemalessOccurrence extends AbstractWandoraTool { private static final long serialVersionUID = 1L; /** Creates a new instance of AddSchemalessOccurrence */ public AddSchemalessOccurrence() { setContext(new LayeredTopicContext()); } public AddSchemalessOccurrence(Context preferredContext) { setContext(preferredContext); } @Override public String getName() { return "Add occurrences"; } @Override public String getDescription() { return "Open occurrence editor. "+ "Editor is used to add an occurrence to the selected topic."; } @Override public void execute(Wandora wandora, Context context) throws TopicMapException { Iterator contextTopics = context.getContextObjects(); if(contextTopics == null || !contextTopics.hasNext()) return; Topic topic = (Topic) contextTopics.next(); if( !contextTopics.hasNext() ) { if(topic != null && !topic.isRemoved()) { FreeOccurrencePrompt d=new FreeOccurrencePrompt(wandora,topic); d.setVisible(true); } } else { log("Context contains more than one topic! Unable to decide topic to add occurrence to."); } } }
2,635
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
PasteOccurrence.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/occurrences/PasteOccurrence.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * PasteOccurrence.java * * Created on 3. Maaliskuuta 2008 * */ package org.wandora.application.tools.occurrences; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.gui.OccurrenceTable; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.TopicMapException; /** * Paste text in clipboard to addressed occurrence. * * @author akivela */ public class PasteOccurrence extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; public PasteOccurrence() { } public PasteOccurrence(Context proposedContext) { this.setContext(proposedContext); } @Override public String getName() { return "Paste occurrence"; } @Override public String getDescription() { return "Paste clipboard text to addressed occurrence."; } @Override public void execute(Wandora wandora, Context context) throws TopicMapException { Object source = getContext().getContextSource(); if(source instanceof OccurrenceTable) { OccurrenceTable ot = (OccurrenceTable) source; ot.paste(); } } @Override public boolean requiresRefresh() { return true; } }
2,173
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
CutOccurrence.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/occurrences/CutOccurrence.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * CutOccurrence.java * * Created on 3. Maaliskuuta 2008 * */ package org.wandora.application.tools.occurrences; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.gui.OccurrenceTable; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.TopicMapException; /** * * @author akivela */ public class CutOccurrence extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; /** Creates a new instance of CutOccurrence */ public CutOccurrence() { } public CutOccurrence(Context proposedContext) { this.setContext(proposedContext); } @Override public String getName() { return "Cut occurrence"; } @Override public String getDescription() { return "Copy occurrence text to clipboard and delete occurrence."; } @Override public void execute(Wandora wandora, Context context) throws TopicMapException { Object source = getContext().getContextSource(); if(source instanceof OccurrenceTable) { OccurrenceTable ot = (OccurrenceTable) source; ot.cut(); } } }
2,094
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SpreadOccurrence.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/occurrences/SpreadOccurrence.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * SpreadOccurrence.java * * Created on 3. Maaliskuuta 2008 * */ package org.wandora.application.tools.occurrences; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.gui.OccurrenceTable; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.XTMPSI; /** * * @author akivela */ public class SpreadOccurrence extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; public SpreadOccurrence() { } public SpreadOccurrence(Context proposedContext) { this.setContext(proposedContext); } @Override public String getName() { return "Spread occurrence"; } @Override public String getDescription() { return "Copies selected occurrence to all other scopes."; } @Override public void execute(Wandora wandora, Context context) throws TopicMapException { Object source = getContext().getContextSource(); // This tool is used mainly in context of occurrence table if(source instanceof OccurrenceTable) { OccurrenceTable ot = (OccurrenceTable) source; ot.spread(); } // But general branch allows also any occurrence spread... else { Iterator topics = context.getContextObjects(); if(!topics.hasNext()) return; Topic otype = wandora.showTopicFinder("Select source occurrence type..."); if( otype == null ) return; Topic oscope = wandora.showTopicFinder("Select source occurrence language..."); if( oscope == null ) return; Collection<Topic> langs = wandora.getTopicMap().getTopicsOfType(XTMPSI.LANGUAGE); if(langs == null || langs.isEmpty()) return; setDefaultLogger(); log("Spreading addressed occurrence to all other scopes."); Topic topic = null; String spreadOccurrence = null; Iterator<Topic> typeIterator = null; Collection<Topic> types = null; Hashtable<Topic, String> occurrences = null; //Iterator occurrenceIterator = null; Topic type = null; Topic scope = null; int progress = 0; int count = 0; ArrayList updatedOccurrences = new ArrayList(); while(topics.hasNext() && !forceStop()) { try { topic = (Topic) topics.next(); if(topic != null && !topic.isRemoved()) { hlog("Investigating topic '" + getTopicName(topic) + "'."); progress++; setProgress(progress); types = topic.getDataTypes(); if(types != null) { typeIterator = types.iterator(); while(typeIterator.hasNext() && !topic.isRemoved()) { try { type = (Topic) typeIterator.next(); spreadOccurrence = null; if(type != null && type.mergesWithTopic(otype)) { occurrences = topic.getData(type); if(occurrences != null) { // First, look for the occurrence text that will be spread! for(Enumeration occurrenceScopes = occurrences.keys(); occurrenceScopes.hasMoreElements();) { scope = (Topic) occurrenceScopes.nextElement(); if(scope != null && scope.mergesWithTopic(oscope)) { spreadOccurrence = occurrences.get(scope); } } if(spreadOccurrence != null) { // Then, iterate through available languages and spread the text for(Iterator occurrenceScopes = langs.iterator(); occurrenceScopes.hasNext();) { scope = (Topic) occurrenceScopes.next(); if(scope != null && !scope.mergesWithTopic(oscope)) { updatedOccurrences.add(topic); updatedOccurrences.add(type); updatedOccurrences.add(scope); updatedOccurrences.add(spreadOccurrence); } } } } } } catch(Exception e) { log(e); } } } } } catch(Exception e) { log(e); } } log("Updating occurrences."); setProgress(0); setProgressMax(updatedOccurrences.size()); progress = 0; String so = null; for(Iterator i = updatedOccurrences.iterator(); i.hasNext() && !forceStop();) { try { setProgress(++progress); topic = (Topic) i.next(); type = (Topic) i.next(); scope = (Topic) i.next(); so = (String) i.next(); if(topic != null && type != null && scope != null && so != null) { topic.setData(type, scope, so); count++; } } catch(Exception e) { log(e); } } log("Total "+count+" occurrences changed!"); } } @Override public boolean requiresRefresh() { return true; } }
7,566
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
OpenURLOccurrence.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/occurrences/OpenURLOccurrence.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * */ package org.wandora.application.tools.occurrences; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.gui.OccurrenceTable; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.TopicMapException; /** * Open browser application and pass occurrence URL to it. * * @author akivela */ public class OpenURLOccurrence extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; /** Creates a new instance of OpenURLOccurrence */ public OpenURLOccurrence() { } public OpenURLOccurrence(Context proposedContext) { this.setContext(proposedContext); } @Override public String getName() { return "Open URL occurrence"; } @Override public String getDescription() { return "Tool is used to fork external browser for URL occurrence."; } @Override public void execute(Wandora admin, Context context) throws TopicMapException { Object contextSource = context.getContextSource(); if(contextSource instanceof OccurrenceTable) { OccurrenceTable ot = (OccurrenceTable) contextSource; ot.openURLOccurrence(); } } }
2,168
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
PasteBinConfiguration.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/occurrences/clipboards/PasteBinConfiguration.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * PasteBinConfiguration.java * * Created on Dec 6, 2011, 5:45:46 PM */ package org.wandora.application.tools.occurrences.clipboards; import java.awt.event.KeyEvent; import javax.swing.JDialog; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.gui.simple.SimpleButton; import org.wandora.application.gui.simple.SimpleCheckBox; import org.wandora.application.gui.simple.SimpleComboBox; import org.wandora.application.gui.simple.SimpleField; import org.wandora.application.gui.simple.SimpleLabel; /** * * @author akivela */ public class PasteBinConfiguration extends javax.swing.JPanel { private static final long serialVersionUID = 1L; private JDialog myDialog = null; private boolean accepted = false; /** Creates new form PasteBinConfiguration */ public PasteBinConfiguration() { initComponents(); expireComboBox.setEditable(false); } public void open(Wandora wandora, WandoraTool t) { myDialog = new JDialog(wandora, true); myDialog.add(this); myDialog.setTitle("Pastebin uploader options"); myDialog.setSize(500, 220); accepted = false; if(wandora != null) wandora.centerWindow(myDialog); myDialog.setVisible(true); } // ------------------------------------------------------------------------- public boolean wasAccepted() { return accepted; } public String getUserId() { return uidTextField.getText(); } public void setUserId(String uid) { uidTextField.setText(uid); } public boolean getReplaceOccurrence() { return replaceOccurrenceCheckBox.isSelected(); } public void setReplaceOccurrence(boolean ro) { replaceOccurrenceCheckBox.setSelected(ro); } public boolean getPrivatePaste() { return pastePrivateCheckBox.isSelected(); } public void setPrivatePaste(boolean pp) { pastePrivateCheckBox.setSelected(pp); } public String getExpiration() { String e = expireComboBox.getSelectedItem().toString(); if("10 minutes".equalsIgnoreCase(e)) return "10M"; if("1 hour".equalsIgnoreCase(e)) return "1H"; if("1 day".equalsIgnoreCase(e)) return "1D"; if("1 month".equalsIgnoreCase(e)) return "1M"; return "N"; // Never } public void setExpiration(String e) { String s = "N"; if("10 minutes".equalsIgnoreCase(e) || "10M".equalsIgnoreCase(e)) s = "10 minutes"; if("1 hour".equalsIgnoreCase(e) || "1H".equalsIgnoreCase(e)) s = "1 hour"; if("1 day".equalsIgnoreCase(e) || "1D".equalsIgnoreCase(e)) s = "1 day"; if("1 month".equalsIgnoreCase(e) || "1M".equalsIgnoreCase(e)) s = "1 month"; expireComboBox.setSelectedItem(s); } // ------------------------------------------------------------------------- /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; infoLabel = new SimpleLabel(); optionsPanel = new javax.swing.JPanel(); replaceOccurrenceLabel = new SimpleLabel(); replaceOccurrenceCheckBox = new SimpleCheckBox(); pastePrivateLabel = new SimpleLabel(); pastePrivateCheckBox = new SimpleCheckBox(); uidLabel = new SimpleLabel(); uidTextField = new SimpleField(); expireLabel = new SimpleLabel(); expireComboBox = new SimpleComboBox(); buttonPanel = new javax.swing.JPanel(); buttonFillerPanel = new javax.swing.JPanel(); okButton = new SimpleButton(); cancelButton = new SimpleButton(); infoLabel.setText("PasteBin occurrence upload options"); setLayout(new java.awt.GridBagLayout()); optionsPanel.setLayout(new java.awt.GridBagLayout()); replaceOccurrenceLabel.setText("Replace occurrence with Pastebin URL"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; gridBagConstraints.insets = new java.awt.Insets(0, 0, 2, 4); optionsPanel.add(replaceOccurrenceLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.insets = new java.awt.Insets(0, 0, 2, 0); optionsPanel.add(replaceOccurrenceCheckBox, gridBagConstraints); pastePrivateLabel.setText("Private paste"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; gridBagConstraints.insets = new java.awt.Insets(0, 0, 2, 4); optionsPanel.add(pastePrivateLabel, gridBagConstraints); pastePrivateCheckBox.setSelected(true); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridwidth = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.insets = new java.awt.Insets(0, 0, 2, 0); optionsPanel.add(pastePrivateCheckBox, gridBagConstraints); uidLabel.setText("API user key"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; gridBagConstraints.insets = new java.awt.Insets(0, 0, 2, 4); optionsPanel.add(uidLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 2, 0); optionsPanel.add(uidTextField, gridBagConstraints); expireLabel.setText("Expire paste in"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; gridBagConstraints.insets = new java.awt.Insets(0, 0, 2, 4); optionsPanel.add(expireLabel, gridBagConstraints); expireComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "10 Minutes", "1 Hour", "1 Day", "1 Month", "Never" })); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 2, 0); optionsPanel.add(expireComboBox, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(10, 20, 10, 10); add(optionsPanel, gridBagConstraints); buttonPanel.setLayout(new java.awt.GridBagLayout()); javax.swing.GroupLayout buttonFillerPanelLayout = new javax.swing.GroupLayout(buttonFillerPanel); buttonFillerPanel.setLayout(buttonFillerPanelLayout); buttonFillerPanelLayout.setHorizontalGroup( buttonFillerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); buttonFillerPanelLayout.setVerticalGroup( buttonFillerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; buttonPanel.add(buttonFillerPanel, gridBagConstraints); okButton.setText("OK"); okButton.setMargin(new java.awt.Insets(0, 2, 0, 2)); okButton.setMinimumSize(new java.awt.Dimension(70, 23)); okButton.setPreferredSize(new java.awt.Dimension(70, 23)); okButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { okButtonMouseReleased(evt); } }); okButton.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { okButtonKeyReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 2); buttonPanel.add(okButton, gridBagConstraints); cancelButton.setText("Cancel"); cancelButton.setMargin(new java.awt.Insets(0, 2, 0, 2)); cancelButton.setMinimumSize(new java.awt.Dimension(70, 23)); cancelButton.setPreferredSize(new java.awt.Dimension(70, 23)); cancelButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { cancelButtonMouseReleased(evt); } }); buttonPanel.add(cancelButton, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); add(buttonPanel, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents private void okButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_okButtonMouseReleased accepted = true; if(myDialog != null) myDialog.setVisible(false); }//GEN-LAST:event_okButtonMouseReleased private void okButtonKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_okButtonKeyReleased accepted = true; if(evt.getKeyCode() == KeyEvent.VK_ENTER) { if(myDialog != null) { myDialog.setVisible(false); } } }//GEN-LAST:event_okButtonKeyReleased private void cancelButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cancelButtonMouseReleased accepted = false; if(myDialog != null) myDialog.setVisible(false); }//GEN-LAST:event_cancelButtonMouseReleased // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel buttonFillerPanel; private javax.swing.JPanel buttonPanel; private javax.swing.JButton cancelButton; private javax.swing.JComboBox expireComboBox; private javax.swing.JLabel expireLabel; private javax.swing.JLabel infoLabel; private javax.swing.JButton okButton; private javax.swing.JPanel optionsPanel; private javax.swing.JCheckBox pastePrivateCheckBox; private javax.swing.JLabel pastePrivateLabel; private javax.swing.JCheckBox replaceOccurrenceCheckBox; private javax.swing.JLabel replaceOccurrenceLabel; private javax.swing.JLabel uidLabel; private javax.swing.JTextField uidTextField; // End of variables declaration//GEN-END:variables }
12,905
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
PasteBinOccurrenceDownloader.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/occurrences/clipboards/PasteBinOccurrenceDownloader.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.wandora.application.tools.occurrences.clipboards; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.util.Collection; import java.util.Hashtable; import java.util.Iterator; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.gui.OccurrenceTable; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; /** * Searches for URL occurrences that address PasteBin resources. If * URL occurrence addresses PasteBin resource, * downloads the resource and replaces the occurrence URL with * it. * * @author akivela */ public class PasteBinOccurrenceDownloader extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; private static final String URL_PREFIX = "http://pastebin.com/"; private static final String RAW_PREFIX = "http://pastebin.com/raw.php?i="; private boolean cancelled = false; public PasteBinOccurrenceDownloader() { } public PasteBinOccurrenceDownloader(Context proposedContext) { this.setContext(proposedContext); } @Override public String getName() { return "Download occurrence from Pastebin"; } @Override public String getDescription() { return "Downloads occurrence from Pastebin."; } @Override public void execute(Wandora w, Context context) { Object source = context.getContextSource(); cancelled = false; String o = null; Topic carrier = null; Topic type = null; Topic lang = null; if(source instanceof OccurrenceTable) { OccurrenceTable ot = (OccurrenceTable) source; o = ot.getPointedOccurrence(); String pid = getPastebinId(o); if(pid != null) { String purl = RAW_PREFIX + pid; type = ot.getPointedOccurrenceType(); lang = ot.getPointedOccurrenceLang(); carrier = ot.getTopic(); restorePastebinData(carrier, type, lang, purl, w); } else { WandoraOptionPane.showMessageDialog(w, "It appears given occurrence is not a Pastebin URL. Cancelling download.", "Cancelling download", WandoraOptionPane.ERROR_MESSAGE); } } else { Iterator contextObjects = context.getContextObjects(); setDefaultLogger(); int counter = 0; while(contextObjects.hasNext() && !forceStop() && !cancelled) { Object co = contextObjects.next(); if(co instanceof Topic) { carrier = (Topic) co; try { Collection<Topic> types = carrier.getDataTypes(); for(Topic otype : types) { if(forceStop() || cancelled) break; type = otype; Hashtable<Topic, String> occurrences = carrier.getData(type); for(Iterator<Topic> scopes = occurrences.keySet().iterator(); scopes.hasNext(); ) { Topic scope = (Topic) scopes.next(); if(scope != null) { o = occurrences.get(scope); String pid = getPastebinId(o); if(pid != null) { String purl = RAW_PREFIX + pid; boolean restored = restorePastebinData(carrier, type, scope, purl, w); if(restored) counter++; if(cancelled) break; } else { // DO NOTHING } } } } } catch(TopicMapException ex) { log(ex); } catch(Exception e) { log(e); } } } if(counter > 0) { log("Total "+counter+" Pastebin stored texts restored."); } else { log("Found no Pastebin URLs. No Pastebin data restored."); } log("Ready."); setState(WAIT); } } public boolean restorePastebinData(Topic carrier, Topic type, Topic scope, String purl, Wandora w) { try { String pastebinContent = getUrl(new URL(purl)); boolean storeToOccurrence = true; if(pastebinContent == null || pastebinContent.length() == 0) { storeToOccurrence = false; int a = WandoraOptionPane.showConfirmDialog(w, "Downloaded data is either null or zero length. Would you like to replace the occurrence with downloaded data anyway", "Downloaded data is invalid", WandoraOptionPane.YES_NO_CANCEL_OPTION); if(a == WandoraOptionPane.CANCEL_OPTION) cancelled = true; if(a == WandoraOptionPane.YES_OPTION) storeToOccurrence = true; } if(storeToOccurrence) { carrier.setData(type, scope, pastebinContent); return true; } } catch(Exception e) { log("Exception '"+e.getMessage()+"' occurred while downloading URL '"+purl+"'."); e.printStackTrace(); } return false; } public static String getPastebinId(String u) { String pid = null; if(u != null) { u = u.trim(); if(u.startsWith(RAW_PREFIX)) { pid = u.substring(RAW_PREFIX.length()); } else if(u.startsWith(URL_PREFIX)) { pid = u.substring(URL_PREFIX.length()); } } return pid; } public static String getUrl(URL url) throws IOException { StringBuilder sb = new StringBuilder(5000); if(url != null) { URLConnection con = url.openConnection(); Wandora.initUrlConnection(con); con.setUseCaches(false); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); String s; while ((s = in.readLine()) != null) { sb.append(s); } in.close(); } return sb.toString(); } }
7,817
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
PasteBinOccurrenceUploader.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/occurrences/clipboards/PasteBinOccurrenceUploader.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * PasteBinOccurrenceUploader.java * * Created on 2011-12-06 * */ package org.wandora.application.tools.occurrences.clipboards; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.util.Collection; import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.gui.OccurrenceTable; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.application.tools.GenericOptionsDialog; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; /** * Uploads occurrence resource to PastBin service and optionally replaces the * occurrence resource with PastBin resource URL address. * * @author akivela */ public class PasteBinOccurrenceUploader extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; private static final String apibase = "http://pastebin.com/api/api_post.php"; private static final String apikey = "e3dbea933563db6ad9d11e2a5a2ab99c"; private static PasteBinConfiguration configuration = null; private boolean requiresRefresh = false; private boolean isConfigured = false; private boolean cancelled = false; private boolean uploadAll = false; public PasteBinOccurrenceUploader() { } public PasteBinOccurrenceUploader(boolean upAll) { this.uploadAll = upAll; } public PasteBinOccurrenceUploader(Context proposedContext) { this.setContext(proposedContext); } @Override public String getName() { return "Upload occurrence to Pastebin"; } @Override public String getDescription() { return "Upload occurrence to Pastebin web service."; } @Override public void execute(Wandora wandora, Context context) throws TopicMapException { requiresRefresh = false; isConfigured = false; cancelled = false; Object source = context.getContextSource(); String o = null; Topic carrier = null; Topic type = null; Topic lang = null; try { if(source instanceof OccurrenceTable) { setDefaultLogger(); OccurrenceTable ot = (OccurrenceTable) source; o = ot.getPointedOccurrence(); type = ot.getPointedOccurrenceType(); lang = ot.getPointedOccurrenceLang(); carrier = ot.getTopic(); if(o != null) { pasteBin(wandora, carrier, type, lang, o); } } else { Iterator contextObjects = context.getContextObjects(); if(!contextObjects.hasNext()) return; boolean wasUploaded = false; int uploadCounter = 0; Topic uploadType = null; Topic uploadLang = null; if(!uploadAll) { GenericOptionsDialog god=new GenericOptionsDialog(wandora,"Occurrence upload options","Occurrence upload options. If you want to limit occurrences, select occurrence type and scope. Leave both topics empty to upload all occurrences.",true,new String[][]{ new String[]{"Occurrence type topic","topic","","Which occurrences are uploaded. Leave blank to include all occurrence types."}, new String[]{"Occurrence scope topic","topic","","Which occurrences are uploaded. Leave blank to include all occurrence scopes."}, },wandora); god.setVisible(true); if(god.wasCancelled()) return; Map<String,String> values=god.getValues(); if(values.get("Occurrence type topic")!=null && values.get("Occurrence type topic").length()>0) { uploadType=wandora.getTopicMap().getTopic(values.get("Occurrence type topic")); } if(values.get("Occurrence scope topic")!=null && values.get("Occurrence scope topic").length()>0) { uploadLang=wandora.getTopicMap().getTopic(values.get("Occurrence scope topic")); } } setDefaultLogger(); while(contextObjects.hasNext() && !forceStop() && !cancelled) { Object co = contextObjects.next(); if(co != null) { if(co instanceof Topic) { carrier = (Topic) co; Collection<Topic> occurrenceTypes = carrier.getDataTypes(); for(Topic otype : occurrenceTypes) { if(forceStop()) break; if(cancelled) break; type = otype; if(uploadType == null || uploadType.mergesWithTopic(type)) { Hashtable<Topic,String> occurrences = carrier.getData(type); for(Enumeration<Topic> langs = occurrences.keys() ; langs.hasMoreElements() ; ) { lang = langs.nextElement(); if(lang != null) { if(uploadLang == null || lang.mergesWithTopic(uploadLang)) { o = occurrences.get(lang); if(o != null) { wasUploaded = pasteBin(wandora, carrier, type, lang, o); if(wasUploaded) uploadCounter++; if(cancelled) break; } } } } } } } } } if(uploadCounter > 0) { log("Total "+uploadCounter+" occurrences uploaded to Pastebin."); } else if(uploadCounter == 0) { log("No occurrences uploaded to Pastebin."); } log("Ready."); } } catch(Exception e) { log(e); } setState(WAIT); } public boolean pasteBin(Wandora wandora, Topic carrier, Topic type, Topic lang, String o) throws TopicMapException { if(!isConfigured) { isConfigured = true; if(configuration == null) { configuration = new PasteBinConfiguration(); } configuration.open(wandora, this); if(!configuration.wasAccepted()) { cancelled = true; return false; } } String apiUserKey = configuration.getUserId(); String apiPastePrivate = (configuration.getPrivatePaste() ? "1" : "0"); String apiPasteName = "Wandora-"+System.currentTimeMillis(); String apiPasteExpireDate = configuration.getExpiration(); String apiPasteFormat = null; String apiDevKey = apikey; String reply = pasteBin(apiUserKey, apiPastePrivate, apiPasteName, apiPasteExpireDate, apiPasteFormat, apiDevKey, o); if(reply.startsWith("Bad API request")) { log("Bad API request: "+reply); } else { log("Occurrence successfully uloaded to Pastebin. Pastebin returned '"+reply+"'."); if(configuration.getReplaceOccurrence()) { if(carrier != null && type != null && lang != null) { carrier.setData(type, lang, reply); requiresRefresh = true; log("Replaced occurrence with a Pastebin URL '"+reply+"'."); } } return true; } return false; } // ------------------------------------------------------------------------- public String pasteBin(String apiUserKey, String apiPastePrivate, String apiPasteName, String apiPasteExpireDate, String apiPasteFormat, String apiDevKey, String apiPasteCode) { StringBuilder data = new StringBuilder(""); data.append("api_option=paste"); if(apiUserKey != null && apiUserKey.length() > 0) data.append("&api_user_key=").append(apiUserKey); if(apiPastePrivate != null) data.append("&api_paste_private=").append(apiPastePrivate); if(apiPasteName != null) data.append("&api_paste_name=").append(encode(apiPasteName)); if(apiPasteExpireDate != null) data.append("&api_paste_expire_date=").append(apiPasteExpireDate); if(apiPasteFormat != null) data.append("&api_paste_format=").append(apiPasteFormat); if(apiDevKey != null) data.append("&api_dev_key=").append(apiDevKey); if(apiPasteCode != null) data.append("&api_paste_code=").append(encode(apiPasteCode)); String reply = null; try { reply = sendRequest(new URL(apibase), data.toString(), "application/x-www-form-urlencoded", "POST"); } catch(Exception e) { reply = e.getMessage(); } return reply; } private String encode(String str) { try { return URLEncoder.encode(str, "utf-8"); } catch(Exception e) { // PASS } return str; } public static String sendRequest(URL url, String data, String ctype, String method) throws IOException { StringBuilder sb = new StringBuilder(1000); if (url != null) { URLConnection con = url.openConnection(); Wandora.initUrlConnection(con); con.setDoInput(true); con.setUseCaches(false); if(method != null && con instanceof HttpURLConnection) { ((HttpURLConnection) con).setRequestMethod(method); //System.out.println("****** Setting HTTP request method to "+method); } if(ctype != null) { con.setRequestProperty("Content-type", ctype); } if(data != null && data.length() > 0) { con.setRequestProperty("Content-length", data.length() + ""); con.setDoOutput(true); PrintWriter out = new PrintWriter(con.getOutputStream()); out.print(data); out.flush(); out.close(); } // DataInputStream in = new DataInputStream(con.getInputStream()); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String s; while ((s = in.readLine()) != null) { sb.append(s); } in.close(); } return sb.toString(); } @Override public boolean requiresRefresh() { return requiresRefresh; } }
12,389
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
RunOccurrenceAsQuery.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/occurrences/run/RunOccurrenceAsQuery.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.wandora.application.tools.occurrences.run; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Collection; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.gui.OccurrenceTable; import org.wandora.application.gui.table.MixedTopicTable; import org.wandora.application.gui.table.TableViewerPanel; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.query2.QueryRunner; import org.wandora.topicmap.Topic; import org.wandora.utils.DataURL; /** * * @author akivela */ public class RunOccurrenceAsQuery extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; public RunOccurrenceAsQuery() {} public RunOccurrenceAsQuery(Context preferredContext) { setContext(preferredContext); } @Override public String getName() { return "Run Wandora Query script in occurrence"; } @Override public String getDescription() { return "Run Wandora Query script stored in occurrence."; } @Override public void execute(Wandora wandora, Context context) { Object contextSource = context.getContextSource(); // ***** OCCURRENCE TABLE ***** if(contextSource instanceof OccurrenceTable) { OccurrenceTable ot = (OccurrenceTable) contextSource; String occurrence = ot.getPointedOccurrence(); if(DataURL.isDataURL(occurrence)) { DataURL dataURL = null; try { dataURL = new DataURL(occurrence); } catch (MalformedURLException ex) { log(ex); } if(dataURL != null) { occurrence = new String(dataURL.getData()); } } System.out.println("Running Wandora Query script:\n"+occurrence); try { QueryRunner queryRunner = new QueryRunner(); Collection<Topic> contextTopics = new ArrayList<>(); contextTopics.add(ot.getTopic()); QueryRunner.QueryResult result = new QueryRunner.QueryResult(queryRunner.runQuery(occurrence, contextTopics)); Object[][] data = result.getData(); Object[] columns = result.getColumns(); MixedTopicTable table = new MixedTopicTable(wandora); table.initialize(data,columns); String title = "Query result"; TableViewerPanel viewer = new TableViewerPanel(); viewer.openInDialog(table, title); } catch(Exception e) { wandora.handleError(e); e.printStackTrace(); } } } }
3,759
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
UClassifyOccurrenceExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/occurrences/refine/UClassifyOccurrenceExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.wandora.application.tools.occurrences.refine; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.application.tools.extractors.uclassify.UClassifier; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; /** * * @author akivela */ public class UClassifyOccurrenceExtractor extends AbstractOccurrenceExtractor { private static final long serialVersionUID = 1L; private String forceClassifier = null; private String forceOwner = null; private double forceProbability = 0.1; public UClassifyOccurrenceExtractor() { } public UClassifyOccurrenceExtractor(String classifier, String owner, double probability) { forceClassifier = classifier; forceOwner = owner; forceProbability = probability; } public UClassifyOccurrenceExtractor(Context preferredContext) { super(preferredContext); } @Override public String getName() { return "uClassify occurrence extractor"; } @Override public String getDescription(){ return "Extracts terms out of given occurrences using uClassify web service."; } public boolean _extractTopicsFrom(String occurrenceData, Topic masterTopic, TopicMap topicMap, Wandora wandora) throws Exception { if(occurrenceData != null && occurrenceData.length() > 0) { UClassifier extractor = null; if(forceClassifier != null && forceOwner != null) { extractor = new UClassifier(forceClassifier, forceOwner, forceProbability); } else { extractor = new UClassifier(); } extractor.setToolLogger(getDefaultLogger()); if(masterTopic != null) extractor.setMasterSubject(masterTopic); extractor._extractTopicsFrom(occurrenceData, topicMap); } return true; } }
2,746
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AbstractOccurrenceExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/occurrences/refine/AbstractOccurrenceExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * */ package org.wandora.application.tools.occurrences.refine; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.application.tools.GenericOptionsDialog; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; /** * * @author akivela */ public abstract class AbstractOccurrenceExtractor extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; private Context preferredContext = null; public AbstractOccurrenceExtractor() { } public AbstractOccurrenceExtractor(Context context) { this.preferredContext = context; } public abstract boolean _extractTopicsFrom(String occurrenceData, Topic masterTopic, TopicMap topicMap, Wandora wandora) throws Exception; @Override public void execute(Wandora wandora, Context context) { Iterator topics = null; if(preferredContext != null) topics = preferredContext.getContextObjects(); else topics = context.getContextObjects(); if(topics != null && topics.hasNext()) { try { Topic topic = null; int total = 0; int count = 0; TopicMap tm = wandora.getTopicMap(); GenericOptionsDialog god=new GenericOptionsDialog(wandora, "Extract information from occurrences", "To extract information from occurrences please address type and scope of occurrences.",true,new String[][]{ new String[]{"Type of occurrences","topic","","Type of changed occurrences"}, new String[]{"Scope of occurrences","topic","","Scope i.e. language of changed occurrences"}, },wandora); god.setVisible(true); if(god.wasCancelled()) return; Map<String,String> values=god.getValues(); Topic typeTopic = null; Topic scopeTopic = null; typeTopic = tm.getTopic(values.get("Type of occurrences")); scopeTopic = tm.getTopic(values.get("Scope of occurrences")); setDefaultLogger(); setLogTitle("Extracting from occurrences..."); ArrayList<Topic> dtopics = new ArrayList<Topic>(); while(topics.hasNext() && !forceStop()) { dtopics.add((Topic) topics.next()); } topics = dtopics.iterator(); while(topics.hasNext() && !forceStop()) { try { total++; topic = (Topic) topics.next(); if(topic != null && !topic.isRemoved()) { if(typeTopic != null) { Hashtable<Topic,String> scopedOccurrences = topic.getData(typeTopic); if(scopedOccurrences != null && scopedOccurrences.size() > 0) { if(scopeTopic != null) { String occurrence = scopedOccurrences.get(scopeTopic); if(occurrence != null) { count++; _extractTopicsFrom(occurrence, topic, tm, wandora); } } else { Enumeration<Topic> scopeTopics = scopedOccurrences.keys(); while(scopeTopics.hasMoreElements()) { Topic oscopeTopic = scopeTopics.nextElement(); String occurrence = scopedOccurrences.get(oscopeTopic); if(occurrence != null && occurrence.length() > 0) { count++; _extractTopicsFrom(occurrence, topic, tm, wandora); } } } } } else { Collection<Topic> occurrenceTypes = topic.getDataTypes(); for(Topic type : occurrenceTypes) { typeTopic = type; Hashtable<Topic,String> scopedOccurrences = topic.getData(type); Enumeration<Topic> scopeTopics = scopedOccurrences.keys(); while(scopeTopics.hasMoreElements()) { Topic oscopeTopic = scopeTopics.nextElement(); String occurrence = scopedOccurrences.get(oscopeTopic); if(occurrence != null && occurrence.length() > 0) { count++; _extractTopicsFrom(occurrence, topic, tm, wandora); } } } } } } catch (Exception e) { log(e); } // WAIT FOR A WHILE BEFORE SENDING ANOTHER REQUEST if(topics.hasNext() && !forceStop()) { try { Thread.sleep(100); } catch(Exception e) {} } } log("Total " + total + " topics investigated!"); log("Total " + count + " occurrences extracted!"); } catch (Exception e) { log(e); } setState(WAIT); } } }
7,156
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
FindNearByGeoNamesOccurrence.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/occurrences/refine/FindNearByGeoNamesOccurrence.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.wandora.application.tools.occurrences.refine; import java.net.URL; import java.net.URLEncoder; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.application.tools.extractors.geonames.FindNearByGeoNames; import org.wandora.application.tools.extractors.geonames.GeoNamesExtractorSelector; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.xml.sax.SAXException; /** * * @author akivela */ public class FindNearByGeoNamesOccurrence extends AbstractOccurrenceExtractor { private static final long serialVersionUID = 1L; private static int rows = 1000; private static int radius = 1; private static String lang = "en"; public FindNearByGeoNamesOccurrence() { } public FindNearByGeoNamesOccurrence(Context preferredContext) { super(preferredContext); } @Override public String getName() { return "Find near by occurrence extractor"; } @Override public String getDescription(){ return "Extracts near by locations of given geo coordinate occurrences using GeoNames web service."; } public boolean _extractTopicsFrom(String occurrenceData, Topic masterTopic, TopicMap topicMap, Wandora wandora) throws Exception { if(occurrenceData != null && occurrenceData.length() > 0) { String[] coords = solveGeoCoordinates(occurrenceData); if(coords != null) { if(coords.length > 1) { try { FindNearByGeoNames e = new FindNearByGeoNames(); if(masterTopic != null) { e.setMasterSubject(masterTopic); } String urlStr = GeoNamesExtractorSelector.BASE_URL+"findNearby?style=full"; urlStr += "&lang="+lang; urlStr += "&lat="+URLEncoder.encode(coords[0], "utf-8"); urlStr += "&lng="+URLEncoder.encode(coords[1], "utf-8"); urlStr += "&maxRows="+rows; urlStr += "&radius="+radius; log("Finding geolocations near by "+coords[0]+", "+coords[1]); System.out.println("Extracting: "+urlStr); e.setForceUrls( new String[] { urlStr } ); e.setToolLogger(getDefaultLogger()); e._extractTopicsFrom(new URL(urlStr), topicMap); } catch (Exception e) { if(!(e instanceof SAXException) || !e.getMessage().equals("User interrupt")) log(e); } } } else { log("Found no geo coordinates in occurrence!"); } } return true; } public String[] solveGeoCoordinates(String coords) { coords = coords.trim(); if(coords.indexOf(';') > -1) { return coords.split(";"); } else if(coords.indexOf(',') > -1) { return coords.split(","); } else if(coords.indexOf(':') > -1) { return coords.split(":"); } return null; } }
4,090
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
StanfordNEROccurrenceExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/occurrences/refine/StanfordNEROccurrenceExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.wandora.application.tools.occurrences.refine; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.application.tools.extractors.stanfordner.StanfordNERClassifier; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; /** * * @author akivela */ public class StanfordNEROccurrenceExtractor extends AbstractOccurrenceExtractor { private static final long serialVersionUID = 1L; public StanfordNEROccurrenceExtractor() { } public StanfordNEROccurrenceExtractor(Context preferredContext) { super(preferredContext); } @Override public String getName() { return "Stanford Named Entity Recognizer occurrence extractor"; } @Override public String getDescription(){ return "Extracts terms out of given occurrences using Stanford Named Entity Recognizer (NER)."; } public boolean _extractTopicsFrom(String occurrenceData, Topic masterTopic, TopicMap topicMap, Wandora wandora) throws Exception { if(occurrenceData != null && occurrenceData.length() > 0) { StanfordNERClassifier extractor = new StanfordNERClassifier(); extractor.setToolLogger(getDefaultLogger()); if(masterTopic != null) extractor.setMasterSubject(masterTopic); extractor._extractTopicsFrom(occurrenceData, topicMap); } return true; } }
2,251
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AnnieOccurrenceExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/occurrences/refine/AnnieOccurrenceExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.wandora.application.tools.occurrences.refine; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.application.tools.extractors.gate.AnnieExtractor; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; /** * * @author akivela */ public class AnnieOccurrenceExtractor extends AbstractOccurrenceExtractor { private static final long serialVersionUID = 1L; public AnnieOccurrenceExtractor() { } public AnnieOccurrenceExtractor(Context preferredContext) { super(preferredContext); } @Override public String getName() { return "GATE Annie occurrence extractor"; } @Override public String getDescription(){ return "Extracts terms out of given occurrences using GATE Annie."; } public boolean _extractTopicsFrom(String occurrenceData, Topic masterTopic, TopicMap topicMap, Wandora wandora) throws Exception { if(occurrenceData != null && occurrenceData.length() > 0) { AnnieExtractor extractor = new AnnieExtractor(); extractor.setToolLogger(getDefaultLogger()); if(masterTopic != null) extractor.setMasterSubject(masterTopic); extractor._extractTopicsFrom(occurrenceData, topicMap); } return true; } }
2,154
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ExtractHelper.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/ExtractHelper.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * */ package org.wandora.application.tools.extractors; import java.net.URL; import org.wandora.application.Wandora; import org.wandora.application.tools.browserextractors.BrowserExtractRequest; import org.wandora.application.tools.browserextractors.BrowserPluginExtractor; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.XTMPSI; import org.wandora.utils.IObox; import org.wandora.utils.MSOfficeBox; import org.wandora.utils.PDFbox; import org.wandora.utils.Textbox; import org.wandora.utils.XMLbox; /** * * @author akivela */ public class ExtractHelper { public static final String TOPIC_SI = "http://wandora.org/si/topic"; public static final String SOURCE_SI = "http://wandora.org/si/source"; public static final String DOCUMENT_SI = "http://wandora.org/si/document"; public static Topic getOrCreateTopic(String si, TopicMap tm) throws TopicMapException { return getOrCreateTopic(si, null, tm); } public static Topic getOrCreateTopic(String si, String bn, TopicMap tm) throws TopicMapException { if(si != null) { Locator l = tm.createLocator(si); Topic t=tm.getTopic(l); if(t==null) { if(bn != null) { t = tm.getTopicWithBaseName(bn); } if(t == null) { t=tm.createTopic(); t.addSubjectIdentifier(l); if(bn!=null) t.setBaseName(bn); } else { t.addSubjectIdentifier(l); } } return t; } else{ Topic t=tm.getTopicWithBaseName(bn); if(t==null) { t=tm.createTopic(); t.setBaseName(bn); t.addSubjectIdentifier(tm.makeSubjectIndicatorAsLocator()); } return t; } } public static Topic getOrCreateTopic(String si, String bn, Topic type, TopicMap tm) throws TopicMapException { if(si != null) { Locator l = tm.createLocator(si); Topic t=tm.getTopic(l); if(t==null) { if(bn != null) { t = tm.getTopicWithBaseName(bn); } if(t == null) { t=tm.createTopic(); t.addSubjectIdentifier(l); if(bn!=null) t.setBaseName(bn); } else { t.addSubjectIdentifier(l); } } if(t != null && type != null) { t.addType(type); } return t; } else{ Topic t=tm.getTopicWithBaseName(bn); if(t==null){ t=tm.createTopic(); if(bn!=null) t.setBaseName(bn); t.addSubjectIdentifier(tm.makeSubjectIndicatorAsLocator()); } if(t != null && type != null) { t.addType(type); } return t; } } public static Topic getOrCreateTopic(Locator si, String bn, String displayName, Topic typeTopic, TopicMap tm) throws TopicMapException { Topic topic = null; if(si != null) { topic = tm.getTopic(si); if(topic == null) { if(bn != null) { bn = bn.trim(); if(bn.length() > 0) { topic = tm.getTopicWithBaseName(bn); } } if(topic == null) { topic = tm.createTopic(); } topic.addSubjectIdentifier(si); if(bn != null) { if(!bn.equals(topic.getBaseName())) topic.setBaseName(bn); } if(displayName != null) { displayName = displayName.trim(); if(displayName.length() > 0) { topic.setDisplayName("en", displayName); } } if(typeTopic != null) { if(!topic.isOfType(typeTopic)) topic.addType(typeTopic); } } else { if(bn != null && topic.getBaseName() == null) { topic.setBaseName(bn); } if(displayName != null && topic.getDisplayName("en") == null) { displayName = displayName.trim(); if(displayName.length() > 0) { topic.setDisplayName("en", displayName); } } if(typeTopic != null) { if(!topic.isOfType(typeTopic)) topic.addType(typeTopic); } } } return topic; } // ------------------------------------------------------------------------- public static void makeSubclassOf(Topic subclass, Topic superclass, TopicMap tm) throws TopicMapException { Topic supersubClassTopic = getOrCreateTopic(XTMPSI.SUPERCLASS_SUBCLASS, "superclass-subclass", tm); Topic subclassTopic = getOrCreateTopic(XTMPSI.SUBCLASS, "subclass", tm); Topic superclassTopic = getOrCreateTopic(XTMPSI.SUPERCLASS, "superclass", tm); Association ta = tm.createAssociation(supersubClassTopic); ta.addPlayer(subclass, subclassTopic); ta.addPlayer(superclass, superclassTopic); } // ------------------------------------------------------------------------- public static String getContent(URL url) { return getContent(url.toExternalForm()); } public static String getContent(String url) { String content = null; try { if(url.endsWith(".pdf") || url.endsWith(".PDF")) { System.out.println("Found no content. Reading the url content as a PDF."); content = PDFbox.extractTextOutOfPDF(url); } else if(url.endsWith(".doc") || url.endsWith(".DOC") || url.endsWith(".ppt") || url.endsWith(".PPT")) { System.out.println("Found no content. Reading the url content as a MS Office file."); content = MSOfficeBox.getText(new URL(url)); } else { System.out.println("Found no content. Reading the url content."); content = IObox.doUrl(new URL(url)); } } catch(Exception e) { e.printStackTrace(); } return content; } public static String getContent(BrowserExtractRequest request) { String url = request.getSource(); String content = request.getSelection(); if(content == null && url != null) { try { // Reading url content from url instead of request.getContent(). // Sometimes browser modifies the content and wrong content is transferred // to Wandora. String lurl = url.toLowerCase(); if(lurl.endsWith(".pdf")) { System.out.println("Found no content. Reading the url content as a PDF."); content = PDFbox.extractTextOutOfPDF(url); } else if(lurl.endsWith(".doc") || lurl.endsWith(".ppt") || lurl.endsWith(".xsl")) { System.out.println("Found no content. Reading the url content as a MS Office file."); content = MSOfficeBox.getText(new URL(url)); } else if(lurl.endsWith(".xml")) { System.out.println("Found no content. Reading the url content as an XML file."); content = getContent(url); } else if(lurl.endsWith(".rdf") || lurl.endsWith(".owl")) { System.out.println("Found no content. Reading the url content as an RDF file."); content = getContent(url); } } catch(Exception e) { e.printStackTrace(); } } if(content == null) { content = request.getContent(); } if(content == null && url != null) { try { System.out.println("Found no content. Reading the url content."); content = getContent(url); } catch(Exception e) { e.printStackTrace(); } } return content; } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- public static String doBrowserExtractForClassifiers(AbstractExtractor callback, BrowserExtractRequest request, Wandora wandora, String defaultEncoding) throws TopicMapException { try { String url=request.getSource(); TopicMap tm=wandora.getTopicMap(); Topic theTopic=null; String content = request.getSelection(); // SOURCE IS A FRACTION OF URL if(content!=null) { System.out.println("Found selection."); String tidyContent = XMLbox.cleanUp( content ); if(tidyContent != null && tidyContent.length() > 0) { content = XMLbox.getAsText(tidyContent, defaultEncoding); } Topic sourceTopic=tm.getTopicBySubjectLocator(url); if(sourceTopic==null) { sourceTopic=tm.createTopic(); org.wandora.topicmap.Locator l = tm.createLocator(url); sourceTopic.addSubjectIdentifier(l); sourceTopic.setSubjectLocator(l); } theTopic = tm.createTopic(); theTopic.addSubjectIdentifier(tm.makeSubjectIndicatorAsLocator()); fillDocumentTopic(callback, theTopic, tm, content); Association a = tm.createAssociation(getSourceType(tm)); a.addPlayer(theTopic, getDocumentType(tm)); a.addPlayer(sourceTopic, getSourceType(tm)); } // SOURCE IS A COMPLETE URL else { if(content == null && url != null) { content = ExtractHelper.getContent(url); } if(content == null) { content = request.getContent(); } theTopic=tm.getTopicBySubjectLocator(url); if(theTopic==null) { theTopic=tm.createTopic(); org.wandora.topicmap.Locator l = tm.createLocator(url); theTopic.addSubjectIdentifier(l); theTopic.setSubjectLocator(l); fillDocumentTopic(callback, theTopic, tm, content); } } callback.setMasterSubject( theTopic.getOneSubjectIdentifier().toExternalForm() ); callback._extractTopicsFrom(content, tm); wandora.doRefresh(); callback.clearMasterSubject(); return null; } catch(Exception e) { callback.clearMasterSubject(); e.printStackTrace(); return BrowserPluginExtractor.RETURN_ERROR+e.getMessage(); } } public static String solveTitle(String content) { if(content == null || content.length() == 0) return "empty-document"; boolean forceTrim = false; String title = null; int i = content.indexOf("\n"); if(i > 0) title = content.substring(0, i); else { title = content.substring(0, Math.min(80, content.length())); forceTrim = true; } if(title != null && (forceTrim || title.length() > 80)) { title = title.substring(0, Math.min(80, title.length())); while(!title.endsWith(" ") && title.length()>10) { title = title.substring(0, title.length()-1); } title = Textbox.trimExtraSpaces(title) + "..."; } return title; } public static void fillDocumentTopic(AbstractExtractor callback, Topic textTopic, TopicMap topicMap, String content) { try { String trimmedText = Textbox.trimExtraSpaces(content); if(trimmedText != null && trimmedText.length() > 0) { Topic contentType = callback.createTopic(topicMap, "document-text"); callback.setData(textTopic, contentType, "en", trimmedText); } String title = solveTitle(trimmedText); if(title != null) { textTopic.setBaseName(title + " (" + content.hashCode() + ")"); textTopic.setDisplayName("en", title); } Topic documentType = getDocumentType(topicMap); textTopic.addType(documentType); } catch(Exception e) { callback.log(e); } } public static Topic getSourceType(TopicMap tm) throws TopicMapException { return getOrCreateTopic(SOURCE_SI, "Source", tm); } public static Topic getDocumentType(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(DOCUMENT_SI, "Document", tm); Topic wandoraClass = getWandoraClass(tm); makeSubclassOf(type, wandoraClass, tm); return type; } public static Topic getWandoraClass(TopicMap tm) throws TopicMapException { return getOrCreateTopic(TMBox.WANDORACLASS_SI, "Wandora class", tm); } // ------------------------------------------------------------------------- public static String getTextData(String data) { String tdata = data; try { tdata = XMLbox.cleanUp(data); if(tdata == null || tdata.length() < 1) { // Tidy failed to fix the file... tdata = data; //contentType = "text/html"; } else { // Ok, Tidy fixed the html/xml document tdata = XMLbox.getAsText(tdata, "UTF-8"); //System.out.println("content after getAsText: "+content); //contentType = "text/txt"; } } catch(Exception e) { e.printStackTrace(); tdata = data; //contentType = "text/raw"; } return tdata; } }
15,704
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MobyThesaurusExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/MobyThesaurusExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * MobyThesaurusExtractor.java * * Created on 15. lokakuuta 2007, 18:08 * */ package org.wandora.application.tools.extractors; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.InputStreamReader; import java.io.StringReader; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import org.wandora.application.WandoraTool; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicTools; /** * <p> * Tool reads Moby thesaurus file and converts if to a topic map. Moby thesaurus * file is a simple text file where each line defines single word and related * words. For example: * <p> * <p> * word1 relatedWord1 relatedWord2 relatedWord3 relatedWord4 ...<br> * word2 relatedWord1 relatedWord2 relatedWord3 relatedWord4 ...<br> * </p> * <p> * This extractor creates a topic for each word (including related words) and * a binary association for each word-relatedWord pair. If word has four related * words then extractor creates four associations. Notice the word may be a * related word for some other word, increasing the overall number of associations * one word eventually gets. * </p> * <p> * Moby thesaurus is public domain and can be acquired from * http://www.gutenberg.org/etext/3202 * </p> * <p> * As the Moby thesaurus contains hundreds of thousands words Wandora * requires at least 2G of memory to extract complete thesaurus. * </p> * * @author akivela */ public class MobyThesaurusExtractor extends AbstractExtractor implements WandoraTool { private static final long serialVersionUID = 1L; public String locatorPrefix = "http://wandora.org/si/moby/"; public boolean ANTISYMMETRIC_ASSOCIATIONS = true; public boolean REMOVE_RARE_WORDS = false; /** Creates a new instance of MobyThesaurusExtractor */ public MobyThesaurusExtractor() { } @Override public String getName() { return "Moby thesaurus extractor"; } @Override public String getDescription() { return "Extract Moby thesaurus database."; } @Override public String getGUIText(int textType) { switch(textType) { case SELECT_DIALOG_TITLE: return "Select Moby thesaurus data file(s) or directories containing Moby thesaurus data files!"; case POINT_START_URL_TEXT: return "Where would you like to start the crawl?"; case INFO_WAIT_WHILE_WORKING: return "Wait while seeking Moby thesaurus data files!"; case FILE_PATTERN: return ".*"; case DONE_FAILED: return "Ready. No extractions! %1 Moby thesaurus data file(s) crawled!"; case DONE_ONE: return "Ready. Successful extraction! %1 Moby thesaurus data file(s) crawled!"; case DONE_MANY: return "Ready. Total %0 successful extractions! %1 Moby thesaurus data file(s) crawled!"; case LOG_TITLE: return "Moby thesaurus extraction Log"; } return ""; } @Override public boolean browserExtractorConsumesPlainText() { return true; } public boolean _extractTopicsFrom(URL url, TopicMap topicMap) throws Exception { if(url == null) return false; BufferedReader urlReader = new BufferedReader( new InputStreamReader ( url.openStream() ) ); return _extractTopicsFrom(urlReader, topicMap); } public boolean _extractTopicsFrom(File thesaurusFile, TopicMap topicMap) throws Exception { boolean result = false; BufferedReader breader = null; try { if(thesaurusFile == null) { log("No Moby thesaurus data file addressed! Using default file name 'mobythesaurus.txt'!"); thesaurusFile = new File("mobythesaurus.txt"); } FileReader fr = new FileReader(thesaurusFile); breader = new BufferedReader(fr); result = _extractTopicsFrom(breader, topicMap); } finally { if(breader != null) breader.close(); } return result; } public boolean _extractTopicsFrom(String str, TopicMap topicMap) throws Exception { boolean answer = _extractTopicsFrom(new BufferedReader(new StringReader(str)), topicMap); return answer; } public boolean _extractTopicsFrom(BufferedReader breader, TopicMap topicMap) throws Exception { int basewordCounter = 0; int associationCounter = 0; int wordCounter = 0; try { Topic relatedType = getOrCreateTopic(topicMap, makeSI("schema/related-words"), "moby-related-words", null); Topic role1 = getOrCreateTopic(topicMap, makeSI("schema/word1"), "word-1", null); Topic role2 = getOrCreateTopic(topicMap, makeSI("schema/word2"), "word-2", null); String line = ""; Association association = null; String[] words; Topic baseword; String basewordString; Topic relatedWord; String relatedWordString; line = breader.readLine(); while(line != null && !forceStop()) { words = line.split(","); if(words.length > 0) { basewordString = words[0]; if(basewordString != null) { basewordString = basewordString.trim(); if(basewordString.length() > 0) { basewordCounter++; wordCounter++; baseword = getOrCreateTopic(topicMap, makeSI(basewordString), basewordString, null); hlog("Found word '"+basewordString+"'."); for(int i=1; i<words.length && !forceStop(); i++) { relatedWordString = words[i]; if(relatedWordString != null) { relatedWordString = relatedWordString.trim(); if(relatedWordString.length() > 0 && !relatedWordString.equals(basewordString)) { relatedWord = getOrCreateTopic(topicMap, makeSI(relatedWordString), relatedWordString, null); wordCounter++; if(ANTISYMMETRIC_ASSOCIATIONS || !associationExists(baseword, relatedWord, relatedType)) { association = topicMap.createAssociation(relatedType); association.addPlayer(baseword, role1); association.addPlayer(relatedWord, role2); associationCounter++; } } } } } } } setProgress(basewordCounter); line = breader.readLine(); } if(REMOVE_RARE_WORDS) { log("Removing rare words with maximum one connection!"); Topic wordTopic = null; ArrayList<Topic> rareWords = new ArrayList<Topic>(); for( Iterator<Topic> wordTopicIter = topicMap.getTopics(); wordTopicIter.hasNext(); ) { wordTopic = wordTopicIter.next(); if(wordTopic.getAssociations().size() < 2) { rareWords.add(wordTopic); } } for(Iterator<Topic> wordTopicIter = rareWords.iterator(); wordTopicIter.hasNext(); ) { wordTopic = wordTopicIter.next(); if(!wordTopic.mergesWithTopic(role1) && !wordTopic.mergesWithTopic(role2) && !wordTopic.mergesWithTopic(relatedType)) { if(wordTopic.isDeleteAllowed()) { log("Removing '"+getTopicName(wordTopic)+"'."); wordTopic.remove(); } } } } } catch(Exception e) { log(e); } log("Found total "+basewordCounter+" basewords"); log("Found total "+wordCounter+" words"); log("Created total "+associationCounter+" associations"); return true; } public boolean associationExists(Topic t1, Topic t2, Topic at) { if(t1 == null || t2 == null || at == null) return false; try { Collection<Association> c = t1.getAssociations(at); Association a = null; Collection<Topic> roles = null; Topic player = null; for(Iterator<Association> i=c.iterator(); i.hasNext(); ) { a = i.next(); roles = a.getRoles(); for(Iterator<Topic> it = roles.iterator(); it.hasNext(); ) { player = a.getPlayer(it.next()); if(player != null && t2.mergesWithTopic(player)) return true; } } } catch(Exception e) { e.printStackTrace(); } return false; } public Topic getOrCreateTopic(TopicMap topicmap, String si, String baseName, String displayName) { return getOrCreateTopic(topicmap, new Locator(si), baseName, displayName, null); } public Topic getOrCreateTopic(TopicMap topicmap, Locator si, String baseName, String displayName) { return getOrCreateTopic(topicmap, si, baseName, displayName, null); } public Topic getOrCreateTopic(TopicMap topicmap, Locator si, String baseName, String displayName, Topic typeTopic) { try { return ExtractHelper.getOrCreateTopic(si, baseName, displayName, typeTopic, topicmap); } catch(Exception e) { log(e); } return null; } public Locator makeSI(String str) { return new Locator( TopicTools.cleanDirtyLocator(locatorPrefix + str) ); } @Override public boolean useTempTopicMap() { return false; } }
11,340
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
IMDBExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/IMDBExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * IMDBExtractor.java * * Created on 16.6.2006, 10:41 */ package org.wandora.application.tools.extractors; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.StringReader; import java.net.URL; import java.util.HashMap; import java.util.HashSet; import org.wandora.application.WandoraTool; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicTools; import org.wandora.topicmap.XTMPSI; import org.wandora.topicmap.database2.DatabaseTopicMap; import org.wandora.topicmap.layered.LayerStack; /** * * @author olli */ public class IMDBExtractor extends AbstractExtractor implements WandoraTool { private static final long serialVersionUID = 1L; public static final String ACTOR_SI="http://wandora.org/si/imdb/actor"; public static final String DIRECTOR_SI="http://wandora.org/si/imdb/director"; public static final String PRODUCER_SI="http://wandora.org/si/imdb/producer"; public static final String ROLE_SI="http://wandora.org/imdb/si/role"; public static final String EPISODE_SI="http://wandora.org/si/imdb/episode"; public static final String SHOW_SI="http://wandora.org/si/imdb/show"; public static final String TVSHOW_SI="http://wandora.org/si/imdb/tvshow"; public static final String TVMINI_SI="http://wandora.org/si/imdb/tvmini"; public static final String MOVIE_SI="http://wandora.org/si/imdb/movie"; public static final String TVMOVIE_SI="http://wandora.org/si/imdb/tvmovie"; public static final String VIDEOMOVIE_SI="http://wandora.org/si/imdb/videomovie"; public static final String VIDEOGAME_SI="http://wandora.org/si/imdb/videogame"; public static final String KEYWORD_SI="http://wandora.org/si/imdb/keyword"; public static final String LANGUAGE_SI="http://wandora.org/si/imdb/language"; public static final String COUNTRY_SI="http://wandora.org/si/imdb/country"; public static final String YEAR_SI="http://wandora.org/si/imdb/year"; public static final String GENRE_SI="http://wandora.org/si/imdb/genre"; public static final String LOCATION_SI="http://wandora.org/si/imdb/location"; public static final String RUNTIME_SI="http://wandora.org/si/imdb/runtime"; public static final String RUNTIMEINFO_SI="http://wandora.org/si/imdb/runtimeinfo"; public static final String RELEASEDATE_SI="http://wandora.org/si/imdb/releasedate"; public static final String RELEASEDATEINFO_SI="http://wandora.org/si/imdb/releasedateinfo"; public static final String PLOT_SI="http://wandora.org/si/imdb/plot"; public static final String PERSON_SI="http://wandora.org/si/imdb/person"; public static final String DATE_SI="http://wandora.org/si/imdb/date"; public static final String DATEOFBIRTH_SI="http://wandora.org/si/imdb/dateofbirth"; public static final String DATEOFDEATH_SI="http://wandora.org/si/imdb/dateofdeath"; public static final String BIOGRAPHY_SI="http://wandora.org/si/imdb/biography"; public static final String REALNAME_SI="http://wandora.org/si/imdb/realname"; public static final String PLACE_SI="http://wandora.org/si/imdb/place"; /** Creates a new instance of IMDBExtractor */ public IMDBExtractor() { } @Override public String getName() { return "IMDB Extractor"; } @Override public String getDescription(){ return "Extract data from Internet Movie Database data files"; } @Override public boolean useTempTopicMap(){ return false; } @Override public String getGUIText(int textType) { switch(textType) { case SELECT_DIALOG_TITLE: return "Select IMDB list file(s) or directories containing list files!"; case POINT_START_URL_TEXT: return "Where would you like to start the crawl?"; case INFO_WAIT_WHILE_WORKING: return "Wait while seeking list files!"; case FILE_PATTERN: return ".*\\.list"; case DONE_FAILED: return "Ready. No extractions! %1 list file(s) crawled!"; case DONE_ONE: return "Ready. Successful extraction! %1 list file(s) crawled!"; case DONE_MANY: return "Ready. Total %0 successful extractions! %1 list file(s) crawled!"; case LOG_TITLE: return "IMDB data extraction Log"; } return ""; } @Override public boolean browserExtractorConsumesPlainText() { return true; } public boolean _extractTopicsFrom(String str, TopicMap topicMap) throws Exception { boolean answer = extractFromReader(new BufferedReader(new StringReader(str)), topicMap); return answer; } public boolean _extractTopicsFrom(File f, TopicMap t) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f))); boolean result = false; try { result = extractFromReader(br,t); } finally { if(br != null) br.close(); } return result; } public boolean _extractTopicsFrom(URL u, TopicMap t) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(u.openStream())); boolean result = false; try { result = extractFromReader(br,t); } finally { if(br != null) br.close(); } return result; } public boolean extractFromReader(BufferedReader in,TopicMap tm) throws Exception { boolean resetIndexes=false; if(tm instanceof LayerStack){ LayerStack ls=(LayerStack)tm; tm=ls.getSelectedLayer().getTopicMap(); } if(tm instanceof DatabaseTopicMap){ ((DatabaseTopicMap)tm).setCompleteIndex(); resetIndexes=true; } boolean oldConsistencyCheck=tm.getConsistencyCheck(); tm.setConsistencyCheck(false); tm.disableAllListeners(); try{ String line=null; int counter=0; while( (line=in.readLine())!=null ){ if(line.equals("THE ACTORS LIST")){ log("Extracting actor list"); in.readLine(); // =============== in.readLine(); // in.readLine(); // Name in.readLine(); // ---- return extractActorList(in,tm); } else if(line.equals("THE ACTRESSES LIST")){ log("Extracting actor list"); in.readLine(); // =============== in.readLine(); // in.readLine(); // Name in.readLine(); // ---- return extractActorList(in,tm); } else if(line.equals("8: THE KEYWORDS LIST")){ log("Extracting keyword list"); in.readLine(); // ============== in.readLine(); // return extractKeywordList(in,tm); } else if(line.equals("COUNTRIES LIST")){ log("Extracting country list"); in.readLine(); // ============== return extractCountryList(in,tm); } else if(line.equals("LANGUAGE LIST")){ log("Extracting language list"); in.readLine(); // ============== return extractLanguageList(in,tm); } else if(line.equals("LOCATIONS LIST")){ log("Extracting location list"); in.readLine(); // ============== in.readLine(); // return extractLocationList(in,tm); } else if(line.equals("8: THE GENRES LIST")){ log("Extracting genre list"); in.readLine(); // ============== in.readLine(); // return extractGenreList(in,tm); } else if(line.equals("MOVIES LIST")){ log("Extracting movie list"); in.readLine(); // ============== in.readLine(); // return extractMovieList(in,tm); } else if(line.equals("BIOGRAPHY LIST")){ log("Extracting biography list"); in.readLine(); // ============== in.readLine(); // -------------- return extractBiographyList(in,tm); } else if(line.equals("THE PRODUCERS LIST")){ log("Extracting producer list"); in.readLine(); // ============== in.readLine(); // in.readLine(); // Name Titles in.readLine(); // ---- ------ return extractProducerList(in,tm); } else if(line.equals("THE DIRECTORS LIST")){ log("Extracting directors list"); in.readLine(); // ============== in.readLine(); // in.readLine(); // Name Titles in.readLine(); // ---- ------ return extractDirectorList(in,tm); } else if(line.equals("PLOT SUMMARIES LIST")){ log("Extracting plot summary list"); in.readLine(); // ============== in.readLine(); // return extractPlotList(in,tm); } else if(line.equals("RUNNING TIMES LIST")){ log("Extracting running time list"); in.readLine(); // ============== return extractRunningTimeList(in,tm); } else if(line.equals("RELEASE DATES LIST")){ log("Extracting release date list"); in.readLine(); // ============== return extractReleaseDateList(in,tm); } counter++; if(counter>20000) break; } log("Unknown file type"); if(resetIndexes){ ((DatabaseTopicMap)tm).resetCompleteIndex(); } return false; } finally{ tm.enableAllListeners(); tm.setConsistencyCheck(oldConsistencyCheck); } } public void createSchemaTopics(TopicMap tm) throws TopicMapException { Topic actor=getOrCreateTopic(tm,ACTOR_SI); actor.setBaseName("Actor"); Topic director=getOrCreateTopic(tm,DIRECTOR_SI); director.setBaseName("Director"); Topic producer=getOrCreateTopic(tm,PRODUCER_SI); producer.setBaseName("Producer"); Topic role=getOrCreateTopic(tm,ROLE_SI); role.setBaseName("Role name"); Topic episode=getOrCreateTopic(tm,EPISODE_SI); episode.setBaseName("Episode"); Topic show=getOrCreateTopic(tm,SHOW_SI); show.setBaseName("Show"); Topic tvshow=getOrCreateTopic(tm,TVSHOW_SI); tvshow.setBaseName("TV series"); Topic tvmini=getOrCreateTopic(tm,TVMINI_SI); tvmini.setBaseName("TV mini series"); Topic movie=getOrCreateTopic(tm,MOVIE_SI); movie.setBaseName("Movie"); Topic tvmovie=getOrCreateTopic(tm,TVMOVIE_SI); tvmovie.setBaseName("TV Movie"); Topic videomovie=getOrCreateTopic(tm,VIDEOMOVIE_SI); videomovie.setBaseName("Video Movie"); Topic videogame=getOrCreateTopic(tm,VIDEOGAME_SI); videogame.setBaseName("Video Game"); Topic keyword=getOrCreateTopic(tm,KEYWORD_SI); keyword.setBaseName("Keyword"); Topic language=getOrCreateTopic(tm,LANGUAGE_SI); language.setBaseName("Language"); Topic country=getOrCreateTopic(tm,COUNTRY_SI); country.setBaseName("Country"); Topic genre=getOrCreateTopic(tm,GENRE_SI); genre.setBaseName("Genre"); Topic location=getOrCreateTopic(tm,LOCATION_SI); location.setBaseName("Location"); Topic person=getOrCreateTopic(tm,PERSON_SI); person.setBaseName("Person"); Topic date=getOrCreateTopic(tm,DATE_SI); date.setBaseName("Date"); Topic dateofbirth=getOrCreateTopic(tm,DATEOFBIRTH_SI); dateofbirth.setBaseName("Date of birth"); Topic dateofdeath=getOrCreateTopic(tm,DATEOFDEATH_SI); dateofdeath.setBaseName("Date of death"); Topic biography=getOrCreateTopic(tm,BIOGRAPHY_SI); biography.setBaseName("Biography"); Topic realname=getOrCreateTopic(tm,REALNAME_SI); realname.setBaseName("Real name"); Topic place=getOrCreateTopic(tm,PLACE_SI); place.setBaseName("Place"); Topic plot=getOrCreateTopic(tm,PLOT_SI); plot.setBaseName("Plot"); Topic runtime=getOrCreateTopic(tm,RUNTIME_SI); runtime.setBaseName("Running time"); Topic runtimeinfo=getOrCreateTopic(tm,RUNTIMEINFO_SI); runtimeinfo.setBaseName("Running time info"); Topic releasedate=getOrCreateTopic(tm,RELEASEDATE_SI); releasedate.setBaseName("Release date"); Topic releasedateinfo=getOrCreateTopic(tm,RELEASEDATEINFO_SI); releasedateinfo.setBaseName("Release date info"); } // private HashMap<String,Topic> topicCache=new HashMap<String,Topic>(); public Topic getOrCreateTopic(TopicMap tm, String si) throws TopicMapException { // Topic t=topicCache.get(si); // if(t!=null) return t; Topic t=tm.getTopic(si); if(t==null){ t=tm.createTopic(); t.addSubjectIdentifier(tm.createLocator(si)); } // topicCache.put(si,t); return t; } private static String cleanLocator(String s){ s=TopicTools.cleanDirtyLocator(s); if(s.length()>255) s=s.substring(0,255); return s; } public Topic getPersonTopic(TopicMap tm,String name) throws TopicMapException { return getPersonTopic(tm,name,null); } public Topic getPersonTopic(TopicMap tm,String name,String type) throws TopicMapException { if(type==null) type=PERSON_SI; Locator l=tm.createLocator(cleanLocator(type+"/"+name)); Topic t=tm.getTopicWithBaseName(name); if(t==null) t=tm.getTopic(l); if(t==null){ t=tm.createTopic(); t.addSubjectIdentifier(l); t.setBaseName(name); t.addType(getOrCreateTopic(tm,type)); } return t; } public Topic getActorTopic(TopicMap tm,String name) throws TopicMapException { return getPersonTopic(tm,name,ACTOR_SI); } private HashSet<String> typeFilter; // { typeFilter=null; } { typeFilter=new HashSet<String>(); typeFilter.add(MOVIE_SI); } public Topic getShowTopic(TopicMap tm,String name) throws TopicMapException { Topic t=tm.getTopicWithBaseName(name); if(t==null){ String type=null; if(name.startsWith("\"")){ if(name.contains("(mini)")) type=TVMINI_SI; else type=TVSHOW_SI; } else if(name.contains("(TV)")) type=TVMOVIE_SI; else if(name.contains("(V)")) type=VIDEOMOVIE_SI; else if(name.contains("(VG)")) type=VIDEOGAME_SI; else type=MOVIE_SI; if(typeFilter!=null && !typeFilter.contains(type)) return null; Locator l=tm.createLocator(cleanLocator(type+"/"+name)); t=tm.getTopic(l); if(t!=null) return t; t=tm.createTopic(); t.addSubjectIdentifier(l); t.setBaseName(name); t.addType(getOrCreateTopic(tm,type)); String dispName=name; int ind=dispName.indexOf("("); if(ind!=-1) dispName=dispName.substring(0,ind).trim(); if(dispName.startsWith("\"")){ int ind2=dispName.lastIndexOf("\""); if(ind2>ind) dispName=dispName.substring(1,ind2).trim(); } t.setDisplayName(null,dispName); } return t; } public Topic getRoleTopic(TopicMap tm,String name) throws TopicMapException { Locator l=tm.createLocator(cleanLocator(ROLE_SI+"/"+name)); Topic t=tm.getTopicWithBaseName(name+" (role name)"); if(t==null) t=tm.getTopic(l); if(t==null){ t=tm.createTopic(); t.addSubjectIdentifier(l); t.setBaseName(name+" (role name)"); t.addType(getOrCreateTopic(tm,ROLE_SI)); } return t; } public Topic getEpisodeTopic(TopicMap tm,Topic show,String name) throws TopicMapException { Locator l=tm.createLocator(cleanLocator(EPISODE_SI+"/"+show.getBaseName()+"/"+name)); Topic t=tm.getTopicWithBaseName(show.getBaseName()+" {"+name+"}"); if(t==null) t=tm.getTopic(l); if(t==null){ t=tm.createTopic(); t.addSubjectIdentifier(l); t.setBaseName(show.getBaseName()+" {"+name+"}"); Topic episodeTopic=getOrCreateTopic(tm,EPISODE_SI); t.addType(episodeTopic); Association a=tm.createAssociation(episodeTopic); a.addPlayer(show,getOrCreateTopic(tm,SHOW_SI)); a.addPlayer(t,episodeTopic); } return t; } private static final HashMap<String,String> typeNames=new HashMap<String,String>(); static { typeNames.put(KEYWORD_SI,"keyword"); typeNames.put(LANGUAGE_SI,"language"); typeNames.put(COUNTRY_SI,"country"); typeNames.put(GENRE_SI,"genre"); typeNames.put(LOCATION_SI,"location"); typeNames.put(RUNTIME_SI,"runtime"); typeNames.put(RUNTIMEINFO_SI,"runtimeinfo"); typeNames.put(RELEASEDATE_SI,"releasedate"); typeNames.put(RELEASEDATEINFO_SI,"releasedateinfo"); } public Topic getKeywordTopic(TopicMap tm,String name,String keywordType) throws TopicMapException { String typeName=typeNames.get(keywordType); Locator l=tm.createLocator(cleanLocator(keywordType+"/"+name)); Topic t=tm.getTopicWithBaseName(name+" ("+typeName+")"); if(t==null) t=tm.getTopic(l); if(t==null){ t=tm.createTopic(); t.addSubjectIdentifier(l); t.setBaseName(name+" ("+typeName+")"); Topic keywordTopic=getOrCreateTopic(tm,keywordType); t.addType(keywordTopic); } return t; } public Topic getDateTopic(TopicMap tm,String text) throws TopicMapException { Locator l=tm.createLocator(cleanLocator(DATE_SI+"/"+text)); Topic t=tm.getTopicWithBaseName(text); if(t==null) t=tm.getTopic(l); if(t==null){ t=tm.createTopic(); t.addSubjectIdentifier(l); t.setBaseName(text); Topic keywordTopic=getOrCreateTopic(tm,DATE_SI); t.addType(keywordTopic); } return t; } public Topic getPlaceTopic(TopicMap tm,String text) throws TopicMapException { Locator l=tm.createLocator(cleanLocator(PLACE_SI+"/"+text)); Topic t=tm.getTopicWithBaseName(text); if(t==null) t=tm.getTopic(l); if(t==null){ t=tm.createTopic(); t.addSubjectIdentifier(l); t.setBaseName(text); Topic keywordTopic=getOrCreateTopic(tm,PLACE_SI); t.addType(keywordTopic); } return t; } public Association addAppearance(TopicMap tm,Topic actor,Topic show,Topic episode,Topic role,String type) throws TopicMapException { Topic actorType=getOrCreateTopic(tm,type); Association a=tm.createAssociation(actorType); a.addPlayer(actor,actorType); a.addPlayer(show,getOrCreateTopic(tm,SHOW_SI)); if(episode!=null) a.addPlayer(episode,getOrCreateTopic(tm,EPISODE_SI)); if(role!=null) a.addPlayer(role,getOrCreateTopic(tm,ROLE_SI)); return a; } public Association addKeyword(TopicMap tm,Topic show,Topic keyword,String keywordType) throws TopicMapException { Topic keywordTopic=getOrCreateTopic(tm,keywordType); Association a=tm.createAssociation(keywordTopic); a.addPlayer(keyword,keywordTopic); a.addPlayer(show,getOrCreateTopic(tm,SHOW_SI)); return a; } public void addDateOfBirth(TopicMap tm,Topic person,String text) throws TopicMapException { int ind=text.indexOf("("); if(ind!=-1) text=text.substring(0,ind).trim(); ind=text.indexOf(","); String date=text; String place=null; if(ind!=-1) { date=text.substring(0,ind); place=text.substring(ind+1).trim(); } Association a=tm.createAssociation(getOrCreateTopic(tm,DATEOFBIRTH_SI)); a.addPlayer(person,getOrCreateTopic(tm,PERSON_SI)); a.addPlayer(getDateTopic(tm,date),getOrCreateTopic(tm,DATE_SI)); if(place!=null) a.addPlayer(getPlaceTopic(tm,place),getOrCreateTopic(tm,PLACE_SI)); } public void addDateOfDeath(TopicMap tm,Topic person,String text) throws TopicMapException { int ind=text.indexOf("("); if(ind!=-1) text=text.substring(0,ind).trim(); ind=text.indexOf(","); String date=text; String place=null; if(ind!=-1) { date=text.substring(0,ind); place=text.substring(ind+1).trim(); } Association a=tm.createAssociation(getOrCreateTopic(tm,DATEOFDEATH_SI)); a.addPlayer(person,getOrCreateTopic(tm,PERSON_SI)); a.addPlayer(getDateTopic(tm,date),getOrCreateTopic(tm,DATE_SI)); if(place!=null) a.addPlayer(getPlaceTopic(tm,place),getOrCreateTopic(tm,PLACE_SI)); } public void addRuntime(TopicMap tm,Topic show,Topic runtime,Topic runtimeinfo) throws TopicMapException { Topic runtimeType=getOrCreateTopic(tm,RUNTIME_SI); Association a=tm.createAssociation(runtimeType); a.addPlayer(show,getOrCreateTopic(tm,SHOW_SI)); a.addPlayer(runtime,runtimeType); if(runtimeinfo!=null) a.addPlayer(runtimeinfo,getOrCreateTopic(tm,RUNTIMEINFO_SI)); } public void addReleaseDate(TopicMap tm,Topic show,Topic date,Topic info) throws TopicMapException { Association a=tm.createAssociation(getOrCreateTopic(tm,RELEASEDATE_SI)); a.addPlayer(show,getOrCreateTopic(tm,SHOW_SI)); a.addPlayer(date,getOrCreateTopic(tm,DATE_SI)); if(info!=null) a.addPlayer(info,getOrCreateTopic(tm,RELEASEDATEINFO_SI)); } public void addBiography(TopicMap tm,Topic person,String text) throws TopicMapException { person.setData(getOrCreateTopic(tm,BIOGRAPHY_SI),getOrCreateTopic(tm,XTMPSI.getLang("en")),text); } public void addRealName(TopicMap tm,Topic person,String text) throws TopicMapException { person.setData(getOrCreateTopic(tm,REALNAME_SI),getOrCreateTopic(tm,XTMPSI.getLang(null)),text); } public void addPlot(TopicMap tm,Topic show,String text) throws TopicMapException { show.setData(getOrCreateTopic(tm,PLOT_SI),getOrCreateTopic(tm,XTMPSI.getLang("en")),text); } public boolean extractDirectorList(BufferedReader in,TopicMap tm) throws Exception { return extractPersonList(in,tm,DIRECTOR_SI); } public boolean extractProducerList(BufferedReader in,TopicMap tm) throws Exception { return extractPersonList(in,tm,PRODUCER_SI); } public boolean extractActorList(BufferedReader in,TopicMap tm) throws Exception { return extractPersonList(in,tm,ACTOR_SI); } public boolean extractPersonList(BufferedReader in,TopicMap tm,String type) throws Exception { String line=null; String actor=null; Topic actorTopic=null; // TopicMap originalMap=tm; // tm=new org.wandora.topicmap.memory.TopicMapImpl(); createSchemaTopics(tm); int counter=0; while( (line=in.readLine())!=null ){ counter++; if((counter%10)==0){ setProgress(counter/100); if(forceStop()) break; takeNap(0); } if((counter%10000)==0){ hlog("Extracting line "+counter); } /* if((counter%10000)==0){ log("merging temporary map at line "+counter); takeNap(0); originalMap.mergeIn(tm); tm=new org.wandora.topicmap.memory.TopicMapImpl(); log("extracting line "+counter); } */ if(line.trim().length()==0) continue; if(line.startsWith("-------------------------------------------------")) break; int tabIndex=line.indexOf("\t"); if(tabIndex>0) { actor=line.substring(0,tabIndex); actorTopic=null; } String appearance=line.substring(tabIndex+1).trim(); int spaceIndex=appearance.indexOf(" "); String show=null; String roleName=null; String episode=null; if(spaceIndex==-1) show=appearance; else{ show=appearance.substring(0,spaceIndex); int roleIndex=appearance.indexOf("[",spaceIndex+2); if(roleIndex!=-1){ int b=appearance.indexOf("]",roleIndex); if(b!=-1) roleName=appearance.substring(roleIndex+1,b); } } int episodeIndex=show.indexOf("{"); if(episodeIndex!=-1){ int b=show.indexOf("}",episodeIndex); if(b!=-1) { episode=show.substring(episodeIndex+1,b); show=show.substring(0,episodeIndex).trim(); } } // if(show.startsWith("\"'")) continue; // MYSQL driver bug? throws exception Topic showTopic=getShowTopic(tm,show); if(showTopic!=null){ if(actorTopic==null) actorTopic=getPersonTopic(tm,actor,type); Topic roleTopic=null; Topic episodeTopic=null; if(roleName!=null) roleTopic=getRoleTopic(tm,roleName); if(episode!=null) episodeTopic=getEpisodeTopic(tm,showTopic,episode); addAppearance(tm,actorTopic,showTopic,episodeTopic,roleTopic,type); } } log("Extracted "+counter+" lines"); return true; } public boolean extractKeywordList(BufferedReader in,TopicMap tm) throws Exception { return extractKeywords(in,tm,KEYWORD_SI); } public boolean extractLanguageList(BufferedReader in,TopicMap tm) throws Exception { return extractKeywords(in,tm,LANGUAGE_SI); } public boolean extractCountryList(BufferedReader in,TopicMap tm) throws Exception { return extractKeywords(in,tm,COUNTRY_SI); } public boolean extractLocationList(BufferedReader in,TopicMap tm) throws Exception { return extractKeywords(in,tm,LOCATION_SI); } public boolean extractGenreList(BufferedReader in,TopicMap tm) throws Exception { return extractKeywords(in,tm,GENRE_SI); } public boolean extractMovieList(BufferedReader in,TopicMap tm) throws Exception { return extractKeywords(in,tm,YEAR_SI); } public boolean extractKeywords(BufferedReader in,TopicMap tm,String keywordType) throws Exception { createSchemaTopics(tm); int counter=0; String line=null; while( (line=in.readLine())!=null ){ counter++; if((counter%10)==0){ setProgress(counter/100); if(forceStop()) break; takeNap(0); } if((counter%10000)==0){ hlog("Extracting line "+counter); } int ind=line.indexOf("\t"); if(ind==-1) continue; String show=line.substring(0,ind).trim(); String keyword=line.substring(ind+1).trim(); Topic showTopic=getShowTopic(tm,show); if(showTopic!=null){ Topic keywordTopic=getKeywordTopic(tm,keyword,keywordType); addKeyword(tm,showTopic,keywordTopic,keywordType); } } log("Extracted "+counter+" lines"); return true; } public boolean extractBiographyList(BufferedReader in,TopicMap tm) throws Exception { createSchemaTopics(tm); int counter=0; String line=null; String type=""; StringBuffer collected=new StringBuffer(); String name=null; boolean bgfound=false; while( (line=in.readLine())!=null ){ counter++; if((counter%10)==0){ setProgress(counter/100); if(forceStop()) break; takeNap(0); } if((counter%10000)==0){ hlog("Extracting line "+counter); } if(line.length()==0){ if(type.equals("NM")) name=collected.toString(); else if(type.equals("RN")){ Topic personTopic=getPersonTopic(tm,name); addRealName(tm,personTopic,collected.toString()); } else if(type.equals("DB")){ Topic personTopic=getPersonTopic(tm,name); addDateOfBirth(tm,personTopic,collected.toString()); } else if(type.equals("DD")){ Topic personTopic=getPersonTopic(tm,name); addDateOfDeath(tm,personTopic,collected.toString()); } else if(type.equals("BG")){ if(!bgfound){ Topic personTopic=getPersonTopic(tm,name); addBiography(tm,personTopic,collected.toString()); bgfound=true; } } collected=new StringBuffer(); type=""; } else{ type=line.substring(0,2); if(collected.length()>0) collected.append(" "); collected.append(line.substring(3).trim()); } if(line.startsWith("----------------------------")) { name=null; bgfound=false; type=""; collected=new StringBuffer(); } } log("Extracted "+counter+" lines"); return true; } public boolean extractPlotList(BufferedReader in,TopicMap tm) throws Exception { createSchemaTopics(tm); int counter=0; String line=null; String type=""; StringBuffer collected=new StringBuffer(); String name=null; boolean plfound=false; while( (line=in.readLine())!=null ){ counter++; if((counter%10)==0){ setProgress(counter/100); if(forceStop()) break; takeNap(0); } if((counter%10000)==0){ hlog("Extracting line "+counter); } if(line.length()==0){ if(type.equals("MV")) name=collected.toString(); else if(type.equals("PL")){ if(!plfound){ Topic show=getShowTopic(tm,name); if(show!=null){ addPlot(tm,show,collected.toString()); } plfound=true; } } collected=new StringBuffer(); type=""; } else{ type=line.substring(0,2); if(collected.length()>0) collected.append(" "); collected.append(line.substring(3).trim()); } if(line.startsWith("----------------------------")) { name=null; plfound=false; type=""; collected=new StringBuffer(); } } log("Extracted "+counter+" lines"); return true; } public boolean extractRunningTimeList(BufferedReader in,TopicMap tm) throws Exception { createSchemaTopics(tm); int counter=0; String line=null; while( (line=in.readLine())!=null ){ counter++; if((counter%10)==0){ setProgress(counter/100); if(forceStop()) break; takeNap(0); } if((counter%10000)==0){ hlog("Extracting line "+counter); } int ind=line.indexOf("\t"); if(ind==-1) continue; String show=line.substring(0,ind).trim(); String time=line.substring(ind+1).trim(); Topic showTopic=getShowTopic(tm,show); if(showTopic!=null){ String extra=null; String country=null; ind=time.indexOf("\t"); if(ind!=-1){ extra=time.substring(ind+1).trim(); time=time.substring(0,ind).trim(); } ind=time.indexOf(":"); if(ind!=-1){ country=time.substring(0,ind); time=time.substring(ind+1); } if(extra!=null){ if(country==null) country=extra; else country+=" "+extra; } Topic runtimeTopic=getKeywordTopic(tm,time,RUNTIME_SI); Topic infoTopic=null; if(country!=null) infoTopic=getKeywordTopic(tm,country,RUNTIMEINFO_SI); addRuntime(tm,showTopic,runtimeTopic,infoTopic); } } log("Extracted "+counter+" lines"); return true; } public boolean extractReleaseDateList(BufferedReader in,TopicMap tm) throws Exception { createSchemaTopics(tm); int counter=0; String line=null; while( (line=in.readLine())!=null ){ counter++; if((counter%10)==0){ setProgress(counter/100); if(forceStop()) break; takeNap(0); } if((counter%10000)==0){ hlog("Extracting line "+counter); } int ind=line.indexOf("\t"); if(ind==-1) continue; String show=line.substring(0,ind).trim(); String time=line.substring(ind+1).trim(); Topic showTopic=getShowTopic(tm,show); if(showTopic!=null){ String extra=null; String country=null; ind=time.indexOf("\t"); if(ind!=-1){ extra=time.substring(ind+1).trim(); time=time.substring(0,ind).trim(); } ind=time.indexOf(":"); if(ind!=-1){ country=time.substring(0,ind); time=time.substring(ind+1); } if(extra!=null){ if(country==null) country=extra; else country+=" "+extra; } Topic dateTopic=getDateTopic(tm,time); Topic infoTopic=null; if(country!=null) infoTopic=getKeywordTopic(tm,country,RELEASEDATEINFO_SI); addReleaseDate(tm,showTopic,dateTopic,infoTopic); } } log("Extracted "+counter+" lines"); return true; } }
37,340
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
VerbOceanExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/VerbOceanExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * SimpleTextDocumentExtractor.java * * Created on 2008-04-18, 12:05 * */ package org.wandora.application.tools.extractors; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * Converts VerbOcean data files to topic maps. VerbOcean data file contains * simple relations between verb words. Each verb relation is quaret with two * verb words and relation name and relation strength. Example relations of * VerbOcean: * * <p><code> * renounce [stronger-than] abandon :: 13.617344<br> * reject [happens-before] abandon :: 11.731130<br> * abandon [similar] reject :: 12.048992<br> * abandon [similar] scrap :: 13.725957<br> * </code></p> * <p> * More about VerbOcean see http://demo.patrickpantel.com/Content/verbocean/ * or paper * </p> * <p> * Timothy Chklovski and Patrick Pantel. 2004.VerbOcean: Mining the Web for * Fine-Grained Semantic Verb Relations. In Proceedings of Conference on Empirical * Methods in Natural Language Processing (EMNLP-04). Barcelona, Spain. * </p> * * @author akivela */ public class VerbOceanExtractor extends AbstractExtractor implements WandoraTool { private static final long serialVersionUID = 1L; boolean INCLUDE_STRENGHTS = true; private Wandora admin = null; private File verbOceanFile = null; /** Creates a new instance of VerbOceanExtractor */ public VerbOceanExtractor() { } @Override public String getName() { return "VerbOcean Extractor"; } @Override public String getDescription() { return "Extracts topics and associations from VerbOcean datafiles. More about VerbOcean see http://demo.patrickpantel.com/Content/verbocean/"; } @Override public boolean useTempTopicMap(){ return false; } @Override public String getGUIText(int textType) { switch(textType) { case SELECT_DIALOG_TITLE: return "Select VerbOcean document(s) or directories containing VerbOcean documents!"; case POINT_START_URL_TEXT: return "Where would you like to start the crawl?"; case INFO_WAIT_WHILE_WORKING: return "Wait while seeking VerbOcean documents!"; case FILE_PATTERN: return ".*\\.txt"; case DONE_FAILED: return "Ready. No extractions! %1 VerbOcean(s) crawled!"; case DONE_ONE: return "Ready. Successful extraction! %1 VerbOcean(s) crawled!"; case DONE_MANY: return "Ready. Total %0 successful extractions! %1 VerbOcean(s) crawled!"; case LOG_TITLE: return "VerbOcean Extraction Log"; } return ""; } @Override public boolean browserExtractorConsumesPlainText() { return true; } public boolean _extractTopicsFrom(URL url, TopicMap topicMap) throws Exception { if(url == null) return false; try { URLConnection uc = null; if(admin != null) { uc = admin.wandoraHttpAuthorizer.getAuthorizedAccess(url); } else { uc = url.openConnection(); Wandora.initUrlConnection(uc); } _extractTopicsFromStream(url.toExternalForm(), uc.getInputStream(), topicMap); return true; } catch(Exception e) { log("Exception occurred while extracting from url\n" + url.toExternalForm(), e); takeNap(1000); } return false; } public boolean _extractTopicsFrom(File file, TopicMap topicMap) throws Exception { if(file == null || file.isDirectory()) return false; try { _extractTopicsFromStream(file.getPath(), new FileInputStream(file), topicMap); return true; } catch(Exception e) { log("Exception occurred while extracting from file " + file.getName(), e); takeNap(1000); } return false; } public boolean _extractTopicsFrom(String str, TopicMap tm) throws Exception { String stringLocator = "http://wandora.org/si/verb-ocean-extractor/"; try { _extractTopicsFromStream(stringLocator, new ByteArrayInputStream(str.getBytes()), tm); return true; } catch(Exception e) { log("Exception occurred while extracting from string.", e); takeNap(1000); } return false; } public void _extractTopicsFromStream(String locator, InputStream inputStream, TopicMap topicMap) { try { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line = reader.readLine(); Pattern linePattern = Pattern.compile("(\\w+)\\s+\\[?([\\w\\-]+)\\]?\\s+(\\w+)\\s*\\:+\\s*(\\d+\\.\\d+)"); Matcher m = null; String verb1 = null; String verb2 = null; String relation = null; String strength = null; Topic verb1Topic = null; Topic verb2Topic = null; int lineCount = 0; int associationCount = 0; //Topic relationTopic = null; Topic strengthTopic = null; log("Prosessing VerbOcean stream!"); while(line != null && line.length() > 0) { lineCount++; setProgress(lineCount / 100); if(!line.startsWith("#")) { m = linePattern.matcher(line); if(m.matches()) { verb1 = m.group(1); relation = m.group(2); verb2 = m.group(3); strength = m.group(4); verb1Topic = getOrCreateTopic(verb1, "verb", topicMap); verb2Topic = getOrCreateTopic(verb2, "verb", topicMap); //relationTopic = getOrCreateTopic(relation, "relation", topicMap); if(INCLUDE_STRENGHTS) { strengthTopic = getOrCreateTopic(strength, "strength", topicMap); associationCount++; createAssociation(relation, verb1Topic, "verb1", verb2Topic, "verb2", strengthTopic, "strength", topicMap); } else { associationCount++; createAssociation(relation, verb1Topic, "verb1", verb2Topic, "verb2", topicMap); } } } line = reader.readLine(); } log("Total "+lineCount+" lines processed!"); log("Total "+associationCount+" VerbOcean associations created!"); log("Ok"); } catch(Exception e) { log(e); } } String SI_BASE = "http://wandora.org/si/verbocean/"; public Topic getOrCreateTopic(String name, String path, TopicMap topicMap) { try { if(topicMap != null) { String si = SI_BASE+path+"/"+name; Topic t = topicMap.getTopic(si); if(t == null) { t = topicMap.createTopic(); t.addSubjectIdentifier(new Locator(si)); t.setBaseName(name); if(path != null && path.length() > 0) { String typeSi = SI_BASE+path; Topic type = topicMap.getTopic(typeSi); if(type == null) { type = topicMap.createTopic(); type.addSubjectIdentifier(new Locator(typeSi)); type.setBaseName(path); } t.addType(type); } } return t; } } catch(Exception e) { log(e); } return null; } public Association createAssociation(String associationType, Topic player1Topic, String role1, Topic player2Topic, String role2, TopicMap topicMap) throws TopicMapException { Topic associationTypeTopic = getOrCreateTopic(associationType, "schema", topicMap); Association association = topicMap.createAssociation(associationTypeTopic); Topic role1Topic = getOrCreateTopic(role1, "schema", topicMap); Topic role2Topic = getOrCreateTopic(role2, "schema", topicMap); association.addPlayer(player1Topic, role1Topic); association.addPlayer(player2Topic, role2Topic); return association; } public Association createAssociation(String associationType, Topic player1Topic, String role1, Topic player2Topic, String role2, Topic player3Topic, String role3, TopicMap topicMap) throws TopicMapException { Topic associationTypeTopic = getOrCreateTopic(associationType, "schema", topicMap); Association association = topicMap.createAssociation(associationTypeTopic); Topic role1Topic = getOrCreateTopic(role1, "schema", topicMap); Topic role2Topic = getOrCreateTopic(role2, "schema", topicMap); Topic role3Topic = getOrCreateTopic(role3, "schema", topicMap); association.addPlayer(player1Topic, role1Topic); association.addPlayer(player2Topic, role2Topic); association.addPlayer(player3Topic, role3Topic); return association; } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- public static final String[] contentTypes=new String[] { "text/plain" }; public String[] getContentTypes() { return contentTypes; } }
11,259
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AbstractExtractorDialog.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/AbstractExtractorDialog.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * AbstractExtractorDialog.java * * Created on 23. toukokuuta 2008, 13:14 */ package org.wandora.application.tools.extractors; import java.awt.Component; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.gui.UIConstants; import org.wandora.application.gui.simple.SimpleFileChooser; import org.wandora.application.gui.simple.SimpleTextPane; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.utils.IObox; /** * * @author akivela */ public class AbstractExtractorDialog extends javax.swing.JDialog { private static final long serialVersionUID = 1L; private Wandora wandora = null; private WandoraTool parentTool = null; private boolean wasAccepted = false; private HashMap<Component,Integer> registeredSources = null; /** Creates new form AbstractExtractorDialog */ public AbstractExtractorDialog(Wandora wandora, boolean modal) { super(wandora, modal); this.wandora = wandora; initComponents(); setSize(640,400); //initialize(null); } public void initialize(WandoraTool parentTool) { this.parentTool = parentTool; wasAccepted = false; ((SimpleTextPane) fileTextPane).dropFileNames(true); ((SimpleTextPane) fileTextPane).setLineWrap(false); ((SimpleTextPane) urlTextPane).dropFileNames(true); ((SimpleTextPane) urlTextPane).setLineWrap(false); if(parentTool instanceof AbstractExtractor) { if(!((AbstractExtractor) parentTool).useURLCrawler()) { crawlerPanel.setVisible(false); } else { crawlerPanel.setVisible(true); } } if(parentTool != null) { setTitle(parentTool.getName()); } else { setTitle("Select extract sources"); } setSize(640,400); if(wandora != null) { wandora.centerWindow(this); } registeredSources = new HashMap<Component,Integer>(); } public boolean wasAccepted() { return wasAccepted; } public int getSelectedSource() { Component selectedComponent = tabbedSourcePane.getSelectedComponent(); Integer source = registeredSources.get(selectedComponent); return source.intValue(); } public void registerSource(String name, Component component, int id) { if(component == null) return; if(registeredSources.get(component) == null) { registeredSources.put(component, Integer.valueOf(id)); tabbedSourcePane.addTab(name, component); } } public void registerUrlSource() { registerSource("Urls", urlPanel, AbstractExtractor.URL_EXTRACTOR); } public void registerFileSource() { registerSource("Files", filePanel, AbstractExtractor.FILE_EXTRACTOR); } public void registerRawSource() { registerSource("Raw", rawPanel, AbstractExtractor.RAW_EXTRACTOR); } // --- CONTENT --- public String getContent() { return rawTextPane.getText(); } // --- FILE SOURCE --- public File[] getFileSources() { String input = fileTextPane.getText(); String[] filenames = splitText(input); ArrayList<File> files = new ArrayList<File>(); File f = null; for(int i=0; i<filenames.length; i++) { if(filenames[i] != null && filenames[i].trim().length() > 0) { f = new File(filenames[i]); if(f.exists()) { files.add(f); } else { if(parentTool != null) { parentTool.log("File '"+filenames[i]+"' not found!"); } } } } return files.toArray( new File[] {} ); } // --- URL SOURCE --- public String[] getURLSources() { String input = urlTextPane.getText(); String[] urls = splitText(input); return urls; } public int getCrawlerMode(int defaultValue) { int mode = defaultValue; try { mode = crawlerComboBox.getSelectedIndex(); // System.out.println("getCrawlerMode: "+ mode); } catch(Exception e) {} return mode; } private String[] splitText(String str) { if(str == null) { return null; } if(str.indexOf("\n") != -1) { String[] s = str.split("\n"); for(int i=0; i<s.length; i++) { s[i] = s[i].trim(); } return s; } else { return new String[] { str.trim() }; } } // ------------------------------------------------------------------------- private void selectFiles() { SimpleFileChooser chooser = UIConstants.getFileChooser(); chooser.setMultiSelectionEnabled(true); //chooser.setDialogTitle(getGUIText(SELECT_DIALOG_TITLE)); chooser.setApproveButtonText("Select"); chooser.setFileSelectionMode(SimpleFileChooser.FILES_AND_DIRECTORIES); //if(accessoryPanel != null) { chooser.setAccessory(accessoryPanel); } if(chooser.open(wandora)==SimpleFileChooser.APPROVE_OPTION) { File[] files = chooser.getSelectedFiles(); File f = null; String fs = ""; for(int i=0; i<files.length; i++) { f = files[i]; fs = fs + f.getAbsolutePath(); if(i<files.length-1) { fs = fs + "\n"; } } String s = fileTextPane.getText(); if(s == null || s.length() == 0) { s = fs; } else { s = s + "\n" + fs; } fileTextPane.setText(s); } } private void selectContextSLFiles() { if(parentTool == null) { return; } Context context = parentTool.getContext(); Iterator iter = context.getContextObjects(); Object o = null; Topic t = null; Locator locator = null; StringBuilder sb = new StringBuilder(""); while(iter.hasNext()) { try { o = iter.next(); if(o == null) continue; if(o instanceof Topic) { t = (Topic) o; if(!t.isRemoved()) { locator = t.getSubjectLocator(); if(locator != null) { String locatorStr = locator.toExternalForm(); if(locatorStr.startsWith("file:")) { locatorStr = IObox.getFileFromURL(locatorStr); sb.append(locatorStr).append("\n"); } } } } } catch(Exception e) { parentTool.log(e); } } String s = urlTextPane.getText(); if(s == null || s.length() == 0) { s = sb.toString(); } else { s = s + "\n" + sb.toString(); } fileTextPane.setText(s); } private void selectContextSLs() { if(parentTool == null) return; Context context = parentTool.getContext(); Iterator iter = context.getContextObjects(); Object o = null; Topic t = null; Locator locator = null; StringBuilder sb = new StringBuilder(""); while(iter.hasNext()) { try { o = iter.next(); if(o == null) continue; if(o instanceof Topic) { t = (Topic) o; if(!t.isRemoved()) { locator = t.getSubjectLocator(); if(locator != null) { String locatorStr = locator.toExternalForm(); sb.append(locatorStr).append("\n"); } } } } catch(Exception e) { parentTool.log(e); } } String s = urlTextPane.getText(); if(s == null || s.length() == 0) { s = sb.toString(); } else { s = s + "\n" + sb.toString(); } urlTextPane.setText(s); } private void selectContextSIs() { if(parentTool == null) return; Context context = parentTool.getContext(); Iterator iter = context.getContextObjects(); Object o = null; Topic t = null; Locator locator = null; StringBuilder sb = new StringBuilder(""); while(iter.hasNext()) { try { o = iter.next(); if(o == null) continue; if(o instanceof Topic) { t = (Topic) o; if(!t.isRemoved()) { Collection<Locator> ls = t.getSubjectIdentifiers(); Iterator<Locator> ils = ls.iterator(); while(ils.hasNext()) { locator = ils.next(); if(locator != null) { String locatorStr = locator.toExternalForm(); sb.append(locatorStr).append("\n"); } } } } } catch(Exception e) { parentTool.log(e); } } String s = urlTextPane.getText(); if(s == null || s.length() == 0) { s = sb.toString(); } else { s = s + "\n" + sb.toString(); } urlTextPane.setText(s); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; urlPanel = new javax.swing.JPanel(); urlLabel = new org.wandora.application.gui.simple.SimpleLabel(); crawlerPanel = new javax.swing.JPanel(); crawlerLabel = new org.wandora.application.gui.simple.SimpleLabel(); crawlerComboBox = new org.wandora.application.gui.simple.SimpleComboBox(); crawlerComboBox.setEditable(false); urlScrollPane = new javax.swing.JScrollPane(); urlTextPane = new org.wandora.application.gui.simple.SimpleTextPane(); urlButtonPanel = new javax.swing.JPanel(); urlGetSIButton = new org.wandora.application.gui.simple.SimpleButton(); urlGetSLButton = new org.wandora.application.gui.simple.SimpleButton(); urlClearButton = new org.wandora.application.gui.simple.SimpleButton(); filePanel = new javax.swing.JPanel(); fileLabel = new org.wandora.application.gui.simple.SimpleLabel(); fileScrollPane = new javax.swing.JScrollPane(); fileTextPane = new org.wandora.application.gui.simple.SimpleTextPane(); fileButtonPanel = new javax.swing.JPanel(); fileBrowseButton = new org.wandora.application.gui.simple.SimpleButton(); fileGetSLButton = new org.wandora.application.gui.simple.SimpleButton(); fileClearButton = new org.wandora.application.gui.simple.SimpleButton(); rawPanel = new javax.swing.JPanel(); rawLabel = new org.wandora.application.gui.simple.SimpleLabel(); rawScrollPane = new javax.swing.JScrollPane(); rawTextPane = new org.wandora.application.gui.simple.SimpleTextPane(); tabbedSourcePane = new org.wandora.application.gui.simple.SimpleTabbedPane(); buttonPanel = new javax.swing.JPanel(); fillerPanel = new javax.swing.JPanel(); extractButton = new org.wandora.application.gui.simple.SimpleButton(); cancelButton = new org.wandora.application.gui.simple.SimpleButton(); urlPanel.setLayout(new java.awt.GridBagLayout()); urlLabel.setText("<html>Select URLs to be extracted. Write URL addresses below or get subjects from the context topics.</html>"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); urlPanel.add(urlLabel, gridBagConstraints); crawlerPanel.setLayout(new java.awt.GridBagLayout()); crawlerLabel.setText("Extract"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); crawlerPanel.add(crawlerLabel, gridBagConstraints); crawlerComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "exactly given urls", "given urls and directly linked documents", "given urls and urls below", "given urls and crawled documents in url domain", "given urls and all crawled documents" })); crawlerComboBox.setPreferredSize(new java.awt.Dimension(200, 21)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; crawlerPanel.add(crawlerComboBox, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(2, 5, 5, 5); urlPanel.add(crawlerPanel, gridBagConstraints); urlScrollPane.setPreferredSize(new java.awt.Dimension(10, 100)); urlScrollPane.setViewportView(urlTextPane); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 5); urlPanel.add(urlScrollPane, gridBagConstraints); urlButtonPanel.setLayout(new java.awt.GridBagLayout()); urlGetSIButton.setText("Get subject identifiers"); urlGetSIButton.setMargin(new java.awt.Insets(1, 6, 1, 6)); urlGetSIButton.setPreferredSize(new java.awt.Dimension(130, 21)); urlGetSIButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { urlGetSIButtonMouseReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 1); urlButtonPanel.add(urlGetSIButton, gridBagConstraints); urlGetSLButton.setText("Get subject locators"); urlGetSLButton.setMargin(new java.awt.Insets(1, 6, 1, 6)); urlGetSLButton.setPreferredSize(new java.awt.Dimension(130, 21)); urlGetSLButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { urlGetSLButtonMouseReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 1); urlButtonPanel.add(urlGetSLButton, gridBagConstraints); urlClearButton.setText("Clear"); urlClearButton.setMargin(new java.awt.Insets(1, 6, 1, 6)); urlClearButton.setPreferredSize(new java.awt.Dimension(60, 21)); urlClearButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { urlClearButtonMouseReleased(evt); } }); urlButtonPanel.add(urlClearButton, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); urlPanel.add(urlButtonPanel, gridBagConstraints); filePanel.setLayout(new java.awt.GridBagLayout()); fileLabel.setText("<html>Select files to be extracted. Write, browse or get subject locators. Text field accepts file drops too.</html>"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); filePanel.add(fileLabel, gridBagConstraints); fileLabel.getAccessibleContext().setAccessibleName("<html>Select files to be extracted. Write or browse filenames or get files from subject locators. The text field accepts file drops too.</html>"); fileScrollPane.setPreferredSize(new java.awt.Dimension(10, 100)); fileScrollPane.setViewportView(fileTextPane); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 5); filePanel.add(fileScrollPane, gridBagConstraints); fileButtonPanel.setLayout(new java.awt.GridBagLayout()); fileBrowseButton.setText("Browse"); fileBrowseButton.setMargin(new java.awt.Insets(1, 6, 1, 6)); fileBrowseButton.setPreferredSize(new java.awt.Dimension(70, 21)); fileBrowseButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { fileBrowseButtonMouseReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 1); fileButtonPanel.add(fileBrowseButton, gridBagConstraints); fileGetSLButton.setText("Get subject locators"); fileGetSLButton.setMargin(new java.awt.Insets(1, 6, 1, 6)); fileGetSLButton.setPreferredSize(new java.awt.Dimension(130, 21)); fileGetSLButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { fileGetSLButtonMouseReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 1); fileButtonPanel.add(fileGetSLButton, gridBagConstraints); fileClearButton.setText("Clear"); fileClearButton.setMargin(new java.awt.Insets(1, 6, 1, 6)); fileClearButton.setPreferredSize(new java.awt.Dimension(60, 21)); fileClearButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { fileClearButtonMouseReleased(evt); } }); fileButtonPanel.add(fileClearButton, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); filePanel.add(fileButtonPanel, gridBagConstraints); rawPanel.setLayout(new java.awt.GridBagLayout()); rawLabel.setText("<html>This tab is used to inject raw content for the extractor. Write, paste or drop the content to the text field.</html>"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); rawPanel.add(rawLabel, gridBagConstraints); rawScrollPane.setPreferredSize(new java.awt.Dimension(10, 100)); rawScrollPane.setViewportView(rawTextPane); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 5, 5, 5); rawPanel.add(rawScrollPane, gridBagConstraints); getContentPane().setLayout(new java.awt.GridBagLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 4, 0); getContentPane().add(tabbedSourcePane, gridBagConstraints); buttonPanel.setLayout(new java.awt.GridBagLayout()); fillerPanel.setPreferredSize(new java.awt.Dimension(100, 10)); javax.swing.GroupLayout fillerPanelLayout = new javax.swing.GroupLayout(fillerPanel); fillerPanel.setLayout(fillerPanelLayout); fillerPanelLayout.setHorizontalGroup( fillerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 270, Short.MAX_VALUE) ); fillerPanelLayout.setVerticalGroup( fillerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 10, Short.MAX_VALUE) ); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; buttonPanel.add(fillerPanel, gridBagConstraints); extractButton.setText("Extract"); extractButton.setMargin(new java.awt.Insets(2, 2, 2, 2)); extractButton.setPreferredSize(new java.awt.Dimension(70, 23)); extractButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { extractButtonMouseReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3); buttonPanel.add(extractButton, gridBagConstraints); cancelButton.setText("Cancel"); cancelButton.setPreferredSize(new java.awt.Dimension(70, 23)); cancelButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { cancelButtonMouseReleased(evt); } }); buttonPanel.add(cancelButton, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 4); getContentPane().add(buttonPanel, gridBagConstraints); pack(); }// </editor-fold>//GEN-END:initComponents private void urlClearButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_urlClearButtonMouseReleased this.urlTextPane.setText(""); }//GEN-LAST:event_urlClearButtonMouseReleased private void fileClearButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_fileClearButtonMouseReleased this.fileTextPane.setText(""); }//GEN-LAST:event_fileClearButtonMouseReleased private void cancelButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cancelButtonMouseReleased wasAccepted = false; setVisible(false); }//GEN-LAST:event_cancelButtonMouseReleased private void extractButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_extractButtonMouseReleased wasAccepted = true; setVisible(false); }//GEN-LAST:event_extractButtonMouseReleased private void fileBrowseButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_fileBrowseButtonMouseReleased selectFiles(); }//GEN-LAST:event_fileBrowseButtonMouseReleased private void fileGetSLButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_fileGetSLButtonMouseReleased selectContextSLFiles(); }//GEN-LAST:event_fileGetSLButtonMouseReleased private void urlGetSLButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_urlGetSLButtonMouseReleased selectContextSLs(); }//GEN-LAST:event_urlGetSLButtonMouseReleased private void urlGetSIButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_urlGetSIButtonMouseReleased selectContextSIs(); }//GEN-LAST:event_urlGetSIButtonMouseReleased // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel buttonPanel; private javax.swing.JButton cancelButton; private javax.swing.JComboBox crawlerComboBox; private javax.swing.JLabel crawlerLabel; private javax.swing.JPanel crawlerPanel; private javax.swing.JButton extractButton; private javax.swing.JButton fileBrowseButton; private javax.swing.JPanel fileButtonPanel; private javax.swing.JButton fileClearButton; private javax.swing.JButton fileGetSLButton; private javax.swing.JLabel fileLabel; private javax.swing.JPanel filePanel; private javax.swing.JScrollPane fileScrollPane; private javax.swing.JTextPane fileTextPane; private javax.swing.JPanel fillerPanel; private javax.swing.JLabel rawLabel; private javax.swing.JPanel rawPanel; private javax.swing.JScrollPane rawScrollPane; private javax.swing.JTextPane rawTextPane; private javax.swing.JTabbedPane tabbedSourcePane; private javax.swing.JPanel urlButtonPanel; private javax.swing.JButton urlClearButton; private javax.swing.JButton urlGetSIButton; private javax.swing.JButton urlGetSLButton; private javax.swing.JLabel urlLabel; private javax.swing.JPanel urlPanel; private javax.swing.JScrollPane urlScrollPane; private javax.swing.JTextPane urlTextPane; // End of variables declaration//GEN-END:variables }
28,299
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
GenericDatabaseExtractorConfigurationDialog.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/GenericDatabaseExtractorConfigurationDialog.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * GenericDatabaseExtractorConfigurationDialog.java * * Created on 14. helmikuuta 2007, 11:23 */ package org.wandora.application.tools.extractors; import java.awt.GridBagConstraints; import java.util.Vector; import javax.swing.JPanel; import org.wandora.application.Wandora; import org.wandora.application.gui.simple.SimpleButton; import org.wandora.utils.swing.GuiTools; /** * * @author olli */ public class GenericDatabaseExtractorConfigurationDialog extends javax.swing.JDialog { private static final long serialVersionUID = 1L; private Wandora wandora; private boolean wasCancelled=true; private Vector<GenericDatabaseExtractorConfigurationPanel> panels; /** Creates new form GenericDatabaseExtractorConfigurationDialog */ public GenericDatabaseExtractorConfigurationDialog(Wandora wandora,boolean modal,GenericDatabaseExtractor.DatabaseSchema schema) { super(wandora, modal); this.wandora=wandora; initComponents(); this.setTitle("Configure extraction"); setTables(schema); GuiTools.centerWindow(this,wandora); } private void setTables(GenericDatabaseExtractor.DatabaseSchema schema){ panels=new Vector<GenericDatabaseExtractorConfigurationPanel>(); GridBagConstraints gbc=new GridBagConstraints(); gbc.gridx=0; gbc.gridy=0; gbc.fill=gbc.BOTH; gbc.weightx=1.0; gbc.weighty=0.0; for(String table : schema.tables){ GenericDatabaseExtractorConfigurationPanel panel=new GenericDatabaseExtractorConfigurationPanel(schema,table); tableContainer.add(panel,gbc); panels.add(panel); gbc.gridy++; } gbc.weighty=1.0; tableContainer.add(new JPanel(),gbc); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; jScrollPane1 = new javax.swing.JScrollPane(); tableContainer = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); cancelButton = new SimpleButton(); okButton = new SimpleButton(); getContentPane().setLayout(new java.awt.GridBagLayout()); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); tableContainer.setLayout(new java.awt.GridBagLayout()); jScrollPane1.setViewportView(tableContainer); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; getContentPane().add(jScrollPane1, gridBagConstraints); jPanel2.setLayout(new java.awt.GridBagLayout()); cancelButton.setText("Cancel"); cancelButton.setMaximumSize(new java.awt.Dimension(70, 23)); cancelButton.setMinimumSize(new java.awt.Dimension(70, 23)); cancelButton.setPreferredSize(new java.awt.Dimension(70, 23)); cancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel2.add(cancelButton, gridBagConstraints); okButton.setText("OK"); okButton.setMaximumSize(new java.awt.Dimension(70, 23)); okButton.setMinimumSize(new java.awt.Dimension(70, 23)); okButton.setPreferredSize(new java.awt.Dimension(70, 23)); okButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { okButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel2.add(okButton, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; getContentPane().add(jPanel2, gridBagConstraints); setBounds(0, 0, 521, 510); }// </editor-fold>//GEN-END:initComponents private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed this.wasCancelled=true; this.setVisible(false); }//GEN-LAST:event_cancelButtonActionPerformed private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed this.wasCancelled=false; this.setVisible(false); }//GEN-LAST:event_okButtonActionPerformed public boolean wasCancelled(){ return wasCancelled; } public void updateSchema(GenericDatabaseExtractor.DatabaseSchema schema){ for(GenericDatabaseExtractorConfigurationPanel panel : panels){ panel.updateSchema(schema); } } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton cancelButton; private javax.swing.JPanel jPanel2; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JButton okButton; private javax.swing.JPanel tableContainer; // End of variables declaration//GEN-END:variables }
6,663
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AbstractExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/AbstractExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * AbstractExtractor.java * * Created on November 10, 2004, 7:44 PM */ package org.wandora.application.tools.extractors; import java.io.File; import java.io.FileNotFoundException; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.Icon; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.WandoraToolType; import org.wandora.application.contexts.Context; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.texteditor.OccurrenceTextEditor; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.application.tools.DropExtractor; import org.wandora.application.tools.browserextractors.BrowserExtractRequest; import org.wandora.application.tools.browserextractors.BrowserPluginExtractor; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.XTMPSI; import org.wandora.utils.XMLbox; /** * @author akivela */ public abstract class AbstractExtractor extends AbstractWandoraTool implements WandoraTool, Runnable, DropExtractor, BrowserPluginExtractor { private static final long serialVersionUID = 1L; public final static String STRING_EXTRACTOR_NOT_SUPPORTED_MESSAGE = "String extractor not supported"; // Extractor types... public final static int CUSTOM_EXTRACTOR = 1; public final static int RAW_EXTRACTOR = 2; public final static int FILE_EXTRACTOR = 4; public final static int URL_EXTRACTOR = 8; // Crawler Modes (used by url extractor)... public final static int EXACTLY_GIVEN_URLS = 0; public final static int GIVEN_URLS_AND_LINKED_DOCUMENTS = 1; public final static int GIVEN_URLS_AND_URL_BELOW = 2; public final static int GIVEN_URLS_AND_CRAWLED_DOCUMENTS_IN_URL_DOMAIN = 3; public final static int GIVEN_URLS_AND_ALL_CRAWLED_DOCUMENTS = 4; public final static int SELECT_DIALOG_TITLE = 1000; public final static int POINT_START_URL_TEXT = 1010; public final static int INFO_WAIT_WHILE_WORKING = 1020; public final static int FILE_PATTERN = 9000; public final static int DONE_FAILED = 6000; public final static int DONE_ONE = 6010; public final static int DONE_MANY = 6020; public final static int LOG_TITLE = 6100; private Wandora wandora = null; private TopicMap topicMap; private String[] forceUrls = null; private File[] forceFiles = null; private Object forceContent = null; private int maximumCrawlCounter = 99999; private int extractionCounter = 0; private int foundCounter = 0; private int browseCounter = 0; private long errorNapTime = 500; private AbstractExtractorDialog extractorSourceDialog = null; private String masterSubject = null; /** Creates a new instance of AbstractExtractor */ public AbstractExtractor() { this.wandora = Wandora.getWandora(); if(wandora != null) this.topicMap = wandora.getTopicMap(); } @Override public WandoraToolType getType(){ return WandoraToolType.createExtractType(); } @Override public String getName(){ return "Abstract Extractor"; } @Override public String getDescription(){ return "AbstractExtractor is a base implementation for extractors."; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract.png"); } @Override public boolean runInOwnThread(){ return true; } public boolean useTempTopicMap(){ return false; } public boolean useURLCrawler() { return false; } // ------------------------------------------------------- DropExtractor --- public boolean instantDropHandle() { return false; } @Override public void dropExtract(File[] files) throws TopicMapException { if(instantDropHandle()) { this.wandora = Wandora.getWandora(); topicMap = wandora.getTopicMap(); handleFiles(files, topicMap); wandora.doRefresh(); } else { this.forceFiles = files; this.execute(Wandora.getWandora()); } } @Override public void dropExtract(String[] urls) throws TopicMapException { if(instantDropHandle()) { this.wandora = Wandora.getWandora(); topicMap = wandora.getTopicMap(); handleUrls(urls, topicMap); wandora.doRefresh(); } else { this.forceUrls = urls; this.execute(Wandora.getWandora()); } } @Override public void dropExtract(String content) throws TopicMapException { if(instantDropHandle()) { this.wandora = Wandora.getWandora(); topicMap = wandora.getTopicMap(); handleContent(content, topicMap); wandora.doRefresh(); } else { this.forceContent = content; this.execute(Wandora.getWandora()); } } // ------------------------------------------------------------------------- public String getGUIText(int textType, Object[] params) { String guiText = getGUIText(textType); for(int i=0; i<params.length; i++) { guiText = guiText.replace("%"+i, params[i].toString()); } return guiText; } public String getGUIText(int textType) { switch(textType) { case SELECT_DIALOG_TITLE: return "Select file(s) or directories!"; case POINT_START_URL_TEXT: return "Where would you like to start the crawl?"; case INFO_WAIT_WHILE_WORKING: return "Wait while seeking files with metadata!"; case FILE_PATTERN: return ".*"; case DONE_FAILED: return "Ready. No extractions!"; case DONE_ONE: return "Ready."; case DONE_MANY: return "Ready. Total %0 successful extractions!"; case LOG_TITLE: return "Extraction Log"; } System.out.println("Requesting Illegal extraction GUI text: " + textType); return ""; } public void setForceFiles(File[] ffiles) { this.forceFiles = ffiles; } public void setForceUrls(String[] furls) { this.forceUrls = furls; } public void setForceContent(Object fcontent) { this.forceContent = fcontent; } public File[] getForceFiles() { return this.forceFiles; } public String[] getForceUrls() { return this.forceUrls; } public Object getForceContent() { return this.forceContent; } public int getExtractorType() { return FILE_EXTRACTOR | URL_EXTRACTOR | RAW_EXTRACTOR; } public void initializeCustomType() { // TO BE OVERLOADED IN USER WRITTEN EXTRACTORS } public void handleCustomType() { // TO BE OVERLOADED IN USER WRITTEN EXTRACTORS } @Override public void execute(Wandora wandora, Context context) { setWandora(wandora); if(wandora != null) topicMap = wandora.getTopicMap(); Object contextSource = context.getContextSource(); if(contextSource instanceof OccurrenceTextEditor) { try { OccurrenceTextEditor occurrenceEditor = (OccurrenceTextEditor) contextSource; if(context.getContextObjects().hasNext()) { Topic masterTopic = (Topic) context.getContextObjects().next(); setMasterSubject(masterTopic); String str = occurrenceEditor.getSelectedText(); if(str == null || str.length() == 0) { str = occurrenceEditor.getText(); } _extractTopicsFrom(str, topicMap); } } catch(Exception e) { log(e); } } else { try { extractionCounter = 0; foundCounter = 0; browseCounter = 0; boolean handledForcedContent = handleForcedContent(); if(!handledForcedContent) { // --- ASK CONTENT FOR EXTRACTION --- int possibleTypes = getExtractorType(); extractorSourceDialog = new AbstractExtractorDialog(wandora, true); extractorSourceDialog.initialize(this); if((possibleTypes & FILE_EXTRACTOR) != 0) extractorSourceDialog.registerFileSource(); if((possibleTypes & URL_EXTRACTOR) != 0) extractorSourceDialog.registerUrlSource(); if((possibleTypes & RAW_EXTRACTOR) != 0) extractorSourceDialog.registerRawSource(); if((possibleTypes & CUSTOM_EXTRACTOR) != 0) initializeCustomType(); extractorSourceDialog.setVisible(true); if(!extractorSourceDialog.wasAccepted()) return; int selectedType = extractorSourceDialog.getSelectedSource(); setDefaultLogger(); log(getGUIText(INFO_WAIT_WHILE_WORKING)); // --- FILE TYPE --- if((selectedType & FILE_EXTRACTOR) != 0) { handleFiles( extractorSourceDialog.getFileSources(), topicMap ); } // --- URL TYPE --- if((selectedType & URL_EXTRACTOR) != 0) { handleUrls( extractorSourceDialog.getURLSources(), topicMap ); } // --- RAW TYPE --- if((selectedType & RAW_EXTRACTOR) != 0) { handleContent( extractorSourceDialog.getContent(), topicMap ); } // --- CUSTOM TYPE --- if((selectedType & CUSTOM_EXTRACTOR) != 0) { handleCustomType(); } lockLog(false); Object[] params = new Object[] { ""+extractionCounter, +foundCounter, ""+browseCounter }; if(extractionCounter == 0) { log(getGUIText(DONE_FAILED, params)); } else if(extractionCounter == 1) { log(getGUIText(DONE_ONE, params)); } else { log(getGUIText(DONE_MANY, params)); } setState(WAIT); } } catch(Exception e) { log(e); setState(WAIT); } } clearMasterSubject(); } public boolean handleForcedContent() { boolean handledForcedContent = false; if(forceUrls != null) { handleUrls(forceUrls, topicMap); handledForcedContent = true; forceUrls = null; } else if(forceFiles != null) { handleFiles(forceFiles, topicMap); handledForcedContent = true; forceFiles = null; } else if(forceContent != null){ handleContent(forceContent, topicMap); handledForcedContent = true; forceContent = null; } return handledForcedContent; } public void handleFiles(File[] files, TopicMap tm) { if(files == null || files.length == 0) return; for(int i=0; i<files.length && !forceStop(); i++) { if(files[i] != null) { // FILES if(files[i].isFile()) { try { extractTopicsFrom(files[i], tm); } catch(Exception e) { log(e); log("Extraction from '" + croppedFilename(files[i].getName()) + "' failed."); takeNap(errorNapTime); } } // DIRECTORIES if(files[i].isDirectory()) { try { String absName = files[i].getPath(); extractTopicsFrom(absName, Pattern.compile(getGUIText(FILE_PATTERN)), 30, 900000); } catch (Exception e) { log(e); takeNap(errorNapTime); } } } } } public void handleUrls(String[] urls, TopicMap tm) { if(urls == null || urls.length == 0) return; int counter = 0; for(int i=0; i<urls.length && !forceStop(); i++) { try { extractTopicsFrom(new URL(urls[i]), tm); counter++; } catch(FileNotFoundException fmfe) { log("File not found exception occurred while reading '"+urls[i]+"'."); } catch(Exception e) { log(e); } } if(counter > 1) { log("Total "+ counter + " URLs extracted."); } if(counter == 0) { log("No URLs extracted."); } else { //log("Ready."); } } public void handleContent(Object content, TopicMap tm) { if(content instanceof String) { handleStringContent((String) content, tm); } } public void handleStringContent(String stringContent, TopicMap tm) { if(stringContent != null){ try { extractTopicsFromText(stringContent, tm); } catch (Exception e) { log(e); } } } // ------------------------------------------------------------------------- public void setTopicMap(TopicMap tm) { this.topicMap = tm; } public int getCrawlerMode() { if(extractorSourceDialog != null) { return extractorSourceDialog.getCrawlerMode(EXACTLY_GIVEN_URLS); } else { return EXACTLY_GIVEN_URLS; } } protected void takeNap(long napTime) { try { Thread.sleep(napTime); } catch (Exception e) { } } // --------------------------------------------------------------------- // --- extractTopicsFrom ----------------------------------------------- // --------------------------------------------------------------------- public int extractTopicsFrom(String fileName, Pattern fileMask, int depth, int space) { return extractTopicsFrom(fileName, new ArrayList<String>(), fileMask, depth, space); } public int extractTopicsFrom(String fileName, Collection<String> visited, Pattern fileMask, int depth, int space) { browseCounter++; if(!forceStop()) { //System.out.println("depth: "+depth); if(depth >= 0) { if(space >= 0) { if(!visited.contains(fileName)) { visited.add(fileName); File file = new File(fileName); if (file.exists()) { try { if(fileMask == null) { extractTopicsFrom(file, topicMap); } else { Matcher m = fileMask.matcher(fileName); if(m.matches()) { extractTopicsFrom(file, topicMap); //log("matching file found: " + fileName); } } } catch (Exception e) { log("Extracting from '" + croppedFilename(file) + "' failed.", e); takeNap(errorNapTime); } if(file.isDirectory()) { try { //log("a dir found: " + fileName); String[] directoryFiles = file.list(); for(int i=0; i<directoryFiles.length; i++) { //log(" trying: " + File.separator + directoryFiles[i]); space = extractTopicsFrom(fileName + File.separator + directoryFiles[i], visited, fileMask, depth-1, space); } } catch (Exception e) { e.printStackTrace(); } } } } } else { log("Maximum number of files exceeded! Rejecting next files!"); } } else { log("Maximum browse depth exceeded!"); } } return --space; } public synchronized void extractTopicsFrom(URL url, TopicMap topicMap) throws Exception { foundCounter++; setProgress(foundCounter); if(url != null) { log("Extracting from " + croppedUrlString(url)); TopicMap tempMap=null; if(useTempTopicMap()) { tempMap=new org.wandora.topicmap.memory.TopicMapImpl(); } else { tempMap=topicMap; } if(_extractTopicsFrom(url, tempMap)) { if(useTempTopicMap()) { topicMap.mergeIn(tempMap); } extractionCounter++; } else { log("Found no valid metadata in " + croppedUrlString(url)); try { Thread.sleep(errorNapTime); } catch (Exception e) {} } } } public void extractTopicsFromText(String content, TopicMap topicMap) throws Exception { foundCounter++; setProgress(foundCounter); if(content != null) { // log("Extracting from given string."); TopicMap tempMap=null; if(useTempTopicMap()) { tempMap=new org.wandora.topicmap.memory.TopicMapImpl(); } else { tempMap=topicMap; } if(_extractTopicsFrom(content, tempMap)) { if(useTempTopicMap()) { topicMap.mergeIn(tempMap); } extractionCounter++; } else { log("Found no valid metadata in given string."); try { Thread.sleep(errorNapTime); } catch (Exception e) {} } } } public void extractTopicsFrom(File file, TopicMap topicMap) throws Exception { foundCounter++; setProgress(foundCounter); if(file != null) { log("Extracting from " + croppedFilename(file)); TopicMap tempMap=null; if(useTempTopicMap()) { tempMap=new org.wandora.topicmap.memory.TopicMapImpl(); } else { tempMap=topicMap; } if(_extractTopicsFrom(file, tempMap)) { if(useTempTopicMap()) { topicMap.mergeIn(tempMap); } extractionCounter++; } else { log("Found no valid metadata in " + croppedFilename(file)); try { Thread.sleep(errorNapTime); } catch (Exception e) {} } } } public Locator buildSL(File file) { return new Locator(file.toURI().toString()); // String path = file.getAbsolutePath(); // path = path.replaceAll("\\\\", "\\/"); // return new Locator("file://" + path); } // ========================================================================= // ================ SUBCLASS SHOULD OVERWRITE THESE METHODS! =============== // ========================================================================= public abstract boolean _extractTopicsFrom(File f, TopicMap t) throws Exception; public abstract boolean _extractTopicsFrom(URL u, TopicMap t) throws Exception; public abstract boolean _extractTopicsFrom(String str, TopicMap t) throws Exception; // ------------------------------------------------------------------------- // -------------------------------------------------------- TOPIC METHODS--- // ------------------------------------------------------------------------- protected static String urlEncode(String str) { try { str = URLEncoder.encode(str, "utf-8"); } catch(Exception e) {} return str; } public Locator buildSI(String siend) { if(siend == null) siend = "" + System.currentTimeMillis() + Math.random()*999999; if(siend.startsWith("http:")) return new Locator(siend); if(siend.startsWith("file:")) return new Locator(siend); if(siend.startsWith("https:")) return new Locator(siend); if(siend.startsWith("ftp:")) return new Locator(siend); if(siend.startsWith("ftps:")) return new Locator(siend); if(siend.startsWith("mailto:")) return new Locator(siend); if(siend.startsWith("/")) siend = siend.substring(1); return new Locator("http://wandora.org/si/default/" + urlEncode(siend)); } public Topic createTopic(TopicMap topicMap, String baseString) throws TopicMapException { return createTopic(topicMap, baseString, "", baseString, new Topic[] { }); } public Topic createTopic(TopicMap topicMap, String siString, String baseString) throws TopicMapException { return createTopic(topicMap, siString, "", baseString, new Topic[] { }); } public Topic createTopic(TopicMap topicMap, String siString, String baseString, Topic type) throws TopicMapException { return createTopic(topicMap, siString, "", baseString, new Topic[] { type }); } public Topic createTopic(TopicMap topicMap, String baseString, Topic type) throws TopicMapException { return createTopic(topicMap, baseString, "", baseString, new Topic[] { type }); } public Topic createTopic(TopicMap topicMap, String siString, String baseNameString, String baseString) throws TopicMapException { return createTopic(topicMap, siString, baseNameString, baseString, new Topic[] { }); } public Topic createTopic(TopicMap topicMap, String siString, String baseNameString, String baseString, Topic type) throws TopicMapException { return createTopic(topicMap, siString, baseNameString, baseString, new Topic[] { type }); } public Topic createTopic(TopicMap topicMap, String siString, String baseNameString, String baseString, Topic[] types) throws TopicMapException { if(baseString != null && baseString.length() > 0) { Locator si = buildSI(siString); Topic t = topicMap.getTopic(si); if(t == null) { t = topicMap.getTopicWithBaseName(baseString + baseNameString); if(t == null) { t = topicMap.createTopic(); t.setBaseName(baseString + baseNameString); } t.addSubjectIdentifier(si); } //setDisplayName(t, "fi", baseString); setDisplayName(t, "en", baseString); for(int i=0; i<types.length; i++) { Topic typeTopic = types[i]; if(typeTopic != null) { if(!t.isOfType(typeTopic)) { t.addType(typeTopic); } } } return t; } System.out.println("Failed to create topic!"); return null; } public Association createAssociation(TopicMap topicMap, Topic aType, Topic[] players) throws TopicMapException { Association a = topicMap.createAssociation(aType); Topic player; Topic role; Collection<Topic> playerTypes; for(int i=0; i<players.length; i++) { player = players[i]; if(player != null && !player.isRemoved()) { playerTypes = player.getTypes(); if(playerTypes.size() > 0) { role = (Topic) playerTypes.iterator().next(); if(role != null && !role.isRemoved()) { a.addPlayer(player, role); } } } } return a; } public Association createAssociation(TopicMap topicMap, Topic aType, Topic[] players, Topic[] roles) throws TopicMapException { Association a = null; if(aType != null) { a = topicMap.createAssociation(aType); Topic player; Topic role; for(int i=0; i<players.length; i++) { player = players[i]; role = roles[i]; if(player != null && role != null && !player.isRemoved() && !role.isRemoved()) { a.addPlayer(player, role); } } } return a; } public void setDisplayName(Topic t, String lang, String name) throws TopicMapException { if(t != null & lang != null && name != null) { String langsi=XTMPSI.getLang(lang); Topic langT=t.getTopicMap().getTopic(langsi); if(langT == null) { langT = t.getTopicMap().createTopic(); langT.addSubjectIdentifier(new Locator(langsi)); try { langT.setBaseName("Language " + lang.toUpperCase()); } catch (Exception e) { langT.setBaseName("Language " + langsi); } } String dispsi=XTMPSI.DISPLAY; Topic dispT=t.getTopicMap().getTopic(dispsi); if(dispT == null) { dispT = t.getTopicMap().createTopic(); dispT.addSubjectIdentifier(new Locator(dispsi)); dispT.setBaseName("Scope Display"); } HashSet<Topic> scope=new LinkedHashSet<>(); if(langT!=null) scope.add(langT); if(dispT!=null) scope.add(dispT); t.setVariant(scope, name); } } public void setData(Topic t, Topic type, String lang, String text) throws TopicMapException { if(t != null & type != null && lang != null && text != null) { String langsi=XTMPSI.getLang(lang); Topic langT=t.getTopicMap().getTopic(langsi); if(langT == null) { langT = t.getTopicMap().createTopic(); langT.addSubjectIdentifier(new Locator(langsi)); try { langT.setBaseName("Language " + lang.toUpperCase()); } catch (Exception e) { langT.setBaseName("Language " + langsi); } } t.setData(type, langT, text); } } public void makeSubclassOfWandoraClass(Topic t, TopicMap tm) throws TopicMapException { if(tm != null && t != null) { Topic wandoraClass = tm.getTopic(TMBox.WANDORACLASS_SI); Topic superclassSubclass = tm.getTopic(XTMPSI.SUPERCLASS_SUBCLASS); Topic superclass = tm.getTopic(XTMPSI.SUPERCLASS); Topic subclass = tm.getTopic(XTMPSI.SUBCLASS); if(wandoraClass != null && superclassSubclass != null && superclass != null && subclass != null) { Association a = tm.createAssociation(superclassSubclass); a.addPlayer(t, subclass); a.addPlayer(wandoraClass, superclass); } } } // ------------------------------------------------------------------------- protected String croppedFilename(String filename) { if(filename != null) { if(filename.length() > 70) { filename = filename.substring(0,45) + "..." + filename.substring(filename.length()-22); } return filename; } return ""; } protected String croppedFilename(File file) { if(file != null) { return croppedFilename(file.getPath()); } return ""; } protected String croppedUrlString(URL url) { return croppedUrlString(url.toExternalForm()); } protected String croppedUrlString(String urlString) { return (urlString.length() > 70 ? urlString.substring(0,45) + "..." + urlString.substring(urlString.length()-22): urlString); } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- public String[] getContentTypes() { return new String [] { "*/*" }; } // ---------------------------------------------------- PLUGIN EXTRACTOR --- @Override public String doBrowserExtract(BrowserExtractRequest request, Wandora wandora) throws TopicMapException { try { setWandora(wandora); String content = ExtractHelper.getContent(request); if(content != null) { if(browserExtractorConsumesPlainText()) { String tidyContent = XMLbox.cleanUp( content ); if(tidyContent != null && tidyContent.length() > 0) { content = XMLbox.getAsText(tidyContent, "ISO-8859-1"); } } System.out.println("--- browser plugin processing content ---"); System.out.println(content); _extractTopicsFrom(content, wandora.getTopicMap()); wandora.doRefresh(); return null; } else { return BrowserPluginExtractor.RETURN_ERROR+"Couldn't solve browser extractor content. Nothing extracted."; } } catch(Exception e){ e.printStackTrace(); return BrowserPluginExtractor.RETURN_ERROR+e.getMessage(); } } @Override public boolean acceptBrowserExtractRequest(BrowserExtractRequest request, Wandora wandora) throws TopicMapException { return true; } @Override public String getBrowserExtractorName() { return getName(); } public boolean browserExtractorConsumesPlainText() { return false; } // ------------------------------------------------------------------------- public String getMasterSubject() { return masterSubject; } public void setMasterSubject(Topic t) { try { masterSubject = t.getOneSubjectIdentifier().toExternalForm(); } catch(Exception e) { masterSubject = null; } } public void setMasterSubject(String subject) { masterSubject = subject; } public void clearMasterSubject() { masterSubject = null; } // ------------------------------------------------------------------------- public void setWandora(Wandora app) { wandora = app; } public Wandora getWandora() { if(wandora != null) return wandora; else return Wandora.getWandora(); } }
33,747
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
GenericDatabaseExtractorConfigurationPanel.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/GenericDatabaseExtractorConfigurationPanel.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * GenericDatabaseExtractorConfigurationPanel.java * * Created on 14. helmikuuta 2007, 11:03 */ package org.wandora.application.tools.extractors; import java.awt.GridBagConstraints; import java.util.ArrayList; import java.util.HashMap; import javax.swing.DefaultCellEditor; import javax.swing.JComboBox; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import javax.swing.table.DefaultTableModel; import javax.swing.table.JTableHeader; import javax.swing.table.TableColumnModel; import org.wandora.application.gui.simple.SimpleLabel; /** * * @author olli */ public class GenericDatabaseExtractorConfigurationPanel extends javax.swing.JPanel implements TableModelListener { private static final long serialVersionUID = 1L; // private GenericDatabaseExtractor.DatabaseSchema schema; private String table; private JTableHeader jTableHeader; private boolean ignoreChanges=false; /** Creates new form GenericDatabaseExtractorConfigurationPanel */ public GenericDatabaseExtractorConfigurationPanel(GenericDatabaseExtractor.DatabaseSchema schema,String table) { this.table=table; initComponents(); jTableHeader=new JTableHeader(jTable.getColumnModel()); jTable.setTableHeader(jTableHeader); GridBagConstraints gbc=new GridBagConstraints(); gbc.gridx=0; gbc.gridy=1; gbc.fill=gbc.HORIZONTAL; gbc.anchor=gbc.SOUTH; gbc.insets=new java.awt.Insets(5,5,0,5); this.add(jTableHeader,gbc); tableLabel.setText(table); JComboBox refCombo=new JComboBox(); refCombo.addItem("<None>"); for(ArrayList<GenericDatabaseExtractor.DBColumn> cs : schema.columns.values()){ for(GenericDatabaseExtractor.DBColumn c : cs){ refCombo.addItem(c); } } DefaultTableModel model=(DefaultTableModel)jTable.getModel(); for(GenericDatabaseExtractor.DBColumn column : schema.columns.get(table)){ model.addRow(new Object[]{column.column, // column.references==null?"":"-> "+column.references.table+"."+column.references.column, column.references==null?"<None>":column.references, true, column.baseName, column.makeTopics}); } TableColumnModel cmodel=jTable.getColumnModel(); cmodel.getColumn(1).setCellEditor(new DefaultCellEditor(refCombo)); model.addTableModelListener(this); } public void updateSchema(GenericDatabaseExtractor.DatabaseSchema schema){ ArrayList<GenericDatabaseExtractor.DBColumn> columns=schema.columns.get(table); HashMap<String,GenericDatabaseExtractor.DBColumn> columnHash=new HashMap<String,GenericDatabaseExtractor.DBColumn>(); for(GenericDatabaseExtractor.DBColumn column : columns){ columnHash.put(column.column,column); } DefaultTableModel model=(DefaultTableModel)jTable.getModel(); for(int i=0;i<model.getRowCount();i++){ String columnName=(String)model.getValueAt(i,0); GenericDatabaseExtractor.DBColumn column=columnHash.get(columnName); if(column==null) continue; Object refObject=model.getValueAt(i,1); boolean include=(Boolean)model.getValueAt(i,2); boolean baseName=(Boolean)model.getValueAt(i,3); boolean makeTopics=(Boolean)model.getValueAt(i,4); if(refObject==null || !(refObject instanceof GenericDatabaseExtractor.DBColumn)) column.references=null; else column.references=(GenericDatabaseExtractor.DBColumn)refObject; column.include=include; column.baseName=baseName; column.makeTopics=makeTopics; } } public void tableChanged(TableModelEvent e) { if(e.getColumn()==3){ if(ignoreChanges) return; DefaultTableModel model=(DefaultTableModel)jTable.getModel(); synchronized(this){ for(int i=e.getFirstRow();i<=e.getLastRow();i++){ if((Boolean)model.getValueAt(i,3)){ ignoreChanges=true; for(int j=0;j<model.getRowCount();j++){ if(j==i) continue; model.setValueAt((Boolean)false,j,3); } ignoreChanges=false; break; } } } } } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; jScrollPane1 = new javax.swing.JScrollPane(); tableLabel = new SimpleLabel(); jTable = new javax.swing.JTable(); setLayout(new java.awt.GridBagLayout()); tableLabel.setText("Table name"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); add(tableLabel, gridBagConstraints); jTable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Column", "Foreign key", "Include column", "Basename", "Make topics" } ) { Class[] types = new Class [] { java.lang.String.class, java.lang.String.class, java.lang.Boolean.class, java.lang.Boolean.class, java.lang.Boolean.class }; boolean[] canEdit = new boolean [] { false, true, true, true, true }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 5, 15, 5); add(jTable, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTable; private javax.swing.JLabel tableLabel; // End of variables declaration//GEN-END:variables }
8,080
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
GenericDatabaseExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/GenericDatabaseExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * DatabaseImport.java * * Created on 30.6.2006, 14:14 * */ package org.wandora.application.tools.extractors; import static org.wandora.utils.Tuples.t2; import java.io.PrintStream; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import javax.swing.Icon; import org.wandora.application.Wandora; import org.wandora.application.WandoraToolType; import org.wandora.application.contexts.Context; import org.wandora.application.gui.DatabaseConfigurationDialog; import org.wandora.application.gui.DatabaseConfigurationPanel; import org.wandora.application.gui.UIBox; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.Association; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.XTMPSI; import org.wandora.topicmap.database2.DatabaseTopicMap; import org.wandora.topicmap.layered.LayerStack; import org.wandora.utils.Tuples.T2; /** * * TODO: * - Test that extending tables works properly, extend chains, no unnecessary associations * from extending columns. * - Test that all different kinds of tables work properly, different values of * hasReferences and hasNonReferences (test this with extending another table and not). * - Test that not including columns works properly. * * @author olli */ public class GenericDatabaseExtractor extends AbstractWandoraTool { private static final long serialVersionUID = 1L; /** Creates a new instance of GenericDatabaseExtractor */ public GenericDatabaseExtractor() { } @Override public String getName() { return "Database Extractor"; } @Override public String getDescription() { return "Extracts and converts data from database to topic map."; } @Override public WandoraToolType getType(){ return WandoraToolType.createExtractType(); } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_database.png"); } public void execute(Wandora wandora, Context context) throws TopicMapException { setDefaultLogger(); DatabaseConfigurationDialog d=new DatabaseConfigurationDialog(wandora,true); d.setTitle("Select extracted database"); d.setVisible(true); if(d.wasCancelled()) return; DatabaseConfigurationPanel.StoredConnection sc=d.getSelection(); if(sc==null) return; T2<String,String> params=DatabaseConfigurationPanel.getConnectionDriverAndString(sc); Connection con=null; try{ log("Connecting to database"); Class.forName(params.e1); con=DriverManager.getConnection(params.e2,sc.user,sc.pass); DatabaseMetaData metadata=con.getMetaData(); DatabaseSchema schema=getDatabaseSchema(metadata,null,sc.user); setDefaultBaseNameColumns(schema); System.out.println("Found tables:"); schema.print(System.out); if(!configureSchema(wandora,schema)){ return; } TopicMap tm=wandora.getTopicMap(); if(tm instanceof LayerStack){ tm=((LayerStack)tm).getSelectedLayer().getTopicMap(); } boolean resetIndexes=false; if(tm instanceof DatabaseTopicMap){ ((DatabaseTopicMap)tm).setCompleteIndex(); resetIndexes=true; } boolean oldConsistencyCheck=tm.getConsistencyCheck(); tm.setConsistencyCheck(false); tm.disableAllListeners(); try{ makeTopicMap(tm,con,schema); if(resetIndexes) ((DatabaseTopicMap)tm).resetCompleteIndex(); } finally{ tm.enableAllListeners(); tm.setConsistencyCheck(oldConsistencyCheck); } } catch(Exception e){ log(e); throw new TopicMapException(e); } finally{ try{ if(con!=null) con.close(); }catch(SQLException sqle){sqle.printStackTrace();} } } private boolean configureSchema(Wandora admin,DatabaseSchema schema){ GenericDatabaseExtractorConfigurationDialog d=new GenericDatabaseExtractorConfigurationDialog(admin,true,schema); d.setVisible(true); if(d.wasCancelled()) return false; d.updateSchema(schema); return true; } public static void printResultSet(ResultSet rs) throws SQLException { ResultSetMetaData rsmd=rs.getMetaData(); while(rs.next()){ for(int i=0;i<rsmd.getColumnCount();i++){ System.out.println(rsmd.getColumnLabel(i+1)+": "+rs.getObject(i+1)); } System.out.println("--------------------------"); } } public static String makeIdentifier(String[] row, DBColumn[] columns, String table) throws SQLException { String identifier=""; for(int i=0;i<row.length;i++){ DBColumn column=columns[i]; if(!column.primaryKey) continue; if(identifier.length()>0) identifier+="--"; identifier+=row[i]; } return identifier; } public static Topic getOrCreateTopic(TopicMap tm,String s) throws TopicMapException { Topic t=tm.getTopic(s); if(t==null){ t=tm.createTopic(); t.addSubjectIdentifier(tm.createLocator(s)); } return t; } public HashMap<String,Topic> topicCache; public Topic getOrCreateCached(TopicMap tm,String s) throws TopicMapException { Topic t=topicCache.get(s); if(t==null) { t=getOrCreateTopic(tm,s); topicCache.put(s,t); } return t; } public static DBColumn findColumn(Collection<DBColumn> columns,String name){ for(DBColumn column : columns){ if(column.column.equals(name)) return column; } return null; } public static String cropBaseName(String value, String postfix){ if(postfix==null){ if(value.length()>255) return value.substring(0,255); else return value; } if(value.length()+postfix.length()+3>255){ return value.substring(0,255-3-postfix.length())+" ("+postfix+")"; } else return value+" ("+postfix+")"; } public void makeTopicMap(TopicMap tm,Connection con,DatabaseSchema schema) throws SQLException,TopicMapException { log("Extracting database"); topicCache=new HashMap<String,Topic>(); // Set base names to data types, roles association types etc for(String table : schema.tables){ ArrayList<DBColumn> columns=schema.columns.get(table); boolean hasNonReferences=false; boolean hasReferences=false; boolean includedColumns=false; for(DBColumn column : columns){ if(!column.include) continue; includedColumns=true; if(column.references!=null) hasReferences=true; else hasNonReferences=true; } if(!includedColumns) continue; if(hasNonReferences){ Topic type=getOrCreateTopic(tm,"http://wandora.org/si/dbimport/type/"+table); type.setBaseName(table+" (type)"); for(DBColumn column : columns){ if(!column.include) continue; if(column.references!=null) continue; if(column.makeTopics){ Topic atype=getOrCreateTopic(tm,"http://wandora.org/si/dbimport/type/"+table+"/"+column.column); atype.setBaseName(table+"/"+column.column+" (association type)"); Topic otherRole=getOrCreateTopic(tm,"http://wandora.org/si/dbimport/role/"+table+"/"+column.column); otherRole.setBaseName(table+"/"+column.column+" (role)"); Topic thisRole=getOrCreateTopic(tm,"http://wandora.org/si/dbimport/role/"+table); thisRole.setBaseName(table+" (role)"); } else{ Topic dataType=getOrCreateTopic(tm,"http://wandora.org/si/dbimport/datatype/"+table+"/"+column.column); dataType.setBaseName(column.column+" (data type)"); } } } if(hasReferences && !hasNonReferences){ Topic associationType=getOrCreateTopic(tm,"http://wandora.org/si/dbimport/association/"+table); associationType.setBaseName(table+" (association type)"); for(DBColumn column : columns){ if(!column.include) continue; Topic role=getOrCreateTopic(tm,"http://wandora.org/si/dbimport/role/"+table+"/"+column.column); role.setBaseName(table+"/"+column.column+" (role)"); } } else if(hasReferences) { Topic thisRole=getOrCreateTopic(tm,"http://wandora.org/si/dbimport/role/"+table); thisRole.setBaseName(table+" (role)"); for(DBColumn column : columns){ if(!column.include) continue; if(column.references==null) continue; Topic type=getOrCreateTopic(tm,"http://wandora.org/si/dbimport/type/"+table+"/"+column.column); type.setBaseName(table+"/"+column.column+" (association type)"); Topic otherRole=getOrCreateTopic(tm,"http://wandora.org/si/dbimport/role/"+column.references.table+"/"+column.references.column); otherRole.setBaseName(column.references.table+"/"+column.references.column+" (role)"); } } } // resolve which table extends what HashMap<String,String> extendsTableMap=new HashMap<String,String>(); for(String table : schema.tables){ ArrayList<DBColumn> columnsOriginal=schema.columns.get(table); String extendsTable=null; for(DBColumn column : columnsOriginal){ if(!column.include) continue; if(column.primaryKey && (extendsTable!=null || column.references==null)){ extendsTable=null; break; } if(column.references!=null && column.primaryKey){ extendsTable=column.references.table; } } if(extendsTable!=null) extendsTableMap.put(table,extendsTable); } // straighten links when tables extend tables that extend other tables for(String table : schema.tables){ String extendsTable=extendsTableMap.get(table); if(extendsTable!=null){ while(extendsTableMap.get(extendsTable)!=null) extendsTable=extendsTableMap.get(extendsTable); extendsTableMap.put(table,extendsTable); } } // process data, one table at a time for(String table : schema.tables) { // check if no column of this table is included, in that case skip table completely boolean hasColumns=false; ArrayList<DBColumn> columnsOriginal=schema.columns.get(table); for(DBColumn column : columnsOriginal){ if(!column.include) continue; hasColumns=true; break; } if(!hasColumns){ log("No columns for table "+table+". Skipping."); continue; } // get table data Statement stmt=con.createStatement(); ResultSet rs=stmt.executeQuery("select * from "+table); try{ ResultSetMetaData metaData=rs.getMetaData(); int numColumns=metaData.getColumnCount(); // Note columns need to be read in the order they are in result set DBColumn[] columns=new DBColumn[numColumns]; for(int i=0;i<numColumns;i++){ columns[i]=findColumn(columnsOriginal,metaData.getColumnName(i+1)); } String extendsTable=extendsTableMap.get(table); boolean hasNonReferences=false; boolean hasReferences=false; for(DBColumn column : columns){ if(!column.include) continue; if(extendsTable!=null && column.references!=null && column.primaryKey) continue; if(column.references!=null) hasReferences=true; else hasNonReferences=true; } int counter=0; log("Processing table "+table); String[] row=new String[numColumns]; while(rs.next()){ counter++; if((counter%10)==0){ if(forceStop()) { log("Extract aborted"); return; } } if((counter%10000)==0) log("Processing table "+table+" row "+counter); for(int i=0;i<numColumns;i++){ row[i]=rs.getString(i+1); } String ids=makeIdentifier(row,columns,table); String identifier="http://wandora.org/si/dbimport/"+table+"/"+ids; if(extendsTable!=null) identifier="http://wandora.org/si/dbimport/"+extendsTable+"/"+ids; if(identifier.length()>255) System.out.println("WARNING! Locator over 255 characters"); if(hasNonReferences){ Topic t=getOrCreateTopic(tm,identifier); Topic type=getOrCreateCached(tm,"http://wandora.org/si/dbimport/type/"+table); t.addType(type); for(int i=0;i<numColumns;i++){ DBColumn column=columns[i]; if(!column.include) continue; String value=row[i]; if(column.references!=null) continue; if(column.baseName && value!=null) t.setBaseName(cropBaseName(value,ids)); if(column.makeTopics && value!=null){ Topic atype=getOrCreateCached(tm,"http://wandora.org/si/dbimport/type/"+table+"/"+column.column); Topic otherRole=getOrCreateCached(tm,"http://wandora.org/si/dbimport/role/"+table+"/"+column.column); Topic thisRole=getOrCreateCached(tm,"http://wandora.org/si/dbimport/role/"+table); Topic other=getOrCreateTopic(tm,"http://wandora.org/si/dbimport/"+table+"/"+column.column+"/"+value); other.addType(atype); other.setBaseName(cropBaseName(value,column.column)); Association a=tm.createAssociation(atype); a.addPlayer(t,thisRole); a.addPlayer(other,otherRole); } else if(value!=null) { Topic dataType=getOrCreateCached(tm,"http://wandora.org/si/dbimport/datatype/"+table+"/"+column.column); Topic version=getOrCreateCached(tm,XTMPSI.getLang(null)); t.setData(dataType,version,value); } } } if(hasReferences && !hasNonReferences){ Topic associationType=getOrCreateCached(tm,"http://wandora.org/si/dbimport/association/"+table); Association a=tm.createAssociation(associationType); for(int i=0;i<numColumns;i++){ DBColumn column=columns[i]; if(!column.include) continue; if(extendsTable!=null && column.primaryKey) continue; String value=row[i]; if(value==null) continue; Topic other=getOrCreateTopic(tm,"http://wandora.org/si/dbimport/"+column.references.table+"/"+value); Topic role=getOrCreateCached(tm,"http://wandora.org/si/dbimport/role/"+table+"/"+column.column); a.addPlayer(other,role); } } else if(hasReferences) { Topic t=getOrCreateTopic(tm,identifier); Topic thisRole=getOrCreateTopic(tm,"http://wandora.org/si/dbimport/role/"+table); for(int i=0;i<numColumns;i++){ DBColumn column=columns[i]; if(!column.include) continue; if(column.references==null) continue; if(extendsTable!=null && column.primaryKey) continue; String value=row[i]; if(value==null) continue; Topic other=getOrCreateTopic(tm,"http://wandora.org/si/dbimport/"+column.references.table+"/"+value); Topic type=getOrCreateCached(tm,"http://wandora.org/si/dbimport/type/"+table+"/"+column.column); Topic otherRole=getOrCreateCached(tm,"http://wandora.org/si/dbimport/role/"+column.references.table); Association a=tm.createAssociation(type); a.addPlayer(t,thisRole); a.addPlayer(other,otherRole); } } } } finally{ rs.close(); stmt.close(); } } topicCache=new HashMap<String,Topic>(); log("Ready."); } public static DBColumn getOrCreateColumn(HashMap<T2<String,String>,DBColumn> columns,String table,String column){ DBColumn c=columns.get(t2(table,column)); if(c==null){ c=new DBColumn(table,column); columns.put(t2(table,column),c); } return c; } /** * Sets the baseName attribute to true in one column of each table. Tries * to guess a column that would make the most sense as a base name, however * currently the heuristic for this is very simple. */ public static void setDefaultBaseNameColumns(DatabaseSchema schema){ for(String table : schema.tables){ ArrayList<DBColumn> columns=schema.columns.get(table); boolean set=false; for(DBColumn column : columns){ if(!column.primaryKey && column.references==null){ set=true; column.baseName=true; break; } } if(!set){ for(DBColumn column : columns){ if(column.primaryKey){ column.baseName=true; break; } } } } } /** * <p> * Gets a database schema based on DatabaseMetaData. Catalog and schema parameters are descibed * in java.sql.DatabaseMetaData.getCrossReference. Practically, catalog is usually null and * schema is the database user name. Thus you will usually do something like this: * </p> * <p><pre> * Connection con=DriverManager.getConnection(conString,user,pass); * DatabaseMetaData metadata=con.getMetaData(); * DatabaseSchema schema=getDatabaseSchema(metadata,null,user); * </pre></p> */ public static DatabaseSchema getDatabaseSchema(DatabaseMetaData metadata,String catalog,String schema) throws SQLException { DatabaseSchema ret=new DatabaseSchema(); HashMap<T2<String,String>,DBColumn> allColumns=new HashMap<T2<String,String>,DBColumn>(); ArrayList<String> tables=new ArrayList<String>(); HashMap<String,ArrayList<DBColumn>> columns=new HashMap<String,ArrayList<DBColumn>>(); ResultSet rs=metadata.getTables(catalog,schema,null,null); while(rs.next()){ String name=rs.getString(3); tables.add(name); } rs.close(); for(int i=0;i<tables.size();i++){ String primaryTable=tables.get(i); for(int j=0;j<tables.size();j++){ String foreignTable=tables.get(j); rs=metadata.getCrossReference(catalog,schema,primaryTable,catalog,schema,foreignTable); while(rs.next()){ DBColumn f=getOrCreateColumn(allColumns,rs.getString(7),rs.getString(8)); DBColumn p=getOrCreateColumn(allColumns,rs.getString(3),rs.getString(4)); f.references=p; } rs.close(); } rs=metadata.getColumns(catalog,schema,primaryTable,null); ArrayList<DBColumn> c=new ArrayList<DBColumn>(); while(rs.next()){ c.add(getOrCreateColumn(allColumns,primaryTable,rs.getString(4))); } rs.close(); rs=metadata.getPrimaryKeys(catalog,schema,primaryTable); while(rs.next()){ DBColumn col=getOrCreateColumn(allColumns,primaryTable,rs.getString(4)); col.primaryKey=true; } rs.close(); columns.put(primaryTable,c); } ret.tables=tables; ret.columns=columns; return ret; } /** * Data structure containing information about database schema. Will have * information about all tables in the database and all columns in all * tables. */ public static class DatabaseSchema { /** * A list of all tables in the database. */ public ArrayList<String> tables; /** * A map containing lists of all the columns in all tables. */ public HashMap<String,ArrayList<DBColumn>> columns; public DatabaseSchema(){ tables=new ArrayList<String>(); columns=new HashMap<String,ArrayList<DBColumn>>(); } public void print(PrintStream out){ for(String table : tables){ out.println("------------- "+table+" -------------"); for(DBColumn column : columns.get(table)){ String key=""; if(column.primaryKey) key=" (primary key)"; if(column.references!=null) out.println(column+" => "+column.references+key); else out.println(column+key); } } } } /** * Datastructure containing information about a single column in a database schema. */ public static class DBColumn { /** Table where this column is. */ public String table; /** Column name. */ public String column; public boolean include; /** Is this column a primary key. */ public boolean primaryKey; /** The column that this column references or null if it does not reference any column. */ public DBColumn references; /** Should Wandora use this column for base names. */ public boolean baseName; /** Should Wandora make topics from this column. */ public boolean makeTopics; public DBColumn(String table,String column){ this.table=table; this.column=column; this.include=true; this.baseName=false; this.makeTopics=false; } @Override public String toString(){ return table+"."+column; } } }
25,474
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
RSSExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/RSSExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * RSSExtractor.java * * Created on 3. marraskuuta 2007, 13:18 * */ package org.wandora.application.tools.extractors; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.Icon; import org.wandora.application.Wandora; import org.wandora.application.gui.UIBox; import org.wandora.application.tools.browserextractors.BrowserExtractRequest; import org.wandora.application.tools.browserextractors.BrowserPluginExtractor; import org.wandora.topicmap.Association; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicTools; import org.wandora.topicmap.XTMPSI; import org.wandora.utils.IObox; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; /** * * @author akivela */ public class RSSExtractor extends AbstractExtractor { private static final long serialVersionUID = 1L; /** Creates a new instance of RSSExtractor */ public RSSExtractor() { } @Override public boolean useURLCrawler() { return false; } @Override public String getName() { return "RSS 2.0 Extractor"; } @Override public String getDescription(){ return "Extractor reads RSS 2.0 feed and converts the feed to a topic map."; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_rss.png"); } private final String[] contentTypes=new String[] { "text/xml", "application/xml", "application/rss+xml", "application/xhtml+xml" }; @Override public String[] getContentTypes() { return contentTypes; } @Override public String doBrowserExtract(BrowserExtractRequest request, Wandora wandora) throws TopicMapException { try { setWandora(wandora); String urlstr = request.getSource(); //System.out.println("FOUND URL: "+urlstr); URL url = new URL(urlstr); URLConnection uc = url.openConnection(); String type = uc.getContentType(); //System.out.println("FOUND TYPE: "+type); if(type != null && type.indexOf("text/html") > -1) { String htmlContent = IObox.doUrl(url); Pattern p1 = Pattern.compile("\\<link [^\\>]+\\>"); Pattern p2 = Pattern.compile("href\\=\"([^\"]+)\""); Matcher m1 = p1.matcher(htmlContent); int sp = 0; while(m1.find(sp)) { String linktag = m1.group(); if(linktag != null && linktag.length() > 0) { if(linktag.indexOf("application/rss+xml") > -1 || linktag.indexOf("application/xml") > -1) { Matcher m2 = p2.matcher(linktag); if(m2.find()) { try { String rssfeed = m2.group(1); _extractTopicsFrom(new URL(rssfeed), wandora.getTopicMap()); } catch(Exception e) { e.printStackTrace(); } } } } sp = m1.end(); } wandora.doRefresh(); return null; } else if(type != null && type.indexOf("application/rss+xml") > -1) { _extractTopicsFrom(url, wandora.getTopicMap()); wandora.doRefresh(); return null; } else if(type != null && type.indexOf("text/xml") > -1) { _extractTopicsFrom(url, wandora.getTopicMap()); wandora.doRefresh(); return null; } else { return BrowserPluginExtractor.RETURN_ERROR + "Couldn't solve browser extractor content. Nothing extracted."; } } catch(Exception e){ e.printStackTrace(); return BrowserPluginExtractor.RETURN_ERROR+e.getMessage(); } } @Override public boolean _extractTopicsFrom(URL url, TopicMap topicMap) throws Exception { URLConnection uc=url.openConnection(); Wandora.initUrlConnection(uc); return _extractTopicsFrom(uc.getInputStream(),topicMap); } @Override public boolean _extractTopicsFrom(File file, TopicMap topicMap) throws Exception { return _extractTopicsFrom(new FileInputStream(file),topicMap); } @Override public boolean _extractTopicsFrom(String str, TopicMap topicMap) throws Exception { boolean answer = _extractTopicsFrom(new ByteArrayInputStream(str.getBytes()), topicMap); return answer; } public boolean _extractTopicsFrom(InputStream in, TopicMap topicMap) throws Exception { javax.xml.parsers.SAXParserFactory factory=javax.xml.parsers.SAXParserFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(false); javax.xml.parsers.SAXParser parser=factory.newSAXParser(); XMLReader reader=parser.getXMLReader(); RSSParser parserHandler = new RSSParser(topicMap,this); reader.setContentHandler(parserHandler); reader.setErrorHandler(parserHandler); try{ reader.parse(new InputSource(in)); } catch(Exception e){ if(!(e instanceof SAXException) || !e.getMessage().equals("User interrupt")) log(e); } log("Total " + parserHandler.channelCount + " RSS channels processed!"); log("Total " + parserHandler.itemCount + " RSS channel items processed!"); return true; } private static class RSSParser implements org.xml.sax.ContentHandler, org.xml.sax.ErrorHandler { public static boolean MAKE_LINK_OCCURRENCE = true; public static boolean MAKE_LINK_SUBJECT_IDENTIFIER = true; public static boolean MAKE_LINK_SUBJECT_LOCATOR = false; public static boolean MAKE_SUBCLASS_OF_WANDORA_CLASS = true; public RSSParser(TopicMap tm, RSSExtractor parent){ this.tm=tm; this.parent=parent; } public int progress=0; public int itemCount = 0; public int channelCount = 0; private TopicMap tm; private RSSExtractor parent; public static final String TAG_RSS="rss"; public static final String TAG_CHANNEL="channel"; public static final String TAG_TITLE="title"; public static final String TAG_LINK="link"; public static final String TAG_DESCRIPTION="description"; public static final String TAG_LANGUAGE="language"; public static final String TAG_PUBDATE="pubDate"; public static final String TAG_LASTBUILDDATE="lastBuildDate"; public static final String TAG_DOCS="docs"; public static final String TAG_GENERATOR="generator"; public static final String TAG_MANAGINGEDITOR="managingEditor"; public static final String TAG_WEBMASTER="webMaster"; public static final String TAG_TTL="ttl"; public static final String TAG_TEXTINPUT="textInput"; public static final String TAG_COPYRIGHT="copyright"; public static final String TAG_RATING="rating"; public static final String TAG_ITEM="item"; public static final String TAG_GUID="guid"; public static final String TAG_CATEGORY="category"; public static final String TAG_AUTHOR="author"; public static final String TAG_IMAGE="image"; public static final String TAG_URL="url"; private static final int STATE_START=0; private static final int STATE_RSS=2; private static final int STATE_CHANNEL=4; private static final int STATE_CHANNEL_TITLE=5; private static final int STATE_CHANNEL_LINK=6; private static final int STATE_CHANNEL_DESCRIPTION=7; private static final int STATE_CHANNEL_LANGUAGE=8; private static final int STATE_CHANNEL_PUBDATE=9; private static final int STATE_CHANNEL_LASTBUILDDATE=10; private static final int STATE_CHANNEL_DOCS=11; private static final int STATE_CHANNEL_GENERATOR=12; private static final int STATE_CHANNEL_MANAGINGEDITOR=13; private static final int STATE_CHANNEL_WEBMASTER=14; private static final int STATE_CHANNEL_TTL=15; private static final int STATE_CHANNEL_TEXTINPUT=16; private static final int STATE_CHANNEL_COPYRIGHT=17; private static final int STATE_CHANNEL_CATEGORY=18; private static final int STATE_CHANNEL_RATING=19; private static final int STATE_CHANNEL_IMAGE=31; private static final int STATE_CHANNEL_IMAGE_URL=32; private static final int STATE_CHANNEL_IMAGE_TITLE=33; private static final int STATE_CHANNEL_IMAGE_LINK=34; private static final int STATE_CHANNEL_IMAGE_DESCRIPTION=35; private static final int STATE_CHANNEL_ITEM=120; private static final int STATE_CHANNEL_ITEM_TITLE=121; private static final int STATE_CHANNEL_ITEM_LINK=122; private static final int STATE_CHANNEL_ITEM_DESCRIPTION=123; private static final int STATE_CHANNEL_ITEM_PUBDATE=124; private static final int STATE_CHANNEL_ITEM_GUID=125; private static final int STATE_CHANNEL_ITEM_CATEGORY=126; private static final int STATE_CHANNEL_ITEM_AUTHOR=127; private int state=STATE_START; public static String RSS_SI = "http://wandora.org/si/rss/2.0/"; public static String SIPREFIX="http://wandora.org/si/rss/2.0/"; public static String CHANNEL_SI=SIPREFIX+"channel"; public static String CHANNEL_LINK_SI=CHANNEL_SI+"/link"; public static String CHANNEL_DESCRIPTION_SI=CHANNEL_SI+"/description"; public static String CHANNEL_LANGUAGE_SI=CHANNEL_SI+"/language"; public static String CHANNEL_PUBDATE_SI=CHANNEL_SI+"/pubdate"; public static String CHANNEL_LASTBUILDDATE_SI=CHANNEL_SI+"/lastbuilddate"; public static String CHANNEL_DOCS_SI=CHANNEL_SI+"/docs"; public static String CHANNEL_GENERATOR_SI=CHANNEL_SI+"/generator"; public static String CHANNEL_MANAGINGEDITOR_SI=CHANNEL_SI+"/managingeditor"; public static String CHANNEL_WEBMASTER_SI=CHANNEL_SI+"/webmaster"; public static String CHANNEL_TTL_SI=CHANNEL_SI+"/ttl"; public static String CHANNEL_TEXTINPUT_SI=CHANNEL_SI+"/textinput"; public static String CHANNEL_COPYRIGHT_SI=CHANNEL_SI+"/copyright"; public static String CHANNEL_CATEGORY_SI=CHANNEL_SI+"/category"; public static String CHANNEL_RATING_SI=CHANNEL_SI+"/rating"; public static String CHANNEL_ITEM_SI=CHANNEL_SI+"/item"; public static String CHANNEL_ITEM_TITLE_SI=CHANNEL_ITEM_SI+"/title"; public static String CHANNEL_ITEM_LINK_SI=CHANNEL_ITEM_SI+"/link"; public static String CHANNEL_ITEM_DESCRIPTION_SI=CHANNEL_ITEM_SI+"/description"; public static String CHANNEL_ITEM_PUBDATE_SI=CHANNEL_ITEM_SI+"/pubdate"; public static String CHANNEL_ITEM_GUID_SI=CHANNEL_ITEM_SI+"/guid"; public static String CHANNEL_ITEM_CATEGORY_SI=CHANNEL_ITEM_SI+"/category"; public static String CHANNEL_ITEM_AUTHOR_SI=CHANNEL_ITEM_SI+"/author"; public static String CHANNEL_IMAGE_SI=CHANNEL_SI+"/image"; public static String CHANNEL_IMAGE_LINK_SI=CHANNEL_IMAGE_SI+"/link"; public static String CHANNEL_IMAGE_DESCRIPTION_SI=CHANNEL_IMAGE_SI+"/description"; public static String DATE_SI="http://wandora.org/si/date"; private String data_channel_title; private String data_channel_link; private String data_channel_description; private String data_channel_language; private String data_channel_pubdate; private String data_channel_lastbuilddate; private String data_channel_docs; private String data_channel_generator; private String data_channel_managingeditor; private String data_channel_webmaster; private String data_channel_ttl; private String data_channel_copyright; private String data_channel_category; private String data_channel_rating; private String data_channel_item_title; private String data_channel_item_link; private String data_channel_item_description; private String data_channel_item_pubdate; private String data_channel_item_guid; private String data_channel_item_category; private String data_channel_item_author; private String data_channel_image_url; private String data_channel_image_title; private String data_channel_image_link; private String data_channel_image_description; private Topic theChannel; private Topic theItem; private Topic getOrCreateTopic(String si) throws TopicMapException { return getOrCreateTopic(si, null); } private Topic getOrCreateTopic(String si,String bn) throws TopicMapException { return ExtractHelper.getOrCreateTopic(si, bn, tm); } @Override public void startDocument() throws SAXException { channelCount = 0; itemCount = 0; } @Override public void endDocument() throws SAXException { } @Override public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { //parent.log("START" + state +" --- " + qName); if(parent.forceStop()){ throw new SAXException("User interrupt"); } switch(state){ case STATE_START: if(qName.equals(TAG_RSS)) { state = STATE_RSS; } break; case STATE_RSS: if(qName.equals(TAG_CHANNEL)) { state = STATE_CHANNEL; try { Topic channelType=getOrCreateTopic(CHANNEL_SI,"RSS Channel"); theChannel = tm.createTopic(); theChannel.addSubjectIdentifier(TopicTools.createDefaultLocator()); theChannel.addType(channelType); channelCount++; Topic rssClass = getOrCreateTopic(RSS_SI, "RSS"); Topic superClass = getOrCreateTopic(XTMPSI.SUPERCLASS, null); Topic subClass = getOrCreateTopic(XTMPSI.SUBCLASS, null); Topic supersubClass = getOrCreateTopic(XTMPSI.SUPERCLASS_SUBCLASS, null); Association supersubClassAssociation = tm.createAssociation(supersubClass); supersubClassAssociation.addPlayer(rssClass, superClass); supersubClassAssociation.addPlayer(channelType, subClass); if(MAKE_SUBCLASS_OF_WANDORA_CLASS) { Topic wandoraClass = getOrCreateTopic(TMBox.WANDORACLASS_SI, "Wandora class"); supersubClassAssociation = tm.createAssociation(supersubClass); supersubClassAssociation.addPlayer(wandoraClass, superClass); supersubClassAssociation.addPlayer(rssClass, subClass); } } catch(Exception e) { parent.log(e); } } break; case STATE_CHANNEL: if(qName.equals(TAG_TITLE)) { state = STATE_CHANNEL_TITLE; data_channel_title = ""; } else if(qName.equals(TAG_LINK)) { state = STATE_CHANNEL_LINK; data_channel_link = ""; } else if(qName.equals(TAG_DESCRIPTION)) { state = STATE_CHANNEL_DESCRIPTION; data_channel_description = ""; } else if(qName.equals(TAG_LANGUAGE)) { state = STATE_CHANNEL_LANGUAGE; data_channel_language = ""; } else if(qName.equals(TAG_PUBDATE)) { state = STATE_CHANNEL_PUBDATE; data_channel_pubdate = ""; } else if(qName.equals(TAG_LASTBUILDDATE)) { state = STATE_CHANNEL_LASTBUILDDATE; data_channel_lastbuilddate = ""; } else if(qName.equals(TAG_DOCS)) { state = STATE_CHANNEL_DOCS; data_channel_docs = ""; } else if(qName.equals(TAG_GENERATOR)) { state = STATE_CHANNEL_GENERATOR; data_channel_generator = ""; } else if(qName.equals(TAG_MANAGINGEDITOR)) { state = STATE_CHANNEL_MANAGINGEDITOR; data_channel_managingeditor = ""; } else if(qName.equals(TAG_WEBMASTER)) { state = STATE_CHANNEL_WEBMASTER; data_channel_webmaster = ""; } else if(qName.equals(TAG_TTL)) { state = STATE_CHANNEL_TTL; data_channel_ttl = ""; } else if(qName.equals(TAG_TEXTINPUT)) { state = STATE_CHANNEL_TEXTINPUT; } else if(qName.equals(TAG_COPYRIGHT)) { state = STATE_CHANNEL_COPYRIGHT; data_channel_copyright = ""; } else if(qName.equals(TAG_CATEGORY)) { state = STATE_CHANNEL_CATEGORY; data_channel_category = ""; } else if(qName.equals(TAG_RATING)) { state = STATE_CHANNEL_RATING; data_channel_rating = ""; } else if(qName.equals(TAG_IMAGE)) { state = STATE_CHANNEL_IMAGE; data_channel_image_title = ""; data_channel_image_url = ""; data_channel_image_link = ""; } else if(qName.equals(TAG_ITEM)) { state = STATE_CHANNEL_ITEM; try { Topic itemType=getOrCreateTopic(CHANNEL_ITEM_SI,"RSS Channel Item"); theItem = tm.createTopic(); theItem.addSubjectIdentifier(TopicTools.createDefaultLocator()); theItem.addType(itemType); itemCount++; Topic rssClass = getOrCreateTopic(RSS_SI, "RSS"); Topic superClass = getOrCreateTopic(XTMPSI.SUPERCLASS, null); Topic subClass = getOrCreateTopic(XTMPSI.SUBCLASS, null); Topic supersubClass = getOrCreateTopic(XTMPSI.SUPERCLASS_SUBCLASS, null); Association supersubClassAssociation = tm.createAssociation(supersubClass); supersubClassAssociation.addPlayer(rssClass, superClass); supersubClassAssociation.addPlayer(itemType, subClass); if(MAKE_SUBCLASS_OF_WANDORA_CLASS) { Topic wandoraClass = getOrCreateTopic(TMBox.WANDORACLASS_SI, "Wandora class"); supersubClassAssociation = tm.createAssociation(supersubClass); supersubClassAssociation.addPlayer(wandoraClass, superClass); supersubClassAssociation.addPlayer(rssClass, subClass); } } catch(Exception e) { parent.log(e); } data_channel_item_title = ""; data_channel_item_link = ""; data_channel_item_description = ""; data_channel_item_pubdate = ""; data_channel_item_guid = ""; data_channel_item_category = ""; data_channel_item_author = ""; } break; case STATE_CHANNEL_ITEM: if(qName.equals(TAG_TITLE)) { data_channel_item_title = ""; state = STATE_CHANNEL_ITEM_TITLE; } else if(qName.equals(TAG_LINK)) { data_channel_item_link = ""; state = STATE_CHANNEL_ITEM_LINK; } else if(qName.equals(TAG_DESCRIPTION)) { data_channel_item_description = ""; state = STATE_CHANNEL_ITEM_DESCRIPTION; } else if(qName.equals(TAG_PUBDATE)) { data_channel_item_pubdate = ""; state = STATE_CHANNEL_ITEM_PUBDATE; } else if(qName.equals(TAG_GUID)) { data_channel_item_guid = ""; state = STATE_CHANNEL_ITEM_GUID; } else if(qName.equals(TAG_CATEGORY)) { data_channel_item_category = ""; state = STATE_CHANNEL_ITEM_CATEGORY; } else if(qName.equals(TAG_AUTHOR)) { data_channel_item_author = ""; state = STATE_CHANNEL_ITEM_AUTHOR; } break; case STATE_CHANNEL_IMAGE: if(qName.equals(TAG_TITLE)) { data_channel_image_title = ""; state = STATE_CHANNEL_IMAGE_TITLE; } else if(qName.equals(TAG_URL)) { data_channel_image_url = ""; state = STATE_CHANNEL_IMAGE_URL; } else if(qName.equals(TAG_LINK)) { data_channel_image_link = ""; state = STATE_CHANNEL_IMAGE_LINK; } else if(qName.equals(TAG_DESCRIPTION)) { data_channel_image_description = ""; state = STATE_CHANNEL_IMAGE_DESCRIPTION; } break; } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { //parent.log(" END" + state +" --- " + qName); switch(state) { case STATE_RSS: { if(qName.equals(TAG_RSS)) { state = STATE_START; } break; } case STATE_CHANNEL: { if(qName.equals(TAG_CHANNEL)) { state = STATE_RSS; if(theChannel != null) { } } break; } case STATE_CHANNEL_TITLE: { if(qName.equals(TAG_TITLE)) { state = STATE_CHANNEL; if(theChannel != null && data_channel_title.length() > 0) { try { theChannel.setBaseName(data_channel_title + " (RSS channel)"); theChannel.setDisplayName("en", data_channel_title); } catch(Exception e) { parent.log(e); } } } break; } case STATE_CHANNEL_LINK: { if(qName.equals(TAG_LINK)) { state = STATE_CHANNEL; if(theChannel != null && data_channel_link.length() > 0) { try { if(MAKE_LINK_SUBJECT_IDENTIFIER) { org.wandora.topicmap.Locator tempSI = theChannel.getOneSubjectIdentifier(); theChannel.addSubjectIdentifier(new org.wandora.topicmap.Locator(data_channel_link)); theChannel.removeSubjectIdentifier(tempSI); } if(MAKE_LINK_SUBJECT_LOCATOR) { theChannel.setSubjectLocator(new org.wandora.topicmap.Locator(data_channel_link)); } if(MAKE_LINK_OCCURRENCE) { Topic linkType = getOrCreateTopic(CHANNEL_LINK_SI,"RSS Channel Link"); parent.setData(theChannel, linkType, "en", data_channel_link); } } catch(Exception e) { parent.log(e); } } } break; } case STATE_CHANNEL_DESCRIPTION: { if(qName.equals(TAG_DESCRIPTION)) { state = STATE_CHANNEL; if(theChannel != null && data_channel_description.length() > 0) { try { Topic descriptionType = getOrCreateTopic(CHANNEL_DESCRIPTION_SI,"RSS Channel Description"); parent.setData(theChannel, descriptionType, "en", data_channel_description); } catch(Exception e) { parent.log(e); } } } break; } case STATE_CHANNEL_LANGUAGE: { if(qName.equals(TAG_LANGUAGE)) { state = STATE_CHANNEL; if(theChannel != null && data_channel_language.length() > 0) { try { Topic channelType = getOrCreateTopic(CHANNEL_SI,"RSS Channel"); Topic languageType = getOrCreateTopic(CHANNEL_LANGUAGE_SI,"RSS Channel Language"); Topic theLanguage = getOrCreateTopic(CHANNEL_LANGUAGE_SI + "/" + data_channel_language, data_channel_language); theLanguage.addType(languageType); Association channelLanguage = tm.createAssociation(languageType); channelLanguage.addPlayer(theChannel, channelType); channelLanguage.addPlayer(theLanguage, languageType); } catch(Exception e) { parent.log(e); } } } break; } case STATE_CHANNEL_COPYRIGHT: { if(qName.equals(TAG_COPYRIGHT)) { state = STATE_CHANNEL; if(theChannel != null && data_channel_copyright.length() > 0) { try { if(true) { Topic channelType = getOrCreateTopic(CHANNEL_SI,"RSS Channel"); Topic copyrightType = getOrCreateTopic(CHANNEL_COPYRIGHT_SI,"RSS Channel Copyright"); Topic theCopyright = getOrCreateTopic(CHANNEL_COPYRIGHT_SI + "/" + data_channel_copyright, data_channel_copyright); theCopyright.addType(copyrightType); Association channelCopyright = tm.createAssociation(copyrightType); channelCopyright.addPlayer(theChannel, channelType); channelCopyright.addPlayer(theCopyright, copyrightType); } else { Topic copyrightType = getOrCreateTopic(CHANNEL_COPYRIGHT_SI,"RSS Channel Copyright"); parent.setData(theChannel, copyrightType, "en", data_channel_copyright); } } catch(Exception e) { parent.log(e); } } } break; } case STATE_CHANNEL_PUBDATE: { if(qName.equals(TAG_PUBDATE)) { state = STATE_CHANNEL; if(theChannel != null && data_channel_pubdate.length() > 0) { try { Topic channelType = getOrCreateTopic(CHANNEL_SI,"RSS Channel"); Topic dateType = getOrCreateTopic(DATE_SI,"Date"); Topic pubdateType = getOrCreateTopic(CHANNEL_PUBDATE_SI,"RSS Channel Publish Date"); Topic theDate = getOrCreateTopic(DATE_SI + "/" + data_channel_pubdate, data_channel_pubdate); theDate.addType(dateType); Association channelPubDate = tm.createAssociation(pubdateType); channelPubDate.addPlayer(theChannel, channelType); channelPubDate.addPlayer(theDate, dateType); } catch(Exception e) { parent.log(e); } } } break; } case STATE_CHANNEL_LASTBUILDDATE: { if(qName.equals(TAG_LASTBUILDDATE)) { state = STATE_CHANNEL; if(theChannel != null && data_channel_lastbuilddate.length() > 0) { try { Topic channelType = getOrCreateTopic(CHANNEL_SI,"RSS Channel"); Topic dateType = getOrCreateTopic(DATE_SI,"Date"); Topic lastbuilddateType = getOrCreateTopic(CHANNEL_LASTBUILDDATE_SI,"RSS Channel Last Build Date"); Topic theDate = getOrCreateTopic(DATE_SI + "/" + data_channel_lastbuilddate, data_channel_lastbuilddate); theDate.addType(dateType); Association channelPubDate = tm.createAssociation(lastbuilddateType); channelPubDate.addPlayer(theChannel, channelType); channelPubDate.addPlayer(theDate, dateType); } catch(Exception e) { parent.log(e); } } } break; } case STATE_CHANNEL_DOCS: { if(qName.equals(TAG_DOCS)) { state = STATE_CHANNEL; if(theChannel != null && data_channel_docs.length() > 0) { try { Topic docsType = getOrCreateTopic(CHANNEL_DOCS_SI,"Channel Docs"); parent.setData(theChannel, docsType, "en", data_channel_docs); } catch(Exception e) { parent.log(e); } } } break; } case STATE_CHANNEL_GENERATOR: { if(qName.equals(TAG_GENERATOR)) { state = STATE_CHANNEL; if(theChannel != null && data_channel_generator.length() > 0) { try { Topic channelType = getOrCreateTopic(CHANNEL_SI,"RSS Channel"); Topic generatorType = getOrCreateTopic(CHANNEL_GENERATOR_SI,"RSS Channel Generator"); Topic theGenerator = getOrCreateTopic(CHANNEL_GENERATOR_SI + "/" + data_channel_generator, data_channel_generator); theGenerator.addType(generatorType); Association channelGenerator = tm.createAssociation(generatorType); channelGenerator.addPlayer(theChannel, channelType); channelGenerator.addPlayer(theGenerator, generatorType); } catch(Exception e) { parent.log(e); } } } break; } case STATE_CHANNEL_MANAGINGEDITOR: { if(qName.equals(TAG_MANAGINGEDITOR)) { state = STATE_CHANNEL; if(theChannel != null && data_channel_managingeditor.length() > 0) { try { Topic channelType = getOrCreateTopic(CHANNEL_SI,"RSS Channel"); Topic managerType = getOrCreateTopic(CHANNEL_MANAGINGEDITOR_SI,"RSS Channel Managing Editor"); Topic theManager = getOrCreateTopic(CHANNEL_MANAGINGEDITOR_SI + "/" + data_channel_managingeditor, data_channel_managingeditor); theManager.addType(managerType); Association channelManager = tm.createAssociation(managerType); channelManager.addPlayer(theChannel, channelType); channelManager.addPlayer(theManager, managerType); } catch(Exception e) { parent.log(e); } } } break; } case STATE_CHANNEL_WEBMASTER: { if(qName.equals(TAG_WEBMASTER)) { state = STATE_CHANNEL; if(theChannel != null && data_channel_webmaster.length() > 0) { try { Topic channelType = getOrCreateTopic(CHANNEL_SI,"RSS Channel"); Topic webmasterType = getOrCreateTopic(CHANNEL_WEBMASTER_SI,"RSS Channel Web Master"); Topic theWebmaster = getOrCreateTopic(CHANNEL_WEBMASTER_SI + "/" + data_channel_webmaster, data_channel_webmaster); theWebmaster.addType(webmasterType); Association channelWebmaster = tm.createAssociation(webmasterType); channelWebmaster.addPlayer(theChannel, channelType); channelWebmaster.addPlayer(theWebmaster, webmasterType); } catch(Exception e) { parent.log(e); } } } break; } case STATE_CHANNEL_TTL: { if(qName.equals(TAG_TTL)) { state = STATE_CHANNEL; if(theChannel != null && data_channel_ttl.length() > 0) { try { Topic ttlType = getOrCreateTopic(CHANNEL_TTL_SI,"RSS Channel Time To Live"); parent.setData(theChannel, ttlType, "en", data_channel_ttl); } catch(Exception e) { parent.log(e); } } } break; } case STATE_CHANNEL_CATEGORY: { if(qName.equals(TAG_CATEGORY)) { state = STATE_CHANNEL; if(theChannel != null && data_channel_category.length() > 0) { try { Topic channelType = getOrCreateTopic(CHANNEL_SI,"RSS Channel"); Topic categoryType = getOrCreateTopic(CHANNEL_CATEGORY_SI,"RSS Channel Category"); Topic theCategory = getOrCreateTopic(CHANNEL_CATEGORY_SI + "/" + data_channel_category, data_channel_category); theCategory.addType(categoryType); Association channelCategory = tm.createAssociation(categoryType); channelCategory.addPlayer(theChannel, channelType); channelCategory.addPlayer(theCategory, categoryType); } catch(Exception e) { parent.log(e); } } } break; } case STATE_CHANNEL_RATING: { if(qName.equals(TAG_RATING)) { state = STATE_CHANNEL; if(theChannel != null && data_channel_rating.length() > 0) { try { Topic channelType = getOrCreateTopic(CHANNEL_SI,"RSS Channel"); Topic ratingType = getOrCreateTopic(CHANNEL_RATING_SI,"RSS Channel Rating"); Topic theRating = getOrCreateTopic(CHANNEL_RATING_SI + "/" + data_channel_rating, data_channel_rating); theRating.addType(ratingType); Association channelRating = tm.createAssociation(ratingType); channelRating.addPlayer(theChannel, channelType); channelRating.addPlayer(theRating, ratingType); } catch(Exception e) { parent.log(e); } } } break; } case STATE_CHANNEL_TEXTINPUT: { if(qName.equals(TAG_TEXTINPUT)) { state = STATE_CHANNEL; } break; } case STATE_CHANNEL_ITEM: { if(qName.equals(TAG_ITEM)) { state = STATE_CHANNEL; if(theItem != null) { if(theChannel != null) { try { Topic channelType = getOrCreateTopic(CHANNEL_SI,"RSS Channel"); Topic itemType = getOrCreateTopic(CHANNEL_ITEM_SI,"RSS Channel Item"); Association channelItem = tm.createAssociation(itemType); channelItem.addPlayer(theChannel, channelType); channelItem.addPlayer(theItem, itemType); } catch(Exception e) { parent.log(e); } } } } break; } // **** ITEM **** case STATE_CHANNEL_ITEM_TITLE: { if(qName.equals(TAG_TITLE)) { state = STATE_CHANNEL_ITEM; if(theItem != null && data_channel_item_title.length() > 0) { try { theItem.setBaseName(data_channel_item_title + " (RSS item)"); theItem.setDisplayName("en", data_channel_item_title); } catch(Exception e) { parent.log(e); } } } break; } case STATE_CHANNEL_ITEM_LINK: { if(qName.equals(TAG_LINK)) { state = STATE_CHANNEL_ITEM; if(theItem != null && data_channel_item_link.length() > 0) { try { if(MAKE_LINK_SUBJECT_IDENTIFIER) { org.wandora.topicmap.Locator tempSI = theItem.getOneSubjectIdentifier(); theItem.addSubjectIdentifier(new org.wandora.topicmap.Locator(data_channel_item_link)); theItem.removeSubjectIdentifier(tempSI); } if(MAKE_LINK_SUBJECT_LOCATOR) { theItem.setSubjectLocator(new org.wandora.topicmap.Locator(data_channel_item_link)); } if(MAKE_LINK_OCCURRENCE) { Topic linkType = getOrCreateTopic(CHANNEL_ITEM_LINK_SI,"RSS Channel Item Link"); parent.setData(theItem, linkType, "en", data_channel_item_link); } } catch(Exception e) { parent.log(e); } } } break; } case STATE_CHANNEL_ITEM_DESCRIPTION: { if(qName.equals(TAG_DESCRIPTION)) { state = STATE_CHANNEL_ITEM; if(theItem != null && data_channel_item_description.length() > 0) { try { Topic descriptionType = getOrCreateTopic(CHANNEL_ITEM_DESCRIPTION_SI,"RSS Channel Item Description"); parent.setData(theItem, descriptionType, "en", data_channel_item_description); } catch(Exception e) { parent.log(e); } } } break; } case STATE_CHANNEL_ITEM_PUBDATE: { if(qName.equals(TAG_PUBDATE)) { state = STATE_CHANNEL_ITEM; if(theItem != null && data_channel_item_pubdate.length() > 0) { try { Topic itemType = getOrCreateTopic(CHANNEL_ITEM_SI,"RSS Channel Item"); Topic dateType = getOrCreateTopic(DATE_SI,"Date"); Topic pubdateType = getOrCreateTopic(CHANNEL_ITEM_PUBDATE_SI,"RSS Channel Item Publish Date"); Topic theDate = getOrCreateTopic(DATE_SI + "/" + data_channel_item_pubdate, data_channel_item_pubdate); theDate.addType(dateType); Association itemPubdate = tm.createAssociation(pubdateType); itemPubdate.addPlayer(theItem, itemType); itemPubdate.addPlayer(theDate, dateType); } catch(Exception e) { parent.log(e); } } } break; } case STATE_CHANNEL_ITEM_GUID: { if(qName.equals(TAG_GUID)) { state = STATE_CHANNEL_ITEM; if(theItem != null && data_channel_item_guid.length() > 0) { try { //theItem.addSubjectIdentifier(new org.wandora.topicmap.Locator(data_channel_item_guid)); Topic guidType = getOrCreateTopic(CHANNEL_ITEM_GUID_SI,"RSS Channel Item GUID"); parent.setData(theItem, guidType, "en", data_channel_item_guid); } catch(Exception e) { parent.log(e); } } } break; } case STATE_CHANNEL_ITEM_CATEGORY: { if(qName.equals(TAG_CATEGORY)) { state = STATE_CHANNEL_ITEM; if(theItem != null && data_channel_item_category.length() > 0) { try { Topic itemType = getOrCreateTopic(CHANNEL_ITEM_SI,"RSS Channel Item"); Topic categoryType = getOrCreateTopic(CHANNEL_ITEM_CATEGORY_SI,"RSS Channel Item Category"); Topic theCategory = getOrCreateTopic(CHANNEL_ITEM_CATEGORY_SI + "/" + data_channel_item_category, data_channel_item_category); theCategory.addType(categoryType); Association itemCategory = tm.createAssociation(categoryType); itemCategory.addPlayer(theItem, itemType); itemCategory.addPlayer(theCategory, categoryType); } catch(Exception e) { parent.log(e); } } } break; } case STATE_CHANNEL_ITEM_AUTHOR: { if(qName.equals(TAG_AUTHOR)) { state = STATE_CHANNEL_ITEM; if(theItem != null && data_channel_item_author.length() > 0) { try { Topic itemType = getOrCreateTopic(CHANNEL_ITEM_SI,"RSS Channel Item"); Topic authorType = getOrCreateTopic(CHANNEL_ITEM_AUTHOR_SI,"RSS Channel Item Author"); Topic theAuthor = getOrCreateTopic(CHANNEL_ITEM_AUTHOR_SI + "/" + data_channel_item_author, data_channel_item_author); theAuthor.addType(authorType); Association itemAuthor = tm.createAssociation(authorType); itemAuthor.addPlayer(theItem, itemType); itemAuthor.addPlayer(theAuthor, authorType); } catch(Exception e) { parent.log(e); } } } break; } // ***** IMAGE ***** case STATE_CHANNEL_IMAGE: { if(qName.equals(TAG_IMAGE)) { state = STATE_CHANNEL; if(theChannel != null) if(data_channel_image_title != null && data_channel_image_title.length() > 0) { try { Topic channelType = getOrCreateTopic(CHANNEL_SI,"RSS Channel Item"); Topic imageType = getOrCreateTopic(CHANNEL_IMAGE_SI,"RSS Channel Image"); Topic theImage = getOrCreateTopic(CHANNEL_IMAGE_SI + "/" + data_channel_image_title, data_channel_image_title + " (RSS channel image)"); if(data_channel_image_url != null && data_channel_image_url.length() > 0) { theImage.setSubjectLocator(new org.wandora.topicmap.Locator(data_channel_image_url)); } theImage.addType(imageType); Association channelImage = tm.createAssociation(imageType); channelImage.addPlayer(theChannel, channelType); channelImage.addPlayer(theImage, imageType); if(data_channel_image_link != null && data_channel_image_link.length() > 0) { Topic linkType = getOrCreateTopic(CHANNEL_IMAGE_LINK_SI,"Channel Image Link"); parent.setData(theImage, linkType, "en", data_channel_image_link); } if(data_channel_image_description != null && data_channel_image_description.length() > 0) { Topic descriptionType = getOrCreateTopic(CHANNEL_IMAGE_DESCRIPTION_SI,"Channel Image Description"); parent.setData(theImage, descriptionType, "en", data_channel_image_description); } } catch(Exception e) { parent.log(e); } } } } break; case STATE_CHANNEL_IMAGE_LINK: if(qName.equals(TAG_LINK)) { state = STATE_CHANNEL_IMAGE; } break; case STATE_CHANNEL_IMAGE_URL: if(qName.equals(TAG_URL)) { state = STATE_CHANNEL_IMAGE; } break; case STATE_CHANNEL_IMAGE_TITLE: if(qName.equals(TAG_TITLE)) { state = STATE_CHANNEL_IMAGE; } break; case STATE_CHANNEL_IMAGE_DESCRIPTION: if(qName.equals(TAG_DESCRIPTION)) { state = STATE_CHANNEL_IMAGE; } break; } } public void characters(char[] ch, int start, int length) throws SAXException { switch(state){ case STATE_CHANNEL_TITLE: data_channel_title+=new String(ch,start,length); break; case STATE_CHANNEL_LINK: data_channel_link+=new String(ch,start,length); break; case STATE_CHANNEL_DESCRIPTION: data_channel_description+=new String(ch,start,length); break; case STATE_CHANNEL_LANGUAGE: data_channel_language+=new String(ch,start,length); break; case STATE_CHANNEL_PUBDATE: data_channel_pubdate+=new String(ch,start,length); break; case STATE_CHANNEL_LASTBUILDDATE: data_channel_lastbuilddate+=new String(ch,start,length); break; case STATE_CHANNEL_DOCS: data_channel_docs+=new String(ch,start,length); break; case STATE_CHANNEL_GENERATOR: data_channel_generator+=new String(ch,start,length); break; case STATE_CHANNEL_MANAGINGEDITOR: data_channel_managingeditor+=new String(ch,start,length); break; case STATE_CHANNEL_WEBMASTER: data_channel_webmaster+=new String(ch,start,length); break; case STATE_CHANNEL_TTL: data_channel_ttl+=new String(ch,start,length); break; case STATE_CHANNEL_COPYRIGHT: data_channel_copyright+=new String(ch,start,length); break; case STATE_CHANNEL_CATEGORY: data_channel_category+=new String(ch,start,length); break; case STATE_CHANNEL_RATING: data_channel_rating+=new String(ch,start,length); break; case STATE_CHANNEL_ITEM_TITLE: data_channel_item_title+=new String(ch,start,length); break; case STATE_CHANNEL_ITEM_LINK: data_channel_item_link+=new String(ch,start,length); break; case STATE_CHANNEL_ITEM_DESCRIPTION: data_channel_item_description+=new String(ch,start,length); break; case STATE_CHANNEL_ITEM_PUBDATE: data_channel_item_pubdate+=new String(ch,start,length); break; case STATE_CHANNEL_ITEM_GUID: data_channel_item_guid+=new String(ch,start,length); break; case STATE_CHANNEL_ITEM_CATEGORY: data_channel_item_category+=new String(ch,start,length); break; case STATE_CHANNEL_ITEM_AUTHOR: data_channel_item_author+=new String(ch,start,length); break; case STATE_CHANNEL_IMAGE_TITLE: data_channel_image_title+=new String(ch,start,length); break; case STATE_CHANNEL_IMAGE_LINK: data_channel_image_link+=new String(ch,start,length); break; case STATE_CHANNEL_IMAGE_URL: data_channel_image_url+=new String(ch,start,length); break; case STATE_CHANNEL_IMAGE_DESCRIPTION: data_channel_image_description+=new String(ch,start,length); break; } } public void warning(SAXParseException exception) throws SAXException { parent.log("Warning while parsing XML document at "+exception.getLineNumber()+","+exception.getColumnNumber(),exception); } public void error(SAXParseException exception) throws SAXException { parent.log("Error parsing XML document at "+exception.getLineNumber()+","+exception.getColumnNumber(),exception); } public void fatalError(SAXParseException exception) throws SAXException { parent.log("Fatal error parsing XML document at "+exception.getLineNumber()+","+exception.getColumnNumber(),exception); } public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {} public void processingInstruction(String target, String data) throws SAXException {} public void startPrefixMapping(String prefix, String uri) throws SAXException {} public void endPrefixMapping(String prefix) throws SAXException {} public void setDocumentLocator(org.xml.sax.Locator locator) {} public void skippedEntity(String name) throws SAXException {} } }
58,612
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Sentences2Associations.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/Sentences2Associations.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.wandora.application.tools.extractors; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.util.ArrayList; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.tools.browserextractors.BrowserExtractRequest; import org.wandora.topicmap.Association; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * Extractor takes text as input and transforms sentences to associations where * words are association players. * * @author akivela */ public class Sentences2Associations extends AbstractExtractor implements WandoraTool { private static final long serialVersionUID = 1L; public static boolean ADD_SOURCE_AS_PLAYER = true; public static String SOURCE_SI = "http://wandora.org/si/sentence-source"; public static String WORD_SI_BASE = "http://wandora.org/si/word/"; public static String ROLE_SI_BASE = "http://wandora.org/si/word-slot/"; public static String SENTENCE_SI_BASE = "http://wandora.org/si/sentence"; public static String ORDER_SI_BASE = "http://wandora.org/si/sentence/"; public static String SENTENCES_TO_ASSOCIATIONS = "http://wandora.org/si/sentences2associations"; private URL basePath = null; /** Creates a new instance of Sentences2Associations */ public Sentences2Associations() { } @Override public String getName() { return "Sentence extractor"; } @Override public String getDescription() { return "Creates a topic for each word and an association for each sentence. Sentence words are association players."; } @Override public boolean useTempTopicMap(){ return false; } @Override public String getGUIText(int textType) { switch(textType) { case SELECT_DIALOG_TITLE: return "Select sentence document(s) or directories containing sentence documents!"; case POINT_START_URL_TEXT: return "Where would you like to start the crawl?"; case INFO_WAIT_WHILE_WORKING: return "Wait while seeking sentence documents!"; case FILE_PATTERN: return ".*"; case DONE_FAILED: return "Ready. No extractions! %1 sentence file(s) crawled!"; case DONE_ONE: return "Ready. Successful extraction! %1 sentence file(s) crawled!"; case DONE_MANY: return "Ready. Total %0 successful extractions! %1 sentence file(s) crawled!"; case LOG_TITLE: return "Sentences to associations extraction Log"; } return ""; } @Override public boolean browserExtractorConsumesPlainText() { return true; } @Override public String doBrowserExtract(BrowserExtractRequest request, Wandora wandora) throws TopicMapException { try { basePath = new URL(request.getSource()); } catch(Exception e) { e.printStackTrace(); } String s = super.doBrowserExtract(request, wandora); basePath = null; return s; } @Override public boolean _extractTopicsFrom(URL url, TopicMap topicMap) throws Exception { if(url == null) return false; try { basePath = url; URLConnection uc = null; if(getWandora() != null) { uc = getWandora().wandoraHttpAuthorizer.getAuthorizedAccess(url); } else { uc = url.openConnection(); Wandora.initUrlConnection(uc); } _extractTopicsFromStream(url.toExternalForm(), uc.getInputStream(), topicMap); basePath = null; return true; } catch(Exception e) { log("Exception occurred while extracting from url\n" + url.toExternalForm(), e); takeNap(1000); } basePath = null; return false; } @Override public boolean _extractTopicsFrom(File file, TopicMap topicMap) throws Exception { if(file == null || file.isDirectory()) return false; try { basePath = file.toURI().toURL(); _extractTopicsFromStream(file.getPath(), new FileInputStream(file), topicMap); basePath = null; return true; } catch(Exception e) { log("Exception occurred while extracting from file " + file.getName(), e); takeNap(1000); } basePath = null; return false; } @Override public boolean _extractTopicsFrom(String str, TopicMap tm) throws Exception { String stringLocator = "http://wandora.org/si/sentences2associations/"; try { _extractTopicsFromStream(stringLocator, new ByteArrayInputStream(str.getBytes()), tm); return true; } catch(Exception e) { log("Exception occurred while extracting from string '" + str + "'.", e); takeNap(1000); } return false; } public void _extractTopicsFromStream(String locator, InputStream inputStream, TopicMap tm) { try { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuffer word = null; Topic wordTopic = null; Topic orderTopic = null; Topic roleTopic = null; int count = 0; int associationCount = 0; log("Prosessing word stream!"); int c = reader.read(); word = new StringBuffer(""); ArrayList<String> words = new ArrayList(); while(c != -1) { count++; setProgress(count / 100); while(!isWordDelimiter(c) && !isSentenceDelimiter(c)) { word.append((char) c); c = reader.read(); } if(isWordDelimiter(c) || isSentenceDelimiter(c)) { if(word != null) { String wordStr = word.toString(); if(wordStr.trim().length() > 0) { log("Found word '"+wordStr+"'."); words.add(wordStr); } word = new StringBuffer(""); } } if(isSentenceDelimiter(c)) { if(words.size() > 0) { log("Processing sentence with "+words.size()+" words."); associationCount++; Association a = tm.createAssociation(getSentenceTopic(tm)); if(ADD_SOURCE_AS_PLAYER) { if(basePath != null) { Topic sourceTopic = getOrCreateTopic(tm, basePath.toExternalForm(), null); Topic sourceRole = getOrCreateTopic(tm, SOURCE_SI, "sentence-source" ); if(sourceTopic != null && sourceRole != null) { a.addPlayer(sourceTopic, sourceRole); } } } orderTopic = getOrCreateTopic(tm, ORDER_SI_BASE+associationCount, "sentence-"+associationCount); roleTopic = getOrCreateTopic(tm, ROLE_SI_BASE+"order", "sentence-order" ); if(orderTopic != null) { orderTopic.addType(getSentenceTopic(tm)); if(roleTopic != null) { a.addPlayer(orderTopic, roleTopic); } } for(int i=0; i<words.size(); i++) { String w = words.get(i); if(w != null) { wordTopic = getWordTopic(tm, w); String istr = ""+i; if(istr.length() == 1) istr = "0"+istr; roleTopic = getOrCreateTopic(tm, ROLE_SI_BASE+i, "slot-"+istr ); if(wordTopic != null && roleTopic != null) { a.addPlayer(wordTopic, roleTopic); } } } words = new ArrayList(); } } while((isWordDelimiter(c) || isSentenceDelimiter(c)) && c != -1) { c = reader.read(); } } log("Total "+associationCount+" sentence associations created!"); log("Ok"); } catch(Exception e) { log(e); } } public boolean isWordDelimiter(int c) { if(c == ' ') return true; if(c == ',') return true; else return false; } public boolean isSentenceDelimiter(int c) { if(c == '.') return true; if(c == '\n') return true; if(c == -1) return true; else return false; } public Topic getSentenceTopic(TopicMap tm) throws TopicMapException { Topic s = getOrCreateTopic(tm, SENTENCE_SI_BASE, "sentence"); Topic stype = getSentenceTypeTopic(tm); ExtractHelper.makeSubclassOf(s, stype, tm); return s; } public Topic getWordTopic(TopicMap tm, String word) throws TopicMapException { String encWord = word; try { encWord = URLEncoder.encode(word, "UTF-8"); } catch(Exception e) { /* PASS */ } Topic wordTopic = getOrCreateTopic(tm, WORD_SI_BASE+encWord, word); Topic wordTypeTopic = getOrCreateTopic(tm, WORD_SI_BASE, "word"); wordTopic.addType(wordTypeTopic); Topic stype = getSentenceTypeTopic(tm); ExtractHelper.makeSubclassOf(wordTypeTopic, stype, tm); return wordTopic; } public Topic getSentenceTypeTopic(TopicMap tm) throws TopicMapException { Topic s = getOrCreateTopic(tm, SENTENCES_TO_ASSOCIATIONS, "Sentences to associations"); Topic wc = getOrCreateTopic(tm, TMBox.WANDORACLASS_SI, "Wandora class"); ExtractHelper.makeSubclassOf(s, wc, tm); return s; } protected Topic getOrCreateTopic(TopicMap tm, String si, String bn) throws TopicMapException { return ExtractHelper.getOrCreateTopic(si, bn, tm); } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- public static final String[] contentTypes=new String[] { "text/plain" }; @Override public String[] getContentTypes() { return contentTypes; } }
12,050
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MediaWikiExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/MediaWikiExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * MediaWikiExtractor.java * * Created on 9. maaliskuuta 2007, 11:33 * */ package org.wandora.application.tools.extractors; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.net.URL; import java.util.HashSet; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.Icon; import org.wandora.application.gui.UIBox; import org.wandora.topicmap.Association; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.XTMPSI; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; /** * Extracts text and metadata from exported MediaWiki pages. Exported MediaWiki * pages are XML dumps. Example of exported MediaWiki page can be found at * * http://wandora.orgwiki/Special:Export/Wandora * * @author olli */ public class MediaWikiExtractor extends AbstractExtractor { // private String extracterUrl = null; private static final long serialVersionUID = 1L; private String wikiBaseURL = null; private boolean followRedirects = false; /** Creates a new instance of MediaWikiExtractor */ public MediaWikiExtractor() { } public void setWikiBaseURL(String url){ wikiBaseURL=url; } public void setFollowRedirects(boolean b){ followRedirects=b; } @Override public String getName() { return "MediaWiki extractor"; } @Override public String getDescription(){ return "Extracts text and metadata from exported MediaWiki pages."; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_mediawiki.png"); } public boolean _extractTopicsFrom(URL url, TopicMap topicMap) throws Exception { String urlS = url.toExternalForm(); return _extractTopicsFrom(url.openStream(),urlS,topicMap); } public boolean _extractTopicsFrom(File file, TopicMap topicMap) throws Exception { String url = file.toURI().toURL().toExternalForm(); return _extractTopicsFrom(new FileInputStream(file),url,topicMap); } public boolean _extractTopicsFrom(String str, TopicMap topicMap) throws Exception { boolean answer = _extractTopicsFrom(new ByteArrayInputStream(str.getBytes()), "http://wandora.org/si/mediawiki-extractor/"+System.currentTimeMillis(), topicMap); return answer; } public boolean _extractTopicsFrom(InputStream in, String url, TopicMap topicMap) throws Exception { javax.xml.parsers.SAXParserFactory factory=javax.xml.parsers.SAXParserFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(false); javax.xml.parsers.SAXParser parser=factory.newSAXParser(); XMLReader reader=parser.getXMLReader(); WikiParser parserHandler = new WikiParser(url, topicMap, this); reader.setContentHandler(parserHandler); reader.setErrorHandler(parserHandler); try{ reader.parse(new InputSource(in)); }catch(Exception e){ if(!(e instanceof SAXException) || !e.getMessage().equals("User interrupt")) log(e); } return true; } public String extractTopicsFromWiki(String page, TopicMap topicMap) throws Exception { if(wikiBaseURL!=null){ String url=wikiBaseURL.replace("__1__", page.replace(" ", "_")); if(_extractTopicsFrom(new URL(url),topicMap)) return url; else return null; } else return null; } private static class WikiParser implements org.xml.sax.ContentHandler, org.xml.sax.ErrorHandler { public WikiParser(String wikiUrl, TopicMap tm, MediaWikiExtractor parent){ this.url = wikiUrl; this.tm=tm; this.parent=parent; } private String url; private TopicMap tm; private MediaWikiExtractor parent; public static final Pattern redirectPattern=Pattern.compile("#REDIRECT\\s*\\[\\[(.*?)\\]\\]"); public static final String TAG_MEDIAWIKI="mediawiki"; public static final String TAG_SITEINFO="siteinfo"; public static final String TAG_SITENAME="sitename"; public static final String TAG_BASE="base"; public static final String TAG_GENERATOR="generator"; // not used public static final String TAG_CASE="case"; // not used; public static final String TAG_NAMESPACES="namespaces"; public static final String TAG_NAMESPACE="namespace"; public static final String TAG_PAGE="page"; public static final String TAG_TITLE="title"; public static final String TAG_PAGEID="id"; public static final String TAG_RESTRICTIONS="restrictions"; public static final String TAG_REVISION="revision"; public static final String TAG_REVISIONID="id"; public static final String TAG_TIMESTAMP="timestamp"; public static final String TAG_CONTRIBUTOR="contributor"; public static final String TAG_COMMENT="comment"; // not used public static final String TAG_USERNAME="username"; public static final String TAG_CONTRIBUTORID="id"; public static final String TAG_TEXT="text"; private static final int STATE_START=0; private static final int STATE_MEDIAWIKI=1; private static final int STATE_SITEINFO=2; private static final int STATE_SITENAME=3; private static final int STATE_BASE=4; private static final int STATE_NAMESPACES=5; private static final int STATE_NAMESPACE=6; private static final int STATE_PAGE=7; private static final int STATE_TITLE=8; private static final int STATE_PAGEID=9; private static final int STATE_RESTRICTIONS=10; private static final int STATE_REVISION=11; private static final int STATE_REVISIONID=12; private static final int STATE_TIMESTAMP=13; private static final int STATE_CONTRIBUTOR=14; private static final int STATE_COMMENT=15; private static final int STATE_USERNAME=16; private static final int STATE_CONTRIBUTORID=17; private static final int STATE_TEXT=18; private int state=STATE_START; public static String SIPREFIX="http://wandora.org/si/mediawiki/"; public static String CONTRIBUTOR_SI=SIPREFIX+"contributor"; public static String PAGE_SI=SIPREFIX+"page"; public static String TIMESTAMP_SI=SIPREFIX+"timestamp"; public static String TEXT_SI=SIPREFIX+"text"; public static String WIKI_SI=SIPREFIX+"wiki"; public static String REDIRECT_SI=SIPREFIX+"redirect"; public static String REDIRECT_FROM_SI=SIPREFIX+"redirect_from"; public static String REDIRECT_TO_SI=SIPREFIX+"redirect_to"; private String data_sitename; private String data_base; private Vector<String> data_namespaces; private String data_namespace; private String data_title; private String data_pageid; private String data_restrictions; private String data_revisionid; private String data_timestamp; private String data_username; private String data_contributorid; private HashSet<String> data_contributors; private String data_text; private int data_latestrevision; private String data_latesttext; private String data_latesttimestamp; private Topic getOrCreateTopic(String si) throws TopicMapException { return ExtractHelper.getOrCreateTopic(si, tm); } private Topic getOrCreateTopic(String si, String bn) throws TopicMapException { return ExtractHelper.getOrCreateTopic(si, bn, tm); } public void startDocument() throws SAXException { } public void endDocument() throws SAXException { } public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { if(parent.forceStop()){ throw new SAXException("User interrupt"); } switch(state){ case STATE_START: if(qName.equals(TAG_MEDIAWIKI)) { state=STATE_MEDIAWIKI; data_sitename=null; data_base=null; data_namespaces=null; data_title=null; data_namespaces=null; data_contributors=null; data_latestrevision=-1; data_latesttext=null; data_latesttimestamp=null; } break; case STATE_MEDIAWIKI: if(qName.equals(TAG_SITEINFO)){ state=STATE_SITEINFO; } else if(qName.equals(TAG_PAGE)){ state=STATE_PAGE; data_contributors=new HashSet<String>(); data_latestrevision=-1; data_latesttext=null; data_latesttimestamp=null; } break; case STATE_SITEINFO: if(qName.equals(TAG_SITENAME)){ state=STATE_SITENAME; data_sitename=""; } else if(qName.equals(TAG_BASE)){ state=STATE_BASE; data_base=""; } else if(qName.equals(TAG_NAMESPACES)){ state=STATE_NAMESPACES; data_namespaces=new Vector<String>(); } break; case STATE_NAMESPACES: if(qName.equals(TAG_NAMESPACE)){ state=STATE_NAMESPACE; data_namespace=""; } break; case STATE_PAGE: if(qName.equals(TAG_TITLE)){ state=STATE_TITLE; data_title=""; } else if(qName.equals(TAG_PAGEID)){ state=STATE_PAGEID; data_pageid=""; } else if(qName.equals(TAG_RESTRICTIONS)){ state=STATE_RESTRICTIONS; data_restrictions=""; } else if(qName.equals(TAG_REVISION)){ state=STATE_REVISION; data_revisionid=null; data_timestamp=null; data_username=null; data_contributorid=null; data_text=null; } break; case STATE_REVISION: if(qName.equals(TAG_REVISIONID)){ state=STATE_REVISIONID; data_revisionid=""; } else if(qName.equals(TAG_TIMESTAMP)){ state=STATE_TIMESTAMP; data_timestamp=""; } else if(qName.equals(TAG_CONTRIBUTOR)){ state=STATE_CONTRIBUTOR; } else if(qName.equals(TAG_COMMENT)){ state=STATE_COMMENT; } else if(qName.equals(TAG_TEXT)){ state=STATE_TEXT; data_text=""; } break; case STATE_CONTRIBUTOR: if(qName.equals(TAG_USERNAME)){ state=STATE_USERNAME; data_username=""; } else if(qName.equals(TAG_CONTRIBUTORID)){ state=STATE_CONTRIBUTORID; data_contributorid=""; } break; } } public void endElement(String uri, String localName, String qName) throws SAXException { switch(state){ case STATE_SITENAME: if(qName.equals(TAG_SITENAME)) state=STATE_SITEINFO; break; case STATE_BASE: if(qName.equals(TAG_BASE)) state=STATE_SITEINFO; break; case STATE_NAMESPACE: if(qName.equals(TAG_NAMESPACE)){ state=STATE_NAMESPACES; data_namespaces.add(data_namespace); } break; case STATE_NAMESPACES: if(qName.equals(TAG_NAMESPACES)) state=STATE_SITEINFO; break; case STATE_SITEINFO: if(qName.equals(TAG_SITEINFO)) { state=STATE_MEDIAWIKI; if(data_sitename!=null){ try{ Topic wikiTopic=tm.createTopic(); try { URL si = new URL(url); String protocol = si.getProtocol(); String host = si.getHost(); wikiTopic.addSubjectIdentifier(new org.wandora.topicmap.Locator(protocol+"://"+host)); } catch(Exception e) { wikiTopic.addSubjectIdentifier(tm.makeSubjectIndicatorAsLocator()); } wikiTopic.setBaseName(data_sitename); wikiTopic.addType(getOrCreateTopic(WIKI_SI,"Wiki")); }catch(TopicMapException tme){ parent.log(tme); } } } break; case STATE_TITLE: if(qName.equals(TAG_TITLE)) state=STATE_PAGE; break; case STATE_PAGEID: if(qName.equals(TAG_PAGEID)) state=STATE_PAGE; break; case STATE_RESTRICTIONS: if(qName.equals(TAG_RESTRICTIONS)) state=STATE_PAGE; break; case STATE_REVISIONID: if(qName.equals(TAG_REVISIONID)) state=STATE_REVISION; break; case STATE_TIMESTAMP: if(qName.equals(TAG_TIMESTAMP)) state=STATE_REVISION; break; case STATE_USERNAME: if(qName.equals(TAG_USERNAME)) state=STATE_CONTRIBUTOR; break; case STATE_CONTRIBUTORID: if(qName.equals(TAG_CONTRIBUTORID)) state=STATE_CONTRIBUTOR; break; case STATE_CONTRIBUTOR: if(qName.equals(TAG_CONTRIBUTOR)){ state=STATE_REVISION; if(data_username!=null) data_contributors.add(data_username.trim()); } break; case STATE_COMMENT: if(qName.equals(TAG_COMMENT)) state=STATE_REVISION; break; case STATE_TEXT: if(qName.equals(TAG_TEXT)) state=STATE_REVISION; break; case STATE_REVISION: if(qName.equals(TAG_REVISION)) { state=STATE_PAGE; int parsedid=Integer.parseInt(data_revisionid); if(parsedid>data_latestrevision){ data_latestrevision=parsedid; data_latesttext=data_text; data_latesttimestamp=data_timestamp; } } break; case STATE_PAGE: if(qName.equals(TAG_PAGE)) { state=STATE_MEDIAWIKI; try{ Topic t=tm.createTopic(); if(data_sitename!=null && data_pageid!=null) { t.addSubjectIdentifier(tm.createLocator(url)); t.addSubjectIdentifier(tm.createLocator(SIPREFIX+"pages/"+data_sitename+"/"+data_pageid)); } else { t.addSubjectIdentifier(tm.makeSubjectIndicatorAsLocator()); } if(data_title!=null) t.setBaseName(data_title.trim()); Topic contributor_type=getOrCreateTopic(CONTRIBUTOR_SI,"Wiki Contributor"); Topic page_type=getOrCreateTopic(PAGE_SI,"MediaWiki page"); Topic text_type=getOrCreateTopic(TEXT_SI,"Wiki content"); Topic wiki_type=getOrCreateTopic(WIKI_SI,"Wiki"); t.addType(page_type); if(data_sitename!=null){ Topic wikiTopic=getOrCreateTopic(null,data_sitename); Association wa=tm.createAssociation(wiki_type); wa.addPlayer(t,page_type); wa.addPlayer(wikiTopic,wiki_type); } for(String contributor : data_contributors){ Topic ct=getOrCreateTopic(null,"Wiki contributor: "+contributor); if(!ct.isOfType(contributor_type)) ct.addType(contributor_type); Association a=tm.createAssociation(contributor_type); a.addPlayer(t,page_type); a.addPlayer(ct,contributor_type); } if(data_latestrevision!=-1){ t.setData(text_type,getOrCreateTopic(XTMPSI.getLang(null)),data_latesttext); t.setData(getOrCreateTopic(TIMESTAMP_SI,"Wiki timestamp"),getOrCreateTopic(XTMPSI.getLang(null)),data_latesttimestamp); if(parent.followRedirects && parent.wikiBaseURL!=null){ Matcher m=redirectPattern.matcher(data_latesttext); if(m.find()){ String page=m.group(1); parent.log("Following redirect to "+page); try{ String reurl=parent.extractTopicsFromWiki(page, tm); if(reurl!=null){ Topic to=tm.getTopic(reurl); if(to!=null){ Topic redirect_type=getOrCreateTopic(REDIRECT_SI,"Redirect"); Topic from_type=getOrCreateTopic(REDIRECT_FROM_SI,"Redirect from"); Topic to_type=getOrCreateTopic(REDIRECT_TO_SI,"Redirect to"); Association a=tm.createAssociation(redirect_type); a.addPlayer(t, from_type); a.addPlayer(to, to_type); } } }catch(Exception e){ parent.log(e); } } } } }catch(TopicMapException tme){ parent.log(tme); } } break; case STATE_MEDIAWIKI: break; } } public void characters(char[] ch, int start, int length) throws SAXException { switch(state){ case STATE_SITENAME: data_sitename+=new String(ch,start,length); break; case STATE_BASE: data_base+=new String(ch,start,length); break; case STATE_NAMESPACE: data_namespace+=new String(ch,start,length); break; case STATE_TITLE: data_title+=new String(ch,start,length); break; case STATE_PAGEID: data_pageid+=new String(ch,start,length); break; case STATE_RESTRICTIONS: data_restrictions+=new String(ch,start,length); break; case STATE_REVISIONID: data_revisionid+=new String(ch,start,length); break; case STATE_TIMESTAMP: data_timestamp+=new String(ch,start,length); break; case STATE_USERNAME: data_username+=new String(ch,start,length); break; case STATE_CONTRIBUTORID: data_contributorid+=new String(ch,start,length); break; case STATE_TEXT: data_text+=new String(ch,start,length); break; } } public void warning(SAXParseException exception) throws SAXException { } public void error(SAXParseException exception) throws SAXException { parent.log("Error parsing XML document at "+exception.getLineNumber()+","+exception.getColumnNumber(),exception); } public void fatalError(SAXParseException exception) throws SAXException { parent.log("Fatal error parsing XML document at "+exception.getLineNumber()+","+exception.getColumnNumber(),exception); } public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {} public void processingInstruction(String target, String data) throws SAXException {} public void startPrefixMapping(String prefix, String uri) throws SAXException {} public void endPrefixMapping(String prefix) throws SAXException {} public void setDocumentLocator(org.xml.sax.Locator locator) {} public void skippedEntity(String name) throws SAXException {} } public static final String[] contentTypes=new String[] { "application/xml" }; @Override public String[] getContentTypes() { return contentTypes; } }
24,508
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
WikipediaExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/WikipediaExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * */ package org.wandora.application.tools.extractors; import javax.swing.Icon; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.WandoraToolType; import org.wandora.application.contexts.Context; import org.wandora.application.gui.UIBox; import org.wandora.application.tools.AbstractWandoraTool; /** * * @author akivela */ public class WikipediaExtractor extends AbstractWandoraTool { private static final long serialVersionUID = 1L; private static WikipediaExtractorSelector selector = null; /** Creates a new instance of WikipediaExtractor */ public WikipediaExtractor() { } @Override public String getName() { return "Wikipedia extractor"; } @Override public String getDescription(){ return "Extracts text and metadata from Wikipedia."; } @Override public WandoraToolType getType() { return WandoraToolType.createExtractType(); } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_wikipedia.png"); } @Override public void execute(Wandora wandora, Context context) { try { if(selector == null) { selector = new WikipediaExtractorSelector(wandora); } selector.setWandora(wandora); selector.setContext(context); selector.selectAll(); selector.setVisible(true); setDefaultLogger(); if(selector.wasAccepted()) { WandoraTool extractor = selector.getWandoraTool(this); if(extractor != null) { extractor.setToolLogger(getDefaultLogger()); extractor.execute(wandora, context); } } else { log("User cancelled the extraction!"); } } catch(Exception e) { singleLog(e); } if(selector != null && selector.wasAccepted()) setState(WAIT); } }
2,904
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
WikipediaExtractorSelector.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/WikipediaExtractorSelector.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * WikipediaExtractorSelector.java * * Created on 16.7.2008, 21:26 */ package org.wandora.application.tools.extractors; import java.awt.Component; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Iterator; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.topicmap.Topic; /** * * @author akivela */ public class WikipediaExtractorSelector extends javax.swing.JDialog { private static final long serialVersionUID = 1L; private boolean accepted = false; private Wandora wandora = null; private Context context = null; /** Creates new form WikipediaExtractorSelector */ public WikipediaExtractorSelector(Wandora wandora) { super(wandora, true); initComponents(); setSize(450,300); setTitle("Wikipedia extractor"); wandora.centerWindow(this); this.wandora = wandora; accepted = false; } public void setWandora(Wandora wandora) { this.wandora = wandora; } public void setContext(Context context) { this.context = context; } public void selectAll() { termsTextPane.selectAll(); } public boolean wasAccepted() { return accepted; } public WandoraTool getWandoraTool(WandoraTool parentTool) { Component component = tabbedPane.getSelectedComponent(); WandoraTool wt = null; // ***** TERMS ******* if(termsPanel.equals(component)) { String termText = termsTextPane.getText(); String lang = langField.getText(); if(lang != null) { lang = lang.trim(); if(lang.length() == 0) lang = "en"; } String[] terms = encode(termSplitter(termText)); String base = "http://"+lang+".wikipedia.org/wiki/Special:Export/__1__"; String[] termUrls = completeString(base, terms); MediaWikiExtractor ex = new MediaWikiExtractor(); ex.setForceUrls(termUrls); ex.setWikiBaseURL(base); ex.setFollowRedirects(redirectsCheckBox.isSelected()); wt = ex; } return wt; } public String[] termSplitter(String str) { String[] strs=str.split(",|\n"); ArrayList<String> ret=new ArrayList<String>(); for(int i=0;i<strs.length;i++){ strs[i]=strs[i].trim(); if(strs[i].length()>0) ret.add(strs[i]); } return ret.toArray(new String[ret.size()]); /* if(str.indexOf(',') != -1) { String[] strs = str.split(","); ArrayList<String> strList = new ArrayList<String>(); String s = null; for(int i=0; i<strs.length; i++) { s = strs[i]; s = s.trim(); if(s.indexOf('\n') != -1) { String[] strs2 = s.split("\n"); for(int j=0; j<strs2.length; j++) { s = strs[j]; s = s.trim(); if(s.length() > 0) { strList.add(s); } } } else { if(s.length() > 0) { strList.add(s); } } } return strList.toArray( new String[] {} ); } else { return new String[] { str }; } */ } public String[] completeString(String template, String[] strs) { if(strs == null || template == null) return null; String[] completed = new String[strs.length]; for(int i=0; i<strs.length; i++) { completed[i] = template.replaceAll("__1__", strs[i]); } return completed; } public String[] completeString(String template, String[] strs1, String[] strs2) { if(strs1 == null || strs2 == null || template == null) return null; if(strs1.length != strs2.length) return null; String[] completed = new String[strs1.length]; for(int i=0; i<strs1.length; i++) { completed[i] = template.replaceAll("__1__", strs1[i]); completed[i] = completed[i].replaceAll("__2__", strs2[i]); } return completed; } public String[] encode(String[] urls) { if(urls == null) return null; String[] cleanUrls = new String[urls.length]; for(int i=0; i<urls.length; i++) { cleanUrls[i] = urlEncode(urls[i]); } return cleanUrls; } public String urlEncode(String url) { try { if(url != null) url = url.replaceAll(" ", "_"); // Wikipedia terms contains underscores instead of spaces! return URLEncoder.encode(url, "UTF-8"); } catch(Exception e) { return url; } } public String getContextAsString() { StringBuffer sb = new StringBuffer(""); if(context != null) { try { Iterator contextObjects = context.getContextObjects(); String str = null; Object o = null; while(contextObjects.hasNext()) { str = null; o = contextObjects.next(); if(o instanceof Topic) { Topic t = (Topic) o; String lang = langField.getText(); if(lang == null || lang.trim().length() == 0) lang = "en"; str = t.getDisplayName(lang); if(str != null) { str = str.trim(); } } if(str != null && str.length() > 0) { sb.append(str); if(contextObjects.hasNext()) { sb.append(", "); } } } } catch(Exception e) { e.printStackTrace(); } } return sb.toString(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; contextPanel = new javax.swing.JPanel(); contextPanelInner = new javax.swing.JPanel(); contextLabel = new org.wandora.application.gui.simple.SimpleLabel(); contextCheckBox1 = new org.wandora.application.gui.simple.SimpleCheckBox(); contextCheckBox2 = new org.wandora.application.gui.simple.SimpleCheckBox(); tabContainerPanel = new javax.swing.JPanel(); tabbedPane = new org.wandora.application.gui.simple.SimpleTabbedPane(); termsPanel = new javax.swing.JPanel(); termsLabel = new org.wandora.application.gui.simple.SimpleLabel(); jScrollPane1 = new javax.swing.JScrollPane(); termsTextPane = new org.wandora.application.gui.simple.SimpleTextPane(); getButtonPanel = new javax.swing.JPanel(); getTermNameButton = new org.wandora.application.gui.simple.SimpleButton(); buttonPanel = new javax.swing.JPanel(); languagePanel = new javax.swing.JPanel(); langLabel = new org.wandora.application.gui.simple.SimpleLabel(); langField = new org.wandora.application.gui.simple.SimpleField(); redirectsCheckBox = new javax.swing.JCheckBox(); okButton = new org.wandora.application.gui.simple.SimpleButton(); cancelButton = new org.wandora.application.gui.simple.SimpleButton(); contextPanel.setOpaque(false); contextPanel.setVisible(false); contextPanel.setLayout(new java.awt.GridBagLayout()); contextPanelInner.setLayout(new java.awt.GridBagLayout()); contextLabel.setText("jLabel1"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; contextPanelInner.add(contextLabel, gridBagConstraints); contextCheckBox1.setText("jCheckBox1"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 0, 0, 0); contextPanelInner.add(contextCheckBox1, gridBagConstraints); contextCheckBox2.setText("jCheckBox2"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; contextPanelInner.add(contextCheckBox2, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; contextPanel.add(contextPanelInner, gridBagConstraints); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); getContentPane().setLayout(new java.awt.GridBagLayout()); tabContainerPanel.setLayout(new java.awt.BorderLayout()); termsPanel.setLayout(new java.awt.GridBagLayout()); termsLabel.setText("<html>This tab is used to specify Wikipedia terms to be extracted. Write terms into the text field below. Or use pick up buttons to get context terms. Use comma (,) or newline character to separate different terms.</html>"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5); termsPanel.add(termsLabel, gridBagConstraints); jScrollPane1.setViewportView(termsTextPane); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5); termsPanel.add(jScrollPane1, gridBagConstraints); getButtonPanel.setLayout(new java.awt.GridBagLayout()); getTermNameButton.setText("Get context names"); getTermNameButton.setToolTipText("Copies names of selected topics in Wandora to the text area above."); getTermNameButton.setMargin(new java.awt.Insets(2, 2, 2, 2)); getTermNameButton.setMaximumSize(new java.awt.Dimension(130, 23)); getTermNameButton.setMinimumSize(new java.awt.Dimension(130, 23)); getTermNameButton.setPreferredSize(new java.awt.Dimension(130, 21)); getTermNameButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { getTermNameButtonActionPerformed(evt); } }); getButtonPanel.add(getTermNameButton, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); termsPanel.add(getButtonPanel, gridBagConstraints); tabbedPane.addTab("Terms", termsPanel); tabContainerPanel.add(tabbedPane, java.awt.BorderLayout.CENTER); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; getContentPane().add(tabContainerPanel, gridBagConstraints); buttonPanel.setLayout(new java.awt.GridBagLayout()); languagePanel.setLayout(new java.awt.GridBagLayout()); langLabel.setText("Language"); langLabel.setToolTipText("Language assigns the Wikipedia version used to extract."); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4); languagePanel.add(langLabel, gridBagConstraints); langField.setHorizontalAlignment(javax.swing.JTextField.CENTER); langField.setText("en"); langField.setPreferredSize(new java.awt.Dimension(40, 21)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); languagePanel.add(langField, gridBagConstraints); buttonPanel.add(languagePanel, new java.awt.GridBagConstraints()); redirectsCheckBox.setSelected(true); redirectsCheckBox.setText("Follow redirects"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 0); buttonPanel.add(redirectsCheckBox, gridBagConstraints); okButton.setText("Extract"); okButton.setMargin(new java.awt.Insets(2, 2, 2, 2)); okButton.setMaximumSize(new java.awt.Dimension(70, 23)); okButton.setMinimumSize(new java.awt.Dimension(70, 23)); okButton.setPreferredSize(new java.awt.Dimension(70, 23)); okButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { okButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3); buttonPanel.add(okButton, gridBagConstraints); cancelButton.setText("Cancel"); cancelButton.setMargin(new java.awt.Insets(2, 2, 2, 2)); cancelButton.setMaximumSize(new java.awt.Dimension(70, 23)); cancelButton.setMinimumSize(new java.awt.Dimension(70, 23)); cancelButton.setPreferredSize(new java.awt.Dimension(70, 23)); cancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelButtonActionPerformed(evt); } }); buttonPanel.add(cancelButton, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); getContentPane().add(buttonPanel, gridBagConstraints); pack(); }// </editor-fold>//GEN-END:initComponents private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed accepted = true; setVisible(false); }//GEN-LAST:event_okButtonActionPerformed private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed accepted = false; setVisible(false); }//GEN-LAST:event_cancelButtonActionPerformed private void getTermNameButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_getTermNameButtonActionPerformed termsTextPane.setText(getContextAsString()); }//GEN-LAST:event_getTermNameButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel buttonPanel; private javax.swing.JButton cancelButton; private javax.swing.JCheckBox contextCheckBox1; private javax.swing.JCheckBox contextCheckBox2; private javax.swing.JLabel contextLabel; private javax.swing.JPanel contextPanel; private javax.swing.JPanel contextPanelInner; private javax.swing.JPanel getButtonPanel; private javax.swing.JButton getTermNameButton; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextField langField; private javax.swing.JLabel langLabel; private javax.swing.JPanel languagePanel; private javax.swing.JButton okButton; private javax.swing.JCheckBox redirectsCheckBox; private javax.swing.JPanel tabContainerPanel; private javax.swing.JTabbedPane tabbedPane; private javax.swing.JLabel termsLabel; private javax.swing.JPanel termsPanel; private javax.swing.JTextPane termsTextPane; // End of variables declaration//GEN-END:variables }
18,166
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
GellishExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/GellishExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * GellishExtractor.java * * Created on 12. huhtikuuta 2009, 18:08 * */ package org.wandora.application.tools.extractors; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.InputStreamReader; import java.io.StringReader; import java.net.URL; import java.net.URLEncoder; import java.util.Collection; import java.util.Iterator; import org.wandora.application.WandoraTool; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.XTMPSI; /** * * @author akivela */ public class GellishExtractor extends AbstractExtractor implements WandoraTool { private static final long serialVersionUID = 1L; public String locatorPrefix = "http://wandora.org/si/gellish/"; public static String DEFAULT_LANG = "en"; public static boolean EXTRACT_EXTRAS = true; public static boolean REMOVE_SPACES_IN_IDS = true; public static boolean CONNECT_TO_WANDORA_CLASS = true; /** Creates a new instance of GellishExtractor */ public GellishExtractor() { } @Override public String getName() { return "Gellish ontology extractor"; } @Override public String getDescription() { return "Convert tab text formatted Gellish ontologies to Topic Maps."; } public String getGUIText(int textType) { switch(textType) { case SELECT_DIALOG_TITLE: return "Select Gellish ontology file(s) or directories containing Gellish ontology files!"; case POINT_START_URL_TEXT: return "Where would you like to start the crawl?"; case INFO_WAIT_WHILE_WORKING: return "Wait while seeking Gellish ontology files!"; case FILE_PATTERN: return ".*"; case DONE_FAILED: return "Ready. No extractions! %1 Gellish ontology file(s) processed!"; case DONE_ONE: return "Ready. Successful extraction! %1 Gellish ontology file(s) processed!"; case DONE_MANY: return "Ready. Total %0 successful extractions! %1 Gellish ontology file(s) processed!"; case LOG_TITLE: return "Gellish ontology extraction Log"; } return ""; } public boolean _extractTopicsFrom(String str, TopicMap topicMap) throws Exception { boolean answer = _extractTopicsFrom(new BufferedReader(new StringReader(str)), topicMap); return answer; } public boolean _extractTopicsFrom(URL url, TopicMap topicMap) throws Exception { if(url == null) return false; BufferedReader urlReader = new BufferedReader( new InputStreamReader ( url.openStream() ) ); return _extractTopicsFrom(urlReader, topicMap); } public boolean _extractTopicsFrom(File thesaurusFile, TopicMap topicMap) throws Exception { boolean result = false; BufferedReader breader = null; try { if(thesaurusFile == null) { log("No Gellish ontology file addressed!"); return false; } FileReader fr = new FileReader(thesaurusFile); breader = new BufferedReader(fr); result = _extractTopicsFrom(breader, topicMap); } finally { if(breader != null) breader.close(); } return result; } public boolean _extractTopicsFrom(BufferedReader breader, TopicMap topicMap) throws Exception { int factCounter = 0; try { Topic associationType = null; Topic leftRole = null; Topic rightRole = null; Topic leftPlayer = null; Topic rightPlayer = null; Topic extraPlayer = null; Topic associationTypeClass = null; Topic termClass = null; Topic relationType = null; Topic relationTypeClass = null; String leftPlayerId; String rightPlayerId; String leftPlayerName; String rightPlayerName; String associationTypeId; String associationTypeName; String extraPlayerId; String disciplineId; String discipline; String definition; String fullDefinition; String remarks; String status; String dateOfStart; String dateOfChange; String signature; String referenceSource; String collectionName; String line = ""; Association association = null; String[] tokens; line = breader.readLine(); while(line != null && !forceStop()) { tokens = line.split("\t"); if(tokens.length > 12) { factCounter++; for(int i=0; i<tokens.length; i++) { if(tokens[i] != null) tokens[i] = tokens[i].trim(); } leftPlayerId = getToken(4, tokens); leftPlayerName = getToken(6, tokens); extraPlayerId = getToken(7, tokens); associationTypeId = getToken(8, tokens); associationTypeName = getToken(9, tokens); rightPlayerId = getToken(10, tokens); rightPlayerName = getToken(12, tokens); disciplineId = getToken(2, tokens); discipline = getToken(3, tokens); definition = getToken(13, tokens); fullDefinition = getToken(14, tokens); remarks = getToken(17, tokens); status = getToken(18, tokens); dateOfStart = getToken(20, tokens); dateOfChange = getToken(21, tokens); signature = getToken(22, tokens); referenceSource = getToken(23, tokens); collectionName = getToken(24, tokens); if(REMOVE_SPACES_IN_IDS) { leftPlayerId = removeSpacesIn(leftPlayerId); extraPlayerId = removeSpacesIn(extraPlayerId); associationTypeId = removeSpacesIn(associationTypeId); rightPlayerId = removeSpacesIn(rightPlayerId); disciplineId = removeSpacesIn(disciplineId); } if(isValid(leftPlayerId) && isValid(rightPlayerId) && isValid(associationTypeId)) { associationType = getOrCreateTopic(topicMap, makeSI("fact"), "fact (gellish)", "fact"); leftPlayer = getOrCreateConceptTopic(topicMap, leftPlayerId, leftPlayerName); rightPlayer = getOrCreateConceptTopic(topicMap, rightPlayerId, rightPlayerName); relationType = getOrCreateTopic(topicMap, makeSI(associationTypeId), associationTypeName+" ("+associationTypeId+")", associationTypeName); leftRole = getOrCreateTopic(topicMap, makeSI("meta/", "left-hand-object"), "left-hand-object (gellish)", "left-hand-object"); rightRole = getOrCreateTopic(topicMap, makeSI("meta/", "right-hand-object"), "right-hand-object (gellish)", "right-hand-object"); relationTypeClass = getOrCreateTopic(topicMap, makeSI("meta/", "relation-type"), "relation-type (gellish)", "relation-type"); relationType.addType(relationTypeClass); makeSubclassOfGellish(topicMap, relationTypeClass); termClass = getOrCreateTopic(topicMap, makeSI("meta/", "gellish-concept"), "gellish-concept (gellish)", "gellish-concept"); leftPlayer.addType(termClass); rightPlayer.addType(termClass); makeSubclassOfGellish(topicMap, termClass); association = topicMap.createAssociation(associationType); association.addPlayer(leftPlayer, leftRole); association.addPlayer(rightPlayer, rightRole); association.addPlayer(relationType, relationTypeClass); if(EXTRACT_EXTRAS) { if(isValid(extraPlayerId)) { Topic factTopic = getOrCreateTopic(topicMap, makeSI("fact"), "fact (gellish)", "fact"); extraPlayer = getOrCreateTopic(topicMap, makeSI("fact/",extraPlayerId), "fact "+extraPlayerId, null); extraPlayer.addType(factTopic); association.addPlayer(extraPlayer, factTopic); if(isValid(definition)) { Topic definitionType = getOrCreateTopic(topicMap, makeSI("meta/", "definition"), "definition (gellish)", "definition"); Topic definitionLan = getOrCreateTopic(topicMap, XTMPSI.getLang("en"), null, null); extraPlayer.setData(definitionType, definitionLan, definition); } if(isValid(fullDefinition)) { Topic definitionType = getOrCreateTopic(topicMap, makeSI("meta/", "full-definition"), "full-definition (gellish)", "full-definition"); Topic definitionLan = getOrCreateTopic(topicMap, XTMPSI.getLang("en"), null, null); extraPlayer.setData(definitionType, definitionLan, fullDefinition); } if(isValid(dateOfStart)) { Topic dateOfStartType = getOrCreateTopic(topicMap, makeSI("meta/", "date-of-start"), "date-of-start (gellish)", "date-of-start"); Topic dateOfStartTopic = getOrCreateTopic(topicMap, makeSI("meta/date/",dateOfStart), dateOfStart, dateOfStart); Topic dateTopic = getOrCreateTopic(topicMap, makeSI("meta", "date"), "date (meta)", "date"); dateOfStartTopic.addType(dateTopic); Association dateAssociation = topicMap.createAssociation(dateOfStartType); dateAssociation.addPlayer(dateOfStartTopic, dateTopic); dateAssociation.addPlayer(extraPlayer, factTopic); makeSubclassOfGellish(topicMap, dateTopic); } if(isValid(dateOfChange)) { Topic dateOfChangeType = getOrCreateTopic(topicMap, makeSI("meta/", "date-of-change"), "date-of-change (gellish)", "date-of-change"); Topic dateOfChangeTopic = getOrCreateTopic(topicMap, makeSI("meta/date/",dateOfChange), dateOfChange, dateOfChange); Topic dateTopic = getOrCreateTopic(topicMap, makeSI("meta", "date"), "date (meta)", "date"); dateOfChangeTopic.addType(dateTopic); Association dateAssociation = topicMap.createAssociation(dateOfChangeType); dateAssociation.addPlayer(dateOfChangeTopic, dateTopic); dateAssociation.addPlayer(extraPlayer, factTopic); } if(isValid(signature)) { Topic signatureType = getOrCreateTopic(topicMap, makeSI("meta/", "signature"), "signature (gellish)", "signature"); Topic signatureTopic = getOrCreateTopic(topicMap, makeSI("meta/signature/",signature), signature, signature); signatureTopic.addType(signatureType); Association signatureAssociation = topicMap.createAssociation(signatureType); signatureAssociation.addPlayer(signatureTopic, signatureType); signatureAssociation.addPlayer(extraPlayer, factTopic); makeSubclassOfGellish(topicMap, signatureType); } if(isValid(referenceSource)) { Topic referenceType = getOrCreateTopic(topicMap, makeSI("meta/", "reference"), "reference (gellish)", "reference"); Topic referenceTopic = getOrCreateTopic(topicMap, makeSI("meta/reference/",referenceSource), referenceSource, referenceSource); referenceTopic.addType(referenceType); Association referenceAssociation = topicMap.createAssociation(referenceType); referenceAssociation.addPlayer(referenceTopic, referenceType); referenceAssociation.addPlayer(extraPlayer, factTopic); makeSubclassOfGellish(topicMap, referenceType); } if(isValid(collectionName)) { Topic collectionType = getOrCreateTopic(topicMap, makeSI("meta/", "collection"), "collection (gellish)", "collection"); Topic collectionTopic = getOrCreateTopic(topicMap, makeSI("meta/collection/",collectionName), collectionName, collectionName); collectionTopic.addType(collectionType); Association collectionAssociation = topicMap.createAssociation(collectionType); collectionAssociation.addPlayer(collectionTopic, collectionType); collectionAssociation.addPlayer(extraPlayer, factTopic); makeSubclassOfGellish(topicMap, collectionType); } if(isValid(status)) { Topic statusType = getOrCreateTopic(topicMap, makeSI("meta/", "status"), "status (gellish)", "status"); Topic statusTopic = getOrCreateTopic(topicMap, makeSI("meta/status/",status), status, status); statusTopic.addType(statusType); Association statusAssociation = topicMap.createAssociation(statusType); statusAssociation.addPlayer(statusTopic, statusType); statusAssociation.addPlayer(extraPlayer, factTopic); makeSubclassOfGellish(topicMap, statusType); } if(isValid(discipline)) { Topic disciplineType = getOrCreateTopic(topicMap, makeSI("meta/", "discipline"), "discipline (gellish)", "discipline"); Topic disciplineTopic = getOrCreateTopic(topicMap, makeSI("meta/discipline/",disciplineId), discipline+" ("+disciplineId+")", discipline); disciplineTopic.addType(disciplineType); Association disciplineAssociation = topicMap.createAssociation(disciplineType); disciplineAssociation.addPlayer(disciplineTopic, disciplineType); disciplineAssociation.addPlayer(extraPlayer, factTopic); makeSubclassOfGellish(topicMap, disciplineType); } if(isValid(remarks)) { Topic remarksType = getOrCreateTopic(topicMap, makeSI("meta/", "remarks"), "remarks (gellish)", "remarks"); Topic remarksLan = getOrCreateTopic(topicMap, XTMPSI.getLang("en"), null, null); extraPlayer.setData(remarksType, remarksLan, remarks); } } } } } else { log("Rejecting input line as it does not contain enough tokens: "+line); } setProgress(factCounter); line = breader.readLine(); } if(CONNECT_TO_WANDORA_CLASS) { // Finally connect Gellish class to Wandora class makeSubclassOf(topicMap, getGellishClassTopic(topicMap), getOrCreateTopic(topicMap, new Locator(TMBox.WANDORACLASS_SI), null, null)); } } catch(Exception e) { log(e); } log("Found total "+factCounter+" facts"); return true; } protected String getToken(int i, String[] arr) { if(arr.length > i) return arr[i]; else return null; } protected boolean isValid(String str) { if(str == null || str.length() == 0) return false; return true; } protected String removeSpacesIn(String str) { if(str == null) return null; StringBuffer sb = new StringBuffer(""); char ch = 0; for(int i=0; i<str.length(); i++) { ch = str.charAt(i); if("0123456789".indexOf(ch) != -1) { sb.append(ch); } } return sb.toString(); } protected boolean associationExists(Topic t1, Topic t2, Topic at) { if(t1 == null || t2 == null || at == null) return false; try { Collection<Association> c = t1.getAssociations(at); Association a = null; Collection<Topic> roles = null; Topic player = null; for(Iterator<Association> i=c.iterator(); i.hasNext(); ) { a = i.next(); roles = a.getRoles(); for(Iterator<Topic> it = roles.iterator(); it.hasNext(); ) { player = a.getPlayer(it.next()); if(player != null && t2.mergesWithTopic(player)) return true; } } } catch(Exception e) { e.printStackTrace(); } return false; } protected Topic getOrCreateConceptTopic(TopicMap tm, String id, String name) { int count = -1; String newIdPostfix = null; Topic existingTopic = null; boolean nameFound = false; String existingName = null; try { do { count++; newIdPostfix = "#" + count; existingTopic = tm.getTopic(makeSI(null, id, newIdPostfix)); if(existingTopic != null) { existingName = existingTopic.getDisplayName(DEFAULT_LANG); if(existingName != null && existingName.equals(name)) { nameFound = true; } } } while(!nameFound && existingTopic != null && count < 9999); } catch(Exception e) { log(e); } if(nameFound) { return existingTopic; } else { Topic newTopic = getOrCreateTopic(tm, makeSI(null, id, newIdPostfix), name+" ("+id+newIdPostfix+")", name); return newTopic; } } protected Topic getOrCreateTopic(TopicMap topicmap, String si, String baseName, String displayName) { return getOrCreateTopic(topicmap, new Locator(si), baseName, displayName, null); } protected Topic getOrCreateTopic(TopicMap topicmap, Locator si, String baseName, String displayName) { return getOrCreateTopic(topicmap, si, baseName, displayName, null); } protected Topic getOrCreateTopic(TopicMap topicmap, Locator si, String baseName, String displayName, Topic typeTopic) { try { return ExtractHelper.getOrCreateTopic(si, baseName, displayName, typeTopic, topicmap); } catch(Exception e) { log(e); } return null; } protected Locator makeSI(String str) { return makeSI(null, str, null); } protected Locator makeSI(String prefix, String str) { return makeSI(prefix, str, null); } protected Locator makeSI(String prefix, String str, String postfix) { if(str == null) return null; if(str.startsWith("http://")) { return new Locator( str ); } else { try { return new Locator( locatorPrefix + (prefix != null ? prefix : "") + URLEncoder.encode(str, "UTF-8") + (postfix != null ? postfix : "") ); } catch(Exception e) { return new Locator( locatorPrefix + (prefix != null ? prefix : "") + str + (postfix != null ? postfix : "") ); } } } protected void makeSubclassOfGellish(TopicMap tm, Topic subclass) throws TopicMapException { makeSubclassOf(tm, subclass, getGellishClassTopic(tm)); } protected void makeSubclassOf(TopicMap tm, Topic t, Topic superclass) throws TopicMapException { ExtractHelper.makeSubclassOf(t, superclass, tm); } protected Topic getGellishClassTopic(TopicMap tm) throws TopicMapException { return getOrCreateTopic(tm, new Locator(locatorPrefix), "Gellish class", null); } @Override public boolean useTempTopicMap() { return false; } }
23,316
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
FreeDBExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/FreeDBExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * FreeDBExtractor.java * * Created on 5. maaliskuuta 2007, 12:39 * */ package org.wandora.application.tools.extractors; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; import java.net.URL; import java.net.URLConnection; import java.util.Hashtable; import javax.swing.Icon; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.gui.UIBox; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicTools; /** * * * * @author akivela */ public class FreeDBExtractor extends AbstractExtractor implements WandoraTool { private static final long serialVersionUID = 1L; public String locatorPrefix = "http://wandora.org/si/freedb/"; /** Creates a new instance of ExtractIconclassKeywords */ public FreeDBExtractor() { } @Override public String getName() { return "FreeDB extractor"; } @Override public String getDescription() { return "Extract FreeDB database entries."; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_freedb.png"); } @Override public String[] getContentTypes() { return new String[]{"text/plain"}; } @Override public String getGUIText(int textType) { switch(textType) { case SELECT_DIALOG_TITLE: return "Select FreeDB data file(s) or directories containing FreeDB data files!"; case POINT_START_URL_TEXT: return "Where would you like to start the crawl?"; case INFO_WAIT_WHILE_WORKING: return "Wait while seeking FreeDB data files!"; case FILE_PATTERN: return ".*"; case DONE_FAILED: return "Ready. No extractions! %1 FreeDB data file(s) and %2 other file(s) crawled!"; case DONE_ONE: return "Ready. Successful extraction! %1 FreeDB data file(s) and %2 other file(s) crawled!"; case DONE_MANY: return "Ready. Total %0 successful extractions! %1 FreeDB data file(s) and %2 other files crawled!"; case LOG_TITLE: return "FreeDB Extraction Log"; } return ""; } public boolean _extractTopicsFrom(String str, TopicMap topicMap) throws Exception { boolean answer = _extractTopicsFrom(new BufferedReader(new StringReader(str)), topicMap); return answer; } public boolean _extractTopicsFrom(URL url, TopicMap topicMap) throws Exception { if(url == null) return false; URLConnection uc=url.openConnection(); Wandora.initUrlConnection(uc); String enc=uc.getContentEncoding(); if(enc==null) enc="ISO-8859-1"; BufferedReader urlReader = new BufferedReader( new InputStreamReader ( uc.getInputStream(),enc ) ); return _extractTopicsFrom(urlReader, topicMap); } public boolean _extractTopicsFrom(File keywordFile, TopicMap topicMap) throws Exception { boolean result = false; BufferedReader breader = null; try { if(keywordFile == null) { log("No FreeDB data file addressed! Using default file name 'freedb.txt'!"); keywordFile = new File("freedb.txt"); } Reader r=new InputStreamReader(new FileInputStream(keywordFile),"ISO-8859-1"); // FileReader fr = new FileReader(keywordFile); // breader = new BufferedReader(fr); breader = new BufferedReader(r); result = _extractTopicsFrom(breader, topicMap); } finally { if(breader != null) breader.close(); } return result; } public boolean _extractTopicsFrom(BufferedReader breader, TopicMap topicMap) throws Exception { int discCounter = 0; try { Topic discType = getOrCreateTopic(topicMap, makeSI("disc"), "Disc (freedb)", null); Topic yearType = getOrCreateTopic(topicMap, makeSI("year"), "Year (freedb)", null); Topic genreType = getOrCreateTopic(topicMap, makeSI("genre"), "Genre (freedb)", null); Topic trackType = getOrCreateTopic(topicMap, makeSI("track"), "Track (freedb)", null); Topic orderType = getOrCreateTopic(topicMap, makeSI("order"), "Order (freedb)", null); Topic artistType = getOrCreateTopic(topicMap, makeSI("artist"), "Artist (freedb)", null); Topic lengthType = getOrCreateTopic(topicMap, makeSI("length"), "Length (freedb)", null); Topic processedType = getOrCreateTopic(topicMap, makeSI("processedby"), "ProcessedBy (freedb)", null); Topic submittedType = getOrCreateTopic(topicMap, makeSI("submittedvia"), "SubmittedVia (freedb)", null); Topic idType = getOrCreateTopic(topicMap, makeSI("freedb_id"), "id (freedb)", null); String line = ""; String discId = null; String discTitle = null; String discYear = null; Topic discYearTopic = null; String discGenre = null; Topic discGenreTopic = null; String trackData = null; String trackName = null; Topic trackTopic = null; String extraData = null; String discBasename = null; Topic discTopic = null; String artistName = null; Topic artistTopic = null; Association association = null; Hashtable players = null; int dtitleCount = 0; String discLength = null; Topic lengthTopic = null; String processedBy = null; Topic processedByTopic = null; String submittedVia = null; Topic submittedViaTopic = null; line = breader.readLine(); while(line != null && !forceStop()) { if(line.startsWith("# Disc length: ")) { discLength = line.substring(15); } else if(line.startsWith("# Processed by: ")) { processedBy = line.substring(16); } else if(line.startsWith("# Submitted via: ")) { submittedVia = line.substring(17); } else if(line.startsWith("DISCID=")) { discTopic = null; try { discId = line.substring(7); discTopic = getOrCreateTopic(topicMap, makeSI("disc/" + discId), null, null, discType); setData(discTopic, idType, "en", discId); if(discLength != null) { lengthTopic = getOrCreateTopic(topicMap, makeSI("length/" + discLength), discLength+" (length)", discLength, lengthType); if(lengthTopic != null) { players = new Hashtable(); players.put(discType, discTopic); players.put(lengthType, lengthTopic); association = topicMap.createAssociation(lengthType); association.addPlayers(players); } discLength = null; } if(processedBy != null) { processedByTopic = getOrCreateTopic(topicMap, makeSI("processedby/" + processedBy), processedBy+" (processedby)", processedBy, processedType); if(processedByTopic != null) { players = new Hashtable(); players.put(discType, discTopic); players.put(processedType, processedByTopic); association = topicMap.createAssociation(processedType); association.addPlayers(players); } processedBy = null; } if(submittedVia != null) { submittedViaTopic = getOrCreateTopic(topicMap, makeSI("submittedvia/" + submittedVia), submittedVia+" (processedby)", submittedVia, submittedType); if(submittedViaTopic != null) { players = new Hashtable(); players.put(discType, discTopic); players.put(submittedType, submittedViaTopic); association = topicMap.createAssociation(submittedType); association.addPlayers(players); } submittedVia = null; } } catch(Exception e) { log(e); } } else if(line.startsWith("DTITLE=")) { try { if(discTopic != null) { discTitle = line.substring(7).trim(); if(dtitleCount == 0) { if(discTitle != null && discTitle.length() > 0) { int titleDelimiter = discTitle.indexOf(" / "); if(titleDelimiter == -1) titleDelimiter = discTitle.indexOf(" - "); if(titleDelimiter == -1) titleDelimiter = discTitle.indexOf(" : "); if(titleDelimiter > -1) { artistName = discTitle.substring(0, titleDelimiter); if(artistName != null && artistName.length() > 0) { artistTopic = getOrCreateTopic(topicMap, makeSI( "artist/" + artistName ), artistName + " (artist)", artistName, artistType); if(artistTopic != null) { players = new Hashtable(); players.put(discType, discTopic); players.put(artistType, artistTopic); association = topicMap.createAssociation(artistType); association.addPlayers(players); } } discTitle = discTitle.substring(titleDelimiter + 3).trim(); } discTopic.setBaseName(discTitle + " ("+discId+")"); discTopic.setDisplayName("en", discTitle); dtitleCount++; } } else if(dtitleCount > 0) { String oldBasename = discTopic.getBaseName(); String newBasename = oldBasename.substring(0, oldBasename.length() - (" ("+discId+")").length()) + discTitle; discTopic.setBaseName(newBasename + " ("+discId+")"); discTopic.setDisplayName("en", discTopic.getDisplayName("en") + discTitle); } } } catch(Exception e) { log(e); } } else if(line.startsWith("DYEAR=")) { try { if(discTopic != null) { discYear = line.substring(6); if(discYear != null && discYear.length() > 0) { discYearTopic = getOrCreateTopic(topicMap, makeSI("year/"+discYear), discYear+" (year)", discYear, yearType); if(discYearTopic != null) { players = new Hashtable(); players.put(yearType, discYearTopic); players.put(discType, discTopic); association = topicMap.createAssociation(yearType); association.addPlayers(players); } } } } catch(Exception e) { log(e); } } else if(line.startsWith("DGENRE=")) { try { if(discTopic != null) { discGenre = line.substring(7); if(discGenre != null && discGenre.length() > 0) { discGenreTopic = getOrCreateTopic(topicMap, makeSI("genre/"+discGenre), discGenre+" (genre)", discGenre, genreType); if(discGenreTopic != null) { players = new Hashtable(); players.put(genreType, discGenreTopic); players.put(discType, discTopic); association = topicMap.createAssociation(genreType); association.addPlayers(players); } } } } catch(Exception e) { log(e); } } else if(line.startsWith("TTITLE")) { try { if(discTopic != null) { trackData = line.substring(6); if(trackData != null && trackData.length() > 0) { String trackNumber = ""; int i=0; while("0123456789".indexOf(trackData.charAt(i)) > -1) { trackNumber = trackNumber + trackData.charAt(i); i++; } if(trackNumber.length() == 1) trackNumber = "0"+trackNumber; Topic orderTopic = getOrCreateTopic(topicMap, makeSI("order/" + trackNumber), trackNumber + " (order)" , trackNumber, orderType); trackName = trackData.substring(i+1); int trackDelimiter = trackName.indexOf(" / "); if(trackDelimiter == -1) trackDelimiter = trackName.indexOf(" - "); if(trackDelimiter == -1) trackDelimiter = trackName.indexOf(" : "); if(trackDelimiter > -1) { artistName = trackName.substring(0, trackDelimiter); artistTopic = getOrCreateTopic(topicMap, makeSI( "artist/" + artistName ), artistName + " (artist)", artistName, artistType); trackName = trackName.substring(trackDelimiter + 3); } if(trackName != null && trackName.length() > 0) { trackTopic = getOrCreateTopic(topicMap, makeSI("disc/" + discId + "/track/" + trackNumber), trackName + " ("+discId+"/"+trackNumber+")", trackName, trackType ); } if(trackTopic != null && orderTopic != null && discTopic != null && artistTopic != null) { players = new Hashtable(); players.put(trackType, trackTopic); players.put(discType, discTopic); players.put(orderType, orderTopic); players.put(artistType, artistTopic); association = topicMap.createAssociation(trackType); association.addPlayers(players); } } } } catch(Exception e) { log(e); } } //setProgress(discCounter); line = breader.readLine(); } } catch(Exception e) { log(e); } //log("Extracted " + discCounter + " freedb database discs."); return true; } public Topic getOrCreateTopic(TopicMap topicmap, String si, String baseName, String displayName) { return getOrCreateTopic(topicmap, new Locator(si), baseName, displayName, null); } public Topic getOrCreateTopic(TopicMap topicmap, Locator si, String baseName, String displayName) { return getOrCreateTopic(topicmap, si, baseName, displayName, null); } public Topic getOrCreateTopic(TopicMap topicmap, Locator si, String baseName, String displayName, Topic typeTopic) { try { return ExtractHelper.getOrCreateTopic(si, baseName, displayName, typeTopic, topicmap); } catch(Exception e) { log(e); } return null; } public Locator makeSI(String str) { return new Locator( TopicTools.cleanDirtyLocator(locatorPrefix + str) ); } @Override public boolean useTempTopicMap() { return false; } }
19,061
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
JsoupHTMLLinkStructureExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/JsoupHTMLLinkStructureExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * */ package org.wandora.application.tools.extractors; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.wandora.application.WandoraTool; import org.wandora.application.tools.browserextractors.BrowserPluginExtractor; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author Eero */ public class JsoupHTMLLinkStructureExtractor extends AbstractJsoupExtractor implements WandoraTool, BrowserPluginExtractor { private static final long serialVersionUID = 1L; private TopicMap tm; private Topic wandoraClass; private static final String LINK_TYPE = "http://wandora.org/si/link"; private static final String DOC_TYPE = "http://wandora.org/si/document"; @Override public boolean extractTopicsFrom(Document d, String u, TopicMap t) throws Exception { this.tm = t; this.wandoraClass = getWandoraClassTopic(tm); Topic documentType = getOrCreateTopic(tm, DOC_TYPE, "Document"); makeSubclassOf(tm, documentType, wandoraClass); Topic docTopic = getOrCreateTopic(tm, u); docTopic.addType(documentType); Elements links = d.select("a"); for(Element link: links){ try { parseLink(link,docTopic); } catch (TopicMapException tme) { log(tme.getMessage()); } } return true; } private void parseLink(Element link, Topic docTopic) throws TopicMapException { //Get the absolute HREF (if document base URI is specified) String href = link.attr("abs:href").trim(); //Basic validation if(href.length() == 0 || href.indexOf("javascript:") != -1 || href.indexOf("mailto:") != -1) return; Topic linkTopic = getOrCreateTopic(tm, href); linkTopic.setSubjectLocator(new Locator(href)); Topic linkType = getOrCreateTopic(tm, LINK_TYPE, "HTML link"); Topic docType = getOrCreateTopic(tm, DOC_TYPE, "Document"); if(linkType != null) { linkTopic.addType(linkType); makeSubclassOfWandoraClass(linkType, tm); } if(linkType != null && docType != null) { Association a = tm.createAssociation(linkType); a.addPlayer(linkTopic, linkType); a.addPlayer(docTopic, docType); } } }
3,468
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ICalExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/ICalExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.wandora.application.tools.extractors; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.net.URL; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.time.temporal.TemporalAmount; import java.time.temporal.TemporalUnit; import java.util.Calendar; import java.util.Date; import java.util.List; import javax.swing.Icon; import org.wandora.application.WandoraToolType; import org.wandora.application.gui.UIBox; import org.wandora.topicmap.Association; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.XTMPSI; import net.fortuna.ical4j.data.CalendarBuilder; import net.fortuna.ical4j.data.ParserException; import net.fortuna.ical4j.model.Component; import net.fortuna.ical4j.model.ComponentList; import net.fortuna.ical4j.model.Property; import net.fortuna.ical4j.model.component.CalendarComponent; import net.fortuna.ical4j.model.component.VAlarm; import net.fortuna.ical4j.model.component.VEvent; import net.fortuna.ical4j.model.component.VToDo; import net.fortuna.ical4j.model.component.VVenue; import net.fortuna.ical4j.model.property.Action; import net.fortuna.ical4j.model.property.Clazz; import net.fortuna.ical4j.model.property.Description; import net.fortuna.ical4j.model.property.DtEnd; import net.fortuna.ical4j.model.property.DtStamp; import net.fortuna.ical4j.model.property.DtStart; import net.fortuna.ical4j.model.property.Due; import net.fortuna.ical4j.model.property.Duration; import net.fortuna.ical4j.model.property.Geo; import net.fortuna.ical4j.model.property.Location; import net.fortuna.ical4j.model.property.Organizer; import net.fortuna.ical4j.model.property.Priority; import net.fortuna.ical4j.model.property.RecurrenceId; import net.fortuna.ical4j.model.property.Repeat; import net.fortuna.ical4j.model.property.Status; import net.fortuna.ical4j.model.property.Summary; import net.fortuna.ical4j.model.property.Transp; import net.fortuna.ical4j.model.property.Trigger; import net.fortuna.ical4j.model.property.Uid; import net.fortuna.ical4j.model.property.Url; /* * @author * Eero Lehtonen */ public class ICalExtractor extends AbstractExtractor { private static final long serialVersionUID = 1L; public static final String ICAL_SI = "http://tools.ietf.org/html/rfc5545/"; // ****** TYPE SIS FOR GENERAL COMPONENT PROPERTIES ****** public static final String ICAL_CALENDAR_SI = ICAL_SI + "calendar"; public static final String ICAL_VERSION_SI = ICAL_SI + "version"; public static final String ICAL_CALSCALE_SI = ICAL_SI + "calscale"; public static final String ICAL_CAL_TZ_SI = ICAL_SI + "timezone"; public static final String ICAL_NAME_SI = ICAL_SI + "name"; public static final String ICAL_DESCRIPTION_SI = ICAL_SI + "description"; public static final String ICAL_UID_SI = ICAL_SI + "UID"; public static final String ICAL_URL_SI = ICAL_SI + "URL"; public static final String ICAL_LAT_SI = ICAL_SI + "LAT"; public static final String ICAL_LON_SI = ICAL_SI + "LON"; public static final String ICAL_CREATED_SI = ICAL_SI + "created"; public static final String ICAL_MODIFIED_SI = ICAL_SI + "modified"; public static final String ICAL_START_TIME_SI = ICAL_SI + "start-time"; public static final String ICAL_END_TIME_SI = ICAL_SI + "end-time"; public static final String ICAL_SUMMARY_SI = ICAL_SI + "summary"; public static final String ICAL_LOCATION_SI = ICAL_SI + "location"; public static final String ICAL_PRIOR_SI = ICAL_SI + "priority"; public static final String ICAL_CLASS_SI = ICAL_SI + "class"; public static final String ICAL_ORGANIZER_SI = ICAL_SI + "organizer"; public static final String ICAL_STATUS_SI = ICAL_SI + "status"; public static final String ICAL_RECURRENCE_SI = ICAL_SI + "recurrenceID"; public static final String ICAL_CAT_SI = ICAL_SI + "categories"; public static final String ICAL_DATE_SI = ICAL_SI + "date"; // ****** TYPE SIS FOR EVENT SPECIFIC PROPERTIES ****** public static final String ICAL_EVENT_SI = ICAL_SI + "event/"; public static final String ICAL_TRANSP_SI = ICAL_EVENT_SI + "transparency"; // ****** TYPE SIS FOR VENUE SPECIFIC PROPERTIES ****** public static final String ICAL_VENUE_SI = ICAL_SI + "venue/"; public static final String ICAL_STADDR_SI = ICAL_VENUE_SI + "street-address"; public static final String ICAL_EXTADDR_SI = ICAL_VENUE_SI + "extended-address"; public static final String ICAL_LOCALITY_SI = ICAL_VENUE_SI + "locality"; public static final String ICAL_REGION_SI = ICAL_VENUE_SI + "region"; public static final String ICAL_COUNTRY_SI = ICAL_VENUE_SI + "country"; public static final String ICAL_POSTALCODE_SI = ICAL_VENUE_SI + "postal-code"; public static final String ICAL_TZID_SI = ICAL_VENUE_SI + "tzid"; public static final String ICAL_LOCTYPE_SI = ICAL_VENUE_SI + "location-type"; // ****** TYPE SIS FOR ALARM SPECIFIC PROPERTIES ****** public static final String ICAL_ALARM_SI = ICAL_SI + "alarm/"; public static final String ICAL_TRIGGER_SI = ICAL_ALARM_SI + "trigger"; public static final String ICAL_DURATION_SI = ICAL_ALARM_SI + "duration"; public static final String ICAL_REPEAT_SI = ICAL_ALARM_SI + "repeat"; // ****** TYPE SIS FOR TODO SPECIFIC PROPERTIES ****** public static final String ICAL_TODO_SI = ICAL_SI + "todo/"; public static final String ICAL_DUE_TIME_SI = ICAL_TODO_SI + "due-time"; public static final String ICAL_TODO_DATE_COMPLETED_SI = ICAL_TODO_SI + "date completed"; public static final String ICAL_TODO_COMPLETED_SI = ICAL_TODO_SI + "percent-complete"; @Override public WandoraToolType getType() { return WandoraToolType.createExtractType(); } @Override public String getName() { return "iCalendar extractor"; } @Override public String getDescription() { return "The iCalendar Extractor is used to extract topic map data from iCalendar sources."; } @Override public Icon getIcon() { return UIBox.getIcon(0xf133); } @Override public boolean runInOwnThread() { return true; } @Override public boolean useTempTopicMap() { return false; } @Override public boolean useURLCrawler() { return false; } public boolean _extractTopicsFrom(File f, TopicMap t) throws Exception { return _extractTopicsFrom(new FileInputStream(f), t); } public boolean _extractTopicsFrom(URL u, TopicMap t) throws Exception { return _extractTopicsFrom(u.openStream(), t); } public boolean _extractTopicsFrom(String str, TopicMap t) throws Exception { return _extractTopicsFrom(new ByteArrayInputStream(str.getBytes("UTF-8")), t); } public boolean _extractTopicsFrom(InputStream inputStream, TopicMap topicMap) throws Exception { CalendarBuilder builder = new CalendarBuilder(); try { net.fortuna.ical4j.model.Calendar calendar = builder.build(inputStream); return parseCalendar(calendar, topicMap); } catch (ParserException e) { log("There was an error parsing the calendar file."); log(e); } return false; } /* * Parse the given calendar object into a Wandora topic and pass the included events and venues * to separate parsers. Parsed topics aare then associated with the calendar. */ public boolean parseCalendar(net.fortuna.ical4j.model.Calendar calendar, TopicMap topicMap) { try { String prodId = calendar.getProductId().getValue(); if (prodId != null) { Property versionP = calendar.getProperty("VERSION"); String version = versionP != null ? versionP.getValue() : ""; Property calScaleP = calendar.getProperty("CALSCALE"); String calScale = calScaleP != null ? calScaleP.getValue() : ""; Property calTZP = calendar.getProperty("X-WR-TIMEZONE"); String calTZ = calTZP != null ? calTZP.getValue() : ""; Property calDescP = calendar.getProperty("X-WR-CALDESC"); String calDesc = calDescP != null ? calDescP.getValue() : ""; Property calNameP = calendar.getProperty("X-WR-CALNAME"); String calName = calNameP != null ? calNameP.getValue() : ""; //Use the required prodID if the optional (extension) calname is not specified String calendarName = !calName.isEmpty() ? calName : prodId; Topic calendarType = this.getCalendarType(topicMap); Topic calendarTopic = getCalendarTopic(calendarName, topicMap); calendarTopic.setBaseName(calendarName); calendarTopic.setDisplayName(LANG, calendarName); Topic defaultLangTopic = getDefaultLangTopic(topicMap); //Property -> occurrence if (!calDesc.isEmpty()) { createOccurrence(topicMap, calendarTopic, defaultLangTopic, ICAL_DESCRIPTION_SI, "iCalendar description", calDesc); } //Property -> association if (!version.isEmpty()) { createAssociation(topicMap, calendarType, calendarTopic, ICAL_VERSION_SI, "version", "iCalendar calendar version", version); } if (!calScale.isEmpty()) { createAssociation(topicMap, calendarType, calendarTopic, ICAL_CALSCALE_SI, "calScale", "iCalendar calendar scale", calScale); } if (!calTZ.isEmpty()) { createAssociation(topicMap, calendarType, calendarTopic, ICAL_CAL_TZ_SI, "calTZ", "iCalendar calendar time zone", calTZ); } //Parse venues List<CalendarComponent> venues = calendar.getComponents("VVENUE"); if (venues != null) { for (CalendarComponent component : venues) { VVenue venue = (VVenue) component; venue.validate(); Topic venueTopic = parseVenue(venue, topicMap); Topic venueType = getVenueType(topicMap); if (venueTopic != null && venueType != null && calendarType != null && calendarTopic != null) { Association a = topicMap.createAssociation(venueType); a.addPlayer(calendarTopic, calendarType); a.addPlayer(venueTopic, venueType); } } } //Parse events List<CalendarComponent> events = calendar.getComponents("VEVENT"); if (events != null) { for (CalendarComponent component : events) { VEvent event = (VEvent) component; event.validate(); Topic eventTopic = parseEvent(event, topicMap); Topic eventType = getEventType(topicMap); if (eventTopic != null && eventType != null && calendarType != null && calendarTopic != null) { Association a = topicMap.createAssociation(eventType); a.addPlayer(calendarTopic, calendarType); a.addPlayer(eventTopic, eventType); } } } //Parse ToDos List<CalendarComponent> todos = calendar.getComponents("VTODO"); if (todos != null) { for (CalendarComponent component : todos) { VToDo todo = (VToDo) component; todo.validate(); Topic todoTopic = parseToDo(todo, topicMap); Topic todoType = getToDoType(topicMap); if (todoTopic != null && todoType != null && calendarType != null && calendarTopic != null) { Association a = topicMap.createAssociation(todoType); a.addPlayer(calendarTopic, calendarType); a.addPlayer(todoTopic, todoType); } } } } else { log("Calendar missing mandatory prodId -- skipping."); } } catch (Exception e) { log(e); } return true; } /* * Parse a single venue into a topic where the venue's properties are mapped * to the topic's occurrences and associations. */ public Topic parseVenue(VVenue venue, TopicMap topicMap) { try { Property nameP = venue.getProperty("NAME"); String name = nameP != null ? nameP.getValue() : ""; Property descriptionP = venue.getProperty("DESCRIPTION"); String description = descriptionP != null ? descriptionP.getValue() : ""; Property addressP = venue.getProperty("STREET-ADDRESS"); String address = addressP != null ? addressP.getValue() : ""; Property extAddressP = venue.getProperty("EXTENDED-ADDRESS"); String extAddress = extAddressP != null ? extAddressP.getValue() : ""; Property localityP = venue.getProperty("LOCALITY"); String locality = localityP != null ? localityP.getValue() : ""; Property regionP = venue.getProperty("REGION"); String region = regionP != null ? regionP.getValue() : ""; Property countryP = venue.getProperty("COUNTRY"); String country = regionP != null ? countryP.getValue() : ""; Property postalCodeP = venue.getProperty("POSTAL-CODE"); String postalCode = regionP != null ? postalCodeP.getValue() : ""; Property tzidP = venue.getProperty("TZID"); String tzid = regionP != null ? tzidP.getValue() : ""; Property locTypeP = venue.getProperty("LOCATION-TYPE"); String locType = locTypeP != null ? locTypeP.getValue() : ""; Property catP = venue.getProperty("CATEGORIES"); String cat = catP != null ? catP.getValue() : ""; Property uidP = venue.getProperty("UID"); if (uidP != null) { String uid = venue.getProperty("UID").getValue(); String basename = name.isEmpty() ? uid + " (Venue)" : name + " (Venue)"; String displayname = name.isEmpty() ? uid : name; Topic venueTopic = getUTopic(ICAL_VENUE_SI + uid, getVenueType(topicMap), topicMap); Topic defaultLangTopic = getDefaultLangTopic(topicMap); venueTopic.setBaseName(basename); venueTopic.setDisplayName(LANG, displayname); Topic venueUIDtype = this.getComponentUIDType(topicMap); venueTopic.setData(venueUIDtype, defaultLangTopic, uid); Topic venueType = this.getVenueType(topicMap); if (!description.isEmpty()) { createOccurrence(topicMap, venueTopic, defaultLangTopic, ICAL_DESCRIPTION_SI, "iCalendar description", description); } if (!address.isEmpty()) { createOccurrence(topicMap, venueTopic, defaultLangTopic, ICAL_STADDR_SI, "iCalendar street address", address); } if (!extAddress.isEmpty()) { createOccurrence(topicMap, venueTopic, defaultLangTopic, ICAL_EXTADDR_SI, "iCalendar extended address", extAddress); } if (!locality.isEmpty()) { createOccurrence(topicMap, venueTopic, defaultLangTopic, ICAL_LOCALITY_SI, "iCalendar locality", locality); } if (!tzid.isEmpty()) { createOccurrence(topicMap, venueTopic, defaultLangTopic, ICAL_TZID_SI, "iCalendar time zone ID", tzid); } if (!cat.isEmpty()) { createAssociation(topicMap, venueType, venueTopic, ICAL_CAT_SI, "category", "iCalendar category", cat); } if (!country.isEmpty()) { createAssociation(topicMap, venueType, venueTopic, ICAL_COUNTRY_SI, "country", "iCalendar country", country); } if (!region.isEmpty()) { createAssociation(topicMap, venueType, venueTopic, ICAL_REGION_SI, "region", "iCalendar region", region); } if (!locType.isEmpty()) { createAssociation(topicMap, venueType, venueTopic, ICAL_LOCTYPE_SI, "loctype", "iCalendar location type", locType); } if (!postalCode.isEmpty()) { createAssociation(topicMap, venueType, venueTopic, ICAL_POSTALCODE_SI, "postalcode", "iCalendar postal code", postalCode); } return venueTopic; } else { log("a VVenue missing mandatory UID -- skipping."); } } catch (Exception e) { log(e); } return null; } /* * Parse a single event to a topic where the event's properties are mapped to the topic's * occurrences and associations. * * Optional alerts are then parsed and associated with the event. */ public Topic parseEvent(VEvent event, TopicMap topicMap) { try { DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); DateFormat dfDate = new SimpleDateFormat("yyyy-MM-dd"); java.util.Calendar cal = Calendar.getInstance(); //Possible occurrencess Geo ge = event.getGeographicPos(); String lat = (ge != null) ? event.getGeographicPos().getLatitude().toString() : ""; String lon = (ge != null) ? event.getGeographicPos().getLongitude().toString() : ""; Description desc = event.getDescription(); String description = desc != null ? desc.getValue() : ""; Summary summ = event.getSummary(); String summary = summ != null ? event.getSummary().getValue() : ""; Url url = event.getUrl(); String urlString = url != null ? event.getUrl().getValue() : ""; DtStart dtstart = event.getStartDate(); DtEnd dtend = event.getEndDate(true); //Derive from DURATION if there's no DTEND String startString = ""; String endString = ""; if (dtstart != null && !dtstart.getValue().isEmpty()) { Date start = event.getStartDate().getDate(); Date end; //Spec: if DTEND and DURATION aren't defined... if (dtend == null) { //... and DTSTART has a parameter VALUE=DATE ie DTSTART is of type DATE instead of DATE-TIME //the duration for the event is assumed to be one day. if (dtstart.getParameter("VALUE") != null && dtstart.getParameter("VALUE").getValue().equals("DATE")) { cal.setTime(start); cal.add(Calendar.DAY_OF_MONTH, 1); end = cal.getTime(); //... else DTSTART is assumed to be of type DATE-TIME and the event to end on the start time } else { end = start; } } else { end = dtend.getDate(); } startString = df.format(start); endString = df.format(end); } String modified = event.getLastModified() != null ? df.format(event.getLastModified().getDate()) : ""; String created = event.getCreated() != null ? df.format(event.getCreated().getDate()) : ""; //Possible assocs String dateString = event.getStartDate() != null ? dfDate.format(event.getStartDate().getDate()) : ""; Transp transparency = event.getTransparency(); String transp = transparency != null ? transparency.getValue() : "OPAQUE"; Priority prio = event.getPriority(); String priority = prio != null ? prio.getValue() : ""; Clazz claz = event.getClassification(); String clazz = claz != null ? claz.getValue() : ""; Location location = event.getLocation(); Property cats = event.getProperty("CATEGORIES"); String catString = cats != null && !cats.getValue().isEmpty() ? cats.getValue() : ""; String[] catArray = catString.isEmpty() ? null : catString.split(","); Organizer org = event.getOrganizer(); String organizer = org != null ? org.getValue() : ""; Status stat = event.getStatus(); String status = stat != null ? event.getStatus().getValue() : ""; RecurrenceId recur = event.getRecurrenceId(); String recurrence = recur != null ? recur.getDate().toString() : ""; Uid uid = event.getUid(); if (uid != null) { String uidString = uid.getValue(); String basename = summary.isEmpty() ? uidString + " (Event)" : summary + " (Event)"; Topic defaultLangTopic = getDefaultLangTopic(topicMap); Topic eventType = this.getEventType(topicMap); Topic eventTopic = getUTopic(ICAL_EVENT_SI + uidString, getEventType(topicMap), topicMap); eventTopic.setBaseName(basename); eventTopic.setDisplayName(LANG, summary); createOccurrence(topicMap, eventTopic, defaultLangTopic, ICAL_UID_SI, "iCalendar UID", uidString); if (!summary.isEmpty()) { createOccurrence(topicMap, eventTopic, defaultLangTopic, ICAL_SUMMARY_SI, "iCalendar summary", summary); } if (!description.isEmpty()) { createOccurrence(topicMap, eventTopic, defaultLangTopic, ICAL_DESCRIPTION_SI, "iCalendar description", description); } if (!urlString.isEmpty()) { createOccurrence(topicMap, eventTopic, defaultLangTopic, ICAL_URL_SI, "iCalendar URL", urlString); } if (!lat.isEmpty()) { createOccurrence(topicMap, eventTopic, defaultLangTopic, ICAL_LAT_SI, "iCalendar latitude", lat); } if (!lon.isEmpty()) { createOccurrence(topicMap, eventTopic, defaultLangTopic, ICAL_LON_SI, "iCalendar longitude", lon); } if (!startString.isEmpty()) { createOccurrence(topicMap, eventTopic, defaultLangTopic, ICAL_START_TIME_SI, "iCalendar start time", startString); } if (!endString.isEmpty()) { createOccurrence(topicMap, eventTopic, defaultLangTopic, ICAL_END_TIME_SI, "iCalendar end time", endString); } if (!created.isEmpty()) { createOccurrence(topicMap, eventTopic, defaultLangTopic, ICAL_CREATED_SI, "iCalendar time created", created); } if (!modified.isEmpty()) { createOccurrence(topicMap, eventTopic, defaultLangTopic, ICAL_MODIFIED_SI, "iCalendar time modified", modified); } if (!dateString.isEmpty()) { createAssociation(topicMap, eventType, eventTopic, ICAL_DATE_SI, "date", "iCalendar event date", dateString); } if (!transp.isEmpty()) { createAssociation(topicMap, eventType, eventTopic, ICAL_TRANSP_SI, "transparency", "iCalendar component transparency", transp); } if (!priority.isEmpty()) { createAssociation(topicMap, eventType, eventTopic, ICAL_PRIOR_SI, "priority", "iCalendar component priority", priority); } if (!clazz.isEmpty()) { createAssociation(topicMap, eventType, eventTopic, ICAL_CLASS_SI, "class", "iCalendar component class", clazz); } if (!organizer.isEmpty()) { createAssociation(topicMap, eventType, eventTopic, ICAL_ORGANIZER_SI, "organizer", "iCalendar component organizer", clazz); } if (!status.isEmpty()) { createAssociation(topicMap, eventType, eventTopic, ICAL_STATUS_SI, "status", "iCalendar component status", status); } if (!recurrence.isEmpty()) { createAssociation(topicMap, eventType, eventTopic, ICAL_RECURRENCE_SI, "recurrence", "iCalendar component recurrence", recurrence); } if (catArray != null) { for (String cat : catArray) { createAssociation(topicMap, eventType, eventTopic, ICAL_CAT_SI, "category", "iCalendar category", cat); } } if (location != null && !location.getValue().isEmpty()) { Topic eventLocationTopic; if (location.getParameter("VVENUE") != null) { // Use VVenue if found eventLocationTopic = topicMap.getTopic(ICAL_VENUE_SI + location.getParameter("VVENUE").getValue()); } else { eventLocationTopic = getLocationTopic(urlEncode(location.getValue()), topicMap); eventLocationTopic.setBaseName(location.getValue()); eventLocationTopic.setDisplayName(LANG, location.getValue()); } if(eventLocationTopic != null && eventType != null && eventTopic != null){ createAssociation(topicMap, eventLocationTopic, eventType, eventTopic, ICAL_LOCATION_SI, "location", location.getValue()); } } ComponentList alarms = event.getAlarms(); int i = 0; if (alarms != null) { for (Object o : alarms) { Component component = (Component) o; VAlarm alarm = (VAlarm) component; alarm.validate(); Topic alarmTopic = parseAlarm(alarm, topicMap, uid.getValue(), summary, i); Topic alarmType = getAlarmType(topicMap); if (alarmTopic != null && alarmType != null && eventType != null && eventTopic != null) { Association a = topicMap.createAssociation(alarmType); a.addPlayer(eventTopic, eventType); a.addPlayer(alarmTopic, alarmType); } i++; } } return eventTopic; } else { log("a VEvent missing mandatory UID -- skipping."); } } catch (Exception e) { log(e); } return null; } /* * Parse a single alarm to a topic where the alarm's properties are mapped to the topic's * occurrences and associations. */ public Topic parseAlarm(VAlarm alarm, TopicMap topicMap, String eventUid, String eventSummary, int i) { try { Action action = alarm.getAction(); Trigger trigger = alarm.getTrigger(); Description description = alarm.getDescription(); String descString = description != null ? description.getValue() : ""; Duration duration = alarm.getDuration(); String durString = duration != null ? duration.getValue() : ""; Repeat repeat = alarm.getRepeat(); String repString = repeat != null ? repeat.getValue() : ""; Summary summary = alarm.getSummary(); String summString = summary != null ? summary.getValue() : ""; if (action != null && trigger != null) { String trigString = ""; if (trigger.getParameter("VALUE") != null && trigger.getParameter("VALUE").getValue().equals("DATE-TIME")) { Date trigDate = trigger.getDate(); DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); trigString = df.format(trigDate); } else { TemporalAmount d = trigger.getDuration(); List<TemporalUnit> tus = d.getUnits(); for(TemporalUnit u : tus) { if(d.get(u) != 0) { if(!trigString.isEmpty()) { trigString += " "; } trigString += d.get(u) + " " + u.toString(); } } } String actString = action.getValue(); String uidString = actString + "-" + eventUid + "-" + i; String basename = uidString + " (Alarm)"; Topic defaultLangTopic = getDefaultLangTopic(topicMap); Topic alarmTopic = getUTopic(ICAL_ALARM_SI + uidString, getAlarmType(topicMap), topicMap); alarmTopic.setBaseName(basename); alarmTopic.setDisplayName(LANG, actString + " alarm for event \"" + eventSummary + "\""); Topic alarmUIDType = this.getComponentUIDType(topicMap); alarmTopic.setData(alarmUIDType, defaultLangTopic, uidString); if (!trigString.isEmpty()) { createOccurrence(topicMap, alarmTopic, defaultLangTopic, ICAL_TRIGGER_SI, "iCalendar alarm trigger", trigString); } if (!descString.isEmpty()) { createOccurrence(topicMap, alarmTopic, defaultLangTopic, ICAL_DESCRIPTION_SI, "iCalendar description", descString); } if (!durString.isEmpty()) { createOccurrence(topicMap, alarmTopic, defaultLangTopic, ICAL_DURATION_SI, "iCalendar alarm duration", durString); } if (!repString.isEmpty()) { createOccurrence(topicMap, alarmTopic, defaultLangTopic, ICAL_REPEAT_SI, "iCalendar alarm repeat", repString); } if (!summString.isEmpty()) { createOccurrence(topicMap, alarmTopic, defaultLangTopic, ICAL_SUMMARY_SI, "iCalendar summary", summString); } return alarmTopic; } else { log("a VAlarm is missing mandatory action or trigger -- skipping."); } } catch (Exception e) { log(e); } return null; } public Topic parseToDo(VToDo todo, TopicMap topicMap) { try { DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); DateFormat dfDate = new SimpleDateFormat("yyyy-MM-dd"); java.util.Calendar cal = Calendar.getInstance(); //Possible occurrences Uid uid = todo.getUid(); DtStamp stamp = todo.getDateStamp(); Summary summ = todo.getSummary(); String summary = summ != null ? summ.getValue() : ""; Geo ge = todo.getGeographicPos(); String lat = (ge != null) ? todo.getGeographicPos().getLatitude().toString() : ""; String lon = (ge != null) ? todo.getGeographicPos().getLongitude().toString() : ""; Description desc = todo.getDescription(); String description = desc != null ? desc.getValue() : ""; Url url = todo.getUrl(); String urlString = url != null ? todo.getUrl().getValue() : ""; String percentCompleted = todo.getPercentComplete() != null ? todo.getPercentComplete().getValue() : ""; DtStart dtstart = todo.getStartDate(); Duration duration = todo.getDuration(); Due due = todo.getDue(); String startString = ""; String dueString = ""; if (due != null && due.getDate() != null) { Date dueDate = due.getDate(); dueString = df.format(dueDate); } String modified = todo.getLastModified() != null ? df.format(todo.getLastModified().getDate()) : ""; String created = todo.getCreated() != null ? df.format(todo.getCreated().getDate()) : ""; String completed = todo.getDateCompleted() != null ? df.format(todo.getDateCompleted().getDate()) : ""; //Possible assocs String dateString = todo.getDue() != null ? dfDate.format(todo.getDue().getDate()) : ""; Priority prio = todo.getPriority(); String priority = prio != null ? prio.getValue() : ""; Clazz claz = todo.getClassification(); String clazz = claz != null ? claz.getValue() : ""; Location location = todo.getLocation(); Property cats = todo.getProperty("CATEGORIES"); String catString = cats != null && !cats.getValue().isEmpty() ? cats.getValue() : ""; String[] catArray = catString.isEmpty() ? null : catString.split(","); Organizer org = todo.getOrganizer(); String organizer = org != null ? org.getValue() : ""; Status stat = todo.getStatus(); String status = stat != null ? todo.getStatus().getValue() : ""; RecurrenceId recur = todo.getRecurrenceId(); String recurrence = recur != null ? recur.getDate().toString() : ""; if (uid != null && stamp != null) { Topic toDoTopic = getUTopic(ICAL_TODO_SI + uid.getValue(), getToDoType(topicMap), topicMap); Topic toDoType = this.getToDoType(topicMap); Topic defaultLangTopic = getDefaultLangTopic(topicMap); String basename = summary.isEmpty() ? uid.getValue() + " (todo)" : summary + " (todo)"; toDoTopic.setBaseName(basename); String displayname = summary.isEmpty() ? uid.getValue() : summary; toDoTopic.setDisplayName(LANG, displayname); createOccurrence(topicMap, toDoTopic, defaultLangTopic, ICAL_UID_SI, "iCalendar UID", uid.getValue()); if (!summary.isEmpty()) { createOccurrence(topicMap, toDoTopic, defaultLangTopic, ICAL_SUMMARY_SI, "iCalendar summary", summary); } if (!description.isEmpty()) { createOccurrence(topicMap, toDoTopic, defaultLangTopic, ICAL_DESCRIPTION_SI, "iCalendar description", description); } if (!urlString.isEmpty()) { createOccurrence(topicMap, toDoTopic, defaultLangTopic, ICAL_URL_SI, "iCalendar URL", urlString); } if (!lat.isEmpty()) { createOccurrence(topicMap, toDoTopic, defaultLangTopic, ICAL_LAT_SI, "iCalendar latitude", lat); } if (!lon.isEmpty()) { createOccurrence(topicMap, toDoTopic, defaultLangTopic, ICAL_LON_SI, "iCalendar longitude", lon); } if (!startString.isEmpty()) { createOccurrence(topicMap, toDoTopic, defaultLangTopic, ICAL_START_TIME_SI, "iCalendar start time", startString); } if (!dueString.isEmpty()) { createOccurrence(topicMap, toDoTopic, defaultLangTopic, ICAL_DUE_TIME_SI, "iCalendar due time", dueString); } if (!completed.isEmpty()) { createOccurrence(topicMap, toDoTopic, defaultLangTopic, ICAL_TODO_DATE_COMPLETED_SI, "iCalendar ToDo date completed", completed); } if (!percentCompleted.isEmpty()) { createOccurrence(topicMap, toDoTopic, defaultLangTopic, ICAL_TODO_COMPLETED_SI, "iCalendar ToDo percent complete", percentCompleted); } if (!created.isEmpty()) { createOccurrence(topicMap, toDoTopic, defaultLangTopic, ICAL_CREATED_SI, "iCalendar time created", created); } if (!modified.isEmpty()) { createOccurrence(topicMap, toDoTopic, defaultLangTopic, ICAL_MODIFIED_SI, "iCalendar time modified", modified); } if (!dateString.isEmpty()) { createAssociation(topicMap, toDoType, toDoTopic, ICAL_DATE_SI, "date", "iCalendar component date", dateString); } if (!priority.isEmpty()) { createAssociation(topicMap, toDoType, toDoTopic, ICAL_PRIOR_SI, "priority", "iCalendar component priority", priority); } if (!clazz.isEmpty()) { createAssociation(topicMap, toDoType, toDoTopic, ICAL_CLASS_SI, "class", "iCalendar component class", clazz); } if (!organizer.isEmpty()) { createAssociation(topicMap, toDoType, toDoTopic, ICAL_ORGANIZER_SI, "organizer", "iCalendar component organizer", clazz); } if (!status.isEmpty()) { createAssociation(topicMap, toDoType, toDoTopic, ICAL_STATUS_SI, "status", "iCalendar component status", status); } if (!recurrence.isEmpty()) { createAssociation(topicMap, toDoType, toDoTopic, ICAL_RECURRENCE_SI, "recurrence", "iCalendar component recurrence", recurrence); } if (catArray != null) { for (String cat : catArray) { createAssociation(topicMap, toDoType, toDoTopic, ICAL_CAT_SI, "category", "iCalendar category", cat); } } if (location != null && !location.getValue().isEmpty()) { Topic eventLocationTopic; if (location.getParameter("VVENUE") != null) { // Use VVenue if found eventLocationTopic = topicMap.getTopic(ICAL_VENUE_SI + location.getParameter("VVENUE").getValue()); } else { eventLocationTopic = getLocationTopic(urlEncode(location.getValue()), topicMap); eventLocationTopic.setBaseName(location.getValue()); eventLocationTopic.setDisplayName(LANG, location.getValue()); } if(eventLocationTopic != null && toDoType != null && toDoTopic != null){ createAssociation(topicMap, eventLocationTopic, toDoType, toDoTopic, ICAL_LOCATION_SI, "location", location.getValue()); } } } else { log("a VToDo is missing mandatory UID or time stamp -- skipping."); } } catch (Exception e) { log(e); } return null; } // ------------------------------------------------------------------------- protected static Topic getOrCreateTopic(TopicMap tm, String si) throws TopicMapException { return getOrCreateTopic(tm, si, null); } protected static Topic getOrCreateTopic(TopicMap tm, String si, String bn) throws TopicMapException { return ExtractHelper.getOrCreateTopic(si, bn, tm); } protected static Topic getOrCreateTopic(TopicMap tm, String si, String bn, Topic type) throws TopicMapException { return ExtractHelper.getOrCreateTopic(si, bn, type, tm); } protected static void makeSubclassOf(TopicMap tm, Topic t, Topic superclass) throws TopicMapException { ExtractHelper.makeSubclassOf(t, superclass, tm); } // ------------------------------------------------------------------------- protected Topic getATopic(String str, String si, Topic type, TopicMap tm) throws TopicMapException { if (str != null && si != null) { str = str.trim(); if (str.length() > 0) { Topic topic = getOrCreateTopic(tm, si + "/" + urlEncode(str), str); if (type != null) { topic.addType(type); } return topic; } } return null; } protected Topic getUTopic(String si, Topic type, TopicMap tm) throws TopicMapException { if (si != null) { si = si.trim(); if (si.length() > 0) { Topic topic = getOrCreateTopic(tm, si, null); if (type != null) { topic.addType(type); } return topic; } } return null; } // ------------------------------------------------------------------------- public void createAssociation(TopicMap tm, Topic pType, Topic pTopic, String SI, String siExt, String typeName, String topicName) { try { Topic type = getOrCreateTopic(tm, SI, typeName); Topic topic = getOrCreateTopic(tm, SI + "/" + siExt + "/" + topicName, null, type); createAssociation(tm, topic, pType, pTopic, SI, typeName, topicName); } catch (Exception e) { log(e); } } public void createAssociation(TopicMap tm, Topic topic, Topic pType, Topic pTopic, String SI, String typeName, String topicName) { try { Topic type = getOrCreateTopic(tm, SI, typeName); topic.setBaseName(topicName); topic.setDisplayName(LANG, topicName); if (type != null && topic != null) { Association a = tm.createAssociation(type); a.addPlayer(topic, type); a.addPlayer(pTopic, pType); } } catch (Exception e) { log(e); } } public void createOccurrence(TopicMap tm, Topic pTopic, Topic lt, String SI, String typeName, String topicName) { try { Topic type = getOrCreateTopic(tm, SI, typeName); if (type != null && pTopic != null) { pTopic.setData(type, lt, topicName); } } catch (Exception e) { log(e); } } // ------------------------------------------------------------------------- public Topic getCalendarTopic(String calendar, TopicMap tm) throws TopicMapException { return getOrCreateTopic(tm, ICAL_CALENDAR_SI + "/" + calendar, null, getCalendarType(tm)); } public Topic getCalendarType(TopicMap tm) throws TopicMapException { return getOrCreateTopic(tm, ICAL_CALENDAR_SI, "iCalendar calendar", getiCalendarType(tm)); } public Topic getComponentUIDType(TopicMap tm) throws TopicMapException { return getOrCreateTopic(tm, ICAL_UID_SI, "iCalendar component UID"); } public Topic getDescriptionType(TopicMap tm) throws TopicMapException { return getOrCreateTopic(tm, ICAL_DESCRIPTION_SI, "iCalendar component description"); } public Topic getLocationType(TopicMap tm) throws TopicMapException { return getOrCreateTopic(tm, ICAL_LOCATION_SI, "iCalendar component location"); } public Topic getLocationTopic(String location, TopicMap tm) throws TopicMapException { return getOrCreateTopic(tm, ICAL_LOCATION_SI + "/" + location, null, getLocationType(tm)); } public Topic getEventType(TopicMap tm) throws TopicMapException { return getOrCreateTopic(tm, ICAL_EVENT_SI, "iCalendar event", getiCalendarType(tm)); } public Topic getVenueType(TopicMap tm) throws TopicMapException { return getOrCreateTopic(tm, ICAL_VENUE_SI, "iCalendar venue", getiCalendarType(tm)); } public Topic getAlarmType(TopicMap tm) throws TopicMapException { return getOrCreateTopic(tm, ICAL_ALARM_SI, "iCalendar alarm", getiCalendarType(tm)); } public Topic getToDoType(TopicMap tm) throws TopicMapException { return getOrCreateTopic(tm, ICAL_TODO_SI, "iCalendar ToDo", getiCalendarType(tm)); } // ------------------------------------------------------------------------- public Topic getiCalendarType(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, ICAL_SI, "iCalendar"); Topic wandoraClass = getWandoraClass(tm); makeSubclassOf(tm, type, wandoraClass); return type; } public Topic getWandoraClass(TopicMap tm) throws TopicMapException { return getOrCreateTopic(tm, TMBox.WANDORACLASS_SI, "Wandora class"); } public Topic getDefaultLangTopic(TopicMap tm) throws TopicMapException { return getOrCreateTopic(tm, XTMPSI.getLang(LANG)); } public static final String LANG = "en"; }
41,086
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AbstractJsoupExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/AbstractJsoupExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * */ package org.wandora.application.tools.extractors; import java.io.File; import java.net.URL; import javax.swing.Icon; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.wandora.application.gui.UIBox; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicTools; /** * * @author Eero */ public abstract class AbstractJsoupExtractor extends AbstractExtractor { private static final long serialVersionUID = 1L; private static final String LANG_SI = "http://www.topicmaps.org/xtm/1.0/language.xtm#en"; private final String[] contentTypes= new String[] { "text/html" }; @Override public Icon getIcon() { return UIBox.getIcon(0xf121); } @Override public String[] getContentTypes() { return contentTypes; } @Override public boolean _extractTopicsFrom(File f, TopicMap t) throws Exception { if(f.isDirectory()) throw new Exception("Directories are not supported."); Document d = Jsoup.parse(f,"UTF-8"); d.setBaseUri(f.getAbsolutePath()); return extractTopicsFrom(d, f.getAbsolutePath(), t); } @Override public boolean _extractTopicsFrom(URL u, TopicMap t) throws Exception { Document d = Jsoup.connect(u.toExternalForm()).get(); return extractTopicsFrom(d, u.toExternalForm(), t); } @Override public boolean _extractTopicsFrom(String str, TopicMap t) throws Exception { Document d = Jsoup.parse(str); return extractTopicsFrom(d,null,t); } protected static Topic getWandoraClassTopic(TopicMap tm) throws TopicMapException { return getOrCreateTopic(tm, TMBox.WANDORACLASS_SI, "Wandora class"); } protected static Topic getOrCreateTopic(TopicMap tm, String si) throws TopicMapException { return getOrCreateTopic(tm, si, null); } protected static Topic getOrCreateTopic(TopicMap tm, String si, String bn) throws TopicMapException { if(si == null || si.length() == 0) si = TopicTools.createDefaultLocator().toString(); return ExtractHelper.getOrCreateTopic(si, bn, tm); } protected static void makeSubclassOf(TopicMap tm, Topic t, Topic superclass) throws TopicMapException { ExtractHelper.makeSubclassOf(t, superclass, tm); } protected static Topic getLangTopic(TopicMap tm) throws TopicMapException { return getOrCreateTopic(tm, LANG_SI); } public abstract boolean extractTopicsFrom(Document d, String u, TopicMap t) throws Exception; }
3,585
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DummyExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/DummyExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * */ package org.wandora.application.tools.extractors; import org.wandora.application.Wandora; import org.wandora.application.WandoraToolType; import org.wandora.application.contexts.Context; import org.wandora.application.tools.AbstractWandoraTool; /** * Dummy extractor is used as an empty extractor tool and a separator in extractor menu. * * @author akivela */ public class DummyExtractor extends AbstractWandoraTool { private static final long serialVersionUID = 1L; public DummyExtractor() { } @Override public String getName() { return "---Dummy Extractor"; } @Override public String getDescription(){ return "Dummy extractor is an empty extractor tool."; } @Override public WandoraToolType getType() { return WandoraToolType.createExtractType(); } private final String[] contentTypes=new String[] { }; public String[] getContentTypes() { return contentTypes; } public void execute(Wandora admin, Context context) { /* NOTHING HERE */ } }
1,893
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z