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
JavaScriptEncoder.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/velocityhelpers/JavaScriptEncoder.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * JavaScriptEncoder.java * * Created on July 28, 2004, 12:38 PM */ package org.wandora.modules.velocityhelpers; /** * * @author olli */ public class JavaScriptEncoder { /** Creates a new instance of JavaScriptEncoder */ public JavaScriptEncoder() { } public String encode(String s){ /* s=s.replaceAll("\\\\", "\\\\"); s=s.replaceAll("\"", "\\\""); s=s.replaceAll("\'", "\\\'");*/ return s; } public String encodeString(String s){ s=s.replaceAll("\\\\", "\\\\"); s=s.replaceAll("\"", "\\\""); s=s.replaceAll("\'", "\\\'"); return s; } }
1,467
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
HTMLEncoder.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/velocityhelpers/HTMLEncoder.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * HTMLEncoder.java * * Created on 19.7.2005, 14:04 */ package org.wandora.modules.velocityhelpers; /** * * @author olli */ public class HTMLEncoder { /** Creates a new instance of HTMLEncoder */ public HTMLEncoder() { } public String encode(String s){ s=s.replaceAll("&","&amp;"); s=s.replaceAll("<","&lt;"); return s; } public String encodeAttribute(String s){ return encode(s).replaceAll("\"","&quot;"); } }
1,301
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
URLEncoder.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/velocityhelpers/URLEncoder.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * URLEncoder.java * * Created on July 9, 2004, 2:55 PM */ package org.wandora.modules.velocityhelpers; /** * * @author olli */ public class URLEncoder { private String encoding; /** Creates a new instance of URLEncoder */ public URLEncoder() { this("UTF-8"); } public URLEncoder(String encoding) { this.encoding=encoding; } public String encode(String s){ try{ return java.net.URLEncoder.encode(s,encoding); }catch(Exception e){ return s; } } }
1,373
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
JSONBox.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/velocityhelpers/JSONBox.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.modules.velocityhelpers; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import org.json.JSONObject; /** * * @author akivela */ public class JSONBox { public JSONBox() { } public static JSONObject load(String urlStr) { JSONObject json = null; try { if(urlStr != null) { URL url = new URL(urlStr); URLConnection urlConnection = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); StringBuilder sb = new StringBuilder(""); String s; while ((s = in.readLine()) != null) { sb.append(s); } in.close(); json = new JSONObject(sb.toString()); } } catch(Exception e) { e.printStackTrace(); } return json; } public static String JSONEncode(String string) { if (string == null || string.length() == 0) { return ""; } int c = 0; int i; int len = string.length(); StringBuilder sb = new StringBuilder(len + 4); String t; 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: if (c < ' ') { t = "000" + Integer.toHexString(c); sb.append("\\u" + t.substring(t.length() - 4)); } else { sb.append((char) c); } } } return sb.toString(); } }
3,328
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Sorter.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/velocityhelpers/Sorter.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.modules.velocityhelpers; import java.util.Collections; import java.util.List; /** * * @author olli */ public class Sorter { public List sort(List l){ Collections.sort(l); return l; } }
1,035
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SetHashMap.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/velocityhelpers/SetHashMap.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * SetHashMap.java * * Created on July 21, 2004, 9:24 AM */ package org.wandora.modules.velocityhelpers; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Set; /** * * @author olli */ /* Do not implement Map interface or extend classes implementing it. This class is not a map! In Map specification it is specifically said that "each key can map to at most one value." */ public class SetHashMap { private HashMap hm; /** Creates a new instance of MultiHashMap */ public SetHashMap() { hm=new HashMap(); } public Collection get(Object key){ Collection c=(Collection)hm.get(key); if(c==null) return new ArrayList(); else return c; } public boolean add(Object key,Object value){ Collection c=(Collection)hm.get(key); if(c==null){ c=new HashSet(); hm.put(key,c); } return c.add(value); } public boolean isKeyEmpty(Object key){ return hm.containsKey(key); } public boolean containsAt(Object key,Object value){ Collection c=(Collection)hm.get(key); if(c==null) return false; else return c.contains(value); } public boolean clearKey(Object key){ return (hm.remove(key)!=null); } public boolean remove(Object key,Object value){ Collection c=(Collection)hm.get(key); if(c==null) return false; boolean ret=c.remove(value); if(c.isEmpty()) hm.remove(c); return ret; } public Set entrySet(){ return hm.entrySet(); } public Set keySet(){ return hm.keySet(); } }
2,564
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
InstanceMaker.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/velocityhelpers/InstanceMaker.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * InstanceMaker.java * * Created on July 12, 2004, 10:55 AM */ package org.wandora.modules.velocityhelpers; /** * Use this class in velocity when you need to make new instances of some class in * the template. * * @author olli */ public class InstanceMaker { private Class<?> c; /** Creates a new instance of InstanceMaker */ public InstanceMaker(String cls) throws ReflectiveOperationException { c=Class.forName(cls); } public InstanceMaker(Class<?> cls){ this.c=cls; } public Object make() throws Exception { return c.getDeclaredConstructor().newInstance(); } }
1,459
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimpleDataSource.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/velocityhelpers/SimpleDataSource.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * SimpleDataSource.java * * Created on 25. tammikuuta 2006, 11:09 */ package org.wandora.modules.velocityhelpers; import java.io.InputStream; import javax.activation.DataSource; import javax.mail.MessagingException; import javax.mail.internet.MimeBodyPart; /** * * @author olli */ public class SimpleDataSource implements DataSource { private String name; private String contentType; private InputStream in; public SimpleDataSource(String name,String contentType,InputStream in) { this.name=name; this.contentType=contentType; this.in=in; } public java.io.OutputStream getOutputStream() throws java.io.IOException { throw new java.io.IOException("Illegal operation"); } public String getName() { return name; } public java.io.InputStream getInputStream() throws java.io.IOException { return in; } public String getContentType() { return contentType; } public static void addBase64Header(MimeBodyPart mbp) throws MessagingException { mbp.addHeader("Content-Transfer-Encoding","base64"); } }
1,952
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TextBox.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/velocityhelpers/TextBox.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * TextBox.java * * Created on July 13, 2004, 9:17 AM */ package org.wandora.modules.velocityhelpers; import java.util.Properties; /** * * @author olli */ public class TextBox { public static final String PROP_SHORTNAMELENGTH="textbox.shortnamelength"; private int shortNameLength; public TextBox(){ this(new Properties()); } public TextBox(int shortNameLength){ this.shortNameLength=shortNameLength; } /** Creates a new instance of TextBox */ public TextBox(Properties properties) { shortNameLength=30; if(properties.getProperty(PROP_SHORTNAMELENGTH)!=null) shortNameLength=Integer.parseInt(properties.getProperty(PROP_SHORTNAMELENGTH)); } public String shortenName(String name){ if(name.length()<=shortNameLength) return name; else return name.substring(0,shortNameLength/2-2)+"..."+name.substring(name.length()-shortNameLength/2-2); } public String charToStr(int c){ return Character.valueOf((char)c).toString(); } public String repeat(String s,int times){ String r=""; for(int i=0;i<times;i++){ r+=s; } return r; } }
2,052
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
CurrentTime.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/velocityhelpers/CurrentTime.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.modules.velocityhelpers; import java.text.SimpleDateFormat; import java.util.Date; /** * * @author olli */ public class CurrentTime { public CurrentTime(){} public long currentTimeMillis(){ return System.currentTimeMillis(); } public String currentTimeFormatted(String format){ SimpleDateFormat sdf=new SimpleDateFormat(format); return sdf.format(new Date()); } }
1,234
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicsDirective.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query/TopicsDirective.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * TopicsDirective.java * * Created on 20. helmikuuta 2008, 13:46 */ package org.wandora.query; import java.util.ArrayList; import org.wandora.topicmap.Locator; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.XTMPSI; /** * @deprecated * * @author olli */ public class TopicsDirective implements Directive { private ArrayList<ResultRow> result; public TopicsDirective(Locator resultType,Locator resultRole,Locator ... topics) { result=new ArrayList<ResultRow>(); for(int i=0;i<topics.length;i++){ ResultRow r=new ResultRow(resultType,resultRole,topics[i]); result.add(r); } } public TopicsDirective(String resultType,String resultRole,String ... topics) { this(new Locator(resultType),new Locator(resultRole),makeLocatorArray(topics)); } public TopicsDirective(Locator ... topics) { this(new Locator(XTMPSI.TOPIC),new Locator(XTMPSI.TOPIC),topics); } public TopicsDirective(String ... topics) { this(XTMPSI.TOPIC,XTMPSI.TOPIC,topics); } public TopicsDirective(String topic1) { this(new String[]{topic1}); } public TopicsDirective(String topic1,String topic2) { this(new String[]{topic1,topic2}); } public TopicsDirective(String topic1,String topic2,String topic3) { this(new String[]{topic1,topic2,topic3}); } private static Locator[] makeLocatorArray(String[] topics){ Locator[] ret=new Locator[topics.length]; for(int i=0;i<topics.length;i++){ ret[i]=new Locator(topics[i]); } return ret; } public ArrayList<ResultRow> query(QueryContext context) throws TopicMapException { return result; } public boolean isContextSensitive(){ return false; } }
2,664
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
IsOfTypeDirective.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query/IsOfTypeDirective.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * IsOfTypeDirective.java * * Created on 25. lokakuuta 2007, 11:30 * */ package org.wandora.query; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * @deprecated * * @author olli */ public class IsOfTypeDirective extends FilterDirective { private Locator typeContext; private Locator type; /** Creates a new instance of IsOfTypeDirective */ public IsOfTypeDirective(Directive query,Locator typeContext,Locator type,boolean not) { super(query,not); this.query=query; this.typeContext=typeContext; this.type=type; this.not=not; } public IsOfTypeDirective(Directive query,Locator typeContext,Locator type) { this(query,typeContext,type,false); } public IsOfTypeDirective(Directive query,String typeContext,String type,boolean not) { this(query,new Locator(typeContext),new Locator(type),not); } public IsOfTypeDirective(Directive query,String typeContext,String type) { this(query,typeContext,type,false); } public Object startQuery(QueryContext context) throws TopicMapException { TopicMap tm=context.getContextTopic().getTopicMap(); Topic typeTopic=tm.getTopic(type); return typeTopic; } protected int _includeRow(ResultRow row,Topic context,TopicMap tm,Object param) throws TopicMapException { if(param==null) return RES_EXCLUDE; Topic typeTopic=(Topic)param; Locator p=row.getPlayer(typeContext); if(p==null) return RES_EXCLUDE; Topic player=tm.getTopic(p); if(player==null) return RES_IGNORE; return (player.isOfType(typeTopic)?RES_INCLUDE:RES_EXCLUDE); } }
2,635
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
FilterDirective.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query/FilterDirective.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * FilterDirective.java * * Created on 29. lokakuuta 2007, 9:49 * */ package org.wandora.query; import java.util.ArrayList; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * @deprecated * * @author olli */ public abstract class FilterDirective implements Directive { public static final int RES_INCLUDE=1; // include unless not public static final int RES_EXCLUDE=-1; // exclude unless not public static final int RES_IGNORE=0; // do not include, regardless of value of not protected Directive query; protected boolean not; /** Creates a new instance of FilterDirective */ public FilterDirective(Directive query,boolean not) { this.query=query; this.not=not; } /** * Called when evaluation of this filter query is about to start. The return value is passed * as a parameter to _includeRow and endQuery later. Returning a null value should mean that * _includeRow will return RES_EXCLUDE for all rows. So if you don't need a parameter object, * just return any object (this, new Object() or whatever) and simply ignore it later. */ public Object startQuery(QueryContext context) throws TopicMapException {return new Object();} /** * Called when query evaluation is done. If startQuery returned null, this method might not be * called. */ public void endQuery(QueryContext context,Object param) throws TopicMapException {} /** * Return one of RES_INCLUDE, RES_EXCLUDE or RES_INGORE to indicate how to filter the * row. RES_INCLUDE means that the row should be included in the resurt except when * negation if query is desired. RES_EXCLUDE is the opposite, row is not included except * in the case of negation. RES_IGNORE means that row is not included regardless of query * being evaluated in negation mode or not. This can be because for example the association * doesn't have the assumed players. */ protected abstract int _includeRow(ResultRow row,Topic context,TopicMap tm,Object param) throws TopicMapException ; public boolean includeRow(ResultRow row,Topic context,TopicMap tm,Object param) throws TopicMapException { int r=_includeRow(row,context,tm,param); return ((r==1)!=not && r!=0); } public ArrayList<ResultRow> query(QueryContext context) throws TopicMapException { Object param=startQuery(context); if(param==null && !not) return new ArrayList<ResultRow>(); if(query instanceof JoinDirective){ ArrayList<ResultRow> result=((JoinDirective)query).query(context,this,param); endQuery(context,param); return result; } else{ ArrayList<ResultRow> inner=query.query(context); ArrayList<ResultRow> result=new ArrayList<ResultRow>(); Topic contextTopic=context.getContextTopic(); TopicMap tm=contextTopic.getTopicMap(); for(ResultRow row : inner){ if(includeRow(row,contextTopic,tm,param)) result.add(row); } endQuery(context,param); return result; } } public boolean isContextSensitive(){ return query.isContextSensitive(); } }
4,162
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ContextIsOfTypeDirective.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query/ContextIsOfTypeDirective.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * ContextIsOfTypeDirective.java * * Created on 25. lokakuuta 2007, 15:07 * */ package org.wandora.query; import java.util.ArrayList; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * @deprecated * * @author olli */ public class ContextIsOfTypeDirective implements Directive { private Locator type; private Directive query; private boolean not; /** Creates a new instance of ContextIsOfTypeDirective */ public ContextIsOfTypeDirective(Directive query,Locator type,boolean not) { this.query=query; this.type=type; this.not=not; } public ContextIsOfTypeDirective(Directive query,Locator type) { this(query,type,false); } public ContextIsOfTypeDirective(Directive query,String type,boolean not) { this(query,new Locator(type),not); } public ContextIsOfTypeDirective(Directive query,String type) { this(query,type,false); } public ArrayList<ResultRow> query(QueryContext context) throws TopicMapException { Topic contextTopic=context.getContextTopic(); TopicMap tm=contextTopic.getTopicMap(); Topic typeTopic=tm.getTopic(type); if(typeTopic==null) return new ArrayList<ResultRow>(); if(contextTopic.isOfType(typeTopic)==not) return new ArrayList<ResultRow>(); return query.query(context); } public boolean isContextSensitive(){ return true; } }
2,375
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
QueryContext.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query/QueryContext.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * QueryContext.java * * Created on 1. helmikuuta 2008, 13:07 * */ package org.wandora.query; import java.util.HashMap; import org.wandora.topicmap.Topic; /** * @deprecated * * @author olli */ public class QueryContext { private Topic topic; private String lang; private HashMap<String,Object> parameters; /** Creates a new instance of QueryContext */ public QueryContext(Topic topic,String lang,HashMap<String,Object> parameters) { this.topic=topic; this.lang=lang; this.parameters=parameters; } public QueryContext(Topic topic,String lang) { this(topic,lang,new HashMap<String,Object>()); } public Object getParameter(String key){ return parameters.get(key); } public void setParameter(String key,Object o){ parameters.put(key,o); } public Topic getContextTopic(){ return topic; } public String getContextLanguage(){ return lang; } public QueryContext makeNewWithTopic(Topic t){ return new QueryContext(t,lang,parameters); } }
1,926
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
CountDirective.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query/CountDirective.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * CountDirective.java * * Created on 26. marraskuuta 2007, 10:09 * */ package org.wandora.query; import java.util.ArrayList; import org.wandora.topicmap.Locator; import org.wandora.topicmap.TopicMapException; /** * @deprecated * * @author olli */ public class CountDirective implements Directive { private Directive query; private Locator type; private Locator role; public static final String TYPE_SI="http://wandora.org/si/query/counttype"; public static final String ROLE_SI="http://wandora.org/si/query/countrole"; /** Creates a new instance of CountDirective */ public CountDirective(Directive query) { this(query,TYPE_SI,ROLE_SI); } public CountDirective(Directive query,Locator type,Locator role) { this.query=query; this.type=type; this.role=role; } public CountDirective(Directive query,String type,String role) { this(query,new Locator(type),new Locator(role)); } public ArrayList<ResultRow> query(QueryContext context) throws TopicMapException { ArrayList<ResultRow> inner=query.query(context); ArrayList<ResultRow> res=new ArrayList<ResultRow>(); res.add(new ResultRow(type,role,""+inner.size())); return res; } public boolean isContextSensitive(){ return query.isContextSensitive(); } }
2,172
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
OccurrenceDirective.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query/OccurrenceDirective.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * OccurrenceDirective.java * * */ package org.wandora.query; import java.util.ArrayList; import java.util.HashSet; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public class OccurrenceDirective implements Directive { private Locator occurrenceRole; private Locator occurrenceType; private Locator occurrenceVersion; public static final String OCCURRENCE_SI="http://wandora.org/si/query/occurrence"; public OccurrenceDirective(Locator occurrenceType,Locator occurrenceVersion,Locator occurrenceRole) { this.occurrenceType=occurrenceType; this.occurrenceVersion=occurrenceVersion; this.occurrenceRole=occurrenceRole; } public OccurrenceDirective(Locator occurrenceType,Locator occurrenceVersion) { this(occurrenceType,occurrenceVersion,new Locator(OCCURRENCE_SI)); } public OccurrenceDirective(String occurrenceType,String occurrenceVersion,String occurrenceRole) { this(new Locator(occurrenceType),new Locator(occurrenceVersion),new Locator(occurrenceRole)); } public OccurrenceDirective(String occurrenceType,String occurrenceVersion) { this(new Locator(occurrenceType),new Locator(occurrenceVersion),new Locator(OCCURRENCE_SI)); } public ArrayList<ResultRow> query(QueryContext context) throws TopicMapException { Topic contextTopic=context.getContextTopic(); TopicMap tm=contextTopic.getTopicMap(); ArrayList<ResultRow> res=new ArrayList<ResultRow>(); String occurrence=null; Topic t=tm.getTopic(occurrenceType); Topic v=tm.getTopic(occurrenceVersion); if(t!=null && v!=null){ HashSet<Topic> scope=new HashSet<Topic>(); scope.add(t); scope.add(v); occurrence=contextTopic.getData(t, v); } res.add(new ResultRow(occurrenceRole,occurrenceRole,occurrence)); return res; } public boolean isContextSensitive(){ return true; } }
2,928
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TypesOfDirective.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query/TypesOfDirective.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.query; import java.util.ArrayList; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.XTMPSI; /** * @deprecated * * @author olli */ public class TypesOfDirective implements Directive { private Locator role; public TypesOfDirective() { this(XTMPSI.CLASS); } public TypesOfDirective(String role) { this(new Locator(role)); } public TypesOfDirective(Locator role) { this.role=role; } public ArrayList<ResultRow> query(QueryContext context) throws TopicMapException { Topic contextTopic=context.getContextTopic(); TopicMap tm=contextTopic.getTopicMap(); ArrayList<ResultRow> res=new ArrayList<ResultRow>(); for(Topic t : contextTopic.getTypes()){ res.add(new ResultRow(role,role,t.getOneSubjectIdentifier())); } return res; } public boolean isContextSensitive(){ return true; } }
1,896
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
UnionDirective.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query/UnionDirective.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * UnionDirective.java * * Created on 8. helmikuuta 2008, 15:48 * */ package org.wandora.query; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashSet; import org.wandora.topicmap.TopicMapException; /** * @deprecated * * @author olli */ public class UnionDirective implements Directive { private Directive[] directives; private boolean removeDuplicates; /** Creates a new instance of UnionDirective */ public UnionDirective(Directive[] ds) { this(ds,true); } public UnionDirective(Directive[] ds,boolean removeDuplicates) { directives=ds; this.removeDuplicates=removeDuplicates; } public UnionDirective(Collection<Directive> ds) { this(ds.toArray(new Directive[ds.size()])); } public UnionDirective(Directive d1) { this(new Directive[]{d1}); } public UnionDirective(Directive d1,Directive d2) { this(new Directive[]{d1,d2}); } public UnionDirective(Directive d1,Directive d2,Directive d3) { this(new Directive[]{d1,d2,d3}); } public UnionDirective(Directive d1,Directive d2,Directive d3,Directive d4) { this(new Directive[]{d1,d2,d3,d4}); } public UnionDirective(Directive d1,Directive d2,Directive d3,Directive d4,Directive d5) { this(new Directive[]{d1,d2,d3,d4,d5}); } public static void joinResults(ArrayList<ResultRow> dest,ArrayList<ResultRow> source){ // TODO do something smart if results have different roles dest.addAll(source); } public static ArrayList<ResultRow> removeDuplicates(ArrayList<ResultRow> r){ LinkedHashSet<ResultRow> s=new LinkedHashSet<ResultRow>(r); return new ArrayList<ResultRow>(s); } public ArrayList<ResultRow> query(QueryContext context) throws TopicMapException { ArrayList<ResultRow> rows=new ArrayList<ResultRow>(); for(int i=0;i<directives.length;i++){ joinResults(rows,directives[i].query(context)); } if(removeDuplicates) rows=removeDuplicates(rows); return rows; } public boolean isContextSensitive(){ for(int i=0;i<directives.length;i++){ if(directives[i].isContextSensitive()) return true; } return false; } }
3,130
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ExistsDirective.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query/ExistsDirective.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * ExistsDirective.java * * Created on 20. helmikuuta 2008, 14:35 * */ package org.wandora.query; import java.util.ArrayList; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * @deprecated * * @author olli */ public class ExistsDirective extends FilterDirective { private Directive existsDirective; private Locator typeContext; /** Creates a new instance of ExistsDirective */ public ExistsDirective(Directive query,Locator typeContext,Directive exists,boolean not) { super(query,not); this.typeContext=typeContext; this.existsDirective=exists; } public ExistsDirective(Directive query,Locator typeContext,Directive exists) { this(query,typeContext,exists,false); } public ExistsDirective(Directive query,String typeContext,Directive exists,boolean not) { this(query,new Locator(typeContext),exists,not); } public ExistsDirective(Directive query,String typeContext,Directive exists) { this(query,new Locator(typeContext),exists,false); } public Object startQuery(QueryContext context) throws TopicMapException { return context; } protected int _includeRow(ResultRow row,Topic context,TopicMap tm,Object param) throws TopicMapException { if(param==null) return RES_EXCLUDE; QueryContext qContext=(QueryContext)param; Locator p=row.getPlayer(typeContext); if(p==null) return RES_EXCLUDE; Topic player=tm.getTopic(p); if(player==null) return RES_IGNORE; ArrayList<ResultRow> res=existsDirective.query(qContext.makeNewWithTopic(player)); return (res.isEmpty()?RES_EXCLUDE:RES_INCLUDE); } // Note no need to override isContextSensitive. existsDirective doesn't affect // context sensitivity for same reason as in joinDirective. }
2,779
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AndDirective.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query/AndDirective.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * AndDirective.java * * Created on 29. lokakuuta 2007, 13:15 * */ package org.wandora.query; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * @deprecated * * @author olli */ public class AndDirective extends FilterDirective { private FilterDirective[] filters; /** Creates a new instance of AndDirective */ public AndDirective(Directive query,boolean not,FilterDirective ... filters) { super(query,not); this.filters=filters; } public AndDirective(Directive query,boolean not,FilterDirective filter1) { this(query,not,new FilterDirective[]{filter1}); } public AndDirective(Directive query,boolean not,FilterDirective filter1,FilterDirective filter2) { this(query,not,new FilterDirective[]{filter1,filter2}); } public AndDirective(Directive query,boolean not,FilterDirective filter1,FilterDirective filter2,FilterDirective filter3) { this(query,not,new FilterDirective[]{filter1,filter2,filter3}); } public AndDirective(Directive query,boolean not,FilterDirective filter1,FilterDirective filter2,FilterDirective filter3,FilterDirective filter4) { this(query,not,new FilterDirective[]{filter1,filter2,filter3,filter4}); } public Object startQuery(QueryContext context) throws TopicMapException { Object[] params=new Object[filters.length]; for(int i=0;i<filters.length;i++){ params[i]=filters[i].startQuery(context); } return params; } public void endQuery(QueryContext context, Object param) throws TopicMapException { Object[] params=(Object[])param; for(int i=0;i<filters.length;i++){ filters[i].endQuery(context,params[i]); } } protected int _includeRow(ResultRow row, Topic context, TopicMap tm, Object param) throws TopicMapException { Object[] params=(Object[])param; boolean ignore=true; for(int i=0;i<filters.length;i++){ int r=filters[i]._includeRow(row,context,tm,params[i]); if(r==RES_EXCLUDE) return RES_EXCLUDE; else if(r==RES_INCLUDE) ignore=false; } if(ignore) return RES_IGNORE; else return RES_INCLUDE; } public boolean isContextSensitive(){ for(int i=0;i<filters.length;i++){ if(filters[i].isContextSensitive()) return true; } return super.isContextSensitive(); } }
3,320
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
JoinDirective.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query/JoinDirective.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * JoinDirective.java * * Created on 25. lokakuuta 2007, 11:38 * */ package org.wandora.query; import java.util.ArrayList; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * @deprecated * * @author olli */ public class JoinDirective implements Directive { private Directive query; private Locator joinContext; private Directive joinQuery; /** Creates a new instance of JoinDirective */ public JoinDirective(Directive query,Directive joinQuery) { this(query,(Locator)null,joinQuery); } public JoinDirective(Directive query,Locator joinContext,Directive joinQuery) { this.query=query; this.joinContext=joinContext; this.joinQuery=joinQuery; } public JoinDirective(Directive query,String joinContext,Directive joinQuery) { this(query,new Locator(joinContext),joinQuery); } public ArrayList<ResultRow> query(QueryContext context) throws TopicMapException { return query(context,null,null); } public ArrayList<ResultRow> query(QueryContext context,FilterDirective filter,Object filterParam) throws TopicMapException { Topic contextTopic=context.getContextTopic(); TopicMap tm=contextTopic.getTopicMap(); ArrayList<ResultRow> inner=query.query(context); ArrayList<ResultRow> res=new ArrayList<ResultRow>(); ArrayList<ResultRow> cachedJoin=null; boolean useCache=!joinQuery.isContextSensitive(); for(ResultRow row : inner){ Topic t=null; if(joinContext!=null){ Locator c=row.getPlayer(joinContext); if(c==null) continue; t=tm.getTopic(c); } else t=context.getContextTopic(); if(t==null) continue; ArrayList<ResultRow> joinRes; if(!useCache || cachedJoin==null){ joinRes=joinQuery.query(context.makeNewWithTopic(t)); if(useCache) cachedJoin=joinRes; } else joinRes=cachedJoin; for(ResultRow joinRow : joinRes){ ResultRow joined=ResultRow.joinRows(row,joinRow); if(filter!=null && !filter.includeRow(joined, contextTopic, tm, filterParam)) continue; res.add(joined); } } return res; } public boolean isContextSensitive(){ return query.isContextSensitive(); // note joinQuery gets context from query so it's sensitivity is same // as that of query } }
3,462
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
RolesDirective.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query/RolesDirective.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * RolesDirective.java * * Created on 25. lokakuuta 2007, 12:13 * */ package org.wandora.query; import java.util.ArrayList; import org.wandora.topicmap.Locator; import org.wandora.topicmap.TopicMapException; /** * @deprecated * * @author olli */ public class RolesDirective implements Directive { private ArrayList<Locator> roles; private Directive query; /** Creates a new instance of RolesDirective * * roles may contain Strings or Locators */ public RolesDirective(Directive query,ArrayList roles) { this.query=query; this.roles=new ArrayList<Locator>(); for(Object o : roles){ if(o instanceof Locator) this.roles.add((Locator)o); else this.roles.add(new Locator((String)o)); } } public RolesDirective(Directive query,Object ... roles){ this.query=query; this.roles=new ArrayList<Locator>(); for(int i=0;i<roles.length;i++){ if(roles[i] instanceof Locator) this.roles.add((Locator)roles[i]); else this.roles.add(new Locator((String)roles[i])); } } public RolesDirective(Directive query,String role1){ this(query,new Object[]{role1}); } public RolesDirective(Directive query,String role1,String role2){ this(query,new Object[]{role1,role2}); } public RolesDirective(Directive query,String role1,String role2,String role3){ this(query,new Object[]{role1,role2,role3}); } public ArrayList<ResultRow> query(QueryContext context) throws TopicMapException { ArrayList<ResultRow> inner=query.query(context); ArrayList<ResultRow> res=new ArrayList<ResultRow>(); for(ResultRow row : inner){ ArrayList<Object> newValues=new ArrayList<Object>(); ArrayList<Locator> newRoles=new ArrayList<Locator>(); for(Locator r : roles){ Object p=row.getValue(r); newValues.add(p); newRoles.add(r); } res.add(new ResultRow(row.getType(),newRoles,newValues)); } return res; } public boolean isContextSensitive(){ return query.isContextSensitive(); } }
3,071
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ResultRow.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query/ResultRow.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * ResultRow.java * * Created on 25. lokakuuta 2007, 11:05 * */ package org.wandora.query; import java.util.ArrayList; import java.util.List; import org.wandora.topicmap.Locator; /** * @deprecated * * @author olli */ public class ResultRow { private Locator type; private ArrayList<Locator> roles; private ArrayList<Object> values; private int hashCode=-1; /** Creates a new instance of ResultRow */ public ResultRow(Locator type,List<Locator> roles,List<Object> values) { this.type=type; this.roles=new ArrayList<Locator>(roles); this.values=new ArrayList<Object>(values); } // firstRole and firstPlayer to make clearly different method signatures public ResultRow(Locator type,Locator firstRole,Object firstPlayer,Object ... rolesAndValues) { this.type=type; roles=new ArrayList<Locator>(); values=new ArrayList<Object>(); roles.add(firstRole); values.add(firstPlayer); for(int i=0;i+1<rolesAndValues.length;i+=2){ roles.add((Locator)rolesAndValues[i]); values.add(rolesAndValues[i+1]); } } public static ResultRow joinRows(ResultRow ... rows){ Locator type=rows[0].type; ArrayList<Locator> roles=new ArrayList<Locator>(rows[0].roles); ArrayList<Object> values=new ArrayList<Object>(rows[0].values); for(int i=1;i<rows.length;i++){ type=rows[i].type; for(int j=0;j<rows[i].roles.size();j++){ Locator r=rows[i].roles.get(j); int rIndex=roles.indexOf(r); if(rIndex==-1){ roles.add(r); values.add(rows[i].values.get(j)); } else{ values.set(rIndex,rows[i].values.get(j)); } } } return new ResultRow(type,roles,values); } public Locator getType(){return type;} public int getNumValues(){return values.size();} public Locator getPlayer(int index){ Object o=values.get(index); if(o instanceof Locator) return (Locator)o; else return null; } public String getText(int index){ Object o=values.get(index); if(o instanceof String) return (String)o; else return null; } public Object getValue(int index){return values.get(index);} public Locator getRole(int index){return roles.get(index);} public Locator getPlayer(Locator role){ Object o=getValue(role); if(o!=null && o instanceof Locator) return (Locator)o; else return null; } public String getText(Locator role){ Object o=getValue(role); if(o!=null && o instanceof String) return (String)o; else return null; } public Object getValue(Locator role){ int index=roles.indexOf(role); if(index==-1) return null; else return values.get(index); } public ArrayList<Object> getValues() { return values; } public int hashCode(){ if(hashCode==-1) hashCode = type.hashCode()+roles.hashCode()+values.hashCode(); return hashCode; } public boolean equals(Object o){ if(!(o instanceof ResultRow)) return false; ResultRow r=(ResultRow)o; if(r==this) return true; if(hashCode()!=r.hashCode()) return false; return r.type.equals(this.type) && r.roles.equals(this.roles) && r.values.equals(this.values); } }
4,361
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
InstancesDirective.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query/InstancesDirective.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * InstancesDirective.java * * Created on 18. tammikuuta 2008, 14:58 * */ package org.wandora.query; import java.util.ArrayList; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.XTMPSI; /** * @deprecated * * @author olli */ public class InstancesDirective implements Directive { private Locator role; /** Creates a new instance of InstancesDirective */ public InstancesDirective() { this(XTMPSI.INSTANCE); } public InstancesDirective(String role) { this(new Locator(role)); } public InstancesDirective(Locator role) { this.role=role; } public ArrayList<ResultRow> query(QueryContext context) throws TopicMapException { Topic contextTopic=context.getContextTopic(); TopicMap tm=contextTopic.getTopicMap(); ArrayList<ResultRow> res=new ArrayList<ResultRow>(); for(Topic t : tm.getTopicsOfType(contextTopic)){ res.add(new ResultRow(role,role,t.getOneSubjectIdentifier())); } return res; } public boolean isContextSensitive(){ return true; } }
2,062
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
RecursiveDirective.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query/RecursiveDirective.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * RecursiveDirective.java * * Created on 11. helmikuuta 2008, 13:50 */ package org.wandora.query; import java.util.ArrayList; import java.util.HashSet; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * @deprecated * * @author olli */ public class RecursiveDirective implements Directive { private Directive recursion; private Locator recursionContext; private Locator recursionSourceContext; private int maxDepth; private boolean onlyLast; private boolean removeDuplicates; /** Creates a new instance of RecursiveDirective */ public RecursiveDirective(Directive recursion,Locator recursionContext,int maxDepth,boolean onlyLast,boolean removeDuplicates) { this.recursion=recursion; this.recursionContext=recursionContext; this.maxDepth=maxDepth; this.onlyLast=onlyLast; this.removeDuplicates=removeDuplicates; } public RecursiveDirective(Directive recursion,Locator recursionContext) { this(recursion,recursionContext,-1,false,true); } public RecursiveDirective(Directive recursion,String recursionContext) { this(recursion,new Locator(recursionContext)); } public RecursiveDirective(Directive recursion,String recursionContext,int maxDepth,boolean onlyLast,boolean removeDuplicates) { this(recursion,new Locator(recursionContext),maxDepth,onlyLast,removeDuplicates); } public ArrayList<ResultRow> query(QueryContext context) throws TopicMapException { TopicMap tm=context.getContextTopic().getTopicMap(); HashSet<Locator> processed=new HashSet<Locator>(); ArrayList<ResultRow> res=new ArrayList<ResultRow>(); ArrayList<ResultRow> next=null; int depth=0; while(true){ if(next==null) next=recursion.query(context); else { ArrayList<ResultRow> res2=new ArrayList<ResultRow>(); for(ResultRow r : next){ Locator l=r.getPlayer(recursionContext); if(l!=null){ if(processed.contains(l)) continue; processed.add(l); Topic t=tm.getTopic(l); if(t!=null) { ArrayList<ResultRow> res3=recursion.query(context.makeNewWithTopic(t)); if(onlyLast && res3.size()==0) res.add(r); res2.addAll(res3); } } } next=res2; } if(!onlyLast) res.addAll(next); depth++; if(maxDepth!=-1 && depth>=maxDepth) break; if(next.isEmpty()) break; } if(removeDuplicates) res=UnionDirective.removeDuplicates(res); return res; } public boolean isContextSensitive(){ return recursion.isContextSensitive(); } }
3,843
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
BaseNameDirective.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query/BaseNameDirective.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * BaseNameDirective.java * * */ package org.wandora.query; import java.util.ArrayList; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public class BaseNameDirective implements Directive { private Locator nameRole; public static final String NAME_SI="http://wandora.org/si/query/basename"; public BaseNameDirective() { this(NAME_SI); } public BaseNameDirective(Locator nameRole) { this.nameRole=nameRole; } public BaseNameDirective(String nameRole) { this(new Locator(nameRole)); } public ArrayList<ResultRow> query(QueryContext context) throws TopicMapException { Topic contextTopic=context.getContextTopic(); TopicMap tm=contextTopic.getTopicMap(); ArrayList<ResultRow> res=new ArrayList<ResultRow>(); res.add(new ResultRow(nameRole,nameRole,contextTopic.getBaseName())); return res; } public boolean isContextSensitive(){ return true; } }
1,914
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AllTopicsDirective.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query/AllTopicsDirective.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * AllTopicsDirective.java * * Created on 4. tammikuuta 2008, 14:09 * */ package org.wandora.query; import java.util.ArrayList; import java.util.Iterator; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.XTMPSI; /** * @deprecated * * @author olli */ public class AllTopicsDirective implements Directive { private Locator resultType; private Locator resultRole; /** Creates a new instance of AllTopicsDirective */ public AllTopicsDirective(Locator resultType,Locator resultRole) { this.resultType=resultType; this.resultRole=resultRole; } public AllTopicsDirective(String resultType,String resultRole) { this(new Locator(resultType),new Locator(resultRole)); } public AllTopicsDirective() { this(new Locator(XTMPSI.TOPIC),new Locator(XTMPSI.TOPIC)); } public ArrayList<ResultRow> query(TopicMap tm,QueryContext context) throws TopicMapException { Iterator<Topic> iter=tm.getTopics(); ArrayList<ResultRow> res=new ArrayList<ResultRow>(); while(iter.hasNext()){ Topic t=iter.next(); ResultRow r=new ResultRow(resultType,resultRole,t.getOneSubjectIdentifier()); res.add(r); } return res; } public ArrayList<ResultRow> query(QueryContext context) throws TopicMapException { return query(context.getContextTopic().getTopicMap(),context); } public boolean isContextSensitive(){ return false; } }
2,444
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SortDirective.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query/SortDirective.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * SortDirective.java * * Created on 1. marraskuuta 2007, 15:02 */ package org.wandora.query; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * @deprecated * * @author olli */ public class SortDirective implements Directive { private Directive query; private ArrayList<Locator> sortColumns; private boolean descending; /** Creates a new instance of SortDirective */ public SortDirective(Directive query,ArrayList sortColumns,boolean descending) { this.query=query; this.sortColumns=new ArrayList<Locator>(); for(Object o : sortColumns){ if(o instanceof Locator) this.sortColumns.add((Locator)o); else this.sortColumns.add(new Locator((String)o)); } this.descending=descending; } public SortDirective(Directive query,Locator sortColumn,boolean descending) { this(query,QueryTools.makeLocatorArray(sortColumn),descending); } public SortDirective(Directive query,String sortColumn,boolean descending) { this(query,QueryTools.makeLocatorArray(sortColumn),descending); } public SortDirective(Directive query,Locator sortColumn) { this(query,QueryTools.makeLocatorArray(sortColumn),false); } public SortDirective(Directive query,String sortColumn) { this(query,QueryTools.makeLocatorArray(sortColumn),false); } public ArrayList<ResultRow> query(QueryContext context) throws TopicMapException { ArrayList<ResultRow> inner=query.query(context); ArrayList<ResultRow> res=new ArrayList<ResultRow>(inner); Collections.sort(res,new RowComparator(context.getContextTopic().getTopicMap(),context.getContextLanguage())); return res; } private class RowComparator implements Comparator<ResultRow> { public TopicMap tm; public String lang; public HashMap<Locator,String> nameCache; public RowComparator(TopicMap tm,String lang){ this.tm=tm; this.lang=lang; this.nameCache=new HashMap<Locator,String>(); } public int compare(ResultRow o1, ResultRow o2) { return compare(o1,o2,tm,lang); } public int compare(ResultRow o1, ResultRow o2,TopicMap tm,String lang) { for(Locator sortColumn : sortColumns){ try{ int r=compareRoles(o1,o2,sortColumn,tm,lang); if(r!=0) return (descending?-r:r); } catch(TopicMapException tme){ tme.printStackTrace(); break; } } return 0; } public int compareRoles(ResultRow o1, ResultRow o2, Locator role,TopicMap tm,String lang) throws TopicMapException { Object p1=o1.getValue(role); Object p2=o2.getValue(role); if(p1==null){ if(p2==null) return 0; else return -1; } else if(p2==null){ return 1; } if(p1 instanceof String){ if(p2 instanceof String){ return ((String)p1).compareTo((String)p2); } else return -1; } else if(p2 instanceof String) return 1; Topic t1=tm.getTopic((Locator)p1); Topic t2=tm.getTopic((Locator)p2); if(t1==null){ if(t2==null) return 0; else return -1; } else if(t2==null){ return 1; } String n1=nameCache.get((Locator)p1); String n2=nameCache.get((Locator)p2); if(n1==null) { n1=t1.getSortName(lang); nameCache.put((Locator)p1,n1); } if(n2==null) { n2=t2.getSortName(lang); nameCache.put((Locator)p2,n2); } if(n1==null){ if(n2==null) return 0; else return -1; } else if(n2==null){ return 1; } return n1.compareTo(n2); } } public boolean isContextSensitive(){ return query.isContextSensitive(); } }
5,352
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SelectDirective.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query/SelectDirective.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * SelectDirective.java * * Created on 25. lokakuuta 2007, 11:04 */ package org.wandora.query; import java.util.ArrayList; import java.util.Collection; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.utils.GripCollections; /** * @deprecated * * @author olli */ public class SelectDirective implements Directive { private Locator type; private Locator rewriteType; private ArrayList<Locator> roles; private ArrayList<Locator> rewriteRoles; /** Creates a new instance of SelectDirective */ public SelectDirective(Locator type,Collection<Locator> roles) { this.type=type; this.roles=new ArrayList<Locator>(roles); processTempRoles(); } public SelectDirective(String type,Collection<String> roles) { this(new Locator(type),QueryTools.makeLocatorArray(roles)); } public SelectDirective(String type,String ... roles){ this(new Locator(type),QueryTools.makeLocatorArray(GripCollections.arrayToCollection(roles))); } public SelectDirective(String type,String role1){ this(type,new String[]{role1}); } public SelectDirective(String type,String role1,String role2){ this(type,new String[]{role1,role2}); } public SelectDirective(String type,String role1,String role2,String role3){ this(type,new String[]{role1,role2,role3}); } public SelectDirective(Locator type,Collection<Locator> roles,Collection<Locator> rewriteRoles) { this(type,roles); this.rewriteRoles=new ArrayList<Locator>(rewriteRoles); } public SelectDirective(String type,Collection<String> roles,Collection<String> rewriteRoles) { this(new Locator(type),QueryTools.makeLocatorArray(roles),QueryTools.makeLocatorArray(rewriteRoles)); } public SelectDirective(Locator type,Locator rewriteType,Collection<Locator> roles,Collection<Locator> rewriteRoles) { this(type,roles,rewriteRoles); this.rewriteType=rewriteType; } public SelectDirective(String type,String rewriteType,Collection<String> roles,Collection<String> rewriteRoles) { this(new Locator(type),rewriteType==null?null:new Locator(rewriteType),QueryTools.makeLocatorArray(roles),QueryTools.makeLocatorArray(rewriteRoles)); } private void processTempRoles(){ boolean process=false; for(Locator l : roles) if(l.toString().startsWith("~") /*|| l.toString().startsWith("|")*/) { process=true; break; } if(!process) return; this.rewriteRoles=new ArrayList<Locator>(); ArrayList<Locator> newRoles=new ArrayList<Locator>(); for(Locator l : roles){ rewriteRoles.add(l); if(l.toString().startsWith("~")) newRoles.add(new Locator(l.toString().substring(1))); // if(l.toString().startsWith("|")) newRoles.add(new Locator(l.toString().substring(1))); else newRoles.add(l); } this.roles=newRoles; } public ArrayList<ResultRow> query(QueryContext context) throws TopicMapException { Topic contextTopic=context.getContextTopic(); TopicMap tm=contextTopic.getTopicMap(); Topic typeTopic=tm.getTopic(type); if(typeTopic==null) return new ArrayList<ResultRow>(); ArrayList<Topic> roleTopics=new ArrayList<Topic>(); for(Locator r : roles){ Topic role=tm.getTopic(r); if(role==null) return new ArrayList<ResultRow>(); roleTopics.add(role); } Collection<Association> associations=contextTopic.getAssociations(typeTopic); ArrayList<ResultRow> results=new ArrayList<ResultRow>(); AssociationLoop: for(Association a : associations){ ArrayList<Object> players=new ArrayList<Object>(); for(int i=0;i<roleTopics.size();i++){ Topic role=roleTopics.get(i); Topic player=a.getPlayer(role); /* if(player==null) { if(rewriteRoles==null || !rewriteRoles.get(i).toString().startsWith("|")) continue AssociationLoop; }*/ players.add(player==null?null:player.getOneSubjectIdentifier()); } ResultRow row=new ResultRow(rewriteType!=null?rewriteType:type, rewriteRoles!=null?rewriteRoles:roles, players); results.add(row); } return results; } public boolean isContextSensitive(){ return true; } }
5,564
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
IsContextTopicDirective.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query/IsContextTopicDirective.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * IsContextTopicDirective.java * * Created on 9. tammikuuta 2008, 15:15 */ package org.wandora.query; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * @deprecated * * @author olli */ public class IsContextTopicDirective extends FilterDirective { private Locator topicContext; private Directive query; /** Creates a new instance of IsContextTopicDirective */ public IsContextTopicDirective(Directive query,Locator topicContext,boolean not) { super(query,not); this.query=query; this.topicContext=topicContext; } public IsContextTopicDirective(Directive query,Locator topicContext) { this(query,topicContext,false); } public IsContextTopicDirective(Directive query,String topicContext,boolean not) { this(query,new Locator(topicContext),not); } public IsContextTopicDirective(Directive query,String topicContext) { this(query,topicContext,false); } protected int _includeRow(ResultRow row,Topic context,TopicMap tm,Object param) throws TopicMapException { Locator p=row.getPlayer(topicContext); if(p==null) return RES_EXCLUDE; Topic player=tm.getTopic(p); if(player==null) return RES_IGNORE; return (player.mergesWithTopic(context)?RES_INCLUDE:RES_EXCLUDE); } public boolean isContextSensitive(){ return true; } }
2,317
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
RegexDirective.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query/RegexDirective.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * RegexDirective.java * * */ package org.wandora.query; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public class RegexDirective implements Directive { public static final int MODE_MATCH=1; public static final int MODE_GLOBAL=2; public static final int MODE_ICASE=4; private Directive inner; private Locator role; private String regex; private String replace; private boolean match; private boolean global; private boolean icase; private Pattern pattern; public RegexDirective(Directive inner,Locator role,String regex,String replace,int mode){ this.inner=inner; this.role=role; this.regex=regex; this.replace=replace; match=((mode&MODE_MATCH)>0); global=((mode&MODE_GLOBAL)>0); icase=((mode&MODE_ICASE)>0); this.pattern=Pattern.compile(regex,icase?Pattern.CASE_INSENSITIVE:0); } public RegexDirective(Directive inner,String role,String regex,String replace,int mode){ this(inner,new Locator(role),regex,replace,mode); } public RegexDirective(Directive inner,Locator role,String regex,String replace){ this(inner,role,regex,replace,MODE_GLOBAL); } public RegexDirective(Directive inner,String role,String regex,String replace){ this(inner,new Locator(role),regex,replace); } public RegexDirective(Directive inner,Locator role,String regex){ this(inner,role,regex,null,MODE_MATCH|MODE_GLOBAL); } public RegexDirective(Directive inner,String role,String regex){ this(inner,new Locator(role),regex); } private ResultRow makeRow(ResultRow original,Locator role,String replacement){ ArrayList<Locator> newRoles=new ArrayList<Locator>(); ArrayList<Object> newValues=new ArrayList<Object>(); for(int i=0;i<original.getNumValues();i++){ Locator r=original.getRole(i); Object v=original.getValue(i); if(r.equals(role)) v=replacement; newRoles.add(r); newValues.add(v); } return new ResultRow(original.getType(),newRoles, newValues); } public ArrayList<ResultRow> query(QueryContext context) throws TopicMapException { Topic contextTopic=context.getContextTopic(); TopicMap tm=contextTopic.getTopicMap(); ArrayList<ResultRow> res=inner.query(context); ArrayList<ResultRow> ret=new ArrayList<ResultRow>(); for(int i=0;i<res.size();i++){ ResultRow row=res.get(i); Object value=row.getValue(role); if(value==null){ if(!match) ret.add(row); } else if(replace!=null){ String s=value.toString(); Matcher m=pattern.matcher(s); if(global) s=m.replaceAll(replace); else s=m.replaceFirst(replace); if(match){ try{ m.group(); ret.add(makeRow(row,role,s)); }catch(IllegalStateException e){} } else ret.add(makeRow(row,role,s)); } else { String s=value.toString(); Matcher m=pattern.matcher(s); if(global) { if(m.matches()) ret.add(makeRow(row,role,s)); } else { if(m.find()) ret.add(makeRow(row,role,s)); } } } return ret; } public boolean isContextSensitive(){ return inner.isContextSensitive(); } }
4,676
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
VariantDirective.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query/VariantDirective.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * VariantDirective.java * * */ package org.wandora.query; import java.util.ArrayList; import java.util.HashSet; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public class VariantDirective implements Directive { private Locator nameRole; private Locator variantType; private Locator variantVersion; public static final String NAME_SI="http://wandora.org/si/query/variantname"; public VariantDirective(Locator variantType,Locator variantVersion,Locator nameRole) { this.variantType=variantType; this.variantVersion=variantVersion; this.nameRole=nameRole; } public VariantDirective(Locator variantType,Locator variantVersion) { this(variantType,variantVersion,new Locator(NAME_SI)); } public VariantDirective(String variantType,String variantVersion,String namerole) { this(new Locator(variantType),new Locator(variantVersion),new Locator(namerole)); } public VariantDirective(String variantType,String variantVersion) { this(new Locator(variantType),new Locator(variantVersion),new Locator(NAME_SI)); } public ArrayList<ResultRow> query(QueryContext context) throws TopicMapException { Topic contextTopic=context.getContextTopic(); TopicMap tm=contextTopic.getTopicMap(); ArrayList<ResultRow> res=new ArrayList<ResultRow>(); Topic t=tm.getTopic(variantType); Topic v=tm.getTopic(variantVersion); String variant=null; if(t!=null && v!=null){ HashSet<Topic> scope=new HashSet<Topic>(); scope.add(t); scope.add(v); variant=contextTopic.getVariant(scope); } res.add(new ResultRow(nameRole,nameRole,variant)); return res; } public boolean isContextSensitive(){ return true; } }
2,773
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
QueryTools.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query/QueryTools.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * QueryTools.java * * Created on 25. lokakuuta 2007, 13:13 * */ package org.wandora.query; import java.util.ArrayList; import java.util.Collection; import org.wandora.topicmap.Locator; /** * @deprecated * * @author olli */ public class QueryTools { public static ArrayList<Locator> makeLocatorArray(Collection<String> a){ if(a==null) return null; ArrayList<Locator> ret=new ArrayList<Locator>(); for(String s : a){ ret.add(new Locator(s)); } return ret; } public static ArrayList<Locator> makeLocatorArray(Locator ... a){ ArrayList<Locator> ret=new ArrayList<Locator>(); for(int i=0;i<a.length;i++){ ret.add(a[i]); } return ret; } public static ArrayList<Locator> makeLocatorArray(String ... a){ ArrayList<Locator> ret=new ArrayList<Locator>(); for(int i=0;i<a.length;i++){ ret.add(new Locator(a[i])); } return ret; } }
1,813
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Directive.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query/Directive.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * Directive.java * * Created on 25. lokakuuta 2007, 11:29 * */ package org.wandora.query; import java.util.ArrayList; import org.wandora.topicmap.TopicMapException; /** * @deprecated * * @author olli */ public interface Directive { public ArrayList<ResultRow> query(QueryContext context) throws TopicMapException; public boolean isContextSensitive(); }
1,187
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
IsTopicDirective.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query/IsTopicDirective.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * IsTopicDirective.java * * Created on 25. lokakuuta 2007, 11:57 * */ package org.wandora.query; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * @deprecated * * @author olli */ public class IsTopicDirective extends FilterDirective { private Locator topicContext; private Locator topic; private Directive query; /** Creates a new instance of IsTopicDirective */ public IsTopicDirective(Directive query,Locator topicContext,Locator topic,boolean not) { super(query,not); this.query=query; this.topicContext=topicContext; this.topic=topic; } public IsTopicDirective(Directive query,Locator topicContext,Locator topic) { this(query,topicContext,topic,false); } public IsTopicDirective(Directive query,String topicContext,String topic,boolean not) { this(query,new Locator(topicContext),new Locator(topic),not); } public IsTopicDirective(Directive query,String topicContext,String topic) { this(query,topicContext,topic,false); } public Object startQuery(QueryContext context) throws TopicMapException { TopicMap tm=context.getContextTopic().getTopicMap(); Topic t=tm.getTopic(topic); return t; } protected int _includeRow(ResultRow row,Topic context,TopicMap tm,Object param) throws TopicMapException { if(param==null) return RES_EXCLUDE; Topic t=(Topic)param; Locator p=row.getPlayer(topicContext); if(p==null) return RES_EXCLUDE; Topic player=tm.getTopic(p); if(player==null) return RES_IGNORE; return (player.mergesWithTopic(t)?RES_INCLUDE:RES_EXCLUDE); } }
2,623
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TransitiveDirective.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query/TransitiveDirective.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.query; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; 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; /** * @deprecated * * @author olli */ public class TransitiveDirective implements Directive { private Locator associationType; private Locator role1; private Locator role2; public TransitiveDirective(Locator associationType,Locator role1,Locator role2){ this.associationType=associationType; this.role1=role1; this.role2=role2; } public TransitiveDirective(String associationType,String role1,String role2){ this(new Locator(associationType),new Locator(role1),new Locator(role2)); } private ArrayList<ResultRow> query(Topic context,Locator atypel,Locator r1l,Locator r2l) throws TopicMapException{ TopicMap tm=context.getTopicMap(); Topic atype=tm.getTopic(atypel); Topic r1=tm.getTopic(r1l); Topic r2=tm.getTopic(r2l); if(atype==null || r1==null || r2==null) return new ArrayList<ResultRow>(); ArrayList<Locator> collected=new ArrayList<Locator>(); HashSet<Locator> processed=new HashSet<Locator>(); ArrayList<Topic> unprocessed=new ArrayList<Topic>(); unprocessed.add(context); while(!unprocessed.isEmpty()){ ArrayList<Topic> next=new ArrayList<Topic>(); for(Topic t : unprocessed){ Collection<Association> as=t.getAssociations(atype, r1); for(Association a : as){ Topic p=a.getPlayer(r2); if(p==null) continue; Locator si=p.getOneSubjectIdentifier(); if(si==null) continue; if(processed.contains(si)) continue; processed.add(si); next.add(p); collected.add(si); } } unprocessed=next; } ArrayList<ResultRow> ret=new ArrayList<ResultRow>(); Locator cl=context.getOneSubjectIdentifier(); for(Locator l : collected){ ResultRow row=new ResultRow(atypel,r1l,cl,r2l,l); ret.add(row); } return ret; } public ArrayList<ResultRow> query(QueryContext context) throws TopicMapException { Topic contextTopic=context.getContextTopic(); TopicMap tm=contextTopic.getTopicMap(); ArrayList<ResultRow> ret=query(contextTopic,associationType,role1,role2); ret.addAll(query(contextTopic,associationType,role2,role1)); return ret; } public boolean isContextSensitive(){ return true; } }
3,650
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
StringsDirective.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query/StringsDirective.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * StringsDirective.java * */ package org.wandora.query; import java.util.ArrayList; import org.wandora.topicmap.Locator; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public class StringsDirective implements Directive { private ArrayList<ResultRow> result; public static final String STRING_SI="http://wandora.org/si/query/string"; public StringsDirective(Locator resultType,Locator resultRole,String ... strings) { if(resultType==null) resultType=new Locator(STRING_SI); if(resultRole==null) resultRole=new Locator(STRING_SI); result=new ArrayList<ResultRow>(); for(int i=0;i<strings.length;i++){ ResultRow r=new ResultRow(resultType,resultRole,strings[i]); result.add(r); } } public StringsDirective(String resultType,String resultRole,String ... strings) { this(resultType==null?null:new Locator(resultType), resultRole==null?null:new Locator(resultRole),strings); } public StringsDirective(String string) { this((Locator)null,(Locator)null,string); } public ArrayList<ResultRow> query(QueryContext context) throws TopicMapException { return result; } public boolean isContextSensitive(){ return false; } }
2,108
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
CompareDirective.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query/CompareDirective.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * CompareDirective.java * * */ package org.wandora.query; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public class CompareDirective extends FilterDirective { public static final int EQ=0; public static final int NE=1; public static final int LT=2; public static final int GT=3; public static final int LE=4; public static final int GE=5; public static final int TOPIC_EQUAL=6; public static final int TOPIC_NEQUAL=7; private Locator role1; private Locator role2; private int comp; private boolean numeric; public CompareDirective(Directive query,Locator role1,int comp,Locator role2,boolean numeric){ super(query,false); this.role1=role1; this.role2=role2; this.comp=comp; this.numeric=numeric; } public CompareDirective(Directive query,Locator role1,String comp,Locator role2,boolean numeric){ this(query,role1,parseComp(comp),role2,numeric); } public CompareDirective(Directive query,Locator role1,String comp,Locator role2){ this(query,role1,parseComp(comp),role2,false); } public CompareDirective(Directive query,Locator role1,Locator role2,boolean numeric){ this(query,role1,EQ,role2,numeric); } public CompareDirective(Directive query,Locator role1,Locator role2){ this(query,role1,EQ,role2,false); } public CompareDirective(Directive query,String role1,int comp,String role2,boolean numeric){ this(query,new Locator(role1),comp,new Locator(role2),numeric); } public CompareDirective(Directive query,String role1,String comp,String role2,boolean numeric){ this(query,role1,parseComp(comp),role2,numeric); } public CompareDirective(Directive query,String role1,String comp,String role2){ this(query,role1,parseComp(comp),role2,false); } public CompareDirective(Directive query,String role1,String role2,boolean numeric){ this(query,role1,EQ,role2,numeric); } public CompareDirective(Directive query,String role1,String role2){ this(query,role1,EQ,role2,false); } public static int parseComp(String comp){ if(comp.equals("=") || comp.equals("==") || comp.equalsIgnoreCase("eq")) return EQ; else if(comp.equals("!=") || comp.equals("<>") || comp.equals("~=") || comp.equalsIgnoreCase("ne") || comp.equalsIgnoreCase("neq")) return NE; else if(comp.equals("<") || comp.equalsIgnoreCase("lt")) return LT; else if(comp.equals(">") || comp.equalsIgnoreCase("gt")) return GT; else if(comp.equals("<=") || comp.equals("le") || comp.equalsIgnoreCase("lte")) return LE; else if(comp.equals(">=") || comp.equals("ge") || comp.equalsIgnoreCase("gte")) return GE; else if(comp.equalsIgnoreCase("topic") || comp.equalsIgnoreCase("te")) return TOPIC_EQUAL; else if(comp.equalsIgnoreCase("notopic") || comp.equalsIgnoreCase("ntopic") || comp.equalsIgnoreCase("te") || comp.equalsIgnoreCase("tne") || comp.equalsIgnoreCase("tn")) return TOPIC_NEQUAL; else return EQ; } protected int _includeRow(ResultRow row,Topic context,TopicMap tm,Object param) throws TopicMapException { Object v1=row.getValue(role1); Object v2=row.getValue(role2); int compare=0; if(numeric){ if(v1!=null) { try{ v1=Double.parseDouble(v1.toString()); }catch(NumberFormatException nfe){v1=null;} } if(v2!=null) { try{ v2=Double.parseDouble(v2.toString()); }catch(NumberFormatException nfe){v2=null;} } if(v1==null && v2==null) compare=0; else if(v1==null && v2!=null) compare=-1; else if(v2!=null && v2==null) compare=1; else compare=Double.compare((Double)v1, (Double)v2); } else if(comp==TOPIC_EQUAL || comp==TOPIC_NEQUAL){ if(v1==null && v2==null) compare=0; else if(v1==null && v2!=null) compare=-1; else if(v2!=null && v2==null) compare=1; else { Topic t1=tm.getTopic((Locator)v1); Topic t2=tm.getTopic((Locator)v2); if(t1==null || t2==null) compare=-1; else if(t1.mergesWithTopic(t2)) compare=0; else compare=1; } } else { if(v1==null && v2==null) compare=0; else if(v1==null && v2!=null) compare=-1; else if(v2!=null && v2==null) compare=1; else compare=v1.toString().compareTo(v2.toString()); } switch(comp){ case EQ: return compare==0?RES_INCLUDE:RES_EXCLUDE; case NE: return compare!=0?RES_INCLUDE:RES_EXCLUDE; case LT: return compare<0?RES_INCLUDE:RES_EXCLUDE; case GT: return compare>0?RES_INCLUDE:RES_EXCLUDE; case LE: return compare<=0?RES_INCLUDE:RES_EXCLUDE; case GE: return compare>=0?RES_INCLUDE:RES_EXCLUDE; case TOPIC_EQUAL: return compare==0?RES_INCLUDE:RES_EXCLUDE; case TOPIC_NEQUAL: return compare!=0?RES_INCLUDE:RES_EXCLUDE; } return RES_EXCLUDE; } }
6,381
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ContextTopicDirective.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query/ContextTopicDirective.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.query; import java.util.ArrayList; import org.wandora.topicmap.Locator; import org.wandora.topicmap.TopicMapException; /** * @deprecated * * @author olli */ public class ContextTopicDirective implements Directive { private Locator resultType; private Locator resultRole; public ContextTopicDirective(Locator resultType,Locator resultRole) { this.resultType=resultType; this.resultRole=resultRole; } public ContextTopicDirective(String resultType,String resultRole){ this(new Locator(resultType),new Locator(resultRole)); } public ArrayList<ResultRow> query(QueryContext context) throws TopicMapException { ArrayList<ResultRow> result=new ArrayList<ResultRow>(); ResultRow r=new ResultRow(resultType,resultRole,context.getContextTopic().getOneSubjectIdentifier()); result.add(r); return result; } public boolean isContextSensitive(){ return true; } }
1,791
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
OrDirective.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query/OrDirective.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * OrDirective.java * * Created on 29. lokakuuta 2007, 11:08 * */ package org.wandora.query; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * @deprecated * * @author olli */ public class OrDirective extends FilterDirective { private FilterDirective[] filters; /** Creates a new instance of OrDirective */ public OrDirective(Directive query,boolean not,FilterDirective ... filters) { super(query,not); this.filters=filters; } public OrDirective(Directive query,boolean not,FilterDirective filter1) { this(query,not,new FilterDirective[]{filter1}); } public OrDirective(Directive query,boolean not,FilterDirective filter1,FilterDirective filter2) { this(query,not,new FilterDirective[]{filter1,filter2}); } public OrDirective(Directive query,boolean not,FilterDirective filter1,FilterDirective filter2,FilterDirective filter3) { this(query,not,new FilterDirective[]{filter1,filter2,filter3}); } public OrDirective(Directive query,boolean not,FilterDirective filter1,FilterDirective filter2,FilterDirective filter3,FilterDirective filter4) { this(query,not,new FilterDirective[]{filter1,filter2,filter3,filter4}); } public Object startQuery(QueryContext context) throws TopicMapException { Object[] params=new Object[filters.length]; for(int i=0;i<filters.length;i++){ params[i]=filters[i].startQuery(context); } return params; } public void endQuery(QueryContext context, Object param) throws TopicMapException { Object[] params=(Object[])param; for(int i=0;i<filters.length;i++){ filters[i].endQuery(context,params[i]); } } protected int _includeRow(ResultRow row, Topic context, TopicMap tm, Object param) throws TopicMapException { Object[] params=(Object[])param; boolean ignore=true; for(int i=0;i<filters.length;i++){ int r=filters[i]._includeRow(row,context,tm,params[i]); if(r==RES_INCLUDE) return RES_INCLUDE; else if(r==RES_EXCLUDE) ignore=false; } if(ignore) return RES_IGNORE; else return RES_EXCLUDE; } public boolean isContextSensitive(){ for(int i=0;i<filters.length;i++){ if(filters[i].isContextSensitive()) return true; } return super.isContextSensitive(); } }
3,316
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
WandoraHttpAuthorizer.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/WandoraHttpAuthorizer.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * WandoraHttpAuthorizer.java * * Created on 17. toukokuuta 2006, 12:46 * */ package org.wandora.application; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import org.wandora.application.gui.PasswordPrompt; import org.wandora.utils.Base64; import org.wandora.utils.HttpAuthorizer; import org.wandora.utils.IObox; /** * WandoraHttpAuthorizer is a helper class to handle URLs requiring * HTTP authorization. Class captures unauthorized requests and * asks Wandora user for a username and a password to access the * URL. * * @author akivela */ public class WandoraHttpAuthorizer extends HttpAuthorizer { Wandora admin = null; /** * Creates a new instance of HttpAuthorizer */ public WandoraHttpAuthorizer(Wandora admin) { this.admin = admin; } public WandoraHttpAuthorizer(Wandora admin, String storeResource) { super(storeResource); this.admin = admin; } // ------------------------------------------------------------------------- @Override public URLConnection getAuthorizedAccess(URL url) throws Exception { if(url.toExternalForm().startsWith("https://")) { IObox.disableHTTPSCertificateValidation(); try { url = new URL(url.toExternalForm()); } catch (MalformedURLException e) { } } // ------------------------------------- URLConnection uc = url.openConnection(); Wandora.initUrlConnection(uc); if(uc instanceof HttpURLConnection) { int res = ((HttpURLConnection) uc).getResponseCode(); boolean tried = false; while(res == HttpURLConnection.HTTP_UNAUTHORIZED) { String authUser = quessAuthorizedUserFor(url); String authPassword = quessAuthorizedPasswordFor(url); if("__IGNORE".equals(authUser) && "__IGNORE".equals(authPassword)) continue; if(authUser == null || authPassword == null || tried == true) { PasswordPrompt pp = new PasswordPrompt(admin, true); pp.setTitle(uc.getURL().toExternalForm()); admin.centerWindow(pp); pp.setVisible(true); if(!pp.wasCancelled()) { authUser = pp.getUsername(); authPassword = new String(pp.getPassword()); addAuthorization(url, authUser, authPassword); } else { addAuthorization(url, "__IGNORE", "__IGNORE"); continue; } } if(authUser != null && authPassword != null) { String userPassword = authUser + ":" + authPassword; String encodedUserPassword = Base64.encodeBytes(userPassword.getBytes()); uc = (HttpURLConnection) uc.getURL().openConnection(); Wandora.initUrlConnection(uc); uc.setUseCaches(false); uc.setRequestProperty ("Authorization", "Basic " + encodedUserPassword); } tried = true; res = ((HttpURLConnection) uc).getResponseCode(); } } return uc; } }
4,319
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ConcurrentEditingWarning.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/ConcurrentEditingWarning.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * ConcurrentEditingWarning.java * * Created on June 17, 2004, 11:40 AM */ package org.wandora.application; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public class ConcurrentEditingWarning extends javax.swing.JDialog { private static final long serialVersionUID = 1L; /** Creates new form ConcurrentEditingWarning */ public ConcurrentEditingWarning(java.awt.Frame parent, boolean modal,Topic[] failed,Topic[] removed) { super(parent, modal); initComponents(); StringBuffer buf=new StringBuffer(); if(failed.length>0) buf.append("Edited:\n"); try{ for(int i=0;i<failed.length;i++){ buf.append(failed[i].getBaseName()+" ("+failed[i].getSubjectIdentifiers().iterator().next()+")\n"); } if(removed.length>0) buf.append("Removed:\n"); for(int i=0;i<removed.length;i++){ buf.append(removed[i].getBaseName()+" ("+removed[i].getSubjectIdentifiers().iterator().next()+")\n"); } }catch(TopicMapException tme){ tme.printStackTrace(); // TODO EXCEPTION } failedTextArea.setText(buf.toString()); this.setSize(300,400); } /** 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() { jTextArea1 = new javax.swing.JTextArea(); jPanel1 = new javax.swing.JPanel(); okButton = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); failedTextArea = new javax.swing.JTextArea(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); jTextArea1.setEditable(false); jTextArea1.setLineWrap(true); jTextArea1.setText("Concurrent editing of topics detected. Following topics have been edited by you and somebody else at the same time. Fresh copies of these topics have been retrieved. You should now review that they have been merged properly and then either recommit your changes or roll back. Rolling back will cause you to lose whatever changes you have made but will fully preserve the changes of the other user. Topics listed under \"Edited\" have been edited by somebody else and topics under \"Removed\" have been removed. If you commit your changes, removed topics will be recreated unless you first remove them from your editing session. It may also be possible that this is the result of you modifying topic subject identifiers and no real concurrent editing happened. In this case just recommit your changes."); jTextArea1.setWrapStyleWord(true); jTextArea1.setOpaque(false); getContentPane().add(jTextArea1, java.awt.BorderLayout.NORTH); okButton.setText("OK"); okButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { okButtonActionPerformed(evt); } }); jPanel1.add(okButton); getContentPane().add(jPanel1, java.awt.BorderLayout.SOUTH); failedTextArea.setEditable(false); jScrollPane1.setViewportView(failedTextArea); getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER); pack(); } // </editor-fold>//GEN-END:initComponents private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed this.hide(); }//GEN-LAST:event_okButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTextArea failedTextArea; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextArea jTextArea1; private javax.swing.JButton okButton; // End of variables declaration//GEN-END:variables }
4,971
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
WandoraToolManagerPanel2.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/WandoraToolManagerPanel2.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * WandoraToolManagerPanel2.java * * Created on 16. helmikuuta 2009, 17:11 */ package org.wandora.application; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.util.ArrayList; import javax.swing.JDialog; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.application.gui.WandoraToolTable; import org.wandora.application.gui.WandoraToolTree; /** * * @author akivela */ public class WandoraToolManagerPanel2 extends javax.swing.JPanel { private static final long serialVersionUID = 1L; private Wandora wandora; private WandoraToolManager2 manager; private JDialog parent; private WandoraToolSet currentToolSet = null; private WandoraToolTree currentToolTree = null; /** Creates new form WandoraToolManagerPanel2 */ public WandoraToolManagerPanel2(WandoraToolManager2 m, JDialog d, Wandora w) { this.wandora = w; this.parent = d; this.manager = m; initComponents(); initContent(); parent.invalidate(); } private void initContent() { initToolPaths(); initJarPaths(); initAllTools(); initToolSets(); } public void initAllTools() { ArrayList<WandoraTool> allTools = manager.getAllTools(); WandoraToolTable toolTable = new WandoraToolTable(wandora); toolTable.initialize(allTools.toArray( new WandoraTool[] {} )); allToolsTablePanel.removeAll(); allToolsTablePanel.add(toolTable, BorderLayout.NORTH); allToolsScrollPane.setColumnHeaderView(toolTable.getTableHeader()); // allToolsTitlePanel.removeAll(); // allToolsTitlePanel.add(toolTable.getTableHeader(), BorderLayout.CENTER); } // ---------------------------------------------------------- TOOL PATHS --- public void initToolPaths() { ArrayList<String> toolPaths = manager.getToolPaths(); StringBuilder pathString = new StringBuilder(""); for( String path : toolPaths ) { if(path != null) { pathString.append(path).append("\n"); } } pathTextPane.setText(pathString.toString()); } public void initJarPaths(){ ArrayList<String> jarPaths = manager.getJarPaths(); StringBuilder pathString = new StringBuilder(""); for( String path : jarPaths ) { if(path != null) { pathString.append(path).append("\n"); } } jarTextPane.setText(pathString.toString()); } public void saveToolPaths() { String pathString = pathTextPane.getText(); String[] paths = pathString.split("\n"); String path = null; ArrayList<String> toolPaths = new ArrayList<String>(); for(int i=0; i<paths.length; i++) { path = paths[i]; if(path != null) { path = path.trim(); if(path.length() > 0) { toolPaths.add(path); } } } boolean saveToOptions = true; if(toolPaths.isEmpty()) { int a = WandoraOptionPane.showConfirmDialog(parent, "No tool paths found. Do you want to delete all path saved in Wandora options?", "Delete all paths"); if(a == WandoraOptionPane.NO_OPTION) saveToOptions = false; else if(a == WandoraOptionPane.CLOSED_OPTION) saveToOptions = false; else if(a == WandoraOptionPane.CANCEL_OPTION) saveToOptions = false; } if(saveToOptions) { manager.writeToolPaths(toolPaths); } } public void saveJarPaths() { String pathString = jarTextPane.getText(); String[] paths = pathString.split("\n"); String path = null; ArrayList<String> jarPaths = new ArrayList<String>(); for(int i=0; i<paths.length; i++) { path = paths[i]; if(path != null) { path = path.trim(); if(path.length() > 0) { jarPaths.add(path); } } } boolean saveToOptions = true; if(jarPaths.isEmpty()) { int a = WandoraOptionPane.showConfirmDialog(parent, "No jar tool paths found. Do you want to delete all jar path saved in Wandora options?", "Delete all jar paths"); if(a == WandoraOptionPane.NO_OPTION) saveToOptions = false; else if(a == WandoraOptionPane.CLOSED_OPTION) saveToOptions = false; else if(a == WandoraOptionPane.CANCEL_OPTION) saveToOptions = false; } if(saveToOptions) { manager.writeJarPaths(jarPaths); } } public void scanToolPaths() { saveToolPaths(); saveJarPaths(); manager.scanAllTools(); initAllTools(); } // ----------------------------------------------------------- TOOL SETS --- public void initToolSets() { initToolSets(null); } public void initToolSets(WandoraToolSet selectedSet) { ArrayList<WandoraToolSet> toolSets = manager.getToolSets(); toolSetsComboBox.setEditable(false); toolSetsComboBox.removeAllItems(); int selectedIndex = 0; int index = 0; if(toolSets.size() > 0) { for(WandoraToolSet toolSet : toolSets ) { if(toolSet.equals(selectedSet)) selectedIndex = index; toolSetsComboBox.addItem(toolSet.getName()); index++; } toolSetsComboBox.setSelectedIndex(selectedIndex); selectToolSet(toolSets.get(selectedIndex)); } } public void selectToolSet() { int setIndex = Math.max(0, toolSetsComboBox.getSelectedIndex()); ArrayList<WandoraToolSet> toolSets = manager.getToolSets(); selectToolSet(toolSets.get(Math.min(setIndex, toolSets.size()-1))); } public void selectToolSet(WandoraToolSet toolSet) { currentToolSet = toolSet; currentToolTree = new WandoraToolTree(wandora); currentToolTree.initialize(toolSet); toolSetContainerPanel.removeAll(); toolSetContainerPanel.add(currentToolTree, BorderLayout.NORTH); toolSetContainerPanel.validate(); toolSetsScrollPane.validate(); toolSetsScrollPane.repaint(); } public void addToolSet() { String name = WandoraOptionPane.showInputDialog(wandora, "Name of tool set", "", "Name of tool set"); if(name != null) { WandoraToolSet set = manager.getToolSet(name); if(set == null) { set = manager.createToolSet(name); initToolSets(set); } else { WandoraOptionPane.showMessageDialog(wandora, "Tool set name should be unique. Tool set with name '"+name+"' already exists.", "Set name already exists!"); } } } public void deleteToolSet() { boolean deleteAllowed = manager.allowDelete(currentToolSet); if(deleteAllowed) { int a = WandoraOptionPane.showConfirmDialog(wandora, "Delete tool set '"+currentToolSet.getName()+"'?", "Delete tool set '"+currentToolSet.getName()+"'?", WandoraOptionPane.OK_CANCEL_OPTION); if(a == WandoraOptionPane.OK_OPTION) { manager.deleteToolSet(currentToolSet); initToolSets(); } } else { WandoraOptionPane.showMessageDialog(wandora, "You can't delete Wandora's base tool set '"+currentToolSet.getName()+"'. Delete cancelled."); } } // ------------------------------------------------------------------------- /** 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; tabbedPane = new org.wandora.application.gui.simple.SimpleTabbedPane(); toolSetsPanel = new javax.swing.JPanel(); toolSetsLabel = new org.wandora.application.gui.simple.SimpleLabel(); selectSetPanel = new javax.swing.JPanel(); toolSetsComboBox = new org.wandora.application.gui.simple.SimpleComboBox(); newSetButton = new org.wandora.application.gui.simple.SimpleButton(); deleteSetButton = new org.wandora.application.gui.simple.SimpleButton(); toolSetsScrollPane = new org.wandora.application.gui.simple.SimpleScrollPane(); toolSetContainerPanel = new javax.swing.JPanel(); toolSetsButtonPanel = new javax.swing.JPanel(); jSeparator1 = new javax.swing.JSeparator(); addToolButton = new org.wandora.application.gui.simple.SimpleButton(); addGroupButton = new org.wandora.application.gui.simple.SimpleButton(); deleteButton = new org.wandora.application.gui.simple.SimpleButton(); renameButton = new org.wandora.application.gui.simple.SimpleButton(); allToolsPanel = new javax.swing.JPanel(); allToolsLabel = new org.wandora.application.gui.simple.SimpleLabel(); allToolsTitlePanel = new javax.swing.JPanel(); allToolsScrollPane = new org.wandora.application.gui.simple.SimpleScrollPane(); allToolsTablePanel = new javax.swing.JPanel(); pathPanel = new javax.swing.JPanel(); pathLabel = new org.wandora.application.gui.simple.SimpleLabel(); jScrollPane1 = new javax.swing.JScrollPane(); pathTextPane = new org.wandora.application.gui.simple.SimpleTextPane(); pathButtonPanel = new javax.swing.JPanel(); pathButtonFillerPanel = new javax.swing.JPanel(); savePathsButton = new org.wandora.application.gui.simple.SimpleButton(); scanButton = new org.wandora.application.gui.simple.SimpleButton(); jarPanel = new javax.swing.JPanel(); pathLabel1 = new org.wandora.application.gui.simple.SimpleLabel(); jScrollPane2 = new javax.swing.JScrollPane(); jarTextPane = new org.wandora.application.gui.simple.SimpleTextPane(); jarButtonPanel = new javax.swing.JPanel(); pathButtonFillerPanel1 = new javax.swing.JPanel(); saveJarsButton = new org.wandora.application.gui.simple.SimpleButton(); scanJarsButton = new org.wandora.application.gui.simple.SimpleButton(); bottomButtonPanel = new javax.swing.JPanel(); buttonFillerPanel = new javax.swing.JPanel(); closeButton = new org.wandora.application.gui.simple.SimpleButton(); setLayout(new java.awt.GridBagLayout()); toolSetsPanel.setLayout(new java.awt.GridBagLayout()); toolSetsLabel.setText("<html>User can create and edit tool sets in this tab.</html>"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5); toolSetsPanel.add(toolSetsLabel, gridBagConstraints); selectSetPanel.setLayout(new java.awt.GridBagLayout()); toolSetsComboBox.setPreferredSize(new java.awt.Dimension(29, 21)); toolSetsComboBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { toolSetsComboBoxActionPerformed(evt); } }); 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, 0, 2); selectSetPanel.add(toolSetsComboBox, gridBagConstraints); newSetButton.setText("New"); newSetButton.setMargin(new java.awt.Insets(2, 4, 2, 4)); newSetButton.setPreferredSize(new java.awt.Dimension(60, 21)); newSetButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { newSetButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 2); selectSetPanel.add(newSetButton, gridBagConstraints); deleteSetButton.setText("Delete"); deleteSetButton.setMargin(new java.awt.Insets(2, 4, 2, 4)); deleteSetButton.setPreferredSize(new java.awt.Dimension(60, 21)); deleteSetButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { deleteSetButtonActionPerformed(evt); } }); selectSetPanel.add(deleteSetButton, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5); toolSetsPanel.add(selectSetPanel, gridBagConstraints); toolSetContainerPanel.setBackground(new java.awt.Color(255, 255, 255)); toolSetContainerPanel.setLayout(new java.awt.BorderLayout()); toolSetsScrollPane.setViewportView(toolSetContainerPanel); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); toolSetsPanel.add(toolSetsScrollPane, gridBagConstraints); toolSetsButtonPanel.setLayout(new java.awt.GridBagLayout()); jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 3); toolSetsButtonPanel.add(jSeparator1, gridBagConstraints); addToolButton.setText("Add tool"); addToolButton.setMargin(new java.awt.Insets(2, 4, 2, 4)); addToolButton.setPreferredSize(new java.awt.Dimension(75, 21)); addToolButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addToolButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 2); toolSetsButtonPanel.add(addToolButton, gridBagConstraints); addGroupButton.setText("Add group"); addGroupButton.setMargin(new java.awt.Insets(2, 4, 2, 4)); addGroupButton.setPreferredSize(new java.awt.Dimension(75, 21)); addGroupButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addGroupButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 2); toolSetsButtonPanel.add(addGroupButton, gridBagConstraints); deleteButton.setText("Delete"); deleteButton.setMargin(new java.awt.Insets(2, 4, 2, 4)); deleteButton.setPreferredSize(new java.awt.Dimension(75, 21)); deleteButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { deleteButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 2); toolSetsButtonPanel.add(deleteButton, gridBagConstraints); renameButton.setText("Rename"); renameButton.setMargin(new java.awt.Insets(2, 4, 2, 4)); renameButton.setPreferredSize(new java.awt.Dimension(75, 21)); renameButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { renameButtonActionPerformed(evt); } }); toolSetsButtonPanel.add(renameButton, 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, 5, 5, 5); toolSetsPanel.add(toolSetsButtonPanel, gridBagConstraints); tabbedPane.addTab("Tool sets", toolSetsPanel); allToolsPanel.setLayout(new java.awt.GridBagLayout()); allToolsLabel.setText("<html>All known tools are listed here. The list contains also unfinished, buggy and deprecated tools. Running such tool may cause exceptions and unpredictable behaviour. We suggest you don't run tools listed here unless you really know what you are doing.</html>"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5); allToolsPanel.add(allToolsLabel, gridBagConstraints); allToolsTitlePanel.setLayout(new java.awt.BorderLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5); allToolsPanel.add(allToolsTitlePanel, gridBagConstraints); allToolsTablePanel.setLayout(new java.awt.BorderLayout()); allToolsScrollPane.setViewportView(allToolsTablePanel); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 5, 5, 5); allToolsPanel.add(allToolsScrollPane, gridBagConstraints); tabbedPane.addTab("All tools", allToolsPanel); pathPanel.setLayout(new java.awt.GridBagLayout()); pathLabel.setText("<html>This tab is used to view and edit class paths Wandora scans for tool classes."); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5); pathPanel.add(pathLabel, gridBagConstraints); jScrollPane1.setViewportView(pathTextPane); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pathPanel.add(jScrollPane1, gridBagConstraints); pathButtonPanel.setPreferredSize(new java.awt.Dimension(100, 23)); pathButtonPanel.setLayout(new java.awt.GridBagLayout()); javax.swing.GroupLayout pathButtonFillerPanelLayout = new javax.swing.GroupLayout(pathButtonFillerPanel); pathButtonFillerPanel.setLayout(pathButtonFillerPanelLayout); pathButtonFillerPanelLayout.setHorizontalGroup( pathButtonFillerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); pathButtonFillerPanelLayout.setVerticalGroup( pathButtonFillerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); pathButtonPanel.add(pathButtonFillerPanel, new java.awt.GridBagConstraints()); savePathsButton.setText("Save"); savePathsButton.setMargin(new java.awt.Insets(2, 6, 2, 6)); savePathsButton.setPreferredSize(new java.awt.Dimension(60, 21)); savePathsButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mousePressed(java.awt.event.MouseEvent evt) { savePathsButtonMousePressed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 2); pathButtonPanel.add(savePathsButton, gridBagConstraints); scanButton.setText("Scan"); scanButton.setMargin(new java.awt.Insets(2, 6, 2, 6)); scanButton.setPreferredSize(new java.awt.Dimension(60, 21)); scanButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mousePressed(java.awt.event.MouseEvent evt) { scanButtonMousePressed(evt); } }); pathButtonPanel.add(scanButton, 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, 5, 5, 5); pathPanel.add(pathButtonPanel, gridBagConstraints); tabbedPane.addTab("Paths", pathPanel); jarPanel.setLayout(new java.awt.GridBagLayout()); pathLabel1.setText("<html>This tab is used to view and edit paths to JAR files or directories containing JAR files where Wandora scans for tool classes."); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5); jarPanel.add(pathLabel1, gridBagConstraints); jScrollPane2.setViewportView(jarTextPane); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jarPanel.add(jScrollPane2, gridBagConstraints); jarButtonPanel.setPreferredSize(new java.awt.Dimension(100, 23)); jarButtonPanel.setLayout(new java.awt.GridBagLayout()); javax.swing.GroupLayout pathButtonFillerPanel1Layout = new javax.swing.GroupLayout(pathButtonFillerPanel1); pathButtonFillerPanel1.setLayout(pathButtonFillerPanel1Layout); pathButtonFillerPanel1Layout.setHorizontalGroup( pathButtonFillerPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); pathButtonFillerPanel1Layout.setVerticalGroup( pathButtonFillerPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); jarButtonPanel.add(pathButtonFillerPanel1, new java.awt.GridBagConstraints()); saveJarsButton.setText("Save"); saveJarsButton.setMargin(new java.awt.Insets(2, 6, 2, 6)); saveJarsButton.setPreferredSize(new java.awt.Dimension(60, 21)); saveJarsButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mousePressed(java.awt.event.MouseEvent evt) { saveJarsButtonMousePressed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 2); jarButtonPanel.add(saveJarsButton, gridBagConstraints); scanJarsButton.setText("Scan"); scanJarsButton.setMargin(new java.awt.Insets(2, 6, 2, 6)); scanJarsButton.setPreferredSize(new java.awt.Dimension(60, 21)); scanJarsButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mousePressed(java.awt.event.MouseEvent evt) { scanJarsButtonMousePressed(evt); } }); jarButtonPanel.add(scanJarsButton, 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, 5, 5, 5); jarPanel.add(jarButtonPanel, gridBagConstraints); tabbedPane.addTab("JAR paths", jarPanel); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(tabbedPane, gridBagConstraints); bottomButtonPanel.setPreferredSize(new java.awt.Dimension(100, 23)); bottomButtonPanel.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; bottomButtonPanel.add(buttonFillerPanel, gridBagConstraints); closeButton.setText("Close"); closeButton.setMargin(new java.awt.Insets(2, 6, 2, 6)); closeButton.setMaximumSize(new java.awt.Dimension(70, 23)); closeButton.setMinimumSize(new java.awt.Dimension(70, 23)); closeButton.setPreferredSize(new java.awt.Dimension(70, 23)); closeButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mousePressed(java.awt.event.MouseEvent evt) { closeButtonMousePressed(evt); } }); bottomButtonPanel.add(closeButton, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); add(bottomButtonPanel, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents private void closeButtonMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_closeButtonMousePressed parent.setVisible(false); }//GEN-LAST:event_closeButtonMousePressed private void scanButtonMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_scanButtonMousePressed scanToolPaths(); }//GEN-LAST:event_scanButtonMousePressed private void savePathsButtonMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_savePathsButtonMousePressed saveToolPaths(); }//GEN-LAST:event_savePathsButtonMousePressed private void toolSetsComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_toolSetsComboBoxActionPerformed this.selectToolSet(); }//GEN-LAST:event_toolSetsComboBoxActionPerformed private void addToolButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addToolButtonActionPerformed currentToolTree.actionPerformed(new ActionEvent(this, 0, "Add tool")); }//GEN-LAST:event_addToolButtonActionPerformed private void newSetButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newSetButtonActionPerformed addToolSet(); }//GEN-LAST:event_newSetButtonActionPerformed private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed currentToolTree.actionPerformed(new ActionEvent(this, 0, "Delete")); }//GEN-LAST:event_deleteButtonActionPerformed private void deleteSetButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteSetButtonActionPerformed deleteToolSet(); }//GEN-LAST:event_deleteSetButtonActionPerformed private void addGroupButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addGroupButtonActionPerformed currentToolTree.actionPerformed(new ActionEvent(this, 0, "Add group")); }//GEN-LAST:event_addGroupButtonActionPerformed private void renameButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_renameButtonActionPerformed currentToolTree.actionPerformed(new ActionEvent(this, 0, "Rename")); }//GEN-LAST:event_renameButtonActionPerformed private void saveJarsButtonMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_saveJarsButtonMousePressed saveJarPaths(); }//GEN-LAST:event_saveJarsButtonMousePressed private void scanJarsButtonMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_scanJarsButtonMousePressed scanToolPaths(); }//GEN-LAST:event_scanJarsButtonMousePressed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton addGroupButton; private javax.swing.JButton addToolButton; private javax.swing.JLabel allToolsLabel; private javax.swing.JPanel allToolsPanel; private javax.swing.JScrollPane allToolsScrollPane; private javax.swing.JPanel allToolsTablePanel; private javax.swing.JPanel allToolsTitlePanel; private javax.swing.JPanel bottomButtonPanel; private javax.swing.JPanel buttonFillerPanel; private javax.swing.JButton closeButton; private javax.swing.JButton deleteButton; private javax.swing.JButton deleteSetButton; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JSeparator jSeparator1; private javax.swing.JPanel jarButtonPanel; private javax.swing.JPanel jarPanel; private javax.swing.JTextPane jarTextPane; private javax.swing.JButton newSetButton; private javax.swing.JPanel pathButtonFillerPanel; private javax.swing.JPanel pathButtonFillerPanel1; private javax.swing.JPanel pathButtonPanel; private javax.swing.JLabel pathLabel; private javax.swing.JLabel pathLabel1; private javax.swing.JPanel pathPanel; private javax.swing.JTextPane pathTextPane; private javax.swing.JButton renameButton; private javax.swing.JButton saveJarsButton; private javax.swing.JButton savePathsButton; private javax.swing.JButton scanButton; private javax.swing.JButton scanJarsButton; private javax.swing.JPanel selectSetPanel; private javax.swing.JTabbedPane tabbedPane; private javax.swing.JPanel toolSetContainerPanel; private javax.swing.JPanel toolSetsButtonPanel; private javax.swing.JComboBox toolSetsComboBox; private javax.swing.JLabel toolSetsLabel; private javax.swing.JPanel toolSetsPanel; private javax.swing.JScrollPane toolSetsScrollPane; // End of variables declaration//GEN-END:variables }
33,152
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
WandoraToolActionListener.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/WandoraToolActionListener.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * WandoraToolActionListener.java * * Created on 24. lokakuuta 2005, 14:33 * */ package org.wandora.application; import javax.swing.SwingUtilities; import org.wandora.topicmap.TopicMapException; /** * ActionListener that passes execution to a given WandoraTool object * whenever the action is performed. More specifically, action event invokes * tool's execute method. * * @author akivela */ public class WandoraToolActionListener implements java.awt.event.ActionListener { private final WandoraTool tool; private final Wandora wandora; public WandoraToolActionListener(Wandora wandora, WandoraTool tool) { this.wandora = wandora; this.tool = tool; } /** * Invokes tool's execute method by SwingUtilities.invokeLater. * * @param event */ @Override public void actionPerformed(final java.awt.event.ActionEvent event) { if(wandora != null && tool != null) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { try { wandora.applyChanges(); } catch(CancelledException ce) { return; } try { tool.execute(wandora, event); } catch(TopicMapException tme) { wandora.handleError(tme); } } }); } else { System.out.println("No Wandora or tool object specified in WandoraToolActionListener. Can't execute."); } } }
2,536
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AppConfig.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/AppConfig.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * BSHConfig.java * * Created on 29.6.2005, 14:13 */ package org.wandora.application; import org.wandora.utils.CMDParamParser; /** * * @author olli */ public interface AppConfig { public void initialize(CMDParamParser params); public Object getObject(String key); }
1,099
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
WandoraToolManager2.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/WandoraToolManager2.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * WandoraToolManager2.java * * Created on 20. lokakuuta 2005, 16:00 * */ package org.wandora.application; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.io.File; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Set; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JMenu; import javax.swing.JPopupMenu; import javax.swing.KeyStroke; import org.reflections.Reflections; import org.wandora.application.contexts.Context; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.simple.SimpleMenu; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.application.tools.ActivateButtonToolSet; import org.wandora.application.tools.ClearToolLocks; import org.wandora.application.tools.importers.AbstractImportTool; import org.wandora.application.tools.importers.OBOImport; import org.wandora.application.tools.importers.SimpleN3Import; import org.wandora.application.tools.importers.SimpleRDFImport; import org.wandora.application.tools.importers.TopicMapImport; import org.wandora.application.tools.project.LoadWandoraProject; import org.wandora.application.tools.project.MergeWandoraProject; import org.wandora.utils.JarClassLoader; import org.wandora.utils.Options; /** * * @author akivela */ public class WandoraToolManager2 extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; public static final boolean ADDITIONAL_DEBUG = false; private KeyStroke[] accelerators = new KeyStroke[] { KeyStroke.getKeyStroke(KeyEvent.VK_1, InputEvent.CTRL_DOWN_MASK), KeyStroke.getKeyStroke(KeyEvent.VK_2, InputEvent.CTRL_DOWN_MASK), KeyStroke.getKeyStroke(KeyEvent.VK_3, InputEvent.CTRL_DOWN_MASK), KeyStroke.getKeyStroke(KeyEvent.VK_4, InputEvent.CTRL_DOWN_MASK), KeyStroke.getKeyStroke(KeyEvent.VK_5, InputEvent.CTRL_DOWN_MASK), KeyStroke.getKeyStroke(KeyEvent.VK_6, InputEvent.CTRL_DOWN_MASK), KeyStroke.getKeyStroke(KeyEvent.VK_7, InputEvent.CTRL_DOWN_MASK), KeyStroke.getKeyStroke(KeyEvent.VK_8, InputEvent.CTRL_DOWN_MASK), KeyStroke.getKeyStroke(KeyEvent.VK_9, InputEvent.CTRL_DOWN_MASK), }; private KeyStroke[] buttonSetAccelerators = new KeyStroke[] { KeyStroke.getKeyStroke(KeyEvent.VK_F1, InputEvent.SHIFT_DOWN_MASK), KeyStroke.getKeyStroke(KeyEvent.VK_F2, InputEvent.SHIFT_DOWN_MASK), KeyStroke.getKeyStroke(KeyEvent.VK_F3, InputEvent.SHIFT_DOWN_MASK), KeyStroke.getKeyStroke(KeyEvent.VK_F4, InputEvent.SHIFT_DOWN_MASK), KeyStroke.getKeyStroke(KeyEvent.VK_F5, InputEvent.SHIFT_DOWN_MASK), KeyStroke.getKeyStroke(KeyEvent.VK_F6, InputEvent.SHIFT_DOWN_MASK), KeyStroke.getKeyStroke(KeyEvent.VK_F7, InputEvent.SHIFT_DOWN_MASK), KeyStroke.getKeyStroke(KeyEvent.VK_F8, InputEvent.SHIFT_DOWN_MASK), KeyStroke.getKeyStroke(KeyEvent.VK_F9, InputEvent.SHIFT_DOWN_MASK), }; protected Wandora wandora; protected Options options; protected ArrayList<String> toolPaths; protected ArrayList<String> jarPaths; protected ArrayList<WandoraToolSet> toolSets; protected HashMap<WandoraTool, String> optionsPrefixes; protected ArrayList<WandoraTool> allTools; protected HashMap<WandoraTool,ToolInfo> toolInfos; public WandoraToolManager2(Wandora w) { wandora = w; options = w.getOptions(); readToolPaths(); readJarPaths(); scanAllTools(); readToolSets(); } public ArrayList<WandoraToolSet> getToolSets() { return toolSets; } public void addTool(ToolInfo toolInfo){ allTools.add(toolInfo.tool); toolInfos.put(toolInfo.tool,toolInfo); } public void addTool(WandoraTool tool, String sourceType, String source) { addTool(new ToolInfo(tool,sourceType,source)); } public WandoraTool findTool(String cls){ for(WandoraTool tool : allTools){ if(tool.getClass().getName().equals(cls)) return tool; } return null; } public WandoraTool newToolInstance(WandoraTool tool) throws InstantiationException, IllegalAccessException { if(tool==null) return null; return tool.getClass().newInstance(); } // ---------------------------------------------------------- TOOL PATHS --- public ToolInfo getToolInfo(WandoraTool tool){ return toolInfos.get(tool); } public ArrayList<String> getToolPaths() { return toolPaths; } public ArrayList<String> getJarPaths(){ return jarPaths; } public void readJarPaths(){ jarPaths = new ArrayList<String>(); if(options == null) return; int pathCounter=0; boolean continueRefresh = true; while(true) { String jarResourcePath = options.get("tool.jarpath["+pathCounter+"]"); if(jarResourcePath == null || jarResourcePath.length() == 0) { break; } pathCounter++; if(jarPaths.contains(jarResourcePath)) continue; jarPaths.add(jarResourcePath); } } public void readToolPaths() { toolPaths = new ArrayList<String>(); if(options == null) return; int pathCounter=0; boolean continueRefresh = true; while(continueRefresh) { String toolResourcePath = options.get("tool.path["+pathCounter+"]"); if(toolResourcePath == null || toolResourcePath.length() == 0) { toolResourcePath = "org/wandora/application/tools"; //System.out.println("Using default tool resource path: " + toolResourcePath); continueRefresh = false; } pathCounter++; if(toolPaths.contains(toolResourcePath)) continue; toolPaths.add(toolResourcePath); } } public void writeJarPaths(ArrayList<String> newJarPaths){ int c = jarPaths.size(); int i = 0; for( String path : newJarPaths ) { options.put("tool.jarpath["+i+"]", path); i++; } for( ; i<c; i++ ) { options.put("tool.jarpath["+i+"]", null); } } public void writeToolPaths(ArrayList<String> newToolPaths) { int c = toolPaths.size(); int i = 0; for( String path : newToolPaths ) { options.put("tool.path["+i+"]", path); i++; } for( ; i<c; i++ ) { options.put("tool.path["+i+"]", null); } } // ----------------------------------------------------- AVAILABLE TOOLS --- public ArrayList<WandoraTool> getAllTools() { return allTools; } public void scanAllTools() { readToolPaths(); readJarPaths(); allTools=new ArrayList<WandoraTool>(); toolInfos=new HashMap<WandoraTool,ToolInfo>(); for(String path : toolPaths) { try { String classPath = path.replace('/', '.'); Reflections reflections = new Reflections(classPath); Set<Class<? extends WandoraTool>> toolClasses = reflections.getSubTypesOf(WandoraTool.class); for(Class toolClass : toolClasses) { try { if(isValidWandoraToolClass(toolClass)) { WandoraTool tool = (WandoraTool) toolClass.newInstance(); if(tool != null) { addTool(tool, "path", path); } } } catch(Exception e) { if(ADDITIONAL_DEBUG) System.out.println("Rejecting tool. Exception '" + e.toString() + "' occurred while investigating class '" + toolClass + "'."); //e.printStackTrace(); } } } catch(Exception e) { e.printStackTrace(); } } for(String jarPath : jarPaths){ File f=new File(jarPath); scanJarPath(f); } } private boolean isValidWandoraToolClass(Class c) { try { if(!c.isInterface() && !Modifier.isAbstract( c.getModifiers() )) { // throws exception if class has no argumentless constructor. c.getConstructors(); return true; } } catch(Exception e) { } return false; } /* public void scanAllTools() { readToolPaths(); readJarPaths(); allTools=new ArrayList<WandoraTool>(); toolInfos=new HashMap<WandoraTool,ToolInfo>(); for(String path : toolPaths) { try { String classPath = path.replace('/', '.'); Enumeration toolResources = ClassLoader.getSystemResources(path); while(toolResources.hasMoreElements()) { URL toolBaseUrl = (URL) toolResources.nextElement(); if(toolBaseUrl.toExternalForm().startsWith("file:")) { String baseDir = IObox.getFileFromURL(toolBaseUrl); // String baseDir = URLDecoder.decode(toolBaseUrl.toExternalForm().substring(6), "UTF-8"); if(!baseDir.startsWith("/") && !baseDir.startsWith("\\") && baseDir.charAt(1)!=':') baseDir="/"+baseDir; //System.out.println("Basedir: " + baseDir); HashSet<String> toolFileNames = IObox.getFilesAsHash(baseDir, ".*\\.class", 1, 9000); for(String classFileName : toolFileNames) { try { File classFile = new File(classFileName); String className = classPath + "." + classFile.getName().replaceFirst("\\.class", ""); if(className.indexOf("$")>-1) continue; WandoraTool tool=null; if(className.equals(this.getClass().getName())) tool=this; else { Class cls=Class.forName(className); if(!WandoraTool.class.isAssignableFrom(cls)) { if(ADDITIONAL_DEBUG) System.out.println("Rejecting '" + cls.getSimpleName() + "'. Does not implement Tool interface!"); continue; } if(cls.isInterface()) { if(ADDITIONAL_DEBUG) System.out.println("Rejecting '" + cls.getSimpleName() + "'. Is interface!"); continue; } try { cls.getConstructor(); } catch(NoSuchMethodException nsme){ if(ADDITIONAL_DEBUG) System.out.println("Rejecting '" + cls.getSimpleName() + "'. No constructor!"); continue; } tool=(WandoraTool)Class.forName(className).newInstance(); } if(tool != null) { addTool(tool, "path", path); //allTools.add(tool); } } catch(Exception ex) { if(ADDITIONAL_DEBUG) System.out.println("Rejecting tool. Exception '" + ex.toString() + "' occurred while investigating '" + classFileName + "'."); //ex.printStackTrace(); } } } } } catch(Exception e) { e.printStackTrace(); } } for(String jarPath : jarPaths){ File f=new File(jarPath); scanJarPath(f); } } */ public void scanJarPath(File f){ if(!f.exists()) return; if(f.isDirectory()){ for(File f2 : f.listFiles()){ scanJarPath(f2); } } else { try{ JarClassLoader jc=new JarClassLoader(f); Collection<String> clsNames=jc.listClasses(); for(String clsName : clsNames){ try{ Class cls=jc.loadClass(clsName); if(!WandoraTool.class.isAssignableFrom(cls)){ if(ADDITIONAL_DEBUG) System.out.println("Rejecting '" + cls.getSimpleName() + "'. Does not implement Tool interface!"); continue; } if(cls.isInterface()) { if(ADDITIONAL_DEBUG) System.out.println("Rejecting '" + cls.getSimpleName() + "'. Is interface!"); continue; } try{ Constructor constructor=cls.getConstructor(); Object o=constructor.newInstance(); WandoraTool tool=(WandoraTool)o; //allTools.add(tool); addTool(tool,"jar",f.getAbsolutePath()); } catch(NoSuchMethodException nsme){ if(ADDITIONAL_DEBUG) System.out.println("Rejecting '" + cls.getSimpleName() + "'. No constructor!"); continue; } } catch(Exception ex){ if(ADDITIONAL_DEBUG) System.out.println("Rejecting tool. Exception '" + ex.toString() + "' occurred while investigating '" + clsName + "'."); } } }catch(MalformedURLException mue){ mue.printStackTrace(); }catch(IOException ioe){ ioe.printStackTrace(); } } } // ----------------------------------------------------------- TOOL SETS --- public void readToolSets() { optionsPrefixes = new HashMap<WandoraTool, String>(); toolSets = new ArrayList<WandoraToolSet>(); if(options == null) return; int toolSetIndex = 0; String toolSetName; WandoraToolSet toolSet = null; while(true) { toolSetName = options.get("tool.set["+toolSetIndex+"].name"); if(toolSetName != null) { toolSet = new WandoraToolSet(toolSetName, toolSetIndex, wandora); readToolSet(toolSet, null); toolSets.add(toolSet); } else { break; } toolSetIndex++; } } private WandoraToolSet readToolSet(WandoraToolSet set, String optionsPath) { if(set == null) return null; if(optionsPath == null) optionsPath = "tool.set["+set.getIndex()+"]"; int counter = 0; while(true) { String newPath = optionsPath + ".item["+counter+"]"; String name = options.get(newPath + ".name"); if(name==null) break; String cls = options.get(newPath + ".class"); if(cls != null) { try { WandoraTool tool=null; if(cls.equals(this.getClass().getName())) tool=this; else tool=newToolInstance(findTool(cls)); if(tool!=null){ optionsPrefixes.put(tool, newPath+".options."); tool.initialize(wandora,options,newPath+".options."); set.add(name, tool); } else { System.out.println("Options refer tool class '" + cls + "' not available! Discarding tool!"); } } catch(NoClassDefFoundError ncdfe) { System.out.println("A tool configured in options requires a class that was not found. This is most likely caused by a missing library. Missing class was "+ncdfe.getMessage()+". Discarding tool!"); } catch(Exception e) { System.out.println(e); } } else { //String subtreename = options.get(newPath + ".item[0].name"); //if(subtreename != null) { WandoraToolSet newToolSet = new WandoraToolSet(name, wandora); set.add(readToolSet(newToolSet, newPath)); //} } counter++; } return set; } public void writeToolSets() { options.removeAll("tool.set"); int index = 0; for(WandoraToolSet toolSet : toolSets) { writeToolSet(toolSet, "tool.set["+index+"]"); index++; } } private void writeToolSet(WandoraToolSet set, String optionsPath) { options.removeAll(optionsPath); options.put(optionsPath+".name", set.getName()); // System.out.println("writeToolSet: " + optionsPath + " ---- "+set); Object[] array = set.asArray(); Object o = null; WandoraToolSet.ToolItem toolItem = null; WandoraToolSet innerSet = null; for( int i=0; i<array.length; i++ ) { o = array[i]; if(o instanceof WandoraToolSet.ToolItem) { toolItem = (WandoraToolSet.ToolItem) o; // System.out.println(" "+optionsPath+".item["+i+"].name = "+toolItem.getName()); options.put(optionsPath+".item["+i+"].name", toolItem.getName()); options.put(optionsPath+".item["+i+"].class", toolItem.getTool().getClass().getName()); } else if(o instanceof WandoraToolSet) { innerSet = (WandoraToolSet) o; writeToolSet(innerSet, optionsPath+".item["+i+"]"); } } } public boolean deleteToolSet(WandoraToolSet set) { if(!allowDelete(set)) return false; toolSets.remove(set); writeToolSets(); return true; } public WandoraToolSet createToolSet(String name) { WandoraToolSet newSet = new WandoraToolSet(name, wandora); toolSets.add(newSet); writeToolSets(); return newSet; } /* public void addToolToSet(WandoraToolSet set, WandoraToolSet.ToolItem toolItem) { set.add(toolItem); writeToolSets(); } public void addToolToSet(WandoraToolSet set, WandoraTool tool, String instanceName) { set.add(instanceName, tool); writeToolSets(); } public void addSetToSet(WandoraToolSet set, WandoraToolSet child) { set.add(child); System.out.println("adding set to set: parent == "+set+", child == "+child); writeToolSets(); } public void removeToolOrSet(WandoraToolSet set, Object toolOrSet) { set.remove(toolOrSet); writeToolSets(); } public void renameToolOrSet(WandoraToolSet set, Object toolOrSet, String newName) { if(toolOrSet instanceof WandoraToolSet) { //System.out.println("WandoraToolSet == "+toolOrSet + " --- new name === "+newName+ " --- currentSet = "+set); ((WandoraToolSet) toolOrSet).setName(newName); } else if(toolOrSet instanceof WandoraToolSet.ToolItem) { //System.out.println("WandoraToolSet.ToolItem == "+toolOrSet + " --- new name === "+newName+ " --- currentSet = "+set); ((WandoraToolSet.ToolItem) toolOrSet).setName(newName); } writeToolSets(); } */ public boolean allowDelete(WandoraToolSet set) { if(WandoraToolType.IMPORT_TYPE.equals(set.getName())) return false; if(WandoraToolType.IMPORT_MERGE_TYPE.equals(set.getName())) return false; if(WandoraToolType.EXTRACT_TYPE.equals(set.getName())) return false; if(WandoraToolType.EXPORT_TYPE.equals(set.getName())) return false; if(WandoraToolType.GENERIC_TYPE.equals(set.getName())) return false; if(WandoraToolType.GENERATOR_TYPE.equals(set.getName())) return false; if(WandoraToolType.BROWSER_EXTRACTOR_TYPE.equals(set.getName())) return false; if(WandoraToolType.WANDORA_BUTTON_TYPE.equals(set.getName())) return false; return true; } public WandoraToolSet getToolSet(String name){ for( WandoraToolSet set : toolSets ) { if(set != null) { if(set.getName().equals(name)) { return set; } } } return null; } /* public WandoraTool getToolForName(String name) { WandoraTool t = null; for( WandoraToolSet set : toolSets ) { if(set != null) { t = set.getToolForName(name); if(t != null) { return t; } } } return null; } public WandoraTool getToolForName(String name, WandoraToolSet set) { if(set != null) { WandoraTool t = set.getToolForName(name); if(t != null) { return t; } } return null; } public WandoraTool getToolForRealName(String name) { WandoraTool t = null; for( WandoraToolSet set : toolSets ) { if(set != null) { t = set.getToolForRealName(name); if(t != null) { return t; } } } return null; } public WandoraTool getToolForRealName(String name, WandoraToolSet set) { if(set != null) { WandoraTool t = set.getToolForRealName(name); if(t != null) { return t; } } return null; } */ // ------------------------------------------------------------------------- public String getOptionsPrefix(WandoraTool tool) { String prefix = null; try { prefix = optionsPrefixes.get(tool); } catch(Exception e) {} return prefix; } // ------------------------------------------------------------------------- public void execute(Wandora w, Context context) { scanAllTools(); readToolSets(); JDialog d=new JDialog(w,"Tool Manager",true); WandoraToolManagerPanel2 panel=new WandoraToolManagerPanel2(this, d, wandora); d.getContentPane().add(panel); d.setSize(900,400); org.wandora.utils.swing.GuiTools.centerWindow(d, w); d.setVisible(true); // ***** WAIT TILL USER CLOSES TOOL MANAGER DIALOG writeToolSets(); scanAllTools(); readToolSets(); toolsChanged(); } @Override public String getName() { return "Tool manager v2..."; } @Override public String getDescription() { return "Manage Wandora's tools and tool sets."; } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- public Object[] getToolButtonSelectMenuStruct() { String[] set = getToolButtonSetNames(); ArrayList<Object> menuStruct = new ArrayList<Object>(); for(int i=0; i<set.length; i++) { menuStruct.add( set[i] ); menuStruct.add( new ActivateButtonToolSet( set[i] ) ); if(i<buttonSetAccelerators.length) { menuStruct.add(buttonSetAccelerators[i]); } } return menuStruct.toArray(); } public JMenu getToolButtonSelectMenu() { Object[] struct = new Object[] { "Select button tool set", getToolButtonSelectMenuStruct() }; return UIBox.makeMenu(struct, wandora); } public JPopupMenu getToolButtonSelectPopupMenu() { return UIBox.makePopupMenu(getToolButtonSelectMenuStruct(), wandora); } public String[] getToolButtonSetNames() { ArrayList<String> buttonSets = new ArrayList<String>(); if(toolSets != null) { String name = null; for(WandoraToolSet set : toolSets) { name = set.getName(); if(name != null && name.indexOf("button") != -1) { buttonSets.add(name); } } } return buttonSets.toArray( new String[] {} ); } public JComponent getToolButtonBar() { return getToolButtonBar(WandoraToolType.WANDORA_BUTTON_TYPE); } public JComponent getToolButtonBar(String setName) { WandoraToolSet toolset = getToolSet(setName); if(toolset != null && toolset.size() > 0) { Object[] struct = toolset.getAsObjectArray(); JComponent buttonbar = UIBox.makeButtonContainer(struct, wandora); if(buttonbar != null) { return buttonbar; } } return null; } // ------------------------------------------------------------------------- public JMenu getToolMenu(){ JMenu toolMenu = new SimpleMenu("Tools"); toolMenu.setIcon(null); toolMenu = getToolMenu(toolMenu); return toolMenu; } public JMenu getToolMenu(JMenu toolMenu){ toolMenu = getMenu(toolMenu, getToolSet(WandoraToolType.GENERIC_TYPE), accelerators, 0); ClearToolLocks clearToolLocks = new ClearToolLocks(); toolMenu.insert(clearToolLocks.getToolMenuItem(wandora, clearToolLocks.getName(), KeyStroke.getKeyStroke(KeyEvent.VK_Y, InputEvent.CTRL_MASK)), 0); JMenu buttonSelectorSubmenus = this.getToolButtonSelectMenu(); toolMenu.insert(buttonSelectorSubmenus, 1); toolMenu.insert(this.getToolMenuItem(wandora, getName(), KeyStroke.getKeyStroke(KeyEvent.VK_T, InputEvent.CTRL_MASK)), 0); toolMenu.insertSeparator(2); toolMenu.insertSeparator(4); return toolMenu; } public JMenu getGeneratorMenu() { JMenu toolMenu = new SimpleMenu("Generate"); toolMenu.setIcon( UIBox.getIcon("gui/icons/generate.png") ); return getGeneratorMenu(toolMenu); } public JMenu getGeneratorMenu(JMenu toolMenu){ return getMenu(toolMenu, WandoraToolType.GENERATOR_TYPE); } public JMenu getExtractMenu() { JMenu toolMenu = new SimpleMenu("Extract"); toolMenu.setIcon( UIBox.getIcon("gui/icons/extract.png") ); return getExtractMenu(toolMenu); } public JMenu getExtractMenu(JMenu toolMenu){ return getMenu(toolMenu, WandoraToolType.EXTRACT_TYPE); } public JMenu getImportMergeMenu(JMenu toolMenu) { toolMenu.removeAll(); WandoraToolSet toolSet = getToolSet(WandoraToolType.IMPORT_MERGE_TYPE); if(toolSet == null) return toolMenu; List toolItems = toolSet.getTools(); for(Object toolItem : toolItems) { if(toolItem != null) { if(toolItem instanceof WandoraToolSet.ToolItem) { WandoraTool tool = ((WandoraToolSet.ToolItem) toolItem).getTool(); if(tool instanceof AbstractImportTool) { AbstractImportTool aiTool = (AbstractImportTool) tool; aiTool.setOptions(AbstractImportTool.TOPICMAP_DIRECT_MERGE); } } } } return toolSet.getMenu(toolMenu, toolSet); } public JMenu getImportMenu(){ JMenu toolMenu = new SimpleMenu("Import"); toolMenu.setIcon( UIBox.getIcon("gui/icons/import.png") ); return getImportMenu(toolMenu); } public JMenu getImportMenu(JMenu toolMenu){ return getMenu(toolMenu, WandoraToolType.IMPORT_TYPE); } public JMenu getExportMenu(){ JMenu toolMenu = new SimpleMenu("Export"); toolMenu.setIcon( UIBox.getIcon("gui/icons/export.png") ); return getExportMenu(toolMenu); } public JMenu getExportMenu(JMenu toolMenu){ return getMenu(toolMenu, WandoraToolType.EXPORT_TYPE); } public JMenu getMenu(JMenu toolMenu, String setName){ return getMenu(toolMenu, getToolSet(setName), null, 0); } public JMenu getMenu(JMenu toolMenu, WandoraToolSet toolSet, KeyStroke[] keyStrokes, int strokeIndex) { toolMenu.removeAll(); if(toolSet == null) return toolMenu; return toolSet.getMenu(toolMenu, toolSet); } // ------------------------------------------------------------------------- public static ArrayList<WandoraTool> getImportTools(java.util.List<File> files, int orders){ String fileName = null; ArrayList<WandoraTool> importTools = new ArrayList<WandoraTool>(); for( File file : files ) { fileName = file.getName().toLowerCase(); if(fileName.endsWith(".xtm20") || fileName.endsWith(".xtm2") || fileName.endsWith(".xtm10") || fileName.endsWith(".xtm1") || fileName.endsWith(".xtm") || fileName.endsWith(".ltm") || fileName.endsWith(".jtm")) { TopicMapImport importer = new TopicMapImport(orders); importer.forceFiles = file; importTools.add(importer); } else if(fileName.endsWith(".rdf") || fileName.endsWith(".rdfs") || fileName.endsWith(".owl") || fileName.endsWith(".daml")) { SimpleRDFImport importer = new SimpleRDFImport(orders); importer.forceFiles = file; importTools.add(importer); } else if(fileName.endsWith(".n3")) { SimpleN3Import importer = new SimpleN3Import(orders); importer.forceFiles = file; importTools.add(importer); } else if(fileName.endsWith(".obo")) { OBOImport importer = new OBOImport(orders); importer.forceFiles = file; importTools.add(importer); } else if(fileName.endsWith(".wpr")) { if(importTools.isEmpty()) { LoadWandoraProject loader = new LoadWandoraProject(file); importTools.add(loader); } else { MergeWandoraProject merger = new MergeWandoraProject(file); importTools.add(merger); } } else { importTools.add(null); } } return importTools; } public void toolsChanged() { if(wandora != null) wandora.toolsChanged(); } // ------------------------------------------------------------------------- public static class ToolInfo { public WandoraTool tool; public String sourceType; public String source; public ToolInfo() { } public ToolInfo(WandoraTool tool, String sourceType, String source) { this.tool = tool; this.sourceType = sourceType; this.source = source; } } }
33,446
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ErrorMessages.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/ErrorMessages.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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; import org.wandora.exceptions.OpenTopicNotSupportedException; /** * This class contains static methods to transform some common Java exceptions and errors to * error messages. Messages can be viewed to the user using the ErrorHandler, for example. * * @author akivela */ public class ErrorMessages { public static String getMessage(Throwable e) { String msg = "An exception has occurred in Wandora."; if(e != null) { if(e instanceof org.wandora.topicmap.TopicMapReadOnlyException) { msg = "Can't change current topic map because current topic map is read-only topic map. "+ "Check if the current topic map layer is locked and unlock the layer "+ "or discard changes. Topic map layer is unlocked by clicking the lock icon beside the layer name."; } else if(e instanceof org.wandora.topicmap.TopicMapException) { msg = "Can't perform topic map operations because of the TopicMapException. "+ "Look at the stacktrace for details. "+ "If this message appears again, we suggest you save your project project and restart Wandora application."; } else if(e instanceof java.util.regex.PatternSyntaxException) { msg = "Wandora uses regular expressions for search and replace. " + "The given regular expression pattern contains an error: <br><br>"+ "<pre>"+ e.getMessage()+ "</pre><br><br>"+ "For more information see Java's Pattern API documentation at "+ "https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html"; } else if(e instanceof OpenTopicNotSupportedException) { msg = "The topic panel can't open a topic. "+ "In other words, the open topic operation is not supported by the topic panel. "+ "You can select or create another topic panel and try again."; } else if(e instanceof java.lang.OutOfMemoryError) { msg = "Wandora is running out of memory. "+ "Save your project and restart Wandora application. "+ "If possible, use startup script with larger memory."; } else if(e instanceof java.lang.StackOverflowError) { msg = "Wandora is running out of stack memory (StackOverflowError). "+ "Save your project and restart Wandora application."; } else if(e instanceof java.lang.VirtualMachineError) { msg = "Wandora uses Java Virtual Machine for execution and the Java Virtual Machine is broken or has run out of resources necessary for it to continue operating. "+ "Save your project and restart Wandora application. "+ "If this message appears again, try to reinstall Java Virtual Machine (JRE)."; } else { msg = "An error has occurred in Wandora. Error message follows:\n\n"+e.getMessage(); } } return msg; } public static String getMessage(Throwable e, WandoraTool t) { String msg = getMessage(e); return msg; } }
4,377
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
WandoraTool.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/WandoraTool.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * WandoraTool.java * * Created on June 17, 2004, 3:35 PM */ package org.wandora.application; import java.awt.event.ActionEvent; import java.io.Serializable; import javax.swing.Icon; import org.wandora.application.contexts.Context; import org.wandora.application.gui.simple.SimpleMenuItem; import org.wandora.topicmap.TopicMapException; import org.wandora.utils.Options; /** * The interface for Wandora tools. Wandora tool is a fundamental way of packing * actions in Wandora. Instead of implementing this interface directly, you * should extend <code>AbstractWandoraTool</code>. It contains implementation * for most of the interface methods and eases developing tools. * * @see org.wandora.application.tools.AbstractWandoraTool * @author olli, akivela */ public interface WandoraTool extends WandoraToolLogger, Serializable { /** * Return tool's name. * * @return String representing tool's name. */ public String getName(); /** * Returns description of the tool. * * @return String representing tool's description. */ public String getDescription(); /** * Runs the tool. * * @param wandora is the application context. * @param actionEvent is the event triggering the event. * @throws TopicMapException */ public void execute(Wandora wandora, ActionEvent actionEvent) throws TopicMapException; /** * Runs the tool. This is the main entry to the tool. Here the context * * * @param wandora * @param context * @throws TopicMapException */ public void execute(Wandora wandora, Context context) throws TopicMapException; /** * Runs the tool. * * @param wandora * @throws TopicMapException */ public void execute(Wandora wandora) throws TopicMapException; /** * Returns boolean value true if the tool is running and false if the * execution has ended. * * @return true if the tool is running. */ public boolean isRunning(); /** * Set tool's execution context. The context contains topics and associations * the tool should process, and application component that was active * when the tool was executed. Usually the context is given as an argument * while executing the tool. * * @param context Tool's new context. */ public void setContext(Context context); /** * Get tool's execution context. * * @return Context object. */ public Context getContext(); /** * Returns tool's type. Tool type is a deprecated feature. It was originally * used to distinguish tools that import, extract and export something. * These days it has no strict meaning in Wandora. * * @return Tool's type object. */ public WandoraToolType getType(); // ------------------------------------------------------- CONFIGURATION --- /** * Read settings from options and initialize tool. * * @param wandora * @param options * @param prefix * @throws org.wandora.topicmap.TopicMapException */ public void initialize(Wandora wandora, Options options, String prefix) throws TopicMapException; /** * Return true if tool has something to configure. * * @return true if the tool is configurable. */ public boolean isConfigurable(); /** * Open configuration dialog and allow user to configure the tool. Should save * changes to options after the configuration. * * @param wandora * @param options * @param prefix * @throws org.wandora.topicmap.TopicMapException */ public void configure(Wandora wandora, Options options, String prefix) throws TopicMapException; /** * Save current tool settings to options. * * @param wandora * @param options * @param prefix */ public void writeOptions(Wandora wandora,Options options,String prefix); /** * Should the Wandora application refresh. Refresh is required if the tool * changed options, topics or associations, or any other setting that * has an effect to the user interface. * * @return true if Wandora application should refresh user interface. */ public boolean requiresRefresh(); public SimpleMenuItem getToolMenuItem(Wandora wandora, String instanceName); //public WandoraButton getToolButton(Wandora admin); //public WandoraButton getToolButton(Wandora admin, int styleHints); /** * Return tool's icon. Wandora views the icon in the user interface. * * @return icon for the tool. */ public Icon getIcon(); // -------------------------------------------------------------- LOGGER --- /** * Sets tools logger. Logger is used to output textual message about * the progress of tool execution. * * @param logger is new logger object. */ public void setToolLogger(WandoraToolLogger logger); /** * Shortcut to access tool's logger. * * @param message to be logged. */ @Override public void hlog(String message); /** * Shortcut to access tool's logger. * * @param message to be logged. */ @Override public void log(String message); /** * Shortcut to access tool's logger. * * @param message to be logged. * @param e Exception to be logged. */ @Override public void log(String message, Exception e); /** * Shortcut to access tool's logger. * * @param e Exception to be logged. */ @Override public void log(Exception e); /** * Shortcut to access tool's logger. * * @param e Error to be logged. */ @Override public void log(Error e); }
6,893
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
WandoraToolSet.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/WandoraToolSet.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * WandoraToolSet.java * * Created on 17.2.2009, 16:00 * */ package org.wandora.application; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.swing.JMenu; import javax.swing.JSeparator; import org.wandora.application.gui.simple.SimpleMenu; import org.wandora.application.gui.simple.SimpleMenuItem; import org.wandora.utils.Textbox; /** * * @author akivela */ public class WandoraToolSet implements Serializable { private static final long serialVersionUID = 1L; private int index = 0; private String name = null; private List tools = new ArrayList(); private Wandora wandora = null; public WandoraToolSet(String n, Wandora w) { this.name = n; this.wandora = w; } public WandoraToolSet(String n, int i, Wandora w) { this.name = n; this.index = i; this.wandora = w; } public void add(Object o) { if(o instanceof ToolItem || o instanceof WandoraToolSet) { tools.add(o); } } public void add(Object o, int index) { if(o instanceof ToolItem || o instanceof WandoraToolSet) { tools.add(index, o); } } public void add(String name, WandoraTool t, int index) { tools.add(index, new ToolItem(name, t)); } public void add(String name, WandoraTool t) { tools.add(new ToolItem(name, t)); } public String getName() { return name; } public void setName(String n) { this.name = n; } public int getIndex() { return index; } @Override public String toString() { return name; } public int size() { return tools.size(); } public String getNameForTool(WandoraTool tool) { return getNameForTool(tool, tools); } public String getNameForTool(WandoraTool tool, List set) { for(Object o : set) { if(o != null) { if(o instanceof ToolItem) { ToolItem t = (ToolItem) o; if(tool.equals(t.getTool())) { return t.getName(); } } else if(o instanceof WandoraToolSet) { WandoraToolSet ts = (WandoraToolSet) o; String n = ts.getNameForTool(tool); if(n != null) return n; } } } return null; } public Object getToolWrapperWithHash(int hash) { for(Object o : tools) { if(o != null) { if(o instanceof ToolItem) { if(hash == o.hashCode()) { return o; } } else if(o instanceof WandoraToolSet) { WandoraToolSet ts = (WandoraToolSet) o; Object s = ts.getToolWrapperWithHash(hash); if(s != null) return s; } } } if(hash == this.hashCode()) return this; return null; } public WandoraTool getToolForRealName(String name) { return getToolForRealName(name, tools); } public WandoraTool getToolForRealName(String name, List set) { for(Object o : set) { if(o != null) { if(o instanceof ToolItem) { ToolItem t = (ToolItem) o; if(name.equals(t.getTool().getName())) { return t.getTool(); } } else if(o instanceof WandoraToolSet) { WandoraToolSet ts = (WandoraToolSet) o; WandoraTool t = ts.getToolForRealName(name); if(t != null) return t; } } } return null; } public WandoraTool getToolForName(String name) { return getToolForName(name, tools); } public WandoraTool getToolForName(String name, List set) { for(Object o : set) { if(o != null) { if(o instanceof ToolItem) { ToolItem t = (ToolItem) o; if(name.equals(t.getName())) { return t.getTool(); } } else if(o instanceof WandoraToolSet) { WandoraToolSet ts = (WandoraToolSet) o; WandoraTool t = ts.getToolForName(name); if(t != null) return t; } } } return null; } public List getTools() { if(tools == null) { tools = new ArrayList(); } return tools; } public boolean remove(Object toolOrSet) { if(toolOrSet == null) return false; for(Object o : tools) { if(o != null) { if(toolOrSet.equals(o)) { tools.remove(o); return true; } else if(o instanceof WandoraToolSet) { WandoraToolSet ts = (WandoraToolSet) o; boolean removed = ts.remove(toolOrSet); if(removed) return true; } } } return false; } public JMenu getMenu(JMenu toolMenu) { return getMenu(toolMenu, this); } public JMenu getMenu(JMenu toolMenu, WandoraToolSet toolSet) { toolMenu.removeAll(); if(toolSet == null) return toolMenu; for(Object o : toolSet.getTools()) { if(o instanceof WandoraToolSet) { WandoraToolSet subTools = (WandoraToolSet) o; if(subTools.size() > 0) { JMenu subMenu = new SimpleMenu(subTools.getName()); getMenu(subMenu, subTools); toolMenu.add(subMenu); } } else if(o instanceof ToolItem) { ToolItem wrappedTool = (ToolItem) o; String toolName = wrappedTool.getName(); if(toolName.startsWith("---")) { toolMenu.add(new JSeparator()); } else { WandoraTool tool = wrappedTool.getTool(); SimpleMenuItem item = tool.getToolMenuItem(wandora, toolName); item.setToolTipText(Textbox.makeHTMLParagraph(tool.getDescription(), 40)); toolMenu.add(item); } } } return toolMenu; } public Object[] getAsObjectArray() { return getAsObjectArray(this, null); } public Object[] getAsObjectArray(ToolFilter filter) { Object[] array = getAsObjectArray(this, filter); return array; } public Object[] getAsObjectArray(WandoraToolSet toolSet) { return getAsObjectArray(toolSet, null); } public Object[] getAsObjectArray(WandoraToolSet toolSet, ToolFilter filter) { List array = new ArrayList(); if(toolSet == null) return array.toArray(); boolean previousWasSeparator = true; for(Object o : toolSet.getTools()) { if(o instanceof WandoraToolSet) { WandoraToolSet subTools = (WandoraToolSet) o; if(subTools.size() > 0) { Object[] subArray = getAsObjectArray(subTools, filter); if(subArray != null && subArray.length > 0) { array.add(subTools.getName()); array.add(subArray); previousWasSeparator = false; } } } else if(o instanceof ToolItem) { ToolItem toolItem = (ToolItem) o; String toolName = toolItem.getName(); if(toolName.startsWith("---")) { if(!previousWasSeparator) { array.add(toolName); } previousWasSeparator = true; } else { WandoraTool tool = toolItem.getTool(); if(filter == null || filter.acceptTool(tool)) { array.add(toolName); array.add(filter == null ? tool : filter.polishTool(tool)); previousWasSeparator = false; if(filter != null) { Object[] extra = filter.addAfterTool(tool); if(extra != null && extra.length > 0) { array.addAll(Arrays.asList(extra)); } } } } } } return array.toArray(); } public Object[] asArray() { return tools.toArray(); } public Map<String,WandoraTool> getAsMap() { return getAsMap(this, null); } public Map<String,WandoraTool> getAsMap(ToolFilter filter) { Map<String,WandoraTool> map = getAsMap(this, filter); return map; } public Map<String,WandoraTool> getAsMap(WandoraToolSet toolSet) { return getAsMap(toolSet, null); } public Map<String,WandoraTool> getAsMap(WandoraToolSet toolSet, ToolFilter filter) { Map map = new LinkedHashMap(); if(toolSet == null) return map; for(Object o : toolSet.getTools()) { if(o instanceof WandoraToolSet) { WandoraToolSet subTools = (WandoraToolSet) o; if(subTools.size() > 0) { Map subMap = getAsMap(subTools, filter); if(subMap != null && !subMap.isEmpty()) { map.putAll(subMap); } } } else if(o instanceof ToolItem) { ToolItem toolItem = (ToolItem) o; WandoraTool tool = toolItem.getTool(); if(filter == null || filter.acceptTool(tool)) { String toolName = toolItem.getName(); map.put(toolName, tool); } } } return map; } // ------------------------------------------------------------------------- public class ToolFilter { public boolean acceptTool(WandoraTool tool) { return true; } public WandoraTool polishTool(WandoraTool tool) { return tool; } public Object[] addAfterTool(WandoraTool tool) { return null; } } // ------------------------------------------------------------------------- public class ToolItem implements Serializable { private String name = null; private WandoraTool tool = null; public ToolItem(String n, WandoraTool t) { this.name = n; this.tool = t; } public String getName() { return name; } public void setName(String n) { this.name = n; } public WandoraTool getTool() { return tool; } @Override public String toString() { return name; } } }
12,232
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
WandoraToolType.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/WandoraToolType.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * WandoraToolType.java * * Created on Jan 12, 2009 */ package org.wandora.application; import java.util.HashSet; import java.util.Iterator; import java.util.Set; /** * * @author akivela */ public class WandoraToolType { public static final String WANDORA_BUTTON_TYPE = "Default buttons"; public static final String BROWSER_EXTRACTOR_TYPE = "Browser extractors"; public static final String GENERIC_TYPE = "generic"; public static final String IMPORT_TYPE = "import"; public static final String IMPORT_MERGE_TYPE = "import-merge"; public static final String EXPORT_TYPE = "export"; public static final String EXTRACT_TYPE = "extract"; public static final String GENERATOR_TYPE = "generator"; private Set<String> types = new HashSet<String>(); public WandoraToolType(String type) { types.add(type); } public WandoraToolType(String type1, String type2) { types.add(type1); types.add(type2); } public WandoraToolType(String type1, String type2, String type3) { types.add(type1); types.add(type2); types.add(type3); } public Set<String> asSet() { return types; } public String oneType() { if(!types.isEmpty()) return types.iterator().next(); else return null; } // ------------------------------------------------------ TEST THIS TYPE --- public boolean isOfType(String t) { return types.contains(t); } public boolean isOfType(String t1, String t2) { return (types.contains(t1) && types.contains(t2)); } public boolean isOfType(String t1, String t2, String t3) { return (types.contains(t1) && types.contains(t2) && types.contains(t3)); } // --------------------------------------------------------- MODIFY TYPE --- public void addType(String t) { types.add(t); } public void removeType(String t) { types.remove(t); } // ---------------------------------------------------- STATIC FACTORIES --- public static WandoraToolType createGenericType() { return new WandoraToolType(GENERIC_TYPE); } public static WandoraToolType createImportType() { return new WandoraToolType(IMPORT_TYPE); } public static WandoraToolType createExportType() { return new WandoraToolType(EXPORT_TYPE); } public static WandoraToolType createExtractType() { return new WandoraToolType(EXTRACT_TYPE); } public static WandoraToolType createGeneratorType() { return new WandoraToolType(GENERATOR_TYPE); } public static WandoraToolType createImportExportType() { return new WandoraToolType(IMPORT_TYPE, EXPORT_TYPE); } // ------------------------------------------------------------------------- @Override public String toString() { StringBuilder sb = new StringBuilder(""); for( Iterator<String> typeIterator = types.iterator(); typeIterator.hasNext(); ) { sb.append(typeIterator.next()); if(typeIterator.hasNext()) { sb.append(", "); } } return sb.toString(); } }
4,158
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Wandora.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/Wandora.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * Wandora.java * * * * Created on June 8, 2004, 11:22 AM */ package org.wandora.application; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dialog; import java.awt.Dimension; import java.awt.Point; import java.awt.Toolkit; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseListener; import java.awt.image.BufferedImage; import java.io.File; import java.net.URLConnection; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JToolBar; import javax.swing.JViewport; import org.wandora.application.gui.ErrorDialog; import org.wandora.application.gui.LayerTree; import org.wandora.application.gui.LogoAnimation; import org.wandora.application.gui.SplashWindow; import org.wandora.application.gui.TabbedTopicSelector; import org.wandora.application.gui.TopicEditorPanel; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.UIConstants; import org.wandora.application.gui.search.QueryPanel; import org.wandora.application.gui.search.SearchPanel; import org.wandora.application.gui.search.SimilarityPanel; import org.wandora.application.gui.simple.SimpleButton; import org.wandora.application.gui.simple.SimpleLabel; import org.wandora.application.gui.simple.SimplePanel; import org.wandora.application.gui.simple.SimpleTabbedPane; import org.wandora.application.gui.topicpanels.TopicPanel; import org.wandora.application.gui.topicpanels.TopicPanelManager; import org.wandora.application.gui.topicstringify.TopicToString; import org.wandora.application.gui.tree.TopicTree; import org.wandora.application.gui.tree.TopicTreePanel; import org.wandora.application.gui.tree.TopicTreeTabManager; import org.wandora.application.modulesserver.WandoraModulesServer; import org.wandora.application.tools.importers.SimpleN3Import; import org.wandora.application.tools.importers.SimpleRDFImport; import org.wandora.application.tools.importers.SimpleRDFJsonLDImport; import org.wandora.application.tools.importers.SimpleRDFTurtleImport; import org.wandora.application.tools.importers.TopicMapImport; import org.wandora.application.tools.navigate.Back; import org.wandora.application.tools.navigate.Forward; import org.wandora.application.tools.navigate.OpenTopic; import org.wandora.application.tools.project.LoadWandoraProject; import org.wandora.exceptions.OpenTopicNotSupportedException; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicMapListener; import org.wandora.topicmap.layered.ContainerTopicMap; import org.wandora.topicmap.layered.Layer; import org.wandora.topicmap.layered.LayerStack; import org.wandora.topicmap.layered.LayeredTopic; import org.wandora.topicmap.memory.TopicMapImpl; import org.wandora.topicmap.undowrapper.UndoException; import org.wandora.topicmap.undowrapper.UndoTopicMap; import org.wandora.utils.CMDParamParser; import org.wandora.utils.Delegate; import org.wandora.utils.Options; import org.wandora.utils.Textbox; import org.wandora.utils.Tuples.T2; import org.wandora.utils.logger.Logger; import org.wandora.utils.logger.SystemOutLogger; import org.wandora.utils.swing.ImagePanel; /** * * The main frame of Wandora application. Contains, among other things, initialization * of the application, top level handling tools, topic trees, browse history, * application options, topic map event propagation and user interaction. * * @author olli, akivela */ public class Wandora extends javax.swing.JFrame implements ErrorHandler, ActionListener, MouseListener, TopicMapListener { private static final long serialVersionUID = 1L; /* * If the application makes URL requests and the URL stream is initialized * properly, USER_AGENT is a user agent string for Wandora application. */ public static String USER_AGENT = "Wandora"; /* * Static variable that is initialized during application startup. Contains * a reference to a running Wandora application. Variable is returned * with a static method called <code>getWandora</code>. */ private static Wandora wandora = null; /* * Most menu structures of Wandora are stored and initialized in * <code>menuManager</code>. */ public WandoraMenuManager menuManager; /* * The main topic map in Wandora is a layer stack. Notice that layer stack * is not a real topic map implementation that can it self store topics and * associations. Layer stack needs a real topic map implementation inside * to be usable. */ private LayerStack topicMap; /* * <code>layerTree</code> is a UI component that is used to view the * layer stack topic map. Notice that the <code>LayerTree</code> is * actually a modified <code>JTree</code>. */ public LayerTree layerTree; /* * <code>topicPanelManager</code> handles the topic editors and visualizations in * Wandora's main frame. It is one of the big UI elements of Wandora and * provides content for the editorPanel. Notice that the default topic panel * is a DockingFramePanel at the moment. */ public TopicPanelManager topicPanelManager; /* * <code>searchPanel</code> stores the UI component for the search * tab in the Wandora application. Search tab locates in left upper * corner, beside the Topics tab of Wandora application. */ private SearchPanel searchPanel; /* * <code>toolmanager</code> is a special manager that is used handle * all available tool classes and class paths. It has a UI of it's own * that can be used to customize button lists, import and extract features * for example. */ public WandoraToolManager2 toolManager; /* * <code>options</code> is a data structure that contains application * specific information required to initialize the application. <code>options</code> * is read from XML file <code>conf/options.xml</code> at startup and * stored to the same file at shutdown. Broken or incomplete options data structure * may prevent running the Wandora application. */ public Options options; /* * If Wandora faces an HTTP authentication, during an extraction, for exmple, * a user name and a password are resolved using <code>wandoraHttpAuthorizer</code>. * <code>wandoraHttpAuthorizer</code> asks these from the Wandora user if * suitable information has not been provided earlier. Notice that * <code>wandoraHttpAuthorizer</code> doesn't store given user names nor * passwords over use sessions. */ public WandoraHttpAuthorizer wandoraHttpAuthorizer; /* * <code>topicHilights</code> implements a hidden feature in Wandora application. * It is poorly used at the moment. <code>topicHilights</code> provides * a way to color topics in Wandora's user interface. */ public TopicHilights topicHilights; public TopicMap clipboardtm = new org.wandora.topicmap.memory.TopicMapImpl(); public Shortcuts shortcuts; private String frameTitle="Wandora"; private Set<TopicMapListener> topicMapListeners; private Set<RefreshListener> refreshListeners; private Component focusOwner; private JPopupMenu backPopup = new JPopupMenu(); private JPopupMenu forwardPopup = new JPopupMenu(); private Set<Object> animationCallers = new LinkedHashSet<>(); private TopicTreeTabManager topicTreeManager = null; /* * If application user has explicitly opened a project file or has saved a * project file, the application knows the name of the project file. Known * project file name is stored in variable <code>currentProjectFileName</code>. * It is viewed in the application top bar. */ private String currentProjectFileName = null; /* * Wandora contains an embedded HTTP server. Variable <code>httpServer</code> * contains a reference to the embedded HTTP server. */ // public WandoraWebAppServer httpServer; public WandoraModulesServer httpServer; /* * <code>wandoraIcons</code> is a data structure for Wandora application icons. */ public List<BufferedImage> wandoraIcons = new ArrayList<>(); /* * Current implementation of back and forward butons uses a global * data structure implemented in <code>LocatorHistory</code> class. <code>history</code> * is a variable that contains the actual navigation history of Wandora * application. */ private LocatorHistory history = new LocatorHistory(); /* * Not in use at the moment. */ private boolean skipTopicMapListenerEvents = false; private TabbedTopicSelector topicSelector = null; /** Creates new form Wandora */ public Wandora() throws java.io.IOException { this(null); } public Wandora(CMDParamParser cmdparams) { Wandora.wandora = this; if(cmdparams != null && cmdparams.isSet("options")) { this.options = new Options(cmdparams.get("options")); } else { this.options = new Options("conf/options.xml"); } try { wandoraIcons.add( UIBox.getImage("gui/appicon/64x64_24bit.png") ); wandoraIcons.add( UIBox.getImage("gui/appicon/48x48_24bit.png") ); wandoraIcons.add( UIBox.getImage("gui/appicon/32x32_24bit.png") ); wandoraIcons.add( UIBox.getImage("gui/appicon/24x24_24bit.png") ); wandoraIcons.add( UIBox.getImage("gui/appicon/16x16.png") ); wandoraIcons.add( UIBox.getImage("gui/appicon/icon.gif") ); } catch(Exception e) { e.printStackTrace(); } try { topicMapListeners=new LinkedHashSet<>(); refreshListeners=new LinkedHashSet<>(); //JPopupMenu.setDefaultLightWeightPopupEnabled(false); initComponents(); initializeWandora(); } catch(Exception e) { displayException("Exception occurred during startup!", e); } } public WandoraModulesServer getHTTPServer(){ if(httpServer==null) { try { // httpServer=new WandoraHttpServer(this); // httpServer=new WandoraWebAppServer(this); httpServer=new WandoraModulesServer(this); httpServer.setStatusComponent(serverButton,"gui/icons/server_start.png","gui/icons/server_stop.png","gui/icons/server_hit.png"); } catch(Exception e) { handleError(e); } } return httpServer; } public void startHTTPServer() { WandoraModulesServer server = getHTTPServer(); if(server != null) { server.start(); menuManager.refreshServerMenu(); } } public void stopHTTPServer() { WandoraModulesServer server = getHTTPServer(); if(server != null) { server.stopServer(); } } public JPanel getStartupPanel(){ return startupPanel; } public void addRefreshListener(RefreshListener l){ refreshListeners.add(l); } public void removeRefreshListener(RefreshListener l){ refreshListeners.remove(l); } public void addTopicMapListener(TopicMapListener l){ topicMapListeners.add(l); } public void removeTopicMapListener(TopicMapListener l){ topicMapListeners.remove(l); } /** * <p> * Informs refresh listeners that now is an appropriate time to refresh any * components that contain information about the topic map that may have changed. * This method should be called after a tool has finished modifying topic map * or any other operation that modifies topic map is finished. It shouldn't * be called after every single minor change to topic map while the complete operation * is still unfinished.</p> * <p> * Effectively informs the listeners that a complex logical * operation which consists of several small changes to topic map has finished.</p> * <p> * Listeners will include topic trees, topic panels and any such components * that contain information about topic map that needs to be kept up to date. * </p> */ private boolean alreadyRefreshing = false; public void doRefresh() { if(!alreadyRefreshing) { alreadyRefreshing = true; try { topicMap.clearTopicMapIndexes(); } catch(Exception e) { // IGNORE } Collection<RefreshListener> duplicate=new ArrayList<>(); duplicate.addAll(refreshListeners); // refresh may result in closeTopic which modifies refreshListeners for(RefreshListener l : duplicate){ try { l.doRefresh(); } catch(Exception tme){ handleError(tme); } } refreshInfoFields(); menuManager.refreshViewMenu(); alreadyRefreshing = false; addUndoMarker(); } } public WandoraToolManager2 getToolManager(){ return toolManager; } public JViewport getViewPort() { return contentScrollPane.getViewport(); } /** * Creates a new layered topic map and initializes it with the base topic map. */ public void initializeTopicMap() throws TopicMapException { topicMap=new LayerStack(); try{ topicMap.setUseUndo(true); } catch(UndoException ue){handleError(ue);} TopicMap initialTopicMap = new org.wandora.topicmap.memory.TopicMapImpl(); try { String basemapFile = options.get("basemap"); if(!new File(basemapFile).exists()) { basemapFile = "resources/"+basemapFile; if(!new File(basemapFile).exists()) { basemapFile = "build/"+basemapFile; } } initialTopicMap.importTopicMap(basemapFile); } catch(Exception e) { handleError(e); } topicMap.addLayer(new Layer(initialTopicMap, "Base", topicMap)); topicMap.resetTopicMapChanged(); this.setCurrentProjectFileName(null); } /** * Called when the topic map object is changed to another topic map object. */ private void topicMapObjectChanged(){ layerTree=new LayerTree(topicMap,this); layerTree.setChangingListener(new Delegate<Boolean,Object>() { @Override public Boolean invoke(Object o) { TopicPanel topicPanel = topicPanelManager.getCurrentTopicPanel(); boolean reponse = true; if(topicPanel!=null) { try { topicPanel.applyChanges(); } catch(CancelledException ce) { reponse = false; } catch(TopicMapException tme) { handleError(tme); reponse = false; } } return reponse; } }); layerTree.setChangedListener(new Delegate<Object,Object>(){ @Override public Object invoke(Object o){ try { refreshTopicTrees(); doRefresh(); } catch(Exception e) { handleError(e); } return null; } }); layersPanel.removeAll(); layersPanel.add(layerTree,BorderLayout.CENTER); topicMap.addTopicMapListener(this); topicTreeManager = new TopicTreeTabManager(this, tabbedPane); topicTreeManager.initializeTopicTrees(); tabbedPane.addTab("Finder", finderPanel); searchPanel = new SearchPanel(); finderPanel.removeAll(); finderPanel.add(searchPanel, BorderLayout.CENTER); } private void removeButtonActionListeners(JButton b){ ActionListener[] listeners=b.getActionListeners(); for (ActionListener listener : listeners) { b.removeActionListener(listener); } } /** * Performs most of Wandora initialization. */ public void initializeWandora() { try { USER_AGENT = options.get("httpuseragent"); currentProjectFileName = null; this.focusOwner = null; this.topicHilights = new TopicHilights(this); this.topicPanelManager = new TopicPanelManager(this); this.toolManager = new WandoraToolManager2(this); initializeTopicMap(); topicMapObjectChanged(); // this also initializes topic trees placeWindow(); history = new LocatorHistory(); backButton.setEnabled(false); forwardButton.setEnabled(false); removeButtonActionListeners(openButton); removeButtonActionListeners(backButton); removeButtonActionListeners(forwardButton); openButton.addActionListener(new WandoraToolActionListener(this, new OpenTopic(OpenTopic.ASK_USER))); backButton.addActionListener(new WandoraToolActionListener(this, new Back())); forwardButton.addActionListener(new WandoraToolActionListener(this, new Forward())); backButton.setComponentPopupMenu(backPopup); forwardButton.setComponentPopupMenu(forwardPopup); openButton.addMouseListener( new MouseAdapter() { @Override public void mouseEntered(java.awt.event.MouseEvent evt) { evt.getComponent().setBackground(UIConstants.defaultActiveBackground); } @Override public void mouseExited(java.awt.event.MouseEvent evt) { evt.getComponent().setBackground(UIConstants.buttonBarBackgroundColor); } @Override public void mouseReleased(java.awt.event.MouseEvent evt) { evt.getComponent().setBackground(UIConstants.buttonBarBackgroundColor); } } ); backButton.addMouseListener( new MouseAdapter() { @Override public void mouseEntered(java.awt.event.MouseEvent evt) { if(evt.getComponent().isEnabled()) evt.getComponent().setBackground(UIConstants.defaultActiveBackground); } @Override public void mouseExited(java.awt.event.MouseEvent evt) { if(evt.getComponent().isEnabled()) evt.getComponent().setBackground(UIConstants.buttonBarBackgroundColor); } @Override public void mouseReleased(java.awt.event.MouseEvent evt) { evt.getComponent().setBackground(UIConstants.buttonBarBackgroundColor); } } ); forwardButton.addMouseListener( new MouseAdapter() { @Override public void mouseEntered(java.awt.event.MouseEvent evt) { if(evt.getComponent().isEnabled()) evt.getComponent().setBackground(UIConstants.defaultActiveBackground); } @Override public void mouseExited(java.awt.event.MouseEvent evt) { if(evt.getComponent().isEnabled()) evt.getComponent().setBackground(UIConstants.buttonBarBackgroundColor); } @Override public void mouseReleased(java.awt.event.MouseEvent evt) { evt.getComponent().setBackground(UIConstants.buttonBarBackgroundColor); } } ); refreshToolPanel(); this.wandoraHttpAuthorizer = new WandoraHttpAuthorizer(this); this.shortcuts = new Shortcuts(this); this.menuManager = new WandoraMenuManager(this); this.setJMenuBar(menuManager.getWandoraMenuBar()); getHTTPServer(); // this will also create the server and initialize it if it doesn't exist yet if(httpServer.isAutoStart()) { startHTTPServer(); } refresh(); topicPanelManager.reset(); } catch(Exception e) { handleError(e); } } public void refreshToolPanel() { buttonToolPanel.removeAll(); String currentToolSetName = options.get("gui.toolPanel.currentToolSet"); JComponent buttonToolBar = toolManager.getToolButtonBar(currentToolSetName); if(buttonToolBar != null) { Dimension d = buttonToolBar.getPreferredSize(); d = new Dimension(d.width+5, d.height); buttonToolPanel.add(buttonToolBar); buttonToolPanel.setPreferredSize(d); buttonToolPanel.setMinimumSize(d); } logoContainer.setComponentPopupMenu(toolManager.getToolButtonSelectPopupMenu()); buttonToolPanel.invalidate(); buttonToolPanel.repaint(); } public String getTopicGUIName(Topic t){ return TopicToString.toString(t); } /** * Refreshes all topic trees. This method doesn't refresh TreeTopicPanels. */ public void refreshTopicTrees() { try { Map<String,TopicTreePanel> trees = topicTreeManager.getTrees(); if(trees != null) { for(TopicTreePanel tree : trees.values()){ tree.refresh(); tree.repaint(); } } } catch(Exception e) { e.printStackTrace(); } } /** * Opens a dialog and shows information about an exception and a String message. */ public void displayException(String message,Throwable e){ ErrorDialog ed = new ErrorDialog(this,true,e,message); ed.setVisible(true); } /** * Displays an exception dialog with the given message and throwable object and * buttons labeled with parameters yes and no. If yes button is pressed returns 1 * otherwise returns 0. */ public int displayExceptionYesNo(String message,Throwable e,String no,String yes){ ErrorDialog ed=new ErrorDialog(this,true,e,message,no,yes); ed.setVisible(true); return ed.getButton(); } public int displayExceptionYesNo(String message,Throwable e){ return displayExceptionYesNo(message,e,"No","Yes"); } private SearchPanel searchTopicSelector = null; private SimilarityPanel similarityTopicSelector = null; private QueryPanel queryTopicSelector = null; private Collection<TopicTreePanel> topicTreeSelectors = null; /** * Creates a topic selector with all configured tree choosers and a SelectTopicPanel. The returned * selector will be a tabbed selector with one tab for each tree and the SelectTopicPanel. */ public TabbedTopicSelector getTopicFinder() throws TopicMapException { boolean refreshSelectors = true; Component currentSelector = null; if(topicSelector != null) { refreshSelectors = !topicSelector.remember(); } if(!refreshSelectors) { currentSelector = topicSelector.getSelectedSelector(); } topicSelector = new TabbedTopicSelector(); topicSelector.setRemember(!refreshSelectors); if(topicTreeSelectors == null || refreshSelectors) { topicTreeSelectors = topicTreeManager.getTreeChoosers(); } for(TopicTreePanel c : topicTreeSelectors){ topicSelector.addTab(c); } if(searchTopicSelector == null || refreshSelectors) { searchTopicSelector = new SearchPanel(false); } topicSelector.addTab(searchTopicSelector); if(similarityTopicSelector == null || refreshSelectors) { similarityTopicSelector = new SimilarityPanel(); } topicSelector.addTab(similarityTopicSelector); if(queryTopicSelector == null || refreshSelectors) { queryTopicSelector = new QueryPanel(); } topicSelector.addTab(queryTopicSelector); if(currentSelector != null && !refreshSelectors) { topicSelector.setSelectedSelector(currentSelector); } return topicSelector; } /** * Informs that tools have changed. Will cause all menus containing configurable * tools to be refreshed. */ public void toolsChanged() { refreshToolPanel(); menuManager.refreshToolMenu(); menuManager.refreshImportMenu(); menuManager.refreshGeneratorMenu(); menuManager.refreshExportMenu(); menuManager.refreshExtractMenu(); // this.validateTree(); // TRIGGERS EXCEPTION IN JAVA 1.7 //repaint(); refresh(); } public void shortcutsChanged() throws TopicMapException { menuManager.refreshShortcutsMenu(); } public void topicPanelsChanged() { menuManager.refreshViewMenu(); } /** * Places the window according to options in the <code>options</code> object. * Sets window placement, width, height and horizontal and vertical splitter * locations. */ public void placeWindow() { boolean placedSuccessfully = false; if(options != null) { placedSuccessfully = true; try { int x = options.getInt("options.window.x"); int y = options.getInt("options.window.y"); int width = options.getInt("options.window.width"); int height = options.getInt("options.window.height"); if(x <= 0) x = 10; if(y <= 0) y = 10; if(width <= 0) width = 300; if(height <= 0) height = 300; try { Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); if(x > screenSize.width) { x = screenSize.width - 300; width = 300; } if(y > screenSize.height) { y = screenSize.height - 300; height = 300; } } catch(Exception e) {} if(x > 0 && y > 0 && width > 0 && height > 0) { super.setSize(width, height); super.setLocation(x, y); } int split1 = options.getInt("options.window.horizontalsplitter"); int split2 = options.getInt("options.window.verticalsplitter"); if(split1 > 0 && split2 > 0) { paragraphSplitPane.setDividerLocation(split1); toolSplitPane.setDividerLocation(split2); } } catch (Exception e) { handleError(e); } } if(!placedSuccessfully) { super.setSize(800, 600); UIBox.centerScreen(this); } } public void setTitleMessage(String message) { if(message == null || message.length() == 0) { this.setTitle(frameTitle); } else { this.setTitle(frameTitle+" - "+message); } } /** * Gets a property from application options. */ public String getProperty(String key){ return options.get(key); } public String getLang(){ return "en"; } public TopicPanel getTopicPanel() { return topicPanelManager.getCurrentTopicPanel(); } public Shortcuts getShortcuts() { return this.shortcuts; } public TopicTreeTabManager getTopicTreeManager() { return topicTreeManager; } public TopicTree getCurrentTopicTree() { if(tabbedPane != null) { Component selectedTab = tabbedPane.getSelectedComponent(); if(selectedTab != null && !selectedTab.equals(finderPanel)) { TopicTreePanel treeTopicChooser = (TopicTreePanel) selectedTab; return treeTopicChooser.getTopicTree(); } } return null; } public String getCurrentProjectFileName() { return currentProjectFileName; } public void setCurrentProjectFileName(String f) { currentProjectFileName = f; if(f != null && f.length() > 0) { int i = f.lastIndexOf(File.separator); if(i>-1) { f = f.substring(i+1); } } this.setTitleMessage(f); } /** 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; topicChooserPanel = new javax.swing.JPanel(); selectPanel = new javax.swing.JPanel(); statLabel = new org.wandora.application.gui.simple.SimpleLabel(); toolBar = new javax.swing.JToolBar(); openButton = new SimpleButton(); backButton = new org.wandora.application.gui.simple.SimpleButton(); forwardButton = new org.wandora.application.gui.simple.SimpleButton(); buttonToolPanel = new javax.swing.JPanel(); logoContainer = new javax.swing.JPanel(); toolbarFillerPanel = new javax.swing.JPanel(); logoPanel = new ImagePanel("gui/main_logo.gif"); logoAnimPanel = new LogoAnimation(this); paragraphSplitPane = new javax.swing.JSplitPane(); contentContainerPanel = new javax.swing.JPanel(); contentScrollPane = new org.wandora.application.gui.simple.SimpleScrollPane(); editorPanel = new TopicEditorPanel(this, this); startupPanel = new javax.swing.JPanel(); titlePanel = new ImagePanel("gui/startup_image.gif"); infoBar = new javax.swing.JToolBar(); infobarPanel = new javax.swing.JPanel(); numberOfTopicAssociationsLabel = new SimpleLabel(); fillerPanel = new javax.swing.JPanel(); topicLabel = new org.wandora.application.gui.simple.SimpleLabel(); jSeparator1 = new javax.swing.JSeparator(); topicDistributionLabel = new org.wandora.application.gui.simple.SimpleLabel(); jSeparator4 = new javax.swing.JSeparator(); layerLabel = new org.wandora.application.gui.simple.SimpleLabel(); jSeparator3 = new javax.swing.JSeparator(); stringifierButton = new javax.swing.JButton(); panelButton = new javax.swing.JButton(); serverButton = new javax.swing.JButton(); toolSplitPane = new javax.swing.JSplitPane(); layersPanel = new javax.swing.JPanel(); tabbedPane = new SimpleTabbedPane(); finderPanel = new SimplePanel(); topicChooserPanel.setLayout(new java.awt.BorderLayout()); selectPanel.setLayout(new java.awt.BorderLayout()); statLabel.setFont(org.wandora.application.gui.UIConstants.plainFont); statLabel.setText("OK"); statLabel.setToolTipText(""); statLabel.setVerticalAlignment(javax.swing.SwingConstants.TOP); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Wandora"); setIconImage(org.wandora.application.gui.UIBox.getImage("gui/appicon/48x48_24bit.png")); setIconImages(wandoraIcons); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { formWindowClosing(evt); } }); toolBar.setFloatable(false); toolBar.setOrientation(JToolBar.HORIZONTAL); toolBar.setAlignmentX(0.0F); toolBar.setMinimumSize(new java.awt.Dimension(900, 46)); toolBar.setPreferredSize(new java.awt.Dimension(900, 46)); openButton.setBackground(new Color(238,238,238)); openButton.setIcon(org.wandora.application.gui.UIBox.getIcon("gui/button_open.png")); openButton.setToolTipText("Open topic..."); openButton.setBorder(javax.swing.BorderFactory.createEtchedBorder(java.awt.Color.white, java.awt.Color.gray)); openButton.setFocusPainted(false); openButton.setMaximumSize(new java.awt.Dimension(60, 46)); openButton.setMinimumSize(new java.awt.Dimension(60, 46)); openButton.setPreferredSize(new java.awt.Dimension(60, 46)); toolBar.add(openButton); backButton.setBackground(new Color(238,238,238)); backButton.setIcon(org.wandora.application.gui.UIBox.getIcon("gui/button_back.png")); backButton.setToolTipText("Backward"); backButton.setBorder(javax.swing.BorderFactory.createEtchedBorder(java.awt.Color.white, java.awt.Color.gray)); backButton.setFocusPainted(false); backButton.setMaximumSize(new java.awt.Dimension(60, 46)); backButton.setMinimumSize(new java.awt.Dimension(60, 46)); backButton.setPreferredSize(new java.awt.Dimension(60, 46)); toolBar.add(backButton); forwardButton.setBackground(new Color(238,238,238)); forwardButton.setIcon(org.wandora.application.gui.UIBox.getIcon("gui/button_forward.png")); forwardButton.setToolTipText("Forward"); forwardButton.setBorder(javax.swing.BorderFactory.createEtchedBorder(java.awt.Color.white, java.awt.Color.gray)); forwardButton.setFocusPainted(false); forwardButton.setMaximumSize(new java.awt.Dimension(60, 46)); forwardButton.setMinimumSize(new java.awt.Dimension(60, 46)); forwardButton.setPreferredSize(new java.awt.Dimension(60, 46)); toolBar.add(forwardButton); buttonToolPanel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); toolBar.add(buttonToolPanel); logoContainer.setAlignmentX(0.0F); logoContainer.setPreferredSize(new java.awt.Dimension(300, 48)); logoContainer.setLayout(new java.awt.GridBagLayout()); toolbarFillerPanel.setMinimumSize(new java.awt.Dimension(10, 46)); toolbarFillerPanel.setPreferredSize(new java.awt.Dimension(10, 46)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; logoContainer.add(toolbarFillerPanel, gridBagConstraints); logoPanel.setAlignmentX(0.0F); logoPanel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT, 0, 0)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; logoContainer.add(logoPanel, gridBagConstraints); logoAnimPanel.setMinimumSize(new java.awt.Dimension(64, 46)); logoAnimPanel.setPreferredSize(new java.awt.Dimension(64, 46)); logoContainer.add(logoAnimPanel, new java.awt.GridBagConstraints()); toolBar.add(logoContainer); getContentPane().add(toolBar, java.awt.BorderLayout.NORTH); paragraphSplitPane.setDividerLocation(220); paragraphSplitPane.setDividerSize(2); paragraphSplitPane.setOneTouchExpandable(true); paragraphSplitPane.setPreferredSize(new java.awt.Dimension(10, 6)); contentContainerPanel.setMinimumSize(new java.awt.Dimension(44, 44)); contentContainerPanel.setPreferredSize(new java.awt.Dimension(800, 600)); contentContainerPanel.setLayout(new java.awt.BorderLayout()); contentScrollPane.setBackground(new java.awt.Color(255, 255, 255)); contentScrollPane.setPreferredSize(new java.awt.Dimension(300, 300)); editorPanel.setBackground(new java.awt.Color(255, 255, 255)); editorPanel.setLayout(new java.awt.BorderLayout()); startupPanel.setBackground(new java.awt.Color(255, 255, 255)); startupPanel.setPreferredSize(new java.awt.Dimension(800, 600)); startupPanel.setLayout(new java.awt.GridBagLayout()); titlePanel.setBackground(new java.awt.Color(255, 255, 255)); titlePanel.setFocusable(false); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; startupPanel.add(titlePanel, gridBagConstraints); editorPanel.add(startupPanel, java.awt.BorderLayout.CENTER); contentScrollPane.setViewportView(editorPanel); contentContainerPanel.add(contentScrollPane, java.awt.BorderLayout.CENTER); infoBar.setMinimumSize(new java.awt.Dimension(350, 20)); infoBar.setPreferredSize(new java.awt.Dimension(350, 20)); infobarPanel.setMinimumSize(new java.awt.Dimension(350, 18)); infobarPanel.setPreferredSize(new java.awt.Dimension(350, 18)); infobarPanel.setLayout(new java.awt.GridBagLayout()); numberOfTopicAssociationsLabel.setFont(org.wandora.application.gui.UIConstants.plainFont); numberOfTopicAssociationsLabel.setForeground(new java.awt.Color(51, 51, 51)); numberOfTopicAssociationsLabel.setToolTipText("Number of topics and associations in layer stack."); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 4); infobarPanel.add(numberOfTopicAssociationsLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; infobarPanel.add(fillerPanel, gridBagConstraints); topicLabel.setFont(org.wandora.application.gui.UIConstants.plainFont ); topicLabel.setForeground(new java.awt.Color(51, 51, 51)); topicLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); topicLabel.setText("topic name"); topicLabel.setToolTipText("Name or subject identifier of current topic in panel."); topicLabel.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 1, 0, 1)); topicLabel.setMaximumSize(new java.awt.Dimension(300, 14)); topicLabel.setMinimumSize(new java.awt.Dimension(53, 14)); topicLabel.setPreferredSize(new java.awt.Dimension(300, 14)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHEAST; gridBagConstraints.weightx = 1.0; infobarPanel.add(topicLabel, gridBagConstraints); jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(3, 8, 3, 8); infobarPanel.add(jSeparator1, gridBagConstraints); topicDistributionLabel.setFont(org.wandora.application.gui.UIConstants.plainFont); topicDistributionLabel.setForeground(new java.awt.Color(51, 51, 51)); topicDistributionLabel.setText("0"); topicDistributionLabel.setToolTipText("Layer distribution of current topic."); topicDistributionLabel.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 1, 0, 1)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHEAST; infobarPanel.add(topicDistributionLabel, gridBagConstraints); jSeparator4.setOrientation(javax.swing.SwingConstants.VERTICAL); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(3, 8, 3, 8); infobarPanel.add(jSeparator4, gridBagConstraints); layerLabel.setFont(org.wandora.application.gui.UIConstants.plainFont); layerLabel.setForeground(new java.awt.Color(51, 51, 51)); layerLabel.setText("layer name"); layerLabel.setToolTipText("Name of selected topic map layer."); layerLabel.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 1, 0, 1)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHEAST; infobarPanel.add(layerLabel, gridBagConstraints); jSeparator3.setOrientation(javax.swing.SwingConstants.VERTICAL); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(3, 8, 3, 8); infobarPanel.add(jSeparator3, gridBagConstraints); stringifierButton.setToolTipText("View topics as..."); stringifierButton.setBorder(null); stringifierButton.setBorderPainted(false); stringifierButton.setContentAreaFilled(false); stringifierButton.setMaximumSize(new java.awt.Dimension(16, 16)); stringifierButton.setMinimumSize(new java.awt.Dimension(16, 16)); stringifierButton.setPreferredSize(new java.awt.Dimension(16, 16)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); infobarPanel.add(stringifierButton, gridBagConstraints); panelButton.setToolTipText("Type of current topic panel."); panelButton.setBorder(null); panelButton.setBorderPainted(false); panelButton.setContentAreaFilled(false); panelButton.setMaximumSize(new java.awt.Dimension(16, 16)); panelButton.setMinimumSize(new java.awt.Dimension(16, 16)); panelButton.setPreferredSize(new java.awt.Dimension(16, 16)); panelButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { panelButtonMouseClicked(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); infobarPanel.add(panelButton, gridBagConstraints); serverButton.setToolTipText("Status of Wandora's internal web server."); serverButton.setBorder(null); serverButton.setBorderPainted(false); serverButton.setContentAreaFilled(false); serverButton.setMaximumSize(new java.awt.Dimension(16, 16)); serverButton.setMinimumSize(new java.awt.Dimension(16, 16)); serverButton.setPreferredSize(new java.awt.Dimension(16, 16)); serverButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { serverButtonMouseClicked(evt); } }); infobarPanel.add(serverButton, new java.awt.GridBagConstraints()); infoBar.add(infobarPanel); contentContainerPanel.add(infoBar, java.awt.BorderLayout.SOUTH); paragraphSplitPane.setRightComponent(contentContainerPanel); toolSplitPane.setDividerLocation(350); toolSplitPane.setDividerSize(3); toolSplitPane.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT); toolSplitPane.setResizeWeight(1.0); toolSplitPane.setOneTouchExpandable(true); layersPanel.setBackground(new java.awt.Color(255, 255, 255)); layersPanel.setLayout(new java.awt.BorderLayout()); toolSplitPane.setBottomComponent(layersPanel); tabbedPane.setTabLayoutPolicy(javax.swing.JTabbedPane.SCROLL_TAB_LAYOUT); tabbedPane.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tabbedPaneMouseClicked(evt); } }); finderPanel.setLayout(new java.awt.BorderLayout()); tabbedPane.addTab("Finder", finderPanel); toolSplitPane.setTopComponent(tabbedPane); paragraphSplitPane.setLeftComponent(toolSplitPane); getContentPane().add(paragraphSplitPane, java.awt.BorderLayout.CENTER); pack(); }// </editor-fold>//GEN-END:initComponents private void tabbedPaneMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabbedPaneMouseClicked topicTreeManager.tabbedPaneMouseClicked(evt); if(tabbedPane != null) { Component selectedTab = tabbedPane.getSelectedComponent(); if(selectedTab != null && selectedTab.equals(finderPanel)) { if(searchPanel != null) { searchPanel.requestSearchFieldFocus(); } } } }//GEN-LAST:event_tabbedPaneMouseClicked private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing tryExit(); }//GEN-LAST:event_formWindowClosing private void serverButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_serverButtonMouseClicked WandoraModulesServer server = getHTTPServer(); if(server != null) { if(server.isRunning()) { stopHTTPServer(); } else { startHTTPServer(); } menuManager.refreshServerMenu(); } }//GEN-LAST:event_serverButtonMouseClicked private void panelButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_panelButtonMouseClicked JPopupMenu popup = new JPopupMenu(); topicPanelManager.getTopicPanelMenu(popup); popup.show(evt.getComponent(), evt.getX(), evt.getY()); }//GEN-LAST:event_panelButtonMouseClicked /** * Starts and stops logo animation at the right upper corner of the window. */ public void setAnimated(boolean shouldAnimate, Object caller) { if(shouldAnimate) { if(caller != null) animationCallers.add(caller); ((LogoAnimation) logoAnimPanel).animate(shouldAnimate); } else { if(caller != null) animationCallers.remove(caller); if(animationCallers.isEmpty()) { ((LogoAnimation) logoAnimPanel).animate(shouldAnimate); } } } public void forceStopAnimation() { animationCallers.clear(); ((LogoAnimation) logoAnimPanel).animate(false); } /** * Resets Wandora application. Will close topic and do a complete reinitialization * of the application. */ public void resetWandora() { // DO NOT ADD A USER CONFIRMATION MECHANISM HERE. // CALLER HANDLES USER CONFIRMATION! stopHTTPServer(); resetTopicPanels(); clearHistory(); saveOptions(); topicMap.close(); exitCode = RESTART_APPLICATION; } /** * Exits the application, checking possible changes first. The current topic panel * may contain changes that haven't been committed in topic map yet. These may * cause merges which require user confirmation. The user may cancel the operation at * this point. * * Also the topic map itself may be unsaved in which case a warning dialog is shown. * User may either cancel the operation or exit the application losing all changes. */ public void tryExit(){ try { applyChanges(); } catch(Exception ce){ return; } /* // note that manager.isUnsaved always returned false, uncomment this when unsaved tracking works if(manager.isUnsaved()){ if(WandoraOptionPane.showConfirmDialog(this,"Unsaved changes exist. Are you sure you want to exit?","Unsaved changes",WandoraOptionPane.YES_NO_OPTION) ==WandoraOptionPane.YES_OPTION){ doExit(); } } else*/ doExit(); } /** * Closes the application without any user interaction and without saving any * unsaved data. */ public void doExit() { try { stopHTTPServer(); saveOptions(); topicMap.close(); } catch(Exception e) { } exitCode = EXIT_APPLICATION; } /** * Stores application window placement, size and splitter locations to the * <code>options</code> object and commands the <code>options</code> to * save itself. Saving the <code>options</code> writes it into an XML * file. By default this file is <code>conf/options.xml</code>. */ public void saveOptions() { try { if(options != null) { Dimension d = super.getSize(); options.put("options.window.width", d.width); options.put("options.window.height", d.height); options.put("options.window.x", this.getX()); options.put("options.window.y", this.getY()); options.put("options.window.horizontalsplitter",paragraphSplitPane.getDividerLocation()); options.put("options.window.verticalsplitter",toolSplitPane.getDividerLocation()); options.save(); } } catch (Exception e) { handleError(e); } } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton backButton; private javax.swing.JPanel buttonToolPanel; private javax.swing.JPanel contentContainerPanel; public javax.swing.JScrollPane contentScrollPane; public javax.swing.JPanel editorPanel; private javax.swing.JPanel fillerPanel; private javax.swing.JPanel finderPanel; private javax.swing.JButton forwardButton; public javax.swing.JToolBar infoBar; private javax.swing.JPanel infobarPanel; private javax.swing.JSeparator jSeparator1; private javax.swing.JSeparator jSeparator3; private javax.swing.JSeparator jSeparator4; private javax.swing.JLabel layerLabel; private javax.swing.JPanel layersPanel; private javax.swing.JPanel logoAnimPanel; private javax.swing.JPanel logoContainer; private javax.swing.JPanel logoPanel; private javax.swing.JLabel numberOfTopicAssociationsLabel; private javax.swing.JButton openButton; private javax.swing.JButton panelButton; private javax.swing.JSplitPane paragraphSplitPane; private javax.swing.JPanel selectPanel; private javax.swing.JButton serverButton; private javax.swing.JPanel startupPanel; private javax.swing.JLabel statLabel; private javax.swing.JButton stringifierButton; private javax.swing.JTabbedPane tabbedPane; private javax.swing.JPanel titlePanel; private javax.swing.JToolBar toolBar; private javax.swing.JSplitPane toolSplitPane; private javax.swing.JPanel toolbarFillerPanel; private javax.swing.JPanel topicChooserPanel; private javax.swing.JLabel topicDistributionLabel; public javax.swing.JLabel topicLabel; // End of variables declaration//GEN-END:variables /** * Returns the <code>options</code> object containing all application options. * Options are persistent, they are saved when application exits and loaded * when it starts. */ public Options getOptions(){ return options; } /** * Returns the currently open layered topic map that. */ public LayerStack getTopicMap() { return topicMap; } public void setTopicMap(LayerStack topicMap) { if(this.topicMap!=null) { this.topicMap.removeTopicMapListener(this); } this.topicMap=topicMap; topicMapObjectChanged(); } /** * Returns the currently open topic or <code>null</code> if no topic is open. */ public Topic getOpenTopic(){ return topicPanelManager.getOpenTopic(); } // ------------------------------------------------------------------------- // ------------------------------------------------------------- HISTORY --- // ------------------------------------------------------------------------- public void addToHistory(Topic topic) { try { if(topic != null && !topic.isRemoved()) { Point viewPos = contentScrollPane.getViewport().getViewPosition(); history.setCurrentViewPosition(viewPos.y); history.add(topic.getOneSubjectIdentifier(),0); forwardButton.setEnabled(history.peekNext() != null); backButton.setEnabled(history.peekPrevious() != null); updateHistoryPopups(); } } catch(Exception e) { e.printStackTrace(); } } /** * Performs a back history operation moving to the topic that was previously * open. * @see #forward() * @see #clearHistory() */ public void back() { try { Point viewPos = contentScrollPane.getViewport().getViewPosition(); history.setCurrentViewPosition(viewPos.y); T2<Locator,Integer> page = history.getPrevious(); topicPanelManager.openTopic(topicMap.getTopic(page.e1)); contentScrollPane.getViewport().setViewPosition(new Point(0,page.e2)); forwardButton.setEnabled(history.peekNext() != null); backButton.setEnabled(history.peekPrevious() != null); updateHistoryPopups(); } catch(Exception e) { handleError(e); } } /** * Performs a forward history operation moving to the topic that was open * before last back operation. * @see #back() * @see #clearHistory() */ public void forward() { try { Point viewPos = contentScrollPane.getViewport().getViewPosition(); history.setCurrentViewPosition(viewPos.y); T2<Locator,Integer> page = history.getNext(); topicPanelManager.openTopic(topicMap.getTopic(page.e1)); contentScrollPane.getViewport().setViewPosition(new Point(0,page.e2)); forwardButton.setEnabled(history.peekNext() != null); backButton.setEnabled(history.peekPrevious() != null); updateHistoryPopups(); } catch(Exception e) { handleError(e); } } /** * Clears application history. * @see #back() * @see #forward() */ public void clearHistory() { history.clear(); backButton.setEnabled(false); forwardButton.setEnabled(false); updateHistoryPopups(); refresh(); } /** * Pop-up menus activated on back and forward button. * This should be called when history or current location in history has been * changed. */ public void updateHistoryPopups() { Object[] popupStruct = history.getBackPopupStruct(this); backPopup.removeAll(); UIBox.attachPopup(backPopup, popupStruct, this); popupStruct = history.getForwardPopupStruct(this); forwardPopup.removeAll(); UIBox.attachPopup(forwardPopup, popupStruct, this); } // ------------------------------------------------------------------------- // ---------------------------------------------------------- OPEN TOPIC --- // ------------------------------------------------------------------------- /** * Opens the given topic without applying changes made to the currently open topic. * * @return <code>true</code> if the topic was opened, <code>false</code> if there * was a topic map error. */ public boolean openTopic(Topic topic) { try { addToHistory(topic); topicPanelManager.openTopic(topic); return true; } catch(TopicMapException tme) { handleError(tme); return false; } catch (OpenTopicNotSupportedException otnse) { handleError(otnse); return false; } } public boolean openTopic(Locator l) { try { return openTopic(topicMap.getTopic(l)); } catch(Exception e) { handleError(e); return false; } } public void reopenTopic() { try { topicPanelManager.reopenTopic(); refresh(); } catch(Exception e) { handleError(e); } } public void applyChangesAndOpen(Topic topic) { boolean shouldOpen = topicPanelManager.applyChanges(); if(shouldOpen) { openTopic(topic); } // SHOULD NEXT REALLY BE HERE OR NOT? refreshInfoFields(); } public void applyChangesAndOpen(Locator l) { try { applyChangesAndOpen(topicMap.getTopic(l)); } catch(Exception e) { handleError(e); } } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- /** * Applies changes made to the currently open topic. This may cause merges * in the topic map which will open a warning dialog. User may use the dialog * to cancel the operation which will cause a <code>CancelledException</code> * to be thrown. */ public void applyChanges() throws CancelledException { topicPanelManager.applyChanges(); } /** * Resets topic panel manager. */ public void resetTopicPanels(){ topicPanelManager.reset(); } /** * Refreshes currently open topic panel. Applies changes first which may cause * topics to be merged and a warning dialog to be shown to the user. User may * cancel the operation, which will cause a <code>CancelledException</code> * to be thrown. */ public void refreshTopic() throws CancelledException, TopicMapException { refreshTopic(true); } /** * Refreshes currently open topic panel. If <code>applyChanges</code> parameter * is true, will apply changes first which may cause * topics to be merged and a warning dialog to be shown to the user. User may * cancel the operation, which will cause a <code>CancelledException</code> * to be thrown. */ public void refreshTopic(boolean applyChanges) throws CancelledException, TopicMapException { if(applyChanges) { applyChanges(); } reopenTopic(); refresh(); } private Object errorHandlerLock=new Object(); private boolean handleErrors=true; /** * A generic method to handle exceptions thrown anywhere. Will show a dialog * with the message "Exception occurred" and the exception stack trace. * Also ErrorHandler implementation. */ public void handleError(Throwable throwable) { synchronized(errorHandlerLock){ /*debug*/ throwable.printStackTrace(); if(!handleErrors) return; new ErrorDialog(this, throwable); } } // ------------------------------------------------------------------------- // ------------------------------------------------------------- REFRESH --- // ------------------------------------------------------------------------- /** * Refreshes the main window and main panels. */ public void refresh() { //System.out.println("Wandora - refresh"); Dimension d = super.getSize(); Point l = super.getLocation(); if(options != null) { options.put("options.window.width", d.width); options.put("options.window.height", d.height); options.put("options.window.x", l.x); options.put("options.window.y", l.y); options.put("options.window.horizontalsplitter",paragraphSplitPane.getDividerLocation()); options.put("options.window.verticalsplitter",toolSplitPane.getDividerLocation()); } //initMenuBar(); refreshTopicTrees(); refreshInfoFields(); searchPanel.refresh(); editorPanel.revalidate(); searchPanel.refresh(); finderPanel.revalidate(); toolbarFillerPanel.revalidate(); repaint(); } public String makeDistributionVector(LayeredTopic topic,Layer selectedLayer,ContainerTopicMap tm) throws TopicMapException { StringBuilder sb=new StringBuilder(); for(Layer l : tm.getLayers()) { if(sb.length()!=0) { sb.append(":"); } TopicMap ltm=l.getTopicMap(); if(ltm instanceof ContainerTopicMap) { sb.append("<font color=\"#606060\">(</font>"); sb.append(makeDistributionVector(topic,selectedLayer,(ContainerTopicMap)ltm)); sb.append("<font color=\"#606060\">)</font>"); } else { if(!l.equals(selectedLayer)){ sb.append("<font color=\"#").append(Textbox.getColorHTMLCode(TopicHilights.notActiveLayerColor)).append("\">"); } int num=0; if(l.isVisible()) { num=l.getTopicMap().getMergingTopics(topic).size(); sb.append("").append(num); } else { // Layer is set invisble and we don't know topic's distribution in the layer. sb.append("u"); } if(!l.equals(selectedLayer)) { sb.append("</font>"); } } } return sb.toString(); } /** * Refreshes various labels in the main user interface. */ public void refreshInfoFields() { refreshStatus(); refreshLayerInfo(); refreshTopicDistribution(); refreshCurrentTopicString(); refreshTopicStringifierIcon(); refreshTopicPanelIcon(); infobarPanel.revalidate(); infobarPanel.repaint(); } public void refreshStatus() { String statText = ""; try { //statText = "local mode: "+topicMap.getNumTopics() + " topics, " + topicMap.getNumAssociations() + " associations"; statText = "OK"; statLabel.setText(statText); } catch(Exception e) { handleError(e); } } private String getNumberOfTopicsAndAssociationsInCurrentLayer() { String label = ""; try { LayerStack ls = topicMap; Layer layer = null; TopicMap tm = null; int c=10; while(ls != null && c-- > 0) { layer = ls.getSelectedLayer(); tm = layer.getTopicMap(); if(tm != null && tm instanceof LayerStack) { ls = (LayerStack) tm; } else { ls = null; } } if(layer != null && layer.isVisible()) { if(tm != null) { if(tm instanceof UndoTopicMap) { tm = ((UndoTopicMap) tm).getWrappedTopicMap(); } if(tm != null && tm instanceof TopicMapImpl) { label = tm.getNumTopics() + "," + tm.getNumAssociations(); } } } } catch(Exception e) { label = ""; } return label; } private Color selectedLayerReadOnlyColor = new Color(0x990000); private Color selectedLayerColor = new Color(0x333333); public void refreshLayerInfo() { try { String layerInfo = getNumberOfTopicsAndAssociationsInCurrentLayer(); // :" + (layerControlPanel.layerStack.getSelectedIndex()+1) + "/" + layerControlPanel.layerStack.getLayers().size(); if(layerTree.isSelectedReadOnly()) { layerLabel.setForeground(selectedLayerReadOnlyColor); } else { layerLabel.setForeground(selectedLayerColor); } if(layerInfo != null && layerInfo.length() > 0) { layerLabel.setText("" + layerTree.getSelectedName() + " (" + layerInfo + ")"); } else { layerLabel.setText("" + layerTree.getSelectedName()); } } catch(Exception e) { System.out.println("Exception '"+ e.toString() +"' thrown while updating layer info!"); //e.printStackTrace(); } } public void refreshTopicDistribution() { try { Layer currentLayer = layerTree.getSelectedLayer(); Topic openedTopic = topicPanelManager.getOpenTopic(); if(openedTopic != null && openedTopic instanceof LayeredTopic && currentLayer!=null) { String s="<html><nobr>"+makeDistributionVector((LayeredTopic)openedTopic, currentLayer, topicMap)+"</nobr></html>"; topicDistributionLabel.setText(s); } else { topicDistributionLabel.setText("-"); } } catch(Exception e) { System.out.println("Exception '"+ e.toString() +"' thrown while updating topic distribution info!"); } } public void refreshCurrentTopicString() { try { String name = "no open topic"; Topic openedTopic = topicPanelManager.getOpenTopic(); if(openedTopic != null) { name = TopicToString.toString(openedTopic); } topicLabel.setText(name); } catch(Exception e) { System.out.println("Exception '"+ e.toString() +"' thrown while updating topic status panel!"); //e.printStackTrace(); } } public void refreshTopicStringifierIcon() { stringifierButton.setIcon(TopicToString.getIcon()); } public void refreshTopicPanelIcon() { panelButton.setIcon(topicPanelManager.getIcon()); } // ------------------------------------------------------------------------- // -------------------------------------------------------- TOPIC FINDER --- // ------------------------------------------------------------------------- private T2<Topic,Boolean> _showTopicFinder(JDialog d,java.awt.Component parent,String title,boolean clearButton,TabbedTopicSelector finder) throws TopicMapException { if(title!=null) { d.setTitle(title); } d.add(finder); d.setSize(500,600); org.wandora.utils.swing.GuiTools.centerWindow(d,parent); finder.init(); if(clearButton) { finder.setClearVisible(true); } d.setVisible(true); T2<Topic,Boolean> ret=null; if(finder.wasCancelled()) { ret=new T2<>((Topic) null, true); } else { ret=new T2<>(finder.getSelectedTopic(), false); } finder.cleanup(); return ret; } public Topic showTopicFinder(java.awt.Frame parent) throws TopicMapException { return showTopicFinder(parent,"Select topic"); } public Topic showTopicFinder(java.awt.Frame parent,TabbedTopicSelector finder) throws TopicMapException { return showTopicFinder(parent,"Select topic",finder); } public Topic showTopicFinder(java.awt.Dialog parent) throws TopicMapException { return showTopicFinder(parent,"Select topic"); } public Topic showTopicFinder(java.awt.Dialog parent,TabbedTopicSelector finder) throws TopicMapException { return showTopicFinder(parent,"Select topic",finder); } public Topic showTopicFinder() throws TopicMapException { return showTopicFinder("Select topic"); } public Topic showTopicFinder(java.awt.Frame parent,String title) throws TopicMapException { return showTopicFinder(parent,title,getTopicFinder()); } public Topic showTopicFinder(java.awt.Frame parent,String title,TabbedTopicSelector finder) throws TopicMapException { JDialog d=new JDialog(parent,true); return _showTopicFinder(d,parent,title,false,finder).e1; } /** * Opens a modal topic finder dialog which the user can use to select a topic. * @return The selected topic. */ public Topic showTopicFinder(java.awt.Dialog parent,String title) throws TopicMapException { return showTopicFinder(parent,title,getTopicFinder()); } public Topic showTopicFinder(java.awt.Dialog parent,String title,TabbedTopicSelector finder) throws TopicMapException { JDialog d=new JDialog(parent,true); return _showTopicFinder(d,parent,title,false,finder).e1; } public Topic showTopicFinder(String title) throws TopicMapException { JDialog d=new JDialog(this,true); return _showTopicFinder(d,this,title,false,getTopicFinder()).e1; } public T2<Topic,Boolean> showTopicFinderWithNone() throws TopicMapException { return showTopicFinderWithNone(this,"Select topic"); } public T2<Topic,Boolean> showTopicFinderWithNone(java.awt.Dialog parent) throws TopicMapException { return showTopicFinderWithNone(parent,"Select topic"); } public T2<Topic,Boolean> showTopicFinderWithNone(java.awt.Frame parent) throws TopicMapException { return showTopicFinderWithNone(parent,"Select topic"); } /** * Opens a modal topic finder dialog which the user can use to select a topic with * the option to select none. * @return The selected topic or null if none was selected. */ public T2<Topic,Boolean> showTopicFinderWithNone(java.awt.Dialog parent,String title) throws TopicMapException { return showTopicFinderWithNone(parent,title,getTopicFinder()); } public T2<Topic,Boolean> showTopicFinderWithNone(java.awt.Dialog parent,String title,TabbedTopicSelector finder) throws TopicMapException { JDialog d=new JDialog(parent,true); return _showTopicFinder(d,this,title,true,finder); } public T2<Topic,Boolean> showTopicFinderWithNone(java.awt.Frame parent,String title) throws TopicMapException { return showTopicFinderWithNone(parent,title,getTopicFinder()); } public T2<Topic,Boolean> showTopicFinderWithNone(java.awt.Frame parent,String title,TabbedTopicSelector finder) throws TopicMapException { JDialog d=new JDialog(parent,true); return _showTopicFinder(d,this,title,true,finder); } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- @Override public void actionPerformed(java.awt.event.ActionEvent actionEvent) { String c = actionEvent.getActionCommand(); System.out.println("Wandora catched action command '" + c + "'."); if("Reset".equalsIgnoreCase(c)) { resetWandora(); } else { System.out.println("Warning: Action command " + c + " NOT processed!"); } } // ---- mouse ----- @Override public void mouseClicked(java.awt.event.MouseEvent mouseEvent) { } @Override public void mouseEntered(java.awt.event.MouseEvent mouseEvent) { } @Override public void mouseExited(java.awt.event.MouseEvent mouseEvent) { } @Override public void mousePressed(java.awt.event.MouseEvent mouseEvent) { } @Override public void mouseReleased(java.awt.event.MouseEvent mouseEvent) { } public void centerWindow(Dialog win, Dialog parent) { win.setLocation(parent.getX()+parent.getWidth()/2-win.getWidth()/2,parent.getY()+parent.getHeight()/2-win.getHeight()/2); } public void centerWindow(Dialog win) { win.setLocation(this.getX()+this.getWidth()/2-win.getWidth()/2,this.getY()+this.getHeight()/2-win.getHeight()/2); } public void centerWindow(JDialog win, JDialog parent) { win.setLocation(parent.getX()+parent.getWidth()/2-win.getWidth()/2,parent.getY()+parent.getHeight()/2-win.getHeight()/2); } public void centerWindow(JDialog win) { win.setLocation(this.getX()+this.getWidth()/2-win.getWidth()/2,this.getY()+this.getHeight()/2-win.getHeight()/2); } public void centerWindow(JDialog win, int deltax, int deltay) { win.setLocation(this.getX()+this.getWidth()/2-win.getWidth()/2 + deltax,this.getY()+this.getHeight()/2-win.getHeight()/2 + deltay); } public void centerWindow(JFrame win) { win.setLocation(this.getX()+this.getWidth()/2-win.getWidth()/2,this.getY()+this.getHeight()/2-win.getHeight()/2); } public void centerWindow(JFrame win, int deltax, int deltay) { win.setLocation(this.getX()+this.getWidth()/2-win.getWidth()/2 + deltax,this.getY()+this.getHeight()/2-win.getHeight()/2 + deltay); } public static Wandora getWandora(Component c) { Wandora w = wandora; try { while(!(c instanceof Wandora) && c.getParent() != null) { c = c.getParent(); } if(c instanceof Wandora) { w = (Wandora) c; } } catch (Exception e) { System.out.println("Couldn't solve Wandora with component '"+c+"'. Exception '"+e.toString()+"' occurred."); } return w; } public static Wandora getWandora() { return wandora; } public static URLConnection initUrlConnection(URLConnection uc) { if(uc == null) return null; if(USER_AGENT!=null && USER_AGENT.length()>0){ uc.setRequestProperty("User-Agent", USER_AGENT); } else { uc.setRequestProperty("User-Agent", ""); } return uc; } // ------------------------------------------------------------------------- // --------------------------------------------------------- FOCUS OWNER --- // ------------------------------------------------------------------------- public void gainFocus(Component c) { focusOwner = c; // System.out.println("gain focus for "+(c==null?"null":c.getClass())); } public void looseFocus(Component c) { if(focusOwner == c) { focusOwner = null; } } @Override public Component getFocusOwner() { return focusOwner; } public void clearFocus() { focusOwner = null; } // ------------------------------------------------------------------------- // --------------------------------------------------- Topicmap listener --- // ------------------------------------------------------------------------- @Override public void topicRemoved(Topic t) throws TopicMapException { if(skipTopicMapListenerEvents) return; for(TopicMapListener c : topicMapListeners){ c.topicRemoved(t); } } @Override public void associationRemoved(Association a) throws TopicMapException { if(skipTopicMapListenerEvents) return; for(TopicMapListener c : topicMapListeners){ c.associationRemoved(a); } } @Override public void topicSubjectIdentifierChanged(Topic t,Locator added,Locator removed) throws TopicMapException { if(skipTopicMapListenerEvents) return; for(TopicMapListener c : topicMapListeners){ c.topicSubjectIdentifierChanged(t,added,removed); } } @Override public void topicBaseNameChanged(Topic t,String newName,String oldName) throws TopicMapException { if(skipTopicMapListenerEvents) return; for(TopicMapListener c : topicMapListeners){ c.topicBaseNameChanged(t,newName,oldName); } } @Override public void topicTypeChanged(Topic t,Topic added,Topic removed) throws TopicMapException { if(skipTopicMapListenerEvents) return; for(TopicMapListener c : topicMapListeners){ c.topicTypeChanged(t,added,removed); } } @Override public void topicVariantChanged(Topic t,Collection<Topic> scope,String newName,String oldName) throws TopicMapException { if(skipTopicMapListenerEvents) return; for(TopicMapListener c : topicMapListeners){ c.topicVariantChanged(t,scope,newName,oldName); } } @Override public void topicDataChanged(Topic t,Topic type,Topic version,String newValue,String oldValue) throws TopicMapException { if(skipTopicMapListenerEvents) return; for(TopicMapListener c : topicMapListeners){ c.topicDataChanged(t,type,version,newValue,oldValue); } } @Override public void topicSubjectLocatorChanged(Topic t,Locator newLocator,Locator oldLocator) throws TopicMapException { if(skipTopicMapListenerEvents) return; for(TopicMapListener c : topicMapListeners){ c.topicSubjectLocatorChanged(t,newLocator,oldLocator); } } @Override public void topicChanged(Topic t) throws TopicMapException { if(skipTopicMapListenerEvents) return; for(TopicMapListener c : topicMapListeners){ c.topicChanged(t); } } @Override public void associationTypeChanged(Association a,Topic newType,Topic oldType) throws TopicMapException { if(skipTopicMapListenerEvents) return; for(TopicMapListener c : topicMapListeners){ c.associationTypeChanged(a,newType,oldType); } } @Override public void associationPlayerChanged(Association a,Topic role,Topic newPlayer,Topic oldPlayer) throws TopicMapException { if(skipTopicMapListenerEvents) return; for(TopicMapListener c : topicMapListeners){ c.associationPlayerChanged(a,role,newPlayer,oldPlayer); } } @Override public void associationChanged(Association a) throws TopicMapException { if(skipTopicMapListenerEvents) return; for(TopicMapListener c : topicMapListeners){ c.associationChanged(a); } } // --------------------------------------------------------- UNDO / REDO --- public void redo() throws UndoException { if(topicMap != null) { topicMap.redo(); } } public void undo() throws UndoException { if(topicMap != null) { topicMap.undo(); } } public void addUndoMarker() { addUndoMarker((String) null); } public void addUndoMarker(String label) { if(topicMap != null) { topicMap.addUndoMarker(label); } } public void clearUndoBuffers() { if(topicMap != null) { topicMap.clearUndoBuffers(); } } // ------------------------------------------------------------------------- // ---------------------------------------------------------------- MAIN --- // ------------------------------------------------------------------------- public static final int WAIT_FOR_APPLICATION = 0; public static final int RESTART_APPLICATION = 1; public static final int EXIT_APPLICATION = 2; /* * Global variable <code>exitCode</code> is used to pass application state out of * <code>Wandora</code> object. Specifically, it is used to decide if * the application should be restarted. */ public static int exitCode = WAIT_FOR_APPLICATION; /** * @param args the command line arguments */ public static void main(String args[]) throws Exception { CMDParamParser cmdparams=new CMDParamParser(args); UIConstants.initializeGUI(); SplashWindow splashWindow = new SplashWindow(); Logger.setLogger(new SystemOutLogger()); do { Wandora wandoraApplication = new Wandora(cmdparams); initializeWandoraApplication(wandoraApplication, cmdparams); if(splashWindow.isVisible()) { splashWindow.setVisible(false); } wandoraApplication.setVisible(true); exitCode = WAIT_FOR_APPLICATION; do { try { Thread.sleep(300); } catch(Exception e) {} } while(exitCode == WAIT_FOR_APPLICATION); wandoraApplication.setVisible(false); wandoraApplication.dispose(); } while(exitCode == RESTART_APPLICATION); System.exit(0); } private static void initializeWandoraApplication(Wandora w, CMDParamParser cmdparams) { // If command line paramenters contain a project file, XTM or LTM file // then load the file to Wandora. String lastParam = cmdparams.getLast(); if(lastParam != null) { String lastParamLower = lastParam.toLowerCase(); if(lastParamLower.endsWith(".wpr")) { try { LoadWandoraProject projectLoader = new LoadWandoraProject(); projectLoader.loadProject(new File(lastParam), wandora); } catch(Exception e) { w.displayException("Unable to load project file '"+lastParam+"' due to an exception!", e); } } else if(lastParamLower.endsWith(".xtm20") || lastParamLower.endsWith(".xtm10") || lastParamLower.endsWith(".xtm1") || lastParamLower.endsWith(".xtm2") || lastParamLower.endsWith(".xtm") || lastParamLower.endsWith(".ltm") || lastParamLower.endsWith(".jtm")) { try { TopicMapImport importer = new TopicMapImport(); importer.setOptions(importer.getOptions() | TopicMapImport.CLOSE_LOGS); importer.forceFiles = new File(lastParam); importer.execute(w); } catch(Exception e) { String type = "XTM"; if(lastParamLower.endsWith(".ltm")) { type = "LTM"; } w.displayException("Unable to load "+type+" file '"+lastParam+"' due to an exception!", e); } } else if(lastParamLower.endsWith(".rdf") || lastParamLower.endsWith(".rdfs")) { try { SimpleRDFImport importer = new SimpleRDFImport(); importer.setOptions(importer.getOptions() | TopicMapImport.CLOSE_LOGS); importer.forceFiles = new File(lastParam); importer.execute(w); } catch(Exception e) { w.displayException("Unable to load RDF file '"+lastParam+"' due to an exception!", e); } } else if(lastParamLower.endsWith(".n3")) { try { SimpleN3Import importer = new SimpleN3Import(); importer.setOptions(importer.getOptions() | TopicMapImport.CLOSE_LOGS); importer.forceFiles = new File(lastParam); importer.execute(w); } catch(Exception e) { w.displayException("Unable to load N3 file '"+lastParam+"' due to an exception!", e); } } else if(lastParamLower.endsWith(".ttl")) { try { SimpleRDFTurtleImport importer = new SimpleRDFTurtleImport(); importer.setOptions(importer.getOptions() | TopicMapImport.CLOSE_LOGS); importer.forceFiles = new File(lastParam); importer.execute(w); } catch(Exception e) { w.displayException("Unable to load RDF turtle file '"+lastParam+"' due to an exception!", e); } } else if(lastParamLower.endsWith(".jsonld")) { try { SimpleRDFJsonLDImport importer = new SimpleRDFJsonLDImport(); importer.setOptions(importer.getOptions() | TopicMapImport.CLOSE_LOGS); importer.forceFiles = new File(lastParam); importer.execute(w); } catch(Exception e) { w.displayException("Unable to load JSON-LD file '"+lastParam+"' due to an exception!", e); } } } } }
88,314
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicHilights.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/TopicHilights.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * TopicHilights.java * * Created on 17. lokakuuta 2005, 16:21 * */ package org.wandora.application; import java.awt.Color; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.layered.ContainerTopicMap; import org.wandora.topicmap.layered.Layer; import org.wandora.topicmap.layered.LayeredTopic; import org.wandora.utils.Tuples.T2; import org.wandora.utils.Tuples.T3; /** * <p> * TopicHilights is used to color topics in Wandora's user interface, typically * in topic tables and trees. Generally a topic is colored black. If the topic * doesn't locate in current layer, the topic is colored dark red. * </p> * <p> * This class doesn't set colors in GraphTopicPanel nor TopicTreePanel. * </p> * * @author akivela **/ public class TopicHilights { private Map<String, Color> hilighted = new LinkedHashMap<>(); private Wandora wandora = null; private Map<Topic, Color> hilightedTopics = new LinkedHashMap<>(); public static Color removedTopicColor = new Color(0xa00000); /** Creates a new instance of TopicHilights */ public TopicHilights(Wandora w) { this.wandora = w; } // ------------------------------------------------------------------------- public void add(String si, Color color) throws TopicMapException { if(si == null || color == null) return; hilighted.put(si, color); Topic t = wandora.getTopicMap().getTopic(si); if(t != null) hilightedTopics.put(t, color); } public void add(Topic topic, Color color) throws TopicMapException { if(topic != null) { remove(topic); if(color != null) { hilighted.put(topic.getOneSubjectIdentifier().toExternalForm(), color); hilightedTopics.put(topic, color); } } } public void add(Topic[] topics, Color color) throws TopicMapException { if(topics != null && topics.length > 0) { for(int i=0; i<topics.length; i++) { add(topics[i], color); } } } // ------------------------------------------------------------------------- public Color get(String si) { try { if(si == null) return null; else return (Color) hilighted.get(si); } catch (Exception e) { System.out.println("Exception occurred while getting topic hilight color!"); e.printStackTrace(); } return null; } public Color getBaseNameColor(Topic topic) throws TopicMapException { if(topic instanceof LayeredTopic){ LayeredTopic lt=(LayeredTopic)topic; Topic t=lt.getBaseNameSource(); Layer l=lt.getLayerStack().getLayer(t); if(t==null) return null; while(t instanceof LayeredTopic){ Topic t2=((LayeredTopic)t).getBaseNameSource(); if(t2==null) return null; l=((LayeredTopic)t).getLayerStack().getLayer(t2); t=t2; } if(l==null) return null; if(lt.getLayerStack().getSelectedTreeLayer()!=l) return notActiveLayerColor; return null; } else return null; } public Color getSubjectLocatorColor(Topic topic) throws TopicMapException { if(topic instanceof LayeredTopic){ LayeredTopic lt=(LayeredTopic)topic; Topic t=lt.getSubjectLocatorSource(); Layer l=lt.getLayerStack().getLayer(t); if(t==null) return null; while(t instanceof LayeredTopic){ Topic t2=((LayeredTopic)t).getSubjectLocatorSource(); if(t2==null) return null; l=((LayeredTopic)t).getLayerStack().getLayer(t2); t=t2; } if(l==null) return null; if(lt.getLayerStack().getSelectedTreeLayer()!=l) return notActiveLayerColor; return null; } else return null; } public Color getVariantColor(Topic topic,Set<Topic> scope) throws TopicMapException { if(topic instanceof LayeredTopic){ LayeredTopic lt=(LayeredTopic)topic; T2<Topic,Set<Topic>> source=lt.getVariantSource(scope); if(source==null) return null; Layer l=lt.getLayerStack().getLayer(source.e1); while(source.e1 instanceof LayeredTopic){ T2<Topic,Set<Topic>> source2=((LayeredTopic)source.e1).getVariantSource(source.e2); if(source2==null) return null; l=((LayeredTopic)source.e1).getLayerStack().getLayer(source2.e1); source=source2; } if(l==null) return null; if(lt.getLayerStack().getSelectedTreeLayer()!=l) return notActiveLayerColor; return null; } else return null; } public Color getSIColor(Topic topic,Locator l) throws TopicMapException { if(l==null) return null; if(topic instanceof LayeredTopic){ LayeredTopic lt=(LayeredTopic)topic; Collection<Topic> c=lt.getLayerStack().getTopicsForSelectedTreeLayer(lt); for(Topic t : c){ if(t.getSubjectIdentifiers().contains(l)) return null; } return notActiveLayerColor; } else return null; } public Color getOccurrenceColor(Topic topic,Topic type,Topic lang) throws TopicMapException { if(topic instanceof LayeredTopic){ LayeredTopic lt=(LayeredTopic)topic; T3<Topic,Topic,Topic> source=lt.getDataSource(type,lang); if(source==null) return null; Layer l=lt.getLayerStack().getLayer(source.e1); while(source.e1 instanceof LayeredTopic){ T3<Topic,Topic,Topic> source2=((LayeredTopic)source.e1).getDataSource(source.e2,source.e3); if(source2==null) return null; l=((LayeredTopic)source.e1).getLayerStack().getLayer(source2.e1); source=source2; } if(l==null) return null; if(lt.getLayerStack().getSelectedTreeLayer()!=l) return notActiveLayerColor; return null; } else return null; } public Color get(Topic topic) { try { if(topic == null) return null; else if(topic.isRemoved()) return removedTopicColor; else return (Color) hilightedTopics.get(topic); } catch(Exception e) { System.out.println("Exception occurred while getting topic hilight color!"); e.printStackTrace(); } return null; } // public Color notActiveLayerColor = new Color(0xfff6f6); public static Color notActiveLayerColor = new Color(0x800000); public Color getLayerColor(Topic topic) { try { if(topic == null || !(topic.getTopicMap() instanceof ContainerTopicMap)) return null; else { if(((ContainerTopicMap) topic.getTopicMap()).getTopicForSelectedTreeLayer(topic) == null) { return notActiveLayerColor; } } } catch(Exception e) { System.out.println("Exception occurred while getting topic hilight color!"); e.printStackTrace(); } return null; } // ------------------------------------------------------------------------- public void remove(Topic topic) throws TopicMapException { if(topic != null) { for(Iterator<Locator> i = topic.getSubjectIdentifiers().iterator(); i.hasNext();) { try { String si = ((Locator) i.next()).toExternalForm(); hilighted.remove(si); hilightedTopics.remove(topic); } catch(Exception e) { e.printStackTrace(); } } } } public void remove(Topic[] topics) throws TopicMapException { if(topics != null && topics.length > 0) { for(int i=0; i<topics.length; i++) { remove(topics[i]); } } } public void removeAll() { hilighted.clear(); hilightedTopics.clear(); } }
9,597
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Shortcuts.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/Shortcuts.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * Shortcuts.java * * Created on 13. tammikuuta 2005, 15:01 */ package org.wandora.application; import java.awt.Dimension; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.KeyStroke; import javax.swing.ListSelectionModel; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.UIConstants; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.application.gui.simple.SimpleButton; import org.wandora.application.gui.simple.SimpleList; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.utils.ClipboardBox; import org.wandora.utils.IObox; import org.wandora.utils.Options; import org.wandora.utils.Textbox; /** * Shortcuts is a subject identifier storage implementing * Wandora's shortcuts menu and a manager for shortcuts. Subject identifiers * stored into shortcuts are stored to Wandora's options. * * @see org.wandora.utils.Options * @author akivela */ public class Shortcuts implements ActionListener { public static final String OPTIONS_PREFIX = "shortcuts."; private List<String> shortcuts; private Wandora wandora; private ManageDialog manageDialog = null; private Object[] accelerators = new Object[] { KeyStroke.getKeyStroke(KeyEvent.VK_1, InputEvent.CTRL_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK), KeyStroke.getKeyStroke(KeyEvent.VK_2, InputEvent.CTRL_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK), KeyStroke.getKeyStroke(KeyEvent.VK_3, InputEvent.CTRL_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK), KeyStroke.getKeyStroke(KeyEvent.VK_4, InputEvent.CTRL_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK), KeyStroke.getKeyStroke(KeyEvent.VK_5, InputEvent.CTRL_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK), KeyStroke.getKeyStroke(KeyEvent.VK_6, InputEvent.CTRL_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK), KeyStroke.getKeyStroke(KeyEvent.VK_7, InputEvent.CTRL_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK), KeyStroke.getKeyStroke(KeyEvent.VK_8, InputEvent.CTRL_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK), KeyStroke.getKeyStroke(KeyEvent.VK_9, InputEvent.CTRL_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK), }; Object[] staticMenuStructure = new Object[] { "Add shortcut", UIBox.getIcon("gui/icons/shortcut_new.png"), "Manage shortcuts...", UIBox.getIcon("gui/icons/shortcuts_configure.png"), "---" }; Object[] staticFullMenuStructure = new Object[] { "Shortcuts", staticMenuStructure }; ShortcutMenuListener shortcutMenuListener = new ShortcutMenuListener(); /** Creates a new instance of Shortcuts */ public Shortcuts(Wandora w) { this.wandora = w; shortcuts = new ArrayList<>(); loadShortcuts(wandora.options); } public void addShortcut(String shortcut) { if(shortcuts.contains(shortcut)) shortcuts.remove(shortcut); shortcuts.add(0, shortcut); } public void manage() { manageDialog=new ManageDialog(wandora, false, this); manageDialog.setSize(600, 400); wandora.centerWindow(manageDialog); manageDialog.setVisible(true); } public JMenu getShortcutsMenu(JMenu shortcutsMenu) throws TopicMapException { shortcutsMenu.removeAll(); UIBox.attachMenu(shortcutsMenu, staticMenuStructure, this); UIBox.attachMenu(shortcutsMenu, getMenuStructure(), shortcutMenuListener); return shortcutsMenu; } public JMenu getShortcutsMenu() throws TopicMapException { return UIBox.attachMenu(UIBox.makeMenu(staticFullMenuStructure, this), getMenuStructure(), shortcutMenuListener); } public Object[] getMenuStructure() throws TopicMapException { List<Object> shortcutMenuStructure = new ArrayList<>(); Topic t = null; TopicMap topicMap = wandora.getTopicMap(); if(topicMap != null) { String name = null; int acceleratorCount = 0; for(Iterator<String> iter=shortcuts.iterator(); iter.hasNext(); ) { String si = iter.next(); t = null; try{ t=topicMap.getTopic(si); } catch(TopicMapException tme) { tme.printStackTrace(); //admin.handleError(tme); } if(t != null) { name = t.getBaseName(); if(name != null && name.length() > 0) { shortcutMenuStructure.add(name); } else { shortcutMenuStructure.add(si); } } else { shortcutMenuStructure.add(si); } if(acceleratorCount < accelerators.length) { shortcutMenuStructure.add(accelerators[acceleratorCount++]); } shortcutMenuStructure.add(UIBox.getIcon("gui/icons/shortcut.png")); } } return shortcutMenuStructure.toArray(); } @Override public void actionPerformed(java.awt.event.ActionEvent actionEvent) { String c = actionEvent.getActionCommand(); if("Add shortcut".equalsIgnoreCase(c)) { Topic t=wandora.getOpenTopic(); if(t != null) { Collection<Locator> tsis=null; try { tsis=t.getSubjectIdentifiers(); if(tsis!=null && tsis.size() > 1) { Object[] tsisArray = tsis.toArray(); Object answer = WandoraOptionPane.showOptionDialog(wandora, "Topic contains multiple subject identifiers. Select subject identifier for the shortcut.", "Select subject identifier", WandoraOptionPane.QUESTION_MESSAGE, tsisArray, tsisArray[0]); if(answer == null) return; else { String si=answer.toString(); addShortcut(si); } } else { Locator si = (Locator) (tsis.iterator().next()); addShortcut(si.toExternalForm()); } wandora.shortcutsChanged(); } catch(Exception e) { if(wandora != null) wandora.handleError(e); else e.printStackTrace(); return; } if(wandora != null) saveShortcuts(wandora.options); } } else if("Manage shortcuts...".equalsIgnoreCase(c)) { manage(); } else { // Should not be here! } } public void loadShortcuts(Options opts) { int i = 0; boolean loadOk = true; String shortcut = null; while(loadOk) { shortcut = opts.get(OPTIONS_PREFIX + "si["+i+"]"); if(shortcut != null && shortcut.length() > 0) { if(!shortcuts.contains(shortcut)) shortcuts.add(shortcut); i++; } else { loadOk = false; } } } public void loadShortcuts(String filename) { try { String shortcutString = IObox.loadFile(filename); parseShortcuts(shortcutString); } catch (Exception e) { System.out.println("Exception occurred '" + e.toString() + "' while loading shortcuts from '" + filename + "'!"); if(wandora != null) wandora.handleError(e); else e.printStackTrace(); } } public void parseShortcuts(String shortcutString) { try { StringTokenizer st = new StringTokenizer(shortcutString, "\n"); while(st.hasMoreTokens()) { String shortcut = Textbox.trimExtraSpaces(st.nextToken()); if(shortcut != null && shortcut.length() > 0) { if(!shortcuts.contains(shortcut)) shortcuts.add(shortcut); } } } catch (Exception e) { System.out.println("Exception occurred '" + e.toString() + "' while parsing shortcuts!"); wandora.handleError(e); } } public void saveShortcuts(String fileName) { saveShortcuts(new File(fileName)); } public void saveShortcuts(File file) { try { OutputStream fos=new FileOutputStream(file); PrintWriter writer=new PrintWriter(fos); Iterator<String> iter=shortcuts.iterator(); while(iter.hasNext()) { writer.print(iter.next()+ "\n"); } writer.close(); } catch(Exception e) { //System.out.println("Exception occurred '" + e.toString() + "' while saving shortcuts to '" + file.getPath() + "'!"); WandoraOptionPane.showMessageDialog(wandora, "Exception occurred '" + e.toString() + "' while saving shortcuts to '" + file.getPath() + "'!", WandoraOptionPane.ERROR_MESSAGE); } } public void saveShortcuts(Options opts) { try { int i=0; Iterator<String> iter=shortcuts.iterator(); while(iter.hasNext()) { opts.put(OPTIONS_PREFIX + "si["+i+"]", iter.next()); i++; } } catch(Exception e) { //System.out.println("Exception occurred '" + e.toString() + "' while saving shortcuts to options!"); WandoraOptionPane.showMessageDialog(wandora,"Exception occurred '" + e.toString() + "' while saving shortcuts to options!"); } } // ------------------------------------------------------------------------- // ---- Shortcut menu listener opens topics selected from menu. ------------ // ------------------------------------------------------------------------- private class ShortcutMenuListener implements ActionListener { @Override public void actionPerformed(java.awt.event.ActionEvent actionEvent) { try { // Expecting action command to be si or base name! String c = actionEvent.getActionCommand(); Topic t = null; TopicMap topicMap = wandora.getTopicMap(); boolean updateMenu = false; t = topicMap.getTopicWithBaseName(c); // base name if(t == null) { t = topicMap.getTopic(c); // subject identifier updateMenu = true; } if(t == null) { wandora.applyChangesAndOpen(new Locator(c)); } else { wandora.applyChangesAndOpen(t); } } catch (Exception e) { e.printStackTrace(); wandora.handleError(e); } } } // ------------------------------------------------------------------------- // --- Shortcut's manage dialog -------------------------------------------- // ------------------------------------------------------------------------- private class ManageDialog extends JDialog implements ActionListener { private static final long serialVersionUID = 1L; Object[] fileMenuStructure = new Object[] { "File", new Object[] { "Import...", "Merge...", "Export...", "---", "Close", } }; Object[] editMenuStructure = new Object[] { "Edit", new Object[] { "Open", "---", "Cut", "Copy", "Paste", "---", "Delete", "---", "Move up", "Move down", "Move top", "Move bottom" } }; JList list = null; Wandora wandora = null; public ManageDialog(Wandora w, boolean modal, Shortcuts parent) { super((JFrame) w, modal); this.setTitle("Manage shortcuts"); this.wandora = w; JMenuBar menuBar = new JMenuBar(); menuBar.add(UIBox.makeMenu(fileMenuStructure, this)); menuBar.add(UIBox.makeMenu(editMenuStructure, this)); setJMenuBar(menuBar); this.getContentPane().setLayout(new java.awt.BorderLayout()); list=new SimpleList(shortcuts.toArray()); list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); list.setFont(UIConstants.plainFont); list.setComponentPopupMenu(getPopupMenu(this)); JScrollPane scrollPane = new JScrollPane(); scrollPane.setPreferredSize(new java.awt.Dimension(500,300)); scrollPane.setViewportView(list); this.getContentPane().add(scrollPane, java.awt.BorderLayout.CENTER); JPanel panel=new JPanel(); JButton okButton=new SimpleButton("Close"); okButton.setFont(UIConstants.buttonLabelFont); okButton.setPreferredSize(new Dimension(80, 23)); okButton.setActionCommand("Close"); okButton.addActionListener(this); JButton importButton=new SimpleButton("Import"); importButton.setPreferredSize(new Dimension(80, 23)); importButton.setFont(UIConstants.buttonLabelFont); importButton.setActionCommand("Import"); importButton.addActionListener(this); JButton saveButton=new SimpleButton("Export"); saveButton.setPreferredSize(new Dimension(80, 23)); saveButton.setFont(UIConstants.buttonLabelFont); saveButton.setActionCommand("Export"); saveButton.addActionListener(this); JButton removeButton=new SimpleButton("Delete"); removeButton.setFont(UIConstants.buttonLabelFont); removeButton.setPreferredSize(new Dimension(80, 23)); removeButton.setActionCommand("Delete"); removeButton.addActionListener(this); JButton openButton=new SimpleButton("Open"); openButton.setPreferredSize(new Dimension(80, 23)); openButton.setFont(UIConstants.buttonLabelFont); openButton.setActionCommand("Open"); openButton.addActionListener(this); panel.add(openButton); panel.add(removeButton); panel.add(importButton); panel.add(saveButton); panel.add(okButton); this.getContentPane().add(panel,java.awt.BorderLayout.SOUTH); this.pack(); } public void update() { list.setListData(shortcuts.toArray()); list.clearSelection(); repaint(); if(wandora != null) saveShortcuts(wandora.options); } public JPopupMenu getPopupMenu(ActionListener listener) { Object[] menuStructure = new Object[] { "Open", "---", "Cut", "Copy", "Paste", "---", "Delete", "---", "Move up", "Move down", "Move top", "Move bottom" }; return UIBox.makePopupMenu(menuStructure, listener); } @Override public void actionPerformed(java.awt.event.ActionEvent actionEvent) { String c = actionEvent.getActionCommand(); if("Move up".equalsIgnoreCase(c)) { int[] selected=manageDialog.list.getSelectedIndices(); for(int i=0; i<selected.length; i++) { shortcuts.add(selected[i]-1 < 0 ? 0 : selected[i]-1, shortcuts.get(selected[i])); shortcuts.remove(selected[i]+1); } update(); } else if("Move down".equalsIgnoreCase(c)) { int[] selected=manageDialog.list.getSelectedIndices(); for(int i=selected.length-1; i>=0; i--) { shortcuts.add(selected[i]+2 >= shortcuts.size() ? shortcuts.size() : selected[i]+2, shortcuts.get(selected[i])); shortcuts.remove(selected[i]); } update(); } else if("Move bottom".equalsIgnoreCase(c)) { int[] selected=manageDialog.list.getSelectedIndices(); int p = 0; for(int i=selected.length-1; i>=0; i--) { shortcuts.add(shortcuts.size()-p, shortcuts.get(selected[i])); p++; shortcuts.remove(selected[i]); } update(); } if("Move top".equalsIgnoreCase(c)) { int[] selected=manageDialog.list.getSelectedIndices(); for(int i=0; i<selected.length; i++) { shortcuts.add(i, shortcuts.get(selected[i])); shortcuts.remove(selected[i]+1); } update(); } if("Cut".equalsIgnoreCase(c)) { int[] selected=manageDialog.list.getSelectedIndices(); StringBuilder sb = new StringBuilder(""); for(int i=0; i<selected.length; i++) { String si = (String) shortcuts.get(selected[i]); sb.append(si).append("\n"); } ClipboardBox.setClipboard(sb.toString()); for(int i=selected.length-1; i>=0; i--) { shortcuts.remove(selected[i]); } update(); } else if("Copy".equalsIgnoreCase(c)) { int[] selected=manageDialog.list.getSelectedIndices(); StringBuilder sb = new StringBuilder(""); for(int i=0; i<selected.length; i++) { String si = (String) shortcuts.get(selected[i]); sb.append(si).append("\n"); } ClipboardBox.setClipboard(sb.toString()); } else if("Paste".equalsIgnoreCase(c)) { String shortcutString = ClipboardBox.getClipboard(); parseShortcuts(shortcutString); update(); } else if("Delete".equalsIgnoreCase(c)) { int[] selected=manageDialog.list.getSelectedIndices(); for(int i=selected.length-1;i>=0;i--){ shortcuts.remove(selected[i]); } update(); } else if("Export".equalsIgnoreCase(c) || "Export...".equalsIgnoreCase(c)) { JFileChooser chooser=new JFileChooser(); chooser.setDialogTitle("Export shortcuts..."); if(wandora != null) { String currentDirectoryString = wandora.options.get("current.directory"); if(currentDirectoryString != null) { chooser.setCurrentDirectory(new File(currentDirectoryString)); } } if(chooser.showDialog(this, "Export")==JFileChooser.APPROVE_OPTION) { if(wandora != null) { wandora.options.put("current.directory", chooser.getCurrentDirectory().getPath()); } saveShortcuts(chooser.getSelectedFile().getPath()); } } else if("Import".equalsIgnoreCase(c) || "Import...".equalsIgnoreCase(c)) { JFileChooser chooser=new JFileChooser(); chooser.setDialogTitle("Import shortcuts..."); if(wandora != null) { String currentDirectoryString = wandora.options.get("current.directory"); if(currentDirectoryString != null) { chooser.setCurrentDirectory(new File(currentDirectoryString)); } } if(chooser.showDialog(this, "Import")==JFileChooser.APPROVE_OPTION){ shortcuts = new ArrayList<>(); if(wandora != null) { wandora.options.put("current.directory", chooser.getCurrentDirectory().getPath()); } loadShortcuts(chooser.getSelectedFile().getPath()); } update(); } else if("Merge".equalsIgnoreCase(c) || "Merge...".equalsIgnoreCase(c)) { JFileChooser chooser=new JFileChooser(); chooser.setDialogTitle("Merge shortcuts..."); if(wandora != null) { String currentDirectoryString = wandora.options.get("current.directory"); if(currentDirectoryString != null) { chooser.setCurrentDirectory(new File(currentDirectoryString)); } } if(chooser.showDialog(this, "Merge")==JFileChooser.APPROVE_OPTION){ if(wandora != null) { wandora.options.put("current.directory", chooser.getCurrentDirectory().getPath()); } loadShortcuts(chooser.getSelectedFile().getPath()); } update(); } else if("Open".equalsIgnoreCase(c)) { int[] selected=manageDialog.list.getSelectedIndices(); for(int i=selected.length-1;i>=0;i--) { wandora.openTopic(new Locator((String) shortcuts.get(selected[i]))); } manageDialog.repaint(); } else if("Close".equalsIgnoreCase(c)) { this.setVisible(false); try { wandora.shortcutsChanged(); } catch(TopicMapException tme) { tme.printStackTrace(); wandora.handleError(tme); } } } } }
24,499
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
WandoraMenuManager.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/WandoraMenuManager.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * WandoraMenuManager.java * * Created on 13. huhtikuuta 2006, 14:06 * */ package org.wandora.application; import static java.awt.event.InputEvent.ALT_DOWN_MASK; import static java.awt.event.InputEvent.CTRL_DOWN_MASK; import static java.awt.event.InputEvent.META_DOWN_MASK; import static java.awt.event.InputEvent.SHIFT_DOWN_MASK; import static java.awt.event.KeyEvent.VK_A; import static java.awt.event.KeyEvent.VK_C; import static java.awt.event.KeyEvent.VK_D; import static java.awt.event.KeyEvent.VK_DELETE; import static java.awt.event.KeyEvent.VK_DOWN; import static java.awt.event.KeyEvent.VK_END; import static java.awt.event.KeyEvent.VK_F; import static java.awt.event.KeyEvent.VK_H; import static java.awt.event.KeyEvent.VK_HOME; import static java.awt.event.KeyEvent.VK_I; import static java.awt.event.KeyEvent.VK_L; import static java.awt.event.KeyEvent.VK_M; import static java.awt.event.KeyEvent.VK_N; import static java.awt.event.KeyEvent.VK_O; import static java.awt.event.KeyEvent.VK_P; import static java.awt.event.KeyEvent.VK_Q; import static java.awt.event.KeyEvent.VK_R; import static java.awt.event.KeyEvent.VK_S; import static java.awt.event.KeyEvent.VK_U; import static java.awt.event.KeyEvent.VK_UP; import static java.awt.event.KeyEvent.VK_V; import static java.awt.event.KeyEvent.VK_W; import static java.awt.event.KeyEvent.VK_X; import static java.awt.event.KeyEvent.VK_Y; import static java.awt.event.KeyEvent.VK_Z; import static org.wandora.application.gui.topicpanels.traditional.AbstractTraditionalTopicPanel.OPTIONS_PREFIX; import static org.wandora.application.gui.topicpanels.traditional.AbstractTraditionalTopicPanel.VARIANT_GUITYPE_OPTIONS_KEY; import static org.wandora.application.gui.topicpanels.traditional.AbstractTraditionalTopicPanel.VARIANT_GUITYPE_SCHEMA; import static org.wandora.application.gui.topicpanels.traditional.AbstractTraditionalTopicPanel.VARIANT_GUITYPE_USED; import java.awt.Component; import java.util.List; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import javax.swing.Icon; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JSeparator; import javax.swing.KeyStroke; import org.wandora.application.contexts.ApplicationAssociationContext; import org.wandora.application.contexts.ApplicationContext; import org.wandora.application.contexts.AssociationContext; import org.wandora.application.contexts.Context; import org.wandora.application.contexts.EmptyContext; import org.wandora.application.contexts.LayeredTopicContext; import org.wandora.application.contexts.SIContext; import org.wandora.application.contexts.TopicContext; import org.wandora.application.gui.LayerTree; import org.wandora.application.gui.OccurrenceTable; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.simple.SimpleMenu; import org.wandora.application.gui.table.TopicGrid; import org.wandora.application.gui.table.TopicTable; import org.wandora.application.gui.topicpanels.DockingFramePanel; import org.wandora.application.gui.topicpanels.TopicPanel; import org.wandora.application.gui.topicstringify.DefaultTopicStringifier; import org.wandora.application.gui.topicstringify.TopicStringifierToVariant; import org.wandora.application.gui.tree.TopicTree; import org.wandora.application.modulesserver.ModulesWebApp; import org.wandora.application.modulesserver.WandoraModulesServer; import org.wandora.application.tools.AboutCredits; import org.wandora.application.tools.AboutWandora; import org.wandora.application.tools.AddClass; import org.wandora.application.tools.AddInstance; import org.wandora.application.tools.ApplyPatchTool; import org.wandora.application.tools.CopyAsImage; import org.wandora.application.tools.CopyTopicAssociationTypes; import org.wandora.application.tools.CopyTopicClasses; import org.wandora.application.tools.CopyTopicInstances; import org.wandora.application.tools.CopyTopicPlayers; import org.wandora.application.tools.CopyTopicRoles; import org.wandora.application.tools.CopyTopics; import org.wandora.application.tools.CopyTopicsToLayer; import org.wandora.application.tools.CreateAssociationType; import org.wandora.application.tools.DeleteFromTopics; import org.wandora.application.tools.DeleteTopics; import org.wandora.application.tools.DeleteTopicsExceptSelected; import org.wandora.application.tools.DeleteTopicsWithBasenameRegex; import org.wandora.application.tools.DeleteTopicsWithSIRegex; import org.wandora.application.tools.DeleteTopicsWithoutACI; import org.wandora.application.tools.DeleteTopicsWithoutAI; import org.wandora.application.tools.DeleteTopicsWithoutAssociations; import org.wandora.application.tools.DeleteTopicsWithoutBasename; import org.wandora.application.tools.DeleteTopicsWithoutClasses; import org.wandora.application.tools.DeleteTopicsWithoutInstances; import org.wandora.application.tools.DeleteTopicsWithoutOccurrences; import org.wandora.application.tools.DeleteTopicsWithoutVariants; import org.wandora.application.tools.DiffTool; import org.wandora.application.tools.DuplicateTopics; import org.wandora.application.tools.ExecBrowser; import org.wandora.application.tools.ExitWandora; import org.wandora.application.tools.FlipNameMatrix; import org.wandora.application.tools.MakeInstancesWithAssociations; import org.wandora.application.tools.MergeTopics; import org.wandora.application.tools.NewTopic; import org.wandora.application.tools.NewTopicExtended; import org.wandora.application.tools.PasteClasses; import org.wandora.application.tools.PasteInstances; import org.wandora.application.tools.PasteTopics; import org.wandora.application.tools.Print; import org.wandora.application.tools.RefreshTopicTrees; import org.wandora.application.tools.Search; import org.wandora.application.tools.SetTopicStringifier; import org.wandora.application.tools.SplitToInstancesWithBasename; import org.wandora.application.tools.SplitToSuperclassesWithBasename; import org.wandora.application.tools.SplitTopics; import org.wandora.application.tools.SplitTopicsWithBasename; import org.wandora.application.tools.SystemClipboard; import org.wandora.application.tools.associations.AddSchemalessAssociation; import org.wandora.application.tools.associations.ChangeAssociationRole; import org.wandora.application.tools.associations.ChangeAssociationType; import org.wandora.application.tools.associations.CollectNary; import org.wandora.application.tools.associations.CopyAssociations; import org.wandora.application.tools.associations.CopyEdgePath; import org.wandora.application.tools.associations.CreateSymmetricAssociation; import org.wandora.application.tools.associations.DeleteAssociations; import org.wandora.application.tools.associations.DeleteAssociationsInTopic; import org.wandora.application.tools.associations.DeleteAssociationsInTopicWithType; import org.wandora.application.tools.associations.DeleteSymmetricAssociation; import org.wandora.application.tools.associations.DeleteUnaryAssociations; import org.wandora.application.tools.associations.DetectCycles; import org.wandora.application.tools.associations.DuplicateAssociations; import org.wandora.application.tools.associations.FindAssociationsInOccurrence; import org.wandora.application.tools.associations.FindAssociationsInOccurrenceSimple; import org.wandora.application.tools.associations.InsertPlayer; import org.wandora.application.tools.associations.MakeAssociationWithClassInstance; import org.wandora.application.tools.associations.MakeAssociationWithOccurrence; import org.wandora.application.tools.associations.MakeSubclassOf; import org.wandora.application.tools.associations.MakeSuperclassOf; import org.wandora.application.tools.associations.MergePlayers; import org.wandora.application.tools.associations.ModifySchemalessAssociation; import org.wandora.application.tools.associations.OpenEdgeTopic; import org.wandora.application.tools.associations.PasteAssociations; import org.wandora.application.tools.associations.RemovePlayer; import org.wandora.application.tools.associations.SplitToBinaryAssociations; import org.wandora.application.tools.associations.SwapPlayers; import org.wandora.application.tools.associations.TransposeAssociations; import org.wandora.application.tools.exporters.AdjacencyMatrixExport; import org.wandora.application.tools.exporters.DOTExport; import org.wandora.application.tools.exporters.ExportTopicMap; import org.wandora.application.tools.exporters.GMLExport; import org.wandora.application.tools.exporters.GXLExport; import org.wandora.application.tools.exporters.GephiExport; import org.wandora.application.tools.exporters.GraphMLExport; import org.wandora.application.tools.exporters.GraphXMLExport; import org.wandora.application.tools.exporters.IncidenceMatrixExport; import org.wandora.application.tools.exporters.OccurrenceSummaryReport; import org.wandora.application.tools.exporters.RDFExport; import org.wandora.application.tools.exporters.SimilarityMatrixExport; import org.wandora.application.tools.exporters.site.ExportSite; import org.wandora.application.tools.extractors.AbstractExtractor; import org.wandora.application.tools.git.Clone; import org.wandora.application.tools.git.Commit; import org.wandora.application.tools.git.CommitPush; import org.wandora.application.tools.git.Init; import org.wandora.application.tools.git.Pull; import org.wandora.application.tools.git.Push; import org.wandora.application.tools.git.Status; import org.wandora.application.tools.layers.ArrangeLayers; import org.wandora.application.tools.layers.ClearTopicMap; import org.wandora.application.tools.layers.ClearTopicMapIndexes; import org.wandora.application.tools.layers.ConfigureLayer; import org.wandora.application.tools.layers.DeleteLayer; import org.wandora.application.tools.layers.LockLayers; import org.wandora.application.tools.layers.MakeAssociationConsistentTool; import org.wandora.application.tools.layers.MergeLayers; import org.wandora.application.tools.layers.NewLayer; import org.wandora.application.tools.layers.RenameLayer; import org.wandora.application.tools.layers.ViewLayers; import org.wandora.application.tools.maiana.MaianaExport; import org.wandora.application.tools.mediawiki.MediawikiOccurrenceUploader; import org.wandora.application.tools.mediawiki.MediawikiSubjectLocatorUploader; import org.wandora.application.tools.mediawikiapi.MediaWikiAPIUploader; import org.wandora.application.tools.navigate.CloseCurrentTopicPanel; import org.wandora.application.tools.navigate.OpenTopic; import org.wandora.application.tools.navigate.OpenTopicIn; import org.wandora.application.tools.navigate.OpenTopicInNew; import org.wandora.application.tools.occurrences.AddSchemalessOccurrence; import org.wandora.application.tools.occurrences.AppendOccurrence; import org.wandora.application.tools.occurrences.ChangeOccurrenceTableRowHeight; import org.wandora.application.tools.occurrences.ChangeOccurrenceType; import org.wandora.application.tools.occurrences.ChangeOccurrenceView; import org.wandora.application.tools.occurrences.CopyOccurrence; import org.wandora.application.tools.occurrences.CutOccurrence; import org.wandora.application.tools.occurrences.DeleteAllOccurrences; import org.wandora.application.tools.occurrences.DeleteOccurrence; import org.wandora.application.tools.occurrences.DownloadAllOccurrences; import org.wandora.application.tools.occurrences.DownloadOccurrence; import org.wandora.application.tools.occurrences.DuplicateOccurrence; import org.wandora.application.tools.occurrences.EditOccurrences; import org.wandora.application.tools.occurrences.MakeOccurrenceFromAssociation; import org.wandora.application.tools.occurrences.MakeOccurrenceFromBasename; import org.wandora.application.tools.occurrences.MakeOccurrenceFromSubjectIdentifier; import org.wandora.application.tools.occurrences.MakeOccurrenceFromSubjectLocator; import org.wandora.application.tools.occurrences.MakeOccurrenceFromVariant; import org.wandora.application.tools.occurrences.MakeOccurrencesFromVariants; import org.wandora.application.tools.occurrences.OccurrenceRegexReplacerAll; import org.wandora.application.tools.occurrences.OccurrenceRegexReplacerOne; import org.wandora.application.tools.occurrences.OccurrenceScopeCopier; import org.wandora.application.tools.occurrences.OpenURLOccurrence; import org.wandora.application.tools.occurrences.PasteOccurrence; import org.wandora.application.tools.occurrences.SpreadOccurrence; import org.wandora.application.tools.occurrences.URLOccurrenceChecker; import org.wandora.application.tools.occurrences.clipboards.PasteBinOccurrenceDownloader; import org.wandora.application.tools.occurrences.clipboards.PasteBinOccurrenceUploader; import org.wandora.application.tools.occurrences.refine.AnnieOccurrenceExtractor; import org.wandora.application.tools.occurrences.refine.FindNearByGeoNamesOccurrence; import org.wandora.application.tools.occurrences.refine.StanfordNEROccurrenceExtractor; import org.wandora.application.tools.occurrences.refine.UClassifyOccurrenceExtractor; import org.wandora.application.tools.occurrences.run.RunOccurrenceAsQuery; import org.wandora.application.tools.project.LoadWandoraProject; import org.wandora.application.tools.project.MergeWandoraProject; import org.wandora.application.tools.project.ResetWandora; import org.wandora.application.tools.project.RevertWandoraProject; import org.wandora.application.tools.project.SaveWandoraProject; import org.wandora.application.tools.selections.ClearSelection; import org.wandora.application.tools.selections.InvertSelection; import org.wandora.application.tools.selections.LocateSelectTopicInTree; import org.wandora.application.tools.selections.SelectAll; import org.wandora.application.tools.selections.SelectColumns; import org.wandora.application.tools.selections.SelectRows; import org.wandora.application.tools.selections.SelectTopicIfInLayer; import org.wandora.application.tools.selections.SelectTopicIfNoAI; import org.wandora.application.tools.selections.SelectTopicIfNoAssociations; import org.wandora.application.tools.selections.SelectTopicIfNoBasenames; import org.wandora.application.tools.selections.SelectTopicIfNoClasses; import org.wandora.application.tools.selections.SelectTopicIfNoInstances; import org.wandora.application.tools.selections.SelectTopicIfNoOccurrences; import org.wandora.application.tools.selections.SelectTopicIfNotInLayer; import org.wandora.application.tools.selections.SelectTopicIfSL; import org.wandora.application.tools.selections.SelectTopicWithAssociationType; import org.wandora.application.tools.selections.SelectTopicWithClipboard; import org.wandora.application.tools.selections.SelectTopicWithClipboardRegex; import org.wandora.application.tools.selections.SelectionInfo; import org.wandora.application.tools.server.HTTPServerTool; import org.wandora.application.tools.som.SOMClassifier; import org.wandora.application.tools.statistics.AssetWeights; import org.wandora.application.tools.statistics.AssociationCounterTool; import org.wandora.application.tools.statistics.AverageClusteringCoefficient; import org.wandora.application.tools.statistics.MergeMatrixTool; import org.wandora.application.tools.statistics.TopicMapDiameter; import org.wandora.application.tools.statistics.TopicMapStatistics; import org.wandora.application.tools.subjects.AddSubjectIdentifier; import org.wandora.application.tools.subjects.CheckSubjectIdentifiers; import org.wandora.application.tools.subjects.CheckSubjectLocator; import org.wandora.application.tools.subjects.ConvertSubjectLocatorToDataURL; import org.wandora.application.tools.subjects.CopySubjectIdentifiers; import org.wandora.application.tools.subjects.DeleteSubjectIdentifiers; import org.wandora.application.tools.subjects.DeleteSubjectIdentifiersWithRegex; import org.wandora.application.tools.subjects.DeleteSubjectLocator; import org.wandora.application.tools.subjects.DownloadSubjectLocators; import org.wandora.application.tools.subjects.DuplicateSubjectIdentifier; import org.wandora.application.tools.subjects.ExtractWithSubjectLocator; import org.wandora.application.tools.subjects.FixSubjectIdentifiers2; import org.wandora.application.tools.subjects.FlattenSubjectIdentifiers; import org.wandora.application.tools.subjects.MakeSubjectIdentifierFromBasename; import org.wandora.application.tools.subjects.MakeSubjectIdentifierFromFilename; import org.wandora.application.tools.subjects.MakeSubjectIdentifierFromOccurrence; import org.wandora.application.tools.subjects.MakeSubjectIdentifierFromSubjectLocator; import org.wandora.application.tools.subjects.MakeSubjectLocatorFromBasename; import org.wandora.application.tools.subjects.MakeSubjectLocatorFromFileContent; import org.wandora.application.tools.subjects.MakeSubjectLocatorFromFilename; import org.wandora.application.tools.subjects.MakeSubjectLocatorFromOccurrence; import org.wandora.application.tools.subjects.MakeSubjectLocatorFromSubjectIdentifier; import org.wandora.application.tools.subjects.ModifySubjectIdentifiersWithRegex; import org.wandora.application.tools.subjects.ModifySubjectLocatorWithRegex; import org.wandora.application.tools.subjects.OpenSubjectIdentifier; import org.wandora.application.tools.subjects.OpenSubjectLocator; import org.wandora.application.tools.subjects.PasteSubjectIdentifiers; import org.wandora.application.tools.subjects.RemoveReferencesInSubjectIdentifiers; import org.wandora.application.tools.subjects.expand.SameAs270aStoreSubjectExpander; import org.wandora.application.tools.subjects.expand.SameAsAnywhereSubjectExpander; import org.wandora.application.tools.subjects.expand.SameAsBritishLibraryStoreSubjectExpander; import org.wandora.application.tools.subjects.expand.SameAsDataSouthamptonStoreSubjectExpander; import org.wandora.application.tools.subjects.expand.SameAsDisaster20StoreSubjectExpander; import org.wandora.application.tools.subjects.expand.SameAsEmailStoreSubjectExpander; import org.wandora.application.tools.subjects.expand.SameAsFreebaseStoreSubjectExpander; import org.wandora.application.tools.subjects.expand.SameAsKelleStoreSubjectExpander; import org.wandora.application.tools.subjects.expand.SameAsLATCStoreSubjectExpander; import org.wandora.application.tools.subjects.expand.SameAsLibrisStoreSubjectExpander; import org.wandora.application.tools.subjects.expand.SameAsMusicNetStoreSubjectExpander; import org.wandora.application.tools.subjects.expand.SameAsNoTubeStoreSubjectExpander; import org.wandora.application.tools.subjects.expand.SameAsOrdnanceSurveyStoreSubjectExpander; import org.wandora.application.tools.subjects.expand.SameAsPleiadesStoreSubjectExpander; import org.wandora.application.tools.subjects.expand.SameAsSchemaOrgStoreSubjectExpander; import org.wandora.application.tools.subjects.expand.SameAsSubjectExpander; import org.wandora.application.tools.subjects.expand.SameAsTorverDataStoreSubjectExpander; import org.wandora.application.tools.subjects.expand.SameAsVIAFStoreSubjectExpander; import org.wandora.application.tools.subjects.expand.SameAsWebIndexStoreSubjectExpander; import org.wandora.application.tools.topicnames.AddImplicitDisplayScopeToVariants; import org.wandora.application.tools.topicnames.AddImplicitSortScopeToVariants; import org.wandora.application.tools.topicnames.AddMissingLanguageScope; import org.wandora.application.tools.topicnames.AddVariantName; import org.wandora.application.tools.topicnames.AllEmptyVariantRemover; import org.wandora.application.tools.topicnames.AllVariantRemover; import org.wandora.application.tools.topicnames.BasenameNewlineRemover; import org.wandora.application.tools.topicnames.BasenameRegexReplacer; import org.wandora.application.tools.topicnames.BasenameRemover; import org.wandora.application.tools.topicnames.BasenameTrimmer; import org.wandora.application.tools.topicnames.BasenameWhiteSpaceCollapser; import org.wandora.application.tools.topicnames.ChangeVariantView; import org.wandora.application.tools.topicnames.MakeBasenameFromOccurrence; import org.wandora.application.tools.topicnames.MakeBasenameFromSubjectIdentifier; import org.wandora.application.tools.topicnames.MakeDisplayVariantsFromBasename; import org.wandora.application.tools.topicnames.MakeDisplayVariantsFromOccurrences; import org.wandora.application.tools.topicnames.MakeSortVariantsFromBasename; import org.wandora.application.tools.topicnames.TopicNameCopier; import org.wandora.application.tools.topicnames.VariantNewlineRemover; import org.wandora.application.tools.topicnames.VariantRegexReplacer; import org.wandora.application.tools.topicnames.VariantRemover; import org.wandora.application.tools.topicnames.VariantScopeCopier; import org.wandora.application.tools.topicnames.VariantWhiteSpaceCollapser; import org.wandora.application.tools.topicnames.VariantsToTopicsAndAssociations; import org.wandora.application.tools.undoredo.Redo; import org.wandora.application.tools.undoredo.Undo; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; import org.wandora.utils.Options; import bibliothek.gui.Dockable; /** * <p> * WandoraMenuManager is a storage for most menu structures used in * Wandora. Class contains static methods to retrieve menu content * of the File menu, for example. * </p> * <p> * As menu structures are centralized here, it should be rather easy to * customize Wandora. * </p> * * @see WandoraToolManager * @author akivela */ public class WandoraMenuManager { public JMenu importToLayerMenu = new SimpleMenu("Merge to layer", UIBox.getIcon("gui/icons/layers_importto.png")); public JMenu exportLayerMenu = new SimpleMenu("Export layer", UIBox.getIcon("gui/icons/layers_export.png")); public JMenu generatorLayerMenu = new SimpleMenu("Generate to layer", UIBox.getIcon("gui/icons/layers_generateto.png")); public JMenu importMenu = new SimpleMenu("Import", UIBox.getIcon("gui/icons/import.png")); public JMenu exportMenu = new SimpleMenu("Export", UIBox.getIcon("gui/icons/export.png")); public JMenu extractMenu = new SimpleMenu("Extract", UIBox.getIcon("gui/icons/extract.png")); public JMenu generatorMenu = new SimpleMenu("Generate", UIBox.getIcon("gui/icons/generate.png")); public static Map SLExtractorMenus = new LinkedHashMap(); //public static JMenu extractWithSLTableMenu = new SimpleMenu("Extract with SL"); // Here the context is default topic context. //public static JMenu extractWithSLTreeMenu = new SimpleMenu("Extract with SL"); // Here the context is default topic context. public JMenu extractWithSLTopicMenu = new SimpleMenu("Extract with subject locator"); // Here the context is application. public JMenu fileMenu = new SimpleMenu("File", (Icon) null); public JMenu editMenu = new SimpleMenu("Edit", (Icon) null); public JMenu viewMenu = new SimpleMenu("View", (Icon) null); public JMenu topicMenu = new SimpleMenu("Topics", (Icon) null); public JMenu layersMenu = new SimpleMenu("Layers", (Icon) null); public JMenu shortcutsMenu = new SimpleMenu("Shortcuts", (Icon) null); public JMenu toolMenu = new SimpleMenu("Tools", (Icon) null); public JMenu serverMenu = new SimpleMenu("Server", (Icon) null); public JMenu helpMenu = new SimpleMenu("Help", (Icon) null); public JMenu[] wandoraBarMenus = new JMenu[] { fileMenu, editMenu, viewMenu, topicMenu, layersMenu, layersMenu, shortcutsMenu, toolMenu, serverMenu, helpMenu }; private JMenuBar wandoraMenuBar; private Wandora wandora; private WandoraToolManager2 toolManager; private static WandoraMenuManager menuManager; private static int DEF_MASK = UIBox.isMac() ? META_DOWN_MASK : CTRL_DOWN_MASK; /** * Creates a new instance of WandoraMenuManager */ public WandoraMenuManager(Wandora wandora) throws TopicMapException { this.menuManager = this; this.wandora = wandora; this.toolManager = wandora.toolManager; refreshMenus(); this.wandoraMenuBar = new JMenuBar(); refreshMenuBar(); } public void refreshMenus() throws TopicMapException { associationsPopupStruct = null; defaultAddToTopicMenuStruct = null; defaultBasenameMenuStruct = null; defaultCopyAlsoMenuStruct = null; defaultCopyMenuStruct = null; defaultDeleteFromTopicMenuStruct = null; defaultDeleteTopicMenuStruct = null; defaultNewTopicMenuStruct = null; defaultOccurrenceMenuStruct = null; defaultPasteAlsoMenuStruct = null; defaultSIMenuStruct = null; defaultSLMenuStruct = null; defaultSelectMenuStruct = null; defaultSelectMenuStructForTopicTable = null; defaultVariantNameMenu = null; layerTreeMenuStructure = null; logoMenuStructure = null; SLExtractorMenus = new LinkedHashMap<>(); refreshFileMenu(); refreshEditMenu(); refreshViewMenu(); refreshTopicsMenu(); refreshLayersMenu(); refreshShortcutsMenu(); refreshToolMenu(); refreshServerMenu(); refreshHelpMenu(); } public void refreshMenuBar() { wandoraMenuBar.removeAll(); JMenu menu = null; for(int i=0; i<wandoraBarMenus.length; i++) { menu = wandoraBarMenus[i]; if(menu != null) { wandoraMenuBar.add( menu ); } else { System.out.println("Warning! Null menu item found in wandoraAdminBarMenus"); } } } public JMenuBar getWandoraMenuBar() { return wandoraMenuBar; } // ------------------------------------------------------------------------- public void refreshToolMenu() { toolManager.getToolMenu( toolMenu ); } public void refreshShortcutsMenu() throws TopicMapException { wandora.shortcuts.getShortcutsMenu( shortcutsMenu ); } public void refreshImportMenu() { toolManager.getImportMenu( importMenu ); toolManager.getImportMergeMenu( importToLayerMenu ); } public void refreshExtractMenu() { toolManager.getExtractMenu( extractMenu ); for(Iterator i=SLExtractorMenus.values().iterator(); i.hasNext();) { refreshExtractWithSLMenu( (JMenu) i.next(), null, wandora); } refreshExtractWithSLMenu( extractWithSLTopicMenu, new ApplicationContext() , wandora); } public void refreshExportMenu() { toolManager.getExportMenu( exportMenu ); toolManager.getExportMenu( exportLayerMenu ); } public void refreshGeneratorMenu() { toolManager.getGeneratorMenu( generatorMenu ); toolManager.getGeneratorMenu( generatorLayerMenu ); } public void refreshLayersMenu() { refreshImportMenu(); refreshExtractMenu(); refreshExportMenu(); refreshGeneratorMenu(); // --- Merge --- Object[] mergeLayers = new Object[] { "Merge up...", KeyStroke.getKeyStroke(VK_UP, SHIFT_DOWN_MASK | ALT_DOWN_MASK), new MergeLayers(MergeLayers.MERGE_UP), "Merge down...", KeyStroke.getKeyStroke(VK_DOWN, SHIFT_DOWN_MASK | ALT_DOWN_MASK), new MergeLayers(MergeLayers.MERGE_DOWN), "Merge all...", KeyStroke.getKeyStroke(VK_M, SHIFT_DOWN_MASK | ALT_DOWN_MASK), new MergeLayers(MergeLayers.MERGE_ALL), "Merge visible...", KeyStroke.getKeyStroke(VK_M, ALT_DOWN_MASK), new MergeLayers(MergeLayers.MERGE_VISIBLE), }; JMenu mergeLayersMenu = new SimpleMenu("Merge layers", UIBox.getIcon("gui/icons/layers_merge.png")); UIBox.attachMenu( mergeLayersMenu, mergeLayers, wandora ); // --- Arrange --- Object[] arrangeLayers = new Object[] { "Move up", UIBox.getIcon("gui/icons/move_up.png"), KeyStroke.getKeyStroke(VK_UP, ALT_DOWN_MASK), new ArrangeLayers(LayerTree.MOVE_LAYER_UP), "Move down", UIBox.getIcon("gui/icons/move_down.png"), KeyStroke.getKeyStroke(VK_DOWN, ALT_DOWN_MASK), new ArrangeLayers(LayerTree.MOVE_LAYER_DOWN), "Move top", UIBox.getIcon("gui/icons/move_top.png"), KeyStroke.getKeyStroke(VK_HOME, ALT_DOWN_MASK), new ArrangeLayers(LayerTree.MOVE_LAYER_TOP), "Move bottom", UIBox.getIcon("gui/icons/move_bottom.png"), KeyStroke.getKeyStroke(VK_END, ALT_DOWN_MASK), new ArrangeLayers(LayerTree.MOVE_LAYER_BOTTOM), "---", "Reverse order", UIBox.getIcon("gui/icons/reverse_order.png"), new ArrangeLayers(LayerTree.REVERSE_LAYERS), }; JMenu arrangeLayersMenu = new SimpleMenu("Arrange layers", UIBox.getIcon("gui/icons/layers_arrange.png")); UIBox.attachMenu( arrangeLayersMenu, arrangeLayers, wandora ); // --- View --- Object[] viewLayers = new Object[] { "View all", KeyStroke.getKeyStroke(VK_V, ALT_DOWN_MASK), new ViewLayers(ViewLayers.VIEW_ALL), "Hide all", KeyStroke.getKeyStroke(VK_H, ALT_DOWN_MASK), new ViewLayers(ViewLayers.HIDE_ALL), "Hide all but current", KeyStroke.getKeyStroke(VK_V, SHIFT_DOWN_MASK | ALT_DOWN_MASK), new ViewLayers(ViewLayers.HIDE_ALL_BUT_CURRENT), "Reverse visibility", new ViewLayers(ViewLayers.REVERSE_VISIBILITY), }; JMenu viewLayersMenu = new SimpleMenu("View layers", UIBox.getIcon("gui/icons/layers_view.png")); UIBox.attachMenu( viewLayersMenu, viewLayers, wandora ); // --- Lock --- Object[] lockLayers = new Object[] { "Lock all", KeyStroke.getKeyStroke(VK_L, ALT_DOWN_MASK), new LockLayers(LockLayers.LOCK_ALL), "Unlock all", KeyStroke.getKeyStroke(VK_U, ALT_DOWN_MASK), new LockLayers(LockLayers.UNLOCK_ALL), "Lock all but current", KeyStroke.getKeyStroke(VK_L, SHIFT_DOWN_MASK | ALT_DOWN_MASK), new LockLayers(LockLayers.LOCK_ALL_BUT_CURRENT), "Reverse locks", new LockLayers(LockLayers.REVERSE_LOCKS), }; JMenu lockLayersMenu = new SimpleMenu("Lock layers", UIBox.getIcon("gui/icons/layers_lock.png")); UIBox.attachMenu( lockLayersMenu, lockLayers, wandora ); // --- Stats --- Object[] statLayers = new Object[] { "Topic map info...", UIBox.getIcon("gui/icons/layer_info.png"), KeyStroke.getKeyStroke(VK_I, ALT_DOWN_MASK), new TopicMapStatistics(), "Topic map connection statistics...", UIBox.getIcon("gui/icons/layer_acount.png"), new AssociationCounterTool(), "Asset weights...", UIBox.getIcon("gui/icons/asset_weight.png"), new AssetWeights(AssetWeights.CONTEXT_IS_TOPICMAP), "Topic map diameter...", UIBox.getIcon("gui/icons/topicmap_diameter.png"), new TopicMapDiameter(), //"Topic map diameter (alternative)...", UIBox.getIcon("gui/icons/topicmap_diameter.png"), new TopicMapDiameterAlternative(), "Average clustering coefficient...", UIBox.getIcon("gui/icons/clustering_coefficient.png"), new AverageClusteringCoefficient(), "Merge ratio matrix...",UIBox.getIcon("gui/icons/layer_info.png"), new MergeMatrixTool(), "---", "Occurrence summary report...", UIBox.getIcon("gui/icons/summary_report.png"), new OccurrenceSummaryReport(), }; JMenu statsMenu = new SimpleMenu("Statistics", UIBox.getIcon("gui/icons/layer_stats.png")); UIBox.attachMenu( statsMenu, statLayers, wandora ); // --- Compose Layer Menu --- Object[] menuStructure = new Object[] { "New layer...", UIBox.getIcon("gui/icons/layer_create.png"), KeyStroke.getKeyStroke(VK_N, ALT_DOWN_MASK), new NewLayer(), "---", "Rename layer", UIBox.getIcon("gui/icons/layer_rename.png"), KeyStroke.getKeyStroke(VK_R, ALT_DOWN_MASK), new RenameLayer(), "Configure layer...", UIBox.getIcon("gui/icons/layer_configure.png"), KeyStroke.getKeyStroke(VK_O, ALT_DOWN_MASK), new ConfigureLayer(), "Delete layer...", UIBox.getIcon("gui/icons/layer_delete.png"), KeyStroke.getKeyStroke(VK_DELETE, ALT_DOWN_MASK), new DeleteLayer(), "Clear layer topic map...", UIBox.getIcon("gui/icons/layer_topicmap_clear.png"), new ClearTopicMap(), "Clear topic map indexes...", UIBox.getIcon("gui/icons/layer_index_clear.png"), new ClearTopicMapIndexes(), "---", mergeLayersMenu, importToLayerMenu, generatorLayerMenu, exportLayerMenu, "---", arrangeLayersMenu, viewLayersMenu, lockLayersMenu, "---", statsMenu, }; layersMenu.removeAll(); UIBox.attachMenu( layersMenu, menuStructure, wandora ); } public void refreshServerMenu() { List<Object> menuStructure = new ArrayList<>(); WandoraModulesServer httpServer = wandora.getHTTPServer(); if(httpServer != null) { if(httpServer.isRunning()){ menuStructure.add("Stop server"); menuStructure.add(UIBox.getIcon("gui/icons/server_stop.png")); //menuStructure[2]=KeyStroke.getKeyStroke(VK_M, DEF_MASK); menuStructure.add(new HTTPServerTool(HTTPServerTool.STOP_AND_MENU)); } else{ menuStructure.add("Start server"); menuStructure.add(UIBox.getIcon("gui/icons/server_start.png")); //menuStructure[2]=KeyStroke.getKeyStroke(VK_M, DEF_MASK); menuStructure.add(new HTTPServerTool(HTTPServerTool.START_AND_MENU)); } List<ModulesWebApp> webApps=httpServer.getWebApps(); Map<String,ModulesWebApp> webAppsMap=new HashMap<>(); for(ModulesWebApp wa : webApps) { webAppsMap.put(wa.getAppName(), wa); } List<String> sorted = new ArrayList<>(webAppsMap.keySet()); Collections.sort(sorted); List<Object> browseServices = new ArrayList<>(); JMenu browseServicesMenu = new SimpleMenu("Browse services", UIBox.getIcon("gui/icons/server_open.png")); for(String appName : sorted) { ModulesWebApp wa=webAppsMap.get(appName); if(wa.isRunning()) { String url=wa.getAppStartPage(); if(url==null) continue; browseServices.add(appName); browseServices.add(UIBox.getIcon("gui/icons/open_browser.png")); browseServices.add(new HTTPServerTool(HTTPServerTool.OPEN_PAGE, wa)); } else { browseServices.add(appName); browseServices.add(UIBox.getIcon("gui/icons/open_browser.png")); browseServices.add(new HTTPServerTool(HTTPServerTool.OPEN_PAGE, wa)); } } UIBox.attachMenu(browseServicesMenu, browseServices.toArray(), wandora); menuStructure.add( browseServicesMenu ); menuStructure.add("Server settings..."); menuStructure.add(UIBox.getIcon("gui/icons/server_configure.png")); menuStructure.add(new HTTPServerTool(HTTPServerTool.CONFIGURE+HTTPServerTool.UPDATE_MENU)); } else { menuStructure.add("[No server available]"); } serverMenu.removeAll(); UIBox.attachMenu( serverMenu, menuStructure.toArray(), wandora ); } public void refreshHelpMenu() { Object[] menuStructure = new Object[] { "Wandora home", UIBox.getIcon("gui/icons/open_browser.png"), KeyStroke.getKeyStroke(VK_H, DEF_MASK), new ExecBrowser("http://www.wandora.org"), "---", "Documentation", UIBox.getIcon("gui/icons/open_browser.png"), new ExecBrowser("http://wandora.org/wiki/Documentation"), "Forum", UIBox.getIcon("gui/icons/open_browser.png"), new ExecBrowser("http://wandora.org/forum/index.php"), "YouTube channel", UIBox.getIcon("gui/icons/open_browser.png"), new ExecBrowser("http://wandora.org/tv/"), "Github repository", UIBox.getIcon("gui/icons/open_browser.png"), new ExecBrowser("https://github.com/wandora-team/wandora"), "Twitter", UIBox.getIcon("gui/icons/open_browser.png"), new ExecBrowser("https://twitter.com/wandora_app"), "---", "About Wandora...", UIBox.getIcon("gui/icons/info.png"),new AboutWandora(), "Wandora credits...", UIBox.getIcon("gui/icons/info.png"),new AboutCredits(), }; helpMenu.removeAll(); UIBox.attachMenu( helpMenu, menuStructure, wandora ); } public void refreshViewMenu() { viewMenu.removeAll(); UIBox.attachMenu(viewMenu, wandora.topicPanelManager.getViewMenuStruct() , wandora); JMenu viewTopicAsMenu = new SimpleMenu("View topic as", UIBox.getIcon("gui/icons/view_topic_as.png")); Object[] viewTopicAsMenuStructure = new Object[] { "Base name", UIBox.getIcon("gui/icons/view_topic_as_basename.png"), new SetTopicStringifier(new DefaultTopicStringifier(DefaultTopicStringifier.TOPIC_RENDERS_BASENAME)), "Subject identifier", UIBox.getIcon("gui/icons/view_topic_as_si.png"), new SetTopicStringifier(new DefaultTopicStringifier(DefaultTopicStringifier.TOPIC_RENDERS_SI)), "Subject identifier without domain", UIBox.getIcon("gui/icons/view_topic_as_si_wo_domain.png"), new SetTopicStringifier(new DefaultTopicStringifier(DefaultTopicStringifier.TOPIC_RENDERS_SI_WITHOUT_DOMAIN)), "Subject locator", UIBox.getIcon("gui/icons/view_topic_as_sl.png"), new SetTopicStringifier(new DefaultTopicStringifier(DefaultTopicStringifier.TOPIC_RENDERS_SL)), "---", "English display name", UIBox.getIcon("gui/icons/view_topic_as_english_display.png"), new SetTopicStringifier(new DefaultTopicStringifier(DefaultTopicStringifier.TOPIC_RENDERS_ENGLISH_DISPLAY_NAME)), "Variant name...", UIBox.getIcon("gui/icons/view_topic_as_variant.png"), new SetTopicStringifier(new TopicStringifierToVariant()), "---", "Base name with topic info", UIBox.getIcon("gui/icons/view_topic_as_basename.png"), new SetTopicStringifier(new DefaultTopicStringifier(DefaultTopicStringifier.TOPIC_RENDERS_BASENAME_WITH_INFO)), }; UIBox.attachMenu( viewTopicAsMenu, viewTopicAsMenuStructure, wandora ); viewMenu.add(new JSeparator()); viewMenu.add(viewTopicAsMenu); } public void refreshTopicsMenu() { Object[] splitTopicStructure = new Object[] { "Split topic with subject identifiers", KeyStroke.getKeyStroke(VK_S, DEF_MASK | SHIFT_DOWN_MASK), new SplitTopics(new ApplicationContext()), "Split topic with a base name regex...", new SplitTopicsWithBasename(new ApplicationContext()), "---", "Split to descending instances with a base name regex...", new SplitToInstancesWithBasename(new ApplicationContext(), true), "Split to ascending instances with a base name regex...", new SplitToInstancesWithBasename(new ApplicationContext(), false), "---", "Split to descending superclasses with a base name regex...", new SplitToSuperclassesWithBasename(new ApplicationContext(), true), "Split to ascending superclasses with a base name regex...", new SplitToSuperclassesWithBasename(new ApplicationContext(), false), }; JMenu splitTopicMenu = new SimpleMenu("Split topic", UIBox.getIcon("gui/icons/topic_split.png")); splitTopicMenu.removeAll(); UIBox.attachMenu( splitTopicMenu, splitTopicStructure, wandora ); // ---- THE STRUCTURE ---- Object[] menuStructure = new Object[] { "Open topic", UIBox.getIcon("gui/icons/topic_open.png"), KeyStroke.getKeyStroke(VK_O, DEF_MASK), new OpenTopic(OpenTopic.ASK_USER), "Close panel", UIBox.getIcon("gui/icons/topic_close.png"), KeyStroke.getKeyStroke(VK_W, DEF_MASK), new CloseCurrentTopicPanel(), "---", "New topic...", UIBox.getIcon("gui/icons/new_topic.png"), KeyStroke.getKeyStroke(VK_N, DEF_MASK), new NewTopicExtended(), "Delete topic...", UIBox.getIcon("gui/icons/topic_delete.png"), KeyStroke.getKeyStroke(VK_DELETE, DEF_MASK), new DeleteTopics(new ApplicationContext()), "Duplicate topic...", UIBox.getIcon("gui/icons/topic_duplicate.png"), KeyStroke.getKeyStroke(VK_D, DEF_MASK), new DuplicateTopics(new ApplicationContext()), splitTopicMenu, "---", "Add to topic", new Object[] { "Add class...", new AddClass(new ApplicationContext()), "Add instance...",new AddInstance(new ApplicationContext()), // "Add associations...", new AddAssociations(new ApplicationContext()), "Add association...", new AddSchemalessAssociation(new ApplicationContext()), //"Add occurrence...", new AddOccurrences(new ApplicationContext()), "Add variant name...", new AddVariantName(new ApplicationContext()), "Add occurrence...", new AddSchemalessOccurrence(new ApplicationContext()), "Add subject identifier...", new AddSubjectIdentifier(new ApplicationContext()), }, "Delete from topic", new Object[] { "Delete associations with type...",new DeleteAssociationsInTopicWithType(new ApplicationContext()), "Delete empty and unary associations...", new DeleteUnaryAssociations(new ApplicationContext()), "Delete all associations...",new DeleteAssociationsInTopic(new ApplicationContext()), "---", "Delete base name...", new BasenameRemover(new ApplicationContext()), "Delete all variant names...", new AllVariantRemover(new ApplicationContext()), "---", "Delete instances...",new DeleteFromTopics(new ApplicationContext(), DeleteFromTopics.LOOSE_INSTANCES), "Delete classes...",new DeleteFromTopics(new ApplicationContext(), DeleteFromTopics.LOOSE_CLASSES), "---", "Delete all but one subject identifier...", new FlattenSubjectIdentifiers(new ApplicationContext()), "Delete subject locator...", new DeleteSubjectLocator(new ApplicationContext()), }, "---", "Subject locator", new Object[] { "Open subject locator...", new OpenSubjectLocator(new ApplicationContext()), "Check subject locator...", new CheckSubjectLocator(new ApplicationContext()), "---", "Make subject locator from a filename...", new MakeSubjectLocatorFromFilename(new ApplicationContext()), "Make subject locator from file content...", new MakeSubjectLocatorFromFileContent(new ApplicationContext()), "Make subject locator from a subject identifier...", new MakeSubjectLocatorFromSubjectIdentifier(new ApplicationContext()), "Make subject locator from a base name...", new MakeSubjectLocatorFromBasename(new ApplicationContext()), "Make subject locator from an occurrence...", new MakeSubjectLocatorFromOccurrence(new ApplicationContext()), "---", "Download subject locator...", new DownloadSubjectLocators(new ApplicationContext()), "Download and change subject locator...", new DownloadSubjectLocators(new ApplicationContext(), true), "Convert to data url", new ConvertSubjectLocatorToDataURL(new ApplicationContext()), "Upload subject locator resource to Mediawiki...", new MediawikiSubjectLocatorUploader(new ApplicationContext()), "---", "Modify subject locator with a regex...", new ModifySubjectLocatorWithRegex(new ApplicationContext()), "---", "Remove subject locator...", new DeleteSubjectLocator(new ApplicationContext()), "---", extractWithSLTopicMenu, }, "Subject identifiers", new Object[] { "Open subject identifiers...", new OpenSubjectIdentifier(new ApplicationContext()), "Check subject identifiers...", new CheckSubjectIdentifiers(new ApplicationContext()), "---", "Make subject identifier from a filename...", new MakeSubjectIdentifierFromFilename(new ApplicationContext()), "Make subject identifier from a subject locator", new MakeSubjectIdentifierFromSubjectLocator(new ApplicationContext()), "Make subject identifier from a base name...", new MakeSubjectIdentifierFromBasename(new ApplicationContext()), "Make subject identifier from an occurrence...", new MakeSubjectIdentifierFromOccurrence(new ApplicationContext()), "---", "Copy subject identifiers", new CopySubjectIdentifiers(new ApplicationContext()), "Paste subject identifiers", new PasteSubjectIdentifiers(new ApplicationContext()), "Duplicate subject identifiers...", new DuplicateSubjectIdentifier(new ApplicationContext()), "---", "Flatten identity...", new FlattenSubjectIdentifiers(new ApplicationContext()), "Remove subject identifiers with a regex...", new DeleteSubjectIdentifiersWithRegex(new ApplicationContext()), "---", "Remove references in subject identifiers", new RemoveReferencesInSubjectIdentifiers(new ApplicationContext()), "Modify subject identifiers with a regex...", new ModifySubjectIdentifiersWithRegex(new ApplicationContext()), // "Fix SIs", new SIFixer(new ApplicationContext()), "Fix subject identifiers", new FixSubjectIdentifiers2(new ApplicationContext()), }, "Base name", new Object[] { "Make base name from a subject identifier", new MakeBasenameFromSubjectIdentifier(new ApplicationContext()), "Make base name from an occurrence...", new MakeBasenameFromOccurrence(new ApplicationContext()), "---", "Modify base name with a regex...", new BasenameRegexReplacer(new ApplicationContext()), "Remove new line characters", new BasenameNewlineRemover(new ApplicationContext()), "Collapse white spaces", new BasenameWhiteSpaceCollapser(new ApplicationContext()), "Trim base name", new BasenameTrimmer(new ApplicationContext()), "---", "Remove base name...", new BasenameRemover(new ApplicationContext()), }, "Variant names", new Object[] { "Make display variants from occurrences", new MakeDisplayVariantsFromOccurrences(new ApplicationContext()), "Make display variants from base names", new MakeDisplayVariantsFromBasename(new ApplicationContext()), "Make sort variants from base names", new MakeSortVariantsFromBasename(new ApplicationContext()), "---", "Copy all variant names to clipboard", new TopicNameCopier(new ApplicationContext()), "---", "Copy variant names to other scope...", new VariantScopeCopier(new ApplicationContext()), "Move variant names to other scope...", new VariantScopeCopier(true, new ApplicationContext()), "---", "Transform variants to topics...", new VariantsToTopicsAndAssociations(new ApplicationContext()), "---", "Modify variant names with a regex...", new VariantRegexReplacer(new ApplicationContext()), "Remove new line characters", new VariantNewlineRemover(new ApplicationContext()), "Collapse white spaces", new VariantWhiteSpaceCollapser(new ApplicationContext()), "---", "Add missing display scope", new AddImplicitDisplayScopeToVariants(new ApplicationContext()), "Add missing sort scope", new AddImplicitSortScopeToVariants(new ApplicationContext()), "Add missing language...", new AddMissingLanguageScope(new ApplicationContext()), "---", "Remove variant names...", new VariantRemover(new ApplicationContext()), "Remove all empty variant names...", new AllEmptyVariantRemover(new ApplicationContext()), "Remove all variant names...", new AllVariantRemover(new ApplicationContext()), }, "Occurrences", new Object[] { "Make occurrence from a subject locator...", new MakeOccurrenceFromSubjectLocator(new ApplicationContext()), "Make occurrence from a subject identifier...", new MakeOccurrenceFromSubjectIdentifier(new ApplicationContext()), "Make occurrence from a base name...", new MakeOccurrenceFromBasename(new ApplicationContext()), "Make occurrence from a variant name...", new MakeOccurrenceFromVariant(new ApplicationContext()), "Make occurrences from all variant name languages...", new MakeOccurrencesFromVariants(new ApplicationContext()), "Make occurrence from an association...", new MakeOccurrenceFromAssociation(new ApplicationContext()), "---", "Modify occurrences with a regex...", new OccurrenceRegexReplacerOne(new ApplicationContext()), "Modify all occurrences with a regex...", new OccurrenceRegexReplacerAll(new ApplicationContext()), "---", "Copy occurrence to all other scopes...", new SpreadOccurrence(new ApplicationContext()), "Copy occurrence to other scope...", new OccurrenceScopeCopier(new ApplicationContext()), "Move occurrence to other scope...", new OccurrenceScopeCopier(true, new ApplicationContext()), "---", "Check URL occurrences...", new URLOccurrenceChecker(new ApplicationContext()), "Download URL occurrences...", new DownloadOccurrence(new ApplicationContext()), "Download all URL occurrences...", new DownloadAllOccurrences(new ApplicationContext()), "---", "Upload to Pastebin...", new PasteBinOccurrenceUploader(new ApplicationContext()), "Download from Pastebin", new PasteBinOccurrenceDownloader(new ApplicationContext()), "---", "Upload URL resource to MediaWiki", new MediawikiOccurrenceUploader(new ApplicationContext()), "Upload content to MediaWiki...", new MediaWikiAPIUploader(new ApplicationContext()), "---", "Delete occurrence with type...", new DeleteOccurrence(new ApplicationContext()), }, "---", "Schema", new Object[] { "Create association type...", new CreateAssociationType(new EmptyContext()), "Create association type from selected topics...", new CreateAssociationType(new TopicContext()), "Create association type from selected association...", new CreateAssociationType(new AssociationContext()), } }; topicMenu.removeAll(); UIBox.attachMenu( topicMenu, menuStructure, wandora ); } public void refreshEditMenu() { Object[] menuStructure = new Object[] { "Undo", KeyStroke.getKeyStroke(VK_Z, DEF_MASK), UIBox.getIcon("gui/icons/undo_undo.png"), new Undo(), "Redo", KeyStroke.getKeyStroke(VK_Y, DEF_MASK), UIBox.getIcon("gui/icons/undo_redo.png"), new Redo(), "---", "Cut", KeyStroke.getKeyStroke(VK_X, DEF_MASK), UIBox.getIcon("gui/icons/cut.png"), new SystemClipboard(SystemClipboard.CUT), "Copy", KeyStroke.getKeyStroke(VK_C, DEF_MASK), UIBox.getIcon("gui/icons/copy.png"), new SystemClipboard(SystemClipboard.COPY), "Paste", KeyStroke.getKeyStroke(VK_V, DEF_MASK), UIBox.getIcon("gui/icons/paste.png"), new SystemClipboard(SystemClipboard.PASTE), "---", "Select", new Object[] { "Select all", KeyStroke.getKeyStroke(VK_A, DEF_MASK), new SelectAll(), /* "Select row(s)", new SelectRows(), "Select column(s)", new SelectColumns(), **/ "Deselect", new ClearSelection(), "Invert selection", new InvertSelection(), "---", "Select topics without associations", new SelectTopicIfNoAssociations(), "Select topics without occurrences", new SelectTopicIfNoOccurrences(), "Select topics without base names", new SelectTopicIfNoBasenames(), "Select topics without classes", new SelectTopicIfNoClasses(), "Select topics without instances", new SelectTopicIfNoInstances(), "Select topics without A+I", new SelectTopicIfNoAI(), "---", "Select topics with subject locator", new SelectTopicIfSL(), "Select topics with typed associations", new SelectTopicWithAssociationType(), "---", "Select topics with clipboard identifiers", new SelectTopicWithClipboard(), "Select topics with clipboard regexes", new SelectTopicWithClipboardRegex(), "Select topics with clipboard regex finders", new SelectTopicWithClipboardRegex(false), }, "Selection info...", new SelectionInfo(), "---", /* "[Copy topic]", new CopyToClipBoard(clipboardtm), "[Import topic clipboard...]", new ImportClipBoard(clipboardtm), "[Save topic clipboard...]", new SaveClipBoard(clipboardtm), "---", **/ "Search...", KeyStroke.getKeyStroke(VK_F, DEF_MASK), UIBox.getIcon("gui/icons/find_topics.png"), new Search(), // "Go to...", KeyStroke.getKeyStroke(VK_G, DEF_MASK), UIBox.getIcon("gui/icons/goto2.png"), new OpenTopicWithSX(), // "---", // "Locate topic in tree", new LocateSelectTopicInTree(), }; editMenu.removeAll(); UIBox.attachMenu( editMenu, menuStructure, wandora ); } public void refreshFileMenu() { refreshImportMenu(); refreshExtractMenu(); refreshExportMenu(); refreshGeneratorMenu(); Icon gitIcon = UIBox.getIcon(0xf1d3); // alt 0xf1d2 // ***** GIT ***** Object[] teamMenuStruct = new Object[] { "Initialize by cloning remote repository...", gitIcon, new Clone(), "Commit and push to remote...", gitIcon, new CommitPush(), "Commit to local...", gitIcon, new Commit(), "Push to remote...", gitIcon, new Push(), "Pull from remote...", gitIcon, new Pull(), "---", "Initialize local repository...", gitIcon, new Init(), "Commit to local...", gitIcon, new Commit(), "---", "Status...", gitIcon, new Status() }; JMenu teamMenu = new SimpleMenu("Git", gitIcon); teamMenu.removeAll(); UIBox.attachMenu( teamMenu, teamMenuStruct, wandora ); // ***** PATCH ****** Object[] patchMenuStruct = new Object[] { "Compare topic maps...", UIBox.getIcon("gui/icons/compare_topicmaps.png"), new DiffTool(), "Apply topic map patch...", UIBox.getIcon("gui/icons/patch_topicmap.png"), new ApplyPatchTool(), }; JMenu patchMenu = new SimpleMenu("Compare and patch", UIBox.getIcon("gui/icons/compare_patch_topicmaps.png")); patchMenu.removeAll(); UIBox.attachMenu( patchMenu, patchMenuStruct, wandora ); Object[] menuStructure = new Object[] { "New project...", KeyStroke.getKeyStroke(VK_N, DEF_MASK | SHIFT_DOWN_MASK), UIBox.getIcon("gui/icons/new_project.png"), new ResetWandora(), "Open project...", KeyStroke.getKeyStroke(VK_L, DEF_MASK), UIBox.getIcon("gui/icons/load_project.png"), new LoadWandoraProject(), "Merge project...", KeyStroke.getKeyStroke(VK_M, DEF_MASK), UIBox.getIcon("gui/icons/merge_project.png"), new MergeWandoraProject(), "---", "Save project", KeyStroke.getKeyStroke(VK_S, DEF_MASK), UIBox.getIcon("gui/icons/save_project.png"), new SaveWandoraProject(true), "Save project as...", KeyStroke.getKeyStroke(VK_S, DEF_MASK | SHIFT_DOWN_MASK), UIBox.getIcon("gui/icons/save_project_as.png"), new SaveWandoraProject(), "Revert", UIBox.getIcon("gui/icons/revert_project.png"), new RevertWandoraProject(), "---", importMenu, extractMenu, generatorMenu, exportMenu, teamMenu, "---", patchMenu, "---", "Print...", new Print(), KeyStroke.getKeyStroke(VK_P, DEF_MASK), UIBox.getIcon("gui/icons/print.png"), "---", "Exit", KeyStroke.getKeyStroke(VK_Q, DEF_MASK), UIBox.getIcon("gui/icons/exit.png"), new ExitWandora(), }; fileMenu.removeAll(); UIBox.makeMenu( fileMenu, menuStructure, wandora ); } // ------------------------------------------------------------------------- public String disableMenuIfNoTopic(String menuName) { return menuName; // TO DO... At the moment menus are static!!! Menu's visual representation // does NOT change if there is no topic open in topic panel. // return (this.openedTopic == null ? "["+ menuName +"]" : menuName); } public void hideMenu(String menuName) { Component menu = UIBox.getComponentByName(menuName, wandora); if(menu != null) { menu.setVisible(false); } } public void showMenu(String menuName) { Component menu = UIBox.getComponentByName(menuName, wandora); if(menu != null) { menu.setVisible(true); } } // ------------------------------------------------------------------------- // ------------------------------------------------ STATIC MENU STRUCTS ---- // ------------------------------------------------------------------------- private static Object[] defaultNewTopicMenuStruct = null; public static Object[] getDefaultNewTopicMenuStruct(Wandora admin, Object source) { if(defaultNewTopicMenuStruct == null) { try { defaultNewTopicMenuStruct = new Object[] { "New topic...", new NewTopicExtended(), "---", "New instance topic...", new NewTopic(NewTopic.MAKE_INSTANCE_OF_CONTEXT), "New subclass topic...", new NewTopic(NewTopic.MAKE_SUBCLASS_OF_CONTEXT), }; } catch(Exception e) { if(admin != null) admin.handleError(e); else e.printStackTrace(); } } return defaultNewTopicMenuStruct; } private static Object[] defaultDeleteTopicMenuStruct = null; public static Object[] getDefaultDeleteTopicMenuStruct(Wandora admin, Object source) { if(defaultDeleteTopicMenuStruct == null) { try { defaultDeleteTopicMenuStruct = new Object[] { "Delete topics...", new DeleteTopics(), "---", "Delete topics without A+C+I...", new DeleteTopicsWithoutACI(), "Delete topics without A+I...", new DeleteTopicsWithoutAI(), "Delete topics without associations...", new DeleteTopicsWithoutAssociations(), "Delete topics without classes...", new DeleteTopicsWithoutClasses(), "Delete topics without instances...", new DeleteTopicsWithoutInstances(), "Delete topics without base names...", new DeleteTopicsWithoutBasename(), "Delete topics without variant names...", new DeleteTopicsWithoutVariants(), "Delete topics without occurrences...", new DeleteTopicsWithoutOccurrences(), "---", "Delete topics with SI regexes...", new DeleteTopicsWithSIRegex(), "Delete topics with base name regexes...", new DeleteTopicsWithBasenameRegex(), "---", "Delete all topics in layer except selected...", new DeleteTopicsExceptSelected(), }; } catch(Exception e) { if(admin != null) admin.handleError(e); else e.printStackTrace(); } } return defaultDeleteTopicMenuStruct; } private static Object[] defaultAddToTopicMenuStruct = null; public static Object[] getDefaultAddToTopicMenuStruct(Wandora admin, Object source) { if(defaultAddToTopicMenuStruct == null) { try { defaultAddToTopicMenuStruct = new Object[] { "Add class...", new AddClass(), "Add instance...",new AddInstance(), // "Add associations...", new AddAssociations(), "Add association...", new AddSchemalessAssociation(), // "Add occurrences...", new AddOccurrences(), "Add variant name...", new AddVariantName(), "Add occurrence...", new AddSchemalessOccurrence(), "Add subject identifier...", new AddSubjectIdentifier(), }; } catch(Exception e) { if(admin != null) admin.handleError(e); else e.printStackTrace(); } } return defaultAddToTopicMenuStruct; } private static Object[] defaultDeleteFromTopicMenuStruct = null; public static Object[] getDefaultDeleteFromTopicMenuStruct(Wandora admin, Object source) { if(defaultDeleteFromTopicMenuStruct == null) { try { defaultDeleteFromTopicMenuStruct = new Object[] { "Delete base names within...", new BasenameRemover(), "Delete variant names within...", new VariantRemover(), "Delete all variant names within...", new AllVariantRemover(), "---", "Delete classes within...", new DeleteFromTopics(DeleteFromTopics.LOOSE_CLASSES), "Delete instances within...", new DeleteFromTopics(DeleteFromTopics.LOOSE_INSTANCES), "---", "Delete associations within...", new DeleteAssociationsInTopic(), "Delete associations within with type...",new DeleteAssociationsInTopicWithType(), "Delete empty and unary associations within...", new DeleteUnaryAssociations(), "---", "Delete occurrences within...", new DeleteFromTopics(DeleteFromTopics.DELETE_TEXTDATAS), "Delete occurrences within with type...", new DeleteOccurrence(), "---", "Delete subject locator within...", new DeleteSubjectLocator(), "Delete all but one subject identifier within...", new FlattenSubjectIdentifiers(), }; } catch(Exception e) { if(admin != null) admin.handleError(e); else e.printStackTrace(); } } return defaultDeleteFromTopicMenuStruct; } private static Object[] defaultSelectMenuStructForTopicGrid = null; private static Object[] defaultSelectMenuStructForTopicTable = null; private static Object[] defaultSelectMenuStruct = null; public static Object[] getDefaultSelectMenuStruct(Wandora admin, Object source) { Object[] menuStruct = null; try { if(source instanceof TopicGrid) { if(defaultSelectMenuStructForTopicGrid == null) { defaultSelectMenuStructForTopicGrid = new Object[] { "Select all", new SelectAll(), "Select row(s)", new SelectRows(), "Select column(s)", new SelectColumns(), "Invert selection", new InvertSelection(), "Deselect", new ClearSelection(), "---", "Select topics without associations", new SelectTopicIfNoAssociations(), "Select topics without occurrences", new SelectTopicIfNoOccurrences(), "Select topics without base names", new SelectTopicIfNoBasenames(), "Select topics without classes", new SelectTopicIfNoClasses(), "Select topics without instances", new SelectTopicIfNoInstances(), "Select topics without A+I", new SelectTopicIfNoAI(), "---", "Select topics with SL", new SelectTopicIfSL(), "Select topics with typed associations", new SelectTopicWithAssociationType(), "---", "Select topics with clipboard identifiers", new SelectTopicWithClipboard(), "Select topics with clipboard regexes", new SelectTopicWithClipboardRegex(), "Select topics with clipboard regex finders", new SelectTopicWithClipboardRegex(false), "---", "Select topics in selected layer", new SelectTopicIfInLayer(), "Select topics not in selected layer", new SelectTopicIfNotInLayer(), "---", "Selection info...", new SelectionInfo(), }; } menuStruct = defaultSelectMenuStructForTopicGrid; } else if(source instanceof TopicTable) { if(defaultSelectMenuStructForTopicTable == null) { defaultSelectMenuStructForTopicTable = new Object[] { "Select all", new SelectAll(), "Select row(s)", new SelectRows(), "Select column(s)", new SelectColumns(), "Invert selection", new InvertSelection(), "Deselect", new ClearSelection(), "---", "Select topics without associations", new SelectTopicIfNoAssociations(), "Select topics without occurrences", new SelectTopicIfNoOccurrences(), "Select topics without base names", new SelectTopicIfNoBasenames(), "Select topics without classes", new SelectTopicIfNoClasses(), "Select topics without instances", new SelectTopicIfNoInstances(), "Select topics without A+I", new SelectTopicIfNoAI(), "---", "Select topics with subject locator", new SelectTopicIfSL(), "Select topics with typed associations", new SelectTopicWithAssociationType(), "---", "Select topics with clipboard identifiers", new SelectTopicWithClipboard(), "Select topics with clipboard regexes", new SelectTopicWithClipboardRegex(), "Select topics with clipboard regex finders", new SelectTopicWithClipboardRegex(false), "---", "Select topics in selected layer", new SelectTopicIfInLayer(), "Select topics not in selected layer", new SelectTopicIfNotInLayer(), "---", "Selection info...", new SelectionInfo(), }; } menuStruct = defaultSelectMenuStructForTopicTable; } else { if(defaultSelectMenuStruct == null) { defaultSelectMenuStruct = new Object[] { "Select all", new SelectAll(), "Invert selection", new InvertSelection(), "Deselect", new ClearSelection(), "---", "Select topics without associations", new SelectTopicIfNoAssociations(), "Select topics without occurrences", new SelectTopicIfNoOccurrences(), "Select topics without base names", new SelectTopicIfNoBasenames(), "Select topics without classes", new SelectTopicIfNoClasses(), "Select topics without instances", new SelectTopicIfNoInstances(), "Select topics without A+I", new SelectTopicIfNoAI(), "---", "Select topics with subject locator", new SelectTopicIfSL(), "Select topics with typed associations", new SelectTopicWithAssociationType(), "---", "Select topics with clipboard identifiers", new SelectTopicWithClipboard(), "Select topics with clipboard regexes", new SelectTopicWithClipboardRegex(), "Select topics with clipboard regex finders", new SelectTopicWithClipboardRegex(false), "---", "Select topics in selected layer", new SelectTopicIfInLayer(), "Select topics not in selected layer", new SelectTopicIfNotInLayer(), "---", "Selection info...", new SelectionInfo(), }; } menuStruct = defaultSelectMenuStruct; } } catch(Exception e) { if(admin != null) admin.handleError(e); else e.printStackTrace(); } return menuStruct; } private static Object[] defaultCopyAlsoMenuStruct = null; public static Object[] getDefaultCopyAlsoMenuStruct(Wandora admin, Object source) { if(defaultCopyAlsoMenuStruct == null) { try { defaultCopyAlsoMenuStruct = new Object[] { "Copy also names", new CopyTopics(CopyTopics.INCLUDE_NAMES), "Copy also subject locator", new CopyTopics(CopyTopics.INCLUDE_SLS), "Copy also subject identifiers", new CopyTopics(CopyTopics.INCLUDE_SIS), "Copy also classes", new CopyTopics(CopyTopics.INCLUDE_CLASSES), "Copy also instances", new CopyTopics(CopyTopics.INCLUDE_INSTANCES), "Copy also players...", new CopyTopics(CopyTopics.INCLUDE_PLAYERS), "Copy also played roles", new CopyTopics(CopyTopics.INCLUDE_PLAYED_ROLES), "Copy also occurrences...", new CopyTopics(CopyTopics.INCLUDE_OCCURRENCES), "Copy also all occurrences", new CopyTopics(CopyTopics.INCLUDE_ALL_OCCURRENCES), "Copy also occurrence types", new CopyTopics(CopyTopics.INCLUDE_OCCURRENCE_TYPES), "Copy also association types", new CopyTopics(CopyTopics.INCLUDE_ASSOCIATION_TYPES), "---", "Copy also subject identifier count", new CopyTopics(CopyTopics.INCLUDE_SI_COUNT), "Copy also class count", new CopyTopics(CopyTopics.INCLUDE_CLASS_COUNT), "Copy also instance count", new CopyTopics(CopyTopics.INCLUDE_INSTANCE_COUNT), "Copy also association count", new CopyTopics(CopyTopics.INCLUDE_ASSOCIATION_COUNT), "Copy also typed association count...", new CopyTopics(CopyTopics.INCLUDE_TYPED_ASSOCIATION_COUNT), "Copy also occurrence count", new CopyTopics(CopyTopics.INCLUDE_OCCURRENCE_COUNT), "---", "Copy also topic's layer distribution", new CopyTopics(CopyTopics.INCLUDE_LAYER_DISTRIBUTION), "Copy also topic's clustering coefficient", new CopyTopics(CopyTopics.INCLUDE_CLUSTER_COEFFICIENT), }; } catch(Exception e) { if(admin != null) admin.handleError(e); else e.printStackTrace(); } } return defaultCopyAlsoMenuStruct; } private static Object[] defaultCopyMenuStruct = null; public static Object[] getDefaultCopyMenuStruct(Wandora admin, Object source) { if(defaultCopyMenuStruct == null) { try { defaultCopyMenuStruct = new Object[] { "Copy base name", new CopyTopics(), "Copy subject identifier", new CopyTopics(CopyTopics.COPY_SIS, CopyTopics.INCLUDE_NOTHING), "---", "Copy instances within...", new CopyTopicInstances(), "Copy classes within...", new CopyTopicClasses(), "Copy associations within...", new CopyAssociations(), "Copy roles within...", new CopyTopicRoles(), "Copy players within...", new CopyTopicPlayers(), "Copy association types within...", new CopyTopicAssociationTypes(), "Copy variant names within", new TopicNameCopier(), "---", "Copy as image", new CopyAsImage(), }; } catch(Exception e) { if(admin != null) admin.handleError(e); else e.printStackTrace(); } } return defaultCopyMenuStruct; } private static Object[] defaultCopyToLayerMenuStruct = null; public static Object[] getDefaultCopyToLayerMenuStruct(Wandora wandora, Object source) { if(defaultCopyToLayerMenuStruct == null) { try { defaultCopyToLayerMenuStruct = new Object[] { "Copy to layer as a single subject identifier stub", new CopyTopicsToLayer(CopyTopicsToLayer.COPY_TOPIC_AS_A_SINGLE_SI_STUB), "Copy to layer as a subject identifier stub", new CopyTopicsToLayer(CopyTopicsToLayer.COPY_TOPIC_AS_A_SI_STUB), "---", "Copy to layer as a stub", new CopyTopicsToLayer(CopyTopicsToLayer.COPY_TOPIC_AS_A_STUB), "Copy to layer as a stub with variants", new CopyTopicsToLayer(CopyTopicsToLayer.COPY_TOPIC_AS_A_STUB_WITH_VARIANTS), "Copy to layer as a stub with occurrences", new CopyTopicsToLayer(CopyTopicsToLayer.COPY_TOPIC_AS_A_STUB_WITH_OCCURRENCES), "---", "Copy to layer as a complete topic", new CopyTopicsToLayer(CopyTopicsToLayer.COPY_TOPIC), "Copy to layer as a complete topic with associations", new CopyTopicsToLayer(CopyTopicsToLayer.COPY_TOPIC_WITH_ASSOCIATIONS), "---", "Deep copy to layer...", new CopyTopicsToLayer(CopyTopicsToLayer.COPY_DEEP), }; } catch(Exception e) { if(wandora != null) wandora.handleError(e); else e.printStackTrace(); } } return defaultCopyToLayerMenuStruct; } public static Object[] getDefaultPasteMenuStruct(Wandora admin, Object source) { Object[] menuStruct = null; try { menuStruct = new Object[] { "Paste instances", new PasteInstances(), "Paste classes", new PasteClasses(), "Paste associations", new PasteAssociations(), }; } catch(Exception e) { if(admin != null) admin.handleError(e); else e.printStackTrace(); } return menuStruct; } private static Object[] defaultPasteAlsoMenuStruct = null; public static Object[] getDefaultPasteAlsoMenuStruct(Wandora admin, Object source) { if(defaultPasteAlsoMenuStruct == null) { try { defaultPasteAlsoMenuStruct = new Object[] { "Paste also names...", new PasteTopics(PasteTopics.INCLUDE_NAMES), "Paste also subject locators...", new PasteTopics(PasteTopics.INCLUDE_SLS), "Paste also subject identifiers...", new PasteTopics(PasteTopics.INCLUDE_SIS), "Paste also classes...", new PasteTopics(PasteTopics.INCLUDE_CLASSES), "Paste also instances...", new PasteTopics(PasteTopics.INCLUDE_INSTANCES), "Paste also players...", new PasteTopics(PasteTopics.INCLUDE_PLAYERS), "Paste also occurrences...", new PasteTopics(PasteTopics.INCLUDE_TEXTDATAS), }; } catch(Exception e) { if(admin != null) admin.handleError(e); else e.printStackTrace(); } } return defaultPasteAlsoMenuStruct; } private static Object[] defaultSLMenuStruct = null; public static Object[] getDefaultSLMenuStruct(Wandora admin, Object source) { if(true || defaultSLMenuStruct == null) { //System.out.println("Creating extractor menus for " + source.hashCode()); //System.out.println("SLExtractor menu number " + SLExtractorMenus.size()); JMenu extractMenu = (JMenu) SLExtractorMenus.get(source); if(source == null || extractMenu == null) { extractMenu = new SimpleMenu("Extract with subject locator"); //refreshExtractWithSLMenu(extractMenu, null, admin); refreshExtractWithSLMenu(extractMenu, null, admin); SLExtractorMenus.put(source, extractMenu); } try { defaultSLMenuStruct = new Object[] { "Open subject locator...", new OpenSubjectLocator(), "Check subject locator...", new CheckSubjectLocator(), "---", "Make subject locator from a filename...", new MakeSubjectLocatorFromFilename(), "Make subject locator from file content...", new MakeSubjectLocatorFromFileContent(), "Make subject locator from a subject identifier...", new MakeSubjectLocatorFromSubjectIdentifier(), "Make subject locator from a base name...", new MakeSubjectLocatorFromBasename(), "Make subject locator from an occurrence...", new MakeSubjectLocatorFromOccurrence(), "---", // "Find SLs...", new FindSubjectLocator(), // "Find SLs with base names...", new FindSubjectLocatorWithBasename(), // "---", "Modify subject locator with a regex...", new ModifySubjectLocatorWithRegex(), "Remove subject locator...", new DeleteSubjectLocator(), "---", "Download subject locator...", new DownloadSubjectLocators(), "Download and change subject locator...", new DownloadSubjectLocators(true), "Convert to data url", new ConvertSubjectLocatorToDataURL(), "Upload subject locator resource to Mediawiki", new MediawikiSubjectLocatorUploader(new ApplicationContext()), "---", extractMenu, }; } catch(Exception e) { if(admin != null) admin.handleError(e); else e.printStackTrace(); } } return defaultSLMenuStruct; } private static Object[] defaultSIMenuStruct = null; public static Object[] getDefaultSIMenuStruct(Wandora admin, Object source) { if(defaultSIMenuStruct == null) { try { defaultSIMenuStruct = new Object[] { "Open subject identifier...", new OpenSubjectIdentifier(), "Check subject identifiers...", new CheckSubjectIdentifiers(), "---", "Make subject identifier from a file", new MakeSubjectIdentifierFromFilename(), "Make subject identifier from a subject locator", new MakeSubjectIdentifierFromSubjectLocator(), "Make subject identifier from a base name...", new MakeSubjectIdentifierFromBasename(), "Make subject identifier from an occurrence...", new MakeSubjectIdentifierFromOccurrence(), "---", "Copy subject identifiers", new CopySubjectIdentifiers(), "Paste subject identifiers", new PasteSubjectIdentifiers(), "Duplicate subject identifiers...", new DuplicateSubjectIdentifier(), "---", "Remove subject identifiers with a regex...", new DeleteSubjectIdentifiersWithRegex(), "Remove reference-parts in subject identifiers...", new RemoveReferencesInSubjectIdentifiers(), "Modify subject identifiers with a regex...", new ModifySubjectIdentifiersWithRegex(), // "Fix SIs", new SIFixer(), "Fix subject identifiers...", new FixSubjectIdentifiers2(), "Flatten identity...", new FlattenSubjectIdentifiers(), "Expand identity", new Object[] { "Expand with sameAs.org", new SameAsSubjectExpander(), "Expand with sameAs.org store", new Object[] { "Expand with 270a store", new SameAs270aStoreSubjectExpander(), "Expand with British Library store", new SameAsBritishLibraryStoreSubjectExpander(), "Expand with Data Southampton store", new SameAsDataSouthamptonStoreSubjectExpander(), "Expand with Disaster 20 store", new SameAsDisaster20StoreSubjectExpander(), "Expand with Email store", new SameAsEmailStoreSubjectExpander(), "Expand with Freebase store", new SameAsFreebaseStoreSubjectExpander(), "Expand with Kelle store", new SameAsKelleStoreSubjectExpander(), "Expand with LATC store", new SameAsLATCStoreSubjectExpander(), "Expand with Libris store", new SameAsLibrisStoreSubjectExpander(), "Expand with MusicNet store", new SameAsMusicNetStoreSubjectExpander(), "Expand with NoTube store", new SameAsNoTubeStoreSubjectExpander(), "Expand with Ordnance Survey store", new SameAsOrdnanceSurveyStoreSubjectExpander(), "Expand with Pleiades store", new SameAsPleiadesStoreSubjectExpander(), "Expand with Schema.org store", new SameAsSchemaOrgStoreSubjectExpander(), "Expand with Torver Data store", new SameAsTorverDataStoreSubjectExpander(), "Expand with VIAF store", new SameAsVIAFStoreSubjectExpander(), "Expand with Web Index store", new SameAsWebIndexStoreSubjectExpander(), }, "Expand with sameAs anywhere", new SameAsAnywhereSubjectExpander(), }, }; } catch(Exception e) { if(admin != null) admin.handleError(e); else e.printStackTrace(); } } return defaultSIMenuStruct; } private static Object[] defaultBasenameMenuStruct = null; public static Object[] getDefaultBasenameMenuStruct(Wandora admin, Object source) { if(defaultBasenameMenuStruct == null) { try { defaultBasenameMenuStruct = new Object[] { "Make base name from a subject identifier", new MakeBasenameFromSubjectIdentifier(), "Make base name from an occurrence...", new MakeBasenameFromOccurrence(), "---", "Modify base names with a regex...", new BasenameRegexReplacer(), "Remove new line characters", new BasenameNewlineRemover(), "Collapse white spaces", new BasenameWhiteSpaceCollapser(), "Trim base names", new BasenameTrimmer(), "---", "Remove base names...", new BasenameRemover(), }; } catch(Exception e) { if(admin != null) admin.handleError(e); else e.printStackTrace(); } } return defaultBasenameMenuStruct; } private static Object[] defaultVariantNameMenu = null; public static Object[] getDefaultVariantNameMenuStruct(Wandora admin, Object source) { if(defaultVariantNameMenu == null) { try { defaultVariantNameMenu = new Object[] { "Add variant name...", new AddVariantName(), "---", "Make display variants from occurrences", new MakeDisplayVariantsFromOccurrences(), "Make display variants from base names...", new MakeDisplayVariantsFromBasename(), "Make sort variants from base names...", new MakeSortVariantsFromBasename(), "---", "Copy all variant names to clipboard", new TopicNameCopier(), "---", "Copy variant names to other scope...", new VariantScopeCopier(), "Move variant names to other scope...", new VariantScopeCopier(true), "---", "Modify variant names with a regex...", new VariantRegexReplacer(), "Remove new line characters", new VariantNewlineRemover(), "Collapse white spaces", new VariantWhiteSpaceCollapser(), "---", "Add missing display scope", new AddImplicitDisplayScopeToVariants(), "Add missing sort scope", new AddImplicitSortScopeToVariants(), "Add missing language...", new AddMissingLanguageScope(), "---", "Remove variant names...", new VariantRemover(), "Remove all empty variant names...", new AllEmptyVariantRemover(), "Remove all variant names...", new AllVariantRemover(), "---", "Transform variants to topics...", new VariantsToTopicsAndAssociations(), }; } catch(Exception e) { if(admin != null) admin.handleError(e); else e.printStackTrace(); } } return defaultVariantNameMenu; } private static Object[] defaultAssociationMenuStruct = null; public static Object[] getDefaultAssociationMenuStruct(Wandora admin, Object source) { if(defaultAssociationMenuStruct == null) { try { defaultAssociationMenuStruct = new Object[] { "Add association...", new AddSchemalessAssociation(), "---", "Make superclass of current topic", new MakeSuperclassOf(), "Make subclass of current topic", new MakeSubclassOf(), "Make class-instances with associations", new MakeInstancesWithAssociations(), "Make associations with class-instances", new MakeAssociationWithClassInstance(), "---", "Make associations from occurrences...", new MakeAssociationWithOccurrence(), "Find associations in occurrences...", new FindAssociationsInOccurrence(), // "---", // "Collect binary associations to n-ary association...", new CollectBinaryToNary(), // "Steal associations...", new StealAssociations(), "---", "Delete associations with type...",new DeleteAssociationsInTopicWithType(), "Delete empty and unary associations...", new DeleteUnaryAssociations(), "Delete all associations...",new DeleteAssociationsInTopic(), }; } catch(Exception e) { if(admin != null) admin.handleError(e); else e.printStackTrace(); } } return defaultAssociationMenuStruct; } private static Object[] defaultOccurrenceMenuStruct = null; public static Object[] getDefaultOccurrenceMenuStruct(Wandora admin, Object source) { if(defaultOccurrenceMenuStruct == null) { try { defaultOccurrenceMenuStruct = new Object[] { "Make occurrences from subject locators...", new MakeOccurrenceFromSubjectLocator(), "Make occurrences from subject identifiers...", new MakeOccurrenceFromSubjectIdentifier(), "Make occurrences from base names...", new MakeOccurrenceFromBasename(), "Make occurrences from variant names...", new MakeOccurrenceFromVariant(), "Make occurrences from all variant names...", new MakeOccurrencesFromVariants(), "Make occurrences from associations...", new MakeOccurrenceFromAssociation(), "---", "Modify occurrences with a regex...", new OccurrenceRegexReplacerOne(), "Modify all occurrences with a regex...", new OccurrenceRegexReplacerAll(), "---", "Copy occurrence to all other scopes...", new SpreadOccurrence(), "Copy occurrences to other scope...", new OccurrenceScopeCopier(), "Move occurrences to other scope...", new OccurrenceScopeCopier(true), "---", "Refine occurrences", new Object[] { "With GATE Annie...", new AnnieOccurrenceExtractor(), UIBox.getIcon("gui/icons/extract_gate.png"), "With Stanford NER...", new StanfordNEROccurrenceExtractor(), UIBox.getIcon("gui/icons/extract_stanford_ner.png"), "---", "With uClassify sentiment classifier...", new UClassifyOccurrenceExtractor("Sentiment", "uClassify", 0.001), UIBox.getIcon("gui/icons/extract_uclassify.png"), "With uClassify text language classifier...", new UClassifyOccurrenceExtractor("Text Language", "uClassify", 0.001), UIBox.getIcon("gui/icons/extract_uclassify.png"), "With uClassify topics classifier...", new UClassifyOccurrenceExtractor("Topics", "uClassify", 0.001), UIBox.getIcon("gui/icons/extract_uclassify.png"), "With uClassify mood classifier...", new UClassifyOccurrenceExtractor("Mood", "prfekt", 0.001), UIBox.getIcon("gui/icons/extract_uclassify.png"), "With uClassify news classifier...", new UClassifyOccurrenceExtractor("News Classifier", "mvazquez", 0.001), UIBox.getIcon("gui/icons/extract_uclassify.png"), "---", "With GeoNames near by extractor...", new FindNearByGeoNamesOccurrence(), UIBox.getIcon("gui/icons/extract_geonames.png"), "---", "Find associations in occurrences....", new FindAssociationsInOccurrenceSimple(), "Find associations in occurrences using a pattern....", new FindAssociationsInOccurrence(), // "---", // "Associate points in polygons occurrence carriers...", new FindPointInPolygonOccurrence(), // "Associate nearby point occurrence carriers...", new AssociateNearByOccurrenceCarriers(), }, "---", "Check URL occurrences...", new URLOccurrenceChecker(), "Download URL occurrences...", new DownloadOccurrence(), "Download all URL occurrences...", new DownloadAllOccurrences(), "---", "Upload to Pastebin...", new PasteBinOccurrenceUploader(), "Download from Pastebin", new PasteBinOccurrenceDownloader(), "---", "Upload URL resource to MediaWiki", new MediawikiOccurrenceUploader(), "Upload content to MediaWiki...", new MediaWikiAPIUploader(), "---", "Delete occurrences with type...", new DeleteOccurrence(), "Delete all occurrences...", new DeleteFromTopics(DeleteFromTopics.DELETE_TEXTDATAS), }; } catch(Exception e) { if(admin != null) admin.handleError(e); else e.printStackTrace(); } } return defaultOccurrenceMenuStruct; } public static Object[] getDefaultTopicMenuStruct(Wandora admin, Object source) { /* Notice: topicMenuStruct can NOT be cached as source parameter is used * to build the structure!!! */ Object[] topicMenuStruct = null; try { topicMenuStruct = new Object[] { "New topic...", new NewTopicExtended(), "Duplicate topics...", new DuplicateTopics(), "Merge topics...", new MergeTopics(), "Split topics", new Object[] { "Split topic with subject identifiers", new SplitTopics(), "Split topic with a base name regex...", new SplitTopicsWithBasename(), "---", "Split to descending instances with a base name regex...", new SplitToInstancesWithBasename(true), "Split to ascending instances with a base name regex...", new SplitToInstancesWithBasename(false), "---", "Split to descending superclasses with a base name regex...", new SplitToSuperclassesWithBasename(true), "Split to ascending superclasses with a base name regex...", new SplitToSuperclassesWithBasename(false), }, "Delete topics", getDefaultDeleteTopicMenuStruct(admin, source), "---", "Add to topic", getDefaultAddToTopicMenuStruct(admin, source), "Delete from topics", getDefaultDeleteFromTopicMenuStruct(admin, source), "---", "Copy", getDefaultCopyMenuStruct(admin, source), "Copy also", getDefaultCopyAlsoMenuStruct(admin, source), "Copy to layer", getDefaultCopyToLayerMenuStruct(admin, source), "Paste", getDefaultPasteMenuStruct(admin, source), "Paste also", getDefaultPasteAlsoMenuStruct(admin, source), "Export", new Object[] { "Export selection as topic map...", new ExportTopicMap(true), UIBox.getIcon("gui/icons/export_topicmap.png"), "Export selection to Maiana...", new MaianaExport(true), UIBox.getIcon("gui/icons/export_maiana.png"), "Export selection as RDF N3...", new RDFExport(true), UIBox.getIcon("gui/icons/export_rdf.png"), "---", "Export selection as DOT graph...", new DOTExport(true), UIBox.getIcon("gui/icons/export_graph.png"), "Export selection as GML graph...", new GMLExport(true), UIBox.getIcon("gui/icons/export_graph.png"), "Export selection as GraphML graph...", new GraphMLExport(true), UIBox.getIcon("gui/icons/export_graph.png"), "Export selection as GraphXML graph...", new GraphXMLExport(true), UIBox.getIcon("gui/icons/export_graph.png"), "Export selection as GXL graph...", new GXLExport(true), UIBox.getIcon("gui/icons/export_graph.png"), "Export selection as Gephi graph...", new GephiExport(true), UIBox.getIcon("gui/icons/export_graph.png"), "---", "Export selection as adjacency matrix...", new AdjacencyMatrixExport(true), UIBox.getIcon("gui/icons/export_adjacency_matrix.png"), "Export selection as similarity matrix...", new SimilarityMatrixExport(true), UIBox.getIcon("gui/icons/export_similarity_matrix.png"), "Export selection as incidence matrix...", new IncidenceMatrixExport(true), UIBox.getIcon("gui/icons/export_incidence_matrix.png"), "---", "Export selection as a HTML page collection...", new ExportSite(true), UIBox.getIcon("gui/icons/export_site.png"), }, "---", "Subject locators", getDefaultSLMenuStruct(admin, source), "Subject identifiers", getDefaultSIMenuStruct(admin, source), "Base names", getDefaultBasenameMenuStruct(admin, source), "Variant names", getDefaultVariantNameMenuStruct(admin, source), "Associations", getDefaultAssociationMenuStruct(admin, source), "Occurrences", getDefaultOccurrenceMenuStruct(admin, source), "---", "Statistics", new Object[] { "Asset weights...", UIBox.getIcon("gui/icons/asset_weight.png"), new AssetWeights(), }, }; } catch(Exception e) { if(admin != null) admin.handleError(e); else e.printStackTrace(); } return topicMenuStruct; } public static void refreshExtractWithSLMenu(JMenu m, Context proposedContext, Wandora admin) { m.removeAll(); UIBox.attachMenu(m, getSubjectLocatorExtractorMenu(admin, proposedContext), admin); } public static Object[] getSubjectLocatorExtractorMenu(Wandora admin) { return getSubjectLocatorExtractorMenu(admin, null); } public static Object[] getSubjectLocatorExtractorMenu(Wandora admin, Context proposedContext) { return getSubjectLocatorExtractorMenu(admin, proposedContext, admin.toolManager.getToolSet("extract")); } public static Object[] getSubjectLocatorExtractorMenu(Wandora admin, Context proposedContext, WandoraToolSet extractTools) { final Context context = proposedContext; if(extractTools == null) { return new Object[] {}; } else { return extractTools.getAsObjectArray( extractTools.new ToolFilter() { @Override public boolean acceptTool(WandoraTool tool) { return (tool instanceof AbstractExtractor); } @Override public WandoraTool polishTool(WandoraTool tool) { ExtractWithSubjectLocator wrapper = null; if(context != null) { wrapper = new ExtractWithSubjectLocator((AbstractExtractor) tool, context); } else { wrapper = new ExtractWithSubjectLocator((AbstractExtractor) tool); } return wrapper; } @Override public Object[] addAfterTool(WandoraTool tool) { return new Object[] { tool.getIcon() }; } } ); } } // ------------------------------------------------------------------------- private static Object[] associationsPopupStruct = null; public static Object[] getAssociationsPopupStruct() { if(associationsPopupStruct == null) { associationsPopupStruct = new Object[] { "---", "Copy associations", new Object[] { "Copy associations as Wandora layout tab text", new CopyAssociations(), "Copy associations as Wandora layout HTML", new CopyAssociations(CopyAssociations.HTML_OUTPUT), "---", "Copy associations as LTM layout tab text", new CopyAssociations(CopyAssociations.TABTEXT_OUTPUT, CopyAssociations.LTM_LAYOUT), "Copy associations as LTM layout HTML", new CopyAssociations(CopyAssociations.HTML_OUTPUT, CopyAssociations.LTM_LAYOUT), }, // "Add associations...", new AddAssociations(new ApplicationContext()), "Edit association...", new ModifySchemalessAssociation(), "Delete associations...", new DeleteAssociations(), // "Duplicate associations...", "---", "Change association type...", new ChangeAssociationType(), "Change association role...", new ChangeAssociationRole(), // "Change association roles...", new ChangeAssociationRoles(), "Insert player to associations...", new InsertPlayer(), "Delete players in associations...", new RemovePlayer(), "Merge players in associations...", new MergePlayers(), "---", "Swap players within associations", new SwapPlayers(), "Create symmetric associations", new CreateSymmetricAssociation(), "Delete symmetric associations", new DeleteSymmetricAssociation(), "---", "Collect to n-ary association...", new CollectNary(), // "Collect binary to n-ary", new CollectBinaryToNary(), "Split n-ary to binary associations...", new SplitToBinaryAssociations(), "Transpose associations...", new TransposeAssociations(), "---", "Open edge of associations", new OpenEdgeTopic(), "Copy path to the edge of associations", new CopyEdgePath(), "Detect cycle...", new DetectCycles(), "---", "SOM classifier...", new SOMClassifier(new AssociationContext()), /* "---", "Cut associations", new Object[] { "Copy all associations as tab text", new CopyAssociations(), "Copy all associations as HTML", new CopyAssociations(CopyAssociations.HTML_OUTPUT), }, **/ }; } return associationsPopupStruct; } // ------------------------------------------------------------------------- private static Object[] layerTreeMenuStructure = null; public static Object[] getLayerTreeMenu() { if(layerTreeMenuStructure == null) { layerTreeMenuStructure = new Object[] { "New layer...", new NewLayer(), "---", //"Rename layer...", new RenameLayer(), "Configure layer...", new ConfigureLayer(), "Delete layer...", new DeleteLayer(), "Clear layer topic map...", new ClearTopicMap(), "Clear topic map indexes...", new ClearTopicMapIndexes(), "---", "Make association consistent...",new MakeAssociationConsistentTool(), "___TOPICMAPMENU___", // topic map implementation specific menu gets inserted here, this item must be on top level in the menu "---", "Merge layers", new Object[] { "Merge up...", new MergeLayers(MergeLayers.MERGE_UP), "Merge down...", new MergeLayers(MergeLayers.MERGE_DOWN), "Merge all...", new MergeLayers(MergeLayers.MERGE_ALL), "Merge visible...", new MergeLayers(MergeLayers.MERGE_VISIBLE), }, "___IMPORTMENU___", "___GENERATEMENU___", "___EXPORTMENU___", "---", "Arrange", new Object[] { "Move up", new ArrangeLayers(LayerTree.MOVE_LAYER_UP), "Move down", new ArrangeLayers(LayerTree.MOVE_LAYER_DOWN), "Move top", new ArrangeLayers(LayerTree.MOVE_LAYER_TOP), "Move bottom", new ArrangeLayers(LayerTree.MOVE_LAYER_BOTTOM), "---", "Reverse order", new ArrangeLayers(LayerTree.REVERSE_LAYERS), }, "View",new Object[] { "View all", new ViewLayers(ViewLayers.VIEW_ALL), "Hide all", new ViewLayers(ViewLayers.HIDE_ALL), "Hide all but current", new ViewLayers(ViewLayers.HIDE_ALL_BUT_CURRENT), "Reverse visibility", new ViewLayers(ViewLayers.REVERSE_VISIBILITY), }, "Lock",new Object[] { "Lock all", new LockLayers(LockLayers.LOCK_ALL), "Unlock all", new LockLayers(LockLayers.UNLOCK_ALL), "Lock all but current", new LockLayers(LockLayers.LOCK_ALL_BUT_CURRENT), "Reverse locks", new LockLayers(LockLayers.REVERSE_LOCKS), }, "---", "Topics", new Object[] { "Delete topics",new Object[] { "Delete topics without A+C+I...", new DeleteTopicsWithoutACI(), "Delete topics without A+I...", new DeleteTopicsWithoutAI(), "Delete topics without associations...", new DeleteTopicsWithoutAssociations(), "Delete topics without classes...", new DeleteTopicsWithoutClasses(), "Delete topics without instances...", new DeleteTopicsWithoutInstances(), "Delete topics without base names...", new DeleteTopicsWithoutBasename(), "Delete topics without occurrences...", new DeleteTopicsWithoutOccurrences(), "---", "Delete topics with SI regex...", new DeleteTopicsWithSIRegex(), "Delete topics with base name regex...", new DeleteTopicsWithBasenameRegex(), }, "---", "Subject locators", new Object[] { "Make subject locator from a subject identifier...", new MakeSubjectLocatorFromSubjectIdentifier(), "Make subject locator from a base name...", new MakeSubjectLocatorFromBasename(), "Make subject locator from an occurrence...", new MakeSubjectLocatorFromOccurrence(), "---", "Check subject locators...", new CheckSubjectLocator(), "---", "Modify subject locators with a regex...", new ModifySubjectLocatorWithRegex(), "Remove subject locators...", new DeleteSubjectLocator(), "---", "Download subject locators...", new DownloadSubjectLocators(), "Download and change subject locators...", new DownloadSubjectLocators(true), "Convert to data url", new ConvertSubjectLocatorToDataURL(), // "---", // "Find SLs...", new FindSubjectLocator(), // "Find SLs with base names...", new FindSubjectLocatorWithBasename(), "Upload subject locator resources to Mediawiki", new MediawikiSubjectLocatorUploader(), }, "Subject identifiers", new Object[] { "Make subject identifier from a subject locator", new MakeSubjectIdentifierFromSubjectLocator(), "Make subject identifier from a base name...", new MakeSubjectIdentifierFromBasename(), "Make subject identifier from an occurrence...", new MakeSubjectIdentifierFromOccurrence(), "---", "Check subject identifiers...", new CheckSubjectIdentifiers(), "Modify subject identifiers with a regex...", new ModifySubjectIdentifiersWithRegex(), // "Fix SIs", new SIFixer(), "Fix subject identifiers", new FixSubjectIdentifiers2(), "Remove references in subject identifiers...", new RemoveReferencesInSubjectIdentifiers(), "---", "Flatten indentity...", new FlattenSubjectIdentifiers(), "Remove subject identifiers with a regex...", new DeleteSubjectIdentifiersWithRegex(), }, "Base names", new Object[] { "Make base name from a subject identifier", new MakeBasenameFromSubjectIdentifier(), "Make base name from an occurrence...", new MakeBasenameFromOccurrence(), "---", "Modify base names with a regex...", new BasenameRegexReplacer(), "Remove new line characters", new BasenameNewlineRemover(), "Collapse white spaces", new BasenameWhiteSpaceCollapser(), "Trim base names", new BasenameTrimmer(), "---", "Remove base names...", new BasenameRemover(), }, "Variant names", new Object[] { "Add variant name...", new AddVariantName(), "---", "Make display variants from occurrences", new MakeDisplayVariantsFromOccurrences(), "Make display variants from base names...", new MakeDisplayVariantsFromBasename(), "Make sort variants from base names", new MakeSortVariantsFromBasename(), "---", "Modify variant names with a regex...", new VariantRegexReplacer(), "Remove new line characters", new VariantNewlineRemover(), "---", "Copy variant names to other scope...", new VariantScopeCopier(), "Move variant names to other scope...", new VariantScopeCopier(true), "---", "Remove variant name...", new VariantRemover(), "Remove all empty variant names...", new AllEmptyVariantRemover(), "Remove all variant names...", new AllVariantRemover(), "---", "Add missing display scope to variant names", new AddImplicitDisplayScopeToVariants(), "Add missing sort scope to variant names", new AddImplicitSortScopeToVariants(), "Add missing language to variant names...", new AddMissingLanguageScope(), "---", "Transform variant names to topics...", new VariantsToTopicsAndAssociations(), }, "Associations", new Object[] { "Make associations from occurrences...", new MakeAssociationWithOccurrence(), "Find associations in occurrences...", new FindAssociationsInOccurrence(), "---", "Delete associations with type...",new DeleteAssociationsInTopicWithType(), "Delete empty and unary associations...", new DeleteUnaryAssociations(), "Delete all associations...",new DeleteAssociationsInTopic(new LayeredTopicContext()), }, "Occurrences", new Object[] { "Delete occurrences with a type...", new DeleteOccurrence(), "Delete all occurrences...", new DeleteFromTopics(DeleteFromTopics.DELETE_TEXTDATAS), "---", "Modify occurrences with a regex...", new OccurrenceRegexReplacerAll(), "---", "Copy occurrences to other scope...", new OccurrenceScopeCopier(), "Move occurrences to other scope...", new OccurrenceScopeCopier(true), "---", "Check URL occurrences...", new URLOccurrenceChecker(), "Download URL occurrences...", new DownloadOccurrence(), "Download all URL occurrences...", new DownloadAllOccurrences(), "---", "Upload occurrences to Pastebin...", new PasteBinOccurrenceUploader(), "Download occurrences from Pastebin", new PasteBinOccurrenceDownloader(), "---", "Upload occurrences to Mediawiki...", new MediawikiOccurrenceUploader(), "Upload content to MediaWiki...", new MediaWikiAPIUploader() } }, "---", "Statistics", new Object[] { "Layer info...", UIBox.getIcon("gui/icons/layer_info.png"), new TopicMapStatistics(), "Layer connection statistics...", UIBox.getIcon("gui/icons/layer_acount.png"), new AssociationCounterTool(), "Asset weights...", UIBox.getIcon("gui/icons/asset_weight.png"), new AssetWeights(AssetWeights.CONTEXT_IS_TOPICMAP), "Topic map diameter...", UIBox.getIcon("gui/icons/topicmap_diameter.png"), new TopicMapDiameter(), "Average clustering coefficient...", UIBox.getIcon("gui/icons/clustering_coefficient.png"), new AverageClusteringCoefficient(), "---", "Occurrence summary report...", UIBox.getIcon("gui/icons/summary_report.png"), new OccurrenceSummaryReport(), } // "---", // "Debug tool",new TestTool(), }; } return layerTreeMenuStructure; } public static Object[] getSimpleLayerTreeMenu() { Object[] simpleMenuStructure = new Object[] { "New layer...", new NewLayer(), }; return simpleMenuStructure; } private static Object[] logoMenuStructure = null; public static Object[] getLogoMenu() { if(logoMenuStructure == null) { logoMenuStructure = new Object[] { "Wandora home", UIBox.getIcon("gui/icons/open_browser.png"), KeyStroke.getKeyStroke(VK_H, DEF_MASK), new ExecBrowser("http://www.wandora.org"), "---", "Documentation", UIBox.getIcon("gui/icons/open_browser.png"), new ExecBrowser("http://wandora.org/wiki/Documentation"), "Discussion forum", UIBox.getIcon("gui/icons/open_browser.png"), new ExecBrowser("http://wandora.org/forum/"), "WandoraTV", UIBox.getIcon("gui/icons/open_browser.png"), new ExecBrowser("http://wandora.org/tv/"), "---", "About Wandora...", UIBox.getIcon("gui/icons/info.png"),new AboutWandora(), "Wandora credits...", UIBox.getIcon("gui/icons/info.png"),new AboutCredits(), }; } return logoMenuStructure; } public static Object[] getOccurrenceTableMenu(OccurrenceTable ot, Options options) { String viewType = OccurrenceTable.VIEW_SCHEMA; int rowHeight = 0; try { if(options != null) { viewType = options.get(OccurrenceTable.VIEW_OPTIONS_KEY, OccurrenceTable.VIEW_SCHEMA); rowHeight = options.getInt(OccurrenceTable.ROW_HEIGHT_OPTIONS_KEY, rowHeight); } } catch(Exception e) {} return new Object[] { "Cut occurrence", new CutOccurrence(), "Copy occurrence", new CopyOccurrence(), "Paste occurrence", new PasteOccurrence(), "---", "Append occurrence", new AppendOccurrence(), "Spread occurrence", new SpreadOccurrence(), "---", "Duplicate occurrence...", new DuplicateOccurrence(), "Change type of the occurrence...", new ChangeOccurrenceType(), "Delete occurrence...", new DeleteOccurrence(), "---", "Open URL occurrence...", new OpenURLOccurrence(), "Download URL to the occurrence", new DownloadOccurrence(DownloadOccurrence.TARGET_OCCURRENCE), "Save URL to a file...", new DownloadOccurrence(DownloadOccurrence.TARGET_FILE), "---", "Upload occurrence to Pastebin...", new PasteBinOccurrenceUploader(), "Download occurrence from Pastebin", new PasteBinOccurrenceDownloader(), "---", "Upload URL occurrence resource to Mediawiki...", new MediawikiOccurrenceUploader(), "Upload content to MediaWiki...", new MediaWikiAPIUploader(), "---", "Run occurrence", new Object[] { "Run as Query", new RunOccurrenceAsQuery() }, "---", "View", new Object[] { "View schema scopes", new ChangeOccurrenceView(OccurrenceTable.VIEW_SCHEMA, options), (OccurrenceTable.VIEW_SCHEMA.equals(viewType) ? UIBox.getIcon("gui/icons/checkbox_selected.png") : UIBox.getIcon("gui/icons/checkbox.png")), "View used scopes", new ChangeOccurrenceView(OccurrenceTable.VIEW_USED, options), (OccurrenceTable.VIEW_USED.equals(viewType) ? UIBox.getIcon("gui/icons/checkbox_selected.png") : UIBox.getIcon("gui/icons/checkbox.png")), "View schema and used scopes", new ChangeOccurrenceView(OccurrenceTable.VIEW_USED_AND_SCHEMA, options), (OccurrenceTable.VIEW_USED_AND_SCHEMA.equals(viewType) ? UIBox.getIcon("gui/icons/checkbox_selected.png") : UIBox.getIcon("gui/icons/checkbox.png")), "---", "Auto row height", new ChangeOccurrenceTableRowHeight(0, options), (rowHeight == 0 ? UIBox.getIcon("gui/icons/checkbox_selected.png") : UIBox.getIcon("gui/icons/checkbox.png")), "View single row", new ChangeOccurrenceTableRowHeight(1, options), (rowHeight == 1 ? UIBox.getIcon("gui/icons/checkbox_selected.png") : UIBox.getIcon("gui/icons/checkbox.png")), "View 5 rows", new ChangeOccurrenceTableRowHeight(5, options), (rowHeight == 5 ? UIBox.getIcon("gui/icons/checkbox_selected.png") : UIBox.getIcon("gui/icons/checkbox.png")), "View 10 rows", new ChangeOccurrenceTableRowHeight(10, options), (rowHeight == 10 ? UIBox.getIcon("gui/icons/checkbox_selected.png") : UIBox.getIcon("gui/icons/checkbox.png")), "View 20 rows", new ChangeOccurrenceTableRowHeight(20, options), (rowHeight == 20 ? UIBox.getIcon("gui/icons/checkbox_selected.png") : UIBox.getIcon("gui/icons/checkbox.png")), }, }; } public static Object[] getOccurrenceTypeLabelPopupStruct(Topic occurrenceType, Topic topic) { return new Object[] { "Open topic", new OpenTopic(), // "Open topic in", getOpenInMenu(), "---", "Edit occurrences", new EditOccurrences(occurrenceType, topic), "Duplicate occurrences...", new DuplicateOccurrence(occurrenceType, topic), "Change occurrence type...", new ChangeOccurrenceType(occurrenceType, topic), "Delete occurrences...", new DeleteOccurrence(occurrenceType, topic), }; } public static Object[] getTreeMenu(Wandora wandora, TopicTree tree) { return new Object[] { "Open topic", new OpenTopic(), "Open topic in", getOpenInMenu(), "---", "New topic...", new NewTopicExtended(), "Delete topic...", new DeleteTopics(), "Duplicate topic...", new DuplicateTopics(), "Split topic", new Object[] { "Split topic with subject identifiers", new SplitTopics(), "Split topic with a base name regex...", new SplitTopicsWithBasename(), "---", "Split to descending instances with a base name regex...", new SplitToInstancesWithBasename(true), "Split to ascending instances with a base name regex...", new SplitToInstancesWithBasename(false), "---", "Split to descending superclasses with a base name regex...", new SplitToSuperclassesWithBasename(true), "Split to ascending superclasses with a base name regex...", new SplitToSuperclassesWithBasename(false), }, "---", "Add to topic", getDefaultAddToTopicMenuStruct(wandora, tree), "Delete from topic", getDefaultDeleteFromTopicMenuStruct(wandora, tree), "---", "Copy", getDefaultCopyMenuStruct(wandora, tree), "Copy also", getDefaultCopyAlsoMenuStruct(wandora, tree), "Copy to layer", getDefaultCopyToLayerMenuStruct(wandora, tree), "Paste", getDefaultPasteMenuStruct(wandora, tree), "Paste also", getDefaultPasteAlsoMenuStruct(wandora, tree), "Export", new Object[] { "Export selection as topic map...", new ExportTopicMap(true), "Export selection as RDF N3...", new RDFExport(true), "---", "Export selection as GML graph...", new GMLExport(true), "Export selection as GraphML graph...", new GraphMLExport(true), "Export selection as GraphXML graph...", new GraphXMLExport(true), "Export selection as GXL graph...", new GXLExport(true), "---", "Export selection as adjacency matrix...", new AdjacencyMatrixExport(true), "Export selection as incidence matrix...", new IncidenceMatrixExport(true), "---", "Export selection as a HTML page collection...", new ExportSite(true), }, "---", "Subject locator", getDefaultSLMenuStruct(wandora, tree), "Subject identifiers", getDefaultSIMenuStruct(wandora, tree), "Base name", getDefaultBasenameMenuStruct(wandora, tree), "Variant names", getDefaultVariantNameMenuStruct(wandora, tree), "Associations", getDefaultAssociationMenuStruct(wandora, tree), "Occurrences", getDefaultOccurrenceMenuStruct(wandora, tree), "---", "Refresh tree", new RefreshTopicTrees(), }; } public static Object[] getOpenInMenu() { Wandora wandora = Wandora.getWandora(); List<Object> struct = new ArrayList<>(); if(wandora != null) { Map<Dockable,TopicPanel> dockedTopicPanels = wandora.topicPanelManager.getDockedTopicPanels(); if(dockedTopicPanels != null && !dockedTopicPanels.isEmpty()) { for(Dockable dockable : dockedTopicPanels.keySet()) { TopicPanel tp = dockedTopicPanels.get(dockable); if(tp != null && tp.supportsOpenTopic()) { struct.add( tp.getName() + DockingFramePanel.getAdditionalLabel(tp) ); struct.add( tp.getIcon() ); struct.add( new OpenTopicIn(tp) ); } } } else { struct.add("[No panels open]"); } struct.add("---"); java.util.List<java.util.List<Object>> availableTopicPanels = wandora.topicPanelManager.getAvailableTopicPanelsSupportingOpenTopic(); for(java.util.List<Object> panelData : availableTopicPanels) { try { Class panelClass = Class.forName((String) panelData.get(0)); if(!DockingFramePanel.class.equals(panelClass)) { struct.add( "New " + (String) panelData.get(1) ); struct.add( (Icon) panelData.get(2) ); struct.add( new OpenTopicInNew( panelClass ) ); } } catch(Exception e) {} } struct.add( "---" ); struct.add("Locate in topic tree"); struct.add(UIBox.getIcon("gui/icons/locate_in_tree.png")); struct.add(new LocateSelectTopicInTree()); } return struct.toArray( new Object[] {} ); } public static Object[] getSubjectIdentifierTablePopupStruct() { return new Object[] { "Open...", new OpenSubjectIdentifier(new SIContext()), "Add...", new AddSubjectIdentifier(), "---", "Select all", new SelectAll(), "Deselect", new ClearSelection(), "Invert selection", new InvertSelection(), "---", "Copy", new CopySubjectIdentifiers(new SIContext()), "Paste", new PasteSubjectIdentifiers(new SIContext()), "---", "Duplicate", new DuplicateSubjectIdentifier(new SIContext()), "Remove...", new DeleteSubjectIdentifiers(new SIContext()), "Remove with regex...", new DeleteSubjectIdentifiersWithRegex(new SIContext()), "Flatten...", new FlattenSubjectIdentifiers(), "Expand", new Object[] { "Expand with sameAs.org", new SameAsSubjectExpander(new SIContext()), "Expand with sameAs.org store", new Object[] { "Expand with 270a store", new SameAs270aStoreSubjectExpander(new SIContext()), "Expand with British Library store", new SameAsBritishLibraryStoreSubjectExpander(new SIContext()), "Expand with Data Southampton store", new SameAsDataSouthamptonStoreSubjectExpander(new SIContext()), "Expand with Disaster 20 store", new SameAsDisaster20StoreSubjectExpander(new SIContext()), "Expand with Email store", new SameAsEmailStoreSubjectExpander(new SIContext()), "Expand with Freebase store", new SameAsFreebaseStoreSubjectExpander(new SIContext()), "Expand with Kelle store", new SameAsKelleStoreSubjectExpander(new SIContext()), "Expand with LATC store", new SameAsLATCStoreSubjectExpander(new SIContext()), "Expand with Libris store", new SameAsLibrisStoreSubjectExpander(new SIContext()), "Expand with MusicNet store", new SameAsMusicNetStoreSubjectExpander(new SIContext()), "Expand with NoTube store", new SameAsNoTubeStoreSubjectExpander(new SIContext()), "Expand with Ordnance Survey store", new SameAsOrdnanceSurveyStoreSubjectExpander(new SIContext()), "Expand with Pleiades store", new SameAsPleiadesStoreSubjectExpander(new SIContext()), "Expand with Schema.org store", new SameAsSchemaOrgStoreSubjectExpander(new SIContext()), "Expand with Torver Data store", new SameAsTorverDataStoreSubjectExpander(new SIContext()), "Expand with VIAF store", new SameAsVIAFStoreSubjectExpander(new SIContext()), "Expand with Web Index store", new SameAsWebIndexStoreSubjectExpander(new SIContext()), }, "Expand with sameAs anywhere", new SameAsAnywhereSubjectExpander(new SIContext()), }, "---", "Copy to subject locator", new MakeSubjectLocatorFromSubjectIdentifier(new SIContext()), }; } public static Object[] getSubjectIdentifierLabelPopupStruct() { return new Object[] { "Add...", new AddSubjectIdentifier(new ApplicationContext()), "Copy", new CopySubjectIdentifiers(new ApplicationContext()), "Paste", new PasteSubjectIdentifiers(new ApplicationContext()), "---", "Flatten...", new FlattenSubjectIdentifiers(new ApplicationContext()), "Expand", new Object[] { "Expand with sameAs.org", new SameAsSubjectExpander(new ApplicationContext()), "Expand with sameAs.org store", new Object[] { "Expand with 270a store", new SameAs270aStoreSubjectExpander(new ApplicationContext()), "Expand with British Library store", new SameAsBritishLibraryStoreSubjectExpander(new ApplicationContext()), "Expand with Data Southampton store", new SameAsDataSouthamptonStoreSubjectExpander(new ApplicationContext()), "Expand with Disaster 20 store", new SameAsDisaster20StoreSubjectExpander(new ApplicationContext()), "Expand with Email store", new SameAsEmailStoreSubjectExpander(new ApplicationContext()), "Expand with Freebase store", new SameAsFreebaseStoreSubjectExpander(new ApplicationContext()), "Expand with Kelle store", new SameAsKelleStoreSubjectExpander(new ApplicationContext()), "Expand with LATC store", new SameAsLATCStoreSubjectExpander(new ApplicationContext()), "Expand with Libris store", new SameAsLibrisStoreSubjectExpander(new ApplicationContext()), "Expand with MusicNet store", new SameAsMusicNetStoreSubjectExpander(new ApplicationContext()), "Expand with NoTube store", new SameAsNoTubeStoreSubjectExpander(new ApplicationContext()), "Expand with Ordnance Survey store", new SameAsOrdnanceSurveyStoreSubjectExpander(new ApplicationContext()), "Expand with Pleiades store", new SameAsPleiadesStoreSubjectExpander(new ApplicationContext()), "Expand with Schema.org store", new SameAsSchemaOrgStoreSubjectExpander(new ApplicationContext()), "Expand with Torver Data store", new SameAsTorverDataStoreSubjectExpander(new ApplicationContext()), "Expand with VIAF store", new SameAsVIAFStoreSubjectExpander(new ApplicationContext()), "Expand with Web Index store", new SameAsWebIndexStoreSubjectExpander(new ApplicationContext()), }, "Expand with sameAs anywhere", new SameAsAnywhereSubjectExpander(new ApplicationContext()), } }; } public static Object[] getSubjectLocatorLabelPopupStruct() { return new Object[] { "Open...", new OpenSubjectLocator(new ApplicationContext()), "---", "Copy from filename...", new MakeSubjectLocatorFromFilename(new ApplicationContext()), "Copy from file content...", new MakeSubjectLocatorFromFileContent(new ApplicationContext()), "Copy from subject identifier", new MakeSubjectLocatorFromSubjectIdentifier(new ApplicationContext()), "Copy from basename...", new MakeSubjectLocatorFromBasename(new ApplicationContext()), "Copy from occurrence...", new MakeSubjectLocatorFromOccurrence(new ApplicationContext()), "---", "Copy to subject identifier", new MakeSubjectIdentifierFromSubjectLocator(new ApplicationContext()), "Copy to occurrence", new MakeOccurrenceFromSubjectLocator(new ApplicationContext()), "---", "Remove...", new DeleteSubjectLocator(new ApplicationContext()), "---", "Check...", new CheckSubjectLocator(new ApplicationContext()), "Download...", new DownloadSubjectLocators(new ApplicationContext()), "Download and change...", new DownloadSubjectLocators(new ApplicationContext(), true), //"Move to fileserver", new MoveSubjectLocators(new ApplicationContext()), // new ContextToolWrapper( // parent.getToolManager().getConfigurableTool(MoveSubjectLocators.class,"movesl","Move SL to fileserver"), // new ApplicationContext()), "Convert as data url", new ConvertSubjectLocatorToDataURL(new ApplicationContext()), "Upload to Mediawiki...", new MediawikiSubjectLocatorUploader(new ApplicationContext()), "---", "Extract", WandoraMenuManager.getSubjectLocatorExtractorMenu(Wandora.getWandora(), new ApplicationContext()), }; } public static Object[] getInstancesTablePopupStruct() { return new Object[] { "Add instance...", new AddInstance(new ApplicationContext()), "Paste instances", new Object[] { "Paste instances as base names...", new PasteInstances(new ApplicationContext()), "Paste instances as subject identifiers...", new PasteInstances(new ApplicationContext(), PasteInstances.INCLUDE_NOTHING, PasteInstances.PASTE_SIS), "---", "Paste instances with names...", new PasteInstances(new ApplicationContext(), PasteInstances.INCLUDE_NAMES), "Paste instances with subject locators...", new PasteInstances(new ApplicationContext(), PasteInstances.INCLUDE_SLS), "Paste instances with subject identifiers...", new PasteInstances(new ApplicationContext(), PasteInstances.INCLUDE_SIS), "Paste instances with classes...", new PasteInstances(new ApplicationContext(), PasteInstances.INCLUDE_CLASSES), "Paste instances with instances...", new PasteInstances(new ApplicationContext(), PasteInstances.INCLUDE_INSTANCES), "Paste instances with players...", new PasteInstances(new ApplicationContext(), PasteInstances.INCLUDE_PLAYERS), "Paste instances with occurrences...", new PasteInstances(new ApplicationContext(), PasteInstances.INCLUDE_TEXTDATAS), }, }; } public static Object[] getClassesTablePopupStruct() { return new Object[] { "Add class...", new AddClass(new ApplicationContext()), "Paste classes", new Object[] { "Paste classes as base names...", new PasteClasses(new ApplicationContext()), "Paste classes as subject identifiers...", new PasteClasses(new ApplicationContext(), PasteClasses.INCLUDE_NOTHING, PasteInstances.PASTE_SIS), "---", "Paste classes with names...", new PasteClasses(new ApplicationContext(), PasteInstances.INCLUDE_NAMES), "Paste classes with subject lcoators...", new PasteClasses(new ApplicationContext(), PasteInstances.INCLUDE_SLS), "Paste classes with subject identifiers...", new PasteClasses(new ApplicationContext(), PasteInstances.INCLUDE_SIS), "Paste classes with classes...", new PasteClasses(new ApplicationContext(), PasteInstances.INCLUDE_CLASSES), "Paste classes with instances...", new PasteClasses(new ApplicationContext(), PasteInstances.INCLUDE_INSTANCES), "Paste classes with players...", new PasteClasses(new ApplicationContext(), PasteInstances.INCLUDE_PLAYERS), "Paste classes with occurrences...", new PasteClasses(new ApplicationContext(), PasteInstances.INCLUDE_TEXTDATAS), }, }; } public static Object[] getVariantsLabelPopupStruct(Options options) { String variantGUIType = VARIANT_GUITYPE_SCHEMA; try { variantGUIType = options.get(VARIANT_GUITYPE_OPTIONS_KEY, variantGUIType); } catch(Exception e) {} return new Object[] { "Add variant name...", new AddVariantName(new ApplicationContext()), "---", "Add missing display scope", new AddImplicitDisplayScopeToVariants(new ApplicationContext()), "Add missing sort scope", new AddImplicitSortScopeToVariants(new ApplicationContext()), "Add missing language...", new AddMissingLanguageScope(new ApplicationContext()), "---", "Copy all variant names", new TopicNameCopier(new ApplicationContext()), "---", "Remove variant name...", new VariantRemover(new ApplicationContext()), "Remove all empty variant names...", new AllEmptyVariantRemover(new ApplicationContext()), "---", "View", new Object[] { "View schema scopes", new ChangeVariantView(VARIANT_GUITYPE_SCHEMA, options), (VARIANT_GUITYPE_SCHEMA.equals(variantGUIType) ? UIBox.getIcon("gui/icons/checkbox_selected.png") : UIBox.getIcon("gui/icons/checkbox.png")), "View used scopes", new ChangeVariantView(VARIANT_GUITYPE_USED, options), (VARIANT_GUITYPE_USED.equals(variantGUIType) ? UIBox.getIcon("gui/icons/checkbox_selected.png") : UIBox.getIcon("gui/icons/checkbox.png")), "---", "Flip name matrix", new FlipNameMatrix(OPTIONS_PREFIX, options), } }; } public static Object[] getOccurrencesLabelPopupStruct(Options options) { String viewType = OccurrenceTable.VIEW_SCHEMA; int rowHeight = 0; try { if(options != null) { viewType = options.get(OccurrenceTable.VIEW_OPTIONS_KEY, OccurrenceTable.VIEW_SCHEMA); rowHeight = options.getInt(OccurrenceTable.ROW_HEIGHT_OPTIONS_KEY, rowHeight); } } catch(Exception e) {} return new Object[] { "Add occurrence...", new AddSchemalessOccurrence(new ApplicationContext()), "Delete all occurrences...", new DeleteAllOccurrences(new ApplicationContext()), "---", "View", new Object[] { "View schema scopes", new ChangeOccurrenceView(OccurrenceTable.VIEW_SCHEMA, options), (OccurrenceTable.VIEW_SCHEMA.equals(viewType) ? UIBox.getIcon("gui/icons/checkbox_selected.png") : UIBox.getIcon("gui/icons/checkbox.png")), "View used scopes", new ChangeOccurrenceView(OccurrenceTable.VIEW_USED, options), (OccurrenceTable.VIEW_USED.equals(viewType) ? UIBox.getIcon("gui/icons/checkbox_selected.png") : UIBox.getIcon("gui/icons/checkbox.png")), "View schema and used scopes", new ChangeOccurrenceView(OccurrenceTable.VIEW_USED_AND_SCHEMA, options), (OccurrenceTable.VIEW_USED_AND_SCHEMA.equals(viewType) ? UIBox.getIcon("gui/icons/checkbox_selected.png") : UIBox.getIcon("gui/icons/checkbox.png")), "---", "Auto row height", new ChangeOccurrenceTableRowHeight(0, options), (rowHeight == 0 ? UIBox.getIcon("gui/icons/checkbox_selected.png") : UIBox.getIcon("gui/icons/checkbox.png")), "View single row", new ChangeOccurrenceTableRowHeight(1, options), (rowHeight == 1 ? UIBox.getIcon("gui/icons/checkbox_selected.png") : UIBox.getIcon("gui/icons/checkbox.png")), "View 5 rows", new ChangeOccurrenceTableRowHeight(5, options), (rowHeight == 5 ? UIBox.getIcon("gui/icons/checkbox_selected.png") : UIBox.getIcon("gui/icons/checkbox.png")), "View 10 rows", new ChangeOccurrenceTableRowHeight(10, options), (rowHeight == 10 ? UIBox.getIcon("gui/icons/checkbox_selected.png") : UIBox.getIcon("gui/icons/checkbox.png")), "View 20 rows", new ChangeOccurrenceTableRowHeight(20, options), (rowHeight == 20 ? UIBox.getIcon("gui/icons/checkbox_selected.png") : UIBox.getIcon("gui/icons/checkbox.png")), }, }; } public static Object[] getAssociationTableLabelPopupStruct() { return new Object[] { // "Add association...", new AddAssociations(new ApplicationContext()), "Add association...", new AddSchemalessAssociation(new ApplicationContext()), "---", /* "Count associations...", new CountAssociations(), "---", **/ "Copy", new Object[] { "Copy associations as Wandora layout tab text", new CopyAssociations(new ApplicationAssociationContext()), "Copy associations as Wandora layout HTML", new CopyAssociations(new ApplicationAssociationContext(), CopyAssociations.HTML_OUTPUT), "---", "Copy associations as LTM layout tab text", new CopyAssociations(new ApplicationAssociationContext(), CopyAssociations.TABTEXT_OUTPUT, CopyAssociations.LTM_LAYOUT), "Copy associations as LTM layout HTML", new CopyAssociations(new ApplicationAssociationContext(), CopyAssociations.HTML_OUTPUT, CopyAssociations.LTM_LAYOUT), }, "Paste", new Object[] { "Paste associations...", new PasteAssociations(new ApplicationContext()), }, "Delete", new Object[] { "Delete associations...", new DeleteAssociationsInTopic(new ApplicationContext()), "Delete associated topics...", new DeleteFromTopics(new ApplicationContext(), DeleteFromTopics.DELETE_ASSOCIATED_TOPICS), } }; } public static Object[] getAssociationTypeLabelPopupStruct() { return new Object[] { "Open association type topic", new OpenTopic(), /* "---", "Count associations of type...", new CountAssociationsOfType(), "---", "Copy", new Object[] { "Copy association type's base name", new CopyTopics(CopyTopics.INCLUDE_NOTHING), "Copy association type's SIs", new CopyTopics(CopyTopics.INCLUDE_NOTHING), "---", "Copy associations of this type as tab text", "Copy associations of this type as HTML", "---", "Copy all associations of this type as tab text", "Copy all associations of this type as HTML", }, "Paste", new Object[] { "Paste tab text associations", new PasteAssociationsOfType(), }, ***/ "---", "Duplicate associations of type...", new DuplicateAssociations(), "Delete associations of this type...", new DeleteAssociations(), "Change association type...", new ChangeAssociationType(), "Change association role...", new ChangeAssociationRole(), //"Make players instance of role...", //new AddInstanceToPlayers(), }; } }
145,440
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
WandoraToolManagerPanel.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/WandoraToolManagerPanel.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * WandoraToolManagerPanel.java * * Created on 30. tammikuuta 2006, 11:56 */ package org.wandora.application; import static org.wandora.utils.Tuples.t2; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Vector; import javax.swing.DefaultListModel; import javax.swing.JDialog; import org.wandora.application.gui.UIConstants; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.topicmap.TopicMapException; import org.wandora.utils.Tuples.T2; /** * * @author olli */ public class WandoraToolManagerPanel extends javax.swing.JPanel { private static final long serialVersionUID = 1L; public static class ListWrapper { public T2<WandoraTool,String> tool; public ListWrapper(T2<WandoraTool,String> tool){ this.tool=tool; } public String toString(){ return tool.e2; } } public static class ComboboxWrapper{ public WandoraTool tool; public ComboboxWrapper(WandoraTool tool){ this.tool=tool; } public String toString(){ return tool.getName()+" ("+tool.getClass().getName()+")"; } } private Wandora admin; private WandoraToolManager manager; private DefaultListModel listModel; private JDialog newDialog; private JDialog parent; private JDialog renameDialog; private boolean renameCancelled; /** Creates new form AdminToolManagerPanel */ public WandoraToolManagerPanel(WandoraToolManager manager, JDialog parent, Wandora admin) { this.admin = admin; this.manager = manager; this.parent = parent; listModel = new DefaultListModel(); initComponents(); refreshTools(); newDialog=new JDialog(parent,true); newDialog.getContentPane().add(newToolPanel); newDialog.setTitle("New tool"); renameDialog=new JDialog(parent,true); renameDialog.getContentPane().add(renamePanel); renameDialog.setTitle("Rename tool"); } public void refreshTools(){ listModel.removeAllElements(); Vector<T2<WandoraTool,String>> tools=manager.getTools(typeComboBox.getSelectedItem().toString()); for(T2<WandoraTool,String> tool : tools){ listModel.addElement(new ListWrapper(tool)); } toolList.repaint(); } private String getCurrentType() { return typeComboBox.getSelectedItem().toString(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; newToolPanel = new javax.swing.JPanel(); toolLabel = new org.wandora.application.gui.simple.SimpleLabel(); toolComboBox = new org.wandora.application.gui.simple.SimpleComboBox(); nameLabel = new org.wandora.application.gui.simple.SimpleLabel(); nameTextField = new org.wandora.application.gui.simple.SimpleField(); jSeparator2 = new javax.swing.JSeparator(); descriptionLabel = new org.wandora.application.gui.simple.SimpleLabel(); descriptionScrollPane = new javax.swing.JScrollPane(); descriptionTextPane = new javax.swing.JTextPane(); jPanel2 = new javax.swing.JPanel(); newOKButton = new org.wandora.application.gui.simple.SimpleButton(); newCancelButton = new org.wandora.application.gui.simple.SimpleButton(); renamePanel = new javax.swing.JPanel(); jLabel3 = new org.wandora.application.gui.simple.SimpleLabel(); renameTextField = new org.wandora.application.gui.simple.SimpleField(); jPanel3 = new javax.swing.JPanel(); renameOKButton = new org.wandora.application.gui.simple.SimpleButton(); renameCancelButton = new org.wandora.application.gui.simple.SimpleButton(); jScrollPane1 = new javax.swing.JScrollPane(); toolList = new javax.swing.JList(listModel); buttonPanel = new javax.swing.JPanel(); newButton = new org.wandora.application.gui.simple.SimpleButton(); removeButton = new org.wandora.application.gui.simple.SimpleButton(); configureButton = new org.wandora.application.gui.simple.SimpleButton(); upButton = new org.wandora.application.gui.simple.SimpleButton(); downButton = new org.wandora.application.gui.simple.SimpleButton(); renameButton = new org.wandora.application.gui.simple.SimpleButton(); okButton = new org.wandora.application.gui.simple.SimpleButton(); typePanel = new javax.swing.JPanel(); jLabel4 = new org.wandora.application.gui.simple.SimpleLabel(); typeComboBox = new org.wandora.application.gui.simple.SimpleComboBox(org.wandora.application.WandoraToolManager.toolTypes); jSeparator1 = new javax.swing.JSeparator(); newToolPanel.setLayout(new java.awt.GridBagLayout()); toolLabel.setText("Tool class"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(7, 7, 0, 5); newToolPanel.add(toolLabel, gridBagConstraints); toolComboBox.setPreferredSize(new java.awt.Dimension(29, 21)); toolComboBox.setEditable(false); toolComboBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { toolComboBoxActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(7, 5, 0, 7); newToolPanel.add(toolComboBox, gridBagConstraints); nameLabel.setText("Name"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 7, 5, 5); newToolPanel.add(nameLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 7); newToolPanel.add(nameTextField, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 1; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(10, 7, 0, 7); newToolPanel.add(jSeparator2, gridBagConstraints); descriptionLabel.setText("Description"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(0, 7, 2, 5); newToolPanel.add(descriptionLabel, gridBagConstraints); descriptionScrollPane.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(153, 153, 153))); descriptionScrollPane.setMaximumSize(new java.awt.Dimension(3, 50)); descriptionScrollPane.setMinimumSize(new java.awt.Dimension(3, 50)); descriptionScrollPane.setPreferredSize(new java.awt.Dimension(3, 50)); descriptionTextPane.setBorder(null); descriptionTextPane.setEditable(false); descriptionTextPane.setFont(UIConstants.smallButtonLabelFont); descriptionTextPane.setMaximumSize(new java.awt.Dimension(1, 40)); descriptionTextPane.setMinimumSize(new java.awt.Dimension(1, 40)); descriptionTextPane.setPreferredSize(new java.awt.Dimension(1, 40)); descriptionScrollPane.setViewportView(descriptionTextPane); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 5, 2, 7); newToolPanel.add(descriptionScrollPane, gridBagConstraints); jPanel2.setLayout(new java.awt.GridBagLayout()); newOKButton.setText("OK"); newOKButton.setMargin(new java.awt.Insets(2, 6, 2, 6)); newOKButton.setMaximumSize(new java.awt.Dimension(65, 23)); newOKButton.setPreferredSize(new java.awt.Dimension(65, 23)); newOKButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { newOKButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 0); jPanel2.add(newOKButton, gridBagConstraints); newCancelButton.setText("Cancel"); newCancelButton.setMargin(new java.awt.Insets(2, 6, 2, 6)); newCancelButton.setMaximumSize(new java.awt.Dimension(65, 23)); newCancelButton.setPreferredSize(new java.awt.Dimension(65, 23)); newCancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { newCancelButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 8, 0, 0); jPanel2.add(newCancelButton, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.gridwidth = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHEAST; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 7, 7, 7); newToolPanel.add(jPanel2, gridBagConstraints); renamePanel.setLayout(new java.awt.GridBagLayout()); jLabel3.setText("New name"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(7, 7, 5, 5); renamePanel.add(jLabel3, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(7, 5, 5, 7); renamePanel.add(renameTextField, gridBagConstraints); renameOKButton.setText("OK"); renameOKButton.setMargin(new java.awt.Insets(2, 6, 2, 6)); renameOKButton.setMaximumSize(new java.awt.Dimension(65, 23)); renameOKButton.setPreferredSize(new java.awt.Dimension(65, 23)); renameOKButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { renameOKButtonActionPerformed(evt); } }); jPanel3.add(renameOKButton); renameCancelButton.setText("Cancel"); renameCancelButton.setMargin(new java.awt.Insets(2, 6, 2, 6)); renameCancelButton.setMaximumSize(new java.awt.Dimension(65, 23)); renameCancelButton.setPreferredSize(new java.awt.Dimension(65, 23)); renameCancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { renameCancelButtonActionPerformed(evt); } }); jPanel3.add(renameCancelButton); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.gridwidth = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHEAST; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 2, 5, 2); renamePanel.add(jPanel3, gridBagConstraints); setLayout(new java.awt.GridBagLayout()); toolList.setFont(UIConstants.labelFont); toolList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); toolList.addListSelectionListener(new javax.swing.event.ListSelectionListener() { public void valueChanged(javax.swing.event.ListSelectionEvent evt) { toolListValueChanged(evt); } }); jScrollPane1.setViewportView(toolList); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.gridheight = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); add(jScrollPane1, gridBagConstraints); buttonPanel.setLayout(new java.awt.GridBagLayout()); newButton.setText("New"); newButton.setMaximumSize(new java.awt.Dimension(90, 23)); newButton.setMinimumSize(new java.awt.Dimension(90, 23)); newButton.setPreferredSize(new java.awt.Dimension(90, 23)); newButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { newButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(5, 5, 3, 5); buttonPanel.add(newButton, gridBagConstraints); removeButton.setText("Remove"); removeButton.setMaximumSize(new java.awt.Dimension(90, 23)); removeButton.setMinimumSize(new java.awt.Dimension(90, 23)); removeButton.setPreferredSize(new java.awt.Dimension(90, 23)); removeButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { removeButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.insets = new java.awt.Insets(0, 5, 3, 5); buttonPanel.add(removeButton, gridBagConstraints); configureButton.setText("Configure"); configureButton.setEnabled(false); configureButton.setMaximumSize(new java.awt.Dimension(90, 23)); configureButton.setMinimumSize(new java.awt.Dimension(90, 23)); configureButton.setPreferredSize(new java.awt.Dimension(90, 23)); configureButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { configureButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); buttonPanel.add(configureButton, gridBagConstraints); upButton.setText("Up"); upButton.setMaximumSize(new java.awt.Dimension(90, 23)); upButton.setMinimumSize(new java.awt.Dimension(90, 23)); upButton.setPreferredSize(new java.awt.Dimension(90, 23)); upButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { upButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.insets = new java.awt.Insets(5, 5, 3, 5); buttonPanel.add(upButton, gridBagConstraints); downButton.setText("Down"); downButton.setMaximumSize(new java.awt.Dimension(90, 23)); downButton.setMinimumSize(new java.awt.Dimension(90, 23)); downButton.setPreferredSize(new java.awt.Dimension(90, 23)); downButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { downButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.insets = new java.awt.Insets(0, 5, 5, 5); buttonPanel.add(downButton, gridBagConstraints); renameButton.setText("Rename"); renameButton.setMaximumSize(new java.awt.Dimension(90, 23)); renameButton.setMinimumSize(new java.awt.Dimension(90, 23)); renameButton.setPreferredSize(new java.awt.Dimension(90, 23)); renameButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { renameButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.insets = new java.awt.Insets(0, 5, 5, 5); buttonPanel.add(renameButton, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; add(buttonPanel, gridBagConstraints); okButton.setText("OK"); okButton.setMaximumSize(new java.awt.Dimension(90, 23)); okButton.setMinimumSize(new java.awt.Dimension(90, 23)); okButton.setPreferredSize(new java.awt.Dimension(90, 23)); okButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { okButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTH; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); add(okButton, gridBagConstraints); typePanel.setLayout(new java.awt.GridBagLayout()); jLabel4.setText("Tool type"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); typePanel.add(jLabel4, gridBagConstraints); typeComboBox.setPreferredSize(new java.awt.Dimension(29, 21)); typeComboBox.setEditable(false); typeComboBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { typeComboBoxActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); typePanel.add(typeComboBox, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; add(typePanel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 1; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); add(jSeparator1, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents private void typeComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_typeComboBoxActionPerformed refreshTools(); boolean enableButtons=true; if("configurable".equals(getCurrentType())) { enableButtons=false; } renameButton.setEnabled(enableButtons); newButton.setEnabled(enableButtons); removeButton.setEnabled(enableButtons); upButton.setEnabled(enableButtons); downButton.setEnabled(enableButtons); }//GEN-LAST:event_typeComboBoxActionPerformed private void renameCancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_renameCancelButtonActionPerformed renameCancelled=true; renameDialog.setVisible(false); }//GEN-LAST:event_renameCancelButtonActionPerformed private void renameOKButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_renameOKButtonActionPerformed renameCancelled=false; renameDialog.setVisible(false); }//GEN-LAST:event_renameOKButtonActionPerformed private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed parent.setVisible(false); }//GEN-LAST:event_okButtonActionPerformed private void newCancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newCancelButtonActionPerformed newDialog.setVisible(false); }//GEN-LAST:event_newCancelButtonActionPerformed private void toolComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_toolComboBoxActionPerformed if(toolComboBox.getSelectedItem() != null) { WandoraTool tool = ((ComboboxWrapper)toolComboBox.getSelectedItem()).tool; if(tool != null) { nameTextField.setText(tool.getName()); descriptionTextPane.setText(tool.getDescription()); } } }//GEN-LAST:event_toolComboBoxActionPerformed private void newOKButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newOKButtonActionPerformed String name=nameTextField.getText(); if(name.trim().length()==0) { WandoraOptionPane.showMessageDialog(this, "You must enter a name for the tool!"); return; } boolean added=manager.addTool(((ComboboxWrapper)toolComboBox.getSelectedItem()).tool,name,getCurrentType()); if(!added) { WandoraOptionPane.showMessageDialog(this, "That name is already used for another tool!"); return; } refreshTools(); newDialog.setVisible(false); }//GEN-LAST:event_newOKButtonActionPerformed private void toolListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_toolListValueChanged ListWrapper wrapper=(ListWrapper)toolList.getSelectedValue(); if(wrapper==null) { configureButton.setEnabled(false); return; } WandoraTool tool=wrapper.tool.e1; configureButton.setEnabled(tool.isConfigurable()); }//GEN-LAST:event_toolListValueChanged private void downButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_downButtonActionPerformed int sel=toolList.getSelectedIndex(); Vector<T2<WandoraTool,String>> tools=manager.getTools(getCurrentType()); if(sel==-1 || sel==tools.size()-1) return; T2<WandoraTool,String> temp=tools.get(sel+1); tools.setElementAt(tools.get(sel), sel+1); tools.setElementAt(temp,sel); refreshTools(); toolList.setSelectedIndex(sel+1); manager.rewriteOptions(); manager.getAdmin().toolsChanged(); }//GEN-LAST:event_downButtonActionPerformed private void upButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_upButtonActionPerformed int sel=toolList.getSelectedIndex(); if(sel==-1 || sel==0) return; Vector<T2<WandoraTool,String>> tools=manager.getTools(getCurrentType()); T2<WandoraTool,String> temp=tools.get(sel-1); tools.setElementAt(tools.get(sel), sel-1); tools.setElementAt(temp,sel); refreshTools(); toolList.setSelectedIndex(sel-1); manager.rewriteOptions(); manager.getAdmin().toolsChanged(); }//GEN-LAST:event_upButtonActionPerformed private void configureButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_configureButtonActionPerformed ListWrapper wrapper=(ListWrapper)toolList.getSelectedValue(); if(wrapper==null){ configureButton.setEnabled(false); return; } WandoraTool tool=wrapper.tool.e1; int counter=toolList.getSelectedIndex(); if(tool.isConfigurable()) { try{ String type=getCurrentType(); tool.configure(manager.getAdmin(),manager.getAdmin().getOptions(),"tools."+type+".item"+counter+".options."); }catch(TopicMapException tme){ tme.printStackTrace(); // TODO EXCEPTION } } }//GEN-LAST:event_configureButtonActionPerformed private void renameButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_renameButtonActionPerformed int sel=toolList.getSelectedIndex(); if(sel==-1) return; renameDialog.setSize(400,100); if(admin != null) admin.centerWindow(renameDialog); renameTextField.setText(manager.getTools(getCurrentType()).get(sel).e2); renameTextField.setSelectionStart(0); renameTextField.setSelectionEnd(renameTextField.getText().length()); renameDialog.setVisible(true); if(renameCancelled) return; String name=renameTextField.getText(); while(!manager.checkName(name)){ WandoraOptionPane.showMessageDialog(this, "That name is already used by another tool."); renameDialog.setSize(400,100); org.wandora.utils.swing.GuiTools.centerWindow(renameDialog,this); renameTextField.setText(name); renameTextField.setSelectionStart(0); renameTextField.setSelectionEnd(renameTextField.getText().length()); renameDialog.setVisible(true); if(renameCancelled) return; name=renameTextField.getText(); } Vector<T2<WandoraTool,String>> tools=manager.getTools(getCurrentType()); T2<WandoraTool,String> tool=tools.get(sel); tools.setElementAt(t2(tool.e1,name),sel); refreshTools(); manager.rewriteOptions(); manager.getAdmin().toolsChanged(); }//GEN-LAST:event_renameButtonActionPerformed private void removeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeButtonActionPerformed int sel=toolList.getSelectedIndex(); if(sel==-1) return; Vector<T2<WandoraTool,String>> tools=manager.getTools(getCurrentType()); T2<WandoraTool,String> tool=tools.get(sel); manager.removeTool(tool.e1, tool.e2, getCurrentType()); refreshTools(); manager.rewriteOptions(); manager.getAdmin().toolsChanged(); }//GEN-LAST:event_removeButtonActionPerformed private void newButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newButtonActionPerformed List<WandoraTool> tools=new Vector<WandoraTool>(); for(WandoraTool tool : manager.getToolList(getCurrentType())) { tools.add(tool); } Collections.sort(tools,new Comparator<WandoraTool>() { public int compare(WandoraTool a1,WandoraTool a2){ return a1.getName().compareTo(a2.getName()); } }); toolComboBox.removeAllItems(); for(WandoraTool tool : tools) { toolComboBox.addItem(new ComboboxWrapper(tool)); } newDialog.setSize(600,190); if(admin != null) admin.centerWindow(newDialog); newDialog.setVisible(true); }//GEN-LAST:event_newButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel buttonPanel; private javax.swing.JButton configureButton; private javax.swing.JLabel descriptionLabel; private javax.swing.JScrollPane descriptionScrollPane; private javax.swing.JTextPane descriptionTextPane; private javax.swing.JButton downButton; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JSeparator jSeparator1; private javax.swing.JSeparator jSeparator2; private javax.swing.JLabel nameLabel; private javax.swing.JTextField nameTextField; private javax.swing.JButton newButton; private javax.swing.JButton newCancelButton; private javax.swing.JButton newOKButton; private javax.swing.JPanel newToolPanel; private javax.swing.JButton okButton; private javax.swing.JButton removeButton; private javax.swing.JButton renameButton; private javax.swing.JButton renameCancelButton; private javax.swing.JButton renameOKButton; private javax.swing.JPanel renamePanel; private javax.swing.JTextField renameTextField; private javax.swing.JComboBox toolComboBox; private javax.swing.JLabel toolLabel; private javax.swing.JList toolList; private javax.swing.JComboBox typeComboBox; private javax.swing.JPanel typePanel; private javax.swing.JButton upButton; // End of variables declaration//GEN-END:variables }
31,396
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
CancelledException.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/CancelledException.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * CancelledException.java * * Created on August 30, 2004, 2:42 PM */ package org.wandora.application; /** * An exception that is thrown when the user cancels an operation. This is * usually thrown by TopicPanel.applyChanges. That method will apply any * changes made in the topic panel. These changes may result in topics being * merged or split which will cause a warning dialog to be shown. The user * can cancel the operation with this dialog which will cause the changes done * in the panel to not be applied and this exception be thrown. In such a case * the operation that called applyChanges should be canceled. You should also * always call applyChanges right at the start of your tool or operation so that * you can cancel early and not need to revert back any changes after user * aborts the operation. * * @author olli */ public class CancelledException extends Exception { private static final long serialVersionUID = 1L; /** Creates a new instance of CancelledException */ public CancelledException() { } }
1,870
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
WandoraScriptManager.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/WandoraScriptManager.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * WandoraScriptManager.java * * Created on 9. tammikuuta 2008, 11:23 * */ package org.wandora.application; import javax.script.ScriptException; import org.wandora.utils.ScriptManager; /** * * @author olli */ public class WandoraScriptManager extends ScriptManager { public void showScriptExceptionDialog(String scriptName,ScriptException e){ System.out.println("Script: "+scriptName+" Line: "+e.getLineNumber()+" Column: "+e.getColumnNumber()); e.printStackTrace(); Throwable cause=e.getCause(); if(cause!=null) { System.out.println("Cause:"); cause.printStackTrace(); } } }
1,469
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
WandoraToolManager.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/WandoraToolManager.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * WandoraToolManager.java * * Created on 20. lokakuuta 2005, 16:00 * */ package org.wandora.application; import static org.wandora.utils.Tuples.t2; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.io.File; import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Vector; import javax.swing.JDialog; import javax.swing.JMenu; import javax.swing.JSeparator; import javax.swing.KeyStroke; import org.wandora.application.contexts.Context; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.simple.SimpleMenu; import org.wandora.application.gui.simple.SimpleMenuItem; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.application.tools.ClearToolLocks; import org.wandora.application.tools.importers.OBOImport; import org.wandora.application.tools.importers.SimpleN3Import; import org.wandora.application.tools.importers.SimpleRDFImport; import org.wandora.application.tools.importers.SimpleRDFJsonLDImport; import org.wandora.application.tools.importers.SimpleRDFTurtleImport; import org.wandora.application.tools.importers.TopicMapImport; import org.wandora.application.tools.project.LoadWandoraProject; import org.wandora.application.tools.project.MergeWandoraProject; import org.wandora.utils.GripCollections; import org.wandora.utils.IObox; import org.wandora.utils.Options; import org.wandora.utils.Textbox; import org.wandora.utils.Tuples.T2; /** * WandoraToolManager implements Wandora's Tool Manager. Tool Manager is * used manage Wandora's Tool menu content as well as Import, Extract, and * Export menu contents. * * @author akivela */ public class WandoraToolManager extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; private KeyStroke[] accelerators = new KeyStroke[] { KeyStroke.getKeyStroke(KeyEvent.VK_1, InputEvent.CTRL_DOWN_MASK), KeyStroke.getKeyStroke(KeyEvent.VK_2, InputEvent.CTRL_DOWN_MASK), KeyStroke.getKeyStroke(KeyEvent.VK_3, InputEvent.CTRL_DOWN_MASK), KeyStroke.getKeyStroke(KeyEvent.VK_4, InputEvent.CTRL_DOWN_MASK), KeyStroke.getKeyStroke(KeyEvent.VK_5, InputEvent.CTRL_DOWN_MASK), KeyStroke.getKeyStroke(KeyEvent.VK_6, InputEvent.CTRL_DOWN_MASK), KeyStroke.getKeyStroke(KeyEvent.VK_7, InputEvent.CTRL_DOWN_MASK), KeyStroke.getKeyStroke(KeyEvent.VK_8, InputEvent.CTRL_DOWN_MASK), KeyStroke.getKeyStroke(KeyEvent.VK_9, InputEvent.CTRL_DOWN_MASK), }; protected Wandora admin; // type tool instanceName protected HashMap<String,Vector<T2<WandoraTool,String>>> tools; // protected Vector<T2<AdminTool,String>> tools; // type toolList protected HashMap<String,WandoraTool[]> allTools; public static Vector<String> toolTypes=org.wandora.utils.GripCollections.newVector( WandoraToolType.GENERIC_TYPE, WandoraToolType.IMPORT_TYPE, WandoraToolType.EXPORT_TYPE, WandoraToolType.GENERATOR_TYPE, WandoraToolType.EXTRACT_TYPE /*,"configurable" */ ); //protected HashMap<String,WandoraTool> configurableTools; //protected HashMap<WandoraTool,String> configurableIDs; public WandoraToolManager(Wandora admin) { this.admin=admin; tools=null; allTools=new HashMap<String,WandoraTool[]>(); //configurableTools=new HashMap<String,WandoraTool>(); //configurableIDs=new HashMap<WandoraTool,String>(); refreshTools(); } /* public WandoraTool getConfigurableTool(Class<? extends WandoraTool> c,String id,String label){ WandoraTool tool=configurableTools.get(id); if(tool!=null) return tool; try{ tool=c.newInstance(); }catch(Exception e){ e.printStackTrace(); return null; } configurableTools.put(id,tool); configurableIDs.put(tool,id); Vector<T2<WandoraTool,String>> ts=tools.get("configurable"); if(ts==null) { ts=new Vector<T2<WandoraTool,String>>(); tools.put("configurable",ts); } ts.add(t2(tool,label)); return tool; } */ public Wandora getAdmin(){ return admin; } public WandoraTool[] getToolList(String type){ return getToolList(type,false); } public WandoraTool[] getToolList(String type, boolean forceRefresh){ if(!forceRefresh && allTools.get(type)!=null) return allTools.get(type); try { Vector<WandoraTool> tools=new Vector<WandoraTool>(); int pathCounter = 0; boolean continueSearch = true; ArrayList<String> paths = new ArrayList<String>(); while(continueSearch) { pathCounter++; String toolResourcePath = admin.options.get("tools.path["+pathCounter+"]"); if(toolResourcePath == null || toolResourcePath.length() == 0) { toolResourcePath = "org/wandora/application/tools"; //System.out.println("Using default tool resource path: " + toolResourcePath); continueSearch = false; } if(paths.contains(toolResourcePath)) continue; paths.add(toolResourcePath); String classPath = toolResourcePath.replace('/', '.'); Enumeration toolResources = ClassLoader.getSystemResources(toolResourcePath); while(toolResources.hasMoreElements()) { URL toolBaseUrl = (URL) toolResources.nextElement(); if(toolBaseUrl.toExternalForm().startsWith("file:")) { String baseDir = IObox.getFileFromURL(toolBaseUrl); // String baseDir = URLDecoder.decode(toolBaseUrl.toExternalForm().substring(6), "UTF-8"); if(!baseDir.startsWith("/") && !baseDir.startsWith("\\") && baseDir.charAt(1)!=':') baseDir="/"+baseDir; //System.out.println("Basedir: " + baseDir); HashSet<String> toolFileNames = IObox.getFilesAsHash(baseDir, ".*\\.class", 1, 1000); for(String classFileName : toolFileNames) { try { File classFile = new File(classFileName); String className = classPath + "." + classFile.getName().replaceFirst("\\.class", ""); if(className.indexOf("$")>-1) continue; WandoraTool tool=null; if(className.equals(this.getClass().getName())) tool=this; else { Class cls=Class.forName(className); if(!WandoraTool.class.isAssignableFrom(cls)) { System.out.println("Rejecting '" + className + "'. Does not implement AdminTool interface!"); continue; } if(cls.isInterface()) { System.out.println("Rejecting '" + className + "'. Is interface!"); continue; } try { cls.getConstructor(); } catch(NoSuchMethodException nsme){ System.out.println("Rejecting '" + className + "'. No constructor!"); continue; } tool=(WandoraTool)Class.forName(className).newInstance(); } if(tool.getType().isOfType(type)) { tools.add(tool); } } catch(Exception ex) { System.out.println("Rejecting tool. Exception '" + ex.toString() + "' occurred while investigating tool class '" + classFileName + "'."); //ex.printStackTrace(); } } } } } allTools.put(type,GripCollections.collectionToArray(tools, WandoraTool.class)); return allTools.get(type); } catch (Exception e) { e.printStackTrace(); } return null; } public void execute(Wandora admin, Context context) { JDialog d=new JDialog(admin,"Tool Manager",true); WandoraToolManagerPanel panel=new WandoraToolManagerPanel(this, d, admin); d.getContentPane().add(panel); d.setSize(400,400); org.wandora.utils.swing.GuiTools.centerWindow(d, admin); d.setVisible(true); } public String getName() { return "Tool manager..."; } public String getDescription() { return "Manage Wandora's tools."; } public JMenu getToolMenu(){ JMenu toolMenu = new SimpleMenu("Tools"); toolMenu.setIcon(null); toolMenu = getToolMenu(toolMenu); return toolMenu; } public JMenu getToolMenu(JMenu toolMenu){ toolMenu = getMenu(toolMenu, WandoraToolType.GENERIC_TYPE, accelerators); if(toolMenu.getMenuComponentCount() > 0) toolMenu.add(new JSeparator()); toolMenu.add(this.getToolMenuItem(admin, getName(), KeyStroke.getKeyStroke(KeyEvent.VK_T, InputEvent.CTRL_MASK))); ClearToolLocks clearToolLocks = new ClearToolLocks(); toolMenu.add(clearToolLocks.getToolMenuItem(admin, clearToolLocks.getName(), KeyStroke.getKeyStroke(KeyEvent.VK_Y, InputEvent.CTRL_MASK))); return toolMenu; } public JMenu getGeneratorMenu() { JMenu toolMenu = new SimpleMenu("Generate"); toolMenu.setIcon( UIBox.getIcon("gui/icons/generate.png") ); return getGeneratorMenu(toolMenu); } public JMenu getGeneratorMenu(JMenu toolMenu){ return getMenu(toolMenu, WandoraToolType.GENERATOR_TYPE); } public JMenu getExtractMenu() { JMenu toolMenu = new SimpleMenu("Extract"); toolMenu.setIcon( UIBox.getIcon("gui/icons/extract.png") ); return getExtractMenu(toolMenu); } public JMenu getExtractMenu(JMenu toolMenu){ return getMenu(toolMenu, WandoraToolType.EXTRACT_TYPE); } public JMenu getImportMenu(){ JMenu toolMenu = new SimpleMenu("Import"); toolMenu.setIcon( UIBox.getIcon("gui/icons/import.png") ); return getImportMenu(toolMenu); } public JMenu getImportMenu(JMenu toolMenu){ return getMenu(toolMenu, WandoraToolType.IMPORT_TYPE); } public JMenu getExportMenu(){ JMenu toolMenu = new SimpleMenu("Export"); toolMenu.setIcon( UIBox.getIcon("gui/icons/export.png") ); return getExportMenu(toolMenu); } public JMenu getExportMenu(JMenu toolMenu){ return getMenu(toolMenu, WandoraToolType.EXPORT_TYPE); } public JMenu getMenu(JMenu toolMenu, String type){ return getMenu(toolMenu, type, null); } public JMenu getMenu(JMenu toolMenu, String type, KeyStroke[] keyStrokes){ int strokeIndex = 0; toolMenu.removeAll(); Collection<T2<WandoraTool,String>> ts=tools.get(type); if(ts==null) return toolMenu; for(T2<WandoraTool,String> tool : ts) { if(tool.e2 != null && tool.e2.startsWith("---")) { toolMenu.addSeparator(); } else { SimpleMenuItem item=tool.e1.getToolMenuItem(admin, tool.e2); item.setToolTipText(Textbox.makeHTMLParagraph(tool.e1.getDescription(), 40)); if(keyStrokes != null && strokeIndex < keyStrokes.length) item.setAccelerator(keyStrokes[strokeIndex++]); toolMenu.add(item); } } return toolMenu; } public Vector<T2<WandoraTool,String>> getTools(String type){ Vector<T2<WandoraTool,String>> ts=tools.get(type); if(ts==null) return new Vector<T2<WandoraTool,String>>(); else return ts; } public boolean checkName(String instanceName){ for(Vector<T2<WandoraTool,String>> ts : tools.values()){ for(T2<WandoraTool,String> t : ts){ if(t.e2.equals(instanceName)) return false; } } return true; } public boolean addTool(WandoraTool tool,String instanceName, String type){ if(type == null) return false; if(!checkName(instanceName)) return false; Vector<T2<WandoraTool,String>> ts=tools.get(type); if(ts==null) { ts=new Vector<T2<WandoraTool,String>>(); tools.put(type,ts); } ts.add(t2(tool,instanceName)); Options options=admin.getOptions(); int id=tools.get(type).size()-1; options.put("tools."+type+".item["+id+"].class",tool.getClass().getName()); options.put("tools."+type+".item["+id+"].instanceName",instanceName); tool.writeOptions(admin,options, "tools."+type+".item["+id+"].options."); admin.toolsChanged(); return true; } public boolean removeTool(WandoraTool removedTool, String instanceName, String type) { boolean success = false; Vector<T2<WandoraTool,String>> ts = tools.get(type); if(ts != null) { for(T2<WandoraTool,String> tool : ts){ if(tool != null) { if(tool.e1.equals(removedTool) && tool.e2.equals(instanceName)) { ts.remove(tool); success = true; break; } } } } return success; } public void refreshTools(){ tools=new HashMap<String,Vector<T2<WandoraTool,String>>>(); //configurableTools=new HashMap<String,WandoraTool>(); //configurableIDs=new HashMap<WandoraTool,String>(); Options options=admin.getOptions(); for(String type : toolTypes){ int counter=0; while(true){ String cls=options.get("tools."+type+".item["+counter+"].class"); if(cls==null) break; String instanceName=options.get("tools."+type+".item["+counter+"].instanceName"); try { WandoraTool tool=null; if(cls.equals(this.getClass().getName())) tool=this; else tool=(WandoraTool)Class.forName(cls).newInstance(); tool.initialize(admin,options,"tools."+type+".item["+counter+"].options."); // String type=tool.getType(); Vector<T2<WandoraTool,String>> ts=tools.get(type); if(ts==null) { ts=new Vector<T2<WandoraTool,String>>(); tools.put(type,ts); } ts.add(t2(tool,instanceName)); /* if(type.equals("configurable")){ String id=options.get("tools."+type+".item"+counter+".id"); configurableTools.put(id,tool); configurableIDs.put(tool,id); } */ } catch(ClassNotFoundException cnfe) { System.out.println("Options refer tool class '" + cls + "' not available! Discarding tool!"); } catch(NoClassDefFoundError ncdfe) { System.out.println("A tool configured in options requires a class that was not found. This is most likely caused by a missing library. Missing class was "+ncdfe.getMessage()+". Discarding tool!"); } catch(Exception e) { System.out.println(e); } counter++; } } } public String getOptionsPrefix(WandoraTool adminTool){ HashMap<String,Integer> counters=new HashMap<String,Integer>(); for(Vector<T2<WandoraTool,String>> ts : tools.values()){ for(T2<WandoraTool,String> tool : ts){ String type=tool.e1.getType().oneType(); int counter=0; if(counters.containsKey(type)) counter=counters.get(type); if(adminTool==tool.e1) return "tools."+type+".item["+counter+"].options."; counter++; counters.put(type,counter); } } return null; } public void rewriteOptions(){ Options options=admin.getOptions(); Collection<String> keys=options.keySet(); for(String key : keys){ if(key.startsWith("options.tools") && !key.startsWith("options.tools.path")){ options.put(key,null); } } HashMap<String,Integer> counters=new HashMap<String,Integer>(); for(Vector<T2<WandoraTool,String>> ts : tools.values()){ if(ts != null) { for(T2<WandoraTool,String> tool : ts){ if(tool != null) { String type=tool.e1.getType().oneType(); int counter=0; if(counters.containsKey(type)) counter=counters.get(type); System.out.println("rewriting option "+type+" == "+ tool.e2); options.put("tools."+type+".item["+counter+"].class",tool.e1.getClass().getName()); options.put("tools."+type+".item["+counter+"].instanceName",tool.e2); /* if(type.equals("configurable")){ String id=configurableIDs.get(tool); options.put("tools."+type+".item"+counter+".id",id); } */ tool.e1.writeOptions(admin, options, "tools."+type+".item["+counter+"].options."); counter++; counters.put(type,counter); } } } } } public static ArrayList<WandoraTool> getImportTools(File file, int orders) { ArrayList<File> files = new ArrayList<>(); files.add(file); ArrayList<WandoraTool> toolList = getImportTools(files, orders); return toolList; } public static ArrayList<WandoraTool> getImportTools(java.util.List<File> files, int orders) { String fileName = null; ArrayList<WandoraTool> importTools = new ArrayList<WandoraTool>(); for( File file : files ) { fileName = file.getName().toLowerCase(); if(fileName.endsWith(".xtm20") || fileName.endsWith(".xtm2") || fileName.endsWith(".xtm10") || fileName.endsWith(".xtm1") || fileName.endsWith(".xtm") || fileName.endsWith(".ltm") || fileName.endsWith(".jtm")) { TopicMapImport importer = new TopicMapImport(orders); importer.forceFiles = file; importTools.add(importer); } else if(fileName.endsWith(".rdf") || fileName.endsWith(".rdfs") || fileName.endsWith(".owl") || fileName.endsWith(".daml")) { SimpleRDFImport importer = new SimpleRDFImport(orders); importer.forceFiles = file; importTools.add(importer); } else if(fileName.endsWith(".n3")) { SimpleN3Import importer = new SimpleN3Import(orders); importer.forceFiles = file; importTools.add(importer); } else if(fileName.endsWith(".ttl")) { SimpleRDFTurtleImport importer = new SimpleRDFTurtleImport(orders); importer.forceFiles = file; importTools.add(importer); } else if(fileName.endsWith(".jsonld")) { SimpleRDFJsonLDImport importer = new SimpleRDFJsonLDImport(orders); importer.forceFiles = file; importTools.add(importer); } else if(fileName.endsWith(".obo")) { OBOImport importer = new OBOImport(orders); importer.forceFiles = file; importTools.add(importer); } else if(fileName.endsWith(".wpr")) { if(importTools.isEmpty()) { LoadWandoraProject loader = new LoadWandoraProject(file); importTools.add(loader); } else { MergeWandoraProject merger = new MergeWandoraProject(file); importTools.add(merger); } } } return importTools; } public static ArrayList<WandoraTool> getURIImportTools(java.util.List<URI> uris, int orders) { String fileName = null; ArrayList<WandoraTool> importTools = new ArrayList<WandoraTool>(); for( URI uri : uris ) { try { fileName = uri.toURL().toExternalForm(); if(fileName.endsWith(".xtm20") || fileName.endsWith(".xtm2") || fileName.endsWith(".xtm10") || fileName.endsWith(".xtm1") || fileName.endsWith(".xtm") || fileName.endsWith(".ltm") || fileName.endsWith(".jtm")) { TopicMapImport importer = new TopicMapImport(orders); importer.forceFiles = uri.toURL(); importTools.add(importer); } else if(fileName.endsWith(".rdf") || fileName.endsWith(".rdfs") || fileName.endsWith(".owl") || fileName.endsWith(".daml")) { SimpleRDFImport importer = new SimpleRDFImport(orders); importer.forceFiles = uri.toURL(); importTools.add(importer); } else if(fileName.endsWith(".n3")) { SimpleN3Import importer = new SimpleN3Import(orders); importer.forceFiles = uri.toURL(); importTools.add(importer); } else if(fileName.endsWith(".obo")) { OBOImport importer = new OBOImport(orders); importer.forceFiles = uri.toURL(); importTools.add(importer); } /* else if(fileName.endsWith(".wpr")) { if(importTools.size() == 0) { LoadWandoraProject loader = new LoadWandoraProject(uri.toURL()); importTools.add(loader); } else { MergeWandoraProject merger = new MergeWandoraProject(uri.toURL()); importTools.add(merger); } } */ else { TopicMapImport importer = new TopicMapImport(orders); importer.forceFiles = uri.toURL(); importTools.add(importer); } } catch(Exception e) { e.printStackTrace(); } } return importTools; } }
24,789
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
WandoraToolLogger.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/WandoraToolLogger.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * WandoraToolLogger.java * * Created on 31. toukokuuta 2006, 11:26 * */ package org.wandora.application; import org.wandora.topicmap.TopicMapLogger; /** * Interface defines constants and methods for loggers used by <code>WandoraTool</code> * classes. * * @author akivela */ public interface WandoraToolLogger extends TopicMapLogger { /** * Constant defines logger state. When logger EXECUTEs, it accepts logs. */ public static final int EXECUTE = 100; /** * Constant defines logger state. When logger WAITs, it views log history * and accepts no logs. */ public static final int WAIT = 200; /** * Constant defines logger state. When logger is CLOSEd, it has no visual * representation and log history is forgot. Generally logger is CLOSEd when * tool exists and logging is not required any more. */ public static final int CLOSE = 300; /** * Constant defines logger state. When logger is INVISIBLE, it has no visual * representation but accepts logs and history is available. Generally logger * is made INVISIBLE when tool needs to close logger temporarily. */ public static final int INVISIBLE = 400; /** * Constant defines logger state. When logger is set visible, it is made * once again visible after temporal invisibility. */ public static final int VISIBLE = 401; /** * Logs given string but doesn't add the string to logger history. The * method is used to log repetitive logs such as progress meter that would * choke the history. * * @param message is the logged text. */ @Override public void hlog(String message); // Historyless log == log is not saved to history! /** * Logs given string and adds the string to log history. History can be * browsed later when logging has ended. * * @param message is the logged string message. */ @Override public void log(String message); /** * Logs given string and exception. * * @param message is the logged message. * @param e is the exception to be logged. */ @Override public void log(String message, Exception e); /** * Logs given exception. * * @param e is the logged exception. */ @Override public void log(Exception e); /** * Logs given error. * * @param e is the logged error. */ public void log(Error e); /** * Logger may view progress information for operation. This method is used to * update current progress information with integer n. By default the * progress information is 0..100 but user may change the value range with * <code>setProgressMax</code>. * * @param n is integer value representing the state of current progress. */ @Override public void setProgress(int n); /** * Set the progress point where operation is ready. Default value is 100. * * @param maxn is integer value representing progress when the task is ready. */ @Override public void setProgressMax(int maxn); /** * Logging system may have a title. Normally title is the dialog window's * title. Method changes the title. * * @param title is a string viewed as a title of logger window. */ @Override public void setLogTitle(String title); /** * Should the logger change current log message? If true, the log should * keep the current message visible although new log data is generated. * If false, the logger is free to change the log message whenever new * log is generated. * * @param lock boolean variable that locks or unlocks logger. */ public void lockLog(boolean lock); /** * Returns all collected logs as a string. * * @return String containing all logged messages. */ public String getHistory(); /** * Sets logger's current state. Supported logger states are EXECUTE, * WAIT, CLOSE, INVISIBLE, VISIBLE. * * @param state of logger. */ public void setState(int state); /** * Returns logger's current state. Supported logger states are EXECUTE, * WAIT, CLOSE, INVISIBLE, VISIBLE. * * @return Integer value representing current state of logger. */ public int getState(); /** * <p> * Logger should have a mechanism to receive user interruption. Typically this * is realized with a Cancel or Stop button. Whenever the user interrupts the * operation the logger should return true as the return code of <code>forceStop</code> * method. * </p> * <p> * <code>forceStop</code> mechanism relies that the tool using the logger polls * <code>forceStop</code> method frequently and cancels the operation as soon as * true is returned. * </p> * * @return boolean, if true the tool should stop immediately and return. */ @Override public boolean forceStop(); }
5,947
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
RefreshListener.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/RefreshListener.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * RefreshListener.java * * Created on 30. toukokuuta 2006, 13:35 */ package org.wandora.application; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public interface RefreshListener { public void doRefresh() throws TopicMapException; }
1,089
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ErrorHandler.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/ErrorHandler.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * ErrorHandler.java * * Created on September 8, 2004, 10:59 AM */ package org.wandora.application; /** * * @author olli */ public interface ErrorHandler { public void handleError(Throwable throwable); }
1,032
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
LocatorHistory.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/LocatorHistory.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * LocatorHistory.java * * Created on 18. huhtikuuta 2006, 15:42 * */ package org.wandora.application; import static org.wandora.utils.Tuples.t2; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.swing.Icon; import org.wandora.application.contexts.PreContext; import org.wandora.application.gui.UIBox; import org.wandora.application.tools.navigate.OpenTopic; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.utils.Tuples.T2; /** * <p> * LocatorHistory is used to track browse history in Wandora. Whenever user * opens a topic, topic's subject identifier is stored into LocatorHistory. * Stored subject identifier is later acquired to restore a topic in * browse history. * </p> * <p> * Arrow buttons in Wandora window are used to navigate browse history. * </p> */ public class LocatorHistory { private static final int DEFAULT_MAX_SIZE = 999; private List<T2<Locator,Integer>> history; // location of history "cursor" private int index; // Size of current history private int top; private int maxsize; public LocatorHistory() { this(DEFAULT_MAX_SIZE); } /** Creates a new instance of History */ public LocatorHistory(int max) { maxsize = max; clear(); } public void clear() { history = new ArrayList<>(maxsize); for(int i=0; i<maxsize; i++) history.add(null); index = 0; top = 0; } public void setCurrentViewPosition(int pos){ T2<Locator,Integer> page=peekCurrent(); if(page==null) return; history.set(index-1, t2(page.e1,pos)); } public void add(Locator o) { add(o,0); } public void add(Locator o,int pos) { if(index == 0 || (o != null && !o.equals( history.get(index-1).e1 ))) { if(index >= history.size()) { history.remove(0); history.add(null); index--; } history.set(index++, t2(o,pos)); top = index; //Logger.println("history: " + index + ", " + top); } } // ------------------------------------------------------------------------- public T2<Locator,Integer> getPrevious() { if(index > 1) { index = index - 2; return history.get(index++); } return null; } public T2<Locator,Integer> getNext() { if(top > index) { return history.get(index++); } return null; } // ------------------------------------------------------------------------- public T2<Locator,Integer> peekPrevious() { if(index > 1) { return history.get(index-2); } return null; } public T2<Locator,Integer> peekNext() { if(top > index) { return history.get(index); } return null; } public T2<Locator,Integer> peekCurrent(){ if(index > 0) { return history.get(index-1); } return null; } public boolean isEmpty() { return top == 0; } public Collection<Locator> getLocators() { Collection<Locator> locs = new ArrayList<>(); Locator l = null; for(int i=0; i<top; i++) { l = history.get(i).e1; if(l != null) { locs.add(l); } } return locs; } public Object[] getBackPopupStruct(Wandora admin) { Collection<Object> struct = new ArrayList<>(); Locator l = null; Topic t = null; String name = null; Icon icon = UIBox.getIcon("gui/icons/shortcut.png"); int max = 10; for(int i=index-2; i>=0 && max-- >= 0; i--) { l = history.get(i).e1; if(l != null) { try { t = admin.getTopicMap().getTopic(l); if(t != null) { name = t.getBaseName(); if(name != null && name.length() > 0) { struct.add(name); } else { struct.add(l.toExternalForm()); } struct.add(new OpenTopic(new PreContext(l))); struct.add(icon); } } catch(Exception e) { e.printStackTrace(); } } } return struct.toArray(); } public Object[] getForwardPopupStruct(Wandora admin) { Collection<Object> struct = new ArrayList<>(); Locator l = null; Topic t = null; String name = null; Icon icon = UIBox.getIcon("gui/icons/shortcut.png"); int max = 10; for(int i=index; i<top && max-- >= 0; i++) { l = history.get(i).e1; if(l != null) { try { t = admin.getTopicMap().getTopic(l); if(t != null) { name = t.getBaseName(); if(name != null && name.length() > 0) { struct.add(name); } else { struct.add(l.toExternalForm()); } struct.add(new OpenTopic(new PreContext(l))); struct.add(icon); } } catch(Exception e) { e.printStackTrace(); } } } return struct.toArray(); } }
6,711
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ServerException.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/ServerException.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * ServerException.java * * Created on September 8, 2004, 11:19 AM */ package org.wandora.application; /** * This class is mostly used by the old remote topic map implementation. However, * it is not completely deprecated as it is also used by some tools that perform * actions that previously were an integral part of remote topic maps but are * now separate tools. These tools are related to uploading files to a remote * server. * * @author olli */ public class ServerException extends Exception { private static final long serialVersionUID = 1L; /** Creates a new instance of ServerException */ public ServerException(){ super(); } public ServerException(String message) { super(message); } public ServerException(Throwable cause){ super(cause); } public ServerException(String message,Throwable cause){ super(message,cause); } }
1,736
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
WandoraModuleManager.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/modulesserver/WandoraModuleManager.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.modulesserver; import java.io.File; import java.io.IOException; import java.util.HashMap; import org.wandora.modules.ScopedModuleManager; import org.wandora.modules.servlet.ServletModule; /** * Module manager extension used by Wandora. The main new feature is * reading module bundles contained in subdirectories. * * @author olli */ public class WandoraModuleManager extends ScopedModuleManager { protected WandoraModulesServer server; public WandoraModuleManager(WandoraModulesServer server){ this.server=server; this.setVariable("port",""+server.getPort()); this.setVariable("serverHome",server.getServerPath()); } public void readBundle(File dir) throws IOException { try { File config=new File(dir,"config.xml"); if(!config.exists()) return; log.info("Reading bundle "+dir.getPath()); ModuleBundle bundle=new ModuleBundle(); initNewBundle(bundle, dir); bundle.readXMLOptionsFile(config.getCanonicalPath()); if(bundle.getBundleName()==null){ bundle.setBundleName(dir.getName()); } addModule(bundle); } catch(Exception e) { log.error("Error while initializing bundle module in directory "+dir.getAbsolutePath(), e); } } protected void initNewBundle(ModuleBundle bundle,File dir) throws IOException { String relativeHome=dir.getCanonicalPath(); if(relativeHome.startsWith(getServerHome())){ relativeHome=relativeHome.substring(getServerHome().length()); if(relativeHome.startsWith(File.separator) && getServerHome().length()>0 ){ relativeHome=relativeHome.substring(1); } } String urlPrefix=relativeHome; if(!File.separator.equals("/")) urlPrefix=urlPrefix.replace(File.separator, "/"); if(!urlPrefix.endsWith("/")) urlPrefix+="/"; String urlBase=server.getServletURL(); if(!urlBase.endsWith("/")) urlBase+="/"; urlBase+=urlPrefix; bundle.setVariable("home", dir.getCanonicalPath()); bundle.setVariable("relativeHome", relativeHome); bundle.setVariable("urlbase", urlBase); bundle.setVariable("port",""+server.getPort()); { // Add a servlet module to the bundle that the bundle services // will use. It's configured to catch requests with the bundle // directory in the URL. BundleContext bundleServlet=new BundleContext(); HashMap<String,Object> servletParams=new HashMap<String,Object>(); servletParams.put("contextDir",relativeHome); ModuleSettings settings=new ModuleSettings("bundleServlet", true, 1, null); bundle.addModule(bundleServlet, servletParams, settings); // We also have to add the root servlet as an import so the bundle // servlet can hook into that. bundle.addImport(new Import(ServletModule.class, false)); } bundle.setParentManager(this); bundle.setLogging(log); } public String getServerHome(){ return server.getServerPath(); } public void readBundles() throws IOException { readBundleDirectories(new File(server.getServerPath())); } protected void readBundleDirectories(File dir) throws IOException { if(!dir.exists() || !dir.isDirectory()) return; File config=new File(dir,"config.xml"); if(config.exists()){ readBundle(dir); } else { File[] l=dir.listFiles(); for(File f : l) { if(f.isDirectory()) { readBundleDirectories(f); } } } } }
4,755
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
WandoraServletModule.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/modulesserver/WandoraServletModule.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.modulesserver; import java.io.IOException; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.handler.AbstractHandler; import org.wandora.modules.AbstractModule; import org.wandora.modules.servlet.ActionException; import org.wandora.modules.servlet.ModulesServlet; import org.wandora.modules.servlet.ServletModule; import org.wandora.utils.ListenerList; import org.wandora.utils.ParallelListenerList; import jakarta.servlet.ServletException; /** * * @author olli */ public class WandoraServletModule extends AbstractModule implements ServletModule { protected JettyHandler jettyHandler; protected WandoraModulesServer server; protected final ParallelListenerList<ServletModule.RequestListener> requestListeners=new ParallelListenerList<ServletModule.RequestListener>(ServletModule.RequestListener.class); public WandoraServletModule(WandoraModulesServer server){ this.server=server; jettyHandler=new JettyHandler(); } public Handler getJettyHandler(){ return jettyHandler; } @Override public void addRequestListener(RequestListener listener) { requestListeners.addListener(listener); } @Override public void removeRequestListener(RequestListener listener) { requestListeners.removeListener(listener); } @Override public String getServletURL() { if(server.isUseSSL()) { return "https://127.0.0.1:"+server.getPort()+"/"; } else { return "http://127.0.0.1:"+server.getPort()+"/"; } } @Override public String getContextPath() { return server.getServerPath(); } private class JettyHandler extends AbstractHandler { @Override public void handle( String target, Request rqst, jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response) throws IOException, jakarta.servlet.ServletException { try { final ServletException[] se = new ServletException[1]; final IOException[] ioe = new IOException[1]; final ActionException[] ae = new ActionException[1]; final boolean[] handledA = new boolean[]{false}; final ModulesServlet.HttpMethod method = ModulesServlet.HttpMethod.valueOf(request.getMethod()); requestListeners.forEach(new ListenerList.EachDelegate<ServletModule.RequestListener>() { private boolean handled=false; @Override public void run(ServletModule.RequestListener listener, Object... params) { if(handled) return; try { handled=listener.handleRequest(request, response, method, null); if(handled) handledA[0]=true; } catch(ServletException ex) { handled=true; se[0]=ex; } catch(IOException ex) { handled=true; ioe[0]=ex; } catch(ActionException ex) { handled=true; ae[0]=ex; } } }); if(se[0]!=null) throw se[0]; else if(ioe[0]!=null) throw ioe[0]; else if(ae[0]!=null) { throw new ServletException(ae[0]); } } catch(ServletException | IOException e){ server.log.error(e); } } } }
4,721
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
XTMWebApp.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/modulesserver/XTMWebApp.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.modulesserver; import java.io.IOException; import java.io.OutputStream; import java.util.Map; import org.wandora.modules.ModuleException; import org.wandora.modules.ModuleManager; import org.wandora.modules.servlet.ActionException; import org.wandora.modules.servlet.ModulesServlet; import org.wandora.modules.usercontrol.User; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.memory.TopicMapImpl; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * * @author olli */ public class XTMWebApp extends AbstractTopicWebApp { protected boolean deepCopy = false; @Override public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException { Object o=settings.get("deepCopy"); if(o!=null) deepCopy=Boolean.parseBoolean(o.toString().trim()); super.init(manager, settings); } @Override public boolean handleAction(HttpServletRequest req, HttpServletResponse resp, ModulesServlet.HttpMethod method, String action, User user) throws ServletException, IOException, ActionException { try { String query=req.getParameter(topicRequestKey); if(query!=null) query=query.trim(); if(query!=null && query.length()==0) query=null; // resolveTopic will try to get the open topic in Wandora if query==null Topic topic = resolveTopic(query); if(topic != null) { OutputStream out = resp.getOutputStream(); resp.setContentType("text/xml"); resp.setCharacterEncoding("UTF-8"); TopicMap outTm = new TopicMapImpl(); outTm.copyTopicIn(topic, deepCopy); outTm.copyTopicAssociationsIn(topic); outTm.exportXTM20(out, outTm); out.close(); return true; } else return false; } catch(Exception e) { logging.error(e); return false; } } }
3,041
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ModulesWebApp.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/modulesserver/ModulesWebApp.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.modulesserver; import org.wandora.modules.Module; /** * An interface for modules that are web apps. A web app here means that * the module is usable in a meaningful way from a normal web browser. The * web app should have a name and usually also a start page of some kind. In * addition, it may also have a page for each topic, however this isn't always * the case. * * @author olli */ public interface ModulesWebApp extends Module { /** * Returns the name of the web app. * @return The name of the web app. */ public String getAppName(); /** * Returns the URL for the start page of the web app. If the web app * doesn't have a meaningful start page, return null instead. * * @return The start page of the web app. */ public String getAppStartPage(); /** * Returns the URL representing the topic with the given subject * identifier. If there is no meaningful page for the topic, return null. * This should not be dependent on whether the topic exists or not, the returned * page should be the URL if the topic is assumed to exist. * * @param si The subject identifier of the topic. * @return The URL of the page representing the topic. */ public String getAppTopicPage(String si); }
2,133
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SameAsService.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/modulesserver/SameAsService.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.modulesserver; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.wandora.modules.ModuleException; import org.wandora.modules.ModuleManager; import org.wandora.modules.servlet.ActionException; import org.wandora.modules.servlet.ModulesServlet; import org.wandora.modules.topicmap.ViewTopicAction; import org.wandora.modules.usercontrol.User; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * <p> * SameAsService implements a simple web service that returns all subject identifiers * of a given topic. Given topic is recognized with a single subject identifier * given in URL parameter. * </p> * <p> * The response format is similar to the JSON response format * of the sameAs.org service. Thus, Wandora can be used as a part of LOD machinery, * a web service returning similar URIs. * </p> * <p> * Wandora features a subject expander, SameAsAnywhereSubjectExpander, that * can be used to retrieve subjects provided by the SameAsService. * </p> * * @author akivela */ public class SameAsService extends AbstractTopicWebApp { @Override public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException { super.init(manager, settings); } @Override public boolean handleAction(HttpServletRequest req, HttpServletResponse resp, ModulesServlet.HttpMethod method, String action, User user) throws ServletException, IOException, ActionException { try { String query = req.getParameter(topicRequestKey); if(query == null) query = req.getParameter("uri"); if(query != null) query = query.trim(); if(query!=null && query.length()==0) query=null; Topic topic = resolveTopic(query); if(query == null && topic != null) { query = topic.getOneSubjectIdentifier().toExternalForm(); } if(query != null) { OutputStream out = resp.getOutputStream(); resp.setContentType("application/json"); resp.setCharacterEncoding("UTF-8"); String json = makeJSON(getSameAs(query, topic)); out.write(json.getBytes()); out.close(); return true; } else return false; } catch(Exception e) { logging.error(e); return false; } } @Override public Topic resolveTopic(String query) { TopicMap tm = tmManager.getTopicMap(); if(tm==null) return null; try { Topic t=null; if(query!=null) t = ViewTopicAction.getTopic(query, tm); return t; } catch(TopicMapException tme){ return null; } } protected String makeJSON(SameAs sameas) { StringBuilder sb = new StringBuilder(""); sb.append("["); sb.append("{"); sb.append("\"uri\": ").append(encodeJSON(sameas.url)).append(","); sb.append("\"numDuplicates\": \"").append(sameas.getSameCount()).append("\","); sb.append("\"duplicates\": ["); List<String> sames = sameas.sames; for(int i=0; i<sames.size(); i++) { String url = sames.get(i); sb.append(encodeJSON(url)); if(i < sames.size()-1) sb.append(","); } sb.append("]"); sb.append("}"); sb.append("]"); return sb.toString(); } protected SameAs getSameAs(String u, Topic t) throws TopicMapException { SameAs sameas = new SameAs(u); if(t != null && !t.isRemoved()) { for(Locator l : t.getSubjectIdentifiers()) { sameas.addSame(l.toExternalForm()); } } else { sameas.addSame(u); } return sameas; } protected String encodeJSON(String string) { if(string == null || string.length() == 0) { return "\"\""; } char c = 0; int i; int len = string.length(); StringBuilder sb = new StringBuilder(len + 4); sb.append("\""); String t; for(i = 0; i < len; i += 1) { c = string.charAt(i); switch (c) { case '\\': case '"': sb.append('\\'); sb.append(c); break; case '/': // if (b == '<') { sb.append('\\'); // } sb.append(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: if(c < ' ') { t = "000" + Integer.toHexString(c); sb.append("\\u" + t.substring(t.length() - 4)); } else { sb.append(c); } } } sb.append("\""); return sb.toString(); } // ------------------------------------------------------------------------- /** * SameAs is a helper class to store the URL and all similar URLs. **/ protected class SameAs { public String url = null; public List<String> sames = new ArrayList<>(); public SameAs() { } public SameAs(String u) { url = u; } public void addSame(String u) { if(sames == null) sames = new ArrayList<>(); sames.add(u); } public int getSameCount() { if(sames == null) sames = new ArrayList<>(); return sames.size(); } } }
7,394
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ViewTopicWebApp.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/modulesserver/ViewTopicWebApp.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.modulesserver; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Map; import org.wandora.modules.ModuleException; import org.wandora.modules.ModuleManager; import org.wandora.modules.ModuleManager.ModuleSettings; import org.wandora.modules.topicmap.ViewTopicAction; /** * * @author olli */ public class ViewTopicWebApp extends ViewTopicAction implements ModulesWebApp { protected String webAppName; protected String appStartPage; public ViewTopicWebApp(){ } @Override public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException { // NOTE: ViewTopicWebApp does not extend AbstractWebApp so you may want // to do any modifications here in AbstractWebApp also. Object o=settings.get("webAppName"); if(o!=null) webAppName=o.toString().trim(); else { ModuleSettings ms=manager.getModuleSettings(this); if(ms!=null && ms.name!=null) webAppName=ms.name; else webAppName="Unnamed Webapp"; } super.init(manager, settings); } @Override public void start(ModuleManager manager) throws ModuleException { // NOTE: ViewTopicWebApp does not extend AbstractWebApp so you may want // to do any modifications here in AbstractWebApp also. super.start(manager); if(appStartPage==null){ if(isDefaultAction){ appStartPage=servletModule.getServletURL(); } else if(!handledActions.isEmpty()){ String action=handledActions.iterator().next(); appStartPage=servletModule.getServletURL(); if(appStartPage!=null){ try { appStartPage+="?"+actionParamKey+"="+URLEncoder.encode(action, "UTF-8"); } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex); // shouldn't happen } } } } } @Override public String getAppName() { return webAppName; } @Override public String getAppStartPage() { return appStartPage; } @Override public String getAppTopicPage(String si) { // NOTE: ViewTopicWebApp does not extend AbstractWebApp so you may want // to do any modifications here in AbstractWebApp also. if(appStartPage==null) return null; try{ String page=appStartPage; if(page.indexOf("?")<0) page+="?"; else page+="&"; return page+topicRequestKey+"="+URLEncoder.encode(si, "UTF-8"); }catch(UnsupportedEncodingException uee){ throw new RuntimeException(uee); // shouldn't happen } } }
3,725
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
BundleContext.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/modulesserver/BundleContext.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.modulesserver; import org.wandora.modules.servlet.GenericContext; /** * * A servlet context for the bundle. Currently it doesn't add anything to * the generic context but it might in the future. * * @author olli */ public class BundleContext extends GenericContext { }
1,126
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
RDFWebApp.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/modulesserver/RDFWebApp.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.modulesserver; import java.io.IOException; import java.io.OutputStream; import java.util.Map; import org.wandora.application.tools.exporters.RDFExport; import org.wandora.modules.ModuleException; import org.wandora.modules.ModuleManager; import org.wandora.modules.servlet.ActionException; import org.wandora.modules.servlet.ModulesServlet; import org.wandora.modules.usercontrol.User; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.memory.TopicMapImpl; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * * @author olli */ public class RDFWebApp extends AbstractTopicWebApp { protected boolean deepCopy = false; @Override public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException { Object o=settings.get("deepCopy"); if(o!=null) deepCopy=Boolean.parseBoolean(o.toString().trim()); super.init(manager, settings); } @Override public boolean handleAction(HttpServletRequest req, HttpServletResponse resp, ModulesServlet.HttpMethod method, String action, User user) throws ServletException, IOException, ActionException { try { String query=req.getParameter(topicRequestKey); if(query!=null) query=query.trim(); if(query!=null && query.length()==0) query=null; // resolveTopic will try to get the open topic in Wandora if query==null Topic topic = resolveTopic(query); if(topic != null) { OutputStream out = resp.getOutputStream(); resp.setContentType("text/n3"); resp.setCharacterEncoding("UTF-8"); TopicMap tmOut = new TopicMapImpl(); tmOut.copyTopicIn(topic, deepCopy); tmOut.copyTopicAssociationsIn(topic); RDFExport rdfExport = new RDFExport(); rdfExport.exportRDF(out, tmOut, null); out.close(); return true; } else return false; } catch(Exception e) { logging.error(e); return false; } } }
3,131
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
WaianaService.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/modulesserver/WaianaService.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.modulesserver; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.nio.file.Files; import java.nio.file.Paths; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.wandora.modules.Module; import org.wandora.modules.ModuleException; import org.wandora.modules.ModuleManager; import org.wandora.modules.servlet.ActionException; import org.wandora.modules.servlet.ModulesServlet; import org.wandora.modules.usercontrol.User; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.memory.TopicMapImpl; import org.wandora.utils.IObox; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * <p> * WaianaService implements an API used to store and retrieve topic maps via * JSON fragments submitted over HTTP. The service stores topic maps as XTM * files into the directory of service. The API mimics Maiana API * (http://projects.topicmapslab.de/projects/maiana/wiki/API_Controller) * created in Topic Maps Labs (http://www.topicmapslab.de/). * </p> * <p> * Wandora features separate import and export tools that use original Maiana API, * that can be used to import and export topic maps into Waiana too. These import * and export tools locate in the <b>org.wandora.application.tools.maiana</b> package. * </p> * * @author akivela */ public class WaianaService extends AbstractTopicWebApp { private WaianaStorage storage = null; private boolean allowURLParameterUsage = true; @Override public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException { /* The default actionParamKey is "action" which conflicts with operation of this action. The actionParamKey can still be set in module initialisation parameters if needed. For usual bundle operations this action will be made the default action so action param is not needed. */ actionParamKey=null; storage = new WaianaStorage(); try { Object basePath = settings.get("basePath"); if(basePath != null) storage.setBasePath(basePath.toString().trim()); Object topicMapsPath = settings.get("topicMapsPath"); if(topicMapsPath != null) storage.setTopicMapsPath(topicMapsPath.toString().trim()); Object storageFilename = settings.get("storageFilename"); if(storageFilename != null) storage.setStorageFilename(storageFilename.toString().trim()); Object skipRightsManagement = settings.get("skipRightsManagement"); if(skipRightsManagement != null) storage.setSkipRightsManagement(Boolean.parseBoolean(skipRightsManagement.toString().trim())); Object blockAllWrites = settings.get("blockAllWrites"); if(blockAllWrites != null) storage.setBlockAllWrites(Boolean.parseBoolean(blockAllWrites.toString().trim())); Object saveAlwaysAfterChange = settings.get("saveAlwaysAfterChange"); if(saveAlwaysAfterChange != null) storage.setSaveAlwaysAfterChange(Boolean.parseBoolean(saveAlwaysAfterChange.toString().trim())); Object keepDeletedFiles = settings.get("keepDeletedFiles"); if(keepDeletedFiles != null) storage.setKeepDeletedFiles(Boolean.parseBoolean(keepDeletedFiles.toString().trim())); } catch(Exception e) {}; storage.loadData(); super.init(manager, settings); } @Override public void stop(ModuleManager manager) { storage.saveData(); super.stop(manager); } @Override public void start(ModuleManager manager) throws ModuleException { super.start(manager); } @Override public Collection<Module> getDependencies(ModuleManager manager) throws ModuleException { Collection<Module> deps=super.getDependencies(manager); requireLogging(manager, deps); return deps; } @Override public boolean handleAction(HttpServletRequest request, HttpServletResponse response, ModulesServlet.HttpMethod _method, String _action, User user) throws ServletException, IOException, ActionException { boolean success = true; JSONObject responseJSON = new JSONObject(); try { if(storage != null) { JSONObject requestJSON = getRequestJSON(request); if(requestJSON != null) { String api_key = WaianaAPIRequestUtils.getAPIKey(requestJSON); String command = WaianaAPIRequestUtils.getCommand(requestJSON); if("show_local_file_list".equalsIgnoreCase(command) || "show_topic_map_list".equalsIgnoreCase(command) || "show_local_topic_map_list".equalsIgnoreCase(command)) { responseJSON = storage.getIndex(); } else if("download_topic_map".equalsIgnoreCase(command) || "download_local_file".equalsIgnoreCase(command)) { responseJSON = storage.getTopicMap(user, WaianaAPIRequestUtils.getShortName(requestJSON)); } else if("create_local_file".equalsIgnoreCase(command) || "create_topic_map".equalsIgnoreCase(command) || "update_local_file".equalsIgnoreCase(command) || "update_topic_map".equalsIgnoreCase(command)) { String data = WaianaAPIRequestUtils.getData(requestJSON); String shortName = WaianaAPIRequestUtils.getShortName(requestJSON); String name = WaianaAPIRequestUtils.getName(requestJSON); boolean isPublic = WaianaAPIRequestUtils.getIsPublic(requestJSON); boolean isDownloadable = WaianaAPIRequestUtils.getIsDownloadable(requestJSON); boolean isEditable = WaianaAPIRequestUtils.getIsEditable(requestJSON); boolean isSchema = WaianaAPIRequestUtils.getIsSchema(requestJSON); responseJSON = storage.putTopicMap(user, name, shortName, isPublic, isDownloadable, isEditable, isSchema, data, request.getRequestURL()); } else if("delete_local_file".equalsIgnoreCase(command) || "delete_topic_map".equalsIgnoreCase(command)) { responseJSON = storage.deleteTopicMap(user, WaianaAPIRequestUtils.getShortName(requestJSON)); } else { responseJSON = createReply(1, "Illegal command value '"+command+"' given in request JSON."); } } // The request has no JSON data or the JSON has no command. else if(allowURLParameterUsage) { String apiKey = request.getParameter("apiKey"); String command = request.getParameter("command"); if(command != null && command.length() > 0) { if("show_local_file_list".equalsIgnoreCase(command) || "show_topic_map_list".equalsIgnoreCase(command) || "show_local_topic_map_list".equalsIgnoreCase(command)) { responseJSON = storage.getIndex(); } else if("download_topic_map".equalsIgnoreCase(command) || "download_local_file".equalsIgnoreCase(command)) { String shortName = request.getParameter("shortName"); responseJSON = storage.getTopicMap(user, shortName); } else if("stream".equalsIgnoreCase(command)) { String shortName = request.getParameter("shortName"); String format = request.getParameter("format"); return storage.streamTopicMap(response, user, shortName, format); } else if("create_local_file".equalsIgnoreCase(command) || "create_topic_map".equalsIgnoreCase(command) || "update_local_file".equalsIgnoreCase(command) || "update_topic_map".equalsIgnoreCase(command)) { String data = request.getParameter("data"); String shortName = request.getParameter("shortName"); String name = request.getParameter("name"); boolean isPublic = false; if(request.getParameter("isPublic") != null) { isPublic = Boolean.parseBoolean(request.getParameter("isPublic")); } boolean isDownloadable = false; if(request.getParameter("isDownloadable") != null) { isDownloadable = Boolean.parseBoolean(request.getParameter("isDownloadable")); } boolean isEditable = false; if(request.getParameter("isEditable") != null) { isEditable = Boolean.parseBoolean(request.getParameter("isEditable")); } boolean isSchema = false; if(request.getParameter("isSchema") != null) { Boolean.parseBoolean(request.getParameter("isSchema")); } responseJSON = storage.putTopicMap(user, name, shortName, isPublic, isDownloadable, isEditable, isSchema, data, request.getRequestURL()); } else if("delete_local_file".equalsIgnoreCase(command) || "delete_topic_map".equalsIgnoreCase(command)) { String shortName = request.getParameter("shortName"); responseJSON = storage.deleteTopicMap(user, shortName); } else { responseJSON = createReply(1, "Illegal command value '"+command+"' given in URL parameter."); } } else { responseJSON = createReply(1, "Invalid command parameter value '"+command+"' found."); } } else { responseJSON = createReply(1, "Can't find required parameters in the request."); } } } catch(Exception e) { responseJSON = createReply(1, "Exception '"+e.toString()+"' occurred while processing the maiana api request."); e.printStackTrace(); } if(responseJSON == null || !responseJSON.has("code")) { responseJSON = createReply(1, "The response JSON has not been set successfully."); } response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); PrintWriter writer = new PrintWriter(new OutputStreamWriter(response.getOutputStream(),"UTF-8")); writer.print(responseJSON.toString()); writer.flush(); writer.close(); return success; } // ------------------------------------------------------------------------- protected JSONObject getRequestJSON(HttpServletRequest request) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8")); StringBuilder sb = new StringBuilder(); String str; while ((str = in.readLine()) != null) { sb.append(str); } in.close(); // System.out.println("FOUND:\n"+sb.toString()); if(sb.length() > 0) { try { JSONObject requestJSON = new JSONObject(sb.toString()); // System.out.println("requestJSON:" +requestJSON.toString()); return requestJSON; } catch (JSONException ex) { // This exception is not logged because the user may user URL // parameters instead of JSON data. ex.printStackTrace(); } } return null; } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- protected static class WaianaAPIRequestUtils { public static String getAPIKey(JSONObject json) { return getStringSafely(json, "api_key"); } public static String getData(JSONObject json) { return getStringSafely(json, "data"); } public static JSONObject getParameters(JSONObject json) { try { return json.getJSONObject("parameters"); } catch(Exception e) { e.printStackTrace(); } return null; } public static String getCommand(JSONObject json) { JSONObject parameters = getParameters(json); return getStringSafely(parameters, "command"); } public static String getEndpointType(JSONObject json) { JSONObject parameters = getParameters(json); return getStringSafely(parameters, "endpoint_type"); } public static String getShortName(JSONObject json) { JSONObject parameters = getParameters(json); return getStringSafely(parameters, "short_name"); } public static String getName(JSONObject json) { JSONObject parameters = getParameters(json); return getStringSafely(parameters, "name"); } public static boolean getIsPublic(JSONObject json) { JSONObject parameters = getParameters(json); return getBooleanSafely(parameters, "is_public", false); } public static boolean getIsDownloadable(JSONObject json) { JSONObject parameters = getParameters(json); return getBooleanSafely(parameters, "is_downloadable", false); } public static boolean getIsEditable(JSONObject json) { JSONObject parameters = getParameters(json); return getBooleanSafely(parameters, "is_editable", false); } public static boolean getIsSchema(JSONObject json) { JSONObject parameters = getParameters(json); return getBooleanSafely(parameters, "is_schema", false); } public static String getStringSafely(JSONObject json, String key) { try { if(json != null && json.has(key)) { return json.getString(key); } } catch(Exception e) { e.printStackTrace(); } return null; } public static boolean getBooleanSafely(JSONObject json, String key, boolean defaultValue) { try { if(json != null && json.has(key)) { return json.getBoolean(key); } } catch(Exception e) { e.printStackTrace(); } return defaultValue; } } // ------------------------------------------------------------------------- // ------------------------------------------------------- WaianaStorage --- // ------------------------------------------------------------------------- public class WaianaStorage { private boolean blockAllWrites = false; private boolean skipRightsManagement = false; private boolean saveAlwaysAfterChange = true; private boolean keepDeletedFiles = false; private String basePath = ""; private String topicMapsPath = "topicmaps"; private String storageFilename = "topicmaps_data.json"; private HashMap<String, JSONObject> data = null; public WaianaStorage() { data = new LinkedHashMap<>(); } // ------------------------------------------------------------ SETS --- public void setSkipRightsManagement(boolean b) { skipRightsManagement = b; } public void setBlockAllWrites(boolean b) { blockAllWrites = b; } public void setStorageFilename(String s) { if(s != null) storageFilename = s; } public void setBasePath(String b) { if(b != null) basePath = b; } public void setSaveAlwaysAfterChange(boolean b) { saveAlwaysAfterChange = b; } public void setKeepDeletedFiles(boolean b) { keepDeletedFiles = b; } public void setTopicMapsPath(String l) { if(l != null) topicMapsPath = l; } // --------------------------------------------------------------------- public void loadData() { try { String inStr = readFile(basePath+"/"+storageFilename); if(inStr != null) { JSONArray dataArray = new JSONArray(inStr); for(int i=0; i<dataArray.length(); i++) { JSONObject d = dataArray.getJSONObject(i); if(!d.has("short_name")) { d.put("short_name", "temporal-"+i); } data.put(d.getString("short_name"), d); } } } catch(Exception e) { e.printStackTrace(); } } public void saveData() { try { JSONArray topicmapArray = new JSONArray(); for(JSONObject d : data.values()) { topicmapArray.put(d); } String outStr = topicmapArray.toString(); IObox.saveFile(basePath+"/"+storageFilename, outStr); } catch (Exception ex) { ex.printStackTrace(); } } // --------------------------------------------------------------------- public JSONObject putTopicMap(User user, String name, String shortName, boolean isPublic, boolean isDownloadable, boolean isEditable, boolean isSchema, String topicMapData, StringBuffer url) { shortName = sanitizeShortName(shortName); JSONObject dataEntry = data.get(shortName); if(hasWriteRights(user, dataEntry)) { try { if(dataEntry == null) { dataEntry = new JSONObject(); dataEntry.put("creation_date", getDateString()); } dataEntry.put("name", name); dataEntry.put("short_name", shortName); dataEntry.put("is_public", isPublic); dataEntry.put("is_downloadable", isDownloadable); dataEntry.put("is_editable", isEditable); dataEntry.put("is_schema", isSchema); dataEntry.put("edit_date", getDateString()); if(user != null) dataEntry.put("owner", user.getUserName()); writeFile(basePath+"/"+topicMapsPath+"/"+shortName+".xtm", topicMapData); } catch (IOException ex) { return createReply(1, "Exception '"+ex.getMessage()+"' occurred while saving topic map '"+shortName+"' data."); } catch(JSONException jex) { return createReply(1, "Exception '"+jex.getMessage()+"' occurred while processing input data for '"+shortName+"'."); } data.put(shortName, dataEntry); if(saveAlwaysAfterChange) saveData(); return createReply(0, "Successfully created topic map '"+name+"'", url+"?command=stream&shortName="+shortName); } else { return createReply(1, "Waiana storage already contains a topic map with a short name '"+shortName+"' and you have no sufficient rights to update it."); } } public JSONObject deleteTopicMap(User user, String shortName) { shortName = sanitizeShortName(shortName); JSONObject dataEntry = data.get(shortName); if(dataEntry != null) { if(hasDeleteRights(user, dataEntry)) { data.remove(shortName); if(!keepDeletedFiles) { try { IObox.deleteFile(basePath+"/"+topicMapsPath+"/"+shortName+".xtm"); } catch (Exception ex) { ex.printStackTrace(); } } if(saveAlwaysAfterChange) saveData(); return createReply(0, "Successfully deleted topic map '"+shortName+"'."); } else { return createReply(1, "You have no sufficient rights to delete the topic map with a short name '"+shortName+"'."); } } else { return createReply(1, "Waiana storage doesn't contain topic map with a short name '"+shortName+"'."); } } public JSONObject getTopicMap(User user, String shortName) { shortName = sanitizeShortName(shortName); JSONObject dataEntry = data.get(shortName); if(dataEntry != null) { if(hasReadRights(user, dataEntry)) { JSONObject reply = new JSONObject(); try { reply.put("code", 0); try { String topicMapData = readFile(basePath+"/"+topicMapsPath+"/"+shortName+".xtm"); // System.out.println(topicMapData); reply.put("data", topicMapData); return reply; } catch (IOException ex) { return createReply(1, "Exception '"+ex.getMessage()+"' occurred while loading topic map '"+shortName+"' data."); } } catch(Exception e) { return createReply(1, "Internal exception '"+e.getMessage()+"' occurred while building topic map reply."); } } else { return createReply(1, "You have no sufficient rights to read the topic map with a short name '"+shortName+"'."); } } else { return createReply(1, "Waiana storage doesn't contain topic map with a short name '"+shortName+"'."); } } public boolean streamTopicMap(HttpServletResponse response, User user, String shortName, String format) { shortName = sanitizeShortName(shortName); JSONObject dataEntry = data.get(shortName); if(dataEntry != null) { if(hasReadRights(user, dataEntry)) { try { try { if("jtm".equalsIgnoreCase(format)) { response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.setHeader("Content-Disposition", "filename="+shortName+".jtm" ); OutputStream out = response.getOutputStream(); TopicMap tm = new TopicMapImpl(); tm.importXTM(new FileInputStream(new File(basePath+"/"+topicMapsPath+"/"+shortName+".xtm"))); tm.exportJTM(out); out.close(); return true; } else { response.setContentType("application/xml"); response.setCharacterEncoding("UTF-8"); response.setHeader("Content-Disposition", "filename="+shortName+".xtm" ); OutputStream out = response.getOutputStream(); InputStream in = new FileInputStream(basePath+"/"+topicMapsPath+"/"+shortName+".xtm"); IObox.moveData(in, out); out.close(); return true; } } catch (IOException ex) { writeStringToResponse(response, "Exception '"+ex.getMessage()+"' occurred while loading topic map '"+shortName+"' data."); } } catch(Exception e) { writeStringToResponse(response, "Internal exception '"+e.getMessage()+"' occurred while building topic map reply."); } } else { writeStringToResponse(response, "You have no sufficient rights to read the topic map with a short name '"+shortName+"'."); } } else { writeStringToResponse(response, "Waiana storage doesn't contain topic map with a short name '"+shortName+"'."); } return false; } public JSONObject getIndex() { JSONObject indexReply = new JSONObject(); try { indexReply.put("code", 0); JSONArray allDatas = new JSONArray(); for(JSONObject d : data.values()) { allDatas.put(d); } indexReply.put("data", allDatas); return indexReply; } catch(Exception e) { return createReply(1, "Internal exception '"+e.getMessage()+"' occurred while building index."); } } // --------------------------------------------------------------------- public boolean hasWriteRights(User user, JSONObject dataEntry) { if(blockAllWrites) return false; if(skipRightsManagement) return true; if(dataEntry == null) return true; if(dataEntry.has("is_editable")) { try { if(dataEntry.has("is_editable")) { boolean isEditable = dataEntry.getBoolean("is_editable"); if(isEditable) return true; } } catch (JSONException ex) { } } if(dataEntry.has("owner")) { if(user == null) return false; else { try { if(dataEntry.has("owner")) { if(dataEntry.getString("owner").equals(user.getUserName())) { return true; } } } catch (JSONException ex) { } } } return false; } public boolean hasReadRights(User user, JSONObject dataEntry) { if(skipRightsManagement) return true; if(dataEntry.has("is_public")) { try { if(dataEntry.has("is_public")) { boolean isPublic = dataEntry.getBoolean("is_public"); if(isPublic) return true; } } catch (JSONException ex) {} } if(dataEntry.has("owner")) { if(user == null) return false; else { try { if(dataEntry.has("owner")) { if(dataEntry.getString("owner").equals(user.getUserName())) { return true; } } } catch (JSONException ex) {} } } return false; } public boolean hasDeleteRights(User user, JSONObject dataEntry) { if(blockAllWrites) return false; if(dataEntry == null) return false; if(skipRightsManagement) return true; if(dataEntry.has("is_editable")) { try { if(dataEntry.has("is_editable")) { boolean isEditable = dataEntry.getBoolean("is_editable"); if(isEditable) return true; } } catch (JSONException ex) { } } if(dataEntry.has("owner")) { if(user == null) return true; else { try { if(dataEntry.has("owner")) { if(dataEntry.getString("owner").equals(user.getUserName())) { return true; } } } catch (JSONException ex) { } } } return false; } // --------------------------------------------------------------------- private String sanitizeShortName(String sn) { if(sn == null || sn.length() == 0) sn = "temp-"+System.currentTimeMillis(); 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(); } } // --------------------------------------------------------------------- protected static JSONObject createReply(int code, String msg, String data) { JSONObject reply = new JSONObject(); try { reply.put("code", code); reply.put("msg", msg); reply.put("data", data); } catch(Exception e) { e.printStackTrace(); } return reply; } protected static JSONObject createReply(int code, String msg) { JSONObject reply = new JSONObject(); try { reply.put("code", code); reply.put("msg", msg); } catch(Exception e) { e.printStackTrace(); } return reply; } protected static DateFormat df = new SimpleDateFormat("y-M-d H:m"); protected static String getDateString() { return df.format(new Date(System.currentTimeMillis())); } protected static void writeStringToResponse(HttpServletResponse response, String str) { try { response.setContentType("application/text"); response.setCharacterEncoding("UTF-8"); OutputStreamWriter out = new OutputStreamWriter(response.getOutputStream(), "UTF-8"); out.write(str); out.flush(); out.close(); } catch(Exception e) { e.printStackTrace(); } } protected static void writeFile(String fname, String data) throws IOException { File pf = new File(fname); if (pf.exists()) { pf.delete(); System.out.println("Deleting previously existing file '" + fname + "' before save file operation!"); } PrintWriter writer=new PrintWriter(new OutputStreamWriter(new FileOutputStream(fname),"UTF-8")); writer.print(data); writer.flush(); writer.close(); System.out.println("Saving a file '" + fname + "'"); } static String readFile(String path) throws IOException { byte[] encoded = Files.readAllBytes(Paths.get(path)); return new String(encoded, "UTF-8"); } }
34,552
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ScreenCastWebApp.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/modulesserver/ScreenCastWebApp.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.modulesserver; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.Rectangle; import java.awt.Robot; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.OutputStream; import java.util.Collection; import java.util.Map; import javax.imageio.ImageIO; import org.wandora.application.Wandora; import org.wandora.modules.Module; import org.wandora.modules.ModuleException; import org.wandora.modules.ModuleManager; import org.wandora.modules.servlet.ActionException; import org.wandora.modules.servlet.ModulesServlet; import org.wandora.modules.usercontrol.User; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * * @author olli */ public class ScreenCastWebApp extends AbstractWebApp { protected String format="jpeg"; @Override public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException { Object o=settings.get("format"); if(o!=null) format=o.toString().trim(); super.init(manager, settings); } @Override public Collection<Module> getDependencies(ModuleManager manager) throws ModuleException { Collection<Module> deps=super.getDependencies(manager); requireLogging(manager, deps); return deps; } @Override public boolean handleAction(HttpServletRequest req, HttpServletResponse resp, ModulesServlet.HttpMethod method, String action, User user) throws ServletException, IOException, ActionException { try { Wandora w = Wandora.getWandora(); GraphicsDevice gd=null; GraphicsConfiguration gc=w.getGraphicsConfiguration(); if(gc!=null) gd=gc.getDevice(); Rectangle rect = new Rectangle(w.getX(), w.getY(), w.getWidth(), w.getHeight()); Robot r = null; if(gd!=null) { r=new Robot(gd); Rectangle bounds=gc.getBounds(); rect = new Rectangle(rect.x-bounds.x, rect.y-bounds.y, rect.width, rect.height); } else r=new Robot(); BufferedImage img = r.createScreenCapture(rect); OutputStream out = resp.getOutputStream(); resp.setContentType("image/"+format); ImageIO.write(img,format,out); out.close(); return true; } catch(Exception e) { logging.error(e); return false; } } }
3,436
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
WandoraModulesServer.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/modulesserver/WandoraModulesServer.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.modulesserver; import java.io.File; import java.io.IOException; import java.util.ArrayList; import org.apache.commons.logging.Log; import org.apache.commons.logging.impl.Jdk14Logger; import org.eclipse.jetty.http.MimeTypes; import org.eclipse.jetty.server.ConnectionFactory; import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.HttpConfiguration; import org.eclipse.jetty.server.HttpConnectionFactory; import org.eclipse.jetty.server.SecureRequestCustomizer; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.server.SslConnectionFactory; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.wandora.application.Wandora; import org.wandora.application.gui.UIBox; import org.wandora.modules.LoggingModule; import org.wandora.utils.Options; /** * * @author olli */ public class WandoraModulesServer { private static final int defaultPort=8898; public static final String OPTION_AUTOSTART="httpmodulesserver.autostart"; public static final String OPTION_PORT="httpmodulesserver.port"; public static final String OPTION_LOCALONLY="httpmodulesserver.localonly"; public static final String OPTION_SERVERPATH="httpmodulesserver.serverpath"; public static final String OPTION_USESSL="httpmodulesserver.usessl"; public static final String OPTION_KEYSTORE_FILE="httpmodulesserver.keystore.file"; public static final String OPTION_KEYSTORE_PASSWORD="httpmodulesserver.keystore.password"; public static final String OPTION_LOGLEVEL="httpmodulesserver.loglevel"; private Wandora wandora; private int port; private boolean useSSL; private String keystoreFile; private String keystorePassword; private String serverPath; private boolean localOnly=true; private boolean autoStart=false; private javax.swing.JButton statusButton; private javax.swing.Icon onIcon; private javax.swing.Icon offIcon; private javax.swing.Icon hitIcon; private Thread iconThread; private long lastHit; protected Log rootLog; protected Log log; protected int logLevel=LoggingModule.SubLog.LOG_WARN; protected Server jettyServer; protected ServerConnector serverConnector; protected MimeTypes mimeTypes; protected WandoraModuleManager moduleManager; protected WandoraServletModule servletModule; public WandoraModulesServer(Wandora wandora){ this.wandora = wandora; jettyServer = new Server(); rootLog = new Jdk14Logger("ModulesServlet"); log = rootLog; Options options = wandora.getOptions(); readOptions(options); mimeTypes = new MimeTypes(); initModuleManager(); readBundleDirectories(); } public void initModuleManager() { moduleManager = new WandoraModuleManager(this); moduleManager.setLogging(log); moduleManager.setVariable("home", getServerPath()); log.info("Reading modules server base config"); File f = new File(getServerPath(),"baseconfig.xml"); if(f.exists()) { try { moduleManager.readXMLOptionsFile(f.getCanonicalPath()); } catch(IOException ioe){ log.error("Unable to read base config for modules server",ioe); } } else log.warn("baseconfig.xml not found for modules server"); servletModule=new WandoraServletModule(this); moduleManager.addModule(servletModule,"rootServlet"); moduleManager.addModule(new JettyModule(jettyServer),"jetty"); } public void readBundleDirectories(){ log.info("Scanning bundles"); try { moduleManager.readBundles(); moduleManager.initAllModules(); } catch(Exception e){ log.error("Unable to read bundles", e); } } public Server getJetty() { return jettyServer; } public Wandora getWandora() { return wandora; } public ArrayList<ModulesWebApp> getWebApps() { return moduleManager.findModulesRecursive(ModulesWebApp.class); } public void readOptions(Options options) { localOnly =! options.isFalse(OPTION_LOCALONLY); autoStart = options.isTrue(OPTION_AUTOSTART); port = options.getInt(OPTION_PORT, defaultPort); serverPath = options.get(OPTION_SERVERPATH, "resources/server/"); try { serverPath = new File(serverPath).getCanonicalPath(); } catch (IOException ex) { log.warn("Couldn't resolve canonical path for server",ex); } useSSL = options.isTrue(OPTION_USESSL); keystoreFile = options.get(OPTION_KEYSTORE_FILE, "conf/keystore/keystore"); try { keystoreFile = new File(keystoreFile).getCanonicalPath(); } catch (IOException ex) { log.warn("Couldn't resolve canonical file for keystore",ex); } keystorePassword = options.get(OPTION_KEYSTORE_PASSWORD, "wandora"); setLogLevel(options.getInt(OPTION_LOGLEVEL, LoggingModule.SubLog.LOG_WARN)); } public void writeOptions(Options options){ options.put(OPTION_LOCALONLY, ""+localOnly); options.put(OPTION_AUTOSTART, ""+autoStart); options.put(OPTION_PORT, ""+port); options.put(OPTION_SERVERPATH, serverPath); options.put(OPTION_USESSL, ""+useSSL); options.put(OPTION_KEYSTORE_FILE, ""+keystoreFile); options.put(OPTION_KEYSTORE_PASSWORD, ""+keystorePassword); options.put(OPTION_LOGLEVEL, ""+logLevel); } private void updateStatusIcon(){ if(jettyServer!=null && jettyServer.isRunning()) { statusButton.setIcon(this.onIcon); statusButton.setToolTipText("Http server is running. Click to stop."); } else { statusButton.setIcon(this.offIcon); statusButton.setToolTipText("Http server is not running. Click to start."); } } public void setStatusComponent(javax.swing.JButton button,String onIcon,String offIcon,String hitIcon){ this.statusButton = button; this.onIcon = UIBox.getIcon(onIcon); this.offIcon = UIBox.getIcon(offIcon); this.hitIcon = UIBox.getIcon(hitIcon); updateStatusIcon(); } public boolean isRunning(){ return jettyServer != null && jettyServer.isRunning(); } public void start() { try { if(useSSL) { SslContextFactory.Server sslCtxFactory = new SslContextFactory.Server(); sslCtxFactory.setKeyStorePath(keystoreFile); sslCtxFactory.setKeyStorePassword(keystorePassword); SslConnectionFactory https = new SslConnectionFactory(sslCtxFactory, "http/1.1"); HttpConfiguration httpConfiguration = new HttpConfiguration(); httpConfiguration.setSecurePort(port); httpConfiguration.setSecureScheme("https"); httpConfiguration.addCustomizer(new SecureRequestCustomizer()); ConnectionFactory http = new HttpConnectionFactory(httpConfiguration); serverConnector = new ServerConnector(jettyServer, https, http); serverConnector.setPort(port); } else { HttpConfiguration httpConfiguration = new HttpConfiguration(); ConnectionFactory http = new HttpConnectionFactory(httpConfiguration); serverConnector = new ServerConnector(jettyServer, http); serverConnector.setPort(port); } jettyServer.setConnectors(new Connector[] { serverConnector }); jettyServer.setHandler(servletModule.getJettyHandler()); moduleManager.autostartModules(); jettyServer.start(); if(statusButton!=null) { updateStatusIcon(); iconThread=new IconThread(); iconThread.start(); } } catch(Exception e){ wandora.handleError(e); } } public void stopServer(){ try{ if(jettyServer!=null) { jettyServer.stop(); jettyServer.setHandler(null); if(serverConnector != null) { jettyServer.removeConnector(serverConnector); serverConnector.close(); serverConnector.stop(); } jettyServer.setConnectors(null); } moduleManager.stopAllModules(); while(iconThread!=null && iconThread.isAlive()){ iconThread.interrupt(); try{ iconThread.join(); }catch(InterruptedException ie){} } if(statusButton!=null) updateStatusIcon(); iconThread=null; }catch(Exception e){ wandora.handleError(e); } } public void setPort(int p) { port=p; } public int getPort() { return port; } public void setUseSSL(boolean b) { useSSL=b; } public boolean isUseSSL() { return useSSL; } public void setKeystoreFile(String filename) { keystoreFile = filename; } public String getKeystoreFile() { return keystoreFile; } public void setKeystorePassword(String password) { keystorePassword = password; } public String getKeystorePassword() { return keystorePassword; } public void setServerPath(String p) { serverPath=p; } public String getServerPath() { return serverPath; } public boolean isLocalOnly() { return localOnly; } public void setLocalOnly(boolean b) { localOnly=b; } public boolean isAutoStart() { return autoStart; } public void setAutoStart(boolean b) { autoStart=b; } public String getServletURL() { return servletModule.getServletURL(); } public void setLogLevel(int l) { logLevel=l; if(logLevel>LoggingModule.SubLog.LOG_TRACE) log=new LoggingModule.SubLog("", rootLog, logLevel); } public int getLogLevel() { return logLevel; } public static int resolvePort(Wandora wandora){ return wandora.getOptions().getInt(OPTION_PORT,defaultPort); } // ------------------------------------------------------------------------- public class IconThread extends Thread { public static final int hitTime=1000; @Override public void run(){ while(jettyServer!=null && jettyServer.isRunning()){ synchronized(this){ long time=System.currentTimeMillis(); if(time-lastHit<hitTime) statusButton.setIcon(hitIcon); else statusButton.setIcon(onIcon); time=hitTime-(time-lastHit); try{ if(time<=0) this.wait(); else this.wait(time); } catch(InterruptedException ie){} } } } } }
12,505
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
GraphMLWebApp.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/modulesserver/GraphMLWebApp.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.modulesserver; import java.io.IOException; import java.io.OutputStream; import java.util.Map; import org.wandora.application.tools.exporters.GraphMLExport; import org.wandora.modules.ModuleException; import org.wandora.modules.ModuleManager; import org.wandora.modules.servlet.ActionException; import org.wandora.modules.servlet.ModulesServlet; import org.wandora.modules.usercontrol.User; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.memory.TopicMapImpl; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * * @author olli */ public class GraphMLWebApp extends AbstractTopicWebApp { protected boolean deepCopy = false; @Override public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException { Object o=settings.get("deepCopy"); if(o!=null) deepCopy=Boolean.parseBoolean(o.toString().trim()); super.init(manager, settings); } @Override public boolean handleAction(HttpServletRequest req, HttpServletResponse resp, ModulesServlet.HttpMethod method, String action, User user) throws ServletException, IOException, ActionException { try { String query=req.getParameter(topicRequestKey); if(query!=null) query=query.trim(); if(query!=null && query.length()==0) query=null; // resolveTopic will try to get the open topic in Wandora if query==null Topic topic = resolveTopic(query); if(topic != null) { OutputStream out = resp.getOutputStream(); resp.setContentType("text/xml"); resp.setCharacterEncoding("ISO-8859-1"); TopicMap tm = new TopicMapImpl(); tm.copyTopicIn(topic, deepCopy); tm.copyTopicAssociationsIn(topic); GraphMLExport graphMLExport = new GraphMLExport(); graphMLExport.exportGraphML(out, tm, "wandora_server_"+System.currentTimeMillis(), null); out.close(); return true; } else return false; } catch(Exception e) { logging.error(e); return false; } } }
3,223
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AbstractWebApp.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/modulesserver/AbstractWebApp.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.modulesserver; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Collection; import java.util.Map; import org.wandora.modules.Module; import org.wandora.modules.ModuleException; import org.wandora.modules.ModuleManager; import org.wandora.modules.servlet.AbstractAction; /** * * * @author olli */ public abstract class AbstractWebApp extends AbstractAction implements ModulesWebApp { protected String webAppName; protected String appStartPage; protected String topicRequestKey="topic"; @Override public Collection<Module> getDependencies(ModuleManager manager) throws ModuleException { Collection<Module> deps=super.getDependencies(manager); requireLogging(manager, deps); return deps; } @Override public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException { // NOTE: ViewTopicWebApp does not extend this so all modifications here // should probably be done there as well. Object o=settings.get("webAppName"); if(o!=null) webAppName=o.toString().trim(); else { ModuleManager.ModuleSettings ms=manager.getModuleSettings(this); if(ms!=null && ms.name!=null) webAppName=ms.name; else webAppName="Unnamed Webapp"; } o=settings.get("appStartPage"); if(o!=null) appStartPage=o.toString().trim(); super.init(manager, settings); } @Override public void start(ModuleManager manager) throws ModuleException { super.start(manager); // NOTE: ViewTopicWebApp does not extend this so all modifications here // should probably be done there as well. if(appStartPage==null){ if(isDefaultAction){ appStartPage=servletModule.getServletURL(); } else if(!handledActions.isEmpty()){ String action=handledActions.iterator().next(); appStartPage=servletModule.getServletURL(); if(appStartPage!=null){ try { appStartPage+="?"+actionParamKey+"="+URLEncoder.encode(action, "UTF-8"); } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex); // shouldn't happen } } } } } @Override public String getAppName() { return webAppName; } @Override public String getAppStartPage() { return appStartPage; } @Override public String getAppTopicPage(String si) { // NOTE: ViewTopicWebApp does not extend this so all modifications here // should probably be done there as well. if(appStartPage==null) return null; try{ String page=appStartPage; if(page.indexOf("?")<0) page+="?"; else page+="&"; return page+topicRequestKey+"="+URLEncoder.encode(si, "UTF-8"); }catch(UnsupportedEncodingException uee){ throw new RuntimeException(uee); // shouldn't happen } } }
4,055
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
IIIFWebApp.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/modulesserver/IIIFWebApp.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.modulesserver; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.InvocationTargetException; import java.util.Map; import org.wandora.application.Wandora; import org.wandora.application.contexts.LayeredTopicContext; import org.wandora.application.tools.exporters.iiifexport.IIIFBuilder; import org.wandora.application.tools.exporters.iiifexport.IIIFExport; import org.wandora.application.tools.exporters.iiifexport.Manifest; import org.wandora.application.tools.exporters.iiifexport.SelectionInstancesIIIFBuilder; import org.wandora.modules.ModuleException; import org.wandora.modules.ModuleManager; import org.wandora.modules.servlet.ActionException; import org.wandora.modules.servlet.ModulesServlet; import org.wandora.modules.usercontrol.User; import org.wandora.topicmap.Topic; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * * @author olli */ public class IIIFWebApp extends AbstractTopicWebApp { protected IIIFBuilder builder; protected boolean prettyPrint=true; @Override public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException { Object o=settings.get("iiifBuilder"); if(o!=null) o=SelectionInstancesIIIFBuilder.class.getName(); try{ builder=(IIIFBuilder)Class.forName(o.toString()).getDeclaredConstructor().newInstance(); } catch (ClassNotFoundException | IllegalAccessException | InstantiationException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e){ logging.error(e); } o=settings.get("prettyPrint"); if(o!=null) prettyPrint=Boolean.parseBoolean(o.toString()); super.init(manager, settings); } @Override public boolean handleAction(HttpServletRequest req, HttpServletResponse resp, ModulesServlet.HttpMethod method, String action, User user) throws ServletException, IOException, ActionException { try { String query=req.getParameter(topicRequestKey); if(query!=null) query=query.trim(); if(query!=null && query.length()==0) query=null; // resolveTopic will try to get the open topic in Wandora if query==null Topic topic = resolveTopic(query); if(topic != null) { LayeredTopicContext context=new LayeredTopicContext(); context.setContextSource(topic); // the export tool itself is only needed for logging Manifest m=builder.buildIIIF(Wandora.getWandora(), context, new IIIFExport(){ private static final long serialVersionUID = 1L; @Override public void log(Error e) { logging.error(e); } @Override public void log(Exception e) { logging.error(e); } @Override public void log(String message, Exception e) { logging.error(message, e); } @Override public void log(String message) { logging.info(message); } @Override public void hlog(String message) { logging.info(message); } }); if(m==null) return false; StringBuilder sb=new StringBuilder(); m.toJsonLD().outputJson(sb, prettyPrint?"":null ); OutputStream out = resp.getOutputStream(); resp.setContentType("application/ld+json"); resp.setCharacterEncoding("UTF-8"); out.write(sb.toString().getBytes("UTF-8")); out.close(); return true; } else return false; } catch(Exception e) { logging.error(e); return false; } } }
5,190
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ModuleBundle.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/modulesserver/ModuleBundle.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.modulesserver; import java.util.ArrayList; import java.util.Collection; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.wandora.modules.Module; import org.wandora.modules.ScopedModuleManager; /** * An extension of the ScopedModuleManager, meant to represent a * bundle of modules. Currently the only added feature is reading the bundle * name from an element named bundleName (note, not initialisation parameter but * an actual &lt;bundleName> element). * * @author olli */ public class ModuleBundle extends ScopedModuleManager { protected String bundleName; public String getBundleName(){ return bundleName; } public void setBundleName(String s){ bundleName=s; } @Override public Collection<Module> parseXMLConfigElement(Node doc, String source) { try{ ArrayList<Module> ret=new ArrayList<Module>(); XPath xpath=XPathFactory.newInstance().newXPath(); NodeList nl=(NodeList)xpath.evaluate("//bundleName",doc,XPathConstants.NODESET); if(nl.getLength()>0){ Element e2=(Element)nl.item(0); String s=e2.getTextContent().trim(); if(s.length()>0) setBundleName(s); } return super.parseXMLConfigElement(doc, source); }catch(Exception ex){ if(log!=null) log.error("Error reading options file", ex); return null; } } }
2,458
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
BrowserPluginService.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/modulesserver/BrowserPluginService.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.modulesserver; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Collection; import java.util.Map; import org.wandora.application.Wandora; import org.wandora.application.tools.browserextractors.BrowserExtractRequest; import org.wandora.application.tools.browserextractors.BrowserExtractorManager; import org.wandora.application.tools.browserextractors.BrowserPluginExtractor; import org.wandora.modules.Module; import org.wandora.modules.ModuleException; import org.wandora.modules.ModuleManager; import org.wandora.modules.servlet.AbstractAction; import org.wandora.modules.servlet.ActionException; import org.wandora.modules.servlet.ModulesServlet; import org.wandora.modules.usercontrol.User; import org.wandora.utils.XMLbox; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * * @author olli */ public class BrowserPluginService extends AbstractAction { private BrowserExtractorManager extractorManager; @Override public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException { /* The default actionParamKey is "action" which conflicts with operation of this action. The actionParamKey can still be set in module initialisation parameters if needed. For usual bundle operations this action will be made the default action so action param is not needed. */ actionParamKey=null; super.init(manager, settings); } @Override public void stop(ModuleManager manager) { extractorManager=null; super.stop(manager); } @Override public void start(ModuleManager manager) throws ModuleException { extractorManager=new BrowserExtractorManager(Wandora.getWandora()); super.start(manager); } @Override public Collection<Module> getDependencies(ModuleManager manager) throws ModuleException { Collection<Module> deps=super.getDependencies(manager); requireLogging(manager, deps); return deps; } protected PrintWriter startPluginResponse(HttpServletResponse response,int code,String text){ try{ PrintWriter writer=new PrintWriter(new OutputStreamWriter(response.getOutputStream(),"UTF-8")); writer.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); writer.println("<wandoraplugin>"); writer.println(" <resultcode>"+code+"</resultcode>"); writer.println(" <resulttext>"+text+"</resulttext>"); return writer; } catch(IOException ioe){ logging.error(ioe); return null; } } @Override public boolean handleAction(HttpServletRequest request, HttpServletResponse response, ModulesServlet.HttpMethod _method, String _action, User user) throws ServletException, IOException, ActionException { String content=request.getParameter("content"); String page=request.getParameter("page"); String selectionStart=request.getParameter("selectionStart"); String selectionEnd=request.getParameter("selectionEnd"); String selectionText=request.getParameter("selectionText"); int sStart=-1; int sEnd=-1; try{ if(selectionStart!=null && selectionStart.length()>0) sStart=Integer.parseInt(selectionStart); if(selectionEnd!=null && selectionEnd.length()>0) sEnd=Integer.parseInt(selectionEnd); } catch(NumberFormatException nfe){nfe.printStackTrace();} String action=request.getParameter("action"); String app=request.getParameter("application"); if(action==null || action.length()==0) action="doextract"; if(action.equalsIgnoreCase("getextractors")){ response.setContentType("text/xml"); response.setCharacterEncoding("UTF-8"); PrintWriter writer=startPluginResponse(response,0,"OK"); BrowserExtractRequest extractRequest=new BrowserExtractRequest(page, content, null, app,sStart,sEnd,selectionText); String[] methods=extractorManager.getExtractionMethods(extractRequest); for(int i=0;i<methods.length;i++){ writer.println(" <method>"+methods[i]+"</method>"); } writer.println("</wandoraplugin>"); writer.flush(); return true; } else if(action.equalsIgnoreCase("doextract")){ String method=request.getParameter("method"); if(method!=null && method.length()>0){ String[] methods=method.split(";"); String message=null; for(String m : methods){ BrowserExtractRequest extractRequest=new BrowserExtractRequest(page, content, m, app,sStart,sEnd,selectionText); message=extractorManager.doPluginExtract(extractRequest); if(message!=null && message.startsWith(BrowserPluginExtractor.RETURN_ERROR)){ break; } } response.setContentType("text/xml"); response.setCharacterEncoding("UTF-8"); PrintWriter writer; if(message==null || !message.startsWith(BrowserPluginExtractor.RETURN_ERROR)){ writer=startPluginResponse(response,0,"OK"); if(message!=null){ int ind=message.indexOf(" "); if(ind>0 && ind<10) message=message.substring(ind+1); writer.print("<returnmessage>"); writer.print(XMLbox.cleanForXML(message)); writer.println("</returnmessage>"); } } else{ writer=startPluginResponse(response,3,message); } writer.println("</wandoraplugin>"); writer.flush(); return true; } else{ PrintWriter writer=startPluginResponse(response,2,"No method provided for doextract"); writer.println("</wandoraplugin>"); writer.flush(); return true; } } else{ response.setContentType("text/xml"); response.setCharacterEncoding("UTF-8"); PrintWriter writer=startPluginResponse(response,1,"Invalid action"); writer.println("</wandoraplugin>"); writer.flush(); return true; } } }
7,558
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AbstractTopicWebApp.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/modulesserver/AbstractTopicWebApp.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.modulesserver; import java.util.Collection; import org.wandora.application.Wandora; import org.wandora.application.gui.tree.TopicTree; import org.wandora.modules.Module; import org.wandora.modules.ModuleException; import org.wandora.modules.ModuleManager; import org.wandora.modules.topicmap.TopicMapManager; import org.wandora.modules.topicmap.ViewTopicAction; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public abstract class AbstractTopicWebApp extends AbstractWebApp { protected TopicMapManager tmManager; public Topic resolveTopic(String query){ TopicMap tm = tmManager.getTopicMap(); if(tm==null) return null; try{ Topic t=null; if(query!=null) t=ViewTopicAction.getTopic(query, tm); else { Wandora wandora=Wandora.getWandora(); if(wandora != null) { t = wandora.getOpenTopic(); if(t == null) { TopicTree tree = wandora.getCurrentTopicTree(); if(tree != null) { t = tree.getSelection(); } if(t == null) { t = tm.getTopic(TMBox.WANDORACLASS_SI); } } } } return t; }catch(TopicMapException tme){ return null; } } @Override public void start(ModuleManager manager) throws ModuleException { tmManager=manager.findModule(this,TopicMapManager.class); super.start(manager); } @Override public void stop(ModuleManager manager) { tmManager=null; super.stop(manager); } @Override public Collection<Module> getDependencies(ModuleManager manager) throws ModuleException { Collection<Module> deps=super.getDependencies(manager); manager.requireModule(this,TopicMapManager.class, deps); return deps; } }
2,992
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
JettyModule.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/modulesserver/JettyModule.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.modulesserver; import org.eclipse.jetty.server.Server; import org.wandora.modules.AbstractModule; /** * A module that exposes the Jetty server object itself. This can be used * for low level access to the web server. Note that using this makes the module * bundle dependent on Jetty being the servlet container. * * @author olli */ public class JettyModule extends AbstractModule { protected Server jettyServer; public JettyModule(Server jettyServer){ this.jettyServer=jettyServer; } public Server getJetty(){ return jettyServer; } }
1,433
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
JTMWebApp.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/modulesserver/JTMWebApp.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.modulesserver; import java.io.IOException; import java.io.OutputStream; import java.util.Map; import org.wandora.modules.ModuleException; import org.wandora.modules.ModuleManager; import org.wandora.modules.servlet.ActionException; import org.wandora.modules.servlet.ModulesServlet; import org.wandora.modules.usercontrol.User; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.memory.TopicMapImpl; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * * @author olli */ public class JTMWebApp extends AbstractTopicWebApp { protected boolean deepCopy = false; @Override public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException { Object o=settings.get("deepCopy"); if(o!=null) deepCopy=Boolean.parseBoolean(o.toString().trim()); super.init(manager, settings); } @Override public boolean handleAction(HttpServletRequest req, HttpServletResponse resp, ModulesServlet.HttpMethod method, String action, User user) throws ServletException, IOException, ActionException { try { String query=req.getParameter(topicRequestKey); if(query!=null) query=query.trim(); if(query!=null && query.length()==0) query=null; // resolveTopic will try to get the open topic in Wandora if query==null Topic topic = resolveTopic(query); if(topic != null) { OutputStream out = resp.getOutputStream(); resp.setContentType("application/json"); resp.setCharacterEncoding("UTF-8"); TopicMap tmOut = new TopicMapImpl(); tmOut.copyTopicIn(topic, deepCopy); tmOut.copyTopicAssociationsIn(topic); tmOut.exportJTM(out, tmOut); out.close(); return true; } else return false; } catch(Exception e) { logging.error(e); return false; } } }
3,020
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
BSHComponent.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/beanshell/BSHComponent.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * BSHComponent.java * * Created on 21. lokakuuta 2005, 20:44 */ package org.wandora.application.beanshell; /** * * @author olli, akivela */ public interface BSHComponent { public boolean includeComponentIn(String where); public String getTitle(); public String getDescription(); public int getOrder(); public Object makeNew(Object parent); }
1,174
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
BSHLibrary.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/beanshell/BSHLibrary.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * BSHLibrary.java * * Created on 21. lokakuuta 2005, 20:37 * */ package org.wandora.application.beanshell; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.HashMap; import java.util.Map; import java.util.Vector; import org.wandora.utils.Options; import org.wandora.utils.RegexFileChooser; import org.wandora.utils.logger.Log4j2Logger; import bsh.Interpreter; /** * * @author akivela */ public class BSHLibrary extends Vector<BSHComponent> { private static final Log4j2Logger logger = Log4j2Logger.getLogger(BSHLibrary.class); private static final long serialVersionUID = 1L; private Map<String,Vector<BSHComponent>> componentCache = null; private Interpreter interpreter = null; private int limit = 1000; public boolean useCache = true; public BSHLibrary(Options options) { this(options.get("bsh.dir")); } /** Creates a new instance of BSHLibrary */ public BSHLibrary(String bshDir) { componentCache = new HashMap<>(); interpreter = new Interpreter(); readBSHScripts(new File(bshDir)); } public Vector<BSHComponent> getComponentsByName(String name) { if(useCache && componentCache.get(name) != null) { return (Vector<BSHComponent>) componentCache.get(name); } else { Vector<BSHComponent> components = new Vector<>(); for(BSHComponent bshc : this) { if(bshc.includeComponentIn(name)) { components.add(bshc); } } if(useCache) componentCache.put(name, components); return components; } } public void readBSHScripts(File file) { if(!file.exists()) logger.info("Beanshell directory "+file.getAbsolutePath()+" does not exists."); if(!file.isDirectory()) logger.info("Beanshell directory "+file.getAbsolutePath()+" is not a directory."); if(file.exists() && file.isDirectory()) { File[] files=file.listFiles(RegexFileChooser.ioFileFilter(RegexFileChooser.suffixChooser("bsh","Beanshell scripts"))); for(File f: files){ if(f.isFile()) { try{ Reader reader=new InputStreamReader(new FileInputStream(f.getAbsolutePath())); Object bshc=interpreter.eval(reader); reader.close(); if(bshc==null) { logger.info("Beanshell script "+f.getAbsolutePath()+" returned null."); } else if(!(bshc instanceof BSHComponent)){ logger.info("Beanshell script "+f.getAbsolutePath()+" returned object which is not instanceof BSHComponent."); } else{ this.add((BSHComponent)bshc); } }catch(Exception e){ e.printStackTrace(); } } else { if(--limit > 0) { readBSHScripts(f); } } } } } }
4,184
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
CopyTopicAssociationTypes.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/CopyTopicAssociationTypes.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * CopyTopicAssociationTypes.java * * Created on 13. huhtikuuta 2006, 11:59 * */ package org.wandora.application.tools; import org.wandora.application.contexts.AssociationTypeContext; import org.wandora.topicmap.TopicMapException; /** * Copies association type topics of selected topics to clipboard. * * @author akivela */ public class CopyTopicAssociationTypes extends CopyTopics { private static final long serialVersionUID = 1L; public CopyTopicAssociationTypes() throws TopicMapException { } @Override public String getName() { return "Copy topic association types"; } @Override public String getDescription() { return "Tool copies association type topics of selected topics to clipboard."; } @Override public void initialize(int copyOrders, int includeOrders) { super.initialize(copyOrders, includeOrders); setContext( new AssociationTypeContext() ); } }
1,768
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DeleteTopicsWithoutClasses.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/DeleteTopicsWithoutClasses.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * DeleteTopicsWithoutClasses.java * * Created on 12.6.2006, 17:47 * */ package org.wandora.application.tools; import java.util.Collection; import org.wandora.application.WandoraTool; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; /** * * @author akivela */ public class DeleteTopicsWithoutClasses extends DeleteTopics implements WandoraTool { private static final long serialVersionUID = 1L; @Override public String getName() { return "Delete topics without classes"; } @Override public String getDescription() { return "Delete context topics without classes (i.e. types)."; } @Override public boolean shouldDelete(Topic topic) throws TopicMapException { try { if(topic != null && !topic.isRemoved()) { Collection<Topic> types = topic.getTypes(); if(types == null || types.isEmpty()) { if(confirm) { return confirmDelete(topic); } else { return true; } } } } catch(Exception e) { log(e); } return false; } }
2,085
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
CopyTopicInstances.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/CopyTopicInstances.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * CopyTopicInstances.java * * Created on 12. huhtikuuta 2006, 18:50 * */ package org.wandora.application.tools; import org.wandora.application.contexts.InstanceContext; import org.wandora.topicmap.TopicMapException; /** * Copies instance topics of selected topics to clipboard. * * @author akivela */ public class CopyTopicInstances extends CopyTopics { private static final long serialVersionUID = 1L; /** Creates a new instance of CopyTopicInstances */ public CopyTopicInstances() throws TopicMapException { } @Override public String getName() { return "Copy topic instances"; } @Override public String getDescription() { return "Copies instance topics of selected topics to clipboard."; } @Override public void initialize(int copyOrders, int includeOrders) { super.initialize(copyOrders, includeOrders); setContext(new InstanceContext()); } }
1,758
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DeleteTopicsWithoutACI.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/DeleteTopicsWithoutACI.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * DeleteTopicsWithoutACI.java * * Created on 12.7.2006, 14:55 * */ package org.wandora.application.tools; import org.wandora.application.WandoraTool; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; /** * * @author akivela */ public class DeleteTopicsWithoutACI extends DeleteTopics implements WandoraTool { private static final long serialVersionUID = 1L; /** Creates a new instance of DeleteTopicsWithoutACI */ public DeleteTopicsWithoutACI() { } @Override public String getName() { return "Delete topics without associations, instances and classes"; } @Override public String getDescription() { return "Tool is used delete such context topics that have no associations, classes and instances."; } @Override public boolean shouldDelete(Topic topic) throws TopicMapException { try { if(topic != null && !topic.isRemoved()) { if(topic.getAssociations().isEmpty() && topic.getTypes().isEmpty() && topic.getTopicMap().getTopicsOfType(topic).isEmpty()) { if(confirm) { return confirmDelete(topic); } else { return true; } } } } catch(Exception e) { log(e); } return false; } }
2,267
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicHilighter.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/TopicHilighter.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * TopicHilighter.java * * Created on 21. marraskuuta 2005, 21:13 * */ package org.wandora.application.tools; import java.awt.Color; import javax.swing.JColorChooser; 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.gui.table.TopicTable; import org.wandora.topicmap.Topic; /** * * @author akivela */ public class TopicHilighter extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; public static final int ADD_HILIGHT = 1000; public static final int REMOVE_HILIGHT = 1010; public static final int REMOVE_ALL_HILIGHTS = 1020; public int hilightOrders = ADD_HILIGHT; public TopicHilighter(int hilightOrders) { this.hilightOrders = hilightOrders; } public void execute(Wandora wandora, Context context) { try { TopicTable table = (TopicTable) getContext().getContextSource(); switch(hilightOrders) { case ADD_HILIGHT: { Topic[] topics = table.getSelectedTopics(); Color newColor = JColorChooser.showDialog( wandora, "Choose topic hilight color", Color.BLUE); if(newColor != null) { wandora.topicHilights.add(topics, newColor); table.refreshGUI(); } break; } case REMOVE_HILIGHT: { Topic[] topics = table.getSelectedTopics(); wandora.topicHilights.remove(topics); table.refreshGUI(); break; } case REMOVE_ALL_HILIGHTS: { String message = "Remove all topic hilights?"; int r = WandoraOptionPane.showConfirmDialog( wandora, message, "Confirm hilight remove", WandoraOptionPane.YES_NO_OPTION); if(r == WandoraOptionPane.YES_OPTION) { wandora.topicHilights.removeAll(); table.refreshGUI(); } break; } } } catch (Exception e) { log(e); } } @Override public String getName() { return "Topic Hilighter"; } @Override public String getDescription() { return "Set hilight color for context topics."; } @Override public boolean requiresRefresh() { return false; } }
3,702
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ExecBrowser.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/ExecBrowser.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * ExecBrowser.java * * Created on 22.6.2009, 11:29 */ package org.wandora.application.tools; import java.awt.Desktop; import java.net.URI; 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; /** * Open a WWW browser with a given URL address. * * @author akivela */ public class ExecBrowser extends AbstractWandoraTool implements WandoraTool, Runnable { private static final long serialVersionUID = 1L; private String uri = null; public ExecBrowser(){ } public ExecBrowser(String uri) { this.uri=uri; } @Override public void execute(Wandora wandora, Context context) { if(uri != null) { try { Desktop desktop = Desktop.getDesktop(); desktop.browse(new URI(uri)); } catch(Exception e) { log(e); } } else { singleLog("No uri set!"); } } @Override public boolean allowMultipleInvocations() { return true; } @Override public String getName() { return "Open WWW browser"; } @Override public String getDescription() { return "Open WWW browser with address "+uri; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/open_browser.png"); } @Override public boolean requiresRefresh() { return false; } }
2,416
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
CopyTopicPlayers.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/CopyTopicPlayers.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * CopyTopicPlayers.java * * Created on 13. huhtikuuta 2006, 11:58 * */ package org.wandora.application.tools; import org.wandora.application.contexts.PlayerContext; import org.wandora.topicmap.TopicMapException; /** * Copies association player topics of associations in selected topics to clipboard. * * @author akivela */ public class CopyTopicPlayers extends CopyTopics { private static final long serialVersionUID = 1L; public CopyTopicPlayers() throws TopicMapException { } @Override public String getName() { return "Copy topic players"; } @Override public String getDescription() { return "Copies association player topics of associations in selected topics to clipboard."; } @Override public void initialize(int copyOrders, int includeOrders) { super.initialize(copyOrders, includeOrders); setContext(new PlayerContext()); } }
1,750
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Print.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/Print.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.wandora.application.tools; import java.awt.Component; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.awt.print.PageFormat; import java.awt.print.Printable; import java.awt.print.PrinterException; import java.awt.print.PrinterJob; import javax.swing.Icon; import javax.swing.JComponent; 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.topicmap.TopicMapException; /** * * @author akikivela */ public class Print extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; @Override public void execute(Wandora wandora, Context context) throws TopicMapException { TopicPanel topicPanel = wandora.getTopicPanel(); Component printable = null; if(topicPanel != null) { if(topicPanel instanceof DockingFramePanel) { DockingFramePanel dockingPanel = (DockingFramePanel) topicPanel; TopicPanel currentTopicPanel = dockingPanel.getCurrentTopicPanel(); if(currentTopicPanel != null) { printable = currentTopicPanel.getGui(); } } } if(printable == null) { printable = wandora; } print(printable); } public void print(Component component) { if(component != null) { BufferedImage image = new BufferedImage(component.getWidth(), component.getHeight(), BufferedImage.TYPE_INT_ARGB); Graphics2D g = image.createGraphics(); if(component instanceof JComponent) { ((JComponent) component).setDoubleBuffered(false); } component.paint(g); if(component instanceof JComponent) { ((JComponent) component).setDoubleBuffered(true); } printImage(image); } } public void printImage(final BufferedImage image) { if(image != null) { PrinterJob pj = PrinterJob.getPrinterJob(); pj.setJobName("Wandora"); pj.setPrintable( new Printable() { @Override public int print(Graphics pg, PageFormat pageFormat, int pageNum) { if(pageNum > 0) { return Printable.NO_SUCH_PAGE; } Graphics2D g2 = (Graphics2D) pg; double scaleX = pageFormat.getImageableWidth() / image.getWidth(); double scaleY = pageFormat.getImageableHeight() / image.getHeight(); // Maintain aspect ratio, 2 as a maximum double scale = Math.min(2, Math.min(scaleX, scaleY)); g2.translate(pageFormat.getImageableX(), pageFormat.getImageableY()); g2.scale(scale, scale); g2.drawImage(image, 0, 0, null); return Printable.PAGE_EXISTS; } } ); if (pj.printDialog() == false) { return; } try { pj.print(); } catch (PrinterException ex) { log(ex); } } } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/print.png"); } @Override public String getName() { return "Print"; } @Override public String getDescription() { return "Print current topic panel."; } @Override public boolean requiresRefresh() { return false; } }
4,875
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ChainExecuter.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/ChainExecuter.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * ChainExecuter.java * * Created on 2.6.2006, 13:50 * */ package org.wandora.application.tools; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import javax.swing.Icon; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.gui.UIBox; /** * This meta-tool executes given tools in sequential order. * * @author akivela */ public class ChainExecuter extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; private ArrayList<WandoraTool> tools = new ArrayList<WandoraTool>(); public ChainExecuter() { } public ChainExecuter(WandoraTool tool) { tools.add(tool); } public ChainExecuter(WandoraTool tool1, WandoraTool tool2) { tools.add(tool1); tools.add(tool2); } public ChainExecuter(WandoraTool tool1, WandoraTool tool2, WandoraTool tool3) { tools.add(tool1); tools.add(tool2); tools.add(tool3); } public ChainExecuter(Collection<WandoraTool> mytools) { for(Iterator<WandoraTool> toolIterator = mytools.iterator(); toolIterator.hasNext();) { tools.add(toolIterator.next()); } } @Override public void execute(Wandora wandora, Context context) { for(WandoraTool tool : tools) { try { if(tool != null) { tool.setContext(context); tool.execute(wandora, context.getContextEvent()); while(tool.isRunning() && !forceStop()) { try { Thread.sleep(250); } catch(Exception e) {} } } } catch(Exception e) { log(e); } } } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/chain_executer.png"); } @Override public String getName() { return "Chain executer"; } @Override public String getDescription() { return "Executes multiple tools in sequential order."; } }
3,103
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SetOptions.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/SetOptions.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * SetOptions.java * * Created on 9. marraskuuta 2005, 21:30 * */ package org.wandora.application.tools; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.utils.Options; /** * * @author akivela */ public class SetOptions extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; private Map<String,String> options = new LinkedHashMap<>(); private boolean requiresRefresh = false; public SetOptions() { } public SetOptions(String key, int value, boolean rf) { requiresRefresh = rf; options.put(key, "" + value); } public SetOptions(String key, String value, boolean rf) { requiresRefresh = rf; options.put(key, value); } public void setOption(String key, String value) { if(key != null && value != null) { options.put(key, value); } } public void setOptions(Map<String,String> subOptions) { if(subOptions != null) { options.putAll(subOptions); } } @Override public String getName() { return "Set options"; } @Override public void execute(Wandora wandora, Context context) { Options globalOptions = wandora.getOptions(); if(globalOptions != null) { String key = null; String value = null; for(Iterator<String> keys = options.keySet().iterator(); keys.hasNext(); ) { try { key = (String) keys.next(); value = (String) options.get(key); globalOptions.put(key, value); } catch(Exception e) { log(e); } } } } @Override public boolean requiresRefresh() { return requiresRefresh; } }
2,871
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
GenericOptionsPanel.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/GenericOptionsPanel.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * GenericOptionsPanel.java * * Created on 25.7.2006, 15:30 */ package org.wandora.application.tools; import java.awt.Component; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.util.HashMap; import java.util.Map; import javax.swing.Icon; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSeparator; import org.wandora.application.Wandora; import org.wandora.application.gui.GetTopicButton; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.simple.SimpleCheckBox; import org.wandora.application.gui.simple.SimpleComboBox; import org.wandora.application.gui.simple.SimpleField; import org.wandora.application.gui.simple.SimpleLabel; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; import org.wandora.utils.Textbox; /** * * @author olli */ public class GenericOptionsPanel extends JPanel { private static final long serialVersionUID = 1L; protected HashMap<String,Component> components; protected Wandora admin; protected JPanel paddingPanel; protected boolean padding; public GenericOptionsPanel(String[][] fields,Wandora wandora){ this(fields,wandora,true); } public GenericOptionsPanel(String[][] fields,Wandora wandora,boolean padding){ this.admin=wandora; this.padding=padding; initFields(fields); } public static GridBagConstraints makeGBC(){ GridBagConstraints gbc=new GridBagConstraints(); gbc.insets=new Insets(5,5,0,5); gbc.fill=GridBagConstraints.HORIZONTAL; return gbc; } @Override public void setLayout(java.awt.LayoutManager layout){ } /** * Init fields in the options panel. Fields are given in an array of arrays. * First index is the field index. The inner array should have id of the field, * and the type of the field. Optionally it may also contain the initial value * of the field and a short help text. The order of the parameters is: id, type, * initial value and help text. * Type can be "string", "password", "boolean" or "topic". A suitable user interface * element will be used for each field depending on their type. For example * boolean fields will have check boxes. New types may be added in the future. * The id is also used as the user visible label of the field. */ public void initFields(String[][] fields){ components=new HashMap<String,Component>(); this.removeAll(); super.setLayout(new GridBagLayout()); GridBagConstraints gbc=makeGBC(); Icon icon=UIBox.getIcon("gui/icons/help2.png"); for(int i=0;i<fields.length;i++){ gbc.gridy=i; gbc.gridx=0; gbc.weightx=0.0; gbc.gridwidth=1; gbc.insets=new Insets(5,5,0,5); String id=fields[i][0]; String type=fields[i][1]; String value=""; if(fields[i].length>2) value=fields[i][2]; if(!type.equalsIgnoreCase("separator")){ this.add(new SimpleLabel(id),gbc); } Component c=null; if(type.equalsIgnoreCase("string")){ c=new SimpleField(); ((SimpleField)c).setText(value); } else if(type.equalsIgnoreCase("password")){ c=new SimpleField(); ((SimpleField)c).setText(value); } else if(type.equalsIgnoreCase("boolean")){ c=new SimpleCheckBox(); if(value.equalsIgnoreCase("true")) ((SimpleCheckBox)c).setSelected(true); else ((SimpleCheckBox)c).setSelected(false); } else if(type.equalsIgnoreCase("separator")){ c=new JSeparator(); ((JSeparator) c).setOrientation(JSeparator.HORIZONTAL); } else if(type.equalsIgnoreCase("topic")){ try{ if(value == null || value.length()==0) { c=new GetTopicButton((Topic)null,admin,admin,true); } else { c=new GetTopicButton(admin.getTopicMap().getTopic(value),admin,admin,true); } } catch(TopicMapException tme){ admin.handleError(tme); c=new SimpleLabel("Topic map exception"); } } else if(type.toLowerCase().startsWith("combo:")) { String[] options=type.substring("combo:".length()).split(";"); c=new SimpleComboBox(options); ((SimpleComboBox)c).setEditable(false); ((SimpleComboBox)c).setSelectedItem(value); } if(type.equalsIgnoreCase("separator")){ gbc.gridx=0; gbc.gridwidth = 2; gbc.insets=new Insets(12,5,7,5); } else { gbc.gridx=1; gbc.gridwidth=1; gbc.insets=new Insets(5,5,0,5); } gbc.weightx=1.0; this.add(c,gbc); components.put(id,c); if(fields[i].length>3) { gbc.gridx=2; gbc.weightx=0.0; JLabel label=new JLabel(icon); label.setToolTipText(Textbox.makeHTMLParagraph( fields[i][3], 40 ) ); this.add(label,gbc); } } if(padding){ addPadding(fields.length); } else this.invalidate(); } public void removePadding(){ if(paddingPanel!=null){ this.remove(paddingPanel); } } public void addPadding(int pos){ paddingPanel=new JPanel(); GridBagConstraints gbc=new GridBagConstraints(); gbc.gridy=pos; gbc.gridx=0; gbc.weighty=1.0; gbc.weightx=0.0; this.add(paddingPanel,gbc); this.invalidate(); } /** * Gets the values from this options panel. Return value is a map that * maps field IDs to their values. Note that all values are converted to * string regardless of the field type. Boolean fields are converted to * "true" or "false". */ public Map<String,String> getValues(){ HashMap<String,String> ret=new HashMap<String,String>(); for(Map.Entry<String,Component> e : components.entrySet()){ String id=e.getKey(); Component c=e.getValue(); if(c instanceof SimpleField){ ret.put(id,((SimpleField)c).getText()); } else if(c instanceof SimpleCheckBox){ if(((SimpleCheckBox)c).isSelected()) ret.put(id,"true"); else ret.put(id,"false"); } else if(c instanceof GetTopicButton){ try{ String si=((GetTopicButton)c).getTopicSI(); if(si==null) ret.put(id,""); else ret.put(id,si); }catch(TopicMapException tme){ admin.handleError(tme); ret.put(id,""); } } else if(c instanceof SimpleComboBox){ ret.put(id,((SimpleComboBox)c).getSelectedItem().toString()); } else{ ret.put(id,""); } } return ret; } }
8,310
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ClearToolLocks.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/ClearToolLocks.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * ClearToolLocks.java * * Created on 13. lokakuuta 2006, 23:14 * */ package org.wandora.application.tools; import javax.swing.Icon; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.gui.UIBox; /** * Clears all tool locks preventing sequential tool executions. Notice that clearing * locks doesn't stop threads running in tools. * * @author akivela */ public class ClearToolLocks extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; /** Creates a new instance of ClearToolLocks */ public ClearToolLocks() { } @Override public void execute(Wandora wandora, Context context) { int n = clearToolLocks(); if(n > 0) { log("There exists "+n+" tool(s) locked. All tool locks released. "+ "Unlocked tools may be executed once again but they may fail "+ "depending on the execution history of the tool."); } else { log("There is no tools locked at the moment. No locks released."); } } @Override public boolean runInOwnThread() { return false; } @Override public boolean allowMultipleInvocations(){ return true; } @Override public String getName() { return "Clear tool locks"; } @Override public String getDescription() { return "Clears all tool locks and enable sequential tool executions. Notice that clearing locks doesn't stop threads in tools."; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/clear_tool_locks.png"); } }
2,573
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
CopyTopicRoles.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/CopyTopicRoles.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * CopyTopicRoles.java * * Created on 13. huhtikuuta 2006, 11:57 * */ package org.wandora.application.tools; import org.wandora.application.contexts.RoleContext; import org.wandora.topicmap.TopicMapException; /** * Copies association role topics of associations in selected topics to clipboard. * * @author akivela */ public class CopyTopicRoles extends CopyTopics { private static final long serialVersionUID = 1L; public CopyTopicRoles() throws TopicMapException { } @Override public String getName() { return "Copy topic roles"; } @Override public String getDescription() { return "Copies association role topics of associations in selected topics to clipboard."; } @Override public void initialize(int copyOrders, int includeOrders) { super.initialize(copyOrders, includeOrders); setContext(new RoleContext()); } }
1,733
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
RefreshTopicTrees.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/RefreshTopicTrees.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * RefreshTopicTrees.java * * Created on 7. huhtikuuta 2006, 14:20 * */ package org.wandora.application.tools; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public class RefreshTopicTrees extends AbstractWandoraTool { private static final long serialVersionUID = 1L; /** Creates a new instance of RefreshTopicTrees */ public RefreshTopicTrees() { } @Override public String getName() { return "Refresh topic trees"; } @Override public String getDescription() { return "Refresh topic trees."; } @Override public void execute(Wandora wandora, Context context) throws TopicMapException { wandora.refreshTopicTrees(); } }
1,643
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SystemClipboard.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/SystemClipboard.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * SystemClipboard.java * * Created on 9. marraskuuta 2005, 18:56 * */ package org.wandora.application.tools; import javax.swing.Icon; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.gui.Clipboardable; import org.wandora.application.gui.UIBox; /** * WandoraTool that transfers Wandora application data to system clipboard and vice versa. * Transfer direction is selected with an argument to constructor. * * @author akivela */ public class SystemClipboard extends AbstractWandoraTool implements WandoraTool { private static final long serialVersionUID = 1L; public static final int PASTE = 1; public static final int COPY = 2; public static final int CUT = 4; private int operation = COPY; public SystemClipboard() { } public SystemClipboard(int operation) { this.operation = operation; } @Override public void execute(Wandora wandora, Context context) { Object focusOwner = wandora.getFocusOwner(); if(focusOwner != null) { if(focusOwner instanceof Clipboardable) { Clipboardable clipboardable = (Clipboardable) focusOwner; switch(operation) { case COPY: { clipboardable.copy(); break; } case CUT: { clipboardable.cut(); break; } case PASTE: { clipboardable.paste(); break; } } } } } @Override public Icon getIcon() { switch(operation) { case COPY: { return UIBox.getIcon("gui/icons/copy.png"); } case CUT: { return UIBox.getIcon("gui/icons/cut.png"); } case PASTE: { return UIBox.getIcon("gui/icons/paste.png"); } } return super.getIcon(); } @Override public String getName() { switch(operation) { case COPY: { return "Copy"; } case CUT: { return "Cut"; } case PASTE: { return "Paste"; } } return "System clipboard"; } @Override public String getDescription() { switch(operation) { case COPY: { return "Copy selection of current UI element to the system clipboard."; } case CUT: { return "Cut selection of current UI element to the system clipboard."; } case PASTE: { return "Paste data on system clipboard to Wandora's active UI element."; } } return "Transfers Wandora application originated data to system clipboard and vice versa."; } @Override public boolean requiresRefresh() { switch(operation) { case COPY: { return false; } case CUT: { return true; } case PASTE: { return true; } } return true; } }
4,226
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z