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
ModelClass.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/exporters/simberg/ModelClass.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.exporters.simberg; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; /** * * @author olli */ public class ModelClass { private String name; private final Set<ModelField> fields=new LinkedHashSet<ModelField>(); public ModelClass() { } public ModelClass(String name) { this.name = name; } public List<ModelField> getFields() { return new ArrayList<ModelField>(fields); } public ModelField findField(String fieldName){ for(ModelField field : fields){ if(field.getName().equals(fieldName)) return field; } return null; } public void addField(ModelField field){ fields.add(field); } public void setFields(List<ModelField> fields) { this.fields.clear(); this.fields.addAll(fields); } public boolean hasField(ModelField f){ return fields.contains(f); } public String getName() { return name; } public void setName(String name) { this.name = name; } }
1,957
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ModelField.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/exporters/simberg/ModelField.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.exporters.simberg; /** * * @author olli */ public class ModelField { private String name; private Type type; public ModelField() { } public ModelField(String name, Type type) { this.name = name; this.type = type; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Type getType() { return type; } public void setType(Type type) { this.type = type; } public static enum Type { String,StringList,Topic,TopicList } }
1,443
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ExportSite.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/exporters/site/ExportSite.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/>. * * * ExportSite.java * * Created on November 5, 2004, 5:20 PM */ package org.wandora.application.tools.exporters.site; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.event.ActionListener; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.InputStream; import java.io.PrintWriter; import java.net.MalformedURLException; import java.net.URL; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; import java.util.TreeMap; import javax.swing.Icon; import javax.swing.JButton; import javax.swing.JPanel; 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.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.gui.PasswordPrompt; import org.wandora.application.gui.UIBox; import org.wandora.application.tools.exporters.AbstractExportTool; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.utils.GripCollections; import org.wandora.utils.IObox; import org.wandora.utils.ImageBox; import org.wandora.utils.velocity.InstanceMaker; import org.wandora.utils.velocity.JavaScriptEncoder; import org.wandora.utils.velocity.TextBox; /** * <p> * ExportSite is a tool to export all topics to separate files, * using a velocity template. Normally velocity templates generate HTML * resulting interlinked HTML pages. * </p> * * @author pasi, ak */ public class ExportSite extends AbstractExportTool implements WandoraTool, ActionListener { private static final long serialVersionUID = 1L; public boolean EXPORT_SELECTION_INSTEAD_TOPIC_MAP = false; String templateEncoding = "UTF-8"; String topicmapfile = ""; String outputdir = "."; String siurl = null; String templatefile = "gui/export/sitepage.vhtml"; String pageindextemplatefile = "gui/export/siteindex.vhtml"; Wandora wandora = null; File currentDirectory = null; Object codec = null; Locale locale = Locale.getDefault(); TopicMap topicMap = null; boolean resizeImages = false; int resizeWidth = 320; int resizeHeight = 200; int resizeQuality = 75; PrintWriter log; private JButton button; private JPanel panel; private boolean forceStop; private boolean fetchUrls = true; private long napAfterFetch = 100; private String authUser = null; private String authPassword = null; boolean forgetAuth = false; boolean useScondaryUrlSource = false; String secondaryUrlSource = "http://127.0.0.1/wandora/wandora?lang=fi&action=geturl&url="; String logName = "export.log"; String filesDirectory = "files"; Topic currentTopic = null; ExportSiteDialog exportDialog = null; /** Creates a new instance of ExportSite */ public ExportSite() { this(GripCollections.addArrayToMap(new LinkedHashMap(),new Object[]{ "pageTemplate","gui/export/sitepage.vhtml", "indexTemplate","gui/export/siteindex.vhtml", "templateEncoding","UTF-8", "fetchUrls","false", "resizeImages","true", "imageWidth","800", "imageHeight","600", })); } public ExportSite(boolean exportSite) { this(); EXPORT_SELECTION_INSTEAD_TOPIC_MAP = exportSite; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/export_site.png"); } @Override public boolean requiresRefresh() { return false; } public ExportSite(Map map) { if(map != null) { for(Iterator i = map.keySet().iterator(); i.hasNext(); ) { Object key = i.next(); Object value = map.get(key); if(key instanceof String && value instanceof String && value != null) { String skey = (String) key; String svalue = (String) value; //log(" MAP: " + skey + " == " + svalue); if("pageTemplate".equalsIgnoreCase(skey)) templatefile = svalue; else if("indexTemplate".equalsIgnoreCase(skey)) pageindextemplatefile = svalue; else if("templateEncoding".equalsIgnoreCase(skey)) templateEncoding = svalue; else if("fetchUrls".equalsIgnoreCase(skey)) { try { fetchUrls = Boolean.valueOf(svalue).booleanValue(); } catch (Exception e) {} } else if("resizeImages".equalsIgnoreCase(skey)) { try { resizeImages = Boolean.valueOf(svalue).booleanValue(); } catch (Exception e) {} } else if("imageWidth".equalsIgnoreCase(skey)) { try { resizeWidth = Integer.parseInt(svalue); } catch (Exception e) {} } else if("imageHeight".equalsIgnoreCase(skey)) { try { resizeHeight = Integer.parseInt(svalue); } catch (Exception e) {} } else if("currentDirectory".equalsIgnoreCase(skey)) { try { outputdir = svalue; } catch (Exception e) { log(e); } } } } } } @Override public void execute(Wandora wandora, Context context) { forceStop = false; this.wandora = wandora; if(wandora!=null) { try { // --- Solve first topic map to be exported if(EXPORT_SELECTION_INSTEAD_TOPIC_MAP) { topicMap = makeTopicMapWith(context); } else { topicMap = solveContextTopicMap(wandora, context); } currentTopic = wandora.getOpenTopic(); if(exportDialog == null) { exportDialog = new ExportSiteDialog(wandora, true); exportDialog.setExportDirectory(outputdir); exportDialog.setPageTemplate(this.templatefile); exportDialog.setIndexTemplate(this.pageindextemplatefile); exportDialog.shouldImportSubjectLocators(this.fetchUrls); exportDialog.resizeImages(this.resizeImages); exportDialog.resizeImageWidth(this.resizeWidth); exportDialog.resizeImageHeight(this.resizeHeight); } exportDialog.setVisible(true); if(exportDialog.accept) { panel = new JPanel(); panel.setLayout(new FlowLayout()); button = new JButton("Stop"); button.addActionListener(this); button.setActionCommand("forcestop"); button.setPreferredSize(new Dimension(80, 23)); panel.add(button); setDefaultLogger(); if(exportDialog != null) { outputdir = exportDialog.getExportDirectory(); templatefile = exportDialog.getPageTemplate(); pageindextemplatefile = exportDialog.getIndexTemplate(); fetchUrls = exportDialog.shouldImportSubjectLocators(); resizeImages = exportDialog.shouldResizeImages(); resizeWidth = exportDialog.resizeImageWidth(); resizeHeight = exportDialog.resizeImageHeight(); } try { log = new PrintWriter(outputdir + "/" + logName); } catch (Exception e) { log = new PrintWriter(System.out); } work(); } } catch (Exception e) { log(e); } /* try { WandoraFileChooser chooser=new WandoraFileChooser(); chooser.setDialogTitle("Exported site to directory..."); chooser.setFileSelectionMode(WandoraFileChooser.DIRECTORIES_ONLY); chooser.setFileHidingEnabled(true); chooser.setDialogType(WandoraFileChooser.CUSTOM_DIALOG); chooser.setApproveButtonToolTipText("Export site to directory..."); if(chooser.open(wandora, "Export")==WandoraFileChooser.APPROVE_OPTION) { currentDirectory = chooser.getSelectedFile(); try { log = new PrintWriter(currentDirectory.getPath() + "/" + logName); } catch (Exception e) { log = new PrintWriter(System.out); } info = new InfoThread(wandora); panel = new JPanel(); panel.setLayout(new FlowLayout()); button = new JButton("Stop"); button.addActionListener(this); button.setActionCommand("forcestop"); button.setPreferredSize(new Dimension(80, 23)); panel.add(button); info = new InfoThread(parent, panel); info.start(); while(!info.dialog.isVisible()) { Thread.yield(); } // this will probably get executed from the ui thead so better not do anything big in this thread outputdir = chooser.getSelectedFile().getPath(); Thread worker = new Thread(this, getName()); worker.start(); } } catch (Exception e) { log(e); } **/ } } @Override public String getName() { return "Export site"; } @Override public String getDescription() { return "Exports topics as interlinked HTML pages generated with given Velocity template. "+ "Tool can also download subject locator resources to local files."; } public void work() { log.println("Export begins..."); log("Wait while exporting site..."); generateFilesFromTopicMap(topicMap, templatefile, templateEncoding, pageindextemplatefile, currentTopic, outputdir, locale, codec); log("Export finished. See '" + logName + "' for details!"); log.println("Export finished"); log.flush(); takeNap(2000); setState(WAIT); log.close(); } private void takeNap(long napTime) { try { Thread.sleep(napTime); } catch (Exception e) { } } // ------------------------------------------------------------------------- private TopicMap topicMapFromFile(String topicMapFileName) { File f = new File(topicMapFileName); try { return initTM(f.toURI().toURL().toString()); } catch (MalformedURLException mue) { log.println("topicMapFromFile(): file '"+f.getName()+"' produced MalformedURLException. Topic map not read."); } return null; } private TopicMap initTM(String uri) { TopicMap tm = null; try { InputStream in=new FileInputStream(uri); tm=new org.wandora.topicmap.memory.TopicMapImpl(); tm.importXTM(in); in.close(); } catch (Exception e) { e.printStackTrace(log); } return tm; } private void collectParams(Map<String,Object> localParams, Topic currentTopic, TopicMap topicMap, Locale loc) { localParams.put("lang", "en"); if (currentTopic!=null) { localParams.put("topic",currentTopic); } try { localParams.put("collectionmaker", new InstanceMaker("java.util.HashSet")); } catch (Exception e) {} try { localParams.put("listmaker", new InstanceMaker("java.util.ArrayList")); } catch (Exception e) {} try { localParams.put("mapmaker", new InstanceMaker("java.util.HashMap")); } catch (Exception e) {} try { localParams.put("stackmaker", new InstanceMaker("java.util.Stack")); } catch (Exception e) {} localParams.put("urlencoder", org.wandora.utils.velocity.URLEncoder.class); localParams.put("javascriptencoder", JavaScriptEncoder.class); localParams.put("tmbox", new org.wandora.topicmap.TMBox()); localParams.put("textbox", new TextBox()); localParams.put("intparser", Integer.valueOf(0)); // localParams.put("filter", new com.gripstudios.applications.assembly.AssemblyTopicFilter(new String[] { "http://wandora.org/si/common/picture", "http://wandora.org/si/common/video" }, "http://wandora.org/si/common/unmoderatedpicture" )); localParams.put("vhelper", new org.wandora.utils.velocity.VelocityMediaHelper()); localParams.put("helper", new org.wandora.topicmap.TopicTools()); localParams.put("topicmap", topicMap); } // Attempts to retrieve all external documents referenced by occurrences of the topic locally private void fetchSubjectLocator(Topic t, String directoryToStore, String filesDir, Map<String,String> urlmap) throws TopicMapException { if(t.getSubjectLocator() != null) { String mappedName = fetchURL(t.getSubjectLocator().toExternalForm(), directoryToStore, filesDir); if (mappedName!=null) { urlmap.put(t.getSubjectLocator().toExternalForm(), mappedName); } } } // Fetch url and store it locally unless fetchUrl is set false! private String fetchURL(String surl, String directoryStore, String filesDir) { if(fetchUrls == false) return surl; String localFileName = null; String mappedFileName = null; URL url = null; String fileName; log("Fetching external file\n" + surl); log.println("Fetching external file " + surl); if (surl.lastIndexOf("/") != -1) fileName = surl.substring(surl.lastIndexOf("/")); else fileName = surl; localFileName = directoryStore + File.separatorChar + filesDir + File.separatorChar + fileName; File f = new File(localFileName); File d = f.getParentFile(); if (d.mkdirs()) { log.println("Created directory '"+d.getAbsolutePath()+"' for file retrieved from url '"+surl+"'!"); } try { IObox.moveUrl(new URL(surl), f, authUser, authPassword, false); } catch (Exception e) { log(e); if(IObox.isAuthException(e)) { log.println("Authentication required to fecth url " + f.getPath()); boolean success = false; PasswordPrompt pp = new PasswordPrompt((Frame) wandora, true); pp.setTitle(surl); while(!success && !forgetAuth) { log.println("Consulting user!"); pp.setVisible(true); if(!pp.wasCancelled()) { authUser = pp.getUsername(); authPassword = new String(pp.getPassword()); try { success = true; IObox.moveUrl(new URL(surl), f, authUser, authPassword, false); } catch (Exception e1) { if(IObox.isAuthException(e1)) success = false; } } else { forgetAuth = true; authUser = null; authPassword = null; } } } else { if(useScondaryUrlSource) { try { IObox.moveUrl(new URL(secondaryUrlSource + surl), f); } catch (Exception e1) { e1.printStackTrace(log); } } else e.printStackTrace(log); } } if(resizeImages) { log("Trying to resize image\n" + f.getPath()); log.println("Trying to resize image " + f.getPath()); try { ImageBox.makeThumbnail(f.getPath(), f.getPath(), resizeWidth, resizeHeight, resizeQuality); } catch (Exception e) { e.printStackTrace(log); } } mappedFileName = "file://" + f.getPath(); takeNap(napAfterFetch); return mappedFileName; } public void generateFilesFromTopicMap(Object topicmap, String templatefilename, String templateEncoding, String indextemplatefilename, Topic currentTopic, String outputdir, Locale loc, Object codec) { forgetAuth = false; authUser = null; authPassword = null; TopicMap tm = null; Comparator c = java.text.Collator.getInstance(loc); Map index = new TreeMap(c); if (topicmap instanceof TopicMap) { tm = (TopicMap) topicmap; } else if (topicmap instanceof String) { tm = topicMapFromFile((String)topicmap); } Map<String,String> globalUrlMap = new HashMap<>(); VelocityContext context = null; Template template = null; //Template ntemplate = null; Template itemplate = null; FileWriter writer = null; File templateFile = null; //File nameTemplateFile; File indexTemplateFile = null; String templatePath = null; VelocityEngine velocityEngine = null; Map<String,Object> localParams; try { templateFile = new File(templatefilename); templatePath = templateFile.getParent(); 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(); if(templateEncoding != null && templateEncoding.length()>0) template = velocityEngine.getTemplate(templateFile.getName(), templateEncoding); else template = velocityEngine.getTemplate(templateFile.getName()); /* if (nametemplatefilename != null) { nameTemplateFile = new File(nametemplatefilename); if (templateEncoding != null && templateEncoding.length()>0) ntemplate = velocityEngine.getTemplate(nameTemplateFile.getName(), templateEncoding); else ntemplate = velocityEngine.getTemplate(nameTemplateFile.getName()); } */ if (indextemplatefilename != null) { indexTemplateFile = new File(indextemplatefilename); if (templateEncoding != null && templateEncoding.length()>0) itemplate = velocityEngine.getTemplate(indexTemplateFile.getName(), templateEncoding); else itemplate = velocityEngine.getTemplate(indexTemplateFile.getName()); } // --- Iterate topics --- for (java.util.Iterator<Topic> ti = tm.getTopics(); ti.hasNext() && !forceStop; ) { Topic t = (Topic)ti.next(); if(t == null || t.isRemoved()) continue; boolean isIndexFile = false; log("Exporting topic '" + getTopicName(t) + "'."); Map<String,String> urlMap = new LinkedHashMap<>(); fetchSubjectLocator(t, outputdir, filesDirectory, urlMap); localParams = new HashMap<>(); localParams.put("urlMap", urlMap); globalUrlMap.putAll(urlMap); collectParams( localParams, t, tm, loc); context = new VelocityContext(); for (Iterator<String> hit = localParams.keySet().iterator(); hit.hasNext(); ) { Object key = (String) hit.next(); if (key instanceof String && key != null) { Object value = localParams.get(key); context.put((String)key, value); } } if(codec != null) context.put("codec", codec); if(outputdir != null) context.put("outputdir", ""); // for generating files in proper directories String outputfilename = null; String fulloutputfilename = null; outputfilename = (t.getID().hashCode()) + ".html"; webPageIndexBuild(index, t, outputfilename, loc); fulloutputfilename = outputdir + File.separatorChar + outputfilename; writer = new FileWriter(fulloutputfilename); template.merge( context, writer ); writer.flush(); writer.close(); log.println("Generated output file '"+fulloutputfilename+"' for '"+getTopicName(t)+"'."); // --- create starthere.html --- if(t != null && currentTopic != null && t.mergesWithTopic(currentTopic)) { try { File f = new File(fulloutputfilename); File indexfile = new File(f.getParent()+File.separatorChar+"starthere.html"); FileOutputStream fos = new FileOutputStream(indexfile); indexfile.createNewFile(); FileInputStream fis = new FileInputStream(f); int b = -1; while ((b = fis.read()) != -1) { fos.write(b); } fos.close(); fis.close(); log.println("Created "+indexfile.getCanonicalPath()+" file as a copy of "+fulloutputfilename); } catch (Exception e) { log.println("Caught exception '"+e.getMessage()+"' while creating starthere.html file."); e.printStackTrace(log); } } log.flush(); } // --- time to output master index file --- log.println("Creating index.html"); localParams = new HashMap<>(); localParams.put("urlMap", globalUrlMap); collectParams(localParams, null, tm, loc); context = new VelocityContext(); context.put("index", index); log("Exporting index for the site!"); for (Iterator<String> hit = localParams.keySet().iterator(); hit.hasNext(); ) { Object key = (String) hit.next(); if (key instanceof String && key != null) { Object value = localParams.get(key); context.put((String)key, value); } } writer = new FileWriter(outputdir + File.separatorChar + "index.html"); itemplate.merge( context, writer ); writer.flush(); writer.close(); log.println("Generated page index file '"+outputdir + File.separatorChar + "index.html'"); } catch( ResourceNotFoundException rnfe ) { // couldn't find the template log("Unable to find specified template file for velocity export!"); log.println("Unable to find specified template file for velocity export!"); rnfe.printStackTrace(log); } catch( ParseErrorException pee ) { // syntax error : problem parsing the template log("Unable to parse the velocity template file! Parse exp:"+pee.getLocalizedMessage()); log.println("Unable to parse the velocity template file! Parse exp:"+pee.getLocalizedMessage()); pee.printStackTrace(log); } catch( MethodInvocationException mie ) { // something invoked in the template threw an exception log("Velocity template causes method invocation exception!"); log.println("Velocity template causes method invocation exception!"); mie.printStackTrace(log); } catch( Exception e ) { log("Exception '" + e.toString() + "' occurred while exporting site!"); log.println("Exception '" + e.toString() + "' occurred while exporting site!"); e.printStackTrace(log); } finally { if(writer != null) { try { writer.flush(); writer.close(); } catch (Exception e2) {} } } } private void webPageIndexBuild(Map index, Topic t, String webfilename, Locale loc) throws TopicMapException { String dname = t.getBaseName(); if (dname!=null) index.put(dname, webfilename); } @Override public void actionPerformed(java.awt.event.ActionEvent actionEvent) { String actionCommand = actionEvent.getActionCommand(); if("forcestop".equals(actionCommand)) { forceStop = true; log("Wait while stopping...\nThis may take few minutes depending on the current work phase!"); } } }
27,539
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ExportSiteDialog.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/exporters/site/ExportSiteDialog.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/>. * * * ExportSiteDialog.java * * Created on 6. tammikuuta 2005, 18:36 */ package org.wandora.application.tools.exporters.site; import java.io.File; import javax.swing.ComboBoxModel; import javax.swing.DefaultComboBoxModel; import org.wandora.application.Wandora; import org.wandora.application.gui.UIConstants; 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.SimpleFileChooser; import org.wandora.application.gui.simple.SimpleLabel; import org.wandora.application.gui.simple.SimpleTabbedPane; /** * * @author akivela <key>pageTemplate</key><value>classes/gui/export/sitepage.vhtml</value> <key>indexTemplate</key><value>classes/gui/export/siteindex.vhtml</value> <key>templateEncoding</key><value>ISO-8859-1</value> <key>fetchUrls</key><value>false</value> <key>resizeImages</key><value>true</value> <key>imageWidth</key><value>800</value> <key>imageHeight</key><value>600</value> * */ public class ExportSiteDialog extends javax.swing.JDialog { private static final long serialVersionUID = 1L; private Wandora wandora; public boolean accept = false; /** Creates new form ExportSiteDialog */ public ExportSiteDialog(Wandora wandora, boolean modal) { super(wandora, modal); this.wandora = wandora; initComponents(); hideSubjectLocatorPanels(); wandora.centerWindow(this); } public void hideSubjectLocatorPanels() { optionsTabbedPanel.remove(imagePanel); } public void viewSubjectLocatorPanels() { optionsTabbedPanel.addTab("Images", imagePanel); } public void toggleSubjectLocatorPanels() { if(importSLsCheckBox.isSelected()) { viewSubjectLocatorPanels(); } else { hideSubjectLocatorPanels(); } } /** 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; dialogPanel = new javax.swing.JPanel(); exportDirectoryPanel = new javax.swing.JPanel(); exportDirectoryLabel = new SimpleLabel(); exportDirectoryField = new SimpleField(); browseExportDirectoryButton = new SimpleButton(); optionsTabbedPanel = new SimpleTabbedPane(); subjectLocatorPanel = new javax.swing.JPanel(); importSLsCheckBox = new SimpleCheckBox(); templatePanel = new javax.swing.JPanel(); pageTemplatePanel = new javax.swing.JPanel(); pageTemplateLabel = new SimpleLabel(); pageTemplateField = new SimpleField(); browsePageTemplateButton = new SimpleButton(); indexTemplatePanel = new javax.swing.JPanel(); indexTemplateLabel = new SimpleLabel(); indexTemplateField = new SimpleField(); browseIndexTemplateButton = new SimpleButton(); templateEncodingPanel = new javax.swing.JPanel(); templateEncodingLabel = new SimpleLabel(); templateEncodingComboBox = new SimpleComboBox(); jPanel5 = new javax.swing.JPanel(); imagePanel = new javax.swing.JPanel(); jPanel10 = new javax.swing.JPanel(); resizeImagesCheckBox = new SimpleCheckBox(); jPanel7 = new javax.swing.JPanel(); newWidthLabel = new SimpleLabel(); newWidthField = new SimpleField(); jPanel8 = new javax.swing.JPanel(); newHeightLabel = new SimpleLabel(); newHeightField = new SimpleField(); buttonPanel = new javax.swing.JPanel(); jPanel1 = new javax.swing.JPanel(); exportButton = new SimpleButton(); cancelButton = new SimpleButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Export site"); setMinimumSize(new java.awt.Dimension(400, 300)); setPreferredSize(new java.awt.Dimension(640, 300)); getContentPane().setLayout(new java.awt.BorderLayout(10, 0)); dialogPanel.setMinimumSize(new java.awt.Dimension(400, 200)); dialogPanel.setLayout(new java.awt.GridBagLayout()); exportDirectoryPanel.setLayout(new java.awt.GridBagLayout()); exportDirectoryLabel.setText("Export into a directory"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3); exportDirectoryPanel.add(exportDirectoryLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3); exportDirectoryPanel.add(exportDirectoryField, gridBagConstraints); browseExportDirectoryButton.setText("Browse"); browseExportDirectoryButton.setMargin(new java.awt.Insets(2, 8, 2, 8)); browseExportDirectoryButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { browseExportDirectoryButtonActionPerformed(evt); } }); exportDirectoryPanel.add(browseExportDirectoryButton, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); dialogPanel.add(exportDirectoryPanel, gridBagConstraints); optionsTabbedPanel.setMinimumSize(new java.awt.Dimension(410, 150)); optionsTabbedPanel.setPreferredSize(new java.awt.Dimension(410, 150)); subjectLocatorPanel.setLayout(new java.awt.BorderLayout()); importSLsCheckBox.setText("Import Subject Locators"); importSLsCheckBox.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); importSLsCheckBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { importSLsCheckBoxActionPerformed(evt); } }); subjectLocatorPanel.add(importSLsCheckBox, java.awt.BorderLayout.CENTER); optionsTabbedPanel.addTab("Options", subjectLocatorPanel); templatePanel.setLayout(new java.awt.GridBagLayout()); pageTemplatePanel.setLayout(new java.awt.GridBagLayout()); pageTemplateLabel.setText("Page template"); pageTemplateLabel.setMinimumSize(new java.awt.Dimension(100, 14)); pageTemplateLabel.setPreferredSize(new java.awt.Dimension(100, 14)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3); pageTemplatePanel.add(pageTemplateLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3); pageTemplatePanel.add(pageTemplateField, gridBagConstraints); browsePageTemplateButton.setLabel("Browse"); browsePageTemplateButton.setMargin(new java.awt.Insets(2, 8, 2, 8)); browsePageTemplateButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { browsePageTemplateButtonActionPerformed(evt); } }); pageTemplatePanel.add(browsePageTemplateButton, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 12, 0, 12); templatePanel.add(pageTemplatePanel, gridBagConstraints); indexTemplatePanel.setLayout(new java.awt.GridBagLayout()); indexTemplateLabel.setText("Index template"); indexTemplateLabel.setMinimumSize(new java.awt.Dimension(100, 14)); indexTemplateLabel.setPreferredSize(new java.awt.Dimension(100, 14)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3); indexTemplatePanel.add(indexTemplateLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3); indexTemplatePanel.add(indexTemplateField, gridBagConstraints); browseIndexTemplateButton.setLabel("Browse"); browseIndexTemplateButton.setMargin(new java.awt.Insets(2, 8, 2, 8)); browseIndexTemplateButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { browseIndexTemplateButtonActionPerformed(evt); } }); indexTemplatePanel.add(browseIndexTemplateButton, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 12, 0, 12); templatePanel.add(indexTemplatePanel, gridBagConstraints); templateEncodingPanel.setLayout(new java.awt.GridBagLayout()); templateEncodingLabel.setText("Encoding"); templateEncodingLabel.setMinimumSize(new java.awt.Dimension(100, 14)); templateEncodingLabel.setPreferredSize(new java.awt.Dimension(100, 14)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3); templateEncodingPanel.add(templateEncodingLabel, gridBagConstraints); templateEncodingComboBox.setEditable(true); templateEncodingComboBox.setModel(getEncodings()); templateEncodingComboBox.setMinimumSize(new java.awt.Dimension(200, 20)); templateEncodingComboBox.setPreferredSize(new java.awt.Dimension(200, 25)); templateEncodingPanel.add(templateEncodingComboBox, new java.awt.GridBagConstraints()); jPanel5.setPreferredSize(new java.awt.Dimension(75, 10)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; templateEncodingPanel.add(jPanel5, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 12, 0, 12); templatePanel.add(templateEncodingPanel, gridBagConstraints); optionsTabbedPanel.addTab("Templates", templatePanel); imagePanel.setLayout(new java.awt.BorderLayout()); jPanel10.setLayout(new java.awt.GridBagLayout()); resizeImagesCheckBox.setText("Resize images"); resizeImagesCheckBox.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT); resizeImagesCheckBox.setMinimumSize(new java.awt.Dimension(120, 23)); resizeImagesCheckBox.setPreferredSize(new java.awt.Dimension(120, 23)); jPanel10.add(resizeImagesCheckBox, new java.awt.GridBagConstraints()); jPanel7.setMinimumSize(new java.awt.Dimension(115, 30)); newWidthLabel.setText("New width"); jPanel7.add(newWidthLabel); newWidthField.setPreferredSize(new java.awt.Dimension(50, 25)); jPanel7.add(newWidthField); jPanel10.add(jPanel7, new java.awt.GridBagConstraints()); jPanel8.setMinimumSize(new java.awt.Dimension(115, 30)); newHeightLabel.setText("New height"); jPanel8.add(newHeightLabel); newHeightField.setPreferredSize(new java.awt.Dimension(50, 25)); jPanel8.add(newHeightField); jPanel10.add(jPanel8, new java.awt.GridBagConstraints()); imagePanel.add(jPanel10, java.awt.BorderLayout.CENTER); optionsTabbedPanel.addTab("Images", imagePanel); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 10, 10, 10); dialogPanel.add(optionsTabbedPanel, gridBagConstraints); buttonPanel.setPreferredSize(new java.awt.Dimension(410, 30)); buttonPanel.setLayout(new java.awt.GridBagLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; buttonPanel.add(jPanel1, gridBagConstraints); exportButton.setText("Export"); exportButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exportButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3); buttonPanel.add(exportButton, gridBagConstraints); cancelButton.setText("Cancel"); 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, 0, 0, 4); buttonPanel.add(cancelButton, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 10, 10, 10); dialogPanel.add(buttonPanel, gridBagConstraints); getContentPane().add(dialogPanel, java.awt.BorderLayout.CENTER); pack(); }// </editor-fold>//GEN-END:initComponents private void importSLsCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_importSLsCheckBoxActionPerformed toggleSubjectLocatorPanels(); }//GEN-LAST:event_importSLsCheckBoxActionPerformed private void exportButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportButtonActionPerformed accept = true; this.setVisible(false); }//GEN-LAST:event_exportButtonActionPerformed private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed accept = false; this.setVisible(false); }//GEN-LAST:event_cancelButtonActionPerformed private void browseIndexTemplateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseIndexTemplateButtonActionPerformed String indexTemplateFile = selectFile(indexTemplateField.getText(), "Use page template..."); if(indexTemplateFile != null) indexTemplateField.setText(indexTemplateFile); }//GEN-LAST:event_browseIndexTemplateButtonActionPerformed private void browseExportDirectoryButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseExportDirectoryButtonActionPerformed String newDirectory = selectDirectory(exportDirectoryField.getText(), "Export site to directory..."); if(newDirectory != null) exportDirectoryField.setText(newDirectory); }//GEN-LAST:event_browseExportDirectoryButtonActionPerformed private void browsePageTemplateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browsePageTemplateButtonActionPerformed String pageTemplateFile = selectFile(pageTemplateField.getText(), "Use page template..."); if(pageTemplateFile != null) pageTemplateField.setText(pageTemplateFile); }//GEN-LAST:event_browsePageTemplateButtonActionPerformed private String selectDirectory(String currentDirectoryString, String title) { SimpleFileChooser chooser=UIConstants.getFileChooser(); File currentDirectory; if(currentDirectoryString != null && currentDirectoryString.length() > 0) { try { currentDirectory = new File(currentDirectoryString); if(currentDirectory != null) { chooser.setCurrentDirectory(currentDirectory.getParentFile()); chooser.setSelectedFile(currentDirectory); } } catch (Exception e) { e.printStackTrace(); } } chooser.setDialogTitle(title); chooser.setFileSelectionMode(SimpleFileChooser.DIRECTORIES_ONLY); chooser.setFileHidingEnabled(true); chooser.setDialogType(SimpleFileChooser.CUSTOM_DIALOG); chooser.setApproveButtonToolTipText("Select directory"); if(chooser.open(wandora, "Select")==SimpleFileChooser.APPROVE_OPTION) { currentDirectory = chooser.getSelectedFile(); return currentDirectory.getPath(); } return null; } private String selectFile(String currentFileString, String title) { SimpleFileChooser chooser=new SimpleFileChooser(); File currentFile; if(currentFileString != null && currentFileString.length() > 0) { try { currentFile = new File(currentFileString); if(currentFile != null) { chooser.setCurrentDirectory(currentFile.getParentFile()); chooser.setSelectedFile(currentFile); } } catch (Exception e) { e.printStackTrace(); } } chooser.setDialogTitle(title); chooser.setFileSelectionMode(SimpleFileChooser.FILES_ONLY); if(chooser.open(wandora, "Select")==SimpleFileChooser.APPROVE_OPTION) { currentFile = chooser.getSelectedFile(); return currentFile.getPath(); } return null; } public ComboBoxModel getEncodings() { return new DefaultComboBoxModel( new String[] { "UTF-8", "ISO-8859-1", "US-ASCII", "UTF-16" } ); } public String getExportDirectory() { return exportDirectoryField.getText(); } public String getPageTemplate() { return pageTemplateField.getText(); } public String getIndexTemplate() { return indexTemplateField.getText(); } public String getTemplateEncoding() { return templateEncodingComboBox.getSelectedItem().toString(); } public boolean shouldImportSubjectLocators() { return importSLsCheckBox.isSelected(); } public boolean shouldResizeImages() { return resizeImagesCheckBox.isSelected(); } public int resizeImageWidth() { try { return Integer.parseInt(newWidthField.getText()); } catch (Exception e) {} return 100; } public int resizeImageHeight() { try { return Integer.parseInt(newHeightField.getText()); } catch (Exception e) {} return 100; } public void setExportDirectory(String val) { exportDirectoryField.setText(val); } public void setPageTemplate(String val) { pageTemplateField.setText(val); } public void setIndexTemplate(String val) { indexTemplateField.setText(val); } public void setTemplateEncoding(String val) { templateEncodingComboBox.setSelectedItem(val); } public void shouldImportSubjectLocators(boolean val) { importSLsCheckBox.setSelected(val); } public void resizeImages(boolean val) { resizeImagesCheckBox.setSelected(val); } public void resizeImageWidth(int val) { newWidthField.setText("" + val); } public void resizeImageHeight(int val) { newHeightField.setText("" + val); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton browseExportDirectoryButton; private javax.swing.JButton browseIndexTemplateButton; private javax.swing.JButton browsePageTemplateButton; private javax.swing.JPanel buttonPanel; private javax.swing.JButton cancelButton; private javax.swing.JPanel dialogPanel; private javax.swing.JButton exportButton; private javax.swing.JTextField exportDirectoryField; private javax.swing.JLabel exportDirectoryLabel; private javax.swing.JPanel exportDirectoryPanel; private javax.swing.JPanel imagePanel; private javax.swing.JCheckBox importSLsCheckBox; private javax.swing.JTextField indexTemplateField; private javax.swing.JLabel indexTemplateLabel; private javax.swing.JPanel indexTemplatePanel; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel10; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel7; private javax.swing.JPanel jPanel8; private javax.swing.JTextField newHeightField; private javax.swing.JLabel newHeightLabel; private javax.swing.JTextField newWidthField; private javax.swing.JLabel newWidthLabel; private javax.swing.JTabbedPane optionsTabbedPanel; private javax.swing.JTextField pageTemplateField; private javax.swing.JLabel pageTemplateLabel; private javax.swing.JPanel pageTemplatePanel; private javax.swing.JCheckBox resizeImagesCheckBox; private javax.swing.JPanel subjectLocatorPanel; private javax.swing.JComboBox templateEncodingComboBox; private javax.swing.JLabel templateEncodingLabel; private javax.swing.JPanel templateEncodingPanel; private javax.swing.JPanel templatePanel; // End of variables declaration//GEN-END:variables }
23,907
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
FullIIIFBuilder.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/exporters/iiifexport/FullIIIFBuilder.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.exporters.iiifexport; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.application.tools.extractors.rdf.AbstractRDFExtractor; import org.wandora.application.tools.extractors.rdf.rdfmappings.DublinCoreMapping; import org.wandora.application.tools.extractors.rdf.rdfmappings.EXIFMapping; import org.wandora.application.tools.extractors.rdf.rdfmappings.OAMapping; import org.wandora.application.tools.extractors.rdf.rdfmappings.RDFMapping; import org.wandora.application.tools.extractors.rdf.rdfmappings.SCMapping; import org.wandora.application.tools.importers.SimpleRDFImport; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public class FullIIIFBuilder implements IIIFBuilder { @Override public Manifest buildIIIF(Wandora wandora, Context context, IIIFExport tool) throws TopicMapException { Iterator iter=context.getContextObjects(); if(!iter.hasNext()) return null; Topic topic=(Topic)iter.next(); return buildManifest(topic,tool); } protected void setItem(Object modelObject, String setter, Object value) throws TopicMapException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException { boolean languageString=false; Method setterMethod=null; if(value instanceof Integer){ try{ setterMethod=modelObject.getClass().getMethod(setter, Integer.TYPE); } catch(NoSuchMethodException nsme){ try{ setterMethod=modelObject.getClass().getMethod(setter, Integer.class); } catch(NoSuchMethodException nsme2){throw nsme;} } } else { try{ setterMethod=modelObject.getClass().getMethod(setter, String.class); } catch(NoSuchMethodException nsme){ try { languageString=true; setterMethod=modelObject.getClass().getMethod(setter, LanguageString.class); } catch(NoSuchMethodException nsme2){ throw nsme; } } } if(languageString) setterMethod.invoke(modelObject, new LanguageString((String)value)); else setterMethod.invoke(modelObject, value); } protected void copyOccurrenceInteger(Object modelObject, String setter, Topic t, String occurrenceType) throws TopicMapException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException { Topic type=t.getTopicMap().getTopic(occurrenceType); String o=t.getData(type, (String)null); if(o!=null) { try{ int i=Integer.parseInt(o); setItem(modelObject, setter, i); }catch(NumberFormatException nfe){} } } protected void copyOccurrence(Object modelObject, String setter, Topic t, String occurrenceType) throws TopicMapException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException { Topic type=t.getTopicMap().getTopic(occurrenceType); String o=t.getData(type, (String)null); if(o!=null) setItem(modelObject, setter, o); } protected void copyAssociationString(Object modelObject, String setter, Topic t, String associationType, String roleType) throws TopicMapException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException { Topic type=t.getTopicMap().getTopic(associationType); Topic role=t.getTopicMap().getTopic(roleType); if(type==null || role==null) return; ArrayList<Association> as=new ArrayList<>(t.getAssociations(type)); for(Association a : as){ Topic p=a.getPlayer(role); if(p!=null && !p.mergesWithTopic(t) && p.getBaseName()!=null) { setItem(modelObject,setter, p.getBaseName()); break; } } } protected void copyAssociationSI(Object modelObject, String setter, Topic t, String associationType, String roleType) throws TopicMapException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException { Topic type=t.getTopicMap().getTopic(associationType); Topic role=t.getTopicMap().getTopic(roleType); if(type==null || role==null) return; ArrayList<Association> as=new ArrayList<>(t.getAssociations(type)); for(Association a : as){ Topic p=a.getPlayer(role); if(p!=null && !p.mergesWithTopic(t)) { setItem(modelObject,setter, p.getOneSubjectIdentifier().toExternalForm()); break; } } } protected boolean orderByOrderRole(ArrayList<Association> associations) throws TopicMapException { if(associations.isEmpty()) return false; TopicMap tm=associations.get(0).getTopicMap(); final Topic orderTopic=tm.getTopic(AbstractRDFExtractor.RDF_LIST_ORDER); if(orderTopic==null) return false; Collections.sort(associations,new Comparator<Association>(){ @Override public int compare(Association o1, Association o2) { try{ Topic t1=o1.getPlayer(orderTopic); Topic t2=o2.getPlayer(orderTopic); if(t1!=null && t2!=null) { String bn1=t1.getBaseName(); String bn2=t2.getBaseName(); if(bn1!=null && bn2!=null){ int i1=-1; int i2=-1; try{ i1=Integer.parseInt(bn1); } catch(NumberFormatException nfe){} try{ i2=Integer.parseInt(bn2); } catch(NumberFormatException nfe){} return i2-i1; } else if(bn1!=null) return -1; else if(bn2!=null) return 1; else return 0; } else if(t1!=null) return -1; else if(t2!=null) return 1; else return 0; }catch(TopicMapException tme){ return 0; } } }); return true; } protected Manifest buildManifest(Topic t,IIIFExport tool) throws TopicMapException { TopicMap tm=t.getTopicMap(); Manifest m=new Manifest(); String name=t.getDisplayName(); if(name!=null) m.addLabel(new LanguageString(name)); try{ copyOccurrence(m, "addAttribution", t, SCMapping.SC_NS+"attributionLabel"); copyOccurrence(m, "addDescription", t, DublinCoreMapping.DC_ELEMENTS_NS+"description"); } catch(IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e){ tool.log(e); } m.setId(t.getOneSubjectIdentifier().toExternalForm()); Topic hasSequences=tm.getTopic(SCMapping.SC_NS+"hasSequences"); if(hasSequences!=null){ ArrayList<Association> sequences=new ArrayList<>(t.getAssociations(hasSequences)); Topic sequenceType=tm.getTopic(SCMapping.SC_NS+"Sequence"); if(sequenceType!=null){ orderByOrderRole(sequences); for(Association a : sequences){ Topic sequence=a.getPlayer(sequenceType); if(sequence!=null){ Sequence s=buildSequence(sequence,tool); if(s!=null) m.addSequence(s); } } } } return m; } protected Sequence buildSequence(Topic t,IIIFExport tool) throws TopicMapException { TopicMap tm=t.getTopicMap(); Sequence s=new Sequence(); String name=t.getDisplayName(); if(name!=null) s.addLabel(new LanguageString(name)); try{ copyOccurrence(s, "addAttribution", t, SCMapping.SC_NS+"attributionLabel"); copyOccurrence(s, "addDescription", t, DublinCoreMapping.DC_ELEMENTS_NS+"description"); } catch(IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e){ tool.log(e); } s.setId(t.getOneSubjectIdentifier().toExternalForm()); Topic hasCanvases=tm.getTopic(SCMapping.SC_NS+"hasCanvases"); if(hasCanvases!=null){ ArrayList<Association> canvases=new ArrayList<>(t.getAssociations(hasCanvases)); Topic canvasType=tm.getTopic(SCMapping.SC_NS+"Canvas"); if(canvasType!=null){ orderByOrderRole(canvases); for(Association a : canvases){ Topic canvas=a.getPlayer(canvasType); if(canvas!=null){ Canvas c=buildCanvas(canvas,tool); if(c!=null) s.addCanvas(c); } } } } return s; } protected Canvas buildCanvas(Topic t,IIIFExport tool) throws TopicMapException { TopicMap tm=t.getTopicMap(); Canvas c=new Canvas(); String name=t.getDisplayName(); if(name!=null) c.addLabel(new LanguageString(name)); try{ copyOccurrence(c, "addDescription", t, DublinCoreMapping.DC_ELEMENTS_NS+"description"); copyOccurrenceInteger(c, "setWidth", t, EXIFMapping.EXIF_NS+"width"); copyOccurrenceInteger(c, "setHeight", t, EXIFMapping.EXIF_NS+"height"); } catch(IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e){ tool.log(e); } c.setId(t.getOneSubjectIdentifier().toExternalForm()); Topic hasImageAnnotations=tm.getTopic(SCMapping.SC_NS+"hasImageAnnotations"); if(hasImageAnnotations!=null){ ArrayList<Association> imageAnnotations=new ArrayList<>(t.getAssociations(hasImageAnnotations)); Topic imageAnnotationType=tm.getTopic(OAMapping.OA_NS+"Annotation"); if(imageAnnotationType!=null){ orderByOrderRole(imageAnnotations); for(Association a : imageAnnotations){ Topic imageAnnotation=a.getPlayer(imageAnnotationType); if(imageAnnotation!=null){ Content co=buildContent(imageAnnotation,tool); if(co!=null) c.addImage(co); } } } } return c; } protected Content buildContent(Topic t, IIIFExport tool) throws TopicMapException { TopicMap tm=t.getTopicMap(); Content c=new Content(); String name=t.getDisplayName(); if(name!=null) c.addLabel(new LanguageString(name)); try{ copyAssociationString(c, "setMotivation", t, OAMapping.OA_NS+"motivatedBy", OAMapping.OA_NS+"Motivation"); } catch(IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e){ tool.log(e); } c.setId(t.getOneSubjectIdentifier().toExternalForm()); c.setResourceType(Content.RESOURCE_TYPE_IMAGE); Topic hasBody=tm.getTopic(OAMapping.OA_NS+"hasBody"); Topic rdfObject=tm.getTopic(RDFMapping.RDF_NS+"object"); if(hasBody!=null && rdfObject!=null){ ArrayList<Association> bodies=new ArrayList<>(t.getAssociations(hasBody)); if(!bodies.isEmpty()) { Topic body=bodies.get(0).getPlayer(rdfObject); if(body!=null){ addContentBody(c, body, tool); } } } return c; } protected void addContentBody(Content c, Topic t, IIIFExport tool) throws TopicMapException { TopicMap tm=t.getTopicMap(); try{ copyOccurrenceInteger(c, "setWidth", t, EXIFMapping.EXIF_NS+"width"); copyOccurrenceInteger(c, "setHeight", t, EXIFMapping.EXIF_NS+"height"); copyOccurrence(c, "setFormat", t, DublinCoreMapping.DC_ELEMENTS_NS+"format"); } catch(IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e){ tool.log(e); } Locator l=t.getSubjectLocator(); if(l==null) l=t.getOneSubjectIdentifier(); c.setResourceId(l.toExternalForm()); Topic hasService=tm.getTopic(SCMapping.SC_NS+"hasRelatedService"); Topic rdfObject=tm.getTopic(RDFMapping.RDF_NS+"object"); if(hasService!=null && rdfObject!=null){ ArrayList<Association> services=new ArrayList<>(t.getAssociations(hasService)); for(Association a : services){ Topic service=a.getPlayer(rdfObject); if(service!=null){ Service s=buildService(service, tool); if(s!=null) c.addResourceService(s); } } } } protected Service buildService(Topic t, IIIFExport tool) throws TopicMapException { TopicMap tm=t.getTopicMap(); Service s=new Service(); try{ copyAssociationSI(s, "setProfile", t, DublinCoreMapping.DC_TERMS_NS+"conformsTo", SimpleRDFImport.objectTypeSI); } catch(IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e){ tool.log(e); } s.setId(t.getOneSubjectIdentifier().toExternalForm()); return s; } @Override public String getBuilderName() { return "Full IIIF Builder"; } }
15,672
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
JsonLDOutput.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/exporters/iiifexport/JsonLDOutput.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.exporters.iiifexport; /** * * @author olli */ public interface JsonLDOutput { public JsonLD toJsonLD(); }
959
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
JsonLD.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/exporters/iiifexport/JsonLD.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.exporters.iiifexport; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; /** * * @author olli */ public class JsonLD { protected Object unstructuredValue=null; protected final LinkedHashMap<String,Object> map=new LinkedHashMap<>(); public JsonLD(){ } public JsonLD(Object unstructuredValue){ this.unstructuredValue=unstructuredValue; } public JsonLD append(String key,Object val){ map.put(key, toJsonLD(val)); return this; } public JsonLD appendNotNull(String key,Object val){ if(val!=null) map.put(key,toJsonLD(val)); return this; } public JsonLD appendNotEmpty(String key, Collection val, boolean unwrapSingle){ if(!val.isEmpty()) append(key,val,unwrapSingle); return this; } public JsonLD append(String key, Collection val, boolean unwrapSingle){ if(unwrapSingle && val.size()==1) append(key,val.iterator().next()); else append(key,val); return this; } private Object toJsonLD(Object o){ if(o==null) return null; else if(o instanceof JsonLD) return o; else if(o instanceof JsonLDOutput){ return ((JsonLDOutput)o).toJsonLD(); } else if(o instanceof Number) return o; else if(o instanceof Iterable){ ArrayList<Object> list=new ArrayList<>(); for(Object o2 : (Iterable)o){ list.add(toJsonLD(o2)); } return list; } else if(o instanceof Map){ JsonLD jsonLD=new JsonLD(); for(Map.Entry<?,?> e : ((Map<?,?>)o).entrySet()){ jsonLD.append(e.getKey().toString(), e.getValue()); } return jsonLD; } else return o.toString(); } public static String jsonLDString(String s){ return "\""+s.replace("\\", "\\\\").replace("\"","\\\"").replace("\n","\\n")+"\""; } public String outputJson(boolean pretty){ StringBuilder sb=new StringBuilder(); outputJson(sb,pretty?"":null); return sb.toString(); } public void outputJsonValue(Object val,StringBuilder sb,String indent){ boolean pretty=(indent!=null); if(val==null){ sb.append("null"); } else if(val instanceof JsonLD){ ((JsonLD)val).outputJson(sb, indent); } else if(val instanceof ArrayList){ ArrayList l=(ArrayList)val; if(l.isEmpty()) sb.append("[]"); else if(l.size()==1){ sb.append("["); outputJsonValue(l.get(0),sb,indent); sb.append("]"); } else { sb.append("["); boolean first=true; for(Object o : l){ if(!first) sb.append(", "); else first=false; if(pretty) sb.append("\n").append(indent).append("\t"); outputJsonValue(o,sb,indent+"\t"); } if(pretty) sb.append("\n").append(indent); sb.append("]"); } } else if(val instanceof Number){ sb.append(val.toString()); } else { sb.append(jsonLDString(val.toString())); } } public void outputJson(StringBuilder sb,String indent){ if(unstructuredValue!=null) { outputJsonValue(unstructuredValue, sb, indent); return; } boolean pretty=(indent!=null); sb.append("{"); boolean first=true; for(Map.Entry<String,Object> e : map.entrySet() ){ if(!first) sb.append(", "); else first=false; if(pretty) sb.append("\n").append(indent).append("\t"); sb.append(jsonLDString(e.getKey())); sb.append(": "); outputJsonValue(e.getValue(), sb, indent+"\t"); } if(pretty && !map.isEmpty()) sb.append("\n").append(indent); sb.append("}"); } }
5,076
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
IIIFExport.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/exporters/iiifexport/IIIFExport.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.exporters.iiifexport; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import org.wandora.application.Wandora; import org.wandora.application.WandoraToolType; import org.wandora.application.contexts.Context; import org.wandora.application.gui.UIConstants; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.application.gui.simple.SimpleFileChooser; import org.wandora.application.tools.GenericOptionsDialog; import org.wandora.application.tools.exporters.AbstractExportTool; import org.wandora.topicmap.TopicMapException; import org.wandora.utils.Options; /** * * @author olli */ public class IIIFExport extends AbstractExportTool { protected HashMap<String,String> options; protected IIIFBuilder selectedBuilder; protected boolean prettyPrint=true; @Override public WandoraToolType getType() { return WandoraToolType.createExportType(); } @Override public String getDescription() { return "Exports image data in IIIF format JSON-LD"; } @Override public String getName() { return "IIIF Export"; } public ArrayList<IIIFBuilder> getBuilders(){ // TODO: smart scanning of builders ArrayList<IIIFBuilder> al=new ArrayList<>(); al.add(new SimpleSelectionIIIFBuilder()); al.add(new SelectionInstancesIIIFBuilder()); al.add(new FullIIIFBuilder()); return al; } public IIIFBuilder resolveBuilder(String name){ ArrayList<IIIFBuilder> builders=getBuilders(); for(IIIFBuilder builder : builders){ if(builder.getBuilderName().equals(name)) { return builder; } } return null; } @Override public void initialize(Wandora wandora, Options options, String prefix) throws TopicMapException { super.initialize(wandora, options, prefix); if(options!=null){ String builderStr=options.get(prefix+"builder"); selectedBuilder=null; ArrayList<IIIFBuilder> builders=getBuilders(); if(builderStr!=null){ selectedBuilder=resolveBuilder(builderStr); if(selectedBuilder==null){ WandoraOptionPane.showMessageDialog(wandora, "Cannot find IIIF builder \""+builderStr+"\" which was specified in options."); } } if(selectedBuilder==null){ selectedBuilder=builders.get(0); } prettyPrint=options.getBoolean(prefix+"prettyprint",prettyPrint); } } @Override public void writeOptions(Wandora wandora, Options options, String prefix) { if(selectedBuilder!=null) options.put(prefix+"builder",selectedBuilder.getBuilderName()); options.put(prefix+"prettyprint",""+prettyPrint); } @Override public void configure(Wandora wandora, Options options, String prefix) throws TopicMapException { ArrayList<IIIFBuilder> builders=getBuilders(); String builderOptions=""; for(IIIFBuilder builder : builders){ if(!builderOptions.isEmpty()) builderOptions+=";"; builderOptions+=builder.getBuilderName(); } GenericOptionsDialog god=new GenericOptionsDialog(wandora, "IIIF Export options", "Options for IIIF Export", true, new String[][]{ new String[]{"IIIF Builder","combo:"+builderOptions,builders.get(0).getBuilderName(),"Select the builder that transforms topic map constructs into the IIIF model"}, new String[]{"Pretty print","boolean",""+prettyPrint,"Add line feeds and tabs into output"} }, wandora); god.setVisible(true); if(!god.wasCancelled()){ Map values=god.getValues(); String builderStr=values.get("IIIF Builder").toString(); selectedBuilder=resolveBuilder(builderStr); options.put(prefix+"builder", builderStr); prettyPrint=Boolean.parseBoolean(values.get("Pretty print").toString()); options.put(prefix+"prettyprint", ""+prettyPrint); } } /* These two methods are mostly intended for situations where the export is inside other code and normal configuration dialogs and options mechanics are skipped. */ public void setBuilder(IIIFBuilder builder){ selectedBuilder=builder; } public void setPrettyPrint(boolean p){ prettyPrint=p; } @Override public boolean isConfigurable() { return true; } @Override public void execute(Wandora wandora, Context context) throws TopicMapException { SimpleFileChooser chooser=UIConstants.getFileChooser(); chooser.setDialogTitle("IIIF Export"); if(chooser.open(wandora, "Export")==SimpleFileChooser.APPROVE_OPTION){ setDefaultLogger(); File file = chooser.getSelectedFile(); Manifest m=selectedBuilder.buildIIIF(wandora, context, this); StringBuilder sb=new StringBuilder(); m.toJsonLD().outputJson(sb, prettyPrint?"":null ); try (FileOutputStream os=new FileOutputStream(file)) { OutputStreamWriter out=new OutputStreamWriter(os,"UTF-8"); out.write(sb.toString()); out.flush(); } catch(IOException ioe){ log(ioe); } setState(WAIT); } } }
6,582
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ModelBase.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/exporters/iiifexport/ModelBase.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.exporters.iiifexport; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; /** * Base class for the different IIIF model objects. All the different model * objects have mostly the same fields so they are all defined here. What's * different between the different model objects is which fields are required * and which are only optional. Some fields may also be automatically set by * different model class implementations. * * See http://iiif.io/api/presentation/2.0/ for details. * * @author olli */ public class ModelBase implements JsonLDOutput { protected final ArrayList<LanguageString> label=new ArrayList<>(); protected final HashMap<String,ArrayList<LanguageString>> metaData=new HashMap<>(); protected final ArrayList<LanguageString> description=new ArrayList<>(); protected String thumbnail; protected final ArrayList<LanguageString> attribution=new ArrayList<>(); protected String logo; protected String license; protected String id; protected String type; // format specified in content only // width and height specified in canvas and content only // viewingDirection specified in manifest and sequence only protected String viewingHint; protected final ArrayList<String> related=new ArrayList<>(); protected final ArrayList<String> seeAlso=new ArrayList<>(); protected String within; protected final ArrayList<Service> service=new ArrayList<>(); // json-ld context protected final ArrayList<String> context=new ArrayList<>(); /** * Check that the fields have legal values. Mostly only checks that * the required fields have some value rather than null. * * TODO: add some checks, also subclasses * * @return true if all fields are valid. */ public boolean validateFields(){ return true; } public void addContext(String context){ this.context.add(context); } public void addLabel(LanguageString label){ this.label.add(label); } public void addMetaData(String key,LanguageString value){ if(!metaData.containsKey(key)) metaData.put(key, new ArrayList<LanguageString>()); ArrayList<LanguageString> l=metaData.get(key); l.add(value); } public void addDescription(LanguageString description){ this.description.add(description); } public void addAttribution(LanguageString attribution){ this.attribution.add(attribution); } public void addRelated(String related){ this.related.add(related); } public void addSeeAlso(String seeAlso){ this.seeAlso.add(seeAlso); } public void addService(Service service){ this.service.add(service); } public ArrayList<String> getContextsList(){ return context; } public ArrayList<LanguageString> getLabelsList() { return label; } public HashMap<String, ArrayList<LanguageString>> getMetaDataMap() { return metaData; } public ArrayList<LanguageString> getDescriptionsList() { return description; } public ArrayList<LanguageString> getAttributionsList() { return attribution; } public ArrayList<String> getRelatedList() { return related; } public ArrayList<String> getSeeAlsoList() { return seeAlso; } public ArrayList<Service> getServicesList() { return service; } public String getThumbnail() { return thumbnail; } public void setThumbnail(String thumbnail) { this.thumbnail = thumbnail; } public String getLogo() { return logo; } public void setLogo(String logo) { this.logo = logo; } public String getLicense() { return license; } public void setLicense(String license) { this.license = license; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getViewingHint() { return viewingHint; } public void setViewingHint(String viewingHint) { this.viewingHint = viewingHint; } public String getWithin() { return within; } public void setWithin(String within) { this.within = within; } public ArrayList<JsonLD> metaDataToJsonLD(){ ArrayList<JsonLD> ret=new ArrayList<>(); for(Map.Entry<String,ArrayList<LanguageString>> e : metaData.entrySet()){ if(e.getValue().isEmpty()) continue; JsonLD jsonLD=new JsonLD(); jsonLD.append("label",e.getKey()); jsonLD.appendNotEmpty("value", e.getValue(), true); ret.add(jsonLD); } return ret; } @Override public JsonLD toJsonLD() { JsonLD jsonLD=new JsonLD(); jsonLD.appendNotEmpty("@context", context, true) .appendNotNull("@type", type) .appendNotNull("@id", id) .appendNotEmpty("label", label, true) .appendNotNull("metadata",metaData.isEmpty()?null:metaDataToJsonLD()) .appendNotEmpty("description", description, true) .appendNotEmpty("attribution", attribution, true) .appendNotNull("logo", logo) .appendNotNull("license", license) .appendNotNull("viewingHint", viewingHint) .appendNotEmpty("related", related, true) .appendNotEmpty("seeAlso", seeAlso, true) .appendNotNull("within", within) .appendNotEmpty("service", service, true); return jsonLD; } public static enum ViewingDirection { leftToRight("left-to-right"), rightToLeft("right-to-left"), topToBottom("top-to-bottom"), bottomToTop("bottom-to-top"); private String label; private ViewingDirection(String label){ this.label=label; } @Override public String toString(){return label;} } }
7,131
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SelectionInstancesIIIFBuilder.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/exporters/iiifexport/SelectionInstancesIIIFBuilder.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.exporters.iiifexport; import java.util.Iterator; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicHashSet; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public class SelectionInstancesIIIFBuilder extends SimpleSelectionIIIFBuilder { @Override public String getBuilderName(){ return "Selection Instances Builder"; } @Override protected void processTopics(Wandora wandora,Context context, Sequence sequence,IIIFExport tool) throws TopicMapException { TopicHashSet processed=new TopicHashSet(); Iterator iter=context.getContextObjects(); while(iter.hasNext()){ Object o=iter.next(); if(!(o instanceof Topic)) continue; Topic t=(Topic)o; for(Topic instance : t.getTopicMap().getTopicsOfType(t)){ if(processed.add(instance)){ processTopic(instance, sequence, tool); } } } } }
1,985
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
LanguageString.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/exporters/iiifexport/LanguageString.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.exporters.iiifexport; /** * * @author olli */ public class LanguageString implements JsonLDOutput { private String content; private String language; public LanguageString(String content){ this(content,null); } public LanguageString(String content,String language){ this.content=content; this.language=language; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } @Override public JsonLD toJsonLD(){ if(language==null) return new JsonLD(content); else return new JsonLD().append("@value",content) .append("@language",language); } }
1,743
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Service.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/exporters/iiifexport/Service.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.exporters.iiifexport; /** * * @author olli */ public class Service implements JsonLDOutput { public static final String IIIF_IMAGE_API_LEVEL_1="http://library.stanford.edu/iiif/image-api/1.1/conformance.html#level1"; protected String id; protected String profile; public Service(){ } public Service(String id, String profile) { this.id = id; this.profile = profile; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getProfile() { return profile; } public void setProfile(String profile) { this.profile = profile; } @Override public JsonLD toJsonLD() { JsonLD jsonLD=new JsonLD(); jsonLD.append("@id",id) .appendNotNull("profile",profile); return jsonLD; } }
1,766
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Manifest.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/exporters/iiifexport/Manifest.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.exporters.iiifexport; import java.util.ArrayList; /** * * @author olli */ public class Manifest extends ModelBase { protected ViewingDirection viewingDirection; protected final ArrayList<Sequence> sequences=new ArrayList<>(); public Manifest(){ addContext("http://iiif.io/api/presentation/2/context.json"); setType("sc:Manifest"); } public void addSequence(Sequence sequence){ this.sequences.add(sequence); } public ArrayList<Sequence> getSequencesList(){ return sequences; } public ViewingDirection getViewingDirection() { return viewingDirection; } public void setViewingDirection(ViewingDirection viewingDirection) { this.viewingDirection = viewingDirection; } @Override public JsonLD toJsonLD() { return super.toJsonLD() .appendNotNull("viewingDirection", viewingDirection) .append("sequences",sequences); } }
1,856
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Canvas.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/exporters/iiifexport/Canvas.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.exporters.iiifexport; import java.util.ArrayList; /** * * @author olli */ public class Canvas extends ModelBase { protected int width=-1; protected int height=-1; protected final ArrayList<Content> images=new ArrayList<>(); protected final ArrayList<Content> resources=new ArrayList<>(); public Canvas(){ setType("sc:Canvas"); } public void addImage(Content image){ this.images.add(image); image.setOn(this); } public ArrayList<Content> getImagesList(){ return images; } public int getWidth() { return width; } public void setWidth(int width) { this.width = width; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } @Override public JsonLD toJsonLD() { // if images list is manipulated directly, // the on fields might not have been set. for(Content c : images){ c.setOn(this); } return super.toJsonLD() .appendNotNull("width", width<0?null:width) .appendNotNull("height", height<0?null:height) .append("images", images); } }
2,136
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Content.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/exporters/iiifexport/Content.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.exporters.iiifexport; import java.util.ArrayList; /** * * @author olli */ public class Content extends ModelBase { public static final String MOTIVATION_PAINTING="sc:painting"; public static final String RESOURCE_TYPE_IMAGE="dctypes:Image"; protected String resourceId; // essentially the uri for the image protected String resourceType; protected final ArrayList<Service> resourceService=new ArrayList<>(); protected String format; // mime format of the resource protected int width=-1; protected int height=-1; protected String motivation; protected Canvas on; public Content(){ setType("oa:Annotation"); // motivation is practically always this setMotivation(MOTIVATION_PAINTING); } public void addResourceService(Service service){ this.resourceService.add(service); } public ArrayList<Service> getResourceServicesList(){ return resourceService; } public Canvas getOn() { return on; } public void setOn(Canvas on) { this.on = on; } public String getResourceId() { return resourceId; } public void setResourceId(String resourceId) { this.resourceId = resourceId; } public String getResourceType() { return resourceType; } public void setResourceType(String resourceType) { this.resourceType = resourceType; } public String getFormat() { return format; } public void setFormat(String format) { this.format = format; } public int getWidth() { return width; } public void setWidth(int width) { this.width = width; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } public String getMotivation() { return motivation; } public void setMotivation(String motivation) { this.motivation = motivation; } public JsonLD getResourceJsonLD(){ JsonLD jsonLD=new JsonLD(); jsonLD.append("@id", resourceId) .append("@type", resourceType) .appendNotNull("width", width<0?null:width) .appendNotNull("height", height<0?null:height) .append("format", format) .appendNotEmpty("service", resourceService, true); return jsonLD; } @Override public JsonLD toJsonLD() { return super.toJsonLD() .appendNotNull("motivation", motivation) .appendNotNull("on",on==null?null:on.getId()) .append("resource", getResourceJsonLD()); } }
3,589
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Sequence.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/exporters/iiifexport/Sequence.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.exporters.iiifexport; import java.util.ArrayList; /** * * @author olli */ public class Sequence extends ModelBase { protected ViewingDirection viewingDirection; protected Canvas startCanvas; protected final ArrayList<Canvas> canvases=new ArrayList<>(); public Sequence(){ setType("sc:Sequence"); } public void addCanvas(Canvas canvas){ this.canvases.add(canvas); } public ArrayList<Canvas> getCanvasesList(){ return canvases; } public ViewingDirection getViewingDirection() { return viewingDirection; } public void setViewingDirection(ViewingDirection viewingDirection) { this.viewingDirection = viewingDirection; } public Canvas getStartCanvas() { return startCanvas; } public void setStartCanvas(Canvas startCanvas) { this.startCanvas = startCanvas; } @Override public JsonLD toJsonLD() { return super.toJsonLD() .appendNotNull("viewingDirection", viewingDirection) .appendNotNull("startCanvas", startCanvas==null?null:startCanvas.getId() ) .append("canvases", canvases); } }
2,074
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimpleSelectionIIIFBuilder.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/exporters/iiifexport/SimpleSelectionIIIFBuilder.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.exporters.iiifexport; import java.io.IOException; import java.net.URL; import java.util.Iterator; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.stream.ImageInputStream; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; import org.wandora.utils.MimeTypes; import org.wandora.utils.Tuples; /** * * Simple IIIF builder that uses subject locators of selected topics for * images. The class is broken into many overrideable methods so that it can * also be used as a base class for other IIIF builders. * * @author olli */ public class SimpleSelectionIIIFBuilder implements IIIFBuilder { @Override public String getBuilderName(){ return "Simple Selection Builder"; } // This reads the image dimensions without reading the whole file, which would take // a lot of time for a big collection of big images. The parameter can be // a variety of things like a File or an InputStream, // see ImageIO.createImageInputStream documentation. public static int[] getImageDimensions(Object f) throws IOException { if(f instanceof URL) f=((URL)f).openStream(); ImageInputStream in = ImageIO.createImageInputStream(f); try{ final Iterator readers = ImageIO.getImageReaders(in); if(readers.hasNext()){ ImageReader reader=(ImageReader)readers.next(); try{ reader.setInput(in); return new int[]{reader.getWidth(0), reader.getHeight(0)}; }finally{ reader.dispose(); } } }finally { if(in!=null) in.close(); } return null; } protected String guessFormat(String url){ int ind=url.lastIndexOf("?"); if(ind>0) url=url.substring(0,ind); ind=url.lastIndexOf("#"); if(ind>0) url=url.substring(0,ind); return MimeTypes.getMimeType(url); } @Override public Manifest buildIIIF(Wandora wandora, Context context,IIIFExport tool) throws TopicMapException { startBuild(wandora,context); Manifest manifest=prepareManifest(wandora, context, tool); Sequence sequence=prepareSequence(wandora, context, manifest, tool); processTopics(wandora, context, sequence, tool); endBuild(); return manifest; } protected void startBuild(Wandora wandora, Context context) throws TopicMapException { } protected Manifest prepareManifest(Wandora wandora,Context context,IIIFExport tool) throws TopicMapException { Manifest manifest=new Manifest(); manifest.addLabel(new LanguageString("Wandora IIIF Export")); // ID is required, create something manifest.setId(wandora.getTopicMap().makeSubjectIndicator()); return manifest; } protected Sequence prepareSequence(Wandora wandora,Context context,Manifest manifest,IIIFExport tool) throws TopicMapException { Sequence sequence=new Sequence(); sequence.addLabel(new LanguageString("Default sequence")); manifest.addSequence(sequence); return sequence; } protected void processTopics(Wandora wandora,Context context, Sequence sequence,IIIFExport tool) throws TopicMapException { Iterator iter=context.getContextObjects(); while(iter.hasNext()){ Object o=iter.next(); if(!(o instanceof Topic)) continue; Topic t=(Topic)o; processTopic(t, sequence, tool); } } protected void processTopic(Topic t, Sequence sequence,IIIFExport tool) throws TopicMapException { Content content=getTopicContent(t, tool); if(content==null) return; Canvas canvas=new Canvas(); canvas.addLabel(new LanguageString(t.getDisplayName())); canvas.setId(t.getOneSubjectIdentifier().toExternalForm()); canvas.setWidth(content.getWidth()); canvas.setHeight(content.getHeight()); sequence.addCanvas(canvas); canvas.addImage(content); } protected Content getTopicContent(Topic t,IIIFExport tool) throws TopicMapException { Tuples.T2<String,String> urlAndFormat=getImageUrlAndFormat(t, tool); if(urlAndFormat==null) return null; int[] dimensions=null; try{ dimensions=getImageDimensions(new URL(urlAndFormat.e1)); }catch(IOException ioe){ tool.log("Unable to get image dimensions for "+urlAndFormat.e1,ioe); return null; } Content content=new Content(); content.setResourceId(urlAndFormat.e1); content.setFormat(urlAndFormat.e2); content.setResourceType(Content.RESOURCE_TYPE_IMAGE); content.setWidth(dimensions[0]); content.setHeight(dimensions[1]); return content; } protected Tuples.T2<String,String> getImageUrlAndFormat(Topic t,IIIFExport tool) throws TopicMapException { Locator sl=t.getSubjectLocator(); if(sl==null) return null; String url=sl.toExternalForm(); String format=guessFormat(url); if(format==null) return null; return Tuples.t2(url,format); } protected void endBuild(){ } }
6,472
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
IIIFBuilder.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/exporters/iiifexport/IIIFBuilder.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.exporters.iiifexport; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public interface IIIFBuilder { public Manifest buildIIIF(Wandora wandora, Context context,IIIFExport tool) throws TopicMapException; public String getBuilderName(); }
1,203
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ClearTopicMapIndexes.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/layers/ClearTopicMapIndexes.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/>. * * * ClearTopicMap.java * * Created on 20.6.2006, 11:42 * */ package org.wandora.application.tools.layers; import javax.swing.Icon; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.layered.Layer; import org.wandora.topicmap.layered.LayerStack; /** * <p> * Clears all indexes of current topic map. Indexes are used to cache some * elements in topic map. Caching elements may prevent the user in seeing * all possible changes in topic maps. * </p> * <p> * It should be noted that it depends on topic map implementation if * it uses indexing and if clearing indexes really clears them. For example, * memory topic map implementation <code>TopicMapImpl</code> doesn't use * indexing. * </p> * * @author olli, akivela */ public class ClearTopicMapIndexes extends AbstractLayerTool { private static final long serialVersionUID = 1L; /** Creates a new instance of ClearTopicMapIndexes */ public ClearTopicMapIndexes() { } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/layer_index_clear.png"); } @Override public String getName() { return "Clear topic map indexes"; } @Override public String getDescription() { return "Clears topic map indexes of selected layer. Indexes are used to "+ "cache topic map elements. Indexing may prevent Wandora user "+ "seeing modifications of co-users in distributed environments. Clearing "+ "index causes Wandora to update topic map elements."; } @Override public boolean requiresRefresh(){ return true; } @Override public void execute(Wandora wandora, Context context) throws TopicMapException { Layer l = solveContextLayer(wandora, context); if(l == null) { WandoraOptionPane.showMessageDialog(wandora, "There is no current topic map layer. Create a topic map layer first.", "No layer selected", WandoraOptionPane.WARNING_MESSAGE); return; } TopicMap tm=wandora.getTopicMap(); if(l != null) { int answer = WandoraOptionPane.showConfirmDialog(wandora,"Are you sure you want to clear layer's '"+l.getName()+"' topic map indexes?", "Clear topic map indexes", WandoraOptionPane.YES_NO_OPTION); if(answer != WandoraOptionPane.YES_OPTION ) return; l.getTopicMap().clearTopicMapIndexes(); if(tm instanceof LayerStack) { ((LayerStack)tm).clearTopicIndex(); } } } }
3,598
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
LockLayers.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/layers/LockLayers.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/>. * * * LockLayers.java * * Created on 21. huhtikuuta 2006, 21:19 * */ package org.wandora.application.tools.layers; 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.layered.Layer; /** * <p> * Locks and unlock topic map layers. If topic map layer is locked, the layer accepts * only read operations. Reader should note that the layer locking feature of Wandora * application is not bullet proof. * </p> * <p> * Available modes are <code>LOCK_ALL</code>, <code>UNLOCK_ALL</code>, * <code>LOCK_ALL_BUT_CURRENT</code> and <code>REVERSE_LOCKS</code>. * </p> * * @author akivela */ public class LockLayers extends AbstractLayerTool implements WandoraTool { private static final long serialVersionUID = 1L; public static final int LOCK_ALL = 1000; public static final int UNLOCK_ALL = 1010; public static final int LOCK_ALL_BUT_CURRENT = 1020; public static final int REVERSE_LOCKS = 1030; private int option = UNLOCK_ALL; /** Creates a new instance of LockLayers */ public LockLayers(int options) { this.option = options; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/layers_merge.png"); } @Override public String getName() { switch(option) { case LOCK_ALL: { return "Lock all layers"; } case UNLOCK_ALL: { return "Unlock all layers"; } case LOCK_ALL_BUT_CURRENT: { return "Lock all layers except current"; } case REVERSE_LOCKS: { return "Reverse layer locks"; } } return "Lock Layers"; } @Override public String getDescription() { switch(option) { case LOCK_ALL: { return "Lock all layers."; } case UNLOCK_ALL: { return "Unlock all layers."; } case LOCK_ALL_BUT_CURRENT: { return "Lock all layers except current."; } case REVERSE_LOCKS: { return "Reverse layer locks."; } } return "Tool is used to change layer locks in layer stack."; } @Override public void execute(Wandora wandora, Context context) { try { Layer selected = solveContextLayer(wandora, context); if(selected == null) { WandoraOptionPane.showMessageDialog(wandora, "There is no current topic map layer. Create a topic map layer first.", "No layer selected", WandoraOptionPane.WARNING_MESSAGE); return; } Collection<Layer> layers = wandora.layerTree.getAllLayers(); Iterator<Layer> layerIterator = layers.iterator(); Layer layer = null; while(layerIterator.hasNext()) { layer = (Layer) layerIterator.next(); switch(option) { case LOCK_ALL: { layer.setReadOnly(true); break; } case UNLOCK_ALL: { layer.setReadOnly(false); break; } case LOCK_ALL_BUT_CURRENT: { if(selected.equals(layer)) layer.setReadOnly(false); else layer.setReadOnly(true); break; } case REVERSE_LOCKS: { if(layer.isReadOnly()) layer.setReadOnly(false); else layer.setReadOnly(true); break; } default: { log("Unknown option '"+option+"' used in LockLayers."); break; } } } wandora.layerTree.resetLayers(); } catch(Exception e) { singleLog(e); } } }
5,169
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ConfigureLayer.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/layers/ConfigureLayer.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/>. * * * ConfigureLayer.java * * Created on 21. huhtikuuta 2006, 19:58 * */ package org.wandora.application.tools.layers; 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.layered.Layer; /** * <p> * Configures existing topic map layer. For example, configuring a database * topic map layer allows the user to change database options such as * database server address. * </p> * <p> * Notice that some topic map layer implementations such as memory topic map * doesn't support configuration. * </p> * * @author akivela */ public class ConfigureLayer extends AbstractLayerTool implements WandoraTool { private static final long serialVersionUID = 1L; /** Creates a new instance of ConfigureLayer */ public ConfigureLayer() { } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/layer_configure.png"); } @Override public String getName() { return "Configure Layer"; } @Override public String getDescription() { return "Allows Wandora user to reconfigures current layer. Reconfiguration is required when database settings have changed, for example."; } public void execute(Wandora wandora, Context context) { try { Layer contextLayer = solveContextLayer(wandora, context); if(contextLayer == null) { WandoraOptionPane.showMessageDialog(wandora, "There is no current topic map layer. Create a topic map layer first.", "No layer selected", WandoraOptionPane.WARNING_MESSAGE); return; } wandora.layerTree.modifyLayer(contextLayer); } catch(Exception e) { singleLog(e); } } }
2,799
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MergeLayers.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/layers/MergeLayers.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/>. * * * MergeLayers.java * * Created on 17. helmikuuta 2006, 11:47 * */ package org.wandora.application.tools.layers; import java.util.List; import java.util.Vector; 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.LayerTree; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.layered.ContainerTopicMap; import org.wandora.topicmap.layered.Layer; import org.wandora.topicmap.linked.LinkedTopicMap; /** * Merges two or more topic map * layers. Mode is set with the constructor attribute <code>options</code>. * * @author akivela */ public class MergeLayers extends AbstractLayerTool implements WandoraTool { private static final long serialVersionUID = 1L; private static final String message = "You are about to merge topic map layers. "+ "Depending on topic map sizes this operation may take a long time. "+ "Are you sure you want to start merge?"; private static final String title = "Confirm"; public static final int MERGE_UP = 100; public static final int MERGE_DOWN = 200; public static final int MERGE_ALL = 300; public static final int MERGE_ALL_UP = 310; public static final int MERGE_ALL_DOWN = 320; public static final int MERGE_VISIBLE = 500; private int options = 0; /** Creates a new instance of MergeLayers */ public MergeLayers() { this.options = MERGE_UP; } public MergeLayers(int options) { this.options = options; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/layers_merge.png"); } @Override public String getName() { return "Merge Topic Map Layers"; } @Override public String getDescription() { return "Tool merges two or more topic map layers."; } public void setOptions(int opts) { this.options = opts; } @Override public void execute(Wandora wandora, Context context) { mergeLayers(wandora, options, context); } public void mergeLayers(Wandora wandora, int options, Context context) { Layer targetLayer = solveContextLayer(wandora, context); if(targetLayer == null) { WandoraOptionPane.showMessageDialog(wandora, "There is no current topic map layer. Create a topic map layer first.", "No layer selected", WandoraOptionPane.WARNING_MESSAGE); return; } if(WandoraOptionPane.YES_OPTION != WandoraOptionPane.showConfirmDialog(wandora, message, title, WandoraOptionPane.YES_NO_OPTION)) { return; } setDefaultLogger(); ContainerTopicMap layerStack = targetLayer.getContainer(); Vector<Layer> sourceLayers = getSourceLayers(targetLayer, layerStack, options); Layer sourceLayer = null; if(sourceLayers.size() < 1) { log("Merge couldn't finish as there exists no suitable layers to merge to..."); } else { LayerTree layerTree=wandora.layerTree; for(Layer l : layerTree.getRootStack().getTreeLayers()){ TopicMap tm=l.getTopicMap(); if(tm instanceof LinkedTopicMap){ for(Layer l2 : sourceLayers){ if(((LinkedTopicMap)tm).getLinkedTopicMap()==l2.getTopicMap()){ WandoraOptionPane.showMessageDialog(wandora, "One of the merged layers is used in the linked topic layer \""+l.getName()+"\" and cannot be merged.","Merge layers",WandoraOptionPane.ERROR_MESSAGE); return; } } } } long startTime = System.currentTimeMillis(); try { wandora.getTopicMap().clearTopicMapIndexes(); } catch(Exception e) { log(e); } for(int i=sourceLayers.size()-1; i>=0 && !forceStop(); i--) { try { sourceLayer = sourceLayers.elementAt(i); if(!targetLayer.equals(sourceLayer)) { log("Merging topic map layers '"+sourceLayer.getName()+"' and '"+targetLayer.getName() + "'!"); targetLayer.getTopicMap().mergeIn(sourceLayer.getTopicMap(),getCurrentLogger()); layerStack.removeLayer(sourceLayer); } sourceLayers.remove(sourceLayer); wandora.layerTree.resetLayers(); } catch (Exception e) { log("Merging topic map layers\n"+sourceLayer.getName()+" and "+targetLayer.getName()+" failed!", e); } } long endTime = System.currentTimeMillis(); long duration = (endTime-startTime)/1000; if(duration > 5) { log("Merge took " + duration + " seconds."); } } log("Ready."); wandora.layerTree.resetLayers(); setState(WAIT); } public Vector<Layer> getSourceLayers(Layer selected, ContainerTopicMap layers, int options) { Vector<Layer>sourceLayers = new Vector<Layer>(); int selectedIndex = layers.getLayerZPos(selected); List<Layer> layerList = layers.getLayers(); switch(options) { case MERGE_ALL: { for(int i=0; i<layerList.size(); i++) { if(i != selectedIndex) sourceLayers.add(layerList.get(i)); } break; } case MERGE_ALL_UP: { for(int i=selectedIndex+1; i<layerList.size(); i++) { if(i != selectedIndex) sourceLayers.add(layerList.get(i)); } break; } case MERGE_ALL_DOWN: { int j=0; for(int i=0; i<selectedIndex; i++) { if(i != selectedIndex) sourceLayers.add(layerList.get(i)); } break; } case MERGE_UP: { if(selectedIndex > 0) { sourceLayers.add(layerList.get(selectedIndex-1)); } break; } case MERGE_DOWN: { if(selectedIndex < layerList.size()-1) { sourceLayers.add(layerList.get(selectedIndex+1)); } break; } case MERGE_VISIBLE: { List<Layer> visibleLayerList = layers.getVisibleLayers(); Layer visibleLayer = null; for(int i=0; i<visibleLayerList.size(); i++) { visibleLayer = visibleLayerList.get(i); if(!selected.equals(visibleLayer)) { sourceLayers.add(visibleLayer); } } break; } } return sourceLayers; } }
8,121
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
NewLayer.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/layers/NewLayer.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/>. * * * NewLayer.java * * Created on 26. helmikuuta 2006, 18:35 * */ package org.wandora.application.tools.layers; 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.topicmap.TopicMap; import org.wandora.topicmap.layered.ContainerTopicMap; import org.wandora.topicmap.layered.Layer; import org.wandora.topicmap.undowrapper.UndoTopicMap; /** * Create new topic map layer. Topic map layer is a single topic map wrapped * into a layer container. Wandora can handle several topic map layers at once. * Separate layers are stored in a special stack structure. * * Tool passes the execution to <code>LayerControlPanel.createLayer</code>. * * @author akivela */ public class NewLayer extends AbstractLayerTool implements WandoraTool { private static final long serialVersionUID = 1L; /** Creates a new instance of NewLayer */ public NewLayer() { } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/layer_create.png"); } @Override public String getName() { return "New layer"; } @Override public String getDescription() { return "Creates new topic map layer."; } @Override public void execute(Wandora wandora, Context context) { try { Layer selected = solveContextLayer(wandora, context); ContainerTopicMap container=null; if(selected != null) { if(selected.getTopicMap() instanceof UndoTopicMap) { TopicMap wrapped = ((UndoTopicMap) selected.getTopicMap()).getWrappedTopicMap(); if(wrapped != null && wrapped instanceof ContainerTopicMap) { container = (ContainerTopicMap) wrapped; } } if(container == null) { if(selected.getTopicMap() instanceof ContainerTopicMap) { container=(ContainerTopicMap)selected.getTopicMap(); } else { container=selected.getContainer(); } } } if(container == null) { container=wandora.getTopicMap(); } try { wandora.getTopicMap().clearTopicMapIndexes(); } catch(Exception e) { log(e); } wandora.layerTree.createLayer(container); } catch(Exception e) { singleLog(e); } } }
3,526
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MakeSIConsistentTool.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/layers/MakeSIConsistentTool.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/>. * * * MakeSIConsistentTool.java * * Created on 6. maaliskuuta 2006, 11:50 * */ package org.wandora.application.tools.layers; 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.TopicMap; import org.wandora.topicmap.database.DatabaseTopicMap; import org.wandora.topicmap.layered.Layer; /** * @author akivela */ public class MakeSIConsistentTool extends AbstractLayerTool implements WandoraTool { private static final long serialVersionUID = 1L; private boolean requiresRefresh = false; private static final String title = "Confirm"; /** Creates a new instance of MakeConsistentTool */ public MakeSIConsistentTool() { } @Override public String getName() { return "Make SI Consistent"; } @Override public String getDescription() { return "Ensure that all topic's in topic map have at least one subject identifier."; } @Override public boolean requiresRefresh() { return requiresRefresh; } @Override public void execute(Wandora admin, Context context) { requiresRefresh = false; Layer contextLayer = solveContextLayer(admin, context); if(contextLayer == null) { WandoraOptionPane.showMessageDialog(admin, "There is no current topic map layer. Create a topic map layer first.", "No layer selected", WandoraOptionPane.WARNING_MESSAGE); return; } TopicMap topicMap = contextLayer.getTopicMap(); if(!(topicMap instanceof DatabaseTopicMap)) { WandoraOptionPane.showMessageDialog(admin, "Topic map in layer '"+contextLayer.getName()+"' "+ "is not a database topic map. SI consistency check is currently supported only "+ "by database topic map."); return; } if(WandoraOptionPane.YES_OPTION != WandoraOptionPane.showConfirmDialog(admin, "You are about to start topic map SI consistency check for layer '"+contextLayer.getName()+"'. "+ "Are you sure you want to start SI consistency check?", title, WandoraOptionPane.YES_NO_OPTION)) { return; } setDefaultLogger(); try { log("Checking SI consistency of layer '"+contextLayer.getName()+"'."); long st = System.currentTimeMillis(); requiresRefresh = true; ((DatabaseTopicMap) topicMap).checkSIConsistency(getCurrentLogger()); long et = System.currentTimeMillis(); log("SI Consistency check took " + ((int)((et-st)/1000)) + " seconds."); log("Ready."); } catch(Exception e) { log(e); } setState(WAIT); } }
3,776
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MakeAssociationConsistentTool.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/layers/MakeAssociationConsistentTool.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/>. * * * MakeConsistentTool.java * * Created on 6. maaliskuuta 2006, 11:50 * */ package org.wandora.application.tools.layers; 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.TopicMap; import org.wandora.topicmap.layered.Layer; /** * <p> * Merge all identical associations in selected topic map. As a result * the number of associations may decrease. * </p> * * @author olli */ public class MakeAssociationConsistentTool extends AbstractLayerTool implements WandoraTool { private static final long serialVersionUID = 1L; private boolean requiresRefresh = false; private static final String title = "Confirm"; /** Creates a new instance of MakeAssociationConsistentTool */ public MakeAssociationConsistentTool() { } @Override public String getName() { return "Make association consistent"; } @Override public String getDescription() { return "Ensure the topic map does not contain identical associations."; } @Override public boolean requiresRefresh() { return requiresRefresh; } @Override public void execute(Wandora wandora, Context context) { requiresRefresh = false; Layer contextLayer = solveContextLayer(wandora, context); if(contextLayer == null) { WandoraOptionPane.showMessageDialog(wandora, "There is no current topic map layer. Create a topic map layer first.", "No layer selected", WandoraOptionPane.WARNING_MESSAGE); return; } if(WandoraOptionPane.YES_OPTION != WandoraOptionPane.showConfirmDialog(wandora, "You are about to start topic map consistency check for layer '"+contextLayer.getName()+"'. "+ "Depending on your topic map size this operation may take a long time. "+ "Are you sure you want to start consistency check?", title, WandoraOptionPane.YES_NO_OPTION)) { return; } setDefaultLogger(); try { requiresRefresh = true; long startTime = System.currentTimeMillis(); TopicMap tm = contextLayer.getTopicMap(); int an = tm.getNumAssociations(); log("Layer's topic map contains " + an + " associations."); log("Checking association consistency of layer '"+contextLayer.getName()+"'."); tm.checkAssociationConsistency(getCurrentLogger()); int ana = tm.getNumAssociations(); long endTime = System.currentTimeMillis(); int executionDuration = ((int)((endTime-startTime)/1000)); if(executionDuration > 1) log("Consistency check took " + executionDuration + " seconds."); // log("After association consistency check the topic map contains " + ana + " associations."); log("Removed " + (an-ana) + " associations."); log("Ready."); } catch(Exception e) { log(e); } setState(WAIT); } }
4,031
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ArrangeLayers.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/layers/ArrangeLayers.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/>. * * * ArrangeLayers.java * * Created on 26. helmikuuta 2006, 19:12 * */ package org.wandora.application.tools.layers; 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.LayerTree; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.topicmap.layered.Layer; /** * <p> * Arranged topic map layers in layer stack. * Topic map layer can be moved upward, downward, top and bottom. Also, * topic map layer order can be reversed. * </p> * <p> * Exact behavior of tool is specified with <code>options</code> parameter * shipped to class constructor. Tool has no public set method for behavior * and it can not be altered after construction. * </p> * <p> * Tool does not alter the layer order directly but calls <code>arrangeLayers</code> * method in <code>LayerControlPanel</code>. * </p> * * @author akivela */ public class ArrangeLayers extends AbstractLayerTool implements WandoraTool { private static final long serialVersionUID = 1L; private int option = LayerTree.MOVE_LAYER_UP; /** Creates a new instance of ArrangeLayers */ public ArrangeLayers() { } public ArrangeLayers(int option) { this.option = option; } @Override public Icon getIcon() { switch(option) { case LayerTree.MOVE_LAYER_UP: { return UIBox.getIcon("gui/icons/move_up.png"); } case LayerTree.MOVE_LAYER_DOWN: { return UIBox.getIcon("gui/icons/move_down.png"); } case LayerTree.MOVE_LAYER_TOP: { return UIBox.getIcon("gui/icons/move_top.png"); } case LayerTree.MOVE_LAYER_BOTTOM: { return UIBox.getIcon("gui/icons/move_bottom.png"); } case LayerTree.REVERSE_LAYERS: { return UIBox.getIcon("gui/icons/reverse_order.png.png"); } } return UIBox.getIcon("gui/icons/layers_arrange.png"); } @Override public String getName() { switch(option) { case LayerTree.MOVE_LAYER_UP: { return "Move layer upward"; } case LayerTree.MOVE_LAYER_DOWN: { return "Move layer downward"; } case LayerTree.MOVE_LAYER_TOP: { return "Move layer to top"; } case LayerTree.MOVE_LAYER_BOTTOM: { return "Move layer to bottom"; } case LayerTree.REVERSE_LAYERS: { return "Reverse layer order"; } } return "Arrange Layers"; } @Override public String getDescription() { switch(option) { case LayerTree.MOVE_LAYER_UP: { return "Move current layer upward."; } case LayerTree.MOVE_LAYER_DOWN: { return "Move current layer downward."; } case LayerTree.MOVE_LAYER_TOP: { return "Move current layer to top."; } case LayerTree.MOVE_LAYER_BOTTOM: { return "Move current layer to bottom."; } case LayerTree.REVERSE_LAYERS: { return "Reverse layer order."; } } return "Tool is used to modify order of topic map layers."; } @Override public void execute(Wandora wandora, Context context) { try { LayerTree layerTree = wandora.layerTree; Layer contextLayer = solveContextLayer(wandora, context); if(contextLayer != null) { layerTree.arrangeLayers(contextLayer, option); } else { WandoraOptionPane.showMessageDialog(wandora, "There is no current topic map layer. Create a topic map layer first.", "No layer selected", WandoraOptionPane.WARNING_MESSAGE); } } catch(Exception e) { singleLog(e); } } }
4,996
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AbstractLayerTool.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/layers/AbstractLayerTool.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/>. * * * AbstractLayerTool.java * * Created on 13.6.2006, 18:47 * */ package org.wandora.application.tools.layers; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.gui.LayerTree; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.layered.Layer; /** * * @author akivela */ public abstract class AbstractLayerTool extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; protected Layer solveContextLayer(Wandora wandora, Context context) { LayerTree layerTree = wandora.layerTree; Layer layer=null; if(context.getContextSource() instanceof LayerTree){ layer = ((LayerTree)context.getContextSource()).getLastClickedLayer(); } if(layer == null) layer = layerTree.getSelectedLayer(); return layer; } }
1,776
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
RenameLayer.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/layers/RenameLayer.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/>. * * * RenameLayer.java * * Created on 21. huhtikuuta 2006, 20:00 */ package org.wandora.application.tools.layers; 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.LayerTree; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.topicmap.layered.Layer; /** * Renames topic map layer. * Like many other layer tools, this tool passes the execution to * <code>LayerStatusPanel</code>. * * @author akivela */ public class RenameLayer extends AbstractLayerTool implements WandoraTool { private static final long serialVersionUID = 1L; /** Creates a new instance of RenameLayer */ public RenameLayer() { } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/layer_rename.png"); } @Override public String getName() { return "Rename layer"; } @Override public String getDescription() { return "Rename current layer."; } @Override public void execute(Wandora wandora, Context context) { try { LayerTree layerTree = wandora.layerTree; Layer selected = solveContextLayer(wandora, context); if(selected != null) { String newName = WandoraOptionPane.showInputDialog(wandora,"New name for the layer" , selected.getName(),"New layer name" , WandoraOptionPane.QUESTION_MESSAGE ); if(newName != null) { selected.setName(newName); layerTree.resetLayers(); } } else { WandoraOptionPane.showMessageDialog(wandora, "There is no current topic map layer. Create a topic map layer first.", "No layer selected", WandoraOptionPane.WARNING_MESSAGE); } } catch(Exception e) { singleLog(e); } } }
2,845
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DeleteLayer.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/layers/DeleteLayer.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/>. * * * DeleteLayer.java * * Created on 26. helmikuuta 2006, 18:39 * */ package org.wandora.application.tools.layers; 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.LayerTree; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.layered.Layer; import org.wandora.topicmap.linked.LinkedTopicMap; /** * <p> * Deletes topic map layer. Layer deletion is confirmed by the <code>LayerControlPanel</code>. * </p> * * @author akivela */ public class DeleteLayer extends AbstractLayerTool implements WandoraTool { private static final long serialVersionUID = 1L; /** Creates a new instance of DeleteLayer */ public DeleteLayer() { } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/layer_delete.png"); } @Override public String getName() { return "Delete layer"; } @Override public String getDescription() { return "Delete current topic map layer."; } @Override public void execute(Wandora wandora, Context context) { LayerTree layerTree = wandora.layerTree; Layer contextLayer = solveContextLayer(wandora, context); if(contextLayer == null) { WandoraOptionPane.showMessageDialog(wandora, "There is no current topic map layer.", "No layer selected", WandoraOptionPane.WARNING_MESSAGE); return; } TopicMap contextTM=contextLayer.getTopicMap(); for(Layer l : layerTree.getRootStack().getTreeLayers()){ TopicMap tm=l.getTopicMap(); if(tm instanceof LinkedTopicMap){ if(((LinkedTopicMap)tm).getLinkedTopicMap()==contextTM){ WandoraOptionPane.showMessageDialog(wandora, "Layer is used in the linked topic layer \""+l.getName()+"\" and cannot be deleted.","Delete layer",WandoraOptionPane.ERROR_MESSAGE); return; } } } try { wandora.getTopicMap().clearTopicMapIndexes(); } catch(Exception e) { singleLog(e); } layerTree.deleteLayer(contextLayer); } }
3,206
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ViewLayers.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/layers/ViewLayers.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/>. * * * ViewLayers.java * * Created on 21. huhtikuuta 2006, 20:38 * */ package org.wandora.application.tools.layers; import java.util.ArrayList; 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.layered.Layer; /** * Controls topic map layer visibility. Visibility * is used to view or hide topics and associations in layer. Tools specific * function is defined in constructor with <code>options</code> parameter. * * @author akivela */ public class ViewLayers extends AbstractLayerTool implements WandoraTool { private static final long serialVersionUID = 1L; public static final int VIEW_ALL = 1000; public static final int HIDE_ALL = 1010; public static final int HIDE_ALL_BUT_CURRENT = 1020; public static final int REVERSE_VISIBILITY = 1030; private int option = VIEW_ALL; /** Creates a new instance of ViewLayers */ public ViewLayers(int options) { this.option = options; } @Override public Icon getIcon() { if(option == VIEW_ALL) { return UIBox.getIcon("gui/icons/view.png"); } if(option == HIDE_ALL || option == HIDE_ALL_BUT_CURRENT) { return UIBox.getIcon("gui/icons/view_no.png"); } if(option == REVERSE_VISIBILITY) { return UIBox.getIcon("gui/icons/view_reverse.png"); } return UIBox.getIcon("gui/icons/view.png"); } @Override public String getName() { if(option == VIEW_ALL) { return "View all layers"; } if(option == HIDE_ALL) { return "Hide all layers"; } if(option == HIDE_ALL_BUT_CURRENT) { return "Hide all but current layer"; } if(option == REVERSE_VISIBILITY) { return "Reverse layer order"; } return "View layer"; } @Override public String getDescription() { if(option == VIEW_ALL) { return "Change all layers visible."; } if(option == HIDE_ALL) { return "Change all layers invisible."; } if(option == HIDE_ALL_BUT_CURRENT) { return "Change current layer visible and all other layers invisible."; } if(option == REVERSE_VISIBILITY) { return "Change visible layers invisible and invisible layers visible."; } return "Tool is used to change layer visibility in layer stack."; } @Override public void execute(Wandora wandora, Context context) { try { Layer selected = solveContextLayer(wandora, context); if(selected == null) { WandoraOptionPane.showMessageDialog(wandora, "There is no current topic map layer. Create a topic map layer first.", "No layer selected", WandoraOptionPane.WARNING_MESSAGE); return; } ArrayList<Layer> layers = wandora.layerTree.getAllLayers(); try { wandora.getTopicMap().clearTopicMapIndexes(); } catch(Exception e) { log(e); } for(Layer layer : layers){ switch(option) { case VIEW_ALL: { layer.setVisible(true); break; } case HIDE_ALL: { layer.setVisible(false); break; } case HIDE_ALL_BUT_CURRENT: { if(selected.equals(layer)) layer.setVisible(true); else layer.setVisible(false); break; } case REVERSE_VISIBILITY: { if(layer.isVisible()) layer.setVisible(false); else layer.setVisible(true); break; } default: { log("Unknown option '"+option+"' used in ViewLayers."); break; } } } wandora.layerTree.resetLayers(); } catch(Exception e) { singleLog(e); } } }
5,279
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ClearTopicMap.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/layers/ClearTopicMap.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/>. * * * ClearTopicMap.java * * Created on 20.6.2006, 11:42 * */ package org.wandora.application.tools.layers; import javax.swing.Icon; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.layered.Layer; import org.wandora.topicmap.layered.LayerStack; /** * <p> * Clears topic map in selected layer. Clearing a topic map may be * necessary with layer implementations where layer deletion is * not possible or costly operation. * </p> * * @author olli */ public class ClearTopicMap extends AbstractLayerTool { private static final long serialVersionUID = 1L; /** Creates a new instance of ClearTopicMap */ public ClearTopicMap() { } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/layer_topicmap_clear.png"); } @Override public String getName() { return "Clear layer's topic map"; } @Override public String getDescription() { return "You are about to clear the topic map in selected layer. Clearing deletes all topics "+ "and associations in the topic map. "+ "Operation is undoable. Are you sure?"; } @Override public boolean requiresRefresh(){ return true; } @Override public void execute(Wandora wandora, Context context) throws TopicMapException { Layer l = solveContextLayer(wandora, context); if(l != null) { int answer = WandoraOptionPane.showConfirmDialog(wandora,"Are you sure you want to clear layer \""+l.getName()+"\"? Everything in the topic map will be deleted.", "Clear topic map", WandoraOptionPane.YES_NO_OPTION); if(answer != WandoraOptionPane.YES_OPTION ) return; setDefaultLogger(); log("Deleting content of topic map in layer '"+l.getName()+"'."); l.getTopicMap().clearTopicMap(); TopicMap tm=wandora.getTopicMap(); if(tm instanceof LayerStack){ ((LayerStack)tm).clearTopicIndex(); } setState(CLOSE); } else { WandoraOptionPane.showMessageDialog(wandora, "There is no current topic map layer. Create a topic map layer first.", "No layer selected", WandoraOptionPane.WARNING_MESSAGE); } } }
3,350
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MaianaImportPanel.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/maiana/MaianaImportPanel.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/>. * * * * * MaianaImportPanel.java * * Created on 12.10.2010, 10:34:55 */ package org.wandora.application.tools.maiana; import java.awt.Cursor; import java.net.URL; import javax.swing.JDialog; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableColumn; import javax.swing.table.TableModel; import javax.swing.table.TableRowSorter; import org.json.JSONArray; import org.json.JSONObject; import org.wandora.application.Wandora; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.application.gui.simple.SimpleButton; import org.wandora.application.gui.simple.SimpleField; import org.wandora.application.gui.simple.SimpleLabel; import org.wandora.application.gui.simple.SimpleScrollPane; import org.wandora.utils.IObox; /** * * @author akivela */ public class MaianaImportPanel extends javax.swing.JPanel { private static final long serialVersionUID = 1L; private boolean autoLoadList = false; private boolean wasAccepted = false; private JDialog window = null; private JTable mapTable = null; /** Creates new form MaianaImportPanel */ public MaianaImportPanel() { initComponents(); } public void open(Wandora wandora) { window = new JDialog(wandora, true); window.setSize(800, 450); window.add(this); window.setTitle("Import from Waiana"); wandora.centerWindow(window); if(autoLoadList) { setTopicMapsList(); } window.setVisible(true); } public void setAccepted(boolean accepted) { wasAccepted = accepted; } public boolean wasAccepted() { return wasAccepted; } public String[] getTopicMapNames() { if(nameTextField.getText() != null && nameTextField.getText().length() > 0) { return new String[] { nameTextField.getText() }; } else { if(mapTable != null) { return getSelectedRowsOfColumn(0); } } return new String[] { }; } public String[] getTopicMapShortNames() { if(nameTextField.getText() != null && nameTextField.getText().length() > 0) { return new String[] { nameTextField.getText() }; } else { if(mapTable != null) { return getSelectedRowsOfColumn(1); } } return new String[] { }; } public String[] getOwners() { if(ownerTextField.getText() != null && ownerTextField.getText().length() > 0) { return new String[] { ownerTextField.getText() }; } else { if(mapTable != null) { return getSelectedRowsOfColumn(2); } } return new String[] { }; } private String[] getSelectedRowsOfColumn(int col) { int[] rows = mapTable.getSelectedRows(); for (int i = 0; i < rows.length; i++) { rows[i] = mapTable.convertRowIndexToModel(rows[i]); } String[] data = new String[rows.length]; for (int i = 0; i < rows.length; i++) { data[i] = (String) mapTable.getModel().getValueAt(rows[i], col); } return data; } public void setTopicMapName(String n) { nameTextField.setText(n); } public void setOwner(String o) { ownerTextField.setText(o); } public void setApiKey(String key) { apiKeyTextField.setText(key); } public String getApiKey() { return apiKeyTextField.getText(); } public String getFormat() { return "xtm20"; } public void setFormat(String format) { } public String getApiEndPoint() { return apiEndPointField.getSelectedItem().toString(); } public void setApiEndPoint(String endpoint) { apiEndPointField.setSelectedItem(endpoint); } public void setTopicMapsList() { if(getApiKey() != null) { try { JSONObject list = MaianaUtils.listAvailableTopicMaps(getApiEndPoint(), getApiKey()); if(list.has("msg")) { WandoraOptionPane.showMessageDialog(window, list.getString("msg"), "API says", WandoraOptionPane.WARNING_MESSAGE); //System.out.println("REPLY:"+list.toString()); } if(list.has("data")) { mapTable = new JTable(); mapTable.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); if(list != null) { JSONArray datas = list.getJSONArray("data"); TopicMapsTableModel myModel = new TopicMapsTableModel(datas); mapTable.setModel(myModel); mapTable.setRowSorter(new TableRowSorter(myModel)); mapTable.setColumnSelectionAllowed(false); mapTable.setRowSelectionAllowed(true); mapTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); TableColumn column = null; for (int i=0; i < mapTable.getColumnCount(); i++) { column = mapTable.getColumnModel().getColumn(i); column.setPreferredWidth(myModel.getColumnWidth(i)); } tableScrollPane.setViewportView(mapTable); } } } catch(Exception e) { Wandora.getWandora().displayException("Exception '"+e.getMessage()+"' occurred while getting the list of topic maps.", e); } } } // ------------------------------------------------------------------------- /** 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; entryPanel = new javax.swing.JPanel(); entryInnerPanel = new javax.swing.JPanel(); nameLabel = new SimpleLabel(); nameTextField = new SimpleField(); ownerLabel = new SimpleLabel(); ownerTextField = new SimpleField(); contentPanel = new javax.swing.JPanel(); infoLabel = new SimpleLabel(); namePanel = new javax.swing.JPanel(); apiEndPointLabel = new javax.swing.JLabel(); apiEndPointField = new javax.swing.JComboBox(); apiKeyLabel = new javax.swing.JLabel(); apiKeyTextField = new SimpleField(); refreshListButton = new SimpleButton(); tablePanel = new javax.swing.JPanel(); tableScrollPane = new SimpleScrollPane(); tempLabel = new SimpleLabel(); buttonPanel = new javax.swing.JPanel(); deleteButton = new SimpleButton(); buttonFillerPanel = new javax.swing.JPanel(); importButton = new SimpleButton(); cancelButton = new SimpleButton(); entryPanel.setLayout(new java.awt.GridBagLayout()); entryInnerPanel.setLayout(new java.awt.GridBagLayout()); nameLabel.setText("Topic map name"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 4, 0); entryInnerPanel.add(nameLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 5, 4, 0); entryInnerPanel.add(nameTextField, gridBagConstraints); ownerLabel.setText("Topic map owner"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; entryInnerPanel.add(ownerLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 0); entryInnerPanel.add(ownerTextField, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); entryPanel.add(entryInnerPanel, gridBagConstraints); setLayout(new java.awt.GridBagLayout()); contentPanel.setLayout(new java.awt.GridBagLayout()); infoLabel.setText("<html>Import topic maps from Waiana or Maiana. Select API endpoint and enter your personal API key to the fields below. Then fetch the list of available topic maps and select one or more in the list.</html>"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.ipadx = 1; gridBagConstraints.insets = new java.awt.Insets(0, 0, 10, 0); contentPanel.add(infoLabel, gridBagConstraints); namePanel.setLayout(new java.awt.GridBagLayout()); apiEndPointLabel.setText("API endpoint"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; namePanel.add(apiEndPointLabel, gridBagConstraints); apiEndPointField.setEditable(true); apiEndPointField.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "http://127.0.0.1:8898/waiana/", "http://maiana.topicmapslab.de/api" })); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(0, 5, 4, 0); namePanel.add(apiEndPointField, gridBagConstraints); apiKeyLabel.setText("API key"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 4, 0); namePanel.add(apiKeyLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 5, 4, 0); namePanel.add(apiKeyTextField, gridBagConstraints); refreshListButton.setText("Fetch list"); refreshListButton.setMargin(new java.awt.Insets(2, 4, 2, 4)); refreshListButton.setMaximumSize(new java.awt.Dimension(75, 24)); refreshListButton.setMinimumSize(new java.awt.Dimension(75, 24)); refreshListButton.setPreferredSize(new java.awt.Dimension(75, 24)); refreshListButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { refreshListButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 0); namePanel.add(refreshListButton, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 4, 0); contentPanel.add(namePanel, gridBagConstraints); tablePanel.setLayout(new java.awt.BorderLayout()); tempLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); tempLabel.setText("Press Fetch list button..."); tableScrollPane.setViewportView(tempLabel); tablePanel.add(tableScrollPane, java.awt.BorderLayout.CENTER); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; contentPanel.add(tablePanel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(contentPanel, gridBagConstraints); buttonPanel.setLayout(new java.awt.GridBagLayout()); deleteButton.setText("Delete"); deleteButton.setMargin(new java.awt.Insets(2, 6, 2, 6)); deleteButton.setMinimumSize(new java.awt.Dimension(65, 23)); deleteButton.setPreferredSize(new java.awt.Dimension(65, 23)); deleteButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { deleteButtonActionPerformed(evt); } }); buttonPanel.add(deleteButton, new java.awt.GridBagConstraints()); javax.swing.GroupLayout buttonFillerPanelLayout = new javax.swing.GroupLayout(buttonFillerPanel); buttonFillerPanel.setLayout(buttonFillerPanelLayout); buttonFillerPanelLayout.setHorizontalGroup( buttonFillerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); buttonFillerPanelLayout.setVerticalGroup( buttonFillerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; buttonPanel.add(buttonFillerPanel, gridBagConstraints); importButton.setText("Import"); importButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { importButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4); buttonPanel.add(importButton, gridBagConstraints); cancelButton.setText("Cancel"); cancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelButtonActionPerformed(evt); } }); buttonPanel.add(cancelButton, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 10, 10, 10); add(buttonPanel, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents private void refreshListButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refreshListButtonActionPerformed if(getApiKey() != null) { setTopicMapsList(); } else { WandoraOptionPane.showMessageDialog(window, "In order to fetch a topic map list, Wandora needs a valid api key. Please, write your API key to the api key field first.", "Missing API key", WandoraOptionPane.INFORMATION_MESSAGE); } }//GEN-LAST:event_refreshListButtonActionPerformed private void importButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_importButtonActionPerformed wasAccepted = true; if(window != null) window.setVisible(false); }//GEN-LAST:event_importButtonActionPerformed private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed wasAccepted = false; if(window != null) window.setVisible(false); }//GEN-LAST:event_cancelButtonActionPerformed private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed deleteSelectedTopicMaps(); }//GEN-LAST:event_deleteButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JComboBox apiEndPointField; private javax.swing.JLabel apiEndPointLabel; private javax.swing.JLabel apiKeyLabel; private javax.swing.JTextField apiKeyTextField; private javax.swing.JPanel buttonFillerPanel; private javax.swing.JPanel buttonPanel; private javax.swing.JButton cancelButton; private javax.swing.JPanel contentPanel; private javax.swing.JButton deleteButton; private javax.swing.JPanel entryInnerPanel; private javax.swing.JPanel entryPanel; private javax.swing.JButton importButton; private javax.swing.JLabel infoLabel; private javax.swing.JLabel nameLabel; private javax.swing.JPanel namePanel; private javax.swing.JTextField nameTextField; private javax.swing.JLabel ownerLabel; private javax.swing.JTextField ownerTextField; private javax.swing.JButton refreshListButton; private javax.swing.JPanel tablePanel; private javax.swing.JScrollPane tableScrollPane; private javax.swing.JLabel tempLabel; // End of variables declaration//GEN-END:variables // ------------------------------------------------------------------------- class TopicMapsTableModel extends DefaultTableModel implements TableModel { private static final long serialVersionUID = 1L; JSONArray jsonModel = null; public TopicMapsTableModel(JSONArray m) { jsonModel = m; } @Override public int getRowCount() { if(jsonModel == null) return 0; return jsonModel.length(); } @Override public int getColumnCount() { return 6; } @Override public String getColumnName(int columnIndex) { switch(columnIndex) { case 0: return "Name"; case 1: return "Short name"; case 2: return "Owner"; case 3: return "Is schema"; case 4: return "Is editable"; case 5: return "Is downloadable"; default: return "Illegal column"; } } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return false; } @Override public Object getValueAt(int rowIndex, int columnIndex) { if(jsonModel == null) return null; if(rowIndex >= 0 && rowIndex < jsonModel.length()) { if(columnIndex >= 0 && columnIndex < 6) { try { JSONObject v = jsonModel.getJSONObject(rowIndex); switch(columnIndex) { case 0: return v.get("name").toString(); case 1: return v.get("short_name").toString(); case 2: return v.get("owner").toString(); case 3: return v.get("is_schema").toString(); case 4: return v.get("is_editable").toString(); case 5: return v.get("is_downloadable").toString(); } } catch(Exception e) { return ""; } } } return null; } @Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) { } public int getColumnWidth(int col) { switch(col) { case 0: return 200; case 1: return 100; case 2: return 100; case 3: return 20; case 4: return 20; case 5: return 20; default: return 100; } } } // ------------------------------------------------------------------------- private void deleteSelectedTopicMaps() { boolean requiresListRefresh = false; MaianaUtils.setApiKey(getApiKey()); MaianaUtils.setApiEndPoint(getApiEndPoint()); String[] shortNames = getTopicMapShortNames(); String[] names = getTopicMapNames(); String[] owners = getOwners(); String apikey = MaianaUtils.getApiKey(); if(shortNames.length == 0) { log("You didn't specify which topic maps should be deleted."); } else { int a = WandoraOptionPane.showConfirmDialog(Wandora.getWandora(), "Are you sure you want to delete selected topic maps?", "Are you sure?", WandoraOptionPane.YES_NO_OPTION); if(a != WandoraOptionPane.YES_OPTION) return; } try { for(int i=0; i<shortNames.length; i++) { String sn = shortNames[i]; String o = ""; try { o = owners[i]; } catch(Exception e) {} String n = ""; try { n = names[i]; } catch(Exception e) { n = sn; } String request = MaianaUtils.getDeleteTemplate(apikey, sn); String apiEndPoint = getApiEndPoint(); MaianaUtils.checkForLocalService(apiEndPoint); requiresListRefresh = true; String reply = IObox.doUrl(new URL(apiEndPoint), request, "application/json"); //System.out.println("reply:\n"+reply); JSONObject replyObject = new JSONObject(reply); if(replyObject.has("code")) { String code = replyObject.getString("code"); if(!"0".equals(code)) { if(i<shortNames.length) { int a = WandoraOptionPane.showConfirmDialog(Wandora.getWandora(), "An error occurred while deleting topic map '"+n+"' created by '"+o+"'. Do you want to continue deletion?", "Continue?", WandoraOptionPane.YES_NO_OPTION); if(a != WandoraOptionPane.YES_OPTION) break; } else { log("An error occurred while deleting topic map '"+n+"' created by '"+o+"'."); } } } if(replyObject.has("msg")) { String msg = replyObject.getString("msg"); // log(msg); } } } catch(Exception e) { e.printStackTrace(); } if(requiresListRefresh) { setTopicMapsList(); } } private void log(String msg) { WandoraOptionPane.showMessageDialog(Wandora.getWandora(), msg); } }
25,040
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MaianaExport.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/maiana/MaianaExport.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.maiana; import java.io.ByteArrayOutputStream; import java.net.URL; import java.text.SimpleDateFormat; import javax.swing.Icon; import org.json.JSONObject; 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.tools.exporters.AbstractExportTool; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * See: http://projects.topicmapslab.de/projects/maiana/wiki/API_Controller * * @author akivela */ public class MaianaExport extends AbstractExportTool implements WandoraTool { private static final long serialVersionUID = 1L; public boolean EXPORT_SELECTION_INSTEAD_TOPIC_MAP = false; public MaianaExport() { } public MaianaExport(boolean exportSelection) { EXPORT_SELECTION_INSTEAD_TOPIC_MAP = exportSelection; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/export_maiana.png"); } @Override public boolean isConfigurable(){ return false; } @Override public void configure(Wandora admin,org.wandora.utils.Options options,String prefix) throws TopicMapException { /* Next commented code is here for an example. GenericOptionsDialog god=new GenericOptionsDialog(admin,"GML export options","GML export options",true,new String[][]{ new String[]{"Export classes","boolean",(EXPORT_CLASSES ? "true" : "false"),"Should Wandora export also topic types (class-instance relations)?"}, new String[]{"Export occurrences","boolean",(EXPORT_OCCURRENCES ? "true" : "false"),"Should topic occurrences also export?"}, new String[]{"Export n associations","boolean",(EXPORT_N_ASSOCIATIONS ? "true" : "false"), "Should associations with more than 2 players also export?"}, new String[]{"Is directed","boolean",(EXPORT_DIRECTED ? "true" : "false"), "Export directed or undirected graph" }, },admin); god.setVisible(true); if(god.wasCancelled()) return; Map<String, String> values = god.getValues(); EXPORT_CLASSES = ("true".equals(values.get("Export classes")) ? true : false ); EXPORT_OCCURRENCES = ("true".equals(values.get("Export occurrences")) ? true : false ); EXPORT_N_ASSOCIATIONS = ("true".equals(values.get("Export n associations")) ? true : false ); EXPORT_DIRECTED = ("true".equals(values.get("Is directed")) ? true : false ); * */ } @Override public void execute(Wandora wandora, Context context) { String topicMapName = null; String shortName = null; String exportInfo = null; SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss"); String stamp = sdf.format(System.currentTimeMillis()); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String fineStamp = df.format(System.currentTimeMillis()); // --- Solve first topic map to be exported TopicMap tm = null; if(EXPORT_SELECTION_INSTEAD_TOPIC_MAP) { tm = makeTopicMapWith(context); exportInfo = "Exporting selected topics"; shortName = "wandora_export_"+stamp; topicMapName = "Wandora export "+fineStamp; } else { tm = solveContextTopicMap(wandora, context); topicMapName = this.solveNameForTopicMap(wandora, tm); if(topicMapName != null) { exportInfo = "Exporting topic map in layer '" + topicMapName + "'"; shortName = MaianaUtils.makeShortName(topicMapName); } else { exportInfo = "Exporting topic map"; shortName = "wandora_export_"+stamp; topicMapName = "Wandora export "+fineStamp; } } MaianaExportPanel maianaPanel = new MaianaExportPanel(); maianaPanel.setTopicMapName(topicMapName); maianaPanel.setShortName(shortName); if(MaianaUtils.getApiEndPoint() != null) maianaPanel.setApiEndPoint(MaianaUtils.getApiEndPoint()); if(MaianaUtils.getApiKey() != null) maianaPanel.setApiKey(MaianaUtils.getApiKey()); maianaPanel.open(wandora); if(maianaPanel.wasAccepted()) { try { MaianaUtils.setApiKey(maianaPanel.getApiKey()); MaianaUtils.setApiEndPoint(maianaPanel.getApiEndPoint()); setDefaultLogger(); log(exportInfo); ByteArrayOutputStream out = new ByteArrayOutputStream(); tm.exportXTM(out); String json = MaianaUtils.getExportTemplate(maianaPanel.getApiKey(), maianaPanel.getShortName(), maianaPanel.getTopicMapName(), maianaPanel.isPublic(), maianaPanel.isDownloable(), maianaPanel.isEditable(), maianaPanel.isSchema(), out.toString("UTF-8")); String apiEndPoint = maianaPanel.getApiEndPoint(); MaianaUtils.checkForLocalService(apiEndPoint); String reply = MaianaUtils.doUrl(new URL(apiEndPoint), json, "application/json"); //System.out.println("reply:\n"+reply); JSONObject replyObject = new JSONObject(reply); if(replyObject.has("msg")) { String msg = replyObject.getString("msg"); log("API says '"+msg+"'"); } if(replyObject.has("data")) { String u = replyObject.getString("data"); log("You can access your topic map now with URL "); log(u); } } catch(Exception e) { log(e); } log("Ready."); setState(WAIT); } } @Override public String getName() { return "Export topic map to Waiana"; } @Override public String getDescription() { return "Export topic map to Waiana or Maiana API."; } @Override public boolean requiresRefresh() { return false; } // ------------------------------------------------------------------------- }
7,153
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MaianaUtils.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/maiana/MaianaUtils.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.maiana; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.URL; import java.net.URLConnection; import java.nio.charset.StandardCharsets; import org.json.JSONException; import org.json.JSONObject; import org.wandora.application.Wandora; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.utils.IObox; /** * * @author akivela */ public class MaianaUtils { private static String apiKey = ""; private static String apiEndPoint = null; private static String EXPORT_CMD = "create_local_file"; // create_topic_map"; private static String IMPORT_CMD = "download_local_file"; // download_topic_map; private static String DELETE_CMD = "delete_local_file"; // delete_topic_map; private static String LIST_CMD = "show_local_file_list"; // show_topic_map_list"; public static String exportTemplate = "{ \n"+ " \"api_key\": \"__APIKEY__\", \n"+ " \"parameters\": { \n"+ " \"command\": \"__CMD__\", \n"+ " \"short_name\": \"__SHORTNAME__\", \n"+ " \"name\": \"__NAME__\", \n"+ " \"is_public\": __ISPUBLIC__, \n"+ " \"is_downloadable\": __ISDOWNLOADABLE__, \n"+ " \"is_editable\": __ISEDITABLE__, \n"+ " \"is_schema\": __ISSCHEMA__ \n"+ " }, \n"+ " \"data\": \"__DATA__\" \n"+ "} \n"; public static String importTemplate = "{ \n"+ " \"api_key\": \"__APIKEY__\", \n"+ " \"parameters\": { \n"+ " \"command\": \"__CMD__\", \n"+ " \"short_name\": \"__SHORTNAME__\", \n"+ " \"owner\": \"__NAME__\", \n"+ " \"format\": \"__FORMAT__\" \n"+ " } \n"+ "} \n"; public static String deleteTemplate = "{ \n"+ " \"api_key\": \"__APIKEY__\", \n"+ " \"parameters\": { \n"+ " \"command\": \"__CMD__\", \n"+ " \"short_name\": \"__SHORTNAME__\", \n"+ " } \n"+ "} \n"; public static String listTemplate = "{ \n"+ " \"api_key\": \"__APIKEY__\", \n"+ " \"parameters\": { \n"+ " \"command\": \"__CMD__\" \n"+ " } \n"+ "} \n"; public static void setApiKey(String key) { apiKey = key; } public static String getApiKey() { return apiKey; } public static void setApiEndPoint(String endpoint) { apiEndPoint = endpoint; } public static String getApiEndPoint() { return apiEndPoint; } public static String getExportTemplate(String apikey, String sn, String n, boolean isPublic, boolean isDownloadable, boolean isEditable, boolean isSchema, String data) { String json = exportTemplate; json = json.replace("__APIKEY__", makeJSON(apikey)); json = json.replace("__CMD__", EXPORT_CMD); json = json.replace("__SHORTNAME__", makeJSON(makeShortName(sn))); json = json.replace("__NAME__", makeJSON(n) ); json = json.replace("__ISPUBLIC__", isPublic ? "true" : "false" ); json = json.replace("__ISDOWNLOADABLE__", isDownloadable ? "true" : "false" ); json = json.replace("__ISEDITABLE__", isEditable ? "true" : "false" ); json = json.replace("__ISSCHEMA__", isSchema ? "true" : "false" ); //json = json.replace("__DATA__", "" ); json = json.replace("__DATA__", makeJSON( data ) ); return json; } public static String getImportTemplate(String apikey, String sn, String n, String format) { String json = importTemplate; json = json.replace("__APIKEY__", makeJSON(apikey)); json = json.replace("__CMD__", IMPORT_CMD); json = json.replace("__SHORTNAME__", makeJSON(makeShortName(sn))); json = json.replace("__NAME__", makeJSON(n)); json = json.replace("__FORMAT__", makeJSON(format)); //System.out.println("json:\n"+json); return json; } public static String getDeleteTemplate(String apikey, String sn) { String json = deleteTemplate; json = json.replace("__APIKEY__", makeJSON(apikey)); json = json.replace("__CMD__", DELETE_CMD); json = json.replace("__SHORTNAME__", makeJSON(makeShortName(sn))); return json; } public static String getListTemplate(String apikey) { String json = listTemplate; json = json.replace("__APIKEY__", makeJSON(apikey)); json = json.replace("__CMD__", LIST_CMD); return json; } public static JSONObject listAvailableTopicMaps(String endpoint, String apikey) throws IOException, JSONException { String in = getListTemplate(apikey); checkForLocalService(endpoint); String reply = IObox.doUrl(new URL(endpoint), in, "application/json"); //System.out.println("reply:\n"+reply); JSONObject replyObject = new JSONObject(reply); return replyObject; } // ------------------------------------------------------------------------- public static String makeShortName(String sn) { sn = sn.toLowerCase(); sn = sn.replace(' ', '_'); StringBuilder nsn = new StringBuilder(""); for(int i=0; i<sn.length(); i++) { if(Character.isLetterOrDigit(sn.charAt(i))) { nsn.append(sn.charAt(i)); } else { nsn.append('_'); } } return nsn.toString(); } public static String makeJSON(String string) { if (string == null || string.length() == 0) { return ""; } int c = 0; int i; int len = string.length(); StringBuilder sb = new StringBuilder(len + 4); for (i=0; i<len; i=i+1) { c = string.charAt(i); switch (c) { case '\\': case '"': sb.append('\\'); sb.append((char) c); break; case '/': // if (b == '<') { sb.append('\\'); // } sb.append((char) c); break; case '\b': sb.append("\\b"); break; case '\t': sb.append("\\t"); break; case '\n': sb.append("\\n"); break; case '\f': sb.append("\\f"); break; case '\r': sb.append("\\r"); break; default: sb.append((char) c); } } return sb.toString(); } // ------------------------------------------------------------------------- public static void checkForLocalService(String endpoint) { try { if(endpoint != null && endpoint.startsWith("http://127.0.0.1:8898/waiana")) { Wandora wandora = Wandora.getWandora(); if(wandora != null) { if(!wandora.getHTTPServer().isRunning()) { int a = WandoraOptionPane.showConfirmDialog(wandora, "Wandora's HTTP server is not running at the moment. Would you like to start the server first?", "Start HTTP server?", WandoraOptionPane.OK_CANCEL_OPTION); if( a == WandoraOptionPane.OK_OPTION) { wandora.startHTTPServer(); wandora.menuManager.refreshServerMenu(); } } } } } catch(Exception e) { e.printStackTrace(); } } public static String doUrl(URL url, String data, String ctype) throws IOException { StringBuilder sb = new StringBuilder(5000); if (url != null) { URLConnection con = url.openConnection(); Wandora.initUrlConnection(con); con.setDoInput(true); con.setUseCaches(false); if(ctype != null) { con.setRequestProperty("Content-type", ctype); } if(data != null && data.length() > 0) { con.setRequestProperty("Content-length", data.length() + ""); // con.setRequestProperty("Accept-Charset", "UTF-8"); con.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream(), StandardCharsets.UTF_8); out.write(data); out.flush(); out.close(); } //DataInputStream in = new DataInputStream(con.getInputStream()); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); String s; while ((s = in.readLine()) != null) { sb.append(s); } in.close(); } return sb.toString(); } }
10,116
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MaianaExportPanel.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/maiana/MaianaExportPanel.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/>. * * * * MaianaExportPanel.java * * Created on 11.10.2010, 15:33:31 */ package org.wandora.application.tools.maiana; import java.text.SimpleDateFormat; import javax.swing.JDialog; import org.wandora.application.Wandora; import org.wandora.application.gui.simple.SimpleButton; import org.wandora.application.gui.simple.SimpleCheckBox; import org.wandora.application.gui.simple.SimpleField; import org.wandora.application.gui.simple.SimpleLabel; /** * * @author akivela */ public class MaianaExportPanel extends javax.swing.JPanel { private static final long serialVersionUID = 1L; private boolean wasAccepted = false; private JDialog window = null; /** Creates new form MaianaExportPanel */ public MaianaExportPanel() { initComponents(); } public void open(Wandora wandora) { window = new JDialog(wandora, true); window.setSize(800, 280); window.add(this); window.setTitle("Export to Waiana"); wandora.centerWindow(window); window.setVisible(true); } public void setApiKey(String key) { apiKeyTextField.setText(key); } public String getApiKey() { return apiKeyTextField.getText(); } public void setTopicMapName(String n) { nameTextField.setText(n); } public String getTopicMapName() { return nameTextField.getText(); } public void setShortName(String sn) { shortNameTextField.setText(sn); } public String getShortName() { return shortNameTextField.getText(); } public void setPublic(boolean isPublic) { isPublicCheckBox.setSelected(isPublic); } public boolean isPublic() { return isPublicCheckBox.isSelected(); } public void setDownloadable(boolean isDownloadable) { isDownloadableCheckBox.setSelected(isDownloadable); } public boolean isDownloable() { return isDownloadableCheckBox.isSelected(); } public void setEditable(boolean isEditable) { isEditableCheckBox.setSelected(isEditable); } public boolean isEditable() { return isEditableCheckBox.isSelected(); } public void setSchema(boolean isSchema) { isSchemaCheckBox.setSelected(isSchema); } public boolean isSchema() { return isSchemaCheckBox.isSelected(); } public String getApiEndPoint() { return apiEndPointField.getSelectedItem().toString(); } public void setApiEndPoint(String endpoint) { apiEndPointField.setSelectedItem(endpoint); } public boolean wasAccepted() { return wasAccepted; } /** 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; contentPanel = new javax.swing.JPanel(); infoLabel = new SimpleLabel(); apiEndPointLabel = new javax.swing.JLabel(); apiEndPointField = new javax.swing.JComboBox(); apiKeyLabel = new SimpleLabel(); apiKeyTextField = new SimpleField(); nameLabel = new SimpleLabel(); nameTextField = new SimpleField(); shortNameLabel = new SimpleLabel(); shortNamePanel = new javax.swing.JPanel(); shortNameTextField = new SimpleField(); addDateStampButton = new SimpleButton(); flagsLabel = new SimpleLabel(); flagsPanel = new javax.swing.JPanel(); isPublicCheckBox = new SimpleCheckBox(); isDownloadableCheckBox = new SimpleCheckBox(); isEditableCheckBox = new SimpleCheckBox(); isSchemaCheckBox = new SimpleCheckBox(); flagsFillerPanel = new javax.swing.JPanel(); buttonPanel = new javax.swing.JPanel(); buttonFillerPanel = new javax.swing.JPanel(); uploadButton = new SimpleButton(); cancelButton = new SimpleButton(); setLayout(new java.awt.GridBagLayout()); contentPanel.setLayout(new java.awt.GridBagLayout()); infoLabel.setText("<html>Export selected topic map or selected topics to Waiana or Maiana. Check the API endpoint, your personal API key, topic map names and publishing settings. Topic map's short name is unique and can contain only alphanum characters.</html>"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(0, 0, 15, 0); contentPanel.add(infoLabel, gridBagConstraints); apiEndPointLabel.setText("API endpoint"); 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); contentPanel.add(apiEndPointLabel, gridBagConstraints); apiEndPointField.setEditable(true); apiEndPointField.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "http://127.0.0.1:8898/waiana/", "http://maiana.topicmapslab.de/api" })); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(0, 0, 2, 0); contentPanel.add(apiEndPointField, gridBagConstraints); apiKeyLabel.setText("API key"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 2, 4); contentPanel.add(apiKeyLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 2, 0); contentPanel.add(apiKeyTextField, gridBagConstraints); nameLabel.setText("Topic map name"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 2, 4); contentPanel.add(nameLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 2, 0); contentPanel.add(nameTextField, gridBagConstraints); shortNameLabel.setText("Short name"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 2, 4); contentPanel.add(shortNameLabel, gridBagConstraints); shortNamePanel.setLayout(new java.awt.GridBagLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 2, 0); shortNamePanel.add(shortNameTextField, gridBagConstraints); addDateStampButton.setText("add date stamp"); addDateStampButton.setMargin(new java.awt.Insets(0, 2, 0, 2)); addDateStampButton.setPreferredSize(new java.awt.Dimension(87, 25)); addDateStampButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addDateStampButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 2, 2, 0); shortNamePanel.add(addDateStampButton, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; contentPanel.add(shortNamePanel, gridBagConstraints); flagsLabel.setText("Exported topic map is"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 2, 4); contentPanel.add(flagsLabel, gridBagConstraints); flagsPanel.setLayout(new java.awt.GridBagLayout()); isPublicCheckBox.setFont(org.wandora.application.gui.UIConstants.labelFont); isPublicCheckBox.setSelected(true); isPublicCheckBox.setText("public"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); flagsPanel.add(isPublicCheckBox, gridBagConstraints); isDownloadableCheckBox.setFont(org.wandora.application.gui.UIConstants.labelFont); isDownloadableCheckBox.setSelected(true); isDownloadableCheckBox.setText("downloadable"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); flagsPanel.add(isDownloadableCheckBox, gridBagConstraints); isEditableCheckBox.setFont(org.wandora.application.gui.UIConstants.labelFont); isEditableCheckBox.setSelected(true); isEditableCheckBox.setText("editable"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); flagsPanel.add(isEditableCheckBox, gridBagConstraints); isSchemaCheckBox.setFont(org.wandora.application.gui.UIConstants.labelFont); isSchemaCheckBox.setText("schema"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); flagsPanel.add(isSchemaCheckBox, gridBagConstraints); flagsFillerPanel.setPreferredSize(new java.awt.Dimension(101, 15)); javax.swing.GroupLayout flagsFillerPanelLayout = new javax.swing.GroupLayout(flagsFillerPanel); flagsFillerPanel.setLayout(flagsFillerPanelLayout); flagsFillerPanelLayout.setHorizontalGroup( flagsFillerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); flagsFillerPanelLayout.setVerticalGroup( flagsFillerPanelLayout.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; flagsPanel.add(flagsFillerPanel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 2, 0); contentPanel.add(flagsPanel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(8, 8, 8, 8); add(contentPanel, gridBagConstraints); buttonPanel.setLayout(new java.awt.GridBagLayout()); javax.swing.GroupLayout buttonFillerPanelLayout = new javax.swing.GroupLayout(buttonFillerPanel); buttonFillerPanel.setLayout(buttonFillerPanelLayout); buttonFillerPanelLayout.setHorizontalGroup( buttonFillerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); buttonFillerPanelLayout.setVerticalGroup( buttonFillerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; buttonPanel.add(buttonFillerPanel, gridBagConstraints); uploadButton.setText("Export"); uploadButton.setPreferredSize(new java.awt.Dimension(75, 23)); uploadButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { uploadButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4); buttonPanel.add(uploadButton, gridBagConstraints); cancelButton.setText("Cancel"); cancelButton.setPreferredSize(new java.awt.Dimension(75, 23)); cancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelButtonActionPerformed(evt); } }); buttonPanel.add(cancelButton, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 8, 8, 8); add(buttonPanel, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents private void uploadButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_uploadButtonActionPerformed wasAccepted = true; if(window != null) window.setVisible(false); }//GEN-LAST:event_uploadButtonActionPerformed private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed wasAccepted = false; if(window != null) window.setVisible(false); }//GEN-LAST:event_cancelButtonActionPerformed private void addDateStampButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addDateStampButtonActionPerformed SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss"); String stamp = sdf.format(System.currentTimeMillis()); shortNameTextField.setText(shortNameTextField.getText()+"_"+stamp); }//GEN-LAST:event_addDateStampButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton addDateStampButton; private javax.swing.JComboBox apiEndPointField; private javax.swing.JLabel apiEndPointLabel; private javax.swing.JLabel apiKeyLabel; private javax.swing.JTextField apiKeyTextField; private javax.swing.JPanel buttonFillerPanel; private javax.swing.JPanel buttonPanel; private javax.swing.JButton cancelButton; private javax.swing.JPanel contentPanel; private javax.swing.JPanel flagsFillerPanel; private javax.swing.JLabel flagsLabel; private javax.swing.JPanel flagsPanel; private javax.swing.JLabel infoLabel; private javax.swing.JCheckBox isDownloadableCheckBox; private javax.swing.JCheckBox isEditableCheckBox; private javax.swing.JCheckBox isPublicCheckBox; private javax.swing.JCheckBox isSchemaCheckBox; private javax.swing.JLabel nameLabel; private javax.swing.JTextField nameTextField; private javax.swing.JLabel shortNameLabel; private javax.swing.JPanel shortNamePanel; private javax.swing.JTextField shortNameTextField; private javax.swing.JButton uploadButton; // End of variables declaration//GEN-END:variables }
17,417
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MaianaImport.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/maiana/MaianaImport.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.maiana; import java.io.ByteArrayInputStream; import java.net.URL; import javax.swing.Icon; import org.json.JSONObject; 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.tools.AbstractWandoraTool; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.layered.Layer; import org.wandora.topicmap.layered.LayerStack; /** * * @author akivela */ public class MaianaImport extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; public MaianaImport() { } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/import_maiana.png"); } @Override public boolean isConfigurable(){ return false; } @Override public void configure(Wandora wandora,org.wandora.utils.Options options,String prefix) throws TopicMapException { /* THESE ARE HERE FOR A REFERENCE. HOW TO SET UP CONFIGURABLE OPTIONS. COPIED FROM GML EXPORT. GenericOptionsDialog god=new GenericOptionsDialog(wandora,"GML export options","GML export options",true,new String[][]{ new String[]{"Export classes","boolean",(EXPORT_CLASSES ? "true" : "false"),"Should Wandora export also topic types (class-instance relations)?"}, new String[]{"Export occurrences","boolean",(EXPORT_OCCURRENCES ? "true" : "false"),"Should topic occurrences also export?"}, new String[]{"Export n associations","boolean",(EXPORT_N_ASSOCIATIONS ? "true" : "false"), "Should associations with more than 2 players also export?"}, new String[]{"Is directed","boolean",(EXPORT_DIRECTED ? "true" : "false"), "Export directed or undirected graph" }, },wandora); god.setVisible(true); if(god.wasCancelled()) return; Map<String, String> values = god.getValues(); EXPORT_CLASSES = ("true".equals(values.get("Export classes")) ? true : false ); EXPORT_OCCURRENCES = ("true".equals(values.get("Export occurrences")) ? true : false ); EXPORT_N_ASSOCIATIONS = ("true".equals(values.get("Export n associations")) ? true : false ); EXPORT_DIRECTED = ("true".equals(values.get("Is directed")) ? true : false ); * */ } @Override public void execute(Wandora wandora, Context context) { String topicMapName = ""; String topicMapOwner = ""; MaianaImportPanel maianaPanel = new MaianaImportPanel(); maianaPanel.setName(topicMapName); maianaPanel.setOwner(topicMapOwner); if(MaianaUtils.getApiKey() != null) maianaPanel.setApiKey(MaianaUtils.getApiKey()); if(MaianaUtils.getApiEndPoint() != null) maianaPanel.setApiEndPoint(MaianaUtils.getApiEndPoint()); maianaPanel.open(wandora); if(maianaPanel.wasAccepted()) { try { MaianaUtils.setApiKey(maianaPanel.getApiKey()); MaianaUtils.setApiEndPoint(maianaPanel.getApiEndPoint()); setDefaultLogger(); String[] shortNames = maianaPanel.getTopicMapShortNames(); String[] names = maianaPanel.getTopicMapNames(); String[] owners = maianaPanel.getOwners(); String format = maianaPanel.getFormat(); String apikey = MaianaUtils.getApiKey(); if(shortNames.length > 0) { if(shortNames.length > 1) { log("Importing " + shortNames.length + " topic maps..."); } } else { log("You didn't specify which topic maps should be imported. Aborting."); } for(int i=0; i<shortNames.length; i++) { String sn = shortNames[i]; String o = ""; try { o = owners[i]; } catch(Exception e) {} String n = ""; try { n = names[i]; } catch(Exception e) { n = sn; } log("Importing topic map '"+n+"'..."); String request = MaianaUtils.getImportTemplate(apikey, sn, o, format); String apiEndPoint = maianaPanel.getApiEndPoint(); MaianaUtils.checkForLocalService(apiEndPoint); String reply = MaianaUtils.doUrl(new URL(apiEndPoint), request, "application/json"); //System.out.println("reply:\n"+reply); JSONObject replyObject = new JSONObject(reply); if(replyObject.has("code")) { Object code = replyObject.get("code"); if(code != null) { if(!"0".equals(code.toString())) { log("An error occurred while requesting a topic map '"+n+"' from user '"+o+"'."); } } } if(replyObject.has("msg")) { String msg = replyObject.getString("msg"); log(msg); } if(replyObject.has("data")) { String serializedTopicMap = replyObject.getString("data"); //log("Downloaded topic map is "+serializedTopicMap); log("Parsing topic map '"+n+"'..."); ByteArrayInputStream topicMapStream = new ByteArrayInputStream(serializedTopicMap.getBytes("UTF-8")); TopicMap map = new org.wandora.topicmap.memory.TopicMapImpl(); map.importXTM(topicMapStream, getCurrentLogger()); LayerStack layerStack = wandora.getTopicMap(); String layerName = n; int c = 2; if(layerStack.getLayer(layerName) != null) { String originalLayerName = layerName; do { layerName = originalLayerName + " " + c; c++; } while(layerStack.getLayer(layerName) != null); } log("Creating new layer '" + layerName + "' for the topic map."); Layer importedLayer = new Layer(map,layerName,layerStack); layerStack.addLayer(importedLayer); wandora.layerTree.resetLayers(); wandora.layerTree.selectLayer(importedLayer); } else { log("Invalid topic map serialization for '"+n+"'."); } } } catch(Exception e) { log(e); } log("Ready."); setState(WAIT); } } @Override public String getName() { return "Import topic map from Waiana"; } @Override public String getDescription() { return "Import topic map from Waiana or Maiana API."; } // ------------------------------------------------------------------------- }
8,303
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MediaWikiAPIConfig.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/mediawikiapi/MediaWikiAPIConfig.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.mediawikiapi; /** * * Simple internal container for storing connection configuration. * * @author Eero */ class MediaWikiAPIConfig { private String url; private String uname; private String password; //-------------------------------------------------------------------------- protected String getURL(){ return url; } protected String getUName(){ return uname; } protected String getPassword(){ return password; } //-------------------------------------------------------------------------- protected void setURL(String url){ this.url = url; } protected void setUName(String uname){ this.uname = uname; } protected void setPassword(String password){ this.password = password; } }
1,694
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MediaWikiAPIHandler.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/mediawikiapi/MediaWikiAPIHandler.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.mediawikiapi; import java.util.HashMap; import java.util.Map; import org.json.JSONObject; import org.wandora.application.tools.AbstractWandoraTool; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.JsonNode; import com.mashape.unirest.http.Unirest; /** * * @author Eero */ abstract class MediaWikiAPIHandler extends AbstractWandoraTool{ private static final long serialVersionUID = 1L; private static boolean loggedIn = false; private static String token = null; private static String editToken = null; private static final String VERSION = "1.0"; private static final String USER_AGENT = "MediaWikiAPIHandler " + VERSION; private static final String API_ENDPOINT = "/api.php"; private JSONObject postJSON(String u, Map<String,Object> f) throws Exception{ HttpResponse<JsonNode> resp = Unirest.post(u).fields(f).asJson(); JSONObject respJSON = resp.getBody().getObject(); return respJSON; } protected boolean getLoginStatus(){ return loggedIn; } protected boolean login(MediaWikiAPIConfig config) throws Exception{ String url = config.getURL(); String uname = config.getUName(); String password = config.getPassword(); String tokenCandidate = token; StringBuilder requestBuilder = new StringBuilder() .append(url) .append(API_ENDPOINT); Map<String,Object> requestFields = new HashMap<String, Object>(); requestFields.put("action", "login"); requestFields.put("format", "json"); requestFields.put("lgname", uname); requestFields.put("lgpassword",password); if(tokenCandidate != null) requestBuilder .append("&lgtoken=") .append(tokenCandidate); String requestURL = requestBuilder.toString(); JSONObject respJSON = postJSON(requestURL,requestFields); JSONObject loginJSON = respJSON.getJSONObject("login"); String result = loginJSON.getString("result"); if(result.equals("NeedToken")){ tokenCandidate = loginJSON.getString("token"); requestFields.put("lgtoken",tokenCandidate); requestURL = requestBuilder.toString(); respJSON = postJSON(requestURL,requestFields); loginJSON = respJSON.getJSONObject("login"); result = loginJSON.getString("result"); } if(result.equals("Success")){ token = tokenCandidate; loggedIn = true; return true; } return false; } protected boolean getEditToken(MediaWikiAPIConfig config) throws Exception{ if(editToken != null) return true; String url = config.getURL(); StringBuilder requestBuilder = new StringBuilder() .append(url) .append(API_ENDPOINT); String requestURL = requestBuilder.toString(); Map<String,Object> requestFields = new HashMap<String, Object>(); requestFields.put("action", "tokens"); requestFields.put("format", "json"); JSONObject respJSON = postJSON(requestURL,requestFields); JSONObject tokens = respJSON.getJSONObject("tokens"); String editTokenCandidate = tokens.getString("edittoken"); if(editTokenCandidate.length() > 0){ editToken = editTokenCandidate; return true; } return false; } protected boolean postContent(MediaWikiAPIConfig config, String title, String content) throws Exception{ String url = config.getURL(); StringBuilder requestBuilder = new StringBuilder() .append(url) .append(API_ENDPOINT); String requestURL = requestBuilder.toString(); Map<String,Object> requestFields = new HashMap<String, Object>(); requestFields.put("action", "edit"); requestFields.put("format", "json"); requestFields.put("title",title); requestFields.put("text",content); requestFields.put("token",editToken); JSONObject respJSON = postJSON(requestURL,requestFields); if(respJSON.has("error")){ JSONObject error = respJSON.getJSONObject("error"); StringBuilder errorBuilder = new StringBuilder() .append("API returned error code ") .append(error.getString("code")) .append(": ") .append(error.getString("info")); log(errorBuilder.toString()); return false; } else if(respJSON.has("edit")){ JSONObject edit = respJSON.getJSONObject("edit"); if(edit.has("result") && edit.getString("result").equals("Success")){ log("Succesfully added article: " + title); return true; } else { log("Unknown response from API"); } } else { log("Unknown response from API"); } return false; } }
6,245
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MediaWikiAPIUploader.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/mediawikiapi/MediaWikiAPIUploader.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.mediawikiapi; import java.util.Collection; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.WandoraToolLogger; import org.wandora.application.contexts.Context; import org.wandora.application.tools.GenericOptionsDialog; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author Eero */ public class MediaWikiAPIUploader extends MediaWikiAPIHandler implements WandoraTool{ private static final long serialVersionUID = 1L; private static final String DEFAULT_TYPE_SI = "http://wandora.org/si/mediawiki/api/content/"; private static final String DEFAULT_SCOPE_SI = "http://www.topicmaps.org/xtm/1.0/language.xtm#en"; private static final String TYPE_KEY = "Occurrence type topic"; private static final String SCOPE_KEY = "Occurrence scope topic"; private static final String TYPE_SCOPE_DIALOG_TITLE = "Occurrence upload options"; private static final String TYPE_SCOPE_DIALOG_DESCRIPTION = "Occurrence upload options. If you want to limit occurrences, " + "select occurrence type and scope. Leave both topics empty to " + "use the values the MediaWiki API Extractor uses."; private static final String[][] TYPE_SCOPE_DIALOG_FIELDS = { new String[]{ "Occurrence type topic", "topic","", "Which occurrences are uploaded. Leave blank to use the occurrence " +"type used by the MediaWiki API Extractor." }, new String[]{ "Occurrence scope topic", "topic", "", "Which occurrences are uploaded. Leave blank to use the scope used " +"by the MediaWiki API Extractor." } }; private Wandora wandora; private Context context; private WandoraToolLogger logger; private MediaWikiAPIConfig conf; //-------------------------------------------------------------------------- public MediaWikiAPIUploader(){ super(); this.conf = null; } public MediaWikiAPIUploader(Context c){ super(); this.setContext(c); this.conf = null; } //-------------------------------------------------------------------------- /** * Helper for fetching the content type and scope. * @param w The Wandora object * @return a map of type topics if found, otherwise null * @throws TopicMapException */ private HashMap<String,Topic> getContentTypeAndScope(Wandora w) throws TopicMapException{ /* * Display a dialog for the user. Lets the user choose a type and scope * for the occurrence to specify an occurrence of a topic to use as the * corresponding wiki page content. */ GenericOptionsDialog god=new GenericOptionsDialog(w, TYPE_SCOPE_DIALOG_TITLE,TYPE_SCOPE_DIALOG_DESCRIPTION,true, TYPE_SCOPE_DIALOG_FIELDS,w); god.setVisible(true); if(god.wasCancelled()) return null; /* * We should get a map in the form of * { * occurrence type topic: <type topic SI>, * occurrence scope topic: <scope topic SI> * } */ Map<String,String> values=god.getValues(); /* * Solve topics from the SIs fetched above. The dialog 'should' return * proper topics but we should be careful anyway... */ HashMap<String, Topic> typeAndScope = new HashMap<String, Topic>(); TopicMap tm = w.getTopicMap(); if(values.get(TYPE_KEY).length() > 0) typeAndScope.put(TYPE_KEY, tm.getTopic(values.get(TYPE_KEY))); else typeAndScope.put(TYPE_KEY, tm.getTopic(DEFAULT_TYPE_SI)); if(values.get(SCOPE_KEY).length() > 0) typeAndScope.put(SCOPE_KEY, tm.getTopic(values.get(SCOPE_KEY))); else typeAndScope.put(SCOPE_KEY, tm.getTopic(DEFAULT_SCOPE_SI)); /* * Return null if the map is invalid. */ boolean mapIsValid = (typeAndScope.size() == 2); if(!typeAndScope.containsKey(TYPE_KEY)) mapIsValid = false; if(!typeAndScope.containsKey(SCOPE_KEY)) mapIsValid = false; return mapIsValid ? typeAndScope : null; } /** * Present an UI for the user to input configuration. Update the class * configuration if we got an usable configuration. * * @return whether we got an usable configuration. */ private boolean initializeConfiguartion() { MediaWikiAPIConfigUI ui = new MediaWikiAPIConfigUI(); ui.open(wandora,this); MediaWikiAPIConfig config; try { config = ui.getConfig(); } catch (Exception e) { log(e.getMessage()); return false; } this.conf = config; return true; } /** * Process a single context object (which we want to be a Topic) * @param type The content type topic * @param scope The content scope topic * @param co The context object */ private void processContextObject(Topic type, Topic scope, Object co) { //Early return in the case the object is not applicable if(co == null || !(co instanceof Topic)) return; Topic ct = (Topic) co; Collection<Topic> ctDataTypes; String content; try { /* * Iterate over all occurrence types of ct, discern hit as a merge * between 'type' and the current 'ctType' */ ctDataTypes = ct.getDataTypes(); Hashtable<Topic, String> occurrence; for (Topic ctType : ctDataTypes) { if(!ctType.mergesWithTopic(type)) continue; /* * Occurrence type matches. Iterate over all scopes of the * occurrence. Again, discern hit as a merge between 'scope' and * 'ctScope' */ occurrence = ct.getData(ctType); for(Topic ctScope: occurrence.keySet()){ if(!ctScope.mergesWithTopic(scope)) continue; /* * We got our content! */ try { log("Processing " + ct.getBaseName()); } catch (Exception e) { log(e.getMessage()); e.printStackTrace(); } content = occurrence.get(ctScope); boolean uploaded = upload(ct.getBaseName(), content); } } } catch (TopicMapException tme) { log(tme); } } private boolean upload(String title, String content) { try { if(!getLoginStatus()) login(conf); getEditToken(conf); postContent(conf, title, content); return true; } catch (Exception e) { log(e.getMessage()); } return false; } //-------------------------------------------------------------------------- /** * The public API this package exposes. * @param w Wandora * @param c Context * @throws TopicMapException */ @Override public void execute(Wandora w, Context c) throws TopicMapException { this.wandora = w; this.context = c; setDefaultLogger(); logger = getDefaultLogger(); Topic contentType; Topic contentScope; //Get the context Objects (Topics) Iterator contextObjects = context.getContextObjects(); //Log and early return on context selection failure if(!contextObjects.hasNext()){ log("No context objects found!"); return; } //Prompt the user for the content occurrence type and scope HashMap<String,Topic> typeAndScope = getContentTypeAndScope(w); //Log and early return on configuration failure if(typeAndScope == null) { log("Invalid content type and/or scope"); return; } boolean gotConfig = initializeConfiguartion(); //Log and early return on configuration failure if(!gotConfig) { log("Invalid configuration parameters!"); return; } contentType = typeAndScope.get(TYPE_KEY); contentScope = typeAndScope.get(SCOPE_KEY); while(contextObjects.hasNext() && !forceStop()) processContextObject(contentType,contentScope,contextObjects.next()); setState(WAIT); } }
10,188
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MediaWikiAPIConfigUI.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/mediawikiapi/MediaWikiAPIConfigUI.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.mediawikiapi; 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.SimpleField; import org.wandora.application.gui.simple.SimpleLabel; /** * * @author Eero */ class MediaWikiAPIConfigUI extends javax.swing.JPanel { private static final long serialVersionUID = 1L; private JDialog dialog = null; private boolean accepted; /** * Creates new form MediaWikiAPIConfigUI */ public MediaWikiAPIConfigUI() { initComponents(); } protected void open(Wandora wandora, WandoraTool t) { dialog = new JDialog(wandora, true); dialog.add(this); dialog.setTitle("Mediawiki API uploader options"); dialog.setSize(500, 220); accepted = false; if(wandora != null) wandora.centerWindow(dialog); dialog.setVisible(true); } protected MediaWikiAPIConfig getConfig() throws Exception{ MediaWikiAPIConfig conf = new MediaWikiAPIConfig(); String url = wikiUrlTextField.getText(); if(url.length() == 0) throw new Exception("Missing URL"); String uname = usernameTextField.getText(); if(url.length() == 0) throw new Exception("Missing username"); String password = passwordTextField.getText(); if(url.length() == 0) throw new Exception("Missing password"); conf.setURL(url); conf.setUName(uname); conf.setPassword(password); return conf; } /** * 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; wikiUrlLabel = new SimpleLabel(); wikiUrlTextField = new SimpleField(); usernameLabel = new SimpleLabel(); usernameTextField = new SimpleField(); passwordLabel = new SimpleLabel(); passwordTextField = new SimpleField(); buttonPanel = new javax.swing.JPanel(); FillerjPanel = new javax.swing.JPanel(); okButton = new SimpleButton(); cancelButton = new SimpleButton(); description = new SimpleLabel(); 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.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; gridBagConstraints.insets = new java.awt.Insets(0, 8, 2, 4); 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.gridy = 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, 8); 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.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; gridBagConstraints.insets = new java.awt.Insets(0, 8, 0, 4); 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.gridy = 2; 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, 8); add(usernameTextField, gridBagConstraints); passwordLabel.setText("Password"); passwordLabel.setToolTipText("Password is used to login the Mediawiki."); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; gridBagConstraints.insets = new java.awt.Insets(0, 8, 0, 4); 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.gridy = 3; 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, 8); add(passwordTextField, 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.gridy = 4; gridBagConstraints.gridwidth = 2; 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, 8); add(buttonPanel, gridBagConstraints); description.setText("<html><head></head><body>The details for the targeted MediaWiki instance. The URL should be the one where index.php and api.php are reached. (http://en.wikipedia.org/w/ for the English Wikipedia) The user should have write access to the wiki.</body>"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(8, 8, 8, 8); add(description, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents private void okButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_okButtonMouseReleased accepted = true; if(dialog != null) dialog.setVisible(false); }//GEN-LAST:event_okButtonMouseReleased private void okButtonKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_okButtonKeyReleased accepted = true; if(evt.getKeyCode() == KeyEvent.VK_ENTER) { if(dialog != null) { dialog.setVisible(false); } } }//GEN-LAST:event_okButtonKeyReleased private void cancelButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cancelButtonMouseReleased accepted = false; if(dialog != null) dialog.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.JLabel description; private javax.swing.JButton okButton; private javax.swing.JLabel passwordLabel; private javax.swing.JTextField passwordTextField; 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 }
12,118
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
BasenameWhiteSpaceCollapser.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/topicnames/BasenameWhiteSpaceCollapser.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.topicnames; import java.util.ArrayList; import java.util.HashMap; 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.tools.AbstractWandoraTool; import org.wandora.topicmap.Topic; /** * * @author akivela */ public class BasenameWhiteSpaceCollapser extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; public BasenameWhiteSpaceCollapser() { } public BasenameWhiteSpaceCollapser(Context preferredContext) { setContext(preferredContext); } @Override public String getName() { return "Base name white space collapser"; } @Override public String getDescription() { return "Iterates through selected topics and collapses white spaces in topics' base names"; } @Override public void execute(Wandora wandora, Context context) { try { setDefaultLogger(); setLogTitle("Collapsing white space characters in base names"); log("Collapsing white space characters in base names"); Iterator topics = context.getContextObjects(); if(topics == null || !topics.hasNext()) return; Topic topic = null; String basename = null; StringBuffer newBasename = null; int c = 0; int changed = 0; int progress = 0; HashMap<Topic,String> changeTopics = new HashMap<Topic,String>(); while(topics.hasNext() && !forceStop()) { try { topic = (Topic) topics.next(); c++; if(topic != null) { basename = topic.getBaseName(); if(basename != null) { progress++; log("Investigating topic '" + basename + "'."); newBasename = new StringBuffer(); char ch = 0; boolean isFirst = true; boolean hasChanged = false; for(int i=0; i<basename.length(); i++) { ch = basename.charAt(i); if(Character.isSpaceChar(ch)) { if(isFirst) { newBasename.append(ch); isFirst = false; } else { hasChanged = true; } } else { newBasename.append(ch); isFirst = true; } } if(hasChanged) { changeTopics.put(topic, newBasename.toString()); log("Changing base name to '"+newBasename + "'."); changed++; } } } } catch(Exception e) { log(e); } } List<Topic> changeList = new ArrayList<>(); changeList.addAll(changeTopics.keySet()); for(Topic t : changeList) { try { if(forceStop()) break; basename = changeTopics.get(t); t.setBaseName(basename); changed++; } catch(Exception e) { log(e); } } } catch (Exception e) { log(e); } setState(WAIT); } }
4,949
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
VariantWhiteSpaceCollapser.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/topicnames/VariantWhiteSpaceCollapser.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.topicnames; import java.util.Collection; import java.util.Iterator; import java.util.Set; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.Topic; /** * * @author akivela */ public class VariantWhiteSpaceCollapser extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; /** * Creates a new instance of VariantWhiteSpaceCollapser */ public VariantWhiteSpaceCollapser() { } public VariantWhiteSpaceCollapser(Context preferredContext) { setContext(preferredContext); } @Override public String getName() { return "Variant white space collapser"; } @Override public String getDescription() { return "Iterates through selected topics and converts continuous white spaces to a single white space character in variant names."; } public void execute(Wandora wandora, Context context) { try { setDefaultLogger(); setLogTitle("Collapsing white space characters in variant names"); log("Collapsing white space characters in variant names"); Iterator topics = context.getContextObjects(); if(topics == null || !topics.hasNext()) return; Topic topic = null; String variant = null; StringBuffer newVariant = null; Collection<Set<Topic>> scopes = null; Iterator<Set<Topic>> scopeIterator = null; Set<Topic> scope = null; int progress = 0; while(topics.hasNext() && !forceStop()) { try { topic = (Topic) topics.next(); if(topic != null && !topic.isRemoved()) { progress++; scopes = topic.getVariantScopes(); if(scopes != null) { scopeIterator = scopes.iterator(); while(scopeIterator.hasNext()) { try { scope = (Set<Topic>) scopeIterator.next(); variant = topic.getVariant(scope); if(variant != null) { newVariant = new StringBuffer(); char ch = 0; boolean isFirst = true; boolean hasChanged = false; for(int i=0; i<variant.length(); i++) { ch = variant.charAt(i); if(Character.isSpaceChar(ch)) { if(isFirst) { newVariant.append(ch); isFirst = false; } else { hasChanged = true; } } else { newVariant.append(ch); isFirst = true; } } if(hasChanged) { topic.setVariant(scope, newVariant.toString()); log("Changed variant to '"+newVariant + "'."); } } } catch(Exception e) { log(e); } } } } } catch(Exception e) { log(e); } } setState(WAIT); } catch (Exception e) { log(e); } } }
5,313
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
VariantRemover.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/topicnames/VariantRemover.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/>. * * * VariantRemover.java * * Created on 22. toukokuuta 2006, 17:04 * */ package org.wandora.application.tools.topicnames; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; /** * Implements <code>WandoraAdminTool</code> that removes user specified variant names * in context topics. * * @author akivela */ public class VariantRemover extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; /** * Creates a new instance of VariantRemover */ public VariantRemover() { } public VariantRemover(Context preferredContext) { setContext(preferredContext); } @Override public String getName() { return "Variant name remover"; } @Override public String getDescription() { return "Iterates through selected topics and removes user specified variant names."; } @Override public void execute(Wandora wandora, Context context) { try { Iterator topics = context.getContextObjects(); if(topics == null || !topics.hasNext()) return; Topic typeTopic = wandora.showTopicFinder("Select type of variants to be removed..."); if(typeTopic == null) return; Topic scopeTopic = wandora.showTopicFinder("Select scope of variants to be removed..."); if(typeTopic != null && scopeTopic != null) { setDefaultLogger(); setLogTitle("Removing variant names"); log("Removing variant names of type '" + getTopicName(typeTopic) + "' and scope '" + getTopicName(scopeTopic) + "'."); Set<Topic> scope = null; Locator typeTopicSI = typeTopic.getOneSubjectIdentifier(); Locator scopeTopicSI = scopeTopic.getOneSubjectIdentifier(); int progress = 0; int removed = 0; Topic topic = null; while(topics.hasNext() && !forceStop()) { try { topic = (Topic) topics.next(); if(topic != null && !topic.isRemoved()) { progress++; typeTopic = topic.getTopicMap().getTopic(typeTopicSI); scopeTopic = topic.getTopicMap().getTopic(scopeTopicSI); if(typeTopic != null && scopeTopic != null) { scope = new HashSet<Topic>(); scope.add(typeTopic); scope.add(scopeTopic); if(topic.getVariant(scope) != null) { topic.removeVariant(scope); removed++; } } } } catch(Exception e) { log(e); } } log("Removed total " + removed + " variant names."); setState(WAIT); } } catch (Exception e) { log(e); } } }
4,421
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
VariantNewlineRemover.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/topicnames/VariantNewlineRemover.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/>. * * * VariantNewlineRemover.java * * Created on 22. toukokuuta 2006, 14:21 * */ package org.wandora.application.tools.topicnames; import java.util.Collection; import java.util.Iterator; import java.util.Set; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.Topic; /** * As well as base names also variant names containing new line characters * are partially invisible in <code>Wandora</code>. It is recommended * that variant names with new lines are fixed with this tool. * * @author akivela */ public class VariantNewlineRemover extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; public String replacement = ""; /** * Creates a new instance of VariantNewlineRemover */ public VariantNewlineRemover() { } public VariantNewlineRemover(Context preferredContext) { setContext(preferredContext); } @Override public String getName() { return "Variant name new line remover"; } @Override public String getDescription() { return "Iterates through selected topics and removes new line characters in variant names."; } public void execute(Wandora wandora, Context context) { try { setDefaultLogger(); setLogTitle("Removing new line characters in variant names"); log("Removing new line characters in variant names"); Iterator topics = context.getContextObjects(); if(topics == null || !topics.hasNext()) return; Topic topic = null; String variant = null; String newVariant = null; Collection<Set<Topic>> scopes = null; Iterator<Set<Topic>> scopeIterator = null; Set<Topic> scope = null; int progress = 0; while(topics.hasNext() && !forceStop()) { try { topic = (Topic) topics.next(); if(topic != null && !topic.isRemoved()) { progress++; scopes = topic.getVariantScopes(); if(scopes != null) { scopeIterator = scopes.iterator(); while(scopeIterator.hasNext()) { try { scope = (Set<Topic>) scopeIterator.next(); variant = topic.getVariant(scope); if(variant != null) { if(variant.indexOf("\n") != -1 || variant.indexOf("\r") != -1) { newVariant = variant.replaceAll("\r", replacement); newVariant = newVariant.replaceAll("\n", replacement); log("Changing variant '"+variant+"' to\n"+newVariant ); topic.setVariant(scope, newVariant); } } } catch(Exception e) { log(e); } } } } } catch(Exception e) { log(e); } } setState(WAIT); } catch (Exception e) { log(e); } } }
4,561
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MakeDisplayVariantsFromBasename.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/topicnames/MakeDisplayVariantsFromBasename.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/>. * * * MakeDisplayVariantsFromBasename.java * * Created on 22. toukokuuta 2006, 14:55 * */ package org.wandora.application.tools.topicnames; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.XTMPSI; /** * <code>MakeDisplayVariantsFromBasename</code> copies topics base name to * topic's variant names. If topic already contain variant name, boolean * variable <code>overWrite</code> defines if the existing variant name * is over written. Tool solves available variant name scopes and types using * <code>WandoraAdminManager</code>. Only names with available scopes and types * are set. * * * @author akivela */ public class MakeDisplayVariantsFromBasename extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; boolean overWrite = false; /** * Creates a new instance of MakeDisplayVariantsWithBasename */ public MakeDisplayVariantsFromBasename() { } public MakeDisplayVariantsFromBasename(Context preferredContext) { setContext(preferredContext); } @Override public String getName() { return "Makes display variant names using topic's base name."; } @Override public String getDescription() { return "Iterates through selected topics and copies topic's base name to variant names."; } public void execute(Wandora wandora, Context context) { try { setDefaultLogger(); setLogTitle("Copying base name to topic variant names"); log("Copying base name to topic variant names"); Iterator topics = context.getContextObjects(); if(topics == null || !topics.hasNext()) return; Topic topic = null; String basename = null; String variant = null; Iterator<Topic> languageIterator = null; Topic language = null; Set<Topic> scope = null; Collection<Topic> languages = wandora.getTopicMap().getTopicsOfType(TMBox.LANGUAGE_SI); Topic displayScope = wandora.getTopicMap().getTopic(XTMPSI.DISPLAY); int progress = 0; while(topics.hasNext() && !forceStop()) { try { topic = (Topic) topics.next(); if(topic != null && !topic.isRemoved()) { setProgress(progress++); basename = topic.getBaseName(); if(languages != null) { languageIterator = languages.iterator(); while(languageIterator.hasNext()) { try { language = (Topic) languageIterator.next(); scope = new LinkedHashSet<>(); scope.add(language); scope.add(displayScope); variant = topic.getVariant(scope); if(variant == null || overWrite) { topic.setVariant(scope, basename); } } catch(Exception e) { log(e); } } } } } catch(Exception e) { log(e); } } log("Ready."); setState(WAIT); } catch (Exception e) { log(e); } } }
4,878
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AddImplicitSortScopeToVariants.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/topicnames/AddImplicitSortScopeToVariants.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/>. * * * AddImplicitDisplayScopeToVariants.java * * Created on 22.2.2010, 14:21 * */ package org.wandora.application.tools.topicnames; import java.util.Collection; import java.util.Iterator; import java.util.Set; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.XTMPSI; /** * * @author akivela */ public class AddImplicitSortScopeToVariants extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; /** * Creates a new instance of AddImplicitDisplayScopeToVariants */ public AddImplicitSortScopeToVariants() { } public AddImplicitSortScopeToVariants(Context preferredContext) { setContext(preferredContext); } @Override public String getName() { return "Add implicit sort scope to variants"; } @Override public String getDescription() { return "Iterates through selected topics and adds sort scope to variants that have neither display nor sort scope."; } @Override public void execute(Wandora wandora, Context context) { try { setDefaultLogger(); setLogTitle("Add implicit sort scope to variants"); log("Iterates through selected topics and adds sort scope to variants that have neither display nor sort scope."); TopicMap tm = wandora.getTopicMap(); Iterator topics = context.getContextObjects(); if(topics == null || !topics.hasNext()) return; Topic topic = null; String variant = null; Topic displayScope = tm.getTopic(XTMPSI.DISPLAY); Topic sortScope = tm.getTopic(XTMPSI.SORT); if(sortScope == null) return; Collection<Set<Topic>> scopes = null; Iterator<Set<Topic>> scopeIterator = null; Set<Topic> scope = null; Topic scopeTopic = null; int progress = 0; int count = 0; while(topics.hasNext() && !forceStop()) { try { topic = (Topic) topics.next(); if(topic != null && !topic.isRemoved()) { progress++; topic = tm.getTopic(topic.getOneSubjectIdentifier()); // Change topic to layer stack topic instead of layer topic! scopes = topic.getVariantScopes(); if(scopes != null) { scopeIterator = scopes.iterator(); while(scopeIterator.hasNext() && !forceStop()) { try { scope = (Set<Topic>) scopeIterator.next(); boolean scopeIsComplete = false; for( Iterator<Topic> scopeTopicIterator = scope.iterator(); scopeTopicIterator.hasNext(); ) { scopeTopic = scopeTopicIterator.next(); if(scopeTopic != null) { if(scopeTopic.mergesWithTopic(sortScope)) { scopeIsComplete = true; break; } else if(displayScope != null && scopeTopic.mergesWithTopic(displayScope)) { scopeIsComplete = true; break; } } } if(!scopeIsComplete) { // Incomplete scope... Adding sort scope! variant = topic.getVariant(scope); if(variant != null) { topic.removeVariant(scope); scope.add(sortScope); topic.setVariant(scope, variant); count++; } } } catch(Exception e) { log(e); } } } } } catch(Exception e) { log(e); } } log("Found "+count+" variant names without display nor sort scope. Added sort scope."); log("OK"); setState(WAIT); } catch (Exception e) { log(e); } } }
5,859
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
BasenameTrimmer.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/topicnames/BasenameTrimmer.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/>. * * * BasenameNewlineRemover.java * * Created on 19. toukokuuta 2006, 12:16 * */ package org.wandora.application.tools.topicnames; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; 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.tools.AbstractWandoraTool; import org.wandora.topicmap.Topic; /** * This is a Tool used to remove surrounding white space characters in basenames. * * @author akivela */ public class BasenameTrimmer extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; public BasenameTrimmer() { } public BasenameTrimmer(Context preferredContext) { setContext(preferredContext); } @Override public String getName() { return "Basename trimmer"; } @Override public String getDescription() { return "Iterates through selected topics and removes surrounding white space characters in basenames."; } @Override public void execute(Wandora wandora, Context context) { try { setDefaultLogger(); setLogTitle("Removing surrounding white space characters in basenames"); log("Removing surrounding white space characters in basenames"); Iterator<Topic> topics = context.getContextObjects(); if(topics == null || !topics.hasNext()) return; Topic topic = null; String basename = null; String newBasename = null; int c = 0; int changed = 0; int progress = 0; Map<Topic,String> changeTopics = new HashMap<Topic,String>(); while(topics.hasNext() && !forceStop()) { try { topic = (Topic) topics.next(); c++; if(topic != null) { basename = topic.getBaseName(); if(basename != null) { progress++; hlog("Investigating topic '" + basename + "'."); newBasename = basename.trim(); if(!basename.equals(newBasename)) { changeTopics.put(topic, newBasename); } } } } catch(Exception e) { log(e); } } List<Topic> changeList = new ArrayList<>(); changeList.addAll(changeTopics.keySet()); for(Topic t : changeList) { try { if(forceStop()) break; newBasename = changeTopics.get(t); t.setBaseName(newBasename); log("Changed base name to '"+newBasename + "'."); changed++; } catch(Exception e) { log(e); } } } catch (Exception e) { log(e); } setState(WAIT); } }
4,105
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AllEmptyVariantRemover.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/topicnames/AllEmptyVariantRemover.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/>. * * * AllEmptyVariantRemover.java * * Created on 22. toukokuuta 2006, 17:04 * */ package org.wandora.application.tools.topicnames; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Set; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.Topic; /** * Tool removes all variant empty names of context topics. Empty variant name * has a name length of 0. * * @author akivela */ public class AllEmptyVariantRemover extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; public AllEmptyVariantRemover() { } public AllEmptyVariantRemover(Context preferredContext) { setContext(preferredContext); } @Override public String getName() { return "All empty variant name remover"; } @Override public String getDescription() { return "Iterates through selected topics and removes all empty variant names."; } @Override public void execute(Wandora wandora, Context context) { try { Iterator topics = context.getContextObjects(); if(topics == null || !topics.hasNext()) return; if(WandoraOptionPane.showConfirmDialog(wandora, "Are you sure you want to remove all empty variant names of selected topics?","Confirm variant name remove", WandoraOptionPane.YES_NO_OPTION)==WandoraOptionPane.YES_OPTION){ setDefaultLogger(); setLogTitle("Removing all empty variant names"); log("Removing all empty variant names"); Topic topic = null; String variant = null; List<Set<Topic>> deleteScopes = null; Collection<Set<Topic>> scopes = null; Iterator<Set<Topic>> scopeIterator = null; Set<Topic> scope = null; int progress = 0; int deleted = 0; while(topics.hasNext() && !forceStop()) { try { topic = (Topic) topics.next(); if(topic != null && !topic.isRemoved()) { progress++; scopes = topic.getVariantScopes(); if(scopes != null) { deleteScopes = new ArrayList<>(); scopeIterator = scopes.iterator(); while(scopeIterator.hasNext()) { try { scope = (Set<Topic>) scopeIterator.next(); variant = topic.getVariant(scope); if(variant != null && variant.length() == 0) { deleteScopes.add(scope); } } catch(Exception e) { log(e); } } scopeIterator = deleteScopes.iterator(); while(scopeIterator.hasNext()) { try { scope = (Set<Topic>) scopeIterator.next(); topic.removeVariant(scope); deleted++; } catch(Exception e) { log(e); } } } } } catch(Exception e) { log(e); } } log("Total " + progress + " topics inspected."); log("Total " + deleted + " variant names removed."); setState(WAIT); } } catch (Exception e) { log(e); } } }
5,234
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
BasenameNewlineRemover.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/topicnames/BasenameNewlineRemover.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/>. * * * BasenameNewlineRemover.java * * Created on 19. toukokuuta 2006, 12:16 * */ package org.wandora.application.tools.topicnames; import java.util.ArrayList; import java.util.HashMap; 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.tools.AbstractWandoraTool; import org.wandora.topicmap.Topic; /** * This is a WandoraAdminTool used to remove new line characters in base names. * Current Wandora GUI represent topics using their base names and multiline * representation is rarely available due to used GUI elements. As a result * multiline base name is partially invisible in Wandora. * * @author akivela */ public class BasenameNewlineRemover extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; public BasenameNewlineRemover() { } public BasenameNewlineRemover(Context preferredContext) { setContext(preferredContext); } @Override public String getName() { return "Base name newline remover"; } @Override public String getDescription() { return "Iterates through selected topics and removes new line characters in base names."; } public void execute(Wandora wandora, Context context) { try { setDefaultLogger(); setLogTitle("Removing newline characters in base names"); log("Removing newline characters in base names"); Iterator topics = context.getContextObjects(); if(topics == null || !topics.hasNext()) return; Topic topic = null; String basename = null; String newBasename = null; int c = 0; int changed = 0; int progress = 0; HashMap<Topic,String> changeTopics = new HashMap<Topic,String>(); while(topics.hasNext() && !forceStop()) { try { topic = (Topic) topics.next(); c++; if(topic != null) { basename = topic.getBaseName(); if(basename != null) { progress++; hlog("Investigating topic '" + basename + "'."); if(basename.indexOf("\n") != -1 || basename.indexOf("\r") != -1) { newBasename = basename.replaceAll("\r", ""); newBasename = newBasename.replaceAll("\n", ""); changeTopics.put(topic, newBasename); } } } } catch(Exception e) { log(e); } } List<Topic> changeList = new ArrayList<>(); changeList.addAll(changeTopics.keySet()); for(Topic t : changeList) { try { if(forceStop()) break; newBasename = changeTopics.get(t); t.setBaseName(newBasename); log("Changed base name to '"+newBasename + "'."); changed++; } catch(Exception e) { log(e); } } } catch (Exception e) { log(e); } setState(WAIT); } }
4,390
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MakeBasenameFromOccurrence.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/topicnames/MakeBasenameFromOccurrence.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/>. * * * MakeBasenameFromOccurrence.java * * Created on 25. toukokuuta 2006, 10:57 * */ package org.wandora.application.tools.topicnames; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; /** * This tool can be used to fill topic base name with topic's occurrence. * For example <code>SimpleRDFImport</code> results topics without * base name but each RDF resource label is text occurrence and can be converted * to base name. Base name is constructed using <code>template</code> string. * All %OCCURRENCE% strings in template are replaced with topic's occurrence * string. As occurrences may be identical, tool may result topic merges. * * Before base name is set, new line characters are removed from occurrence * texts and text length is limited to <code>MAXLEN</code>. * * @author akivela */ public class MakeBasenameFromOccurrence extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; public static int MAXLEN = 256; public String replacement = ""; public String template = "%OCCURRENCE%"; boolean overWrite = false; boolean askTemplate = true; boolean narrowIdentity = false; /** Creates a new instance of MakeBasenameWithOccurrence */ public MakeBasenameFromOccurrence() { } public MakeBasenameFromOccurrence(Context preferredContext) { setContext(preferredContext); } @Override public String getName() { return "Copy occurrence to topic base name"; } @Override public String getDescription() { return "Iterates through selected topics and fills empty base names with occurrence."; } public void execute(Wandora wandora, Context context) { try { template = "%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(); if(askTemplate) { template = WandoraOptionPane.showInputDialog(wandora, "Make base name from occurrence using following template. String '%OCCURRENCE%' is replaced with the occurrence.", "%OCCURRENCE%"); if(template == null || template.length() == 0 || !template.contains("%OCCURRENCE%")) { int a = WandoraOptionPane.showConfirmDialog(wandora, "Your template string '"+ template +"' does not contain '%OCCURRENCE%'. This results identical base names and topic merges. Are you sure you want to continue?", "Invalid template given", WandoraOptionPane.YES_NO_CANCEL_OPTION); if(a != WandoraOptionPane.YES_OPTION) return; } } int a = WandoraOptionPane.showConfirmDialog(wandora, "Changing base name may cause topic merges and SI explosion in certain topics. Would you like to limit number of SIs in a single topic to 10?", "Narrow identity?", WandoraOptionPane.YES_NO_CANCEL_OPTION); if(a == WandoraOptionPane.CANCEL_OPTION) return; else if(a == WandoraOptionPane.YES_OPTION) narrowIdentity = true; else if(a == WandoraOptionPane.NO_OPTION) narrowIdentity = false; setDefaultLogger(); setLogTitle("Copying occurrence to base name"); log("Copying occurrence to topic's base name"); Topic topic = null; String basename = null; int progress = 0; String occurrence = null; int count = 0; ArrayList<Object> dt = new ArrayList<Object>(); while(topics.hasNext() && !forceStop()) { dt.add(topics.next()); } topics = dt.iterator(); while(topics.hasNext() && !forceStop()) { try { topic = (Topic) topics.next(); if(topic != null && !topic.isRemoved()) { setProgress(progress++); basename = topic.getBaseName(); if(overWrite || basename == null) { occurrenceType = topic.getTopicMap().getTopic(occurrenceTypeLocator); occurrenceScope = topic.getTopicMap().getTopic(occurrenceScopeLocator); occurrence = topic.getData(occurrenceType, occurrenceScope); if(occurrence != null && occurrence.length() > 0) { if(occurrence.length() > MAXLEN) { occurrence.substring(0, MAXLEN); } if(occurrence.indexOf("\n") != -1 || occurrence.indexOf("\r") != -1) { occurrence = occurrence.replaceAll("\r", replacement); occurrence = occurrence.replaceAll("\n", replacement); } occurrence = occurrence.trim(); basename = template; basename = basename.replaceAll("%OCCURRENCE%", occurrence); log("Adding topic base name '"+basename+"'"); topic.setBaseName(basename); count++; if(narrowIdentity) { Collection<Locator> sis = topic.getSubjectIdentifiers(); int s = sis.size(); ArrayList<Locator> deleteThese = new ArrayList<Locator>(); if(s > 10) { int n = 0; Iterator<Locator> sii = sis.iterator(); while(s-n>10 && sii.hasNext()) { deleteThese.add(sii.next()); n++; } Iterator<Locator> deleteIterator = deleteThese.iterator(); while(deleteIterator.hasNext()) { topic.removeSubjectIdentifier(deleteIterator.next()); } } } } } } } catch(Exception e) { log(e); } } log("Total "+progress+" topics investigated!"); log("Total "+count+" basenames set!"); setState(WAIT); } catch (Exception e) { log(e); } } }
8,569
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MakeBasenameFromSubjectIdentifier.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/topicnames/MakeBasenameFromSubjectIdentifier.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/>. * * * MakeBasenameFromSubjectIdentifier.java * * Created on 25. toukokuuta 2006, 10:43 * */ package org.wandora.application.tools.topicnames; import java.net.URLDecoder; 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.tools.AbstractWandoraTool; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; /** * Sometimes topic lacks base names. For example <code>SimpleRDFImport</code> * produces topics without base names. This tool can be used to fill topic * base name with subject identifier's file name. As subject identifier's * file name is only partial fraction of URL, applying tool to a numerous * topics may result merges. * * @author akivela */ public class MakeBasenameFromSubjectIdentifier extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; boolean overWrite = false; /** * Creates a new instance of MakeBasenameWithSI */ public MakeBasenameFromSubjectIdentifier() { } public MakeBasenameFromSubjectIdentifier(Context preferredContext) { setContext(preferredContext); } @Override public String getName() { return "Copy SI to topic base name"; } @Override public String getDescription() { return "Iterates through selected topics and fills empty basenames with subject identifier filename."; } public void execute(Wandora wandora, Context context) { try { setDefaultLogger(); setLogTitle("Copying SI to base name"); log("Copying subject identifier file name to topic base name"); Iterator topics = context.getContextObjects(); if(topics == null || !topics.hasNext()) return; Topic topic = null; String basename = null; Collection<Locator> sis = null; int progress = 0; List<Object> dt = new ArrayList<Object>(); while(topics.hasNext() && !forceStop()) { dt.add(topics.next()); } topics = dt.iterator(); while(topics.hasNext() && !forceStop()) { try { topic = (Topic) topics.next(); if(topic != null && !topic.isRemoved()) { setProgress(progress++); basename = topic.getBaseName(); if(overWrite || basename == null) { sis = topic.getSubjectIdentifiers(); if(sis != null && sis.size() > 0) { basename = ((Locator) sis.iterator().next()).toExternalForm(); if(!basename.endsWith("/")) { if(basename.indexOf("/") != -1) { String oldBasename = basename; basename = basename.substring(basename.lastIndexOf("/")+1); if(basename.length() == 0) { basename = oldBasename; } } if(basename != null && basename.length() > 0) { basename = URLDecoder.decode(basename, "UTF-8"); } log("Adding topic base name '"+basename+"'"); topic.setBaseName(basename); } } } } } catch(Exception e) { log(e); } } setState(WAIT); } catch (Exception e) { log(e); } } }
4,947
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DeleteScopeTopicInVariantName.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/topicnames/DeleteScopeTopicInVariantName.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.topicnames; import java.util.LinkedHashSet; import java.util.Set; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.Topic; /** * * @author akivela */ public class DeleteScopeTopicInVariantName extends AbstractWandoraTool { private static final long serialVersionUID = 1L; private Topic t = null; private Set<Topic> scope = null; private Topic scopeTopic = null; public DeleteScopeTopicInVariantName(Topic variantCarrier, Set<Topic> variantScope, Topic st) { t = variantCarrier; scope = variantScope; scopeTopic = st; } @Override public String getName() { return "Delete scope topic in variant name"; } @Override public String getDescription() { return "Deletes scope topic in variant name of a topic and a scope specified in constructor."; } public void execute(Wandora wandora, Context context) { try { if(t != null && !t.isRemoved() && scopeTopic != null && !scopeTopic.isRemoved()) { if(scope != null) { String n = t.getVariant(scope); if(n != null) { t.removeVariant(scope); Set<Topic> newScope = new LinkedHashSet<Topic>(); newScope.addAll(scope); newScope.remove(scopeTopic); t.setVariant(newScope, n); } } } } catch(Exception e) { e.printStackTrace(); } } }
2,515
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AddImplicitDisplayScopeToVariants.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/topicnames/AddImplicitDisplayScopeToVariants.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/>. * * * AddImplicitDisplayScopeToVariants.java * * Created on 22.2.2010, 14:21 * */ package org.wandora.application.tools.topicnames; import java.util.Collection; import java.util.Iterator; import java.util.Set; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.XTMPSI; /** * * @author akivela */ public class AddImplicitDisplayScopeToVariants extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; /** * Creates a new instance of AddImplicitDisplayScopeToVariants */ public AddImplicitDisplayScopeToVariants() { } public AddImplicitDisplayScopeToVariants(Context preferredContext) { setContext(preferredContext); } @Override public String getName() { return "Add implicit display scope to variants"; } @Override public String getDescription() { return "Iterates through selected topics and adds display scope to variants that have neither display nor sort scope."; } @Override public void execute(Wandora wandora, Context context) { try { setDefaultLogger(); setLogTitle("Add implicit display scope to variants"); log("Iterates through selected topics and adds display scope to variants that have neither display nor sort scope."); TopicMap tm = wandora.getTopicMap(); Iterator topics = context.getContextObjects(); if(topics == null || !topics.hasNext()) return; Topic topic = null; String variant = null; Topic displayScope = tm.getTopic(XTMPSI.DISPLAY); if(displayScope == null) return; Topic sortScope = tm.getTopic(XTMPSI.SORT); Collection<Set<Topic>> scopes = null; Iterator<Set<Topic>> scopeIterator = null; Set<Topic> scope = null; Topic scopeTopic = null; int progress = 0; int count = 0; while(topics.hasNext() && !forceStop()) { try { topic = (Topic) topics.next(); if(topic != null && !topic.isRemoved()) { progress++; topic = tm.getTopic(topic.getOneSubjectIdentifier()); // Change topic to layer stack topic instead of layer topic! scopes = topic.getVariantScopes(); if(scopes != null) { scopeIterator = scopes.iterator(); while(scopeIterator.hasNext() && !forceStop()) { try { scope = (Set<Topic>) scopeIterator.next(); boolean scopeIsComplete = false; for( Iterator<Topic> scopeTopicIterator = scope.iterator(); scopeTopicIterator.hasNext(); ) { scopeTopic = scopeTopicIterator.next(); if(scopeTopic != null) { if(scopeTopic.mergesWithTopic(displayScope)) { scopeIsComplete = true; break; } else if(sortScope != null && scopeTopic.mergesWithTopic(sortScope)) { scopeIsComplete = true; break; } } } if(!scopeIsComplete) { // Incomplete scope... Adding display scope! variant = topic.getVariant(scope); if(variant != null) { topic.removeVariant(scope); scope.add(displayScope); topic.setVariant(scope, variant); count++; } } } catch(Exception e) { log(e); } } } } } catch(Exception e) { log(e); } } log("Found "+count+" variant names without display nor sort scope. Added display scope."); log("OK"); setState(WAIT); } catch (Exception e) { log(e); } } }
5,900
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AllVariantRemover.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/topicnames/AllVariantRemover.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/>. * * * AllVariantRemover.java * * Created on 22. toukokuuta 2006, 17:04 * */ package org.wandora.application.tools.topicnames; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Set; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.Topic; /** * Tool removes all variant names in context topics. Deletion is confirmed. * * @author akivela */ public class AllVariantRemover extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; public AllVariantRemover() { } public AllVariantRemover(Context preferredContext) { setContext(preferredContext); } @Override public String getName() { return "All variant name remover"; } @Override public String getDescription() { return "Iterates through selected topics and removes all variant names."; } @Override public void execute(Wandora wandora, Context context) { try { Iterator topics = context.getContextObjects(); if(topics == null || !topics.hasNext()) return; if(WandoraOptionPane.showConfirmDialog(wandora, "Are you sure you want to remove all variant names of selected topics?","Confirm variant name remove", WandoraOptionPane.YES_NO_OPTION)==WandoraOptionPane.YES_OPTION){ setDefaultLogger(); setLogTitle("Removing all variant names"); log("Removing all variant names"); Topic topic = null; String variant = null; List<Set<Topic>> deleteScopes; Collection<Set<Topic>> scopes = null; Iterator<Set<Topic>> scopeIterator = null; Set<Topic> scope = null; int progress = 0; int deleted = 0; while(topics.hasNext() && !forceStop()) { try { topic = (Topic) topics.next(); if(topic != null && !topic.isRemoved()) { progress++; scopes = topic.getVariantScopes(); if(scopes != null) { deleteScopes = new ArrayList<>(); scopeIterator = scopes.iterator(); while(scopeIterator.hasNext()) { try { scope = scopeIterator.next(); variant = topic.getVariant(scope); if(variant != null) { deleteScopes.add(scope); } } catch(Exception e) { log(e); } } scopeIterator = deleteScopes.iterator(); while(scopeIterator.hasNext()) { try { scope = scopeIterator.next(); topic.removeVariant(scope); deleted++; } catch(Exception e) { log(e); } } } } } catch(Exception e) { log(e); } } setState(WAIT); } } catch (Exception e) { log(e); } } }
4,964
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ChangeVariantView.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/topicnames/ChangeVariantView.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/>. * * * ChangeVariantView.java * * Created on 2008-11-14 * */ package org.wandora.application.tools.topicnames; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.gui.OccurrenceTable; import org.wandora.application.gui.topicpanels.TraditionalTopicPanel; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.TopicMapException; import org.wandora.utils.Options; /** * Changes Wandora application options to reflect user selected variant name * view. * * @author akivela */ public class ChangeVariantView extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; private String viewType = OccurrenceTable.VIEW_SCHEMA; private Options localOptions = null; /** Creates a new instance of ChangeVariantView */ public ChangeVariantView(String type) { viewType = type; } public ChangeVariantView(String type, Options localOpts) { viewType = type; localOptions = localOpts; } @Override public String getName() { return "Change variant name table view"; } @Override public String getDescription() { return "Change variant name table view."; } @Override public void execute(Wandora wandora, Context context) throws TopicMapException { if(localOptions != null) { localOptions.put(TraditionalTopicPanel.VARIANT_GUITYPE_OPTIONS_KEY, viewType); } if(wandora != null) { Options ops = wandora.getOptions(); ops.put(TraditionalTopicPanel.VARIANT_GUITYPE_OPTIONS_KEY, viewType); //System.out.println("ops == " + ops.get(TraditionalTopicPanel.VARIANT_GUITYPE_OPTIONS_KEY)); } } @Override public boolean requiresRefresh() { return true; } }
2,767
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AddMissingLanguageScope.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/topicnames/AddMissingLanguageScope.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/>. * * * AddMissingLanguageScope.java * * Created on 22.2.2010, 14:21 * */ package org.wandora.application.tools.topicnames; import java.util.Collection; import java.util.Iterator; import java.util.Set; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.XTMPSI; /** * * @author akivela */ public class AddMissingLanguageScope extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; /** * Creates a new instance of AddMissingLanguageScope */ public AddMissingLanguageScope() { } public AddMissingLanguageScope(Context preferredContext) { setContext(preferredContext); } @Override public String getName() { return "Add implicit language scope to variants"; } @Override public String getDescription() { return "Iterates through selected topics and adds given scope topic to variants that have only display or sort scope."; } @Override public void execute(Wandora wandora, Context context) { try { setDefaultLogger(); setLogTitle("Add implicit language scope to variants"); log("Iterates through selected topics and adds given scope topic to variants that have only display or sort scope."); TopicMap tm = wandora.getTopicMap(); Iterator topics = context.getContextObjects(); if(topics == null || !topics.hasNext()) return; Topic topic = null; String variant = null; Topic displayScope = tm.getTopic(XTMPSI.DISPLAY); Topic sortScope = tm.getTopic(XTMPSI.SORT); Topic langScope = wandora.showTopicFinder("Select language scope topic..."); if(langScope == null) return; Collection<Set<Topic>> scopes = null; Iterator<Set<Topic>> scopeIterator = null; Set<Topic> scope = null; Topic scopeTopic = null; int progress = 0; int count = 0; while(topics.hasNext() && !forceStop()) { try { topic = (Topic) topics.next(); if(topic != null && !topic.isRemoved()) { progress++; topic = tm.getTopic(topic.getOneSubjectIdentifier()); // Change topic to layer stack topic instead of layer topic! scopes = topic.getVariantScopes(); if(scopes != null) { scopeIterator = scopes.iterator(); while(scopeIterator.hasNext() && !forceStop()) { try { scope = (Set<Topic>) scopeIterator.next(); boolean scopeIsComplete = false; for( Iterator<Topic> scopeTopicIterator = scope.iterator(); scopeTopicIterator.hasNext(); ) { scopeTopic = scopeTopicIterator.next(); if(scopeTopic != null) { // If scope contains anything else than display or sort scope then scope is complete! if(!scopeTopic.mergesWithTopic(displayScope) && !scopeTopic.mergesWithTopic(sortScope)) { scopeIsComplete = true; break; } } } if(!scopeIsComplete) { // Incomplete scope... Adding lang scope! variant = topic.getVariant(scope); if(variant != null) { topic.removeVariant(scope); scope.add(langScope); topic.setVariant(scope, variant); count++; } } } catch(Exception e) { log(e); } } } } } catch(Exception e) { log(e); } } log("Found "+count+" variant names without language scope. Added language scope."); log("OK"); setState(WAIT); } catch (Exception e) { log(e); } } }
5,798
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicNameCopier.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/topicnames/TopicNameCopier.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/>. * * * TopicNameCopier.java * * Created on 2. helmikuuta 2007, 16:04 * */ package org.wandora.application.tools.topicnames; import java.util.Collection; import java.util.Iterator; import java.util.Set; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.Topic; import org.wandora.utils.ClipboardBox; /** * * @author akivela */ public class TopicNameCopier extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; /** * Creates a new instance of TopicNameCopier */ public TopicNameCopier() { } public TopicNameCopier(Context preferredContext) { setContext(preferredContext); } @Override public String getName() { return "Variant name copier"; } @Override public String getDescription() { return "Iterates through selected topics and copies ALL variant names to clipboard."; } @Override public void execute(Wandora wandora, Context context) { try { setDefaultLogger(); setLogTitle("Copying variant names of topic"); log("Copying variant names of topic"); Iterator topics = context.getContextObjects(); if(topics == null || !topics.hasNext()) return; Topic topic = null; String variant = null; Collection<Set<Topic>> scopes = null; Iterator<Set<Topic>> scopeIterator = null; Set<Topic> scope = null; int progress = 0; StringBuilder stringBuffer = new StringBuilder(""); StringBuilder logString = null; while(topics.hasNext() && !forceStop()) { try { topic = (Topic) topics.next(); if(topic != null && !topic.isRemoved()) { progress++; stringBuffer.append(topic.getBaseName()); logString = new StringBuilder(""+topic.getBaseName()); scopes = topic.getVariantScopes(); int count = 0; if(scopes != null) { scopeIterator = scopes.iterator(); while(scopeIterator.hasNext()) { try { scope = (Set<Topic>) scopeIterator.next(); variant = topic.getVariant(scope); if(variant != null) { count++; stringBuffer.append("\n\t").append(variant); logString.append("\n\t").append(variant); Iterator<Topic> scopeIter = scope.iterator(); Topic scopeTopic = null; while(scopeIter.hasNext()) { scopeTopic = scopeIter.next(); try { stringBuffer.append("\n\t\t").append(scopeTopic.getOneSubjectIdentifier().toExternalForm()); logString.append("\n\t\t").append(scopeTopic.getOneSubjectIdentifier().toExternalForm()); } catch(Exception e) { log(e); } } stringBuffer.append("\n"); logString.append("\n"); } } catch(Exception e) { log(e); } } } if(count == 0) { stringBuffer.append("\n\t[NO VARIANTS]"); logString.append("\n\t[NO VARIANTS]"); } } stringBuffer.append("\n"); log(logString.toString()); } catch(Exception e) { log(e); } } ClipboardBox.setClipboard(stringBuffer.toString()); log("OK"); setState(WAIT); } catch (Exception e) { log(e); } } @Override public boolean requiresRefresh() { return false; } }
5,716
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
VariantsToTopicsAndAssociations.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/topicnames/VariantsToTopicsAndAssociations.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.topicnames; 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.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; import org.wandora.topicmap.TopicTools; import org.wandora.utils.Tuples.T2; /** * A tool inspired by Patrick Durusau. * * @author akivela */ public class VariantsToTopicsAndAssociations extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; public VariantsToTopicsAndAssociations() { } public VariantsToTopicsAndAssociations(Context preferredContext) { setContext(preferredContext); } @Override public String getName() { return "Transform variants to topics and associations"; } @Override public String getDescription() { return "Transforms variants to topics and associates variant topic with the variant carrier. "+ "Variant scope is also added to the association as third player."; } public void execute(Wandora wandora, Context context) { try { GenericOptionsDialog god=new GenericOptionsDialog(wandora,"Transform variants to topics and associations","Transform variants to topics and associations",true,new String[][]{ new String[]{"Association type topic","topic","","What kind of associations you wish to create."}, new String[]{"Variant role topic","topic","","Role topic of player topics created out of actual variant names."}, new String[]{"Scope role topic","topic","", "Role of variant name scope topics."}, new String[]{"Original role topic","topic","", "Role of the original topic carrying the variant name"}, new String[]{"Delete variant names","boolean","true"}, },wandora); god.setVisible(true); if(god.wasCancelled()) return; Map<String,String> values=god.getValues(); setDefaultLogger(); setLogTitle("Transform variants to topcs and associations"); log("Transforming variants to topcs and associations"); Iterator topics = context.getContextObjects(); if(topics == null || !topics.hasNext()) return; TopicMap tm = wandora.getTopicMap(); Topic associationType = tm.getTopic( values.get("Association type topic") ); Topic variantRole = tm.getTopic( values.get("Variant role topic") ); Topic scopeRole = tm.getTopic( values.get("Scope role topic") ); Topic originalRole = tm.getTopic( values.get("Original role topic") ); boolean deleteVariants = Boolean.parseBoolean(values.get("Delete variant names")); if(associationType == null) log("Association type topic has not been specified. Aborting."); if(variantRole == null) log("Variant role topic has not been specified. Aborting."); if(scopeRole == null) log("Scope role topic has not been specified. Aborting."); if(originalRole == null) log("Original role topic has not been specified. Aborting."); if(associationType != null && variantRole != null && scopeRole != null && originalRole != null) { int progress = 0; int associationCount = 0; List<T2<Topic,Set<Topic>>> deleteScopes = new ArrayList<>(); while(topics.hasNext() && !forceStop()) { try { Topic topic = (Topic) topics.next(); if(topic != null && !topic.isRemoved()) { progress++; Collection<Set<Topic>> scopes = topic.getVariantScopes(); if(scopes != null) { Iterator<Set<Topic>> scopeIterator = scopes.iterator(); while(scopeIterator.hasNext()) { try { Set<Topic> scope = (Set<Topic>) scopeIterator.next(); String variant = topic.getVariant(scope); if(variant != null) { for(Topic scopeTopic : scope) { log("Transforming variant '"+variant+"' to topics and associations" ); try { Topic variantTopic = tm.getTopicWithBaseName(variant); if(variantTopic == null) { variantTopic = tm.createTopic(); variantTopic.addSubjectIdentifier(TopicTools.createDefaultLocator()); variantTopic.setBaseName(variant); } Association a = tm.createAssociation(associationType); a.addPlayer(variantTopic, variantRole); a.addPlayer(scopeTopic, scopeRole); a.addPlayer(topic, originalRole); associationCount++; } catch(Exception e) { e.printStackTrace(); log(e); } } if(deleteVariants) { deleteScopes.add(new T2<Topic,Set<Topic>>(topic, scope)); } } } catch(Exception e) { e.printStackTrace(); log(e); } } } } } catch(Exception e) { log(e); } } if(deleteScopes != null && !deleteScopes.isEmpty()) { log("Deleting original variant names..."); for(T2<Topic,Set<Topic>> deleteScope : deleteScopes) { try { deleteScope.e1.removeVariant(deleteScope.e2); } catch(Exception e) { e.printStackTrace(); } } log("Ready."); } log("Total "+associationCount+" associations created out of given variants."); } setState(WAIT); } catch (Exception e) { log(e); } } }
8,473
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DeleteVariantName.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/topicnames/DeleteVariantName.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.topicnames; import java.util.Set; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.Topic; /** * * @author akivela */ public class DeleteVariantName extends AbstractWandoraTool { private static final long serialVersionUID = 1L; private Topic t = null; private Set<Topic> scope = null; public DeleteVariantName(Topic variantCarrier, Set<Topic> variantScope) { t = variantCarrier; scope = variantScope; } @Override public String getName() { return "Delete single variant name of given topic"; } @Override public String getDescription() { return "Deletes single variant name of a topic and a scope specified in constructor."; } public void execute(Wandora wandora, Context context) { try { if(t != null && !t.isRemoved()) { if(scope != null) { t.removeVariant(scope); } } } catch(Exception e) { e.printStackTrace(); } } }
2,000
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AddVariantName.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/topicnames/AddVariantName.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.topicnames; import java.util.Iterator; import java.util.Set; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.gui.VariantNameEditor; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.Topic; /** * * @author akivela */ public class AddVariantName extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; public AddVariantName() { } public AddVariantName(Context preferredContext) { setContext(preferredContext); } @Override public String getName() { return "Add variant name"; } @Override public String getDescription() { return "Add variant name to selected topics."; } @Override public void execute(Wandora wandora, Context context) { try { Iterator topics = context.getContextObjects(); if(topics == null || !topics.hasNext()) return; VariantNameEditor editor = new VariantNameEditor(wandora); editor.openEditor("Add variant name"); if(editor.wasAccepted()) { String variantString = editor.getVariantString(); Set<Topic> variantScope = editor.getVariantScope(); Topic topic = null; while(topics.hasNext() && !forceStop()) { try { topic = (Topic) topics.next(); if(topic != null && !topic.isRemoved()) { topic.setVariant(variantScope, variantString); } } catch(Exception e) { e.printStackTrace(); } } } } catch (Exception e) { log(e); } } }
2,775
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
VariantRegexReplacer.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/topicnames/VariantRegexReplacer.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/>. * * * VariantRegexReplacer.java * * Created on 22. toukokuuta 2006, 14:31 * */ package org.wandora.application.tools.topicnames; import java.util.Collection; import java.util.Iterator; import java.util.Set; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.contexts.TopicContext; import org.wandora.application.gui.RegularExpressionEditor; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.Topic; /** * <code>VariantRegexReplacer</code> implements tool modifying topic's * variant names with given regular expression. Regular expression is * applied to every variant name available in the topic. Regular expression * can be used to carry out complex name replace operations for example. * * @author akivela */ public class VariantRegexReplacer extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; RegularExpressionEditor editor = null; /** Creates a new instance of VariantRegexReplacer */ public VariantRegexReplacer() { setContext(new TopicContext()); } public VariantRegexReplacer(Context preferredContext) { setContext(preferredContext); } @Override public String getName() { return "Variant regular expression replacer"; } @Override public String getDescription() { return "Iterates through selected topics and applies given regular expression to variant names."; } public void execute(Wandora wandora, Context context) { Iterator topics = context.getContextObjects(); if(topics == null || !topics.hasNext()) return; try { editor = RegularExpressionEditor.getReplaceExpressionEditor(wandora); editor.approve = false; editor.setVisible(true); if(editor.approve == true) { setDefaultLogger(); log("Transforming variant names with regular expression."); Topic topic = null; String variant = null; String newVariant = null; Collection<Set<Topic>> scopes = null; Iterator<Set<Topic>> scopeIterator = null; Set<Topic> scope = null; int progress = 0; int count = 0; while(topics.hasNext() && !forceStop()) { try { topic = (Topic) topics.next(); if(topic != null && !topic.isRemoved()) { progress++; scopes = topic.getVariantScopes(); if(scopes != null) { scopeIterator = scopes.iterator(); while(scopeIterator.hasNext()) { try { scope = (Set<Topic>) scopeIterator.next(); variant = topic.getVariant(scope); if(variant != null) { hlog("Investigating variant '" + variant + "'."); newVariant = editor.replace(variant); if(newVariant != null && !variant.equalsIgnoreCase(newVariant)) { log("Regex matches! New variant name is '"+newVariant + "'." ); topic.setVariant(scope, newVariant); count++; } } } catch(Exception e) { log(e); } } } } } catch(Exception e) { log(e); } } log("Total "+count+" variant names changed!"); } } catch (Exception e) { log(e); } setState(WAIT); } }
5,212
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AddScopeTopicToVariantName.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/topicnames/AddScopeTopicToVariantName.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.topicnames; import java.util.LinkedHashSet; import java.util.Set; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.Topic; /** * * @author akivela */ public class AddScopeTopicToVariantName extends AbstractWandoraTool { private static final long serialVersionUID = 1L; private Topic t = null; private Set<Topic> scope = null; private Topic predefinedScopeTopic = null; public AddScopeTopicToVariantName(Topic variantCarrier, Set<Topic> variantScope, Topic st) { t = variantCarrier; scope = variantScope; predefinedScopeTopic = st; } public AddScopeTopicToVariantName(Topic variantCarrier, Set<Topic> variantScope) { t = variantCarrier; scope = variantScope; } @Override public String getName() { return "Add scope topic to variant name"; } @Override public String getDescription() { return "Add scope topic to variant name of a topic and a scope specified in constructor."; } @Override public void execute(Wandora wandora, Context context) { try { Topic scopeTopic = null; if(predefinedScopeTopic == null) { scopeTopic = wandora.showTopicFinder(wandora, "Select scope topic"); } else { scopeTopic = predefinedScopeTopic; } if(t != null && !t.isRemoved() && scopeTopic != null) { if(scope != null) { String n = t.getVariant(scope); if(n != null) { t.removeVariant(scope); Set<Topic> newScope = new LinkedHashSet<Topic>(); newScope.addAll(scope); newScope.add(scopeTopic); t.setVariant(newScope, n); } } } } catch(Exception e) { e.printStackTrace(); } } }
2,924
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MakeSortVariantsFromBasename.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/topicnames/MakeSortVariantsFromBasename.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/>. * * * MakeDisplayVariantsWithBasename.java * * Created on 22. toukokuuta 2006, 14:55 * */ package org.wandora.application.tools.topicnames; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.XTMPSI; /** * <code>MakeDisplayVariantsWithBasename</code> copies topics base name to * topic's variant names. If topic already contain variant name, boolean * variable <code>overWrite</code> defines if the existing variant name * is over written. Tool solves available variant name scopes and types using * <code>WandoraAdminManager</code>. Only names with available scopes and types * are set. * * * @author akivela */ public class MakeSortVariantsFromBasename extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; boolean overWrite = false; /** * Creates a new instance of MakeSortVariantsWithBasename */ public MakeSortVariantsFromBasename() { } public MakeSortVariantsFromBasename(Context preferredContext) { setContext(preferredContext); } @Override public String getName() { return "Makes sort variant names using topic's base name."; } @Override public String getDescription() { return "Iterates through selected topics and copies topic's base name to variant names."; } public void execute(Wandora wandora, Context context) { try { setDefaultLogger(); setLogTitle("Copying base name to topic variant names"); log("Copying base name to topic variant names"); Iterator topics = context.getContextObjects(); if(topics == null || !topics.hasNext()) return; Topic topic = null; String basename = null; String variant = null; Iterator<Topic> languageIterator = null; Topic language = null; Set<Topic> scope = null; Collection<Topic> languages = wandora.getTopicMap().getTopicsOfType(TMBox.LANGUAGE_SI); Topic displayScope = wandora.getTopicMap().getTopic(XTMPSI.SORT); int progress = 0; while(topics.hasNext() && !forceStop()) { try { topic = (Topic) topics.next(); if(topic != null && !topic.isRemoved()) { setProgress(progress++); basename = topic.getBaseName(); if(languages != null) { languageIterator = languages.iterator(); while(languageIterator.hasNext()) { try { language = (Topic) languageIterator.next(); scope = new LinkedHashSet<>(); scope.add(language); scope.add(displayScope); variant = topic.getVariant(scope); if(variant == null || overWrite) { topic.setVariant(scope, basename); } } catch(Exception e) { log(e); } } } } } catch(Exception e) { log(e); } } log("Ready."); setState(WAIT); } catch (Exception e) { log(e); } } }
4,859
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
VariantScopeCopier.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/topicnames/VariantScopeCopier.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/>. * * * VariantScopeCopier.java * * Created on 2008-07-16, 17:04 * */ package org.wandora.application.tools.topicnames; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.application.tools.GenericOptionsDialog; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; /** * Implements <code>WandoraAdminTool</code> that copies or removes variant names * to other scope. * * @author akivela */ public class VariantScopeCopier extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; private boolean REMOVE_AFTER_COPY = false; private boolean COPY_NULLS = false; private boolean OVERWRITE_OLDIES = true; /** * Creates a new instance of VariantScopeCopier */ public VariantScopeCopier() { REMOVE_AFTER_COPY = false; } public VariantScopeCopier(Context preferredContext) { REMOVE_AFTER_COPY = false; setContext(preferredContext); } public VariantScopeCopier(boolean removeAfterCopy) { REMOVE_AFTER_COPY = false; } public VariantScopeCopier(boolean removeAfterCopy, Context preferredContext) { REMOVE_AFTER_COPY = removeAfterCopy; setContext(preferredContext); } @Override public String getName() { return "Variant scope copier"; } @Override public String getDescription() { return "Iterates through selected topics and copies or moves user specified variant names to other scope."; } public void execute(Wandora wandora, Context context) { try { Iterator topics = context.getContextObjects(); if(topics == null || !topics.hasNext()) return; GenericOptionsDialog god=new GenericOptionsDialog(wandora, ( REMOVE_AFTER_COPY ? "Move variant name to other type and scope" : "Copy variant name to other type and scope" ), "To change variant name types and scopes please address source and target types and scopes.",true,new String[][]{ new String[]{"Type of source variants","topic","","Variant name type of changed names (display name for example)"}, new String[]{"Scope of source variants","topic","","Variant name scope i.e. language of changed names (English for example)"}, new String[]{"Type of target variants","topic","","Variant name type of new names (display name for example)"}, new String[]{"Scope of target variants","topic","","Variant name scope i.e. language of new names (English for example)"}, new String[]{"Overwrite existing names?","boolean","false","Save existing target names?"}, new String[]{"Copy also null names?","boolean","false","Set target variant although source variant is null?"}, },wandora); god.setVisible(true); if(god.wasCancelled()) return; Map<String,String> values=god.getValues(); COPY_NULLS = "true".equals( values.get("Copy also null names?") ) ? true : false; OVERWRITE_OLDIES = "true".equals( values.get("Overwrite existing names?") ) ? true : false; Topic sourceTypeTopic = null; Topic sourceScopeTopic = null; Topic targetTypeTopic = null; Topic targetScopeTopic = null; TopicMap tm = null; Set<Topic> sourceScope = null; Set<Topic> targetScope = null; setDefaultLogger(); if( REMOVE_AFTER_COPY ) { setLogTitle("Moving variant names to other scope"); } else { setLogTitle("Copying variant names to other scope"); } if( OVERWRITE_OLDIES ) log("Overwriting existing names."); if( COPY_NULLS ) log("Copying also null names."); int progress = 0; int processed = 0; Topic topic = null; String variant = ""; String targetVariant = null; while(topics.hasNext() && !forceStop()) { try { topic = (Topic) topics.next(); if(topic != null && !topic.isRemoved()) { tm = topic.getTopicMap(); try { sourceTypeTopic = null; sourceScopeTopic = null; targetTypeTopic = null; targetScopeTopic = null; sourceTypeTopic = tm.getTopic(values.get("Type of source variants")); sourceScopeTopic = tm.getTopic(values.get("Scope of source variants")); targetTypeTopic = tm.getTopic(values.get("Type of target variants")); targetScopeTopic = tm.getTopic(values.get("Scope of target variants")); } catch(Exception e) { } if(sourceTypeTopic != null && sourceScopeTopic != null && targetTypeTopic != null && targetScopeTopic != null) { sourceScope = new HashSet<Topic>(); sourceScope.add(sourceScopeTopic); sourceScope.add(sourceTypeTopic); targetScope = new HashSet<Topic>(); targetScope.add(targetScopeTopic); targetScope.add(targetTypeTopic); progress++; variant = topic.getVariant(sourceScope); targetVariant = topic.getVariant(targetScope); Set<Set<Topic>> scopes = topic.getVariantScopes(); // System.out.println("scopes "+scopes); // System.out.println("scopes size "+scopes.size()); // System.out.println("Processing "+getTopicName(topic)+" with variant "+variant); if(variant != null) { if(REMOVE_AFTER_COPY) topic.setVariant(sourceScope, null); if(targetVariant == null || OVERWRITE_OLDIES) { topic.setVariant(targetScope, variant); processed++; } } else { if(COPY_NULLS) { if(targetVariant == null || OVERWRITE_OLDIES) { topic.setVariant(targetScope, null); processed++; } } } } else { if(sourceTypeTopic == null) log("Can't find source type for "+getTopicName(topic)+". Skipping topic."); else if(sourceScopeTopic == null) log("Can't find source scope for "+getTopicName(topic)+". Skipping topic."); else if(targetTypeTopic == null) log("Can't find target type for "+getTopicName(topic)+". Skipping topic."); else if(targetScopeTopic == null) log("Can't find target scope for "+getTopicName(topic)+". Skipping topic."); } } } catch(Exception e) { log(e); } } log("Processed total " + processed + " variant names."); setState(WAIT); } catch (Exception e) { log(e); } } }
8,903
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
BasenameRemover.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/topicnames/BasenameRemover.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/>. * * * BasenameRemover.java * * Created on 25. toukokuuta 2006, 11:17 * */ package org.wandora.application.tools.topicnames; 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.Topic; /** * Although Wandora relies that a topic has a basename and it is not * encouraged to create a topic without a basename, it may sometimes be * necessary to remove topic's basename. Removing may be useful for example * if the basename is later filled with subject identifier or occurrence string. * This class implements a tool used to remove basenames of context topics. * * @author akivela */ public class BasenameRemover extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; public BasenameRemover() { } public BasenameRemover(Context preferredContext) { setContext(preferredContext); } @Override public String getName() { return "Topic base name remover"; } @Override public String getDescription() { return "Iterates through selected topics and removes all base names."; } @Override public void execute(Wandora wandora, Context context) { try { Iterator topics = context.getContextObjects(); if(topics == null || !topics.hasNext()) return; if(WandoraOptionPane.showConfirmDialog(wandora, "Are you sure you want to remove all base names of selected topics?","Confirm base name remove", WandoraOptionPane.YES_NO_OPTION)==WandoraOptionPane.YES_OPTION){ setDefaultLogger(); setLogTitle("Removing all base names"); log("Removing all base names"); Topic topic = null; int progress = 0; while(topics.hasNext() && !forceStop()) { try { topic = (Topic) topics.next(); if(topic != null && !topic.isRemoved()) { progress++; topic.setBaseName(null); } } catch(Exception e) { log(e); } } log("Ready."); setState(WAIT); } } catch (Exception e) { log(e); } } }
3,440
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
BasenameRegexReplacer.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/topicnames/BasenameRegexReplacer.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/>. * * * BasenameRegexReplacer.java * * Created on 19. toukokuuta 2006, 12:51 */ package org.wandora.application.tools.topicnames; import java.util.ArrayList; import java.util.HashMap; 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.RegularExpressionEditor; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.Topic; /** * This is a WandoraAdminTool used to modify context topic base names with * a given regular expression. Used regular expression is given with the * <code>RegularExpressionEditor</code>. * * * @author akivela */ public class BasenameRegexReplacer extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; RegularExpressionEditor editor = null; public BasenameRegexReplacer() { } public BasenameRegexReplacer(Context preferredContext) { setContext(preferredContext); } @Override public String getName() { return "Base name regular expression replacer"; } @Override public String getDescription() { return "Iterates through selected topics and applies given regular expression to base names."; } public void execute(Wandora wandora, Context context) { Iterator topics = context.getContextObjects(); if(topics == null || !topics.hasNext()) return; try { editor = RegularExpressionEditor.getReplaceExpressionEditor(wandora); editor.approve = false; editor.setVisible(true); if(editor.approve == true) { setDefaultLogger(); setLogTitle("Base name regex replacer"); log("Transforming base names with regular expression."); Topic topic = null; String basename = null; String newBasename = null; int progress = 0; int count = 0; HashMap<Topic,String> changeTopics = new HashMap<Topic,String>(); while(topics.hasNext() && !forceStop()) { try { topic = (Topic) topics.next(); if(topic != null && !topic.isRemoved()) { basename = topic.getBaseName(); if(basename != null) { progress++; hlog("Investigating base name '" + basename + "'."); newBasename = editor.replace(basename); if(newBasename != null && !basename.equalsIgnoreCase(newBasename)) { changeTopics.put(topic, newBasename); log("Regex matches! New base name is '"+newBasename +"'."); } } } } catch(Exception e) { log(e); } } List<Topic> changeList = new ArrayList<>(); changeList.addAll(changeTopics.keySet()); for(Topic t : changeList) { if(forceStop()) break; newBasename = changeTopics.get(t); t.setBaseName(newBasename); count++; } log("Total "+count+" base names changed!"); } } catch (Exception e) { log(e); } setState(WAIT); } }
4,570
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MakeDisplayVariantsFromOccurrences.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/topicnames/MakeDisplayVariantsFromOccurrences.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.topicnames; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.XTMPSI; /** * * @author akivela */ public class MakeDisplayVariantsFromOccurrences extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; boolean overWrite = false; /** * Creates a new instance of MakeDisplayVariantsWithOccurrences */ public MakeDisplayVariantsFromOccurrences() { } public MakeDisplayVariantsFromOccurrences(Context preferredContext) { setContext(preferredContext); } @Override public String getName() { return "Make display variants with occurrences"; } @Override public String getDescription() { return "Iterates through selected topics and copies occurrence datas to variant names."; } public void execute(Wandora wandora, Context context) { try { Iterator topics = context.getContextObjects(); if(topics == null || !topics.hasNext()) return; Topic topic = null; String occurrence = null; String variant = null; Iterator<Topic> languageIterator = null; Topic language = null; Set<Topic> scope = null; Collection<Topic> languages = wandora.getTopicMap().getTopicsOfType(TMBox.LANGUAGE_SI); Topic displayScope = wandora.getTopicMap().getTopic(XTMPSI.DISPLAY); int progress = 0; Topic type = null; if(topics.hasNext()) { type = wandora.showTopicFinder("Select occurrence type..."); } if(type == null) return; setDefaultLogger(); setLogTitle("Copying occurrences to variant names"); log("Copying occurrences to variant names"); while(topics.hasNext() && !forceStop()) { try { topic = (Topic) topics.next(); if(topic != null && !topic.isRemoved()) { setProgress(progress++); if(languages != null) { languageIterator = languages.iterator(); while(languageIterator.hasNext()) { try { language = (Topic) languageIterator.next(); occurrence = topic.getData(type, language); if(occurrence != null) { occurrence = occurrence.replace("\n", " "); scope = new LinkedHashSet<>(); scope.add(language); scope.add(displayScope); variant = topic.getVariant(scope); if(variant == null || overWrite) { topic.setVariant(scope, occurrence); } } } catch(Exception e) { log(e); } } } } } catch(Exception e) { log(e); } } setState(WAIT); } catch (Exception e) { log(e); } } }
4,804
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
PingerWorker.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/iot/PingerWorker.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.iot; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.Iterator; import org.apache.commons.io.IOUtils; import org.wandora.application.Wandora; import org.wandora.application.tools.extractors.ExtractHelper; import org.wandora.application.tools.iot.PingerPanel.Logger; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.XTMPSI; import org.wandora.utils.DataURL; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.http.exceptions.UnirestException; /** * * @author Eero Lehtonen */ class PingerWorker { private static final DateFormat df = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss"); static void run(Topic targetType, Topic sourceType, TopicMap tm, Logger logger, boolean isBinary, File saveFolder){ run(targetType, sourceType, tm, logger, isBinary); String fileName = "iot_" + df.format(new Date()) + ".jtm"; try { tm.exportJTM(saveFolder.getAbsolutePath() + File.separator + fileName); } catch (IOException | TopicMapException e) { logger.log(e); } } static void run(Topic targetType, Topic sourceType, TopicMap tm, Logger logger, boolean isBinary) { logger.log("Initiating run"); Collection<Topic> validTopics; Collection<Topic> languageTopics; Unirest.clearDefaultHeaders(); Unirest.setDefaultHeader("User-Agent", Wandora.USER_AGENT); try { languageTopics = getLanguageTopics(tm); validTopics = getValidTopics(tm, sourceType); } catch (Exception e) { logger.log(e); return; } int successCount = 0; for(Topic t : validTopics) { for(Topic lang : languageTopics) { try { boolean success = handleTopic(t, targetType, sourceType, lang, isBinary); if(success) successCount++; } catch (TopicMapException | UnirestException | IOException e) { logger.log(e); } } } if(successCount == 0) { logger.log("Found no occurrence urls. Done nothing."); } else if(successCount == 1) { logger.log("Found and processed one occurrence url."); } else { logger.log("Found and processed "+successCount+" occurrence urls."); } } private static boolean handleTopic(Topic t, Topic targetType, Topic sourceType, Topic lang, boolean isBinary) throws TopicMapException, UnirestException, IOException { boolean success = false; String url = t.getData(sourceType, lang); if(url != null) { // Check if URL matches any virtual sources SourceMapping sourceMapping = SourceMapping.getInstance(); IoTSource iotSource = sourceMapping.match(url); if(iotSource != null) { String data = iotSource.getData(url); t.setData(targetType, lang, data); success = true; } else if(isBinary) { // Fallback: check if we're fetching binary data HttpResponse<InputStream> response = Unirest.get(url).asBinary(); InputStream stream = response.getBody(); String contentType = response.getHeaders().getFirst("content-type"); byte[] data = IOUtils.toByteArray(stream); DataURL durl = new DataURL(contentType, data); t.setData(targetType, lang, durl.toExternalForm()); success = true; } else { // Fallback: fetch as String HttpResponse<String> response = Unirest.get(url).asString(); String data = response.getBody(); t.setData(targetType, lang, data); success = true; } } return success; } private static Collection<Topic> getValidTopics(TopicMap tm, Topic sourceType) throws TopicMapException { Iterator<Topic> topics = tm.getTopics(); Collection<Topic> validTopics = new ArrayList<>(); while(topics.hasNext()){ Topic t = topics.next(); if(t.getDataTypes().contains(sourceType)){ validTopics.add(t); } } return validTopics; } private static Collection<Topic> getLanguageTopics(TopicMap tm) throws TopicMapException { Collection<Topic> languageTopics = tm.getTopicsOfType(XTMPSI.LANGUAGE); if(languageTopics == null) { languageTopics = new ArrayList<>(); } if(languageTopics.isEmpty()) { Topic lang = ExtractHelper.getOrCreateTopic(TMBox.LANGINDEPENDENT_SI, tm); languageTopics.add(lang); } return languageTopics; } }
6,175
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TimeSource.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/iot/TimeSource.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.iot; import java.net.MalformedURLException; import java.net.URL; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Map; /** * * @author Eero Lehtonen */ class TimeSource extends AbstractIoTSource implements IoTSource { private static final String HOST = "wandora.org"; private static final String PATH = "/si/iot/source/time"; @Override public String getData(String url) { Map<String,String> params; try { URL u = new URL(url); params = parseParams(u); if(params != null && params.containsKey("format")) { String formatString = params.get("format"); DateFormat format = new SimpleDateFormat(formatString); Date date = new Date(); return format.format(date); } } catch (Exception ex) { ex.printStackTrace(); } return Long.toString(System.currentTimeMillis()); // Default } @Override public boolean matches(String url) throws MalformedURLException{ URL u = new URL(url); return u.getHost().equals(HOST) && u.getPath().equals(PATH); } }
2,124
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
PingerPanel.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/iot/PingerPanel.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.iot; import java.awt.Dimension; import java.io.File; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Timer; import java.util.TimerTask; import javax.swing.InputVerifier; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JFormattedTextField; import javax.swing.JOptionPane; import javax.swing.JTextField; import org.wandora.application.Wandora; import org.wandora.application.gui.GetTopicButton; import org.wandora.application.gui.simple.SimpleButton; import org.wandora.application.gui.simple.SimpleCheckBox; import org.wandora.application.gui.simple.SimpleLabel; import org.wandora.application.gui.simple.SimplePanel; import org.wandora.application.gui.simple.SimpleScrollPane; import org.wandora.application.gui.simple.SimpleTabbedPane; import org.wandora.application.gui.simple.SimpleTextArea; import org.wandora.application.gui.simple.SimpleToggleButton; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; /** * * @author Eero Lehtonen */ public class PingerPanel extends javax.swing.JPanel { private static final long serialVersionUID = 1L; private static final String PANEL_TITLE = "IoT pinger"; private GetTopicButton maybeTargetButton; private GetTopicButton maybeSourceButton; private boolean expires; private boolean isRunning; private int delay; private TimerTask task; private static final DateFormat df = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss Z"); private File saveFolder = null; private TopicMap tm; /** * Creates new form PingerPanel * @param tm */ public PingerPanel(TopicMap tm) { this.tm = tm; isRunning = false; try { maybeTargetButton = new GetTopicButton(); maybeSourceButton = new GetTopicButton(); } catch (Exception e) { return; } initComponents(); InputVerifier verifier = new InputVerifier(){ @Override public boolean verify(JComponent input) { JFormattedTextField tf = (JFormattedTextField)input; int v = Integer.parseInt(tf.getText()); return v >= 0; } }; yearField.setInputVerifier(verifier); monthField.setInputVerifier(verifier); dayField.setInputVerifier(verifier); hoursField.setInputVerifier(verifier); minutesField.setInputVerifier(verifier); secondsField.setInputVerifier(verifier); delayField.setInputVerifier(verifier); toggleExpirationFieldEnabled(); setSetupEnabled(isRunning); } protected void openInOwnWindow(Wandora w) { JDialog dialog = new JDialog(w, false); dialog.add(this); dialog.setSize(600, 380); dialog.setMinimumSize(new Dimension(600, 380)); dialog.setLocationRelativeTo(w); dialog.setVisible(true); dialog.setTitle(PANEL_TITLE); } private void openFileChooser() { JFileChooser chooser = new JFileChooser(); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); chooser.setAcceptAllFileFilterUsed(false); chooser.setDialogTitle("Choose folder for saved data"); if(chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { saveFolder = chooser.getSelectedFile(); saveFolderField.setText(saveFolder.getAbsolutePath()); } else if(saveFolder == null) { // saveFolder is invalid, revert to default saveToggle.setSelected(false); saveButton.setEnabled(false); } } private void toggleExpirationFieldEnabled() { setTimeFieldsEnabled(expires); Calendar c = Calendar.getInstance(); yearField.setValue(c.get(Calendar.YEAR)); monthField.setValue(c.get(Calendar.MONTH)+1); dayField.setValue(c.get(Calendar.DAY_OF_MONTH)); hoursField.setValue(c.get(Calendar.HOUR_OF_DAY)+1); minutesField.setValue(c.get(Calendar.MINUTE)); secondsField.setValue(c.get(Calendar.SECOND)); } private void setTimeFieldsEnabled(boolean enabled){ yearField.setEnabled(enabled); monthField.setEnabled(enabled); dayField.setEnabled(enabled); hoursField.setEnabled(enabled); minutesField.setEnabled(enabled); secondsField.setEnabled(enabled); } private void setSetupEnabled(boolean running) { boolean saveOnTick = saveToggle.isSelected(); targetButton.setEnabled(!running); sourceButton.setEnabled(!running); delayField.setEnabled(!running); sourceIsBinaryButton.setEnabled(!running); expiryToggle.setEnabled(!running); saveToggle.setEnabled(!running); saveFolderField.setEnabled(saveOnTick && !running); saveButton.setEnabled(saveOnTick && !running); setTimeFieldsEnabled(expires && !running); } /** * Logging helper passed to PingerWorker */ protected interface Logger { void log(Exception e); void log(String s); } private Logger logger = new Logger() { @Override public void log(Exception e) { this.log(e.getMessage()); } @Override public void log(String s) { logArea.append("[" + df.format(new Date()) + "] " + s + "\n"); try { logArea.setCaretPosition(logArea.getLineStartOffset(logArea.getLineCount() - 1)); } catch(Exception e) { // IGNORE } } }; private long getExpiry() { Calendar expCal = Calendar.getInstance(); try { int year = getIntegerFieldValue(yearField, expCal.get(Calendar.YEAR)); int month = getIntegerFieldValue(monthField, expCal.get(Calendar.MONTH)); int day = getIntegerFieldValue(dayField, expCal.get(Calendar.DAY_OF_MONTH)); int hours = getIntegerFieldValue(hoursField, expCal.get(Calendar.HOUR)); int minutes = getIntegerFieldValue(minutesField, expCal.get(Calendar.MINUTE)); int seconds = getIntegerFieldValue(secondsField, expCal.get(Calendar.SECOND)); expCal.set( year, month-1, day, hours, minutes, seconds ); } catch(Exception e) { e.printStackTrace(); } return expCal.getTimeInMillis(); } private int getIntegerFieldValue(JTextField field, int defaultValue) { if(field != null) { String text = field.getText(); if(text != null && text.length() > 0) { try { int integerValue = Integer.parseInt(text); return integerValue; } catch(Exception e) { // IGNORE } } } return defaultValue; } private boolean start() { final Topic targetType = ((GetTopicButton)targetButton).getTopic(); final Topic sourceType = ((GetTopicButton)sourceButton).getTopic(); if(targetType == null || sourceType == null){ JOptionPane.showMessageDialog(this, "Target or Source type not set."); return false; } final boolean isBinary = sourceIsBinaryButton.isSelected(); final long expiry = (expires) ? getExpiry() : Long.MAX_VALUE; if(saveToggle.isSelected() && saveFolder == null) { openFileChooser(); if(saveFolder == null) { JOptionPane.showMessageDialog(this, "Save folder not set. "); return false; } } delay = ((Number)delayField.getValue()).intValue(); Timer timer = new Timer(); task = new TimerTask() { @Override public void run() { if(expires && expiry < System.currentTimeMillis()){ logger.log("Stopping due to expiry"); stop(); return; } if(expires) { long tillExpiry = (expiry - System.currentTimeMillis()) / 1000; startStopButton.setText("Running, stops automatically in "+tillExpiry+" seconds. Press to force stop."); } else { startStopButton.setText("Running, press to stop"); } statusField.setText("Running"); try { if(saveToggle.isSelected()){ PingerWorker.run(targetType, sourceType, tm, logger, isBinary, saveFolder); } else { PingerWorker.run(targetType, sourceType, tm, logger, isBinary); } } catch (Exception e) { logger.log(e); } } }; logger.log("Starting pinger"); isRunning = true; setSetupEnabled(isRunning); timer.schedule(task, 0, Math.max(5000, delay*1000)); return true; } private void stop() { if(task != null) { logger.log("Stopping pinger"); task.cancel(); } startStopButton.setText("Start"); startStopButton.setSelected(false); statusField.setText("Stopped"); setupPane.setEnabled(true); isRunning = false; setSetupEnabled(isRunning); } /** * 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; statusField = new javax.swing.JTextField(); tabs = new SimpleTabbedPane(); Setupcontainer = new SimplePanel(); setupPane = new SimplePanel(); description = new SimpleTextArea(); targetLabel = new SimpleLabel(); targetButton = maybeTargetButton; sourceLabel = new SimpleLabel(); sourceButton = maybeSourceButton; sourceIsBinaryButton = new SimpleCheckBox(); delayLabel = new SimpleLabel(); delayField = new javax.swing.JFormattedTextField(); secondLabel = new SimpleLabel(); expiresLabel = new SimpleLabel(); expiryToggle = new SimpleCheckBox(); yearLabel = new SimpleLabel(); yearField = new javax.swing.JFormattedTextField(); monthLabel = new SimpleLabel(); monthField = new javax.swing.JFormattedTextField(); dayLabel = new SimpleLabel(); dayField = new javax.swing.JFormattedTextField(); hoursLabel = new SimpleLabel(); hoursField = new javax.swing.JFormattedTextField(); minutesLabel = new SimpleLabel(); minutesField = new javax.swing.JFormattedTextField(); secondsLabel = new SimpleLabel(); secondsField = new javax.swing.JFormattedTextField(); saveLabel = new SimpleLabel(); saveToggle = new SimpleCheckBox(); saveFolderField = new javax.swing.JTextField(); saveButton = new SimpleButton(); logPane = new SimplePanel(); logScroll = new SimpleScrollPane(); logArea = new SimpleTextArea(); startStopButton = new SimpleToggleButton(); statusField.setEditable(false); statusField.setText("Stopped"); statusField.setBorder(null); statusField.setOpaque(false); setMinimumSize(new java.awt.Dimension(520, 300)); setPreferredSize(new java.awt.Dimension(520, 300)); setLayout(new java.awt.GridBagLayout()); Setupcontainer.setLayout(new java.awt.GridBagLayout()); setupPane.setMaximumSize(new java.awt.Dimension(520, 300)); setupPane.setMinimumSize(new java.awt.Dimension(520, 300)); setupPane.setPreferredSize(new java.awt.Dimension(520, 300)); setupPane.setLayout(new java.awt.GridBagLayout()); description.setEditable(false); description.setColumns(20); description.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N description.setLineWrap(true); description.setRows(4); description.setText("The IoT pinger facilitates fetching data from an abritrary HTTP endpoint and storing it as an occurrence of a topic. The pinger looks for an source occurrence in each topic for the endpoint and stores the fetched response as a target occurrence of the corresponding topic. The process is repeated according to the delay parameter.\n"); description.setWrapStyleWord(true); description.setOpaque(false); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 8; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.PAGE_START; gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 4); setupPane.add(description, gridBagConstraints); targetLabel.setText("Target occurrence type"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); setupPane.add(targetLabel, gridBagConstraints); targetButton.setMaximumSize(new java.awt.Dimension(35, 9)); targetButton.setMinimumSize(new java.awt.Dimension(35, 9)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.gridwidth = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(0, 0, 4, 4); setupPane.add(targetButton, gridBagConstraints); sourceLabel.setText("Source occurrence type"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; gridBagConstraints.insets = new java.awt.Insets(0, 3, 4, 4); setupPane.add(sourceLabel, gridBagConstraints); sourceButton.setMaximumSize(new java.awt.Dimension(35, 9)); sourceButton.setMinimumSize(new java.awt.Dimension(35, 9)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(0, 0, 4, 4); setupPane.add(sourceButton, gridBagConstraints); sourceIsBinaryButton.setText("is binary"); sourceIsBinaryButton.setToolTipText("Is the downloaded resource binary data. Check to turn the downloaded resource into a data url."); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.insets = new java.awt.Insets(0, 0, 4, 4); setupPane.add(sourceIsBinaryButton, gridBagConstraints); delayLabel.setText("Delay"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 4); setupPane.add(delayLabel, gridBagConstraints); delayField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0")))); delayField.setHorizontalAlignment(javax.swing.JTextField.CENTER); delayField.setPreferredSize(new java.awt.Dimension(6, 23)); delayField.setValue(Integer.valueOf(10)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(0, 0, 4, 4); setupPane.add(delayField, gridBagConstraints); secondLabel.setText("s"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.insets = new java.awt.Insets(0, 0, 4, 4); setupPane.add(secondLabel, gridBagConstraints); expiresLabel.setText("Expires"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 4); setupPane.add(expiresLabel, gridBagConstraints); expiryToggle.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { expiryToggleActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 5; gridBagConstraints.insets = new java.awt.Insets(0, 0, 4, 4); setupPane.add(expiryToggle, gridBagConstraints); yearLabel.setText("Y"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 4; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4); setupPane.add(yearLabel, gridBagConstraints); yearField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0")))); yearField.setHorizontalAlignment(javax.swing.JTextField.CENTER); yearField.setMinimumSize(new java.awt.Dimension(30, 20)); yearField.setPreferredSize(new java.awt.Dimension(30, 23)); yearField.setValue(Integer.valueOf(5)); yearField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { yearFieldActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 0.1; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4); setupPane.add(yearField, gridBagConstraints); monthLabel.setText("M"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 4; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4); setupPane.add(monthLabel, gridBagConstraints); monthField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0")))); monthField.setHorizontalAlignment(javax.swing.JTextField.CENTER); monthField.setMaximumSize(new java.awt.Dimension(10, 20)); monthField.setMinimumSize(new java.awt.Dimension(10, 20)); monthField.setPreferredSize(new java.awt.Dimension(10, 23)); monthField.setValue(Integer.valueOf(5)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 0.1; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4); setupPane.add(monthField, gridBagConstraints); dayLabel.setText("D"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 4; gridBagConstraints.gridy = 4; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4); setupPane.add(dayLabel, gridBagConstraints); dayField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0")))); dayField.setHorizontalAlignment(javax.swing.JTextField.CENTER); dayField.setMaximumSize(new java.awt.Dimension(10, 20)); dayField.setMinimumSize(new java.awt.Dimension(10, 20)); dayField.setPreferredSize(new java.awt.Dimension(10, 23)); dayField.setValue(Integer.valueOf(5)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 4; gridBagConstraints.gridy = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 0.1; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4); setupPane.add(dayField, gridBagConstraints); hoursLabel.setText("H"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 5; gridBagConstraints.gridy = 4; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4); setupPane.add(hoursLabel, gridBagConstraints); hoursField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0")))); hoursField.setHorizontalAlignment(javax.swing.JTextField.CENTER); hoursField.setMaximumSize(new java.awt.Dimension(10, 20)); hoursField.setMinimumSize(new java.awt.Dimension(10, 20)); hoursField.setPreferredSize(new java.awt.Dimension(10, 23)); hoursField.setValue(Integer.valueOf(5)); hoursField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { hoursFieldActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 5; gridBagConstraints.gridy = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 0.1; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4); setupPane.add(hoursField, gridBagConstraints); minutesLabel.setText("M"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 6; gridBagConstraints.gridy = 4; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4); setupPane.add(minutesLabel, gridBagConstraints); minutesField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0")))); minutesField.setHorizontalAlignment(javax.swing.JTextField.CENTER); minutesField.setMaximumSize(new java.awt.Dimension(10, 20)); minutesField.setMinimumSize(new java.awt.Dimension(10, 20)); minutesField.setPreferredSize(new java.awt.Dimension(10, 23)); minutesField.setValue(Integer.valueOf(5)); minutesField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { minutesFieldActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 6; gridBagConstraints.gridy = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 0.1; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4); setupPane.add(minutesField, gridBagConstraints); secondsLabel.setText("S"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 7; gridBagConstraints.gridy = 4; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4); setupPane.add(secondsLabel, gridBagConstraints); secondsField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0")))); secondsField.setHorizontalAlignment(javax.swing.JTextField.CENTER); secondsField.setMaximumSize(new java.awt.Dimension(10, 20)); secondsField.setMinimumSize(new java.awt.Dimension(10, 20)); secondsField.setPreferredSize(new java.awt.Dimension(10, 23)); secondsField.setValue(Integer.valueOf(5)); secondsField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { secondsFieldActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 7; gridBagConstraints.gridy = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 0.1; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4); setupPane.add(secondsField, gridBagConstraints); saveLabel.setText("Save on tick"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 6; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 4); setupPane.add(saveLabel, gridBagConstraints); saveToggle.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { saveToggleActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 6; gridBagConstraints.insets = new java.awt.Insets(0, 0, 4, 4); setupPane.add(saveToggle, gridBagConstraints); saveFolderField.setEditable(false); saveFolderField.setPreferredSize(new java.awt.Dimension(6, 23)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 6; gridBagConstraints.gridwidth = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(0, 0, 4, 4); setupPane.add(saveFolderField, gridBagConstraints); saveButton.setText("Browse"); saveButton.setMargin(new java.awt.Insets(1, 6, 1, 6)); saveButton.setPreferredSize(new java.awt.Dimension(60, 23)); saveButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { saveButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 6; gridBagConstraints.gridy = 6; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; gridBagConstraints.insets = new java.awt.Insets(0, 0, 4, 4); setupPane.add(saveButton, gridBagConstraints); Setupcontainer.add(setupPane, new java.awt.GridBagConstraints()); tabs.addTab("Setup", Setupcontainer); logPane.setLayout(new java.awt.GridBagLayout()); logArea.setEditable(false); logArea.setColumns(20); logArea.setRows(5); logArea.setMargin(new java.awt.Insets(4, 4, 4, 4)); logScroll.setViewportView(logArea); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 0.1; gridBagConstraints.weighty = 0.1; logPane.add(logScroll, gridBagConstraints); tabs.addTab("Log", logPane); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 0.1; gridBagConstraints.weighty = 0.2; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); add(tabs, gridBagConstraints); startStopButton.setText("Start"); startStopButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { startStopButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.gridheight = java.awt.GridBagConstraints.RELATIVE; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 4); add(startStopButton, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents private void yearFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_yearFieldActionPerformed // TODO add your handling code here: }//GEN-LAST:event_yearFieldActionPerformed private void secondsFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_secondsFieldActionPerformed // TODO add your handling code here: }//GEN-LAST:event_secondsFieldActionPerformed private void hoursFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_hoursFieldActionPerformed // TODO add your handling code here: }//GEN-LAST:event_hoursFieldActionPerformed private void expiryToggleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_expiryToggleActionPerformed expires = expiryToggle.isSelected(); toggleExpirationFieldEnabled(); }//GEN-LAST:event_expiryToggleActionPerformed private void minutesFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_minutesFieldActionPerformed // TODO add your handling code here: }//GEN-LAST:event_minutesFieldActionPerformed private void saveToggleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveToggleActionPerformed boolean selected = saveToggle.isSelected(); saveFolderField.setEnabled(selected); saveButton.setEnabled(selected); if(selected && saveFolder == null) { openFileChooser(); } }//GEN-LAST:event_saveToggleActionPerformed private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed openFileChooser(); }//GEN-LAST:event_saveButtonActionPerformed private void startStopButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startStopButtonActionPerformed isRunning = !isRunning; if(isRunning) { isRunning = start(); } else { stop(); } startStopButton.setSelected(isRunning); }//GEN-LAST:event_startStopButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel Setupcontainer; private javax.swing.JFormattedTextField dayField; private javax.swing.JLabel dayLabel; private javax.swing.JFormattedTextField delayField; private javax.swing.JLabel delayLabel; private javax.swing.JTextArea description; private javax.swing.JLabel expiresLabel; private javax.swing.JCheckBox expiryToggle; private javax.swing.JFormattedTextField hoursField; private javax.swing.JLabel hoursLabel; private javax.swing.JTextArea logArea; private javax.swing.JPanel logPane; private javax.swing.JScrollPane logScroll; private javax.swing.JFormattedTextField minutesField; private javax.swing.JLabel minutesLabel; private javax.swing.JFormattedTextField monthField; private javax.swing.JLabel monthLabel; private javax.swing.JButton saveButton; private javax.swing.JTextField saveFolderField; private javax.swing.JLabel saveLabel; private javax.swing.JCheckBox saveToggle; private javax.swing.JLabel secondLabel; private javax.swing.JFormattedTextField secondsField; private javax.swing.JLabel secondsLabel; private javax.swing.JPanel setupPane; private javax.swing.JButton sourceButton; private javax.swing.JCheckBox sourceIsBinaryButton; private javax.swing.JLabel sourceLabel; private javax.swing.JToggleButton startStopButton; private javax.swing.JTextField statusField; private javax.swing.JTabbedPane tabs; private javax.swing.JButton targetButton; private javax.swing.JLabel targetLabel; private javax.swing.JFormattedTextField yearField; private javax.swing.JLabel yearLabel; // End of variables declaration//GEN-END:variables }
35,371
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
IoTSource.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/iot/IoTSource.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.iot; import java.net.MalformedURLException; /** * An IoTSource represents a simple virtual source of data for the IoT tool. It * functions as a callback for a given URL in SourceMapping. * * @author Eero Lehtonen */ public interface IoTSource { /** * getData returns a String representation corresponding to the output of * the virtual service. (e.g. a simple virtual time service just returns a * String representation of the current system time.)' * * @param url * @return a response from the virtual endpoint */ String getData(String url); boolean matches(String url) throws MalformedURLException; }
1,519
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Pinger.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/iot/Pinger.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.iot; 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.tools.AbstractWandoraTool; import org.wandora.topicmap.TopicMapException; /** * * @author Eero Lehtonen */ public class Pinger extends AbstractWandoraTool implements WandoraTool, Runnable { private static final long serialVersionUID = 1L; @Override public String getDescription(){ return "Open the IoT pinger"; } @Override public String getName(){ return "IoT pinger"; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/iot_pinger.png"); } @Override public void execute(final Wandora wandora, Context context) throws TopicMapException { PingerPanel panel = new PingerPanel(wandora.getTopicMap()); panel.openInOwnWindow(wandora); } }
1,849
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SourceMapping.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/iot/SourceMapping.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.iot; import java.net.MalformedURLException; import java.util.ArrayList; /** * * @author Eero Lehtonen */ final class SourceMapping { protected static final String BASE_URL = "http://wandora.org/si/iot/source/"; private static final ArrayList<IoTSource> sources; static { sources = new ArrayList<>(); sources.add(new TimeSource()); sources.add(new GeolocationSource()); sources.add(new TMStatsSource()); } private static SourceMapping instance = null; protected static synchronized SourceMapping getInstance() { if(instance == null) instance = new SourceMapping(); return instance; } public IoTSource match(String url) { for(IoTSource source : sources) { try{ if(source.matches(url)) { return source; } } catch (MalformedURLException e) { } } return null; } }
1,883
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
GeolocationSource.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/iot/GeolocationSource.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.iot; import java.net.MalformedURLException; import java.net.URL; import org.json.JSONObject; import com.mashape.unirest.http.JsonNode; import com.mashape.unirest.http.Unirest; /** * * @author Eero Lehtonen */ public class GeolocationSource extends AbstractIoTSource implements IoTSource { private static final String HOST = "wandora.org"; private static final String PATH = "/si/iot/source/geolocation"; private static final String API_URL = "http://ip-api.com/json"; @Override public String getData(String url) { try { JsonNode resp = Unirest.get(API_URL).asJson().getBody(); JSONObject obj = resp.getObject(); return Double.toString(obj.getDouble("lat")) + ", " + Double.toString(obj.getDouble("lon")); } catch (Exception ex) { // IGNORE } return null; } @Override public boolean matches(String url) throws MalformedURLException { URL u = new URL(url); return u.getHost().equals(HOST) && u.getPath().equals(PATH); } }
1,919
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TMStatsSource.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/iot/TMStatsSource.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.iot; import java.net.MalformedURLException; import java.net.URL; import org.json.JSONException; import org.json.JSONObject; import org.wandora.application.Wandora; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author Eero Lehtonen */ public class TMStatsSource extends AbstractIoTSource implements IoTSource { private static final String HOST = "wandora.org"; private static final String PATH = "/si/iot/source/tm-stats"; @Override public String getData(String url) { TopicMap tm = Wandora.getWandora().getTopicMap(); try { JSONObject o = new JSONObject(); o.put("num_topics", tm.getNumTopics()); o.put("num_associations", tm.getNumAssociations()); return o.toString(); } catch (TopicMapException | JSONException e) { // IGNORE } return null; } @Override public boolean matches(String url) throws MalformedURLException { URL u = new URL(url); return u.getHost().equals(HOST) && u.getPath().equals(PATH); } }
1,992
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AbstractIoTSource.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/iot/AbstractIoTSource.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.iot; import java.net.URL; import java.net.URLDecoder; import java.util.HashMap; import java.util.Map; /** * * @author Eero Lehtonen */ abstract class AbstractIoTSource { protected Map<String,String> parseParams(URL u) { Map<String, String> params = new HashMap<>(); String q = u.getQuery(); if(q == null) return params; String[] splits = q.split("&"); for(String split: splits) { int idx = split.indexOf("="); try { String k = URLDecoder.decode(split.substring(0, idx), "UTF-8"); String v = URLDecoder.decode(split.substring(idx+1), "UTF-8"); params.put(k,v); } catch (Exception e) { // IGNORE } } return params; } }
1,704
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MergeWandoraProject.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/project/MergeWandoraProject.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/>. * * * MergeWandoraProject.java * * Created on 11. joulukuuta 2006, 10:50 * */ package org.wandora.application.tools.project; import java.io.File; 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.UIConstants; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.application.gui.simple.SimpleFileChooser; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapType; import org.wandora.topicmap.TopicMapTypeManager; import org.wandora.topicmap.layered.LayerStack; import org.wandora.topicmap.packageio.DirectoryPackageInput; import org.wandora.topicmap.packageio.PackageInput; import org.wandora.topicmap.packageio.ZipPackageInput; /** * * @author akivela */ public class MergeWandoraProject extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; public File forceFile = null; /** * Creates a new instance of MergeWandoraProject */ public MergeWandoraProject() { } public MergeWandoraProject(String projectFilename) { this(new File(projectFilename)); } public MergeWandoraProject(File projectFile) { this.forceFile = projectFile; } @Override public void execute(Wandora wandora, Context context) { if(forceFile == null) { SimpleFileChooser chooser = UIConstants.getWandoraProjectFileChooser(); chooser.setMultiSelectionEnabled(true); chooser.setDialogTitle("Merge Wandora project"); chooser.setApproveButtonText("Merge"); if(chooser.open(wandora)==SimpleFileChooser.APPROVE_OPTION) { File f = chooser.getSelectedFile(); mergeProject(f, wandora); } } else { mergeProject(forceFile, wandora); forceFile = null; } } public void mergeProject(File f, Wandora wandora) { if(f == null) { return; } if(f.exists() && !f.isDirectory() && !f.getName().toUpperCase().endsWith(".WPR")) { int a = WandoraOptionPane.showConfirmDialog(wandora, "The project file doesn't end with Wandora project suffix WPR.\nDo you want to open the file as a Wandora project?", "Wrong file suffix", WandoraOptionPane.YES_NO_OPTION); if(a == WandoraOptionPane.NO_OPTION) return; } setDefaultLogger(); setLogTitle("Merging Wandora project"); log("Merging Wandora project '" + f.getPath() + "'."); wandora.options.put("current.directory", f.getPath()); try { wandora.getTopicMap().clearTopicMapIndexes(); } catch(Exception e) { log(e); } try { PackageInput in = null; if(!f.isDirectory()) { in = new ZipPackageInput(f); } else { in = new DirectoryPackageInput(f); } TopicMapType type = TopicMapTypeManager.getType(org.wandora.topicmap.layered.LayerStack.class); TopicMap tm = wandora.getTopicMap(); TopicMap results = type.unpackageTopicMap(tm,in,"",getCurrentLogger(),wandora); in.close(); if(results != null) { // Next is used to signalize Wandora to redraw the layer stack wandora.setTopicMap((LayerStack)tm); if(!forceStop()) { setState(CLOSE); } else { log("Merging interrupted."); log("Project was only partially merged to Wandora."); setState(WAIT); } } else { setState(WAIT); } } catch(Exception e){ log(e); setState(WAIT); } } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/merge_project.png"); } @Override public String getName() { return "Merge project"; } @Override public String getDescription() { return "Merges Wandora project to the current project in Wandora. Wandora imports topic map layers in merged project file."; } @Override public boolean runInOwnThread() { return true; } @Override public boolean requiresRefresh() { return true; } }
5,518
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
LoadWandoraProject.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/project/LoadWandoraProject.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/>. * * * LoadWandoraProject.java * * Created on 17. helmikuuta 2006, 16:25 * */ package org.wandora.application.tools.project; import java.io.File; 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.UIConstants; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.application.gui.simple.SimpleFileChooser; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapType; import org.wandora.topicmap.TopicMapTypeManager; import org.wandora.topicmap.layered.LayerStack; import org.wandora.topicmap.packageio.DirectoryPackageInput; import org.wandora.topicmap.packageio.PackageInput; import org.wandora.topicmap.packageio.ZipPackageInput; /** * Class implements WandoraTool used to open and load Wandora project file. * Wandora project file is a zipped collection of XTM topic maps and one configuration * file named options.xml. Each XTM topic map represents one layer in Wandora. * Configuration file contains layer name and type settings. * * @author akivela */ public class LoadWandoraProject extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; public File forceFile = null; /** * Creates a new instance of LoadWandoraProject */ public LoadWandoraProject() { } /** * Creates a new instance of LoadWandoraProject * @param projectFilename is a name for opened Wandora project file. */ public LoadWandoraProject(String projectFilename) { this(new File(projectFilename)); } /** * Creates a new instance of LoadWandoraProject * @param projectFile is a file of opened Wandora project file. */ public LoadWandoraProject(File projectFile) { this.forceFile = projectFile; } @Override public void execute(Wandora wandora, Context context) { if(forceFile == null) { SimpleFileChooser chooser=UIConstants.getWandoraProjectFileChooser(); chooser.setDialogTitle("Open Wandora project"); if(chooser.open(wandora)==SimpleFileChooser.APPROVE_OPTION) { File f=chooser.getSelectedFile(); loadProject(f, wandora); } } else { loadProject(forceFile, wandora); forceFile = null; } } /** * Tool uses method loadProject to actually load the project into the Wandora. * @param f Wandora project file. * @param wandora Wandora object. */ public void loadProject(File f, Wandora wandora) { if(f == null) return; if(f.exists() && !f.isDirectory() && !f.getName().toUpperCase().endsWith(".WPR")) { int a = WandoraOptionPane.showConfirmDialog(wandora, "The project file doesn't end with Wandora project suffix WPR.\nDo you want to open the file as a Wandora project?", "Wrong file suffix", WandoraOptionPane.YES_NO_OPTION); if(a == WandoraOptionPane.NO_OPTION) return; } setDefaultLogger(); setLogTitle("Loading Wandora project"); if(!f.exists()) { log("Project '"+f.getName()+"' not found error!"); setState(WAIT); return; } log("Loading Wandora project '" + f.getPath() + "'."); try { wandora.getTopicMap().clearTopicMapIndexes(); } catch(Exception e) { log(e); } try { PackageInput in = null; if(!f.isDirectory()) { in = new ZipPackageInput(f); } else { in = new DirectoryPackageInput(f); } TopicMapType type = TopicMapTypeManager.getType(LayerStack.class); TopicMap tm = type.unpackageTopicMap(in, "", getCurrentLogger(), wandora); in.close(); if(tm != null) { wandora.setTopicMap((LayerStack)tm); wandora.setCurrentProjectFileName(f.getAbsolutePath()); if(!forceStop()) { setState(CLOSE); } else { log("Loading interrupted."); log("Project was only partially loaded."); setState(WAIT); } } else { setState(WAIT); } } catch(Exception e){ log(e); setState(WAIT); } } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/load_project.png"); } @Override public String getName() { return "Open project"; } @Override public String getDescription() { return "Open Wandora project."; } @Override public boolean runInOwnThread() { return true; } @Override public boolean requiresRefresh() { return true; } }
6,000
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SaveWandoraProject.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/project/SaveWandoraProject.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/>. * * * SaveWandoraProject.java * * Created on 17. helmikuuta 2006, 16:27 * */ package org.wandora.application.tools.project; import java.io.File; import java.io.FileOutputStream; 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.UIConstants; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.application.gui.simple.SimpleFileChooser; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapType; import org.wandora.topicmap.TopicMapTypeManager; import org.wandora.topicmap.packageio.DirectoryPackageOutput; import org.wandora.topicmap.packageio.PackageOutput; import org.wandora.topicmap.packageio.ZipPackageOutput; import org.wandora.utils.IObox; /** * * @author akivela */ public class SaveWandoraProject extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; private boolean useCurrentFileName = false; public SaveWandoraProject() { } public SaveWandoraProject(boolean u) { useCurrentFileName = u; } @Override public void execute(Wandora wandora, Context context) { File f = null; boolean doSave = false; try { if(useCurrentFileName) { String fname = wandora.getCurrentProjectFileName(); if(fname != null) f = new File(fname); doSave = true; } if(f == null) { SimpleFileChooser chooser = UIConstants.getWandoraProjectFileChooser(); chooser.setDialogTitle("Save Wandora project"); if(chooser.open(wandora, SimpleFileChooser.SAVE_DIALOG)==SimpleFileChooser.APPROVE_OPTION) { f = chooser.getSelectedFile(); if(!f.exists() || !f.isDirectory()) { f = IObox.addFileExtension(f, "wpr"); } doSave = true; } } } catch(Exception e) { wandora.handleError(e); } if(doSave && f!=null) { try { if(f.exists() && !f.isDirectory() && !useCurrentFileName) { int overWrite = WandoraOptionPane.showConfirmDialog(wandora, "Overwrite existing project file '"+f.getName()+"'?", "Overwrite file?", WandoraOptionPane.YES_NO_OPTION); if(overWrite == WandoraOptionPane.NO_OPTION) return; } setDefaultLogger(); log("Saving project to '" + f.getName() + "'."); TopicMap tm = wandora.getTopicMap(); TopicMapType tmtype = TopicMapTypeManager.getType(tm); PackageOutput out = null; if(!f.isDirectory() || !f.exists()) { out = new ZipPackageOutput(new FileOutputStream(f)); } else { out = new DirectoryPackageOutput(f.getAbsolutePath()); } tmtype.packageTopicMap(tm,out,"",getCurrentLogger()); out.close(); wandora.setCurrentProjectFileName(f.getAbsolutePath()); if(!forceStop()) { setState(CLOSE); } else { log("Saving interrupted."); log("Project was only partially saved."); setState(WAIT); } } catch(Exception e){ log(e); setState(WAIT); } } } @Override public Icon getIcon() { if(useCurrentFileName) return UIBox.getIcon("gui/icons/save_project.png"); else return UIBox.getIcon("gui/icons/save_project_as.png"); } @Override public String getName() { if(useCurrentFileName) return "Save project as"; else return "Save project"; } @Override public String getDescription() { return "Saves all topic map layers in Wandora to a Wandora project."; } @Override public boolean runInOwnThread() { return true; } }
5,244
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
RevertWandoraProject.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/project/RevertWandoraProject.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/>. * * * * RevertWandoraProject.java * * Created on 17. helmikuuta 2006, 16:25 * */ package org.wandora.application.tools.project; import java.io.File; 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.TopicMap; import org.wandora.topicmap.TopicMapType; import org.wandora.topicmap.TopicMapTypeManager; import org.wandora.topicmap.layered.LayerStack; import org.wandora.topicmap.packageio.DirectoryPackageInput; import org.wandora.topicmap.packageio.PackageInput; import org.wandora.topicmap.packageio.ZipPackageInput; /** * * @author akivela */ public class RevertWandoraProject extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; /** * Creates a new instance of RevertWandoraProject */ public RevertWandoraProject() { } @Override public void execute(Wandora wandora, Context context) { String recentProject = wandora.getCurrentProjectFileName(); if(recentProject != null && recentProject.length() > 0) { File recentProjectFile = new File(recentProject); if(recentProjectFile != null && recentProjectFile.exists()) { loadProject(recentProjectFile, wandora); } else { singleLog("Recent project file not found!"); } } else { singleLog("No recent project file available!"); } } /** * Tool uses method loadProject to actually load the project into the Wandora. * @param f Wandora project file. * @param wandora Wandora object. */ public void loadProject(File f, Wandora wandora) { if(f == null) return; if(f.exists() && !f.isDirectory() && !f.getName().toUpperCase().endsWith(".WPR")) { int a = WandoraOptionPane.showConfirmDialog(wandora, "The project file doesn't end with Wandora project suffix WPR.\nDo you want to open given the file as a Wandora project?", "Wrong file suffix", WandoraOptionPane.YES_NO_OPTION); if(a == WandoraOptionPane.NO_OPTION) return; } setDefaultLogger(); setLogTitle("Reverting Wandora Project"); if(!f.exists()) { log("Project '"+f.getName()+"' not found error!"); setState(WAIT); return; } log("Reverting Wandora project '" + f.getPath() + "'."); try { wandora.getTopicMap().clearTopicMapIndexes(); } catch(Exception e) { log(e); } try { PackageInput in = null; if(!f.isDirectory()) { in = new ZipPackageInput(f); } else { in = new DirectoryPackageInput(f); } TopicMapType type = TopicMapTypeManager.getType(LayerStack.class); TopicMap tm = type.unpackageTopicMap(in,"",getCurrentLogger(),wandora); in.close(); if(tm != null) { wandora.setTopicMap((LayerStack)tm); wandora.setCurrentProjectFileName(f.getAbsolutePath()); if(!forceStop()) { setState(CLOSE); } else { log("Revert interrupted."); log("Project was only partially loaded."); setState(WAIT); } } else { setState(WAIT); } } catch(Exception e){ log(e); setState(WAIT); } } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/revert_project.png"); } @Override public String getName() { return "Revert project"; } @Override public String getDescription() { return "Reverts to recently opened Wandora project."; } @Override public boolean runInOwnThread() { return true; } @Override public boolean requiresRefresh() { return true; } }
5,167
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ResetWandora.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/project/ResetWandora.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/>. * * * ResetWandora.java * * Created on September 21, 2004, 4:50 PM */ package org.wandora.application.tools.project; 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; /** * * @author akivela */ public class ResetWandora extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; public ResetWandora() { } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/new_project.png"); } @Override public String getName() { return "Restart Wandora"; } @Override public String getDescription() { return "Restarts Wandora application."; } public void execute(Wandora wandora, Context context) { int a = WandoraOptionPane.showConfirmDialog(wandora, "Starting new Wandora project restarts Wandora. Restarting Wandora application you'll loose all changes you have made. Do you really want to restart Wandora?", "Restarting Wandora"); if(a == WandoraOptionPane.YES_OPTION) { wandora.resetWandora(); } } }
2,174
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AbstractDockingTool.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/docking/AbstractDockingTool.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.docking; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.gui.topicpanels.DockingFramePanel; import org.wandora.application.gui.topicpanels.TopicPanel; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.TopicMapException; /** * * @author akivela */ public class AbstractDockingTool extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; @Override public void execute(Wandora wandora, Context context) throws TopicMapException { System.out.println("Warning: Docking tool is not overriding execute method."); } public DockingFramePanel solveDockingFramePanel(Wandora wandora, Context context) { if(context != null) { Object contextSource = context.getContextSource(); if(contextSource != null && contextSource instanceof DockingFramePanel) { return ((DockingFramePanel)contextSource); } } if(wandora != null) { TopicPanel topicPanel = wandora.getTopicPanel(); if(topicPanel != null && topicPanel instanceof DockingFramePanel) { return ((DockingFramePanel)topicPanel); } } return null; } }
2,224
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DeleteAllDockables.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/docking/DeleteAllDockables.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.docking; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.application.gui.topicpanels.DockingFramePanel; /** * * @author akivela */ public class DeleteAllDockables extends AbstractDockingTool { private static final long serialVersionUID = 1L; /** Creates a new instance of DeleteAllDockables */ public DeleteAllDockables() { } @Override public String getName() { return "Close all dockables"; } @Override public void execute(Wandora w, Context context) { DockingFramePanel dockingPanel = this.solveDockingFramePanel(w, context); if(dockingPanel != null) { try { dockingPanel.deleteAllDockables(); } catch(Exception e) { e.printStackTrace(); } } } }
1,741
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SelectDockable.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/docking/SelectDockable.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.docking; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.application.gui.topicpanels.DockingFramePanel; import bibliothek.gui.Dockable; /** * * @author akivela */ public class SelectDockable extends AbstractDockingTool { private static final long serialVersionUID = 1L; private Dockable dockable = null; /** Creates a new instance of SelectDockable */ public SelectDockable(Dockable d) { dockable = d; } @Override public String getName() { if(dockable != null) { return "Select dockable "+dockable.getTitleText(); } else { return "Select dockable"; } } @Override public void execute(Wandora w, Context context) { DockingFramePanel dockingPanel = this.solveDockingFramePanel(w, context); if(dockingPanel != null && dockable != null) { try { dockingPanel.selectDockable(dockable); } catch(Exception e) { e.printStackTrace(); } } } }
1,982
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MaximizeDockable.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/docking/MaximizeDockable.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.docking; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.application.gui.topicpanels.DockingFramePanel; import bibliothek.gui.Dockable; /** * * @author akivela */ public class MaximizeDockable extends AbstractDockingTool { private static final long serialVersionUID = 1L; private Dockable dockable = null; /** Creates a new instance of MaximizeDockable */ public MaximizeDockable(Dockable d) { dockable = d; } @Override public String getName() { if(dockable != null) { return "Maximize dockable "+dockable.getTitleText(); } else { return "Maximize dockable"; } } @Override public void execute(Wandora w, Context context) { DockingFramePanel dockingPanel = this.solveDockingFramePanel(w, context); if(dockingPanel != null && dockable != null) { try { dockingPanel.maximizeDockable(dockable); } catch(Exception e) { e.printStackTrace(); } } } }
1,996
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DeleteCurrentDockable.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/docking/DeleteCurrentDockable.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.docking; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.application.gui.topicpanels.DockingFramePanel; /** * * @author akivela */ public class DeleteCurrentDockable extends AbstractDockingTool { private static final long serialVersionUID = 1L; /** Creates a new instance of DeleteCurrentDockable */ public DeleteCurrentDockable() { } @Override public String getName() { return "Close current dockable"; } @Override public void execute(Wandora w, Context context) { DockingFramePanel dockingPanel = this.solveDockingFramePanel(w, context); if(dockingPanel != null) { try { dockingPanel.deleteCurrentDockable(); } catch(Exception e) { e.printStackTrace(); } } } }
1,755
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AddDockable.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/docking/AddDockable.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.docking; import java.util.Iterator; import javax.swing.Icon; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.topicpanels.DockingFramePanel; import org.wandora.application.gui.topicpanels.TopicPanel; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; /** * Add a topic panel into the <code>DockingFramePanel</code>. Added topic panel * is specified with a class argument passed to the constructor. A single * <code>AddDockable</code> object can add only one type of topic panels. * Whenever a topic panel is added a context topic is passed to the topic panel * as an argument. * * @author akivela */ public class AddDockable extends AbstractDockingTool { private static final long serialVersionUID = 1L; private Class dockableClass = null; private Icon dockableIcon = null; /** Creates a new instance of AddDockable */ public AddDockable(Class dc) { dockableClass = dc; } public AddDockable(String className) { try { if(className != null) { dockableClass = Class.forName(className); } else { System.out.println("AddDockable can't use given class name 'null'."); } } catch(Exception e) { System.out.println("AddDockable can't use given class name '"+className+"'."); } } @Override public String getName() { if(dockableClass != null) { return "New dockable "+dockableClass.getName(); } else { return "New dockable"; } } @Override public Icon getIcon() { if(dockableClass == null) { return UIBox.getIcon("gui/icons/topic_panel_add.png"); } else { if(dockableIcon == null) { try { Object o = dockableClass.getDeclaredConstructor().newInstance(); if(o instanceof TopicPanel) { TopicPanel tp = (TopicPanel) o; dockableIcon = tp.getIcon(); } } catch(Exception e) { e.printStackTrace(); } } if(dockableIcon == null) { return UIBox.getIcon("gui/icons/topic_panel_add.png"); } else { return dockableIcon; } } } @Override public void execute(Wandora w, Context context) { DockingFramePanel dockingPanel = this.solveDockingFramePanel(w, context); if(dockableClass != null && dockingPanel != null) { try { Topic t = null; Iterator i = context.getContextObjects(); if(i.hasNext()) { try { t = (Topic) i.next(); } catch(Exception e) {} } if(t == null) { t = w.getOpenTopic(); } if(t == null) { t = w.getTopicMap().getTopic(TMBox.WANDORACLASS_SI); } dockingPanel.addDockable(dockableClass.getDeclaredConstructor().newInstance(), t); } catch(Exception e) { e.printStackTrace(); } } else { System.out.println("No valid dockable class registered in AddDockable. Can't create new dockable."); } } @Override public boolean requiresRefresh() { return true; } }
4,622
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DeleteDockable.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/docking/DeleteDockable.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.docking; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.application.gui.topicpanels.DockingFramePanel; import bibliothek.gui.Dockable; /** * * @author akivela */ public class DeleteDockable extends AbstractDockingTool { private static final long serialVersionUID = 1L; private Dockable dockable = null; /** Creates a new instance of DeleteDockable */ public DeleteDockable(Dockable d) { dockable = d; } @Override public String getName() { if(dockable != null) { return "Close dockable "+dockable.getTitleText(); } else { return "Close dockable"; } } @Override public void execute(Wandora w, Context context) { DockingFramePanel dockingPanel = this.solveDockingFramePanel(w, context); if(dockingPanel != null && dockable != null) { try { dockingPanel.deleteDockable(dockable); } catch(Exception e) { e.printStackTrace(); } } } }
1,982
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AddTraditional.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/docking/add/AddTraditional.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.docking.add; import org.wandora.application.gui.topicpanels.TraditionalTopicPanel; import org.wandora.application.tools.docking.AddDockable; /** * * @author akivela */ public class AddTraditional extends AddDockable { private static final long serialVersionUID = 1L; public AddTraditional() { super(TraditionalTopicPanel.class); } }
1,209
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AddGraph.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/docking/add/AddGraph.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.docking.add; import org.wandora.application.gui.topicpanels.GraphTopicPanel; import org.wandora.application.tools.docking.AddDockable; /** * * @author akivela */ public class AddGraph extends AddDockable { private static final long serialVersionUID = 1L; public AddGraph() { super(GraphTopicPanel.class); } }
1,183
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AddWebView.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/docking/add/AddWebView.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.docking.add; import org.wandora.application.gui.topicpanels.WebViewTopicPanel; import org.wandora.application.tools.docking.AddDockable; /** * * @author akivela */ public class AddWebView extends AddDockable { private static final long serialVersionUID = 1L; public AddWebView() { super(WebViewTopicPanel.class); } }
1,195
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AddSketchGrid.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/docking/add/AddSketchGrid.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.docking.add; import org.wandora.application.gui.topicpanels.SketchGridPanel; import org.wandora.application.tools.docking.AddDockable; /** * * @author akivela */ public class AddSketchGrid extends AddDockable { private static final long serialVersionUID = 1L; public AddSketchGrid() { super(SketchGridPanel.class); } }
1,197
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AddSearch.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/docking/add/AddSearch.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.docking.add; import org.wandora.application.gui.topicpanels.SearchTopicPanel; import org.wandora.application.tools.docking.AddDockable; /** * * @author akivela */ public class AddSearch extends AddDockable { private static final long serialVersionUID = 1L; public AddSearch() { super(SearchTopicPanel.class); } }
1,191
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AddTree.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/docking/add/AddTree.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.docking.add; import org.wandora.application.gui.topicpanels.TreeTopicPanel; import org.wandora.application.tools.docking.AddDockable; /** * * @author akivela */ public class AddTree extends AddDockable { private static final long serialVersionUID = 1L; public AddTree() { super(TreeTopicPanel.class); } }
1,183
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
OpenTopicWithSX.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/navigate/OpenTopicWithSX.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/>. * * * OpenTopicWithSX.java * * Created on July 19, 2004, 2:25 PM */ package org.wandora.application.tools.navigate; 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.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.utils.Textbox; import org.wandora.utils.swing.InputDialogWithHistory; /** * * @author olli, akivela */ public class OpenTopicWithSX extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; private static InputDialogWithHistory dialog = null; public OpenTopicWithSX() { } @Override public void execute(Wandora wandora, Context context) throws TopicMapException { if(dialog == null) { dialog = new InputDialogWithHistory((java.awt.Frame) wandora, true, "Enter subject indentifier or subject locator", "Go to topic..."); } String sx = dialog.showDialog(); if(sx != null && dialog.accepted) { sx = Textbox.trimExtraSpaces(sx); if(sx.length() > 0) { TopicMap topicMap = wandora.getTopicMap(); Topic t = topicMap.getTopic(sx); if(t == null) { t = topicMap.getTopicBySubjectLocator(sx); if(t == null) { WandoraOptionPane.showMessageDialog(wandora, "Topic not found with given SI or SL.", WandoraOptionPane.ERROR_MESSAGE); } } if(t != null) { wandora.openTopic(t); } } } } @Override public String getName() { return "Open with SX"; } @Override public String getDescription() { return "Open a topic with a subject identifier URI or "+ "a subject locator URI."; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/open_topic_sx.png"); } }
3,096
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
OpenTopicInNew.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/navigate/OpenTopicInNew.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * */ package org.wandora.application.tools.navigate; import java.awt.Component; import java.util.Iterator; import javax.swing.Icon; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.application.gui.topicpanels.DockingFramePanel; import org.wandora.application.gui.topicpanels.TraditionalTopicPanel; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; /** * * @author akivela */ public class OpenTopicInNew extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; public final static int ASK_USER = 100; public final static int SOLVE_USING_CONTEXT = 102; public int options = SOLVE_USING_CONTEXT; private Class<Component> dockableClass = null; /** Creates a new instance of OpenTopicAt */ public OpenTopicInNew(Class<Component> c) { dockableClass = c; } public OpenTopicInNew(Class<Component> c, Context preferredContext) { dockableClass = c; setContext(preferredContext); } public OpenTopicInNew(Class<Component> c, int preferredOptions) { dockableClass = c; this.options = preferredOptions; } @Override public void execute(Wandora wandora, Context context) throws TopicMapException { try { DockingFramePanel dockingPanel = (DockingFramePanel) wandora.topicPanelManager.getTopicPanel(); Iterator contextTopics = context.getContextObjects(); if(options == SOLVE_USING_CONTEXT && contextTopics != null && contextTopics.hasNext()) { int count = 0; while(contextTopics.hasNext()) { count++; boolean doIt = true; if(count > 20) { int a = WandoraOptionPane.showConfirmDialog(wandora, "You have already opened 20 topic panels. You sure want to open yet another?", "Many topic panels already open", WandoraOptionPane.YES_NO_CANCEL_OPTION); if(a != WandoraOptionPane.CANCEL_OPTION) break; else if(a != WandoraOptionPane.YES_OPTION) doIt = false; } if(doIt) { Topic t = (Topic) contextTopics.next(); if(t != null) { wandora.addToHistory(t); if(dockableClass != null) { dockingPanel.addDockable(dockableClass.newInstance(), t); } else { dockingPanel.addDockable((Component) new TraditionalTopicPanel(), t); } } else { WandoraOptionPane.showMessageDialog(wandora, "Can't open a topic. Select a valid topic first.", "Can't open a topic", WandoraOptionPane.WARNING_MESSAGE); } } } } else { if(dockableClass != null) { Topic t = wandora.showTopicFinder(); if(t != null) { dockingPanel.addDockable(dockableClass.getDeclaredConstructor().newInstance(), t); } } else { Topic t = wandora.showTopicFinder(); if(t != null) { dockingPanel.addDockable((Component) new TraditionalTopicPanel(), t); } } } } catch(Exception e) { e.printStackTrace(); } } @Override public String getName() { return "Open topic in new"; } @Override public String getDescription() { return "Open selected topic in new topic panel."; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/topic_open.png"); } @Override public boolean requiresRefresh() { return true; } @Override public boolean runInOwnThread() { return false; } }
5,269
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
OpenTopic.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/navigate/OpenTopic.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/>. * * * OpenTopic.java * * Created on October 1, 2004, 12:12 PM */ package org.wandora.application.tools.navigate; import java.util.Iterator; import javax.swing.Icon; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; /** * * @author akivela */ public class OpenTopic extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; public final static int ASK_USER = 100; public final static int SOLVE_USING_CONTEXT = 102; public int options = SOLVE_USING_CONTEXT; /** Creates a new instance of OpenTopic */ public OpenTopic() { } public OpenTopic(Context preferredContext) { setContext(preferredContext); } public OpenTopic(int preferredOptions) { this.options = preferredOptions; } @Override public void execute(Wandora wandora, Context context) throws TopicMapException { Iterator contextTopics = context.getContextObjects(); if(options == SOLVE_USING_CONTEXT && contextTopics != null && contextTopics.hasNext()) { Topic t = (Topic) (Topic) contextTopics.next(); if(t != null && !t.isRemoved()) { wandora.openTopic(t); } else { WandoraOptionPane.showMessageDialog(wandora, "Can't open a topic. Select a valid topic first.", "Can't open a topic", WandoraOptionPane.WARNING_MESSAGE); } } else { Topic t = wandora.showTopicFinder(); if(t != null) { wandora.openTopic(t); } } } @Override public String getName() { return "Open topic"; } @Override public String getDescription() { return "Open selected topic. If no topic is selected, a topic selection dialog is opened."; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/topic_open.png"); } @Override public boolean requiresRefresh() { return false; } @Override public boolean runInOwnThread() { return false; } }
3,287
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
CloseCurrentTopicPanel.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/navigate/CloseCurrentTopicPanel.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/>. * * * CloseCurrentTopicPanel.java * * Created on 22. huhtikuuta 2006, 10:15 * */ package org.wandora.application.tools.navigate; 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.DockingFramePanel; import org.wandora.application.gui.topicpanels.TopicPanel; import org.wandora.application.tools.AbstractWandoraTool; /** * * @author akivela */ public class CloseCurrentTopicPanel extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; /** Creates a new instance of CloseCurrentTopicPanel */ public CloseCurrentTopicPanel() { } @Override public String getName() { return "Close current topic panels"; } @Override public String getDescription() { return "Close current topic panel."; } @Override public void execute(Wandora wandora, Context context) { TopicPanel tp = wandora.getTopicPanel(); if(tp != null && tp instanceof DockingFramePanel) { DockingFramePanel dfp = (DockingFramePanel) tp; dfp.deleteCurrentDockable(); } } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/topic_close.png"); } }
2,213
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Back.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/navigate/Back.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/>. * * * Back.java * * Created on 28. huhtikuuta 2006, 14:24 * */ package org.wandora.application.tools.navigate; import javax.swing.Icon; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.application.gui.UIBox; import org.wandora.application.tools.AbstractWandoraTool; /** * * @author olli */ public class Back extends AbstractWandoraTool { private static final long serialVersionUID = 1L; /** Creates a new instance of Back */ public Back() { } @Override public void execute(Wandora wandora, Context context) { wandora.back(); } @Override public String getName() { return "Back"; } @Override public String getDescription() { return "Go back to the previous topic in the topic history."; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/back.png"); } @Override public boolean runInOwnThread(){ return false; } }
1,837
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Forward.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/navigate/Forward.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/>. * * * Forward.java * * Created on 28. huhtikuuta 2006, 14:24 * */ package org.wandora.application.tools.navigate; import javax.swing.Icon; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.application.gui.UIBox; import org.wandora.application.tools.AbstractWandoraTool; /** * * @author olli */ public class Forward extends AbstractWandoraTool { private static final long serialVersionUID = 1L; /** Creates a new instance of Forward */ public Forward() { } @Override public void execute(Wandora wandora, Context context) { wandora.forward(); } @Override public String getName() { return "Forward"; } @Override public String getDescription() { return "Go back to the next topic in the topic history."; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/forward.png"); } @Override public boolean runInOwnThread(){ return false; } }
1,862
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z