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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
DeleteTopicsWithSIRegex.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/DeleteTopicsWithSIRegex.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/>.
*
*
*
* DeleteTopicsWithSIRegex.java
*
* Created on 18.7.2006, 12:43
*
*/
package org.wandora.application.tools;
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.RegularExpressionEditor;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author akivela
*/
public class DeleteTopicsWithSIRegex extends DeleteTopics implements WandoraTool {
RegularExpressionEditor editor = null;
/** Creates a new instance of DeleteTopicsWithSIRegex */
public DeleteTopicsWithSIRegex() {
}
public DeleteTopicsWithSIRegex(Context preferredContext) {
setContext(preferredContext);
}
@Override
public void execute(Wandora admin, Context context) throws TopicMapException {
editor = RegularExpressionEditor.getMatchExpressionEditor(admin);
editor.approve = false;
editor.setVisible(true);
if(editor.approve == true) {
super.execute(admin, context);
}
}
@Override
public String getName() {
return "Delete topics with SI regex";
}
@Override
public String getDescription() {
return "Delete topics with subject identifier matching to given regular expression.";
}
@Override
public boolean shouldDelete(Topic topic) throws TopicMapException {
try {
if(topic != null && !topic.isRemoved()) {
Iterator<Locator> sii = topic.getSubjectIdentifiers().iterator();
Locator l = null;
while(sii.hasNext()) {
l = sii.next();
if(editor.matches(l.toExternalForm())) {
return true;
}
}
}
}
catch(Exception e) {
log(e);
}
return false;
}
}
| 2,850 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
CopyAsImage.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/CopyAsImage.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/>.
*
*
* CopyAsImage.java
*
* Created on 14.6.2007, 16:54
*
*/
package org.wandora.application.tools;
import java.awt.Component;
import java.awt.image.BufferedImage;
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.topicpanels.GraphTopicPanel;
import org.wandora.utils.ClipboardBox;
/**
* Copies selected UI component as an image and store the image to system clipboard.
*
* @author akivela
*/
public class CopyAsImage extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
/** Creates a new instance of CopyAsImage */
public CopyAsImage() {
}
public CopyAsImage(Context proposedContext) {
setContext(proposedContext);
}
@Override
public void execute(Wandora wandora, Context context) {
Object o = context.getContextSource();
if(o instanceof Component) {
try {
Component c = (Component) o;
if(c instanceof GraphTopicPanel) {
c = ((GraphTopicPanel) c).getGraphPanel();
}
BufferedImage image = new BufferedImage(c.getWidth(), c.getHeight(), BufferedImage.TYPE_INT_RGB);
c.print(image.getGraphics());
ClipboardBox.setClipboard(image);
log("Copied context component to system clipboard as an image. Ready.");
}
catch(Exception e) {
log(e);
}
}
}
@Override
public boolean runInOwnThread() {
return false;
}
@Override
public boolean allowMultipleInvocations(){
return true;
}
@Override
public String getName() {
return "Copy as image";
}
@Override
public String getDescription() {
return "Copies current UI element to system clipboard as a bitmap image.";
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/copy_as_image.png");
}
@Override
public boolean requiresRefresh() {
return false;
}
}
| 3,069 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
ActivateButtonToolSet.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/ActivateButtonToolSet.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;
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.utils.Options;
/**
* Activates button tool set. Button tools sets are created in ToolManager2.
* Button tool set is viewed in Wandora window below topic menu bar. Activated
* button tool set is given as an argument to constructor.
*
* @author akivela
*/
public class ActivateButtonToolSet extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
private String toolSetName = null;
public ActivateButtonToolSet() {
toolSetName = WandoraToolType.WANDORA_BUTTON_TYPE;
}
public ActivateButtonToolSet(String setName) {
toolSetName = setName;
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/button_set.png");
}
@Override
public String getName() {
return "Activate set '"+toolSetName+"'";
}
@Override
public String getDescription() {
return "Activates button tool set named '"+toolSetName+"'";
}
@Override
public void execute(Wandora wandora, Context context) {
try {
Options options = wandora.getOptions();
if(options != null) {
options.put("gui.toolPanel.currentToolSet", toolSetName);
wandora.refreshToolPanel();
wandora.refresh();
}
}
catch(Exception e) {
log(e);
}
}
@Override
public boolean requiresRefresh() {
return true;
}
}
| 2,582 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
DropExtractor.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/DropExtractor.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/>.
*
*
*
* DropExtractor.java
*
* Created on 24. tammikuuta 2007, 14:38
*
*/
package org.wandora.application.tools;
import java.io.File;
import org.wandora.topicmap.TopicMapException;
/**
* Drop extractor is a special UI area in Wandora. Drop extractor locates in
* lower right corner of empty topic panel area. Wandora user can drop files and
* strings into the drop extractor. This interface specifies the extractor methods
* a drop extractor must implement. Notice, AbstractExtractor implements
* DropExtractor. As a consequence almost all extractors are automatically also
* DropExtractors.
*
* @author akivela
*/
public interface DropExtractor {
public void dropExtract(File[] files) throws TopicMapException;
public void dropExtract(String[] urls) throws TopicMapException;
public void dropExtract(String content) throws TopicMapException;
}
| 1,685 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
DeleteTopicsWithoutOccurrences.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/DeleteTopicsWithoutOccurrences.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/>.
*
*
*
* DeleteTopicsWithoutOccurrences.java
*
* Created on 12.6.2006, 17:43
*
*/
package org.wandora.application.tools;
import java.util.Collection;
import org.wandora.application.WandoraTool;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author akivela
*/
public class DeleteTopicsWithoutOccurrences extends DeleteTopics implements WandoraTool {
private static final long serialVersionUID = 1L;
@Override
public String getName() {
return "Delete topics without occurrences";
}
@Override
public String getDescription() {
return "Delete context topics without occurrences.";
}
@Override
public boolean shouldDelete(Topic topic) throws TopicMapException {
try {
Collection<Topic> dataTypes = topic.getDataTypes();
if(dataTypes == null || dataTypes.isEmpty()) {
if(confirm) {
return confirmDelete(topic);
}
else {
return true;
}
}
}
catch(Exception e) {
log(e);
}
return false;
}
}
| 2,008 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AboutWandora.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/AboutWandora.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/>.
*
*
* AboutApplication.java
*
* Created on September 11, 2004, 2:56 PM
*/
package org.wandora.application.tools;
import java.awt.Dimension;
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.simple.SimpleButton;
import org.wandora.utils.swing.ImagePanel;
import org.wandora.utils.swing.MultiLineLabel;
/**
* Class implements <code>WandoraAdminTool</code> and opens simple dialog
* panel viewing general information about Wandora application.
*
* @author akivela
*/
public class AboutWandora extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
private javax.swing.JDialog aboutDialog;
private MultiLineLabel textLabel;
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/info.png");
}
@Override
public String getName() {
return "About Wandora";
}
@Override
public String getDescription() {
return "Views general information about Wandora software application.";
}
@Override
public void execute(Wandora wandora, Context context) {
try {
aboutDialog=new javax.swing.JDialog(wandora,"About Wandora",true);
aboutDialog.getContentPane().setLayout(new java.awt.BorderLayout(20,0));
ImagePanel titleLabel = new ImagePanel("gui/label_about_wandora.png");
aboutDialog.getContentPane().add(titleLabel,java.awt.BorderLayout.NORTH);
String text =
"Wandora is a general purpose knowledge editor application.\n"+
"Copyright (C) 2004-2023 Wandora Team\n \n"+
"This program is free software: you can redistribute it\n" +
"and/or modify it under the terms of the GNU General Public\n"+
"License as published by the Free Software Foundation,\n"+
"either version 3 of the License, or (at your option) any\n"+
"later version.\n \n"+
"This program is distributed in the hope that it will be useful,\n"+
"but WITHOUT ANY WARRANTY; without even the implied warranty\n"+
"of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n"+
"PURPOSE. See the GNU General Public License for\n"+
"more details.\n \n"+
"For more information see http://wandora.org\n";
textLabel=new MultiLineLabel(text);
textLabel.setVisible(true);
textLabel.setForeground(new java.awt.Color(50,50,50));
textLabel.setBackground(wandora.getBackground());
textLabel.setAlignment(textLabel.CENTER);
textLabel.setMaximumSize(new Dimension(370, 50));
textLabel.setMinimumSize(new Dimension(370, 50));
textLabel.setPreferredSize(new Dimension(370, 50));
aboutDialog.getContentPane().add(textLabel, java.awt.BorderLayout.CENTER);
SimpleButton okButton = new SimpleButton();
okButton.setText("OK");
okButton.setMaximumSize(new Dimension(70, 24));
okButton.setMinimumSize(new Dimension(70, 24));
okButton.setPreferredSize(new Dimension(70, 24));
okButton.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
okButtonActionPerformed(evt);
}
});
javax.swing.JPanel buttonContainer = new javax.swing.JPanel(new java.awt.FlowLayout());
buttonContainer.add(okButton);
aboutDialog.getContentPane().add(buttonContainer, java.awt.BorderLayout.SOUTH);
aboutDialog.setDefaultCloseOperation(javax.swing.JDialog.DISPOSE_ON_CLOSE);
aboutDialog.setResizable(false);
aboutDialog.pack();
if(wandora != null) wandora.centerWindow(aboutDialog);
aboutDialog.setVisible(true);
}
catch (Exception e) {
log(e);
}
}
private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {
aboutDialog.setVisible(false);
}
@Override
public boolean requiresRefresh() {
return false;
}
}
| 5,308 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
NewTopicExtended.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/NewTopicExtended.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/>.
*
*
*
* NewTopicExtended.java
*
* Created on 2013-04-28
*
*/
package org.wandora.application.tools;
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.NewTopicPanelExtended;
import org.wandora.application.gui.UIBox;
import org.wandora.application.gui.table.TopicGrid;
import org.wandora.application.gui.topicpanels.GraphTopicPanel;
import org.wandora.application.gui.topicpanels.graphpanel.TopicMapGraphPanel;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author akivela
*/
public class NewTopicExtended extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
/** Creates a new instance of NewTopicExtended */
public NewTopicExtended() {
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
NewTopicPanelExtended newTopicPanel = new NewTopicPanelExtended(context);
if(newTopicPanel.getAccepted()) {
Topic newTopic = newTopicPanel.createTopic();
postExecute(newTopic, context);
}
}
private void postExecute(Topic newTopic, Context context) {
try {
if(newTopic != null) {
Object contextSource = context.getContextSource();
if(contextSource != null) {
if(contextSource instanceof TopicGrid) {
((TopicGrid) contextSource).setCurrentTopic(newTopic);
}
else if(contextSource instanceof TopicMapGraphPanel) {
((TopicMapGraphPanel) contextSource).setRootTopic(newTopic);
}
else if(contextSource instanceof GraphTopicPanel) {
((GraphTopicPanel) contextSource).open(newTopic);
}
}
}
}
catch(Exception e) {
// SKIP SILENTLY...
}
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/new_topic.png");
}
@Override
public String getName() {
return "New Topic";
}
@Override
public String getDescription() {
return "Creates new topic.";
}
}
| 3,226 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
CopyTopics.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/CopyTopics.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/>.
*
*
* CopyTopics.java
*
* Created on 30. lokakuuta 2005, 19:04
*
*/
package org.wandora.application.tools;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
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.topicstringify.TopicToString;
import org.wandora.application.tools.statistics.TopicClusteringCoefficient;
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.topicmap.layered.ContainerTopicMap;
import org.wandora.topicmap.layered.Layer;
import org.wandora.topicmap.layered.LayeredTopic;
import org.wandora.utils.ClipboardBox;
/**
*
* @author akivela
*/
public class CopyTopics extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
public static final boolean OUTPUT_LOG = false;
public static String NEW_LINE_SUBSTITUTE_STRING = "\\n";
public static String TAB_SUBSTITUTE_STRING = "\\t";
public static String NO_BASENAME_STRING = "[no basename found]";
public static final int COPY_BASENAMES = 100;
public static final int COPY_SIS = 101;
public static final int INCLUDE_NOTHING = 1000;
public static final int INCLUDE_NAMES = 1001;
public static final int INCLUDE_NAMES_AND_SCOPES = 1901;
public static final int INCLUDE_SLS = 1002;
public static final int INCLUDE_SIS = 1003;
public static final int INCLUDE_CLASSES = 1004;
public static final int INCLUDE_INSTANCES = 1005;
public static final int INCLUDE_PLAYERS = 1006;
public static final int INCLUDE_PLAYED_ROLES = 1904;
public static final int INCLUDE_OCCURRENCES = 1007;
public static final int INCLUDE_ALL_OCCURRENCES = 1008;
public static final int INCLUDE_OCCURRENCE_TYPES = 1009;
public static final int INCLUDE_ASSOCIATION_TYPES = 1010;
public static final int INCLUDE_SI_COUNT = 1103;
public static final int INCLUDE_CLASS_COUNT = 1104;
public static final int INCLUDE_INSTANCE_COUNT = 1105;
public static final int INCLUDE_ASSOCIATION_COUNT = 1106;
public static final int INCLUDE_TYPED_ASSOCIATION_COUNT = 1107;
public static final int INCLUDE_OCCURRENCE_COUNT = 1108;
public static final int INCLUDE_LAYER_DISTRIBUTION = 1200;
public static final int INCLUDE_CLUSTER_COEFFICIENT = 1400;
public int copyOrders = COPY_BASENAMES;
public int includeOrders = 0;
Topic associationType = null;
Topic role = null;
Topic occurrenceType = null;
List<Topic> allOccurrenceTypes = null;
Set<Topic> scopeMemory = null;
Wandora wandora = null;
Iterator topics = null;
public CopyTopics() throws TopicMapException {
this((Collection) null, COPY_BASENAMES, INCLUDE_NOTHING);
}
public CopyTopics(Wandora admin, Collection topics) throws TopicMapException {
this(admin, topics, COPY_BASENAMES, INCLUDE_NOTHING);
}
public CopyTopics(Wandora admin, Collection topics, int includeOrders) throws TopicMapException {
this(admin, topics, COPY_BASENAMES, includeOrders);
}
public CopyTopics(Wandora admin, Collection topics, int copyOrders, int includeOrders) throws TopicMapException {
this.topics = topics.iterator();
initialize(copyOrders, includeOrders);
execute(admin);
}
public CopyTopics(Collection topics, int includeOrders) {
this(topics, COPY_BASENAMES, includeOrders);
}
public CopyTopics(Collection topics, int copyOrders, int includeOrders) {
if(topics != null) this.topics = topics.iterator();
initialize(copyOrders, includeOrders);
}
public CopyTopics(int copyOrders, int includeOrders) {
this((Collection) null, copyOrders, includeOrders);
}
public CopyTopics(int includeOrders) {
this((Collection) null, COPY_BASENAMES, includeOrders);
}
public CopyTopics(Context context, int copyOrders, int includeOrders) {
if(context != null) setContext(context);
initialize(copyOrders, includeOrders);
}
public CopyTopics(Context context, int includeOrders) {
if(context != null) setContext(context);
initialize(COPY_BASENAMES, includeOrders);
}
protected void initialize(int copyOrders, int includeOrders) {
this.copyOrders = copyOrders;
this.includeOrders = includeOrders;
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/copy_topic.png");
}
@Override
public String getName() {
return "Copy topics";
}
@Override
public String getDescription() {
StringBuilder sb = new StringBuilder("Copy selected topics to the clipboard.");
switch(includeOrders) {
case INCLUDE_SLS: sb.append(" Include subject locators."); break;
case INCLUDE_SIS: sb.append(" Include subject indentifiers."); break;
case INCLUDE_NAMES: sb.append(" Include variant names."); break;
case INCLUDE_NAMES_AND_SCOPES: sb.append(" Include variant names and name scopes."); break;
case INCLUDE_INSTANCES: sb.append(" Include instance topics."); break;
case INCLUDE_CLASSES: sb.append(" Include class topics."); break;
case INCLUDE_PLAYERS: sb.append(" Include player topics."); break;
case INCLUDE_PLAYED_ROLES: sb.append(" Include played roles."); break;
case INCLUDE_OCCURRENCES: sb.append(" Include occurrences."); break;
case INCLUDE_OCCURRENCE_TYPES: sb.append(" Include occurrence types."); break;
case INCLUDE_ALL_OCCURRENCES: sb.append(" Include all occurrences."); break;
case INCLUDE_ASSOCIATION_TYPES: sb.append(" Include association types."); break;
case INCLUDE_SI_COUNT: sb.append(" Include subject identifier count."); break;
case INCLUDE_CLASS_COUNT: sb.append(" Include class count."); break;
case INCLUDE_INSTANCE_COUNT: sb.append(" Include instance count."); break;
case INCLUDE_ASSOCIATION_COUNT: sb.append(" Include association count."); break;
case INCLUDE_TYPED_ASSOCIATION_COUNT: sb.append(" Include association count of specific type."); break;
case INCLUDE_OCCURRENCE_COUNT: sb.append(" Include occurrence count."); break;
case INCLUDE_LAYER_DISTRIBUTION: sb.append(" Include topic's distribution over topic map layers."); break;
case INCLUDE_CLUSTER_COEFFICIENT: sb.append(" Include topic's clustering coefficient."); break;
};
return sb.toString();
}
public String getTopicTypeName() {
return "topics";
}
@Override
public boolean requiresRefresh() {
return false;
}
public void setTopics(Collection topics) {
this.topics = topics.iterator();
}
public void setTopics(Topic[] topicArray) {
List<Topic> topicList = new ArrayList<>();
if(topicArray != null) {
for(int i=0; i<topicArray.length; i++) {
topicList.add(topicArray[i]);
}
}
topics = topicList.iterator();
}
@Override
public void execute(Wandora wandora, Context context) {
this.wandora = wandora;
try {
if(wandora != null) {
scopeMemory = new LinkedHashSet<>();
associationType = null;
role = null;
if(includeOrders == INCLUDE_TYPED_ASSOCIATION_COUNT) {
associationType=wandora.showTopicFinder("Select association type...");
if(associationType == null) return;
}
if(includeOrders == INCLUDE_PLAYERS) {
associationType=wandora.showTopicFinder("Select association type...");
if(associationType == null) return;
role=wandora.showTopicFinder("Select role...");
if(role == null) return;
}
occurrenceType = null;
if(includeOrders == INCLUDE_OCCURRENCES) {
occurrenceType=wandora.showTopicFinder("Select occurrence type...");
if(occurrenceType == null) return;
}
allOccurrenceTypes = new ArrayList<Topic>();
if(includeOrders == INCLUDE_ALL_OCCURRENCES) {
allOccurrenceTypes = getOccurrenceTypes(wandora.getTopicMap());
}
}
work();
}
catch(Exception e) {
log(e);
}
}
public void work() {
if(OUTPUT_LOG) setDefaultLogger();
try {
Collection countCollection = null;
List<String> lines = new ArrayList<>();
if(OUTPUT_LOG) log("Copying "+ getTopicTypeName() +" to clipboard...");
Topic topic = null;
if(topics == null) {
topics = getContext().getContextObjects();
}
if(topics == null) topics = (new ArrayList()).iterator();
int count = 0;
while(topics.hasNext() && !forceStop()) {
StringBuilder sb = new StringBuilder("");
try {
count++;
setProgress(count);
topic = (Topic) topics.next();
String topicName = null;
if(topic != null) {
topicName = TopicToString.toString(topic);
if(OUTPUT_LOG) {
hlog("Copying from '" + topicName + "'.");
}
switch(copyOrders) {
case COPY_BASENAMES: {
if(topic.getBaseName() != null) {
sb.append(topic.getBaseName());
}
else {
sb.append(NO_BASENAME_STRING);
}
break;
}
case COPY_SIS: {
sb.append(topic.getOneSubjectIdentifier().toExternalForm());
break;
}
}
switch(includeOrders) {
case INCLUDE_SLS: {
Locator sl = topic.getSubjectLocator();
if(sl != null) {
sb.append("\t").append(sl.toExternalForm());
}
break;
}
case INCLUDE_SIS: {
Locator si = topic.getOneSubjectIdentifier();
if(si != null) {
sb.append("\t").append(si.toExternalForm());
}
break;
}
case INCLUDE_SI_COUNT: {
countCollection = topic.getSubjectIdentifiers();
if(countCollection != null) {
sb.append("\t").append(countCollection.size());
}
else {
sb.append("\tNA");
}
break;
}
case INCLUDE_CLASSES: {
Collection<Topic> types = topic.getTypes();
for(Topic type : types) {
if(type != null) {
sb.append("\t").append(TopicToString.toString(type));
}
}
break;
}
case INCLUDE_CLASS_COUNT: {
countCollection = topic.getTypes();
if(countCollection != null) {
sb.append("\t").append(countCollection.size());
}
else {
sb.append("\tNA");
}
break;
}
case INCLUDE_INSTANCES: {
Collection<Topic> instances = topic.getTopicMap().getTopicsOfType(topic);
for(Topic instance : instances) {
if(instance != null) {
sb.append("\t").append(TopicToString.toString(instance));
}
}
break;
}
case INCLUDE_INSTANCE_COUNT: {
countCollection = topic.getTopicMap().getTopicsOfType(topic);
if(countCollection != null) {
sb.append("\t").append(countCollection.size());
}
else {
sb.append("\tNA");
}
break;
}
case INCLUDE_NAMES: {
Set<Set<Topic>> scopes = topic.getVariantScopes();
if(scopes != null && !scopes.isEmpty()) {
for(Set<Topic> scope : scopes) {
if(scope != null && !scope.isEmpty()) {
sb.append("\t").append(topic.getVariant(scope));
}
}
}
break;
}
case INCLUDE_NAMES_AND_SCOPES: {
Set<Set<Topic>> scopes = topic.getVariantScopes();
if(scopes != null && !scopes.isEmpty()) {
for(Set<Topic> scope : scopes) {
if(scope != null && !scope.isEmpty()) {
sb.append("\t").append(topic.getVariant(scope));
for(Topic scopeTopic : scope) {
sb.append("\t").append(TopicToString.toString(scopeTopic));
}
}
sb.append("\n");
}
sb.deleteCharAt(sb.length()-1);
}
break;
}
case INCLUDE_OCCURRENCES: {
Hashtable<Topic,String> occurrence = topic.getData(occurrenceType);
scopeMemory.addAll(occurrence.keySet());
for(Topic scope : scopeMemory) {
String occurrenceStr = occurrence.get(scope);
sb.append("\t");
if(occurrenceStr != null && occurrenceStr.length() > 0) {
occurrenceStr = occurrenceStr.replace("\t", TAB_SUBSTITUTE_STRING);
occurrenceStr = occurrenceStr.replace("\n", NEW_LINE_SUBSTITUTE_STRING);
sb.append(occurrenceStr);
}
}
if(OUTPUT_LOG) {
log("Replaced all tab characters with '"+TAB_SUBSTITUTE_STRING+"'.");
log("Replaced all new line characters with '"+NEW_LINE_SUBSTITUTE_STRING+"'.");
}
break;
}
case INCLUDE_ALL_OCCURRENCES: {
if(allOccurrenceTypes != null && !allOccurrenceTypes.isEmpty()) {
for(Topic occurrenceType : allOccurrenceTypes) {
if(occurrenceType != null && !occurrenceType.isRemoved()) {
Hashtable<Topic,String> occurrence = topic.getData(occurrenceType);
if(occurrence != null && !occurrence.keySet().isEmpty()) {
scopeMemory.addAll(occurrence.keySet());
sb.append("\t");
sb.append(TopicToString.toString(occurrenceType));
for(Topic scope : scopeMemory) {
sb.append("\t");
String occurrenceStr = occurrence.get(scope);
if(occurrenceStr != null && occurrenceStr.length() > 0) {
occurrenceStr = occurrenceStr.replace("\t", TAB_SUBSTITUTE_STRING);
occurrenceStr = occurrenceStr.replace("\n", NEW_LINE_SUBSTITUTE_STRING);
sb.append(occurrenceStr);
}
}
sb.append("\n");
}
}
}
// Trim last new line character.
sb.deleteCharAt(sb.length()-1);
if(OUTPUT_LOG) {
log("Replaced all tab characters with '"+TAB_SUBSTITUTE_STRING+"'.");
log("Replaced all new line characters with '"+NEW_LINE_SUBSTITUTE_STRING+"'.");
}
}
break;
}
case INCLUDE_OCCURRENCE_TYPES: {
ArrayList<Topic> occurrenceTypes = new ArrayList(topic.getDataTypes());
Collections.sort(occurrenceTypes, new TMBox.TopicBNAndSIComparator());
for(Topic t : occurrenceTypes) {
sb.append("\t").append(TopicToString.toString(t));
}
break;
}
case INCLUDE_OCCURRENCE_COUNT: {
Collection<Topic> occurrenceTypes = topic.getDataTypes();
int occurrenceCount = 0;
for(Topic occurrenceType : occurrenceTypes) {
Hashtable<Topic,String> scopedOccurrences = topic.getData(occurrenceType);
occurrenceCount = occurrenceCount + scopedOccurrences.size();
}
sb.append("\t");
sb.append(occurrenceCount);
break;
}
case INCLUDE_ASSOCIATION_TYPES: {
Collection<Association> associations = topic.getAssociations();
Set<String> associationTypes = new LinkedHashSet<>();
for(Association association : associations) {
associationTypes.add(TopicToString.toString(association.getType()));
}
for(String associationType : new TreeSet<String>(associationTypes)) {
sb.append("\t").append(associationType);
}
break;
}
case INCLUDE_PLAYERS: {
if(associationType != null && role != null) {
Collection<Association> associations = topic.getAssociations(associationType);
for(Association association : associations) {
if(association != null) {
Topic player = association.getPlayer(role);
if(player != null) {
sb.append("\t").append(TopicToString.toString(player));
}
}
}
}
break;
}
case INCLUDE_PLAYED_ROLES: {
Collection<Association> associations = topic.getAssociations();
Set<Topic> usedRoles = new HashSet<>();
for(Association association : associations) {
if(association != null) {
Collection<Topic> roles = association.getRoles();
for(Topic role : roles) {
Topic player = association.getPlayer(role);
if(player != null) {
if(player.mergesWithTopic(topic)) {
if(!usedRoles.contains(role)) {
usedRoles.add(role);
sb.append("\t").append(TopicToString.toString(role));
}
}
}
}
}
}
break;
}
case INCLUDE_ASSOCIATION_COUNT: {
countCollection = topic.getAssociations();
if(countCollection != null) {
sb.append("\t").append(countCollection.size());
}
else {
sb.append("\tNA");
}
break;
}
case INCLUDE_TYPED_ASSOCIATION_COUNT: {
countCollection = topic.getAssociations(associationType);
if(countCollection != null) {
sb.append("\t").append(countCollection.size());
}
else {
sb.append("\tNA");
}
break;
}
case INCLUDE_LAYER_DISTRIBUTION: {
if(topic instanceof LayeredTopic) {
String s = makeDistributionVector((LayeredTopic)topic, wandora.getTopicMap());
sb.append("\t").append(s);
}
break;
}
case INCLUDE_CLUSTER_COEFFICIENT: {
sb.append("\t").append(TopicClusteringCoefficient.getClusteringCoefficientFor(topic, new TopicClusteringCoefficient.DefaultNeighborhood()));
}
}
lines.add(sb.toString());
}
}
catch (Exception e) {
log(e);
}
}
if(OUTPUT_LOG) log("Sorting clipboard text.");
Collections.sort(lines);
ClipboardBox.setClipboard(stringSerialize(lines));
if(OUTPUT_LOG) log("Total " + count + " topics copied.");
if(OUTPUT_LOG) log("Ready.");
if(OUTPUT_LOG) setState(WAIT);
topics = null;
}
catch(Exception e) {
log("Copying "+ getTopicTypeName() +" to clipboard failed!", e);
}
}
private String stringSerialize(List<String> lines) {
StringBuilder sb = new StringBuilder("");
if(lines != null) {
for(String line : lines) {
sb.append(line);
sb.append("\n");
}
}
return sb.toString();
};
private String makeDistributionVector(LayeredTopic topic,ContainerTopicMap tm) throws TopicMapException {
StringBuilder sb=new StringBuilder();
for(Layer l : tm.getLayers()){
// if(sb.length()!=0) sb.append(":");
if(sb.length()!=0) sb.append("\t");
TopicMap ltm=l.getTopicMap();
if(ltm instanceof ContainerTopicMap){
sb.append("(\t");
sb.append(makeDistributionVector(topic,(ContainerTopicMap)ltm));
sb.append("\t)");
}
else{
int num=0;
if(l.isVisible()) num=l.getTopicMap().getMergingTopics(topic).size();
sb.append("").append(num);
}
}
return sb.toString();
}
private String getDisplayName(Topic t, String lang) throws TopicMapException {
String langsi=XTMPSI.getLang(lang);
Topic langT =t.getTopicMap().getTopic(langsi);
String dispsi=XTMPSI.DISPLAY;
Topic dispT=t.getTopicMap().getTopic(dispsi);
Set<Topic> scope=new LinkedHashSet<>();
if(langT!=null) scope.add(langT);
if(dispT!=null) scope.add(dispT);
String variantName = t.getVariant(scope);
return (variantName == null ? "" : variantName);
}
private String getTextData(Topic t, Topic type, String versions) throws TopicMapException {
String langsi=XTMPSI.getLang(versions);
Topic version=t.getTopicMap().getTopic(langsi);
String textData = t.getData(type, version);
return (textData == null ? "" : textData);
}
private List<Topic> getOccurrenceTypes(TopicMap tm) throws TopicMapException {
Set<Topic> occurrenceTypes = new LinkedHashSet<>();
if(tm != null) {
Topic t = null;
Iterator<Topic> topics = tm.getTopics();
while(topics.hasNext() && !forceStop()) {
t = topics.next();
if(t != null && !t.isRemoved()) {
occurrenceTypes.addAll(t.getDataTypes());
}
}
}
List<Topic> ot = new ArrayList<>();
ot.addAll(occurrenceTypes);
return ot;
}
}
| 30,258 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
FindTopicsWithSimilarOccurrence.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/FindTopicsWithSimilarOccurrence.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;
import java.util.HashSet;
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.search.SearchTopicsResults;
import org.wandora.application.gui.texteditor.OccurrenceTextEditor;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import uk.ac.shef.wit.simmetrics.similaritymetrics.InterfaceStringMetric;
import uk.ac.shef.wit.simmetrics.similaritymetrics.Levenshtein;
/**
*
* @author akivela
*/
public class FindTopicsWithSimilarOccurrence extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
public static final String OPTIONS_PREFIX = "options.occurrence.similarity.";
private InterfaceStringMetric stringMetric = null;
private float similarityThreshold = 0.5f;
private boolean allowOverride = true;
public FindTopicsWithSimilarOccurrence() {
stringMetric = new Levenshtein();
}
public FindTopicsWithSimilarOccurrence(Context preferredContext) {
stringMetric = new Levenshtein();
this.setContext(preferredContext);
}
public FindTopicsWithSimilarOccurrence(Context preferredContext, InterfaceStringMetric stringMetric, float threshold) {
this.setContext(preferredContext);
this.stringMetric = stringMetric;
this.similarityThreshold = threshold;
allowOverride = false;
}
public FindTopicsWithSimilarOccurrence(InterfaceStringMetric stringMetric, float threshold) {
this.stringMetric = stringMetric;
this.similarityThreshold = threshold;
allowOverride = false;
}
@Override
public void initialize(Wandora wandora, org.wandora.utils.Options options,String prefix) throws TopicMapException {
if(allowOverride) {
try {
String metric=options.get(OPTIONS_PREFIX+"metric");
if(metric != null){
setMetricByClassName(metric);
}
similarityThreshold=options.getFloat(OPTIONS_PREFIX+"threshold", 0.75f);
}
catch(Exception e) {
wandora.handleError(e);
}
}
}
@Override
public boolean isConfigurable(){
return true;
}
@Override
public void configure(Wandora wandora, org.wandora.utils.Options options, String prefix) throws TopicMapException {
if(allowOverride) {
try {
initialize(wandora, options, prefix);
GenericOptionsDialog god=new GenericOptionsDialog(wandora,"Configurable options for similar occurrence topic finder","Find topic with similar occurrence options",true,new String[][]{
new String[]{"Similarity metric","string",stringMetric.getClass().getCanonicalName(),"Class name for similarity metric."},
new String[]{"Similarity threshold","string", ""+similarityThreshold, "0.0 - 1.0"},
},wandora);
god.setVisible(true);
if(god.wasCancelled()) return;
// ---- ok ----
Map<String,String> values=god.getValues();
setMetricByClassName(values.get("Similarity metric"));
String thresholdString = values.get("Similarity threshold");
similarityThreshold = Float.parseFloat(thresholdString);
writeOptions(wandora, options, prefix);
}
catch(Exception e) {
wandora.handleError(e);
}
}
}
@Override
public void writeOptions(Wandora wandora, org.wandora.utils.Options options, String prefix){
if(allowOverride) {
options.put(OPTIONS_PREFIX+"metric", stringMetric.getClass().getCanonicalName());
options.put(OPTIONS_PREFIX+"threshold", ""+similarityThreshold);
}
}
private void setMetricByClassName(String metric) throws Exception {
if(metric != null){
Class metricClass = Class.forName(metric);
if(metricClass != null) {
stringMetric = (InterfaceStringMetric) metricClass.getConstructor().newInstance();
}
}
}
@Override
public String getName() {
return "Find topics with similar occurrence";
}
@Override
public String getDescription() {
return "Find topics with similar occurrence.";
}
@Override
public void execute(Wandora wandora, Context context) {
Iterator topics = context.getContextObjects();
if(topics == null || !topics.hasNext()) return;
String o1 = null;
Topic o1Type = null;
Topic o1Scope = null;
try {
Object source = getContext().getContextSource();
if(source instanceof OccurrenceTextEditor) {
OccurrenceTextEditor editor = (OccurrenceTextEditor) source;
o1Type = editor.getOccurrenceType();
o1Scope = editor.getOccurrenceVersion();
o1 = editor.getSelectedText();
if(o1 == null || o1.length() == 0) {
o1 = editor.getText();
}
}
// Ensure occurrence type and scope are really ok...
if(o1Type == null) {
o1Type=wandora.showTopicFinder("Select occurrence type...");
if(o1Type == null) return;
}
if(o1Scope == null) {
o1Scope=wandora.showTopicFinder("Select occurrence scope...");
if(o1Scope == null) return;
}
if(o1 == null) {
Topic o1Topic = (Topic) topics.next();
o1 = o1Topic.getData(o1Type, o1Scope);
}
// Initialize tool logger and variable...
setDefaultLogger();
setLogTitle("Find topics with similar occurrences");
log("Searching for topics with similar occurrences");
if(o1 == null || o1.length() == 0) {
log("Found no reference occurrence or reference occurrence length is zero.");
}
else {
HashSet<Topic> results = new HashSet<Topic>();
TopicMap tm = wandora.getTopicMap();
Iterator<Topic> allTopics = tm.getTopics();
Topic t = null;
String o2;
float similarity = 0.0f;
int progress = 0;
while(allTopics.hasNext() && !forceStop()) {
t = allTopics.next();
if(t != null && !t.isRemoved()) {
o2 = t.getData(o1Type, o1Scope);
if(o2 != null && o2.length() > 0) {
similarity = stringMetric.getSimilarity(o1, o2);
if(similarity > similarityThreshold) {
results.add(t);
log("Found '"+getTopicName(t)+"'");
}
}
}
setProgress(progress++);
}
if(results.size() > 0) {
SearchTopicsResults resultDialog = new SearchTopicsResults(wandora, results);
resultDialog.hideAgainButton();
setState(INVISIBLE);
resultDialog.setVisible(true);
return;
}
else {
log("Found no topics with similar occurrences.");
}
}
}
catch(Exception e){
log(e);
}
setState(WAIT);
}
@Override
public boolean requiresRefresh() {
return false;
}
}
| 8,848 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
PictureView.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/PictureView.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/>.
*
*
*
* PictureView.java
*
* Created on July 19, 2004, 2:38 PM
*/
package org.wandora.application.tools;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
/**
*
* @author olli
*/
public class PictureView extends javax.swing.JDialog {
private BufferedImage image;
/** Creates new form PictureView */
public PictureView(java.awt.Dialog parent, boolean modal,BufferedImage image) {
super(parent, modal);
this.image=image;
initComponents();
this.picturePanel.setMinimumSize(new java.awt.Dimension(image.getWidth(),image.getHeight()));
this.picturePanel.setPreferredSize(new java.awt.Dimension(image.getWidth(),image.getHeight()));
// this.picturePanel.setSize(image.getWidth(),image.getHeight());
org.wandora.utils.swing.GuiTools.centerWindow(this,parent);
this.invalidate();
}
public PictureView(java.awt.Frame parent, boolean modal,BufferedImage image) {
super(parent, modal);
this.image=image;
initComponents();
this.picturePanel.setMinimumSize(new java.awt.Dimension(image.getWidth(),image.getHeight()));
this.picturePanel.setPreferredSize(new java.awt.Dimension(image.getWidth(),image.getHeight()));
// this.picturePanel.setSize(image.getWidth(),image.getHeight());
this.setLocation(parent.getLocation().x+parent.getWidth()/2-this.getWidth()/2,
parent.getLocation().y+parent.getHeight()/2-this.getHeight()/2);
this.invalidate();
}
/** 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.
*/
private void initComponents() {//GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
jButton = new javax.swing.JButton();
jScrollPane = new javax.swing.JScrollPane();
picturePanel = new javax.swing.JPanel() {
public void paint(Graphics g){
super.paint(g);
g.drawImage(image,0,0,image.getWidth(),image.getHeight(),null);
}
};
getContentPane().setLayout(new java.awt.GridBagLayout());
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jButton.setText("Close");
jButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
getContentPane().add(jButton, gridBagConstraints);
jScrollPane.setViewportView(picturePanel);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
getContentPane().add(jScrollPane, gridBagConstraints);
setBounds(0, 0, 567, 560);
}//GEN-END:initComponents
private void jButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonActionPerformed
this.setVisible(false);
}//GEN-LAST:event_jButtonActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton;
private javax.swing.JScrollPane jScrollPane;
private javax.swing.JPanel picturePanel;
// End of variables declaration//GEN-END:variables
}
| 4,528 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SystemClipboardCopy.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/SystemClipboardCopy.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;
/**
*
* @author akikivela
*/
public class SystemClipboardCopy extends SystemClipboard {
private static final long serialVersionUID = 1L;
public SystemClipboardCopy() {
super(SystemClipboard.COPY);
}
}
| 1,070 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
GenericOptionsDialog.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/GenericOptionsDialog.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/>.
*
*
*
* GenericOptionsDialog.java
*
* Created on 25.7.2006, 15:30
*/
package org.wandora.application.tools;
import java.util.Map;
import javax.swing.JPanel;
import org.wandora.application.Wandora;
import org.wandora.application.gui.simple.SimpleScrollPane;
import org.wandora.utils.swing.GuiTools;
/**
* <p>
* This is a class to display a customizable options dialog. You can choose how
* many and what kinds of fields there will be in the dialog. However if you need
* a more complex options dialog than just a collection input fields, you will need
* to make a separate class for that. This class is only able to make simple
* options dialogs but at the same time it is very easy to use this class.
* </p>
*
* @author olli
*/
public class GenericOptionsDialog extends javax.swing.JDialog {
private static final long serialVersionUID = 1L;
protected String[][] fieldData;
protected boolean wasCancelled=true;
protected Wandora admin;
protected JPanel paddingPanel;
/**
* Creates and initializes an options dialog. You need to give a string for
* dialog title and a short info text. You will also need to give a data
* structure describing all fields used in the dialog. See initFields for
* description about the data structure. Wandora is needed if field type
* "topic" is used.
*/
public GenericOptionsDialog(java.awt.Frame parent, String title,String info,boolean modal,String[][] fields,Wandora admin) {
super(parent, modal);
this.admin=admin;
this.fieldData=fields;
initComponents();
this.setTitle(title);
infoLabel.setText("<html>"+info+"</html>");
GuiTools.centerWindow(this,parent);
}
public GenericOptionsDialog(java.awt.Frame parent, String title,String info,boolean modal,String[][] fields) {
this(parent,title,info,modal,fields,null);
}
/**
* Gets the values from this options dialog. Return value is a map that
* maps field IDs to their values. Note that all values are converted to
* string regardless of the field type. Boolean fields are converted to
* "true" or "false".
*/
public Map<String,String> getValues(){
return ((GenericOptionsPanel)contentPanel).getValues();
}
public GenericOptionsPanel getContentPanel(){
return (GenericOptionsPanel)contentPanel;
}
/** 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;
scrollPane = new SimpleScrollPane();
contentPanel = new GenericOptionsPanel(fieldData,admin);
jPanel1 = new javax.swing.JPanel();
okButton = new org.wandora.application.gui.simple.SimpleButton();
cancelButton = new org.wandora.application.gui.simple.SimpleButton();
infoLabel = new org.wandora.application.gui.simple.SimpleLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
getContentPane().setLayout(new java.awt.GridBagLayout());
contentPanel.setLayout(new javax.swing.BoxLayout(contentPanel, javax.swing.BoxLayout.LINE_AXIS));
scrollPane.setViewportView(contentPanel);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 0, 4);
getContentPane().add(scrollPane, gridBagConstraints);
jPanel1.setLayout(new java.awt.GridBagLayout());
okButton.setText("OK");
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.insets = new java.awt.Insets(0, 0, 0, 3);
jPanel1.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);
}
});
jPanel1.add(cancelButton, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
getContentPane().add(jPanel1, gridBagConstraints);
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);
getContentPane().add(infoLabel, gridBagConstraints);
setSize(new java.awt.Dimension(442, 339));
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
wasCancelled=true;
this.setVisible(false);
}//GEN-LAST:event_cancelButtonActionPerformed
private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
wasCancelled=false;
this.setVisible(false);
}//GEN-LAST:event_okButtonActionPerformed
/**
* Checks if user closed the dialog with the cancel button.
*/
public boolean wasCancelled(){
return wasCancelled;
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton cancelButton;
protected javax.swing.JPanel contentPanel;
private javax.swing.JLabel infoLabel;
private javax.swing.JPanel jPanel1;
private javax.swing.JButton okButton;
private javax.swing.JScrollPane scrollPane;
// End of variables declaration//GEN-END:variables
}
| 7,926 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SetTopicStringifier.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/SetTopicStringifier.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/>.
*
*
* SetTopicStringifier.java
*
*/
package org.wandora.application.tools;
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.topicstringify.TopicStringifier;
import org.wandora.application.gui.topicstringify.TopicToString;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author akivela
*/
public class SetTopicStringifier extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
private TopicStringifier topicStringifier = null;
public SetTopicStringifier(TopicStringifier r) {
topicStringifier = r;
}
@Override
public String getName() {
return "Topic renders";
}
@Override
public String getDescription() {
if(topicStringifier == null) {
return "Topic renders";
}
else {
return topicStringifier.getDescription();
}
}
@Override
public boolean requiresRefresh() {
return true;
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/view_topic_as.png");
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
boolean success = topicStringifier.initialize(wandora, context);
if(success) {
TopicToString.setStringifier(topicStringifier);
}
}
}
| 2,379 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
DeleteTopicsWithoutBasename.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/DeleteTopicsWithoutBasename.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/>.
*
*
*
* DeleteTopicsWithoutBasename.java
*
* Created on 10. huhtikuuta 2005, 14:32
*/
package org.wandora.application.tools;
import org.wandora.application.WandoraTool;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author akivela
*/
public class DeleteTopicsWithoutBasename extends DeleteTopics implements WandoraTool {
private static final long serialVersionUID = 1L;
@Override
public String getName() {
return "Delete topics without base name";
}
@Override
public String getDescription() {
return "Delete context topics that have no base name or base name length is zero.";
}
@Override
public boolean shouldDelete(Topic topic) throws TopicMapException {
try {
if(topic != null && !topic.isRemoved()) {
String basename = topic.getBaseName();
if(basename == null || basename.length() == 0) {
if(confirm) {
return confirmDelete(topic);
}
else {
return true;
}
}
}
}
catch(Exception e) {
log(e);
}
return false;
}
}
| 2,108 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AddClass.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/AddClass.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/>.
*
*
* AddClass.java
*
* Created on 24. lokakuuta 2005, 20:04
*
*/
package org.wandora.application.tools;
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;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author akivela
*/
public class AddClass extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
private boolean shouldRefresh = false;
/** Creates a new instance of AddClass */
public AddClass() {
}
public AddClass(Context preferredContext) {
setContext(preferredContext);
}
@Override
public String getName() {
return "Add class";
}
@Override
public String getDescription() {
return "Add a class topic to selected topics.";
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
shouldRefresh = false;
Iterator topics = context.getContextObjects();
if(topics != null && topics.hasNext()) {
Topic classTopic=wandora.showTopicFinder();
Topic topic = null;
if(classTopic != null) {
while(topics.hasNext() && !forceStop()) {
try {
topic = (Topic) topics.next();
if(topic != null && !topic.isRemoved()) {
shouldRefresh = true;
topic.addType(classTopic);
}
}
catch(Exception e) {
log(e);
}
}
}
}
}
@Override
public boolean requiresRefresh() {
return shouldRefresh;
}
}
| 2,715 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
Exec.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/Exec.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/>.
*
*
*
* Exec.java
*
* Created on 7. marraskuuta 2005, 11:29
*/
package org.wandora.application.tools;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.Context;
/**
* WandoraTool executing an external application such as WWW browser.
*
* @author akivela
*/
public class Exec extends AbstractWandoraTool implements WandoraTool, Runnable {
private static final long serialVersionUID = 1L;
private String command = null;
public Exec(){
}
public Exec(String command){
this.command=command;
}
@Override
public void execute(Wandora admin, Context context) {
Process process=null;
try {
if(command != null) {
process=Runtime.getRuntime().exec(command,new String[]{"HOME=/home/"});
}
else {
singleLog("No external command defined!");
}
}
catch(Exception e) {
return;
}
/*
* TODO: Looks like the thread is never released here!
* A tool should not be kept by the thread for ever!!!
*
byte[] buf=new byte[256];
boolean running=true;
while(running){
int r=0;
try{
if(process.getInputStream().available()>0){
r+=process.getInputStream().read(buf);
System.out.write(buf,0,r);
}
if(process.getErrorStream().available()>0){
r+=process.getErrorStream().read(buf);
System.err.write(buf,0,r);
}
}catch(java.io.IOException ioe){return;}
if(r==0){
try{
Thread.sleep(500);
}catch(InterruptedException ie){return;}
}
}
**/
}
@Override
public boolean allowMultipleInvocations() {
return true;
}
@Override
public String getName() {
return "Exec";
}
@Override
public String getDescription() {
return "Execute external applications such as WWW browser.";
}
@Override
public boolean requiresRefresh() {
return false;
}
}
| 3,121 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
UploadFile.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/UploadFile.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/>.
*
*
*
* UploadFile.java
*
* Created on 26.7.2006, 12:21
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package org.wandora.application.tools;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;
import org.wandora.application.Wandora;
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.topicmap.TopicMapException;
/*
* 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/>.
*
*/
import org.wandora.utils.fileserver.SimpleFileServerClient;
/**
*
* @author olli
*/
public class UploadFile extends AbstractWandoraTool {
private static final long serialVersionUID = 1L;
private String host;
private int port;
private String user;
private String password;
boolean useSSL;
/** Creates a new instance of UploadFile */
public UploadFile() {
host="127.0.0.1";
port=8898;
user=null;
password=null;
useSSL=false;
}
@Override
public String getName() {
return "Upload file";
}
@Override
public String getDescription() {
return "Uploads a file to a file server.";
}
@Override
public void initialize(Wandora admin,org.wandora.utils.Options options,String prefix) throws TopicMapException {
host=options.get(prefix+"host");
String p=options.get(prefix+"port");
port=Integer.parseInt(p);
user=options.get(prefix+"user");
if(user!=null && user.length()==0) user=null;
password=options.get(prefix+"password");
if(password!=null && password.length()==0) password=null;
String s=options.get(prefix+"usessl");
if(s!=null && s.equalsIgnoreCase("true")) useSSL=true;
else useSSL=false;
}
@Override
public boolean isConfigurable(){
return true;
}
@Override
public void configure(Wandora admin,org.wandora.utils.Options options,String prefix) throws TopicMapException {
GenericOptionsDialog god=new GenericOptionsDialog(admin,"Upload file options","File server connection options",true,new String[][]{
new String[]{"Host","string",host},
new String[]{"Port","string",""+port},
new String[]{"Use SSL","boolean",""+useSSL},
new String[]{"User","string",user},
new String[]{"Password","password",password},
});
god.setVisible(true);
if(god.wasCancelled()) return;
Map<String,String> values=god.getValues();
host=values.get("Host");
port=Integer.parseInt(values.get("Port"));
useSSL=values.get("Use SSL").equalsIgnoreCase("true");
user=values.get("User");
password=values.get("Password");
if(user!=null && user.length()==0) user=null;
if(password!=null && password.length()==0) password=null;
writeOptions(admin,options,prefix);
}
@Override
public void writeOptions(Wandora admin,org.wandora.utils.Options options,String prefix){
options.put(prefix+"host",host);
options.put(prefix+"port",""+port);
options.put(prefix+"user",user==null?"":user);
options.put(prefix+"password",password==null?"":password);
options.put(prefix+"usessl",useSSL?"true":"false");
}
@Override
public void execute(Wandora admin, Context context) throws TopicMapException {
setDefaultLogger();
SimpleFileChooser chooser=UIConstants.getFileChooser();
chooser.setMultiSelectionEnabled(true);
chooser.setDialogTitle("Select file to send");
if(chooser.open(admin, SimpleFileChooser.OPEN_DIALOG)==SimpleFileChooser.APPROVE_OPTION) {
File f=chooser.getSelectedFile();
if(f==null) return;
String filename=WandoraOptionPane.showInputDialog(admin,"Enter remote path and filename",f.getName());
if(filename==null) return;
java.net.Socket s=null;
try{
SimpleFileServerClient fs=new SimpleFileServerClient();
s=fs.connect(host,port,useSSL);
InputStream in=s.getInputStream();
OutputStream out=s.getOutputStream();
Writer writer=new OutputStreamWriter(out);
if(!fs.login(in,writer,user,password)){
log("Couldn't login to file server");
log("Server response: "+fs.getLastServerResponse());
setState(WAIT);
return;
}
if(!fs.sendFile(in,writer,out,filename,chooser.getSelectedFile())){
log("Could not send file");
log("Server response: "+fs.getLastServerResponse());
setState(WAIT);
return;
}
String url=fs.getURLFor(in,writer,filename);
if(url==null) log("File sent, could not get url for file.");
else if(url.length()==0) log("File sent, server did not return url for file.");
else log("File sent, url for file is "+url);
fs.logout(writer);
}
catch(IOException ioe){
log(ioe);
}
finally{
if(s!=null) try{s.close();}catch(IOException ioe){}
}
setState(WAIT);
}
}
}
| 7,254 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AbstractWandoraTool.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/AbstractWandoraTool.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/>.
*
*
* AbstractWandoraTool.java
*
* Created on 20. lokakuuta 2005, 19:20
*
*/
package org.wandora.application.tools;
import static org.wandora.application.gui.ConfirmResult.cancel;
import static org.wandora.application.gui.ConfirmResult.notoall;
import java.awt.Desktop;
import java.awt.event.ActionEvent;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import javax.swing.Icon;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import org.wandora.application.ErrorMessages;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.WandoraToolActionListener;
import org.wandora.application.WandoraToolLogger;
import org.wandora.application.WandoraToolType;
import org.wandora.application.contexts.Context;
import org.wandora.application.contexts.LayeredTopicContext;
import org.wandora.application.gui.ConfirmResult;
import org.wandora.application.gui.InfoDialog;
import org.wandora.application.gui.LayerTree;
import org.wandora.application.gui.UIBox;
import org.wandora.application.gui.WandoraOptionPane;
import org.wandora.application.gui.simple.SimpleMenuItem;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.topicmap.layered.Layer;
import org.wandora.utils.Textbox;
import org.wandora.utils.Tuples.T2;
/**
* <code>AbstractWandoraTool</code> provides basic services and methods to
* all <code>WandoraTool</code> classes. All tools should extend this
* abstract class.
*
* @author akivela
*/
public abstract class AbstractWandoraTool implements WandoraTool, Runnable {
private static final long serialVersionUID = 1L;
private Exception toolException;
private WandoraToolLogger lastLogger = null;
private WandoraToolLogger logger = null;
private boolean internalForceStop;
private Wandora runAdmin = null;
private Context runContext = null;
private static final Set<Class> toolLocks = new LinkedHashSet<Class>();
private static final Map<Thread,T2<Class,Long>> toolThreads = new HashMap<Thread,T2<Class,Long>>();
public AbstractWandoraTool() {
}
// -------------------------------------------------------------------------
// ------------------------------------------------------ EXECUTING TOOL ---
// -------------------------------------------------------------------------
/* *
* This is first entry point to execute the tool. Use this entry point when
* you wish to execute the tool from your own code. Method just fills the
* event slot with null and calls the event triggered execute.
*/
@Override
public void execute(Wandora wandora) throws TopicMapException {
execute(wandora, (ActionEvent) null);
}
/**
* This is the primary entry point to execute the tool. All UI
* actions should enter the tool here. Usually this method is called
* from the <code>WandoraToolActionListener</code>.
*/
@Override
public void execute(Wandora wandora, ActionEvent event) throws TopicMapException {
internalForceStop = false;
if(event != null) {
int modifiers=event.getModifiers();
if((modifiers&ActionEvent.SHIFT_MASK)!=0 && (modifiers&ActionEvent.CTRL_MASK)!=0 && (modifiers&ActionEvent.MOUSE_EVENT_MASK)!=0 ) {
try {
if(wandora != null) {
String className = this.getClass().getName();
String helpName = className.substring(className.lastIndexOf('.')+1);
String helpUrl = wandora.getOptions().get("helpviewer");
if(helpUrl != null) helpUrl = helpUrl.replaceAll("__HELP__", helpName);
Desktop desktop = Desktop.getDesktop();
desktop.browse(new URI(helpUrl));
try { Thread.sleep(200); }
catch(Exception e) {} // WAKEUP!
}
}
catch(Exception e) {
e.printStackTrace();
}
return;
}
if((modifiers&ActionEvent.CTRL_MASK)!=0 && (modifiers&ActionEvent.MOUSE_EVENT_MASK)!=0 ) {
try {
boolean configured=false;
if(isConfigurable()){
String prefix=wandora.getToolManager().getOptionsPrefix(this);
if(prefix == null) {
prefix = "options."+this.getClass().getCanonicalName();
}
configured=true;
configure(wandora,wandora.getOptions(),prefix);
}
if(!configured) WandoraOptionPane.showMessageDialog(wandora,"Tool is not configurable","Tool is not configurable");
if(!allowMultipleInvocations()){
synchronized(toolLocks){
toolLocks.remove(this.getClass());
}
}
}
catch(Exception e) {
e.printStackTrace();
}
return;
}
if((modifiers&ActionEvent.ALT_MASK)!=0 && (modifiers&ActionEvent.MOUSE_EVENT_MASK)!=0 ) {
try {
synchronized(toolLocks){
toolLocks.remove(this.getClass());
}
}
catch(Exception e) {
e.printStackTrace();
}
}
}
if(!allowMultipleInvocations()){
synchronized(toolLocks){
if(toolLocks.contains(this.getClass())){
singleLog("Tool '"+this.getName()+"' already running!\nWait or use clear tool locks.");
return;
}
toolLocks.add(this.getClass());
}
}
runAdmin = wandora;
if(runContext == null) { runContext = new LayeredTopicContext(); }
// TODO: runContext is overwritten if the same instance of a tool
// is executed again.
runContext.initialize(wandora, event, this);
if(runInOwnThread()) {
Thread worker = new Thread(this, getName());
synchronized(toolThreads) {
toolThreads.put(worker, new T2(this.getClass(), Long.valueOf(System.currentTimeMillis())));
}
//SwingUtilities.invokeLater(worker);
worker.start();
}
else {
run();
}
}
/**
* Runs the tool. If <code>runInOwnThread</code> returns false,
* this method is called directly instead of creating a new <code>Thread</code>.
* This method passes the execution to extending implementation of
* <code>execute</code>.
*/
@Override
public void run() {
toolException = null;
try {
if(runAdmin != null) {
runAdmin.setAnimated(true, this);
}
execute(runAdmin, runContext);
}
catch(Exception e) {
if(runAdmin != null) {
runAdmin.displayException(ErrorMessages.getMessage(e, this), e);
}
toolException = e;
}
catch(Error er) {
if(runAdmin != null) {
runAdmin.displayException(ErrorMessages.getMessage(er, this), er);
}
}
if(!allowMultipleInvocations()) {
synchronized(toolLocks){
toolLocks.remove(this.getClass());
}
}
if(runInOwnThread()) {
synchronized(toolThreads) {
try {
toolThreads.remove(Thread.currentThread());
}
catch(Exception e) {
e.printStackTrace();
}
}
}
try {
if(runAdmin != null) {
if(requiresRefresh()) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
runAdmin.doRefresh();
}
catch(Exception e) {
// SKIPPING
}
}
});
}
else {
// requiresRefresh() == false --> Do nothing
}
}
}
catch(Exception e) {
System.out.println("Refresh failed in AbstractAdminTool!");
e.printStackTrace();
}
if(runAdmin != null) {
runAdmin.setAnimated(false, this);
}
if(logger != null && logger.getState() == EXECUTE) {
System.out.println("Warning! Logger still running when leaving tool! Closing logger!");
logger.setState(CLOSE);
}
if(logger != null) {
lastLogger = logger;
logger = null;
}
}
/**
* Checks if this (extended) tool is running.
*
* @return boolean true if the tool is running.
*/
@Override
public boolean isRunning() {
return isRunning(this.getClass());
}
/**
* Checks if given tool is already running and
* locked.
*
* @return boolean true if the tool is running.
*/
public boolean isRunning(Class c) {
synchronized(toolLocks){
if(toolLocks.contains(c)){
return true;
}
}
return false;
}
/**
* Releases a tool lock for this (extending) tool class.
*
* @return boolean true if a lock was released.
*/
public boolean clearToolLock() {
return clearToolLock(this.getClass());
}
/**
* Releases a tool lock for a given tool class. Tool lock prevents tool execution
* while previous execution is unfinished. Doesn't stop nor kill the thread
* that runs the previous execution.
*
* @param c Tool class to be released.
* @return boolean true if a lock was released.
*/
public static boolean clearToolLock(Class c) {
if(c != null) {
synchronized(toolLocks){
if(toolLocks.contains(c)) {
toolLocks.remove(c);
return true;
}
}
}
return false;
}
/**
* Releases all locks that prevent tools to be executed again.
* Notice the method doesn't kill any threads. Threads must be interrupted
* separately with interruptAllThreads method.
*
* @return Integer number of locks released.
*/
public static int clearToolLocks() {
int n = 0;
synchronized(toolLocks){
n = toolLocks.size();
toolLocks.clear();
}
Wandora w = Wandora.getWandora();
if(w != null) {
w.forceStopAnimation();
}
return n;
}
public void interruptThreads() {
interruptThreads(this.getClass());
}
public static void interruptThreads(Class c) {
if(c == null) return;
synchronized(toolThreads) {
try {
T2<Class, Long> timedClass = null;
for( Thread toolThread : toolThreads.keySet() ) {
timedClass = toolThreads.get(toolThread);
if(c.equals(timedClass.e1)) {
toolThread.interrupt();
}
}
}
catch(Exception e) {
e.printStackTrace();
}
}
}
public static void interruptAllThreads() {
synchronized(toolThreads) {
try {
for( Thread toolThread : toolThreads.keySet() ) {
toolThread.interrupt();
}
}
catch(Exception e) {
e.printStackTrace();
}
}
}
public void clearThreads() {
clearThreads(this.getClass());
}
public static void clearThreads(Class c) {
if(c == null) return;
synchronized(toolThreads) {
ArrayList<Thread> threadList = new ArrayList<Thread>();
try {
T2<Class, Long> timedClass = null;
for( Thread toolThread : toolThreads.keySet() ) {
timedClass = toolThreads.get(toolThread);
if(c.equals(timedClass.e1)) {
threadList.add(toolThread);
}
}
for( Thread toolThread : threadList ) {
toolThreads.remove(toolThread);
}
}
catch(Exception e) {
e.printStackTrace();
}
}
}
public static void clearAllThreads() {
synchronized(toolThreads) {
ArrayList<Thread> threadList = new ArrayList<Thread>();
try {
for( Thread toolThread : toolThreads.keySet() ) {
threadList.add(toolThread);
}
for( Thread toolThread : threadList ) {
toolThreads.remove(toolThread);
}
}
catch(Exception e) {
e.printStackTrace();
}
}
}
public ArrayList<T2<Thread,Long>> getThreads() {
return getThreads(this.getClass());
}
public static ArrayList<T2<Thread,Long>> getThreads(Class c) {
ArrayList<T2<Thread, Long>> threadList = new ArrayList<T2<Thread, Long>>();
if(c != null) {
synchronized(toolThreads) {
try {
T2<Class, Long> timedClass = null;
for( Thread toolThread : toolThreads.keySet() ) {
timedClass = toolThreads.get(toolThread);
if(c.equals(timedClass.e1)) {
threadList.add( new T2(toolThread, timedClass.e2) );
}
}
}
catch(Exception e) {
e.printStackTrace();
}
}
}
return threadList;
}
// -------------------------------------------------------------------------
// -------------------------------------------------------- TOOL FLAVOUR ---
// -------------------------------------------------------------------------
/**
* Whether or not this tool should fork own thread. If own thread is allowed,
* the execution of the tool return immediately. If own thread is not allowed
* the thread entering initial execute method is used. Extending classes should
* override this method.
*
* @return true if the tool should should be ran in separate thread.
*/
public boolean runInOwnThread() {
return true;
}
/**
* <p>
* Tool type is used to categorize tools. Tool type has no real effect today,
* it is merely an informative property of a tool.
* </p>
*/
@Override
public WandoraToolType getType(){
return WandoraToolType.createGenericType();
}
/**
* Tools name represent the tool in UI unless the tool has been given
* explicitly another GUI name. All tools should override this method and
* return a valid string representing name of the tool.
*/
@Override
public String getName() {
return "Abstract Tool";
}
/**
* AdminToolManager views tool descriptions while user browses available
* tools and build user customizable GUI elements such as Tools menu.
* By default description equals the tool name.
* All tools should override this method.
*/
@Override
public String getDescription() {
return getName();
}
/**
* <p>
* If any visible topic has been changed during tool execution GUI is
* automatically refreshed. If tool doesn't change topics but GUI still
* requires refresh, tool should override this method and return true.</p>
* <p>
* For example tools that alter the GUI but change no topics should
* return true.</p>
*/
@Override
public boolean requiresRefresh() {
return true;
}
/**
* Should the tool allow more than one running occurrence of same tool class.
* Sometimes it is necessary to prevent user running same tool after previous
* execution has ended. This is the case if tool for example requires much
* computing power or locks computing resources. By default tool is not
* allowed to run multiple parallel instances.
*
* @return true if the tool can be executed while previous executions is
* still running.
*/
public boolean allowMultipleInvocations() {
return false;
}
/**
* <code>WandoraWandoraTool</code> should be GUI independent allowing tool
* to be inserted into various type of GUI elements such as menus.
* This method is used to wrap tool into <code>SimpleMenuItem</code>.
*/
@Override
public SimpleMenuItem getToolMenuItem(Wandora wandora, String instanceName) {
SimpleMenuItem manageMenuItem = new SimpleMenuItem(instanceName, new WandoraToolActionListener(wandora, this));
Icon icon=getIcon();
if(icon!=null) {
manageMenuItem.setIcon(icon);
}
String description = getDescription();
if(description != null && description.length() > 0) {
manageMenuItem.setToolTipText(Textbox.makeHTMLParagraph(description, 30));
}
return manageMenuItem;
}
public SimpleMenuItem getToolMenuItem(Wandora wandora, String instanceName, KeyStroke keyStroke) {
SimpleMenuItem menuItem = getToolMenuItem(wandora,instanceName);
if(keyStroke != null) {
menuItem.setAccelerator(keyStroke);
}
return menuItem;
}
/**
* All tools may have identifying graphic icon used within tool GUI elements.
* <code>getIcon</code> should return <code>Icon</code> object of
* the tool.
*/
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/generic_tool.png");
}
// -------------------------------------------------------------------------
// ---------------------------------------------------- CONFIGURING TOOL ---
// -------------------------------------------------------------------------
/**
* Initializes a tool with options saved in the options. Options for
* this tool start with the given prefix. What options the tool saves
* is entirely tool specific.
*/
@Override
public void initialize(Wandora wandora, org.wandora.utils.Options options, String prefix) throws TopicMapException {
}
/**
* Whether this tool is configurable. Configurable tools will provide an interface
* to configure themselves. To make a configurable tool you will need to:
* <ul>
* <li>Implement isConfigurable method and return true there.</li>
* <li>Implement initialize method to initialize the tool with saved options.</li>
* <li>Implement configure method to provide the user interface for configuration and then
* save the new options.</li>
* <li>Implement writeOptions method to save the current options.</li>
* </ul>
*/
@Override
public boolean isConfigurable(){
return false;
}
/**
* If the tool is configurable, shows an user interface to configure the tool. The user
* may edit tool options which this method also need to save. Options specific
* to this tool should be saved with keys starting with the given prefix.
*/
@Override
public void configure(Wandora wandora ,org.wandora.utils.Options options, String prefix) throws TopicMapException {
}
/**
* If the tool is configurable, saves all current tool options. Options specific
* to this tool should be saved with keys starting with the given prefix.
*/
@Override
public void writeOptions(Wandora wandora, org.wandora.utils.Options options, String prefix){
}
// -------------------------------------------------------------------------
// --------------------------------------------------- ACCESSING CONTEXT ---
// -------------------------------------------------------------------------
/**
* Each executed tool has <code>Context</code> containing context source and
* context objects. Context source is a GUI element that originates the
* tool execution. <code>Context</code> object reads context source and
* solves context objects available in tool. Generally tools modify context
* objects. <code>setContext</code> method is used to set the <code>Context</code>
* object that transforms context source into context objects. If tool has
* no explicitly set context <code>AbstractWandoraTool</code> uses <code>LayeredTopicContext</code>.
*/
@Override
public void setContext(Context context) { runContext = context; }
/**
* Return tools <code>Context</code>. If tool uses default context ie.
* <code>setContext</code> has not been called with valid <code>Context</code>
* object, tool's context remains undefined (<code>null</code>) until tool
* is executed. Tool context is resolved finally during execution. More over
* context source and thus context object at least are solved during
* execution, not before.
*/
@Override
public Context getContext() { return runContext; }
// -------------------------------------------------------------------------
// ---------------------------------------------------- ACCESSING LOGGER ---
// -------------------------------------------------------------------------
/**
* <p>
* <code>AbstractWandoraTool</code> provides simple framework for tool-user
* communication. If <code>Wandora</code> object is passed to the execute method
* logger is simple dialog window capable to output tool
* originated messages and progress meter. Default dialog also contains simple
* stop button allowing user to interrupt the tool execution (if tool
* acknowledges user interrupts). Default logger dialog is activated
* with <code>setDefaultLogger</code> method.</p>
* <p>
* Note: If your tool requires rich interaction between user and tool
* You may not want to activate default logger at the very beginning of
* your tool.</p>
*/
public void setDefaultLogger() {
setToolLogger(getDefaultLogger());
setLogTitle(getName());
}
public WandoraToolLogger getDefaultLogger() {
if(logger != null) return logger;
if(runAdmin != null) {
InfoDialog infoDialog = new InfoDialog(runAdmin);
infoDialog.setState(InfoDialog.EXECUTE);
return infoDialog;
}
return null;
}
public WandoraToolLogger getCurrentLogger() {
return logger;
}
public WandoraToolLogger getLastLogger() {
return lastLogger;
}
public void singleLog(String message) {
setDefaultLogger();
log(message);
setState(WandoraToolLogger.WAIT);
}
public void singleLog(Exception e) {
setDefaultLogger();
log(e);
setState(WandoraToolLogger.WAIT);
}
public void singleLog(String message, Exception e) {
setDefaultLogger();
log(message, e);
setState(WandoraToolLogger.WAIT);
}
// -------------------------------------------------------------------------
@Override
public void setToolLogger(WandoraToolLogger logger) {
this.logger = logger;
}
// -------------------------------------------------------------------------
@Override
public void hlog(String message) {
if(logger != null) {
logger.hlog(message);
}
else if(runAdmin != null) {
WandoraOptionPane.showMessageDialog(runAdmin, message);
}
else System.out.println(message);
}
@Override
public void log(String message) {
if(logger != null) {
logger.log(message);
}
else if(runAdmin != null) {
WandoraOptionPane.showMessageDialog(runAdmin, message);
}
else System.out.println(message);
}
@Override
public void log(String message, Exception e) {
if(logger != null) {
logger.log(message, e);
}
else if(runAdmin != null) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
WandoraOptionPane.showMessageDialog(runAdmin, message + "\n" + sw.toString(), WandoraOptionPane.ERROR_MESSAGE);
internalForceStop = true;
}
else {
System.out.println(message);
e.printStackTrace();
}
}
@Override
public void log(Exception e) {
if(logger != null) {
logger.log(e);
}
else if(runAdmin != null) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
WandoraOptionPane.showMessageDialog(runAdmin, sw.toString(), WandoraOptionPane.ERROR_MESSAGE);
internalForceStop = true;
}
else {
e.printStackTrace();
}
}
@Override
public void log(Error e) {
if(logger != null) {
logger.log(e);
}
else if(runAdmin != null) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
WandoraOptionPane.showMessageDialog(runAdmin, sw.toString(), WandoraOptionPane.ERROR_MESSAGE);
internalForceStop = true;
}
else {
e.printStackTrace();
}
}
@Override
public void setProgress(int n) {
if(logger != null) logger.setProgress(n);
}
@Override
public void setProgressMax(int maxn) {
if(logger != null) {
logger.setProgressMax(maxn);
}
}
@Override
public void setLogTitle(String title) {
if(logger != null) {
logger.setLogTitle(title);
}
else System.out.println(title);
}
@Override
public void lockLog(boolean lock) {
if(logger != null) {
logger.lockLog(lock);
}
}
@Override
public String getHistory() {
if(logger != null) {
return logger.getHistory();
}
else {
return "";
}
}
@Override
public void setState(int state) {
if(logger != null) {
logger.setState(state);
}
}
@Override
public int getState() {
if(logger != null) {
return logger.getState();
}
else {
return 0;
}
}
@Override
public boolean forceStop() {
if(logger != null) {
return logger.forceStop();
}
else {
return internalForceStop;
}
}
public boolean forceStop(ConfirmResult result) {
if(result == notoall || result == cancel) return true;
if(logger != null) return logger.forceStop();
else return internalForceStop;
}
// -------------------------------------------------------------------------
public TopicMap solveContextTopicMap(Wandora wandora, Context context) {
if(context != null) {
//System.out.println("context-source: " + context.getContextSource());
Object contextSource = context.getContextSource();
if(contextSource != null) {
if(contextSource instanceof TopicMap) {
return (TopicMap) contextSource;
}
else if(contextSource instanceof Layer){
return ((Layer)contextSource).getTopicMap();
}
else if(context.getContextSource() instanceof LayerTree){
return ((LayerTree)context.getContextSource()).getLastClickedLayer().getTopicMap();
}
else if(contextSource instanceof Wandora) {
return ((Wandora) contextSource).getTopicMap();
}
}
}
// Finally if everything else fails...
return wandora.getTopicMap();
}
protected String solveNameForTopicMap(Wandora wandora, TopicMap topicMap) {
if(wandora != null) {
Layer l=wandora.layerTree.findLayerFor(topicMap);
if(l!=null) {
return l.getName();
}
if(topicMap != null && topicMap.equals(wandora.getTopicMap())) {
return "Layer stack";
}
}
return "Unknown";
}
/*
protected Topic getTopicForSelectedLayer(Topic topic) {
if(topic instanceof LayeredTopic) {
topic = ((LayeredTopic) topic).getTopicForSelectedLayer();
}
return topic;
}
**/
// -------------------------------------------------------------------------
/*
* Tools need topic names very often, for logging for example.
* This shortcut method gives an easy way to get topic's name.
*
* <p>Should this method use the class <code>TopicToString</code> instead
* of it's own name resolution code?? Yes, it should!</p>
*/
public static String getTopicName(Topic t) {
if(t == null) {
return "[null]";
}
try {
if(t.isRemoved()) {
return "[removed]";
}
if(t.getBaseName() == null) {
return t.getOneSubjectIdentifier().toExternalForm();
}
return t.getBaseName();
}
catch(Exception e) {
e.printStackTrace();
}
return "[error]";
}
// --------------------------------------------------------- UNDO / REDO ---
protected void addUndoMarker() {
addUndoMarker(this.getName());
}
protected void addUndoMarker(String label) {
if(runAdmin != null) {
String cn = this.getClass().getName();
if(!"org.wandora.application.tools.Undo".equals(cn) && !"org.wandora.application.tools.Redo".equals(cn)) {
runAdmin.addUndoMarker(label);
}
}
}
}
| 32,493 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
DiffToolConfigPanel.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/DiffToolConfigPanel.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;
import java.io.File;
import java.util.List;
import javax.swing.JDialog;
import org.wandora.application.Wandora;
import org.wandora.application.gui.UIConstants;
import org.wandora.application.gui.filechooser.TopicMapFileChooser;
import org.wandora.topicmap.layered.Layer;
/**
*
* @author olli
*/
public class DiffToolConfigPanel extends javax.swing.JPanel {
private static final long serialVersionUID = 1L;
public static final int MODE_FILE=1;
public static final int MODE_LAYER=2;
public static final int MODE_PROJECT=3;
public static final int MODE_NONE=99;
protected Wandora wandora;
protected JDialog parentDialog;
protected boolean cancelled=true;
/** Creates new form DiffToolConfigPanel */
public DiffToolConfigPanel(Wandora wandora,JDialog parentDialog) {
initComponents();
this.wandora=wandora;
this.parentDialog=parentDialog;
List<Layer> layers=wandora.getTopicMap().getLayers();
for(Layer l : layers){
layerComboBox1.addItem(l.getName());
layerComboBox2.addItem(l.getName());
}
map1GroupChanged();
map2GroupChanged();
}
/** 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;
map1Group = new javax.swing.ButtonGroup();
map2Group = new javax.swing.ButtonGroup();
jPanel1 = new javax.swing.JPanel();
map1FileButton = new org.wandora.application.gui.simple.SimpleRadioButton();
map1LayerButton = new org.wandora.application.gui.simple.SimpleRadioButton();
map1ProjectButton = new org.wandora.application.gui.simple.SimpleRadioButton();
layerComboBox1 = new org.wandora.application.gui.simple.SimpleComboBox();
layerComboBox1.setEditable(false);
fileTextField1 = new org.wandora.application.gui.simple.SimpleField();
fileButton1 = new org.wandora.application.gui.simple.SimpleButton();
jPanel2 = new javax.swing.JPanel();
map2FileButton = new org.wandora.application.gui.simple.SimpleRadioButton();
map2LayerButton = new org.wandora.application.gui.simple.SimpleRadioButton();
map2ProjectButton = new org.wandora.application.gui.simple.SimpleRadioButton();
layerComboBox2 = new org.wandora.application.gui.simple.SimpleComboBox();
layerComboBox2.setEditable(false);
fileTextField2 = new org.wandora.application.gui.simple.SimpleField();
fileButton2 = new org.wandora.application.gui.simple.SimpleButton();
formatComboBox = new org.wandora.application.gui.simple.SimpleComboBox();
formatComboBox.setEditable(false);
jLabel1 = new org.wandora.application.gui.simple.SimpleLabel();
buttonsPanel = new javax.swing.JPanel();
okButton = new org.wandora.application.gui.simple.SimpleButton();
cancelButton = new org.wandora.application.gui.simple.SimpleButton();
setLayout(new java.awt.GridBagLayout());
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Topic map 1", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, UIConstants.plainFont));
jPanel1.setLayout(new java.awt.GridBagLayout());
map1Group.add(map1FileButton);
map1FileButton.setSelected(true);
map1FileButton.setText("File");
map1FileButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
map1FileButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 3);
jPanel1.add(map1FileButton, gridBagConstraints);
map1Group.add(map1LayerButton);
map1LayerButton.setText("Layer");
map1LayerButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
map1LayerButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 3);
jPanel1.add(map1LayerButton, gridBagConstraints);
map1Group.add(map1ProjectButton);
map1ProjectButton.setText("Layer stack");
map1ProjectButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
map1ProjectButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 3);
jPanel1.add(map1ProjectButton, gridBagConstraints);
layerComboBox1.setPreferredSize(new java.awt.Dimension(29, 25));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 3);
jPanel1.add(layerComboBox1, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 3);
jPanel1.add(fileTextField1, gridBagConstraints);
fileButton1.setText("Browse");
fileButton1.setMargin(new java.awt.Insets(0, 7, 0, 7));
fileButton1.setPreferredSize(new java.awt.Dimension(69, 25));
fileButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
fileButton1ActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 3);
jPanel1.add(fileButton1, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 3, 5);
add(jPanel1, gridBagConstraints);
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Topic Map 2", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, UIConstants.plainFont));
jPanel2.setLayout(new java.awt.GridBagLayout());
map2Group.add(map2FileButton);
map2FileButton.setSelected(true);
map2FileButton.setText("File");
map2FileButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
map2FileButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 3);
jPanel2.add(map2FileButton, gridBagConstraints);
map2Group.add(map2LayerButton);
map2LayerButton.setText("Layer");
map2LayerButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
map2LayerButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 3);
jPanel2.add(map2LayerButton, gridBagConstraints);
map2Group.add(map2ProjectButton);
map2ProjectButton.setText("Layer stack");
map2ProjectButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
map2ProjectButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 3);
jPanel2.add(map2ProjectButton, gridBagConstraints);
layerComboBox2.setPreferredSize(new java.awt.Dimension(29, 25));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 3);
jPanel2.add(layerComboBox2, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 3);
jPanel2.add(fileTextField2, gridBagConstraints);
fileButton2.setText("Browse");
fileButton2.setMargin(new java.awt.Insets(0, 7, 0, 7));
fileButton2.setPreferredSize(new java.awt.Dimension(69, 25));
fileButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
fileButton2ActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 3);
jPanel2.add(fileButton2, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(3, 5, 3, 5);
add(jPanel2, gridBagConstraints);
formatComboBox.setPreferredSize(new java.awt.Dimension(29, 25));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new java.awt.Insets(3, 5, 3, 7);
add(formatComboBox, gridBagConstraints);
jLabel1.setText("Format");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(3, 10, 3, 5);
add(jLabel1, gridBagConstraints);
buttonsPanel.setLayout(new java.awt.GridBagLayout());
okButton.setText("Compare");
okButton.setMargin(new java.awt.Insets(2, 5, 2, 5));
okButton.setMaximumSize(new java.awt.Dimension(70, 25));
okButton.setMinimumSize(new java.awt.Dimension(70, 25));
okButton.setPreferredSize(new java.awt.Dimension(70, 25));
okButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
okButtonActionPerformed(evt);
}
});
buttonsPanel.add(okButton, new java.awt.GridBagConstraints());
cancelButton.setText("Cancel");
cancelButton.setMargin(new java.awt.Insets(2, 5, 2, 5));
cancelButton.setMaximumSize(new java.awt.Dimension(70, 25));
cancelButton.setMinimumSize(new java.awt.Dimension(70, 25));
cancelButton.setPreferredSize(new java.awt.Dimension(70, 25));
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(0, 5, 0, 0);
buttonsPanel.add(cancelButton, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.insets = new java.awt.Insets(7, 5, 5, 3);
add(buttonsPanel, gridBagConstraints);
}// </editor-fold>//GEN-END:initComponents
public int getMap1Mode(){
if(map1FileButton.isSelected()) return MODE_FILE;
else if(map1LayerButton.isSelected()) return MODE_LAYER;
else if(map1ProjectButton.isSelected()) return MODE_PROJECT;
else return MODE_NONE;
}
public int getMap2Mode(){
if(map2FileButton.isSelected()) return MODE_FILE;
else if(map2LayerButton.isSelected()) return MODE_LAYER;
else if(map2ProjectButton.isSelected()) return MODE_PROJECT;
else return MODE_NONE;
}
public String getMap1Value(){
if(map1FileButton.isSelected()) return fileTextField1.getText();
else if(map1LayerButton.isSelected()) return layerComboBox1.getSelectedItem().toString();
else return null;
}
public String getMap2Value(){
if(map2FileButton.isSelected()) return fileTextField2.getText();
else if(map2LayerButton.isSelected()) return layerComboBox2.getSelectedItem().toString();
else return null;
}
public void addFormat(String format){
formatComboBox.addItem(format);
}
public String getFormat(){
return formatComboBox.getSelectedItem().toString();
}
private void map1GroupChanged(){
fileTextField1.setEnabled(map1FileButton.isSelected());
fileButton1.setEnabled(map1FileButton.isSelected());
layerComboBox1.setEnabled(map1LayerButton.isSelected());
}
private void map2GroupChanged(){
fileTextField2.setEnabled(map2FileButton.isSelected());
fileButton2.setEnabled(map2FileButton.isSelected());
layerComboBox2.setEnabled(map2LayerButton.isSelected());
}
private void map1FileButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_map1FileButtonActionPerformed
map1GroupChanged();
}//GEN-LAST:event_map1FileButtonActionPerformed
private void map1LayerButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_map1LayerButtonActionPerformed
map1GroupChanged();
}//GEN-LAST:event_map1LayerButtonActionPerformed
private void map1ProjectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_map1ProjectButtonActionPerformed
map1GroupChanged();
}//GEN-LAST:event_map1ProjectButtonActionPerformed
private void map2FileButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_map2FileButtonActionPerformed
map2GroupChanged();
}//GEN-LAST:event_map2FileButtonActionPerformed
private void map2LayerButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_map2LayerButtonActionPerformed
map2GroupChanged();
}//GEN-LAST:event_map2LayerButtonActionPerformed
private void map2ProjectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_map2ProjectButtonActionPerformed
map2GroupChanged();
}//GEN-LAST:event_map2ProjectButtonActionPerformed
private String browseFile(){
TopicMapFileChooser chooser=new TopicMapFileChooser();
if(chooser.open(wandora, "Select")==TopicMapFileChooser.APPROVE_OPTION){
File file = chooser.getSelectedFile();
return file.getAbsolutePath();
}
else return null;
}
private void fileButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fileButton1ActionPerformed
String f=browseFile();
if(f!=null) fileTextField1.setText(f);
}//GEN-LAST:event_fileButton1ActionPerformed
private void fileButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fileButton2ActionPerformed
String f=browseFile();
if(f!=null) fileTextField2.setText(f);
}//GEN-LAST:event_fileButton2ActionPerformed
public boolean wasCancelled(){
return cancelled;
}
private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
cancelled=false;
if(parentDialog!=null) parentDialog.setVisible(false);
}//GEN-LAST:event_okButtonActionPerformed
private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
cancelled=true;
if(parentDialog!=null) parentDialog.setVisible(false);
}//GEN-LAST:event_cancelButtonActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel buttonsPanel;
private javax.swing.JButton cancelButton;
private javax.swing.JButton fileButton1;
private javax.swing.JButton fileButton2;
private javax.swing.JTextField fileTextField1;
private javax.swing.JTextField fileTextField2;
private javax.swing.JComboBox formatComboBox;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JComboBox layerComboBox1;
private javax.swing.JComboBox layerComboBox2;
private javax.swing.JRadioButton map1FileButton;
private javax.swing.ButtonGroup map1Group;
private javax.swing.JRadioButton map1LayerButton;
private javax.swing.JRadioButton map1ProjectButton;
private javax.swing.JRadioButton map2FileButton;
private javax.swing.ButtonGroup map2Group;
private javax.swing.JRadioButton map2LayerButton;
private javax.swing.JRadioButton map2ProjectButton;
private javax.swing.JButton okButton;
// End of variables declaration//GEN-END:variables
}
| 20,343 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SearchAndReplaceOccurrences.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/SearchAndReplaceOccurrences.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;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import org.wandora.application.Wandora;
import org.wandora.application.contexts.Context;
import org.wandora.application.contexts.TopicContext;
import org.wandora.application.gui.WandoraOptionPane;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
public class SearchAndReplaceOccurrences extends AbstractWandoraTool {
private static final long serialVersionUID = 1L;
public SearchAndReplaceOccurrences() {
this.setContext(new TopicContext());
}
@Override
public void execute(final Wandora wandora, Context context) {
String search=WandoraOptionPane.showInputDialog(wandora,"Enter search string","","Search and replace");
if(search==null || search.length()==0) return;
String replace=WandoraOptionPane.showInputDialog(wandora,"Enter replace string","","Search and replace");
if(replace==null) return;
Iterator iter=context.getContextObjects();
Pattern pattern;
try{
pattern=Pattern.compile(search);
}catch(PatternSyntaxException pse){
singleLog(pse);
return;
}
int counter=0;
while(iter.hasNext()){
counter++;
if((counter%100)==0){
if(forceStop()){
singleLog("Aborting execute");
return;
}
}
Object cObject=iter.next();
if(!(cObject instanceof Topic)) continue;
Topic cTopic=(Topic)cObject;
try{
for(Topic type : cTopic.getDataTypes()){
Hashtable<Topic,String> data=cTopic.getData(type);
for(Topic version : data.keySet()){
String occurrence=data.get(version);
Matcher matcher=pattern.matcher(occurrence);
occurrence=matcher.replaceAll(replace);
cTopic.setData(type,version,occurrence);
}
}
}
catch(TopicMapException tme){
singleLog(tme);
return;
}
}
}
@Override
public String getName() {
return "Search and replace in occurrences";
}
@Override
public String getDescription() {
return "Tool searches for matches of a regular expression in topic occurrences and replaces them with another string. "+
"Replacement is done with the Java java.util.regex.Matcher.replaceAll method which allows you to refer to mathed "+
"subsequences with with a dollar sign ($). Backslash (\\) can be used to escape literal characters, especially the "+
"dollar sign and backslash itself.";
}
}
| 3,825 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
CreateAssociationType.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/CreateAssociationType.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/>.
*
*
* CreateAssociationType.java
*
* Created on 15.6.2006, 10:36
*
*/
package org.wandora.application.tools;
import java.util.Iterator;
import java.util.Vector;
import org.wandora.application.Wandora;
import org.wandora.application.contexts.Context;
import org.wandora.application.contexts.TopicContext;
import org.wandora.application.gui.CreateAssociationTypePrompt;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author olli
*/
public class CreateAssociationType extends AbstractWandoraTool {
private static final long serialVersionUID = 1L;
/** Creates a new instance of CreateAssociationType */
public CreateAssociationType(Context preferredContext) {
setContext(preferredContext);
}
public CreateAssociationType() {
setContext(new TopicContext());
}
@Override
public String getName() {
return "Create association type";
}
@Override
public String getDescription() {
return "Opens an editor used to create a new association type. ";
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
Iterator contextObjects = context.getContextObjects();
Vector<Topic> objects=new Vector<Topic>();
Association a=null;
if(contextObjects!=null && contextObjects.hasNext()){
Object o=contextObjects.next();
if(o instanceof Association) a=(Association)o;
else if(o instanceof Topic){
objects.add((Topic)o);
while(contextObjects.hasNext()){
objects.add((Topic)contextObjects.next());
}
}
}
CreateAssociationTypePrompt d=null;
if(a!=null) d=new CreateAssociationTypePrompt(wandora,a);
else if(objects.size()>0) d=new CreateAssociationTypePrompt(wandora,objects);
else d=new CreateAssociationTypePrompt(wandora);
d.setVisible(true);
}
}
| 2,867 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SplitTopics.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/SplitTopics.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/>.
*
*
*
* SplitTopics.java
*
* Created on 12.6.2006, 18:19
*
*/
package org.wandora.application.tools;
import java.util.ArrayList;
import java.util.Collection;
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.topicmap.Association;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
/**
* WandoraTool splitting a topic with several subject identifiers. A new topic is
* created for each subject identifier. Thus, split can be seen as a counter operation
* of merge. To prevent immediate merge new topic's will be given a slightly modified
* base name and subject locator. Split topics are similar in associations,
* instances, classes and occurrences.
*
* @author akivela
*/
public class SplitTopics extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
public boolean duplicateAssociations = true;
public boolean copyInstances = true;
public boolean askName=false;
public SplitTopics() {
}
public SplitTopics(Context preferredContext) {
setContext(preferredContext);
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/topic_split.png");
}
@Override
public String getName() {
return "Split topic";
}
@Override
public String getDescription() {
return "Splits topic using subject identifiers.";
}
@Override
public void execute(Wandora w, Context context) {
duplicateAssociations = true;
copyInstances = true;
askName=false;
Iterator topics = getContext().getContextObjects();
if(topics == null || !topics.hasNext()) return;
TopicMap tm = w.getTopicMap();
Topic topic = null;
setDefaultLogger();
while(topics.hasNext() && !forceStop()) {
try {
topic = (Topic) topics.next();
if(topic != null) {
if(!topic.isRemoved()) {
Topic ltopic = tm.getTopic(topic.getOneSubjectIdentifier());
splitTopic(ltopic, tm, w);
}
}
}
catch(Exception e) {
log(e);
}
}
}
public void splitTopic(Topic original, TopicMap topicMap, Wandora w) throws TopicMapException {
Collection<Locator> originalSIs = original.getSubjectIdentifiers();
if(originalSIs == null || originalSIs.isEmpty() || originalSIs.size() == 1) {
log("Topic '"+ getTopicName(original) +"' has only one subject identifier. Can't split.");
return;
}
ArrayList<Locator> SIParts = new ArrayList<Locator>();
SIParts.addAll(originalSIs);
Topic split = null;
for(Locator splitSI : SIParts) {
String osplitSI = splitSI.toExternalForm();
// --- copy topic and associations ---
TopicMap splitMap = new org.wandora.topicmap.memory.TopicMapImpl();
split = splitMap.copyTopicIn(original, false);
if(duplicateAssociations) {
Collection<Association> associations = original.getAssociations();
if(associations != null && !associations.isEmpty()) {
for(Association association : associations) {
splitMap.copyAssociationIn(association);
}
}
}
// --- resolve new subject base name ---
if(original.getBaseName() != null) {
String newBaseName = original.getBaseName() + " (split)";
int c = 2;
while(topicMap.getTopicWithBaseName(newBaseName) != null && c<10000) {
newBaseName = original.getBaseName() + " (split " + c + ")";
c++;
}
if(askName){
while(true){
String input=WandoraOptionPane.showInputDialog(w,"Enter new base name for the topic", newBaseName);
if(input==null) return;
newBaseName=input;
if(topicMap.getTopicWithBaseName(input)!=null){
int a=WandoraOptionPane.showConfirmDialog(w,"Topic with base name '"+input+"' already exists and will be merged with new topic. Do you want to continue?");
if(a==WandoraOptionPane.CANCEL_OPTION) return;
else if(a==WandoraOptionPane.YES_OPTION) break;
}
else break;
}
}
split.setBaseName(newBaseName);
}
// --- resolve new subject locator ---
if(original.getSubjectLocator() != null) {
int c = 2;
Locator newSubjectLocator = new Locator(original.getSubjectLocator().toExternalForm() + "_copy");
while(topicMap.getTopicBySubjectLocator(newSubjectLocator) != null && c<10000) {
newSubjectLocator = new Locator(original.getSubjectLocator().toExternalForm() + "_copy" + c);
c++;
}
split.setSubjectLocator(newSubjectLocator);
}
// --- resolve new subject identifiers ---
for(Locator si : SIParts) {
if(!si.equals(splitSI)) {
split.removeSubjectIdentifier(si);
}
}
original.removeSubjectIdentifier(splitSI);
//log("Merging splitted topic to original map...");
topicMap.mergeIn(splitMap);
split = topicMap.getTopic(splitSI);
// --- attach instances ---
if(split != null && copyInstances) {
Collection<Topic> instances = topicMap.getTopicsOfType(original);
if(instances != null && !instances.isEmpty()) {
for(Topic instance : instances) {
instance.addType(split);
}
}
}
}
}
}
| 7,378 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
ApplyPatchToolConfigPanel.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/ApplyPatchToolConfigPanel.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;
import java.io.File;
import java.util.List;
import javax.swing.JDialog;
import org.wandora.application.Wandora;
import org.wandora.application.gui.UIConstants;
import org.wandora.application.gui.filechooser.TopicMapFileChooser;
import org.wandora.application.gui.simple.SimpleFileChooser;
import org.wandora.topicmap.layered.Layer;
/**
*
* @author olli
*/
public class ApplyPatchToolConfigPanel extends javax.swing.JPanel {
private static final long serialVersionUID = 1L;
public static final int MODE_FILE=1;
public static final int MODE_LAYER=2;
public static final int MODE_PROJECT=3;
public static final int MODE_NONE=99;
protected Wandora wandora;
protected JDialog parentDialog;
protected boolean cancelled=true;
/** Creates new form ApplyPatchToolConfigPanel */
public ApplyPatchToolConfigPanel(Wandora wandora, JDialog parentDialog) {
initComponents();
this.wandora=wandora;
this.parentDialog=parentDialog;
List<Layer> layers=wandora.getTopicMap().getLayers();
for(Layer l : layers){
layerComboBox1.addItem(l.getName());
}
mapGroupChanged();
}
/** 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;
mapGroup = new javax.swing.ButtonGroup();
map1ProjectButton = new org.wandora.application.gui.simple.SimpleRadioButton();
jPanel1 = new javax.swing.JPanel();
map1FileButton = new org.wandora.application.gui.simple.SimpleRadioButton();
map1LayerButton = new org.wandora.application.gui.simple.SimpleRadioButton();
layerComboBox1 = new org.wandora.application.gui.simple.SimpleComboBox();
layerComboBox1.setEditable(false);
fileTextField1 = new org.wandora.application.gui.simple.SimpleField();
fileButton1 = new org.wandora.application.gui.simple.SimpleButton();
jPanel2 = new javax.swing.JPanel();
patchTextField = new org.wandora.application.gui.simple.SimpleField();
patchButton = new org.wandora.application.gui.simple.SimpleButton();
jLabel1 = new org.wandora.application.gui.simple.SimpleLabel();
reverseCheckBox = new org.wandora.application.gui.simple.SimpleCheckBox();
buttonsPanel = new javax.swing.JPanel();
okButton = new org.wandora.application.gui.simple.SimpleButton();
cancelButton = new org.wandora.application.gui.simple.SimpleButton();
mapGroup.add(map1ProjectButton);
map1ProjectButton.setText("Layer stack");
map1ProjectButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
map1ProjectButtonActionPerformed(evt);
}
});
setLayout(new java.awt.GridBagLayout());
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Topic map", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, UIConstants.plainFont));
jPanel1.setLayout(new java.awt.GridBagLayout());
mapGroup.add(map1FileButton);
map1FileButton.setSelected(true);
map1FileButton.setText("File");
map1FileButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
map1FileButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 3);
jPanel1.add(map1FileButton, gridBagConstraints);
mapGroup.add(map1LayerButton);
map1LayerButton.setText("Layer");
map1LayerButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
map1LayerButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 3);
jPanel1.add(map1LayerButton, gridBagConstraints);
layerComboBox1.setPreferredSize(new java.awt.Dimension(29, 25));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 3);
jPanel1.add(layerComboBox1, gridBagConstraints);
fileTextField1.setPreferredSize(new java.awt.Dimension(6, 25));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 3);
jPanel1.add(fileTextField1, gridBagConstraints);
fileButton1.setText("Browse");
fileButton1.setMargin(new java.awt.Insets(0, 7, 0, 7));
fileButton1.setPreferredSize(new java.awt.Dimension(69, 25));
fileButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
fileButton1ActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 3);
jPanel1.add(fileButton1, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 3, 5);
add(jPanel1, gridBagConstraints);
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Patch", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, UIConstants.plainFont));
jPanel2.setLayout(new java.awt.GridBagLayout());
patchTextField.setPreferredSize(new java.awt.Dimension(6, 25));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 3);
jPanel2.add(patchTextField, gridBagConstraints);
patchButton.setText("Browse");
patchButton.setMargin(new java.awt.Insets(0, 7, 0, 7));
patchButton.setPreferredSize(new java.awt.Dimension(69, 25));
patchButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
patchButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 3);
jPanel2.add(patchButton, gridBagConstraints);
jLabel1.setText("Patch file");
jLabel1.setPreferredSize(new java.awt.Dimension(76, 14));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(2, 7, 2, 3);
jPanel2.add(jLabel1, gridBagConstraints);
reverseCheckBox.setText("Reverse patch");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 3);
jPanel2.add(reverseCheckBox, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 3, 5);
add(jPanel2, gridBagConstraints);
buttonsPanel.setLayout(new java.awt.GridBagLayout());
okButton.setText("Patch");
okButton.setMargin(new java.awt.Insets(2, 5, 2, 5));
okButton.setPreferredSize(new java.awt.Dimension(70, 25));
okButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
okButtonActionPerformed(evt);
}
});
buttonsPanel.add(okButton, new java.awt.GridBagConstraints());
cancelButton.setText("Cancel");
cancelButton.setMargin(new java.awt.Insets(2, 5, 2, 5));
cancelButton.setPreferredSize(new java.awt.Dimension(70, 25));
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(0, 5, 0, 0);
buttonsPanel.add(cancelButton, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.insets = new java.awt.Insets(7, 5, 5, 3);
add(buttonsPanel, gridBagConstraints);
}// </editor-fold>//GEN-END:initComponents
public int getMapMode(){
if(map1FileButton.isSelected()) return MODE_FILE;
else if(map1LayerButton.isSelected()) return MODE_LAYER;
else if(map1ProjectButton.isSelected()) return MODE_PROJECT;
else return MODE_NONE;
}
public String getMapValue(){
if(map1FileButton.isSelected()) return fileTextField1.getText();
else if(map1LayerButton.isSelected()) return layerComboBox1.getSelectedItem().toString();
else return null;
}
public String getPatchFile(){
return patchTextField.getText();
}
public boolean getPatchReverse(){
return reverseCheckBox.isSelected();
}
private void mapGroupChanged(){
fileTextField1.setEnabled(map1FileButton.isSelected());
fileButton1.setEnabled(map1FileButton.isSelected());
layerComboBox1.setEnabled(map1LayerButton.isSelected());
}
private String browseTopicMap(){
TopicMapFileChooser chooser;
String currentDirectory = wandora.options.get("current.directory");
if(currentDirectory != null) chooser = new TopicMapFileChooser(currentDirectory);
else chooser=new TopicMapFileChooser();
if(chooser.open(wandora, "Select")==TopicMapFileChooser.APPROVE_OPTION){
File file = chooser.getSelectedFile();
return file.getAbsolutePath();
}
else return null;
}
private String browseFile(){
SimpleFileChooser chooser=UIConstants.getFileChooser();
if(chooser.showDialog(wandora, "Select")==SimpleFileChooser.APPROVE_OPTION){
File file = chooser.getSelectedFile();
return file.getAbsolutePath();
}
else return null;
}
public boolean wasCancelled(){
return cancelled;
}
private void map1FileButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_map1FileButtonActionPerformed
mapGroupChanged();
}//GEN-LAST:event_map1FileButtonActionPerformed
private void map1LayerButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_map1LayerButtonActionPerformed
mapGroupChanged();
}//GEN-LAST:event_map1LayerButtonActionPerformed
private void map1ProjectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_map1ProjectButtonActionPerformed
mapGroupChanged();
}//GEN-LAST:event_map1ProjectButtonActionPerformed
private void fileButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fileButton1ActionPerformed
String f=browseTopicMap();
if(f!=null) fileTextField1.setText(f);
}//GEN-LAST:event_fileButton1ActionPerformed
private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
cancelled=false;
if(parentDialog!=null) parentDialog.setVisible(false);
}//GEN-LAST:event_okButtonActionPerformed
private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
cancelled=true;
if(parentDialog!=null) parentDialog.setVisible(false);
}//GEN-LAST:event_cancelButtonActionPerformed
private void patchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_patchButtonActionPerformed
String f=browseFile();
if(f!=null) patchTextField.setText(f);
}//GEN-LAST:event_patchButtonActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel buttonsPanel;
private javax.swing.JButton cancelButton;
private javax.swing.JButton fileButton1;
private javax.swing.JTextField fileTextField1;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JComboBox layerComboBox1;
private javax.swing.JRadioButton map1FileButton;
private javax.swing.JRadioButton map1LayerButton;
private javax.swing.JRadioButton map1ProjectButton;
private javax.swing.ButtonGroup mapGroup;
private javax.swing.JButton okButton;
private javax.swing.JButton patchButton;
private javax.swing.JTextField patchTextField;
private javax.swing.JCheckBox reverseCheckBox;
// End of variables declaration//GEN-END:variables
}
| 15,810 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
PrintTopic.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/PrintTopic.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/>.
*
*
*
* PrintTopic.java
*
* Created on October 7, 2004, 5:56 PM
*/
package org.wandora.application.tools;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.RenderingHints;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterJob;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.StringWriter;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.swing.Icon;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.RepaintManager;
import javax.swing.text.html.HTMLEditorKit;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
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.SimpleButton;
import org.wandora.application.gui.simple.SimpleComboBox;
import org.wandora.application.gui.simple.SimpleFileChooser;
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.utils.ClipboardBox;
import org.wandora.utils.IObox;
/**
*
* @author akivela
*/
public class PrintTopic extends AbstractWandoraTool implements ActionListener, KeyListener {
private static final long serialVersionUID = 1L;
private static final int NO_SORT = 0;
private static final int SORT_DESC = -1;
private static final int SORT = 1;
public static final String OPTIONS_PREFIX = "printTopic.";
JFrame frame;
JPanel toolPanel;
SimpleButton cancelBtn;
SimpleButton printBtn;
SimpleButton copyBtn;
SimpleButton saveBtn;
SimpleComboBox templateSelector;
SimpleComboBox pageSelector;
JPanel previewPanel;
Preview preview;
JScrollPane scrollArea;
Wandora parent;
JPanel framePanel;
Topic printTopic = null;
HashMap<String, String> templates = new HashMap<String, String>();
PrinterJob printJob = null;
/** Creates a new instance of PrintTopic */
public PrintTopic() {
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/print.png");
}
@Override
public String getName() {
return "Print topic";
}
@Override
public String getDescription() {
return "Print current topic.";
}
public boolean useDefaultGui() {
return false;
}
@Override
public boolean requiresRefresh() {
return false;
}
@Override
public void execute(Wandora admin, Context context) throws TopicMapException {
this.parent = admin;
if(frame == null) {
initializeGui();
}
if(context.getContextObjects().hasNext()) {
printTopic = (Topic) context.getContextObjects().next();
}
else {
printTopic = admin.getOpenTopic();
}
String previewTitle = printTopic == null ? "No topic selected!" : (printTopic.getBaseName() == null ? printTopic.getOneSubjectIdentifier().toExternalForm() : printTopic.getBaseName());
if(previewTitle.length() > 60) previewTitle = previewTitle.substring(0, 59) + "...";
String currentTemplate = parent.options.get(OPTIONS_PREFIX+"currentTemplate");
if(currentTemplate != null && currentTemplate.length() > 0) {
templateSelector.setSelectedItem(currentTemplate);
}
updatePreview();
frame.pack();
PageFormat pageFormat = printJob.defaultPage();
frame.setSize(new Dimension((int) pageFormat.getWidth(), (int) pageFormat.getHeight()+toolPanel.getHeight()));
parent.centerWindow(frame);
int x = frame.getX();
x = x > 0 ? x : 0;
int y = frame.getY();
y = y > 0 ? y : 0;
frame.setLocation(x,y);
frame.setVisible(true);
}
private void initializeGui() {
frame = new JFrame();
frame.setResizable(true);
framePanel = new JPanel();
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
framePanel.setLayout(gridbag);
cancelBtn = new SimpleButton("Cancel");
printBtn = new SimpleButton("Print");
copyBtn = new SimpleButton("Copy");
saveBtn = new SimpleButton("Save");
templateSelector = new SimpleComboBox();
pageSelector = new SimpleComboBox();
pageSelector.setEditable(false);
pageSelector.setPreferredSize(new Dimension(50,21));
cancelBtn.setPreferredSize(new Dimension(70,23));
printBtn.setPreferredSize(new Dimension(70,23));
copyBtn.setPreferredSize(new Dimension(70,23));
saveBtn.setPreferredSize(new Dimension(70,23));
cancelBtn.setMargin(new Insets(2,2,2,2));
printBtn.setMargin(new Insets(2,2,2,2));
copyBtn.setMargin(new Insets(2,2,2,2));
saveBtn.setMargin(new Insets(2,2,2,2));
templateSelector.setPreferredSize(new Dimension(150,21));
templateSelector.setEditable(false);
cancelBtn.setToolTipText("Cancel printing and close print preview");
printBtn.setToolTipText("Print");
copyBtn.setToolTipText("Copy HTML source to clipboard");
saveBtn.setToolTipText("Save as HTML source");
templateSelector.setToolTipText("Select print template");
pageSelector.setToolTipText("Change preview page");
solveTemplates();
templateSelector.setOptions(templates.keySet());
toolPanel = new JPanel(new BorderLayout());
JPanel p1 = new JPanel(new FlowLayout());
p1.add(templateSelector);
p1.add(pageSelector);
JPanel p2 = new JPanel(new FlowLayout());
p2.add(copyBtn);
p2.add(saveBtn);
p2.add(printBtn);
p2.add(cancelBtn);
toolPanel.add(p1, BorderLayout.WEST);
toolPanel.add(p2, BorderLayout.EAST);
printJob = PrinterJob.getPrinterJob();
PrintRequestAttributeSet printAttrs = new HashPrintRequestAttributeSet();
previewPanel = new JPanel(new BorderLayout());
//previewPanel.setPreferredSize(new Dimension((int) pageFormat.getWidth(), (int) pageFormat.getHeight()));
preview = new Preview("", printJob.getPageFormat(printAttrs));
scrollArea = new JScrollPane(preview, JScrollPane.VERTICAL_SCROLLBAR_NEVER, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
previewPanel.add(scrollArea, BorderLayout.CENTER);
c.gridx = 0;
c.gridy = GridBagConstraints.RELATIVE;
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
c.weighty = 1.0;
gridbag.setConstraints(previewPanel, c);
framePanel.add(previewPanel);
c.gridx = 0;
c.gridy = GridBagConstraints.RELATIVE;
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1.0;
c.weighty = 0.0;
gridbag.setConstraints(toolPanel, c);
framePanel.add(toolPanel);
frame.add(framePanel, BorderLayout.CENTER);
frame.setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
frame.setTitle("Print topic");
//frame.setIconImage(UIBox.getImage("gui/appicon/48x48_24bit.png"));
frame.setIconImage(UIBox.getImage("gui/appicon/icon.gif"));
printBtn.addActionListener(this);
cancelBtn.addActionListener(this);
copyBtn.addActionListener(this);
saveBtn.addActionListener(this);
templateSelector.addActionListener(this);
pageSelector.addActionListener(this);
frame.addKeyListener(this);
preview.addKeyListener(this);
}
// ---------------------------------------------------- Action Listener ---
public void actionPerformed(java.awt.event.ActionEvent evt) {
Object evtSource = evt.getSource();
if(evtSource == null) return;
if(evtSource.equals(copyBtn)) {
ClipboardBox.setClipboard(getTopicAsText(parent));
}
else if(evtSource.equals(cancelBtn)) {
frame.setVisible(false);
}
else if(evtSource.equals(printBtn)) {
try {
if( preview.print() ) {
frame.setVisible(false);
}
}
catch(Exception e) {
log(e);
}
/*
if(printJob != null) {
printJob.setPrintable(preview);
PrintRequestAttributeSet printAttrs = new HashPrintRequestAttributeSet();
//printAttrs.add( new PageRanges(1,2) );
//printAttrs.add( PrintQuality.HIGH );
//printAttrs.add( new PrinterResolution(600,600, PrinterResolution.DPI ) );
if(printJob.printDialog()) {
try {
preview.setPageFormat(printJob.getPageFormat(printAttrs));
printJob.print();
}
catch(PrinterException pe) {
log("Error printing: " + pe);
}
}
}
frame.setVisible(false);
* */
}
else if(evtSource.equals(saveBtn)) {
if(preview != null) preview.save();
}
else if(evtSource.equals(templateSelector)) {
//System.out.println("----------------------- Updating preview!");
parent.options.put(OPTIONS_PREFIX+"currentTemplate", templateSelector.getSelectedItem().toString());
updatePreview();
}
else if(evtSource.equals(pageSelector)) {
//System.out.println("----------------------- Page change!");
String pageString = (String) pageSelector.getSelectedItem();
if(pageString != null && pageString.length() > 0) {
try {
int page = Integer.parseInt(pageString);
preview.setPage(page-1);
preview.invalidate();
}
catch(Exception e) {
log(e);
}
}
}
else {
System.out.println("Unknown action event source: " +evtSource);
}
}
// -------------------------------------------------------- Key Listener ---
protected Object[] keyMap = new Object[] {
KeyEvent.VK_1, Integer.valueOf(0),
KeyEvent.VK_2, Integer.valueOf(1),
KeyEvent.VK_3, Integer.valueOf(2),
KeyEvent.VK_4, Integer.valueOf(3),
KeyEvent.VK_5, Integer.valueOf(4),
KeyEvent.VK_6, Integer.valueOf(5),
KeyEvent.VK_7, Integer.valueOf(6),
KeyEvent.VK_8, Integer.valueOf(7),
KeyEvent.VK_9, Integer.valueOf(8),
};
public void keyTyped(KeyEvent e) {
//System.out.println("keyTyped "+e);
}
public void keyPressed(KeyEvent e) {
//System.out.println("keyPressed "+e);
}
public void keyReleased(KeyEvent e) {
//System.out.println("keyReleased "+e);
if(e == null) return;
for(int i=0; i<keyMap.length; i+=2) {
if(keyMap[i].equals(e.getKeyCode())) {
int pn = ((Integer) keyMap[i+1]).intValue();
if(pn < preview.numberOfPages) {
//preview.setPage(pn);
//System.out.println("changing page to "+pn);
pageSelector.setSelectedIndex(pn);
}
break;
}
}
}
// -------------------------------------------------------------------------
private void formWindowClosing(java.awt.event.WindowEvent evt) {
frame.setVisible(false);
}
public String getTemplateFile() {
String current = (String) templateSelector.getItemAt(templateSelector.getSelectedIndex());
return templates.get(current);
}
public void updatePreview() {
setPreview(printTopic, parent);
}
public void setPreview(Topic t, Wandora admin) {
setPreview(t, getTemplateFile(), admin);
}
public void setPreview(Topic t, String template, Wandora admin) {
//System.out.println("setPreview()");
try {
String text = getTopicAsText(admin, t, template, SORT);
if(preview != null) {
preview.setText(text);
preview.invalidate();
}
}
catch (Exception e) {
log(e);
}
}
public void updatePageSelector() {
//System.out.println("updatePageSelector()");
String[] pageNumbers = preview.getPageNumbers();
pageSelector.setOptions(pageNumbers);
if(pageNumbers.length > 0) {
pageSelector.setSelectedIndex(0);
preview.setPage(0);
}
pageSelector.invalidate();
}
// -------------------------------------------------------------------------
public String getTopicAsText(Wandora admin) {
return getTopicAsText(admin, printTopic, getTemplateFile(), SORT);
}
public String getTopicAsText(Wandora wandora, Topic t, String templateFile, int sortFlag) {
Map<String, Object> hash = new LinkedHashMap<>();
try {
if(wandora!=null) {
if(t == null) {
t = wandora.getOpenTopic();
}
if(t == null) {
hash.put("error", "*** Can't find topic to print. ***");
return "Can't find topic to print.";
}
//log("getTopicAsTextLines: " + t.getBaseName());
TopicMap topicMap = wandora.getTopicMap();
List<String> temp = new ArrayList<>();
hash.put("topicmap", topicMap);
hash.put("topic", t);
// --- base name
String baseName = getTopicName(t);
hash.put("basename", baseName);
// --- subject locator
if(t.getSubjectLocator() != null) {
Locator newSubjectLocator = t.getSubjectLocator();
hash.put("sl", newSubjectLocator.toExternalForm());
}
// --- names
if(!t.getVariantScopes().isEmpty()) {
Map<List<String>,String> names = new LinkedHashMap<>();
for(Set<Topic> scope : t.getVariantScopes()){
List<String> nameScope = new ArrayList<>();
for(Topic t2 : scope) {
nameScope.add(getTopicName(t2));
}
names.put(nameScope, t.getVariant(scope));
}
if(!names.isEmpty()) {
hash.put("names", names);
}
}
// --- classes
temp = new ArrayList<>();
for(Topic t2 : t.getTypes()) {
temp.add(getTopicName(t2));
}
if(!temp.isEmpty()) {
hash.put("classes", sortArray(temp, sortFlag));
}
// --- occurrence
Map<String,Map<String,String>> occurrences = new LinkedHashMap<>();
Map<String,String> occurrence = new LinkedHashMap<>();
for(Topic t2 : t.getDataTypes()) {
occurrence = new LinkedHashMap<>();
Hashtable<Topic,String> data = t.getData(t2);
for(Enumeration<Topic> en = data.keys(); en.hasMoreElements(); ) {
Topic key = (Topic) en.nextElement();
occurrence.put(getTopicName(key), data.get(key));
}
occurrences.put(getTopicName(t2), occurrence);
}
if(!temp.isEmpty()) {
hash.put("data", occurrences);
}
// --- associations
Map<String,List<Map<String,String>>> associationsByType = new LinkedHashMap<>();
Map<String,Map<String,String>> rolesByType = new HashMap<>();
List<Map<String,String>> allAssociations = new ArrayList<>();
for(Association a : t.getAssociations()) {
Topic type = a.getType();
String typeName = getTopicName(type);
List<Map<String,String>> typedAssociations = associationsByType.get(typeName);
if(typedAssociations == null) typedAssociations = new ArrayList<>();
Collection<Topic> aRoles = a.getRoles();
Map<String,String> roles = rolesByType.get(typeName);
if(roles == null) roles = new LinkedHashMap<>();
Map<String,String> association = new LinkedHashMap<>();
for(Iterator<Topic> aRoleIter = aRoles.iterator(); aRoleIter.hasNext(); ) {
Topic role = (Topic) aRoleIter.next();
Topic player = a.getPlayer(role);
String roleName = getTopicName(role);
String playerName = getTopicName(player);
association.put(roleName, playerName);
roles.put(roleName, roleName); // <-- IS THIS RIGHT!
}
allAssociations.add(association);
typedAssociations.add(association);
rolesByType.put(typeName, roles);
associationsByType.put(typeName, typedAssociations);
}
if(!associationsByType.isEmpty()) {
hash.put("associationsbytype", associationsByType);
hash.put("associationrolesbytype", rolesByType);
hash.put("allassociations", allAssociations);
}
// --- subject identifiers
temp = new ArrayList<>();
for(Locator l : t.getSubjectIdentifiers() ) {
temp.add(l.toExternalForm());
}
hash.put("si", temp);
// --- instances
temp = new ArrayList<>();
for(Topic t2 : topicMap.getTopicsOfType(t)) {
temp.add(getTopicName(t2));
}
if(!temp.isEmpty()) {
List<String> sorted = sortArray(temp, sortFlag);
hash.put("instances", sorted);
}
}
}
catch(Exception e) {
hash.put("error", "*** Exception occurred while building print! ***");
log(e);
}
return getVelocityString(wandora, hash, templateFile);
}
/*
* Use method in AbstractWandoraTool instead!
*
public String getTopicName(Topic t) {
try {
if(t.getBaseName() == null) {
return t.getOneSubjectIdentifier().toExternalForm();
}
else {
return t.getBaseName();
}
}
catch(Exception e) {
log(e);
return "";
}
}
*/
public String getVelocityString(Wandora wandora, Map hash, String templateFile) {
VelocityContext context;
Template template;
StringWriter writer;
VelocityEngine velocityEngine;
String templateEncoding = "UTF-8";
Object codec = null;
try {
//templateFile = new File(templateName);
//templatePath = templateFile.getParent();
writer = new StringWriter();
velocityEngine = new VelocityEngine();
//velocityEngine.setProperty("file.resource.loader.path", templatePath );
//velocityEngine.setProperty("runtime.log.error.stacktrace", "false" );
//velocityEngine.setProperty("runtime.log.warn.stacktrace", "false" );
//velocityEngine.setProperty("runtime.log.info.stacktrace", "false" );
velocityEngine.init();
context = new VelocityContext();
context.put("topic", hash);
context.put("date" , DateFormat.getDateTimeInstance().format(new Date()));
if(codec != null) context.put("codec", codec);
if(templateEncoding != null && templateEncoding.length()>0) template = velocityEngine.getTemplate(templateFile, templateEncoding);
else template = velocityEngine.getTemplate(templateFile);
template.merge( context, writer );
writer.flush();
writer.close();
String text = writer.toString();
//log("Processed Velocity text follows:\n" + text);
return text;
}
catch( ResourceNotFoundException rnfe ) {
// couldn't find the template
log("Unable to find the template file '" + templateFile + "' for velocity!", rnfe);
}
catch( ParseErrorException pee ) {
// syntax error : problem parsing the template
log("Unable to parse the velocity template file '" + templateFile + "'!");
}
catch( MethodInvocationException mie ) {
// something invoked in the template threw an exception
log("Velocity template '" + templateFile + "' causes method invocation exception!", mie);
}
catch( Exception e ) {
log("Exception '" + e.toString() + "' occurred while working with velocity template '" + templateFile + "'!", e);
}
return "";
}
public <T> List<T> sortArray(List<T> v, int sortFlag) {
if(sortFlag == NO_SORT) return v;
if(v == null) return null;
if(v.size() == 1) return v;
T[] array = (T[]) v.toArray(new Object[0]);
T o1;
T o2;
String s1;
String s2;
for(int i=array.length-1; i>0; i--) {
for(int j=0; j<i ; j++) {
o1 = array[i];
o2 = array[j];
if(o1 instanceof String && o2 instanceof String) {
s1 = (String) o1;
s2 = (String) o2;
if((sortFlag == SORT && s1.compareToIgnoreCase(s2) < 0) ||
(sortFlag == SORT_DESC && s1.compareToIgnoreCase(s2) > 0)) {
array[j] = o1;
array[i] = o2;
}
}
}
}
v = new ArrayList<>();
v.addAll(Arrays.asList(array));
return v;
}
public void solveTemplates() {
try {
HashSet<String> templateFiles = IObox.getFilesAsHash("gui/printtemplates", ".+\\.vhtml", 1, 999);
for(String templateFilename : templateFiles) {
if(templateFilename != null) {
try {
//System.out.println("found template: " + templateFilename );
boolean nameFound = false;
BufferedReader reader = new BufferedReader(new FileReader(templateFilename));
String firstLine = reader.readLine();
if(firstLine != null) {
if(firstLine.startsWith("##TEMPLATE-NAME:")) {
String name = firstLine.substring(16);
name = name.trim();
if(name != null && name.length() > 0) {
nameFound = true;
templates.put(name, templateFilename);
}
}
}
reader.close();
if(nameFound == false) {
templates.put(templateFilename, templateFilename);
}
}
catch(Exception ex) {
log(ex);
}
}
}
}
catch(Exception e) {
log(e);
}
}
// -------------------------------------------------------------------------
// ---- Preview ------------------------------------------------------------
// -------------------------------------------------------------------------
class Preview extends JEditorPane implements Printable, MouseListener, ActionListener {
private static final long serialVersionUID = 1L;
int numberOfPages = 0;
int page = 0;
protected JPopupMenu popup;
protected Object[] popupStruct = new Object[] {
"Copy", UIBox.getIcon("gui/icons/copy.png"),
"Copy as image", UIBox.getIcon("gui/icons/copy.png"),
"---",
"Save...", UIBox.getIcon("gui/icons/file_save.png"),
"---",
"Print...", UIBox.getIcon("gui/icons/print.png"),
"---",
"Close", UIBox.getIcon("gui/icons/exit.png"),
};
private PageFormat pageFormat;
Preview(String text, PageFormat page) {
super("text/html", text);
//this.putClientProperty("JEditorPane.w3cLengthUnits", Boolean.TRUE);
pageFormat = page;
this.addMouseListener(this);
this.setText(text);
this.setEditable(false);
popup = UIBox.makePopupMenu(popupStruct, this);
setComponentPopupMenu(popup);
}
/*
public Dimension getPreferredSize() {
if(pageFormat != null) {
return new Dimension((int) pageFormat.getWidth(), (int) pageFormat.getHeight());
}
else {
return new Dimension((int) (72*8.27), (int) (72*11.69));
}
}
* */
@Override
public void setText(String newText) {
setEditorKit(new HTMLEditorKit() );
super.setText(newText);
setCaretPosition(0);
repaint();
}
public void setPage(int p) {
page = p;
repaint();
}
public String[] getPageNumbers() {
String[] pageNumbers = new String[getPageCount()];
for(int i=0; i<pageNumbers.length; i++) {
pageNumbers[i] = ""+(i+1);
}
return pageNumbers;
}
public void setPageFormat(PageFormat page) {
pageFormat = page;
paint(this.getGraphics());
}
public int getPageCount() {
return getPageCount(this.getGraphics(), pageFormat);
}
public int getPageCount(Graphics g, java.awt.print.PageFormat pageFormat) {
int pageCount = (int) Math.ceil(this.getHeight() / pageFormat.getImageableHeight());
return pageCount;
}
public int print(java.awt.Graphics g, java.awt.print.PageFormat pageFormat, int p) throws java.awt.print.PrinterException {
if(p < getPageCount(g, pageFormat)) {
//System.out.println("Printing page " + p);
page = p;
Graphics2D g2d = (Graphics2D)g;
RepaintManager currentManager = RepaintManager.currentManager(this);
currentManager.setDoubleBufferingEnabled(false);
paint(g2d);
currentManager.setDoubleBufferingEnabled(true);
return(PAGE_EXISTS);
}
else {
return(NO_SUCH_PAGE);
}
}
@Override
public void paint(Graphics g) {
int pc = getPageCount(g, pageFormat);
if(pc != numberOfPages) {
updatePageSelector();
page = 0;
numberOfPages = pc;
}
double iHeight = pageFormat.getImageableHeight();
double iWidth = pageFormat.getImageableWidth();
double iX = pageFormat.getImageableX();
double iY = pageFormat.getImageableY();
g.setColor(Color.WHITE);
g.clipRect(0, 0, this.getWidth(), this.getHeight());
g.fillRect(0, 0, this.getWidth(), this.getHeight());
g.setColor(new Color(245,245,245));
g.drawRect((int) iX-1, (int) iY-1, (int) iWidth+1, (int) iHeight+1);
if(g instanceof Graphics2D) {
RenderingHints qualityHints = new RenderingHints(
RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
RenderingHints antialiasHints = new RenderingHints(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
RenderingHints metricsHints = new RenderingHints(
RenderingHints.KEY_FRACTIONALMETRICS,
RenderingHints.VALUE_FRACTIONALMETRICS_OFF);
((Graphics2D) g).addRenderingHints(qualityHints);
((Graphics2D) g).addRenderingHints(antialiasHints);
((Graphics2D) g).addRenderingHints(metricsHints);
((Graphics2D) g).translate(pageFormat.getImageableX(), pageFormat.getImageableY()-(page*iHeight));
((Graphics2D) g).clipRect(0, (int) (page*iHeight), (int) iWidth, (int) (iHeight));
//System.out.println("printing=="+(page*iHeight)+"-"+((page+1)*iHeight));
//System.out.println("((page+1)*iHeight)=="+((page+1)*iHeight));
//g.setColor(Color.WHITE);
//g.fillRect(0, (int) (page*iHeight), (int) iWidth, (int) iHeight);
}
super.paint(g);
}
// --------------------------------------------------------------- MOUSE ---
public void mouseClicked(java.awt.event.MouseEvent mouseEvent) {
}
public void mouseEntered(java.awt.event.MouseEvent mouseEvent) {
}
public void mouseExited(java.awt.event.MouseEvent mouseEvent) {
}
public void mousePressed(java.awt.event.MouseEvent mouseEvent) {
}
public void mouseReleased(java.awt.event.MouseEvent mouseEvent) {
}
public void actionPerformed(java.awt.event.ActionEvent actionEvent) {
//System.out.println("actionPerformed at Preview");
String c = actionEvent.getActionCommand();
if(c.equals("Copy")) {
ClipboardBox.setClipboard(getTopicAsText(parent));
}
if(c.equals("Copy as image")) {
BufferedImage image = new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_RGB);
this.print(image.getGraphics());
ClipboardBox.setClipboard(image);
}
else if(c.startsWith("Save")) {
save();
}
else if(c.startsWith("Print")) {
try{
print();
}catch(java.awt.print.PrinterException pe){
pe.printStackTrace();
}
}
else if(c.startsWith("Close")) {
frame.setVisible(false);
}
}
public void save() {
SimpleFileChooser chooser=UIConstants.getFileChooser();
chooser.setDialogTitle("Save text file");
if(chooser.open(parent, SimpleFileChooser.SAVE_DIALOG)==SimpleFileChooser.APPROVE_OPTION) {
save(chooser.getSelectedFile());
}
}
public void save(File textFile) {
if(textFile != null) {
String newText = "";
try {
FileWriter writer=new FileWriter(textFile);
write(writer);
writer.close();
//IObox.saveFile(textFile, textPane.getText());
}
catch(Exception e) {
System.out.println("Exception '" + e.toString() + "' occurred while saving file '" + textFile.getPath() + "'.");
}
}
}
}
}
| 35,687 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
PasteClasses.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/PasteClasses.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/>.
*
*
*
* PasteClasses.java
*
* Created on 7. marraskuuta 2005, 10:39
*/
package org.wandora.application.tools;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.Context;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
/**
* Inject clipboard topics i.e. base names to current topic as classes.
*
* @author akivela
*/
public class PasteClasses extends PasteTopics implements WandoraTool {
private static final long serialVersionUID = 1L;
public PasteClasses() {
super();
}
public PasteClasses(int includeOrders) {
super(includeOrders);
}
public PasteClasses(int includeOrders, int pasteOrders) {
super(includeOrders, pasteOrders);
}
public PasteClasses(Context preferredContext) {
setContext(preferredContext);
}
public PasteClasses(Context preferredContext, int includeOrders) {
super(includeOrders);
setContext(preferredContext);
}
public PasteClasses(Context preferredContext, int includeOrders, int pasteOrders) {
super(includeOrders, pasteOrders);
setContext(preferredContext);
}
@Override
public String getName() {
return "Paste classes";
}
@Override
public String getDescription() {
return "Inject clipboard topics i.e. basenames "+
"to current topic as classes.";
}
@Override
public void initialize(Wandora wandora) {
super.initialize(wandora);
ACCEPT_UNKNOWN_TOPICS = true;
}
@Override
public void topicPrologue(Topic topic) {
if(topic != null && currentTopic != null) {
try{
currentTopic.addType(topic);
}
catch(TopicMapException tme){
log(tme);
}
}
}
}
| 2,769 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
DummyTool.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/DummyTool.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;
import org.wandora.application.Wandora;
import org.wandora.application.contexts.Context;
/**
* An empty WandoraTool that doesn't do anything. Tool can be used as a
* separator in tool lists, for example.
*
* @author akivela
*/
public class DummyTool extends AbstractWandoraTool {
private static final long serialVersionUID = 1L;
@Override
public String getName() {
return "Dummy tool";
}
@Override
public String getDescription() {
return "This tool does nothing! It is used as a empty tool.";
}
@Override
public void execute(Wandora wandora, Context context) {
// NOTHING HERE!
}
@Override
public boolean requiresRefresh() {
return false;
}
}
| 1,589 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
CopyTopicClasses.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/CopyTopicClasses.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/>.
*
*
* CopyTopicClasses.java
*
* Created on 13. huhtikuuta 2006, 11:55
*
*/
package org.wandora.application.tools;
import org.wandora.application.contexts.ClassContext;
import org.wandora.topicmap.TopicMapException;
/**
* Copies class topics of selected topics to clipboard.
*
* @author akivela
*/
public class CopyTopicClasses extends CopyTopics {
private static final long serialVersionUID = 1L;
public CopyTopicClasses() throws TopicMapException {
}
@Override
public String getName() {
return "Copy topic classes";
}
@Override
public String getDescription() {
return "Copies class topics of selected topics to clipboard.";
}
@Override
public void initialize(int copyOrders, int includeOrders) {
super.initialize(copyOrders, includeOrders);
setContext(new ClassContext());
}
}
| 1,684 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SplitTopicsWithBasename.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/SplitTopicsWithBasename.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/>.
*
*
*
* SplitTopicsWithBasename.java
*
* Created on 13.7.2006, 16:41
*
*/
package org.wandora.application.tools;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
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.topicstringify.TopicToString;
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.TopicMapReadOnlyException;
/**
* WandoraTool splitting a topic with a regular expression applied to topic's base name.
* As a result, topic map contains one topic for each identified base name part.
* To prevent immediate merge subject identifiers and subject locators are
* modified a bit.
*
* @author akivela
*/
public class SplitTopicsWithBasename extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
public static boolean SKIP_WHITE_SPACE_SPLIT_PARTS = true;
public boolean duplicateAssociations = true;
public boolean copyInstances = true;
public boolean askName=false;
public static String splitString = "";
private int topicCounter = 0;
private int splitCounter = 0;
public SplitTopicsWithBasename() {
}
public SplitTopicsWithBasename(Context preferredContext) {
setContext(preferredContext);
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/topic_split.png");
}
@Override
public String getName() {
return "Split topics with base name";
}
@Override
public String getDescription() {
return "Tool splits topics with base name.";
}
@Override
public void execute(Wandora w, Context context) {
Iterator topics = getContext().getContextObjects();
if(topics == null || !topics.hasNext()) return;
TopicMap tm = w.getTopicMap();
splitString = WandoraOptionPane.showInputDialog(w, "Enter regular expression string used to split base name:", splitString);
if(splitString == null || splitString.length() == 0) return;
String splitStringCopy = splitString;
Topic topic = null;
duplicateAssociations = true;
copyInstances = true;
askName=false;
splitCounter = 0;
topicCounter = 0;
setDefaultLogger();
while(topics.hasNext() && !forceStop()) {
try {
topic = (Topic) topics.next();
if(topic != null) {
if(!topic.isRemoved()) {
Topic ltopic = tm.getTopic(topic.getOneSubjectIdentifier());
splitTopic(ltopic, splitStringCopy, tm, w);
}
}
}
catch(TopicMapReadOnlyException tmroe) {
log("Selected topic map is read only and can't be written. Can't split topic '"+TopicToString.toString(topic)+"'");
}
catch(TopicMapException tme) {
log(tme);
}
catch(Exception e) {
log(e);
}
}
if(topicCounter == 0) log("No topics splitted.");
else if(topicCounter == 1) log("One topic splitted.");
else log("Total "+topicCounter+" topics splitted.");
if(splitCounter == 0) log("Created no splitted topics.");
else if(splitCounter == 1) log("Created one splitted topic.");
else log("Created total "+splitCounter+" splitted topics.");
setState(WAIT);
}
public void splitTopic(Topic original, String splitString, TopicMap topicMap, Wandora w) throws TopicMapException {
if(original == null) return;
if(original.getBaseName() == null) {
log("Topic has no basename. Can't split.");
return;
}
if(original.getBaseName().length() == 0) {
log("Topic's basename length is zero. Can't split.");
}
String[] splitParts = original.getBaseName().split(splitString);
if(splitParts.length < 2) {
log("No split parts found for topic '"+ getTopicName(original) +"'.");
return;
}
Topic split = null;
String splitBasename = null;
for(int i=1; i<splitParts.length; i++) {
splitBasename = splitParts[i];
if(splitBasename == null || splitBasename.length() == 0) {
log("Zero length split part found for topic '"+ getTopicName(original) +"'.");
continue;
}
if(SKIP_WHITE_SPACE_SPLIT_PARTS) {
if(splitBasename.trim().length() == 0) {
log("White space split part found for topic '"+ getTopicName(original) +"'.");
continue;
}
}
// --- copy topic and associations ---
TopicMap splitMap = new org.wandora.topicmap.memory.TopicMapImpl();
split = splitMap.copyTopicIn(original, false);
if(duplicateAssociations) {
Collection<Association> associations = original.getAssociations();
if(associations != null && !associations.isEmpty()) {
for(Association association : associations) {
splitMap.copyAssociationIn(association);
}
}
}
// --- resolve new subject base name ---
String newBaseName = splitBasename;
if(askName){
while(true){
String input=WandoraOptionPane.showInputDialog(w, "Enter new base name for the topic", newBaseName);
if(input==null) return;
newBaseName=input;
if(topicMap.getTopicWithBaseName(input)!=null){
int a=WandoraOptionPane.showConfirmDialog(w, "Topic with base name '"+input+"' already exists and will be merged with new topic. Do you want to continue?");
if(a==WandoraOptionPane.CANCEL_OPTION) return;
else if(a==WandoraOptionPane.YES_OPTION) break;
}
else break;
}
}
split.setBaseName(newBaseName);
// --- resolve new subject locator ---
if(original.getSubjectLocator() != null) {
int c = 2;
Locator newSubjectLocator = new Locator(original.getSubjectLocator().toExternalForm() + "_split");
while(topicMap.getTopicBySubjectLocator(newSubjectLocator) != null && c<10000) {
newSubjectLocator = new Locator(original.getSubjectLocator().toExternalForm() + "_split" + c);
c++;
}
split.setSubjectLocator(newSubjectLocator);
}
// --- resolve new subject identifiers ---
Collection<Locator> sis = split.getSubjectIdentifiers();
ArrayList<Locator> siv = new ArrayList();
siv.addAll(sis);
Locator l = null;
for(Locator lo : siv) {
l = new Locator(lo.toExternalForm() + "_split");
int c = 2;
while((topicMap.getTopic(l) != null || splitMap.getTopic(l) != null) && c<10000) {
l = new Locator(lo.toExternalForm() + "_split" + c);
c++;
}
split.addSubjectIdentifier(l);
split.removeSubjectIdentifier(lo);
}
//log("Merging splitted topic to original map...");
topicMap.mergeIn(splitMap);
split = topicMap.getTopicWithBaseName(newBaseName);
// --- attach instances ---
if(split != null && copyInstances) {
Collection<Topic> instances = topicMap.getTopicsOfType(original);
if(instances != null && !instances.isEmpty()) {
for(Topic instance : instances) {
instance.addType(split);
}
}
}
splitCounter++;
}
// Change base name of the original topic....
original.setBaseName(splitParts[0]);
topicCounter++;
}
// -------------------------------------------------------------------------
public static void main(String[] args) {
String originalFilename = "F:\\projects\\kokoelmat\\update150615\\asiasanat\\original.txt";
String modsFilename = "F:\\projects\\kokoelmat\\update150615\\asiasanat\\mods.txt";
FileInputStream fstream = null;
BufferedReader br = null;
FileInputStream fstream2 = null;
BufferedReader br2 = null;
try {
fstream = new FileInputStream(originalFilename);
br = new BufferedReader(new InputStreamReader(fstream));
String str = null;
Map<String,String> originals = new LinkedHashMap<>();
while ((str = br.readLine()) != null) {
String[] keyValue = str.split("\t");
if(keyValue.length == 2) {
String key = keyValue[1].trim();
String value = keyValue[0];
if(!originals.containsKey(key)) {
originals.put(key, value);
// System.out.println("Adding key: "+key);
}
else {
System.out.println("Originals already contains key: "+key);
originals.put(key, originals.get(key) + " ; " + value);
}
}
else {
System.out.println("Illegal number of elements in original line: "+str);
}
}
System.out.println("Originals has "+originals.size()+" values.");
br.close();
fstream2 = new FileInputStream(modsFilename);
br2 = new BufferedReader(new InputStreamReader(fstream2));
while ((str = br2.readLine()) != null) {
String[] keyValue = str.split("\t");
if(keyValue.length == 2) {
String key = keyValue[1].trim();
String value = keyValue[0];
if(originals.containsKey(key)) {
String originalValue = (String) originals.get(key);
if(originalValue.contains(value)) {
// OK!
}
else {
System.out.println("Original key "+keyValue[1]+ " contains no '"+keyValue[0]+"'");
}
}
else {
System.out.println("Originals has no key: "+keyValue[1]);
}
}
else {
System.out.println("Illegal number of elements in original line: "+str);
}
}
}
catch(Exception e) {
e.printStackTrace();
}
finally {
if(br != null) {
try { br.close(); } catch(Exception e) {}
}
if(fstream != null) {
try { fstream.close(); } catch(Exception e) {}
}
if(br2 != null) {
try { br2.close(); } catch(Exception e ) {}
}
if(fstream2 != null) {
try { fstream2.close(); } catch(Exception e) {}
}
}
}
}
| 13,046 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
ContextToolWrapper.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/ContextToolWrapper.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/>.
*
*
* ContextToolWrapper.java
*
* Created on 28.7.2006, 12:43
*/
package org.wandora.application.tools;
import java.awt.event.ActionEvent;
import javax.swing.Icon;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.WandoraToolLogger;
import org.wandora.application.WandoraToolType;
import org.wandora.application.contexts.Context;
import org.wandora.application.contexts.LayeredTopicContext;
import org.wandora.application.gui.simple.SimpleMenuItem;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author olli
*/
public class ContextToolWrapper implements WandoraTool {
private static final long serialVersionUID = 1L;
private WandoraTool wrapped;
private Context context;
/** Creates a new instance of ContextToolWrapper */
public ContextToolWrapper(WandoraTool wrapped) {
this(wrapped,new LayeredTopicContext());
}
public ContextToolWrapper(WandoraTool wrapped,Context context) {
this.wrapped=wrapped;
this.context=context;
}
@Override
public WandoraToolType getType(){
return wrapped.getType();
}
@Override
public Context getContext(){
return context;
}
@Override
public void setContext(Context context){
this.context=context;
}
@Override
public boolean forceStop(){
return wrapped.forceStop();
}
@Override
public int getState(){
return wrapped.getState();
}
@Override
public void setState(int state){
wrapped.setState(state);
}
@Override
public void setToolLogger(WandoraToolLogger logger) {
wrapped.setToolLogger(logger);
}
@Override
public void hlog(String message){
wrapped.hlog(message);
}
@Override
public void log(String message){
wrapped.log(message);
}
@Override
public void log(String message, Exception e){
wrapped.log(message,e);
}
@Override
public void log(Exception e){
wrapped.log(e);
}
@Override
public void log(Error e){
wrapped.log(e);
}
@Override
public void setProgress(int n){
wrapped.setProgress(n);
}
@Override
public void setProgressMax(int maxn){
wrapped.setProgressMax(maxn);
}
@Override
public void setLogTitle(String title){
wrapped.setLogTitle(title);
}
@Override
public void lockLog(boolean lock){
wrapped.lockLog(lock);
}
@Override
public String getHistory(){
return wrapped.getHistory();
}
@Override
public String getName() {
return wrapped.getName();
}
@Override
public String getDescription() {
return wrapped.getDescription();
}
@Override
public void initialize(Wandora wandora,org.wandora.utils.Options options,String prefix) throws TopicMapException {
wrapped.initialize(wandora,options,prefix);
}
@Override
public boolean isConfigurable(){
return wrapped.isConfigurable();
}
@Override
public void configure(Wandora wandora,org.wandora.utils.Options options,String prefix) throws TopicMapException {
wrapped.configure(wandora,options,prefix);
}
@Override
public void writeOptions(Wandora wandora,org.wandora.utils.Options options,String prefix){
wrapped.writeOptions(wandora,options,prefix);
}
@Override
public void execute(Wandora wandora) throws TopicMapException {
execute(wandora, (ActionEvent) null);
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
wrapped.execute(wandora,context);
}
@Override
public void execute(Wandora wandora, ActionEvent event) throws TopicMapException {
wrapped.setContext(context);
wrapped.execute(wandora,event);
}
@Override
public boolean isRunning() {
return wrapped.isRunning();
}
@Override
public boolean requiresRefresh(){
return wrapped.requiresRefresh();
}
@Override
public SimpleMenuItem getToolMenuItem(Wandora wandora,String instanceName){
return wrapped.getToolMenuItem(wandora,instanceName);
}
@Override
public Icon getIcon() {
return wrapped.getIcon();
}
}
| 5,224 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
DeleteTopicsWithoutVariants.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/DeleteTopicsWithoutVariants.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;
import java.util.Set;
import org.wandora.application.WandoraTool;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author akivela
*/
public class DeleteTopicsWithoutVariants extends DeleteTopics implements WandoraTool {
private static final long serialVersionUID = 1L;
/** Creates a new instance of DeleteTopicsWithoutVariants */
public DeleteTopicsWithoutVariants() {
}
@Override
public String getName() {
return "Delete topics without variant names";
}
@Override
public String getDescription() {
return "Delete context topics without variant names.";
}
@Override
public boolean shouldDelete(Topic topic) throws TopicMapException {
try {
if(topic != null && !topic.isRemoved()) {
Set<Set<Topic>> variantScopes = topic.getVariantScopes();
if(variantScopes == null || variantScopes.isEmpty()) {
if(confirm) {
return confirmDelete(topic);
}
else {
return true;
}
}
}
}
catch(Exception e) {
log(e);
}
return false;
}
} | 2,138 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
PasteTopics.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/PasteTopics.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/>.
*
*
*
* PasteTopics.java
*
* Created on 30. lokakuuta 2005, 20:19
*
*/
package org.wandora.application.tools;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.StringTokenizer;
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.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.XTMPSI;
import org.wandora.utils.ClipboardBox;
import org.wandora.utils.Textbox;
/**
*
* @author akivela
*/
public class PasteTopics extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
public static final int PASTE_SIS = 99;
public static final int PASTE_BASENAMES = 1000;
public static final int INCLUDE_NAMES = 1001;
public static final int INCLUDE_CLASSES = 1002;
public static final int INCLUDE_INSTANCES = 1003;
public static final int INCLUDE_SLS = 1004;
public static final int INCLUDE_SIS = 1005;
public static final int INCLUDE_PLAYERS = 1006;
public static final int INCLUDE_TEXTDATAS = 1007;
public static final int INCLUDE_NOTHING = 9999;
public int includeOrders = INCLUDE_NOTHING;
public int pasteOrders = PASTE_BASENAMES;
public boolean forceStop = false;
public boolean PLAYER_SHOULD_NOT_BE_EQUAL_TO_INSTANCE = true;
public boolean ASK_TOPIC_CREATION = true;
public boolean ACCEPT_UNKNOWN_TOPICS = false;
public boolean USER_HAS_BEEN_ASKED = false;
public Iterator contextTopics = null;
public Topic currentTopic = null;
public TopicMap topicMap = null;
public PasteTopics() {
this(INCLUDE_NOTHING);
}
public PasteTopics(int includeOrders) {
this.includeOrders = includeOrders;
}
public PasteTopics(int includeOrders, int pasteOrders) {
this.pasteOrders = pasteOrders;
this.includeOrders = includeOrders;
}
public PasteTopics(Context context) {
this(INCLUDE_NOTHING);
setContext(context);
}
public PasteTopics(Context context, int includeOrders) {
this(includeOrders);
setContext(context);
}
public PasteTopics(Context context, int includeOrders, int pasteOrders) {
this(includeOrders, pasteOrders);
setContext(context);
}
public void initialize(Wandora wandora) {
ASK_TOPIC_CREATION = true;
ACCEPT_UNKNOWN_TOPICS = false;
USER_HAS_BEEN_ASKED = false;
forceStop = false;
topicMap = wandora.getTopicMap();
}
@Override
public void execute(Wandora wandora, Context context) {
initialize(wandora);
try {
if(WandoraOptionPane.showConfirmDialog(
wandora,
"Are you sure you want to paste topics using text on clipboard?",
"Confirm paste",
WandoraOptionPane.YES_NO_OPTION)==WandoraOptionPane.YES_OPTION) {
String tabText = ClipboardBox.getClipboard();
StringTokenizer st = new StringTokenizer(tabText, "\n");
Topic occurrenceType = null;
Topic occurrenceScope = null;
if(includeOrders == INCLUDE_TEXTDATAS) {
occurrenceType=wandora.showTopicFinder("Select occurrence type...");
if(occurrenceType == null) return;
occurrenceScope=wandora.showTopicFinder("Select occurrence language (scope)...");
if(occurrenceScope == null) return;
}
Topic associationType = null;
Topic topicRole = null;
Topic playerRole = null;
if(includeOrders == INCLUDE_PLAYERS) {
associationType=wandora.showTopicFinder("Select association type...");
if(associationType == null) return;
topicRole=wandora.showTopicFinder("Select instance's role...");
if(topicRole == null) return;
playerRole=wandora.showTopicFinder("Select player's role...");
if(playerRole == null) return;
}
Set<Topic> nameScope = new HashSet<>();
if(includeOrders == INCLUDE_NAMES) {
Topic langTopic=wandora.showTopicFinder("Select name language...");
if(langTopic == null) return;
Topic scopeTopic=wandora.showTopicFinder("Select name scope...");
if(scopeTopic == null) return;
nameScope.add(langTopic);
nameScope.add(scopeTopic);
}
try {
String names = null;
while(st.hasMoreTokens() && !forceStop && !forceStop()) {
names = st.nextToken();
StringTokenizer nt = new StringTokenizer(names, "\t");
try {
String topicIdentifier = null;
if(nt.hasMoreTokens()) {
topicIdentifier = nt.nextToken();
if(topicIdentifier != null && topicIdentifier.length() > 0) {
Topic topic = getTopic(wandora, topicMap, topicIdentifier, pasteOrders == PASTE_BASENAMES);
//log("topic: " + topic);
if(!ACCEPT_UNKNOWN_TOPICS && !isKnownTopic(topic, context) && !USER_HAS_BEEN_ASKED) {
USER_HAS_BEEN_ASKED = true;
ACCEPT_UNKNOWN_TOPICS = WandoraOptionPane.showConfirmDialog(wandora, "Clipboard data addresses topics not in selection! Paste anyway?") == WandoraOptionPane.YES_OPTION;
}
if(ACCEPT_UNKNOWN_TOPICS || isKnownTopic(topic, context)) {
contextTopics = context.getContextObjects();
while(contextTopics.hasNext()) {
currentTopic = (Topic) contextTopics.next();
if(topic != null && currentTopic != null) {
topicPrologue(topic);
switch(includeOrders) {
case INCLUDE_NAMES: {
if(nt.hasMoreTokens()) {
topic.setVariant(nameScope, nt.nextToken());
}
break;
}
case INCLUDE_CLASSES: {
while(nt.hasMoreTokens() && !forceStop) {
String instanceClass = nt.nextToken();
Topic instanceClassTopic = getTopic(wandora, topicMap, instanceClass, true);
if(instanceClassTopic != null) {
topic.addType(instanceClassTopic);
}
}
break;
}
case INCLUDE_INSTANCES: {
while(nt.hasMoreTokens() && !forceStop) {
String instance = nt.nextToken();
Topic instanceTopic = getTopic(wandora, topicMap, instance, true);
if(instanceTopic != null) {
instanceTopic.addType(topic);
}
}
break;
}
case INCLUDE_SIS: {
while(nt.hasMoreTokens() && !forceStop) {
String si = nt.nextToken();
if(si != null && si.length() > 0) {
try {
//System.out.println("Adding SI '" +si+ "' to " + topic.getBaseName());
topic.addSubjectIdentifier(new Locator(si));
}
catch (Exception e) {
log(e);
}
}
}
break;
}
case INCLUDE_SLS: {
if(nt.hasMoreTokens() && !forceStop) {
String sl = nt.nextToken();
if(sl != null && sl.length() > 0) {
try {
topic.setSubjectLocator(new Locator(sl));
}
catch (Exception e) {
log(e);
}
}
}
break;
}
case INCLUDE_TEXTDATAS: {
if(nt.hasMoreTokens()) {
topic.setData(occurrenceType, occurrenceScope, nt.nextToken());
}
break;
}
case INCLUDE_PLAYERS: {
while(nt.hasMoreTokens() && !forceStop) {
String player = nt.nextToken();
if(player != null && player.length() > 0) {
if(PLAYER_SHOULD_NOT_BE_EQUAL_TO_INSTANCE && player.equals(topic)) break;
Topic playerTopic = getTopic(wandora, topicMap, player, true);
if(playerTopic != null && !forceStop) {
Association a = topicMap.createAssociation(associationType);
a.addPlayer(topic, topicRole);
a.addPlayer(playerTopic, playerRole);
}
}
}
break;
}
}
topicEpilogue(topic);
}
}
}
}
}
}
catch (Exception e) {
log(e);
}
}
}
catch(Exception e) {
log(e);
}
}
}
catch(Exception e) {
log(e);
}
}
public void topicPrologue(Topic topic) {
}
public void topicEpilogue(Topic topic) {
}
@Override
public String getName() {
return "Paste Topics";
}
@Override
public String getDescription() {
return "Injects clipboard topics to the topic map.";
}
public void setPasteOrders(int pasteOrders) {
this.pasteOrders = pasteOrders;
}
public Topic getTopic(Wandora admin, TopicMap topicMap, String identifier, boolean isBasename) throws TopicMapException {
if(identifier != null) {
identifier = Textbox.trimExtraSpaces(identifier);
if(identifier.length() > 0) {
Topic t = null;
// Identifier is base name!
if(isBasename) {
t = topicMap.getTopicWithBaseName(identifier);
if(t == null && identifier.indexOf(',') != -1) {
t = topicMap.getTopicWithBaseName(identifier.substring(0, identifier.indexOf(',')));
if(t != null) {
//log("t == " + t.getBaseName());
t.setBaseName(identifier);
}
}
//if(t != null) log("t.basename == " + t.getBaseName());
//else log("t == null (for " + identifier + ")");
}
else {
t = topicMap.getTopicWithBaseName(identifier);
if(t == null) t = topicMap.getTopic(identifier);
}
if(t == null) {
try {
boolean createTopic = true;
if(ASK_TOPIC_CREATION) {
String[] topicCreationOptions = new String[] {
"Create topic '" + identifier + "'",
"Create topic '" + identifier + "' and all subsequent topics",
"Don't create topic '" + identifier + "' but continue operation",
"Don't create topic '" + identifier + "' and cancel operation",
};
String answer = (String) WandoraOptionPane.showOptionDialog(admin ,"Topic does not exists! Would you like to create new topic for '" + identifier + "'?","Create new topic?",WandoraOptionPane.PLAIN_MESSAGE, topicCreationOptions, topicCreationOptions[0]);
//log("answer == " + answer);
if(topicCreationOptions[0].equalsIgnoreCase(answer)) { createTopic = true; }
else if(topicCreationOptions[1].equalsIgnoreCase(answer)) { ASK_TOPIC_CREATION = false; createTopic = true; }
else if(topicCreationOptions[2].equalsIgnoreCase(answer)) { createTopic = false; }
else if(topicCreationOptions[3].equalsIgnoreCase(answer)) { createTopic = false; forceStop = true; }
else createTopic = false;
}
if(createTopic) {
if(isBasename) {
t = topicMap.createTopic();
t.setBaseName(identifier);
String si = "http://wandora.org/si/" + System.currentTimeMillis();
int counter = 1000;
while(topicMap.getTopic(si) != null && --counter > 0) {
si = "http://wandora.org/si/" + System.currentTimeMillis() + Math.floor(Math.random() * 10000);
}
t.addSubjectIdentifier(new Locator(si));
}
else { // is subjet locator.....
Locator l = new Locator(identifier);
if(l != null) {
t = topicMap.createTopic();
t.addSubjectIdentifier(l);
}
}
}
}
catch (Exception e) {
WandoraOptionPane.showMessageDialog(admin ,"Unable to create new topic with identifier '" + identifier + "'. Exception occurred: " + e.getMessage(),"Exception occurred!",WandoraOptionPane.ERROR_MESSAGE);
}
}
return t;
}
}
return null;
}
public boolean isKnownTopic(Topic topic, Context context) throws TopicMapException {
if(topic == null || context == null) return false;
Iterator topics = context.getContextObjects();
while(topics.hasNext()) {
if(topic.mergesWithTopic((Topic) topics.next())) return true;
}
return false;
}
public void setDisplayName(Topic t, String lang, String name) throws TopicMapException {
if(t != null) {
String variantName = Textbox.trimExtraSpaces(name);
if(variantName != null && variantName.length() > 0) {
String langsi=XTMPSI.getLang(lang);
Topic langT =t.getTopicMap().getTopic(langsi);
String dispsi=XTMPSI.DISPLAY;
Topic dispT=t.getTopicMap().getTopic(dispsi);
Set<Topic> scope=new LinkedHashSet<>();
if(langT!=null) scope.add(langT);
if(dispT!=null) scope.add(dispT);
t.setVariant(scope, variantName);
}
}
}
public void setTextdata(Topic t, Topic type, String version, String data) throws TopicMapException {
if(t != null) {
data = Textbox.trimExtraSpaces(data);
if(data != null && data.length() > 0) {
String langsi=XTMPSI.getLang(version);
Topic langT =t.getTopicMap().getTopic(langsi);
t.setData(type, langT, data);
}
}
}
}
| 20,779 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
PasteInstances.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/PasteInstances.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/>.
*
*
*
* PasteInstances.java
*
* Created on 6. tammikuuta 2005, 12:56
*/
package org.wandora.application.tools;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.Context;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
/**
* Inject clipboard topics i.e. base names to current topic as instances.
*
* @author akivela
*/
public class PasteInstances extends PasteTopics implements WandoraTool {
private static final long serialVersionUID = 1L;
public PasteInstances() {}
public PasteInstances(int includeOrders) {
super(includeOrders);
}
public PasteInstances(int includeOrders, int pasteOrders) {
super(includeOrders, pasteOrders);
}
public PasteInstances(Context preferredContext) {
setContext(preferredContext);
}
public PasteInstances(Context preferredContext, int includeOrders) {
super(includeOrders);
setContext(preferredContext);
}
public PasteInstances(Context preferredContext, int includeOrders, int pasteOrders) {
super(includeOrders, pasteOrders);
setContext(preferredContext);
}
@Override
public String getName() {
return "Paste instances";
}
@Override
public String getDescription() {
return "Inject clipboard topics to selected topic as instances.";
}
@Override
public void initialize(Wandora admin) {
super.initialize(admin);
ACCEPT_UNKNOWN_TOPICS = true;
}
@Override
public void topicPrologue(Topic topic) {
if(topic != null && currentTopic != null) {
try {
topic.addType(currentTopic);
} catch(TopicMapException tme){
log(tme);
}
}
}
}
| 2,712 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
NewTopic.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/NewTopic.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/>.
*
*
*
* NewTopic.java
*
* Created on 28. joulukuuta 2005, 21:49
*
*/
package org.wandora.application.tools;
import java.net.URL;
import java.util.Iterator;
import javax.swing.Icon;
import javax.swing.JDialog;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.ConfirmResult;
import org.wandora.application.gui.NewTopicPanel;
import org.wandora.application.gui.UIBox;
import org.wandora.application.gui.WandoraOptionPane;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.SchemaBox;
import org.wandora.topicmap.TMBox;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
/**
* WandoraTool for topic creation. User may enter topic's base name and subject
* identifier. If constructor argument is given, created topic is associated with
* a context topic.
*
* @author akivela
*/
public class NewTopic extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
public static final int MAKE_INSTANCE_OF_CONTEXT = 100;
public static final int MAKE_SUBCLASS_OF_CONTEXT = 101;
public int orders = 0;
public boolean confirm = true;
/** Creates a new instance of NewTopic */
public NewTopic() {
}
public NewTopic(int orders) {
this.orders = orders;
}
// -------------------------------------------------------------------------
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
Topic newTopic = null;
String confirmMessage = null;
String basename = null;
int answer = 0;
Topic contextTopic = null;
// --- New topic is created using a custom dialog panel.
newTopic = createNewTopic(wandora, "Create new topic", context);
if(newTopic==null) return;
// --- Now we are going to post process the created topic.
switch(orders) {
case MAKE_INSTANCE_OF_CONTEXT: {
Iterator contextTopics = getContext().getContextObjects();
if(contextTopics != null && contextTopics.hasNext()) {
while(contextTopics.hasNext()) {
contextTopic = (Topic) contextTopics.next();
if(confirm) {
basename = contextTopic.getBaseName();
// confirmMessage = "Make created topic instance of '" + basename + "'?";
// answer = WandoraOptionPane.showConfirmDialog(admin, confirmMessage,"Make instance" );
// if(answer == WandoraOptionPane.YES_OPTION) {
newTopic.addType(contextTopic);
// }
// else if(answer == WandoraOptionPane.CANCEL_OPTION) {
// break;
// }
}
else {
newTopic.addType(contextTopic);
}
}
}
else {
WandoraOptionPane.showMessageDialog(
wandora,
"Select class topic for the new topic.",
"Select class topic",
WandoraOptionPane.WARNING_MESSAGE);
}
break;
}
case MAKE_SUBCLASS_OF_CONTEXT: {
Iterator contextTopics = getContext().getContextObjects();
if(contextTopics != null && contextTopics.hasNext()) {
while(contextTopics.hasNext()) {
contextTopic = (Topic) contextTopics.next();
if(confirm) {
basename = contextTopic.getBaseName();
// confirmMessage = "Make created topic subclass of '" + basename + "'?";
// answer = WandoraOptionPane.showConfirmDialog(admin, confirmMessage,"Make subclass of" );
// if(answer == WandoraOptionPane.YES_OPTION) {
SchemaBox.setSuperClass(newTopic, contextTopic);
// }
// else if(answer == WandoraOptionPane.CANCEL_OPTION) {
// break;
// }
}
else {
SchemaBox.setSuperClass(newTopic, contextTopic);
}
}
}
else {
WandoraOptionPane.showMessageDialog(
wandora,
"Select superclass topic for the new topic.",
"Select superclass topic",
WandoraOptionPane.WARNING_MESSAGE);
}
break;
}
default: {
break;
}
}
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/new_topic.png");
}
@Override
public String getName() {
return "New Topic";
}
@Override
public String getDescription() {
return "Creates new topic in Wandora. "+
"User may enter initial basename and SI for the new topic.";
}
// -------------------------------------------------------------------------
public Topic createNewTopic(Wandora wandora, String windowTitle, Context context) throws TopicMapException {
Topic newTopic = null;
TopicMap topicMap = wandora.getTopicMap();
JDialog newTopicDialog = new JDialog(wandora, windowTitle, true);
newTopicDialog.setSize(600, 250);
wandora.centerWindow(newTopicDialog);
NewTopicPanel newTopicPanel = new NewTopicPanel(newTopicDialog);
//String name=WandoraOptionPane.showInputDialog(admin, "Enter topic base name");
String name = newTopicPanel.getBasename();
String si = newTopicPanel.getSI();
if(name != null) name = name.trim();
if(si != null) si = si.trim();
if(newTopicPanel.getAccepted()) {
if((name != null && name.length() > 0) || (si != null && si.length() > 0)) {
newTopic=topicMap.createTopic();
if(name != null && name.length() > 0) {
if(TMBox.checkBaseNameChange(wandora,newTopic,name)!=ConfirmResult.yes){
newTopic.remove();
return null;
}
}
if(si!=null && si.length()>0) {
if(TMBox.checkSubjectIdentifierChange(wandora,newTopic,topicMap.createLocator(si),true)!=ConfirmResult.yes){
newTopic.remove();
return null;
}
}
if(name != null && name.length()>0) {
newTopic.setBaseName(name);
}
if(si != null && si.length() > 0) {
try {
URL siUrl = new URL(si);
newTopic.addSubjectIdentifier(topicMap.createLocator(siUrl.toExternalForm()));
}
catch(Exception e) {
log(e);
}
}
if(newTopic.getSubjectIdentifiers().isEmpty()) {
Locator defaultSI = topicMap.makeSubjectIndicatorAsLocator();
newTopic.addSubjectIdentifier(defaultSI);
WandoraOptionPane.showMessageDialog(wandora, "Valid subject identifier was not available. Topic was given default subject identifier '"+defaultSI.toExternalForm()+"'.", "Default SI given to new topic", WandoraOptionPane.INFORMATION_MESSAGE);
}
else{
// newTopic is layeredTopic so it may not have a SI in the selected layer
newTopic.addSubjectIdentifier(newTopic.getOneSubjectIdentifier());
}
}
else {
WandoraOptionPane.showMessageDialog(wandora, "No subject identifier nor basename was given. No topic created!", "No topic created", WandoraOptionPane.WARNING_MESSAGE);
}
}
return newTopic;
}
}
| 9,507 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
DeleteTopicsExceptSelected.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/DeleteTopicsExceptSelected.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;
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.WandoraOptionPane;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author akivela
*/
public class DeleteTopicsExceptSelected extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
/** Creates a new instance of DeleteTopicsExceptSelected */
public DeleteTopicsExceptSelected() {
}
@Override
public String getName() {
return "Delete all topics except selected";
}
@Override
public String getDescription() {
return "Deleted all topics except selected ones in current layer.";
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
Iterator selectedTopics = getContext().getContextObjects();
Topic selectedTopic = null;
int count = 0;
int answer = WandoraOptionPane.showConfirmDialog(wandora,"This tool deletes all topics in selected layer except selected topics! Are you sure you want to continue?", "Delete all topics except selected?", WandoraOptionPane.YES_NO_OPTION);
if(answer == WandoraOptionPane.YES_OPTION) {
setDefaultLogger();
TopicMap contextTopicMap = wandora.getTopicMap(); // solveContextTopicMap(wandora, context);
Iterator<Topic> allTopics = contextTopicMap.getTopics();
Topic atopic = null;
while(allTopics.hasNext() && !forceStop()) {
atopic = allTopics.next();
try {
if(atopic != null && !atopic.isRemoved() && !atopic.isDeleteAllowed()) {
boolean deleteATopic = true;
selectedTopics = getContext().getContextObjects();
if(selectedTopics != null && selectedTopics.hasNext()) {
while(selectedTopics.hasNext() && !forceStop()) {
selectedTopic = (Topic) selectedTopics.next();
if(selectedTopic != null) {
if(selectedTopic.mergesWithTopic(atopic)) {
deleteATopic = false;
break;
}
}
}
}
if(deleteATopic) {
try {
hlog("Deleting topic '" + getTopicName(atopic) + "'.");
atopic.remove();
count++;
}
catch(Exception e) {
log(e);
}
}
}
}
catch(Exception e) {
log(e);
}
}
log("Total " + count + " topics deleted!");
setState(WAIT);
}
}
}
| 4,110 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
DiffTool.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/DiffTool.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;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringWriter;
import javax.swing.Icon;
import javax.swing.JDialog;
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.texteditor.TextEditor;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.topicmap.TopicMapType;
import org.wandora.topicmap.TopicMapTypeManager;
import org.wandora.topicmap.diff.BasicDiffOutput;
import org.wandora.topicmap.diff.DiffEntryFormatter;
import org.wandora.topicmap.diff.HTMLDiffEntryFormatter;
import org.wandora.topicmap.diff.PatchDiffEntryFormatter;
import org.wandora.topicmap.diff.PlainTextDiffEntryFormatter;
import org.wandora.topicmap.diff.TopicMapDiff;
import org.wandora.topicmap.layered.Layer;
import org.wandora.topicmap.layered.LayerStack;
import org.wandora.topicmap.memory.TopicMapImpl;
import org.wandora.topicmap.packageio.PackageInput;
import org.wandora.topicmap.packageio.ZipPackageInput;
import org.wandora.utils.swing.GuiTools;
/**
*
* @author olli
*/
public class DiffTool extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
@Override
public String getName() {
return "Topic map diff";
}
@Override
public String getDescription() {
return "Finds differences between two topic maps";
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/compare_topicmaps.png");
}
@Override
public boolean requiresRefresh() {
return false;
}
public TopicMap openFile(String f,Wandora admin) throws IOException, TopicMapException {
String extension="";
int ind=f.lastIndexOf(".");
if(ind>-1) extension=f.substring(ind+1);
if(extension.equalsIgnoreCase("wpr")){
PackageInput in=new ZipPackageInput(f);
TopicMapType type=TopicMapTypeManager.getType(LayerStack.class);
log("Loading Wandora project file");
TopicMap tm=type.unpackageTopicMap(in,"",getCurrentLogger(),admin);
in.close();
return tm;
}
else if(extension.equalsIgnoreCase("ltm")){
TopicMap tm=new TopicMapImpl();
log("Loading LTM topic map");
tm.importLTM(f);
return tm;
}
else if(extension.equalsIgnoreCase("jtm")){
TopicMap tm=new TopicMapImpl();
log("Loading JTM topic map");
tm.importJTM(f);
return tm;
}
else{ // xtm
TopicMap tm=new TopicMapImpl();
log("Loading XTM topic map");
tm.importXTM(f);
return tm;
}
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
JDialog dialog=new JDialog(wandora,"Compare topic maps",true);
DiffToolConfigPanel configPanel=new DiffToolConfigPanel(wandora,dialog);
dialog.getContentPane().add(configPanel);
dialog.setSize(500, 350);
configPanel.addFormat("Plain text format");
configPanel.addFormat("HTML format");
configPanel.addFormat("Patch format");
GuiTools.centerWindow(dialog, wandora);
dialog.setVisible(true);
if(configPanel.wasCancelled()) return;
setDefaultLogger();
setProgressMax(10000);
String filename=null;
try{
TopicMap tm1=null;
TopicMap tm2=null;
int mode1=configPanel.getMap1Mode();
if(mode1==DiffToolConfigPanel.MODE_FILE){
filename = configPanel.getMap1Value();
if(filename != null && !"".equals(filename)) {
tm1=openFile(filename,wandora);
}
else {
log("Filename not specified for topic map 1!");
log("Cancelling compare.");
setState(WAIT);
return;
}
}
else if(mode1==DiffToolConfigPanel.MODE_LAYER){
Layer l=wandora.getTopicMap().getLayer(configPanel.getMap1Value());
if(l==null) {
log("Layer not found");
log("Cancelling compare.");
setState(WAIT);
return;
}
tm1=l.getTopicMap();
}
else if(mode1==DiffToolConfigPanel.MODE_PROJECT){
tm1=wandora.getTopicMap();
}
int mode2=configPanel.getMap2Mode();
filename = null;
if(mode2==DiffToolConfigPanel.MODE_FILE){
filename = configPanel.getMap2Value();
if(filename != null && !"".equals(filename)) {
tm2=openFile(filename,wandora);
}
else {
log("Filename not specified for topic map 2!");
log("Cancelling compare.");
setState(WAIT);
return;
}
}
else if(mode2==DiffToolConfigPanel.MODE_LAYER){
Layer l=wandora.getTopicMap().getLayer(configPanel.getMap2Value());
if(l==null) {
log("Layer not found");
log("Cancelling compare.");
setState(WAIT);
return;
}
tm2=l.getTopicMap();
}
else if(mode2==DiffToolConfigPanel.MODE_PROJECT){
tm2=wandora.getTopicMap();
}
TopicMapDiff diffMaker=new TopicMapDiff();
ToolDiffOutput output=null;
String format=configPanel.getFormat();
boolean html=true;
if(format.equalsIgnoreCase("Patch format")){
html=false;
output=new ToolDiffOutput(new PatchDiffEntryFormatter());
}
else if(format.equalsIgnoreCase("Plain text format")){
html=false;
output=new ToolDiffOutput(new PlainTextDiffEntryFormatter());
}
else{
output=new ToolDiffOutput(new HTMLDiffEntryFormatter());
}
log("Comparing topic maps.");
if(diffMaker.makeDiff(tm1,tm2,output)){
log("Comparison ready. Opening results...");
TextEditor e = new TextEditor(wandora, true);
String result = output.getResult();
if(html) {
e.setContentType("text/html");
e.setSuperText("<html>"+result+"</html>");
//=new TextEditor(admin,true,"<html>"+result+"</html>","text/html");
}
else {
e.setSuperText(result);
}
e.setCancelButtonVisible(false);
setState(INVISIBLE);
e.setVisible(true);
setState(VISIBLE);
setState(CLOSE);
}
else{
setState(WAIT);
}
} catch(FileNotFoundException fnfe) {
log("File not found exception occurred while opening file '"+filename+"'.");
setState(WAIT);
} catch(IOException ioe){
log(ioe);
setState(WAIT);
}
}
private class ToolDiffOutput extends BasicDiffOutput {
private int counter=0;
private StringWriter sw;
public ToolDiffOutput(DiffEntryFormatter formatter){
super(formatter,new StringWriter());
this.sw=(StringWriter)writer;
}
private void increaseCounter(){
counter++;
setProgress(counter);
}
@Override
public boolean outputDiffEntry(TopicMapDiff.DiffEntry d){
if(forceStop()) return false;
increaseCounter();
try{
doOutput(d);
}catch(Exception e){
log(e);
return false;
}
return true;
}
@Override
public boolean noDifferences(Topic t){
if(forceStop()) return false;
increaseCounter();
return true;
}
@Override
public boolean noDifferences(Association a){
if(forceStop()) return false;
increaseCounter();
return true;
}
public String getResult(){
return sw.toString();
}
}
}
| 9,786 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
MakeInstancesWithAssociations.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/MakeInstancesWithAssociations.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/>.
*
*
*
* MakeInstancesWithAssociations.java
*
* Created on 6.7.2006, 14:19
*
*/
package org.wandora.application.tools;
import java.util.Iterator;
import org.wandora.application.Wandora;
import org.wandora.application.contexts.AssociationContext;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.WandoraOptionPane;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
/**
* Makes players of one role of association instances to players
* of another role in the association.
*
* @author olli
*/
public class MakeInstancesWithAssociations extends AbstractWandoraTool {
private static final long serialVersionUID = 1L;
/** Creates a new instance of MakeInstancesWithAssociations */
public MakeInstancesWithAssociations() {
this(new AssociationContext());
}
public MakeInstancesWithAssociations(Context preferredContext) {
setContext(preferredContext);
}
@Override
public String getName() {
return "Make instances with associations";
}
@Override
public String getDescription() {
return "Makes players of one role of association instances to players of another role in the association.";
}
@Override
public void execute(Wandora wandora, Context context) {
Iterator associations=null;
if(context instanceof AssociationContext) {
associations = context.getContextObjects();
}
else return;
Topic classRole=null;
Topic instanceRole=null;
try{
while(associations.hasNext()){
Association a=(Association)associations.next();
if(classRole==null){
Object[] roles=a.getRoles().toArray();
classRole=(Topic)WandoraOptionPane.showOptionDialog(wandora,"Select role topic for classes","Select topic",WandoraOptionPane.YES_NO_OPTION,roles,roles[0]);
//classRole=admin.showTopicFinder("Select role of class topic");
if(classRole==null) return;
}
if(instanceRole==null){
Object[] roles=a.getRoles().toArray();
instanceRole=(Topic)WandoraOptionPane.showOptionDialog(wandora,"Select role topic for instances","Select topic",WandoraOptionPane.YES_NO_OPTION,roles,roles[0]);
//instanceRole=admin.showTopicFinder("Select role of instance topic");
if(instanceRole==null) return;
}
Topic c=a.getPlayer(classRole);
Topic i=a.getPlayer(instanceRole);
if(c!=null && i!=null){
i.addType(c);
}
}
}
catch(Exception e){
log(e);
}
}
}
| 3,708 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
DeleteTopicsWithoutInstances.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/DeleteTopicsWithoutInstances.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/>.
*
*
*
* DeleteTopicsWithoutInstances.java
*
* Created on 12.6.2006, 17:50
*
*/
package org.wandora.application.tools;
import java.util.Collection;
import org.wandora.application.WandoraTool;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author akivela
*/
public class DeleteTopicsWithoutInstances extends DeleteTopics implements WandoraTool {
private static final long serialVersionUID = 1L;
@Override
public String getName() {
return "Delete topics without instances";
}
@Override
public String getDescription() {
return "Delete context topics without instances.";
}
@Override
public boolean shouldDelete(Topic topic) throws TopicMapException {
try {
if(topic != null && topic.isRemoved()) {
TopicMap tm = topic.getTopicMap();
Collection<Topic> types = tm.getTopicsOfType(topic);
if(types == null || types.isEmpty()) {
if(confirm) {
return confirmDelete(topic);
}
else {
return true;
}
}
}
}
catch(Exception e) {
log(e);
}
return false;
}
}
| 2,173 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
DeleteTopicsWithoutAssociations.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/DeleteTopicsWithoutAssociations.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/>.
*
*
*
* DeleteTopicsWithoutAssociations.java
*
* Created on 9. huhtikuuta 2006, 21:42
*
*/
package org.wandora.application.tools;
import org.wandora.application.WandoraTool;
import org.wandora.topicmap.Topic;
/**
*
* @author akivela
*/
public class DeleteTopicsWithoutAssociations extends DeleteTopics implements WandoraTool {
private static final long serialVersionUID = 1L;
public DeleteTopicsWithoutAssociations() {
}
@Override
public String getName() {
return "Delete topic(s) without associations";
}
@Override
public String getDescription() {
return "Delete context topics without associations.";
}
@Override
public boolean shouldDelete(Topic topic) {
try {
if(topic != null && !topic.isRemoved()) {
if(topic.getAssociations().isEmpty()) {
if(confirm) {
return confirmDelete(topic);
}
else {
return true;
}
}
}
}
catch(Exception e) {
log(e);
}
return false;
}
}
| 1,993 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
ExitWandora.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/ExitWandora.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/>.
*
*
*
* ExitWandora.java
*
* Created on September 21, 2004, 4:50 PM
*/
package org.wandora.application.tools;
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;
/**
* Class implements a Wandora tool used to exit the application.
*
* @author akivela
*/
public class ExitWandora extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
/** Creates a new instance of ExitWandora */
public ExitWandora() {
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/exit.png");
}
@Override
public String getName() {
return "Exit Wandora";
}
@Override
public String getDescription() {
return "Exit Wandora application.";
}
@Override
public void execute(Wandora wandora, Context context) {
wandora.tryExit();
}
@Override
public boolean runInOwnThread() {
return false;
}
@Override
public boolean requiresRefresh() {
return false;
}
}
| 2,004 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SplitToSuperclassesWithBasename.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/SplitToSuperclassesWithBasename.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/>.
*
*
*
* SplitToSuperclassesWithBasename.java
*
* Created on 2008-09-19, 16:41
*
*/
package org.wandora.application.tools;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
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.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.XTMPSI;
/**
* WandoraTool splitting a topic with a regular expression applied to topic's base name.
* As a result, topic map contains one topic for each identified base name part.
* To prevent immediate merge subject identifiers and subject locators are
* modified a bit. Topics created out of base name parts are associated with
* ascending/descending sub-superclass relation. This tool can be used to expose a sub-superclass
* relation expressed implicitly with a base name.
*
* @author akivela
*/
public class SplitToSuperclassesWithBasename extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
public boolean descending = false;
public boolean duplicateAssociations = false;
public boolean copyInstances = false;
public boolean copyClasses = false;
public boolean askName=false;
public String splitString = "";
private int topicCounter = 0;
private int splitCounter = 0;
public SplitToSuperclassesWithBasename(boolean desc) {
this.descending = desc;
}
public SplitToSuperclassesWithBasename() {
}
public SplitToSuperclassesWithBasename(Context preferredContext, boolean desc) {
this.descending = desc;
setContext(preferredContext);
}
public SplitToSuperclassesWithBasename(Context preferredContext) {
setContext(preferredContext);
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/topic_split.png");
}
@Override
public String getName() {
return "Split topic to "+(descending ? "descending" : "ascending")+" superclasses with base name";
}
@Override
public String getDescription() {
return "Tool splits topics to "+(descending ? "descending" : "ascending")+" superclass chains with base name.";
}
@Override
public void execute(Wandora wandora, Context context) {
Iterator topics = getContext().getContextObjects();
if(topics == null || !topics.hasNext()) return;
splitString = WandoraOptionPane.showInputDialog(
wandora,
"Enter regular expression string used to split base name:",
splitString);
if(splitString == null || splitString.length() == 0) return;
TopicMap tm = wandora.getTopicMap();
Topic topic = null;
topicCounter = 0;
splitCounter = 0;
setDefaultLogger();
while(topics.hasNext() && !forceStop()) {
try {
topic = (Topic) topics.next();
if(topic != null) {
if(!topic.isRemoved()) {
Topic ltopic = tm.getTopic(topic.getOneSubjectIdentifier());
splitTopic(ltopic, splitString, tm, wandora);
}
}
} catch(Exception e) {
log(e);
}
}
if(topicCounter == 0) log("No topics to split.");
else if(topicCounter == 1) log("One topic splitted.");
else log("Total "+topicCounter+" topics splitted.");
if(splitCounter == 0) log("Created no splitted topics.");
else if(splitCounter == 1) log("Created one splitted topic.");
else log("Created total "+splitCounter+" splitted topics.");
setState(WAIT);
}
public void splitTopic(Topic original, String splitString, TopicMap topicMap, Wandora admin) throws TopicMapException {
if(original == null) return;
if(original.getBaseName() == null) return;
String[] splitParts = original.getBaseName().split(splitString);
if(splitParts.length < 2) {
log("No split parts for topic '"+ getTopicName(original) +"'!");
return;
}
Topic previousSplit = null;
Topic split = null;
String splitBasename = null;
for(int i=0; i<splitParts.length-1; i++) {
splitBasename = splitParts[i];
if(splitBasename == null || splitBasename.length() == 0) {
log("Invalid zero length split part for topic '"+ getTopicName(original) +"'!");
continue;
}
// --- copy topic and associations ---
TopicMap splitMap = new org.wandora.topicmap.memory.TopicMapImpl();
splitCounter++;
split = splitMap.copyTopicIn(original, false);
if(duplicateAssociations) {
Collection<Association> assocs = original.getAssociations();
Association a;
for(Iterator<Association> iter = assocs.iterator(); iter.hasNext();) {
a = (Association) iter.next();
splitMap.copyAssociationIn(a);
}
}
// --- resolve new subject base name ---
String newBaseName = splitBasename;
if(askName){
while(true){
String input=WandoraOptionPane.showInputDialog(admin,"Enter new base name for the topic", newBaseName);
if(input==null) return;
newBaseName=input;
if(topicMap.getTopicWithBaseName(input)!=null){
int a=WandoraOptionPane.showConfirmDialog(admin,"Topic with base name '"+input+"' already exists and will be merged with new topic. Do you want to continue?");
if(a==WandoraOptionPane.CANCEL_OPTION) return;
else if(a==WandoraOptionPane.YES_OPTION) break;
}
else break;
}
}
split.setBaseName(newBaseName);
// --- resolve new subject locator ---
if(original.getSubjectLocator() != null) {
int c = 2;
Locator newSubjectLocator = new Locator(original.getSubjectLocator().toExternalForm() + "_split");
while(topicMap.getTopicBySubjectLocator(newSubjectLocator) != null && c<10000) {
newSubjectLocator = new Locator(original.getSubjectLocator().toExternalForm() + "_split" + c);
c++;
}
split.setSubjectLocator(newSubjectLocator);
}
// --- resolve new subject identifiers ---
Collection<Locator> sis = split.getSubjectIdentifiers();
List<Locator> siv = new ArrayList<>();
for(Iterator<Locator> iter = sis.iterator(); iter.hasNext(); ) {
siv.add(iter.next());
}
Locator lo = null;
Locator l = null;
for(int j=0; j<siv.size(); j++) {
lo = (Locator) siv.get(j);
l = (Locator) new Locator(lo.toExternalForm() + "_split");
int c = 2;
while((topicMap.getTopic(l) != null || splitMap.getTopic(l) != null) && c<10000) {
l = (Locator) new Locator(lo.toExternalForm() + "_split" + c);
c++;
}
split.addSubjectIdentifier(l);
split.removeSubjectIdentifier(lo);
}
//log("Merging splitted topic to original map...");
topicMap.mergeIn(splitMap);
split = topicMap.getTopicWithBaseName(newBaseName);
// --- attach instances ---
if(split != null && copyInstances) {
Collection<Topic> col = topicMap.getTopicsOfType(original);
Iterator<Topic> iter=col.iterator();
Topic t = null;
while(iter.hasNext()) {
t=(Topic)iter.next();
if(t.isOfType(original)) {
t.addType(split);
}
}
}
if(previousSplit != null) {
if(descending)
makeSubclassOf(previousSplit.getTopicMap(), split, previousSplit);
else
makeSubclassOf(split.getTopicMap(), previousSplit, split);
}
previousSplit = split;
}
if(descending)
makeSubclassOf(previousSplit.getTopicMap(), original, previousSplit);
else
makeSubclassOf(original.getTopicMap(), previousSplit, original);
// Change base name of the original topic....
original.setBaseName(splitParts[splitParts.length-1]);
topicCounter++;
}
// -------------------------------------------------------------------------
protected void makeSubclassOf(TopicMap tm, Topic t, Topic superclass) throws TopicMapException {
Topic supersubClassTopic = getOrCreateTopic(tm, XTMPSI.SUPERCLASS_SUBCLASS, null);
Topic subclassTopic = getOrCreateTopic(tm, XTMPSI.SUBCLASS, null);
Topic superclassTopic = getOrCreateTopic(tm, XTMPSI.SUPERCLASS, null);
Association ta = tm.createAssociation(supersubClassTopic);
ta.addPlayer(t, subclassTopic);
ta.addPlayer(superclass, superclassTopic);
}
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);
}
else {
t.addSubjectIdentifier(tm.makeSubjectIndicatorAsLocator());
}
}
return t;
}
}
}
| 11,569 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
DeleteTopicsWithBasenameRegex.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/DeleteTopicsWithBasenameRegex.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/>.
*
*
*
* DeleteTopicsWithBasenameRegex.java
*
* Created on 18.7.2006, 12:56
*
*/
package org.wandora.application.tools;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.RegularExpressionEditor;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author akivela
*/
public class DeleteTopicsWithBasenameRegex extends DeleteTopics implements WandoraTool {
private static final long serialVersionUID = 1L;
RegularExpressionEditor editor = null;
/** Creates a new instance of DeleteTopicsWithBasenameRegex */
public DeleteTopicsWithBasenameRegex() {
}
public DeleteTopicsWithBasenameRegex(Context preferredContext) {
setContext(preferredContext);
}
@Override
public void execute(Wandora admin, Context context) throws TopicMapException {
editor = RegularExpressionEditor.getMatchExpressionEditor(admin);
editor.approve = false;
editor.setVisible(true);
if(editor.approve == true) {
super.execute(admin, context);
}
}
@Override
public String getName() {
return "Delete topics with base name regex";
}
@Override
public String getDescription() {
return "Delete topics with base name matching to given regular expression.";
}
@Override
public boolean shouldDelete(Topic topic) throws TopicMapException {
try {
if(topic != null && !topic.isRemoved()) {
if(topic.getBaseName() != null) {
if(editor.matches(topic.getBaseName())) {
return true;
}
}
}
}
catch(Exception e) {
log(e);
}
return false;
}
}
| 2,737 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
DeleteFromTopics.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/DeleteFromTopics.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/>.
*
*
* DeleteFromTopics.java
*
* Created on 6. tammikuuta 2005, 12:47
*/
package org.wandora.application.tools;
import java.util.ArrayList;
import java.util.Collection;
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.gui.WandoraOptionPane;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author akivela
*/
public class DeleteFromTopics extends AbstractWandoraTool implements WandoraTool, Runnable {
private static final long serialVersionUID = 1L;
public static final int LOOSE_INSTANCES = 100;
public static final int LOOSE_INSTANCES_IN_CONTEXT = 101;
public static final int DELETE_INSTANCE_TOPICS = 110;
public static final int LOOSE_CLASSES = 120;
public static final int LOOSE_SINGLE_CLASS = 130;
public static final int LOOSE_CLASSES_OF_CURRENT = 140;
public static final int DELETE_TYPED_TEXTDATA = 21;
public static final int DELETE_TEXTDATAS = 22;
public static final int DELETE_TYPED_ASSOCIATIONS_OF_CURRENT = 3800;
//public static final int DELETE_TYPED_ASSOCIATIONS = 320;
//public static final int DELETE_ASSOCIATIONS_OF_TYPE = 350;
public static final int DELETE_ASSOCIATED_TOPICS = 380;
//public static final int DELETE_SLS = 41;
//public static final int DELETE_SIS_WITH_REGEX = 800;
public int whatToDelete = 0;
TopicMap topicMap = null;
Topic topicOpen = null;
boolean requiresRefresh = false;
public DeleteFromTopics() {
whatToDelete = 0;
}
public DeleteFromTopics(int orders) {
whatToDelete = orders;
}
public DeleteFromTopics(Context preferredContext, int orders) {
setContext(preferredContext);
whatToDelete = orders;
}
@Override
public String getName() {
return "Delete from topics";
}
@Override
public String getDescription() {
return "Delete selected elements such as instances in selected topics.";
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
Topic topic = null;
Iterator topics = context.getContextObjects();
// Delete from topics.
switch(whatToDelete) {
// REFACTORED TO DeleteSIsWithRegex
/*
case DELETE_SIS_WITH_REGEX: {
try {
RegularExpressionEditor editor;
editor = RegularExpressionEditor.getMatchExpressionEditor(admin);
editor.approve = false;
editor.setVisible(true);
if(editor.approve == true) {
setDefaultLogger();
Topic t = null;
int c = 0;
int tc = 0;
while(topics.hasNext() && !forceStop()) {
t = (Topic) topics.next();
if(t != null && !t.isRemoved()) {
try {
tc++;
hlog("Inspecting topic '" + getTopicName(t) + "'.");
Collection sis = t.getSubjectIdentifiers();
int s = sis.size();
if(s > 1) {
ArrayList sisToDelete = new ArrayList();
Iterator sii = sis.iterator();
Locator l = null;
while(sii.hasNext() && s > 1) {
l = (Locator) sii.next();
String ls = l.toExternalForm();
if(editor.matches(ls)) {
sisToDelete.add(l);
s--;
c++;
hlog("Removing SI '"+ l.toExternalForm() +"'.");
}
}
sii = sisToDelete.iterator();
while(sii.hasNext()) {
t.removeSubjectIdentifier((Locator) sii.next());
}
}
}
catch(Exception e) {
log(e);
}
}
}
log("Inspected total "+tc+" topics.");
log("Deleted total "+c+" subject identifiers.");
setState(WAIT);
}
}
catch(Exception e) {
log(e);
}
break;
}
*/
//
case LOOSE_INSTANCES: {
int c = 0;
try {
c++;
topic = (Topic) topics.next();
if(WandoraOptionPane.showConfirmDialog(wandora,"Are you sure you want to delete all instances of '" + getTopicName(topic) + "'?","Confirm instance delete", WandoraOptionPane.YES_NO_OPTION)==WandoraOptionPane.YES_OPTION) {
Collection<Topic> instances = topic.getTopicMap().getTopicsOfType(topic);
Topic instance = null;
Iterator<Topic> it=instances.iterator();
while(it.hasNext() && !forceStop()) {
try {
instance = (Topic) it.next();
if( !instance.isRemoved() ) {
instance.removeType(topic);
requiresRefresh = true;
}
}
catch(Exception e) {
log(e);
}
}
}
}
catch (Exception e) {
log(e);
}
break;
}
case LOOSE_INSTANCES_IN_CONTEXT: {
Topic openTopic = wandora.getOpenTopic();
if(openTopic != null) {
if(WandoraOptionPane.showConfirmDialog(wandora,"Are you sure you want to delete selected instances of '" + getTopicName(openTopic) + "'?","Confirm instance delete", WandoraOptionPane.YES_NO_OPTION)==WandoraOptionPane.YES_OPTION){
int c = 0;
setDefaultLogger();
Topic instance = null;
while(topics.hasNext() && !forceStop()) {
try {
c++;
instance = (Topic) topics.next();
if( !instance.isRemoved() ) {
log("Deleting instance '"+ getTopicName(instance) +"' from topic '" + getTopicName(openTopic) + "'");
instance.removeType(openTopic);
requiresRefresh = true;
}
}
catch (Exception e) {
log("Exception occurred while deleting instances from topic", e);
}
}
setState(WAIT);
}
}
break;
}
case DELETE_INSTANCE_TOPICS: {
if(WandoraOptionPane.showConfirmDialog(wandora,"Are you sure you want to delete all instance topics?","Confirm delete", WandoraOptionPane.YES_NO_OPTION)==WandoraOptionPane.YES_OPTION){
int c = 0;
int d = 0;
TopicMap tm = wandora.getTopicMap();
setDefaultLogger();
while(topics.hasNext() && !forceStop()) {
Topic typeTopic = (Topic) topics.next();
Iterator<Topic> iter=new ArrayList(tm.getTopicsOfType(typeTopic)).iterator();
Topic t = null;
List<Topic> deleteThese = new ArrayList<>();
while(iter.hasNext() && !forceStop()) {
t=(Topic)iter.next();
if(!t.isRemoved() && t.isOfType(typeTopic)) {
deleteThese.add(t);
c++;
hlog("Preparing instance topic " + getTopicName(t) + "");
}
}
int s = deleteThese.size();
for(int i=0; i<s && !forceStop(); i++) {
try {
topic = (Topic) deleteThese.get(i);
if(!topic.isRemoved() && topic.isDeleteAllowed()) {
d++;
log("Deleting instance topic '" + getTopicName(topic) + "'");
topic.remove();
requiresRefresh = true;
}
}
catch (Exception e) {
log(e);
}
}
}
setState(WAIT);
}
break;
}
case LOOSE_CLASSES_OF_CURRENT: {
Topic currentTopic = wandora.getOpenTopic();
Topic typeTopic = null;
if(currentTopic != null) {
String message = "Delete selected classes from topic "+getTopicName(currentTopic)+"?";
int r = WandoraOptionPane.showConfirmDialog(wandora, message, "Confirm delete", WandoraOptionPane.YES_NO_OPTION);
if(r == WandoraOptionPane.YES_OPTION) {
int c = 0;
setDefaultLogger();
while(topics.hasNext() && !forceStop()) {
try {
c++;
typeTopic = (Topic) topics.next();
if(typeTopic != null && !typeTopic.isRemoved()) {
currentTopic.removeType(typeTopic);
log("Deleting class '" + getTopicName(typeTopic) + "' from topic '" + getTopicName(currentTopic) + "'");
requiresRefresh = true;
}
}
catch(Exception e) {
log(e);
}
}
setState(WAIT);
}
}
break;
}
case LOOSE_SINGLE_CLASS: {
/* BaseNamePrompt prompt=new BaseNamePrompt(admin.getManager(), admin, true);
prompt.setTitle("Select class to be removed from topics...");
prompt.setVisible(true);
Topic t=prompt.getTopic();*/
Topic t=wandora.showTopicFinder("Select class to be removed from topics...");
if (t == null) return;
int c = 0;
setDefaultLogger();
while(topics.hasNext() && !forceStop()) {
try {
c++;
topic = (Topic) topics.next();
if(!topic.isRemoved()) {
log("Deleting class '" + getTopicName(t) + "' from topic '" + getTopicName(topic) + "'");
topic.removeType(t);
requiresRefresh = true;
}
}
catch (Exception e) {
log("Exception occurred while deleting class", e);
try { Thread.sleep(1000); }
catch (Exception timeout) {}
}
}
setState(WAIT);
break;
}
case LOOSE_CLASSES: {
Topic classTopic = null;
int c = 0;
setDefaultLogger();
while(topics.hasNext() && !forceStop()) {
try {
c++;
topic = (Topic) topics.next();
Collection<Topic> classTopics = topic.getTypes();
if(classTopics != null) {
Iterator<Topic> classIterator = classTopics.iterator();
while(classIterator.hasNext()) {
classTopic = classIterator.next();
if(classTopic != null && !classTopic.isRemoved()) {
log("Deleting class '" + getTopicName(classTopic) + "' from topic '" + getTopicName(topic) + "'");
topic.removeType(classTopic);
requiresRefresh = true;
}
}
}
}
catch (Exception e) {
log("Exception occurred while deleting classes from topic", e);
try { Thread.sleep(1000); }
catch (Exception timeout) {}
}
}
setState(WAIT);
break;
}
case DELETE_TYPED_TEXTDATA: {
/* BaseNamePrompt prompt=new BaseNamePrompt(admin.getManager(), admin, true);
prompt.setTitle("Select occurrence type to be removed from topics...");
prompt.setVisible(true);
Topic occurrenceType=prompt.getTopic();*/
Topic occurrenceType=wandora.showTopicFinder("Select occurrence type to be removed from topics...");
if(occurrenceType == null) return;
int c = 0;
setDefaultLogger();
while(topics.hasNext() && !forceStop()) {
try {
c++;
topic = (Topic) topics.next();
if(topic != null && !topic.isRemoved()) {
log("Deleting occurrence of type '" + getTopicName(occurrenceType) + "' from topic '" + getTopicName(topic) + "'");
topic.removeData(occurrenceType);
requiresRefresh = true;
}
}
catch (Exception e) {
log("Exception occurred while deleting occurrence", e);
try { Thread.sleep(1000); }
catch (Exception timeout) {}
}
}
setState(WAIT);
break;
}
case DELETE_TEXTDATAS: {
if(WandoraOptionPane.showConfirmDialog(wandora,"Are you sure you want to delete all occurrences?","Confirm delete", WandoraOptionPane.YES_NO_OPTION)==WandoraOptionPane.YES_OPTION){
setDefaultLogger();
int c = 0;
while(topics.hasNext() && !forceStop()) {
try {
c++;
topic = (Topic) topics.next();
hlog("Inspecting topic '"+getTopicName(topic)+"'.");
Collection<Topic> types = topic.getDataTypes();
for(Iterator<Topic> i2 = types.iterator(); i2.hasNext(); ) {
Topic type = (Topic) i2.next();
if(type != null && !type.isRemoved()) {
log("Deleting occurrences from topic '"+getTopicName(topic)+"'");
topic.removeData(type);
requiresRefresh = true;
}
}
}
catch (Exception e) {
log("Exception occurred while deleting occurrences", e);
try { Thread.sleep(1000); }
catch (Exception timeout) {}
}
}
setState(WAIT);
}
break;
}
/* REFACTORED TO tools.associations.DeleteAssociationsInTopic
*
case DELETE_ASSOCIATIONS: {
if(WandoraOptionPane.showConfirmDialog(wandora,"Are you sure you want to delete all associations?","Confirm delete", WandoraOptionPane.YES_NO_OPTION)==WandoraOptionPane.YES_OPTION){
setDefaultLogger();
int c = 0;
while(topics.hasNext() && !forceStop()) {
try {
c++;
topic = (Topic) topics.next();
hlog("Deleting associations from topic\n" + getTopicName(topic) + "\n" + c + " done...");
Collection associations = topic.getAssociations();
for(Iterator i2 = associations.iterator(); i2.hasNext(); ) {
Association association = (Association) i2.next();
if(association != null) {
association.remove();
requiresRefresh = true;
}
}
}
catch (Exception e) {
log("Exception occurred while deleting associations", e);
try { Thread.currentThread().sleep(1000); }
catch (Exception timeout) {}
}
}
setState(WAIT);
}
break;
}
*/
// REFACTORED TO tools.associations.DeleteAssociationsInTopicWithType
/*
case DELETE_TYPED_ASSOCIATIONS: {
/* BaseNamePrompt prompt=new BaseNamePrompt(admin.getManager(), admin, true);
prompt.setTitle("Select type of association be removed from topics...");
prompt.setVisible(true);
Topic associationType=prompt.getTopic();*/
/*
Topic associationType=admin.showTopicFinder("Select type of association to be removed from topics...");
if(associationType == null) return;
String tname = associationType.getBaseName();
setDefaultLogger();
int c = 0;
while(topics.hasNext() && !forceStop()) {
try {
c++;
topic = (Topic) topics.next();
hlog("Deleting associations of type '" + tname + "' from topic\n" + getTopicName(topic) + "\n" + c + " done...");
Collection associations = topic.getAssociations(associationType);
for(Iterator i2 = associations.iterator(); i2.hasNext(); ) {
Association association = (Association) i2.next();
if(association != null) {
association.remove();
requiresRefresh = true;
}
}
}
catch (Exception e) {
log("Exception occurred while deleting associations", e);
try { Thread.currentThread().sleep(1000); }
catch (Exception timeout) {}
}
}
setState(WAIT);
break;
}
*/
case DELETE_TYPED_ASSOCIATIONS_OF_CURRENT: {
setDefaultLogger();
Topic associationType = null;
Topic currentTopic = null;
String tname = null;
try {
associationType=(Topic) context.getContextObjects().next();
tname = getTopicName(associationType);
currentTopic = wandora.getOpenTopic();
log("Deleting associations of type '" + tname + "' from topic '" + getTopicName(currentTopic) +"'");
Collection<Association> associations = currentTopic.getAssociations(associationType);
for(Iterator<Association> i2 = associations.iterator(); i2.hasNext() && !forceStop(); ) {
Association association = (Association) i2.next();
if(association != null && !association.isRemoved()) {
association.remove();
requiresRefresh = true;
}
}
}
catch (Exception e) {
log("Exception '" + e.toString() + "'\n occurred while deleting associations", e);
try { Thread.sleep(1000); }
catch (Exception timeout) {}
}
setState(WAIT);
break;
}
case DELETE_ASSOCIATED_TOPICS: {
if(WandoraOptionPane.showConfirmDialog(wandora,"Are you sure you want to delete associated topics?","Confirm delete", WandoraOptionPane.YES_NO_OPTION)==WandoraOptionPane.YES_OPTION){
setDefaultLogger();
while(topics.hasNext() && !forceStop()) {
topic = (Topic) topics.next();
Collection<Association> assocs = topic.getAssociations();
Association a;
Topic player;
ArrayList<Association> assocv = new ArrayList<>();
ArrayList<Topic> topicv = new ArrayList<>();
for(Iterator<Association> iter = assocs.iterator(); iter.hasNext();) {
a = (Association) iter.next();
Collection<Topic> roles = a.getRoles();
for(Iterator<Topic> roleiter = roles.iterator(); roleiter.hasNext();) {
player = (Topic) a.getPlayer((Topic) roleiter.next());
if (!player.equals(topic)) {
hlog("Preparing topic '" + getTopicName(player) + "'");
topicv.add(player);
}
}
assocv.add(a);
}
int c = assocv.size();
for(int i=0; i<c; i++) {
a = (Association) assocv.get(i);
log("Deleting association of found topic! "+ (c-i) + " associations to delete.");
a.remove();
requiresRefresh = true;
}
c = topicv.size();
for(int i=0; i<c; i++) {
try {
player = (Topic) topicv.get(i);
if(!player.isRemoved() && player.isDeleteAllowed()) {
log("Deleting topic '" + getTopicName(player) + "'. " + (c-i) + " topics to delete.");
player.remove();
requiresRefresh = true;
}
}
catch(Exception e) {
log(e);
}
}
}
setState(WAIT);
}
}
// REFACTORED TO SubjectLocatorRemover
/*
case DELETE_SLS: {
if(WandoraOptionPane.showConfirmDialog(admin,"Are you sure you want to delete subject locators\nfrom all instance topics?","Confirm delete", WandoraOptionPane.YES_NO_OPTION)==WandoraOptionPane.YES_OPTION){
int c = 0;
setDefaultLogger();
while(topics.hasNext() && !forceStop()) {
try {
c++;
topic = (Topic) topics.next();
log("Deleting subject locators from " + getTopicName(topic) + ", " + c + " done...");
topic.setSubjectLocator(null);
requiresRefresh = true;
}
catch (Exception e) {
log(e);
}
}
setState(WAIT);
}
else {
return;
}
break;
}
*/
default: {
log("Delete from all instances cathed illegal action type (" + whatToDelete + ").");
}
}
}
/*
public Topic[] makeTopicArray(Collection collection) {
Topic[] topics = new Topic[0];
if(collection != null) {
topics = new Topic[collection.size()];
int i = 0;
for(Iterator it = collection.iterator(); it.hasNext(); ) {
try {
topics[i] = (Topic) it.next();
}
catch(Exception e) {
log(e);
}
}
}
return topics;
}
*/
@Override
public boolean requiresRefresh() {
return requiresRefresh;
}
}
| 28,119 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
ApplyPatchTool.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/ApplyPatchTool.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;
import static org.wandora.topicmap.diff.TopicMapDiff.openFile;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import javax.swing.Icon;
import javax.swing.JDialog;
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.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.topicmap.diff.PatchDiffParser;
import org.wandora.topicmap.diff.TopicMapDiff;
import org.wandora.topicmap.diff.TopicMapDiff.DiffEntry;
import org.wandora.topicmap.diff.TopicMapDiff.PatchException;
import org.wandora.topicmap.diff.TopicMapDiff.PatchExceptionHandler;
import org.wandora.topicmap.layered.Layer;
import org.wandora.utils.swing.GuiTools;
/**
* Applies a topic map patch to current topic map. A patch is a special file
* that captures changes in topic map.
*
* @author olli
*/
public class ApplyPatchTool extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/patch_topicmap.png");
}
@Override
public String getName() {
return "Topic map patcher";
}
@Override
public String getDescription() {
return "Applies a topic map patch";
}
@Override
public void execute(final Wandora wandora, Context context) throws TopicMapException {
JDialog dialog=new JDialog(wandora,"Apply topic map patch",true);
ApplyPatchToolConfigPanel configPanel=new ApplyPatchToolConfigPanel(wandora,dialog);
dialog.getContentPane().add(configPanel);
dialog.setSize(500, 280);
GuiTools.centerWindow(dialog, wandora);
dialog.setVisible(true);
if(configPanel.wasCancelled()) return;
setDefaultLogger();
String filename=null;
try{
TopicMap tm=null;
int mode=configPanel.getMapMode();
if(mode==ApplyPatchToolConfigPanel.MODE_FILE){
filename = configPanel.getMapValue();
if(filename != null && !"".equals(filename)) {
log("Reading topic map");
tm=openFile(filename);
}
else {
log("Filename not specified for topic map 1!");
log("Cancelling patching.");
setState(WAIT);
return;
}
}
else if(mode==ApplyPatchToolConfigPanel.MODE_LAYER){
Layer l=wandora.getTopicMap().getLayer(configPanel.getMapValue());
if(l==null) {
log("Layer not found");
log("Cancelling patching.");
setState(WAIT);
return;
}
tm=l.getTopicMap();
}
else if(mode==ApplyPatchToolConfigPanel.MODE_PROJECT){
tm=wandora.getTopicMap();
}
filename=configPanel.getPatchFile();
Reader reader=new InputStreamReader(new FileInputStream(filename),"UTF-8");
ArrayList<DiffEntry> diff=null;
try{
PatchDiffParser parser=new PatchDiffParser(reader);
log("Reading patch");
diff=parser.parse();
}
finally{
reader.close();
}
TopicMapDiff tmDiff=new TopicMapDiff();
if(configPanel.getPatchReverse()) {
log("Reversing patch");
diff=tmDiff.makeInverse(diff);
}
log("Applying patch");
final ArrayList<PatchException> pes=new ArrayList<PatchException>();
final Boolean[] yesToAll=new Boolean[]{false};
final Boolean[] aborted=new Boolean[]{false};
tmDiff.applyDiff(diff, tm,new PatchExceptionHandler(){
public boolean handleException(PatchException e){
pes.add(e);
if(yesToAll[0]) return false;
int c=WandoraOptionPane.showConfirmDialog(
wandora,
"Exception applying patch, do you want to continue?<br>"+
e.level+": "+e.message, "Exception applying patch",
WandoraOptionPane.YES_TO_ALL_NO_OPTION);
if(c==WandoraOptionPane.YES_TO_ALL_OPTION){
yesToAll[0]=true;
return false;
}
else if(c==WandoraOptionPane.YES_OPTION) return true;
else {
aborted[0]=true;
return true;
}
}
});
if(pes.size()>0){
log("Encountered following problems while patching");
for(PatchException pe : pes){
log(pe.level+": "+pe.message);
}
}
if(aborted[0]) log("Patching aborted");
if(mode==ApplyPatchToolConfigPanel.MODE_FILE){
filename = configPanel.getMapValue();
int ind=filename.lastIndexOf(".");
if(ind==-1) filename+="_patched";
else filename=filename.substring(0,ind)+"_patched"+filename.substring(ind);
File f=new File(filename);
if(f.exists()){
int r=WandoraOptionPane.showConfirmDialog(wandora, "File "+filename+" already exists, overwrite?");
if(r!=WandoraOptionPane.YES_OPTION) {
log("Patching aborted");
setState(WAIT);
return;
}
}
log("Writing topic map to "+filename);
tm.exportXTM(filename,getCurrentLogger());
log("Patched topic map written to "+filename);
}
else {
log("Topic map patched");
}
} catch(FileNotFoundException fnfe) {
log("File not found exception occurred while opening file '"+filename+"'.");
} catch(IOException ioe){
log(ioe);
} catch(java.text.ParseException pe){
log("Parse error in patch file at line "+pe.getErrorOffset()+"<br>"+pe.getMessage());
}
setState(WAIT);
}
}
| 7,741 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
DuplicateTopics.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/DuplicateTopics.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/>.
*
*
*
* DuplicateTopics.java
*
* Created on September 22, 2004, 1:20 PM
*/
package org.wandora.application.tools;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
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.topicmap.Association;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
/**
* Duplicate context topics. Duplicated topic is modified in order to prevent
* instant merge. Topic's base name is attached a string '(copy n)' and
* subject identifiers a string '_copyn' where n is first unused number.
*
* @author akivela
*/
public class DuplicateTopics extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
public boolean duplicateAssociations = true;
public boolean copyInstances = true;
public boolean askName=true;
public DuplicateTopics() {
}
public DuplicateTopics(Context preferredContext) {
setContext(preferredContext);
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/topic_duplicate.png");
}
@Override
public String getName() {
return "Duplicate Topics";
}
@Override
public String getDescription() {
return "Duplicate context topics. "+
"Duplicated topic is modified in order to prevent instant merge. "+
"Duplicated topic base name is attached string '(copy n)' and SIs string '_copyn' "+
"where n is first unused number.";
}
@Override
public void execute(Wandora w, Context context) {
Iterator topics = getContext().getContextObjects();
if(topics == null || !topics.hasNext()) return;
TopicMap tm = w.getTopicMap();
Topic topic = null;
while(topics.hasNext() && !forceStop()) {
try {
topic = (Topic) topics.next();
if(topic != null && !topic.isRemoved()) {
Topic ltopic = tm.getTopic(topic.getOneSubjectIdentifier());
duplicateTopic(ltopic, tm, w);
}
} catch(Exception e) {
log(e);
}
}
}
public Topic duplicateTopic(Topic original, TopicMap tm, Wandora w) throws TopicMapException {
// --- copy topic and associations
TopicMap copyMap = new org.wandora.topicmap.memory.TopicMapImpl();
Topic copy = copyMap.copyTopicIn(original, false);
if(duplicateAssociations) {
Collection<Association> assocs = original.getAssociations();
Association a;
for(Iterator<Association> iter = assocs.iterator(); iter.hasNext();) {
a = (Association) iter.next();
copyMap.copyAssociationIn(a);
}
}
// --- resolve new subject base name
if(original.getBaseName() != null) {
String newBaseName = original.getBaseName() + " (copy)";
int c = 2;
while(tm.getTopicWithBaseName(newBaseName) != null && c<10000) {
newBaseName = original.getBaseName() + " (copy " + c + ")";
c++;
}
if(askName){
while(true){
String input=WandoraOptionPane.showInputDialog(w, "Enter new base name for the topic", newBaseName);
if(input==null) return null;
newBaseName=input;
if(tm.getTopicWithBaseName(input)!=null){
int a=WandoraOptionPane.showConfirmDialog(w,"Topic with base name '"+input+"' already exists and will be merged with new topic. Do you want to continue?");
if(a==WandoraOptionPane.CANCEL_OPTION) return null;
else if(a==WandoraOptionPane.YES_OPTION) break;
}
else break;
}
}
copy.setBaseName(newBaseName);
}
// --- resolve new subject locator
if(original.getSubjectLocator() != null) {
int c = 2;
Locator newSubjectLocator = new Locator(original.getSubjectLocator().toExternalForm() + "_copy");
while(tm.getTopicBySubjectLocator(newSubjectLocator) != null && c<10000) {
newSubjectLocator = new Locator(original.getSubjectLocator().toExternalForm() + "_copy" + c);
c++;
}
copy.setSubjectLocator(newSubjectLocator);
}
// --- resolve new subject identifiers
Collection<Locator> sis = copy.getSubjectIdentifiers();
List<Locator> siv = new ArrayList<>();
for(Iterator<Locator> iter = sis.iterator(); iter.hasNext(); ) {
siv.add(iter.next());
}
Locator lo = null;
Locator l = null;
for(int i=0; i<siv.size(); i++) {
lo = (Locator) siv.get(i);
copy.removeSubjectIdentifier(lo);
l = (Locator) new Locator(lo.toExternalForm() + "_copy");
int c = 2;
while(tm.getTopic(l) != null && c<10000) {
l = (Locator) new Locator(lo.toExternalForm() + "_copy" + c);
c++;
}
copy.addSubjectIdentifier(l);
}
//log("Merging duplicated topic to topic map...");
tm.mergeIn(copyMap);
copy = tm.getTopic(l);
// --- attach instances
if(copy != null && copyInstances) {
Collection<Topic> col = tm.getTopicsOfType(original);
Iterator<Topic> iter=col.iterator();
Topic t = null;
while(iter.hasNext()) {
t=(Topic)iter.next();
if(t.isOfType(original)) {
t.addType(copy);
}
}
}
return copy;
}
} | 7,042 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AboutCredits.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/AboutCredits.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/>.
*
*
* AboutApplication.java
*
* Created on September 11, 2004, 2:56 PM
*/
package org.wandora.application.tools;
import java.awt.Dimension;
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.simple.SimpleButton;
import org.wandora.utils.swing.ImagePanel;
import org.wandora.utils.swing.MultiLineLabel;
/**
* Class implements <code>AbstractWandoraTool</code> and opens simple dialog
* panel viewing general information about authors of the Wandora application.
*
* @author akivela
*/
public class AboutCredits extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
private javax.swing.JDialog aboutDialog;
private MultiLineLabel textLabel;
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/info.png");
}
@Override
public String getName() {
return "About Wandora authors";
}
@Override
public String getDescription() {
return "Views credits of Wandora software application.";
}
@Override
public void execute(Wandora wandora, Context context) {
try {
aboutDialog=new javax.swing.JDialog(wandora,"Wandora credits",true);
aboutDialog.getContentPane().setLayout(new java.awt.BorderLayout(20,0));
ImagePanel titleLabel = new ImagePanel("gui/label_about_wandora.png");
aboutDialog.getContentPane().add(titleLabel,java.awt.BorderLayout.NORTH);
String text =
"Copyright (C) 2004-2023 Wandora Team\n"+
" \n"+
"Wandora Team would like to thank Olli Lyytinen, \n" +
"Eero Lehtonen, Elias Tertsunen, Niko Laitinen, \n"+
"Antti Tuppurainen, Pasi Hytönen, Marko Wallgren, \n"+
"Jaakko Lyytinen and Jarno Wallgren for their contribution \n"+
"to the Wandora project.\n"+
" \n"+
"Wandora uses numerous third party libraries made by \n"+
"talented people around the world. Wandora Team would like to\n"+
"express gratitude to all contributing open source projects.\n"+
" \n"+
"For more information see http://wandora.org\n";
textLabel=new MultiLineLabel(text);
textLabel.setVisible(true);
textLabel.setForeground(new java.awt.Color(50,50,50));
textLabel.setBackground(wandora.getBackground());
textLabel.setAlignment(textLabel.CENTER);
textLabel.setMaximumSize(new Dimension(370, 50));
textLabel.setMinimumSize(new Dimension(370, 50));
textLabel.setPreferredSize(new Dimension(370, 50));
aboutDialog.getContentPane().add(textLabel, java.awt.BorderLayout.CENTER);
SimpleButton okButton = new SimpleButton();
okButton.setText("OK");
okButton.setMaximumSize(new Dimension(70, 24));
okButton.setMinimumSize(new Dimension(70, 24));
okButton.setPreferredSize(new Dimension(70, 24));
okButton.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
okButtonActionPerformed(evt);
}
});
javax.swing.JPanel buttonContainer = new javax.swing.JPanel(new java.awt.FlowLayout());
buttonContainer.add(okButton);
aboutDialog.getContentPane().add(buttonContainer, java.awt.BorderLayout.SOUTH);
aboutDialog.setDefaultCloseOperation(javax.swing.JDialog.DISPOSE_ON_CLOSE);
aboutDialog.setResizable(false);
aboutDialog.pack();
if(wandora != null) wandora.centerWindow(aboutDialog);
aboutDialog.setVisible(true);
}
catch (Exception e) {
log(e);
}
}
private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {
aboutDialog.setVisible(false);
}
@Override
public boolean requiresRefresh() {
return false;
}
}
| 5,198 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SplitToInstancesWithBasename.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/SplitToInstancesWithBasename.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/>.
*
*
*
* SplitToInstancesWithBasename.java
*
* Created on 2008-09-19, 16:41
*
*/
package org.wandora.application.tools;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
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.topicmap.Association;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
/**
* WandoraTool splitting a topic with a regular expression applied to topic's base name.
* As a result, topic map contains one topic for each identified base name part.
* To prevent immediate merge subject identifiers and subject locators are
* modified a bit. Topics created out of base name parts are associated with
* ascending/descending instance-class relation. This tool can be used to expose a instance-class
* relation expressed implicitly with a base name.
*
* @author akivela
*/
public class SplitToInstancesWithBasename extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
public boolean descending = false;
public boolean duplicateAssociations = false;
public boolean copyInstances = false;
public boolean copyClasses = false;
public boolean askName=false;
public String splitString = "";
private int topicCounter = 0;
private int splitCounter = 0;
public SplitToInstancesWithBasename(boolean desc) {
this.descending = desc;
}
public SplitToInstancesWithBasename() {
}
public SplitToInstancesWithBasename(Context preferredContext, boolean desc) {
this.descending = desc;
setContext(preferredContext);
}
public SplitToInstancesWithBasename(Context preferredContext) {
setContext(preferredContext);
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/topic_split.png");
}
@Override
public String getName() {
return "Split topic to "+(descending ? "descending" : "ascending")+" instances with base name";
}
@Override
public String getDescription() {
return "Tool splits topics to "+(descending ? "descending" : "ascending")+" instance chains with base name.";
}
@Override
public void execute(Wandora w, Context context) {
Iterator topics = getContext().getContextObjects();
if(topics == null || !topics.hasNext()) return;
splitString = WandoraOptionPane.showInputDialog(w, "Enter regular expression string used to split base name:", splitString);
if(splitString == null || splitString.length() == 0) return;
TopicMap tm = w.getTopicMap();
Topic topic = null;
topicCounter = 0;
splitCounter = 0;
setDefaultLogger();
while(topics.hasNext() && !forceStop()) {
try {
topic = (Topic) topics.next();
if(topic != null) {
if(!topic.isRemoved()) {
Topic ltopic = tm.getTopic(topic.getOneSubjectIdentifier());
splitTopic(ltopic, splitString, tm, w);
}
}
}
catch(Exception e) {
log(e);
}
}
if(topicCounter == 0) log("No topics to split.");
else if(topicCounter == 1) log("One topic splitted.");
else log("Total "+topicCounter+" topics splitted.");
if(splitCounter == 0) log("Created no splitted topics.");
else if(splitCounter == 1) log("Created one splitted topic.");
else log("Created total "+splitCounter+" splitted topics.");
setState(WAIT);
}
public void splitTopic(Topic original, String splitString, TopicMap topicMap, Wandora admin) throws TopicMapException {
if(original == null || original.getBaseName() == null) return;
String[] splitParts = original.getBaseName().split(splitString);
if(splitParts.length < 2) {
log("No split parts for topic '"+ getTopicName(original) +"'!");
return;
}
Topic previousSplit = null;
Topic split = null;
String splitBasename = null;
for(int i=0; i<splitParts.length-1; i++) {
splitBasename = splitParts[i];
if(splitBasename == null || splitBasename.length() == 0) {
log("Invalid zero length split part for topic '"+ getTopicName(original) +"'!");
continue;
}
// --- copy topic and associations ---
TopicMap splitMap = new org.wandora.topicmap.memory.TopicMapImpl();
splitCounter++;
split = splitMap.copyTopicIn(original, false);
if(duplicateAssociations) {
Collection<Association> assocs = original.getAssociations();
Association a;
for(Iterator<Association> iter = assocs.iterator(); iter.hasNext();) {
a = (Association) iter.next();
splitMap.copyAssociationIn(a);
}
}
// --- resolve new subject base name ---
String newBaseName = splitBasename;
if(askName){
while(true){
String input=WandoraOptionPane.showInputDialog(admin,"Enter new base name for the topic", newBaseName);
if(input==null) return;
newBaseName=input;
if(topicMap.getTopicWithBaseName(input)!=null){
int a=WandoraOptionPane.showConfirmDialog(admin,"Topic with base name '"+input+"' already exists and will be merged with new topic. Do you want to continue?");
if(a==WandoraOptionPane.CANCEL_OPTION) return;
else if(a==WandoraOptionPane.YES_OPTION) break;
}
else break;
}
}
split.setBaseName(newBaseName);
// --- resolve new subject locator ---
if(original.getSubjectLocator() != null) {
int c = 2;
Locator newSubjectLocator = new Locator(original.getSubjectLocator().toExternalForm() + "_split");
while(topicMap.getTopicBySubjectLocator(newSubjectLocator) != null && c<10000) {
newSubjectLocator = new Locator(original.getSubjectLocator().toExternalForm() + "_split" + c);
c++;
}
split.setSubjectLocator(newSubjectLocator);
}
// --- resolve new subject identifiers ---
Collection<Locator> sis = split.getSubjectIdentifiers();
List<Locator> siv = new ArrayList<>();
for(Iterator<Locator> iter = sis.iterator(); iter.hasNext(); ) {
siv.add(iter.next());
}
Locator lo = null;
Locator l = null;
for(int j=0; j<siv.size(); j++) {
lo = siv.get(j);
l = new Locator(lo.toExternalForm() + "_split");
int c = 2;
while((topicMap.getTopic(l) != null || splitMap.getTopic(l) != null) && c<10000) {
l = new Locator(lo.toExternalForm() + "_split" + c);
c++;
}
split.addSubjectIdentifier(l);
split.removeSubjectIdentifier(lo);
}
//log("Merging splitted topic to original map...");
topicMap.mergeIn(splitMap);
split = topicMap.getTopicWithBaseName(newBaseName);
// --- attach instances ---
if(split != null && copyInstances) {
Collection<Topic> col = topicMap.getTopicsOfType(original);
Iterator<Topic> iter=col.iterator();
Topic t = null;
while(iter.hasNext()) {
t=(Topic)iter.next();
if(t.isOfType(original)) {
t.addType(split);
}
}
}
if(previousSplit != null) {
if(descending)
split.addType(previousSplit);
else
previousSplit.addType(split);
}
previousSplit = split;
}
if(descending)
original.addType(previousSplit);
else
previousSplit.addType(original);
// Change base name of the original topic....
original.setBaseName(splitParts[splitParts.length-1]);
topicCounter++;
}
}
| 9,844 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
MergeTopics.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/MergeTopics.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/>.
*
*
*
* MergeTopics.java
*
* Created on 2. elokuuta 2006, 17:37
*
*/
package org.wandora.application.tools;
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.application.gui.WandoraOptionPane;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.Topic;
/**
* WandoraTool merging all context topics. Merge is performed by adding one
* subject identifier from one context topic to all other context topics.
* Wandora's topic map model merges topics automatically whenever topics
* share a subject identifier.
*
* @author akivela
*/
public class MergeTopics extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
/** Creates a new instance of MergeTopics */
public MergeTopics() {
}
@Override
public String getName() {
return "Merge topics";
}
@Override
public String getDescription() {
return "Inserts same subject identifier to all selected topics. All selected topics are merged.";
}
@Override
public void execute(Wandora wandora, Context context) {
Iterator topics = context.getContextObjects();
int progress = 0;
ArrayList<Topic> mergeList = new ArrayList<Topic>();
Topic t = null;
while(topics.hasNext()) {
try {
t = (Topic) topics.next();
if(t != null && !t.isRemoved()) {
if(!mergeList.contains(t)) mergeList.add(t);
}
}
catch(Exception e) {
log(e);
}
}
topics = mergeList.iterator();
if(topics != null && topics.hasNext()) {
int a = WandoraOptionPane.showConfirmDialog(wandora, "Are you sure you want to merge selected topics? Restoring topics may be very difficult!", "Confirm Merge", WandoraOptionPane.YES_NO_OPTION);
if(a == WandoraOptionPane.YES_OPTION) {
Topic topic = null;
String si = null;
while(topics.hasNext() && !forceStop()) {
try {
topic = (Topic) topics.next();
if(topic != null && !topic.isRemoved()) {
if(si == null) {
si = topic.getOneSubjectIdentifier().toExternalForm();
continue;
}
setProgress(progress++);
if(si != null) {
topic.addSubjectIdentifier(new Locator(si));
}
}
}
catch(Exception e) {
log(e);
}
}
}
}
}
}
| 3,794 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
Search.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/Search.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/>.
*
*
*
* Search.java
*
* Created on August 30, 2004, 3:32 PM
*/
package org.wandora.application.tools;
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.search.SearchTopicsFrame;
/**
*
* @author olli, ak
*/
public class Search extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
private static SearchTopicsFrame searchFrame = null;
@Override
public void execute(Wandora wandora, Context context) {
if(searchFrame == null) {
searchFrame = new SearchTopicsFrame();
}
if(searchFrame != null) {
searchFrame.setVisible(true);
}
else {
System.out.println("Unable in instantiate SearchTopicsFrame.");
}
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/find_topics.png");
}
@Override
public String getName() {
return "Search";
}
@Override
public String getDescription() {
return "Search for topics.";
}
public boolean useDefaultGui() {
return false;
}
@Override
public boolean requiresRefresh() {
return false;
}
}
| 2,215 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
CopyTopicsToLayer.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/CopyTopicsToLayer.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/>.
*
*
* CopyTopicsToTopicmap.java
*
* Created on August 24, 2004, 11:05 AM
*/
package org.wandora.application.tools;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import javax.swing.Icon;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.WandoraToolLogger;
import org.wandora.application.contexts.Context;
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.TopicMapException;
import org.wandora.topicmap.layered.Layer;
import org.wandora.topicmap.undowrapper.UndoTopicMap;
/**
*
* @author olli, akivela
*/
public class CopyTopicsToLayer extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
public static final int COPY_TOPIC_AS_A_SINGLE_SI_STUB = 101;
public static final int COPY_TOPIC_AS_A_SI_STUB = 102;
public static final int COPY_TOPIC_AS_A_STUB = 106;
public static final int COPY_TOPIC_AS_A_STUB_WITH_VARIANTS = 107;
public static final int COPY_TOPIC_AS_A_STUB_WITH_OCCURRENCES = 108;
public static final int COPY_TOPIC = 103;
public static final int COPY_TOPIC_WITH_ASSOCIATIONS = 104;
public static final int COPY_DEEP = 105;
private static int copyCount = 0;
private static WandoraToolLogger myLogger = null;
private int mode = COPY_DEEP;
private static boolean copyClasses = true;
private static boolean copyInstances = true;
private static boolean copyOccurrenceTypes = true;
private static boolean copyAssociationTypes = true;
private static boolean copyRoles = true;
private static boolean copyPlayers = true;
/**
* Creates a new instance of CopyTopicsToLayer
*/
public CopyTopicsToLayer() {
mode = COPY_TOPIC_AS_A_STUB;
}
public CopyTopicsToLayer(int mymode) {
mode = mymode;
}
@Override
public void execute(Wandora wandora, Context context) {
if(wandora == null) return;
Layer l = wandora.getTopicMap().getSelectedLayer();
TopicMap target = l.getTopicMap();
String layerName = l.getName();
int depth = 1;
copyCount = 0;
if(mode == COPY_TOPIC_AS_A_STUB ||
mode == COPY_TOPIC_AS_A_STUB_WITH_VARIANTS ||
mode == COPY_TOPIC_AS_A_STUB_WITH_OCCURRENCES) {
setDefaultLogger();
Iterator topics = context.getContextObjects();
if(topics != null && topics.hasNext()) {
Topic t = null;
log("Copying topics to topic map layer '"+layerName+"'.");
while(topics.hasNext() && !forceStop()) {
try {
t = (Topic) topics.next();
if(t != null && !t.isRemoved()) {
setProgress(copyCount++);
log("Copying topic '"+getTopicName(t)+"'.");
Topic tt = target.createTopic();
for(Locator locator : t.getSubjectIdentifiers()) {
tt.addSubjectIdentifier(locator);
}
tt.setBaseName(t.getBaseName());
tt.setSubjectLocator(t.getSubjectLocator());
if(COPY_TOPIC_AS_A_STUB_WITH_VARIANTS == mode) {
for(Set<Topic> scope : t.getVariantScopes()) {
Set<Topic> ttScope = new LinkedHashSet<>();
for(Topic scopeTopic : scope) {
Topic ttScopeTopic = target.createTopic();
ttScopeTopic.addSubjectIdentifier(scopeTopic.getFirstSubjectIdentifier());
ttScope.add(ttScopeTopic);
}
if(!tt.isRemoved()) {
tt.setVariant(ttScope, t.getVariant(scope));
}
}
}
if(COPY_TOPIC_AS_A_STUB_WITH_OCCURRENCES == mode) {
for(Topic occurrenceType : t.getDataTypes()) {
for(Topic occurrenceScope : t.getData(occurrenceType).keySet()) {
Topic ttScope = target.createTopic();
ttScope.addSubjectIdentifier(occurrenceScope.getFirstSubjectIdentifier());
Topic ttType = target.createTopic();
ttType.addSubjectIdentifier(occurrenceType.getFirstSubjectIdentifier());
if(!tt.isRemoved() && !ttType.isRemoved() && !ttScope.isRemoved()) {
tt.setData(ttType, ttScope, t.getData(occurrenceType, occurrenceScope));
}
}
}
}
}
}
catch(Exception e) {
log(e);
}
}
log("Total "+copyCount+" topics copied to layer "+layerName);
}
else {
log("Context didn't contain any topics. Nothing copied.");
}
setState(WAIT);
}
else if(mode == COPY_TOPIC_AS_A_SINGLE_SI_STUB ||
mode == COPY_TOPIC_AS_A_SI_STUB) {
setDefaultLogger();
Iterator topics = context.getContextObjects();
if(topics != null && topics.hasNext()) {
Topic t = null;
log("Copying topics to topic map layer '"+layerName+"'.");
while(topics.hasNext() && !forceStop()) {
try {
t = (Topic) topics.next();
if(t != null && !t.isRemoved()) {
setProgress(copyCount++);
log("Copying topic '"+getTopicName(t)+"'.");
Topic tt = target.createTopic();
if(mode == COPY_TOPIC_AS_A_SINGLE_SI_STUB) {
tt.addSubjectIdentifier(t.getFirstSubjectIdentifier());
}
else {
for(Locator locator : t.getSubjectIdentifiers()) {
tt.addSubjectIdentifier(locator);
}
}
}
}
catch(Exception e) {
log(e);
}
}
log("Total "+copyCount+" topics copied to layer "+layerName);
}
else {
log("Context didn't contain any topics. Nothing copied.");
}
setState(WAIT);
}
else {
if(mode == COPY_DEEP) {
try {
GenericOptionsDialog god=new GenericOptionsDialog(wandora,
"Copy topics to layer",
"Copy context topics to current layer '"+layerName+"'.",
true,new String[][]{
new String[] { "Copy depth","string","1" },
new String[] { "Copy association types", "boolean", "true" },
new String[] { "Copy roles", "boolean", "true" },
new String[] { "Copy players", "boolean", "true" },
new String[] { "Copy instances", "boolean", "true" },
new String[] { "Copy classes", "boolean", "true" },
new String[] { "Copy occurrence types", "boolean", "true" },
},wandora);
god.setVisible(true);
if(god.wasCancelled()) return;
Map<String,String> values=god.getValues();
depth=Integer.parseInt(values.get("Copy depth"));
copyRoles = Boolean.parseBoolean(values.get("Copy roles"));
copyPlayers = Boolean.parseBoolean(values.get("Copy players"));
copyAssociationTypes = Boolean.parseBoolean(values.get("Copy association types"));
copyClasses = Boolean.parseBoolean(values.get("Copy classes"));
copyInstances = Boolean.parseBoolean(values.get("Copy instances"));
copyOccurrenceTypes = Boolean.parseBoolean(values.get("Copy occurrence types"));
}
catch(Exception e) {
log(e);
}
}
// QUICK HACK. SURPASSES THE UNDO/REDO.
if(target instanceof UndoTopicMap) {
target = ((UndoTopicMap) target).getWrappedTopicMap();
}
setDefaultLogger();
myLogger = this;
copyCount = 0;
HashMap<Locator,Integer> copied = new HashMap<Locator,Integer>();
Iterator topics = context.getContextObjects();
if(topics != null && topics.hasNext()) {
Topic t = null;
log("Copying topics to topic map layer '"+layerName+"'.");
while(topics.hasNext() && !forceStop()) {
try {
t = (Topic) topics.next();
if(t != null && !t.isRemoved()) {
if(mode == COPY_DEEP) {
copyTopicsIn(t,target,t.getTopicMap(),copied,depth);
}
else {
setProgress(copyCount++);
log("Copying topic '"+getTopicName(t)+"'.");
target.copyTopicIn(t,true);
if(mode == COPY_TOPIC_WITH_ASSOCIATIONS) {
target.copyTopicAssociationsIn(t);
}
}
}
}
catch(Exception e) {
log(e);
}
}
log("Total "+copyCount+" topics copied to layer "+layerName);
log("This includes association types, roles and players.");
}
else {
log("Context didn't contain any topics. Nothing copied.");
}
setState(WAIT);
}
}
public static void copyTopicsIn(Topic t,TopicMap target,TopicMap source, HashMap<Locator,Integer> copied,int depth) throws TopicMapException {
if(myLogger != null && myLogger.forceStop()) return;
if(depth>0){
Integer olddepth=copied.get(t.getOneSubjectIdentifier());
if(olddepth==null || depth>olddepth){
for(Locator l : t.getSubjectIdentifiers()) copied.put(l,depth);
if(olddepth==null) {
if(myLogger != null) {
myLogger.log("Copying topic '"+getTopicName(t)+"'.");
myLogger.setProgress(copyCount++);
}
target.copyTopicIn(t,true);
target.copyTopicAssociationsIn(t);
}
if(depth>1) {
// **** COPYING CLASSES ****
if(copyClasses) {
Collection<Topic> types = t.getTypes();
for(Iterator<Topic> typeIter = types.iterator(); typeIter.hasNext(); ) {
Topic topic = typeIter.next();
if(topic != null && !topic.isRemoved()) {
copyTopicsIn(topic,target,source,copied,depth-1);
}
}
}
// **** COPYING INSTANCES ****
if(copyInstances) {
Collection<Topic> instances = source.getTopicsOfType(t);
for(Iterator<Topic> instanceIter = instances.iterator(); instanceIter.hasNext(); ) {
if(myLogger!=null && myLogger.forceStop()) return;
Topic topic = instanceIter.next();
if(topic != null && !topic.isRemoved()) {
copyTopicsIn(topic,target,source,copied,depth-1);
}
}
}
// **** COPYING ASSOCIATION TYPES & ROLES & PLAYERS ****
for(Association a : t.getAssociations()){
if(myLogger!=null && myLogger.forceStop()) return;
if(copyAssociationTypes) {
copyTopicsIn(a.getType(),target,source,copied,depth-1);
}
if(copyRoles || copyPlayers) {
for(Topic role : a.getRoles()){
if(role != null && !role.isRemoved()) {
if(copyRoles) {
copyTopicsIn(role,target,source,copied,depth-1);
}
if(copyPlayers) {
copyTopicsIn(a.getPlayer(role),target,source,copied,depth-1);
}
}
}
}
}
// **** COPYING OCCURRENCE TYPES ****
if(copyOccurrenceTypes) {
Collection<Topic> occurrenceTypes = t.getDataTypes();
for(Iterator<Topic> occurrenceIter=occurrenceTypes.iterator(); occurrenceIter.hasNext(); ) {
Topic topic = occurrenceIter.next();
if(topic != null && !topic.isRemoved()) {
copyTopicsIn(topic,target,source,copied,depth-1);
}
}
}
}
}
}
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/copy_topic.png");
}
@Override
public String getName() {
return "Copy topics to layer";
}
@Override
public String getDescription() {
if(mode == COPY_TOPIC_AS_A_SINGLE_SI_STUB) {
return "Copy selected topics to active layer as a stub topics including only one subject identifier from the original topic.";
}
else if(mode == COPY_TOPIC_AS_A_SI_STUB) {
return "Copy selected topics to active layer as a stub topics including only the subject identifiers from the original topic.";
}
else if(mode == COPY_TOPIC_AS_A_STUB) {
return "Copy selected topics to active layer as a stub topics including the subject identifiers, the subject locator and the basename from the original topic.";
}
else if(mode == COPY_TOPIC_AS_A_STUB_WITH_VARIANTS) {
return "Copy selected topics to active layer as a stub topics including the subject identifiers, the subject locator and the basename from the original topic. "+
"Variant names are copied too. Necessary scope topics will be created automatically.";
}
else if(mode == COPY_TOPIC_AS_A_STUB_WITH_OCCURRENCES) {
return "Copy selected topics to active layer as a stub topics including the subject identifiers, the subject locator and the basename from the original topic. "+
"Occurrences are copied too. Necessary type and scope topics will be created automatically.";
}
else if(mode == COPY_TOPIC) {
return "Copy selected topics to active layer. Copy includes subject identifiers, basenames, "+
"subject locators, variant names, types and instances. Necessary type and scope topics "+
"are created automatically.";
}
else if(mode == COPY_TOPIC_WITH_ASSOCIATIONS) {
return "Copy selected topics and their association to active layer. Copies only stubs of associated topics.";
}
else if(mode == COPY_DEEP) {
return "Copy selected topics and their associations to active layer. User must set the copy depth.";
}
else return "Copy selected topics to active layer.";
}
}
| 18,043 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
DeleteTopicsWithoutAI.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/DeleteTopicsWithoutAI.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/>.
*
*
*
* DeleteTopicsWithoutAI.java
*
* Created on 14.7.2006, 11:19
*
*/
package org.wandora.application.tools;
import org.wandora.application.WandoraTool;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author akivela
*/
public class DeleteTopicsWithoutAI extends DeleteTopics implements WandoraTool {
private static final long serialVersionUID = 1L;
/** Creates a new instance of DeleteTopicsWithoutAI */
public DeleteTopicsWithoutAI() {
}
@Override
public String getName() {
return "Delete topics without associations and instances";
}
@Override
public String getDescription() {
return "Delete topics having no associations and instances.";
}
@Override
public boolean shouldDelete(Topic topic) throws TopicMapException {
try {
if(topic != null && !topic.isRemoved()) {
if(topic.getAssociations().isEmpty() && topic.getTopicMap().getTopicsOfType(topic).isEmpty()) {
if(confirm) {
return confirmDelete(topic);
}
else {
return true;
}
}
}
}
catch(Exception e) {
log(e);
}
return false;
}
}
| 2,165 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
ApplyChanges.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/ApplyChanges.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/>.
*
*
* ApplyChanges.java
*
* Created on 19. toukokuuta 2006, 11:12
*/
package org.wandora.application.tools;
import org.wandora.application.Wandora;
import org.wandora.application.contexts.Context;
import org.wandora.topicmap.TopicMapException;
/**
*
* @deprecated
* @author olli
*/
public class ApplyChanges extends AbstractWandoraTool {
private static final long serialVersionUID = 1L;
/** Creates a new instance of ApplyChanges */
public ApplyChanges() {
}
@Override
public String getName() {
return "Apply changes";
}
@Override
public String getDescription() {
return "Deprecated. Applies current changes to the opened topic";
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
// Deprecated tool.
// Apply changes is actually done by default in AbstractWandoraTool.
}
}
| 1,718 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
FlipNameMatrix.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/FlipNameMatrix.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/>.
*
*
*
* FlipNameMatrix.java
*
* Created on 5. toukokuuta 2006, 12:39
*
*/
package org.wandora.application.tools;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.Context;
import org.wandora.utils.Options;
/**
* WandoraTool changing the orientation of name matrix in topic panel. Affects only the
* orientation of schema name matrix.
*
* @author akivela
*/
public class FlipNameMatrix extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
private Options localOptions = null;
public String optionsPrefix = "gui.";
/**
* Creates a new instance of FlipNameMatrix
*/
public FlipNameMatrix() {
}
public FlipNameMatrix(String optionsPrefix) {
this.optionsPrefix = optionsPrefix;
}
public FlipNameMatrix(Options localOpts) {
this.localOptions = localOpts;
}
public FlipNameMatrix(String optionsPrefix, Options localOpts) {
this.optionsPrefix = optionsPrefix;
this.localOptions = localOpts;
}
public void execute(Wandora wandora, Context context) {
setFlipOptions(localOptions);
setFlipOptions(wandora.getOptions());
}
private void setFlipOptions(Options options) {
if(options != null) {
if("vertical".equals(options.get(optionsPrefix + "namePanelOrientation"))) {
options.put(optionsPrefix + "namePanelOrientation", "horizontal");
}
else {
options.put(optionsPrefix + "namePanelOrientation", "vertical");
}
}
}
@Override
public String getName() {
return "Flip name matrix";
}
@Override
public String getDescription() {
return "Change the orientation of name matrix in topic panel. Affects only the orientation of schema name matrix.";
}
@Override
public boolean runInOwnThread(){
return false;
}
@Override
public boolean requiresRefresh() {
return true;
}
}
| 2,947 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AddInstance.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/AddInstance.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/>.
*
*
* AddInstance.java
*
* Created on October 1, 2004, 1:12 PM
*/
package org.wandora.application.tools;
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;
import org.wandora.topicmap.TopicMapException;
/**
* Tool is used to add instance to the context topics.
*
* @author akivela
*/
public class AddInstance extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
private boolean shouldRefresh = false;
public AddInstance() {
}
public AddInstance(Context preferredContext) {
setContext(preferredContext);
}
@Override
public String getName() {
return "Add instance";
}
@Override
public String getDescription() {
return "Add instance topic to selected topics.";
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
shouldRefresh = false;
Iterator topics = context.getContextObjects();
if(topics != null && topics.hasNext()) {
Topic instanceTopic=wandora.showTopicFinder("Select instance topic...");
Topic topic = null;
if(instanceTopic != null) {
while(topics.hasNext() && !forceStop()) {
try {
topic = (Topic) topics.next();
if(topic != null && !topic.isRemoved()) {
shouldRefresh = true;
instanceTopic.addType(topic);
}
}
catch(Exception e) {
log(e);
}
}
}
}
}
@Override
public boolean requiresRefresh() {
return shouldRefresh;
}
}
| 2,753 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SetOptionsLocal.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/SetOptionsLocal.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/>.
*
*
*
* SetOptions.java
*
* Created on 9. marraskuuta 2005, 21:30
*
*/
package org.wandora.application.tools;
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.utils.Options;
/**
*
* @author akivela
*/
public class SetOptionsLocal extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
private Map<String,String> options = new LinkedHashMap<>();
private boolean requiresRefresh = false;
private Options localOptions = null;
public SetOptionsLocal() {
}
public SetOptionsLocal(Options localOpts, String key, int value, boolean rf) {
requiresRefresh = rf;
localOptions = localOpts;
options.put(key, "" + value);
}
public SetOptionsLocal(Options localOpts, String key, String value, boolean rf) {
requiresRefresh = rf;
localOptions = localOpts;
options.put(key, value);
}
public void setOption(String key, String value) {
if(key != null && value != null) {
options.put(key, value);
}
}
public void setOptions(Map<String,String> subOptions) {
if(subOptions != null) {
options.putAll(subOptions);
}
}
@Override
public String getName() {
return "Set local options";
}
@Override
public void execute(Wandora wandora, Context context) {
if(localOptions != null) {
String key = null;
String value = null;
for(Iterator<String> keys = options.keySet().iterator(); keys.hasNext(); ) {
try {
key = (String) keys.next();
value = (String) options.get(key);
localOptions.put(key, value);
}
catch(Exception e) {
log(e);
}
}
}
}
@Override
public boolean requiresRefresh() {
return requiresRefresh;
}
}
| 2,985 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
DeleteTopics.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/DeleteTopics.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/>.
*
*
* DeleteTopics.java
*
* Created on September 22, 2004, 12:33 PM
*/
package org.wandora.application.tools;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
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.ConfirmResult;
import org.wandora.application.gui.UIBox;
import org.wandora.application.gui.WandoraOptionPane;
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.TopicMapReadOnlyException;
import org.wandora.topicmap.layered.LayeredTopic;
/**
*
* @author akivela
*/
public class DeleteTopics extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
public boolean forceDelete = true;
public boolean confirm = true;
public boolean shouldContinue = true;
protected Wandora wandora = null;
private String topicName = null;
public DeleteTopics() {
//setContext(new TopicContext());
}
public DeleteTopics(Context preferredContext) {
setContext(preferredContext);
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/topic_delete.png");
}
@Override
public String getName() {
return "Delete topics";
}
@Override
public String getDescription() {
return "Delete topics.";
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
this.wandora = wandora;
ArrayList<Topic> topicsToDelete = new ArrayList<Topic>();
Iterator topics = context.getContextObjects();
Topic topic = null;
Topic ltopic = null;
int count = 0;
ConfirmResult r_all = null;
ConfirmResult r = null;
yesToAll = false;
shouldContinue = true;
if(topics != null && topics.hasNext()) {
while(topics.hasNext() && shouldContinue && !forceStop()) {
topic = (Topic) topics.next();
if(topic != null && !topic.isRemoved()) {
if(topic instanceof LayeredTopic) {
ltopic = ((LayeredTopic) topic).getTopicForSelectedLayer();
if(ltopic == null || ltopic.isRemoved()) {
int answer = WandoraOptionPane.showConfirmDialog(wandora,
"Topic '"+getTopicName(topic)+"' doesn't exist in selected layer. "+
"Would you like to proceed deleting other topics?",
"Topic not in selected layer",
WandoraOptionPane.OK_CANCEL_OPTION);
if(answer == WandoraOptionPane.CANCEL_OPTION) shouldContinue = false;
continue;
}
else {
topic = ltopic;
}
}
topicName = getTopicName(topic);
//hlog("Investigating topic '" + topicName + "'.");
if(topic.isDeleteAllowed()) {
if(shouldDelete(topic)) {
try {
if(r_all == null) r = TMBox.checkTopicRemove(wandora, topic);
else r = r_all;
if(r == ConfirmResult.cancel) break;
else if(r == ConfirmResult.no) continue;
else if(r == ConfirmResult.notoall) { r_all = r; continue; }
else if(r == ConfirmResult.yestoall) { r_all = r; }
topicsToDelete.add(topic);
count++;
}
catch(Exception e2) {
log(e2);
}
}
}
else {
int answer = WandoraOptionPane.showConfirmDialog(wandora,
"Unable to delete topic '"+getTopicName(topic)+"'. "+
"The topic may be an occurrent type, variant name type, association role or association type or has instances. "+
"Would you like to remove related occurrences, variant names, associations and instances and try deletion again?",
"Prepare topic deletion", WandoraOptionPane.YES_NO_CANCEL_OPTION);
if(answer == WandoraOptionPane.YES_OPTION) {
prepareTopicRemove(topic, wandora);
topicsToDelete.add(topic);
count++;
}
else if(answer == WandoraOptionPane.NO_OPTION) continue;
else if(answer == WandoraOptionPane.CANCEL_OPTION) shouldContinue = false;
else shouldContinue = false;
}
}
}
if((count > 0 || shouldContinue) && !forceStop()) {
setDefaultLogger();
int rcount = 0;
for(int i=0; i<count && !forceStop(); i++) {
try {
topic = topicsToDelete.get(i);
if(topic != null && !topic.isRemoved()) {
topic.remove();
rcount++;
if((i % 100) == 0) hlog((count-i) + " topics to delete.");
}
}
catch(TopicMapReadOnlyException tmroe) {
log("Selected topic map is write protected.");
log("Unlock selected topic map layer and try again.");
break;
}
catch(Exception e) {
log(e);
}
}
if(rcount == 0) log("No topics deleted.");
else if(rcount == 1) log("One topic deleted.");
else log(rcount + " topics deleted.");
log("Ready.");
setState(WAIT);
}
}
topicsToDelete = null;
}
public boolean shouldDelete(Topic topic) throws TopicMapException {
if(confirm) {
return confirmDelete(topic);
}
else {
return true;
}
}
public boolean yesToAll = false;
public boolean confirmDelete(Topic topic) throws TopicMapException {
if(yesToAll) {
return true;
}
else {
setState(INVISIBLE);
//topicName = topic.getBaseName();
//if(topicName == null) topicName = topic.getOneSubjectIdentifier().toExternalForm();
String confirmMessage = "Would you like delete topic '" + topicName + "' in selected layer?";
int answer = WandoraOptionPane.showConfirmDialog(wandora, confirmMessage,"Confirm delete", WandoraOptionPane.YES_TO_ALL_NO_CANCEL_OPTION);
setState(VISIBLE);
if(answer == WandoraOptionPane.YES_OPTION) {
return true;
}
if(answer == WandoraOptionPane.YES_TO_ALL_OPTION) {
yesToAll = true;
return true;
}
else if(answer == WandoraOptionPane.CANCEL_OPTION) {
shouldContinue = false;
}
return false;
}
}
public void removeClasses(Topic t) throws TopicMapException {
Collection<Topic> types = t.getTypes();
if(types != null) {
Iterator<Topic> typeIterator = types.iterator();
while(typeIterator.hasNext()) {
t.removeType(typeIterator.next());
}
}
}
public void removeInstances(Topic t) throws TopicMapException {
Collection<Topic> instances = t.getTopicMap().getTopicsOfType(t);
if(instances != null) {
Iterator<Topic> instanceIterator = instances.iterator();
while(instanceIterator.hasNext()) {
instanceIterator.next().removeType(t);
}
}
}
protected void prepareTopicRemove(Topic to, Wandora w) throws TopicMapException {
if(to == null || w == null) return;
TopicMap tm = w.getTopicMap();
if(tm == null) return;
Topic t = tm.getTopic(to.getOneSubjectIdentifier());
if(t == null) return;
Collection<Topic> instances = tm.getTopicsOfType(t);
for(Topic instance : instances) {
instance.removeType(t);
}
Iterator<Association> associations = tm.getAssociations();
Association association = null;
ArrayList<Association> asociationsToBeRemoved = new ArrayList<>();
while(associations.hasNext()) {
association = associations.next();
if(t.mergesWithTopic(association.getType()) || association.getPlayer(t) != null) {
asociationsToBeRemoved.add(association);
}
}
for(Association a : asociationsToBeRemoved) {
a.remove();
}
Iterator<Topic> topics = tm.getTopics();
Topic topic;
while(topics.hasNext()) {
topic = topics.next();
if(!topic.getData(t).isEmpty()) {
topic.removeData(t);
}
Collection<Topic> dataTypes = topic.getDataTypes();
for(Topic dataType : dataTypes) {
topic.removeData(dataType, t);
}
Set<Set<Topic>> variantScopes = topic.getVariantScopes();
for(Set<Topic> variantScope : variantScopes) {
if(variantScope.contains(t)) {
String variant = topic.getVariant(variantScope);
topic.removeVariant(variantScope);
variantScope.remove(t);
if(!variantScope.isEmpty()) {
if(topic.getVariant(variantScope) == null) {
topic.setVariant(variantScope, variant);
}
}
}
}
}
}
}
| 11,491 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SelectTopicIfNoOccurrences.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/selections/SelectTopicIfNoOccurrences.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/>.
*
*
* SelectTopicIfNoOccurrences.java
*
* Created on 14.7.2006, 12:13
*
*/
package org.wandora.application.tools.selections;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author akivela
*/
public class SelectTopicIfNoOccurrences extends DoTopicSelection {
private static final long serialVersionUID = 1L;
@Override
public boolean acceptTopic(Topic topic) {
try {
if(topic != null && !topic.isRemoved() && topic.getDataTypes().isEmpty()) return true;
return false;
}
catch(TopicMapException tme) {
log(tme);
return false;
}
}
@Override
public String getName() {
return "Select if topic has no occurrences.";
}
}
| 1,596 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SelectAll.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/selections/SelectAll.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/>.
*
*
* SelectAll.java
*
* Created on 12. huhtikuuta 2006, 10:17
*
*/
package org.wandora.application.tools.selections;
import java.awt.Component;
import java.util.Iterator;
import javax.swing.Icon;
import javax.swing.JTable;
import javax.swing.text.JTextComponent;
import org.wandora.application.Wandora;
import org.wandora.application.gui.UIBox;
import org.wandora.application.gui.simple.SimpleField;
import org.wandora.application.gui.table.SITable;
import org.wandora.application.gui.table.TopicGrid;
import org.wandora.application.gui.table.TopicTable;
import org.wandora.application.gui.topicpanels.graphpanel.TopicMapGraphPanel;
import org.wandora.application.gui.topicpanels.graphpanel.VModel;
import org.wandora.application.gui.topicpanels.graphpanel.VNode;
/**
* Class implements select tool that tries to select all available elements.
* In case of <code>TopicTable</code> tool selects all cells in current
* focused topic table. In case of text fields and other text containers
* tool selects entire text.
*
* @author akivela
*/
public class SelectAll extends DoSelection {
private static final long serialVersionUID = 1L;
@Override
public void doOtherSelection(Wandora wandora, Component component) {
if(component instanceof JTextComponent) {
JTextComponent tc = (JTextComponent) component;
tc.requestFocus();
tc.selectAll();
}
else if(component instanceof SimpleField) {
SimpleField f = (SimpleField) component;
f.requestFocus();
f.selectAll();
}
else if(component instanceof JTable) {
JTable jt = (JTable) component;
jt.requestFocus();
jt.selectAll();
}
}
@Override
public void doTableSelection(Wandora wandora, SITable siTable) {
siTable.selectAll();
}
@Override
public void doTableSelection(Wandora wandora, TopicTable table) {
table.selectAll();
}
@Override
public void doGridSelection(Wandora wandora, TopicGrid grid) {
grid.selectAll();
}
@Override
public void doGraphSelection(Wandora wandora, TopicMapGraphPanel graph) {
if(graph != null) {
VModel model = graph.getModel();
if(model != null) {
model.deselectAll();
VNode vnode = null;
for(Iterator<VNode> vnodes = model.getNodes().iterator(); vnodes.hasNext(); ) {
vnode = (VNode) vnodes.next();
if(vnode != null) {
model.addSelection(vnode);
}
}
}
}
}
@Override
public String getName() {
return "Select all";
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/select_all.png");
}
}
| 3,705 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SelectionInfo.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/selections/SelectionInfo.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/>.
*
*
* SelectionInfo.java
*
* Created on 12. huhtikuuta 2006, 10:27
*
*/
package org.wandora.application.tools.selections;
import javax.swing.ListSelectionModel;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraToolLogger;
import org.wandora.application.gui.table.AssociationTable;
import org.wandora.application.gui.table.ClassTable;
import org.wandora.application.gui.table.InstanceTable;
import org.wandora.application.gui.table.SITable;
import org.wandora.application.gui.table.TopicGrid;
import org.wandora.application.gui.table.TopicTable;
import org.wandora.application.gui.topicpanels.graphpanel.TopicMapGraphPanel;
import org.wandora.application.gui.topicpanels.graphpanel.VModel;
import org.wandora.application.gui.topicstringify.TopicToString;
import org.wandora.application.gui.tree.TopicTree;
import org.wandora.application.gui.tree.TopicTreeModel;
import org.wandora.utils.swing.anyselectiontable.TableSelectionModel;
/**
* Class implements a special selection tool that does not modify current
* selection but opens an info dialog about the selection. Tool is useful
* to count selection size for example. Current tool supports only topic table
* components. Tool has no defined behavior in context of text components.
*
* @author akivela
*/
public class SelectionInfo extends DoSelection {
private static final long serialVersionUID = 1L;
/** Creates a new instance of SelectionInfo */
public SelectionInfo() {
}
@Override
public void doTableSelection(Wandora admin, SITable table) {
setDefaultLogger();
setLogTitle("Subject identifier table selection info");
int rowsCounter = table.getRowCount();
int colsCounter = table.getColumnCount();
//int rowSelectionCounter = 0;
//int colSelectionCounter = 0;
int cellSelectionCounter = 0;
TableSelectionModel selection = table.getTableSelectionModel();
for(int c=0; c<colsCounter; c++) {
ListSelectionModel columnSelectionModel = selection.getListSelectionModelAt(c);
if(columnSelectionModel != null && !columnSelectionModel.isSelectionEmpty()) {
for(int r=0; r<rowsCounter; r++) {
if(columnSelectionModel.isSelectedIndex(r)) {
cellSelectionCounter++;
}
}
}
}
String message = "Subject identifier table contains " + rowsCounter + " rows";
if(colsCounter > 1) message += " and " + (rowsCounter*colsCounter) + " cells.";
else message += ".";
if(cellSelectionCounter == 1) message += "\nSelection contains " + cellSelectionCounter + " cell.";
if(cellSelectionCounter > 1) message += "\nSelection contains " + cellSelectionCounter + " cells.";
log(message);
setState(WandoraToolLogger.WAIT);
}
@Override
public void doTableSelection(Wandora admin, TopicTable table) {
setDefaultLogger();
setLogTitle("Table selection info");
int rowsCounter = table.getRowCount();
int colsCounter = table.getColumnCount();
//int rowSelectionCounter = 0;
//int colSelectionCounter = 0;
int cellSelectionCounter = 0;
TableSelectionModel selection = table.getTableSelectionModel();
for(int c=0; c<colsCounter; c++) {
ListSelectionModel columnSelectionModel = selection.getListSelectionModelAt(c);
if(columnSelectionModel != null && !columnSelectionModel.isSelectionEmpty()) {
for(int r=0; r<rowsCounter; r++) {
if(columnSelectionModel.isSelectedIndex(r)) {
cellSelectionCounter++;
}
}
}
}
String message = getTableName(table) + " contains " + rowsCounter + " rows";
if(colsCounter > 1) message += " and " + (rowsCounter*colsCounter) + " cells.";
else message += ".";
if(cellSelectionCounter == 1) message += "\nSelection contains " + cellSelectionCounter + " cell.";
if(cellSelectionCounter > 1) message += "\nSelection contains " + cellSelectionCounter + " cells.";
log(message);
setState(WandoraToolLogger.WAIT);
}
private String getTableName(TopicTable t) {
if(t == null) {
return "null";
}
if(t instanceof AssociationTable) {
AssociationTable at = (AssociationTable) t;
return "Association table '"+TopicToString.toString(at.getAssociationTypeTopic())+"'";
}
if(t instanceof ClassTable) {
return "Classes table";
}
if(t instanceof InstanceTable) {
return "Instances table";
}
return "Topic table";
}
@Override
public void doGridSelection(Wandora admin, TopicGrid grid) {
setDefaultLogger();
setLogTitle("Grid selection info");
int rowsCounter = grid.getRowCount();
int colsCounter = grid.getColumnCount();
//int rowSelectionCounter = 0;
//int colSelectionCounter = 0;
int cellSelectionCounter = 0;
TableSelectionModel selection = grid.getTableSelectionModel();
for(int c=0; c<colsCounter; c++) {
ListSelectionModel columnSelectionModel = selection.getListSelectionModelAt(c);
if(columnSelectionModel != null && !columnSelectionModel.isSelectionEmpty()) {
for(int r=0; r<rowsCounter; r++) {
if(columnSelectionModel.isSelectedIndex(r)) {
cellSelectionCounter++;
}
}
}
}
String message = "Grid contains " + rowsCounter + " rows";
if(colsCounter > 1) message += " and " + (rowsCounter*colsCounter) + " cells.";
else message += ".";
if(cellSelectionCounter == 1) message += "\nSelection contains " + cellSelectionCounter + " cell.";
if(cellSelectionCounter > 1) message += "\nSelection contains " + cellSelectionCounter + " cells.";
log(message);
setState(WandoraToolLogger.WAIT);
}
@Override
public void doGraphSelection(Wandora admin, TopicMapGraphPanel graph) {
setDefaultLogger();
setLogTitle("Graph selection info");
if(graph != null) {
VModel model = graph.getModel();
if(model != null) {
int nodeCount = model.getNodes().size();
int edgeCount = model.getEdges().size();
int nodeSelectionCount = model.getSelectedNodes().size();
int edgeSelectionCount = model.getSelectedEdges().size();
String message = "Graph contains " + nodeCount + " nodes and "+ edgeCount + " edges.";
message += "\nSelection contains " + nodeSelectionCount + " nodes and "+ edgeSelectionCount + " edges.";
log(message);
setState(WandoraToolLogger.WAIT);
}
}
}
@Override
public void doTreeSelection(Wandora admin, TopicTree tree) {
setDefaultLogger();
setLogTitle("Tree selection info");
if(tree != null) {
TopicTreeModel model = (TopicTreeModel) tree.getModel();
if(model != null) {
int topicCount = model.getVisibleTopicCount();
String message = "Tree contains " + topicCount + " topics at the moment.";
message += "\nTree selection contains always one topic.";
message += "\nAt the moment selected tree topic is '" + tree.getCopyString() + "'.";
log(message);
setState(WandoraToolLogger.WAIT);
}
}
}
@Override
public String getName() {
return "Topic selection info";
}
}
| 8,774 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
InvertSelection.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/selections/InvertSelection.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/>.
*
*
* InvertSelection.java
*
* Created on 12. huhtikuuta 2006, 10:22
*
*/
package org.wandora.application.tools.selections;
import java.util.Iterator;
import javax.swing.Icon;
import org.wandora.application.Wandora;
import org.wandora.application.gui.UIBox;
import org.wandora.application.gui.table.SITable;
import org.wandora.application.gui.table.TopicGrid;
import org.wandora.application.gui.table.TopicTable;
import org.wandora.application.gui.topicpanels.graphpanel.TopicMapGraphPanel;
import org.wandora.application.gui.topicpanels.graphpanel.VModel;
import org.wandora.application.gui.topicpanels.graphpanel.VNode;
/**
* Tool inverts current selection in current topic table. Inversion deselects
* all selected and selects all unselected cells. Tool supports currently only
* topic table context and has no specified behavior with text components for
* example.
*
* @author akivela
*/
public class InvertSelection extends DoSelection {
private static final long serialVersionUID = 1L;
/** Creates a new instance of InvertSelection */
public InvertSelection() {
}
@Override
public void doTableSelection(Wandora admin, SITable siTable) {
siTable.invertSelection();
}
@Override
public void doTableSelection(Wandora admin, TopicTable table) {
table.invertSelection();
}
@Override
public void doGridSelection(Wandora wandora, TopicGrid grid) {
grid.invertSelection();
}
@Override
public void doGraphSelection(Wandora admin, TopicMapGraphPanel graph) {
if(graph != null) {
VModel model = graph.getModel();
if(model != null) {
VNode vnode = null;
for(Iterator vnodes = model.getNodes().iterator(); vnodes.hasNext(); ) {
vnode = (VNode) vnodes.next();
if(vnode != null) {
if( vnode.isSelected() ) {
model.deselectNode(vnode);
}
else {
model.addSelection(vnode);
}
}
}
}
}
}
@Override
public String getName() {
return "Invert selection";
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/selection_invert.png");
}
}
| 3,253 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SelectTopicIfNotInLayer.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/selections/SelectTopicIfNotInLayer.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/>.
*
*
* SelectTopicIfInLayer.java
*
* Created on 7.1.2012, 12:05
*
*/
package org.wandora.application.tools.selections;
/**
*
* @author akivela
*/
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
import org.wandora.topicmap.layered.LayeredTopic;
public class SelectTopicIfNotInLayer extends DoTopicSelection {
private static final long serialVersionUID = 1L;
@Override
public boolean acceptTopic(Topic topic) {
try{
if(topic != null && !topic.isRemoved()) {
if(topic instanceof LayeredTopic) {
Topic ltopic = ((LayeredTopic) topic).getTopicForSelectedLayer();
if(ltopic == null || ltopic.isRemoved()) {
return true;
}
}
return false;
}
}
catch(TopicMapException tme) {
log(tme);
}
return false;
}
@Override
public String getName() {
return "Select if topic locates in selected layer.";
}
}
| 1,881 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
LocateSelectTopicInTree.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/selections/LocateSelectTopicInTree.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.selections;
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.tree.TopicTree;
import org.wandora.application.tools.AbstractWandoraTool;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author akivela
*/
public class LocateSelectTopicInTree extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
/** Creates a new instance of LocateSelectTopicInTree */
public LocateSelectTopicInTree() {
}
public LocateSelectTopicInTree(Context preferredContext) {
setContext(preferredContext);
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
Iterator contextTopics = context.getContextObjects();
TopicTree tree = wandora.getCurrentTopicTree();
if(tree != null && contextTopics != null && contextTopics.hasNext()) {
try {
boolean found = tree.selectTopic((Topic) contextTopics.next());
if(!found) {
WandoraOptionPane.showMessageDialog(wandora, "Topic is not visible in the topic tree and can't be selected.", "Topic not found in the tree", WandoraOptionPane.INFORMATION_MESSAGE);
}
}
catch(Exception e) {
e.printStackTrace();
}
}
}
@Override
public String getName() {
return "Locate and select topic in tree";
}
@Override
public String getDescription() {
return "Locates current topic in topic tree and selects the located topic.";
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/topic_open.png");
}
@Override
public boolean requiresRefresh() {
return false;
}
}
| 2,928 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
DoTopicSelection.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/selections/DoTopicSelection.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/>.
*
*
* SelectCellsInTopicTable.java
*
* Created on 14.7.2006, 11:51
*
*/
package org.wandora.application.tools.selections;
import java.util.Iterator;
import javax.swing.Icon;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.gui.UIBox;
import org.wandora.application.gui.table.TopicGrid;
import org.wandora.application.gui.table.TopicTable;
import org.wandora.application.gui.topicpanels.graphpanel.Node;
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;
/**
*
* @author akivela
*/
public abstract class DoTopicSelection extends DoSelection implements WandoraTool {
private static final long serialVersionUID = 1L;
@Override
public void doTableSelection(Wandora admin, TopicTable table) {
table.clearSelection();
int colCount = table.getColumnCount();
int rowCount = table.getRowCount();
for(int c=0; c<colCount; c++) {
for(int r=0; r<rowCount; r++) {
if(acceptTopic(table.getTopicAt(r, c))) {
table.selectCell(c,r);
//table.addColumnSelectionInterval(j, j);
//table.addRowSelectionInterval(i, i);
}
}
}
}
@Override
public void doGridSelection(Wandora wandora, TopicGrid grid) {
grid.clearSelection();
int colCount = grid.getColumnCount();
int rowCount = grid.getRowCount();
for(int c=0; c<colCount; c++) {
for(int r=0; r<rowCount; r++) {
if(acceptTopic(grid.getTopicAt(r, c))) {
grid.selectCell(c,r);
//table.addColumnSelectionInterval(j, j);
//table.addRowSelectionInterval(i, i);
}
}
}
}
@Override
public void doGraphSelection(Wandora admin, TopicMapGraphPanel graph) {
if(graph != null) {
VModel model = graph.getModel();
if(model != null) {
model.deselectAll();
VNode vnode = null;
Topic t = null;
for(Iterator vnodes = model.getNodes().iterator(); vnodes.hasNext(); ) {
vnode = (VNode) vnodes.next();
if(vnode != null) {
Node n = vnode.getNode();
if(n instanceof TopicNode) {
t = ((TopicNode) n).getTopic();
if(t != null) {
if(acceptTopic(t)) {
model.addSelection(vnode);
}
}
}
}
}
}
}
}
// ***** EXTEND THIS METHOD IN YOUR SELECTION TOOL *****
public abstract boolean acceptTopic(Topic topic);
@Override
public String getName() {
return "Abstract topic selection tool.";
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/select_topics.png");
}
}
| 4,212 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SelectTopicIfInLayer.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/selections/SelectTopicIfInLayer.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/>.
*
*
* SelectTopicIfInLayer.java
*
* Created on 7.1.2012, 12:05
*
*/
package org.wandora.application.tools.selections;
/**
*
* @author akivela
*/
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
import org.wandora.topicmap.layered.LayeredTopic;
public class SelectTopicIfInLayer extends DoTopicSelection {
private static final long serialVersionUID = 1L;
@Override
public boolean acceptTopic(Topic topic) {
try{
if(topic != null && !topic.isRemoved()) {
if(topic instanceof LayeredTopic) {
Topic ltopic = ((LayeredTopic) topic).getTopicForSelectedLayer();
if(ltopic == null || ltopic.isRemoved()) {
return false;
}
}
return true;
}
}
catch(TopicMapException tme) {
log(tme);
}
return false;
}
@Override
public String getName() {
return "Select if topic locates in selected layer.";
}
}
| 1,897 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SelectColumns.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/selections/SelectColumns.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/>.
*
*
* SelectColumns.java
*
* Created on 12. huhtikuuta 2006, 10:21
*
*/
package org.wandora.application.tools.selections;
import org.wandora.application.Wandora;
import org.wandora.application.gui.table.SITable;
import org.wandora.application.gui.table.TopicGrid;
import org.wandora.application.gui.table.TopicTable;
/**
* Implements <code>WandoraAdminTool</code> used to select
* topic table columns. Class has no defined behavior in any other context.
*
* @author akivela
*/
public class SelectColumns extends DoSelection {
private static final long serialVersionUID = 1L;
/** Creates a new instance of SelectColumns */
public SelectColumns() {
}
@Override
public void doTableSelection(Wandora wandora, SITable siTable) {
siTable.selectColumns();
}
@Override
public void doTableSelection(Wandora admin, TopicTable table) {
table.selectColumns();
}
@Override
public void doGridSelection(Wandora wandora, TopicGrid grid) {
grid.selectColumns();
}
@Override
public String getName() {
return "Select columns in topic table";
}
}
| 1,975 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SelectTopicIfNoClasses.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/selections/SelectTopicIfNoClasses.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/>.
*
*
* SelectTopicIfNoClasses.java
*
* Created on 14.7.2006, 11:57
*
*/
package org.wandora.application.tools.selections;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author akivela
*/
public class SelectTopicIfNoClasses extends DoTopicSelection {
private static final long serialVersionUID = 1L;
@Override
public boolean acceptTopic(Topic topic) {
try {
if(topic != null && !topic.isRemoved() && topic.getTypes().isEmpty()) return true;
return false;
}
catch(TopicMapException tme) {
log(tme);
return false;
}
}
@Override
public String getName() {
return "Select if topic has no classes.";
}
}
| 1,574 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
ClearSelection.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/selections/ClearSelection.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/>.
*
*
* ClearSelection.java
*
* Created on 12. huhtikuuta 2006, 10:22
*
*/
package org.wandora.application.tools.selections;
import java.awt.Component;
import javax.swing.Icon;
import javax.swing.JTable;
import javax.swing.text.JTextComponent;
import org.wandora.application.Wandora;
import org.wandora.application.gui.UIBox;
import org.wandora.application.gui.table.SITable;
import org.wandora.application.gui.table.TopicGrid;
import org.wandora.application.gui.table.TopicTable;
import org.wandora.application.gui.topicpanels.graphpanel.TopicMapGraphPanel;
import org.wandora.application.gui.topicpanels.graphpanel.VModel;
/**
* Class implements <code>WandoraAdminTool</code> used to clear current selection.
* In topic table context all selected cells are unselected and in text component
* context any text selections are cleared.
*
* @author akivela
*/
public class ClearSelection extends DoSelection {
private static final long serialVersionUID = 1L;
/** Creates a new instance of ClearSelection */
public ClearSelection() {
}
@Override
public void doTableSelection(Wandora admin, SITable siTable) {
siTable.clearSelection();
}
@Override
public void doTableSelection(Wandora admin, TopicTable table) {
table.clearSelection();
}
@Override
public void doGridSelection(Wandora wandora, TopicGrid grid) {
grid.clearSelection();
}
@Override
public void doGraphSelection(Wandora admin, TopicMapGraphPanel graph) {
if(graph != null) {
VModel model = graph.getModel();
if(model != null) {
model.deselectAll();
}
}
}
@Override
public void doOtherSelection(Wandora admin, Component component) {
if(component instanceof JTextComponent) {
JTextComponent tc = (JTextComponent) component;
tc.requestFocus();
tc.setSelectionEnd(0);
}
else if(component instanceof JTable) {
JTable jt = (JTable) component;
jt.requestFocus();
jt.clearSelection();
}
}
@Override
public String getName() {
return "Clear selection";
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/selection_clear.png");
}
}
| 3,181 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SelectTopicWithAssociationType.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/selections/SelectTopicWithAssociationType.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/>.
*
*
* SelectTopicWithAssociationType.java
*
* Created on 26.7.2006, 11:51
*
*/
package org.wandora.application.tools.selections;
import java.util.Collection;
import org.wandora.application.Wandora;
import org.wandora.application.contexts.Context;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
/**
* Tool selects topics in topic table if topic plays a role in association with
* given type. Tool lets user to select topics that have associations of certain
* type.
*
* @author akivela
*/
public class SelectTopicWithAssociationType extends DoTopicSelection {
private static final long serialVersionUID = 1L;
Topic type = null;
@Override
public void execute(Wandora wandora, Context context) {
try {
type = wandora.showTopicFinder("Select association type...");
if(type != null) {
super.execute(wandora, context);
}
}
catch(Exception e) {
log(e);
}
}
@Override
public boolean acceptTopic(Topic topic) {
try {
if(type != null) {
Collection<Association> a = topic.getAssociations(type);
if(a != null && a.size() > 0) return true;
}
}
catch(TopicMapException tme) {
log(tme);
}
return false;
}
@Override
public String getName() {
return "Select topics with association type";
}
@Override
public String getDescription() {
return "Select if topic has association of given type.";
}
}
| 2,486 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SelectRows.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/selections/SelectRows.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/>.
*
*
* SelectInTopicTableRows.java
*
* Created on 12. huhtikuuta 2006, 10:21
*
*/
package org.wandora.application.tools.selections;
import org.wandora.application.Wandora;
import org.wandora.application.gui.table.SITable;
import org.wandora.application.gui.table.TopicGrid;
import org.wandora.application.gui.table.TopicTable;
/**
* Selects current row of current topic table. Tool has no specified
* behavior in any other context at the moment.
*
* @author akivela
*/
public class SelectRows extends DoSelection {
private static final long serialVersionUID = 1L;
/** Creates a new instance of SelectRows */
public SelectRows() {
}
@Override
public void doTableSelection(Wandora wandora, SITable siTable) {
siTable.selectRows();
}
@Override
public void doTableSelection(Wandora admin, TopicTable table) {
table.selectRows();
}
@Override
public void doGridSelection(Wandora wandora, TopicGrid grid) {
grid.selectRows();
}
@Override
public String getName() {
return "Select rows in topic table";
}
}
| 1,943 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SelectTopicIfNoBasenames.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/selections/SelectTopicIfNoBasenames.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/>.
*
*
* SelectTopicIfNoBasenames.java
*
* Created on 14.7.2006, 12:14
*/
package org.wandora.application.tools.selections;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author akivela
*/
public class SelectTopicIfNoBasenames extends DoTopicSelection {
private static final long serialVersionUID = 1L;
@Override
public boolean acceptTopic(Topic topic) {
try {
if(topic != null && !topic.isRemoved() && topic.getBaseName() == null) return true;
return false;
}
catch(TopicMapException tme) {
log(tme);
return false;
}
}
@Override
public String getName() {
return "Select if topic has no basenames.";
}
}
| 1,579 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SelectTopicIfNoAI.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/selections/SelectTopicIfNoAI.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/>.
*
*
* SelectTopicIfNoAI.java
*
* Created on 14.7.2006, 12:05
*
*/
package org.wandora.application.tools.selections;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author akivela
*/
public class SelectTopicIfNoAI extends DoTopicSelection {
private static final long serialVersionUID = 1L;
@Override
public boolean acceptTopic(Topic topic) {
try{
if(topic != null && !topic.isRemoved() &&
topic.getAssociations().isEmpty() &&
topic.getTopicMap().getTopicsOfType(topic).isEmpty())
return true;
else
return false;
} catch(TopicMapException tme) {
log(tme);
return false;
}
}
@Override
public String getName() {
return "Select if topic has no associations and no instances.";
}
}
| 1,710 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SelectTopicIfNoAssociations.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/selections/SelectTopicIfNoAssociations.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/>.
*
*
* SelectTopicIfNoAssociations.java
*
* Created on 14.7.2006, 11:55
*
*/
package org.wandora.application.tools.selections;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author akivela
*/
public class SelectTopicIfNoAssociations extends DoTopicSelection {
private static final long serialVersionUID = 1L;
@Override
public boolean acceptTopic(Topic topic) {
try{
if(topic != null && !topic.isRemoved() && topic.getAssociations().isEmpty()) return true;
return false;
} catch(TopicMapException tme) {
log(tme);
return false;
}
}
@Override
public String getName() {
return "Select if topic has no associations.";
}
}
| 1,587 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SelectTopicIfNoInstances.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/selections/SelectTopicIfNoInstances.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/>.
*
*
* SelectTopicIfNoInstances.java
*
* Created on 14.7.2006, 12:00
*
*/
package org.wandora.application.tools.selections;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author akivela
*/
public class SelectTopicIfNoInstances extends DoTopicSelection {
private static final long serialVersionUID = 1L;
@Override
public boolean acceptTopic(Topic topic) {
try {
if(topic != null && !topic.isRemoved() && topic.getTopicMap().getTopicsOfType(topic).isEmpty()) return true;
return false;
}
catch(TopicMapException tme) {
log(tme);
return false;
}
}
@Override
public String getName() {
return "Select if topic has no instances.";
}
}
| 1,606 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
DoSelection.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/selections/DoSelection.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/>.
*
*
* SelectInTopicTable.java
*
* Created on 21. marraskuuta 2005, 19:50
*
*/
package org.wandora.application.tools.selections;
import java.awt.Component;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.table.SITable;
import org.wandora.application.gui.table.TopicGrid;
import org.wandora.application.gui.table.TopicTable;
import org.wandora.application.gui.topicpanels.GraphTopicPanel;
import org.wandora.application.gui.topicpanels.graphpanel.TopicMapGraphPanel;
import org.wandora.application.gui.tree.TopicTree;
import org.wandora.application.tools.AbstractWandoraTool;
/**
* Class implements a tool used to select cells in topic tables. Although
* class name refers only to topic tables tool can be used to make other type
* selections also. Tool execution flows to <code>doOtherSelection</code> if
* <code>contextSource</code> is not instance of <code>TopicTable</code>.
*
* @author akivela
*/
public class DoSelection extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
public DoSelection() {}
@Override
public void execute(Wandora wandora, Context context) {
try {
initializeTool();
SITable siTable = null;
TopicTable table = null;
TopicGrid grid = null;
TopicTree tree = null;
TopicMapGraphPanel graph = null;
Object contextSource = context.getContextSource();
if(contextSource instanceof SITable) {
siTable = (SITable) contextSource;
doTableSelection(wandora, siTable);
}
else if(contextSource instanceof TopicTable) {
table = (TopicTable) contextSource;
doTableSelection(wandora, table);
}
else if(contextSource instanceof TopicGrid) {
grid = (TopicGrid) contextSource;
doGridSelection(wandora, grid);
}
else if(contextSource instanceof TopicTree) {
tree = (TopicTree) contextSource;
doTreeSelection(wandora, tree);
}
else {
Component component = wandora.getFocusOwner();
if(component instanceof TopicTable) {
table = (TopicTable) component;
doTableSelection(wandora, table);
}
else if(component instanceof TopicTree) {
tree = (TopicTree) component;
doTreeSelection(wandora, tree);
}
else if(component instanceof GraphTopicPanel) {
graph = ((GraphTopicPanel) component).getGraphPanel();
doGraphSelection(wandora, graph);
}
else if(component instanceof TopicMapGraphPanel) {
graph = (TopicMapGraphPanel) component;
doGraphSelection(wandora, graph);
}
else if(component != null) {
doOtherSelection(wandora, component);
}
}
}
catch(Exception e) {
log(e);
}
}
public void doOtherSelection(Wandora wandora, Component component) {
}
public void doTableSelection(Wandora wandora, SITable siTable) {
log("Warning: doTableSelection call catched in DoSelection! You should overwrite this method in your own selection class!");
}
public void doTableSelection(Wandora wandora, TopicTable table) {
log("Warning: doTableSelection call catched in DoSelection! You should overwrite this method in your own selection class!");
}
public void doGraphSelection(Wandora wandora, TopicMapGraphPanel graph) {
log("Warning: doGraphSelection call catched in DoSelection! You should overwrite this method in your own selection class!");
}
public void doGridSelection(Wandora wandora, TopicGrid grid) {
log("Warning: doGridSelection call catched in DoSelection! You should overwrite this method in your own selection class!");
}
public void doTreeSelection(Wandora wandora, TopicTree tree) {
log("Topic tree doesn't support chosen selection option. "+
"Please, select topic table type of element and try again.");
}
@Override
public String getName() {
return "Make selections (abstract class)";
}
public void initializeTool() {
// OVERWRITE IF INITIALIZATION IS REQUIRED!!!
}
@Override
public boolean requiresRefresh() {
return false;
}
}
| 5,607 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SelectTopicWithClipboardRegex.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/selections/SelectTopicWithClipboardRegex.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/>.
*
*
* SelectTopicWithClipboardRegex.java
*
* Created on 14.7.2006, 12:18
*
*/
package org.wandora.application.tools.selections;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
import org.wandora.utils.ClipboardBox;
/**
* Tool selects topics in topic table. Topic is selected if clipboard contains
* regular expression that matches topic's subject identifier, base name or subject
* locator. Clipboard may contain multiple regular expressions separated with
* newline character. Depending on parameters given in tool construction tool
* selects full matches (regular expression must match full identifier) or
* partial matches (if regular expression matches any part of the identifier).
*
* Tool uses Java's native regular expressions. See <code>String</code> and
* <code>Pattern</code> classes for more details.
*
* @author akivela
*/
public class SelectTopicWithClipboardRegex extends DoTopicSelection {
private static final long serialVersionUID = 1L;
Pattern[] patterns = null;
Pattern pattern = null;
String[] regexes = null;
String regex = null;
Iterator<Locator> sis = null;
Locator si = null;
String identifier = null;
Matcher m = null;
boolean fullMatch = true;
public SelectTopicWithClipboardRegex() {
this.fullMatch = true;
}
public SelectTopicWithClipboardRegex(boolean fullMatch) {
this.fullMatch = fullMatch;
}
@Override
public void initializeTool() {
regex = ClipboardBox.getClipboard();
if(regex != null) {
if(regex.indexOf("\n") != -1) {
regexes = regex.split("\r*\n\r*");
for(int i=0; i<regexes.length; i++) {
regexes[i] = regexes[i].trim();
patterns[i] = Pattern.compile(regexes[i]);
}
}
else {
regexes = new String[] { regex };
patterns = new Pattern[] { Pattern.compile(regex) };
}
}
}
@Override
public boolean acceptTopic(Topic topic) {
try {
if(patterns != null && patterns.length > 0 && topic != null && !topic.isRemoved()) {
for(int i=0; i<patterns.length; i++) {
pattern = patterns[i];
if(pattern != null) {
if(matches(pattern, topic.getSubjectLocator())) return true;
if(matches(pattern, topic.getBaseName())) return true;
sis = topic.getSubjectIdentifiers().iterator();
while(sis.hasNext()) {
si = sis.next();
if(matches(pattern, si)) return true;
}
}
}
}
}
catch(TopicMapException tme) {
log(tme);
}
return false;
}
public boolean matches(Pattern pattern, Locator locator) {
if(locator != null) {
return matches(pattern, locator.toExternalForm());
}
return false;
}
public boolean matches(Pattern pattern, String str) {
if(str != null && str.length() > 0 && pattern != null) {
m = pattern.matcher(str);
if(fullMatch) {
return m.matches();
}
else {
return m.find();
}
}
return false;
}
@Override
public String getName() {
return "Select topic with clipboard";
}
@Override
public String getDescription() {
return "Select topic if clipboard contains topic's subject locator, base name or subject identifier.";
}
}
| 4,757 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SelectTopicWithClipboard.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/selections/SelectTopicWithClipboard.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/>.
*
*
* SelectTopicWithClipboard.java
*
* Created on 14.7.2006, 12:18
*
*/
package org.wandora.application.tools.selections;
import java.util.Iterator;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
import org.wandora.utils.ClipboardBox;
/**
* Class implements a tool used to select topics in topic table. Topic is
* selected if clipboard contains topic's subject identifier, subject locator
* or base name. Clipboard may contain multiple identifiers separated with
* newline character.
*
* @author akivela
*/
public class SelectTopicWithClipboard extends DoTopicSelection {
private static final long serialVersionUID = 1L;
String[] identifiers = null;
String identifier = null;
Iterator<Locator> sis = null;
Locator si = null;
@Override
public void initializeTool() {
identifier = ClipboardBox.getClipboard();
if(identifier != null) {
if(identifier.indexOf("\n") != -1) {
identifiers = identifier.split("\r*\n\r*");
for(int i=0; i<identifiers.length; i++) {
identifiers[i] = identifiers[i].trim();
}
}
else {
identifiers = new String[] { identifier };
}
}
}
@Override
public boolean acceptTopic(Topic topic) {
try {
if(identifiers != null && identifiers.length > 0 && topic != null && !topic.isRemoved()) {
for(int i=0; i<identifiers.length; i++) {
identifier = identifiers[i];
if(identifier != null || identifier.length() > 0) {
if(topic.getSubjectLocator() != null) {
if(identifier.equals(topic.getSubjectLocator().toExternalForm())) return true;
}
if(identifier.equals(topic.getBaseName())) return true;
sis = topic.getSubjectIdentifiers().iterator();
while(sis.hasNext()) {
si = sis.next();
if(si != null) {
if(identifier.equals(si.toExternalForm())) return true;
}
}
}
}
}
}
catch(TopicMapException tme) {
log(tme);
}
return false;
}
@Override
public String getName() {
return "Select topics with clipboard";
}
@Override
public String getDescription() {
return "Select topic if clipboard contains topic's subject locator, base name or subject identifier.";
}
}
| 3,599 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SelectTopicIfSL.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/selections/SelectTopicIfSL.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/>.
*
*
* SelectTopicIfSL.java
*
* Created on 12. huhtikuuta 2006, 10:53
*
*/
package org.wandora.application.tools.selections;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
/**
* This tool is an example of topic table selection tools where selection
* is carried out using topics in table cells ie. the cell is selected if
* the topic in the cell is accepted by <code>acceptCell</code> method.
*
* Tool selects topic table cell if topic contains subject locator. Otherwise
* cell is unselected.
*
* @author akivela
*/
public class SelectTopicIfSL extends DoTopicSelection {
private static final long serialVersionUID = 1L;
@Override
public boolean acceptTopic(Topic topic) {
try {
if(topic == null || topic.isRemoved()) return false;
Locator SL = topic.getSubjectLocator();
if(SL != null && SL.toExternalForm().length() > 0) return true;
return false;
} catch(TopicMapException tme) {
log(tme);
return false;
}
}
@Override
public String getName() {
return "Select topics with SL";
}
}
| 2,022 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
UndoRedoOptions.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/undoredo/UndoRedoOptions.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.undoredo;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JDialog;
import org.wandora.application.Wandora;
import org.wandora.application.gui.UIBox;
import org.wandora.application.gui.WandoraOptionPane;
import org.wandora.application.gui.simple.SimpleButton;
import org.wandora.application.gui.table.OperationTable;
import org.wandora.topicmap.layered.LayerStack;
import org.wandora.topicmap.undowrapper.UndoOperation;
/**
*
* @author akivela
*/
public class UndoRedoOptions extends javax.swing.JPanel {
private static final long serialVersionUID = 1L;
private Wandora wandora = null;
private JDialog dialog = null;
/**
* Creates new form UndoRedoOptions
*/
public UndoRedoOptions() {
initComponents();
}
public void open(Wandora w) {
wandora = w;
initializeOperationTable();
dialog = new JDialog(w, true);
dialog.setSize(800, 400);
dialog.add(this);
dialog.setTitle("Undo buffer and options");
UIBox.centerWindow(dialog, w);
dialog.setVisible(true);
}
private void initializeOperationTable() {
if(wandora == null) return;
LayerStack ltm = wandora.getTopicMap();
List<UndoOperation> ops = ltm.getUndoOperations();
((OperationTable) operationTable).initialize(ops);
if(ops == null || ops.isEmpty()) {
tableScrollPane.setVisible(false);
noopsLabel.setVisible(true);
}
else {
tableScrollPane.setVisible(true);
noopsLabel.setVisible(false);
}
}
// -------------------------------------------------------------------------
/**
* 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;
headerPanel = new javax.swing.JPanel();
tablePanel = new javax.swing.JPanel();
tableScrollPane = new javax.swing.JScrollPane();
operationTable = new OperationTable();
noopsLabel = new javax.swing.JLabel();
buttonPanel = new javax.swing.JPanel();
undoButtonPanel = new javax.swing.JPanel();
undoButton = new SimpleButton();
redoButton = new SimpleButton();
buttonFillerPanel = new javax.swing.JPanel();
rightButtonPanel = new javax.swing.JPanel();
clearUndoBuffers = new SimpleButton();
closeButton = new SimpleButton();
setLayout(new java.awt.GridBagLayout());
headerPanel.setLayout(new java.awt.GridBagLayout());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
add(headerPanel, gridBagConstraints);
tablePanel.setLayout(new java.awt.GridBagLayout());
operationTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
tableScrollPane.setViewportView(operationTable);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
tablePanel.add(tableScrollPane, gridBagConstraints);
noopsLabel.setText("No undo operations available");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL;
gridBagConstraints.weighty = 1.0;
tablePanel.add(noopsLabel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(tablePanel, gridBagConstraints);
buttonPanel.setLayout(new java.awt.GridBagLayout());
undoButtonPanel.setLayout(new java.awt.GridBagLayout());
undoButton.setText("Undo");
undoButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
undoButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 2);
undoButtonPanel.add(undoButton, gridBagConstraints);
redoButton.setText("Redo");
redoButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
redoButtonActionPerformed(evt);
}
});
undoButtonPanel.add(redoButton, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2);
buttonPanel.add(undoButtonPanel, gridBagConstraints);
buttonFillerPanel.setLayout(new java.awt.GridBagLayout());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
buttonPanel.add(buttonFillerPanel, gridBagConstraints);
rightButtonPanel.setLayout(new java.awt.GridBagLayout());
clearUndoBuffers.setText("Clear undo buffer");
clearUndoBuffers.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
clearUndoBuffersActionPerformed(evt);
}
});
rightButtonPanel.add(clearUndoBuffers, new java.awt.GridBagConstraints());
closeButton.setText("Close");
closeButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
closeButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 0);
rightButtonPanel.add(closeButton, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2);
buttonPanel.add(rightButtonPanel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
add(buttonPanel, gridBagConstraints);
}// </editor-fold>//GEN-END:initComponents
private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeButtonActionPerformed
if(dialog != null) dialog.setVisible(false);
}//GEN-LAST:event_closeButtonActionPerformed
private void clearUndoBuffersActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearUndoBuffersActionPerformed
if(wandora != null) wandora.clearUndoBuffers();
initializeOperationTable();
}//GEN-LAST:event_clearUndoBuffersActionPerformed
private void undoButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_undoButtonActionPerformed
if(wandora != null) {
try {
wandora.undo();
}
catch(Exception e) {
//e.printStackTrace();
WandoraOptionPane.showMessageDialog(wandora, e.getMessage(), "Undo exception");
}
wandora.doRefresh();
}
initializeOperationTable();
}//GEN-LAST:event_undoButtonActionPerformed
private void redoButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_redoButtonActionPerformed
if(wandora != null) {
try {
wandora.redo();
}
catch(Exception e) {
//e.printStackTrace();
WandoraOptionPane.showMessageDialog(wandora, e.getMessage(), "Redo exception");
}
wandora.doRefresh();
}
initializeOperationTable();
}//GEN-LAST:event_redoButtonActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel buttonFillerPanel;
private javax.swing.JPanel buttonPanel;
private javax.swing.JButton clearUndoBuffers;
private javax.swing.JButton closeButton;
private javax.swing.JPanel headerPanel;
private javax.swing.JLabel noopsLabel;
private javax.swing.JTable operationTable;
private javax.swing.JButton redoButton;
private javax.swing.JPanel rightButtonPanel;
private javax.swing.JPanel tablePanel;
private javax.swing.JScrollPane tableScrollPane;
private javax.swing.JButton undoButton;
private javax.swing.JPanel undoButtonPanel;
// End of variables declaration//GEN-END:variables
}
| 10,558 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
Redo.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/undoredo/Redo.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.undoredo;
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.tools.AbstractWandoraTool;
import org.wandora.topicmap.TopicMapException;
import org.wandora.topicmap.undowrapper.UndoException;
/**
*
* @author olli
*/
public class Redo extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/undo_redo.png");
}
@Override
public String getName() {
return "Redo";
}
@Override
public String getDescription() {
return "Redo next topic map operation.";
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
if(wandora != null) {
try {
wandora.redo();
}
catch(UndoException ue) {
if(ue.getMessage() != null) {
WandoraOptionPane.showMessageDialog(wandora,
ue.getMessage()+" In order to redo you need to undo something first.",
ue.getMessage());
}
else {
ue.printStackTrace();
WandoraOptionPane.showMessageDialog(wandora,
"Redo exception occurred. In order to redo you need to undo something first.",
"Redo exception occurred");
}
}
catch(Exception e) {
log(e);
}
}
}
// -------------------------------------------------------------------------
@Override
public void initialize(Wandora wandora,org.wandora.utils.Options options,String prefix) throws TopicMapException {
}
@Override
public boolean isConfigurable(){
return true;
}
@Override
public void configure(Wandora wandora,org.wandora.utils.Options options,String prefix) throws TopicMapException {
//System.out.println(prefix);
UndoRedoOptions dialog=new UndoRedoOptions();
dialog.open(wandora);
}
@Override
public void writeOptions(Wandora wandora,org.wandora.utils.Options options,String prefix){
}
// -------------------------------------------------------------------------
}
| 3,434 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
Undo.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/undoredo/Undo.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.undoredo;
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.tools.AbstractWandoraTool;
import org.wandora.topicmap.TopicMapException;
import org.wandora.topicmap.undowrapper.UndoException;
/**
*
* @author olli
*/
public class Undo extends AbstractWandoraTool implements WandoraTool{
private static final long serialVersionUID = 1L;
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/undo_undo.png");
}
@Override
public String getName() {
return "Undo";
}
@Override
public String getDescription() {
return "Undo previous topic map operation.";
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
if(wandora != null) {
try {
wandora.undo();
}
catch(UndoException ue) {
if(ue.getMessage() != null) {
WandoraOptionPane.showMessageDialog(wandora,
ue.getMessage()+" Undo covers topic map operations only. In order to undo you need to change topic maps, topics or associations.",
ue.getMessage());
}
else {
ue.printStackTrace();
WandoraOptionPane.showMessageDialog(wandora,
"Undo exception occurred. In order to undo you need to change topic maps, topics or associations.",
"Undo exception occurred");
}
}
catch(Exception e) {
log(e);
}
}
}
// -------------------------------------------------------------------------
@Override
public void initialize(Wandora wandora,org.wandora.utils.Options options,String prefix) throws TopicMapException {
}
@Override
public boolean isConfigurable(){
return true;
}
@Override
public void configure(Wandora wandora,org.wandora.utils.Options options,String prefix) throws TopicMapException {
//System.out.println(prefix);
UndoRedoOptions dialog=new UndoRedoOptions();
dialog.open(wandora);
}
@Override
public void writeOptions(Wandora wandora,org.wandora.utils.Options options,String prefix){
}
// -------------------------------------------------------------------------
}
| 3,527 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
ClearUndoBuffers.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/undoredo/ClearUndoBuffers.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.undoredo;
import javax.swing.Icon;
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.TopicMapException;
/**
*
* @author akivela
*/
public class ClearUndoBuffers extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
@Override
public Icon getIcon() {
return super.getIcon();
}
@Override
public String getName() {
return "Clear undo buffers";
}
@Override
public String getDescription() {
return "Clear undo buffers";
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
if(wandora != null) {
wandora.clearUndoBuffers();
}
}
}
| 1,739 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
MediawikiUploaderConfiguration.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/mediawiki/MediawikiUploaderConfiguration.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.mediawiki;
import java.net.URL;
/**
*
* @author nlaitine
*/
public class MediawikiUploaderConfiguration {
private String wikiUrl = null;
private String wikiUser = null;
private String wikiPasswd = null;
private URL wikiFileUrl = null;
private String wikiFilename = null;
private String wikiFileExtension = null;
private String wikiDescription = null;
private boolean wikiStream = false;
public MediawikiUploaderConfiguration() { }
public boolean setWikiUrl(String wikiUrl) {
this.wikiUrl = wikiUrl;
return true;
}
public String getWikiUrl() {
return wikiUrl;
}
public boolean setWikiUser(String wikiUser) {
this.wikiUser = wikiUser;
return true;
}
public String getWikiUser() {
return wikiUser;
}
public boolean setWikiPasswd(String wikiPasswd) {
this.wikiPasswd = wikiPasswd;
return true;
}
public String getWikiPasswd() {
return wikiPasswd;
}
public boolean setWikiFileUrl(URL wikiFileUrl) {
this.wikiFileUrl = wikiFileUrl;
return true;
}
public URL getWikiFileUrl() {
return wikiFileUrl;
}
public boolean setWikiFilename(String wikiFilename) {
this.wikiFilename = wikiFilename;
return true;
}
public String getWikiFilename() {
return wikiFilename;
}
public boolean setWikiFileExtension(String fileExtension) {
this.wikiFileExtension = fileExtension;
return true;
}
public String getWikiFileExtension() {
return this.wikiFileExtension;
}
public boolean setWikiDescription(String wikiDescription) {
this.wikiDescription = wikiDescription;
return true;
}
public String getWikiDescription() {
return wikiDescription;
}
public boolean setWikiStream(boolean wikiStream) {
this.wikiStream = wikiStream;
return true;
}
public boolean getWikiStream() {
return wikiStream;
}
}
| 2,957 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
MediawikiHandler.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/mediawiki/MediawikiHandler.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.mediawiki;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.wandora.application.Wandora;
import org.wandora.application.tools.AbstractWandoraTool;
import org.wandora.utils.IObox;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
*
* @author nlaitine
*/
public abstract class MediawikiHandler extends AbstractWandoraTool {
private static final long serialVersionUID = 1L;
private static boolean logged = false;
private HashMap<String, String> cookies = new HashMap<String, String>(12);
private static final String VERSION = "1.0";
private static final String USER_AGENT = "MediawikiHandler " + VERSION;
//Time to open a connection
private static final int CONNECTION_CONNECT_TIMEOUT_MSEC = 30000; // 30 seconds
private static final int CONNECTION_READ_TIMEOUT_MSEC = 180000; // 180 seconds
public MediawikiHandler() {};
public boolean callWiki(String apiWikiUrl, URL fileUrl, String filename, String description, boolean stream) {
boolean success = false;
if(logged) {
String response = null;
String uploadResult = null;
if(!stream) {
uploadResult = uploadToWiki(apiWikiUrl, fileUrl, filename, description);
} else {
uploadResult = uploadStreamToWiki(apiWikiUrl, fileUrl, filename, description);
}
if(uploadResult.contains("result=\"Success\"")) {
log("Successfully uploaded to Mediawiki.");
response = getResponseMessage(uploadResult, "upload");
log("Server response: " + response);
success = true;
} else {
log("Uploading failed.");
response = getResponseMessage(uploadResult, "upload");
log("Server response: " + response);
}
} else {
log("Not logged in.");
}
return success;
}
private String getResponseMessage(String xml, String caller) {
String reply = null;
String error = "error";
String info = "info";
String node = null;
String attribute = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = null;
if(caller.equals("login")) {
node = "login";
attribute = "result";
} else if(caller.equals("logintoken")) {
node = "login";
attribute = "token";
} else if(caller.equals("edittoken")) {
node = "tokens";
attribute = "edittoken";
} else if (caller.equals("upload")) {
node = "upload";
attribute = "result";
}
try {
db = dbf.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xml));
Document doc = null;
try {
doc = db.parse(is);
Element docRoot = doc.getDocumentElement();
NodeList errors = docRoot.getElementsByTagName(error);
NodeList nodes = docRoot.getElementsByTagName(node);
for( int i = 0; i < errors.getLength(); i++ ) {
Element element = (Element) errors.item(i);
reply = element.getAttributes().getNamedItem(info).getNodeValue();
}
for( int i = 0; i < nodes.getLength(); i++ ) {
Element element = (Element) nodes.item(i);
reply = element.getAttributes().getNamedItem(attribute).getNodeValue();
}
} catch (SAXException e) {
return "SAXException: Error reading server reply.";
} catch (IOException e) {
return "IOException: Error reading server reply.";
}
} catch (ParserConfigurationException e) {
return "ParserConfigurationException: Error reading server reply.";
}
return reply;
}
// -------------------------------------------------------------------------
/*
* Wiki session handling
*/
private String getLoginToken(String apiUrl, String apiUser, String apiPass) {
StringBuilder data = new StringBuilder("");
String token = null;
String reply = null;
String tokenUrl = apiUrl + "/api.php";
apiUser = encode(apiUser);
apiPass = encode(apiPass);
data.append("action=login");
data.append("&lgname=").append(apiUser);
data.append("&lgpassword=").append(apiPass);
data.append("&format=xml");
//log("Getting Login token...");
//log(tokenUrl + "?" + data.toString());
try {
reply = sendRequest(new URL(tokenUrl), data.toString(), "application/x-www-form-urlencoded", "POST");
token = getResponseMessage(reply, "logintoken");
} catch (Exception e) {
log("Login token error: " + e.getMessage());
}
return token;
}
private String getEditToken(String apiUrl) {
String token = null;
String reply = null;
String tokenUrl = apiUrl + "/api.php?action=tokens&format=xml";
//log("Getting Edit token...");
//log(tokenUrl);
try {
reply = sendRequest(new URL(tokenUrl), null, "application/x-www-form-urlencoded", "POST");
token = getResponseMessage(reply, "edittoken");
} catch (Exception e) {
log("Edit token error: " + e.getMessage());
}
return token;
}
public boolean login(String apiWikiUploadUrl, String apiUserName, String apiPasswd) {
if(!logged) {
StringBuilder data = new StringBuilder("");
String apiLoginToken = getLoginToken(apiWikiUploadUrl, apiUserName, apiPasswd);
//Encode parameters
String apiBase = apiWikiUploadUrl + "/api.php";
apiUserName = encode(apiUserName);
apiPasswd = encode(apiPasswd);
apiLoginToken = encode(apiLoginToken);
//Login to wiki
data.append("action=login");
if(apiUserName != null && apiUserName.length() > 0) data.append("&lgname=").append(apiUserName);
if(apiPasswd != null && apiPasswd.length() > 0) data.append("&lgpassword=").append(apiPasswd);
if(apiLoginToken != null && apiLoginToken.length() > 0) data.append("&lgtoken=").append(apiLoginToken);
data.append("&format=xml");
log("Logging in...");
log(apiBase + "?" + data.toString());
try {
String reply = sendRequest(new URL(apiBase), data.toString(), "application/x-www-form-urlencoded", "POST");
if(reply.contains("result=\"Success\"")) {
logged = true;
} else {
String error = getResponseMessage(reply, "login");
log("Bad login request: " + error);
}
}
catch(Exception e) {
log("Login error: " + e.getMessage());
}
}
return logged;
}
public boolean logout(String wikiUrl) {
if(logged) {
String logoutUrl = wikiUrl + "/api.php?action=logout";
try {
sendRequest(new URL(logoutUrl), null, "text/html", "GET");
cookies.clear();
logged = false;
log("Logged out.");
} catch (Exception e) {
log(e.getMessage());
return false;
}
}
return !logged;
}
/*
* Cookie handling
*/
private boolean setCookies(URLConnection con) {
StringBuilder cookie = new StringBuilder(100);
for (Map.Entry<String, String> entry : cookies.entrySet()) {
cookie.append(entry.getKey());
cookie.append("=");
cookie.append(entry.getValue());
cookie.append("; ");
}
con.setRequestProperty("Cookie", cookie.toString());
con.setRequestProperty("User-Agent", USER_AGENT);
return true;
}
private boolean grabCookies(URLConnection u) {
String headerName;
for (int i = 1; (headerName = u.getHeaderFieldKey(i)) != null; i++) {
if (headerName.equals("Set-Cookie")) {
String cookie = u.getHeaderField(i);
cookie = cookie.substring(0, cookie.indexOf(';'));
String name = cookie.substring(0, cookie.indexOf('='));
String value = cookie.substring(cookie.indexOf('=') + 1, cookie.length());
cookies.put(name, value);
}
}
return true;
}
/*
* Wiki operations
*/
public String uploadToWiki(String apiWikiUploadUrl, URL apiOccurranceUrl, String apiOccurranceFilename, String apiOccurranceDescription) {
StringBuilder data = new StringBuilder("");
String reply = null;
String apiFilename = null;
String apiFileUrl = null;
String apiDescription = null;
String apiEditToken = null;
//Get file Url String
apiFileUrl = apiOccurranceUrl.toString();
//Get edit token
apiEditToken = getEditToken(apiWikiUploadUrl);
//Encode parameters
String apiBaseUrl = apiWikiUploadUrl + "/api.php";
apiFilename = encode(apiOccurranceFilename);
apiFileUrl = encode(apiFileUrl);
apiDescription = encode(apiOccurranceDescription);
apiEditToken = encode(apiEditToken);
//Upload content to wiki
data.append("action=upload");
if(apiFilename != null && apiFilename.length() > 0) data.append("&filename=").append(apiFilename);
if(apiFileUrl != null && apiFileUrl.length() > 0) data.append("&url=").append(apiFileUrl);
if(apiDescription != null && apiDescription.length() > 0) data.append("&comment=").append(apiDescription);
if(apiEditToken != null && apiEditToken.length() > 0) data.append("&token=").append(apiEditToken);
data.append("&format=xml");
log("Uploading " + apiFilename + "...");
log(apiBaseUrl + "?" + data.toString());
try {
reply = sendRequest(new URL(apiBaseUrl), data.toString(), "application/x-www-form-urlencoded", "POST");
}
catch(Exception e) {
log("Uploading error: " + e.getMessage());
}
return reply;
}
public String uploadStreamToWiki(String apiWikiUploadUrl, URL apiOccurranceUrl, String apiOccurranceFilename, String apiOccurranceDescription) {
String reply = null;
String apiFilename = null;
String apiDescription = null;
String apiEditToken = null;
byte[] apiFile = null;
String apiBaseUrl = apiWikiUploadUrl + "/api.php";
try {
//Get file
apiFile = getFileBytes(apiOccurranceUrl);
//Get filename
apiFilename = apiOccurranceFilename;
//Get description
apiDescription = apiOccurranceDescription;
//Get edit token
apiEditToken = getEditToken(apiWikiUploadUrl);
//Set parameters
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("action", "upload");
params.put("format", "xml");
params.put("ignorewarnings", "true");
if(apiFilename != null && apiFilename.length() > 0) params.put("filename", apiFilename);
if(apiDescription != null && apiDescription.length() > 0) params.put("comment", apiDescription);
if(apiEditToken != null && apiEditToken.length() > 0) params.put("token", apiEditToken);
if(apiFile != null) params.put("file\"; filename=\"" + apiFilename, apiFile);
log("Uploading " + apiFilename + "...");
log(apiBaseUrl + "?action=" + params.get("action") +
"&format=" + params.get("format") +
"&ignorewarnings=" + params.get("ignorewarnings") +
"&filename=" + params.get("filename") +
"&description=" + params.get("description") +
"&token=" + params.get("token"));
//Set up connection
URLConnection connection = null;
connection = new URL(apiBaseUrl).openConnection();
String boundary = "----------NEXT PART----------";
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
setCookies(connection);
connection.setDoOutput(true);
connection.setConnectTimeout(CONNECTION_CONNECT_TIMEOUT_MSEC);
connection.setReadTimeout(CONNECTION_READ_TIMEOUT_MSEC);
connection.connect();
boundary = "--" + boundary + "\r\n";
//Write to buffer
ByteArrayOutputStream bout = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(bout);
out.writeBytes(boundary);
//Write params
for (Map.Entry<String, Object> entry : params.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
out.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"\r\n");
if (value instanceof String) {
out.writeBytes("Content-Type: text/plain; charset=UTF-8\r\n\r\n");
out.write(((String) value).getBytes("UTF-8"));
} else if (value instanceof byte[]) {
out.writeBytes("Content-Type: application/octet-stream\r\n\r\n");
out.write((byte[]) value);
} else {
throw new UnsupportedOperationException("Unrecognized data type");
}
out.writeBytes("\r\n");
out.writeBytes(boundary);
}
out.writeBytes("--\r\n");
out.close();
// write the buffer to the URLConnection
OutputStream uout = connection.getOutputStream();
uout.write(bout.toByteArray());
uout.close();
//Read response
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
grabCookies(connection);
String line;
StringBuilder temp = new StringBuilder(100000);
while ((line = in.readLine()) != null) {
temp.append(line);
temp.append("\n");
}
in.close();
reply = temp.toString();
} catch (Exception e) {
log("Uploading Stream error: " + e.getMessage());
}
return reply;
}
/*
* Remote file operations
*/
private byte[] getFileBytes(URL fileUrl) {
byte[] file = null;
String scheme = fileUrl.getProtocol();
String host = fileUrl.getHost();
if ("file".equalsIgnoreCase(scheme) && (host == null || "".equals(host)) ) {
try {
Path path = Paths.get(fileUrl.toURI());
file = Files.readAllBytes(path);
} catch (Exception e) {
log(e.getMessage());
}
} else {
try {
file = IObox.fetchUrl(fileUrl);
} catch (Exception e) {
log(e.getMessage());
}
}
return file;
}
/*
* Helper methods
*/
private String encode(String str) {
try {
return URLEncoder.encode(str, "utf-8");
}
catch(Exception e) {
// PASS
}
return str;
}
private String sendRequest(URL url, String data, String ctype, String method) throws IOException {
StringBuilder sb = new StringBuilder(1000);
if (url != null) {
URLConnection con = url.openConnection();
setCookies(con);
Wandora.initUrlConnection(con);
con.setDoInput(true);
con.setUseCaches(false);
if(method != null && con instanceof HttpURLConnection) {
((HttpURLConnection) con).setRequestMethod(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();
}
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
grabCookies(con);
String s;
while ((s = in.readLine()) != null) {
sb.append(s);
}
in.close();
}
return sb.toString();
}
public boolean isValidResourceReference(String str) {
if(str == null) return false;
if(str.length() == 0) return false;
try {
URL u = new URL(str);
if(u != null) return true;
}
catch(Exception e) {}
try {
File f = new File(str);
if(f != null && f.exists()) return true;
}
catch(Exception e) {}
return false;
}
}
| 19,834 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
MediawikiUploaderConfigurationUI.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/mediawiki/MediawikiUploaderConfigurationUI.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/>.
*
*
* MediawikiConfigurationUI.java
*
* Created on 2013-04-25
*
*/
package org.wandora.application.tools.mediawiki;
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;
import org.wandora.topicmap.Topic;
/**
*
* @author nlaitine
*/
public class MediawikiUploaderConfigurationUI extends javax.swing.JPanel {
private static final long serialVersionUID = 1L;
private JDialog myDialog = null;
private boolean accepted = false;
/**
* Creates new form MediawikiUploaderConfiguration
*/
public MediawikiUploaderConfigurationUI() {
initComponents();
}
public void open(Wandora wandora, WandoraTool t) {
myDialog = new JDialog(wandora, true);
myDialog.add(this);
myDialog.setTitle("Mediawiki uploader options");
myDialog.setSize(500, 240);
accepted = false;
if(wandora != null) wandora.centerWindow(myDialog);
myDialog.setVisible(true);
}
// -------------------------------------------------------------------------
public boolean wasAccepted() {
return accepted;
}
public String getWikiUrl() {
return wikiUrlTextField.getText();
}
public String getUser() {
return usernameTextField.getText();
}
public String getPasswd() {
return passwordTextField.getText();
}
public String getFilename() {
return filenameTextField.getText();
}
public boolean setFilename(String name) {
filenameTextField.setText(name);
return true;
}
public boolean showFilename() {
filenameLabel.setVisible(true);
filenameTextField.setVisible(true);
return true;
}
public boolean hideFilename() {
filenameLabel.setVisible(false);
filenameTextField.setVisible(false);
return true;
}
public Object getDescriptionType() {
return descriptionComboBox.getSelectedItem();
}
public boolean addDescriptionTypeItem(String item) {
descriptionComboBox.addItem(item);
return true;
}
public boolean addDescriptionTypeItem(Topic item) {
descriptionComboBox.addItem(item);
return true;
}
public boolean resetDescriptionTypeItems() {
descriptionComboBox.removeAllItems();
descriptionComboBox.setEnabled(false);
return true;
}
public boolean enableDescriptionType() {
descriptionComboBox.setEnabled(true);
return true;
}
public boolean showDescription() {
descriptionLabel.setVisible(true);
descriptionComboBox.setVisible(true);
return true;
}
public boolean hideDescription() {
descriptionLabel.setVisible(false);
descriptionComboBox.setVisible(false);
return true;
}
public String getFileExtension() {
return fileExtensionTextField.getText();
}
public boolean showFileExtension() {
fileExtensionLabel.setVisible(true);
fileExtensionTextField.setVisible(true);
return true;
}
public boolean hideFileExtension() {
fileExtensionLabel.setVisible(false);
fileExtensionTextField.setVisible(false);
return true;
}
public boolean getStream() {
return streamCheckBox.isSelected();
}
// -------------------------------------------------------------------------
/**
* 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;
configPanel = new javax.swing.JPanel();
wikiUrlLabel = new SimpleLabel();
wikiUrlTextField = new SimpleField();
usernameLabel = new SimpleLabel();
usernameTextField = new SimpleField();
passwordLabel = new SimpleLabel();
passwordTextField = new SimpleField();
filenameLabel = new SimpleLabel();
filenameTextField = new SimpleField();
descriptionLabel = new SimpleLabel();
descriptionComboBox = new SimpleComboBox();
streamLabel = new SimpleLabel();
streamCheckBox = new SimpleCheckBox();
fileExtensionLabel = new SimpleLabel();
fileExtensionTextField = new SimpleField();
buttonPanel = new javax.swing.JPanel();
FillerjPanel = new javax.swing.JPanel();
okButton = new SimpleButton();
cancelButton = new SimpleButton();
setMaximumSize(new java.awt.Dimension(394, 220));
setMinimumSize(new java.awt.Dimension(394, 220));
setPreferredSize(new java.awt.Dimension(394, 220));
setLayout(new java.awt.GridBagLayout());
configPanel.setMaximumSize(new java.awt.Dimension(374, 150));
configPanel.setMinimumSize(new java.awt.Dimension(374, 150));
configPanel.setName(""); // NOI18N
configPanel.setPreferredSize(new java.awt.Dimension(374, 150));
configPanel.setLayout(new java.awt.GridBagLayout());
wikiUrlLabel.setText("Mediawiki URL");
wikiUrlLabel.setToolTipText("Mediawiki URL is a base address of the Mediawiki installation where resource will be uploaded.");
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);
configPanel.add(wikiUrlLabel, gridBagConstraints);
wikiUrlTextField.setMaximumSize(new java.awt.Dimension(290, 20000));
wikiUrlTextField.setMinimumSize(new java.awt.Dimension(290, 20));
wikiUrlTextField.setPreferredSize(new java.awt.Dimension(290, 20));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 4, 0);
configPanel.add(wikiUrlTextField, gridBagConstraints);
usernameLabel.setText("Username");
usernameLabel.setToolTipText("Username is used to login the Mediawiki. Uploading resource to the Mediawiki requires a valid username.");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4);
configPanel.add(usernameLabel, gridBagConstraints);
usernameTextField.setMaximumSize(new java.awt.Dimension(90, 20));
usernameTextField.setMinimumSize(new java.awt.Dimension(90, 20));
usernameTextField.setPreferredSize(new java.awt.Dimension(90, 20));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 4, 0);
configPanel.add(usernameTextField, gridBagConstraints);
passwordLabel.setText("Password");
passwordLabel.setToolTipText("Password is used to login the Mediawiki.");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4);
configPanel.add(passwordLabel, gridBagConstraints);
passwordTextField.setMaximumSize(new java.awt.Dimension(90, 20));
passwordTextField.setMinimumSize(new java.awt.Dimension(90, 20));
passwordTextField.setPreferredSize(new java.awt.Dimension(90, 20));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 4, 0);
configPanel.add(passwordTextField, gridBagConstraints);
filenameLabel.setText("Filename");
filenameLabel.setToolTipText("Filename is a name of the resource in Mediawiki.");
filenameLabel.setMaximumSize(null);
filenameLabel.setMinimumSize(null);
filenameLabel.setPreferredSize(null);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4);
configPanel.add(filenameLabel, gridBagConstraints);
filenameTextField.setMaximumSize(new java.awt.Dimension(240, 20));
filenameTextField.setMinimumSize(new java.awt.Dimension(240, 20));
filenameTextField.setPreferredSize(new java.awt.Dimension(240, 20));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 4, 0);
configPanel.add(filenameTextField, gridBagConstraints);
descriptionLabel.setText("Description");
descriptionLabel.setToolTipText("It is possible to add a description into a Mediawiki resource. This description is taken from another occurrence. Available occurrence types are listed in the select box.");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4);
configPanel.add(descriptionLabel, gridBagConstraints);
descriptionComboBox.setMaximumSize(new java.awt.Dimension(180, 20));
descriptionComboBox.setMinimumSize(new java.awt.Dimension(180, 20));
descriptionComboBox.setName(""); // NOI18N
descriptionComboBox.setPreferredSize(new java.awt.Dimension(180, 20));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 4, 0);
configPanel.add(descriptionComboBox, gridBagConstraints);
streamLabel.setText("Send as byte stream");
streamLabel.setToolTipText("If selected, Wandora downloads the resource and uploads it to the Mediawiki as a byte stream. If not selected, an URL is sent to Mediawiki and Mediawiki downloads the resource. Notice, local files can be uploaded only as a byte stream.");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4);
configPanel.add(streamLabel, gridBagConstraints);
streamCheckBox.setSelected(true);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 4, 0);
configPanel.add(streamCheckBox, gridBagConstraints);
fileExtensionLabel.setText("Default file extension");
fileExtensionLabel.setToolTipText("Default file extension is used to specify type of uploaded resources if the type can't be detected any other way.");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4);
configPanel.add(fileExtensionLabel, gridBagConstraints);
fileExtensionTextField.setMaximumSize(new java.awt.Dimension(240, 20));
fileExtensionTextField.setMinimumSize(new java.awt.Dimension(240, 20));
fileExtensionTextField.setPreferredSize(new java.awt.Dimension(240, 20));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 4, 0);
configPanel.add(fileExtensionTextField, 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(configPanel, gridBagConstraints);
buttonPanel.setMaximumSize(new java.awt.Dimension(116, 25));
buttonPanel.setMinimumSize(new java.awt.Dimension(116, 25));
buttonPanel.setPreferredSize(new java.awt.Dimension(116, 25));
buttonPanel.setLayout(new java.awt.GridBagLayout());
FillerjPanel.setMaximumSize(new java.awt.Dimension(0, 0));
javax.swing.GroupLayout FillerjPanelLayout = new javax.swing.GroupLayout(FillerjPanel);
FillerjPanel.setLayout(FillerjPanelLayout);
FillerjPanelLayout.setHorizontalGroup(
FillerjPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
FillerjPanelLayout.setVerticalGroup(
FillerjPanelLayout.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(FillerjPanel, 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.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.setMaximumSize(new java.awt.Dimension(70, 23));
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.anchor = java.awt.GridBagConstraints.SOUTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
add(buttonPanel, gridBagConstraints);
}// </editor-fold>//GEN-END:initComponents
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 okButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_okButtonMouseReleased
accepted = true;
if(myDialog != null) myDialog.setVisible(false);
}//GEN-LAST:event_okButtonMouseReleased
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 FillerjPanel;
private javax.swing.JPanel buttonPanel;
private javax.swing.JButton cancelButton;
private javax.swing.JPanel configPanel;
private javax.swing.JComboBox descriptionComboBox;
private javax.swing.JLabel descriptionLabel;
private javax.swing.JLabel fileExtensionLabel;
private javax.swing.JTextField fileExtensionTextField;
private javax.swing.JLabel filenameLabel;
private javax.swing.JTextField filenameTextField;
private javax.swing.JButton okButton;
private javax.swing.JLabel passwordLabel;
private javax.swing.JTextField passwordTextField;
private javax.swing.JCheckBox streamCheckBox;
private javax.swing.JLabel streamLabel;
private javax.swing.JLabel usernameLabel;
private javax.swing.JTextField usernameTextField;
private javax.swing.JLabel wikiUrlLabel;
private javax.swing.JTextField wikiUrlTextField;
// End of variables declaration//GEN-END:variables
}
| 19,692 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
MediawikiOccurrenceUploader.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/mediawiki/MediawikiOccurrenceUploader.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/>.
*
*
* MediawikiOccurrenceUploader.java
*
* Created on 2013-04-25
*
*/
package org.wandora.application.tools.mediawiki;
import java.io.File;
import java.net.URL;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashSet;
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.GenericOptionsDialog;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author nlaitine
*/
public class MediawikiOccurrenceUploader extends MediawikiHandler implements WandoraTool {
private static final long serialVersionUID = 1L;
private static MediawikiUploaderConfigurationUI configurationUI = null;
private static MediawikiUploaderConfiguration config = new MediawikiUploaderConfiguration();
private boolean requiresRefresh = false;
private boolean isConfigured = false;
private boolean cancelled = false;
private boolean uploadAll = false;
public MediawikiOccurrenceUploader() {
}
public MediawikiOccurrenceUploader(boolean upAll) {
this.uploadAll = upAll;
}
public MediawikiOccurrenceUploader(Context proposedContext) {
this.setContext(proposedContext);
}
@Override
public String getName() {
return "Upload occurrence to Mediawiki.";
}
@Override
public String getDescription() {
return "Upload occurrence to Mediawiki server.";
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
requiresRefresh = false;
isConfigured = false;
cancelled = false;
Object source = context.getContextSource();
String o = null;
Collection<Topic> dataTypes;
HashSet<Topic> typeSet = new HashSet<>();
Topic carrier = null;
Topic type = null;
Topic lang = null;
try {
boolean wasUploaded = false;
if(source instanceof OccurrenceTable) {
setDefaultLogger();
OccurrenceTable ot = (OccurrenceTable) source;
o = ot.getPointedOccurrence();
lang = ot.getPointedOccurrenceLang();
carrier = ot.getTopic();
dataTypes = carrier.getDataTypes();
typeSet.addAll(dataTypes);
if(isValidResourceReference(o)) {
config = setupUI(wandora, typeSet, o, carrier, lang, false);
if(config != null) {
loginToWiki();
wasUploaded = mediaWikiUpload(null);
logoutOfWiki();
}
if(wasUploaded) {
log("Occurrence uploaded to Mediawiki.");
} else {
log("No occurrences uploaded to Mediawiki.");
}
}
else {
log("Occurrence resource is not an URL or a file.");
log("No occurrences uploaded.");
}
log("Ready.");
}
else {
Iterator contextObjects = context.getContextObjects();
if(!contextObjects.hasNext()) return;
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"));
}
}
if(uploadLang == null) return;
setDefaultLogger();
Iterator objects = context.getContextObjects();
Object cx = null;
Topic topic = null;
Collection<Topic> occurranceTypes = null;
while(objects.hasNext()) {
cx = objects.next();
topic = (Topic) cx;
occurranceTypes = topic.getDataTypes();
if (occurranceTypes != null) {
typeSet.addAll(occurranceTypes);
}
}
while(contextObjects.hasNext() && !forceStop() && !cancelled) {
Object co = contextObjects.next();
if(co != null) {
if(co instanceof Topic) {
carrier = (Topic) co;
dataTypes = carrier.getDataTypes();
Iterator<Topic> dataTypeObjects = dataTypes.iterator();
config = setupUI(wandora, typeSet, null, carrier, uploadLang, true);
if(config != null) {
loginToWiki();
while(dataTypeObjects.hasNext()) {
Topic otype = (Topic) dataTypeObjects.next();
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(isValidResourceReference(o)) {
wasUploaded = mediaWikiUpload(o);
if(wasUploaded) uploadCounter++;
if(cancelled) break;
}
}
}
}
}
}
}
}
}
}
if(uploadCounter > 0) {
log("Total "+uploadCounter+" occurrences uploaded to Mediawiki.");
}
else if(uploadCounter == 0) {
log("No occurrences uploaded to Mediawiki.");
}
if(config != null) {
logoutOfWiki();
}
log("Ready.");
}
}
catch(Exception e) {
log(e);
}
setState(WAIT);
}
@Override
public boolean requiresRefresh() {
return requiresRefresh;
}
public MediawikiUploaderConfiguration setupUI(Wandora wandora, HashSet<Topic> dataTypes, String o, Topic carrier, Topic lang, boolean batch) throws TopicMapException {
URL fileUrl = null;
if(!isConfigured) {
isConfigured = true;
if(configurationUI == null) {
configurationUI = new MediawikiUploaderConfigurationUI();
}
configurationUI.resetDescriptionTypeItems();
if (dataTypes.size() > 1) {
configurationUI.addDescriptionTypeItem("none");
for (Iterator<Topic> it = dataTypes.iterator(); it.hasNext();) {
Topic dataType = (Topic) it.next();
configurationUI.addDescriptionTypeItem(dataType);
}
configurationUI.enableDescriptionType();
}
configurationUI.showDescription();
if(!batch) {
configurationUI.showFilename();
fileUrl = stringToUrl(o);
String filename = filenameFromUrl(fileUrl, null);
configurationUI.setFilename(filename);
configurationUI.hideFileExtension();
} else {
configurationUI.hideFilename();
configurationUI.showFileExtension();
}
configurationUI.open(wandora, this);
if(!configurationUI.wasAccepted()) {
cancelled = true;
return null;
}
}
config.setWikiUrl(configurationUI.getWikiUrl().trim());
config.setWikiUser(configurationUI.getUser().trim());
config.setWikiPasswd(configurationUI.getPasswd().trim());
config.setWikiFileUrl(fileUrl);
config.setWikiFilename(configurationUI.getFilename().trim());
config.setWikiStream(configurationUI.getStream());
config.setWikiFileExtension(configurationUI.getFileExtension().trim());
Object selected = configurationUI.getDescriptionType();
if (selected instanceof Topic) {
Topic descType = (Topic) selected;
String desc = carrier.getData(descType, lang);
if (desc != null) {
desc = desc.trim();
config.setWikiDescription(desc);
}
}
return config;
}
private boolean loginToWiki() {
login(config.getWikiUrl(), config.getWikiUser(), config.getWikiPasswd());
return true;
}
private boolean logoutOfWiki() {
boolean loggedOut = logout(config.getWikiUrl());
return loggedOut;
}
public boolean mediaWikiUpload(String o) throws TopicMapException {
boolean success = false;
String apiWikiUrl = config.getWikiUrl();
URL apiFileUrl = null;
String apiFilename = null;
String apiDescription = config.getWikiDescription();
boolean apiStream = config.getWikiStream();
if(o != null && !o.equals("")) {
apiFileUrl = stringToUrl(o);
apiFilename = filenameFromUrl(apiFileUrl, config.getWikiFileExtension());
} else {
apiFileUrl = config.getWikiFileUrl();
apiFilename = config.getWikiFilename();
}
success = callWiki(apiWikiUrl, apiFileUrl, apiFilename, apiDescription, apiStream);
return success;
}
/*
* Helper methods
*/
private URL stringToUrl(String fileString) {
URL url = null;
try {
File file = new File(fileString);
if(file.exists()) {
url = file.toURI().toURL();
} else {
try {
url = new URL(fileString);
} catch (Exception e) {
log(e.getMessage());
}
}
} catch (Exception ex) {
log(ex.getMessage());
}
return url;
}
private String filenameFromUrl(URL url, String extension) {
String filename = url.getFile();
filename = filename.substring( filename.lastIndexOf("/")+1, filename.length() );
filename = filename.replaceAll("/[^a-z0-9\\040\\.]|:/i", "_");
if(extension != null && !extension.equals("")) {
//Get file extension
if(filename.substring(filename.length()-7).equalsIgnoreCase(".tar.gz")) {
//special case
} else {
int lastIndex = filename.lastIndexOf(".");
if(lastIndex == -1) {
lastIndex = 0;
}
String fileExtension = filename.substring(lastIndex, filename.length());
if(fileExtension.length() > 4 || fileExtension.length() < 2) {
//Generate filename for url
if(url.getProtocol().equals("http") && filename.length() > 20) {
filename = "file" + Integer.toString( url.hashCode() );
}
//Add default file extension
if(extension.startsWith(".")) {
filename = filename + extension;
} else {
filename = filename + "." + extension;
}
}
}
}
filename = filename.trim();
return filename;
}
}
| 15,052 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
MediawikiSubjectLocatorUploader.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/mediawiki/MediawikiSubjectLocatorUploader.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/>.
*
*
* MediawikiUploader.java
*
* Created on 2013-04-25
*
*/
package org.wandora.application.tools.mediawiki;
import java.io.File;
import java.net.URL;
import java.util.Iterator;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.Context;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author nlaitine
*/
public class MediawikiSubjectLocatorUploader extends MediawikiHandler implements WandoraTool {
private static final long serialVersionUID = 1L;
private static MediawikiUploaderConfigurationUI configurationUI = null;
private static MediawikiUploaderConfiguration config = new MediawikiUploaderConfiguration();
private boolean requiresRefresh = false;
private boolean isConfigured = false;
private boolean cancelled = false;
public MediawikiSubjectLocatorUploader() {
}
public MediawikiSubjectLocatorUploader(Context proposedContext) {
this.setContext(proposedContext);
}
@Override
public String getName() {
return "Upload occurrence to Mediawiki.";
}
@Override
public String getDescription() {
return "Upload occurrence to Mediawiki server.";
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
requiresRefresh = false;
isConfigured = false;
cancelled = false;
String loc = null;
Topic carrier = null;
Locator lo = null;
try {
Iterator contextObjects = context.getContextObjects();
if (!contextObjects.hasNext()) {
return;
}
boolean wasUploaded = false;
int uploadCounter = 0;
setDefaultLogger();
while (contextObjects.hasNext() && !forceStop() && !cancelled) {
Object co = contextObjects.next();
if (co != null) {
if (co instanceof Topic) {
carrier = (Topic) co;
config = setupUI(wandora);
if(config != null) {
loginToWiki();
if (forceStop()) {
break;
}
if (cancelled) {
break;
}
lo = carrier.getSubjectLocator();
if (lo != null) {
loc = lo.toExternalForm();
wasUploaded = mediaWikiUpload(loc);
if (wasUploaded) {
uploadCounter++;
}
if (cancelled) {
break;
}
}
}
}
}
}
if(uploadCounter > 0) {
log("Total "+uploadCounter+" subject locators uploaded to Mediawiki.");
}
else if(uploadCounter == 0) {
log("No subject locators uploaded to Mediawiki.");
}
if(config != null) {
logoutOfWiki();
}
log("Ready.");
}
catch(Exception e) {
log(e);
}
setState(WAIT);
}
@Override
public boolean requiresRefresh() {
return requiresRefresh;
}
public MediawikiUploaderConfiguration setupUI(Wandora wandora) throws TopicMapException {
if(!isConfigured) {
isConfigured = true;
if(configurationUI == null) {
configurationUI = new MediawikiUploaderConfigurationUI();
}
configurationUI.hideFilename();
configurationUI.hideDescription();
configurationUI.showFileExtension();
configurationUI.open(wandora, this);
if(!configurationUI.wasAccepted()) {
cancelled = true;
return null;
}
}
config.setWikiUrl(configurationUI.getWikiUrl().trim());
config.setWikiUser(configurationUI.getUser().trim());
config.setWikiPasswd(configurationUI.getPasswd().trim());
config.setWikiStream(configurationUI.getStream());
config.setWikiFileExtension(configurationUI.getFileExtension().trim());
return config;
}
private boolean loginToWiki() {
boolean logged = login(config.getWikiUrl(), config.getWikiUser(), config.getWikiPasswd());
return logged;
}
private boolean logoutOfWiki() {
boolean loggedOut = logout(config.getWikiUrl());
return loggedOut;
}
public boolean mediaWikiUpload(String loc) throws TopicMapException {
boolean success = false;
String apiWikiUrl = config.getWikiUrl();
URL apiFileUrl = null;
String apiFilename = null;
String apiDescription = config.getWikiDescription();
boolean apiStream = config.getWikiStream();
if(loc != null && !loc.equals("")) {
apiFileUrl = stringToUrl(loc);
apiFilename = filenameFromUrl(apiFileUrl, config.getWikiFileExtension());
} else {
apiFileUrl = config.getWikiFileUrl();
apiFilename = config.getWikiFilename();
}
success = callWiki(apiWikiUrl, apiFileUrl, apiFilename, apiDescription, apiStream);
return success;
}
/*
* Helper methods
*/
private URL stringToUrl(String fileString) {
URL url = null;
try {
File file = new File(fileString);
if(file.exists()) {
url = file.toURI().toURL();
} else {
try {
url = new URL(fileString);
} catch (Exception e) {
log(e.getMessage());
}
}
} catch (Exception ex) {
log(ex.getMessage());
}
return url;
}
private String filenameFromUrl(URL url, String extension) {
String filename = url.getFile();
filename = filename.substring( filename.lastIndexOf("/")+1, filename.length() );
filename = filename.replaceAll("/[^a-z0-9\\040\\.]|:/i", "_");
if(extension != null && !extension.equals("")) {
//Get file extension
if(filename.substring(filename.length()-7).equalsIgnoreCase(".tar.gz")) {
//special case
} else {
int lastIndex = filename.lastIndexOf(".");
if(lastIndex == -1) {
lastIndex = 0;
}
String fileExtension = filename.substring(lastIndex, filename.length());
if(fileExtension.length() > 4 || fileExtension.length() < 2) {
//Generate filename for url
if(url.getProtocol().equals("http") && filename.length() > 20) {
filename = "file" + Integer.toString( url.hashCode() );
}
//Add default file extension
if(extension.startsWith(".")) {
filename = filename + extension;
} else {
filename = filename + "." + extension;
}
}
}
}
filename = filename.trim();
return filename;
}
}
| 8,792 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SplitToBinaryAssociations.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/associations/SplitToBinaryAssociations.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/>.
*
*
* SplitToBinaryAssociations.java
*
* Created on 1. marraskuuta 2007, 16:33
*
*/
package org.wandora.application.tools.associations;
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.AssociationContext;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.WandoraOptionPane;
import org.wandora.application.gui.topicstringify.TopicToString;
import org.wandora.application.tools.AbstractWandoraTool;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
/**
* <p>
* Tool splits given n-ary association (n>2) to (n-1)
* binary associations. Selected player is used in every generated
* binary association. For example, think 5-ary association with player c
* selected:
* </p>
* <code>
*
*
* a-b-(c)-d-e --> a-c, b-c, d-c, e-c
*
*
* </code>
*
* @author akivela
*/
public class SplitToBinaryAssociations extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
private boolean requiresRefresh = false;
/** Creates a new instance of SplitToBinaryAssociations */
public SplitToBinaryAssociations() {
setContext(new AssociationContext());
}
public SplitToBinaryAssociations(Context preferredContext) {
setContext(preferredContext);
}
@Override
public String getName() {
return "Split to binary associations";
}
@Override
public String getDescription() {
return "Splits n-ary associations to several binary associations.";
}
@Override
public boolean requiresRefresh() {
return requiresRefresh;
}
@Override
public void execute(Wandora wandora, Context context) {
try {
requiresRefresh = false;
TopicMap topicmap = wandora.getTopicMap();
Iterator associations = null;
Topic baseRole = null;
Topic base = null;
Topic player = null;
Topic role = null;
Association a = null;
Association splita = null;
int oldCounter = 0;
int newCounter = 0;
int answer = WandoraOptionPane.showConfirmDialog(wandora, "Tool splits selected n-ary associations to binary associations. Selected player topic is interpreted as the base player. The base player is same in every created association. The other part of created binary associations is one of the other players in source associations. Are you sure you want convert selected associations to binary associations?", "Convert to binary associations?");
if(answer != WandoraOptionPane.YES_OPTION) return;
setDefaultLogger();
if(context instanceof AssociationContext) { // ASSOCIATION CONTEXT!!
associations = context.getContextObjects();
base = wandora.getOpenTopic();
if(base == null) {
log("Base topic not found. Rejecting association.");
}
else {
log("Found base topic " + TopicToString.toString(base));
while(associations.hasNext() && !forceStop()) {
baseRole = null;
role = null;
player = null;
a = (Association) associations.next();
Iterator<Topic> roles = null;
Map<Topic,Topic> splits = new LinkedHashMap<>();
if(a != null && !a.isRemoved()) {
roles = a.getRoles().iterator();
while(roles.hasNext()) {
role = roles.next();
player = a.getPlayer(role);
if(!player.mergesWithTopic(base)) {
splits.put(role, player);
}
else {
log("Found base role " + TopicToString.toString(role));
baseRole = role;
}
}
if(splits.size() < 2) { log("Found less than 2 players in selected association. Rejecting association."); continue; }
if(baseRole == null) { log("Base topic role not found! Rejecting association!"); continue; }
oldCounter++;
a.remove();
Iterator<Topic> splitIterator = splits.keySet().iterator();
while(splitIterator.hasNext() && !forceStop()) {
try {
role = (Topic) splitIterator.next();
player = (Topic) splits.get(role);
if(role != null && player != null) {
requiresRefresh = true;
splita = topicmap.createAssociation(role);
splita.addPlayer(player, role);
splita.addPlayer(base, baseRole);
newCounter++;
}
}
catch(Exception e) {
log(e);
}
}
}
}
log("Total "+oldCounter+" associations splitted.");
log("Total "+newCounter+" binary associations created.");
}
}
else {
log("Illegal context found. Expecting association context.");
}
}
catch(Exception e) {
log(e);
}
setState(WAIT);
}
}
| 7,058 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
CopyEdgePath.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/associations/CopyEdgePath.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.associations;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
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.gui.WandoraOptionPane;
import org.wandora.application.gui.table.AssociationTable;
import org.wandora.application.gui.topicstringify.TopicToString;
import org.wandora.application.tools.AbstractWandoraTool;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicTools;
import org.wandora.utils.ClipboardBox;
/**
* <p>
* Copies a tabulator separated topic list to system clipboard.
* Topic list contains player topics of a given association type and a role type.
* Player topic set is limited to topics that can be reached from the selected
* topic and selected association.
* </p>
* <p>
* For example, think binary associations:
* a-b, b-c, d-e, e-f. Here letters a through f represent players of association.
* As you can easy figure there is an association chain from a to f as you can
* travel from a to f using the association. Now lets think you have
* selected association b-c and player b. Running this
* tool with this selection copies system clipboard a list of topics b, c, d, e, f.
* If you select association b-c and the player c, your clipboard ends up to contain
* player topics c, b, a.
* </p>
* <p>
* Tool can be used to locate a root node of tree like association set, for example.
* Super-subclass relations form usually a tree type association structure.
* </p>
*
* @see OpenEdgeTopic
* @author akivela
*/
public class CopyEdgePath extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
public CopyEdgePath() {
setContext(new AssociationContext());
}
public CopyEdgePath(Context preferredContext) {
setContext(preferredContext);
}
@Override
public String getName() {
return "Copy edge path";
}
@Override
public String getDescription() {
return "Copy topics while traversing to the edge of associations.";
}
@Override
public boolean requiresRefresh() {
return false;
}
@Override
public void execute(Wandora wandora, Context context) {
try {
Map<Association,List<Topic>> associationsWithRoles = null;
Topic role = null;
Association a = null;
StringBuilder pathString = new StringBuilder("");
otherRole = null;
if(context instanceof AssociationContext) { // ASSOCIATION CONTEXT!!
AssociationTable associationTable = null;
Object contextSource = context.getContextSource();
if(contextSource instanceof AssociationTable) {
associationTable = (AssociationTable) context.getContextSource();
}
if(associationTable != null) {
associationsWithRoles = associationTable.getSelectedAssociationsWithSelectedRoles();
}
if(associationsWithRoles != null && associationsWithRoles.size() > 0) {
Set<Association> associationSet = associationsWithRoles.keySet();
Iterator<Association> associationIterator = associationSet.iterator();
while(associationIterator.hasNext() && !forceStop()) {
a = (Association) associationIterator.next();
if(a != null) {
List<Topic> roles = associationsWithRoles.get(a);
Iterator<Topic> roleIterator = roles.iterator();
if(roleIterator.hasNext() && !forceStop()) {
role = roleIterator.next();
if(role != null) {
try {
Topic outRole = findOtherRole(a, role, wandora);
if(outRole != null) {
Topic player = a.getPlayer(role);
List<Topic> topicPath = TopicTools.getSinglePath(player, a.getType(), role, outRole);
Topic pathTopic = null;
pathString.append(player.getBaseName());
for(Iterator<Topic> pathIter=topicPath.iterator(); pathIter.hasNext(); ) {
pathTopic = pathIter.next();
pathString.append(TopicToString.toString(pathTopic));
if(pathIter.hasNext()) pathString.append("\t");
}
pathString.append("\n");
}
}
catch(Exception e) {
singleLog(e);
}
}
}
}
}
ClipboardBox.setClipboard(pathString.toString());
}
else {
singleLog("No associations found in context!");
}
}
else {
singleLog("Illegal context found! Expecting association context!");
}
}
catch(Exception e) {
singleLog(e);
}
}
Topic otherRole = null;
private Topic findOtherRole(Association a, Topic r, Wandora wandora) {
if(otherRole != null) return otherRole;
try {
Collection<Topic> allRoles = a.getRoles();
if(allRoles.size() < 3) {
for(Iterator<Topic> roleIterator = allRoles.iterator(); roleIterator.hasNext(); ) {
otherRole = roleIterator.next();
if(otherRole != null && !otherRole.isRemoved()) {
if(!otherRole.mergesWithTopic(r)) {
return otherRole;
}
}
}
}
else {
allRoles.remove(r);
Object answer = WandoraOptionPane.showOptionDialog(wandora, "Select second role for association travelsal", "Select second role", WandoraOptionPane.OK_CANCEL_OPTION, allRoles.toArray(), allRoles.iterator().next());
if(answer instanceof Topic) {
return (Topic) answer;
}
}
}
catch(Exception e) {
singleLog(e);
}
return null;
}
}
| 8,029 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SwapPlayers.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/associations/SwapPlayers.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/>.
*
*
* SwapPlayers.java
*
* Created on 16. elokuuta 2008, 16:25
*
*/
package org.wandora.application.tools.associations;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
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.gui.table.AssociationTable;
import org.wandora.application.tools.AbstractWandoraTool;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
/**
* <p>
* Changes given associations by swapping two players in associations.
* For example, if binary association contains players with roles P1:R1 and P2:R2
* then player swap results association with players P2:R1 and P1:R2.
* </p>
* <p>
* If given associations are not binary then selected columns in association table
* indicate swapped players. If selection contains more or less than two columns
* tool aborts.
* </p>
* <p>
* Tool can be used to fix symmetric associations where roles have almost same
* semantic meaning. For example RDF triplets are directed and RDF import may
* result symmetric association duplicates that are not elegant in topic maps.
* Swapping players of such symmetric association duplicates causes Wandora
* to merge symmetric associations.
* </p>
*
* @see DeleteSymmetricAssociation
* @see CreateSymmetricAssociation
*
* @author akivela
*/
public class SwapPlayers extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
private boolean requiresRefresh = false;
public SwapPlayers() {
setContext(new AssociationContext());
}
public SwapPlayers(Context preferredContext) {
setContext(preferredContext);
}
@Override
public String getName() {
return "Swap players";
}
@Override
public String getDescription() {
return "Swaps association player roles. If symmetric association already exists "+
"then player swap merges symmetric associations. Feature can be used to remove "+
"symmetric duplicates.";
}
@Override
public boolean requiresRefresh() {
return requiresRefresh;
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
requiresRefresh = false;
Iterator associations = context.getContextObjects();
Association association = null;
int count = 0;
Set<Topic> swapRoles = new HashSet<Topic>();
Collection<Topic> roles = null;
Topic role;
Topic[] swapRoleArray = null;
try {
if(associations != null && associations.hasNext()) {
int i = 0;
int ac = 0;
// First collect all roles in context associations.
while(associations.hasNext() && !forceStop()) {
association = (Association) associations.next();
if(association != null && !association.isRemoved()) {
ac++;
roles = association.getRoles();
for(Iterator<Topic> it = roles.iterator(); it.hasNext(); ) {
role = it.next();
if(!swapRoles.contains(role)) {
swapRoles.add(role);
}
}
}
}
// Check if decent logging is required.
if(ac > 100) {
setDefaultLogger();
log("Swapping players in associations.");
setProgressMax(ac);
}
// Ok, all selected associations are binary. Easy job.
if(swapRoles.size() == 2) {
swapRoleArray = swapRoles.toArray( new Topic[] {} );
associations = context.getContextObjects();
while(associations.hasNext() && !forceStop()) {
association = (Association) associations.next();
if(association != null && !association.isRemoved()) {
count += swapPlayers(association, swapRoleArray[0], swapRoleArray[1]);
setProgress(count);
}
}
log("Total " + count + " associations processed.");
}
// Associations are not binary. Have to investigate more detailed which players to swap.
else if(swapRoles.size() > 2) {
AssociationTable associationTable = null;
Object contextSource = context.getContextSource();
if(contextSource instanceof AssociationTable) {
associationTable = (AssociationTable) context.getContextSource();
}
if(associationTable != null) {
Map<Association,List<Topic>> associationsWithSelectedRoles = associationTable.getSelectedAssociationsWithSelectedRoles();
Set<Association> associationKeys = associationsWithSelectedRoles.keySet();
Iterator<Association> associationKeyIterator = associationKeys.iterator();
List<Topic> swapRoleArrayList = null;
while(associationKeyIterator.hasNext() && !forceStop()) {
association = associationKeyIterator.next();
if(association != null && !association.isRemoved()) {
swapRoleArrayList = associationsWithSelectedRoles.get(association);
if(swapRoleArrayList != null && swapRoleArrayList.size() == 2) {
swapRoleArray = swapRoleArrayList.toArray( new Topic[] {} );
count += swapPlayers(association, swapRoleArray[0], swapRoleArray[1]);
setProgress(count);
}
else {
log("Number of players is less than two or greater than two. Skipping association.");
}
}
}
log("Total " + count + " associations processed.");
}
}
else {
log("The number of association players is less than two. Aborting.");
}
}
}
catch(Exception e) {
singleLog(e);
}
}
public int swapPlayers(Association association, Topic role1, Topic role2) {
int swapCount = 0;
try {
if(association == null || association.isRemoved()) return 0;
if(role1 == null || role2 == null) return 0;
if(role1.isRemoved() || role2.isRemoved()) return 0;
Topic player1 = association.getPlayer(role1);
Topic player2 = association.getPlayer(role2);
if(player1 != null && player2 != null) {
if(!player1.isRemoved() && !player2.isRemoved()) {
requiresRefresh = true;
association.removePlayer(role1);
association.removePlayer(role2);
association.addPlayer(player1, role2);
association.addPlayer(player2, role1);
swapCount++;
}
else {
log("Association contains removed topics. Skipping!");
}
}
}
catch (Exception e) {
log(e);
}
return swapCount;
}
}
| 8,944 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
MakeAssociationWithClassInstance.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/associations/MakeAssociationWithClassInstance.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/>.
*
*
* MakeAssociationWithClassInstance.java
*
* Created on 25. toukokuuta 2012
*
*/
package org.wandora.application.tools.associations;
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.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
/**
* <p>
* <code>MakeAssociationWithClassInstance</code> transforms default class-instance
* relations to any associations.
* </p>
*
* @author akivela
*/
public class MakeAssociationWithClassInstance extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
private boolean deleteClassInstance = false;
private boolean requiresRefresh = false;
public MakeAssociationWithClassInstance() {
}
public MakeAssociationWithClassInstance(Context preferredContext) {
setContext(preferredContext);
}
@Override
public String getName() {
return "Make association out of class-instance relation";
}
@Override
public String getDescription() {
return "Transforms class-instance relations to any associations.";
}
@Override
public boolean requiresRefresh() {
return requiresRefresh;
}
@Override
public void execute(Wandora wandora, Context context) {
try {
Iterator topics = context.getContextObjects();
if(topics == null || !topics.hasNext()) return;
Topic associationType=wandora.showTopicFinder("Select association type...");
if(associationType == null) return;
Topic instanceRole=wandora.showTopicFinder("Select role topic for instances...");
if(instanceRole == null) return;
Topic classRole=wandora.showTopicFinder("Select role topic for classes...");
if(classRole == null) return;
setDefaultLogger();
setLogTitle("Making associations from class-instance relations");
log("Making associations from default class-instance relations");
Topic topic = null;
int progress = 0;
TopicMap map = wandora.getTopicMap();
Association a = null;
ArrayList<Topic> dtopics = new ArrayList<Topic>();
while(topics.hasNext() && !forceStop()) {
dtopics.add((Topic) topics.next());
}
topics = dtopics.iterator();
// Iterate through selected topics...
while(topics.hasNext() && !forceStop()) {
try {
topic = (Topic) topics.next();
if(topic != null && !topic.isRemoved()) {
progress++;
hlog("Inspecting topic '"+getTopicName(topic)+"'");
Collection<Topic> types = new ArrayList<Topic>(topic.getTypes());
// Ok, if topic has types...
if(!types.isEmpty()) {
for(Topic type : types) {
if(forceStop()) break;
if(type != null && !type.isRemoved()) {
log("Processing types of topic '"+getTopicName(topic)+"'");
requiresRefresh = true;
// Creating new association between instance and class topics
hlog("Creating association between '"+getTopicName(topic)+"' and '"+getTopicName(type)+"'.");
a = map.createAssociation(associationType);
a.addPlayer(type, classRole);
a.addPlayer(topic, instanceRole);
// Finally deleting class-instance relation if...
if(deleteClassInstance) {
topic.removeType(type);
}
}
}
}
}
}
catch(Exception e) {
log(e);
}
}
setState(WAIT);
}
catch (Exception e) {
log(e);
}
}
}
| 5,521 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
CollectNary.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/associations/CollectNary.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/>.
*
*
* CollectNary.java
*
* Created on 7. huhtikuuta 2006, 10:53
*
*/
package org.wandora.application.tools.associations;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
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.application.tools.GenericOptionsDialog;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
/**
/**
* <p>
* Tool builds n-association from selected associations.
* </p>
*
* <code>
*
* Four example associations:
*
* a -- b1 -- c1
* a -- b2 -- c2
* a -- b3 -- c3
* a -- b4 -- c4
*
* are transformed to
*
* a -- c1 -- c2 -- c3 -- c4
* (where b1, b2, b3 and b4 are roles)
*
* or
*
* a -- b1 -- b2 -- b3 -- b4
* (where c1, c2, c3 and c4 are roles)
*
* </code>
*
*
* Note: Default context of this tool is <code>AssociationContext</code>!
*
*
* @author akivela
*/
public class CollectNary extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
private boolean requiresRefresh = false;
public CollectNary() {
setContext(new AssociationContext());
}
public CollectNary(Context preferredContext) {
setContext(preferredContext);
}
@Override
public String getName() {
return "Collect to n-ary";
}
@Override
public String getDescription() {
return "Creates one n-association from n binary associations.";
}
@Override
public boolean requiresRefresh() {
return requiresRefresh;
}
@Override
public void execute(Wandora wandora, Context context) {
try {
requiresRefresh = false;
Iterator associations = null;
Topic newAssociationType = null;
Topic groupingRole = null;
Topic roleRole = null;
Topic playerRole = null;
boolean deleteSourceAssociations = false;
TopicMap tm = wandora.getTopicMap();
Association association = null;
int counter = 0;
if(context instanceof AssociationContext) { // ASSOCIATION CONTEXT!!
associations = context.getContextObjects();
if(associations == null || !associations.hasNext()) return;
// ASK USER ABOUT THE ROLES AND TYPE TOPICS!
GenericOptionsDialog god=new GenericOptionsDialog(
wandora,
"Collect n-ary associations",
"Combine selected associations using given grouping role.",
true,
new String[][]{
new String[]{"Grouping role","topic","", "Which player topic sets up a group of role-player pairs put into a single association."},
new String[]{"Role of role topic","topic","","Where is the role topic in association."},
new String[]{"Role of player topic","topic","","Where is the player topic in association."},
new String[]{"New association type","topic","", "What is the type of created associations."},
new String[]{"Delete source associations","boolean","false", "Should Wandora delete source associations afterward."},
},wandora);
god.setVisible(true);
if(god.wasCancelled()) return;
Map<String,String> values=god.getValues();
if(values.get("Role of role topic")!=null && values.get("Role of role topic").length()>0) {
roleRole = tm.getTopic(values.get("Role of role topic"));
}
if(roleRole == null) {
log("Given role topic for roles is illegal (null)! Aborting.");
return;
}
if(values.get("Role of player topic")!=null && values.get("Role of player topic").length()>0) {
playerRole = tm.getTopic(values.get("Role of player topic"));
}
if(playerRole == null) {
log("Given role topic for players is illegal (null)! Aborting.");
return;
}
if(values.get("Grouping role")!=null && values.get("Grouping role").length()>0) {
groupingRole = tm.getTopic(values.get("Grouping role"));
}
if(groupingRole == null) {
log("Given grouping role topic is illegal (null)! Aborting.");
return;
}
if(values.get("New association type")!=null && values.get("New association type").length()>0) {
newAssociationType = tm.getTopic(values.get("New association type"));
}
if(newAssociationType == null) {
log("Given association type topic is illegal (null)! Aborting.");
return;
}
if(values.get("Delete source associations")!=null && values.get("Delete source associations").length()>0) {
deleteSourceAssociations = "true".equals(values.get("Delete source associations"));
}
ArrayList<Association> associationCollection = new ArrayList<Association>();
while(associations.hasNext() && !forceStop()) {
association = (Association) associations.next();
try {
if(association != null && !association.isRemoved()) {
associationCollection.add(association);
}
}
catch(Exception e) {
log(e);
}
}
collectAssociations(associationCollection, groupingRole, roleRole, playerRole, newAssociationType, deleteSourceAssociations, tm);
}
}
catch(Exception e) {
log(e);
}
setState(WAIT);
}
public void collectAssociations(Collection<Association> associations, Topic groupingRole, Topic roleRole, Topic playerRole, Topic newAssociationType, boolean deleteSourceAssociations, TopicMap tm) throws Exception {
// ***** Collect association groups
HashMap<Topic, Collection<Association>> collectedAssociations = new HashMap();
for(Association a : associations) {
if(a != null && !a.isRemoved()) {
Topic groupingPlayer = a.getPlayer(groupingRole);
if(groupingPlayer != null) {
Collection<Association> groupedAssociations = collectedAssociations.get(groupingPlayer);
if(groupedAssociations == null) groupedAssociations = new ArrayList<Association>();
groupedAssociations.add(a);
collectedAssociations.put(groupingPlayer, groupedAssociations);
}
}
}
// ***** Make new grouped associations
for(Topic groupingTopic : collectedAssociations.keySet()) {
Collection<Association> groupedAssociations = collectedAssociations.get(groupingTopic);
Association newA = tm.createAssociation(newAssociationType);
for(Association a : groupedAssociations) {
Topic role = a.getPlayer(roleRole);
Topic player = a.getPlayer(playerRole);
if(role != null && player != null) {
newA.addPlayer(player, role);
for(Topic otherRole : a.getRoles()) {
if(otherRole != null && !otherRole.isRemoved()) {
if(!otherRole.mergesWithTopic(roleRole) && !otherRole.mergesWithTopic(playerRole)) {
if(a.getPlayer(otherRole) != null) {
newA.addPlayer(a.getPlayer(otherRole), otherRole);
}
}
}
}
}
else {
//
}
}
}
// ***** Delete source associations (optional)
if(deleteSourceAssociations) {
for(Association a : associations) {
a.remove();
}
}
}
}
| 9,730 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
PasteAssociations.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/associations/PasteAssociations.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/>.
*
*
* PasteAssociations.java
*
* Created on 22. joulukuuta 2004, 12:27
*/
package org.wandora.application.tools.associations;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
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.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.utils.ClipboardBox;
import org.wandora.utils.Textbox;
/**
* <p>
* Paste association tool class injects associations to Wandora topics.
* Associations are generated with clipboard text. Clipboard should contain text
* in specific format:
* </p>
*
* <code>
* ASSOCIATION_TYPE{newline}
* ROLE_1{tab}ROLE_2{tab}ROLE_3{newline}
* PLAYER_a1{tab}PLAYER_a2{tab}PLAYER_a3{newline}
* PLAYER_b1{tab}PLAYER_b2{tab}PLAYER_b3{newline}
* PLAYER_c1{tab}PLAYER_c2{tab}PLAYER_c3{newline}
* {newline}
* </code>
* <p>
* where all topic references are base names and {newline} is a newline character
* and {tab} a tabulator character.
* Accepted association format is generated by Copy associations tool for example.
* </p>
* If role or player does not exist the tool asks user whether or not it should
* create a new topic for the given base name.
* <p>
* Placing special keyword __CURRENT_TOPIC__ as a player of injected text generates
* associations where player is replaced with a context topic.
* </p>
*
* @see CopyAssociations
*
* @author akivela
*/
public class PasteAssociations extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
private boolean requiresRefresh = false;
private int userInterrupt;
private boolean yesToAllCountErrors;
public PasteAssociations(){
}
public PasteAssociations(Context preferredContext){
setContext(preferredContext);
}
@Override
public String getName() {
return "Paste association";
}
@Override
public String getDescription() {
return "Injects clipboard tab text associations to Wandora.";
}
@Override
public boolean requiresRefresh() {
return requiresRefresh;
}
@Override
public void execute(Wandora wandora, Context context) {
requiresRefresh = false;
TopicMap topicMap = wandora.getTopicMap();
Iterator topics = context.getContextObjects();
Topic topicOpen = null;
if(topics != null && topics.hasNext()) {
topicOpen = (Topic) topics.next();
if(topicOpen != null) {
Association a = null;
String tabText = ClipboardBox.getClipboard();
String[] associationGroups = tabText.split("\n\r?\n\r?");
yesToAllCountErrors = false;
yesToAllNewTopics = false;
userInterrupt = 0;
// AssociationGroup is a collection of associations with same
// association type and same roles. Tool assumes that association groups
// are separated with two new line characters (see split above).
for(int ai=0; ai<associationGroups.length && userInterrupt == 0; ai++) {
StringTokenizer st = new StringTokenizer(associationGroups[ai], "\n");
try {
String aType = null;
if(st.hasMoreTokens()) aType = st.nextToken();
else {
WandoraOptionPane.showMessageDialog(wandora ,"Clipboard contains no association type! No associations created!","Association type missing!",WandoraOptionPane.ERROR_MESSAGE);
return;
}
String aRoles = null;
if(st.hasMoreTokens()) aRoles = st.nextToken();
else {
WandoraOptionPane.showMessageDialog(wandora ,"Clipboard contains no association roles! No associations created!","Association roles missing!",WandoraOptionPane.ERROR_MESSAGE);
return;
}
List<String> aRoleVector = vectorize(aRoles, "\t");
if(!st.hasMoreTokens()) {
WandoraOptionPane.showMessageDialog(wandora ,"Clipboard contains no association players! No associations created!","Association players missing!",WandoraOptionPane.ERROR_MESSAGE);
return;
}
int count = 0;
int line = 0;
boolean hasAssociations = false;
while(st.hasMoreTokens() && aType != null && aRoles != null && userInterrupt == 0) {
line++;
hasAssociations = true;
List<String> playerVector = vectorize(st.nextToken(), "\t");
if(playerVector.size() == aRoleVector.size()) {
List<Topic> aPlayerTopicVector = getTopics(wandora, topicMap, playerVector, topicOpen);
List<Topic> aRoleTopicVector = getTopics(wandora, topicMap, aRoleVector, topicOpen);
if(userInterrupt == WandoraOptionPane.NO_OPTION) {
// User has disallowed topic creation. Skipping this association.
continue;
}
else if(userInterrupt == WandoraOptionPane.CANCEL_OPTION) {
// User has disallowed topic creation and requests for cancellation.
break;
}
a = null;
for(int i=0; i<playerVector.size(); i++) {
Topic player = (Topic) aPlayerTopicVector.get(i);
Topic role = (Topic) aRoleTopicVector.get(i);
if(player != null && role != null) {
if(a == null) {
requiresRefresh = true;
Topic at = getTopic(wandora, topicMap, aType);
if(at == null) break;
a = topicMap.createAssociation(at);
count++;
}
a.addPlayer(player, role);
}
}
}
else {
// It seems that the number of players does not equal number of roles.
// Checking if user cancels operation!
if( !yesToAllCountErrors ) {
int an = WandoraOptionPane.showConfirmDialog(wandora ,"Number of players is not equal to number of roles! " +
"Rejecting association! " +
"Would you like to continue the operation?",
"Player number mismatch number of roles!",
WandoraOptionPane.YES_TO_ALL_NO_OPTION);
if(an == WandoraOptionPane.NO_OPTION) userInterrupt = WandoraOptionPane.NO_OPTION;
else if(an == WandoraOptionPane.YES_TO_ALL_OPTION) yesToAllCountErrors = true;
}
}
}
if(hasAssociations && count == 0) {
WandoraOptionPane.showMessageDialog(wandora ,"Association creation failed! No associations created!","No associations created!",WandoraOptionPane.ERROR_MESSAGE);
}
}
catch (Exception e) {
log("Exception '" + e.toString()+ "' occurred while creating associations!", e);
//if(a != null) a.remove();
}
}
}
else {
log("Can't solve open topic!");
}
}
}
public List<String> vectorize(String str, String delim) {
List<String> v = new ArrayList<>();
if(str != null && str.length() > 0) {
StringTokenizer sto = new StringTokenizer(str, delim);
while(sto.hasMoreTokens()) {
v.add(sto.nextToken());
}
}
return v;
}
private boolean yesToAllNewTopics = false;
public Topic getTopic(Wandora wandora, TopicMap topicMap, String topicName) throws TopicMapException {
if(topicName != null) {
topicName = Textbox.trimExtraSpaces(topicName);
if(topicName.length() > 0) {
Topic t = topicMap.getTopicWithBaseName(topicName);
if(t == null) {
// Testing if topicName matches any subject identifiers.
t = topicMap.getTopic(topicName);
}
if(t == null) {
// Testing if topicName matches any subject locators.
t = topicMap.getTopicBySubjectLocator(topicName);
}
if(t == null) {
// Looks like there is no acquired topic available!
// Checking if user allows topic creation.
if(!yesToAllNewTopics) {
String tempTopicName = topicName;
if(tempTopicName.length() > 256) tempTopicName = tempTopicName.substring(0,256) + "...";
int a = WandoraOptionPane.showConfirmDialog(
wandora,
"Topic '"+tempTopicName+"' does not exists! Would you like to create new topic for '"+tempTopicName+"'.",
"Create topic?",
WandoraOptionPane.YES_TO_ALL_NO_CANCEL_OPTION);
if( a == WandoraOptionPane.NO_OPTION ) { userInterrupt = a; return null; }
if( a == WandoraOptionPane.CANCEL_OPTION ) { userInterrupt = a; return null; }
if( a == WandoraOptionPane.YES_TO_ALL_OPTION ) { yesToAllNewTopics = true; }
}
requiresRefresh = true;
t = topicMap.createTopic();
if(topicName.startsWith("http://") || topicName.startsWith("https://")) {
t.addSubjectIdentifier(new Locator(topicName));
}
else {
t.setBaseName(topicName);
String si = "http://wandora.org/si/" + System.currentTimeMillis();
int counter = 1000;
while(topicMap.getTopic(si) != null && --counter > 0) {
si = "http://wandora.org/si/" + System.currentTimeMillis() + counter;
}
t.addSubjectIdentifier(new Locator(si));
}
}
return t;
}
}
return null;
}
public List<Topic> getTopics(Wandora wandora, TopicMap topicMap, List<String> topicNames, Topic defaultTopic) throws TopicMapException {
List<Topic> topics = new ArrayList<>();
Topic t = null;
for (String topicName : topicNames) {
if("__CURRENT_TOPIC__".equals(topicName)) {
t = defaultTopic;
}
else {
t = getTopic(wandora, topicMap, topicName);
}
if(t != null) topics.add(t);
if(userInterrupt != 0) return null;
}
return topics;
}
}
| 13,564 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AddAssociations.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/associations/AddAssociations.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/>.
*
*
* AddAssociations.java
*
* Created on 24. lokakuuta 2005, 19:52
*
*/
package org.wandora.application.tools.associations;
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.SchemaAssociationPrompt;
import org.wandora.application.tools.AbstractWandoraTool;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
/**
* @deprecated
* @see AddSchemalessAssociation
* @author akivela
*/
public class AddAssociations extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
public AddAssociations() {
}
public AddAssociations(Context preferredContext) {
setContext(preferredContext);
}
@Override
public String getName() {
return "Add Associations";
}
@Override
public String getDescription() {
return "Deprecated. Opens Wandora's schema association editor. "+
"Editor is used to add associations to the selected topic. "+
"Only schema defined associations can be added with this tool.";
}
@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()) {
SchemaAssociationPrompt prompt = new SchemaAssociationPrompt(wandora,topic,true);
prompt.setVisible(true);
if(!prompt.wasCancelled()) {
// ACTUAL ASSOCIATION CREATION IS IN THE ASSOCIATION PROMPT CLASS
}
}
}
else {
log("Context contains more than one topic! Unable to decide topic to add associations to.");
}
}
}
| 2,864 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
DeleteUnaryAssociations.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/associations/DeleteUnaryAssociations.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/>.
*
*
* DeleteUnaryAssociations.java
*
* Created on 2014-03-04, 12:00
*
*/
package org.wandora.application.tools.associations;
import java.util.Collection;
import java.util.LinkedHashSet;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.Context;
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;
/**
* Deletes associations that have zero or one player within.
*
* @author akivela
*/
public class DeleteUnaryAssociations extends DeleteAssociationsInTopic implements WandoraTool {
private static final long serialVersionUID = 1L;
public static final boolean LOOK_AT_ASSOCIATION_TYPES_TOO = true;
public DeleteUnaryAssociations() {
}
public DeleteUnaryAssociations(Context preferredContext) {
setContext(preferredContext);
}
@Override
public boolean shouldDelete(Topic topic, Association association) throws TopicMapException {
try {
if(association != null && !association.isRemoved()) {
if(association.getRoles().size() < 2) {
return super.confirmDelete(association);
}
else {
// Do not delete association if it has 2 or more players.
return false;
}
}
}
catch(Exception e) {
e.printStackTrace();
}
return false;
}
@Override
public Collection<Association> solveTopicAssociations(Topic topic) throws TopicMapException {
TopicMap tm = topic.getTopicMap();
Collection<Association> associations = new LinkedHashSet<>();
associations.addAll(topic.getAssociations());
if(LOOK_AT_ASSOCIATION_TYPES_TOO) {
Topic at = null;
for(Locator l : topic.getSubjectIdentifiers()) {
at = tm.getTopic(l);
if(at != null && !at.isRemoved()) {
associations.addAll( topic.getAssociations(at) );
}
}
}
return associations;
}
}
| 3,036 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
ModifyAssociation.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/associations/ModifyAssociation.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/>.
*
*
*
* ModifyAssociation.java
*
* Created on 24. lokakuuta 2005, 19:52
*
*/
package org.wandora.application.tools.associations;
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.gui.SchemaAssociationPrompt;
import org.wandora.application.tools.AbstractWandoraTool;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author akivela
* @deprecated
*/
public class ModifyAssociation extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
public ModifyAssociation() {
setContext(new AssociationContext());
}
public ModifyAssociation(Context preferredContext) {
setContext(preferredContext);
}
@Override
public String getName() {
return "Modify Association";
}
@Override
public String getDescription() {
return "Deprecated. Opens association editor. "+
"Editor is used to add and modify associations.";
}
public void execute(Wandora wandora, Context context) throws TopicMapException {
Iterator contextAssociations = context.getContextObjects();
if(contextAssociations == null || !contextAssociations.hasNext()) return;
Association association = (Association) contextAssociations.next();
if( !contextAssociations.hasNext() ) {
if(association != null) {
Topic topic = wandora.getOpenTopic();
SchemaAssociationPrompt prompt = new SchemaAssociationPrompt(wandora,topic,true,association);
prompt.setVisible(true);
}
}
else {
log("Context contains more than one association! Unable to decide association to modify.");
}
}
}
| 2,829 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
MergePlayers.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/associations/MergePlayers.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/>.
*
*
* MergePlayers.java
*
* Created on 2012-02-04
*
*/
package org.wandora.application.tools.associations;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
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.gui.table.AssociationTable;
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.TopicMapException;
/**
*
* @author akivela
*/
public class MergePlayers extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
private boolean requiresRefresh = false;
public MergePlayers() {
setContext(new AssociationContext());
}
public MergePlayers(Context preferredContext) {
setContext(preferredContext);
}
@Override
public String getName() {
return "Merge players";
}
@Override
public String getDescription() {
return "Merge selected association player topics per association. "+
"Doesn't remove duplicate players in associations.";
}
@Override
public boolean requiresRefresh() {
return requiresRefresh;
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
requiresRefresh = false;
Iterator associations = context.getContextObjects();
Association association = null;
int count = 0;
try {
if(associations != null && associations.hasNext()) {
AssociationTable associationTable = null;
Object contextSource = context.getContextSource();
if(contextSource instanceof AssociationTable) {
associationTable = (AssociationTable) context.getContextSource();
}
if(associationTable != null) {
Map<Association,List<Topic>> associationsWithSelectedRoles = associationTable.getSelectedAssociationsWithSelectedRoles();
Set<Association> associationKeys = associationsWithSelectedRoles.keySet();
Iterator<Association> associationKeyIterator = associationKeys.iterator();
while(associationKeyIterator.hasNext() && !forceStop()) {
association = (Association) associationKeyIterator.next();
if(association != null && !association.isRemoved()) {
List<Topic> mergeRoles = associationsWithSelectedRoles.get(association);
Topic mergedTopic = null;
for(Topic mergeRole : mergeRoles) {
Topic t = association.getPlayer(mergeRole);
if(t != null && !t.isRemoved()) {
if(mergedTopic == null) mergedTopic = t;
else {
Locator tsi = t.getOneSubjectIdentifier();
mergedTopic.addSubjectIdentifier(tsi);
requiresRefresh = true;
count++;
}
}
}
}
}
log("Total " + count + " associations processed.");
}
}
}
catch(Exception e) {
singleLog(e);
}
}
}
| 4,635 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
OpenEdgeTopic.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/associations/OpenEdgeTopic.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.associations;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
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.gui.WandoraOptionPane;
import org.wandora.application.gui.table.AssociationTable;
import org.wandora.application.tools.AbstractWandoraTool;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicTools;
/**
* <p>This tool is a companion for CopyEdgePath tool. While CopyEdgePath
* copies the player chain to system clipboard, OpenEdgeTopic travels to
* the last player and open it to Wandora's topic panel for detailed
* inspection.</p>
*
* <p>Think for example associations a-b, b-c, c-d. Letters represent
* player topics. All associations have same type and same roles. Now
* think you have selected association a-b and further the player topic a.
* Executing this tool in this context opens topic d to Wandora's
* topic panel. </p>
*
* @see CopyEdgePath
*
* @author akivela
*/
public class OpenEdgeTopic extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
public OpenEdgeTopic() {
setContext(new AssociationContext());
}
public OpenEdgeTopic(Context preferredContext) {
setContext(preferredContext);
}
@Override
public String getName() {
return "Open edge of associations";
}
@Override
public String getDescription() {
return "Find and open edge topic along given association(s)";
}
@Override
public void execute(Wandora wandora, Context context) {
try {
Map<Association,List<Topic>> associationsWithRoles = null;
Topic role = null;
Association a = null;
if(context instanceof AssociationContext) { // ASSOCIATION CONTEXT!!
AssociationTable associationTable = null;
Object contextSource = context.getContextSource();
if(contextSource instanceof AssociationTable) {
associationTable = (AssociationTable) context.getContextSource();
}
if(associationTable != null) {
associationsWithRoles = associationTable.getSelectedAssociationsWithSelectedRoles();
}
if(associationsWithRoles != null && associationsWithRoles.size() > 0) {
Set<Association> associationSet = associationsWithRoles.keySet();
Iterator<Association> associationIterator = associationSet.iterator();
if(associationIterator.hasNext() && !forceStop()) {
a = (Association) associationIterator.next();
if(a != null) {
List<Topic> roles = associationsWithRoles.get(a);
Iterator<Topic> roleIterator = roles.iterator();
if(roleIterator.hasNext() && !forceStop()) {
role = roleIterator.next();
if(role != null) {
try {
Topic outRole = findOtherRole(a, role, wandora);
if(outRole != null) {
Topic player = a.getPlayer(role);
Topic rootTopic = TopicTools.getEdgeTopic(player, a.getType(), role, outRole);
wandora.openTopic(rootTopic);
}
}
catch(Exception e) {
singleLog(e);
}
}
}
}
}
}
else {
singleLog("No associations found in context!");
}
}
else {
singleLog("Illegal context found! Expecting association context!");
}
}
catch(Exception e) {
singleLog(e);
}
}
private Topic findOtherRole(Association a, Topic r, Wandora wandora) {
Topic otherRole = null;
try {
Collection<Topic> allRoles = a.getRoles();
if(allRoles.size() < 3) {
for(Iterator<Topic> roleIterator = allRoles.iterator(); roleIterator.hasNext(); ) {
otherRole = roleIterator.next();
if(otherRole != null && !otherRole.isRemoved()) {
if(!otherRole.mergesWithTopic(r)) {
return otherRole;
}
}
}
}
else {
allRoles.remove(r);
Object answer = WandoraOptionPane.showOptionDialog(wandora, "Select second role for association travelsal", "Select second role", WandoraOptionPane.OK_CANCEL_OPTION, allRoles.toArray(), allRoles.iterator().next());
if(answer instanceof Topic) {
return (Topic) answer;
}
}
}
catch(Exception e) {
singleLog(e);
}
return null;
}
}
| 6,571 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
ChangeAssociationType.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/associations/ChangeAssociationType.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/>.
*
*
* ChangeAssociationType.java
*
* Created on 10. elokuuta 2006, 16:02
*
*/
package org.wandora.application.tools.associations;
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.Topic;
import org.wandora.topicmap.TopicMapException;
/**
* <p>
* Tool is used to changes association type of given associations. Multiple
* association can be modified at once. Tool requests new type topic.
* </p>
*
* @see ChangeAssociationRole
* @author akivela
*/
public class ChangeAssociationType extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
private boolean requiresRefresh = false;
public ChangeAssociationType() {
setContext(new AssociationContext());
}
public ChangeAssociationType(Context preferredContext) {
setContext(preferredContext);
}
@Override
public String getName() {
return "Change association type";
}
@Override
public String getDescription() {
return "Changes association type topics.";
}
@Override
public boolean requiresRefresh() {
return requiresRefresh;
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
requiresRefresh = false;
Iterator<Association> associations = context.getContextObjects();
Association association = null;
int count = 0;
if(associations != null && associations.hasNext()) {
Topic newType = wandora.showTopicFinder("Select new association type...");
if(newType == null) return;
Topic oldType = null;
while(associations.hasNext() && !forceStop()) {
association = (Association) associations.next();
if(association != null && !association.isRemoved()) {
oldType = association.getType();
if(oldType != null && !oldType.mergesWithTopic(newType)) {
requiresRefresh = true;
association.setType(newType);
count++;
}
}
}
}
log("Total " + count + " association type topics changed.");
}
}
| 3,389 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
DuplicateAssociationsOfType.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/associations/DuplicateAssociationsOfType.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/>.
*
*
*
* DuplicateAssociationsOfType.java
*
* Created on 21. joulukuuta 2004, 12:52
*/
package org.wandora.application.tools.associations;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
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.WandoraOptionPane;
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;
/**
* Duplicate associations of given type. New associations will be typed with a
* new association type.
*
* @author akivela
*/
public class DuplicateAssociationsOfType extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
private Topic theTopic = null;
private Topic oldAssociationType = null;
public boolean wasCancelled = false;
public boolean changeRoles = false;
public boolean removeAssociations = false;
private Map<Topic,Object> roleMap = new LinkedHashMap<>();
public DuplicateAssociationsOfType() {
}
public DuplicateAssociationsOfType(boolean shouldChangeRoles) {
changeRoles = shouldChangeRoles;
}
public DuplicateAssociationsOfType(boolean shouldChangeRoles, boolean shouldRemoveAssociations) {
changeRoles = shouldChangeRoles;
removeAssociations = shouldRemoveAssociations;
}
@Override
public String getName() {
return "Duplicate associations of type";
}
public void makeRoleMap(Wandora wandora) throws TopicMapException {
// BaseNamePrompt prompt=new BaseNamePrompt(wandora.getManager(), wandora, true);
roleMap = new LinkedHashMap<>();
//System.out.println("Type: " + oldAssociationType.getBaseName());
Collection<Association> associations = theTopic.getAssociations(oldAssociationType);
Iterator<Association> associationIterator = associations.iterator();
Association association = null;
Topic role = null;
while(associationIterator.hasNext()) {
association = (Association) associationIterator.next();
Collection<Topic> roles = association.getRoles();
for(Iterator<Topic> i2 = roles.iterator(); i2.hasNext(); ) {
role = (Topic) i2.next();
if(!roleMap.containsKey(role)) {
if(changeRoles) {
/* prompt.setTitle("Map role '" + getTopicName(role) + "' to...");
prompt.setVisible(true);
Topic newRole=prompt.getTopic();*/
Topic newRole=wandora.showTopicFinder("Map role '"+getTopicName(role)+"' to...");
if(newRole != null) {
roleMap.put(role, newRole);
}
else {
int answer = WandoraOptionPane.showConfirmDialog(wandora ,
"Would you like exclude players of role " + getTopicName(role) + " from the association? " +
"Press Yes to exclude players! "+
"Press No to use existing role topic!",
"Exclude role players or use existing role?",
WandoraOptionPane.YES_NO_OPTION);
if(answer == WandoraOptionPane.NO_OPTION) {
roleMap.put(role, role); // Don't change roles!
}
else {
roleMap.put(role, "EXCLUDE");
}
}
}
else {
roleMap.put(role, role); // Don't change roles!
}
}
}
}
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
theTopic = wandora.getOpenTopic();
oldAssociationType = (Topic) context.getContextObjects().next();
wasCancelled = false;
/*
BaseNamePrompt prompt=new BaseNamePrompt(wandora.getManager(), wandora, true);
prompt.setTitle("Select new association type...");
prompt.setVisible(true);
Topic newAssociationType=prompt.getTopic();
*/
Topic newAssociationType=wandora.showTopicFinder("Select new association type...");
if (newAssociationType != null) {
makeRoleMap(wandora);
//System.out.println("new type: " + newAssociationType.getBaseName());
if(theTopic != null) {
if(oldAssociationType != null) {
Collection<Association> ass = theTopic.getAssociations();
TopicMap topicMap = null;
List<Association> atemp = new ArrayList<>();
for(Iterator<Association> asi = ass.iterator(); asi.hasNext();) {
atemp.add(asi.next());
}
for(int i=0; i<atemp.size(); i++) {
Association a = (Association) atemp.get(i);
if(a.getType().equals(oldAssociationType)) {
topicMap = a.getTopicMap();
Association ca = topicMap.createAssociation(newAssociationType);
//System.out.println("new type: " + newAssociationType.getBaseName());
Collection<Topic> aRoles = a.getRoles();
for(Iterator<Topic> aRoleIter = aRoles.iterator(); aRoleIter.hasNext(); ) {
Topic role = (Topic) aRoleIter.next();
Topic player = a.getPlayer(role);
if(roleMap != null) {
if(roleMap.get(role) instanceof Topic) {
Topic mappedRole =(Topic) roleMap.get(role);
if(mappedRole != null && mappedRole instanceof Topic) {
//log("mapped role == " + mappedRole.getBaseName());
ca.addPlayer(player, mappedRole);
}
}
}
else {
//log("role == " + role.getBaseName());
ca.addPlayer(player, role);
}
}
if(! ca.equals(a) && removeAssociations) {
a.remove();
}
}
}
}
else {
log("Can't solve old association type!");
}
}
else {
log("Can't solve open topic!");
}
}
else {
wasCancelled = true;
}
}
}
| 8,273 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
MakeAssociationWithOccurrence.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/associations/MakeAssociationWithOccurrence.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/>.
*
*
* MakeAssociationWithOccurrence.java
*
* Created on 25. toukokuuta 2006, 10:57
*
*/
package org.wandora.application.tools.associations;
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.application.gui.WandoraOptionPane;
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;
import org.wandora.topicmap.TopicTools;
/**
* <p>
* <code>MakeAssociationWithOccurrence</code> transforms occurrences
* to associations creating first new topic representing the occurrence and then
* associating the old and the created topic.
* </p>
* <p>
* Association's type will be occurrence's type. New topic created for the occurrence
* is given role identical to occurrence's type. Topic that contains the original
* occurrence is given role pointed by the user. Tool may also delete original
* occurrence if <code>deleteOccurrence</code> is set true.
* </p>
* <p>
* The operation is lossy. Occurrences loose new line characters in transformation.
* Tool also truncates long occurrences.
* </p>
* <p>
* This tool is useful to refactor topic map created with data base import
* for example. See also <code>MakeOccurrenceFromAssociation</code> tool representing
* symmetric counterpart to <code>MakeAssociationWithOccurrence</code>.
* </p>
*
* @author akivela
*/
public class MakeAssociationWithOccurrence extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
public static int MAXLEN = 256;
public String replacement = "";
public String SITemplate = "http://wandora.org/si/occurrence/%OCCURRENCE%";
private boolean deleteOccurrence = false;
private boolean askTemplate = true;
private boolean requiresRefresh = false;
public MakeAssociationWithOccurrence() {
}
public MakeAssociationWithOccurrence(Context preferredContext) {
setContext(preferredContext);
}
@Override
public String getName() {
return "Make association with topic's occurrences";
}
@Override
public String getDescription() {
return "Iterates through selected topics and makes new topic from topic's occurrences and associates original topic to the new one.";
}
@Override
public boolean requiresRefresh() {
return requiresRefresh;
}
@Override
public void execute(Wandora wandora, Context context) {
try {
SITemplate = "http://wandora.org/si/occurrence/%OCCURRENCE%";
Iterator topics = context.getContextObjects();
if(topics == null || !topics.hasNext()) return;
Topic occurrenceType=wandora.showTopicFinder("Select occurrence type...");
if(occurrenceType == null) return;
Locator occurrenceTypeLocator = occurrenceType.getSubjectIdentifiers().iterator().next();
Topic occurrenceScope=wandora.showTopicFinder("Select occurrence scope...");
if(occurrenceScope == null) return;
Locator occurrenceScopeLocator = occurrenceScope.getSubjectIdentifiers().iterator().next();
Topic topicRole=wandora.showTopicFinder("Select topic's role in association...");
if(topicRole == null) return;
if(askTemplate) {
SITemplate = WandoraOptionPane.showInputDialog(wandora, "Make subject identifier to new topic using following template. String '%OCCURRENCE%' is replaced with the occurrence.", SITemplate);
if(SITemplate == null || SITemplate.length() == 0 || !SITemplate.contains("%OCCURRENCE%")) {
int a = WandoraOptionPane.showConfirmDialog(wandora, "Your template string '"+ SITemplate +"' does not contain '%OCCURRENCE%'. This results identical subject identifiers and topic merges. Are you sure you want to continue?", "Invalid template given", WandoraOptionPane.YES_NO_CANCEL_OPTION);
if(a != WandoraOptionPane.YES_OPTION) return;
}
}
setDefaultLogger();
setLogTitle("Making associations from occurrences");
log("Making associations from occurrences");
Topic topic = null;
String topicName = null;
Topic newTopic = null;
String SIString = null;
int progress = 0;
TopicMap map = wandora.getTopicMap();
Association a = null;
String occurrence = null;
Locator l = null;
ArrayList<Topic> dtopics = new ArrayList<Topic>();
while(topics.hasNext() && !forceStop()) {
dtopics.add((Topic) topics.next());
}
topics = dtopics.iterator();
// Iterate through selected topics...
while(topics.hasNext() && !forceStop()) {
try {
topic = (Topic) topics.next();
if(topic != null && !topic.isRemoved()) {
progress++;
hlog("Inspecting topic '"+getTopicName(topic)+"'");
occurrenceType = topic.getTopicMap().getTopic(occurrenceTypeLocator);
occurrenceScope = topic.getTopicMap().getTopic(occurrenceScopeLocator);
occurrence = topic.getData(occurrenceType, occurrenceScope);
// Ok, if topic has sufficient occurrence descent deeper...
if(occurrence != null && occurrence.length() > 0) {
log("Processing occurrence of topic '"+getTopicName(topic)+"'");
// First occurrence is modified to suit as the SI and base name...
if(occurrence.length() > MAXLEN) {
occurrence = occurrence.substring(0, MAXLEN);
}
if(occurrence.contains("\n") || occurrence.contains("\r")) {
occurrence = occurrence.replaceAll("\r", replacement);
occurrence = occurrence.replaceAll("\n", replacement);
}
occurrence = occurrence.trim();
requiresRefresh = true;
SIString = SITemplate;
SIString = SIString.replaceAll("%OCCURRENCE%", occurrence);
l = new Locator(TopicTools.cleanDirtyLocator(SIString));
// Check if required topic already exists
newTopic = map.getTopic(l);
if(newTopic == null) newTopic = map.getTopicWithBaseName(occurrence);
if(newTopic == null) {
// Creating new topic for the occurrence...
newTopic = map.createTopic();
// Giving new topic SI and base name
hlog("Creating new topic from occurrence '"+occurrence+"'");
newTopic.addSubjectIdentifier(l);
newTopic.setBaseName(occurrence);
}
// Topic name for gui use...
topicName = getTopicName(topic);
// Creating new association between old and new topic
hlog("Creating association between '"+occurrence+"' and '"+topicName+"'.");
a = map.createAssociation(occurrenceType);
a.addPlayer(newTopic, occurrenceType);
a.addPlayer(topic, topicRole);
// Finally deleting occurrence if...
if(deleteOccurrence) {
topic.removeData(occurrenceType);
}
}
}
}
catch(Exception e) {
log(e);
}
}
setState(WAIT);
}
catch (Exception e) {
log(e);
}
}
}
| 9,573 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
CopyAssociations.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/associations/CopyAssociations.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/>.
*
*
* CopyAssociations.java
*
* Created on 6. tammikuuta 2005, 16:23
*/
package org.wandora.application.tools.associations;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
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.gui.topicstringify.TopicToString;
import org.wandora.application.tools.AbstractWandoraTool;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
import org.wandora.utils.ClipboardBox;
/**
* <p>
* Tool is used to generate textual representations of given associations. Tool
* puts the generated association representation to system clipboard.
* </p>
* <p>
* Tool is capable to generate plain text and HTML table representation. Default
* format is plain text.
* </p>
*
* @author akivela
*/
public class CopyAssociations extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
public static final int WANDORA_LAYOUT = 5000;
public static final int LTM_LAYOUT = 5010;
public static final int TABTEXT_OUTPUT = 2000;
public static final int HTML_OUTPUT = 2010;
private int outputFormat = 0;
private int layout = WANDORA_LAYOUT;
public CopyAssociations(Wandora wandora, Context context) throws TopicMapException {
this(wandora, context, TABTEXT_OUTPUT);
}
public CopyAssociations(Wandora wandora, Context context, int outputFormat) throws TopicMapException {
this.outputFormat = outputFormat;
setContext(context);
}
public CopyAssociations(Wandora wandora, Context context, int outputFormat, int outputLayout) throws TopicMapException {
this.outputFormat = outputFormat;
this.layout = outputLayout;
setContext(context);
}
public CopyAssociations(Context context) {
this(context, TABTEXT_OUTPUT);
}
public CopyAssociations(Context context, int outputFormat) {
setContext(context);
this.outputFormat = outputFormat;
}
public CopyAssociations(Context context, int outputFormat, int outputLayout) {
setContext(context);
this.outputFormat = outputFormat;
this.layout = outputLayout;
}
public CopyAssociations(int outputFormat) {
this(new AssociationContext(), outputFormat);
}
public CopyAssociations(int outputFormat, int outputLayout) {
this(new AssociationContext(), outputFormat, outputLayout);
}
public CopyAssociations() {
this(new AssociationContext(), TABTEXT_OUTPUT);
}
// -------------------------------------------------------------------------
public void setOutputFormat(int outputFormat) {
this.outputFormat = outputFormat;
}
// -------------------------------------------------------------------------
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
String associationText = makeString(wandora);
if(associationText != null && associationText.length() > 0) {
ClipboardBox.setClipboard(associationText);
}
}
public String makeString(Wandora wandora) throws TopicMapException {
StringBuilder sb = new StringBuilder("");
Map<Topic,List<Map<Topic,Topic>>> associationsByType = new LinkedHashMap<>();
Map<Topic,Set<Topic>> rolesByType = new LinkedHashMap<>();
Iterator<Association> associations = null;
Iterator context = getContext().getContextObjects();
Association a = null;
Topic t = null;
Object aort = null;
int count = 0;
if(context != null) {
setDefaultLogger();
log("Copying associations...");
while(context.hasNext()) {
aort = context.next();
associations = null;
if(aort instanceof Topic) {
t = (Topic) aort;
associations = t.getAssociations().iterator();
}
else if(aort instanceof Association) {
a = (Association) aort;
List<Association> as = new ArrayList<>();
as.add(a);
associations = as.iterator();
}
if(associations == null) continue;
// Ok, at this point we should have a valid association iterator.
while(associations.hasNext()) {
count++;
setProgress(count);
a = (Association) associations.next();
Topic type = a.getType();
hlog("Copying association of type '" + getNameFor(type) + "'.");
List<Map<Topic, Topic>> typedAssociations = associationsByType.get(type);
if(typedAssociations == null) {
typedAssociations = new ArrayList<>();
}
Collection<Topic> aRoles = a.getRoles();
Set<Topic> roles = rolesByType.get(type);
if(roles == null) roles = new LinkedHashSet<>();
Map<Topic,Topic> association = new LinkedHashMap<>();
for(Iterator<Topic> aRoleIter = aRoles.iterator(); aRoleIter.hasNext(); ) {
Topic role = (Topic) aRoleIter.next();
Topic player = a.getPlayer(role);
association.put(role, player);
roles.add(role);
}
typedAssociations.add(association);
rolesByType.put(type, roles);
associationsByType.put(type, typedAssociations);
}
}
if(count != 0) {
log("Formatting output...");
boolean HTMLOutput = (outputFormat == HTML_OUTPUT);
// ----- Transform created data structure to text&html! -----
if(layout == WANDORA_LAYOUT) {
for(Topic associationType : associationsByType.keySet()) {
sb.append(getNameFor(associationType)).append("\n");
if(HTMLOutput) sb.append("<br>\n<table>\n<tr>");
for(Topic role : rolesByType.get(associationType)) {
if(HTMLOutput) sb.append("<td>");
sb.append(getNameFor(role));
if(HTMLOutput) sb.append("</td>");
else sb.append("\t");
}
sb.deleteCharAt(sb.length()-1); // remove last tabulator
if(HTMLOutput) sb.append("</tr>");
sb.append("\n");
for(Map<Topic,Topic> association : associationsByType.get(associationType)) {
if(HTMLOutput) sb.append("<tr>");
for(Topic role : rolesByType.get(associationType)) {
if(HTMLOutput) sb.append("<td>");
Topic player = association.get(role);
sb.append( getNameFor(player) );
if(HTMLOutput) sb.append("</td>");
else sb.append("\t");
}
sb.deleteCharAt(sb.length()-1); // remove last tabulator
if(HTMLOutput) sb.append("</tr>");
sb.append("\n");
}
if(HTMLOutput) sb.append("</table>");
sb.append("\n");
}
}
else if(layout == LTM_LAYOUT) {
for(Topic associationType : associationsByType.keySet()) {
if(HTMLOutput) sb.append("<br>\n<table>\n");
for(Map<Topic,Topic> association : associationsByType.get(associationType)) {
if(HTMLOutput) sb.append("<tr>");
if(HTMLOutput) sb.append("<td>");
sb.append(getNameFor(associationType));
if(HTMLOutput) sb.append("</td>");
else sb.append("\t");
for(Topic role : rolesByType.get(associationType)) {
Topic player = association.get(role);
if(player != null) {
if(HTMLOutput) sb.append("<td>");
sb.append( getNameFor(player) );
if(HTMLOutput) sb.append("</td>");
else sb.append("\t");
if(HTMLOutput) sb.append("<td>");
sb.append( getNameFor(role) );
if(HTMLOutput) sb.append("</td>");
else sb.append("\t");
}
}
sb.deleteCharAt(sb.length()-1); // remove last tabulator
if(HTMLOutput) sb.append("</tr>");
sb.append("\n");
}
if(HTMLOutput) sb.append("</table>");
sb.append("\n");
}
}
log("Total "+count+" associations copied.");
log("Total "+associationsByType.size()+" different association types found.");
}
else {
log("No associations found.");
}
log("Ready.");
setState(WAIT);
}
return(sb.toString());
}
public String getNameFor(Topic t) throws TopicMapException {
if(t != null) {
return TopicToString.toString(t);
}
return "";
}
@Override
public String getName() {
return "Copy associations";
}
@Override
public String getDescription() {
return "Copy selected associations to clipboard.";
}
@Override
public boolean requiresRefresh() {
return false;
}
}
| 11,734 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.