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
PatchDiffEntryFormatter.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/diff/PatchDiffEntryFormatter.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.topicmap.diff; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.diff.TopicMapDiff.AssociationAdded; import org.wandora.topicmap.diff.TopicMapDiff.AssociationDeleted; import org.wandora.topicmap.diff.TopicMapDiff.BNChanged; import org.wandora.topicmap.diff.TopicMapDiff.DiffEntry; import org.wandora.topicmap.diff.TopicMapDiff.SIAdded; import org.wandora.topicmap.diff.TopicMapDiff.SIDeleted; import org.wandora.topicmap.diff.TopicMapDiff.SLChanged; import org.wandora.topicmap.diff.TopicMapDiff.TopicAdded; import org.wandora.topicmap.diff.TopicMapDiff.TopicChanged; import org.wandora.topicmap.diff.TopicMapDiff.TopicDeleted; import org.wandora.topicmap.diff.TopicMapDiff.TopicDiffEntry; import org.wandora.topicmap.diff.TopicMapDiff.TypeAdded; import org.wandora.topicmap.diff.TopicMapDiff.TypeDeleted; import org.wandora.topicmap.diff.TopicMapDiff.VariantChanged; /** * * @author olli */ public class PatchDiffEntryFormatter implements DiffEntryFormatter { protected void formatTopicDiffEntry(ArrayList<TopicDiffEntry> diff,Writer writer) throws IOException,TopicMapException { for(TopicDiffEntry d : diff){ if(d instanceof SIAdded){ writer.write("+I\""+escapeString(((SIAdded)d).si.toString())+"\"\n"); } else if(d instanceof SIDeleted){ writer.write("-I\""+escapeString(((SIDeleted)d).si.toString())+"\"\n"); } else if(d instanceof SLChanged){ Locator l=((SLChanged)d).sl; Locator ol=((SLChanged)d).oldsl; if(l!=null) { if(ol==null) writer.write("+L\""+escapeString(l.toString())+"\"\n"); else writer.write("*L\""+escapeString(l.toString())+"\"/\""+escapeString(ol.toString())+"\"\n"); } else writer.write("-L\""+escapeString(ol.toString())+"\"\n"); } else if(d instanceof BNChanged){ String bn=((BNChanged)d).bn; String oldbn=((BNChanged)d).oldbn; if(bn!=null) { if(oldbn==null) writer.write("+B\""+escapeString(bn)+"\"\n"); else writer.write("*B\""+escapeString(bn)+"\"/\""+escapeString(oldbn)+"\"\n"); } else writer.write("-B\""+escapeString(oldbn)+"\"\n"); } else if(d instanceof TypeAdded){ Topic t=((TypeAdded)d).t; Object t2=((TypeAdded)d).t2; writer.write("+T"+formatTopic(t,t2)+"\n"); } else if(d instanceof TypeDeleted){ Topic t=((TypeDeleted)d).t; Object t2=((TypeDeleted)d).t2; writer.write("-T"+formatTopic(t,t2)+"\n"); } else if(d instanceof VariantChanged){ VariantChanged vc=(VariantChanged)d; String v=vc.name; String oldv=vc.oldname; StringBuffer scopeString=new StringBuffer(""); if(vc.scope!=null){ for(Topic t : vc.scope){ if(scopeString.length()>0) scopeString.append(" "); scopeString.append(formatTopic(t,null)); } } else{ for(Object t : vc.scope2){ if(scopeString.length()>0) scopeString.append(" "); scopeString.append(formatTopic(null,t)); } } if(v!=null) { if(oldv==null) writer.write("+V{"+scopeString+"}\""+escapeString(v)+"\"\n"); else writer.write("*V{"+scopeString+"}\""+escapeString(v)+"\"/\""+escapeString(oldv)+"\"\n"); } else writer.write("-V{"+scopeString+"}\""+escapeString(oldv)+"\"\n"); } } } protected String escapeString(String s){ s=s.replace("\\", "\\\\"); s=s.replace("\"", "\\\""); return s; } protected String formatTopic(Topic t,Object identifier) throws TopicMapException { if(t!=null){ String bn=t.getBaseName(); if(bn!=null) return "B\""+escapeString(bn)+"\""; else { Locator l=t.getOneSubjectIdentifier(); if(l!=null) return "I\""+escapeString(t.getOneSubjectIdentifier().toString())+"\""; return "D\""+t.getID()+"\""; } } else{ if(identifier instanceof Locator) return "I\""+identifier.toString()+"\""; else return "B\""+identifier.toString()+"\""; } } protected void formatAssociation(Association a,Writer writer) throws IOException,TopicMapException { Topic type=a.getType(); writer.write(formatTopic(type,null)+"\n"); for(Topic role : a.getRoles()){ writer.write(formatTopic(role,null)+":"+formatTopic(a.getPlayer(role),null)+"\n"); } } protected void formatAssociation(Topic[] a,Writer writer) throws IOException,TopicMapException { Topic type=a[0]; writer.write(formatTopic(type,null)+"\n"); for(int i=1;i+1<a.length;i+=2){ Topic role=a[i]; Topic player=a[i+1]; writer.write(formatTopic(role,null)+":"+formatTopic(player,null)+"\n"); } } protected void formatAssociation(Object[] a,Writer writer) throws IOException,TopicMapException { Object type=a[0]; writer.write(formatTopic(null,type)+"\n"); for(int i=1;i+1<a.length;i+=2){ Object role=a[i]; Object player=a[i+1]; writer.write(formatTopic(null,role)+":"+formatTopic(null,player)+"\n"); } } public void header(Writer writer) throws IOException, TopicMapException{ } public void footer(Writer writer) throws IOException, TopicMapException{ } public void formatDiffEntry(DiffEntry entry,Writer writer) throws IOException,TopicMapException { if(entry instanceof TopicChanged){ Topic t=((TopicChanged)entry).topic; Object t2=((TopicChanged)entry).topic2; ArrayList<TopicDiffEntry> diff=((TopicChanged)entry).diff; writer.write("*T["+formatTopic(t,t2)+"\n"); formatTopicDiffEntry(diff,writer); writer.write("]\n"); } else if(entry instanceof TopicDeleted){ Topic t=((TopicDeleted)entry).topic; Object t2=((TopicDeleted)entry).topic2; ArrayList<TopicDiffEntry> diff=((TopicDeleted)entry).diff; writer.write("-T["+formatTopic(t,t2)+"\n"); formatTopicDiffEntry(diff,writer); writer.write("]\n"); } else if(entry instanceof TopicAdded){ ArrayList<TopicDiffEntry> diff=((TopicAdded)entry).diff; writer.write("+T[\n"); formatTopicDiffEntry(diff,writer); writer.write("]\n"); } else if(entry instanceof AssociationAdded){ writer.write("+A["); if(((AssociationAdded)entry).a!=null) formatAssociation(((AssociationAdded)entry).a,writer); else formatAssociation(((AssociationAdded)entry).a2,writer); writer.write("]\n"); } else if(entry instanceof AssociationDeleted){ writer.write("-A["); if(((AssociationDeleted)entry).a!=null) formatAssociation(((AssociationDeleted)entry).a,writer); else formatAssociation(((AssociationDeleted)entry).a2,writer); writer.write("]\n"); } } }
8,812
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicMapImpl.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/memory/TopicMapImpl.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * TopicMapImpl.java * * Created on June 10, 2004, 11:30 AM */ package org.wandora.topicmap.memory; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicIterator; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicMapListener; import org.wandora.topicmap.TopicMapLogger; import org.wandora.topicmap.TopicMapReadOnlyException; import org.wandora.topicmap.TopicMapSearchOptions; import org.wandora.topicmap.TopicMapStatData; import org.wandora.topicmap.TopicMapStatOptions; /** * * @author olli, ak */ public class TopicMapImpl extends TopicMap { // private TopicMapListener topicMapListener; private List<TopicMapListener> topicMapListeners; private List<TopicMapListener> disabledListeners; private int topicMapID; // for debugging; private static int topicMapCounter=0; // for debugging (not thread safe) /** * Indexes topics according to their id. */ private Map<String, Topic> idIndex; /** * Indexes topics according to their type. */ private Map<Topic,Collection<Topic>> typeIndex; /** * Indexes topics according to subject identifiers. */ private Map<Locator,Topic> subjectIdentifierIndex; /** * Indexes topics according to subject locators. */ private Map<Locator,Topic> subjectLocatorIndex; /** * Indexes topics according to base names. */ private Map<String,Topic> nameIndex; /** * Indexes associations according to their type. */ private Map<Topic,Collection<Association>> associationTypeIndex; /** * All topics in this topic map. */ private Set<Topic> topics; /** * All associations in this topic map. */ private Set<Association> associations; private boolean trackDependent; private boolean topicMapChanged; /** Creates a new instance of TopicMapImpl */ public TopicMapImpl(String topicmapFile) { this(); try { importTopicMap(topicmapFile); } catch(Exception e) { e.printStackTrace(); } } public TopicMapImpl() { topicMapID = topicMapCounter++; idIndex = Collections.synchronizedMap(new LinkedHashMap<String,Topic>()); typeIndex = Collections.synchronizedMap(new LinkedHashMap<Topic,Collection<Topic>>()); subjectIdentifierIndex = Collections.synchronizedMap(new LinkedHashMap<Locator,Topic>()); subjectLocatorIndex = Collections.synchronizedMap(new LinkedHashMap<Locator,Topic>()); nameIndex = Collections.synchronizedMap(new LinkedHashMap<String,Topic>()); associationTypeIndex = Collections.synchronizedMap(new LinkedHashMap<Topic,Collection<Association>>()); topics = Collections.synchronizedSet(new LinkedHashSet<Topic>()); associations = Collections.synchronizedSet(new LinkedHashSet<Association>()); trackDependent = false; topicMapChanged = false; topicMapListeners = Collections.synchronizedList(new ArrayList<TopicMapListener>()); } @Override public void clearTopicMap() throws TopicMapException{ if(isReadOnly()) throw new TopicMapReadOnlyException(); idIndex = Collections.synchronizedMap(new LinkedHashMap<String,Topic>()); typeIndex = Collections.synchronizedMap(new LinkedHashMap<Topic,Collection<Topic>>()); subjectIdentifierIndex = Collections.synchronizedMap(new LinkedHashMap<Locator,Topic>()); subjectLocatorIndex = Collections.synchronizedMap(new LinkedHashMap<Locator,Topic>()); nameIndex = Collections.synchronizedMap(new LinkedHashMap<String,Topic>()); associationTypeIndex = Collections.synchronizedMap(new LinkedHashMap<Topic,Collection<Association>>()); topics = Collections.synchronizedSet(new LinkedHashSet<Topic>()); associations = Collections.synchronizedSet(new LinkedHashSet<Association>()); topicMapChanged = true; } @Override public void clearTopicMapIndexes() throws TopicMapException { /* Do nothing! * Especially do not clear all the *Index objects. Because all data * is in memory all the time, they can never be out of date and thus * never require refreshing. It is assumed that they always contain * complete data. */ } @Override public void close() { } /** * Checks association consistency and fixes any inconsistencies. Two * associations are said to be inconsistent if they have the same type and * same players with same roles, that is they represent the exact same * association. If several such associations exist all but one of them need * to be removed. */ @Override public void checkAssociationConsistency(TopicMapLogger logger) throws TopicMapException { if(isReadOnly()) throw new TopicMapReadOnlyException(); ArrayList<Association> clonedAssociations = new ArrayList<Association>(); clonedAssociations.addAll(associations); if(logger != null) { System.out.println("associations.size=="+associations.size()); int s = clonedAssociations.size(); logger.setProgressMax(s); } AssociationImpl ai = null; int i=0; for(Association a : clonedAssociations) { if(logger != null) { logger.setProgress(i++); } if(a != null && !a.isRemoved() && a instanceof AssociationImpl) { ai = (AssociationImpl) a; ai.checkRedundancy(); } } System.out.println("associations.size=="+associations.size()); } @Override public List<TopicMapListener> getTopicMapListeners(){ return topicMapListeners; } @Override public void addTopicMapListener(TopicMapListener listener){ topicMapListeners.add(listener); } @Override public void removeTopicMapListener(TopicMapListener listener){ topicMapListeners.remove(listener); } @Override public void disableAllListeners(){ if(disabledListeners==null){ disabledListeners=topicMapListeners; topicMapListeners=new ArrayList<TopicMapListener>(); } } @Override public void enableAllListeners(){ if(disabledListeners!=null){ topicMapListeners=disabledListeners; disabledListeners=null; } } /* public TopicMapListener setTopicMapListener(TopicMapListener listener){ TopicMapListener old=topicMapListener; topicMapListener=listener; return old; }*/ protected TopicImpl constructTopic(String id) throws TopicMapException { return new TopicImpl(id, this); } protected TopicImpl constructTopic() throws TopicMapException { return new TopicImpl(this); } @Override public Topic createTopic(String id) throws TopicMapException { if(isReadOnly()) throw new TopicMapReadOnlyException(); Topic t = null; if(idIndex.get(id) == null) { t = constructTopic(id); topics.add(t); idIndex.put(t.getID(), t); } else { t = idIndex.get(id); } return t; } @Override public Topic createTopic() throws TopicMapException { if(isReadOnly()) throw new TopicMapReadOnlyException(); TopicImpl t=constructTopic(); topics.add(t); idIndex.put(t.getID(), t); // if(topicMapListener!=null) topicMapListener.topicChanged(t); return t; } protected AssociationImpl constructAssociation(Topic type) throws TopicMapException { return new AssociationImpl(this,type); } @Override public Association createAssociation(Topic type) throws TopicMapException { if(isReadOnly()) throw new TopicMapReadOnlyException(); Association a=constructAssociation(type); associations.add(a); // if(topicMapListener!=null) topicMapListener.associationChanged(a); return a; } @Override public Topic getTopic(Locator si) throws TopicMapException { if(si == null) return null; return subjectIdentifierIndex.get(si); } @Override public Topic getTopicWithBaseName(String name) throws TopicMapException { if(name == null) return null; return nameIndex.get(name); } @Override public Collection getTopicsOfType(Topic type) throws TopicMapException{ if(type == null) return new ArrayList(); Collection s=typeIndex.get(type); if(s==null) return new HashSet(); else return s; } // Note that this isn't part of the Wandora topic map API, it's used // in the tmapi wrapper public Collection getTypeTopics() throws TopicMapException { return new ArrayList(typeIndex.keySet()); } @Override public Topic getTopicBySubjectLocator(Locator sl) throws TopicMapException { if(sl == null) return null; return subjectLocatorIndex.get(sl); } @Override public Iterator getTopics() throws TopicMapException { // TODO: synchronization of iterator? final Iterator<Topic> iter=topics.iterator(); return new TopicIterator(){ boolean disposed=false; @Override public void dispose() { disposed=true; } @Override public boolean hasNext() { if(disposed) return false; else return iter.hasNext(); } @Override public Topic next() { return iter.next(); } @Override public void remove() { throw new UnsupportedOperationException("Not supported yet."); } }; } @Override public Topic[] getTopics(String[] sis) throws TopicMapException { if(sis == null) return new Topic[] {}; Topic[] topics = new Topic[sis.length]; for(int i=0; i<sis.length; i++) { topics[i]=getTopic(sis[i]); } return topics; } @Override public Iterator getAssociations() throws TopicMapException { return associations.iterator(); } @Override public Collection getAssociationsOfType(Topic type) throws TopicMapException { if(type == null) return new ArrayList(); Collection<Association> s=associationTypeIndex.get(type); if(s==null) return new HashSet(); else return s; } public Topic getTopic(Collection SIs) throws TopicMapException{ Iterator iter=SIs.iterator(); while(iter.hasNext()){ Locator l=(Locator)iter.next(); Topic t=getTopic(l); if(t!=null) return t; } return null; } private static int idCounter=(int)(100000*Math.random()); private synchronized int getIDCounter(){ if(idCounter>=1000000) idCounter=0; return idCounter++; } private Topic _copyTopicIn(Topic t,boolean deep,Hashtable copied) throws TopicMapException{ return _copyTopicIn(t,deep,false,copied); } private Topic _copyTopicIn(Topic t,boolean deep,boolean stub,Hashtable copied) throws TopicMapException{ if(copied.containsKey(t)) { // Don't return the topic that was created when t was copied because it might have been merged with something // since then. Instead get the topic with one of the subject identifiers of the topic. Locator l=(Locator)copied.get(t); return getTopic(l); } // first check if the topic would be merged, if so, edit the equal topic directly instead of creating new // and letting them merge later Topic nt=getTopic(t.getSubjectIdentifiers()); if(nt==null && t.getBaseName()!=null) nt=getTopicWithBaseName(t.getBaseName()); if(nt==null && t.getSubjectLocator()!=null) nt=getTopicBySubjectLocator(t.getSubjectLocator()); if(nt==null && idIndex.containsKey(t.getID())) nt=idIndex.get(t.getID()); if(nt==null) { nt=createTopic(t.getID()); } boolean newer=(t.getEditTime()>=nt.getEditTime()); Iterator iter=t.getSubjectIdentifiers().iterator(); while(iter.hasNext()){ Locator l=(Locator)iter.next(); nt.addSubjectIdentifier(l); } if(nt.getSubjectIdentifiers().isEmpty()) { System.out.println("Warning! No subject indicators in topic. Creating default SI."); String randomNumber = System.currentTimeMillis()+"-"+getIDCounter(); nt.addSubjectIdentifier(new Locator("http://wandora.org/si/temp/" + randomNumber)); } copied.put(t,(Locator)nt.getSubjectIdentifiers().iterator().next()); if(nt.getSubjectLocator()==null && t.getSubjectLocator()!=null){ nt.setSubjectLocator(t.getSubjectLocator()); // TODO: raise error if different? } if(nt.getBaseName()==null && t.getBaseName()!=null){ nt.setBaseName(t.getBaseName()); } if( (!stub) || deep) { iter=t.getTypes().iterator(); while(iter.hasNext()){ Topic type=(Topic)iter.next(); Topic ntype=_copyTopicIn(type,deep,true,copied); nt.addType(ntype); } iter=t.getVariantScopes().iterator(); while(iter.hasNext()){ Set scope=(Set)iter.next(); Set nscope=new LinkedHashSet(); Iterator iter2=scope.iterator(); while(iter2.hasNext()){ Topic st=(Topic)iter2.next(); Topic nst=_copyTopicIn(st,deep,true,copied); nscope.add(nst); } nt.setVariant(nscope, t.getVariant(scope)); } iter=t.getDataTypes().iterator(); while(iter.hasNext()){ Topic type=(Topic)iter.next(); Topic ntype=_copyTopicIn(type,deep,true,copied); Hashtable versiondata=t.getData(type); Iterator iter2=versiondata.entrySet().iterator(); while(iter2.hasNext()){ Map.Entry e=(Map.Entry)iter2.next(); Topic version=(Topic)e.getKey(); String data=(String)e.getValue(); Topic nversion=_copyTopicIn(version,deep,true,copied); nt.setData(ntype,nversion,data); } } } return nt; } private Association _copyAssociationIn(Association a) throws TopicMapException{ Topic type=a.getType(); Topic ntype=null; if(type.getSubjectIdentifiers().isEmpty()) { System.out.println("Warning, topic has no subject identifiers."); } else { ntype=getTopic((Locator)type.getSubjectIdentifiers().iterator().next()); } if(ntype==null) ntype=copyTopicIn(type,false); Association na=createAssociation(ntype); HashMap<Topic,Topic> players = new LinkedHashMap<Topic,Topic>(); for(Topic role : a.getRoles()) { Topic nrole = null; if(role.getSubjectIdentifiers().isEmpty()) { System.out.println("Warning, topic has no subject identifiers. Creating default SI!"); //role.addSubjectIdentifier(new Locator("http://wandora.org/si/temp/" + System.currentTimeMillis())); } else { nrole=getTopic((Locator)role.getSubjectIdentifiers().iterator().next()); } if(nrole==null) { nrole=copyTopicIn(role,false); } Topic player=a.getPlayer(role); Topic nplayer = null; if(player.getSubjectIdentifiers().isEmpty()) { System.out.println("Warning, topic has no subject identifiers. Creating default SI!"); //player.addSubjectIdentifier(new Locator("http://wandora.org/si/temp/" + System.currentTimeMillis())); } else { nplayer=getTopic((Locator)player.getSubjectIdentifiers().iterator().next()); } if(nplayer==null) nplayer=copyTopicIn(player,false); //na.addPlayer(nplayer,nrole); players.put(nrole,nplayer); } na.addPlayers(players); return na; } @Override public Association copyAssociationIn(Association a) throws TopicMapException { if(isReadOnly()) throw new TopicMapReadOnlyException(); Association n=_copyAssociationIn(a); Topic minTopic=null; int minCount=Integer.MAX_VALUE; Iterator iter2=n.getRoles().iterator(); while(iter2.hasNext()){ Topic role=(Topic)iter2.next(); Topic t=n.getPlayer(role); if(t.getAssociations().size()<minCount){ minCount=t.getAssociations().size(); minTopic=t; } } ((TopicImpl)minTopic).removeDuplicateAssociations(n); return n; } @Override public Topic copyTopicIn(Topic t, boolean deep) throws TopicMapException { if(isReadOnly()) throw new TopicMapReadOnlyException(); return _copyTopicIn(t,deep,false,new Hashtable()); } @Override public void mergeIn(TopicMap tm) throws TopicMapException { if(isReadOnly()) throw new TopicMapReadOnlyException(); Iterator iter=tm.getTopics(); Hashtable copied=new Hashtable(); int tcount=0; while(iter.hasNext()){ Topic t = null; try { t=(Topic)iter.next(); _copyTopicIn(t,true,false,copied); tcount++; } catch (Exception e) { System.out.println("Unable to copy topic (" + t + ")."); e.printStackTrace(); } } HashSet endpoints=new LinkedHashSet(); iter=tm.getAssociations(); int acount=0; while(iter.hasNext()) { try { Association a=(Association)iter.next(); Association na=_copyAssociationIn(a); Topic minTopic=null; int minCount=Integer.MAX_VALUE; Iterator iter2=na.getRoles().iterator(); while(iter2.hasNext()){ Topic role=(Topic)iter2.next(); Topic t=na.getPlayer(role); if(t.getAssociations().size()<minCount){ minCount=t.getAssociations().size(); minTopic=t; } } endpoints.add(minTopic); acount++; } catch (Exception e) { System.out.println("Unable to copy association."); e.printStackTrace(); } } // System.out.println("merged "+tcount+" topics and "+acount+" associations"); iter=endpoints.iterator(); while(iter.hasNext()){ TopicImpl t=(TopicImpl)iter.next(); if(t != null) t.removeDuplicateAssociations(); } } @Override public void copyTopicAssociationsIn(Topic t) throws TopicMapException { if(isReadOnly()) throw new TopicMapReadOnlyException(); Topic nt=getTopic((Locator)t.getSubjectIdentifiers().iterator().next()); if(nt==null) nt=copyTopicIn(t,false); Iterator iter=t.getAssociations().iterator(); while(iter.hasNext()){ _copyAssociationIn((Association)iter.next()); } ((TopicImpl)nt).removeDuplicateAssociations(); } public void addTopicSubjectIdentifier(Topic t,Locator l) throws TopicMapException { if(isReadOnly()) throw new TopicMapReadOnlyException(); subjectIdentifierIndex.put(l,t); } public void removeTopicSubjectIdentifier(Topic t,Locator l) throws TopicMapException { if(isReadOnly()) throw new TopicMapReadOnlyException(); subjectIdentifierIndex.remove(l); } public void setTopicSubjectLocator(Topic t,Locator l,Locator oldLocator) throws TopicMapException { if(isReadOnly()) throw new TopicMapReadOnlyException(); if(oldLocator!=null) subjectLocatorIndex.remove(oldLocator); if(l!=null) subjectLocatorIndex.put(l,t); } public void removeTopicSubjectLocator(Topic t,Locator l) throws TopicMapException { if(isReadOnly()) throw new TopicMapReadOnlyException(); subjectLocatorIndex.remove(l); } public void addTopicType(Topic t,Topic type) throws TopicMapException { if(isReadOnly()) throw new TopicMapReadOnlyException(); Collection s=typeIndex.get(type); if(s==null) { s=new LinkedHashSet(); typeIndex.put(type,s); } s.add(t); } public void removeTopicType(Topic t,Topic type) throws TopicMapException { if(isReadOnly()) throw new TopicMapReadOnlyException(); Collection s=typeIndex.get(type); if(s==null) return; s.remove(t); } public void setTopicName(Topic t,String name,String oldname) throws TopicMapException { if(isReadOnly()) throw new TopicMapReadOnlyException(); if(oldname!=null) nameIndex.remove(oldname); if(name!=null) nameIndex.put(name,t); } public void setAssociationType(Association a,Topic type,Topic oldtype) throws TopicMapException { if(isReadOnly()) throw new TopicMapReadOnlyException(); if(oldtype!=null) { // note: old type can be null only when setting the initial type Collection<Association> s=associationTypeIndex.get(oldtype); if(s!=null){ s.remove(a); } } if(type!=null){ // note: type can be null only when destroying association Collection<Association> s=associationTypeIndex.get(type); if(s==null) { s=new LinkedHashSet(); associationTypeIndex.put(type,s); } s.add(a); } } // -------------------------------------------------- TOPIC MAP LISTENER --- public void topicRemoved(Topic t) throws TopicMapException { topicMapChanged=true; idIndex.remove(t.getID()); topics.remove(t); for(TopicMapListener listener : topicMapListeners){ listener.topicRemoved(t); } } public void associationRemoved(Association a) throws TopicMapException { topicMapChanged=true; associations.remove(a); for(TopicMapListener listener : topicMapListeners){ listener.associationRemoved(a); } } public void topicsMerged(Topic newtopic,Topic deletedtopic){ } public void duplicateAssociationRemoved(Association a,Association removeda){ } @Override public int getNumAssociations() throws TopicMapException{ return associations.size(); } @Override public int getNumTopics() throws TopicMapException{ return topics.size(); } @Override public boolean trackingDependent(){ return trackDependent; } @Override public void setTrackDependent(boolean v){ trackDependent=v; } public void topicSubjectIdentifierChanged(Topic t,Locator added,Locator removed) throws TopicMapException{ topicMapChanged=true; for(TopicMapListener listener : topicMapListeners){ listener.topicSubjectIdentifierChanged(t,added,removed); } } public void topicBaseNameChanged(Topic t,String newName,String oldName) throws TopicMapException{ topicMapChanged=true; for(TopicMapListener listener : topicMapListeners){ listener.topicBaseNameChanged(t,newName,oldName); } } public void topicTypeChanged(Topic t,Topic added,Topic removed) throws TopicMapException { topicMapChanged=true; for(TopicMapListener listener : topicMapListeners){ listener.topicTypeChanged(t,added,removed); } } public void topicVariantChanged(Topic t,Collection<Topic> scope,String newName,String oldName) throws TopicMapException { topicMapChanged=true; for(TopicMapListener listener : topicMapListeners){ listener.topicVariantChanged(t,scope,newName,oldName); } } public void topicDataChanged(Topic t,Topic type,Topic version,String newValue,String oldValue) throws TopicMapException { topicMapChanged=true; for(TopicMapListener listener : topicMapListeners){ listener.topicDataChanged(t,type,version,newValue,oldValue); } } public void topicSubjectLocatorChanged(Topic t,Locator newLocator,Locator oldLocator) throws TopicMapException { topicMapChanged=true; for(TopicMapListener listener : topicMapListeners){ listener.topicSubjectLocatorChanged(t,newLocator,oldLocator); } } public void topicChanged(Topic t) throws TopicMapException { topicMapChanged=true; for(TopicMapListener listener : topicMapListeners){ listener.topicChanged(t); } } public void associationTypeChanged(Association a,Topic newType,Topic oldType) throws TopicMapException { topicMapChanged=true; for(TopicMapListener listener : topicMapListeners){ listener.associationTypeChanged(a,newType,oldType); } } public void associationPlayerChanged(Association a,Topic role,Topic newPlayer,Topic oldPlayer) throws TopicMapException { topicMapChanged=true; for(TopicMapListener listener : topicMapListeners){ listener.associationPlayerChanged(a,role,newPlayer,oldPlayer); } } public void associationChanged(Association a) throws TopicMapException { topicMapChanged=true; for(TopicMapListener listener : topicMapListeners){ listener.associationChanged(a); } } // --------------------------------------------- TOPIC MAP LISTENER ENDS --- @Override public boolean resetTopicMapChanged(){ boolean b=topicMapChanged; topicMapChanged=false; return b; } @Override public boolean isTopicMapChanged(){ return topicMapChanged; } @Override public Collection<Topic> search(String query, TopicMapSearchOptions options) throws TopicMapException{ ArrayList<Topic> searchResult = new ArrayList<Topic>(); Iterator topicIterator = getTopics(); Topic t = null; Pattern p = Pattern.compile(query, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE ); while(topicIterator.hasNext()) { if(options.maxResults>=0 && searchResult.size()>=options.maxResults) break; try { t = (Topic) topicIterator.next(); // --- Basename --- if(options.searchBasenames) { String name = t.getBaseName(); if(searchMatch(name, p)) { searchResult.add(t); continue; } } // --- Variant names --- if(options.searchVariants) { Set varcol = t.getVariantScopes(); Iterator variants = varcol.iterator(); boolean matches = false; while(!matches && variants.hasNext()) { Set scope = (Set)variants.next(); String name = t.getVariant(scope); if(searchMatch(name, p)) { searchResult.add(t); matches = true; break; } } if(matches) continue; } // --- text occurrences --- if(options.searchOccurrences) { boolean matches = false; Iterator iter = t.getDataTypes().iterator(); while(!matches && iter.hasNext()) { Topic type=(Topic)iter.next(); Hashtable versiondata=t.getData(type); Iterator iter2=versiondata.entrySet().iterator(); while(!matches && iter2.hasNext()){ Map.Entry e=(Map.Entry) iter2.next(); Topic version=(Topic)e.getKey(); String data=(String)e.getValue(); if(searchMatch(data, p)) { searchResult.add(t); matches = true; break; } } } if(matches) continue; } // --- locator --- if(options.searchSL) { Locator locator = t.getSubjectLocator(); if(locator != null) { if(searchMatch(locator.toExternalForm(), p)) { searchResult.add(t); continue; } } } // --- sis --- if(options.searchSIs) { Collection sis = t.getSubjectIdentifiers(); Iterator siiter = sis.iterator(); Locator locator = null; boolean matches = false; while(!matches && siiter.hasNext()) { locator = (Locator) siiter.next(); if(locator != null) { if(searchMatch(locator.toExternalForm(), p)) { searchResult.add(t); matches = true; break; } } } if(matches) continue; } } catch (Exception e) { e.printStackTrace(); } } return searchResult; } private boolean searchMatch(String s, Pattern p) { try { Matcher m = p.matcher(s); if(m != null) { return m.find(); } } catch (Exception e) {} return false; } // ------------------------------------------------------------------------- @Override public TopicMapStatData getStatistics(TopicMapStatOptions options) throws TopicMapException { if(options == null) return null; int option = options.getOption(); switch(option) { case TopicMapStatOptions.NUMBER_OF_TOPICS: { return new TopicMapStatData(topics.size()); } case TopicMapStatOptions.NUMBER_OF_TOPIC_CLASSES: { // TODO: WHY typeIndex IS NOT GOOD HERE. // UNDO/REDO CAUSES THE typeIndex LEAK. HashSet typeTopics = new LinkedHashSet(); synchronized(topics) { for(Topic t : topics) { if(t != null && !t.isRemoved()) { Collection<Topic> cts = t.getTypes(); if(cts != null && !cts.isEmpty()) { for(Topic ct : cts) { typeTopics.add(ct); } } } } } return new TopicMapStatData(typeTopics.size()); } case TopicMapStatOptions.NUMBER_OF_ASSOCIATIONS: { return new TopicMapStatData(associations.size()); } case TopicMapStatOptions.NUMBER_OF_ASSOCIATION_PLAYERS: { HashSet associationPlayers = new LinkedHashSet(); Collection associationRoles = null; Iterator<Association> associationIter = null; Iterator<Topic> associationRoleIter = null; Association association = null; Topic role = null; synchronized(associations) { associationIter = associations.iterator(); while(associationIter.hasNext()) { association = associationIter.next(); if(association != null && !association.isRemoved()) { associationRoles = association.getRoles(); if(associationRoles != null) { synchronized(associationRoles) { if(!associationRoles.isEmpty()) { associationRoleIter = associationRoles.iterator(); while(associationRoleIter.hasNext()) { role = associationRoleIter.next(); if(role != null && !role.isRemoved()) { associationPlayers.add(association.getPlayer(role)); } } } } } } } } return new TopicMapStatData(associationPlayers.size()); } case TopicMapStatOptions.NUMBER_OF_ASSOCIATION_ROLES: { HashSet associationRoles = new LinkedHashSet(); Association association = null; synchronized(associations) { Iterator<Association> associationIter = associations.iterator(); while(associationIter.hasNext()) { association = associationIter.next(); if(association != null && !association.isRemoved()) { associationRoles.addAll( association.getRoles() ); } } } return new TopicMapStatData(associationRoles.size()); } case TopicMapStatOptions.NUMBER_OF_ASSOCIATION_TYPES: { // TODO: WHY associationTypeIndex IS NOT GOOD HERE. // UNDO/REDO CAUSES THE associationTypeIndex LEAK. HashSet associationTypes = new LinkedHashSet(); Topic typeTopic = null; synchronized(associations) { Iterator<Association> associationsIterator = associations.iterator(); while(associationsIterator.hasNext()) { Association a = associationsIterator.next(); if(a != null && !a.isRemoved()) { typeTopic = a.getType(); associationTypes.add(typeTopic); } } } return new TopicMapStatData(associationTypes.size()); } case TopicMapStatOptions.NUMBER_OF_BASE_NAMES: { return new TopicMapStatData(this.nameIndex.size()); } case TopicMapStatOptions.NUMBER_OF_OCCURRENCES: { int count=0; Topic t = null; Collection<Topic> dataTypes = null; synchronized(topics) { Iterator topicIter=topics.iterator(); while(topicIter.hasNext()) { t=(Topic) topicIter.next(); if(t != null) { dataTypes = t.getDataTypes(); if(dataTypes != null && !dataTypes.isEmpty()) { for(Topic dataType : dataTypes) { Hashtable<Topic,String> scopedOccurrence = t.getData(dataType); count += scopedOccurrence.size(); } } } } } return new TopicMapStatData(count); } case TopicMapStatOptions.NUMBER_OF_SUBJECT_IDENTIFIERS: { return new TopicMapStatData(this.subjectIdentifierIndex.size()); } case TopicMapStatOptions.NUMBER_OF_SUBJECT_LOCATORS: { return new TopicMapStatData(this.subjectLocatorIndex.size()); } } return new TopicMapStatData(); } }
39,032
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AssociationImpl.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/memory/AssociationImpl.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * AssociationImpl.java * * Created on June 10, 2004, 11:30 AM */ package org.wandora.topicmap.memory; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import org.wandora.topicmap.Association; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicMapReadOnlyException; /** * TODO: maybe we should check for duplicate associations when modifying association and throw an exception if found * * @author olli */ public class AssociationImpl implements Association { private TopicMapImpl topicMap; private Topic type; private Map<Topic,Topic> players; private boolean removed; /** Creates a new instance of AssociationImpl */ public AssociationImpl(TopicMapImpl topicMap, Topic type) throws TopicMapException { this.topicMap=topicMap; players=Collections.synchronizedMap(new LinkedHashMap()); setType(type); removed=false; } @Override public Topic getPlayer(Topic role) { return players.get(role); } @Override public Collection<Topic> getRoles() { return players.keySet(); } @Override public TopicMap getTopicMap() { return topicMap; } @Override public Topic getType() { return type; } @Override public void setType(Topic t) throws TopicMapException { if(removed) throw new TopicMapException(); if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); topicMap.setAssociationType(this,t,type); Topic oldType=type; if(type!=null) ((TopicImpl)type).removedFromAssociationType(this); boolean changed=( (type!=null || t!=null) && ( type==null || t==null || !type.equals(t) ) ); type=t; if(t!=null) ((TopicImpl)t).addedAsAssociationType(this); Iterator iter=players.entrySet().iterator(); while(iter.hasNext()) { Map.Entry e=(Map.Entry)iter.next(); ((TopicImpl)e.getValue()).associationTypeChanged(this,t,oldType,(Topic)e.getKey()); } if(changed) { topicMap.associationTypeChanged(this,t,oldType); if(topicMap.getConsistencyCheck()) checkRedundancy(); } } @Override public void addPlayer(Topic player, Topic role) throws TopicMapException { if(removed) throw new TopicMapException(); if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); if(role == null || player == null) return; // if(players.containsKey(role)) return; // TODO: exception, note also that DatabaseAssociation replaces old // ((TopicImpl)player).addInAssociation(this,role); // ((TopicImpl)role).addedAsRoleType(this); TopicImpl oldPlayer=null; if(players.containsKey(role)) { oldPlayer=(TopicImpl)players.get(role); if(oldPlayer.equals(player)) return; // don't need to do anything players.remove(role); oldPlayer.removeFromAssociation(this, role, players.values().contains(oldPlayer)); ((TopicImpl)player).addInAssociation(this,role); } else { ((TopicImpl)player).addInAssociation(this,role); ((TopicImpl)role).addedAsRoleType(this); } players.put(role,player); if(oldPlayer==null || !oldPlayer.equals(player)) { topicMap.associationPlayerChanged(this,role,player,oldPlayer); if(topicMap.getConsistencyCheck()) { checkRedundancy(); } } } @Override public void addPlayers(Map<Topic,Topic> newPlayers) throws TopicMapException { if(removed) throw new TopicMapException(); if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); boolean changed=false; for(Map.Entry<Topic,Topic> e : newPlayers.entrySet()) { TopicImpl role=(TopicImpl)e.getKey(); TopicImpl player=(TopicImpl)e.getValue(); // if(players.containsKey(role)) continue; // TODO: same as above // player.addInAssociation(this,role); // role.addedAsRoleType(this); TopicImpl oldPlayer=null; if(players.containsKey(role)) { oldPlayer=(TopicImpl)players.get(role); if(oldPlayer.equals(player)) continue; players.remove(role); oldPlayer.removeFromAssociation(this, role, players.values().contains(oldPlayer)); player.addInAssociation(this,role); } else { player.addInAssociation(this,role); role.addedAsRoleType(this); } players.put(role,player); if(oldPlayer==null || !oldPlayer.equals(player)) { changed=true; topicMap.associationPlayerChanged(this,role,player,oldPlayer); } } if(topicMap.getConsistencyCheck()) checkRedundancy(); } @Override public void removePlayer(Topic role) throws TopicMapException { if(removed) throw new TopicMapException(); if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); TopicImpl t=(TopicImpl)players.get(role); if(t!=null) { players.remove(role); t.removeFromAssociation(this,role,players.values().contains(t)); ((TopicImpl)role).removedFromRoleType(this); topicMap.associationPlayerChanged(this,role,null,t); if(!removed) { if(topicMap.getConsistencyCheck()) checkRedundancy(); } } } @Override public void remove() throws TopicMapException { if(removed) throw new TopicMapException(); if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); removed=true; topicMap.associationRemoved(this); ArrayList<Topic> roles = new ArrayList<>(players.keySet()); for(Topic role : roles) { TopicImpl t=(TopicImpl)players.get(role); if(t!=null) { players.remove(role); t.removeFromAssociation(this,role,players.values().contains(t)); ((TopicImpl)role).removedFromRoleType(this); topicMap.associationPlayerChanged(this,role,null,t); } } // set type null topicMap.setAssociationType(this, null, type); Topic oldType=type; if(type != null) ((TopicImpl)type).removedFromAssociationType(this); type = null; if(oldType != null) { topicMap.associationTypeChanged(this, null, oldType); } } @Override public boolean isRemoved(){ return removed; } void checkRedundancy() throws TopicMapException { if(removed) throw new TopicMapException(); if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); if(players.isEmpty()) return; if(type==null) return; Collection<AssociationImpl> smallest=null; for(Topic role : players.keySet()) { Topic player = players.get(role); Collection c = player.getAssociations(type,role); if(smallest==null || c.size()<smallest.size()) { smallest=c; } } Set<Association> delete = new HashSet<Association>(); for(AssociationImpl a : smallest) { if(a==this) continue; if(a._equals(this)) { delete.add(a); } } for(Association a : delete) { topicMap.duplicateAssociationRemoved(this,a); a.remove(); } } int _hashCode() { return players.hashCode()+type.hashCode(); } boolean _equals(AssociationImpl a) { if(a == null) return false; if((players == null && a.players != null) || (players != null && a.players == null)) return false; if(players != null && a.players != null && players.size() != a.players.size()) return false; if(type != a.type) return false; if(players != null && a.players != null) { for(Topic r : players.keySet()) { if(players.get(r) != a.players.get(r)) { return false; } } } return true; } }
9,642
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicImpl.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/memory/TopicImpl.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * TopicImpl.java * * Created on June 10, 2004, 11:30 AM */ package org.wandora.topicmap.memory; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicInUseException; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicMapReadOnlyException; import org.wandora.topicmap.TopicRemovedException; import org.wandora.utils.Tuples; import org.wandora.utils.Tuples.T2; /** * * @author olli */ public class TopicImpl extends Topic { private TopicMapImpl topicMap; private Map<Topic,Map<Topic,String>> data; private Set<Topic> types; private Set<Association> associations; private Map<Topic,Map<Topic,Collection<Association>>> associationIndex; private String baseName; private Locator subjectLocator; private Set<Locator> subjectIdentifiers; private Map<Set<Topic>,String> variants; private Set<Topic> dataTypeIndex; private Set<DataVersionIndexWrapper> dataVersionIndex; private Set<Topic> topicTypeIndex; private Set<Association> associationTypeIndex; private Set<Association> roleTypeIndex; private Set<Topic> variantScopeIndex; private Set<Topic> dependentTopics; private String id; private boolean removed; private boolean denyRemoveIfCoreTopic = true; private long editTime; private long dependentEditTime; private Map<String,String> dispNameCache; private Map<String,String> sortNameCache; /** Creates a new instance of TopicImpl */ public TopicImpl(String id, TopicMapImpl topicMap) { this.topicMap=topicMap; this.id=id; initializeTopicImpl(); } /** Creates a new instance of TopicImpl */ public TopicImpl(TopicMapImpl topicMap) { this.topicMap=topicMap; id=getUniqueID(); initializeTopicImpl(); } private void initializeTopicImpl() { data=Collections.synchronizedMap(new LinkedHashMap()); types=Collections.synchronizedSet(new LinkedHashSet()); associations=Collections.synchronizedSet(new LinkedHashSet()); associationIndex=Collections.synchronizedMap(new LinkedHashMap()); baseName=null; subjectLocator=null; subjectIdentifiers=Collections.synchronizedSet(new LinkedHashSet()); variants=Collections.synchronizedMap(new LinkedHashMap()); dispNameCache=Collections.synchronizedMap(new LinkedHashMap()); sortNameCache=Collections.synchronizedMap(new LinkedHashMap()); dataTypeIndex=Collections.synchronizedSet(new LinkedHashSet()); dataVersionIndex=Collections.synchronizedSet(new LinkedHashSet()); topicTypeIndex=Collections.synchronizedSet(new LinkedHashSet()); associationTypeIndex=Collections.synchronizedSet(new LinkedHashSet()); roleTypeIndex=Collections.synchronizedSet(new LinkedHashSet()); variantScopeIndex=Collections.synchronizedSet(new LinkedHashSet()); removed=false; } public void clearNameCaches(){ dispNameCache.clear(); sortNameCache.clear(); } @Override public String getDisplayName(String lang) throws TopicMapException { if(dispNameCache.containsKey(lang)) return dispNameCache.get(lang); String name=super.getDisplayName(lang); dispNameCache.put(lang,name); return name; } @Override public String getSortName(String lang) throws TopicMapException { if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); if(sortNameCache.containsKey(lang)) return sortNameCache.get(lang); String name=super.getSortName(lang); sortNameCache.put(lang,name); return name; } private static long idcounter=0; public static synchronized String getUniqueID(){ return "topic"+(idcounter++)+"."+System.currentTimeMillis(); } @Override public String getID() throws TopicMapException { return id; } @Override public void setData(Topic type, Topic version, String value) throws TopicMapException { if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); if(removed) throw new TopicRemovedException(); if(value==null) { System.out.println("WRN setData called with null value, redirecting to removeData"); String old=getData(type,version); removeData(type,version); topicMap.topicDataChanged(this,type,version,null,old); return; } ((TopicImpl)type).addedAsDataType(this); ((TopicImpl)version).addedAsDataVersion(this,type); Map<Topic,String> t=data.get(type); if(t==null){ t=new LinkedHashMap(); data.put(type,t); } Object o=t.put(version,value); boolean changed=( o==null || !o.equals(value) ); dependentTopics=null; updateEditTime(); if(changed) { topicMap.topicDataChanged(this,type,version,value,(String)o); } } @Override public void setData(Topic type, Hashtable<Topic,String> versionData) throws TopicMapException { if(removed) throw new TopicRemovedException(); if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); ((TopicImpl)type).addedAsDataType(this); Map<Topic,String> t=data.get(type); if(t==null){ t=new LinkedHashMap(); data.put(type,t); } Iterator iter=versionData.entrySet().iterator(); while(iter.hasNext()){ Map.Entry e=(Map.Entry)iter.next(); Topic version=(Topic)e.getKey(); String value=(String)e.getValue(); if(value==null) throw new NullPointerException("Cannot set null data."); ((TopicImpl)version).addedAsDataVersion(this,type); Object o=t.put(version,value); boolean changed=( o==null || !o.equals(value) ); if(changed) { topicMap.topicDataChanged(this,type,version,value,(String)o); } } dependentTopics=null; updateEditTime(); } @Override public void addSubjectIdentifier(Locator l) throws TopicMapException { if(removed) throw new TopicRemovedException(); if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); Topic t=topicMap.getTopic(l); boolean changed=false; if(t!=null && t!=this) { mergeIn(t); } else { topicMap.addTopicSubjectIdentifier(this,l); changed=subjectIdentifiers.add(l); } updateEditTime(); if(changed) { topicMap.topicSubjectIdentifierChanged(this,l,null); } } @Override public void addType(Topic t) throws TopicMapException { if(removed) throw new TopicRemovedException(); if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); ((TopicImpl)t).addedAsTopicType(this); topicMap.addTopicType(this,t); boolean changed=types.add(t); dependentTopics=null; updateEditTime(); if(changed) { topicMap.topicTypeChanged(this,t,null); } } @Override public Collection<Association> getAssociations() throws TopicMapException { return associations; } @Override public Collection<Association> getAssociations(Topic type) throws TopicMapException { Map<Topic,Collection<Association>> s = associationIndex.get(type); if(s==null) { return new HashSet(); } else { Set as = Collections.synchronizedSet(new LinkedHashSet()); for(Topic role : s.keySet()) { as.addAll(s.get(role)); } return as; } } @Override public Collection<Association> getAssociations(Topic type, Topic role) throws TopicMapException { Map<Topic,Collection<Association>> s = associationIndex.get(type); if(s==null) { return new HashSet(); } else { Collection<Association> s2 = s.get(role); if(s2==null) { return new HashSet(); } else { return s2; } } } @Override public String getBaseName() throws TopicMapException { return baseName; } @Override public String getData(Topic type, Topic version) throws TopicMapException { Map<Topic,String> t=data.get(type); if(t==null) return null; else return t.get(version); } @Override public Hashtable getData(Topic type) throws TopicMapException { Map<Topic,String> t = data.get(type); if(t==null) { return new Hashtable(); } else { Hashtable<Topic,String> ht = new Hashtable(); ht.putAll(t); return ht; } } @Override public Locator getSubjectLocator() throws TopicMapException { return subjectLocator; } @Override public Collection getSubjectIdentifiers() throws TopicMapException { return subjectIdentifiers; } @Override public TopicMap getTopicMap(){ return topicMap; } @Override public Collection<Topic> getTypes() throws TopicMapException { return types; } @Override public String getVariant(Set<Topic> scope) throws TopicMapException { return (String)variants.get(scope); } @Override public boolean isOfType(Topic t) throws TopicMapException { return types.contains(t); } @Override public void removeData(Topic type) throws TopicMapException { if(removed) throw new TopicRemovedException(); if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); Map<Topic,String> t = data.remove(type); ((TopicImpl)type).removedFromDataType(this); if(t != null) { for(Topic version : t.keySet()) { ((TopicImpl)version).removedFromDataVersion(this,type); topicMap.topicDataChanged(this, type, version, null, t.get(version)); } } dependentTopics=null; updateEditTime(); } @Override public void removeData(Topic type, Topic version) throws TopicMapException { if(removed) throw new TopicRemovedException(); if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); Map<Topic,String> t = data.get(type); if(t == null) { return; } ((TopicImpl)version).removedFromDataVersion(this,type); Object o=t.remove(version); if(t.isEmpty()) { data.remove(type); ((TopicImpl)type).removedFromDataType(this); } boolean changed=(o!=null); if(changed) { topicMap.topicDataChanged(this,type,version,null,(String)o); } dependentTopics=null; updateEditTime(); } @Override public void removeSubjectIdentifier(Locator l) throws TopicMapException { if(removed) throw new TopicRemovedException(); if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); topicMap.removeTopicSubjectIdentifier(this,l); boolean changed = subjectIdentifiers.remove(l); updateEditTime(); if(changed) { topicMap.topicSubjectIdentifierChanged(this,null,l); } } @Override public void removeType(Topic t) throws TopicMapException { if(removed) throw new TopicRemovedException(); if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); topicMap.removeTopicType(this,t); boolean changed=types.remove(t); ((TopicImpl)t).removedFromTopicType(this); dependentTopics=null; updateEditTime(); if(changed) { topicMap.topicTypeChanged(this,null,t); } } @Override public void setBaseName(String name) throws TopicMapException { if(removed) throw new TopicRemovedException(); if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); Topic t=null; if(name!=null) t=topicMap.getTopicWithBaseName(name); String old=baseName; topicMap.setTopicName(this,name,baseName); boolean changed = ( (baseName!=null || name!=null) && ( baseName==null || name==null || !baseName.equals(name) ) ); baseName=name; if(t!=null && t!=this) { mergeIn(t); } updateEditTime(); clearNameCaches(); if(changed) { topicMap.topicBaseNameChanged(this,name,old); } } @Override public void setSubjectLocator(Locator l) throws TopicMapException { if(removed) throw new TopicRemovedException(); if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); Topic t=null; if(l!=null) t=topicMap.getTopicBySubjectLocator(l); Locator old=subjectLocator; topicMap.setTopicSubjectLocator(this,l,subjectLocator); boolean changed=( (subjectLocator!=null || l!=null) && ( subjectLocator==null || l==null || !subjectLocator.equals(l) ) ); subjectLocator=l; if(t!=null && t!=this){ mergeIn(t); } updateEditTime(); if(changed) { topicMap.topicSubjectLocatorChanged(this,l,old); } } @Override public long getEditTime() throws TopicMapException { return editTime; } @Override public void setEditTime(long time) throws TopicMapException { editTime=time; } @Override public void remove() throws TopicMapException { if(removed) return; if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); if(!isDeleteAllowed()) { if(!topicTypeIndex.isEmpty()) throw new TopicInUseException(this,TopicInUseException.USEDIN_TOPICTYPE); if(!dataTypeIndex.isEmpty()) throw new TopicInUseException(this,TopicInUseException.USEDIN_DATATYPE); if(!dataVersionIndex.isEmpty()) throw new TopicInUseException(this,TopicInUseException.USEDIN_DATAVERSION); if(!associationTypeIndex.isEmpty()) throw new TopicInUseException(this,TopicInUseException.USEDIN_ASSOCIATIONTYPE); if(!roleTypeIndex.isEmpty()) throw new TopicInUseException(this,TopicInUseException.USEDIN_ASSOCIATIONROLE); if(!variantScopeIndex.isEmpty()) throw new TopicInUseException(this,TopicInUseException.USEDIN_VARIANTSCOPE); } removed=true; ArrayList<Association> tempAssociations=new ArrayList(); tempAssociations.addAll(associations); for(Association a : tempAssociations) { a.remove(); } topicMap.topicRemoved(this); removed=false; // need to be false so we can clear the topic for(Locator l : subjectIdentifiers) { // don't actully remove subject identifiers because in many places they are needed to identify the deleted topic topicMap.removeTopicSubjectIdentifier(this,l); // this.removeSubjectIdentifier(l); } if(subjectLocator!=null) this.setSubjectLocator(null); if(baseName!=null) this.setBaseName(null); ArrayList<Topic> tempTypes = new ArrayList(); tempTypes.addAll(types); for(Topic t : tempTypes) { this.removeType(t); } ArrayList<Set<Topic>> tempVariantScopes = new ArrayList(); tempVariantScopes.addAll(getVariantScopes()); for(Set<Topic> scope : tempVariantScopes) { this.removeVariant(scope); } ArrayList<Topic> tempDataTypes = new ArrayList(); tempDataTypes.addAll(getDataTypes()); for(Topic dataType : tempDataTypes) { this.removeData(dataType); } updateEditTime(); removed=true; } @Override public void removeVariant(Set<Topic> scope) throws TopicMapException { if(removed) throw new TopicRemovedException(); if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); Object o=variants.remove(scope); boolean changed=(o!=null); HashSet allscopes=new HashSet(); for(Collection c : variants.keySet()) { allscopes.addAll(c); } for(Topic t : scope){ if(!allscopes.contains(t)) { ((TopicImpl) t).removedFromVariantScope(this); } } clearNameCaches(); updateEditTime(); if(changed) { topicMap.topicVariantChanged(this,scope,null,(String)o); } } @Override public void setVariant(Set<Topic> scope, String name) throws TopicMapException { if(removed) throw new TopicRemovedException(); if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); if(name == null){ System.out.println("WRN setVariant called with null value, redirecting to removeVariant"); removeVariant(scope); return; } for(Topic t : scope) { ((TopicImpl) t).addedAsVariantScope(this); } Object o = null; o = variants.put(scope,name); boolean changed=( o==null || !o.equals(name)); clearNameCaches(); updateEditTime(); if(changed) { topicMap.topicVariantChanged(this,scope,name,(String)o); } } @Override public Set<Set<Topic>> getVariantScopes() throws TopicMapException { return variants.keySet(); } @Override public Collection<Topic> getDataTypes() throws TopicMapException { return data.keySet(); } @Override public boolean isRemoved() throws TopicMapException { return removed; } /** * Notice, isDeleteAllowed doesn't return true if the topic map is * write protected or if the topic is already deleted. * * @return * @throws TopicMapException */ @Override public boolean isDeleteAllowed() throws TopicMapException { if(!topicTypeIndex.isEmpty()) return false; if(!dataTypeIndex.isEmpty()) return false; if(!dataVersionIndex.isEmpty()) return false; if(!associationTypeIndex.isEmpty()) return false; if(!roleTypeIndex.isEmpty()) return false; if(!variantScopeIndex.isEmpty()) return false; if(denyRemoveIfCoreTopic) { for(Locator l : subjectIdentifiers) { try { if(l != null && l.toExternalForm().startsWith("http://www.topicmaps.org/xtm/1.0/core.xtm")) return false; } catch (Exception e) { e.printStackTrace(); } } } return true; } @Override public long getDependentEditTime() throws TopicMapException { return dependentEditTime; } @Override public void setDependentEditTime(long time) throws TopicMapException { dependentEditTime=time; } @Override public Collection<Topic> getTopicsWithDataType() throws TopicMapException { return dataTypeIndex; } @Override public Collection<Association> getAssociationsWithType() throws TopicMapException { return associationTypeIndex; } @Override public Collection<Association> getAssociationsWithRole() throws TopicMapException { return roleTypeIndex; } @Override public Collection<Topic> getTopicsWithDataVersion() throws TopicMapException { Collection<Topic> dataVersionTopics = new ArrayList<Topic>(); for(DataVersionIndexWrapper dviw : dataVersionIndex) { dataVersionTopics.add(dviw.topic); } return dataVersionTopics; } @Override public Collection<Topic> getTopicsWithVariantScope() throws TopicMapException { return variantScopeIndex; } /* ---------------------------------------------------------------------- */ /* ------------------------------------------------- Internal methods --- */ /* ---------------------------------------------------------------------- */ private void makeDependentTopicsSet() throws TopicMapException { // ### = might not be needed, depends on what should actually be called dependent dependentTopics = new HashSet(); dependentTopics.addAll(topicTypeIndex); dependentTopics.addAll(dataTypeIndex); dependentTopics.addAll(variantScopeIndex); for(DataVersionIndexWrapper ts : dataVersionIndex) { dependentTopics.add(ts.topic); dependentTopics.add(ts.type); // ### } for(Association a : associationTypeIndex) { for(Topic role : a.getRoles()) { dependentTopics.add(role); // ### dependentTopics.add(a.getPlayer(role)); } if(a.getType() != null) dependentTopics.add(a.getType()); // ### } for(Association a : roleTypeIndex) { for(Topic role : a.getRoles()) { dependentTopics.add(role); // ### dependentTopics.add(a.getPlayer(role)); } dependentTopics.add(a.getType()); // ### } for(Association a : associations) { for(Topic role : a.getRoles()) { dependentTopics.add(role); // ### dependentTopics.add(a.getPlayer(role)); } dependentTopics.add(a.getType()); // ### } for(Topic type : types) { dependentTopics.add(type); } for(Topic dataType : data.keySet()) { dependentTopics.add(dataType); } } private void updateEditTime() throws TopicMapException { if(removed) throw new TopicRemovedException(); editTime=System.currentTimeMillis(); if(topicMap.trackingDependent()) { updateDependentEditTime(); if(dependentTopics==null) { makeDependentTopicsSet(); } for(Topic dependentTopic : dependentTopics) { ((TopicImpl) dependentTopic).updateDependentEditTime(); } } } private void updateDependentEditTime() throws TopicMapException { if(removed) throw new TopicRemovedException(); dependentEditTime=System.currentTimeMillis(); } public void mergeIn(Topic t) throws TopicMapException { if(removed) throw new TopicRemovedException(); if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); TopicImpl ti=(TopicImpl)t; topicMap.topicsMerged(this,ti); // ----- add data ----- for(Topic otype : new ArrayList<Topic>(ti.data.keySet())) { Map<Topic,String> hm = ti.data.get(otype); Hashtable ht = new Hashtable(); ht.putAll(hm); this.setData(otype, ht); ti.removeData(otype); } // ----- set base name ----- if(ti.getBaseName() != null) { String name = ti.getBaseName(); ti.setBaseName(null); this.setBaseName(name); } // ----- set subject locator ----- if(ti.getSubjectLocator() != null){ Locator l = ti.getSubjectLocator(); ti.setSubjectLocator(null); this.setSubjectLocator(l); } // ----- set types ----- for(Topic type : ti.getTypes()){ if(type == ti) this.addType(this); else this.addType(type); } // ----- set variant names ----- for(Set scope : ti.getVariantScopes()){ String name = ti.getVariant(scope); this.setVariant(scope,name); } // To prevent ConcurrentModificationException, next changes copy // data into a toBeMapped... ArrayLists first. // ----- change association players ----- ArrayList<T2<Association,Topic>> tobeMappedAssociationRoles = new ArrayList(); for(Map<Topic,Collection<Association>> roledAssociations : ti.associationIndex.values()) { for(Topic role : roledAssociations.keySet()) { Collection<Association> as = roledAssociations.get(role); for(Association a : as) { tobeMappedAssociationRoles.add( new T2(a, role) ); } } } for(T2<Association,Topic> associationAndRole : tobeMappedAssociationRoles) { Association a = associationAndRole.e1; if(a.isRemoved()) continue; Topic role = associationAndRole.e2; // a.removePlayer(role); // a.addPlayer(this,role); // this replaces the old player and is atomic so that there cannot // be an unintended merge between the remove and add a.addPlayer(this,role); } // ----- change association types ----- ArrayList<Association> tobeMappedTypedAssociations = new ArrayList(); tobeMappedTypedAssociations.addAll(ti.associationTypeIndex); for(Association a : tobeMappedTypedAssociations) { a.setType(this); } // ----- change topic types ----- ArrayList<Topic> tobeMappedTopicTypes = new ArrayList(); tobeMappedTopicTypes.addAll(ti.topicTypeIndex); for(Topic type : tobeMappedTopicTypes){ type.removeType(t); type.addType(this); } // ----- change data types ----- ArrayList<Topic> tobeMappedDataTypes = new ArrayList(); tobeMappedDataTypes.addAll(ti.dataTypeIndex); final TopicComparator topicComparator=new TopicComparator(); final ScopeComparator scopeComparator=new ScopeComparator(); // The sorting guarantees that merges in identical topic maps // always have identical results. Which occurrence ends up being used // when types of several collide is undefined but is deterministic // with the sorted array. For same rason the array is sorted for // some other cases down below, but not all of them need it. Collections.sort(tobeMappedDataTypes,topicComparator); for(Topic dataType : tobeMappedDataTypes) { Hashtable val = dataType.getData(t); dataType.removeData(t); dataType.setData(this, val); } // ----- change data versions ----- ArrayList<DataVersionIndexWrapper> tobeMappedDataVersions = new ArrayList(); tobeMappedDataVersions.addAll(ti.dataVersionIndex); Collections.sort(tobeMappedDataVersions, new Comparator<DataVersionIndexWrapper>(){ @Override public int compare(DataVersionIndexWrapper o1, DataVersionIndexWrapper o2) { int c=topicComparator.compare(o1.topic, o2.topic); if(c!=0) return c; return topicComparator.compare(o1.type, o2.type); } }); for(DataVersionIndexWrapper info : tobeMappedDataVersions) { String val=info.topic.getData(info.type,t); info.topic.removeData(info.type,t); info.topic.setData(info.type,this,val); } // ----- change role types ----- ArrayList<Association> tobeMappedRoleTypes = new ArrayList(); tobeMappedRoleTypes.addAll(ti.roleTypeIndex); for(Association a : tobeMappedRoleTypes) { Topic p = a.getPlayer(t); // Doing these in this order guarantees that we don't lose anything // to unintended merges. There might be a merge after the add, but // if that is the case, the two associations would merge in the end // anyway, so we still end up with the correct result. if(p != null) { a.addPlayer(p, this); } if(!a.isRemoved()) { a.removePlayer(t); } } // ----- change variant scopes ----- ArrayList<T2<Topic,Set<Topic>>> tobeMappedVariantScopes = new ArrayList(); for(Topic topic : ti.variantScopeIndex) { Set<Set<Topic>> scopes = new LinkedHashSet(); scopes.addAll(topic.getVariantScopes()); for(Set<Topic> c : scopes) { if(c.contains(t)) { tobeMappedVariantScopes.add(Tuples.t2(topic,c)); } } } Collections.sort(tobeMappedVariantScopes,new Comparator<Tuples.T2<Topic,Set<Topic>>>(){ @Override public int compare(Tuples.T2<Topic,Set<Topic>> t1, Tuples.T2<Topic,Set<Topic>> t2) { int c=topicComparator.compare(t1.e1, t2.e1); if(c!=0) return c; return scopeComparator.compare(t1.e2, t2.e2); } }); for(T2<Topic,Set<Topic>> t2 : tobeMappedVariantScopes) { Topic topic = t2.e1; Set c = t2.e2; Set newscope = Collections.synchronizedSet(new LinkedHashSet()); newscope.addAll(c); newscope.remove(t); newscope.add(this); String name = topic.getVariant(c); topic.removeVariant(c); topic.setVariant(newscope,name); } // set subject identifiers, do this last as some other things rely // on topics still having subject identifiers HashSet<Locator> copied=new LinkedHashSet(); copied.addAll(ti.getSubjectIdentifiers()); for(Locator l : copied) { ti.removeSubjectIdentifier(l); this.addSubjectIdentifier(l); } // check for duplicate associations removeDuplicateAssociations(); // remove merged topic try { t.remove(); } catch(TopicInUseException e){ System.out.println("ERROR couldn't delete merged topic, topic in use. There is a bug in the code if this happens. "+e.getReason()); } topicMap.topicChanged(this); } void removeDuplicateAssociations() throws TopicMapException { if(removed) throw new TopicMapException(); if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); removeDuplicateAssociations(null); } /** * Deletes duplicate associations but does not delete the one given as parameter. * If duplicate associations are found and the one given as parameter is one of * them, then the parameter will remain in the topic map and other equal * associations are deleted. If parameter is null, or when parameter is none * of the equal associations, then the one that remains in topic map is chosen arbitrarily */ void removeDuplicateAssociations(Association notThis) throws TopicMapException { if(removed) throw new TopicMapException(); if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); HashMap<EqualAssociationWrapper,Association> as = new HashMap(); ArrayList<Association> tobeDeleted = new ArrayList(); Association remaining = notThis; for(Association a : associations) { EqualAssociationWrapper eaw = new EqualAssociationWrapper((AssociationImpl) a); if(as.containsKey(eaw)) { if(notThis!=null && notThis==a){ tobeDeleted.add(as.get(eaw)); as.put(eaw,a); } else { tobeDeleted.add(a); } } else { if(remaining!=null) remaining=a; as.put(eaw,a); } } for(Association a : tobeDeleted){ topicMap.duplicateAssociationRemoved(remaining,a); a.remove(); } } void addInAssociation(Association a,Topic role) throws TopicMapException { associations.add(a); Topic type=a.getType(); Map<Topic,Collection<Association>> t = null; if(type != null) { t=associationIndex.get(type); } if(t==null){ t=new LinkedHashMap(); associationIndex.put(type,t); } Collection<Association> s = t.get(role); if(s==null){ s=new LinkedHashSet(); t.put(role,s); } s.add(a); dependentTopics=null; } void removeFromAssociation(Association a,Topic role,boolean otherRoles) throws TopicMapException { if(!otherRoles){ associations.remove(a); } Topic type=a.getType(); Map<Topic,Collection<Association>> t = associationIndex.get(type); Collection<Association> s = t.get(role); s.remove(a); if(s.isEmpty()) t.remove(role); if(t.isEmpty()) associationIndex.remove(type); dependentTopics=null; } void associationTypeChanged(Association a, Topic type, Topic oldType, Topic role){ Map<Topic,Collection<Association>> t = associationIndex.get(oldType); Collection<Association> s = t.get(role); s.remove(a); if(s.isEmpty()) t.remove(role); if(t.isEmpty()) associationIndex.remove(oldType); if(type != null){ t = associationIndex.get(type); if(t == null){ t = new LinkedHashMap(); associationIndex.put(type,t); } s = t.get(role); if(s == null){ s = new LinkedHashSet(); t.put(role,s); } s.add(a); } dependentTopics=null; } void addedAsTopicType(Topic t){ topicTypeIndex.add(t); dependentTopics=null; } void removedFromTopicType(Topic t){ topicTypeIndex.remove(t); dependentTopics=null; } void addedAsDataType(Topic t){ dataTypeIndex.add(t); dependentTopics=null; } void removedFromDataType(Topic t){ dataTypeIndex.remove(t); dependentTopics=null; } void addedAsDataVersion(Topic t,Topic type){ dataVersionIndex.add(new DataVersionIndexWrapper(t,type)); dependentTopics=null; } void removedFromDataVersion(Topic t,Topic type){ dataVersionIndex.remove(new DataVersionIndexWrapper(t,type)); dependentTopics=null; } void addedAsAssociationType(Association a){ associationTypeIndex.add(a); dependentTopics=null; } void removedFromAssociationType(Association a){ associationTypeIndex.remove(a); dependentTopics=null; } void addedAsRoleType(Association a){ roleTypeIndex.add(a); dependentTopics=null; } void removedFromRoleType(Association a){ roleTypeIndex.remove(a); dependentTopics=null; } void addedAsVariantScope(Topic t){ variantScopeIndex.add(t); dependentTopics=null; } void removedFromVariantScope(Topic t){ variantScopeIndex.remove(t); dependentTopics=null; } private class EqualAssociationWrapper { public AssociationImpl a; public EqualAssociationWrapper(AssociationImpl a){ this.a=a; } @Override public boolean equals(Object o){ if(o != null && o instanceof EqualAssociationWrapper) { return a._equals(((EqualAssociationWrapper)o).a); } else { return false; } } @Override public int hashCode(){ return a._hashCode(); } } private static class TopicComparator implements Comparator<Topic> { @Override public int compare(Topic o1, Topic o2) { try { Locator l1=o1.getFirstSubjectIdentifier(); Locator l2=o2.getFirstSubjectIdentifier(); if(l1==null && l2==null) return 0; else if(l1==null) return -1; else if(l2==null) return 1; else return l1.compareTo(l2); } catch(TopicMapException tme){ tme.printStackTrace(); return 0; } } } private static class ScopeComparator implements Comparator<Set<Topic>>{ private TopicComparator topicComparator=new TopicComparator(); @Override public int compare(Set<Topic> o1, Set<Topic> o2) { if(o1.size()<o2.size()) return -1; else if(o1.size()>o2.size()) return 1; if(o1.size()==1) { return topicComparator.compare(o1.iterator().next(),o2.iterator().next()); } List<Topic> l1=new ArrayList<Topic>(o1); List<Topic> l2=new ArrayList<Topic>(o2); Collections.sort(l1,topicComparator); Collections.sort(l2,topicComparator); for(int i=0;i<l1.size();i++) { int c=topicComparator.compare(l1.get(i),l2.get(i)); if(c!=0) return c; } return 0; } } } class DataVersionIndexWrapper { public Topic topic; public Topic type; public DataVersionIndexWrapper(Topic topic,Topic type){ this.topic=topic; this.type=type; } @Override public int hashCode(){ return topic.hashCode()+type.hashCode(); } @Override public boolean equals(Object o){ if(o != null && o instanceof DataVersionIndexWrapper) { DataVersionIndexWrapper w=(DataVersionIndexWrapper)o; return w.type.equals(type) && w.topic.equals(topic); } else { return false; } } }
39,823
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MemoryConfiguration.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/memory/MemoryConfiguration.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * MemoryConfiguration.java * * Created on 24. marraskuuta 2005, 13:42 */ package org.wandora.topicmap.memory; import javax.swing.JFileChooser; import org.wandora.application.Wandora; import org.wandora.topicmap.TopicMapConfigurationPanel; /** * * @author olli */ public class MemoryConfiguration extends TopicMapConfigurationPanel { public static final String LOAD_MINI_SCHEMA_PARAM = "LOAD_MINI_SCHEMA_PARAM"; Wandora admin = null; /** Creates new form MemoryConfiguration */ public MemoryConfiguration(Wandora admin) { initComponents(); } public String getParameters() { if(loadMiniSchemaRadioButton.isSelected()) { return LOAD_MINI_SCHEMA_PARAM; } if(loadRadioButton.isSelected()) return sourceTextField.getText(); else return ""; } /** 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; buttonGroup1 = new javax.swing.ButtonGroup(); jPanel1 = new javax.swing.JPanel(); emptyRadioButton = new org.wandora.application.gui.simple.SimpleRadioButton(); loadMiniSchemaRadioButton = new org.wandora.application.gui.simple.SimpleRadioButton(); loadXTMPanel = new javax.swing.JPanel(); loadRadioButton = new org.wandora.application.gui.simple.SimpleRadioButton(); sourceTextField = new org.wandora.application.gui.simple.SimpleField(); browseButton = new org.wandora.application.gui.simple.SimpleButton(); setLayout(new java.awt.GridBagLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL; gridBagConstraints.weighty = 1.0; add(jPanel1, gridBagConstraints); buttonGroup1.add(emptyRadioButton); emptyRadioButton.setSelected(true); emptyRadioButton.setText("Empty"); emptyRadioButton.setToolTipText("Leave the created topic map layer empty"); emptyRadioButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { emptyRadioButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 0.5; gridBagConstraints.insets = new java.awt.Insets(5, 8, 0, 5); add(emptyRadioButton, gridBagConstraints); buttonGroup1.add(loadMiniSchemaRadioButton); loadMiniSchemaRadioButton.setText("Load mini schema"); loadMiniSchemaRadioButton.setToolTipText("Load minimal Wandora schema to the created topic map"); loadMiniSchemaRadioButton.setBorder(javax.swing.BorderFactory.createEmptyBorder(4, 4, 4, 4)); loadMiniSchemaRadioButton.setPreferredSize(new java.awt.Dimension(110, 23)); loadMiniSchemaRadioButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { loadMiniSchemaRadioButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 0.5; gridBagConstraints.insets = new java.awt.Insets(5, 8, 0, 5); add(loadMiniSchemaRadioButton, gridBagConstraints); loadXTMPanel.setLayout(new java.awt.GridBagLayout()); buttonGroup1.add(loadRadioButton); loadRadioButton.setText("Load XTM"); loadRadioButton.setToolTipText("Load given XTM topic map the created topic map layer"); loadRadioButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { loadRadioButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); loadXTMPanel.add(loadRadioButton, gridBagConstraints); sourceTextField.setEnabled(false); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 3.0; gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 5); loadXTMPanel.add(sourceTextField, gridBagConstraints); browseButton.setText("Browse"); browseButton.setEnabled(false); browseButton.setMargin(new java.awt.Insets(2, 6, 2, 6)); browseButton.setMinimumSize(new java.awt.Dimension(69, 25)); browseButton.setPreferredSize(new java.awt.Dimension(69, 25)); browseButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { browseButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 2; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 8); loadXTMPanel.add(browseButton, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 8, 0, 0); add(loadXTMPanel, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents private void loadMiniSchemaRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadMiniSchemaRadioButtonActionPerformed sourceTextField.setEnabled(false); browseButton.setEnabled(false); }//GEN-LAST:event_loadMiniSchemaRadioButtonActionPerformed private void loadRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadRadioButtonActionPerformed sourceTextField.setEnabled(true); browseButton.setEnabled(true); }//GEN-LAST:event_loadRadioButtonActionPerformed private void emptyRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_emptyRadioButtonActionPerformed sourceTextField.setEnabled(false); browseButton.setEnabled(false); }//GEN-LAST:event_emptyRadioButtonActionPerformed private void browseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseButtonActionPerformed JFileChooser fc=new JFileChooser(); int c=fc.showOpenDialog(this.getParent()); if(c==JFileChooser.APPROVE_OPTION){ sourceTextField.setText(fc.getSelectedFile().getAbsolutePath()); } }//GEN-LAST:event_browseButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton browseButton; private javax.swing.ButtonGroup buttonGroup1; private javax.swing.JRadioButton emptyRadioButton; private javax.swing.JPanel jPanel1; private javax.swing.JRadioButton loadMiniSchemaRadioButton; private javax.swing.JRadioButton loadRadioButton; private javax.swing.JPanel loadXTMPanel; private javax.swing.JTextField sourceTextField; // End of variables declaration//GEN-END:variables }
9,362
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MemoryTopicMapType.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/memory/MemoryTopicMapType.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * MemoryTopicMapType.java * * Created on 24. marraskuuta 2005, 13:41 */ package org.wandora.topicmap.memory; import javax.swing.Icon; import org.wandora.application.Wandora; import org.wandora.application.gui.UIBox; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapConfigurationPanel; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicMapLogger; import org.wandora.topicmap.TopicMapType; import org.wandora.topicmap.packageio.PackageInput; import org.wandora.topicmap.packageio.PackageOutput; import org.wandora.utils.Options; /** * * @author olli */ public class MemoryTopicMapType implements TopicMapType { /** Creates a new instance of MemoryTopicMapType */ public MemoryTopicMapType() { } @Override public String getTypeName(){ return "Memory"; } @Override public TopicMap createTopicMap(Object params) throws TopicMapException { TopicMapImpl tm=new TopicMapImpl(); if(params instanceof String && params != null) { String load = (String) params; if(MemoryConfiguration.LOAD_MINI_SCHEMA_PARAM.equals(params)) { load="conf/wandora_mini.xtm"; } if(load!=null && load.length()>0) { try { tm.importXTM(load); } catch(java.io.IOException ioe){ ioe.printStackTrace(); // TODO } } } return tm; } @Override public TopicMap modifyTopicMap(TopicMap tm, Object params) throws TopicMapException { return tm; } @Override public TopicMapConfigurationPanel getConfigurationPanel(Wandora wandora, Options options){ MemoryConfiguration mc=new MemoryConfiguration(wandora); return mc; } @Override public TopicMapConfigurationPanel getModifyConfigurationPanel(Wandora wandora, Options options, TopicMap tm) { return null; } @Override public String toString() { return getTypeName(); } @Override public void packageTopicMap(TopicMap tm, PackageOutput out, String path, TopicMapLogger logger) throws java.io.IOException,TopicMapException { out.nextEntry(path, "topicmap.xtm"); tm.exportXTM(out.getOutputStream(), logger); } @Override public TopicMap unpackageTopicMap(PackageInput in, String path, TopicMapLogger logger,Wandora wandora) throws java.io.IOException,TopicMapException { TopicMapImpl tm = new TopicMapImpl(); boolean found = in.gotoEntry(path, "topicmap.xtm"); if(!found) { logger.log("Couldn't find topicmap file '"+in.joinPath(path,"topicmap.xtm")+"'."); return null; } else { tm.importXTM(in.getInputStream(), logger); } return tm; } @Override public TopicMap unpackageTopicMap(TopicMap topicmap, PackageInput in, String path, TopicMapLogger logger,Wandora wandora) throws java.io.IOException,TopicMapException { if(topicmap == null) { topicmap = new TopicMapImpl(); } boolean found = in.gotoEntry(path, "topicmap.xtm"); if(!found) { logger.log("Couldn't find topicmap file '"+in.joinPath(path, "topicmap.xtm")+"'."); return null; } else { topicmap.importXTM(in.getInputStream(), logger); } return topicmap; } @Override public javax.swing.JMenuItem[] getTopicMapMenu(TopicMap tm,Wandora admin){ return null; } @Override public Icon getTypeIcon(){ // return UIBox.getIcon("gui/icons/layerinfo/layer_type_memory.png"); return UIBox.getIcon(0xf1b2); } }
4,745
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
LinkedTopicMap.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/linked/LinkedTopicMap.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.topicmap.linked; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicIterator; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicMapListener; import org.wandora.topicmap.TopicMapReadOnlyException; import org.wandora.topicmap.TopicMapSearchOptions; import org.wandora.topicmap.TopicMapStatData; import org.wandora.topicmap.TopicMapStatOptions; import org.wandora.topicmap.layered.ContainerTopicMap; import org.wandora.topicmap.layered.ContainerTopicMapListener; import org.wandora.topicmap.layered.Layer; /** * * @author olli */ public class LinkedTopicMap extends TopicMap implements TopicMapListener, ContainerTopicMapListener { protected TopicMap linkedMap; protected Layer linkedLayer; protected ContainerTopicMap wrappedContainer; protected ArrayList<TopicMapListener> topicMapListeners; protected String wrappedName; public LinkedTopicMap(TopicMap linkedMap){ setLinkedMap(linkedMap); this.topicMapListeners=new ArrayList<TopicMapListener>(); } public LinkedTopicMap(String wrappedName){ this.wrappedName=wrappedName; this.topicMapListeners=new ArrayList<TopicMapListener>(); } // ------------------------------------------------------------------------- @Override public void close() { } public TopicMap getLinkedTopicMap(){ if(linkedMap==null && !findLinkedMap()) return null; return linkedMap; } protected void unlinkMap(){ if(linkedLayer!=null) wrappedName=linkedLayer.getName(); linkedMap=null; linkedLayer=null; } protected void setLinkedMap(Layer l){ linkedLayer=l; linkedMap=l.getTopicMap(); wrappedName=l.getName(); if(wrappedContainer!=null) wrappedContainer.removeContainerListener(this); wrappedContainer=(ContainerTopicMap)linkedMap.getParentTopicMap(); if(wrappedContainer!=null) wrappedContainer.addContainerListener(this); } protected void setLinkedMap(TopicMap tm){ linkedMap=tm; TopicMap root=this.getRootTopicMap(); if(root==null || root==this || !(root instanceof ContainerTopicMap)) return; ContainerTopicMap rootStack=(ContainerTopicMap)root; for(Layer l : rootStack.getTreeLayers()){ if(l.getTopicMap()==tm){ linkedLayer=l; wrappedName=l.getName(); if(wrappedContainer!=null) wrappedContainer.removeContainerListener(this); wrappedContainer=(ContainerTopicMap)linkedMap.getParentTopicMap(); if(wrappedContainer!=null) wrappedContainer.addContainerListener(this); break; } } } protected boolean findLinkedMap(){ if(wrappedName==null) return false; TopicMap root=this.getRootTopicMap(); if(root==null || root==this || !(root instanceof ContainerTopicMap)) return false; ContainerTopicMap rootStack=(ContainerTopicMap)root; Layer l=rootStack.getTreeLayer(wrappedName); if(l==null) return false; setLinkedMap(l); if(topicMapListeners.size()>0) linkedMap.addTopicMapListener(this); return true; } public LinkedTopic getLinkedTopic(Topic t){ if(t==null) return null; return new LinkedTopic(t,this); } public LinkedAssociation getLinkedAssociation(Association a){ if(a==null) return null; return new LinkedAssociation(a,this); } public Collection<Topic> getLinkedTopics(Collection<Topic> topics){ ArrayList<Topic> ret=new ArrayList<Topic>(); for(Topic t : topics){ ret.add(getLinkedTopic(t)); } return ret; } public Set<Topic> getLinkedTopics(Set<Topic> topics){ HashSet<Topic> ret=new HashSet<Topic>(); for(Topic t : topics){ ret.add(getLinkedTopic(t)); } return ret; } public Collection<Association> getLinkedAssociations(Collection<Association> associations){ ArrayList<Association> ret=new ArrayList<Association>(); for(Association a : associations){ ret.add(getLinkedAssociation(a)); } return ret; } public Topic getUnlinkedTopic(Topic t){ if(t==null) return null; return ((LinkedTopic)t).getWrappedTopic(); } public Association getUnlinkedAssociation(Association a){ if(a==null) return null; return ((LinkedAssociation)a).getWrappedAssociation(); } public Collection<Topic> getUnlinkedTopics(Collection<Topic> topics){ ArrayList<Topic> ret=new ArrayList<Topic>(); for(Topic t : topics){ ret.add(getUnlinkedTopic(t)); } return ret; } public Set<Topic> getUnlinkedSetOfTopics(Set<Topic> topics){ HashSet<Topic> ret=new HashSet<Topic>(); for(Topic t : topics){ ret.add(getUnlinkedTopic(t)); } return ret; } public Collection<Association> getUnlinkedAssociations(Collection<Association> associations){ ArrayList<Association> ret=new ArrayList<Association>(); for(Association a : associations){ ret.add(getUnlinkedAssociation(a)); } return ret; } public List<TopicMapListener> getTopicMapListeners(){ return topicMapListeners; } @Override public void addTopicMapListener(TopicMapListener listener) { if(topicMapListeners.isEmpty() && linkedMap!=null) linkedMap.addTopicMapListener(this); if(!topicMapListeners.contains(listener)) topicMapListeners.add(listener); } @Override public void removeTopicMapListener(TopicMapListener listener) { topicMapListeners.add(listener); if(topicMapListeners.size()==0 && linkedMap!=null) linkedMap.removeTopicMapListener(this); } @Override public void clearTopicMap() throws TopicMapException { if(isReadOnly()) throw new TopicMapReadOnlyException(); if(linkedMap==null && !findLinkedMap()) return; linkedMap.clearTopicMap(); } @Override public void clearTopicMapIndexes() throws TopicMapException { if(linkedMap==null && !findLinkedMap()) return; linkedMap.clearTopicMapIndexes(); } @Override public Association copyAssociationIn(Association a) throws TopicMapException { if(isReadOnly()) throw new TopicMapReadOnlyException(); if(linkedMap==null && !findLinkedMap()) return null; return linkedMap.copyAssociationIn(a); } @Override public void copyTopicAssociationsIn(Topic t) throws TopicMapException { if(isReadOnly()) throw new TopicMapReadOnlyException(); if(linkedMap==null && !findLinkedMap()) return; linkedMap.copyTopicAssociationsIn(t); } @Override public Topic copyTopicIn(Topic t, boolean deep) throws TopicMapException { if(isReadOnly()) throw new TopicMapReadOnlyException(); if(linkedMap==null && !findLinkedMap()) return null; return linkedMap.copyTopicIn(t,deep); } @Override public Association createAssociation(Topic type) throws TopicMapException { if(isReadOnly()) throw new TopicMapReadOnlyException(); if(linkedMap==null && !findLinkedMap()) return null; return getLinkedAssociation(linkedMap.createAssociation(getUnlinkedTopic(type))); } @Override public Topic createTopic(String id) throws TopicMapException { if(isReadOnly()) throw new TopicMapReadOnlyException(); if(linkedMap==null && !findLinkedMap()) return null; return getLinkedTopic(linkedMap.createTopic(id)); } @Override public Topic createTopic() throws TopicMapException { if(isReadOnly()) throw new TopicMapReadOnlyException(); if(linkedMap==null && !findLinkedMap()) return null; return getLinkedTopic(linkedMap.createTopic()); } @Override public void disableAllListeners() { if(linkedMap==null && !findLinkedMap()) return; linkedMap.disableAllListeners(); } @Override public void enableAllListeners() { if(linkedMap==null && !findLinkedMap()) return; linkedMap.enableAllListeners(); } @Override public Iterator<Association> getAssociations() throws TopicMapException { if(linkedMap==null && !findLinkedMap()) return new ArrayList<Association>().iterator(); final Iterator<Association> iter=linkedMap.getAssociations(); return new Iterator<Association>(){ public boolean hasNext() { return iter.hasNext(); } public Association next() { return getLinkedAssociation(iter.next()); } public void remove() { iter.remove(); } }; } @Override public Collection<Association> getAssociationsOfType(Topic type) throws TopicMapException { if(linkedMap==null && !findLinkedMap()) return new ArrayList<Association>(); return getLinkedAssociations(linkedMap.getAssociationsOfType(getUnlinkedTopic(type))); } @Override public int getNumAssociations() throws TopicMapException { if(linkedMap==null && !findLinkedMap()) return 0; return linkedMap.getNumAssociations(); } @Override public int getNumTopics() throws TopicMapException { if(linkedMap==null && !findLinkedMap()) return 0; return linkedMap.getNumTopics(); } @Override public TopicMapStatData getStatistics(TopicMapStatOptions options) throws TopicMapException { if(linkedMap==null && !findLinkedMap()) return null; return linkedMap.getStatistics(options); } @Override public Topic getTopic(Locator si) throws TopicMapException { if(linkedMap==null && !findLinkedMap()) return null; return getLinkedTopic(linkedMap.getTopic(si)); } @Override public Topic getTopicBySubjectLocator(Locator sl) throws TopicMapException { if(linkedMap==null && !findLinkedMap()) return null; return getLinkedTopic(linkedMap.getTopicBySubjectLocator(sl)); } @Override public Topic getTopicWithBaseName(String name) throws TopicMapException { if(linkedMap==null && !findLinkedMap()) return null; return getLinkedTopic(linkedMap.getTopicWithBaseName(name)); } @Override public Iterator<Topic> getTopics() throws TopicMapException { if(linkedMap==null && !findLinkedMap()) return new ArrayList<Topic>().iterator(); final Iterator<Topic> iter=linkedMap.getTopics(); return new TopicIterator(){ @Override public void dispose() { if(iter instanceof TopicIterator) ((TopicIterator)iter).dispose(); else while(iter.hasNext()) iter.next(); } public boolean hasNext() { return iter.hasNext(); } public Topic next() { return getLinkedTopic(iter.next()); } public void remove() { iter.remove(); } }; } @Override public Topic[] getTopics(String[] sis) throws TopicMapException { if(linkedMap==null && !findLinkedMap()) return new Topic[sis.length]; Topic[] ts=linkedMap.getTopics(sis); Topic[] ret=new Topic[ts.length]; for(int i=0;i<ts.length;i++){ ret[i]=getLinkedTopic(ts[i]); } return ret; } @Override public Collection<Topic> getTopicsOfType(Topic type) throws TopicMapException { if(linkedMap==null && !findLinkedMap()) return null; return getLinkedTopics(linkedMap.getTopicsOfType(getUnlinkedTopic(type))); } @Override public boolean isTopicMapChanged() throws TopicMapException { if(linkedMap==null && !findLinkedMap()) return false; return linkedMap.isTopicMapChanged(); } @Override public boolean resetTopicMapChanged() throws TopicMapException { if(linkedMap==null && !findLinkedMap()) return false; return linkedMap.resetTopicMapChanged(); } @Override public Collection<Topic> search(String query, TopicMapSearchOptions options) throws TopicMapException { if(linkedMap==null && !findLinkedMap()) return new ArrayList<Topic>(); return getLinkedTopics(linkedMap.search(query,options)); } @Override public void setTrackDependent(boolean v) throws TopicMapException { if(linkedMap==null && !findLinkedMap()) return; linkedMap.setTrackDependent(v); } @Override public boolean trackingDependent() throws TopicMapException { if(linkedMap==null && !findLinkedMap()) return false; return linkedMap.trackingDependent(); } // -------------------------------------------------- TOPIC MAP LISTENER --- @Override public void associationChanged(Association a) throws TopicMapException { Association wa=getLinkedAssociation(a); for(TopicMapListener listener : topicMapListeners){ listener.associationChanged(wa); } } @Override public void associationPlayerChanged(Association a, Topic role, Topic newPlayer, Topic oldPlayer) throws TopicMapException { Association wa=getLinkedAssociation(a); Topic wrole=getLinkedTopic(role); Topic wNewPlayer=getLinkedTopic(newPlayer); Topic wOldPlayer=getLinkedTopic(oldPlayer); for(TopicMapListener listener : topicMapListeners){ listener.associationPlayerChanged(wa,wrole,wNewPlayer,wOldPlayer); } } @Override public void associationRemoved(Association a) throws TopicMapException { Association wa=getLinkedAssociation(a); for(TopicMapListener listener : topicMapListeners){ listener.associationRemoved(wa); } } @Override public void associationTypeChanged(Association a, Topic newType, Topic oldType) throws TopicMapException { Association wa=getLinkedAssociation(a); Topic wNewType=getLinkedTopic(newType); Topic wOldType=getLinkedTopic(oldType); for(TopicMapListener listener : topicMapListeners){ listener.associationTypeChanged(wa,wNewType,wOldType); } } @Override public void topicBaseNameChanged(Topic t, String newName, String oldName) throws TopicMapException { Topic wt=getLinkedTopic(t); for(TopicMapListener listener : topicMapListeners){ listener.topicBaseNameChanged(wt,newName,oldName); } } @Override public void topicChanged(Topic t) throws TopicMapException { Topic wt=getLinkedTopic(t); for(TopicMapListener listener : topicMapListeners){ listener.topicChanged(wt); } } @Override public void topicDataChanged(Topic t, Topic type, Topic version, String newValue, String oldValue) throws TopicMapException { Topic wt=getLinkedTopic(t); Topic wtype=getLinkedTopic(type); Topic wversion=getLinkedTopic(version); for(TopicMapListener listener : topicMapListeners){ listener.topicDataChanged(wt,wtype,wversion,newValue,oldValue); } } @Override public void topicRemoved(Topic t) throws TopicMapException { Topic wt=getLinkedTopic(t); for(TopicMapListener listener : topicMapListeners){ listener.topicRemoved(wt); } } @Override public void topicSubjectIdentifierChanged(Topic t, Locator added, Locator removed) throws TopicMapException { Topic wt=getLinkedTopic(t); for(TopicMapListener listener : topicMapListeners){ listener.topicSubjectIdentifierChanged(wt,added,removed); } } @Override public void topicSubjectLocatorChanged(Topic t, Locator newLocator, Locator oldLocator) throws TopicMapException { Topic wt=getLinkedTopic(t); for(TopicMapListener listener : topicMapListeners){ listener.topicSubjectLocatorChanged(wt,newLocator,oldLocator); } } @Override public void topicTypeChanged(Topic t, Topic added, Topic removed) throws TopicMapException { Topic wt=getLinkedTopic(t); Topic wadded=getLinkedTopic(added); Topic wremoved=getLinkedTopic(removed); for(TopicMapListener listener : topicMapListeners){ listener.topicTypeChanged(wt,wadded,wremoved); } } @Override public void topicVariantChanged(Topic t, Collection<Topic> scope, String newName, String oldName) throws TopicMapException { Topic wt=getLinkedTopic(t); Collection<Topic> wscope=getLinkedTopics(scope); for(TopicMapListener listener : topicMapListeners){ listener.topicVariantChanged(wt,wscope,newName,oldName); } } // ------------------------------------------------------------------------- @Override public void layerAdded(Layer l) {} @Override public void layerChanged(Layer oldLayer, Layer newLayer) { if(oldLayer==linkedLayer) unlinkMap(); } @Override public void layerRemoved(Layer l) { if(l==linkedLayer) unlinkMap(); } @Override public void layerStructureChanged() { unlinkMap(); } @Override public void layerVisibilityChanged(Layer l) {} }
18,717
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
LinkedAssociation.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/linked/LinkedAssociation.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.topicmap.linked; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.wandora.topicmap.Association; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicMapReadOnlyException; /** * * @author olli */ public class LinkedAssociation implements Association { protected Association wrappedAssociation; protected LinkedTopicMap topicMap; public LinkedAssociation(Association wrappedAssociation,LinkedTopicMap topicMap){ this.wrappedAssociation=wrappedAssociation; this.topicMap=topicMap; } public Association getWrappedAssociation() { return wrappedAssociation; } @Override public void addPlayer(Topic player, Topic role) throws TopicMapException { if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); wrappedAssociation.addPlayer(topicMap.getUnlinkedTopic(player),topicMap.getUnlinkedTopic(role)); } @Override public void addPlayers(Map<Topic, Topic> players) throws TopicMapException { if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); Map<Topic,Topic> unwrapped=new HashMap<Topic,Topic>(); for(Map.Entry<Topic,Topic> e : players.entrySet()){ unwrapped.put(topicMap.getUnlinkedTopic(e.getKey()),topicMap.getUnlinkedTopic(e.getValue())); } wrappedAssociation.addPlayers(unwrapped); } @Override public Topic getPlayer(Topic role) throws TopicMapException { return topicMap.getLinkedTopic(wrappedAssociation.getPlayer(topicMap.getUnlinkedTopic(role))); } @Override public Collection<Topic> getRoles() throws TopicMapException { return topicMap.getLinkedTopics(wrappedAssociation.getRoles()); } @Override public TopicMap getTopicMap() { return topicMap; } @Override public Topic getType() throws TopicMapException { return topicMap.getLinkedTopic(wrappedAssociation.getType()); } @Override public boolean isRemoved() throws TopicMapException { return wrappedAssociation.isRemoved(); } @Override public void remove() throws TopicMapException { if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); wrappedAssociation.remove(); } @Override public void removePlayer(Topic role) throws TopicMapException { if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); wrappedAssociation.removePlayer(topicMap.getUnlinkedTopic(role)); } @Override public void setType(Topic t) throws TopicMapException { if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); wrappedAssociation.setType(topicMap.getUnlinkedTopic(t)); } @Override public int hashCode(){ return wrappedAssociation.hashCode()+topicMap.hashCode(); } @Override public boolean equals(Object o){ if(!o.getClass().equals(this.getClass())) return false; LinkedAssociation lt=(LinkedAssociation)o; if(lt.topicMap!=topicMap) return false; if(!lt.wrappedAssociation.equals(wrappedAssociation)) return false; return true; } }
4,111
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
LinkedTopicMapType.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/linked/LinkedTopicMapType.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.topicmap.linked; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import javax.swing.Icon; import javax.swing.JMenuItem; import org.wandora.application.Wandora; import org.wandora.application.gui.UIBox; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapConfigurationPanel; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicMapLogger; import org.wandora.topicmap.TopicMapType; import org.wandora.topicmap.layered.ContainerTopicMap; import org.wandora.topicmap.layered.Layer; import org.wandora.topicmap.packageio.PackageInput; import org.wandora.topicmap.packageio.PackageOutput; import org.wandora.utils.Options; /** * * @author olli */ public class LinkedTopicMapType implements TopicMapType { @Override public TopicMap createTopicMap(Object params) throws TopicMapException { if(params instanceof TopicMap) { return new LinkedTopicMap((TopicMap)params); } else { return new LinkedTopicMap(params.toString()); } } @Override public TopicMapConfigurationPanel getConfigurationPanel(Wandora admin, Options options) { LinkedTopicMapConfiguration c = new LinkedTopicMapConfiguration(admin); return c; } @Override public TopicMapConfigurationPanel getModifyConfigurationPanel(Wandora wandora, Options options, TopicMap tm) { TopicMap linked = ((LinkedTopicMap)tm).getLinkedTopicMap(); ContainerTopicMap root = ((ContainerTopicMap)tm.getRootTopicMap()); Layer l = root.getTreeLayer(linked); String name = l.getName(); LinkedTopicMapConfiguration c = new LinkedTopicMapConfiguration(wandora, tm); c.setSelectedLayer(name); return c; } @Override public JMenuItem[] getTopicMapMenu(TopicMap tm, Wandora admin) { return null; } @Override public String toString(){ return getTypeName(); } @Override public String getTypeName() { return "Linked"; } @Override public TopicMap modifyTopicMap(TopicMap tm, Object params) throws TopicMapException { TopicMap ret=createTopicMap(params); ret.addTopicMapListeners(tm.getTopicMapListeners()); return ret; } @Override public void packageTopicMap(TopicMap tm, PackageOutput out, String path, TopicMapLogger logger) throws IOException, TopicMapException { LinkedTopicMap ltm = (LinkedTopicMap) tm; TopicMap linked = ltm.getLinkedTopicMap(); ContainerTopicMap rootTopicMap = (ContainerTopicMap) ltm.getRootTopicMap(); Layer l = rootTopicMap.getTreeLayer(linked); Options options = new Options(); options.put("linkedmap",l.getName()); if(rootTopicMap.getTreeLayer(l.getName()) == null) { throw new TopicMapException("Target of linked topic map does not exist. Target layer name is "+l.getName()); } out.nextEntry(path,"linkedoptions.xml"); options.save(new java.io.OutputStreamWriter(out.getOutputStream())); } @Override public TopicMap unpackageTopicMap(PackageInput in, String path, TopicMapLogger logger, Wandora wandora) throws IOException, TopicMapException { in.gotoEntry(path, "linkedoptions.xml"); Options options = new Options(); options.parseOptions(new BufferedReader(new InputStreamReader(in.getInputStream()))); String wrappedMap = options.get("linkedmap"); if(wrappedMap == null) { // used to be wrappedmap before 2013-07-18 wrappedMap=options.get("wrappedmap"); } return new LinkedTopicMap(wrappedMap); } @Override public TopicMap unpackageTopicMap(TopicMap tm, PackageInput in, String path, TopicMapLogger logger, Wandora wandora) throws IOException, TopicMapException { return unpackageTopicMap(in,path,logger,wandora); } @Override public Icon getTypeIcon() { //return UIBox.getIcon("gui/icons/layerinfo/layer_type_linked.png"); return UIBox.getIcon(0xf0c1); } }
5,072
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
LinkedTopicMapConfiguration.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/linked/LinkedTopicMapConfiguration.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * LinkedTopicMapConfiguration.java * * Created on 9. toukokuuta 2008, 12:46 */ package org.wandora.topicmap.linked; import org.wandora.application.Wandora; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapConfigurationPanel; import org.wandora.topicmap.layered.ContainerTopicMap; import org.wandora.topicmap.layered.Layer; /** * * @author olli */ public class LinkedTopicMapConfiguration extends TopicMapConfigurationPanel { protected Wandora wandora; protected TopicMap tm; /** Creates new form LinketTopicMapConfiguration */ public LinkedTopicMapConfiguration(Wandora wandora) { this(wandora,null); } public LinkedTopicMapConfiguration(Wandora wandora,TopicMap tm) { this.wandora=wandora; this.tm=tm; initComponents(); fillComboBox(); } protected void fillComboBox(){ linkedMapComboBox.removeAllItems(); fillComboBox(wandora.getTopicMap(),""); } protected void fillComboBox(ContainerTopicMap container,String prefix){ for(Layer l : container.getLayers()){ if(tm!=l.getTopicMap()) linkedMapComboBox.addItem(prefix+l.getName()); if(l.getTopicMap() instanceof ContainerTopicMap){ fillComboBox((ContainerTopicMap)l.getTopicMap(),prefix+" "); } } } public String getSelectedLayerName(){ Object o=linkedMapComboBox.getSelectedItem(); if(o==null) return null; return o.toString().trim(); } public void setSelectedLayer(String name){ int size=linkedMapComboBox.getModel().getSize(); for(int i=0;i<size;i++){ Object o=linkedMapComboBox.getModel().getElementAt(i); if(o.toString().trim().equals(name)) { linkedMapComboBox.setSelectedIndex(i); return; } } } @Override public Object getParameters() { return getSelectedLayerName(); } /** 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; jLabel1 = new org.wandora.application.gui.simple.SimpleLabel(); linkedMapComboBox = new org.wandora.application.gui.simple.SimpleComboBox(); linkedMapComboBox.setEditable(false); jPanel1 = new javax.swing.JPanel(); setLayout(new java.awt.GridBagLayout()); jLabel1.setText("Linked topic map"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 0); add(jLabel1, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 5); add(linkedMapComboBox, gridBagConstraints); jPanel1.setMinimumSize(new java.awt.Dimension(1, 1)); jPanel1.setPreferredSize(new java.awt.Dimension(1, 1)); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 1, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 1, Short.MAX_VALUE) ); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.weighty = 1.0; add(jPanel1, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jLabel1; private javax.swing.JPanel jPanel1; private javax.swing.JComboBox linkedMapComboBox; // End of variables declaration//GEN-END:variables }
5,303
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
LinkedTopic.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/linked/LinkedTopic.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.topicmap.linked; import java.util.Collection; import java.util.HashSet; import java.util.Hashtable; import java.util.Map; import java.util.Set; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicMapReadOnlyException; /** * * @author olli */ public class LinkedTopic extends Topic{ protected Topic wrappedTopic; protected LinkedTopicMap topicMap; public LinkedTopic(Topic wrappedTopic,LinkedTopicMap topicMap){ this.wrappedTopic=wrappedTopic; this.topicMap=topicMap; } public Topic getWrappedTopic(){ return wrappedTopic; } @Override public void addSubjectIdentifier(Locator l) throws TopicMapException { if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); wrappedTopic.addSubjectIdentifier(l); } @Override public void addType(Topic t) throws TopicMapException { if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); wrappedTopic.addType(topicMap.getUnlinkedTopic(t)); } @Override public Collection<Association> getAssociations() throws TopicMapException { return topicMap.getLinkedAssociations(wrappedTopic.getAssociations()); } @Override public Collection<Association> getAssociations(Topic type) throws TopicMapException { return topicMap.getLinkedAssociations(wrappedTopic.getAssociations(topicMap.getUnlinkedTopic(type))); } @Override public Collection<Association> getAssociations(Topic type, Topic role) throws TopicMapException { return topicMap.getLinkedAssociations(wrappedTopic.getAssociations(topicMap.getUnlinkedTopic(type), topicMap.getUnlinkedTopic(role))); } @Override public Collection<Association> getAssociationsWithRole() throws TopicMapException { return topicMap.getLinkedAssociations(wrappedTopic.getAssociationsWithRole()); } @Override public Collection<Association> getAssociationsWithType() throws TopicMapException { return topicMap.getLinkedAssociations(wrappedTopic.getAssociationsWithType()); } @Override public String getBaseName() throws TopicMapException { return wrappedTopic.getBaseName(); } @Override public String getData(Topic type, Topic version) throws TopicMapException { return wrappedTopic.getData(topicMap.getUnlinkedTopic(type),topicMap.getUnlinkedTopic(version)); } @Override public Hashtable<Topic, String> getData(Topic type) throws TopicMapException { Hashtable<Topic,String> data=wrappedTopic.getData(topicMap.getUnlinkedTopic(type)); Hashtable<Topic,String> ret=new Hashtable<Topic,String>(); for(Map.Entry<Topic,String> e : data.entrySet()){ ret.put(topicMap.getLinkedTopic(e.getKey()),e.getValue()); } return ret; } @Override public Collection<Topic> getDataTypes() throws TopicMapException { return topicMap.getLinkedTopics(wrappedTopic.getDataTypes()); } @Override public long getDependentEditTime() throws TopicMapException { return wrappedTopic.getDependentEditTime(); } @Override public long getEditTime() throws TopicMapException { return wrappedTopic.getEditTime(); } @Override public String getID() throws TopicMapException { return wrappedTopic.getID(); } @Override public Collection<Locator> getSubjectIdentifiers() throws TopicMapException { return wrappedTopic.getSubjectIdentifiers(); } @Override public Locator getSubjectLocator() throws TopicMapException { return wrappedTopic.getSubjectLocator(); } @Override public TopicMap getTopicMap() { return topicMap; } @Override public Collection<Topic> getTopicsWithDataType() throws TopicMapException { return topicMap.getLinkedTopics(wrappedTopic.getTopicsWithDataType()); } @Override public Collection<Topic> getTopicsWithDataVersion() throws TopicMapException { return topicMap.getLinkedTopics(wrappedTopic.getTopicsWithDataVersion()); } @Override public Collection<Topic> getTopicsWithVariantScope() throws TopicMapException { return topicMap.getLinkedTopics(wrappedTopic.getTopicsWithVariantScope()); } @Override public Collection<Topic> getTypes() throws TopicMapException { return topicMap.getLinkedTopics(wrappedTopic.getTypes()); } @Override public String getVariant(Set<Topic> scope) throws TopicMapException { return wrappedTopic.getVariant(topicMap.getUnlinkedSetOfTopics(scope)); } @Override public Set<Set<Topic>> getVariantScopes() throws TopicMapException { Set<Set<Topic>> scopes=wrappedTopic.getVariantScopes(); Set<Set<Topic>> ret=new HashSet<Set<Topic>>(); for(Set<Topic> scope : scopes){ ret.add(topicMap.getLinkedTopics(scope)); } return ret; } @Override public boolean isDeleteAllowed() throws TopicMapException { return wrappedTopic.isDeleteAllowed(); } @Override public boolean isOfType(Topic t) throws TopicMapException { return wrappedTopic.isOfType(topicMap.getUnlinkedTopic(t)); } @Override public boolean isRemoved() throws TopicMapException { return wrappedTopic.isRemoved(); } @Override public void remove() throws TopicMapException { if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); wrappedTopic.remove(); } @Override public void removeData(Topic type, Topic version) throws TopicMapException { if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); wrappedTopic.removeData(topicMap.getUnlinkedTopic(type),topicMap.getUnlinkedTopic(version)); } @Override public void removeData(Topic type) throws TopicMapException { if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); wrappedTopic.removeData(topicMap.getUnlinkedTopic(type)); } @Override public void removeSubjectIdentifier(Locator l) throws TopicMapException { if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); wrappedTopic.removeSubjectIdentifier(l); } @Override public void removeType(Topic t) throws TopicMapException { if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); wrappedTopic.removeType(topicMap.getUnlinkedTopic(t)); } @Override public void removeVariant(Set<Topic> scope) throws TopicMapException { if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); wrappedTopic.removeVariant(topicMap.getUnlinkedSetOfTopics(scope)); } @Override public void setBaseName(String name) throws TopicMapException { if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); wrappedTopic.setBaseName(name); } @Override public void setData(Topic type, Hashtable<Topic, String> versionData) throws TopicMapException { if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); Hashtable<Topic,String> unwrappedData=new Hashtable<Topic,String>(); for(Map.Entry<Topic,String> e : versionData.entrySet()){ unwrappedData.put(topicMap.getUnlinkedTopic(e.getKey()),e.getValue()); } wrappedTopic.setData(topicMap.getUnlinkedTopic(type),unwrappedData); } @Override public void setData(Topic type, Topic version, String value) throws TopicMapException { if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); wrappedTopic.setData(topicMap.getUnlinkedTopic(type),topicMap.getUnlinkedTopic(version),value); } @Override public void setDependentEditTime(long time) throws TopicMapException { wrappedTopic.setDependentEditTime(time); } @Override public void setEditTime(long time) throws TopicMapException { wrappedTopic.setEditTime(time); } @Override public void setSubjectLocator(Locator l) throws TopicMapException { if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); wrappedTopic.setSubjectLocator(l); } @Override public void setVariant(Set<Topic> scope, String name) throws TopicMapException { if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); wrappedTopic.setVariant(topicMap.getUnlinkedSetOfTopics(scope),name); } @Override public int hashCode(){ return wrappedTopic.hashCode()+topicMap.hashCode(); } @Override public boolean equals(Object o){ if(o == null) return false; if(!o.getClass().equals(this.getClass())) return false; LinkedTopic lt=(LinkedTopic)o; if(lt.topicMap!=topicMap) return false; if(!lt.wrappedTopic.equals(wrappedTopic)) return false; return true; } }
9,996
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
QueryAssociation.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/query/QueryAssociation.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.topicmap.query; import java.util.Collection; import java.util.Hashtable; import java.util.Map; import org.wandora.topicmap.Association; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicMapReadOnlyException; /** * * @author olli */ public class QueryAssociation implements Association { protected QueryTopicMap tm; protected Topic type; protected Hashtable<Topic,Topic> players; public QueryAssociation(Topic type,Hashtable<Topic,Topic> players,QueryTopicMap tm){ this.type=type; this.players=players; this.tm=tm; } public Topic getPlayer(Topic role) throws TopicMapException { return players.get(role); } public Collection<Topic> getRoles() throws TopicMapException { return players.keySet(); } public TopicMap getTopicMap() { return tm; } public Topic getType() throws TopicMapException { return type; } public void addPlayer(Topic player, Topic role) throws TopicMapException { throw new TopicMapReadOnlyException(); } public void addPlayers(Map<Topic, Topic> players) throws TopicMapException { throw new TopicMapReadOnlyException(); } public boolean isRemoved() throws TopicMapException { return false; } public void remove() throws TopicMapException { throw new TopicMapReadOnlyException(); } public void removePlayer(Topic role) throws TopicMapException { throw new TopicMapReadOnlyException(); } public void setType(Topic t) throws TopicMapException { throw new TopicMapReadOnlyException(); } }
2,559
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
QueryTopicMap.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/query/QueryTopicMap.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.topicmap.query; import static org.wandora.utils.Tuples.t2; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.script.ScriptEngine; import org.wandora.application.Wandora; import org.wandora.application.WandoraScriptManager; import org.wandora.query2.Directive; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicMapListener; import org.wandora.topicmap.TopicMapReadOnlyException; import org.wandora.topicmap.TopicMapSearchOptions; import org.wandora.topicmap.TopicMapStatData; import org.wandora.topicmap.TopicMapStatOptions; import org.wandora.topicmap.layered.ContainerTopicMap; import org.wandora.topicmap.layered.ContainerTopicMapListener; import org.wandora.topicmap.layered.Layer; import org.wandora.topicmap.layered.LayerStack; import org.wandora.utils.Tuples.T2; /** * * @author olli */ public class QueryTopicMap extends ContainerTopicMap implements TopicMapListener, ContainerTopicMapListener { protected LayerStack layerStack; protected Wandora admin; protected Collection<QueryInfo> originalQueries; protected Map<Locator,Directive> queries; protected Map<T2<Locator,Locator>,List<QueryAssociation>> associationCache; public QueryTopicMap(Wandora admin){ setLayerStack(new LayerStack()); this.admin=admin; queries=new HashMap<Locator,Directive>(); clearAssociationCache(); admin.addTopicMapListener(this); /* queries.put(new Locator(XTMPSI.SUPERCLASS_SUBCLASS), new UnionDirective( new JoinDirective( new RecursiveDirective( new RolesDirective( new IsContextTopicDirective( new SelectDirective(XTMPSI.SUPERCLASS_SUBCLASS, XTMPSI.SUPERCLASS,XTMPSI.SUBCLASS), XTMPSI.SUBCLASS), XTMPSI.SUPERCLASS), XTMPSI.SUPERCLASS ), new ContextTopicDirective(XTMPSI.SUPERCLASS_SUBCLASS,XTMPSI.SUBCLASS) ), new JoinDirective( new RecursiveDirective( new RolesDirective( new IsContextTopicDirective( new SelectDirective(XTMPSI.SUPERCLASS_SUBCLASS, XTMPSI.SUPERCLASS,XTMPSI.SUBCLASS), XTMPSI.SUPERCLASS), XTMPSI.SUBCLASS), XTMPSI.SUBCLASS ), new ContextTopicDirective(XTMPSI.SUPERCLASS_SUBCLASS,XTMPSI.SUPERCLASS) ) ) );*/ /* ArrayList<QueryInfo> qinfos=new ArrayList<QueryInfo>(); qinfos.add(new QueryInfo( XTMPSI.SUPERCLASS_SUBCLASS, " importPackage(org.wandora.query);\n"+ " importPackage(org.wandora.topicmap);\n"+ " new UnionDirective(\n"+ " new JoinDirective(\n"+ " new RecursiveDirective(\n"+ " new RolesDirective(\n"+ " new IsContextTopicDirective(\n"+ " new SelectDirective(XTMPSI.SUPERCLASS_SUBCLASS,\n"+ " XTMPSI.SUPERCLASS,XTMPSI.SUBCLASS),\n"+ " XTMPSI.SUBCLASS),\n"+ " XTMPSI.SUPERCLASS),\n"+ " XTMPSI.SUPERCLASS\n"+ " ),\n"+ " new ContextTopicDirective(XTMPSI.SUPERCLASS_SUBCLASS,XTMPSI.SUBCLASS)\n"+ " ),\n"+ " new JoinDirective(\n"+ " new RecursiveDirective(\n"+ " new RolesDirective(\n"+ " new IsContextTopicDirective(\n"+ " new SelectDirective(XTMPSI.SUPERCLASS_SUBCLASS,\n"+ " XTMPSI.SUPERCLASS,XTMPSI.SUBCLASS),\n"+ " XTMPSI.SUPERCLASS),\n"+ " XTMPSI.SUBCLASS),\n"+ " XTMPSI.SUBCLASS\n"+ " ),\n"+ " new ContextTopicDirective(XTMPSI.SUPERCLASS_SUBCLASS,XTMPSI.SUPERCLASS)\n"+ " )\n"+ " );\n", WandoraScriptManager.getDefaultScriptEngine())); setQueries(qinfos);*/ } public static class QueryInfo { public String name; public String script; public String type; public String engine; public QueryInfo(String name){ this(name,"","",WandoraScriptManager.getDefaultScriptEngine()); } public QueryInfo(String type,String script,String engine){ this("",type,script,engine); } public QueryInfo(String name,String type,String script,String engine){ this.name=name; this.type=type; this.script=script; this.engine=engine; } @Override public String toString(){return name;} } @Override public void addLayer(Layer l, int index) { layerStack.addLayer(l,index); } @Override public Layer getLayer(String name) { return layerStack.getLayer(name); } @Override public int getLayerZPos(Layer l) { return layerStack.getLayerZPos(l); } @Override public List<Layer> getLayers() { return layerStack.getLayers(); } @Override public int getSelectedIndex() { return layerStack.getSelectedIndex(); } @Override public Layer getSelectedLayer() { return layerStack.getSelectedLayer(); } @Override public Collection<Topic> getTopicsForLayer(Layer l, Topic t) { return new ArrayList<Topic>(); //return layerStack.getTopicsForLayer(l,t); } @Override public List<Layer> getVisibleLayers() { return layerStack.getVisibleLayers(); } @Override public void notifyLayersChanged() { layerStack.notifyLayersChanged(); } @Override public boolean removeLayer(Layer l) { return layerStack.removeLayer(l); } @Override public void reverseLayerOrder() { layerStack.reverseLayerOrder(); } @Override public void selectLayer(Layer layer) { layerStack.selectLayer(layer); } @Override public void setLayer(Layer l, int pos) { layerStack.setLayer(l,pos); } public void setQueries(Collection<QueryInfo> queryInfos){ this.originalQueries=queryInfos; queries=new HashMap<Locator,Directive>(); WandoraScriptManager sm=new WandoraScriptManager(); for(QueryInfo info : queryInfos){ Locator l=new Locator(info.type); ScriptEngine engine=sm.getScriptEngine(info.engine); try{ Object o=engine.eval(info.script); if(o==null) o=engine.get("query"); if(o!=null && o instanceof Directive) { queries.put(l,(Directive)o); } } catch(Exception e){ admin.handleError(e); } } } public Collection<QueryInfo> getOriginalQueries(){ return originalQueries; } public List<QueryAssociation> getCachedAssociations(Locator topic,Locator type){ if(associationCache==null) associationCache=new HashMap<T2<Locator,Locator>,List<QueryAssociation>>(); return associationCache.get(t2(topic,type)); } public List<QueryAssociation> getCachedAssociations(QueryTopic topic,QueryTopic type){ return getCachedAssociations(topic.si,type.si); } public void cacheAssociations(Locator topic,Locator type,List<QueryAssociation> associations){ if(associationCache==null) associationCache=new HashMap<T2<Locator,Locator>,List<QueryAssociation>>(); associationCache.put(t2(topic,type),associations); } public void cacheAssociations(QueryTopic topic,QueryTopic type,List<QueryAssociation> associations){ cacheAssociations(topic.si,type.si,associations); } public void clearAssociationCache(){ associationCache=null; } public void setLayerStack(LayerStack tm){ if(layerStack!=null){ layerStack.setParentTopicMap(null); layerStack.removeContainerListener(this); } layerStack=tm; layerStack.setParentTopicMap(this); layerStack.addContainerListener(this); } public LayerStack getLayerStack(){ return layerStack; } public Map<Locator,Directive> getQueries(){ return queries; } @Override public boolean isReadOnly(){ return true; } @Override public Topic getTopic(Locator si) throws TopicMapException { if(queries.get(si)!=null) return new QueryTopic(si,this); for(Layer l : layerStack.getLayers()){ if(l.getTopicMap()==this) continue; if(l.getTopicMap().getTopic(si)!=null){ QueryTopic t=new QueryTopic(si,this); return t; } } return null; } @Override public Topic getTopicBySubjectLocator(Locator sl) throws TopicMapException { return null; } @Override public Topic getTopicWithBaseName(String name) throws TopicMapException { return null; } @Override public Iterator<Topic> getTopics() throws TopicMapException { throw new UnsupportedOperationException("Not supported yet."); } @Override public Topic[] getTopics(String[] sis) throws TopicMapException { Topic[] ret=new Topic[sis.length]; for(int i=0;i<ret.length;i++){ ret[i]=getTopic(sis[i]); } return ret; } @Override public Collection<Topic> getTopicsOfType(Topic type) throws TopicMapException { return new ArrayList<Topic>(); } @Override public Collection<Topic> search(String query, TopicMapSearchOptions options) throws TopicMapException { return new ArrayList<Topic>(); } @Override public Iterator<Association> getAssociations() throws TopicMapException { return new ArrayList<Association>().iterator(); } @Override public Collection<Association> getAssociationsOfType(Topic type) throws TopicMapException { return new ArrayList<Association>(); } @Override public int getNumAssociations() throws TopicMapException { return 0; } @Override public int getNumTopics() throws TopicMapException { return 0; } @Override public TopicMapStatData getStatistics(TopicMapStatOptions options) throws TopicMapException { return null; } @Override public boolean isTopicMapChanged() throws TopicMapException { return false; } @Override public boolean resetTopicMapChanged() throws TopicMapException { return false; } @Override public void clearTopicMapIndexes() throws TopicMapException { } @Override public void clearTopicMap() throws TopicMapException { throw new TopicMapReadOnlyException(); } @Override public void close() { } @Override public Association copyAssociationIn(Association a) throws TopicMapException { throw new TopicMapReadOnlyException(); } @Override public void copyTopicAssociationsIn(Topic t) throws TopicMapException { throw new TopicMapReadOnlyException(); } @Override public Topic copyTopicIn(Topic t, boolean deep) throws TopicMapException { throw new TopicMapReadOnlyException(); } @Override public Association createAssociation(Topic type) throws TopicMapException { throw new TopicMapReadOnlyException(); } @Override public Topic createTopic(String id) throws TopicMapException { throw new TopicMapReadOnlyException(); } @Override public Topic createTopic() throws TopicMapException { throw new TopicMapReadOnlyException(); } /* @Override public TopicMapListener setTopicMapListener(TopicMapListener listener) { return null; }*/ public List<TopicMapListener> getTopicMapListeners(){ return new ArrayList<TopicMapListener>(); } public void addTopicMapListener(TopicMapListener listener){ } public void removeTopicMapListener(TopicMapListener listener){ } public void disableAllListeners(){ } public void enableAllListeners(){ } @Override public void setTrackDependent(boolean v) throws TopicMapException { } @Override public boolean trackingDependent() throws TopicMapException { return false; } // ---------------------------------------------------- TopicMapListener --- @Override public void associationChanged(Association a) throws TopicMapException { clearAssociationCache(); } @Override public void associationPlayerChanged(Association a, Topic role, Topic newPlayer, Topic oldPlayer) throws TopicMapException { clearAssociationCache(); } @Override public void associationRemoved(Association a) throws TopicMapException { clearAssociationCache(); } @Override public void associationTypeChanged(Association a, Topic newType, Topic oldType) throws TopicMapException { clearAssociationCache(); } @Override public void topicBaseNameChanged(Topic t, String newName, String oldName) throws TopicMapException { clearAssociationCache(); } @Override public void topicChanged(Topic t) throws TopicMapException { clearAssociationCache(); } @Override public void topicDataChanged(Topic t, Topic type, Topic version, String newValue, String oldValue) throws TopicMapException { clearAssociationCache(); } @Override public void topicRemoved(Topic t) throws TopicMapException { clearAssociationCache(); } @Override public void topicSubjectIdentifierChanged(Topic t, Locator added, Locator removed) throws TopicMapException { clearAssociationCache(); } @Override public void topicSubjectLocatorChanged(Topic t, Locator newLocator, Locator oldLocator) throws TopicMapException { clearAssociationCache(); } @Override public void topicTypeChanged(Topic t, Topic added, Topic removed) throws TopicMapException { clearAssociationCache(); } @Override public void topicVariantChanged(Topic t, Collection<Topic> scope, String newName, String oldName) throws TopicMapException { clearAssociationCache(); } @Override public void layerAdded(Layer l) { fireLayerAdded(l); } @Override public void layerChanged(Layer oldLayer, Layer newLayer) { fireLayerChanged(oldLayer,newLayer); } @Override public void layerRemoved(Layer l) { fireLayerRemoved(l); } @Override public void layerStructureChanged() { fireLayerStructureChanged(); } @Override public void layerVisibilityChanged(Layer l) { fireLayerVisibilityChanged(l); } }
16,640
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
QueryTopicMapType.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/query/QueryTopicMapType.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.topicmap.query; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.swing.Icon; import javax.swing.JMenuItem; import org.wandora.application.Wandora; import org.wandora.application.gui.UIBox; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapConfigurationPanel; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicMapLogger; import org.wandora.topicmap.TopicMapType; import org.wandora.topicmap.layered.LayerStack; import org.wandora.topicmap.layered.LayeredTopicMapType; import org.wandora.topicmap.packageio.PackageInput; import org.wandora.topicmap.packageio.PackageOutput; import org.wandora.utils.Options; /** * * @author olli */ public class QueryTopicMapType implements TopicMapType { public QueryTopicMapType(){ } @Override public TopicMap createTopicMap(Object params) throws TopicMapException { QueryTopicMapConfiguration.QueryTopicMapParams p=(QueryTopicMapConfiguration.QueryTopicMapParams)params; QueryTopicMap qtm=new QueryTopicMap(p.wandora); qtm.setQueries(p.queryInfos); return qtm; } @Override public TopicMap modifyTopicMap(TopicMap tm,Object params) throws TopicMapException { QueryTopicMap qtm=(QueryTopicMap)createTopicMap(params); qtm.addTopicMapListeners(tm.getTopicMapListeners()); qtm.addContainerListeners(((QueryTopicMap)tm).getContainerListeners()); qtm.setLayerStack(((QueryTopicMap)tm).getLayerStack()); return qtm; } @Override public TopicMapConfigurationPanel getConfigurationPanel(Wandora wandora, Options options) { return new QueryTopicMapConfiguration(wandora); //return new QueryConfigPanel(wandora); } @Override public TopicMapConfigurationPanel getModifyConfigurationPanel(Wandora wandora, Options options, TopicMap tm) { QueryTopicMap qtm=(QueryTopicMap)tm; return new QueryTopicMapConfiguration(qtm.getOriginalQueries(),wandora); } @Override public JMenuItem[] getTopicMapMenu(TopicMap tm, Wandora wandora) { return null; } @Override public String getTypeName() { return "Query"; } @Override public String toString(){return getTypeName();} @Override public void packageTopicMap(TopicMap tm, PackageOutput out, String path, TopicMapLogger logger) throws IOException, TopicMapException { QueryTopicMap qtm=(QueryTopicMap)tm; Options options=new Options(); Collection<QueryTopicMap.QueryInfo> queries=qtm.getOriginalQueries(); int counter=1; if(queries!=null){ for(QueryTopicMap.QueryInfo info : queries){ options.put("query"+counter+".engine",info.engine); options.put("query"+counter+".type",info.type); options.put("query"+counter+".script",info.script); options.put("query"+counter+".name",info.name); counter++; } } out.nextEntry(path, "queries.xml"); options.save(new java.io.OutputStreamWriter(out.getOutputStream())); LayerStack ls=((QueryTopicMap)tm).getLayerStack(); LayeredTopicMapType lttype=new LayeredTopicMapType(); lttype.packageTopicMap(ls, out, path, logger); } @Override public TopicMap unpackageTopicMap(PackageInput in, String path, TopicMapLogger logger,Wandora wandora) throws IOException, TopicMapException { in.gotoEntry(path, "queries.xml"); List<QueryTopicMap.QueryInfo> queries = new ArrayList<QueryTopicMap.QueryInfo>(); Options options = new Options(); options.parseOptions(new BufferedReader(new InputStreamReader(in.getInputStream()))); int counter = 1; while(true){ String engine=options.get("query"+counter+".engine"); String type=options.get("query"+counter+".type"); String script=options.get("query"+counter+".script"); String name=options.get("query"+counter+".name"); if(engine==null || type==null || script==null) break; queries.add(new QueryTopicMap.QueryInfo(name,type,script,engine)); counter++; } QueryTopicMap qtm=new QueryTopicMap(wandora); qtm.setQueries(queries); LayeredTopicMapType lttype=new LayeredTopicMapType(); LayerStack ls=(LayerStack)lttype.unpackageTopicMap(in, path, logger, wandora); qtm.setLayerStack(ls); return qtm; } @Override public TopicMap unpackageTopicMap(TopicMap tm, PackageInput in, String path, TopicMapLogger logger,Wandora wandora) throws IOException, TopicMapException { return unpackageTopicMap(in,path,logger,wandora); } public static class QueryConfigPanel extends TopicMapConfigurationPanel { public Object param; public QueryConfigPanel() { } public QueryConfigPanel(Object param) { super(); this.param=param; } @Override public Object getParameters() { return param; } } @Override public Icon getTypeIcon(){ return UIBox.getIcon("gui/icons/layerinfo/layer_type_query.png"); } }
6,346
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
QueryTopic.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/query/QueryTopic.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.topicmap.query; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.Set; import org.wandora.query2.Directive; import org.wandora.query2.QueryContext; import org.wandora.query2.QueryException; import org.wandora.query2.ResultRow; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicMapReadOnlyException; /** * * @author olli */ public class QueryTopic extends Topic { protected Locator si; protected List<Locator> sis; protected QueryTopicMap tm; public QueryTopic(Locator l,QueryTopicMap tm){ this.sis=new ArrayList<Locator>(); sis.add(l); this.si=l; this.tm=tm; } protected List<QueryAssociation> makeAssociations(List<ResultRow> res,Locator type) throws TopicMapException { ArrayList<QueryAssociation> ret=new ArrayList<QueryAssociation>(); if(res.size()==0) return ret; Topic typeTopic=new QueryTopic(type,tm); for(ResultRow row : res){ boolean include=false; for(int i=0;i<row.getNumValues();i++){ Object value=row.getValue(i); if(value==null) continue; if( (value instanceof Topic && ((Topic)value).mergesWithTopic(this)) || (value instanceof Locator && value.equals(si)) || (value instanceof String && value.equals(si.toExternalForm())) ){ include=true; break; } } if(!include) continue; Hashtable<Topic,Topic> players=new Hashtable<Topic,Topic>(); for(int i=0;i<row.getNumValues();i++){ Object value=row.getValue(i); if(value==null) continue; String role=row.getRole(i); if(role.startsWith("#")) role=Directive.DEFAULT_NS+role; Locator roleL=new Locator(role); if(value instanceof Topic){ value=((Topic)value).getOneSubjectIdentifier(); } else if(value instanceof String){ value=new Locator(value.toString()); } else if(value instanceof Locator){} else continue; players.put(new QueryTopic(roleL,tm),new QueryTopic((Locator)value,tm)); } ret.add(new QueryAssociation(typeTopic,players,tm)); } return ret; } private List<QueryAssociation> getQueryAssociations(Locator type) throws TopicMapException { List<QueryAssociation> ret=tm.getCachedAssociations(si, type); // if(ret!=null) return ret; ret=new ArrayList<QueryAssociation>(); Topic t=tm.getLayerStack().getTopic(si); if(t==null) return ret; Directive query=tm.getQueries().get(type); if(query==null) return ret; try{ List<ResultRow> res=query.doQuery(new QueryContext(tm.getLayerStack(),null), new ResultRow(t)); ret.addAll(makeAssociations(res,type)); tm.cacheAssociations(si, type, ret); return ret; }catch(QueryException qe){ qe.printStackTrace(); return new ArrayList<QueryAssociation>(); } } private Object getAssociationsLock=new Object(); private boolean getAssociationsLocked=false; @Override public Collection<Association> getAssociations() throws TopicMapException { synchronized(getAssociationsLock){ if(getAssociationsLocked) return new ArrayList<Association>(); getAssociationsLocked=true; try{ Map<Locator,Directive> queries=tm.getQueries(); List<Association> ret=new ArrayList<Association>(); for(Map.Entry<Locator,Directive> e : queries.entrySet()){ Locator type=e.getKey(); List<QueryAssociation> res=getQueryAssociations(type); ret.addAll(res); } return ret; } finally { getAssociationsLocked=false; } } } @Override public Collection<Association> getAssociations(Topic type) throws TopicMapException { synchronized(getAssociationsLock){ if(getAssociationsLocked) return new ArrayList<Association>(); getAssociationsLocked=true; try{ Map<Locator,Directive> queries=tm.getQueries(); List<Association> ret=new ArrayList<Association>(); List<QueryAssociation> res=getQueryAssociations(((QueryTopic)type).si); ret.addAll(res); return ret; } finally{ getAssociationsLocked=false; } } } @Override public Collection<Association> getAssociations(Topic type, Topic role) throws TopicMapException { synchronized(getAssociationsLock){ if(getAssociationsLocked) return new ArrayList<Association>(); getAssociationsLocked=true; try{ List<QueryAssociation> res=getQueryAssociations(((QueryTopic)type).si); List<Association> ret=new ArrayList<Association>(); for(QueryAssociation a : res){ Topic p=a.getPlayer(role); if(p==null) continue; if(p.equals(this)){ ret.add(a); continue; } } return ret; } finally{ getAssociationsLocked=false; } } } @Override public Collection<Association> getAssociationsWithRole() throws TopicMapException { return new ArrayList<Association>(); } @Override public Collection<Association> getAssociationsWithType() throws TopicMapException { return new ArrayList<Association>(); } @Override public String getBaseName() throws TopicMapException { return null; } @Override public String getData(Topic type, Topic version) throws TopicMapException { return null; } @Override public Hashtable<Topic, String> getData(Topic type) throws TopicMapException { return new Hashtable<Topic,String>(); } @Override public Collection<Topic> getDataTypes() throws TopicMapException { return new ArrayList<Topic>(); } @Override public String getID() throws TopicMapException { return si.toString(); } @Override public Collection<Locator> getSubjectIdentifiers() throws TopicMapException { return sis; } @Override public Locator getSubjectLocator() throws TopicMapException { return null; } @Override public TopicMap getTopicMap() { return tm; } @Override public Collection<Topic> getTopicsWithDataType() throws TopicMapException { return new ArrayList<Topic>(); } @Override public Collection<Topic> getTypes() throws TopicMapException { return new ArrayList<Topic>(); } @Override public Collection<Topic> getTopicsWithDataVersion() throws TopicMapException { return new ArrayList<Topic>(); } @Override public Collection<Topic> getTopicsWithVariantScope() throws TopicMapException { return new ArrayList<Topic>(); } @Override public String getVariant(Set<Topic> scope) throws TopicMapException { return null; } @Override public Set<Set<Topic>> getVariantScopes() throws TopicMapException { return new HashSet<Set<Topic>>(); } @Override public boolean isOfType(Topic t) throws TopicMapException { return false; } @Override public boolean isDeleteAllowed() throws TopicMapException { return false; } @Override public boolean isRemoved() throws TopicMapException { return false; } @Override public long getDependentEditTime() throws TopicMapException { return 0; } @Override public long getEditTime() throws TopicMapException { return 0; } @Override public void addSubjectIdentifier(Locator l) throws TopicMapException { throw new TopicMapReadOnlyException(); } @Override public void addType(Topic t) throws TopicMapException { throw new TopicMapReadOnlyException(); } @Override public void remove() throws TopicMapException { throw new TopicMapReadOnlyException(); } @Override public void removeData(Topic type, Topic version) throws TopicMapException { throw new TopicMapReadOnlyException(); } @Override public void removeData(Topic type) throws TopicMapException { throw new TopicMapReadOnlyException(); } @Override public void removeSubjectIdentifier(Locator l) throws TopicMapException { throw new TopicMapReadOnlyException(); } @Override public void removeType(Topic t) throws TopicMapException { throw new TopicMapReadOnlyException(); } @Override public void removeVariant(Set<Topic> scope) throws TopicMapException { throw new TopicMapReadOnlyException(); } @Override public void setBaseName(String name) throws TopicMapException { throw new TopicMapReadOnlyException(); } @Override public void setData(Topic type, Hashtable<Topic, String> versionData) throws TopicMapException { throw new TopicMapReadOnlyException(); } @Override public void setData(Topic type, Topic version, String value) throws TopicMapException { throw new TopicMapReadOnlyException(); } @Override public void setDependentEditTime(long time) throws TopicMapException { } @Override public void setEditTime(long time) throws TopicMapException { } @Override public void setSubjectLocator(Locator l) throws TopicMapException { throw new TopicMapReadOnlyException(); } @Override public void setVariant(Set<Topic> scope, String name) throws TopicMapException { throw new TopicMapReadOnlyException(); } @Override public int hashCode(){ return si.hashCode(); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final QueryTopic other = (QueryTopic) obj; if (this.si != other.si && (this.si == null || !this.si.equals(other.si))) { return false; } return true; } }
11,849
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
QueryTopicMapConfiguration.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/query/QueryTopicMapConfiguration.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.topicmap.query; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.script.ScriptEngine; import javax.script.ScriptException; import org.wandora.application.Wandora; import org.wandora.application.WandoraScriptManager; 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.SimpleComboBox; import org.wandora.application.gui.simple.SimpleField; import org.wandora.application.gui.simple.SimpleLabel; import org.wandora.application.gui.simple.SimpleTextPane; import org.wandora.topicmap.TopicMapConfigurationPanel; /** * * @author olli */ public class QueryTopicMapConfiguration extends TopicMapConfigurationPanel { private static final long serialVersionUID = 1L; private QueryTopicMap.QueryInfo currentItem; private Wandora wandora; private javax.swing.DefaultListModel listModel; private javax.swing.JDialog editDialog; /** Creates new form QueryTopicMapConfiguration */ public QueryTopicMapConfiguration(Collection<QueryTopicMap.QueryInfo> queryInfos,Wandora wandora) { this(wandora); fillData(queryInfos); } public QueryTopicMapConfiguration(Wandora wandora) { this.wandora=wandora; this.listModel=new javax.swing.DefaultListModel(); initComponents(); } public void fillData(Collection<QueryTopicMap.QueryInfo> queryInfos){ currentItem=null; listModel.removeAllElements(); for(QueryTopicMap.QueryInfo info : queryInfos){ listModel.addElement(info); } } public void saveCurrent(){ if(currentItem==null) return; currentItem.name=nameTextField.getText(); currentItem.type=typeTextField.getText(); currentItem.engine=engineComboBox.getSelectedItem().toString(); currentItem.script=scriptTextPane.getText(); } private void openEditDialog(QueryTopicMap.QueryInfo info){ editDialog=new javax.swing.JDialog(wandora,"Edit query",true); currentItem=info; List<String> engines=WandoraScriptManager.getAvailableEngines(); engineComboBox.removeAllItems(); for(int i=0;i<engines.size();i++){ String e=engines.get(i); engineComboBox.addItem(e); } nameTextField.setText(currentItem.name); typeTextField.setText(currentItem.type); engineComboBox.setSelectedItem(currentItem.engine); scriptTextPane.setText(currentItem.script); editDialog.getContentPane().add(editPanel); editDialog.setSize(400, 500); org.wandora.utils.swing.GuiTools.centerWindow(editDialog, wandora); editDialog.setVisible(true); } @Override public Object getParameters() { saveCurrent(); QueryTopicMapParams ret=new QueryTopicMapParams(wandora); for(int i=0;i<listModel.size();i++){ QueryTopicMap.QueryInfo info=(QueryTopicMap.QueryInfo)listModel.get(i); ret.queryInfos.add(info); } return ret; } /** 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; editPanel = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); scriptTextPane = new SimpleTextPane(); jLabel1 = new SimpleLabel(); engineComboBox = new SimpleComboBox(); jLabel4 = new SimpleLabel(); nameTextField = new SimpleField(); jLabel5 = new SimpleLabel(); typeTextField = new SimpleField(); jPanel3 = new javax.swing.JPanel(); checkButton = new SimpleButton(); okButton = new SimpleButton(); cancelButton = new SimpleButton(); jPanel2 = new javax.swing.JPanel(); addButton = new SimpleButton(); deleteButton = new SimpleButton(); editButton = new SimpleButton(); jScrollPane2 = new javax.swing.JScrollPane(); queryList = new javax.swing.JList(); editPanel.setLayout(new java.awt.GridBagLayout()); jScrollPane1.setViewportView(scriptTextPane); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(2, 5, 0, 5); editPanel.add(jScrollPane1, gridBagConstraints); jLabel1.setText("Script engine"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 0); editPanel.add(jLabel1, gridBagConstraints); engineComboBox.setEditable(true); engineComboBox.setPreferredSize(new java.awt.Dimension(124, 20)); 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(5, 5, 5, 5); editPanel.add(engineComboBox, gridBagConstraints); jLabel4.setText("Name"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 1); editPanel.add(jLabel4, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(6, 5, 0, 5); editPanel.add(nameTextField, gridBagConstraints); jLabel5.setText("Type"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 0); editPanel.add(jLabel5, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5); editPanel.add(typeTextField, gridBagConstraints); jPanel3.setLayout(new java.awt.GridBagLayout()); checkButton.setText("Check Script"); checkButton.setMargin(new java.awt.Insets(2, 4, 2, 4)); checkButton.setPreferredSize(new java.awt.Dimension(80, 23)); checkButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { checkButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel3.add(checkButton, gridBagConstraints); okButton.setText("OK"); okButton.setMaximumSize(new java.awt.Dimension(80, 23)); okButton.setMinimumSize(new java.awt.Dimension(80, 23)); okButton.setPreferredSize(new java.awt.Dimension(80, 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 = 0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 0); jPanel3.add(okButton, gridBagConstraints); cancelButton.setText("Cancel"); cancelButton.setMaximumSize(new java.awt.Dimension(80, 23)); cancelButton.setMinimumSize(new java.awt.Dimension(80, 23)); cancelButton.setPreferredSize(new java.awt.Dimension(80, 23)); cancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel3.add(cancelButton, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.gridwidth = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; editPanel.add(jPanel3, gridBagConstraints); setLayout(new java.awt.GridBagLayout()); jPanel2.setLayout(new java.awt.GridBagLayout()); addButton.setText("Add"); addButton.setMaximumSize(new java.awt.Dimension(70, 23)); addButton.setMinimumSize(new java.awt.Dimension(70, 23)); addButton.setPreferredSize(new java.awt.Dimension(70, 23)); addButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 0); jPanel2.add(addButton, gridBagConstraints); deleteButton.setText("Delete"); deleteButton.setMaximumSize(new java.awt.Dimension(70, 23)); deleteButton.setMinimumSize(new java.awt.Dimension(70, 23)); deleteButton.setPreferredSize(new java.awt.Dimension(70, 23)); deleteButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { deleteButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 0); jPanel2.add(deleteButton, gridBagConstraints); editButton.setText("Edit"); editButton.setMaximumSize(new java.awt.Dimension(70, 23)); editButton.setMinimumSize(new java.awt.Dimension(70, 23)); editButton.setPreferredSize(new java.awt.Dimension(70, 23)); editButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { editButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 5); jPanel2.add(editButton, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.insets = new java.awt.Insets(0, 0, 5, 0); add(jPanel2, gridBagConstraints); queryList.setFont(UIConstants.labelFont); queryList.setModel(listModel); jScrollPane2.setViewportView(queryList); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 3, 5); add(jScrollPane2, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents private String checkScript(String engineString,String script){ WandoraScriptManager sm=new WandoraScriptManager(); ScriptEngine engine=sm.getScriptEngine(engineString); if(engine==null){ return "Couldn't find script engine"; } try{ Object o=engine.eval(script); if(o==null){ return "Script returned null."; } else if(!(o instanceof org.wandora.query2.Directive)){ return "Script didn't return an instance of Directive.<br>"+ "Class of return value is "+o.getClass().getName(); } }catch(ScriptException se){ return "ScriptException at line "+se.getLineNumber()+" column "+se.getColumnNumber()+"<br>"+se.getMessage(); } catch(Exception e){ e.printStackTrace(); return "Exception occurred during execution: "+e.getClass().getName()+" "+e.getMessage(); } return null; } private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed listModel.addElement(new QueryTopicMap.QueryInfo("New query")); }//GEN-LAST:event_addButtonActionPerformed private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed int s=queryList.getSelectedIndex(); if(s!=-1) listModel.remove(s); }//GEN-LAST:event_deleteButtonActionPerformed private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed String message=checkScript(engineComboBox.getSelectedItem().toString(),scriptTextPane.getText()); if(message!=null){ int c=WandoraOptionPane.showConfirmDialog(wandora, "Unabled to evaluate script. Do you want continue?<br><br>"+message,"Error in query"); if(c!=WandoraOptionPane.YES_OPTION) return; } saveCurrent(); editDialog.setVisible(false); queryList.repaint(); }//GEN-LAST:event_okButtonActionPerformed private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed editDialog.setVisible(false); }//GEN-LAST:event_cancelButtonActionPerformed private void editButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editButtonActionPerformed Object o=queryList.getSelectedValue(); if(o!=null) openEditDialog((QueryTopicMap.QueryInfo)o); }//GEN-LAST:event_editButtonActionPerformed private void checkButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkButtonActionPerformed String m=checkScript(engineComboBox.getSelectedItem().toString(),scriptTextPane.getText()); if(m!=null){ WandoraOptionPane.showMessageDialog(wandora, m, "Error in query", WandoraOptionPane.ERROR_MESSAGE); } else WandoraOptionPane.showMessageDialog(wandora, "No errors", "No errors", WandoraOptionPane.INFORMATION_MESSAGE); }//GEN-LAST:event_checkButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton addButton; private javax.swing.JButton cancelButton; private javax.swing.JButton checkButton; private javax.swing.JButton deleteButton; private javax.swing.JButton editButton; private javax.swing.JPanel editPanel; private javax.swing.JComboBox engineComboBox; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JTextField nameTextField; private javax.swing.JButton okButton; private javax.swing.JList queryList; private javax.swing.JTextPane scriptTextPane; private javax.swing.JTextField typeTextField; // End of variables declaration//GEN-END:variables public static class QueryTopicMapParams { public Wandora wandora; public ArrayList<QueryTopicMap.QueryInfo> queryInfos; public QueryTopicMapParams(Wandora wandora){ this(wandora,new ArrayList<QueryTopicMap.QueryInfo>()); } public QueryTopicMapParams(Wandora wandora,ArrayList<QueryTopicMap.QueryInfo> queryInfos){ this.wandora=wandora; this.queryInfos=queryInfos; } } }
18,393
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SLSimilarity.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/similarity/SLSimilarity.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.topicmap.similarity; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import uk.ac.shef.wit.simmetrics.similaritymetrics.InterfaceStringMetric; import uk.ac.shef.wit.simmetrics.similaritymetrics.Levenshtein; /** * Topic similarity measure that compares subject locators. * * @author akivela */ public class SLSimilarity implements TopicSimilarity { private InterfaceStringMetric stringMetric = null; public SLSimilarity() { stringMetric = new Levenshtein(); } public SLSimilarity(InterfaceStringMetric metric) { stringMetric = metric; } @Override public String getName() { return "Subject locator similarity"; } @Override public double similarity(Topic t1, Topic t2) { try { Locator l1 = t1.getSubjectLocator(); Locator l2 = t2.getSubjectLocator(); if(l1 == null || l2 == null) return 0; return stringMetric.getSimilarity(l1.toExternalForm(), l2.toExternalForm()); } catch(Exception e) {} return 0; } }
1,932
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicSimilarityHelper.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/similarity/TopicSimilarityHelper.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.topicmap.similarity; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashSet; import org.wandora.utils.IObox; /** * This helper class reads dynamically all available similarity measures in * the DEFAULT_SIMILARITY_PATH package. Thus, adding a new similarity model * requires no special actions. Wandora finds the similarity measure automatically * if the similarity measure class implements TopicSimilarity interface and the * class package is the DEFAULT_SIMILARITY_PATH. * * @author akivela */ public class TopicSimilarityHelper { public static final String DEFAULT_SIMILARITY_PATH = "org/wandora/topicmap/similarity"; private static boolean ADDITIONAL_DEBUG = true; private static ArrayList<String> similarityPaths = new ArrayList<String>(); public static void addSimilarityMeasuresPath(String path) { if(!similarityPaths.contains(path)) { similarityPaths.add(path); } } public static ArrayList<String> getSimilarityMeasuresPath() { return similarityPaths; } public static void resetSimilarityMeasuresPath() { similarityPaths = new ArrayList<String>(); } public static ArrayList<TopicSimilarity> getTopicSimilarityMeasures() { ArrayList<TopicSimilarity> measures=new ArrayList<TopicSimilarity>(); if(!similarityPaths.contains(DEFAULT_SIMILARITY_PATH)) { similarityPaths.add(DEFAULT_SIMILARITY_PATH); } for(String path : similarityPaths) { try { String classPath = path.replace('/', '.'); Enumeration measureResources = ClassLoader.getSystemResources(path); while(measureResources.hasMoreElements()) { URL measureResourceBaseUrl = (URL) measureResources.nextElement(); if(measureResourceBaseUrl.toExternalForm().startsWith("file:")) { String baseDir = IObox.getFileFromURL(measureResourceBaseUrl); // 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> measureResourceFileNames = IObox.getFilesAsHash(baseDir, ".*\\.class", 1, 1000); for(String classFileName : measureResourceFileNames) { try { File classFile = new File(classFileName); String className = classPath + "." + classFile.getName().replaceFirst("\\.class", ""); if(className.indexOf("$")>-1) continue; TopicSimilarity measureResource=null; Class measureResourceClass=Class.forName(className); if(!TopicSimilarity.class.isAssignableFrom(measureResourceClass)) { if(ADDITIONAL_DEBUG) System.out.println("Rejecting '" + measureResourceClass.getSimpleName() + "'. Does not implement TopicSimilarity interface!"); continue; } if(measureResourceClass.isInterface()) { if(ADDITIONAL_DEBUG) System.out.println("Rejecting '" + measureResourceClass.getSimpleName() + "'. Is interface!"); continue; } try { measureResourceClass.getConstructor(); } catch(NoSuchMethodException nsme){ if(ADDITIONAL_DEBUG) System.out.println("Rejecting '" + measureResourceClass.getSimpleName() + "'. No constructor!"); continue; } measureResource=(TopicSimilarity)Class.forName(className).newInstance(); if(measureResource != null) { measures.add(measureResource); } } catch(Exception ex) { if(ADDITIONAL_DEBUG) System.out.println("Rejecting similarity. Exception '" + ex.toString() + "' occurred while investigating '" + classFileName + "'."); //ex.printStackTrace(); } } } } } catch(Exception e) { e.printStackTrace(); } } return measures; } }
5,841
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
HighestVariantNameSimilarity.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/similarity/HighestVariantNameSimilarity.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.topicmap.similarity; import java.util.Set; import org.wandora.topicmap.Topic; import uk.ac.shef.wit.simmetrics.similaritymetrics.InterfaceStringMetric; import uk.ac.shef.wit.simmetrics.similaritymetrics.Levenshtein; /** * * @author akivela */ public class HighestVariantNameSimilarity implements TopicSimilarity { private InterfaceStringMetric stringMetric = null; public HighestVariantNameSimilarity() { stringMetric = new Levenshtein(); } public HighestVariantNameSimilarity(InterfaceStringMetric metric) { stringMetric = metric; } @Override public String getName() { return "Highest variant name similarity"; } @Override public double similarity(Topic t1, Topic t2) { double highestSimilarity = -1; double similarity = -1; try { for(Set<Topic> s1 : t1.getVariantScopes()) { for(Set<Topic> s2 : t2.getVariantScopes()) { similarity = stringMetric.getSimilarity(t1.getVariant(s1), t2.getVariant(s2)); if(similarity > highestSimilarity) { highestSimilarity = similarity; } } } } catch(Exception e) {} return highestSimilarity; } }
2,143
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TypeSimilarity.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/similarity/TypeSimilarity.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.topicmap.similarity; import java.util.Collection; import org.wandora.topicmap.Topic; /** * * @author akivela */ public class TypeSimilarity implements TopicSimilarity { private double errorDivider = 2.0; public TypeSimilarity() { } public TypeSimilarity(double ed) { errorDivider = ed; } @Override public String getName() { return "Topic type (class) similarity"; } @Override public double similarity(Topic t1, Topic t2) { double similarity = 1; try { Collection<Topic> types1 = t1.getTypes(); Collection<Topic> types2 = t2.getTypes(); if(types1 == null || types1.isEmpty()) return 0; if(types2 == null || types2.isEmpty()) return 0; for(Topic type1 : types1) { if(!types2.contains(type1)) similarity = similarity / errorDivider; } for(Topic type2 : types2) { if(!types1.contains(type2)) similarity = similarity / errorDivider; } } catch(Exception e) {} return similarity; } }
1,987
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
HighestOccurrenceSimilarity.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/similarity/HighestOccurrenceSimilarity.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.topicmap.similarity; import java.util.Hashtable; import org.wandora.topicmap.Topic; import uk.ac.shef.wit.simmetrics.similaritymetrics.InterfaceStringMetric; import uk.ac.shef.wit.simmetrics.similaritymetrics.Levenshtein; /** * * @author akivela */ public class HighestOccurrenceSimilarity implements TopicSimilarity { private InterfaceStringMetric stringMetric = null; public HighestOccurrenceSimilarity() { stringMetric = new Levenshtein(); } public HighestOccurrenceSimilarity(InterfaceStringMetric metric) { stringMetric = metric; } @Override public String getName() { return "Highest occurrence similarity"; } @Override public double similarity(Topic t1, Topic t2) { double highestSimilarity = -1; double similarity = -1; try { for(Topic type1 : t1.getDataTypes()) { Hashtable<Topic, String> o1s = t1.getData(type1); for(Topic o1sk : o1s.keySet()) { String o1 = o1s.get(o1sk); for(Topic type2 : t2.getDataTypes()) { Hashtable<Topic, String> o2s = t2.getData(type2); for(Topic o2sk : o2s.keySet()) { String o2 = o2s.get(o2sk); similarity = stringMetric.getSimilarity(o1, o2); if(similarity > highestSimilarity) { highestSimilarity = similarity; } } } } } } catch(Exception e) {} return highestSimilarity; } }
2,537
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AssociationStringSimilarity.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/similarity/AssociationStringSimilarity.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.topicmap.similarity; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import org.wandora.topicmap.Association; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; import uk.ac.shef.wit.simmetrics.similaritymetrics.InterfaceStringMetric; import uk.ac.shef.wit.simmetrics.similaritymetrics.Levenshtein; /** * * @author akivela */ public class AssociationStringSimilarity implements TopicSimilarity { public static final String TOPIC_DELIMITER = "***"; private InterfaceStringMetric stringMetric = null; public AssociationStringSimilarity() { stringMetric = new Levenshtein(); } @Override public String getName() { return "Association string similarity"; } @Override public double similarity(Topic t1, Topic t2) { double similarity = 0; double overAllSimilarity = 1; double bestSimilarity = 0; try { Collection<String> as1 = getAssociationsAsStrings(t1); Collection<String> as2 = getAssociationsAsStrings(t2); if(as1.isEmpty() || as2.isEmpty()) return 0; for(String s1 : as1) { bestSimilarity = 0; for(String s2 : as2) { similarity = stringMetric.getSimilarity(s1, s2); if(similarity > bestSimilarity) { bestSimilarity = similarity; } } overAllSimilarity = overAllSimilarity * bestSimilarity; //overAllSimilarity = overAllSimilarity / 2; } } catch(Exception e) {} return overAllSimilarity; } public Collection<String> getAssociationsAsStrings(Topic t) throws TopicMapException { Collection<Association> as = t.getAssociations(); ArrayList<String> asStr = new ArrayList<>(); for(Association a : as) { StringBuilder sb = new StringBuilder(""); sb.append(getAsString(a.getType())); sb.append(TOPIC_DELIMITER); Collection<Topic> roles = a.getRoles(); ArrayList<Topic> sortedRoles = new ArrayList<>(); sortedRoles.addAll(roles); Collections.sort(sortedRoles, new TopicStringComparator()); boolean found = false; for(Topic r : sortedRoles) { Topic p = a.getPlayer(r); if(!found && p.mergesWithTopic(t)) { found = true; continue; } sb.append(getAsString(r)); sb.append(TOPIC_DELIMITER); sb.append(getAsString(p)); sb.append(TOPIC_DELIMITER); } asStr.add(sb.toString()); } Collections.sort(asStr); return asStr; } public String getAsString(Topic t) throws TopicMapException { if(t == null) return null; else { return t.getOneSubjectIdentifier().toExternalForm(); } } private class TopicStringComparator implements Comparator<Object> { @Override public int compare(Object o1, Object o2) { try { if(o1 != null && o2 != null) { if(o1 instanceof Topic && o2 instanceof Topic) { Topic t1 = (Topic) o1; Topic t2 = (Topic) o2; String s1 = getAsString(t1); String s2 = getAsString(t2); return s1.compareTo(s2); } else if(o1 instanceof Comparable && o2 instanceof Comparable) { Comparable c1 = (Comparable) o1; Comparable c2 = (Comparable) o2; return c1.compareTo(c2); } } } catch(Exception e) { // EXCEPTION } return 0; } } }
5,028
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicSimilarity.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/similarity/TopicSimilarity.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.topicmap.similarity; import org.wandora.topicmap.Topic; /** * TopicSimilarity is an interface to measure topic similarity. Interface * consists of two methods. The similarity method takes two topics as arguments * and returns a double number. If returned double number is zero, topics are * identical (in the similarity model). Nonzero values suggest the topics * are different. The user should notice the similarity scale is reversed making * it more like "difference scale": Maximum similarity is at 0 and there is no * maximum difference. * * Second interface method is used to return a name for the * similarity measure. * * @author akivela */ public interface TopicSimilarity { public double similarity(Topic t1, Topic t2); public String getName(); }
1,615
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
BasenameSimilarity.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/similarity/BasenameSimilarity.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.topicmap.similarity; import org.wandora.topicmap.Topic; import uk.ac.shef.wit.simmetrics.similaritymetrics.InterfaceStringMetric; import uk.ac.shef.wit.simmetrics.similaritymetrics.Levenshtein; /** * * @author akivela */ public class BasenameSimilarity implements TopicSimilarity { private InterfaceStringMetric stringMetric = null; public BasenameSimilarity() { stringMetric = new Levenshtein(); } public BasenameSimilarity(InterfaceStringMetric metric) { stringMetric = metric; } @Override public String getName() { return "Basename similarity"; } @Override public double similarity(Topic t1, Topic t2) { try { String n1 = t1.getBaseName(); String n2 = t2.getBaseName(); if(n1 == null && n2 == null) return 1; if(n1 == null && "".equals(n2)) return 0; if("".equals(n1) && n2 == null) return 0; if(n1.equals(n2)) return 1; return stringMetric.getSimilarity(n2, n1); } catch(Exception e) {} return 0; } }
1,974
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
HighestSISimilarity.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/similarity/HighestSISimilarity.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.topicmap.similarity; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import uk.ac.shef.wit.simmetrics.similaritymetrics.InterfaceStringMetric; import uk.ac.shef.wit.simmetrics.similaritymetrics.Levenshtein; /** * * @author akivela */ public class HighestSISimilarity implements TopicSimilarity { private InterfaceStringMetric stringMetric = null; public HighestSISimilarity() { stringMetric = new Levenshtein(); } public HighestSISimilarity(InterfaceStringMetric metric) { stringMetric = metric; } @Override public String getName() { return "Highest subject identifier similarity"; } @Override public double similarity(Topic t1, Topic t2) { double highestSimilarity = -1; double similarity = -1; try { for(Locator l1 : t1.getSubjectIdentifiers()) { for(Locator l2 : t2.getSubjectIdentifiers()) { similarity = stringMetric.getSimilarity(l1.toExternalForm(), l2.toExternalForm()); if(similarity > highestSimilarity) { highestSimilarity = similarity; } } } } catch(Exception e) {} return highestSimilarity; } }
2,144
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
RemoveTypeOperation.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/undowrapper/RemoveTypeOperation.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.topicmap.undowrapper; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public class RemoveTypeOperation extends UndoOperation { protected TopicMap tm; protected Locator si; protected Locator typeSi; protected boolean dummy=false; public RemoveTypeOperation(Topic t,Topic type) throws TopicMapException, UndoException { if(!t.isOfType(type)){ dummy=true; return; } tm=t.getTopicMap(); si=t.getOneSubjectIdentifier(); if(si==null) throw new UndoException("Topic doesn't have a subject identifier"); typeSi=type.getOneSubjectIdentifier(); if(typeSi==null) throw new UndoException("Type topic doesn't have a subject identifier"); } @Override public String getLabel() { return "remove type"; } @Override public void undo() throws UndoException { if(dummy) return; try{ Topic t=tm.getTopic(si); if(t==null) throw new UndoException(); Topic type=tm.getTopic(typeSi); if(type==null) throw new UndoException(); t.addType(type); }catch(TopicMapException tme){ throw new UndoException(tme); } } @Override public void redo() throws UndoException { if(dummy) return; try { Topic t=tm.getTopic(si); if(t==null) throw new UndoException(); Topic type=tm.getTopic(typeSi); if(type==null) throw new UndoException(); t.removeType(type); } catch(TopicMapException tme) { throw new UndoException(tme); } } }
2,624
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
UndoAssociation.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/undowrapper/UndoAssociation.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.topicmap.undowrapper; import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import org.wandora.topicmap.Association; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public class UndoAssociation implements Association { private Association wrapped; private UndoTopicMap topicMap; UndoAssociation(Association wrapped,UndoTopicMap topicMap){ this.wrapped=wrapped; this.topicMap=topicMap; } private boolean undoCreated() throws TopicMapException { return !wrapped.getRoles().isEmpty(); } public Association getWrapped(){ return wrapped; } @Override public Topic getType() throws TopicMapException { return topicMap.wrapTopic(wrapped.getType()); } @Override public void setType(Topic t) throws TopicMapException { Topic wtype=((UndoTopic)t).getWrapped(); try { if(undoCreated()) topicMap.addUndoOperation(ModifyAssociationOperation.setType(wrapped, wtype)); } catch(UndoException ue){ topicMap.handleUndoException(ue); } wrapped.setType(wtype); } @Override public Topic getPlayer(Topic role) throws TopicMapException { return topicMap.wrapTopic(wrapped.getPlayer(((UndoTopic)role).getWrapped())); } @Override public void addPlayer(Topic player, Topic role) throws TopicMapException { Topic wrole=((UndoTopic)role).getWrapped(); Topic wplayer=((UndoTopic)player).getWrapped(); if(wrapped.getRoles().isEmpty()) { try { topicMap.addUndoOperation(new CreateAssociationOperation(wrapped.getType(),wrole,wplayer)); } catch(UndoException ue){ topicMap.handleUndoException(ue); } } else { try { topicMap.addUndoOperation(ModifyAssociationOperation.addPlayer(wrapped, wrole, wplayer)); } catch(UndoException ue){ topicMap.handleUndoException(ue); } } wrapped.addPlayer(wplayer,wrole); } @Override public void addPlayers(Map<Topic, Topic> players) throws TopicMapException { HashMap<Topic,Topic> ps=new LinkedHashMap<Topic,Topic>(); for(Map.Entry<Topic,Topic> e : players.entrySet()){ ps.put(((UndoTopic)e.getKey()).getWrapped(),((UndoTopic)e.getValue()).getWrapped()); } if(wrapped.getRoles().isEmpty()) { try { topicMap.addUndoOperation(new CreateAssociationOperation(wrapped.getType(),ps)); } catch(UndoException ue){ topicMap.handleUndoException(ue); } } else { try { topicMap.addUndoOperation(ModifyAssociationOperation.addPlayers(wrapped, ps)); } catch(UndoException ue){ topicMap.handleUndoException(ue); } } wrapped.addPlayers(ps); } @Override public void removePlayer(Topic role) throws TopicMapException { Topic wrole=((UndoTopic)role).getWrapped(); if(wrapped.getRoles().size()==1 && wrapped.getPlayer(role)!=null) { try { topicMap.addUndoOperation(new RemoveAssociationOperation(wrapped)); } catch(UndoException ue){ topicMap.handleUndoException(ue); } } else { try { topicMap.addUndoOperation(ModifyAssociationOperation.removePlayer(wrapped,wrole)); } catch(UndoException ue){ topicMap.handleUndoException(ue); } } wrapped.removePlayer(wrole); } @Override public Collection<Topic> getRoles() throws TopicMapException { return topicMap.wrapTopics(wrapped.getRoles()); } @Override public TopicMap getTopicMap() { return topicMap; } @Override public void remove() throws TopicMapException { try { topicMap.addUndoOperation(new RemoveAssociationOperation(wrapped)); } catch(UndoException ue){ topicMap.handleUndoException(ue); } wrapped.remove(); } @Override public boolean isRemoved() throws TopicMapException { return wrapped.isRemoved(); } }
5,404
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SetOccurrenceOperation.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/undowrapper/SetOccurrenceOperation.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.topicmap.undowrapper; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public class SetOccurrenceOperation extends UndoOperation { protected TopicMap tm; protected Locator si; protected Locator typeSi; protected Locator versionSi; protected String oldValue; protected String newValue; public SetOccurrenceOperation(Topic t,Topic type,Topic version,String value) throws TopicMapException, UndoException { this.tm=t.getTopicMap(); si=t.getOneSubjectIdentifier(); if(si==null) throw new UndoException("Topic has no subject identifier"); typeSi=type.getOneSubjectIdentifier(); if(typeSi==null) throw new UndoException("Type topic has no subject identifier"); versionSi=version.getOneSubjectIdentifier(); if(versionSi==null) throw new UndoException("Version topic has no subject identifier"); oldValue=t.getData(type, version); newValue=value; } @Override public String getLabel() { return "occurrence"; } @Override public void undo() throws UndoException { try{ Topic t=tm.getTopic(si); if(t==null) throw new UndoException(); Topic type=tm.getTopic(typeSi); if(type==null) throw new UndoException(); Topic version=tm.getTopic(versionSi); if(version==null) throw new UndoException(); if(oldValue==null) t.removeData(type,version); else t.setData(type, version,oldValue); }catch(TopicMapException tme){throw new UndoException(tme);} } @Override public void redo() throws UndoException { try{ Topic t=tm.getTopic(si); if(t==null) throw new UndoException(); Topic type=tm.getTopic(typeSi); if(type==null) throw new UndoException(); Topic version=tm.getTopic(versionSi); if(version==null) throw new UndoException(); if(newValue==null) t.removeData(type, version); else t.setData(type, version,newValue); } catch(TopicMapException tme){ throw new UndoException(tme); } } }
3,130
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AddTypeOperation.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/undowrapper/AddTypeOperation.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.topicmap.undowrapper; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public class AddTypeOperation extends UndoOperation { protected TopicMap tm; protected Locator si; protected Locator typeSi; protected boolean dummy=false; public AddTypeOperation(Topic t,Topic type) throws TopicMapException, UndoException { if(t.isOfType(type)){ dummy=true; return; } tm=t.getTopicMap(); si=t.getOneSubjectIdentifier(); if(si==null) throw new UndoException("Topic doesn't have a subject identifier"); typeSi=type.getOneSubjectIdentifier(); if(typeSi==null) throw new UndoException("Type topic doesn't have a subject identifier"); } @Override public String getLabel() { return "add type"; } @Override public void redo() throws UndoException { if(dummy) return; try{ Topic t=tm.getTopic(si); if(t==null) throw new UndoException(); Topic type=tm.getTopic(typeSi); if(type==null) throw new UndoException(); t.addType(type); }catch(TopicMapException tme){ throw new UndoException(tme); } } @Override public void undo() throws UndoException { if(dummy) return; try { Topic t=tm.getTopic(si); if(t==null) throw new UndoException(); Topic type=tm.getTopic(typeSi); if(type==null) throw new UndoException(); t.removeType(type); } catch(TopicMapException tme) { throw new UndoException(tme); } } }
2,608
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ModifyAssociationOperation.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/undowrapper/ModifyAssociationOperation.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.topicmap.undowrapper; import java.util.HashMap; import java.util.Map; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public class ModifyAssociationOperation extends UndoOperation { private RemoveAssociationOperation removeOperation; private CreateAssociationOperation addOperation; private boolean nop=false; // don't do anything if this is true private ModifyAssociationOperation() { } public static ModifyAssociationOperation setType(Association a, Topic type) throws TopicMapException, UndoException { ModifyAssociationOperation ret=new ModifyAssociationOperation(); Topic oldType=a.getType(); if(oldType.mergesWithTopic(type)) { ret.nop=true; return ret; } ret.removeOperation=new RemoveAssociationOperation(a); ret.addOperation=new CreateAssociationOperation(a,false); ret.addOperation.setType(type.getFirstSubjectIdentifier()); return ret; } public static ModifyAssociationOperation addPlayers(Association a, Map<Topic,Topic> members) throws TopicMapException, UndoException { ModifyAssociationOperation ret=new ModifyAssociationOperation(); ret.removeOperation=new RemoveAssociationOperation(a); ret.addOperation=new CreateAssociationOperation(a,false); // make sure that at least one of the players actually changes something, then turn this to false ret.nop=true; HashMap<Locator,Locator> players=ret.addOperation.getPlayers(); for(Map.Entry<Topic,Topic> e : members.entrySet()){ if(ret.nop){ Topic oldPlayer=a.getPlayer(e.getKey()); if(oldPlayer==null || !e.getValue().mergesWithTopic(oldPlayer)) ret.nop=false; } Locator rsi=e.getKey().getFirstSubjectIdentifier(); Locator psi=e.getValue().getFirstSubjectIdentifier(); if(rsi==null || psi==null) throw new UndoException(); players.put(rsi,psi); } ret.addOperation.setPlayers(players); return ret; } public static ModifyAssociationOperation addPlayer(Association a, Topic role, Topic player) throws TopicMapException, UndoException { ModifyAssociationOperation ret=new ModifyAssociationOperation(); Topic oldPlayer=a.getPlayer(role); if(oldPlayer!=null && player!=null && oldPlayer.mergesWithTopic(player)){ ret.nop=true; // the operation doesn't actually change anything at all. return ret; } if(player==null && oldPlayer==null){ ret.nop=true; return ret; } ret.removeOperation=new RemoveAssociationOperation(a); ret.addOperation=new CreateAssociationOperation(a,false); HashMap<Locator,Locator> players=ret.addOperation.getPlayers(); if(player==null) players.remove(role.getFirstSubjectIdentifier()); else players.put(role.getFirstSubjectIdentifier(),player.getFirstSubjectIdentifier()); ret.addOperation.setPlayers(players); return ret; } public static ModifyAssociationOperation removePlayer(Association a, Topic role) throws TopicMapException, UndoException { return addPlayer(a,role,null); } // ------------------------------------------------------------------------- @Override public void undo() throws UndoException { if(nop) return; addOperation.undo(); removeOperation.undo(); } @Override public void redo() throws UndoException { if(nop) return; removeOperation.redo(); addOperation.redo(); } @Override public String getLabel() { return "modify association"; } @Override public UndoOperation combineWith(UndoOperation previous) { if(previous instanceof CreateAssociationOperation){ if(nop) return previous; UndoOperation op=removeOperation.combineWith(previous); if(op!=null && op instanceof NoOperation){ return addOperation.clone(); } } return null; } }
5,248
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
RemoveAssociationOperation.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/undowrapper/RemoveAssociationOperation.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.topicmap.undowrapper; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public class RemoveAssociationOperation extends UndoOperation { private TopicMap tm; private Locator type; private HashMap<Locator,Locator> players; public RemoveAssociationOperation(Association a) throws UndoException, TopicMapException { this.tm=a.getTopicMap(); // getFirstSubjectIdentifier is used as opposed to getOneSubjectIdentifier // to make sure that same association results in same locators // and the operations will be the same according to the equals check and // hashCode. type=a.getType().getFirstSubjectIdentifier(); if(type==null) throw new UndoException(); players=new HashMap<Locator,Locator>(); Collection<Topic> rs=a.getRoles(); // ArrayList<Topic> rs=new ArrayList<Topic>(a.getRoles()); // Collections.sort(rs,new TMBox.TopicNameComparator(null)); for(Topic r : rs){ Locator rsi=r.getFirstSubjectIdentifier(); if(rsi==null) throw new UndoException(); Topic p=a.getPlayer(r); Locator psi=p.getFirstSubjectIdentifier(); if(psi==null) throw new UndoException(); players.put(rsi,psi); } } Locator getType(){return type;}; void setType(Locator type){this.type=type;} HashMap<Locator,Locator> getPlayers(){return players;} void setPlayers(HashMap<Locator,Locator> players){this.players=players;} public static Association findAssociation(TopicMap tm,Locator type,HashMap<Locator,Locator> players) throws TopicMapException, UndoException { Topic t=tm.getTopic(type); if(players.isEmpty()){ if(t==null) throw new UndoException(); Collection<Association> as=tm.getAssociationsOfType(t); for(Association a : as){ if(a.getRoles().isEmpty()) { return a; } } // association not found return null; } Collection<Map.Entry<Locator,Locator>> ms=players.entrySet(); /* ArrayList<Map.Entry<Locator,Locator>> ms=new ArrayList<Map.Entry<Locator,Locator>>(players.entrySet()); Collections.sort(ms,new Comparator<Map.Entry<Locator,Locator>>(){ @Override public int compare(Map.Entry<Locator, Locator> o1, Map.Entry<Locator, Locator> o2) { int c=o1.getKey().compareTo(o2.getKey()); if(c!=0) return c; else return o1.getValue().compareTo(o2.getValue()); } });*/ Map.Entry<Locator,Locator> firstm=ms.iterator().next(); Locator fpSi=firstm.getValue(); // first player Locator frSi=firstm.getKey(); // first role Topic fp=tm.getTopic(fpSi); Topic fr=tm.getTopic(frSi); if(fp==null || fr==null || t==null) throw new UndoException(); Collection<Association> as=fp.getAssociations(t, fr); AssociationsLoop: for(Association a : as){ Collection<Topic> roles=a.getRoles(); if(roles.size()!=players.size()) continue; RolesLoop: for(Topic role : roles){ Collection<Locator> rSis=role.getSubjectIdentifiers(); Collection<Locator> pSis=a.getPlayer(role).getSubjectIdentifiers(); for(Map.Entry<Locator,Locator> m : ms){ if(!rSis.contains(m.getKey())) continue ; if(!pSis.contains(m.getValue())) continue ; // this member matches, check next role continue RolesLoop; } // no member found for the role so the association can't match continue AssociationsLoop; } // all Roles matched so this is the association we're looking for return a; } /* AssociationsLoop: for(Association a : as){ ArrayList<Topic> roles=new ArrayList<Topic>(a.getRoles()); boolean[] used=new boolean[roles.size()]; MembersLoop: for(Map.Entry<Locator,Locator> m : ms){ for(int i=0;i<roles.size();i++){ Topic role=roles.get(i); Collection<Locator> rSis=role.getSubjectIdentifiers(); if(!rSis.contains(m.getKey())) continue; Collection<Locator> pSis=a.getPlayer(role).getSubjectIdentifiers(); if(!pSis.contains(m.getValue())) continue; used[i]=true; continue MembersLoop; } // no matcing player found for member, check next association continue AssociationsLoop; } // a match was found for all members for(int i=0;i<used.length;i++){ if(!used[i]) { // not all roles of the association were used, meaning // that this isn't the association we want, check next continue AssociationsLoop; } } // all members in the map matched and all roles of the association // were used, return this association return a; }*/ return null; } @Override public void undo() throws UndoException { try{ Topic t=tm.getTopic(type); if(t==null) throw new UndoException(); HashMap<Topic,Topic> ps=new HashMap<Topic,Topic>(); for(Map.Entry<Locator,Locator> e : players.entrySet()){ Topic r=tm.getTopic(e.getKey()); Topic p=tm.getTopic(e.getValue()); if(r==null || p==null) throw new UndoException(); ps.put(r,p); } Association a=tm.createAssociation(t); if(ps.size()>0) a.addPlayers(ps); }catch(TopicMapException tme){throw new UndoException(tme);} } @Override public void redo() throws UndoException { try{ Association a=findAssociation(tm,type,players); if(a==null) throw new AssociationNotFoundException(); else a.remove(); }catch(TopicMapException tme){throw new UndoException(tme);} } @Override public String getLabel() { return "remove association"; } @Override public UndoOperation combineWith(UndoOperation previous) { if(previous instanceof CreateAssociationOperation){ CreateAssociationOperation add=(CreateAssociationOperation)previous; if(type.equals(add.getType()) && players.equals(add.getPlayers())) { return new NoOperation(); } } return null; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final RemoveAssociationOperation other = (RemoveAssociationOperation) obj; if (this.type != other.type && (this.type == null || !this.type.equals(other.type))) { return false; } if (this.players != other.players && (this.players == null || !this.players.equals(other.players))) { return false; } return true; } @Override public int hashCode() { int hash = 5; hash = 71 * hash + (this.type != null ? this.type.hashCode() : 0); hash = 71 * hash + (this.players != null ? this.players.hashCode() : 0); return hash; } public static class AssociationNotFoundException extends UndoException { public AssociationNotFoundException(){ super(); } public AssociationNotFoundException(String message){ super(message); } } }
9,259
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
UndoException.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/undowrapper/UndoException.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.topicmap.undowrapper; /** * * @author olli */ public class UndoException extends Exception { public UndoException(){ } public UndoException(String message){ super(message); } public UndoException(Throwable t){ super(t); } public UndoException(String message,Throwable t){ super(message, t); } }
1,185
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
UndoTopic.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/undowrapper/UndoTopic.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.topicmap.undowrapper; import java.util.Collection; import java.util.HashSet; import java.util.Hashtable; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public class UndoTopic extends Topic { private UndoTopicMap topicMap; private Topic wrapped; UndoTopic(Topic wrapped,UndoTopicMap topicMap){ this.wrapped=wrapped; this.topicMap=topicMap; } static Set<Topic> getWrappedScope(Set<Topic> s){ HashSet<Topic> ret=new LinkedHashSet<Topic>(); for(Topic t : s){ ret.add(((UndoTopic)t).getWrapped()); } return ret; } Set<Topic> wrapScope(Set<Topic> s){ HashSet<Topic> ret=new LinkedHashSet<Topic>(); for(Topic t : s) { ret.add(topicMap.wrapTopic(t)); } return ret; } Topic getWrapped(){ return wrapped; } private boolean undoCreated() throws TopicMapException { return !wrapped.getSubjectIdentifiers().isEmpty(); } @Override public String getID() throws TopicMapException { return wrapped.getID(); } @Override public Collection<Locator> getSubjectIdentifiers() throws TopicMapException { return wrapped.getSubjectIdentifiers(); } @Override public void addSubjectIdentifier(Locator l) throws TopicMapException { if(wrapped.getSubjectIdentifiers().isEmpty()){ wrapped.addSubjectIdentifier(l); try { topicMap.addUndoOperation(new CreateTopicOperation(wrapped)); } catch(UndoException ue){ topicMap.handleUndoException(ue); } } else { try { topicMap.addUndoOperation(new AddSubjectIdentifierOperation(wrapped, l)); } catch(UndoException ue){ topicMap.handleUndoException(ue); } wrapped.addSubjectIdentifier(l); } } @Override public void removeSubjectIdentifier(Locator l) throws TopicMapException { if(wrapped.getSubjectIdentifiers().size()==1 && wrapped.getSubjectIdentifiers().contains(l)){ try { topicMap.addUndoOperation(new RemoveTopicOperation(wrapped)); } catch(UndoException ue){ topicMap.handleUndoException(ue); } } else { try { topicMap.addUndoOperation(new RemoveSubjectIdentifierOperation(wrapped, l)); } catch(UndoException ue){ topicMap.handleUndoException(ue); } } wrapped.removeSubjectIdentifier(l); } @Override public String getBaseName() throws TopicMapException { return wrapped.getBaseName(); } @Override public void setBaseName(String name) throws TopicMapException { try { if(undoCreated()) topicMap.addUndoOperation(new SetBaseNameOperation(wrapped, name)); } catch(UndoException ue){ topicMap.handleUndoException(ue); } wrapped.setBaseName(name); } @Override public Collection<Topic> getTypes() throws TopicMapException { return topicMap.wrapTopics(wrapped.getTypes()); } @Override public void addType(Topic t) throws TopicMapException { Topic wtype=((UndoTopic)t).getWrapped(); try { if(undoCreated()) topicMap.addUndoOperation(new AddTypeOperation(wrapped, wtype)); } catch(UndoException ue){ topicMap.handleUndoException(ue); } wrapped.addType(wtype); } @Override public void removeType(Topic t) throws TopicMapException { Topic wtype=((UndoTopic)t).getWrapped(); try { if(undoCreated()) topicMap.addUndoOperation(new RemoveTypeOperation(wrapped, wtype)); } catch(UndoException ue){ topicMap.handleUndoException(ue); } wrapped.removeType(wtype); } @Override public boolean isOfType(Topic t) throws TopicMapException { return wrapped.isOfType(((UndoTopic)t).getWrapped()); } @Override public String getVariant(Set<Topic> scope) throws TopicMapException { return wrapped.getVariant(getWrappedScope(scope)); } @Override public void setVariant(Set<Topic> scope, String name) throws TopicMapException { Set<Topic> wscope=getWrappedScope(scope); try { if(undoCreated()) topicMap.addUndoOperation(new SetVariantOperation(wrapped,wscope,name)); } catch(UndoException ue){ topicMap.handleUndoException(ue); } wrapped.setVariant(wscope,name); } @Override public Set<Set<Topic>> getVariantScopes() throws TopicMapException { Set<Set<Topic>> ret=new LinkedHashSet<Set<Topic>>(); for(Set<Topic> s : wrapped.getVariantScopes()){ ret.add(wrapScope(s)); } return ret; } @Override public void removeVariant(Set<Topic> scope) throws TopicMapException { Set<Topic> wscope=getWrappedScope(scope); try { if(undoCreated()) topicMap.addUndoOperation(new SetVariantOperation(wrapped,wscope,null)); } catch(UndoException ue){ topicMap.handleUndoException(ue); } wrapped.removeVariant(wscope); } @Override public String getData(Topic type, Topic version) throws TopicMapException { return wrapped.getData(((UndoTopic)type).getWrapped(),((UndoTopic)version).getWrapped()); } @Override public Hashtable<Topic, String> getData(Topic type) throws TopicMapException { Hashtable<Topic, String> ret=new Hashtable<Topic, String>(); for(Map.Entry<Topic,String> e : wrapped.getData(((UndoTopic)type).getWrapped()).entrySet() ){ ret.put(topicMap.wrapTopic(e.getKey()),e.getValue()); } return ret; } @Override public Collection<Topic> getDataTypes() throws TopicMapException { return topicMap.wrapTopics(wrapped.getDataTypes()); } @Override public void setData(Topic type, Hashtable<Topic, String> versionData) throws TopicMapException { Topic wtype=((UndoTopic)type).getWrapped(); Hashtable data=new Hashtable<Topic, String>(); for(Map.Entry<Topic,String> e : versionData.entrySet()){ Topic wversion=((UndoTopic)e.getKey()).getWrapped(); String value=e.getValue(); data.put(wversion,value); try { if(undoCreated()) topicMap.addUndoOperation(new SetOccurrenceOperation(wrapped,wtype,wversion,value)); } catch(UndoException ue){ topicMap.handleUndoException(ue); } } wrapped.setData(wtype,data); } @Override public void setData(Topic type, Topic version, String value) throws TopicMapException { Topic wtype=((UndoTopic)type).getWrapped(); Topic wversion=((UndoTopic)version).getWrapped(); try { if(undoCreated()) topicMap.addUndoOperation(new SetOccurrenceOperation(wrapped,wtype,wversion,value)); } catch(UndoException ue){ topicMap.handleUndoException(ue); } wrapped.setData(wtype,wversion,value); } @Override public void removeData(Topic type, Topic version) throws TopicMapException { Topic wtype=((UndoTopic)type).getWrapped(); Topic wversion=((UndoTopic)version).getWrapped(); try { if(undoCreated()) topicMap.addUndoOperation(new SetOccurrenceOperation(wrapped,wtype,wversion,null)); } catch(UndoException ue){ topicMap.handleUndoException(ue); } wrapped.removeData(wtype,wversion); } @Override public void removeData(Topic type) throws TopicMapException { Topic wtype=((UndoTopic)type).getWrapped(); Hashtable<Topic,String> oldData=getWrapped().getData(type); if(oldData != null) { for(Map.Entry<Topic,String> e : oldData.entrySet()){ Topic wversion=((UndoTopic)e.getKey()).getWrapped(); try { if(undoCreated()) topicMap.addUndoOperation(new SetOccurrenceOperation(wrapped,wtype,wversion,null)); } catch(UndoException ue){ topicMap.handleUndoException(ue); } } wrapped.removeData(wtype); } } @Override public Locator getSubjectLocator() throws TopicMapException { return wrapped.getSubjectLocator(); } @Override public void setSubjectLocator(Locator l) throws TopicMapException { try { if(undoCreated()) topicMap.addUndoOperation(new SetSubjectLocatorOperation(wrapped, l)); } catch(UndoException ue){ topicMap.handleUndoException(ue); } wrapped.setSubjectLocator(l); } @Override public TopicMap getTopicMap() { return topicMap; } @Override public Collection<Association> getAssociations() throws TopicMapException { return topicMap.wrapAssociations(wrapped.getAssociations()); } @Override public Collection<Association> getAssociations(Topic type) throws TopicMapException { return topicMap.wrapAssociations(wrapped.getAssociations(((UndoTopic)type).getWrapped())); } @Override public Collection<Association> getAssociations(Topic type, Topic role) throws TopicMapException { return topicMap.wrapAssociations(wrapped.getAssociations(((UndoTopic)type).getWrapped(),((UndoTopic)role).getWrapped())); } @Override public void remove() throws TopicMapException { try { if(undoCreated()) topicMap.addUndoOperation(new RemoveTopicOperation(wrapped)); } catch(UndoException ue){ topicMap.handleUndoException(ue); } wrapped.remove(); } @Override public long getEditTime() throws TopicMapException { return wrapped.getEditTime(); } @Override public void setEditTime(long time) throws TopicMapException { wrapped.setEditTime(time); } @Override public long getDependentEditTime() throws TopicMapException { return wrapped.getDependentEditTime(); } @Override public void setDependentEditTime(long time) throws TopicMapException { wrapped.setDependentEditTime(time); } @Override public boolean isRemoved() throws TopicMapException { return wrapped.isRemoved(); } @Override public boolean isDeleteAllowed() throws TopicMapException { return wrapped.isDeleteAllowed(); } @Override public Collection<Topic> getTopicsWithDataType() throws TopicMapException { return topicMap.wrapTopics(wrapped.getTopicsWithDataType()); } @Override public Collection<Topic> getTopicsWithDataVersion() throws TopicMapException { return topicMap.wrapTopics(wrapped.getTopicsWithDataVersion()); } @Override public Collection<Topic> getTopicsWithVariantScope() throws TopicMapException { return topicMap.wrapTopics(wrapped.getTopicsWithVariantScope()); } @Override public Collection<Association> getAssociationsWithType() throws TopicMapException { return topicMap.wrapAssociations(wrapped.getAssociationsWithType()); } @Override public Collection<Association> getAssociationsWithRole() throws TopicMapException { return topicMap.wrapAssociations(wrapped.getAssociationsWithType()); } }
12,500
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
UndoBuffer.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/undowrapper/UndoBuffer.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.topicmap.undowrapper; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import org.wandora.application.Wandora; import org.wandora.application.gui.WandoraOptionPane; /** * <p> * UndoBuffer implements a storage for undo operations. Stored undo operations * are grouped by a special marker-operations, also stored into the buffer. * Marker-operation is added to the buffer <b>after</b> real operations. * Undoing processes all undo-operations till next marker-operation. * </p> * <p> * UndoBuffer contains a redo-buffer also. Undoed operations are stored * in redo-buffer until next operation is stored into the undo-buffer. * </p> * <p> * Undo-buffer's size is limited to <code>MAX_BUFFER_SIZE</code> operations. * Undo-buffer removes marked sets of operations until the number of operations * is below <code>MAX_BUFFER_SIZE</code>. * </p> * * @author olli */ public class UndoBuffer { /* * Should the UndoBuffer skip markers that have no preceeding * (real) undoable operations. By default UndoBuffer doesn't * store empty markers. */ public static boolean SKIP_EMPTY_OPERATIONS = true; /* * Should the UndoBuffer inform Wandora user when the size of * undo-buffer hits <code>MAX_BUFFER_SIZE</code>. */ public static boolean SHOW_MESSAGE = true; /* * How many operations the undo-buffer can hold until it tries to * remove oldest operations. */ public static final int MAX_BUFFER_SIZE = 50000; public static boolean SKIP_OPERATIONS_TILL_NEXT_MARKER = false; /* * Actual storage of undoable operations. */ private LinkedList<UndoOperation> undobuffer; /* * Actual storage of undoed operations (that can be redoed). */ private LinkedList<UndoOperation> redobuffer; public UndoBuffer(){ undobuffer=new LinkedList<UndoOperation>(); redobuffer=new LinkedList<UndoOperation>(); } /* * Clears both undo-buffer and redo-buffer. */ public void clear(){ undobuffer.clear(); redobuffer.clear(); } /* * This is the hearth of UndoBuffer. AddOperation method stores given * operation into the undo-buffer. There is a special logic to prevent * empty markers to smudge the undo-buffer. Also, added operation * may combine with the previous operation if they support combining. * Method also checks if the size of undo-buffer has exceeded the * <code>MAX_BUFFER_SIZE</code> and removes operations if necessary. */ public void addOperation(UndoOperation op) { if(SKIP_OPERATIONS_TILL_NEXT_MARKER && !op.isMarker()) { return; } if(SKIP_OPERATIONS_TILL_NEXT_MARKER && op.isMarker()) { SKIP_OPERATIONS_TILL_NEXT_MARKER = false; return; } if(!op.isMarker()) { // Redo buffer becomes invalid after new operation. redobuffer.clear(); } if(!undobuffer.isEmpty()) { UndoOperation previous=undobuffer.peekLast(); // If there already is a marker on top of the buffer, don't add another. if(SKIP_EMPTY_OPERATIONS && previous.isMarker() && op.isMarker()) return; // Check if new operation can be combined with a previous one. UndoOperation combined=op.combineWith(previous); if(combined!=null) { undobuffer.removeLast(); op = combined; } } else { // If undo buffer is empty, we really shouldn't add a marker first. if(SKIP_EMPTY_OPERATIONS && op.isMarker()) return; } undobuffer.addLast(op); //System.out.println("undobuffer["+ undobuffer.size() +"] "+op); // If the undo buffer size is too big, remove oldest operation. if(undobuffer.size() > MAX_BUFFER_SIZE ) { if(SHOW_MESSAGE) { Wandora w = Wandora.getWandora(); WandoraOptionPane.showMessageDialog(w, "Undo buffer contains too many operations ("+undobuffer.size()+"). "+ "Wandora removes oldest operations in the undo buffer. "+ "This is a one time message. "+ "Next time the buffer is cleaned automatically without any messages.", "Undo buffer contains too many operations", WandoraOptionPane.INFORMATION_MESSAGE); SHOW_MESSAGE = false; } System.out.println("Removing oldest operations in the undo buffer"); while(!undobuffer.isEmpty() && !undobuffer.peekFirst().isMarker()) { undobuffer.removeFirst(); } if(!undobuffer.isEmpty()) { // Remove the marker if any. undobuffer.removeFirst(); } if(undobuffer.isEmpty()) { // If the undobuffer is empty, do not store any operations during // current execution cycle. SKIP_OPERATIONS_TILL_NEXT_MARKER = true; } } } public void pruneOne(){ while(!undobuffer.isEmpty() && undobuffer.peekLast().isMarker()) { undobuffer.removeLast(); // This handles all preceding markers! } while(!undobuffer.isEmpty() && !undobuffer.peekLast().isMarker()){ undobuffer.removeLast(); } } /* * This is a shurtcut method to add a marker into the undo-buffer. * Markers are used to separate undo-operations from different * sources. */ public void addMarker(String label){ addMarker(label,label); } /* * This is a shurtcut method to add a marker into the undo-buffer. * Markers are used to separate undo-operations from different * sources. */ public void addMarker(String undoLabel,String redoLabel){ addOperation(new UndoMarker(undoLabel,redoLabel)); } /* * Undo next available operation in the undo-buffer. */ private void undoOne() throws UndoException { UndoOperation op=undobuffer.removeLast(); // System.out.println("undo: "+op); op.undo(); redobuffer.addFirst(op); } /* * Undo operations under the first marker, until next marker is faced or * the undo-buffer is empty. */ public void undo() throws UndoException { if(undobuffer.isEmpty()) throw new UndoException("Nothing to undo."); if(!undobuffer.isEmpty() && undobuffer.peekLast().isMarker()) { undoOne(); // This handles the marker } while(!undobuffer.isEmpty() && !undobuffer.peekLast().isMarker()){ undoOne(); } } /* * Redo exactly (and only) first redoable operation if such exists. */ private void redoOne() throws UndoException { UndoOperation op=redobuffer.removeFirst(); // System.out.println("undobuffer["+ undobuffer.size() +"] "+op); op.redo(); undobuffer.addLast(op); } /* * Redo next set of redoable operations. */ public void redo() throws UndoException { if(redobuffer.isEmpty()) throw new UndoException("Nothing to redo."); while(!redobuffer.isEmpty() && !redobuffer.peekFirst().isMarker()){ redoOne(); } if(!redobuffer.isEmpty() && redobuffer.peekFirst().isMarker()){ redoOne(); } } // ----------------- /* * Is there any undoable operations available in the undo-buffer. */ public boolean canUndo(){ return !undobuffer.isEmpty(); } /* * Is there any redoable operations available in the redo-buffer. */ public boolean canRedo(){ return !redobuffer.isEmpty(); } public int getUndoOperationNumber(){ if(undobuffer.isEmpty()) return Integer.MIN_VALUE; else return undobuffer.peekLast().getOperationNumber(); } public int getRedoOperationNumber(){ if(redobuffer.isEmpty()) return Integer.MAX_VALUE; else return redobuffer.peekFirst().getOperationNumber(); } /* * Should the undo-buffer reject a marker operation if it doesn't * preceed real undoable operations i.e. it is empty. This method is used * to set the static boolean type variable. */ public void setSkipEmptyOperations(boolean s) { SKIP_EMPTY_OPERATIONS = s; } // ------------------------------------------------------------------------- /* * Return all stored undo-operations. This method is used to get a * list of stored operations viewed in the configuration dialog * of Undo (and Redo) tools. */ public Collection<UndoOperation> getOperations() { ArrayList<UndoOperation> ops = new ArrayList(); ops.addAll(undobuffer); return ops; } }
10,050
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
UndoMarker.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/undowrapper/UndoMarker.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.topicmap.undowrapper; /** * * @author olli */ public class UndoMarker extends UndoOperation { protected String undoLabel; protected String redoLabel; public UndoMarker(String label) { this(label,label); } public UndoMarker(String undoLabel,String redoLabel){ this.undoLabel=undoLabel; this.redoLabel=redoLabel; this.isMarker=true; } @Override public void undo() throws UndoException { } @Override public void redo() throws UndoException { } @Override public String getLabel() { return undoLabel; } @Override public String getRedoLabel() { return redoLabel; } @Override public String getUndoLabel() { return undoLabel; } @Override public UndoOperation combineWith(UndoOperation previous) { return null; } }
1,726
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
RemoveSubjectIdentifierOperation.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/undowrapper/RemoveSubjectIdentifierOperation.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.topicmap.undowrapper; import java.util.Collection; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public class RemoveSubjectIdentifierOperation extends UndoOperation{ protected TopicMap tm; protected Locator si; protected Locator otherSi; protected boolean dummy=false; public RemoveSubjectIdentifierOperation(Topic t,Locator si) throws TopicMapException, UndoException { this.tm=t.getTopicMap(); this.si=si; Collection<Locator> sis=t.getSubjectIdentifiers(); if(!sis.contains(si)) {dummy=true; return;} for(Locator s : sis){ if(!s.equals(si)) { this.otherSi=s; break; } } if(otherSi==null) throw new UndoException("Topic only has one subject identifier which is about to be removed"); } @Override public String getLabel() { return "Remove Subject Identifier"; } @Override public void undo() throws UndoException { if(dummy) return; try { Topic t=tm.getTopic(otherSi); if(t==null) throw new UndoException(); Topic t2=tm.getTopic(si); if(t2!=null) throw new UndoException(); t.addSubjectIdentifier(si); } catch(TopicMapException tme) { throw new UndoException(tme); } } @Override public void redo() throws UndoException { if(dummy) return; try { Topic t=tm.getTopic(otherSi); if(t==null) throw new UndoException(); if(!t.getSubjectIdentifiers().contains(si)) throw new UndoException(); t.removeSubjectIdentifier(si); } catch(TopicMapException tme) { throw new UndoException(tme); } } }
2,755
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AddSubjectIdentifierOperation.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/undowrapper/AddSubjectIdentifierOperation.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.topicmap.undowrapper; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author akivela */ public class AddSubjectIdentifierOperation extends UndoOperation { protected TopicMap tm; protected Locator si; protected Locator newSI; protected MergeOperation merge; protected boolean dummy=false; public AddSubjectIdentifierOperation(Topic t, Locator newSI) throws TopicMapException, UndoException { this.tm=t.getTopicMap(); if(t.getSubjectIdentifiers().contains(newSI)) dummy=true; else { si=t.getOneSubjectIdentifier(); if(si==null) throw new UndoException("Topic doesn't have a subject identifier"); this.newSI=newSI; Topic t2=tm.getTopic(newSI); if(t2!=null && !t2.mergesWithTopic(t)) { merge=new MergeOperation(t, t2); } } } @Override public String getLabel() { return "Add Subject Identifier"; } @Override public void undo() throws UndoException { if(dummy) return; try{ Topic t = tm.getTopic(si); if(t==null) throw new UndoException(); if(merge!=null) { merge.undo(); } else t.removeSubjectIdentifier(newSI); } catch(TopicMapException tme) { throw new UndoException(tme); } } @Override public void redo() throws UndoException { if(dummy) return; try { Topic t=tm.getTopic(si); if(t==null) throw new UndoException(); t.addSubjectIdentifier(newSI); } catch(TopicMapException tme) { throw new UndoException(tme); } } }
2,700
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
UndoTopicMap.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/undowrapper/UndoTopicMap.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.topicmap.undowrapper; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.WeakHashMap; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicIterator; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicMapListener; import org.wandora.topicmap.TopicMapLogger; import org.wandora.topicmap.TopicMapSearchOptions; import org.wandora.topicmap.TopicMapStatData; import org.wandora.topicmap.TopicMapStatOptions; /** * * @author olli */ public class UndoTopicMap extends TopicMap { private TopicMap wrapped; private UndoBuffer undoBuffer; private boolean undoDisabled=false; private final WeakHashMap<Topic,WeakReference<UndoTopic>> topicIndex=new WeakHashMap<Topic,WeakReference<UndoTopic>>(); public UndoTopicMap(TopicMap wrapped, boolean skipEmptyOperations) { this.wrapped=wrapped; this.undoBuffer=new UndoBuffer(); this.undoBuffer.setSkipEmptyOperations(skipEmptyOperations); } public UndoTopicMap(TopicMap wrapped) { this.wrapped=wrapped; this.undoBuffer=new UndoBuffer(); } public void close() { this.wrapped.close(); } public void setUndoDisabled(boolean value){ this.undoDisabled=value; } public UndoBuffer getUndoBuffer(){ return undoBuffer; } public TopicMap getWrappedTopicMap() { return wrapped; } public void handleUndoException(UndoException ue){ ue.printStackTrace(); } void addUndoOperation(UndoOperation op){ if(undoDisabled) { // clear undo buffer because it would get out of sync with the topic map otherwise clearUndoBuffer(); return; } undoBuffer.addOperation(op); } UndoTopic wrapTopic(Topic t){ if(t==null) return null; synchronized(topicIndex){ UndoTopic ret=null; WeakReference<UndoTopic> ref=topicIndex.get(t); if(ref!=null) ret=ref.get(); if(ret==null){ ret=new UndoTopic(t,this); topicIndex.put(t,new WeakReference<UndoTopic>(ret)); return ret; } else return ret; } } ArrayList<Topic> wrapTopics(Collection<Topic> topics){ ArrayList<Topic> ret=new ArrayList<Topic>(); for(Topic t : topics){ ret.add(wrapTopic(t)); } return ret; } Topic[] wrapTopics(Topic[] topics){ Topic[] ret=new Topic[topics.length]; for(int i=0;i<topics.length;i++){ ret[i]=wrapTopic(topics[i]); } return ret; } Association wrapAssociation(Association a){ if(a==null) return null; return new UndoAssociation(a,this); } Collection<Association> wrapAssociations(Collection<Association> as){ ArrayList<Association> ret=new ArrayList<Association>(); for(Association a : as){ ret.add(wrapAssociation(a)); } return ret; } // ------------------------------------------------------------------------- @Override public TopicMap getParentTopicMap() { return wrapped.getParentTopicMap(); } @Override public TopicMap getRootTopicMap() { return wrapped.getRootTopicMap(); } @Override public void setParentTopicMap(TopicMap parent) { if(wrapped != null) wrapped.setParentTopicMap(parent); } // ------------------------------------------------------------------------- @Override public Topic getTopic(Locator si) throws TopicMapException { return wrapTopic(wrapped.getTopic(si)); } @Override public Topic getTopicBySubjectLocator(Locator sl) throws TopicMapException { return wrapTopic(wrapped.getTopicBySubjectLocator(sl)); } @Override public Topic createTopic(String id) throws TopicMapException { // Create topic operation is not done here because the topic doesn't have // a subject identifier yet. UndoTopic does it when the first subject // identifier is added. return wrapTopic(wrapped.createTopic(id)); } @Override public Topic createTopic() throws TopicMapException { // Create topic operation is not done here because the topic doesn't have // a subject identifier yet. UndoTopic does it when the first subject // identifier is added. return wrapTopic(wrapped.createTopic()); } @Override public Association createAssociation(Topic type) throws TopicMapException { // Create association operatien is not done here because the association // is empty. UndoAssociation does it when the first player is added. return wrapAssociation(wrapped.createAssociation(((UndoTopic)type).getWrapped())); } @Override public Collection<Topic> getTopicsOfType(Topic type) throws TopicMapException { return wrapTopics(wrapped.getTopicsOfType(((UndoTopic)type).getWrapped())); } @Override public Topic getTopicWithBaseName(String name) throws TopicMapException { return wrapTopic(wrapped.getTopicWithBaseName(name)); } @Override public Iterator<Topic> getTopics() throws TopicMapException { final Iterator<Topic> iter=wrapped.getTopics(); return new TopicIterator(){ @Override public void dispose() { if(iter instanceof TopicIterator) ((TopicIterator)iter).dispose(); else while(iter.hasNext()) iter.next(); } public boolean hasNext() { return iter.hasNext(); } public Topic next() { return wrapTopic(iter.next()); } public void remove() {throw new UnsupportedOperationException();} }; } @Override public Topic[] getTopics(String[] sis) throws TopicMapException { return wrapTopics(wrapped.getTopics(sis)); } @Override public Iterator<Association> getAssociations() throws TopicMapException { final Iterator<Association> iter=wrapped.getAssociations(); return new Iterator<Association>(){ public boolean hasNext() { return iter.hasNext(); } public Association next() { return wrapAssociation(iter.next()); } public void remove() {throw new UnsupportedOperationException();} }; } @Override public Collection<Association> getAssociationsOfType(Topic type) throws TopicMapException { return wrapAssociations(wrapped.getAssociationsOfType(((UndoTopic)type).getWrapped())); } @Override public int getNumTopics() throws TopicMapException { return wrapped.getNumTopics(); } @Override public int getNumAssociations() throws TopicMapException { return wrapped.getNumAssociations(); } @Override public Topic copyTopicIn(Topic t, boolean deep) throws TopicMapException { return wrapTopic(wrapped.copyTopicIn(((UndoTopic)t).getWrapped(),deep)); } @Override public Association copyAssociationIn(Association a) throws TopicMapException { return wrapAssociation(wrapped.copyAssociationIn(((UndoAssociation)a).getWrapped())); } @Override public void copyTopicAssociationsIn(Topic t) throws TopicMapException { wrapped.copyTopicAssociationsIn(((UndoTopic)t).getWrapped()); } @Override public void setTrackDependent(boolean v) throws TopicMapException { wrapped.setTrackDependent(v); } @Override public boolean trackingDependent() throws TopicMapException { return wrapped.trackingDependent(); } private HashMap<TopicMapListener,TopicMapListenerWrapper> wrappedListeners=new HashMap<TopicMapListener,TopicMapListenerWrapper>(); private class TopicMapListenerWrapper implements TopicMapListener { private TopicMapListener wrapped; public TopicMapListenerWrapper(TopicMapListener l){ wrapped=l; } public void topicSubjectIdentifierChanged(Topic t, Locator added, Locator removed) throws TopicMapException { wrapped.topicSubjectIdentifierChanged(wrapTopic(t), added, removed); } public void topicBaseNameChanged(Topic t, String newName, String oldName) throws TopicMapException { wrapped.topicBaseNameChanged(wrapTopic(t), newName, oldName); } public void topicTypeChanged(Topic t, Topic added, Topic removed) throws TopicMapException { wrapped.topicTypeChanged(wrapTopic(t), wrapTopic(added), wrapTopic(removed)); } public void topicVariantChanged(Topic t, Collection<Topic> scope, String newName, String oldName) throws TopicMapException { wrapped.topicVariantChanged(wrapTopic(t), wrapTopics(scope), newName, oldName); } public void topicDataChanged(Topic t, Topic type, Topic version, String newValue, String oldValue) throws TopicMapException { wrapped.topicDataChanged(wrapTopic(t), wrapTopic(type), wrapTopic(version), newValue, oldValue); } public void topicSubjectLocatorChanged(Topic t, Locator newLocator, Locator oldLocator) throws TopicMapException { wrapped.topicSubjectLocatorChanged(wrapTopic(t), newLocator, oldLocator); } public void topicRemoved(Topic t) throws TopicMapException { wrapped.topicRemoved(wrapTopic(t)); } public void topicChanged(Topic t) throws TopicMapException { wrapped.topicChanged(wrapTopic(t)); } public void associationTypeChanged(Association a, Topic newType, Topic oldType) throws TopicMapException { wrapped.associationTypeChanged(wrapAssociation(a), wrapTopic(newType), wrapTopic(oldType)); } public void associationPlayerChanged(Association a, Topic role, Topic newPlayer, Topic oldPlayer) throws TopicMapException { wrapped.associationPlayerChanged(wrapAssociation(a), wrapTopic(role), wrapTopic(newPlayer), wrapTopic(oldPlayer)); } public void associationRemoved(Association a) throws TopicMapException { wrapped.associationRemoved(wrapAssociation(a)); } public void associationChanged(Association a) throws TopicMapException { wrapped.associationChanged(wrapAssociation(a)); } } @Override public void addTopicMapListener(TopicMapListener listener) { TopicMapListenerWrapper wrapper=new TopicMapListenerWrapper(listener); wrappedListeners.put(listener,wrapper); wrapped.addTopicMapListener(wrapper); } @Override public void removeTopicMapListener(TopicMapListener listener) { TopicMapListenerWrapper wrapper=wrappedListeners.get(listener); if(listener==null) return; wrapped.removeTopicMapListener(wrapper); } @Override public List<TopicMapListener> getTopicMapListeners() { return new ArrayList<TopicMapListener>(wrappedListeners.values()); } @Override public void disableAllListeners() { wrapped.disableAllListeners(); } @Override public void enableAllListeners() { wrapped.enableAllListeners(); } @Override public boolean isTopicMapChanged() throws TopicMapException { return wrapped.isTopicMapChanged(); } @Override public boolean resetTopicMapChanged() throws TopicMapException { return wrapped.resetTopicMapChanged(); } @Override public Collection<Topic> search(String query, TopicMapSearchOptions options) throws TopicMapException { return wrapTopics(wrapped.search(query,options)); } @Override public TopicMapStatData getStatistics(TopicMapStatOptions options) throws TopicMapException { return wrapped.getStatistics(options); } public void clearUndoBuffer() { undoBuffer.clear(); } @Override public void clearTopicMap() throws TopicMapException { // this operation cannot be undone, clear undo buffer too clearUndoBuffer(); wrapped.clearTopicMap(); } @Override public void clearTopicMapIndexes() throws TopicMapException { wrapped.clearTopicMapIndexes(); } @Override public void checkAssociationConsistency(TopicMapLogger logger) throws TopicMapException { wrapped.checkAssociationConsistency(logger); } @Override public boolean getConsistencyCheck() throws TopicMapException { return wrapped.getConsistencyCheck(); } @Override public boolean isConnected() throws TopicMapException { return wrapped.isConnected(); } @Override public void setReadOnly(boolean readOnly) { wrapped.setReadOnly(readOnly); } @Override public boolean isReadOnly() { return wrapped.isReadOnly(); } @Override public void setConsistencyCheck(boolean value) throws TopicMapException { wrapped.setConsistencyCheck(value); } @Override public void mergeIn(TopicMap tm) throws TopicMapException { wrapped.mergeIn(tm); } @Override public void mergeIn(TopicMap tm,TopicMapLogger tmLogger) throws TopicMapException { wrapped.mergeIn(tm,tmLogger); } // ------------------------------------------------------------------------- }
14,695
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
UndoOperation.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/undowrapper/UndoOperation.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.topicmap.undowrapper; import java.util.concurrent.atomic.AtomicInteger; /** * * @author olli */ public abstract class UndoOperation { private static final AtomicInteger operationCounter=new AtomicInteger(0); protected int operationNumber; protected boolean isMarker; public UndoOperation() { isMarker=false; operationNumber=operationCounter.getAndIncrement(); } public int getOperationNumber(){ return operationNumber; } public boolean isMarker(){ return isMarker; } public boolean canUndo() { return isMarker; } public boolean canRedo(){ return isMarker; } public abstract void undo() throws UndoException; public abstract void redo() throws UndoException; public abstract String getLabel(); public String getUndoLabel(){return getLabel();} public String getRedoLabel(){return getLabel();} public String getDescription() {return getLabel();} // In some cases we might want to combine several operations into one. // Override this and make it return the combination of first doing // the previous edit and then this edit in single operation. That // operation will then replace these two operations in the buffer. public UndoOperation combineWith(UndoOperation previous){return null;} }
2,218
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SetSubjectLocatorOperation.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/undowrapper/SetSubjectLocatorOperation.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.topicmap.undowrapper; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public class SetSubjectLocatorOperation extends UndoOperation { protected TopicMap tm; protected Locator si; protected Locator oldSL; protected Locator newSL; protected MergeOperation merge; protected boolean nop=false; public SetSubjectLocatorOperation(Topic t,Locator newSL) throws TopicMapException, UndoException { if(t.getSubjectLocator()!=null && newSL!=null && t.getSubjectLocator().equals(newSL)){ nop=true; return; } this.tm=t.getTopicMap(); si=t.getOneSubjectIdentifier(); if(si==null) throw new UndoException("Topic doesn't have a subject identifier"); oldSL=t.getSubjectLocator(); this.newSL=newSL; if(newSL!=null){ Topic t2=t.getTopicMap().getTopicBySubjectLocator(newSL); if(t2!=null) merge=new MergeOperation(t, t2); } } @Override public String getLabel() { return "subject locator"; } @Override public void undo() throws UndoException { if(nop) return; try{ if(merge!=null){ merge.undo(); } else { Topic t=tm.getTopic(si); if(t==null) throw new UndoException(); if(oldSL!=null){ Topic t2=tm.getTopicBySubjectLocator(oldSL); if(t2!=null && !t2.mergesWithTopic(t)) throw new UndoException(); } t.setSubjectLocator(oldSL); } }catch(TopicMapException tme){throw new UndoException(tme);} } @Override public void redo() throws UndoException { if(nop) return; try{ Topic t=tm.getTopic(si); if(t==null) throw new UndoException(); if(newSL!=null && merge==null){ // t2 existing is fine if this was supposed to be a merge, // otherwise something's wrong Topic t2=tm.getTopicBySubjectLocator(newSL); if(t2!=null) throw new UndoException(); } // this may result in a merge but that's fine, the topicmap itself // will handle that correctly. t.setSubjectLocator(newSL); }catch(TopicMapException tme){throw new UndoException(tme);} } }
3,384
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
CreateAssociationOperation.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/undowrapper/CreateAssociationOperation.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.topicmap.undowrapper; import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public class CreateAssociationOperation extends UndoOperation { private TopicMap tm; private Locator type; private HashMap<Locator,Locator> players; private boolean associationAlreadyExists = false; public CreateAssociationOperation(TopicMap tm,Locator type,HashMap<Locator,Locator> players) throws UndoException,TopicMapException { this.tm = tm; this.type = type; this.players = players; Association oa=RemoveAssociationOperation.findAssociation(tm,type,players); associationAlreadyExists = (oa!=null); } public CreateAssociationOperation(Topic type,HashMap<Topic,Topic> players) throws UndoException,TopicMapException { this.tm = type.getTopicMap(); this.type = type.getOneSubjectIdentifier(); this.players = new HashMap<Locator,Locator>(); for(Map.Entry<Topic,Topic> e : players.entrySet()){ Locator rsi=e.getKey().getOneSubjectIdentifier(); Locator psi=e.getValue().getOneSubjectIdentifier(); if(rsi==null || psi==null) throw new UndoException(); this.players.put(rsi,psi); } Association oa=RemoveAssociationOperation.findAssociation(tm,this.type,this.players); associationAlreadyExists = (oa!=null); } public CreateAssociationOperation(TopicMap tm,Locator type,Locator role,Locator player) throws UndoException,TopicMapException { this.tm = tm; this.type = type; this.players = new HashMap<Locator,Locator>(); players.put(role,player); Association oa=RemoveAssociationOperation.findAssociation(tm,type,players); associationAlreadyExists = (oa!=null); } public CreateAssociationOperation(Topic type,Topic role,Topic player) throws UndoException,TopicMapException { this.tm = type.getTopicMap(); this.type = type.getOneSubjectIdentifier(); this.players = new HashMap<Locator,Locator>(); Locator rsi=role.getOneSubjectIdentifier(); Locator psi=player.getOneSubjectIdentifier(); if(this.type==null || rsi==null || psi==null) throw new UndoException(); players.put(rsi,psi); Association oa=RemoveAssociationOperation.findAssociation(tm,this.type,players); associationAlreadyExists = (oa!=null); } // this constructor is used by some of the other undo operations, but it // should not be used by outside code as the exists flag needs manual handling CreateAssociationOperation(Association a,boolean exists) throws UndoException, TopicMapException { this.tm=a.getTopicMap(); type=a.getType().getFirstSubjectIdentifier(); if(type==null) throw new UndoException(); players=new LinkedHashMap<Locator,Locator>(); Collection<Topic> rs=a.getRoles(); // ArrayList<Topic> rs=new ArrayList<Topic>(a.getRoles()); // Collections.sort(rs,new TMBox.TopicNameComparator(null)); for(Topic r : rs){ Locator rsi=r.getFirstSubjectIdentifier(); if(rsi==null) throw new UndoException(); Topic p=a.getPlayer(r); Locator psi=p.getFirstSubjectIdentifier(); if(psi==null) throw new UndoException(); players.put(rsi,psi); } this.associationAlreadyExists=exists; } // this constructor is only for the clone method, it should not be used by outside code private CreateAssociationOperation(TopicMap tm,Locator type,HashMap<Locator,Locator> players, boolean exists) { this.tm = tm; this.type = type; this.players = players; this.associationAlreadyExists = exists; } Locator getType(){ return type; }; void setType(Locator type) { this.type=type; try { Association oa=RemoveAssociationOperation.findAssociation(tm,type,players); associationAlreadyExists = (oa!=null); } catch(Exception e) { e.printStackTrace(); } } HashMap<Locator,Locator> getPlayers(){ return players; } void setPlayers(HashMap<Locator,Locator> players) { this.players=players; try { Association oa=RemoveAssociationOperation.findAssociation(tm,type,players); associationAlreadyExists = (oa!=null); } catch(Exception e) { e.printStackTrace(); } } @Override public void redo() throws UndoException { try { if(!associationAlreadyExists) { Topic t=tm.getTopic(type); if(t==null) throw new UndoException(); HashMap<Topic,Topic> ps=new HashMap<Topic,Topic>(); for(Map.Entry<Locator,Locator> e : players.entrySet()) { Topic r=tm.getTopic(e.getKey()); Topic p=tm.getTopic(e.getValue()); if(r==null || p==null) throw new UndoException(); ps.put(r,p); } Association a=tm.createAssociation(t); if(ps.size()>0) a.addPlayers(ps); } } catch(TopicMapException tme){ throw new UndoException(tme); } } @Override public void undo() throws UndoException { try { if(!associationAlreadyExists) { Association a=RemoveAssociationOperation.findAssociation(tm,type,players); if(a != null) { a.remove(); } } } catch(TopicMapException tme) { throw new UndoException(tme); } } @Override public String getLabel() { return "add association"; } @Override public CreateAssociationOperation clone(){ HashMap<Locator,Locator> pclone=new HashMap<Locator,Locator>(); pclone.putAll(players); return new CreateAssociationOperation(tm,type,pclone,associationAlreadyExists); } }
7,347
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
RemoveTopicOperation.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/undowrapper/RemoveTopicOperation.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.topicmap.undowrapper; import java.util.Collection; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.memory.TopicMapImpl; /** * * @author olli */ public class RemoveTopicOperation extends UndoOperation { protected TopicMap tm; protected Locator si; protected TopicMap copytm; protected Topic copyt; public RemoveTopicOperation(Topic t) throws UndoException, TopicMapException { tm=t.getTopicMap(); copytm=new TopicMapImpl(); copyt=copytm.copyTopicIn(t, true); copytm.copyTopicAssociationsIn(t); si=copyt.getOneSubjectIdentifier(); if(si==null) throw new UndoException("Topic doesn't have a subject identifier"); } @Override public void undo() throws UndoException { try { Collection<Topic> merging=tm.getMergingTopics(copyt); if(!merging.isEmpty()) throw new UndoException(); tm.copyTopicIn(copyt, true); tm.copyTopicAssociationsIn(copyt); } catch(TopicMapException tme){ throw new UndoException(tme); } } @Override public void redo() throws UndoException { try{ Topic t=tm.getTopic(si); if(t==null) throw new UndoException(); t.remove(); } catch(TopicMapException tme) { throw new UndoException(tme); } } @Override public String getLabel() { return "remove topic"; } }
2,457
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
CreateTopicOperation.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/undowrapper/CreateTopicOperation.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.topicmap.undowrapper; import java.util.Collection; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.memory.TopicMapImpl; /** * * @author olli */ public class CreateTopicOperation extends UndoOperation { protected TopicMap tm; protected Locator si; protected TopicMap copytm; protected Topic copyt; public CreateTopicOperation(Topic t) throws TopicMapException, UndoException { tm=t.getTopicMap(); copytm=new TopicMapImpl(); copyt=copytm.copyTopicIn(t, true); si=copyt.getOneSubjectIdentifier(); if(si==null) throw new UndoException("Topic doesn't have a subject identifier"); } @Override public String getLabel() { return "create topic"; } @Override public void redo() throws UndoException { try { Collection<Topic> merging=tm.getMergingTopics(copyt); if(!merging.isEmpty()) throw new UndoException(); tm.copyTopicIn(copyt, true); } catch(TopicMapException tme) { throw new UndoException(tme); } } @Override public void undo() throws UndoException { try { Topic t=tm.getTopic(si); if(t==null) throw new UndoException(); t.remove(); } catch(TopicMapException tme) { throw new UndoException(tme); } } }
2,342
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
NoOperation.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/undowrapper/NoOperation.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.topicmap.undowrapper; /** * * @author olli */ public class NoOperation extends UndoOperation { public NoOperation(){} @Override public void undo() throws UndoException { } @Override public void redo() throws UndoException { } @Override public String getLabel() { return "no operation"; } }
1,178
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SetVariantOperation.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/undowrapper/SetVariantOperation.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.topicmap.undowrapper; import java.util.HashSet; import java.util.Set; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public class SetVariantOperation extends UndoOperation { protected TopicMap tm; protected Locator si; protected Set<Locator> scope; protected String oldValue; protected String newValue; public SetVariantOperation(Topic t,Set<Topic> scope,String value) throws TopicMapException, UndoException { this.tm=t.getTopicMap(); si=t.getOneSubjectIdentifier(); if(si==null) throw new UndoException("Topic has no subject identifier"); this.scope=new HashSet<Locator>(); for(Topic s : scope){ Locator ssi=s.getOneSubjectIdentifier(); if(ssi==null) throw new UndoException("Scope topic has no subject identifier"); this.scope.add(ssi); } oldValue=t.getVariant(scope); newValue=value; } @Override public String getLabel() { return "variant"; } @Override public void undo() throws UndoException { try{ Topic t=tm.getTopic(si); if(t==null) throw new UndoException(); HashSet<Topic> scope=new HashSet<Topic>(); for(Locator ssi : this.scope){ Topic st=tm.getTopic(ssi); if(st==null) throw new UndoException(); scope.add(st); } if(oldValue==null) t.removeVariant(scope); else t.setVariant(scope,oldValue); }catch(TopicMapException tme){throw new UndoException(tme);} } @Override public void redo() throws UndoException { try{ Topic t=tm.getTopic(si); if(t==null) throw new UndoException(); HashSet<Topic> scope=new HashSet<Topic>(); for(Locator ssi : this.scope){ Topic st=tm.getTopic(ssi); if(st==null) throw new UndoException(); scope.add(st); } if(newValue==null) t.removeVariant(scope); else t.setVariant(scope,newValue); } catch(TopicMapException tme){ throw new UndoException(tme); } } }
3,158
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SetBaseNameOperation.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/undowrapper/SetBaseNameOperation.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.topicmap.undowrapper; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public class SetBaseNameOperation extends UndoOperation { protected TopicMap tm; protected Locator si; protected String oldName; protected String newName; protected MergeOperation merge; public SetBaseNameOperation(Topic t,String newName) throws TopicMapException, UndoException { this.tm=t.getTopicMap(); si=t.getOneSubjectIdentifier(); if(si==null) throw new UndoException("Topic doesn't have a subject identifier"); oldName=t.getBaseName(); this.newName=newName; if(newName!=null){ Topic t2=t.getTopicMap().getTopicWithBaseName(newName); if(t2!=null && !t2.mergesWithTopic(t)){ merge=new MergeOperation(t, t2); } } } @Override public String getLabel() { return "base name"; } @Override public void undo() throws UndoException { try{ if(merge!=null) { merge.undo(); } else { Topic t=tm.getTopic(si); if(t==null) throw new UndoException(); if(oldName!=null){ Topic t2=tm.getTopicWithBaseName(oldName); if(t2!=null && !t2.mergesWithTopic(t)) throw new UndoException(); } t.setBaseName(oldName); } } catch(TopicMapException tme){ throw new UndoException(tme); } } @Override public void redo() throws UndoException { try { Topic t=tm.getTopic(si); if(t==null) throw new UndoException(); /* if(newName!=null){ Topic t2=tm.getTopicWithBaseName(newName); if(t2!=null) throw new UndoException(); } */ t.setBaseName(newName); } catch(TopicMapException tme) { throw new UndoException(tme); } } }
3,010
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MergeOperation.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/undowrapper/MergeOperation.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.topicmap.undowrapper; import java.util.ArrayList; import java.util.HashSet; import java.util.Hashtable; import java.util.Set; 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.memory.TopicMapImpl; /** * * @author olli */ public class MergeOperation extends UndoOperation{ protected TopicMap tm; protected TopicMap tmcopy; protected Locator si1; protected Locator si2; private HashSet<UndoOperation> dependencies; public MergeOperation(Topic t1, Topic t2) throws TopicMapException, UndoException { tm=t1.getTopicMap(); tmcopy=new TopicMapImpl(); si1=t1.getOneSubjectIdentifier(); si2=t2.getOneSubjectIdentifier(); // This is a HashSet to so that same RemoveAssociationOperations // don't get added twice. // RemoveAssociationOperation makes sure that two operations for same // association will have the same hashCode and match with equals. dependencies=new HashSet<UndoOperation>(); addDependencies(t1); addDependencies(t2); tmcopy.copyTopicIn(t1, true); tmcopy.copyTopicAssociationsIn(t1); tmcopy.copyTopicIn(t2, true); tmcopy.copyTopicAssociationsIn(t2); } private void addDependencies(Topic t) throws TopicMapException, UndoException { for(Topic s : t.getTopicsWithDataType()){ Hashtable<Topic,String> data=s.getData(t); for(Topic version : data.keySet()){ dependencies.add(new SetOccurrenceOperation(s, t, version, null)); } } for(Topic s : t.getTopicsWithDataVersion()){ for(Topic type : s.getDataTypes()) { String data=s.getData(type,t); if(data!=null) { dependencies.add(new SetOccurrenceOperation(s, type, t, null)); // SetOccurrenceOperation(Topic t,Topic type,Topic version,String value) } } } for(Topic s : t.getTopicsWithVariantScope()){ for(Set<Topic> scope : s.getVariantScopes()){ for(Topic st : scope){ if(st.mergesWithTopic(t)) { dependencies.add(new SetVariantOperation(s, scope, null)); break; } } } } for(Topic s : t.getTopicMap().getTopicsOfType(t)){ dependencies.add(new RemoveTypeOperation(s, t)); } for(Association a : t.getAssociationsWithType()){ dependencies.add(new RemoveAssociationOperation(a)); } for(Association a : t.getAssociationsWithRole()){ dependencies.add(new RemoveAssociationOperation(a)); } } private void deleteDependencies(Topic t) throws TopicMapException, UndoException { // make new ArrayLists to avoid concurrent modification for(Topic s : new ArrayList<Topic>(t.getTopicsWithDataType())){ s.removeData(t); } for(Topic s : new ArrayList<Topic>(t.getTopicsWithDataVersion())){ for(Topic type : new ArrayList<Topic>(s.getDataTypes())) { s.removeData(type, t); } } for(Topic s : new ArrayList<Topic>(t.getTopicsWithVariantScope())){ ScopeLoop: for(Set<Topic> scope : new ArrayList<Set<Topic>>(s.getVariantScopes())) { for(Topic st : scope){ if(st.mergesWithTopic(t)) { s.removeVariant(scope); } } } } for(Topic s : new ArrayList<Topic>(t.getTopicMap().getTopicsOfType(t))){ s.removeType(t); } for(Association a : new ArrayList<Association>(t.getAssociationsWithType())){ a.remove(); } for(Association a : new ArrayList<Association>(t.getAssociationsWithRole())){ a.remove(); } } @Override public String getLabel() { return "merge"; } @Override public void undo() throws UndoException { try{ Topic t=tm.getTopic(si1); if(t==null) throw new UndoException(); // this deletes all related things so that we can then remove the topic itself deleteDependencies(t); // remove the topic try { t.remove(); } catch(Exception e) { // This really shouldn't happen if the deleteDependencies worked, // if it does happen then something has gone wrong and it's better // to abort. throw new UndoException(e); // Instead of removing a topic we'll make it a stub containing only // a single subject identifier. //stubizeTopic(t); } // copy in the separate topics Topic t1=tmcopy.getTopic(si1); Topic t2=tmcopy.getTopic(si2); tm.copyTopicIn(t1, true); tm.copyTopicAssociationsIn(t1); tm.copyTopicIn(t2, true); tm.copyTopicAssociationsIn(t2); // this adds back all the related things in the correct separated topics for(UndoOperation uo : dependencies) { uo.undo(); } } catch(TopicMapException tme){ throw new UndoException(tme); } } @Override public void redo() throws UndoException { try { // the topic map itself will handle the merge completely Topic t1=tm.getTopic(si1); if(t1==null) throw new UndoException(); Topic t2=tm.getTopic(si2); if(t2==null) throw new UndoException(); t1.addSubjectIdentifier(si2); } catch(TopicMapException tme) { throw new UndoException(tme); } } /* * Remove all topic properties except one subject identifier. * * NOTE: * This doesn't work in its current form, causes ConcurrentModificationExceptions. * Should be possible to fix it by just making the data type loop iterate over * a copy of the returned list. But this whole method isn't needed at the moment. private void stubizeTopic(Topic t) { if(t == null) return; try { for(Association a : new ArrayList<Association>( t.getAssociations() )) { a.remove(); } for(Topic s : t.getDataTypes()) { t.removeData(s); } for(Set<Topic> s : new ArrayList<Set<Topic>>( t.getVariantScopes() )) { t.removeVariant(s); } for(Topic s : new ArrayList<Topic>( t.getTypes() )) { t.removeType(s); } for(Locator l : new ArrayList<Locator>( t.getSubjectIdentifiers() )) { if(!si1.equals(l)) { t.removeSubjectIdentifier(l); } } // System.out.println("SI: "+t.getOneSubjectIdentifier()); t.setBaseName(null); t.setSubjectLocator(null); } catch(Exception e) { e.printStackTrace(); } } */ }
8,438
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TestRunner.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/undowrapper/tests/TestRunner.java
package org.wandora.topicmap.undowrapper.tests; import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; import java.util.ArrayList; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public class TestRunner extends AbstractWandoraTool { private ArrayList<Test> tests; private Writer output; public TestRunner(){ this.tests=new ArrayList<Test>(); this.output=null; } public void addTest(Test test){ this.tests.add(test); } public void setOutput(Writer out){ this.output=out; } public void setupTests(int count){ for(int i=0;i<count;i++){ this.addTest(new RandomTest()); } } public void runTests(){ if(this.output==null) output=new PrintWriter(System.out); int passed=0; int failed=0; for(Test t : tests){ // while(true){ // Test t=new RandomTest(); try{ t.run(); if(!t.isPassed()){ failed++; this.output.write("FAILED "); } else { this.output.write("PASSED "); passed++; } // if(!t.isPassed()) { this.output.write(t.getLabel()+"\n"); t.getMessages(output); this.output.flush(); // break; // } // if((passed%100)==0) { this.output.write("PASSED "+passed+" tests\n"); this.output.flush(); } // if(!t.isPassed()) break; if(false) break; } catch(Exception e){ try{ this.output.write("FAILED "+t.getLabel()+"\n"); PrintWriter pwriter=new PrintWriter(this.output); e.printStackTrace(pwriter); pwriter.flush(); }catch(IOException ioe){ ioe.printStackTrace(); } } } try{ if(failed==0) this.output.write("PASSED ALL "+passed+" tests\n"); else { this.output.write("PASSED "+passed+" tests\nFAILED "+failed+" tests\n"); } this.output.flush(); }catch(IOException ioe){ ioe.printStackTrace(); } } @Override public String getName() { return "Undo/redo tests"; } @Override public String getDescription() { return "Runs some undo and redo test cases"; } @Override public void execute(Wandora wandora, Context context) throws TopicMapException { this.setupTests(200); this.runTests(); } public static void main(String args[]) throws Exception { TestRunner test=new TestRunner(); test.setupTests(200); test.runTests(); } }
3,188
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
RandomTest.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/undowrapper/tests/RandomTest.java
package org.wandora.topicmap.undowrapper.tests; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.Random; import java.util.Set; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.diff.BasicDiffOutput; import org.wandora.topicmap.diff.PatchDiffEntryFormatter; import org.wandora.topicmap.diff.TopicMapDiff; import org.wandora.topicmap.memory.TopicMapImpl; import org.wandora.topicmap.undowrapper.UndoException; import org.wandora.topicmap.undowrapper.UndoTopicMap; /** * * @author olli */ public class RandomTest implements Test { private long seed; private boolean passed=false; private String messages=null; private boolean checkRedo=true; private static long seedCounter=0; public RandomTest(){ this(System.currentTimeMillis()+(seedCounter++)); } public RandomTest(long seed) { this.seed=seed; } public TopicMap createRandomTopicMap(Random random,int numTopics) throws TopicMapException { TopicMap tm=new TopicMapImpl(); Topic[] topics=new Topic[numTopics]; for(int i=0;i<numTopics;i++){ Topic t=tm.createTopic(); t.addSubjectIdentifier(new Locator("http://wandora.org/si/test/"+i)); t.setBaseName(""+i); topics[i]=t; } for(int i=0;i<numTopics;i++){ int numAssociations=random.nextInt(numTopics); for(int j=0;j<numAssociations;j++){ HashMap<Topic,Topic> players=new HashMap<Topic,Topic>(); Topic role=topics[random.nextInt(topics.length)]; Topic player=topics[i]; players.put(role,player); int numRoles=random.nextInt(Math.min(5,numTopics/2)); for(int k=0;k<numRoles;k++){ role=null; while(role==null || players.containsKey(role)) role=topics[random.nextInt(topics.length)]; player=topics[random.nextInt(topics.length)]; players.put(role,player); } Topic type=topics[random.nextInt(topics.length)]; Association a=tm.createAssociation(type); a.addPlayers(players); } int numSubjectIdentifiers=random.nextInt(5); for(int j=0;j<numSubjectIdentifiers;j++){ topics[i].addSubjectIdentifier(new Locator("http://wandora.org/si/test/"+i+"/si"+random.nextInt(1000000))); } if(random.nextBoolean()){ topics[i].setSubjectLocator(new Locator("http://wandora.org/si/test/"+i+"/sl"+random.nextInt(1000000))); } int numOccurrences=random.nextInt(5); for(int j=0;j<numOccurrences;j++){ Topic type=topics[random.nextInt(topics.length)]; Topic version=topics[random.nextInt(topics.length)]; topics[i].setData(type, version, "occurrence "+i+"/"+j); } int numVariants=random.nextInt(5); for(int j=0;j<numVariants;j++){ int numScopeTopics=1+random.nextInt(Math.min(3,numTopics-1)); HashSet<Topic> scope=new HashSet<Topic>(); for(int k=0;k<numScopeTopics;k++){ Topic s=null; while(s==null || scope.contains(s)) s=topics[random.nextInt(topics.length)]; scope.add(s); } topics[i].setVariant(scope, "variant "+i+"/"+j); } int numTypes=random.nextInt(5); for(int j=0;j<numTypes;j++){ Topic t=topics[random.nextInt(topics.length)]; topics[i].addType(t); } } return tm; } /* * Many topic map methods return things in unpredictable random orders. * To be able to get same behavior always with the same random seed, * randomly picking things from the collections returned by the topic map * must be first sorted. Thus the different gerRandom* methods. */ public Association getRandomAssociation(TopicMap tm,Random random) throws TopicMapException { ArrayList<Association> as=new ArrayList<Association>(); Iterator<Association> iter=tm.getAssociations(); while(iter.hasNext()) as.add(iter.next()); TMBox.AssociationTypeComparator comp=new TMBox.AssociationTypeComparator(new TMBox.TopicBNAndSIComparator()); comp.setFullCompare(true); Collections.sort(as, comp); return getRandom(as,random); } public Topic getRandomTopic(TopicMap tm,Random random) throws TopicMapException { ArrayList<Topic> ts=new ArrayList<Topic>(); Iterator<Topic> iter=tm.getTopics(); while(iter.hasNext()) ts.add(iter.next()); Comparator<Topic> comp=new TMBox.TopicBNAndSIComparator(); Collections.sort(ts, comp); return getRandom(ts,random); } public Topic getRandomTopic(Collection<Topic> c,Random random){ ArrayList<Topic> ts=new ArrayList<Topic>(c); Comparator<Topic> comp=new TMBox.TopicBNAndSIComparator(); Collections.sort(ts, comp); return getRandom(ts,random); } public Locator getRandomLocator(Collection<Locator> c,Random random){ ArrayList<Locator> ts=new ArrayList<Locator>(c); Collections.sort(ts); return getRandom(ts,random); } public Set<Topic> getRandomScope(Collection<Set<Topic>> c, Random random){ ArrayList<Set<Topic>> ts=new ArrayList<Set<Topic>>(c); Comparator<Set<Topic>> comp=new TMBox.ScopeComparator(new TMBox.TopicBNAndSIComparator()); Collections.sort(ts, comp); return getRandom(ts,random); } /* * These two generic getRandom methods will only work predictably if the * collection or the iterator always have elements in the same order, * unlike what most topic map methods return. */ public <T> T getRandom(Collection<T> c,Random random){ return getRandom(c.iterator(),c.size(),random); } public <T> T getRandom(Iterator<T> iter,int count,Random random){ if(count==0) return null; int ind=random.nextInt(count); while(true){ T t=iter.next(); if(ind==0) return t; else ind--; } } public void performRandomOperation(TopicMap tm,Random random) throws TopicMapException { int r=random.nextInt(14); if(r==0){ // add subject identifier Topic t=getRandomTopic(tm,random); if(t==null) return; if(random.nextInt(10)<3){ // do intentional merge Topic t2=getRandomTopic(tm,random); Locator l=getRandomLocator(t2.getSubjectIdentifiers(),random); t.addSubjectIdentifier(l); } else { t.addSubjectIdentifier(new Locator("http://wandora.org/si/test/random/"+random.nextInt(1000000))); } } else if(r==1){ // add type Topic t=getRandomTopic(tm,random); Topic t2=getRandomTopic(tm,random); if(t==null || t2==null) return; t.addType(t2); } else if(r==2){ // create association if(tm.getNumTopics()<2) return; HashMap<Topic,Topic> players=new HashMap<Topic,Topic>(); int numRoles=1+random.nextInt(Math.min(5,tm.getNumTopics()/2)); for(int k=0;k<numRoles;k++){ Topic role=null; while(role==null || players.containsKey(role)) role=getRandomTopic(tm, random); Topic player=getRandomTopic(tm, random); players.put(role,player); } Topic type=getRandomTopic(tm, random); Association a=tm.createAssociation(type); a.addPlayers(players); } else if(r==3){ // create topic Topic t=tm.createTopic(); t.addSubjectIdentifier(new Locator("http://wandora.org/si/test/random/"+random.nextInt(1000000))); } else if(r==4){ // merge if(tm.getNumTopics()<2) return; Topic t=getRandomTopic(tm,random); Topic t2=getRandomTopic(tm,random); while(t2.mergesWithTopic(t)) t2=getRandomTopic(tm, random); t.addSubjectIdentifier(t2.getOneSubjectIdentifier()); } else if(r==5){ // modify association Association a=getRandomAssociation(tm, random); if(a==null) return; int r2=random.nextInt(3); if(r2==0){ // add player Topic role=getRandomTopic(tm, random); Topic player=getRandomTopic(tm, random); a.addPlayer(player, role); } else if(r2==1){ // remove player if(a.getRoles().size()<=1) return; Topic role=getRandomTopic(a.getRoles(),random); a.removePlayer(role); } else if(r2==2){ // set type Topic type=getRandomTopic(tm, random); a.setType(type); } } else if(r==6){ // remove association Association a=getRandomAssociation(tm, random); if(a==null) return; a.remove(); } else if(r==7){ // remove subject identifier Topic t=getRandomTopic(tm,random); if(t.getSubjectIdentifiers().size()>1) { t.removeSubjectIdentifier(getRandomLocator(t.getSubjectIdentifiers(),random)); } } else if(r==8){ // remove topic if(tm.getNumTopics()<2) return; Topic t=getRandomTopic(tm,random); if(!t.isDeleteAllowed()) return; t.remove(); } else if(r==9){ // remove type Topic t=getRandomTopic(tm,random); Topic type=getRandomTopic(t.getTypes(),random); if(type!=null) t.removeType(type); } else if(r==10){ // set base name Topic t=getRandomTopic(tm,random); if(random.nextInt(10)<3){ // do intentional merge Topic t2=getRandomTopic(tm,random); String bn=t2.getBaseName(); if(bn==null) return; t.setBaseName(bn); } else { t.setBaseName("random bn "+random.nextInt(1000000)); } } else if(r==11){ // set occurrence Topic t=getRandomTopic(tm,random); if(t.getDataTypes().isEmpty() || random.nextBoolean()) { Topic type=getRandomTopic(tm,random); Topic version=getRandomTopic(tm,random); t.setData(type, version, "random occurrence "+random.nextInt(1000000)); } else { Topic type=getRandomTopic(t.getDataTypes(),random); if(type==null) return; Hashtable<Topic,String> data=t.getData(type); Topic version=getRandomTopic(data.keySet(),random); t.removeData(type, version); } } else if(r==12){ // set subject locator Topic t=getRandomTopic(tm,random); if(t.getSubjectLocator()==null || random.nextBoolean()){ if(random.nextInt(10)<3) { Topic t2=getRandomTopic(tm,random); if(t2.getSubjectLocator()!=null) { t.setSubjectLocator(t2.getSubjectLocator()); return; } } t.setSubjectLocator(new Locator("http://wandora.org/si/test/random"+random.nextInt(1000000))); } else { t.setSubjectLocator(null); } } else if(r==13){ // set variant Topic t=getRandomTopic(tm,random); if(t.getVariantScopes().isEmpty() || random.nextBoolean()){ int numScopeTopics=1+random.nextInt(Math.min(3,tm.getNumTopics())); HashSet<Topic> scope=new HashSet<Topic>(); for(int k=0;k<numScopeTopics;k++){ Topic s=null; while(s==null || scope.contains(s)) s=getRandomTopic(tm, random); scope.add(s); } t.setVariant(scope, "random variant "+random.nextInt(1000000)); } else { Set<Topic> scope=getRandomScope(t.getVariantScopes(),random); t.removeVariant(scope); } } } @Override public String getLabel() { return "Random test "+this.seed; } private String makeDiff(TopicMap tm1,TopicMap tm2) throws TopicMapException { StringWriter sw=new StringWriter(); TopicMapDiff diff=new TopicMapDiff(); diff.makeDiff(tm1, tm2, new BasicDiffOutput(new PatchDiffEntryFormatter(),sw)); sw.flush(); String ret=sw.toString(); return ret; } private String stringifyException(Throwable t){ StringWriter sw=new StringWriter(); PrintWriter pw=new PrintWriter(sw); t.printStackTrace(pw); pw.flush(); return sw.toString(); } @Override public void run() throws TopicMapException { Random random=new Random(this.seed); UndoTopicMap tm=new UndoTopicMap(createRandomTopicMap(random,10+random.nextInt(10)), false); // String tmstring=makeDiff(new TopicMapImpl(),tm); // just for debugging TopicMap copy=new TopicMapImpl(); copy.mergeIn(tm); String diff=makeDiff(tm,copy); if(diff.length()>0) { passed=false; messages="Initial clone failed diff check\n"; messages+=diff; return; } int numPhases=1+random.nextInt(5); TopicMap[] copies=new TopicMap[numPhases+1]; copies[0]=copy; for(int i=0;i<numPhases;i++){ int numOperations=1+random.nextInt(20); for(int j=0;j<numOperations;j++) { performRandomOperation(tm, random); } tm.getUndoBuffer().addMarker("operation "+i); copies[i+1]=new TopicMapImpl(); copies[i+1].mergeIn(tm); diff=makeDiff(tm,copies[i+1]); if(diff.length()>0) { passed=false; messages="Copy "+i+" failed diff check\n"; messages+=diff; return; } } for(int i=numPhases-1;i>=0;i--){ try{ if(tm.getUndoBuffer().canUndo()) tm.getUndoBuffer().undo(); } catch(UndoException ue){ passed=false; messages="Undo exception at undo "+i+"\n"; messages+=stringifyException(ue); return; } diff=makeDiff(tm,copies[i]); if(diff.length()>0){ passed=false; messages="Undo diff "+i+" failed diff check\n"; messages+=diff; return; } } if(checkRedo){ for(int i=0;i<numPhases;i++){ try{ if(tm.getUndoBuffer().canRedo()) tm.getUndoBuffer().redo(); } catch(UndoException ue){ passed=false; messages="Undo exception at redo "+i+"\n"; messages+=stringifyException(ue); return; } diff=makeDiff(tm,copies[i+1]); if(diff.length()>0){ passed=false; messages="Redo diff "+i+" failed diff check\n"; messages+=diff; return; } } } passed=true; } @Override public boolean isPassed() { return passed; } @Override public void getMessages(Writer out) throws IOException { if(messages!=null && messages.length()>0) out.write(messages+"\n"); } }
17,123
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Test.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/undowrapper/tests/Test.java
package org.wandora.topicmap.undowrapper.tests; import java.io.IOException; import java.io.Writer; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public interface Test { public String getLabel(); public void run() throws TopicMapException; public boolean isPassed(); public void getMessages(Writer out) throws IOException; }
373
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DatabaseTopicMap.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/database/DatabaseTopicMap.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * DatabaseTopicMap.java * * Created on 7. marraskuuta 2005, 11:28 */ package org.wandora.topicmap.database; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.Vector; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicIterator; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicMapListener; import org.wandora.topicmap.TopicMapLogger; import org.wandora.topicmap.TopicMapReadOnlyException; import org.wandora.topicmap.TopicMapSearchOptions; import org.wandora.topicmap.TopicMapStatData; import org.wandora.topicmap.TopicMapStatOptions; import org.wandora.topicmap.TopicTools; import org.wandora.utils.sqlproxy.SQLProxyClient; /** * * @author olli * @deprecated */ public class DatabaseTopicMap extends TopicMap { protected boolean changed; /** The WeakTopicIndex used to index topics. Note that index needs information * about changes in topic map and should also be used to construct new * topics to make sure that there are not two different instances of the same topic. * @see WeakTopicIndex */ protected WeakTopicIndex topicIndex; protected ArrayList<TopicMapListener> topicMapListeners; protected ArrayList<TopicMapListener> disabledListeners; // connection info about current database protected String dbDriver; protected String dbConnectionString; protected String dbUser; protected String dbPassword; protected SQLProxyClient sqlProxy; /** * <p> * The database flavor. Some operations need to be handled differently * with different database vendors. This field is used to store what * kind of database is being used. Currently it may have following values * </p> * <pre> * "mysql" - MySQL database * "generic" - Any other database presumed to be sufficiently standard compliant * </pre> * <p> * It is set automatically based on the connection string used. * </p> */ protected String databaseFlavour; /** * Gets the used jdbc database driver class. */ public String getDBDriver(){return dbDriver;} /** * Gets the used jdbc database connection string. */ public String getDBConnectionString(){return dbConnectionString;} /** * Gets the used database user name. */ public String getDBUser(){return dbUser;} /** * Gets the used database password. */ public String getDBPassword(){return dbPassword;} protected Object connectionParams; /** A connection parameters object may be stored in the database topic map. * It is not used by the database topic map, only stored by it. Currently * this is used to store higher level connection information than the basic * driver, connection string, user name, password. This makes it possible * to modify the stored connection in Wandora. The connection parameters * object is set at the constructor. */ public Object getConnectionParams(){return connectionParams;} //protected boolean consistencyCheck=true; /** * <p> * A flag indicating that the <code>topicIndex</code> is a full index of * everything existing in this topic map. Normally it is not. However, when * you import something in an empty topic map, you can stop the index * cleaner thread that is normally deleting rarely used topics from * index. Because all created topics and associations are added to the index, this will * result in an index containing everything in the topic map. * </p><p> * The index is done with weak references so the actual objects might not * be found in the index but even if this is the case, the index will contain * the information if such an object exists in the actual database or not. * </p> */ protected boolean completeIndexes=false; protected boolean unconnected=false; /** * Note that this is different than topic map read only property. This property * tells the state of the connection: is the connection a read only connection * and does the user have privileges to modify the database. These can only * be changed by connecting to the database using different settings. */ protected boolean isDBReadOnly = false; protected Object indexLock=new Object(); // protected LinkedHashMap<Locator,Topic> siIndex; // protected LinkedHashMap<String,Topic> bnIndex; /** Creates a new instance of DatabaseTopicMap */ public DatabaseTopicMap(String dbDriver,String dbConnectionString, String dbUser, String dbPassword) throws SQLException { this(dbDriver,dbConnectionString,dbUser,dbPassword,null); } public DatabaseTopicMap(String dbDriver,String dbConnectionString, String dbUser, String dbPassword,Object connectionParams) throws SQLException { this(dbDriver,dbConnectionString,dbUser,dbPassword,null,connectionParams); } public DatabaseTopicMap(String dbDriver,String dbConnectionString, String dbUser, String dbPassword,String initScript) throws SQLException { this(dbDriver,dbConnectionString,dbUser,dbPassword,initScript,null); } public DatabaseTopicMap(String dbDriver,String dbConnectionString, String dbUser, String dbPassword,String initScript,Object connectionParams) throws SQLException { this.dbDriver=dbDriver; this.dbConnectionString=dbConnectionString; this.dbUser=dbUser; this.dbPassword=dbPassword; this.connectionParams=connectionParams; topicMapListeners=new ArrayList<TopicMapListener>(); if(dbConnectionString.startsWith("sqlproxy:")){ try{ sqlProxy=SQLProxyClient.createProxy(dbConnectionString,dbUser,dbPassword); databaseFlavour=sqlProxy.getFlavour(); }catch(Exception e){ e.printStackTrace(); } } else { if(dbConnectionString.startsWith("jdbc:mysql")) databaseFlavour="mysql"; else databaseFlavour="generic"; } if(sqlProxy==null){ try{ getConnection(); if(initScript!=null && initScript.trim().length()>0 && !unconnected){ Statement stmt=getConnection().createStatement(); stmt.execute(initScript); isDBReadOnly=testReadOnly(); // readOnly status may change because of init script } } catch(SQLException sqle){ sqle.printStackTrace(); unconnected=true; } } // siIndex=new LinkedHashMap<Locator,Topic>(); // bnIndex=new LinkedHashMap<String,Topic>(); topicIndex=new WeakTopicIndex(); changed=false; } String getDatabaseFlavour() { return databaseFlavour; } /** * Does the topic map only allow reading or both reading and writing. * Note that this is different than topic map read only property. This property * tells the state of the connection: is the connection a read only connection * and does the user have privileges to modify the database. These can only * be changed by connecting to the database using different settings. */ @Override public boolean isReadOnly() { return isDBReadOnly && isReadOnly; } /** * Tests if the connection allows modifying the topic map. The test is done * using an update sql statement that does not change anything in the database * but should raise an exception if modifying is not allowed. Note that this * only tests modifying the topic table and most database implementations * allow specifying different privileges for each tables. */ public boolean testReadOnly() { if(connection==null) return true; try{ Connection con=connection; Statement stmt=con.createStatement();; stmt.executeUpdate("UPDATE TOPIC set TOPICID='READONLYTEST' where TOPICID='READONLYTEST';"); stmt.close(); return false; }catch(SQLException sqle){ // sqle.printStackTrace(); return true; } } /** * Deletes everything in the topic map by clearing the database tables. */ @Override public void clearTopicMap() throws TopicMapException { if(isReadOnly()) throw new TopicMapReadOnlyException(); topicIndex.stopCleanerThread(); executeUpdate("delete from MEMBER"); executeUpdate("delete from ASSOCIATION"); executeUpdate("delete from VARIANTSCOPE"); executeUpdate("delete from VARIANT"); executeUpdate("delete from DATA"); executeUpdate("delete from TOPICTYPE"); executeUpdate("delete from SUBJECTIDENTIFIER"); executeUpdate("delete from TOPIC"); topicIndex=new WeakTopicIndex(); changed=true; } /** * Clears the topic index (cache) containing recently accessed database topics. * Any topic found in the index is not retrieved from the database and it is * impossible for DatabaseTopicMap to detect any changes in the database. Thus * the index may contain outdated information and you will need to manually * clear the index to force retrieving of topics directly from the database. */ @Override public void clearTopicMapIndexes() { topicIndex.stopCleanerThread(); topicIndex = new WeakTopicIndex(); } /** * Checks if the database connection is active. */ @Override public boolean isConnected(){ return !unconnected; } public void printIndexDebugInfo(){ topicIndex.printDebugInfo(); } /* * Method checks if database topic map contains topics without subject * identifiers and inserts default SI to each such topic. * * These unindentified topics occur rarely if a tool or import fails for * example. As unidentified topics cause serious problems if used in * Wandora application user should have a back door to make database * topic map consistent. */ public void checkSIConsistency() throws TopicMapException { checkSIConsistency(getLogger()); } public void checkSIConsistency(TopicMapLogger logger) throws TopicMapException { if(unconnected) return; if(isReadOnly()) throw new TopicMapReadOnlyException(); logger.log("Finding topic's without SIs!"); String query = "select TOPICID from TOPIC left join SUBJECTIDENTIFIER on SUBJECTIDENTIFIER.TOPIC=TOPIC.TOPICID where SI is NULL"; Collection<Map<String,Object>> res=executeQuery(query); String topicID = null; String defaultSI = null; logger.log("Found total "+res.size()+" topics without SIs!"); for(Map<String,Object> row : res) { topicID=row.get("TOPICID").toString(); defaultSI=TopicTools.createDefaultLocator().toExternalForm(); logger.log("Inserting SI '"+defaultSI+" to topic with id '"+topicID+"'."); if(topicID != null && defaultSI != null) { executeUpdate("insert into SUBJECTIDENTIFIER (TOPIC, SI) values ('"+escapeSQL(topicID)+"', '"+escapeSQL(defaultSI)+"')"); } } } @Override public void checkAssociationConsistency(TopicMapLogger logger) throws TopicMapException { if(unconnected) return; if(isReadOnly()) throw new TopicMapReadOnlyException(); // if(true) return; // consistency disabled if(logger != null) logger.log("Checking association consistency!"); int counter=0; int deleted=0; Collection<Map<String,Object>> res=executeQuery("select distinct PLAYER from MEMBER"); for(Map<String,Object> row : res){ String player=row.get("PLAYER").toString(); HashSet<Vector<String>> associations=new LinkedHashSet<Vector<String>>(500); Collection<Map<String,Object>> res2=executeQuery( "select ASSOCIATION.*,M2.* from ASSOCIATION,MEMBER as M1, MEMBER as M2 "+ "where M1.PLAYER='"+escapeSQL(player)+"' and M1.ASSOCIATION=ASSOCIATIONID and "+ "M2.ASSOCIATION=ASSOCIATION.ASSOCIATIONID order by ASSOCIATION.ASSOCIATIONID,M2.ROLE" ); String associationid=""; Vector<String> v=new Vector<String>(9); for(Map<String,Object> row2 : res2){ String id=row2.get("ASSOCIATIONID").toString(); if(!associationid.equals(id)){ if(!associationid.equals("")){ if(!associations.add(v)){ logger.hlog("Deleting association with id "+associationid); executeUpdate("delete from MEMBER where ASSOCIATION='"+escapeSQL(associationid)+"'"); executeUpdate("delete from ASSOCIATION where ASSOCIATIONID='"+escapeSQL(associationid)+"'"); deleted++; } v=new Vector<String>(9); String type=row2.get("TYPE").toString(); v.add(type); } associationid=id; } String r=row2.get("ROLE").toString(); String p=row2.get("PLAYER").toString(); v.add(r); v.add(p); } if(!associations.add(v)){ logger.hlog("Deleting association with id "+associationid); executeUpdate("delete from MEMBER where ASSOCIATION='"+escapeSQL(associationid)+"'"); executeUpdate("delete from ASSOCIATION where ASSOCIATIONID='"+escapeSQL(associationid)+"'"); deleted++; } counter++; // System.out.println("Counter "+counter); } if(logger != null) logger.log("Association consistency deleted "+deleted+" associations!"); } /** * Closes the topic map. This closes the topic index freeing some resources * and closes the database connection. Topic map cannot be used or reopened * after it has been closed. */ @Override public void close(){ topicIndex.destroy(); if(sqlProxy!=null){ try{ sqlProxy.close(); }catch(java.io.IOException ioe){ioe.printStackTrace();} } else if(connection!=null){ try{ connection.close(); }catch(SQLException sqle){sqle.printStackTrace();} } } // the default stored connection protected Connection connection=null; /** * Gets the connection used with database queries. If the old stored connection * has been closed for any reason, tries to create a new connection. */ public Connection getConnection(){ if(sqlProxy!=null) { return null; } synchronized(queryLock){ if(unconnected) { return null; } if(connection==null) { connection=createConnection(true); isDBReadOnly=testReadOnly(); } if(connection==null) { unconnected=true; return null;} try { if(connection.isClosed()) { System.out.println("SQL connection closed. Opening new connection!"); connection=createConnection(true); isDBReadOnly=testReadOnly(); } } catch (SQLException sqle) { System.out.println("SQL exception occurred while acquiring connection:"); sqle.printStackTrace(); System.out.println("Trying to open new connection!"); connection=createConnection(true); isDBReadOnly=testReadOnly(); } return connection; } } /** * Creates a new database connection using the connection parameters given * to the constructor. */ public Connection createConnection(boolean autocommit) { if(sqlProxy!=null) return null; try { Class.forName(dbDriver); Connection con = DriverManager.getConnection(dbConnectionString,dbUser,dbPassword); if(autocommit) { con.setAutoCommit(true); } else { con.setAutoCommit(false); } // System.out.println("Database connection created"); return con; } catch(Exception e){ System.out.println("Database connection failed with"); System.out.println("Driver: " + dbDriver); System.out.println("Connection string: " + dbConnectionString); System.out.println("User: " + dbUser); System.out.println("Password: " + dbPassword); e.printStackTrace(); return null; } } private int queryCounter=1; /** * Turns a collection of strings into sql syntax representing a collection of strings * that can be used with 'in' clauses. The returned string contains each string * in the collection escaped inside single quotes, each separated by commas * and all contain inside parenthesis. For example: ('string1','string2','string3'). */ public String collectionToSQL(Collection<String> col){ StringBuilder sb=new StringBuilder("("); for(String s : col){ if(sb.length()>1) sb.append(","); sb.append("'").append(escapeSQL(s)).append("'"); } sb.append(")"); return sb.toString(); } // ------------------------------------------------------- EXECUTE QUERY --- // A stored statement that can be reused instead of always creating new statement objects // private Statement storedStatement=null; private final Object queryLock = new Object(); public boolean executeUpdate(String query) throws TopicMapException{ return executeUpdate(query, getConnection()); } public boolean executeUpdate(String query, Connection con) throws TopicMapException { synchronized(queryLock) { queryCounter++; // /*if((queryCounter%10)==0)*/ System.out.println("DBG execute update "+queryCounter+" "+query); if(sqlProxy!=null) { try{ sqlProxy.executeUpdate(query); return true; } catch(Exception e) { e.printStackTrace(); throw new TopicMapSQLException(e); } } Statement stmt = null; try { stmt = con.createStatement(); System.out.println(query); stmt.executeUpdate(query); stmt.close(); return true; } catch(SQLException sqle) { if(stmt != null) { try { stmt.close(); con.close(); } catch(Exception e) { e.printStackTrace(); } } sqle.printStackTrace(); throw new TopicMapSQLException(sqle); } } } /** * Executes a database query and returns the results as a collection. Each * element in the collection is a Map and represents a row of the result. * The Map maps column names to the objects returned by query. */ public Collection<Map<String,Object>> executeQuery(String query) throws TopicMapException { return executeQuery(query, getConnection()); } public Collection<Map<String,Object>> executeQuery(String query, Connection con) throws TopicMapException { synchronized(queryLock) { try{ queryCounter++; if(sqlProxy!=null) { try { return sqlProxy.executeQuery(query); } catch(Exception e) { e.printStackTrace(); throw new TopicMapSQLException(e); } } // /*if((queryCounter%10)==0)*/ System.out.println("DBG execute query "+queryCounter+" "+query); Statement stmt=con.createStatement(); ResultSet rs=stmt.executeQuery(query); ResultSetMetaData metaData=rs.getMetaData(); int columns=metaData.getColumnCount(); String[] columnNames=new String[columns]; for(int i=0;i<columns;i++) { columnNames[i]=metaData.getColumnName(i+1); } ArrayList<Map<String,Object>> rows=new ArrayList<Map<String,Object>>(); while(rs.next()) { Map<String,Object> row=new LinkedHashMap<String,Object>(); for(int i=0;i<columns;i++) { row.put(columnNames[i],rs.getObject(i+1)); } rows.add(row); } rs.close(); stmt.close(); return rows; } catch(SQLException sqle) { sqle.printStackTrace(); throw new TopicMapSQLException(sqle); } } } // --------------------------------------------------------- BUILD TOPIC --- /** * Builds a database topic from a database query result row. The row should contain * (at least) three columns with names "TOPICID", "BASENAME" and "SUBJECTLOCATOR" * that are used to build the topic. */ public DatabaseTopic buildTopic(Map<String,Object> row) throws TopicMapException { return buildTopic(row.get("TOPICID"),row.get("BASENAME"),row.get("SUBJECTLOCATOR")); } /** * Builds a database topic when given the topic id, basename and subject locator. */ public DatabaseTopic buildTopic(Object id, Object baseName, Object subjectLocator) throws TopicMapException { return buildTopic((String) id, (String) baseName, (String) subjectLocator); } /** * Builds a database topic when given the topic id, basename and subject locator. */ public DatabaseTopic buildTopic(String id, String baseName, String subjectLocator) throws TopicMapException { DatabaseTopic dbt=topicIndex.getTopicWithID(id); if(dbt==null) { dbt=topicIndex.createTopic(id, this); dbt.initialize(baseName, subjectLocator); } return dbt; } // --------------------------------------------------- BUILD ASSOCIATION --- /** * Builds a database association from a database query result row. The row should contain * (at least) four columns with names "ASSOCIATIONID", "TOPICID", "BASENAME" and "SUBJECTLOCATOR" * where all but the "ASSOCIATIONID" are the core properties of the association type topic. */ public DatabaseAssociation buildAssociation(Map<String,Object> row) throws TopicMapException { return buildAssociation(row.get("ASSOCIATIONID"),row.get("TOPICID"),row.get("BASENAME"),row.get("SUBJECTLOCATOR")); } public DatabaseAssociation buildAssociation(Object associationId,Object typeId,Object typeName,Object typeSL) throws TopicMapException { return buildAssociation((String)associationId,(String)typeId,(String)typeName,(String)typeSL); } public DatabaseAssociation buildAssociation(String associationId,String typeId,String typeName,String typeSL) throws TopicMapException { DatabaseAssociation dba=topicIndex.getAssociation(associationId,this); if(dba!=null) return dba; DatabaseTopic type=buildTopic(typeId,typeName,typeSL); return buildAssociation(associationId,type); } public DatabaseAssociation buildAssociation(String associationId,DatabaseTopic type){ DatabaseAssociation dba=topicIndex.getAssociation(associationId,this); if(dba==null){ dba=topicIndex.createAssociation(associationId,this); dba.initialize(type); } return dba; } // --------------------------------------------------------- QUERY TOPIC --- /** * Executes a database query and returns results as a collection of topics. * The result set must have the same columns used by buildTopic method. */ public Collection<Topic> queryTopic(String query) throws TopicMapException { return queryTopic(query,getConnection()); } public Collection<Topic> queryTopic(String query,Connection con) throws TopicMapException { Collection<Map<String,Object>> res=executeQuery(query,con); Collection<Topic> ret=new ArrayList<Topic>(); for(Map<String,Object> row : res){ ret.add(buildTopic(row)); } return ret; } /** * Same as queryTopic but only returns the first topic in the result set or * null if the result set is empty. */ public Topic querySingleTopic(String query) throws TopicMapException { Collection<Topic> c=queryTopic(query); if(c.isEmpty()) return null; else return c.iterator().next(); } /** * Executes a database query and returns results as a collection of associations. * The result set must have the same columns used by buildAssociation method. */ public Collection<Association> queryAssociation(String query) throws TopicMapException { return queryAssociation(query,getConnection()); } public Collection<Association> queryAssociation(String query,Connection con) throws TopicMapException { Collection<Map<String,Object>> res=executeQuery(query,con); Vector<Association> ret=new Vector<Association>(); for(Map<String,Object>row : res){ ret.add(buildAssociation(row)); } return ret; } /** * Escapes a string so that it can be used in an sql query. */ public String escapeSQL(String s){ s=s.replace("'","''"); if(databaseFlavour.equals("mysql")) s=s.replace("\\","\\\\"); return s; } public Topic getTopic(Collection<Locator> SIs) throws TopicMapException { for(Locator l : SIs){ Topic t=getTopic(l); if(t!=null) return t; } return null; } /* protected void clearSiQueue(){ synchronized(indexLock){ long t=System.currentTimeMillis()-10000; while(!siQueue.isEmpty()){ T2<Long,Locator> first=siQueue.getFirst(); if(first.e1<t){ siIndex.remove(first.e2); siQueue.removeFirst(); } else break; } } } protected void clearBnQueue(){ synchronized(indexLock){ long t=System.currentTimeMillis()-10000; while(!bnQueue.isEmpty()){ T2<Long,String> first=bnQueue.getFirst(); if(first.e1<t){ bnIndex.remove(first.e2); bnQueue.removeFirst(); } else break; } } }*/ /* protected void resetIndexes(){ synchronized(indexLock){ if(!siIndex.isEmpty()){ siIndex=new LinkedHashMap<Locator,Topic>(); } if(!bnIndex.isEmpty()){ bnIndex=new LinkedHashMap<String,Topic>(); } } }*/ /* void addTopicToSIIndex(Topic t){ synchronized(indexLock){ long time=System.currentTimeMillis(); for(Locator l : t.getSubjectIdentifiers()){ siIndex.put(l,t); } } } void addTopicToBNIndex(Topic t){ synchronized(indexLock){ long time=System.currentTimeMillis(); String bn=t.getBaseName(); if(bn==null || bn.length()==0) return;; bnIndex.put(bn,t); } }*/ public void topicSIChanged(DatabaseTopic t,Locator deleted,Locator added){ topicIndex.topicSIChanged(t,deleted,added); } public void topicBNChanged(Topic t,String old) throws TopicMapException { topicIndex.topicBNChanged(t,old); } @Override public Topic getTopic(Locator si) throws TopicMapException { if(unconnected) return null; if(topicIndex.containsKeyWithSI(si)) { Topic t=topicIndex.getTopicWithSI(si); // may return null if, A) has mapping that no topic with si exists or // B) there is a mapping but the weak referenc has been cleared if(t!=null) return t; // clear case, return else if(topicIndex.isNullSI(si)) { // if no topic exists, return null, otherwise refetch the topic return null; } } else if(completeIndexes) return null; // index is complete so if nothing is mentioned then there is no such topic Topic t=querySingleTopic("select TOPIC.* " + "from TOPIC,SUBJECTIDENTIFIER " + "where TOPIC=TOPICID " + "and SI='"+escapeSQL(si.toExternalForm())+"'"); if(t==null) { topicIndex.addNullSI(si); } return t; } @Override public Topic getTopicBySubjectLocator(Locator sl) throws TopicMapException { if(unconnected) return null; return querySingleTopic("select * from TOPIC " +"where SUBJECTLOCATOR='" +escapeSQL(sl.toExternalForm())+"'"); } @Override public Topic createTopic(String id) throws TopicMapException { if(unconnected) return null; if(isReadOnly()) throw new TopicMapReadOnlyException(); DatabaseTopic t=topicIndex.newTopic(id, this); return t; } @Override public Topic createTopic() throws TopicMapException { if(unconnected) return null; if(isReadOnly()) throw new TopicMapReadOnlyException(); DatabaseTopic t=topicIndex.newTopic(this); return t; } @Override public Association createAssociation(Topic type) throws TopicMapException { if(unconnected) return null; if(isReadOnly()) throw new TopicMapReadOnlyException(); DatabaseAssociation a=topicIndex.newAssociation((DatabaseTopic)type,this); return a; } @Override public Collection<Topic> getTopicsOfType(Topic type) throws TopicMapException { if(unconnected) return new ArrayList<Topic>(); Collection<Topic> res=queryTopic("select TOPIC.* " +"from TOPIC,TOPICTYPE " +"where TOPIC=TOPICID " +"and TYPE='"+escapeSQL(type.getID())+"'"); Map<String,DatabaseTopic> collected=new LinkedHashMap<String,DatabaseTopic>(); for(Topic t : res){ collected.put(t.getID(),(DatabaseTopic)t); } DatabaseTopic.fetchAllSubjectIdentifiers( executeQuery("select SUBJECTIDENTIFIER.* " +"from SUBJECTIDENTIFIER,TOPIC,TOPICTYPE " +"where SUBJECTIDENTIFIER.TOPIC=TOPIC.TOPICID " +"and TOPIC.TOPICID=TOPICTYPE.TOPIC " +"and TOPICTYPE.TYPE='"+escapeSQL(type.getID())+"' " +"order by SUBJECTIDENTIFIER.TOPIC"), collected, this); return res; } @Override public Topic getTopicWithBaseName(String name) throws TopicMapException { if(unconnected) return null; if(topicIndex.containsKeyWithBN(name)) { // see notes in getTopic(Locator) Topic t=topicIndex.getTopicWithBN(name); if(t!=null) return t; else if(topicIndex.isNullBN(name)) return null; } else if(completeIndexes) return null; Topic t=querySingleTopic("select * from TOPIC where BASENAME='"+escapeSQL(name)+"'"); if(t==null) topicIndex.addNullBN(name); return t; } @Override public Iterator<Topic> getTopics() { if(unconnected) { return new TopicIterator(){ @Override public boolean hasNext(){return false;} @Override public Topic next(){throw new NoSuchElementException();} @Override public void remove(){throw new UnsupportedOperationException();} @Override public void dispose(){} }; } try { if(sqlProxy!=null) { throw new UnsupportedOperationException(); } final Connection con=createConnection(true); final Statement stmt=con.createStatement(ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY); if(databaseFlavour.equals("mysql")) { // A signal to mysql not to fetch all rows but stream them instead http://dev.mysql.com/doc/connector/j/en/cj-implementation-notes.html stmt.setFetchSize(Integer.MIN_VALUE); } final ResultSet rs=stmt.executeQuery("select * from TOPIC"); ResultSetMetaData metaData=rs.getMetaData(); final int columns=metaData.getColumnCount(); final String[] columnNames=new String[columns]; for(int i=0;i<columns;i++){ columnNames[i]=metaData.getColumnName(i+1); } // NOTE: You must iterate through all rows because statement and result set // will only be closed after last row has been fetched. Or alternatively // call dispose when you're done with the iterator. return new TopicIterator() { boolean calledNext=false; boolean hasNext=false; boolean end=false; boolean disposed=false; @Override public void dispose() { if(disposed) return; disposed=true; end=true; try { rs.close(); stmt.close(); con.close(); } catch(SQLException sqle) { sqle.printStackTrace(); } } @Override public boolean hasNext() { if(end) return false; if(calledNext) return hasNext; else { try { hasNext=rs.next(); calledNext=true; if(hasNext==false){ dispose(); } return hasNext; } catch(SQLException sqle) { sqle.printStackTrace(); return false; } } } @Override public Topic next() { if(!hasNext()) { throw new NoSuchElementException(); } Map<String,Object> row=new LinkedHashMap<String,Object>(); try { for(int i=0;i<columns;i++) { row.put(columnNames[i],rs.getObject(i+1)); } } catch(SQLException sqle) { sqle.printStackTrace(); return null; } calledNext=false; try { return buildTopic(row); } catch(TopicMapException tme) { tme.printStackTrace(); // TODO EXCEPTION return null; } } @Override public void remove() { throw new UnsupportedOperationException(); } }; } catch(SQLException sqle){ sqle.printStackTrace(); return null; } } @Override public Topic[] getTopics(String[] sis) throws TopicMapException { if(unconnected) { return new Topic[0]; } Topic[] ret=new Topic[sis.length]; for(int i=0;i<sis.length;i++){ ret[i]=getTopic(sis[i]); } return ret; } /** * Note that you must iterate through all rows because statement and result set * will only be closed after last row has been fetched. */ @Override public Iterator<Association> getAssociations(){ if(unconnected) { return new Iterator<Association>(){ @Override public boolean hasNext(){ return false; } @Override public Association next(){ throw new NoSuchElementException(); } @Override public void remove(){ throw new UnsupportedOperationException(); } }; } try{ if(sqlProxy!=null) throw new UnsupportedOperationException(); final Connection con=createConnection(true); final Statement stmt=con.createStatement(ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY); if(databaseFlavour.equals("mysql")) stmt.setFetchSize(Integer.MIN_VALUE); final ResultSet rs=stmt.executeQuery("select * from ASSOCIATION,TOPIC where TOPICID=TYPE"); ResultSetMetaData metaData=rs.getMetaData(); final int columns=metaData.getColumnCount(); final String[] columnNames=new String[columns]; for(int i=0;i<columns;i++){ columnNames[i]=metaData.getColumnName(i+1); } return new Iterator<Association>(){ boolean calledNext=false; boolean hasNext=false; boolean end=false; @Override public boolean hasNext(){ if(end) return false; if(calledNext) return hasNext; else { try{ hasNext=rs.next(); calledNext=true; if(hasNext==false){ rs.close(); stmt.close(); con.close(); end=true; } return hasNext; }catch(SQLException sqle){sqle.printStackTrace();return false;} } } @Override public Association next(){ if(!hasNext()) throw new NoSuchElementException(); HashMap<String,Object> row=new LinkedHashMap<String,Object>(); try{ for(int i=0;i<columns;i++){ row.put(columnNames[i],rs.getObject(i+1)); } }catch(SQLException sqle){sqle.printStackTrace();return null;} calledNext=false; try{ return buildAssociation(row); }catch(TopicMapException tme){ tme.printStackTrace(); // TODO EXCEPTION return null; } } @Override public void remove(){ throw new UnsupportedOperationException(); } }; } catch(SQLException sqle){ sqle.printStackTrace(); return null; } } @Override public Collection<Association> getAssociationsOfType(Topic type) throws TopicMapException { if(unconnected) return new Vector<Association>(); return queryAssociation("select * " + "from ASSOCIATION,TOPIC " + "where TYPE=TOPICID " + "and TOPICID='"+escapeSQL(type.getID())+"'"); } @Override public int getNumTopics(){ if(unconnected) return 0; if(sqlProxy!=null){ try{ Collection<Map<String,Object>> res=sqlProxy.executeQuery("select count(*) from TOPIC"); Map<String,Object> row=res.iterator().next(); return ((Number)row.get(row.keySet().iterator().next())).intValue(); } catch(Exception e){ e.printStackTrace(); return 0; } } try{ Connection con=getConnection(); Statement stmt=con.createStatement(); ResultSet rs=stmt.executeQuery("select count(*) from TOPIC"); rs.next(); int count=rs.getInt(1); rs.close(); stmt.close(); return count; } catch(SQLException sqle){ sqle.printStackTrace(); return 0; } } @Override public int getNumAssociations() { if(unconnected) return 0; if(sqlProxy!=null) { try { Collection<Map<String,Object>> res=sqlProxy.executeQuery("select count(*) from ASSOCIATION"); Map<String,Object> row=res.iterator().next(); return ((Number)row.get(row.keySet().iterator().next())).intValue(); } catch(Exception e) { e.printStackTrace(); return 0; } } try { Connection con=getConnection(); Statement stmt=con.createStatement(); ResultSet rs=stmt.executeQuery("select count(*) from ASSOCIATION"); rs.next(); int count=rs.getInt(1); rs.close(); stmt.close(); return count; } catch(SQLException sqle) { sqle.printStackTrace(); return 0; } } // ---------------------------------------- COPY TOPICIN / ASSOCIATIONIN --- private Topic _copyTopicIn(Topic t,boolean deep,Hashtable copied) throws TopicMapException { return _copyTopicIn(t,deep,false,copied); } private Topic _copyTopicIn(Topic t,boolean deep,boolean stub,Hashtable<Topic,Locator> copied) throws TopicMapException { if(copied.containsKey(t)) { // Don't return the topic that was created when t was copied because it might have been merged with something // since then. Instead get the topic with one of the subject identifiers of the topic. Locator l=(Locator)copied.get(t); return getTopic(l); } // first check if the topic would be merged, if so, edit the equal topic directly instead of creating new // and letting them merge later Topic nt=getTopic(t.getSubjectIdentifiers()); if(nt==null && t.getBaseName()!=null) nt=getTopicWithBaseName(t.getBaseName()); if(nt==null && t.getSubjectLocator()!=null) nt=getTopicBySubjectLocator(t.getSubjectLocator()); if(nt==null) { nt=createTopic(); } for(Locator l : t.getSubjectIdentifiers()){ nt.addSubjectIdentifier(l); } if(nt.getSubjectIdentifiers().isEmpty()) { System.out.println("Warning no subject indicators in topic. Creating default SI."); long randomNumber = System.currentTimeMillis() + Math.round(Math.random() * 99999); nt.addSubjectIdentifier(new Locator("http://wandora.org/si/temp/" + randomNumber)); } copied.put(t,(Locator)nt.getSubjectIdentifiers().iterator().next()); if(nt.getSubjectLocator()==null && t.getSubjectLocator()!=null){ nt.setSubjectLocator(t.getSubjectLocator()); // TODO: raise error if different? } if(nt.getBaseName()==null && t.getBaseName()!=null){ nt.setBaseName(t.getBaseName()); } if( (!stub) || deep) { for(Topic type : t.getTypes()){ Topic ntype=_copyTopicIn(type,deep,true,copied); nt.addType(ntype); } for(Set<Topic> scope : t.getVariantScopes()) { Set<Topic> nscope=new LinkedHashSet(); for(Topic st : scope){ Topic nst=_copyTopicIn(st,deep,true,copied); nscope.add(nst); } nt.setVariant(nscope, t.getVariant(scope)); } for(Topic type : t.getDataTypes()) { Topic ntype=_copyTopicIn(type,deep,true,copied); Hashtable<Topic,String> versiondata=t.getData(type); for(Map.Entry<Topic,String> e : versiondata.entrySet()){ Topic version=e.getKey(); String data=e.getValue(); Topic nversion=_copyTopicIn(version,deep,true,copied); nt.setData(ntype,nversion,data); } } } return nt; } private Association _copyAssociationIn(Association a) throws TopicMapException { Topic type=a.getType(); Topic ntype=null; if(type.getSubjectIdentifiers().isEmpty()) { System.out.println("Warning, topic has no subject identifiers."); } else { ntype=getTopic((Locator)type.getSubjectIdentifiers().iterator().next()); } if(ntype==null) ntype=copyTopicIn(type,false); Association na=createAssociation(ntype); for(Topic role : a.getRoles()) { Topic nrole = null; if(role.getSubjectIdentifiers().isEmpty()) { System.out.println("Warning, topic has no subject identifiers. Creating default SI!"); //role.addSubjectIdentifier(new Locator("http://wandora.org/si/temp/" + System.currentTimeMillis())); } else { nrole=getTopic((Locator)role.getSubjectIdentifiers().iterator().next()); } if(nrole==null) nrole=copyTopicIn(role,false); Topic player=a.getPlayer(role); Topic nplayer = null; if(player.getSubjectIdentifiers().isEmpty()) { System.out.println("Warning, topic has no subject identifiers. Creating default SI!"); //player.addSubjectIdentifier(new Locator("http://wandora.org/si/temp/" + System.currentTimeMillis())); } else { nplayer=getTopic((Locator)player.getSubjectIdentifiers().iterator().next()); } if(nplayer==null) nplayer=copyTopicIn(player,false); na.addPlayer(nplayer,nrole); } return na; } @Override public Association copyAssociationIn(Association a) throws TopicMapException { if(unconnected) return null; if(isReadOnly()) throw new TopicMapReadOnlyException(); Association n=_copyAssociationIn(a); Topic minTopic=null; int minCount=Integer.MAX_VALUE; for(Topic role : n.getRoles()) { Topic t=n.getPlayer(role); if(t.getAssociations().size()<minCount){ minCount=t.getAssociations().size(); minTopic=t; } } ((DatabaseTopic)minTopic).removeDuplicateAssociations(); return n; } @Override public Topic copyTopicIn(Topic t, boolean deep) throws TopicMapException { if(unconnected) return null; if(isReadOnly()) throw new TopicMapReadOnlyException(); return _copyTopicIn(t,deep,false,new Hashtable()); } @Override public void copyTopicAssociationsIn(Topic t) throws TopicMapException { if(unconnected) return; if(isReadOnly()) throw new TopicMapReadOnlyException(); Topic nt=getTopic((Locator)t.getSubjectIdentifiers().iterator().next()); if(nt==null) nt=copyTopicIn(t,false); for(Association a : t.getAssociations()) { _copyAssociationIn(a); } ((DatabaseTopic)nt).removeDuplicateAssociations(); } // ------------------------------------------------------ IMPORT / MERGE --- @Override public void importXTM(java.io.InputStream in, TopicMapLogger logger) throws java.io.IOException,TopicMapException { if(unconnected) return; if(isReadOnly()) throw new TopicMapReadOnlyException(); int numTopics=getNumTopics(); if(numTopics==0) { System.out.println("Merging to empty topic map"); topicIndex.stopCleanerThread(); completeIndexes=topicIndex.isFullIndex(); } else System.out.println("Merging to non-empty topic map (numTopcis="+numTopics+")"); boolean old=getConsistencyCheck(); setConsistencyCheck(false); boolean check=!getConsistencyCheck(); super.importXTM(in, logger); topicIndex.clearTopicCache(); topicIndex.startCleanerThread(); completeIndexes=false; if(check && old) checkAssociationConsistency(); setConsistencyCheck(old); } @Override public void importLTM(java.io.InputStream in, TopicMapLogger logger) throws java.io.IOException,TopicMapException { if(unconnected) return; if(isReadOnly()) throw new TopicMapReadOnlyException(); int numTopics=getNumTopics(); if(numTopics==0) { System.out.println("Merging to empty topic map"); topicIndex.stopCleanerThread(); completeIndexes=topicIndex.isFullIndex(); } else System.out.println("Merging to non-empty topic map (numTopcis="+numTopics+")"); boolean old=getConsistencyCheck(); setConsistencyCheck(false); boolean check=!getConsistencyCheck(); super.importLTM(in, logger); topicIndex.clearTopicCache(); topicIndex.startCleanerThread(); completeIndexes=false; if(check && old) checkAssociationConsistency(); setConsistencyCheck(old); } @Override public void importLTM(java.io.File in) throws java.io.IOException,TopicMapException { if(unconnected) return; if(isReadOnly()) throw new TopicMapReadOnlyException(); int numTopics=getNumTopics(); if(numTopics==0) { System.out.println("Merging to empty topic map"); topicIndex.stopCleanerThread(); completeIndexes=topicIndex.isFullIndex(); } else System.out.println("Merging to non-empty topic map (numTopcis="+numTopics+")"); boolean old=getConsistencyCheck(); setConsistencyCheck(false); boolean check=!getConsistencyCheck(); super.importLTM(in); topicIndex.clearTopicCache(); topicIndex.startCleanerThread(); completeIndexes=false; if(check && old) checkAssociationConsistency(); setConsistencyCheck(old); } @Override public void mergeIn(TopicMap tm,TopicMapLogger tmLogger) throws TopicMapException { if(unconnected) return; if(isReadOnly()) throw new TopicMapReadOnlyException(); int numTopics=getNumTopics(); if(numTopics==0) { tmLogger.log("Merging to empty topic map"); topicIndex.stopCleanerThread(); completeIndexes=topicIndex.isFullIndex(); } else tmLogger.log("Merging to non-empty topic map (numTopics="+numTopics+")"); int targetNumTopics=tm.getNumTopics(); int targetNumAssociations=tm.getNumAssociations(); int tcount=0; Hashtable copied=new Hashtable(); { // note that in some topic map implementations (DatabaseTopicMap specifically) // you must always iterate through all topics to close the result set thus // don't break the while loop even after forceStop Iterator<Topic> iter=tm.getTopics(); while(iter.hasNext()){ Topic t = null; try { t=iter.next(); if(!tmLogger.forceStop()) _copyTopicIn(t,true,false,copied); tcount++; } catch (Exception e) { tmLogger.log("Unable to copy topic (" + t + ").",e); } if((tcount%1000)==0) tmLogger.hlog("Copied "+tcount+"/"+targetNumTopics+" topics and 0/"+targetNumAssociations+" associations"); } } if(!tmLogger.forceStop()){ HashSet<Topic> endpoints=new LinkedHashSet<Topic>(); int acount=0; Iterator<Association> iter=tm.getAssociations(); while(iter.hasNext()) { try { Association a=iter.next(); if(!tmLogger.forceStop()) { Association na=_copyAssociationIn(a); Topic minTopic=null; int minCount=Integer.MAX_VALUE; Iterator iter2=na.getRoles().iterator(); while(iter2.hasNext()){ Topic role=(Topic)iter2.next(); Topic t=na.getPlayer(role); if(t.getAssociations().size()<minCount){ minCount=t.getAssociations().size(); minTopic=t; } } endpoints.add(minTopic); } acount++; if((acount%1000)==0) tmLogger.hlog("Copied "+tcount+"/"+targetNumTopics+" topics and "+acount+"/"+targetNumAssociations+" associations"); } catch (Exception e) { tmLogger.log("Unable to copy association.",e); } } tmLogger.log("merged "+tcount+" topics and "+acount+" associations"); tmLogger.log("cleaning associations"); for(Topic t : endpoints){ ((DatabaseTopic)t).removeDuplicateAssociations(); } } topicIndex.startCleanerThread(); completeIndexes=false; } // --------------------------------------------------------------- INDEX --- /** * Tries to set complete index attribute. This is only possible if the topic map is * empty (getNumTopics returns 0). If this is the case, will stop index cleaner * thread and set the completeIndexes attribute to true. * @see #completeIndexes */ public void setCompleteIndex(){ if(getNumTopics()==0) { topicIndex.stopCleanerThread(); completeIndexes=topicIndex.isFullIndex(); } } /** * Restarts the topic index cleaner thread. You need to call this at some point * if you stopped it with setCompleteIndex. */ public void resetCompleteIndex(){ topicIndex.clearTopicCache(); topicIndex.startCleanerThread(); completeIndexes=false; } // ------------------------------------------------------------ TRACKING --- @Override public boolean trackingDependent(){ return false; } @Override public void setTrackDependent(boolean v){ // TODO: dependent times and tracking dependent } // --------------------------------------------------- TOPICMAP LISTENER --- @Override public List<TopicMapListener> getTopicMapListeners(){ return topicMapListeners; } @Override public void addTopicMapListener(TopicMapListener listener){ topicMapListeners.add(listener); } @Override public void removeTopicMapListener(TopicMapListener listener){ topicMapListeners.remove(listener); } @Override public void disableAllListeners(){ if(disabledListeners==null){ disabledListeners=topicMapListeners; topicMapListeners=new ArrayList<TopicMapListener>(); } } @Override public void enableAllListeners(){ if(disabledListeners!=null){ topicMapListeners=disabledListeners; disabledListeners=null; } } /* public TopicMapListener setTopicMapListener(TopicMapListener listener){ TopicMapListener old=topicMapListener; topicMapListener=listener; return old; }*/ @Override public boolean isTopicMapChanged(){ return changed; } @Override public boolean resetTopicMapChanged(){ boolean old=changed; changed=false; return old; } // ----------------------------------------- TOPICMAP LISTENER INTERFACE --- void topicRemoved(Topic t) throws TopicMapException { topicIndex.topicRemoved(t); changed=true; for(TopicMapListener listener : topicMapListeners){ listener.topicRemoved(t); } } void associationRemoved(Association a) throws TopicMapException { changed=true; for(TopicMapListener listener : topicMapListeners){ listener.associationRemoved(a); } } public void topicSubjectIdentifierChanged(Topic t,Locator added,Locator removed) throws TopicMapException{ changed=true; for(TopicMapListener listener : topicMapListeners){ listener.topicSubjectIdentifierChanged(t,added,removed); } } public void topicBaseNameChanged(Topic t,String newName,String oldName) throws TopicMapException{ changed=true; for(TopicMapListener listener : topicMapListeners){ listener.topicBaseNameChanged(t,newName,oldName); } } public void topicTypeChanged(Topic t,Topic added,Topic removed) throws TopicMapException { changed=true; for(TopicMapListener listener : topicMapListeners){ listener.topicTypeChanged(t,added,removed); } } public void topicVariantChanged(Topic t,Collection<Topic> scope,String newName,String oldName) throws TopicMapException { changed=true; for(TopicMapListener listener : topicMapListeners){ listener.topicVariantChanged(t,scope,newName,oldName); } } public void topicDataChanged(Topic t,Topic type,Topic version,String newValue,String oldValue) throws TopicMapException { changed=true; for(TopicMapListener listener : topicMapListeners){ listener.topicDataChanged(t,type,version,newValue,oldValue); } } public void topicSubjectLocatorChanged(Topic t,Locator newLocator,Locator oldLocator) throws TopicMapException { changed=true; for(TopicMapListener listener : topicMapListeners){ listener.topicSubjectLocatorChanged(t,newLocator,oldLocator); } } public void topicChanged(Topic t) throws TopicMapException { changed=true; for(TopicMapListener listener : topicMapListeners){ listener.topicChanged(t); } } public void associationTypeChanged(Association a,Topic newType,Topic oldType) throws TopicMapException { changed=true; for(TopicMapListener listener : topicMapListeners){ listener.associationTypeChanged(a,newType,oldType); } } public void associationPlayerChanged(Association a,Topic role,Topic newPlayer,Topic oldPlayer) throws TopicMapException { changed=true; for(TopicMapListener listener : topicMapListeners){ listener.associationPlayerChanged(a,role,newPlayer,oldPlayer); } } public void associationChanged(Association a) throws TopicMapException{ changed=true; for(TopicMapListener listener : topicMapListeners){ listener.associationChanged(a); } } // -------------------------------------------------------------- SEARCH --- @Override public Collection<Topic> search(String query, TopicMapSearchOptions options) { if(unconnected) return new ArrayList<Topic>(); ArrayList<Topic> searchResult = new ArrayList<Topic>(); int MAX_SEARCH_RESULTS = 999; if(options.maxResults>=0 && options.maxResults<MAX_SEARCH_RESULTS) MAX_SEARCH_RESULTS=options.maxResults; if(query == null || query.length()<4) { return searchResult; } String dbquery = "%" + escapeSQL(query) + "%"; System.out.println("Search starts"); String union=""; // --- Basename --- if(options.searchBasenames) { if(union.length()>0) union+=" union "; union+=" select TOPIC.* from TOPIC where BASENAME like '"+dbquery+"'"; } // --- Variant names --- if(options.searchVariants) { if(union.length()>0) union+=" union "; union+=" select TOPIC.* from TOPIC,VARIANT where TOPICID=VARIANT.TOPIC and VARIANT.VALUE like '"+dbquery+"'"; } // --- text occurrences --- if(options.searchOccurrences) { if(union.length()>0) union+=" union "; union+=" select TOPIC.* from TOPIC,DATA where DATA.TOPIC=TOPICID and DATA.DATA like '"+dbquery+"'"; } // --- locator --- if(options.searchSL) { if(union.length()>0) union+=" union "; union+=" select TOPIC.* from TOPIC where SUBJECTLOCATOR like '"+dbquery+"'"; } // --- sis --- if(options.searchSIs) { if(union.length()>0) union+=" union "; union+=" select TOPIC.* from TOPIC,SUBJECTIDENTIFIER where TOPICID=SUBJECTIDENTIFIER.TOPIC and SUBJECTIDENTIFIER.SI like '"+dbquery+"'"; } try{ Collection<Topic> res=queryTopic(union); int counter=0; for(Topic t : res){ if(t.getOneSubjectIdentifier() == null) { System.out.println("Warning: Topic '"+t.getBaseName()+"' has no SI!"); } else { searchResult.add(t); counter++; if(counter>=MAX_SEARCH_RESULTS) break; } } } catch(Exception e){e.printStackTrace();} System.out.println("Search ends with " + searchResult.size() + " hits."); return searchResult; } // ---------------------------------------------------------- STATISTICS --- @Override public TopicMapStatData getStatistics(TopicMapStatOptions options) throws TopicMapException { if(options == null) return null; int option = options.getOption(); int count = 0; switch(option) { case TopicMapStatOptions.NUMBER_OF_TOPICS: { return new TopicMapStatData(this.getNumTopics()); } case TopicMapStatOptions.NUMBER_OF_TOPIC_CLASSES: { if(unconnected) break; try{ count = executeCountQuery("select count(DISTINCT TYPE) from TOPICTYPE"); return new TopicMapStatData(count); } catch(SQLException sqle) { sqle.printStackTrace(); break; } } case TopicMapStatOptions.NUMBER_OF_ASSOCIATIONS: { return new TopicMapStatData(this.getNumAssociations()); } case TopicMapStatOptions.NUMBER_OF_ASSOCIATION_PLAYERS: { if(unconnected) break; try{ count = executeCountQuery("select count(DISTINCT MEMBER.PLAYER) from MEMBER"); return new TopicMapStatData(count); } catch(SQLException sqle) { sqle.printStackTrace(); break; } } case TopicMapStatOptions.NUMBER_OF_ASSOCIATION_ROLES: { if(unconnected) break; try{ count = executeCountQuery("select count(DISTINCT MEMBER.ROLE) from MEMBER"); return new TopicMapStatData(count); } catch(SQLException sqle) { sqle.printStackTrace(); break; } } case TopicMapStatOptions.NUMBER_OF_ASSOCIATION_TYPES: { if(unconnected) break; try{ count = executeCountQuery("select count(DISTINCT ASSOCIATION.TYPE) from ASSOCIATION"); return new TopicMapStatData(count); } catch(SQLException sqle) { sqle.printStackTrace(); break; } } case TopicMapStatOptions.NUMBER_OF_BASE_NAMES: { if(unconnected) break; try{ count = executeCountQuery("select count(*) from TOPIC where BASENAME is not null"); return new TopicMapStatData(count); } catch(SQLException sqle) { sqle.printStackTrace(); break; } } case TopicMapStatOptions.NUMBER_OF_OCCURRENCES: { if(unconnected) break; try{ count = executeCountQuery("select count(*) from DATA"); return new TopicMapStatData(count); } catch(SQLException sqle) { sqle.printStackTrace(); break; } } case TopicMapStatOptions.NUMBER_OF_SUBJECT_IDENTIFIERS: { if(unconnected) break; try{ count = executeCountQuery("select count(*) from SUBJECTIDENTIFIER"); return new TopicMapStatData(count); } catch(SQLException sqle) { sqle.printStackTrace(); break; } } case TopicMapStatOptions.NUMBER_OF_SUBJECT_LOCATORS: { if(unconnected) break; try{ count = executeCountQuery("select count(*) from TOPIC where SUBJECTLOCATOR is not null"); return new TopicMapStatData(count); } catch(SQLException sqle) { sqle.printStackTrace(); break; } } } return new TopicMapStatData(); } private int executeCountQuery(String query) throws SQLException { if(sqlProxy!=null){ try{ Collection<Map<String,Object>> res=sqlProxy.executeQuery(query); Map<String,Object> row=res.iterator().next(); return ((Number)row.get(row.keySet().iterator().next())).intValue(); }catch(Exception e){ throw new SQLException("Exception querying sqlproxy: "+e.getMessage()); } } Connection con=getConnection(); Statement stmt=con.createStatement(); ResultSet rs=stmt.executeQuery(query); rs.next(); int count=rs.getInt(1); rs.close(); stmt.close(); return count; } }
70,882
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DatabaseAssociation.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/database/DatabaseAssociation.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * DatabaseAssociation.java * * Created on 7. marraskuuta 2005, 11:28 */ package org.wandora.topicmap.database; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.LinkedHashMap; import java.util.Map; import org.wandora.topicmap.Association; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicMapReadOnlyException; import org.wandora.topicmap.TopicRemovedException; /** * * @author olli */ public class DatabaseAssociation implements Association { protected DatabaseTopicMap topicMap; protected String id; protected boolean full; protected DatabaseTopic type; protected Hashtable<Topic,Topic> players; protected boolean removed=false; /** Creates a new instance of DatabaseAssociation */ public DatabaseAssociation(DatabaseTopic type,DatabaseTopicMap topicMap) { this.type=type; this.topicMap=topicMap; full=false; } public DatabaseAssociation(DatabaseTopic type,String id,DatabaseTopicMap topicMap) { this(type,topicMap); this.id=id; } public DatabaseAssociation(String id,DatabaseTopicMap topicMap) { this.topicMap=topicMap; this.id=id; full=false; } public DatabaseAssociation(Map<String,Object> row,DatabaseTopicMap topicMap) throws TopicMapException { this(topicMap.buildTopic(row),topicMap); this.id=row.get("ASSOCIATIONID").toString(); } void initialize(DatabaseTopic type){ this.type=type; } protected String escapeSQL(String s){ return topicMap.escapeSQL(s); } private static int idcounter=0; protected static synchronized String makeID(){ if(idcounter>=100000) idcounter=0; return "A"+System.currentTimeMillis()+"-"+(idcounter++); } public String getID(){ return id; } void create() throws TopicMapException { players=new Hashtable<Topic,Topic>(); full=true; id=makeID(); topicMap.executeUpdate("insert into ASSOCIATION (ASSOCIATIONID,TYPE) values ('"+escapeSQL(id)+"','"+escapeSQL(type.getID())+"')"); } static HashMap<String,DatabaseTopic> makeFullAll(Collection<Map<String,Object>> res,HashMap<String,DatabaseAssociation> associations,DatabaseTopicMap topicMap) throws TopicMapException { HashMap<String,DatabaseTopic> collected=new LinkedHashMap<String,DatabaseTopic>(); String associationID=null; Hashtable<Topic,Topic> players=null; for(Map<String,Object> row : res){ if(associationID==null || !associationID.equals(row.get("ASSOCIATION"))){ if(associationID!=null){ DatabaseAssociation dba=associations.get(associationID); if(dba!=null && !dba.full){ dba.full=true; dba.players=players; } } players=new Hashtable<Topic,Topic>(); associationID=row.get("ASSOCIATION").toString(); } DatabaseTopic player=topicMap.buildTopic(row.get("PLAYERID"),row.get("PLAYERBN"),row.get("PLAYERSL")); DatabaseTopic role=topicMap.buildTopic(row.get("ROLEID"),row.get("ROLEBN"),row.get("ROLESL")); collected.put(player.getID(),player); collected.put(role.getID(),role); players.put(role,player); } if(associationID!=null){ DatabaseAssociation dba=associations.get(associationID); if(dba!=null && !dba.full){ dba.full=true; dba.players=players; } } return collected; } void makeFull() throws TopicMapException { full=true; Collection<Map<String,Object>> res= topicMap.executeQuery("select P.TOPICID as PLAYERID, P.BASENAME as PLAYERNAME, P.SUBJECTLOCATOR as PLAYERSL, "+ "R.TOPICID as ROLEID, R.BASENAME as ROLENAME, R.SUBJECTLOCATOR as ROLESL from "+ "TOPIC as P,TOPIC as R, MEMBER as M where P.TOPICID=M.PLAYER and "+ "R.TOPICID=M.ROLE and M.ASSOCIATION='"+escapeSQL(id)+"'"); players=new Hashtable<Topic,Topic>(); for(Map<String,Object> row : res){ Topic role=topicMap.buildTopic(row.get("ROLEID"),row.get("ROLENAME"),row.get("ROLESL")); Topic player=topicMap.buildTopic(row.get("PLAYERID"),row.get("PLAYERNAME"),row.get("PLAYERSL")); players.put(role,player); } } @Override public Topic getType() throws TopicMapException { return type; } @Override public void setType(Topic t) throws TopicMapException { if( removed ) throw new TopicRemovedException(); if(!full) makeFull(); for(Map.Entry<Topic,Topic> e : players.entrySet()){ Topic role=e.getKey(); Topic player=e.getValue(); ((DatabaseTopic)player).associationChanged(this, t, type, role, role); } Topic old=type; type=(DatabaseTopic)t; topicMap.executeUpdate("update ASSOCIATION set TYPE='"+escapeSQL(type.getID())+"' where ASSOCIATIONID='"+escapeSQL(id)+"'"); topicMap.associationTypeChanged(this,t,old); } @Override public Topic getPlayer(Topic role) throws TopicMapException { if(!full) makeFull(); return players.get(role); } @Override public void addPlayer(Topic player,Topic role) throws TopicMapException { if( removed ) throw new TopicRemovedException(); if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); if(!full) makeFull(); Topic old=players.get(role); if(old!=null){ ((DatabaseTopic)old).associationChanged(this, null, type,null, role); topicMap.executeUpdate("update MEMBER set PLAYER='"+escapeSQL(player.getID())+"' where "+ "ASSOCIATION='"+escapeSQL(id)+"' and ROLE='"+escapeSQL(role.getID())+"'"); } else{ topicMap.executeUpdate("insert into MEMBER (ASSOCIATION,PLAYER,ROLE) values "+ "('"+escapeSQL(id)+"','"+escapeSQL(player.getID())+"','"+escapeSQL(role.getID())+"')"); } ((DatabaseTopic)player).associationChanged(this,type,null,role,null); players.put(role,player); if(topicMap.getConsistencyCheck()) checkRedundancy(); topicMap.associationPlayerChanged(this,role,player,old); } @Override public void addPlayers(Map<Topic,Topic> players) throws TopicMapException { if( removed ) throw new TopicRemovedException(); if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); boolean changed=false; for(Map.Entry<Topic,Topic> e : players.entrySet()){ DatabaseTopic role=(DatabaseTopic)e.getKey(); DatabaseTopic player=(DatabaseTopic)e.getValue(); Topic old=this.players.get(role); if(old!=null){ ((DatabaseTopic)old).associationChanged(this, null, type,null, role); topicMap.executeUpdate("update MEMBER set PLAYER='"+escapeSQL(player.getID())+"' where "+ "ASSOCIATION='"+escapeSQL(id)+"' and ROLE='"+escapeSQL(role.getID())+"'"); } else{ topicMap.executeUpdate("insert into MEMBER (ASSOCIATION,PLAYER,ROLE) values "+ "('"+escapeSQL(id)+"','"+escapeSQL(player.getID())+"','"+escapeSQL(role.getID())+"')"); } ((DatabaseTopic)player).associationChanged(this,type,null,role,null); this.players.put(role,player); topicMap.associationPlayerChanged(this,role,player,old); } if(topicMap.getConsistencyCheck()) checkRedundancy(); } @Override public void removePlayer(Topic role) throws TopicMapException { if( removed ) throw new TopicRemovedException(); if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); if(!full) makeFull(); Topic old=players.get(role); if(old!=null){ ((DatabaseTopic)old).associationChanged(this, null, type,null, role); topicMap.executeUpdate("delete from MEMBER where "+ "ASSOCIATION='"+escapeSQL(id)+"' and ROLE='"+escapeSQL(role.getID())+"'"); } players.remove(role); checkRedundancy(); topicMap.associationPlayerChanged(this,role,null,old); } @Override public Collection<Topic> getRoles() throws TopicMapException { if(!full) makeFull(); return players.keySet(); } @Override public TopicMap getTopicMap(){ return topicMap; } @Override public void remove() throws TopicMapException { if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); if(!full) makeFull(); removed=true; for(Map.Entry<Topic,Topic> e : players.entrySet()){ Topic role=e.getKey(); Topic player=e.getValue(); ((DatabaseTopic)player).associationChanged(this, null, type, null, role); } topicMap.executeUpdate("delete from MEMBER where ASSOCIATION='"+escapeSQL(id)+"'"); topicMap.executeUpdate("delete from ASSOCIATION where ASSOCIATIONID='"+escapeSQL(id)+"'"); topicMap.associationRemoved(this); } @Override public boolean isRemoved() throws TopicMapException { return removed; } public void checkRedundancy() throws TopicMapException { if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); if(players.isEmpty()) return; if(type==null) return; Collection<Association> smallest=null; for(Topic role : players.keySet()){ Topic player=players.get(role); Collection<Association> c=player.getAssociations(type,role); if(smallest==null || c.size()<smallest.size()) smallest=c; // getAssociations may be a timeconsuming method so don't check everything if not necessary if(smallest!=null && smallest.size()<50) break; } HashSet<Association> delete=new HashSet(); for(Association a : smallest){ if(a==this) continue; if(((DatabaseAssociation)a)._equals(this)){ delete.add(a); } } for(Association a : delete){ a.remove(); } } boolean _equals(DatabaseAssociation a){ if(a == null) return false; return (players.equals(a.players)&&(type==a.type)); } int _hashCode(){ return players.hashCode()+type.hashCode(); } /* public int hashCode(){ return id.hashCode(); } public boolean equals(Object o){ if(o instanceof DatabaseAssociation){ return id.equals(((DatabaseAssociation)o).id); } else return false; }*/ }
12,088
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DatabaseTopic.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/database/DatabaseTopic.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * DatabaseTopic.java * * Created on 7. marraskuuta 2005, 11:28 */ package org.wandora.topicmap.database; import static org.wandora.utils.Tuples.t2; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.Vector; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicInUseException; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicMapReadOnlyException; import org.wandora.topicmap.TopicRemovedException; import org.wandora.utils.Tuples.T2; /** * * @author olli */ public class DatabaseTopic extends Topic { protected boolean full; // flags indicating what kind of data has been fecthed from the database protected boolean sisFetched; protected boolean dataFetched; protected boolean variantsFetched; protected boolean typesFetched; // protected boolean associationsFetched; protected DatabaseTopicMap topicMap; protected String baseName; protected String id; protected Locator subjectLocator; protected HashSet<Locator> subjectIdentifiers; protected Hashtable<Topic,Hashtable<Topic,String>> data; // scope value ,variantid protected Hashtable<Set<Topic>,T2<String,String>> variants; protected HashSet<Topic> types; // type , role of this topic //protected Hashtable<Topic,Hashtable<Topic,Collection<Association>>> associations; protected WeakReference<Hashtable<Topic,Hashtable<Topic,Collection<Association>>>> storedAssociations; protected boolean removed=false; /** Creates a new instance of DatabaseTopic */ public DatabaseTopic(DatabaseTopicMap tm) { this.topicMap=tm; full=false; sisFetched=false; dataFetched=false; variantsFetched=false; typesFetched=false; id=null; // associationsFetched=false; } public DatabaseTopic(String id, DatabaseTopicMap tm) { this(tm); this.id=id; } public DatabaseTopic(Map<String,Object> row, DatabaseTopicMap tm) throws TopicMapException { this(tm); Object o=row.get("BASENAME"); if(o!=null) { internalSetBaseName(o.toString()); } o=row.get("SUBJECTLOCATOR"); if(o!=null) { subjectLocator=topicMap.createLocator(o.toString()); } o=row.get("TOPICID"); if(o!=null) { id=o.toString(); } } public DatabaseTopic(Object baseName, Object subjectLocator, Object id, DatabaseTopicMap tm) throws TopicMapException { this(tm); if(baseName!=null) { internalSetBaseName(baseName.toString()); } if(subjectLocator!=null) { this.subjectLocator=topicMap.createLocator(subjectLocator.toString()); } if(id!=null) { this.id=id.toString(); } } void initialize(Object baseName,Object subjectLocator) throws TopicMapException { initialize((String)baseName,(String)subjectLocator); } /** * Initializes this DatabaseTopic object setting the basename and subject locator * but does not modify the actual database. */ void initialize(String baseName,String subjectLocator) throws TopicMapException { internalSetBaseName(baseName); if(subjectLocator!=null) { this.subjectLocator=topicMap.createLocator(subjectLocator); } } /** * Sets the base name in this DatabaseTopic object but does not modify the database. */ protected void internalSetBaseName(String bn) throws TopicMapException { String old=baseName; baseName=bn; topicMap.topicBNChanged(this, old); } private static int idcounter=0; /** * Makes an ID string that can be used as an identifier in the database. * It will be unique if all identifiers are generated using the same Java * virtual machine but if they are being generated by several virtual machine * collisions may occur, however they will be extremely unlikely. */ protected static synchronized String makeID(){ if(idcounter>=100000) idcounter=0; return "T"+System.currentTimeMillis()+"-"+(idcounter++); } /** * Inserts a new topic in the database with the data currently set in this * DatabaseTopic object. A new DatabaseTopic is not inserted in the database * until this method is called. */ void create() throws TopicMapException { subjectIdentifiers=new LinkedHashSet<Locator>(); data=new Hashtable<Topic,Hashtable<Topic,String>>(); variants=new Hashtable<Set<Topic>,T2<String,String>>(); types=new LinkedHashSet<Topic>(); // associations=new Hashtable<Topic,Hashtable<Topic,Collection<Association>>>(); full=true; sisFetched=true; dataFetched=true; variantsFetched=true; typesFetched=true; if(id == null) { id=makeID(); } topicMap.executeUpdate("insert into TOPIC (TOPICID) values ('"+escapeSQL(id)+"')"); } /* void setFull(boolean full){ // what should we do about sisFetched, typesFetched etc. this.full=full; }*/ protected String escapeSQL(String s){ return topicMap.escapeSQL(s); } /** * Sets subject identifiers in this DatabaseTopic but does not modify * the underlying database. */ protected void setSubjectIdentifiers(HashSet<Locator> sis) { HashSet<Locator> oldSIs=subjectIdentifiers; subjectIdentifiers=sis; if(oldSIs!=null && oldSIs.size()>0){ HashSet<Locator> removed=new LinkedHashSet<Locator>(); removed.addAll(oldSIs); removed.removeAll(subjectIdentifiers); for(Locator l : removed){ topicMap.topicSIChanged(this,l,null); } HashSet<Locator> added=new LinkedHashSet<Locator>(); added.addAll(subjectIdentifiers); added.removeAll(oldSIs); for(Locator l : added){ topicMap.topicSIChanged(this,null,l); } } else{ for(Locator l : subjectIdentifiers){ topicMap.topicSIChanged(this,null,l); } } } // --------------------------------------------------------------- FETCH --- protected void fetchSubjectIdentifiers() throws TopicMapException { Collection<Map<String,Object>> res=topicMap.executeQuery("select * from SUBJECTIDENTIFIER where TOPIC='"+escapeSQL(id)+"'"); HashSet<Locator> newSIs=new LinkedHashSet<Locator>(); for(Map<String,Object> row : res){ newSIs.add(topicMap.createLocator(row.get("SI").toString())); } setSubjectIdentifiers(newSIs); sisFetched=true; } protected void fetchData() throws TopicMapException { Collection<Map<String,Object>> res=topicMap.executeQuery( "select DATA.*, " + "Y.TOPICID as TYPEID, Y.BASENAME as TYPEBN, Y.SUBJECTLOCATOR as TYPESL," + "V.TOPICID as VERSIONID, V.BASENAME as VERSIONBN, V.SUBJECTLOCATOR as VERSIONSL " + "from DATA,TOPIC as Y,TOPIC as V where "+ "DATA.TYPE=Y.TOPICID and DATA.VERSION=V.TOPICID and "+ "DATA.TOPIC='"+escapeSQL(id)+"'"); data=new Hashtable<Topic,Hashtable<Topic,String>>(); for(Map<String,Object> row : res){ Topic type=topicMap.buildTopic(row.get("TYPEID"),row.get("TYPEBN"),row.get("TYPESL")); Topic version=topicMap.buildTopic(row.get("VERSIONID"),row.get("VERSIONBN"),row.get("VERSIONSL")); Hashtable<Topic,String> td=data.get(type); if(td==null){ td=new Hashtable<Topic,String>(); data.put(type,td); } td.put(version,row.get("DATA").toString()); } dataFetched=true; } protected void fetchVariants() throws TopicMapException { Collection<Map<String,Object>> res=topicMap.executeQuery( "select TOPIC.*,VARIANT.* from TOPIC,VARIANT,VARIANTSCOPE where "+ "TOPICID=VARIANTSCOPE.TOPIC and VARIANTSCOPE.VARIANT=VARIANTID and "+ "VARIANT.TOPIC='"+escapeSQL(id)+"' order by VARIANTID"); variants=new Hashtable<Set<Topic>,T2<String,String>>(); HashSet<Topic> scope=null; String lastVariant=null; String lastName=null; for(Map<String,Object> row : res){ if(lastVariant==null || !lastVariant.equals(row.get("VARIANTID"))){ if(lastVariant!=null){ variants.put(scope,t2(lastName,lastVariant)); } scope=new LinkedHashSet<Topic>(); lastVariant=row.get("VARIANTID").toString(); lastName=row.get("VALUE").toString(); } scope.add(topicMap.buildTopic(row)); } if(lastVariant!=null){ variants.put(scope,t2(lastName,lastVariant)); } variantsFetched=true; } protected void fetchTypes() throws TopicMapException { Collection<Map<String,Object>> res=topicMap.executeQuery( "select TOPIC.* from TOPIC,TOPICTYPE where TYPE=TOPICID and "+ "TOPIC='"+escapeSQL(id)+"'"); types=new LinkedHashSet<Topic>(); for(Map<String,Object> row : res){ types.add(topicMap.buildTopic(row)); } typesFetched=true; } static void fetchAllSubjectIdentifiers(Collection<Map<String,Object>> res, Map<String,DatabaseTopic> topics,DatabaseTopicMap topicMap) throws TopicMapException { String topicID=null; HashSet<Locator> subjectIdentifiers=new LinkedHashSet<Locator>(); for(Map<String,Object> row : res) { if(topicID==null || !topicID.equals(row.get("TOPIC"))){ if(topicID!=null){ DatabaseTopic dbt=topics.get(topicID); if(dbt!=null && !dbt.sisFetched){ dbt.sisFetched=true; dbt.setSubjectIdentifiers(subjectIdentifiers); } } subjectIdentifiers=new LinkedHashSet<Locator>(); topicID=row.get("TOPIC").toString(); } subjectIdentifiers.add(topicMap.createLocator(row.get("SI").toString())); } if(topicID!=null){ DatabaseTopic dbt=topics.get(topicID); if(dbt!=null && !dbt.sisFetched){ dbt.sisFetched=true; dbt.setSubjectIdentifiers(subjectIdentifiers); } } } protected Hashtable<Topic,Hashtable<Topic,Collection<Association>>> fetchAssociations() throws TopicMapException { if(storedAssociations!=null){ Hashtable<Topic,Hashtable<Topic,Collection<Association>>> associations=storedAssociations.get(); if(associations!=null) return associations; } Collection<Map<String,Object>> res=topicMap.executeQuery( "select R.TOPICID as ROLEID,R.BASENAME as ROLEBN,R.SUBJECTLOCATOR as ROLESL," + "T.TOPICID as TYPEID,T.BASENAME as TYPEBN,T.SUBJECTLOCATOR as TYPESL,ASSOCIATIONID " + "from MEMBER,ASSOCIATION,TOPIC as T,TOPIC as R where "+ "R.TOPICID=MEMBER.ROLE and MEMBER.ASSOCIATION=ASSOCIATION.ASSOCIATIONID and "+ "ASSOCIATION.TYPE=T.TOPICID and MEMBER.PLAYER='"+escapeSQL(id)+"' "+ "order by R.TOPICID" ); Hashtable<Topic,Hashtable<Topic,Collection<Association>>> associations=new Hashtable<Topic,Hashtable<Topic,Collection<Association>>>(); HashMap<String,DatabaseTopic> collectedTopics=new LinkedHashMap<String,DatabaseTopic>(); HashMap<String,DatabaseAssociation> collectedAssociations=new LinkedHashMap<String,DatabaseAssociation>(); for(Map<String,Object> row : res) { DatabaseTopic type=topicMap.buildTopic(row.get("TYPEID"),row.get("TYPEBN"),row.get("TYPESL")); DatabaseTopic role=topicMap.buildTopic(row.get("ROLEID"),row.get("ROLEBN"),row.get("ROLESL")); Hashtable<Topic,Collection<Association>> as=associations.get(type); if(as==null) { as=new Hashtable<Topic,Collection<Association>>(); associations.put(type,as); } Collection<Association> c=as.get(role); if(c==null){ c=new Vector<Association>(); as.put(role,c); } DatabaseAssociation da=topicMap.buildAssociation(row.get("ASSOCIATIONID").toString(),type); c.add(da); collectedAssociations.put(da.getID(),da); collectedTopics.put(type.getID(),type); collectedTopics.put(role.getID(),role); } { collectedTopics.putAll(DatabaseAssociation.makeFullAll(topicMap.executeQuery( "select R.TOPICID as ROLEID,R.BASENAME as ROLEBN,R.SUBJECTLOCATOR as ROLESL," + "P.TOPICID as PLAYERID,P.BASENAME as PLAYERBN,P.SUBJECTLOCATOR as PLAYERSL, OM.ASSOCIATION " + "from MEMBER as LM,MEMBER as OM,TOPIC as P,TOPIC as R where "+ "R.TOPICID=OM.ROLE and P.TOPICID=OM.PLAYER and OM.ASSOCIATION=LM.ASSOCIATION and "+ "LM.PLAYER='"+escapeSQL(id)+"' order by OM.ASSOCIATION" ),collectedAssociations,topicMap)); /* DatabaseTopic.fetchAllSubjectIdentifiers(topicMap.executeQuery( "select * from SUBJECTIDENTIFIER where TOPIC in (select TYPE "+ "from MEMBER as LM,ASSOCIATION where "+ "ASSOCIATIONID=LM.ASSOCIATION and "+ "LM.PLAYER='"+escapeSQL(id)+"' "+ "union "+ "select OM.ROLE "+ "from MEMBER as LM,MEMBER as OM where "+ "OM.ASSOCIATION=LM.ASSOCIATION and "+ "LM.PLAYER='"+escapeSQL(id)+"' "+ "union "+ "select OM.PLAYER "+ "from MEMBER as LM,MEMBER as OM where "+ "OM.ASSOCIATION=LM.ASSOCIATION and "+ "LM.PLAYER='"+escapeSQL(id)+"') order by TOPIC" ),collectedTopics,topicMap); */ DatabaseTopic.fetchAllSubjectIdentifiers(topicMap.executeQuery( "select SUBJECTIDENTIFIER.* from SUBJECTIDENTIFIER, ("+ "select TOPIC.TOPICID "+ "from MEMBER as LM,ASSOCIATION,TOPIC where "+ "ASSOCIATIONID=LM.ASSOCIATION and "+ "LM.PLAYER='"+escapeSQL(id)+"' and TOPIC.TOPICID=ASSOCIATION.TYPE "+ "union "+ "select TOPIC.TOPICID "+ "from MEMBER as LM,MEMBER as OM,TOPIC where "+ "OM.ASSOCIATION=LM.ASSOCIATION and "+ "LM.PLAYER='"+escapeSQL(id)+"' and TOPIC.TOPICID=OM.ROLE "+ "union "+ "select TOPIC.TOPICID "+ "from MEMBER as LM,MEMBER as OM,TOPIC where "+ "OM.ASSOCIATION=LM.ASSOCIATION and "+ "LM.PLAYER='"+escapeSQL(id)+"' and TOPIC.TOPICID=OM.PLAYER "+ ") as TEMP where SUBJECTIDENTIFIER.TOPIC=TEMP.TOPICID order by TOPIC" ),collectedTopics,topicMap); } // associationsFetched=true; storedAssociations=new WeakReference(associations); return associations; } /** * Fetch all information from database that hasn't already been fetched. */ void makeFull() throws TopicMapException { if(!sisFetched) fetchSubjectIdentifiers(); if(!dataFetched) fetchData(); if(!variantsFetched) fetchVariants(); if(!typesFetched) fetchTypes(); // if(!associationsFetched) fetchAssociations(); full=true; } // ------------------------------------------------------------------------- @Override public String getID(){ return id; } @Override public Collection<Locator> getSubjectIdentifiers() throws TopicMapException { if(!sisFetched) fetchSubjectIdentifiers(); return subjectIdentifiers; } @Override public void addSubjectIdentifier(Locator l) throws TopicMapException { if( removed ) throw new TopicRemovedException(); if( topicMap.isReadOnly() ) throw new TopicMapReadOnlyException(); if( l == null ) return; if(!sisFetched) fetchSubjectIdentifiers(); if(!subjectIdentifiers.contains(l)) { Topic t=topicMap.getTopic(l); if(t!=null) { mergeIn(t); } else { subjectIdentifiers.add(l); // System.out.println("Inserting si "+l.toExternalForm()); boolean ok = topicMap.executeUpdate("insert into SUBJECTIDENTIFIER (TOPIC,SI) values ('"+ escapeSQL(id)+"','"+escapeSQL(l.toExternalForm())+"')"); if(!ok) System.out.println("Failed to add si "+l.toExternalForm()); topicMap.topicSIChanged(this, null,l); topicMap.topicSubjectIdentifierChanged(this,l,null); } } // topicMap.topicChanged(this); } public void mergeIn(Topic t) throws TopicMapException { if( removed ) throw new TopicRemovedException(); if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); if( t == null ) return; Collection<Map<String,Object>> tempRes; DatabaseTopic ti=(DatabaseTopic)t; // add data tempRes=topicMap.executeQuery("select D1.* from DATA as D1,DATA as D2 where D1.VERSION=D2.VERSION and "+ "D1.TYPE=D2.TYPE and D1.TOPIC='"+escapeSQL(t.getID())+"' and D2.TOPIC='"+escapeSQL(id)+"'"); for(Map<String,Object> row : tempRes){ topicMap.executeUpdate("delete from DATA where TOPIC='"+escapeSQL((String)row.get("TOPIC"))+"' and "+ "TYPE='"+escapeSQL((String)row.get("TYPE"))+"' and "+ "VERSION='"+escapeSQL((String)row.get("VERSION"))+"'"); } topicMap.executeUpdate("update DATA set TOPIC='"+escapeSQL(id)+"' where "+ "TOPIC='"+escapeSQL(t.getID())+"'"); // set base name if(ti.getBaseName()!=null) { String name=ti.getBaseName(); ti.setBaseName(null); this.setBaseName(name); } // set subject locator if(ti.getSubjectLocator()!=null){ Locator l=ti.getSubjectLocator(); ti.setSubjectLocator(null); this.setSubjectLocator(l); } // for now just update all associations,roles,types etc and remove duplicates later // set types tempRes=topicMap.executeQuery("select T1.* from TOPICTYPE as T1,TOPICTYPE as T2 where T1.TYPE=T2.TYPE and "+ "T1.TOPIC='"+escapeSQL(t.getID())+"' and T2.TOPIC='"+escapeSQL(id)+"'"); for(Map<String,Object> row : tempRes){ topicMap.executeUpdate("delete from TOPICTYPE where TOPIC='"+escapeSQL((String)row.get("TOPIC"))+"' and "+ "TYPE='"+escapeSQL((String)row.get("TYPE"))+"'"); } topicMap.executeUpdate("update TOPICTYPE set TOPIC='"+escapeSQL(id)+"' where "+ "TOPIC='"+escapeSQL(t.getID())+"'"); tempRes=topicMap.executeQuery("select T1.* from TOPICTYPE as T1,TOPICTYPE as T2 where T1.TOPIC=T2.TOPIC and "+ "T1.TYPE='"+escapeSQL(t.getID())+"' and T2.TYPE='"+escapeSQL(id)+"'"); for(Map<String,Object> row : tempRes){ topicMap.executeUpdate("delete from TOPICTYPE where TOPIC='"+escapeSQL((String)row.get("TOPIC"))+"' and "+ "TYPE='"+escapeSQL((String)row.get("TYPE"))+"'"); } topicMap.executeUpdate("update TOPICTYPE set TYPE='"+escapeSQL(id)+"' where "+ "TYPE='"+escapeSQL(t.getID())+"'"); // set variant names topicMap.executeUpdate("update VARIANT set TOPIC='"+escapeSQL(id)+"' where "+ "TOPIC='"+escapeSQL(t.getID())+"'"); // set subject identifiers topicMap.executeUpdate("update SUBJECTIDENTIFIER set TOPIC='"+escapeSQL(id)+"' where "+ "TOPIC='"+escapeSQL(t.getID())+"'"); // change association players topicMap.executeUpdate("update MEMBER set PLAYER='"+escapeSQL(id)+"' where "+ "PLAYER='"+escapeSQL(t.getID())+"'"); // change association types topicMap.executeUpdate("update ASSOCIATION set TYPE='"+escapeSQL(id)+"' where "+ "TYPE='"+escapeSQL(t.getID())+"'"); // change data types tempRes=topicMap.executeQuery("select D1.* from DATA as D1,DATA as D2 where D1.VERSION=D2.VERSION and "+ "D1.TOPIC=D2.TOPIC and D1.TYPE='"+escapeSQL(t.getID())+"' and D2.TYPE='"+escapeSQL(id)+"'"); for(Map<String,Object> row : tempRes){ topicMap.executeUpdate("delete from DATA where TOPIC='"+escapeSQL((String)row.get("TOPIC"))+"' and "+ "TYPE='"+escapeSQL((String)row.get("TYPE"))+"' and "+ "VERSION='"+escapeSQL((String)row.get("VERSION"))+"'"); } topicMap.executeUpdate("update DATA set TYPE='"+escapeSQL(id)+"' where "+ "TYPE='"+escapeSQL(t.getID())+"'"); // change data versions tempRes=topicMap.executeQuery("select D1.* from DATA as D1,DATA as D2 where D1.TYPE=D2.TYPE and "+ "D1.TOPIC=D2.TOPIC and D1.VERSION='"+escapeSQL(t.getID())+"' and D2.VERSION='"+escapeSQL(id)+"'"); for(Map<String,Object> row : tempRes){ topicMap.executeUpdate("delete from DATA where TOPIC='"+escapeSQL((String)row.get("TOPIC"))+"' and "+ "TYPE='"+escapeSQL((String)row.get("TYPE"))+"' and "+ "VERSION='"+escapeSQL((String)row.get("VERSION"))+"'"); } topicMap.executeUpdate("update DATA set VERSION='"+escapeSQL(id)+"' where "+ "VERSION='"+escapeSQL(t.getID())+"'"); // change role types tempRes=topicMap.executeQuery("select M1.* from MEMBER as M1,MEMBER as M2 where M1.ASSOCIATION=M2.ASSOCIATION and "+ "M1.ROLE='"+escapeSQL(t.getID())+"' and M2.ROLE='"+escapeSQL(id)+"'"); for(Map<String,Object> row : tempRes){ topicMap.executeUpdate("delete from MEMBER where ASSOCIATION='"+escapeSQL((String)row.get("ASSOCIATION"))+"' and "+ "ROLE='"+escapeSQL((String)row.get("ROLE"))+"'"); } topicMap.executeUpdate("update MEMBER set ROLE='"+escapeSQL(id)+"' where "+ "ROLE='"+escapeSQL(t.getID())+"'"); // change variant scopes tempRes=topicMap.executeQuery("select V1.* from VARIANTSCOPE as V1,VARIANTSCOPE as V2 where "+ "V1.VARIANT=V2.VARIANT and V1.TOPIC='"+escapeSQL(t.getID())+"' and V2.TOPIC='"+escapeSQL(id)+"'"); for(Map<String,Object> row : tempRes){ topicMap.executeUpdate("delete from VARIANTSCOPE where VARIANT='"+escapeSQL((String)row.get("VARIANT"))+"' and "+ "TOPIC='"+escapeSQL((String)row.get("TOPIC"))+"'"); } topicMap.executeUpdate("update VARIANTSCOPE set TOPIC='"+escapeSQL(id)+"' where "+ "TOPIC='"+escapeSQL(t.getID())+"'"); // remove everything where old topic is still used (these are duplicates) topicMap.executeUpdate("delete from TOPICTYPE where TOPIC='"+escapeSQL(t.getID())+"'"); topicMap.executeUpdate("delete from DATA where TOPIC='"+escapeSQL(t.getID())+"'"); topicMap.executeUpdate("delete from DATA where TYPE='"+escapeSQL(t.getID())+"'"); topicMap.executeUpdate("delete from DATA where VERSION='"+escapeSQL(t.getID())+"'"); topicMap.executeUpdate("delete from MEMBER where ROLE='"+escapeSQL(t.getID())+"'"); topicMap.executeUpdate("delete from VARIANTSCOPE where TOPIC='"+escapeSQL(t.getID())+"'"); { // check for duplicate associations Collection<Map<String,Object>> res=topicMap.executeQuery( "select M1.*,ASSOCIATION.TYPE from MEMBER as M1, ASSOCIATION, MEMBER as M2 where "+ "M1.ASSOCIATION=ASSOCIATIONID and ASSOCIATIONID=M2.ASSOCIATION and "+ "M2.PLAYER='"+escapeSQL(id)+"' order by M1.ASSOCIATION"); // type ,associations{ role ,player} HashSet<T2<String,Collection<T2<String,String>>>> associations=new LinkedHashSet<T2<String,Collection<T2<String,String>>>>(); HashSet<String> delete=new LinkedHashSet<String>(); String oldAssociation="dummy"; String oldType=""; Collection<T2<String,String>> association=null; for(Map<String,Object> row : res){ String aid=(String)row.get("ASSOCIATION"); if(!aid.equals(oldAssociation)){ if(association!=null){ if(associations.contains(t2(oldType,association))) delete.add(oldAssociation); else associations.add(t2(oldType,association)); } association=new LinkedHashSet<T2<String,String>>(); oldAssociation=aid; oldType=(String)row.get("TYPE"); } association.add(t2((String)row.get("ROLE"),(String)row.get("PLAYER"))); } if(association!=null){ if(associations.contains(t2(oldType,association))) delete.add(oldAssociation); } if(delete.size()>0){ String col=topicMap.collectionToSQL(delete); topicMap.executeUpdate("delete from MEMBER where ASSOCIATION in "+col); topicMap.executeUpdate("delete from ASSOCIATION where ASSOCIATIONID in "+col); } } { // check for duplicate variants Collection<Map<String,Object>> res=topicMap.executeQuery( "select VARIANTSCOPE.* from VARIANT,VARIANTSCOPE where "+ "VARIANT.TOPIC='"+escapeSQL(id)+"' and VARIANTID=VARIANT order by VARIANTID"); HashSet<Collection<String>> scopes=new LinkedHashSet<Collection<String>>(); HashSet<String> delete=new LinkedHashSet<String>(); String oldVariant="dummy"; Collection<String> scope=null; for(Map<String,Object> row : res){ String vid=(String)row.get("VARIANT"); if(!vid.equals(oldVariant)){ if(scope!=null){ if(scopes.contains(scope)) delete.add(oldVariant); else scopes.add(scope); } scope=new LinkedHashSet<String>(); oldVariant=vid; } scope.add((String)row.get("TOPIC")); } if(scope!=null){ if(scopes.contains(scope)) delete.add(oldVariant); } if(!delete.isEmpty()){ String col=topicMap.collectionToSQL(delete); topicMap.executeUpdate("delete from VARIANTSCOPE where VARIANT in "+col); topicMap.executeUpdate("delete from VARIANT where VARIANTID in "+col); } } // remove merged topic try{ t.remove(); }catch(TopicInUseException e){ System.out.println("ERROR couldn't delete merged topic, topic in use. There is a bug in the code if this happens. "+e.getReason()); } sisFetched=false; full=false; makeFull(); topicMap.topicChanged(this); } @Override public void removeSubjectIdentifier(Locator l) throws TopicMapException { if( removed ) throw new TopicRemovedException(); if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); if(l == null) return; subjectIdentifiers.remove(l); topicMap.executeUpdate("delete from SUBJECTIDENTIFIER where SI='"+escapeSQL(l.toExternalForm())+"'"); topicMap.topicSubjectIdentifierChanged(this,null,l); topicMap.topicSIChanged(this, l,null); } @Override public String getBaseName(){ return baseName; } @Override public void setBaseName(String name) throws TopicMapException { if( removed ) throw new TopicRemovedException(); if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); if(name==null){ if(baseName!=null){ String old=baseName; internalSetBaseName(null); topicMap.executeUpdate("update TOPIC " +"set BASENAME=null " +"where TOPICID='"+escapeSQL(id)+"'"); topicMap.topicBaseNameChanged(this,null,old); } return; } if(baseName==null || !baseName.equals(name)){ Topic t=topicMap.getTopicWithBaseName(name); if(t!=null){ mergeIn(t); } String old=baseName; internalSetBaseName(name); topicMap.executeUpdate("update TOPIC " +"set BASENAME='"+escapeSQL(name)+"' " +"where TOPICID='"+escapeSQL(id)+"'"); topicMap.topicBaseNameChanged(this,name,old); } } @Override public Collection<Topic> getTypes() throws TopicMapException { if(!full) makeFull(); return types; } @Override public void addType(Topic t) throws TopicMapException { if( removed ) throw new TopicRemovedException(); if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); if(t == null) return; if(!full) makeFull(); if(!types.contains(t)){ types.add(t); topicMap.executeUpdate("insert into TOPICTYPE (TOPIC,TYPE) values ('"+ escapeSQL(id)+"','"+escapeSQL(t.getID())+"')"); topicMap.topicTypeChanged(this,t,null); } } @Override public void removeType(Topic t) throws TopicMapException { if( removed ) throw new TopicRemovedException(); if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); if(t == null) return; if(!full) makeFull(); if(types.contains(t)){ types.remove(t); topicMap.executeUpdate("delete from TOPICTYPE " +"where TOPIC='"+escapeSQL(id)+"' " +"and TYPE='"+escapeSQL(t.getID())+"'"); topicMap.topicTypeChanged(this,null,t); } } @Override public boolean isOfType(Topic t) throws TopicMapException { if(t == null) return false; if(!full) makeFull(); return types.contains(t); } @Override public String getVariant(Set<Topic> scope) throws TopicMapException { if(!full) makeFull(); T2<String,String> variant = variants.get(scope); if(variant != null) return variant.e1; return null; } @Override public void setVariant(Set<Topic> scope,String name) throws TopicMapException { if( removed ) throw new TopicRemovedException(); if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); if(!full) makeFull(); String old=null; if(variants.get(scope)!=null){ String vid=variants.get(scope).e2; topicMap.executeUpdate("update VARIANT set VALUE='"+escapeSQL(name)+"' where VARIANTID='"+escapeSQL(vid)+"'"); old=variants.put(scope,t2(name,vid)).e1; } else{ String vid=makeID(); topicMap.executeUpdate("insert into VARIANT (VARIANTID,TOPIC,VALUE) values ('"+ escapeSQL(vid)+"','"+escapeSQL(id)+"','"+escapeSQL(name)+"')"); for(Topic s : scope){ topicMap.executeUpdate("insert into VARIANTSCOPE (VARIANT,TOPIC) values ('"+ escapeSQL(vid)+"','"+escapeSQL(s.getID())+"')"); } variants.put(scope,t2(name,vid)); } topicMap.topicVariantChanged(this,scope,name,old); } @Override public Set<Set<Topic>> getVariantScopes() throws TopicMapException { if(!full) makeFull(); return variants.keySet(); } @Override public void removeVariant(Set<Topic> scope) throws TopicMapException { if( removed ) throw new TopicRemovedException(); if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); if(!full) makeFull(); T2<String,String> v=variants.get(scope); if(v!=null){ topicMap.executeUpdate("delete from VARIANTSCOPE where VARIANT='"+escapeSQL(v.e2)+"'"); topicMap.executeUpdate("delete from VARIANT where VARIANTID='"+escapeSQL(v.e2)+"'"); variants.remove(scope); topicMap.topicVariantChanged(this,scope,null,v.e1); } } @Override public String getData(Topic type,Topic version) throws TopicMapException { if(type == null || version == null) return null; if(!full) makeFull(); Hashtable<Topic,String> td=data.get(type); if(td==null) return null; return td.get(version); } @Override public Hashtable<Topic,String> getData(Topic type) throws TopicMapException { if(!full) makeFull(); if(data.contains(type)) { return data.get(type); } else { return new Hashtable(); } } @Override public Collection<Topic> getDataTypes() throws TopicMapException { if(!full) makeFull(); return data.keySet(); } @Override public void setData(Topic type,Hashtable<Topic,String> versionData) throws TopicMapException { if( removed ) throw new TopicRemovedException(); if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); for(Map.Entry<Topic,String> e : versionData.entrySet()){ setData(type,e.getKey(),e.getValue()); } } @Override public void setData(Topic type,Topic version,String value) throws TopicMapException { if( removed ) throw new TopicRemovedException(); if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); if(!dataFetched) fetchData(); if(getData(type,version)!=null){ topicMap.executeUpdate("update DATA set DATA='"+escapeSQL(value)+"' " +"where TOPIC='"+escapeSQL(id)+"' " +"and TYPE='"+escapeSQL(type.getID())+"' " +"and VERSION='"+escapeSQL(version.getID())+"'"); } else{ topicMap.executeUpdate("insert into DATA (DATA,TOPIC,TYPE,VERSION) values ("+ "'"+escapeSQL(value)+"','"+escapeSQL(id)+"','"+escapeSQL(type.getID())+"','"+ escapeSQL(version.getID())+"')"); } Hashtable<Topic,String> dt=data.get(type); if(dt==null) { dt=new Hashtable<Topic,String>(); data.put(type,dt); } String old=dt.put(version,value); topicMap.topicDataChanged(this,type,version,value,old); } @Override public void removeData(Topic type,Topic version) throws TopicMapException { if( removed ) throw new TopicRemovedException(); if( topicMap.isReadOnly() ) throw new TopicMapReadOnlyException(); if(type == null || version == null) return; if(!full) makeFull(); if(getData(type,version)!=null){ topicMap.executeUpdate("delete from DATA " +"where TOPIC='"+escapeSQL(id)+"' " +"and TYPE='"+escapeSQL(type.getID())+"' " +"and VERSION='"+escapeSQL(version.getID())+"'"); String old=data.get(type).remove(version); Hashtable<Topic,String> datas = data.get(type); if(datas != null && datas.isEmpty()) { data.remove(type); } topicMap.topicDataChanged(this,type,version,null,old); } } @Override public void removeData(Topic type) throws TopicMapException { if( removed ) throw new TopicRemovedException(); if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); if(type == null) return; if(!full) makeFull(); if(getData(type)!=null){ topicMap.executeUpdate("delete from DATA " +"where TOPIC='"+escapeSQL(id)+"' " +"and TYPE='"+escapeSQL(type.getID())+"'"); Hashtable<Topic,String> old=data.remove(type); for(Map.Entry<Topic,String> e : old.entrySet()){ topicMap.topicDataChanged(this,type,e.getKey(),null,e.getValue()); } } } @Override public Locator getSubjectLocator(){ return subjectLocator; } @Override public void setSubjectLocator(Locator l) throws TopicMapException { if( removed ) throw new TopicRemovedException(); if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); if(l==null){ if(subjectLocator!=null){ Locator old=subjectLocator; subjectLocator=null; topicMap.executeUpdate("update TOPIC set SUBJECTLOCATOR=null where TOPICID='"+escapeSQL(id)+"'"); topicMap.topicSubjectLocatorChanged(this,l,old); } return; } if(subjectLocator==null || !subjectLocator.equals(l)){ Topic t=topicMap.getTopicBySubjectLocator(l); if(t!=null){ mergeIn(t); } Locator old=subjectLocator; subjectLocator=l; topicMap.executeUpdate("update TOPIC set SUBJECTLOCATOR='"+escapeSQL(l.toExternalForm())+"' where TOPICID='"+escapeSQL(id)+"'"); topicMap.topicSubjectLocatorChanged(this,l,old); } } @Override public TopicMap getTopicMap(){ return topicMap; } @Override public Collection<Association> getAssociations() throws TopicMapException { // if(!full) makeFull(); Set<Association> ret=new LinkedHashSet(); Hashtable<Topic,Hashtable<Topic,Collection<Association>>> associations=fetchAssociations(); for(Map.Entry<Topic,Hashtable<Topic,Collection<Association>>> e : associations.entrySet()){ for(Map.Entry<Topic,Collection<Association>> e2 : e.getValue().entrySet()){ for(Association a : e2.getValue()){ ret.add(a); } } } return ret; } @Override public Collection<Association> getAssociations(Topic type) throws TopicMapException { if(type == null) return null; // if(!full) makeFull(); Set<Association> ret=new LinkedHashSet(); Hashtable<Topic,Hashtable<Topic,Collection<Association>>> associations=fetchAssociations(); if(associations.get(type)==null) { return new Vector<Association>(); } for(Map.Entry<Topic,Collection<Association>> e2 : associations.get(type).entrySet()){ for(Association a : e2.getValue()){ ret.add(a); } } return ret; } @Override public Collection<Association> getAssociations(Topic type,Topic role) throws TopicMapException { if(type == null || role == null) return null; // if(!full) makeFull(); Hashtable<Topic,Hashtable<Topic,Collection<Association>>> associations=fetchAssociations(); Hashtable<Topic,Collection<Association>> as=associations.get(type); if(as==null) { return new ArrayList<Association>(); } Collection<Association> ret=as.get(role); if(ret==null) { return new ArrayList<Association>(); } return ret; } @Override public void remove() throws TopicMapException { if( removed ) throw new TopicRemovedException(); if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); if(!isDeleteAllowed()) throw new TopicInUseException(this); String eid=escapeSQL(id); topicMap.executeUpdate("delete from VARIANTSCOPE where VARIANT in (select VARIANTID from VARIANT where TOPIC='"+eid+"')"); topicMap.executeUpdate("delete from VARIANT where VARIANTID='"+eid+"'"); topicMap.executeUpdate("delete from DATA where TOPIC='"+eid+"'"); topicMap.executeUpdate("delete from TOPICTYPE where TOPIC='"+eid+"'"); topicMap.executeUpdate("delete from SUBJECTIDENTIFIER where TOPIC='"+eid+"'"); Collection<Map<String,Object>> res=topicMap.executeQuery("select distinct ASSOCIATIONID " +"from ASSOCIATION,MEMBER " +"where MEMBER.PLAYER='"+eid+"' " +"and MEMBER.ASSOCIATION=ASSOCIATION.ASSOCIATIONID"); String[] aid=new String[res.size()]; int counter=0; for(Map<String,Object> row : res){ aid[counter++]=row.get("ASSOCIATIONID").toString(); } for(int i=0;i<aid.length;i+=50){ String c=""; for(int j=i;j<aid.length && j<i+50;j++){ if(c.length()>0) c+=","; c+="'"+escapeSQL(aid[j])+"'"; } topicMap.executeUpdate("delete from MEMBER where ASSOCIATION in ("+c+")"); topicMap.executeUpdate("delete from ASSOCIATION where ASSOCIATIONID in ("+c+")"); } topicMap.executeUpdate("delete from TOPIC where TOPICID='"+eid+"'"); removed=true; topicMap.topicRemoved(this); } @Override public long getEditTime(){ return 0; // TODO: what to do with edittimes? store in db? } @Override public void setEditTime(long time){ } @Override public long getDependentEditTime(){ return 0; } @Override public void setDependentEditTime(long time){ } @Override public boolean isRemoved(){ return removed; } @Override public boolean isDeleteAllowed() throws TopicMapException { String eid=escapeSQL(id); Collection<Map<String,Object>> res=topicMap.executeQuery( "select TOPICID from TOPIC where TOPICID='"+eid+"' and ("+ "exists (select * from VARIANTSCOPE where TOPIC='"+eid+"') or "+ "exists (select * from DATA where TYPE='"+eid+"' or VERSION='"+eid+"') or "+ "exists (select * from TOPICTYPE where TYPE='"+eid+"') or "+ // "exists (select * from MEMBER where PLAYER='"+eid+"' or ROLE='"+eid+"') or "+ "exists (select * from MEMBER where ROLE='"+eid+"') or "+ "exists (select * from ASSOCIATION where TYPE='"+eid+"') )"); if(!res.isEmpty()) return false; return true; } @Override public Collection<Topic> getTopicsWithDataType() throws TopicMapException { return topicMap.queryTopic("select TOPIC.* " + "from TOPIC,DATA " + "where TOPICID=TOPIC " + "and TYPE='"+escapeSQL(id)+"'"); } @Override public Collection<Association> getAssociationsWithType() throws TopicMapException { return topicMap.queryAssociation("select ASSOCIATION.* " + "from ASSOCIATION " + "where TYPE='"+escapeSQL(id)+"'"); } @Override public Collection<Association> getAssociationsWithRole() throws TopicMapException { return topicMap.queryAssociation("select ASSOCIATION.* " +"from ASSOCIATION,MEMBER " +"where ASSOCIATION=ASSOCIATIONID " +"and ROLE='"+escapeSQL(id)+"'"); } @Override public Collection<Topic> getTopicsWithDataVersion() throws TopicMapException { return topicMap.queryTopic("select TOPIC.* " +"from TOPIC,DATA " +"where TOPICID=TOPIC " +"and VERSION='"+escapeSQL(id)+"'"); } @Override public Collection<Topic> getTopicsWithVariantScope() throws TopicMapException { return topicMap.queryTopic("select distinct TOPIC.* " +"from TOPIC,VARIANT,VARIANTSCOPE " +"where TOPIC.TOPICID=VARIANT.TOPIC " +"and VARIANT.VARIANTID=VARIANTSCOPE.VARIANT " +"and VARIANTSCOPE.TOPIC='"+escapeSQL(id)+"'"); } void associationChanged(DatabaseAssociation a,Topic type,Topic oldType,Topic role,Topic oldRole){ Hashtable<Topic,Hashtable<Topic,Collection<Association>>> associations=null; if(storedAssociations!=null){ associations=storedAssociations.get(); if(associations==null) return; } else return; Hashtable<Topic,Collection<Association>> t=null; Collection<Association> c=null; if(oldType!=null){ t=associations.get(oldType); c=t.get(oldRole); c.remove(a); // remove c from t if it becomes empty? } if(type!=null){ t=associations.get(type); if(t==null){ t=new Hashtable<Topic,Collection<Association>>(); associations.put(type,t); } c=t.get(role); if(c==null){ c=new LinkedHashSet<Association>(); t.put(role,c); } c.add(a); } storedAssociations=new WeakReference(associations); } void removeDuplicateAssociations() throws TopicMapException { if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException(); Set<EqualAssociationWrapper> as=new LinkedHashSet<EqualAssociationWrapper>(); Set<Association> delete=new LinkedHashSet<Association>(); for(Association a : getAssociations()) { if(!as.add(new EqualAssociationWrapper((DatabaseAssociation)a))){ delete.add(a); } } for(Association a : delete) a.remove(); } /* public int hashCode(){ return id.hashCode(); } public boolean equals(Object o){ if(o instanceof DatabaseTopic){ return ((DatabaseTopic)o).id.equals(id); } else return false; }*/ private class EqualAssociationWrapper { public DatabaseAssociation a; private int hashCode=0; public EqualAssociationWrapper(DatabaseAssociation a){ this.a=a; } @Override public boolean equals(Object o){ if(o==null) return false; if(hashCode()!=o.hashCode()) return false; return a._equals(((EqualAssociationWrapper)o).a); } @Override public int hashCode(){ if(hashCode!=0) return hashCode; else { hashCode=a._hashCode(); return hashCode; } } } }
49,323
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicMapSQLException.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/database/TopicMapSQLException.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * TopicMapSQLException.java * * Created on 15. toukokuuta 2006, 14:47 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package org.wandora.topicmap.database; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public class TopicMapSQLException extends TopicMapException { /** Creates a new instance of TopicMapSQLException */ public TopicMapSQLException() { } public TopicMapSQLException(String s) { super(s); } public TopicMapSQLException(Throwable cause){ super(cause); } public TopicMapSQLException(String s,Throwable cause){ super(s,cause); } }
1,510
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
WeakTopicIndex.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/database/WeakTopicIndex.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * WeakTopicIndex.java * * Created on 14. marraskuuta 2005, 13:54 */ package org.wandora.topicmap.database; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; import org.wandora.utils.MultiHashMap; /** * <p> * WeakTopicIndex keeps an index of every topic and association created with it. * Database topic map creates all topics and associations with it instead of * creating them directly. The index is done * with <code>WeakReference</code>s so that Java garbage collector can collect * the indexed topics at any time if there are no strong references to them * elsewhere. With this kind of index, it is possible to make sure that * at any time there is at most one topic object for each individual topic in the * database but at the same time allow garbage collector to clean topics that are * not referenced anywhere else than the index. * </p> * <p> * WeakTopicIndex needs to have a cleaner thread running that cleans the WeakReferences * when garbage collector has collected the referred objects. * </p> * <p> * In addition, a strong reference to 2000 most used topics is maintained. This * acts as a sort of cache to keep frequently accessed topics in memory even if * strong references are not kept outside the index. This cache is maintained with * the <code>WeakTopicIndex.CacheList</code> class. * </p> * * @author olli */ public class WeakTopicIndex implements Runnable { /** * <p> * Cache list is a list of objects where the most used objects are at the top * of the list and least used objects are at the bottom. New objects are * added somewhere in the middle but near the bottom. Objects are accessed * which either moves them up in the list or adds them at the specified * add point if they are not in the list allready. * </p><p> * The idea is that a limited number of objects from a very large object pool * are kept in memeory and it is prefered that objects that are used the most * stay in the list while objects that are used little fall off the list. * Objects are not added right at the bottom to avoid them being falling off * the list straight away and not having any chance of moving up. * </p><p> * List is implemented as a linked list with pointers to the top, bottom * and the marked add position. * </p> */ public static class CacheList<E> { private static class ListItem<E> { public ListItem<E> next=null; public ListItem<E> prev=null; public E item; public ListItem(E item){ this.item=item; } } /** The maximum size of the list */ public static final int cacheSize=2000; /** The position at which new objects are added */ public static final int markPos=200; private int size=0; private ListItem<E> last=null; private ListItem<E> first=null; private ListItem<E> mark=null; private HashMap<E,ListItem<E>> map; public CacheList(){ map=new HashMap<E,ListItem<E>>(cacheSize); } private void addAtMark(E e){ ListItem<E> item=new ListItem<E>(e); if(size<=markPos){ if(last==null) last=first=item; else{ last.next=item; item.prev=last; last=item; } if(size==markPos) mark=item; size++; } else if(size<cacheSize){ item.prev=mark.prev; mark.prev.next=item; mark.prev=item; item.next=mark; mark=item; size++; } else{ item.next=mark.next; mark.next.prev=item; mark.next=item; item.prev=mark; mark=item; map.remove(first.item); first=first.next; first.prev=null; } map.put(e,item); } private void moveUp(ListItem<E> item){ if(item.next==null) return; /* Order before | order after * a a <- may be null * b c=item * c=item b * d d <- may be null */ ListItem<E> a=item.next.next; ListItem<E> b=item.next; ListItem<E> c=item; ListItem<E> d=item.prev; if(a!=null) a.prev=c; c.prev=b; b.prev=d; c.next=a; b.next=c; if(d!=null) d.next=b; if(b==mark) mark=c; else if(c==mark) mark=b; if(b==last) last=c; if(c==first) first=b; } /** * Accesses an object moving it up in the list or adding it to the * list if it isn't in it yet. */ public void access(E e){ ListItem<E> item=map.get(e); if(item!=null) { moveUp(item); // System.out.println("CACHE move up "+size); } else { // System.out.println("CACHE add at mark "+size); addAtMark(e); } } public int size(){ return size; } public void printDebugInfo(){ ListItem<E> prev=null; ListItem<E> item=first; int counter1=0; HashSet<E> uniqTest=new HashSet<E>(); while(item!=null){ uniqTest.add(item.item); prev=item; item=item.next; counter1++; } boolean check1=(prev==last); item=last; int counter2=0; while(item!=null){ prev=item; item=item.prev; counter2++; } boolean check2=(prev==first); System.out.println("Cachelist size "+counter1+", "+counter2+", "+size+", "+uniqTest.size()+", "+check1+", "+check2+")"); } } private boolean running; private Thread thread; // reference queue for topics to receive notifications when topics are garbage collected private ReferenceQueue<DatabaseTopic> topicRefQueue; // map to get topics with their IDs private HashMap<String,WeakReference<DatabaseTopic>> topicIDIndex; // map to get topics with their subject identifiers private HashMap<Locator,WeakReference<DatabaseTopic>> topicSIIndex; // map to get topics with their base names private HashMap<String,WeakReference<DatabaseTopic>> topicBNIndex; /* Inverse indexes are needed to get the id/si/base name of previously stored * topics with the WeakReferenc after the reference has been cleared and the * actual topic is not anymore available. */ private HashMap<WeakReference<DatabaseTopic>,String> topicInvIDIndex; private MultiHashMap<WeakReference<DatabaseTopic>,Locator> topicInvSIIndex; private HashMap<WeakReference<DatabaseTopic>,String> topicInvBNIndex; // reference queue for associations to receive notifications when associations are garbage collected private ReferenceQueue<DatabaseAssociation> associationRefQueue; // map to get oassociationns with their IDs private HashMap<String,WeakReference<DatabaseAssociation>> associationIDIndex; // inverse index for associations private HashMap<WeakReference<DatabaseAssociation>,String> associationInvIDIndex; /** * A CacheList that keeps (strong) references to topics so they do not get * carbage collected. This keeps (roughly speaking) the 2000 most used * topics in memory at all times and allows them to be retrieved quickly * from the weak indexes. Without keeping strong references to them they * would be garbage collected and the indexes would be of little use. */ private CacheList<DatabaseTopic> topicCache; /** * if references queues are being used, that is if we are keeping track * of topics/associations that have been garbage collected */ private boolean useRefQueue=true; /** Creates a new instance of WeakTopicIndex */ public WeakTopicIndex() { useRefQueue=true; topicIDIndex=new HashMap<String,WeakReference<DatabaseTopic>>(); topicSIIndex=new HashMap<Locator,WeakReference<DatabaseTopic>>(); topicBNIndex=new HashMap<String,WeakReference<DatabaseTopic>>(); topicInvIDIndex=new HashMap<WeakReference<DatabaseTopic>,String>(); topicInvSIIndex=new MultiHashMap<WeakReference<DatabaseTopic>,Locator>(); topicInvBNIndex=new HashMap<WeakReference<DatabaseTopic>,String>(); associationIDIndex=new HashMap<String,WeakReference<DatabaseAssociation>>(); associationInvIDIndex=new HashMap<WeakReference<DatabaseAssociation>,String>(); topicCache=new CacheList<DatabaseTopic>(); if(useRefQueue){ running=true; thread=new Thread(this); topicRefQueue=new ReferenceQueue<DatabaseTopic>(); associationRefQueue=new ReferenceQueue<DatabaseAssociation>(); thread.start(); } else{ running=false; topicRefQueue=null; associationRefQueue=null; } } /** * Clears the topic cache allowing any topic that isn't (strongly) referenced * elsewhere to be gargbage collected and removed from the index. * Note that this does not actually clear the index. */ public void clearTopicCache(){ topicCache=new CacheList<DatabaseTopic>(); } /** * Stops the thread that is cleaning indexes of topics/associations that have * been garbage collected. */ public void stopCleanerThread(){ if(useRefQueue){ System.out.println("Stopping index cleaner"); useRefQueue=false; topicInvIDIndex=null; topicInvSIIndex=null; topicInvBNIndex=null; associationInvIDIndex=null; running=false; if(thread!=null) thread.interrupt(); thread=null; topicRefQueue=null; associationRefQueue=null; } } /** * Restarts the thread that is cleaning indexes of topics/associations that * have been garbage collected. */ public void startCleanerThread(){ if(!useRefQueue){ System.out.println("Starting index cleaner"); useRefQueue=true; running=false; if(thread!=null) thread.interrupt(); HashMap<String,WeakReference<DatabaseTopic>> newTopicIDIndex=new HashMap<String,WeakReference<DatabaseTopic>>(); HashMap<WeakReference<DatabaseTopic>,String> newTopicInvIDIndex=new HashMap<WeakReference<DatabaseTopic>,String>(); HashMap<String,WeakReference<DatabaseAssociation>> newAssociationIDIndex=new HashMap<String,WeakReference<DatabaseAssociation>>(); HashMap<WeakReference<DatabaseAssociation>,String> newAssociationInvIDIndex=new HashMap<WeakReference<DatabaseAssociation>,String>(); topicRefQueue=new ReferenceQueue<DatabaseTopic>(); associationRefQueue=new ReferenceQueue<DatabaseAssociation>(); for(WeakReference<DatabaseTopic> ref : topicIDIndex.values()){ DatabaseTopic t=ref.get(); if(t==null) continue; WeakReference<DatabaseTopic> r=new WeakReference<DatabaseTopic>(t,topicRefQueue); newTopicIDIndex.put(t.getID(),r); newTopicInvIDIndex.put(r,t.getID()); } for(WeakReference<DatabaseAssociation> ref : associationIDIndex.values()){ DatabaseAssociation a=ref.get(); if(a==null) continue; WeakReference<DatabaseAssociation> r=new WeakReference<DatabaseAssociation>(a,associationRefQueue); newAssociationIDIndex.put(a.getID(),r); newAssociationInvIDIndex.put(r,a.getID()); } topicIDIndex=newTopicIDIndex; topicInvIDIndex=newTopicInvIDIndex; associationIDIndex=newAssociationIDIndex; associationInvIDIndex=newAssociationInvIDIndex; topicSIIndex=new HashMap<Locator,WeakReference<DatabaseTopic>>(); topicBNIndex=new HashMap<String,WeakReference<DatabaseTopic>>(); topicInvSIIndex=new MultiHashMap<WeakReference<DatabaseTopic>,Locator>(); topicInvBNIndex=new HashMap<WeakReference<DatabaseTopic>,String>(); thread=new Thread(this); running=true; thread.start(); } } /** * If the indexes are complete. Note that even though they are complete some * of the indexed topics/associations may have been garbage collected and * index only contains information that something has been in there. * This makes it possible to determine if some topic exists but isn't * anymore in the index or if it doesn't exist. */ public boolean isFullIndex(){ return !useRefQueue; } public void destroy(){ running=false; } /** * Creates a new topic and adds it to the index. */ public synchronized DatabaseTopic newTopic(String id, DatabaseTopicMap tm) throws TopicMapException { if(topicIDIndex.containsKey(id)) { WeakReference<DatabaseTopic> ref = topicIDIndex.get(id); return topicAccessed(ref.get()); } else { DatabaseTopic t=new DatabaseTopic(id,tm); t.create(); WeakReference<DatabaseTopic> ref=new WeakReference<DatabaseTopic>(t,topicRefQueue); topicIDIndex.put(t.getID(),ref); if(useRefQueue) topicInvIDIndex.put(ref,t.getID()); return topicAccessed(t); } } /** * Creates a new topic and adds it to the index. */ public synchronized DatabaseTopic newTopic(DatabaseTopicMap tm) throws TopicMapException { DatabaseTopic t=new DatabaseTopic(tm); t.create(); WeakReference<DatabaseTopic> ref=new WeakReference<DatabaseTopic>(t,topicRefQueue); topicIDIndex.put(t.getID(),ref); if(useRefQueue) topicInvIDIndex.put(ref,t.getID()); return topicAccessed(t); } /** * Accesses a topic moving it up or adding it to the CacheList. */ private synchronized DatabaseTopic topicAccessed(DatabaseTopic topic){ if(topic==null) return null; topicCache.access(topic); // topicCache.printDebugInfo(); return topic; } /** * Constructs a DatabaseTopic with the given ID. */ public synchronized DatabaseTopic createTopic(String id,DatabaseTopicMap tm){ DatabaseTopic t=getTopicWithID(id); if(t!=null) return topicAccessed(t); t=new DatabaseTopic(id,tm); WeakReference<DatabaseTopic> ref=new WeakReference<DatabaseTopic>(t,topicRefQueue); topicIDIndex.put(id,ref); if(useRefQueue) topicInvIDIndex.put(ref,id); return topicAccessed(t); } /* The containsKey method check if the appropriate index contains an entry * with the given key. The isNull methods check if the index returns null * for the key, that is either they don't have an entry for the key or they * have a null entry. Use containsKey methods to distinguish between the two. * The getTopicWith methods get a topic from the appropriate index and * return null if the index doesn't have an entry for the key, the entry * is null or the entry is a WeakReference that has been cleared but not * yet cleaned by the cleaner thread. */ /* addNull methods can be used to add null entries in the index. These should * be interpreted to mean that a topic does not exist with the given key. */ /* topic*Changed and topicRemoved methods are used to update indexes according * to changes in the topic map. */ public synchronized DatabaseTopic getTopicWithID(String id){ WeakReference<DatabaseTopic> ref=topicIDIndex.get(id); if(ref!=null) { return topicAccessed(ref.get()); } else return null; } public synchronized boolean containsKeyWithID(String id){ return topicIDIndex.containsKey(id); } public synchronized boolean containsKeyWithSI(Locator si){ return topicSIIndex.containsKey(si); } public synchronized boolean containsKeyWithBN(String bn){ return topicBNIndex.containsKey(bn); } public synchronized boolean isNullSI(Locator si){ return topicSIIndex.get(si)==null; } public synchronized boolean isNullBN(String bn){ return topicBNIndex.get(bn)==null; } public synchronized DatabaseTopic getTopicWithSI(Locator si){ WeakReference<DatabaseTopic> ref=topicSIIndex.get(si); if(ref!=null) { return topicAccessed(ref.get()); } else return null; } public synchronized DatabaseTopic getTopicWithBN(String bn){ WeakReference<DatabaseTopic> ref=topicBNIndex.get(bn); if(ref!=null) { return topicAccessed(ref.get()); } else return null; } public synchronized void topicSIChanged(DatabaseTopic t,Locator deleted,Locator added){ if(deleted!=null && topicSIIndex.containsKey(deleted) && (topicSIIndex.get(deleted)==null || topicSIIndex.get(deleted).get()==t)) { WeakReference<DatabaseTopic> tref=topicSIIndex.get(deleted); if(tref!=null && useRefQueue) topicInvSIIndex.remove(tref); topicSIIndex.remove(deleted); } if(added!=null) { WeakReference<DatabaseTopic> ref=topicIDIndex.get(t.getID()); topicSIIndex.put(added,ref); if(useRefQueue) topicInvSIIndex.addUniq(ref,added); } } public synchronized void addNullSI(Locator si){ topicSIIndex.put(si,null); } public synchronized void addNullBN(String bn){ topicBNIndex.put(bn,null); } public synchronized void topicBNChanged(Topic t,String old) throws TopicMapException { if(old!=null && topicBNIndex.containsKey(old) && (topicBNIndex.get(old)==null || topicBNIndex.get(old).get()==t)) { WeakReference<DatabaseTopic> tref=topicBNIndex.get(old); if(tref!=null && useRefQueue) topicInvBNIndex.remove(tref); topicBNIndex.remove(old); } if(t.getBaseName()!=null) { WeakReference<DatabaseTopic> ref=topicIDIndex.get(t.getID()); topicBNIndex.put(t.getBaseName(),ref); if(useRefQueue) topicInvBNIndex.put(ref,t.getBaseName()); } } public synchronized void topicRemoved(Topic t) throws TopicMapException { for(Locator l : t.getSubjectIdentifiers()){ if(topicSIIndex.containsKey(l) && (topicSIIndex.get(l)==null || topicSIIndex.get(l).get()==t)){ WeakReference<DatabaseTopic> tref=topicSIIndex.get(l); if(tref!=null && useRefQueue) topicInvSIIndex.remove(tref); topicSIIndex.remove(l); } } String old=t.getBaseName(); if(old!=null && topicBNIndex.containsKey(old) && (topicBNIndex.get(old)==null || topicBNIndex.get(old).get()==t)) { WeakReference<DatabaseTopic> tref=topicBNIndex.get(old); if(tref!=null && useRefQueue) topicInvBNIndex.remove(tref); topicBNIndex.remove(t.getBaseName()); } } public synchronized DatabaseAssociation newAssociation(DatabaseTopic type,DatabaseTopicMap tm) throws TopicMapException { DatabaseAssociation a=new DatabaseAssociation(type,tm); a.create(); WeakReference<DatabaseAssociation> ref=new WeakReference<DatabaseAssociation>(a,associationRefQueue); associationIDIndex.put(a.getID(),ref); if(useRefQueue) associationInvIDIndex.put(ref,a.getID()); return a; } public synchronized DatabaseAssociation createAssociation(String id,DatabaseTopicMap tm){ DatabaseAssociation a=getAssociation(id,tm); if(a!=null) return a; a=new DatabaseAssociation(id,tm); WeakReference<DatabaseAssociation> ref=new WeakReference<DatabaseAssociation>(a,associationRefQueue); associationIDIndex.put(id,ref); if(useRefQueue) associationInvIDIndex.put(ref,id); return a; } public synchronized DatabaseAssociation getAssociation(String id,DatabaseTopicMap tm){ WeakReference<DatabaseAssociation> ref=associationIDIndex.get(id); if(ref!=null) { return ref.get(); } else return null; } /** * Removes entries that refer to the given WeakReferenc from topic indexes. * This is used after a topic has been gargbage collected and it is not needed * anymore in the indexes. */ private synchronized void removeTopicKey(Reference<? extends DatabaseTopic> ref){ // System.out.println("Removing topic from index"); String id=topicInvIDIndex.get(ref); // will produce null pointer exception if !useRefQueue, but that shouldn't happen if(id!=null) topicIDIndex.remove(id); topicInvIDIndex.remove(ref); String bn=topicInvBNIndex.get(ref); if(bn!=null) topicBNIndex.remove(bn); topicInvBNIndex.remove(ref); Collection<Locator> sis=topicInvSIIndex.get(ref); if(sis!=null){ for(Locator l : sis){ topicSIIndex.remove(l); } } topicInvSIIndex.remove(ref); } private synchronized void removeAssociationKey(Reference<? extends DatabaseAssociation> ref){ // System.out.println("Removing association from index"); String id=associationInvIDIndex.get(ref); if(id!=null) associationIDIndex.remove(id); associationInvIDIndex.remove(ref); } public void printDebugInfo(){ System.out.println("Index sizes "+topicIDIndex.size()+", "+topicInvIDIndex.size()+", "+associationIDIndex.size()+", "+associationInvIDIndex.size()+", "+topicBNIndex.size()+", "+topicInvBNIndex.size()+", "+topicSIIndex.size()+", "+topicInvSIIndex.size()); topicCache.printDebugInfo(); } public void run(){ while(running && Thread.currentThread()==thread){ try{ Reference<? extends DatabaseTopic> ref=topicRefQueue.poll(); if(ref!=null) removeTopicKey(ref); Reference<? extends DatabaseAssociation> ref2=associationRefQueue.poll(); if(ref2!=null) removeAssociationKey(ref2); if(ref==null && ref2==null){ Thread.sleep(1000); } // System.out.println("Index sizes "+topicIDIndex.size()+", "+topicBNIndex.size()+", "+topicSIIndex.size()+", "+associationIDIndex.size()); }catch(InterruptedException ie){} } } }
24,638
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DatabaseTopicMapType.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/database/DatabaseTopicMapType.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * DatabaseTopicMapType.java * * Created on 21. marraskuuta 2005, 13:48 */ package org.wandora.topicmap.database; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.sql.SQLException; import javax.swing.Icon; import javax.swing.JMenu; import javax.swing.JMenuItem; import org.wandora.application.Wandora; import org.wandora.application.gui.DatabaseConfigurationPanel; import org.wandora.application.gui.UIBox; import org.wandora.application.tools.layers.MakeSIConsistentTool; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapConfigurationPanel; import org.wandora.topicmap.TopicMapLogger; import org.wandora.topicmap.TopicMapType; import org.wandora.topicmap.packageio.PackageInput; import org.wandora.topicmap.packageio.PackageOutput; import org.wandora.utils.Options; import org.wandora.utils.Tuples.T2; /** * * @author olli */ public class DatabaseTopicMapType implements TopicMapType { /** Creates a new instance of DatabaseTopicMapType */ public DatabaseTopicMapType() { } @Override public String getTypeName(){ return "Database (deprecated)"; } @Override public TopicMap createTopicMap(Object params){ DatabaseConfigurationPanel.StoredConnection sc=(DatabaseConfigurationPanel.StoredConnection)params; if(sc != null) { T2<String,String> conInfo=DatabaseConfigurationPanel.getConnectionDriverAndString(sc); if(conInfo != null) { try { return new DatabaseTopicMap(conInfo.e1,conInfo.e2,sc.user,sc.pass,sc.script,params); } catch(java.sql.SQLException sqle) { sqle.printStackTrace(); } } } return null; } @Override public TopicMap modifyTopicMap(TopicMap tm, Object params) { TopicMap ret=createTopicMap(params); ret.addTopicMapListeners(tm.getTopicMapListeners()); return ret; } @Override public TopicMapConfigurationPanel getConfigurationPanel(Wandora admin, Options options){ DatabaseConfiguration dc=new DatabaseConfiguration(admin, options); return dc; } @Override public TopicMapConfigurationPanel getModifyConfigurationPanel(Wandora wandora, Options options, TopicMap tm) { DatabaseConfigurationPanel dcp=new DatabaseConfigurationPanel(wandora); DatabaseTopicMap dtm=(DatabaseTopicMap)tm; Object params=dtm.getConnectionParams(); if(params==null){ params=DatabaseConfigurationPanel.StoredConnection.generic( "Unknown connection", DatabaseConfigurationPanel.GENERIC_TYPE, dtm.getDBDriver(), dtm.getDBConnectionString(), dtm.getDBUser(), dtm.getDBPassword() ); } return dcp.getEditConfigurationPanel(params); } @Override public String toString(){return getTypeName();} @Override public void packageTopicMap(TopicMap tm, PackageOutput out, String path, TopicMapLogger logger) throws IOException { DatabaseTopicMap dtm=(DatabaseTopicMap)tm; Options options=new Options(); Object params=dtm.getConnectionParams(); if(params!=null) { DatabaseConfigurationPanel.StoredConnection p=(DatabaseConfigurationPanel.StoredConnection)params; p.writeOptions(options,"params."); } else { options.put("driver",dtm.getDBDriver()); options.put("connectionstring",dtm.getDBConnectionString()); options.put("user",dtm.getDBUser()); options.put("password",dtm.getDBPassword()); } out.nextEntry(path, "dboptions.xml"); options.save(new java.io.OutputStreamWriter(out.getOutputStream())); } @Override public TopicMap unpackageTopicMap(TopicMap topicmap, PackageInput in, String path, TopicMapLogger logger, Wandora wandora) throws IOException { in.gotoEntry(path, "dboptions.xml"); Options options=new Options(); options.parseOptions(new BufferedReader(new InputStreamReader(in.getInputStream()))); if(options.get("params.name")!=null){ DatabaseConfigurationPanel.StoredConnection p=new DatabaseConfigurationPanel.StoredConnection(); p.readOptions(options,"params."); T2<String,String> conInfo=DatabaseConfigurationPanel.getConnectionDriverAndString(p); try { return new DatabaseTopicMap( conInfo.e1, conInfo.e2, p.user, p.pass, p.script, p ); } catch(SQLException sqle){ logger.log(sqle); return null; } } else { try { DatabaseTopicMap dtm=new DatabaseTopicMap( options.get("driver"), options.get("connectionstring"), options.get("user"), options.get("password")); return dtm; } catch(SQLException sqle){ logger.log(sqle); return null; } } } @Override public TopicMap unpackageTopicMap(PackageInput in, String path, TopicMapLogger logger,Wandora wandora) throws IOException { in.gotoEntry(path, "dboptions.xml"); Options options=new Options(); options.parseOptions(new BufferedReader(new InputStreamReader(in.getInputStream()))); if(options.get("params.name")!=null){ DatabaseConfigurationPanel.StoredConnection p=new DatabaseConfigurationPanel.StoredConnection(); p.readOptions(options,"params."); T2<String,String> conInfo=DatabaseConfigurationPanel.getConnectionDriverAndString(p); try { return new DatabaseTopicMap( conInfo.e1, conInfo.e2, p.user, p.pass, p.script, p ); } catch(SQLException sqle){ logger.log(sqle); return null; } } else { try { DatabaseTopicMap dtm=new DatabaseTopicMap( options.get("driver"), options.get("connectionstring"), options.get("user"), options.get("password")); return dtm; } catch(SQLException sqle){ logger.log(sqle); return null; } } } @Override public JMenuItem[] getTopicMapMenu(TopicMap tm, Wandora wandora){ JMenu menu=UIBox.makeMenu( new Object[]{ "Make SI consistent...", new MakeSIConsistentTool(), }, wandora ); JMenuItem[] items=new JMenuItem[menu.getItemCount()]; for(int i=0;i<items.length;i++){ items[i]=menu.getItem(i); items[i].setIcon(null); } return items; } @Override public Icon getTypeIcon(){ return UIBox.getIcon("gui/icons/layerinfo/layer_type_database.png"); } }
8,479
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DatabaseConfiguration.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/database/DatabaseConfiguration.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * DatabaseConfiguration.java * * Created on 21. marraskuuta 2005, 13:47 */ package org.wandora.topicmap.database; import java.util.Collection; import java.util.Vector; import org.wandora.application.Wandora; import org.wandora.application.gui.DatabaseConfigurationPanel; import org.wandora.topicmap.TopicMapConfigurationPanel; import org.wandora.utils.Options; /** * * @author olli */ public class DatabaseConfiguration extends TopicMapConfigurationPanel { private DatabaseConfigurationPanel confPanel; private Options options; /** Creates new form DatabaseConfiguration */ public DatabaseConfiguration(Wandora wandora, Options options) { initComponents(); this.options=options; confPanel=new DatabaseConfigurationPanel(wandora); initialize(options); this.add(confPanel); } public static Collection<DatabaseConfigurationPanel.StoredConnection> parseConnections(Options options){ Collection<DatabaseConfigurationPanel.StoredConnection> connections= new Vector<DatabaseConfigurationPanel.StoredConnection>(); String prefix="options.dbconnections.connection"; int counter=0; while(true){ String type=options.get(prefix+"["+counter+"].type"); if(type==null) break; String name=options.get(prefix+"["+counter+"].name"); String user=options.get(prefix+"["+counter+"].user"); String pass=options.get(prefix+"["+counter+"].pass"); if(type.equals(DatabaseConfigurationPanel.GENERIC_TYPE)){ String driver=options.get(prefix+"["+counter+"].driver"); String conString=options.get(prefix+"["+counter+"].constring"); String script=options.get(prefix+"["+counter+"].script"); connections.add(DatabaseConfigurationPanel.StoredConnection.generic(name,type,driver,conString,user,pass,script)); } else{ String server=options.get(prefix+"["+counter+"].server"); String database=options.get(prefix+"["+counter+"].database"); connections.add(DatabaseConfigurationPanel.StoredConnection.known(name,type,server,database,user,pass)); } counter++; } return connections; } public void initialize(Options options){ Collection<DatabaseConfigurationPanel.StoredConnection> connections=parseConnections(options); confPanel.setConnections(connections); } public void writeOptions(Options options){ writeOptions(options,confPanel); } public static void writeOptions(Options options,DatabaseConfigurationPanel confPanel){ int counter=0; String prefix="options.dbconnections.connection"; while(true){ String type=options.get(prefix+"["+counter+"].type"); if(type==null) break; options.put(prefix+"["+counter+"].name",null); options.put(prefix+"["+counter+"].type",null); options.put(prefix+"["+counter+"].user",null); options.put(prefix+"["+counter+"].pass",null); options.put(prefix+"["+counter+"].driver",null); options.put(prefix+"["+counter+"].constring",null); options.put(prefix+"["+counter+"].server",null); options.put(prefix+"["+counter+"].database",null); counter++; } Collection<DatabaseConfigurationPanel.StoredConnection> connections=confPanel.getAllConnections(); counter=0; for(DatabaseConfigurationPanel.StoredConnection sc : connections){ options.put(prefix+"["+counter+"].name",sc.name); options.put(prefix+"["+counter+"].type",sc.type); options.put(prefix+"["+counter+"].user",sc.user); options.put(prefix+"["+counter+"].pass",sc.pass); if(sc.type.equals(DatabaseConfigurationPanel.GENERIC_TYPE)){ options.put(prefix+"["+counter+"].driver",sc.driver); options.put(prefix+"["+counter+"].constring",sc.conString); options.put(prefix+"["+counter+"].script",sc.script); } else{ options.put(prefix+"["+counter+"].server",sc.server); options.put(prefix+"["+counter+"].database",sc.database); } counter++; } } public Object getParameters(){ writeOptions(options); DatabaseConfigurationPanel.StoredConnection sc=confPanel.getSelectedConnection(); if(sc==null) return null; return sc; } /** 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() { setLayout(new java.awt.BorderLayout()); } // </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables // End of variables declaration//GEN-END:variables }
6,066
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AmbiguityResolution.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/layered/AmbiguityResolution.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * AmbiguityResolution.java * * Created on 24. lokakuuta 2005, 10:27 */ package org.wandora.topicmap.layered; /** * * @author olli */ public enum AmbiguityResolution { doNothing, addToSelected, addToOther, removeFromOther }
1,061
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
LayerStack.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/layered/LayerStack.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * LayerStack.java * * Created on 8. syyskuuta 2005, 11:31 */ package org.wandora.topicmap.layered; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.Vector; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicIterator; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicMapListener; import org.wandora.topicmap.TopicMapLogger; import org.wandora.topicmap.TopicMapReadOnlyException; import org.wandora.topicmap.TopicMapSearchOptions; import org.wandora.topicmap.TopicMapStatData; import org.wandora.topicmap.TopicMapStatOptions; import org.wandora.topicmap.TopicMapType; import org.wandora.topicmap.TopicMapTypeManager; import org.wandora.topicmap.packageio.PackageInput; import org.wandora.topicmap.packageio.ZipPackageInput; import org.wandora.topicmap.undowrapper.UndoBuffer; import org.wandora.topicmap.undowrapper.UndoException; import org.wandora.topicmap.undowrapper.UndoOperation; import org.wandora.topicmap.undowrapper.UndoTopicMap; import org.wandora.utils.Delegate; import org.wandora.utils.KeyedHashMap; import org.wandora.utils.KeyedHashSet; import org.wandora.utils.Tuples.T2; /** * <p> * LayerStack combines several topic maps (called layers) into one topic map. This * has the advantage of being able to hide and show parts of the topic map when * necessary and keep different kinds of information apart from each other but still * be able to view all the information as a single topic map when needed. * </p><p> * All LayeredTopics consist of a collection of topics from all layers. The collection * may contain any number of topics for any layer. * All methods in LayerStack, LayeredTopic and LayeredAssociation always return * layered objects instead of the objects of different layers except for the method * where it is specifically stated that return value consists of individual topics. * Also all methods expect to receive their parameters as Layered objects instead * of objects of individual layers except when something else is specifically stated. * </p><p> * LayerStack has some requirements about the behavior of equals and hashCode * methods. Objects representing the same topic in the topic map must be equal * when checked with the equals method. Also, the hashCode of of a topic must * not change after the creation of the topic. One way to achieve this is to * use the default equals and hashCode methods and at any time have at most one object for * each topic in the topic map. LayerStack itself doesn't meet these requirements, * hashCode of topics will change when the set of topics it contains changes, * and thus you cannot use LayerStacks as layers in another LayerStack. * </p><p> * Note: <br /> * TopicMapListeners work a bit different in LayerStack than other TopicMap implementations. * Listeners may get changed events even when nothing that is visible using TopicMap interface * methods has changed. For example changing a variant name in any layer will cause topicVariantNameChanged * event even if another layer overrides the name. Also changes to subject identifiers may cause * complex merge or split operations which are reported as a single (or in some cases a few) events. * </p> * @author olli */ public class LayerStack extends ContainerTopicMap implements TopicMapListener { protected boolean useTopicIndex=true; protected Object indexLock=new Object(); /** * Maps subject identifiers to layered topics for fast access in makeLayered. * Contains topics that have recently been used in makeLayered topic. Each * subject identifier of every topic in index is (and must be) indexed. * * General principle with updating index is that when a topic changes, it * is removed from index. That is, mappings from all it's (previous) * subject identifiers is removed. It will be added to index later when * it is used in makeLayered again. Indexes are completely wiped after * significant changes in topic map, such as adding layers or changing * visibility of layers. */ protected Map<Locator,LayeredTopic> topicIndex; /** * All layers in the layer stack. */ protected Vector<Layer> layers; /** * Maps the topic maps of each layer to the layer itself. */ protected Map<TopicMap,Layer> layerIndex; /** * The selected layer. */ protected Layer selectedLayer; /** * All layers that are currently visible, in the order they are in the stack. */ protected Vector<Layer> visibleLayers; protected boolean trackDependent; protected List<TopicMapListener> topicMapListeners; protected List<TopicMapListener> disabledListeners; // private LayerControlPanel controlPanel; private AmbiguityResolver ambiguityResolver; protected ContainerTopicMapListener containerListener; protected boolean useUndo=true; /** Creates a new instance of LayerStack */ public LayerStack(String wandoraProjectFilename) { this(); try { File f = new File(wandoraProjectFilename); PackageInput in=new ZipPackageInput(f); TopicMapType type=TopicMapTypeManager.getType(org.wandora.topicmap.layered.LayerStack.class); TopicMap tm=type.unpackageTopicMap(this, in, "", this,null); in.close(); } catch(Exception e) { e.printStackTrace(); } } public LayerStack() { layers=new Vector<Layer>(); visibleLayers=new Vector<Layer>(); layerIndex=new LinkedHashMap<TopicMap,Layer>(); topicMapListeners=new ArrayList<TopicMapListener>(); containerListener=new ContainerTopicMapListener(){ public void layerAdded(Layer l) { notifyLayersChanged(); fireLayerAdded(l); } public void layerChanged(Layer oldLayer, Layer newLayer) { notifyLayersChanged(); fireLayerChanged(oldLayer,newLayer); } public void layerRemoved(Layer l) { notifyLayersChanged(); fireLayerRemoved(l); } public void layerStructureChanged() { notifyLayersChanged(); fireLayerStructureChanged(); } public void layerVisibilityChanged(Layer l) { notifyLayersChanged(); fireLayerVisibilityChanged(l); } }; } @Override public void close() { for(int i=layers.size()-1;i>=0; i--) { Layer layer = layers.elementAt(i); layer.topicMap.close(); log("Closing layer "+layer.getName()); } } public boolean isUseUndo(){ return this.useUndo; } // Use this to make LayerStack wrap layers in UndoTopicMap public void setUseUndo(boolean useUndo) throws UndoException{ /* if(useUndo && !this.useUndo){ // TODO: wrap all existing layers } else if(!useUndo && this.useUndo){ // TODO: unwrap all existing layers }*/ if(!layers.isEmpty()) throw new UndoException("Can't change undo status with existing layers"); this.useUndo=useUndo; } // Use this to temporarily disable undo, for example before a very big // operation that you don't want to end up in the undo buffer. public void setUndoDisabled(boolean value){ for(Layer l : layers){ TopicMap tm=l.getTopicMap(); if(tm instanceof UndoTopicMap) { ((UndoTopicMap)tm).setUndoDisabled(value); } } } public void undo() throws UndoException { if(!this.useUndo) throw new UndoException("Undo is not in use."); UndoBuffer buf=getNextUndo(); if(buf==null) throw new UndoException("Nothing to undo."); buf.undo(); } public void redo() throws UndoException { if(!this.useUndo) throw new UndoException("Undo is not in use."); UndoBuffer buf=getNextRedo(); if(buf==null) throw new UndoException("Nothing to redo."); buf.redo(); } private UndoBuffer getNextUndo(){ T2<Integer,UndoBuffer> nextUndoBuffer = getNextUndo(this); return nextUndoBuffer.e2; } public static T2<Integer,UndoBuffer> getNextUndo(LayerStack lst) { UndoBuffer ret=null; int biggest=Integer.MIN_VALUE; for(Layer l : lst.getLayers()) { TopicMap tm=l.getTopicMap(); if(tm instanceof LayerStack) { T2<Integer,UndoBuffer> subBuffer = getNextUndo((LayerStack) tm); if(subBuffer.e1>biggest){ biggest=subBuffer.e1; ret=subBuffer.e2; } } if(tm instanceof UndoTopicMap) { UndoBuffer buf=((UndoTopicMap)tm).getUndoBuffer(); int num=buf.getUndoOperationNumber(); if(num>biggest){ biggest=num; ret=buf; } } } return new T2<>(Integer.valueOf(biggest), ret); } private UndoBuffer getNextRedo(){ T2<Integer,UndoBuffer> nextRedoBuffer = getNextRedo(this); return nextRedoBuffer.e2; } public static T2<Integer,UndoBuffer> getNextRedo(LayerStack lst) { UndoBuffer ret=null; int smallest=Integer.MAX_VALUE; for(Layer l : lst.getLayers()){ TopicMap tm=l.getTopicMap(); if(tm instanceof LayerStack) { T2<Integer,UndoBuffer> subBuffer = getNextRedo((LayerStack) tm); if(subBuffer.e1<smallest){ smallest=subBuffer.e1; ret=subBuffer.e2; } } if(tm instanceof UndoTopicMap) { UndoBuffer buf=((UndoTopicMap)tm).getUndoBuffer(); int num=buf.getRedoOperationNumber(); if(num<smallest){ smallest=num; ret=buf; } } } return new T2<>(Integer.valueOf(smallest), ret); } public boolean canUndo(){ if(!this.useUndo) return false; UndoBuffer buf=getNextUndo(); if(buf==null) return false; else return true; } public boolean canRedo(){ if(!this.useUndo) return false; UndoBuffer buf=getNextRedo(); if(buf==null) return false; else return true; } public void addUndoMarker(String label) { if(!this.useUndo) return; TopicMap tm = getSelectedLayer().getTopicMap(); if(tm != null && tm instanceof UndoTopicMap) { UndoBuffer buf=((UndoTopicMap)tm).getUndoBuffer(); buf.addMarker(label); } } public void clearUndoBuffers() { if(!this.useUndo) return; for(Layer l : layers){ TopicMap tm=l.getTopicMap(); if(tm instanceof UndoTopicMap) { UndoBuffer buf=((UndoTopicMap)tm).getUndoBuffer(); buf.clear(); } } } public List<UndoOperation> getUndoOperations() { List<UndoOperation> ops = new ArrayList<>(); if(this.useUndo) { for(Layer l : layers){ TopicMap tm=l.getTopicMap(); if(tm instanceof UndoTopicMap) { UndoBuffer buf=((UndoTopicMap)tm).getUndoBuffer(); ops.addAll(buf.getOperations()); } } Collections.sort(ops, new Comparator() { public int compare(Object o1, Object o2) { UndoOperation oo1 = (UndoOperation) o1; UndoOperation oo2 = (UndoOperation) o2; int oo1i = oo1.getOperationNumber(); int oo2i = oo2.getOperationNumber(); return (oo1i>oo2i ? -1 : (oo1i==oo2i ? 0 : 1)); } }); } return ops; } @Override public void clearTopicMap() throws TopicMapException { if(isSelectedReadOnly()) throw new TopicMapReadOnlyException(); getSelectedLayer().getTopicMap().clearTopicMap(); clearTopicIndex(); } @Override public void clearTopicMapIndexes() throws TopicMapException { clearTopicIndex(); Layer layer = null; for(int i=layers.size()-1;i>=0; i--) { layer = layers.elementAt(i); layer.topicMap.clearTopicMapIndexes(); } } /** * Clears topicIndex. */ public void clearTopicIndex(){ if(!useTopicIndex) return; synchronized(indexLock){ topicIndex=new LinkedHashMap<Locator,LayeredTopic>(); } } /** * Removes topic from topicIndex. Each subject identifier of the topic * is removed. It is assumed that each subject identifier of a topic is * in the index. Thus whatever the subject identifier used as parameter is, * the topic will be found if it is in the index. Note that if the indexed * topic doesn't anymore contain all its previous subject identifiers, you * will have to manually remove the old subject identifiers from the index. */ void removeTopicFromIndex(Locator l) throws TopicMapException { if(!useTopicIndex) return; if(l==null) return; synchronized(indexLock){ LayeredTopic lt=topicIndex.get(l); if(lt!=null){ for(Locator lo : lt.getSubjectIdentifiers()){ topicIndex.remove(lo); } } topicIndex.remove(l); // remove the one used as parameter (not in the topic necessarily anymore) } } /** * Adds a topic to topicIndex. Each subject identifier of the topic is * mapped to the layered topic itself. */ void addTopicToIndex(LayeredTopic lt) throws TopicMapException { synchronized(indexLock){ if(topicIndex.size()>500) clearTopicIndex(); for(Locator l : lt.getSubjectIdentifiers()){ topicIndex.put(l,lt); } } } @Override public void setConsistencyCheck(boolean value) throws TopicMapException { consistencyCheck=value; Layer layer = null; for(int i=layers.size()-1; i>=0; i--) { layer = layers.elementAt(i); layer.topicMap.setConsistencyCheck(value); } } @Override public boolean getConsistencyCheck() throws TopicMapException { return consistencyCheck; } /* public LayerControlPanel getControlPanel(){ if(controlPanel!=null) return controlPanel; controlPanel=new LayerControlPanel(this); controlPanel.resetLayers(layers); return controlPanel; }*/ public void setAmbiguityResolver(AmbiguityResolver resolver){ this.ambiguityResolver=resolver; } /* See note beginning of the file about TopicMapListeners in LayerStack */ @Override public void topicRemoved(Topic t) throws TopicMapException { if(!topicMapListeners.isEmpty()) { LayeredTopic lt=makeLayeredTopic(t); for(TopicMapListener listener : topicMapListeners){ listener.topicRemoved(lt); } } removeTopicFromIndex(t.getOneSubjectIdentifier()); } @Override public void associationRemoved(Association a) throws TopicMapException { if(!topicMapListeners.isEmpty()) { for(TopicMapListener listener : topicMapListeners){ listener.associationRemoved(makeLayeredAssociation(a)); } } } @Override public void topicSubjectIdentifierChanged(Topic t,Locator added,Locator removed) throws TopicMapException{ if(removed!=null) removeTopicFromIndex(removed); if(added!=null) removeTopicFromIndex(added); for(Locator l : t.getSubjectIdentifiers()){ removeTopicFromIndex(l); } if(!topicMapListeners.isEmpty()) { LayeredTopic lt=makeLayeredTopic(t); for(TopicMapListener listener : topicMapListeners){ listener.topicSubjectIdentifierChanged(lt,added,removed); } } } @Override public void topicBaseNameChanged(Topic t,String newName,String oldName) throws TopicMapException{ for(Locator l : t.getSubjectIdentifiers()){ removeTopicFromIndex(l); } removeTopicFromIndex(t.getOneSubjectIdentifier()); if(!topicMapListeners.isEmpty()) { LayeredTopic lt=makeLayeredTopic(t); for(TopicMapListener listener : topicMapListeners){ listener.topicBaseNameChanged(lt,newName,oldName); } } } @Override public void topicTypeChanged(Topic t,Topic added,Topic removed) throws TopicMapException { if(!topicMapListeners.isEmpty()) { LayeredTopic lt=makeLayeredTopic(t); LayeredTopic ladded=makeLayeredTopic(added); LayeredTopic lremoved=makeLayeredTopic(removed); for(TopicMapListener listener : topicMapListeners){ listener.topicTypeChanged(lt,ladded,lremoved); } } } @Override public void topicVariantChanged(Topic t,Collection<Topic> scope,String newName,String oldName) throws TopicMapException { if(!topicMapListeners.isEmpty()) { LayeredTopic lt=makeLayeredTopic(t); Collection<Topic> lscope=makeLayeredTopics(scope); for(TopicMapListener listener : topicMapListeners){ listener.topicVariantChanged(lt,lscope,newName,oldName); } } } @Override public void topicDataChanged(Topic t,Topic type,Topic version,String newValue,String oldValue) throws TopicMapException { if(!topicMapListeners.isEmpty()) { LayeredTopic lt=makeLayeredTopic(t); LayeredTopic ltype=makeLayeredTopic(type); LayeredTopic lversion=makeLayeredTopic(version); for(TopicMapListener listener : topicMapListeners){ listener.topicDataChanged(lt,ltype,lversion,newValue,oldValue); } } } @Override public void topicSubjectLocatorChanged(Topic t,Locator newLocator,Locator oldLocator) throws TopicMapException { for(Locator l : t.getSubjectIdentifiers()){ removeTopicFromIndex(l); } if(!topicMapListeners.isEmpty()) { LayeredTopic lt=makeLayeredTopic(t); for(TopicMapListener listener : topicMapListeners){ listener.topicSubjectLocatorChanged(lt,newLocator,oldLocator); } } } @Override public void topicChanged(Topic t) throws TopicMapException { for(Locator l : t.getSubjectIdentifiers()){ removeTopicFromIndex(l); } if(!topicMapListeners.isEmpty()) { LayeredTopic lt=null; if(t instanceof LayeredTopic && t.getTopicMap()==this) lt=(LayeredTopic)t; else lt=makeLayeredTopic(t); for(TopicMapListener listener : topicMapListeners){ listener.topicChanged(lt); } } } @Override public void associationTypeChanged(Association a,Topic newType,Topic oldType) throws TopicMapException { if(!topicMapListeners.isEmpty()) { LayeredAssociation la=makeLayeredAssociation(a); LayeredTopic lNewType=makeLayeredTopic(newType); LayeredTopic lOldType=makeLayeredTopic(oldType); for(TopicMapListener listener : topicMapListeners){ listener.associationTypeChanged(la,lNewType,lOldType); } } } @Override public void associationPlayerChanged(Association a,Topic role,Topic newPlayer,Topic oldPlayer) throws TopicMapException { if(!topicMapListeners.isEmpty()) { LayeredAssociation la=makeLayeredAssociation(a); LayeredTopic lrole=makeLayeredTopic(role); LayeredTopic lNewPlayer=makeLayeredTopic(newPlayer); LayeredTopic lOldPlayer=makeLayeredTopic(oldPlayer); for(TopicMapListener listener : topicMapListeners){ listener.associationPlayerChanged(la,lrole,lNewPlayer,lOldPlayer); } } } @Override public void associationChanged(Association a) throws TopicMapException { if(!topicMapListeners.isEmpty()){ LayeredAssociation la=null; if(a instanceof LayeredAssociation && a.getTopicMap()==this) la=(LayeredAssociation)a; else la=makeLayeredAssociation(a); for(TopicMapListener listener : topicMapListeners){ listener.associationChanged(la); } } } /** * Checks if the selected layer is in read only mode. */ public boolean isSelectedReadOnly(){ return getSelectedLayer().isReadOnly(); } /** * Gets layer position in the stack. Layer with index 0 is at the top. */ public int getLayerZPos(Layer l) { return layers.indexOf(l); } /** * Gets the layer a topic belongs to. */ public Layer getLayer(Topic t) { return getLayer(t.getTopicMap()); } /** * Gets the layer of a topic map. */ public Layer getLayer(TopicMap tm) { return layerIndex.get(tm); } /** * Gets the layer with the specified name. */ @Override public Layer getLayer(String layerName) { Layer layer = null; if(layerName != null) { for(int i=layers.size()-1; i>=0; i--) { layer = layers.elementAt(i); if(layerName.equals(layer.getName())) { return layer; } } } return null; } /** * Gets the selected layer. */ @Override public Layer getSelectedLayer(){ return selectedLayer; } /** * Gets the selected layer position in the stack. */ @Override public int getSelectedIndex(){ return getLayerZPos(selectedLayer); } /** * Makes the specified layer the selected layer. */ @Override public void selectLayer(Layer layer){ selectedLayer=layer; // if(controlPanel!=null) controlPanel.resetLayers(layers); } /** * Gets all layers in the order they are in the stack. */ @Override public List<Layer> getLayers(){ return layers; } /** * Gets all visible layers in the order they are in the stack. */ @Override public List<Layer> getVisibleLayers(){ return visibleLayers; } @Override public void notifyLayersChanged(){ clearTopicIndex(); visibleLayers=new Vector<>(); for(Layer l : layers) { if(l.isVisible()) visibleLayers.add(l); } // TopicMap parent=getParentTopicMap(); // if(parent!=null && parent instanceof LayerStack) ((LayerStack)parent).notifyLayersChanged(); } @Override public Collection<Topic> getTopicsForLayer(Layer l,Topic t) { return ((LayeredTopic)t).getTopicsForLayer(l); } /** * Adds a layer at the bottom of the stack. */ @Override public void addLayer(Layer l) { addLayer(l,layers.size()); } /** * Inserts a layer at the specified position in the stack. Layers after * that index are moved one position down. */ @Override public void addLayer(Layer l,int pos) { if(useUndo) l.wrapInUndo(); if(layers.size()<pos) pos=layers.size(); layers.insertElementAt(l,pos); layerIndex.put(l.getTopicMap(),l); if(layers.size()==1) selectedLayer=layers.elementAt(0); l.getTopicMap().addTopicMapListener(this); if(l.getTopicMap() instanceof ContainerTopicMap) ((ContainerTopicMap)l.getTopicMap()).addContainerListener(containerListener); l.getTopicMap().setParentTopicMap(this); notifyLayersChanged(); // visibilityChanged(l); fireLayerAdded(l); } /** * Sets layer in the specified position removing old layer at that position. */ @Override public void setLayer(Layer l, int pos) { if(useUndo) l.wrapInUndo(); Layer old=layers.elementAt(pos); layerIndex.remove(old); layerIndex.put(l.getTopicMap(),l); old.getTopicMap().removeTopicMapListener(this); if(old.getTopicMap() instanceof ContainerTopicMap) ((ContainerTopicMap)old.getTopicMap()).removeContainerListener(containerListener); layers.setElementAt(l,pos); l.getTopicMap().addTopicMapListener(this); if(l.getTopicMap() instanceof ContainerTopicMap) ((ContainerTopicMap)l.getTopicMap()).addContainerListener(containerListener); l.getTopicMap().setParentTopicMap(this); if(selectedLayer==old) selectedLayer=l; notifyLayersChanged(); // visibilityChanged(l); fireLayerChanged(old, l); } /** * Removes the specified layer. Layers after the removed layer are * moved one position up. */ @Override public boolean removeLayer(Layer l) { if(layers.remove(l)){ layerIndex.remove(l); if(selectedLayer==l) selectedLayer=(layers.size()>0?layers.elementAt(0):null); l.getTopicMap().removeTopicMapListener(this); if(l.getTopicMap() instanceof ContainerTopicMap) { ((ContainerTopicMap)l.getTopicMap()).removeContainerListener(containerListener); } l.getTopicMap().setParentTopicMap(null); l.getTopicMap().close(); notifyLayersChanged(); // visibilityChanged(l); fireLayerRemoved(l); return true; } return false; } /** * Moves layers around to reverse layer order. */ @Override public void reverseLayerOrder() { Vector<Layer> newLayers=new Vector<>(); for(int i=layers.size()-1; i>=0; i--) { newLayers.add(layers.elementAt(i)); } layers = newLayers; notifyLayersChanged(); fireLayerStructureChanged(); } /** * Merges all layers in the specified layer. */ public void mergeAllLayers(int targetLayerIndex) { if(targetLayerIndex < 0 || targetLayerIndex >= layers.size()) return; int[] mergeIndex = new int[layers.size()]; mergeIndex[0] = targetLayerIndex; int j = 1; for(int i=0; i<layers.size(); i++) { if(i != targetLayerIndex) { mergeIndex[j++] = i; } } mergeLayers(mergeIndex); } /** * Merges some layers. The array given as parameter should contain indexes * of layers to be merged. First index is used as the target layer and all * other layers are merged into that. */ public void mergeLayers(int[] layerIndexes) { if(layerIndexes == null || layerIndexes.length < 2) return; Layer targetLayer = layers.elementAt(layerIndexes[0]); Vector<Layer> sourceLayers = new Vector<>(); Layer sourceLayer = null; for(int i=1; i<layerIndexes.length; i++) { sourceLayers.add(layers.elementAt(layerIndexes[i])); } for(int i=sourceLayers.size()-1; i>=0; i--) { try { sourceLayer = sourceLayers.elementAt(i); targetLayer.getTopicMap().mergeIn(sourceLayer.getTopicMap()); removeLayer(sourceLayer); // layers.remove(sourceLayer); sourceLayers.remove(sourceLayer); } catch (Exception e) { e.printStackTrace(); } } } void ambiguity(String s){ if(ambiguityResolver!=null) ambiguityResolver.ambiguity(s); } public AmbiguityResolution resolveAmbiguity(String event){ if(ambiguityResolver!=null) return ambiguityResolver.resolveAmbiguity(event); else return AmbiguityResolution.addToSelected; } public AmbiguityResolution resolveAmbiguity(String event,String msg){ if(ambiguityResolver!=null) return ambiguityResolver.resolveAmbiguity(event,msg); else return AmbiguityResolution.addToSelected; } /* void visibilityChanged(Layer layer){ clearTopicIndex(); visibleLayers=new Vector<Layer>(); for(Layer l : layers){ if(l.isVisible()) visibleLayers.add(l); } // if(controlPanel!=null){ // controlPanel.resetLayers(layers); // } } */ /* ************************* TopicMap functions ************************* */ /** * Collects all topics from all layers that merge with the given topic. */ protected Set<Topic> collectTopics(Topic t) throws TopicMapException { Set<Topic> collected=new KeyedHashSet<>(new TopicAndLayerKeyMaker()); /* if(visibleLayers.size() < 2) { collected.add(t); } else { **/ collectTopics(collected,t); //} return collected; } /** * Collects all topics from all layers that merge with the given topic. Initially * the collected Set is empty but all merging topics are added to it to be returned * later and to avoid processing same topic several times. */ protected void collectTopics(Set<Topic> collected,Topic t) throws TopicMapException { for(Layer l : visibleLayers){ Collection<Topic> merging=l.getTopicMap().getMergingTopics(t); for(Topic m : merging){ if(collected.add(m)){ collectTopics(collected,m); } } } } /** * Makes a layered topic when given a topic in one of the layers, that is a topic * that isn't yet a LayeredTopic of this LayerStack. First * checks if the topic is available in the topicIndex map for fast retrieval. * If not, collects all topics from different layers and adds the topic to * the index before it is returned. */ LayeredTopic makeLayeredTopic(Topic t) throws TopicMapException { if(t==null) return null; if(useTopicIndex){ synchronized(indexLock){ Locator l=t.getOneSubjectIdentifier(); LayeredTopic lt=topicIndex.get(l); if(lt!=null) return lt; } } Set<Topic> collected=collectTopics(t); LayeredTopic lt=new LayeredTopic(collected,this); if(useTopicIndex){ addTopicToIndex(lt); } return lt; } /** * Makes layered topics for all topics in the collection. Note that some topics * in the collection may end up in the same layered topic and thus the returned * collection may have less items than the collection used as the parameter. */ Collection<Topic> makeLayeredTopics(Collection<Topic> ts) throws TopicMapException { List<Topic> ret=new ArrayList<>(); Set<Topic> processed=new KeyedHashSet<>(new TopicAndLayerKeyMaker()); for(Topic t : ts){ if(processed.contains(t)) continue; Set<Topic> collected=collectTopics(t); processed.addAll(collected); ret.add(new LayeredTopic(collected,this)); } return ret; } /** * Makes layered association from an individual association. Note that unlike * LayeredTopic.getAssociations, this method returns only one LayeredAssociation * for each individual association, even if roles have been merged and * there are actually several LayeredAssociations that are constructed from * the association used as parameter. In the case of merged roles, one of * the possible LayeredAssociations is returned arbitrarily. */ LayeredAssociation makeLayeredAssociation(Association a) throws TopicMapException { LayeredTopic type=(a.getType()==null?null:makeLayeredTopic(a.getType())); LayeredAssociation la=new LayeredAssociation(this,type); for(Topic role : a.getRoles()){ Topic player=a.getPlayer(role); LayeredTopic lrole=makeLayeredTopic(role); LayeredTopic lplayer=makeLayeredTopic(player); if(la.getPlayer(lrole)!=null) { ambiguity("Assocition roles merged (makeLayeredAssociation)"); continue; } la.addLayeredPlayer(lplayer,lrole); } return la; } @Override public Topic getTopic(Locator si) throws TopicMapException { for(Layer l : visibleLayers){ Topic t=l.getTopicMap().getTopic(si); if(t!=null) return makeLayeredTopic(t); // note: makeLayeredTopic calls collectTopics which will get rest of topics // with the specified subject identifier } return null; } @Override public Topic[] getTopics(String[] sis) throws TopicMapException { Topic[] ret=new Topic[sis.length]; for(int i=0;i<sis.length;i++){ ret[i]=getTopic(sis[i]); } return ret; } @Override public Topic getTopicBySubjectLocator(Locator sl) throws TopicMapException { for(Layer l : visibleLayers){ Topic t=l.getTopicMap().getTopicBySubjectLocator(sl); if(t!=null) return makeLayeredTopic(t); } return null; } @Override public Topic createTopic(String id) throws TopicMapException { if(isSelectedReadOnly()) throw new TopicMapReadOnlyException(); if(selectedLayer!=null){ Topic t=selectedLayer.getTopicMap().createTopic(id); return new LayeredTopic(t,this); } else{ // TODO: some other exception throw new RuntimeException("No selected layer"); } } @Override public Topic createTopic() throws TopicMapException { if(isSelectedReadOnly()) throw new TopicMapReadOnlyException(); if(selectedLayer!=null){ Topic t=selectedLayer.getTopicMap().createTopic(); return new LayeredTopic(t,this); } else{ // TODO: some other exception throw new RuntimeException("No selected layer"); } } @Override public Association createAssociation(Topic type) throws TopicMapException { if(isSelectedReadOnly()) throw new TopicMapReadOnlyException(); if(selectedLayer!=null){ LayeredTopic lt=(LayeredTopic)type; Collection<Topic> c=lt.getTopicsForSelectedLayer(); Topic st=null; if(c.isEmpty()){ AmbiguityResolution res=resolveAmbiguity("createAssociation.type.noSelected","No type in selected layer"); if(res==AmbiguityResolution.addToSelected){ st=((LayeredTopic)type).copyStubTo(getSelectedLayer().getTopicMap()); if(st==null){ ambiguity("Cannot copy topic to selected layer"); throw new TopicMapException("Cannot copy topic to selected layer"); } } else throw new RuntimeException("Not implemented"); } else{ if(c.size()>1) ambiguity("Multiple possible types in layer (createAssociation)"); st=c.iterator().next(); } // Layer l=getSelectedLayer(); // l.getTopicMap().createAssociation(st); return new LayeredAssociation(this,lt); } else{ throw new RuntimeException("No selected layer"); // TODO: some other exception } } @Override public Collection<Topic> getTopicsOfType(Topic type) throws TopicMapException { Set<Topic> processed=new KeyedHashSet<>(new TopicAndLayerKeyMaker()); List<Topic> ret=new ArrayList<>(); LayeredTopic lt=(LayeredTopic)type; for(Layer l : visibleLayers){ for(Topic typeIn : lt.getTopicsForLayer(l)){ Collection<Topic> c=l.getTopicMap().getTopicsOfType(typeIn); for(Topic t : c){ if(processed.contains(t)) continue; Set<Topic> collected=collectTopics(t); processed.addAll(collected); LayeredTopic add=new LayeredTopic(collected,this); addTopicToIndex(add); ret.add(add); } } } return ret; } @Override public Topic getTopicWithBaseName(String name) throws TopicMapException { for(Layer l : visibleLayers){ Topic t=l.getTopicMap().getTopicWithBaseName(name); if(t!=null) return makeLayeredTopic(t); } return null; } /* public Iterator<Topic> getTopics() throws TopicMapException { // TODO: implementation that doesn't get everything in memory at once Set<Topic> processed=new KeyedHashSet<Topic>(new TopicAndLayerKeyMaker()); Vector<Topic> ret=new Vector<Topic>(); for(Layer l : visibleLayers){ Iterator<Topic> c=l.getTopicMap().getTopics(); while(c.hasNext()){ Topic t=c.next(); if(processed.contains(t)) continue; Set<Topic> collected=collectTopics(t); processed.addAll(collected); ret.add(new LayeredTopic(collected,this)); } } return ret.iterator(); } */ private class TopicsIterator implements TopicIterator { public LayeredTopic next=null; public Iterator<Topic> currentIterator = null; public int layerIndex = 0; public Set<Topic> processed; public TopicsIterator(){ processed=new KeyedHashSet<>(new TopicAndLayerKeyMaker()); } @Override public void dispose() { if(currentIterator!=null){ if(currentIterator instanceof TopicIterator) ((TopicIterator)currentIterator).dispose(); else { while(currentIterator.hasNext()) currentIterator.next(); } currentIterator=null; layerIndex=visibleLayers.size(); next=null; } } @Override public boolean hasNext() { if(next!=null) return true; while(_hasNext()){ Topic t=_next(); if(processed.contains(t)){ continue; } else{ try{ Set<Topic> collected=collectTopics(t); next=new LayeredTopic(collected, LayerStack.this); processed.addAll(collected); break; }catch(TopicMapException tme){ log(tme); next=null; return false; } } } return next!=null; } @Override public Topic next() { if(!hasNext()) throw new NoSuchElementException(); Topic ret=next; next=null; return ret; } public boolean _hasNext(){ currentIterator = solveCurrentIterator(currentIterator); if(currentIterator != null) { return currentIterator.hasNext(); } return false; } public Topic _next() { currentIterator = solveCurrentIterator(currentIterator); if(currentIterator != null) { if(currentIterator.hasNext()) { return currentIterator.next(); } } throw new NoSuchElementException(); } public Iterator<Topic> solveCurrentIterator(Iterator iterator) { while(true){ if(iterator!=null && iterator.hasNext()) return iterator; if( layerIndex < visibleLayers.size()) { try { iterator = visibleLayers.elementAt(layerIndex).getTopicMap().getTopics(); layerIndex++; } catch(Exception e) { e.printStackTrace(); } } else return null; } } @Override public void remove(){ throw new UnsupportedOperationException(); } } @Override public Iterator<Topic> getTopics() throws TopicMapException { return new TopicsIterator(); } /* public Iterator<Association> getAssociations() throws TopicMapException { // TODO: implementation that doesn't get everything in memory at once KeyedHashMap<Topic,LayeredTopic> layeredTopics=new KeyedHashMap<Topic,LayeredTopic>(new TopicAndLayerKeyMaker()); HashSet<Association> associations=new HashSet<Association>(); for(Layer l : visibleLayers) { Iterator<Association> c=l.getTopicMap().getAssociations(); while(c.hasNext()){ Association a=c.next(); LayeredTopic lt=getLayeredTopic(a.getType(),layeredTopics); LayeredAssociation la=new LayeredAssociation(this,lt); for(Topic role : a.getRoles()){ LayeredTopic lrole=getLayeredTopic(role,layeredTopics); Topic player=a.getPlayer(role); LayeredTopic lplayer=getLayeredTopic(player,layeredTopics); la.addLayeredPlayer(lplayer, lrole); } associations.add(la); } } return associations.iterator(); } */ private class AssociationsIterator implements Iterator<Association> { public TopicsIterator topicsIterator; public Association next; public Topic currentTopic; public Iterator<Association> currentAssociations; public AssociationsIterator(){ topicsIterator=new TopicsIterator(); } @Override public boolean hasNext(){ if(next!=null) return true; try{ Outer: while(true){ if(currentAssociations==null || !currentAssociations.hasNext()){ if(topicsIterator.hasNext()){ currentTopic=topicsIterator.next(); currentAssociations=currentTopic.getAssociations().iterator(); continue; } else return false; } Association a=currentAssociations.next(); // if, and only if, any of the players, except current topic, // is in topicsIterator.processed then we have included this // association already for(Topic role : a.getRoles()){ LayeredTopic player=(LayeredTopic)a.getPlayer(role); if(player.mergesWithTopic(currentTopic)) continue; for(Topic t : player.getTopicsForAllLayers()){ if(topicsIterator.processed.contains(t)){ continue Outer; // skip this association } } } next=a; return true; } } catch(TopicMapException tme){ log(tme); return false; } } @Override public Association next(){ if(!hasNext()) throw new NoSuchElementException(); Association ret=next; next=null; return ret; } @Override public void remove(){ throw new UnsupportedOperationException(); } } @Override public Iterator<Association> getAssociations() throws TopicMapException { return new AssociationsIterator(); /* final KeyedHashMap<Topic,LayeredTopic> layeredTopics=new KeyedHashMap<Topic,LayeredTopic>(new TopicAndLayerKeyMaker()); final LayerStack layerStack = this; System.out.println("Getting all associations from layerStack!"); return new Iterator<Association>() { Iterator<Association> currentIterator = null; int layerIndex = 0; public boolean hasNext() { currentIterator = solveCurrentIterator(currentIterator); if(currentIterator != null) { return currentIterator.hasNext(); } return false; } public Association next() { currentIterator = solveCurrentIterator(currentIterator); if(currentIterator != null) { if(currentIterator.hasNext()) { try { Association a=currentIterator.next(); LayeredTopic lt=getLayeredTopic(a.getType(),layeredTopics); LayeredAssociation la=new LayeredAssociation(layerStack, lt); for(Topic role : a.getRoles()){ LayeredTopic lrole=getLayeredTopic(role,layeredTopics); Topic player=a.getPlayer(role); LayeredTopic lplayer=getLayeredTopic(player,layeredTopics); la.addLayeredPlayer(lplayer, lrole); } return la; } catch(Exception e) { e.printStackTrace(); } } } throw new NoSuchElementException(); } public Iterator<Association> solveCurrentIterator(Iterator iterator) { while(true){ if(iterator!=null && iterator.hasNext()) return iterator; if( layerIndex < visibleLayers.size()) { try { iterator = visibleLayers.elementAt(layerIndex).getTopicMap().getAssociations(); layerIndex++; } catch(Exception e) { e.printStackTrace(); } } else return null; } } public void remove(){ throw new UnsupportedOperationException(); } }; */ } LayeredTopic getLayeredTopic(Topic t,Map<Topic,LayeredTopic> layeredTopics) throws TopicMapException { LayeredTopic lt=layeredTopics.get(t); if(lt==null){ Set<Topic> collected=collectTopics(t); lt=new LayeredTopic(collected,this); for(Topic ct : collected) layeredTopics.put(ct,lt); } return lt; } @Override public Collection<Association> getAssociationsOfType(Topic type) throws TopicMapException { LayeredTopic lt=(LayeredTopic)type; Map<Topic,LayeredTopic> layeredTopics=new KeyedHashMap<>(new TopicAndLayerKeyMaker()); Set<Association> associations=new LinkedHashSet<>(); for(Layer l : visibleLayers){ for(Topic typeIn : lt.getTopicsForLayer(l)){ Collection<Association> c=l.getTopicMap().getAssociationsOfType(typeIn); for(Association a : c ){ LayeredAssociation la=new LayeredAssociation(this,lt); for(Topic role : a.getRoles()){ LayeredTopic lrole=getLayeredTopic(role,layeredTopics); Topic player=a.getPlayer(role); LayeredTopic lplayer=getLayeredTopic(player,layeredTopics); la.addLayeredPlayer(lplayer, lrole); } associations.add(la); } } } return associations; } @Override public int getNumTopics() throws TopicMapException { Set<Topic> processed=new KeyedHashSet<>(new TopicAndLayerKeyMaker()); int count=0; for(Layer l : visibleLayers) { Iterator<Topic> c = l.getTopicMap().getTopics(); while(c.hasNext()) { Topic t=c.next(); if(processed.contains(t)) continue; Set<Topic> collected=collectTopics(t); processed.addAll(collected); count++; } } return count; } @Override public int getNumAssociations() throws TopicMapException { int counter=0; AssociationsIterator iter=new AssociationsIterator(); while(iter.hasNext()){ iter.next(); counter++; } return counter; /* KeyedHashMap<Topic,LayeredTopic> layeredTopics=new KeyedHashMap<Topic,LayeredTopic>(new TopicAndLayerKeyMaker()); HashSet<Association> associations=new HashSet<Association>(); for(Layer l : visibleLayers){ Iterator<Association> c=l.getTopicMap().getAssociations(); while(c.hasNext()){ Association a=c.next(); LayeredTopic lt=getLayeredTopic(a.getType(),layeredTopics); LayeredAssociation la=new LayeredAssociation(this,lt); for(Topic role : a.getRoles()){ LayeredTopic lrole=getLayeredTopic(role,layeredTopics); Topic player=a.getPlayer(role); LayeredTopic lplayer=getLayeredTopic(player,layeredTopics); la.addLayeredPlayer(lplayer, lrole); } associations.add(la); } } return associations.size();*/ } @Override public Topic copyTopicIn(Topic t,boolean deep) throws TopicMapException { if(isReadOnly()) throw new TopicMapReadOnlyException(); Topic ct=selectedLayer.topicMap.copyTopicIn(t,deep); return makeLayeredTopic(ct); } @Override public Association copyAssociationIn(Association a) throws TopicMapException { if(isReadOnly()) throw new TopicMapReadOnlyException(); Association ca=selectedLayer.topicMap.copyAssociationIn(a); return makeLayeredAssociation(ca); } @Override public void copyTopicAssociationsIn(Topic t) throws TopicMapException { if(isReadOnly()) throw new TopicMapReadOnlyException(); selectedLayer.topicMap.copyTopicAssociationsIn(t); } @Override public void importXTM(java.io.InputStream in, TopicMapLogger logger) throws java.io.IOException,TopicMapException { if(isReadOnly()) throw new TopicMapReadOnlyException(); selectedLayer.topicMap.importXTM(in, logger); } @Override public void importLTM(java.io.InputStream in, TopicMapLogger logger) throws java.io.IOException, TopicMapException { if(isReadOnly()) throw new TopicMapReadOnlyException(); selectedLayer.topicMap.importLTM(in, logger); } @Override public void importLTM(java.io.File in) throws java.io.IOException, TopicMapException { if(isReadOnly()) throw new TopicMapReadOnlyException(); selectedLayer.topicMap.importLTM(in); } @Override public void mergeIn(TopicMap tm) throws TopicMapException { if(isReadOnly()) throw new TopicMapReadOnlyException(); selectedLayer.topicMap.mergeIn(tm); } @Override public boolean trackingDependent(){ return trackDependent; } @Override public void setTrackDependent(boolean v){ trackDependent=v; } @Override public List<TopicMapListener> getTopicMapListeners(){ return topicMapListeners; } @Override public void addTopicMapListener(TopicMapListener listener){ if(!topicMapListeners.contains(listener)) topicMapListeners.add(listener); } @Override public void removeTopicMapListener(TopicMapListener listener){ topicMapListeners.remove(listener); } @Override public void disableAllListeners(){ if(disabledListeners==null){ disabledListeners=topicMapListeners; topicMapListeners=new ArrayList<>(); } } @Override public void enableAllListeners(){ if(disabledListeners!=null){ topicMapListeners=disabledListeners; disabledListeners=null; } } /* public TopicMapListener setTopicMapListener(TopicMapListener listener){ TopicMapListener old=topicMapListener; topicMapListener=listener; return old; }*/ @Override public boolean resetTopicMapChanged() throws TopicMapException { boolean ret=false; for(Layer l : visibleLayers){ ret|=l.getTopicMap().resetTopicMapChanged(); } return ret; } @Override public boolean isTopicMapChanged() throws TopicMapException { for(Layer l : visibleLayers){ if(l.getTopicMap().isTopicMapChanged()) return true; } return false; } // ------------------------------------------------------------------------- public class TopicAndLayerKeyMaker implements Delegate<String,Topic> { public String invoke(Topic t){ String lname=getLayer(t).getName(); String min=null; try{ for(Locator l : t.getSubjectIdentifiers()){ String s=l.toExternalForm(); if(min==null) min=s; else if(s.compareTo(min)<0) min=s; } return lname+"//"+min; } catch(TopicMapException tme){ tme.printStackTrace(); // TODO EXCEPTION return lname; } } } @Override public Collection<Topic> search(String query, TopicMapSearchOptions options) throws TopicMapException { TopicMapSearchOptions options2=options.duplicate(); options2.maxResults=-1; // we can't know yet how many results we need from individual topic maps Set<Topic> searchResult = new LinkedHashSet<>(); Set<Topic> searchResultLayered = new LinkedHashSet<>(); Outer: for(Layer l : visibleLayers) { searchResult.clear(); searchResult.addAll(l.getTopicMap().search(query, options2)); for(Topic t : searchResult){ searchResultLayered.add(this.getTopic(t.getOneSubjectIdentifier())); if(options.maxResults>=0 && searchResultLayered.size()>=options.maxResults) break Outer; } } return searchResultLayered; } @Override public TopicMapStatData getStatistics(TopicMapStatOptions options) throws TopicMapException { if(options == null) return null; int option = options.getOption(); switch(option) { case TopicMapStatOptions.NUMBER_OF_TOPICS: { return new TopicMapStatData(getNumTopics()); } case TopicMapStatOptions.NUMBER_OF_TOPIC_CLASSES: { Set<Topic> typeIndex = new HashSet<>(); Iterator<Topic> topicIter=this.getTopics(); Topic t = null; Topic type = null; while(topicIter.hasNext()) { t = topicIter.next(); if(t != null && !t.isRemoved()) { Collection<Topic> types = t.getTypes(); if(types != null && !types.isEmpty()) { for(Iterator<Topic> iter = types.iterator(); iter.hasNext(); ) { type = iter.next(); if(type != null && !type.isRemoved()) { typeIndex.add(type); } } } } } return new TopicMapStatData(typeIndex.size()); } case TopicMapStatOptions.NUMBER_OF_ASSOCIATIONS: { return new TopicMapStatData(getNumAssociations()); } case TopicMapStatOptions.NUMBER_OF_ASSOCIATION_PLAYERS: { Set<Topic> associationPlayers = new HashSet<>(); Iterator<Topic> topicIter=this.getTopics(); Topic t = null; Collection<Association> associations = null; Collection<Topic> associationRoles = null; Iterator<Association> associationIter = null; Iterator<Topic> associationRoleIter = null; Association association = null; Topic role = null; while(topicIter.hasNext()) { t=(Topic) topicIter.next(); if(t != null && !t.isRemoved()) { associations = t.getAssociations(); if(associations != null && !associations.isEmpty()) { associationIter = associations.iterator(); while(associationIter.hasNext()) { association = (Association) associationIter.next(); if(association != null && !association.isRemoved()) { associationRoles = association.getRoles(); if(associationRoles != null) { associationRoleIter = associationRoles.iterator(); while(associationRoleIter.hasNext()) { role = (Topic) associationRoleIter.next(); associationPlayers.add(association.getPlayer(role)); } } } } } } } return new TopicMapStatData(associationPlayers.size()); } case TopicMapStatOptions.NUMBER_OF_ASSOCIATION_ROLES: { Set<Topic> associationRoles = new HashSet<>(); Iterator<Topic> topicIter=this.getTopics(); Topic t = null; Collection<Association> associations = null; Iterator<Association> associationIter = null; Association association = null; while(topicIter.hasNext()) { t=(Topic) topicIter.next(); if(t != null && !t.isRemoved()) { associations = t.getAssociations(); if(associations != null && !associations.isEmpty()) { associationIter = associations.iterator(); while(associationIter.hasNext()) { association = (Association) associationIter.next(); if(association != null && !association.isRemoved()) { associationRoles.addAll( association.getRoles() ); } } } } } return new TopicMapStatData(associationRoles.size()); } case TopicMapStatOptions.NUMBER_OF_ASSOCIATION_TYPES: { Set<Topic> typeIndex = new HashSet<>(); Iterator<Association> aIter=this.getAssociations(); Association a = null; Topic t = null; while(aIter.hasNext()) { a = aIter.next(); if(a != null && !a.isRemoved()) { t = a.getType(); if(t != null && !t.isRemoved()) { typeIndex.add(t); } } } return new TopicMapStatData(typeIndex.size()); } case TopicMapStatOptions.NUMBER_OF_BASE_NAMES: { Set<String> nameIndex = new HashSet<>(); Iterator<Topic> topicIter=this.getTopics(); Topic t = null; while(topicIter.hasNext()) { t = topicIter.next(); if(t != null && !t.isRemoved()) { if(t.getBaseName() != null) { nameIndex.add(t.getBaseName()); } } } return new TopicMapStatData(nameIndex.size()); } case TopicMapStatOptions.NUMBER_OF_OCCURRENCES: { int count=0; Iterator<Topic> topicIter=this.getTopics(); Topic t = null; Collection<Topic> dataTypes = null; while(topicIter.hasNext()) { t=(Topic) topicIter.next(); if(t != null && !t.isRemoved()) { dataTypes = t.getDataTypes(); if(dataTypes != null) count += dataTypes.size(); } } return new TopicMapStatData(count); } case TopicMapStatOptions.NUMBER_OF_SUBJECT_IDENTIFIERS: { Set<String> siIndex = new HashSet<>(); Iterator<Topic> topicIter=this.getTopics(); Topic t = null; Collection<Locator> sis = null; while(topicIter.hasNext()) { t = topicIter.next(); if(t != null && !t.isRemoved()) { sis = t.getSubjectIdentifiers(); if(sis != null) { for(Iterator<Locator> iter2=sis.iterator(); iter2.hasNext(); ) { if(iter2 != null) { siIndex.add(iter2.next().toExternalForm()); } } } } } return new TopicMapStatData(siIndex.size()); } case TopicMapStatOptions.NUMBER_OF_SUBJECT_LOCATORS: { int count = 0; Iterator<Topic> topicIter=this.getTopics(); Topic t = null; Locator sl = null; while(topicIter.hasNext()) { t = topicIter.next(); if(t != null && !t.isRemoved()) { sl = t.getSubjectLocator(); if(sl != null) { count++; } } } return new TopicMapStatData(count); } } return new TopicMapStatData(); } public static void main(String[] args) throws Exception { // Note: this is far from exhaustive test Topic t,t2,t3,a,b; LayerStack ls=new LayerStack(); Layer l1=new Layer(new org.wandora.topicmap.memory.TopicMapImpl(),"Layer 1",ls); Layer l2=new Layer(new org.wandora.topicmap.memory.TopicMapImpl(),"Layer 2",ls); Layer l3=new Layer(new org.wandora.topicmap.memory.TopicMapImpl(),"Layer 3",ls); ls.addLayer(l1); ls.addLayer(l2); ls.addLayer(l3); ls.selectLayer(l1); t=ls.createTopic(); t.addSubjectIdentifier(new Locator("http://wandora.org/si/testi/testi1")); t=ls.createTopic(); t.addSubjectIdentifier(new Locator("http://wandora.org/si/testi/testi3")); ls.selectLayer(l2); t=ls.createTopic(); t.addSubjectIdentifier(new Locator("http://wandora.org/si/testi/testi2")); t=ls.createTopic(); t.addSubjectIdentifier(new Locator("http://wandora.org/si/testi/testi3")); t.setBaseName("basename"); ls.selectLayer(l3); t3=ls.createTopic(); t3.addSubjectIdentifier(new Locator("http://wandora.org/si/testi/testi3")); t=ls.createTopic(); t.addSubjectIdentifier(new Locator("http://wandora.org/si/testi/testi1")); t.addType(t3); t2=ls.createTopic(); t2.addSubjectIdentifier(new Locator("http://wandora.org/si/testi/testi2")); t2.addType(t3); a=ls.createTopic(); a.addSubjectIdentifier(new Locator("http://wandora.org/si/testi/testia")); b=ls.createTopic(); b.addSubjectIdentifier(new Locator("http://wandora.org/si/testi/testib")); Association a1=ls.createAssociation(t3); a1.addPlayer(t, a); a1.addPlayer(t2,b); HashSet<Topic> scope=new HashSet<Topic>(); scope.add(a); scope.add(b); t.setVariant(scope, "variant"); int counter=1; Topic test; String s; Collection<Topic> c; Collection<Association> d; l3.setVisible(false); test=ls.getTopic(new Locator("http://wandora.org/si/testi/testi1")); System.out.println("Test "+(counter++)+" "+(test==null?"failed":"passed")); c=test.getTypes(); System.out.println("Test "+(counter++)+" "+(c.size()!=0?"failed":"passed")); d=test.getAssociations(); System.out.println("Test "+(counter++)+" "+(d.size()!=0?"failed":"passed")); l1.setVisible(false); test=ls.getTopic(new Locator("http://wandora.org/si/testi/testi1")); System.out.println("Test "+(counter++)+" "+(test!=null?"failed":"passed")); l1.setVisible(true); test=ls.getTopic(new Locator("http://wandora.org/si/testi/testi1")); System.out.println("Test "+(counter++)+" "+(test==null?"failed":"passed")); l1.setVisible(false); test=ls.getTopic(new Locator("http://wandora.org/si/testi/testi2")); System.out.println("Test "+(counter++)+" "+(test==null?"failed":"passed")); c=test.getTypes(); System.out.println("Test "+(counter++)+" "+(!c.isEmpty()?"failed":"passed")); l2.setVisible(false); test=ls.getTopic(new Locator("http://wandora.org/si/testi/testi2")); System.out.println("Test "+(counter++)+" "+(test!=null?"failed":"passed")); l1.setVisible(true); test=ls.getTopic(new Locator("http://wandora.org/si/testi/testi3")); System.out.println("Test "+(counter++)+" "+(test==null?"failed":"passed")); s=test.getBaseName(); System.out.println("Test "+(counter++)+" "+(s!=null?"failed":"passed")); l1.setVisible(false); l2.setVisible(true); test=ls.getTopic(new Locator("http://wandora.org/si/testi/testi3")); System.out.println("Test "+(counter++)+" "+(test==null?"failed":"passed")); s=test.getBaseName(); System.out.println("Test "+(counter++)+" "+(s==null || !s.equals("basename")?"failed":"passed")); l1.setVisible(false); l2.setVisible(false); test=ls.getTopic(new Locator("http://wandora.org/si/testi/testi3")); System.out.println("Test "+(counter++)+" "+(test!=null?"failed":"passed")); l3.setVisible(true); test=ls.getTopic(new Locator("http://wandora.org/si/testi/testi1")); System.out.println("Test "+(counter++)+" "+(test==null?"failed":"passed")); c=test.getTypes(); System.out.println("Test "+(counter++)+" "+(c.size()!=1?"failed":"passed")); d=test.getAssociations(); System.out.println("Test "+(counter++)+" "+(d.size()!=1?"failed":"passed")); t3=ls.getTopic(new Locator("http://wandora.org/si/testi/testi3")); d=test.getAssociations(t3); System.out.println("Test "+(counter++)+" "+(d.size()!=1?"failed":"passed")); a=ls.getTopic(new Locator("http://wandora.org/si/testi/testia")); b=ls.getTopic(new Locator("http://wandora.org/si/testi/testib")); d=test.getAssociations(t3,a); System.out.println("Test "+(counter++)+" "+(d.size()!=1?"failed":"passed")); a1=d.iterator().next(); System.out.println("Test "+(counter++)+" "+(a1.getPlayer(a)==null?"failed":"passed")); System.out.println("Test "+(counter++)+" "+(a1.getPlayer(b)==null?"failed":"passed")); d=test.getAssociations(a); System.out.println("Test "+(counter++)+" "+(!d.isEmpty()?"failed":"passed")); System.out.println("Test "+(counter++)+" "+(test.getVariantScopes().size()!=1?"failed":"passed")); scope=new HashSet<Topic>(); scope.add(a); scope.add(b); s=test.getVariant(scope); System.out.println("Test "+(counter++)+" "+(s==null?"failed":"passed")); l1.setVisible(true); l2.setVisible(true); test=ls.getTopic(new Locator("http://wandora.org/si/testi/testi3")); c=ls.getTopicsOfType(test); System.out.println("Test "+(counter++)+" "+(c.size()!=2?"failed":"passed")); } }
71,805
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
LayeredTopic.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/layered/LayeredTopic.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * LayeredTopic.java * * Created on 8. syyskuuta 2005, 11:30 */ package org.wandora.topicmap.layered; import static org.wandora.utils.Tuples.t2; import static org.wandora.utils.Tuples.t3; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.Vector; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicMapReadOnlyException; import org.wandora.utils.Delegate; import org.wandora.utils.KeyedHashMap; import org.wandora.utils.Tuples.T2; import org.wandora.utils.Tuples.T3; /** * <p> * A LayeredTopic is a collection of topics in different layers that together * merge with each other. Note that the collection may contain two topics * which do not directly merge with each other but with the addition to some * other topics, they all merge together. These topics are stored in an ordered * collection with topics of top layers first and bottom layers last. Topics of * same layer are ordered according to the smallest (lexicographically) subject identifier. * This is somewhat arbitrary but will give a consistent ordering instead of random * order. * </p><p> * When information is queried, the collection with all the individual topics * is iterated and depending on the data being queried, either the first non null * value is restored or all values are combined. Example of the former case is getting * the base name and example for the latter case is getting subject identifiers. * In general methods that return a collection of something combine the results * from all individual topics (removing duplicates) and methods that return * a single value return the first non null value encountered. Because topics are * ordered in the topic collection, information from top layers is returned * before information of bottom layers when only one non null value is returned. * </p><p> * Methods that modify a LayeredTopic actually modify one of the individual * topics. The topic to be modified is chosen to be a topic of the selected * layer of the layer stack. If such a topic does not exist one is generated * in the layer. In case there are several such topics, one of them is chosen. * Also the parameters to the modifying methods might not exist in the layer, * in which case stubs of them are automatically generated. * </p> * @author olli */ public class LayeredTopic extends Topic { /** * Comparator used to order the topics LayeredTopic consists of. Topics * are first ordered according to the position of the layer of the topic * and then according to the smallest subject identifier of the topic. */ class LayerOrderComparator implements Comparator<Topic>{ private String getMinSI(Topic t){ String min=null; try{ for(Locator l : t.getSubjectIdentifiers()){ String s=l.toExternalForm(); if(min==null) min=s; else if(s.compareTo(min)<0) min=s; } if(min==null) min=""; return min; }catch(TopicMapException tme){ tme.printStackTrace(); return ""; } } public int compare(Topic t1,Topic t2){ int p=layerStack.getLayer(t1).getZPos()-layerStack.getLayer(t2).getZPos(); if(p==0) return getMinSI(t1).compareTo(getMinSI(t2)); else return p; } } /** The topics this LayeredTopic consists of */ protected Vector<Topic> topics; /** The layer stack for this topic */ protected LayerStack layerStack; /** * Creates a new instance of LayeredTopic. This layered topic will consist * of the given topics and them alone. Thus the layer stack must not contain * a topic that merges with any of the topics in the collection that isn't * already in the collection. */ public LayeredTopic(Collection<Topic> topics,LayerStack layerStack) { this.layerStack=layerStack; this.topics=new Vector<>(); this.topics.addAll(topics); reorderLayers(); } /** * Creates a new instance of LayeredTopic. This layered topic will consist * of the one given topic and that alone. Thus the layer stack must not contain * a topic that merges with that topic. */ public LayeredTopic(Topic t,LayerStack layerStack){ this.layerStack=layerStack; this.topics=new Vector<>(); this.topics.add(t); reorderLayers(); } /** * Two LayeredTopics are equal if their topics collections are equal. * Note that this largely depends on the equals check of the * individual topics. */ @Override public boolean equals(Object o){ if(o instanceof LayeredTopic){ if(hashCode!=((LayeredTopic)o).hashCode) return false; return topics.equals(((LayeredTopic)o).topics); } else return false; } // hashCode is updated whenever topics collection changes. private int hashCode=0; @Override public int hashCode(){ return hashCode; } protected void ambiguity(String s){ layerStack.ambiguity(s); } protected AmbiguityResolution resolveAmbiguity(String event){ return layerStack.resolveAmbiguity(event,null); } protected AmbiguityResolution resolveAmbiguity(String event,String msg){ return layerStack.resolveAmbiguity(event,msg); } /** * Remakes the collection of topics this layered topic consists of. * Will use the first topic in the topics collection as the base. * @see #remakeLayered(Topic) */ public void remakeLayered() throws TopicMapException { if(topics.size()>0) remakeLayered(topics.iterator().next()); } /** * Makes a set having one key for each topic in the given collection. * This can be used to later compare two topic collections and see if they * are the same. */ private Set<String> makeKeySet(Collection<Topic> topics){ HashSet<String> keys=new LinkedHashSet<>(); Delegate <String,Topic> keyMaker=layerStack.new TopicAndLayerKeyMaker(); for(Topic t : topics){ keys.add(keyMaker.invoke(t)); } return keys; } /** * Remake this LayeredTopic using the given topic as the base. After a * layered topic has been modified, the topics in topics collection * might not all merge anymore. After base name, subject locator or * subject identifier is changed, the layered topic must be remade. * The modification may have caused a split in which case there are more * than one choice what the this LayeredTopic instance may become. The * parameter of this method is used to collect all other merging topics * and thus decides which of the splitted topics this instance becomes. * Usually there isn't any right way to choose this base topic and it is * chosen arbitrarily like is done in the remakeLayered method which takes * no parameters. */ public void remakeLayered(Topic t) throws TopicMapException { Set<String> oldKeys=makeKeySet(topics); topics=new Vector<>(); topics.addAll(layerStack.collectTopics(t)); Set<String> newKeys=makeKeySet(topics); if(!oldKeys.equals(newKeys)) { // layerStack.removeTopicFromIndex(getOneSubjectIdentifier()); layerStack.topicChanged(this); } reorderLayers(); } /** * Get all topics of selected layer that are part of this LayeredTopic. */ public Collection<Topic> getTopicsForSelectedLayer(){ return getTopicsForLayer(layerStack.getSelectedLayer()); } /** * Get all topics of the given layer that are part of this LayeredTopic. */ public Collection<Topic> getTopicsForLayer(Layer l){ Vector<Topic> v=new Vector<>(); for(Topic t : topics){ if(l==layerStack.getLayer(t)){ v.add(t); } } return v; } /** * Get all topics this layered topic consists of in the order they appear * in layers. Topics of top layers will appear first in the collection. */ public Collection<Topic> getTopicsForAllLayers(){ return topics; } /** * Gets one of the topics of the selected layer that is part of this layered * topic or null if no such topic exists. */ public Topic getTopicForSelectedLayer(){ return getTopicForLayer(layerStack.getSelectedLayer()); } /** * Gets one of the topics of given layer that is part of this layered * topic or null if no such topic exists. */ public Topic getTopicForLayer(Layer l){ Collection<Topic> c=getTopicsForLayer(l); if(c.isEmpty()) return null; else return c.iterator().next(); } /** * Sort the topics collection. This needs to be redone in remakeLayered or * after visibility or order of layers has been changed. */ public void reorderLayers(){ hashCode=topics.hashCode(); Collections.sort(topics,new LayerOrderComparator()); } /** * Returns the id of the first topic in the topics collection with layer name * hash code as prefix. Using layer name prefix makes sure that the returned ID is * unique (provided that layer topic map implementations return unique IDs). * Hash code is used since layer name is user specified and may contain unwanted * characters. Note that the ID will change based on what layers are visible. */ public String getID() throws TopicMapException { if(topics==null || topics.isEmpty()) return null; Topic t=topics.get(0); Layer l=layerStack.getLayer(t); return "L"+l.getName().hashCode()+"---"+t.getID(); } /** * Gets all the subject identifiers of all the topics that this layered topic * consists of. */ @Override public Collection<Locator> getSubjectIdentifiers() throws TopicMapException { Set<Locator> sis = new LinkedHashSet<>(); for(Topic t : topics){ sis.addAll(t.getSubjectIdentifiers()); } return sis; } /** * Copies a stub of this topic to the given topic map. This can be used * to make a stub of this topic when it is needed in a layer that doesn't * have a topic for this layered topic. */ public Topic copyStubTo(TopicMap tm) throws TopicMapException { Topic t=null; Collection<Locator> sis=getSubjectIdentifiers(); if(!sis.isEmpty()) { t=tm.createTopic(); t.addSubjectIdentifier(sis.iterator().next()); } else { String bn=getBaseName(); if(bn!=null && bn.length()>0){ t=tm.createTopic(); t.addSubjectIdentifier(sis.iterator().next()); } } remakeLayered(); return t; } @Override public void addSubjectIdentifier(Locator l) throws TopicMapException { if(layerStack.isReadOnly()) throw new TopicMapReadOnlyException(); Collection<Topic> ts=getTopicsForSelectedLayer(); Topic t=null; if(ts==null || ts.isEmpty()) { AmbiguityResolution res=resolveAmbiguity("addSubjectIdentifier.noSelected","No topic in selected layer"); if(res==AmbiguityResolution.addToSelected){ t=copyStubTo(layerStack.getSelectedLayer().getTopicMap()); if(t==null){ ambiguity("Cannot copy topic to selected layer"); return; } } else throw new RuntimeException("Not implemented"); } else { if(ts.size()>1) ambiguity("Several topics in selected layer (addSubjectIdentifier"); t=ts.iterator().next(); } if(!t.getSubjectIdentifiers().contains(l)){ t.addSubjectIdentifier(l); remakeLayered(t); } } @Override public void removeSubjectIdentifier(Locator l) throws TopicMapException { if(layerStack.isReadOnly()) throw new TopicMapReadOnlyException(); Collection<Topic> ts=getTopicsForSelectedLayer(); if(ts==null || ts.size()==0) { ambiguity("No topic in selected layer, nothing done (addSubjectIdentifier)"); return; } // layerStack.removeTopicFromIndex(l); Topic changed=null; for(Topic t : ts){ if(t.getSubjectIdentifiers().contains(l)){ if(changed!=null){ ambiguity("Several topics in selected layer with subject identifier (removeSubjectIdentifier"); break; } else{ t.removeSubjectIdentifier(l); changed=t; } } } if(changed!=null) remakeLayered(changed); } /** * Returns the layer that is being used to get the base name for this topic. * That is the first layer that contains a topic in this layered topic that has * a non null base name. */ public Topic getBaseNameSource() throws TopicMapException { for(Topic t : topics){ String bn=t.getBaseName(); if(bn!=null && bn.length()>0) // return layerStack.getLayer(t); return t; } return null; } @Override public String getBaseName() throws TopicMapException { for(Topic t : topics){ String bn=t.getBaseName(); if(bn!=null && bn.length()>0) return bn; } return null; } @Override public void setBaseName(String name) throws TopicMapException { if(layerStack.isReadOnly()) throw new TopicMapReadOnlyException(); Collection<Topic> ts=getTopicsForSelectedLayer(); Topic t=null; if(ts.isEmpty()) { AmbiguityResolution res=resolveAmbiguity("setBaseName.noSelected","No topic in selected layer"); if(res==AmbiguityResolution.addToSelected){ t=copyStubTo(layerStack.getSelectedLayer().getTopicMap()); if(t==null){ ambiguity("Cannot copy topic to selected layer"); return; } } else throw new RuntimeException("Not implemented"); } else { if(ts.size()>1) ambiguity("Several topics in selected layer (setBaseName)"); t=ts.iterator().next(); } t.setBaseName(name); remakeLayered(t); } @Override public Collection<Topic> getTypes() throws TopicMapException { Vector<Topic> v=new Vector<>(); for(Topic t : topics){ v.addAll(t.getTypes()); } return layerStack.makeLayeredTopics(v); } @Override public void addType(Topic type) throws TopicMapException { if(layerStack.isReadOnly()) throw new TopicMapReadOnlyException(); LayeredTopic lt=(LayeredTopic)type; Collection<Topic> types=lt.getTopicsForSelectedLayer(); Topic stype=null; if(types.isEmpty()){ AmbiguityResolution res=resolveAmbiguity("addType.type.noSelected","No type in selected layer"); if(res==AmbiguityResolution.addToSelected){ stype=lt.copyStubTo(layerStack.getSelectedLayer().getTopicMap()); if(stype==null){ ambiguity("Cannot copy topic to selected layer"); return; } } else throw new RuntimeException("Not implemented"); } else { if(types.size()>1) ambiguity("Several types in selected layer (addType)"); stype=types.iterator().next(); } Collection<Topic> ts=getTopicsForSelectedLayer(); Topic t=null; if(ts.isEmpty()){ AmbiguityResolution res=resolveAmbiguity("addType.topic.noSelected","No topic in selected layer"); if(res==AmbiguityResolution.addToSelected){ t=copyStubTo(layerStack.getSelectedLayer().getTopicMap()); if(t==null){ ambiguity("Cannot copy topic to selected layer"); return; } } else throw new RuntimeException("Not implemented"); } else { if(ts.size()>1) ambiguity("Several topics in selected layer (addType)"); t=ts.iterator().next(); } t.addType(stype); } @Override public void removeType(Topic type) throws TopicMapException { if(layerStack.isReadOnly()) throw new TopicMapReadOnlyException(); LayeredTopic lt=(LayeredTopic)type; Collection<Topic> types=lt.getTopicsForSelectedLayer(); if(types.isEmpty()){ ambiguity("No type in selected layer, nothing done (removeType)"); return; } else if(types.size()>1) ambiguity("Several types in selected layer (removeType)"); Collection<Topic> ts=getTopicsForSelectedLayer(); if(ts.isEmpty()){ ambiguity("No topic in selected layer, nothing done (removeType)"); return; } else if(ts.size()>1) ambiguity("Several topics in selected layer (removeType)"); ts.iterator().next().removeType(types.iterator().next()); } @Override public boolean isOfType(Topic type) throws TopicMapException { LayeredTopic lt=(LayeredTopic)type; for(Topic t : topics){ Layer l=layerStack.getLayer(t); for(Topic t2 : lt.topics){ if(layerStack.getLayer(t2)==l){ if(t.isOfType(t2)) return true; } } } return false; } /** * Creates a scope from a collection of LayeredTopics that can be used for the * given layer. Note that the given layer might not contain all topics needed * for the scope in which case this will return null. */ protected Set<Topic> createScope(Set<Topic> layeredScope,Layer l) throws TopicMapException { return createScope(layeredScope,l,false); } /** * Creates a scope from a collection of LayeredTopics that can be used for the * given layer. Note that the given layer might not contain all topics needed * for the scope. If copyTopics is true then stubs of these topics are created * in the layer, otherwise null is returned if any of the needed topics isn't * found in the layer. */ protected Set<Topic> createScope(Set<Topic> layeredScope,Layer l,boolean copyTopics) throws TopicMapException { // TODO: doesn't handle correctly theoretical case where scope topics get merged Set<Topic> ret=new LinkedHashSet<>(); for(Topic t : layeredScope){ LayeredTopic lt=(LayeredTopic)t; Collection<Topic> ts=lt.getTopicsForLayer(l); Topic t2=null; if(ts.isEmpty()){ if(copyTopics){ t2=lt.copyStubTo(l.getTopicMap()); if(t2==null) { ambiguity("Cannot copy topic to selected layer"); return null; } } else { ambiguity("No topic in layer (createScope)"); return null; } } else { if(ts.size()>1) ambiguity("Several topics in layer (createScope)"); t2=ts.iterator().next(); } ret.add(t2); } return ret; } /** * Tries to find a variant scope in the given (non layered) topic that matches * the scope consisting of LayeredTopics. If such a scope doesn't exist null * is returned. In case there are several of such scopes, one of them is returned * chosen arbitrarily. */ public Set<Topic> getScopeOfLayeredScope(Topic t, Set<Topic> layeredScope) throws TopicMapException { Layer l =layerStack.getLayer(t); Set<Set<Topic>> scopes=t.getVariantScopes(); LoopA: for(Set<Topic> s : scopes){ Set<Topic> used=new LinkedHashSet<>(); LoopB: for(Topic st : s ){ // Note that st cannot belong to several LayeredTopics in scope // because otherwise those multiple LayeredTopics would be merged and be the same topic for(Topic lst : layeredScope){ LayeredTopic lt=(LayeredTopic)lst; // TODO: depends on equals check if(lt != null && lt.topics != null && lt.topics.contains(st)){ used.add(lst); continue LoopB; // check rest of the topics in s } } continue LoopA; // st didn't belong to any topic in scope, test next scope } // all in s belong to some LayeredTopic in scope, now test if all LayeredTopics // in scope have something in s if(used.size()!=layeredScope.size()) continue; // found matching scope (there might be several matching scopes) return s; } return null; } /** * Returns the layer that is used to get the variant for the given scope. */ public T2<Topic,Set<Topic>> getVariantSource(Set<Topic> scope) throws TopicMapException { for(Topic t : topics){ Set<Topic> s=getScopeOfLayeredScope(t,scope); if(s!=null) { return t2(t,scope); // return layerStack.getLayer(t); } } return null; } @Override public String getVariant(Set<Topic> scope) throws TopicMapException { String ret=null; for(Topic t : topics){ Set<Topic> s=getScopeOfLayeredScope(t,scope); if(s!=null) { String val=t.getVariant(s); if(ret!=null && !ret.equals(val)){ ambiguity("Several matching variants (getVariant)"); return ret; } ret=val; } } return ret; } @Override public void setVariant(Set<Topic> scope,String name) throws TopicMapException { if(layerStack.isReadOnly()) throw new TopicMapReadOnlyException(); Collection<Topic> ts=getTopicsForSelectedLayer(); Topic selectedTopic=null; if(ts.isEmpty()){ AmbiguityResolution res=resolveAmbiguity("setVariant.topic.noSelected","No topic in selected layer"); if(res==AmbiguityResolution.addToSelected){ selectedTopic=copyStubTo(layerStack.getSelectedLayer().getTopicMap()); if(selectedTopic==null){ ambiguity("Cannot copy topic to selected layer"); return; } } else throw new RuntimeException("Not implemented"); } else { if(ts.size()>1) ambiguity("Several topics in selected layer (setVariant)"); selectedTopic=ts.iterator().next(); } Set<Topic> s=getScopeOfLayeredScope(selectedTopic,scope); if(s==null) { s=createScope(scope, layerStack.getSelectedLayer(),false); if(s==null) { AmbiguityResolution res=resolveAmbiguity("setVariant.scope.noSelected","Topics in scope not in selected layer"); if(res==AmbiguityResolution.addToSelected){ s=createScope(scope,layerStack.getSelectedLayer(),true); if(s==null){ ambiguity("Cannot copy scope to selected layer"); return; } } else throw new RuntimeException("Not implemented"); } } selectedTopic.setVariant(s,name); } @Override public Set<Set<Topic>> getVariantScopes() throws TopicMapException { // TODO: doesn't handle correctly theoretical case where scope topics get merged Set<Set<Topic>> ret=new LinkedHashSet<>(); Map<Topic,LayeredTopic> collectedMap=new HashMap<>(); for(Topic t : topics){ Set<Set<Topic>> scopes=t.getVariantScopes(); for(Set<Topic> scope : scopes){ Set<Topic> layeredScope=new LinkedHashSet<>(); for(Topic st : scope){ LayeredTopic lt=collectedMap.get(st); if(lt==null) { Collection<Topic> collected=layerStack.collectTopics(st); lt=new LayeredTopic(collected,layerStack); for(Topic ct : collected) collectedMap.put(ct,lt); } layeredScope.add(lt); } ret.add(layeredScope); } } return ret; } @Override public void removeVariant(Set<Topic> scope) throws TopicMapException { if(layerStack.isReadOnly()) throw new TopicMapReadOnlyException(); // TODO: if multiple, remove all or one? in none ask? boolean removed=false; for(Topic selectedTopic : getTopicsForSelectedLayer()){ Set<Topic> s=getScopeOfLayeredScope(selectedTopic,scope); if(s!=null){ if(removed){ ambiguity("Several variants in selected layer (removeVariant)"); return; } selectedTopic.removeVariant(s); removed=true; } } } /** * Returns the topic that is used to get data with specified type and version and * the type and version topics for the source topic layer. */ public T3<Topic,Topic,Topic> getDataSource(Topic type,Topic version) throws TopicMapException { LayeredTopic lt=(LayeredTopic)type; LayeredTopic lv=(LayeredTopic)version; String found=null; for(Topic t : topics){ Layer l=layerStack.getLayer(t); for(Topic st : lt.getTopicsForLayer(l)){ for(Topic sv : lv.getTopicsForLayer(l)){ String data=t.getData(st,sv); if(data!=null && data.length()>0) { return t3(t,st,sv); // return layerStack.getLayer(t); } } } } return null; } @Override public String getData(Topic type,Topic version) throws TopicMapException { LayeredTopic lt=(LayeredTopic)type; LayeredTopic lv=(LayeredTopic)version; String found=null; for(Topic t : topics){ Layer l=layerStack.getLayer(t); for(Topic st : lt.getTopicsForLayer(l)){ for(Topic sv : lv.getTopicsForLayer(l)){ String data=t.getData(st,sv); if(data!=null && data.length()>0) { if(found!=null && !found.equals(data)){ ambiguity("Several data versions in layer (getData)"); return found; } found=data; } } } } return found; } @Override public Hashtable<Topic,String> getData(Topic type) throws TopicMapException { LayeredTopic lt=(LayeredTopic)type; Hashtable<Topic,String> ret=new Hashtable<>(); Map<Topic,LayeredTopic> layeredTopics=new KeyedHashMap<>(layerStack.new TopicAndLayerKeyMaker()); for(Topic t : topics){ for(Topic st : lt.getTopicsForLayer(layerStack.getLayer(t))){ Hashtable<Topic,String> data=t.getData(st); if(data!=null && data.size()>0){ for(Map.Entry<Topic,String> e : data.entrySet()){ LayeredTopic lversion=layerStack.getLayeredTopic(e.getKey(), layeredTopics); String val=e.getValue(); String old=ret.put(lversion,val); if(old!=null && !old.equals(val)){ ambiguity("Several data for given type and version (getData)"); } } } } } return ret; } @Override public Collection<Topic> getDataTypes() throws TopicMapException { Set<Topic> used=new LinkedHashSet<>(); Set<Topic> ret=new LinkedHashSet<>(); Map<Topic,LayeredTopic> layeredTopics=new KeyedHashMap<>(layerStack.new TopicAndLayerKeyMaker()); for(Topic t : topics){ for(Topic dt : t.getDataTypes()){ if(used.contains(dt)) continue; LayeredTopic lt=layerStack.getLayeredTopic(dt,layeredTopics); ret.add(lt); } } return ret; } @Override public void setData(Topic type,Hashtable<Topic,String> versionData) throws TopicMapException { if(layerStack.isReadOnly()) throw new TopicMapReadOnlyException(); for(Map.Entry<Topic,String> e : versionData.entrySet()){ setData(type,e.getKey(),e.getValue()); } } @Override public void setData(Topic type,Topic version,String value) throws TopicMapException { if(layerStack.isReadOnly()) throw new TopicMapReadOnlyException(); LayeredTopic lt=(LayeredTopic)type; LayeredTopic lv=(LayeredTopic)version; Collection<Topic> ts=getTopicsForSelectedLayer(); Topic t=null; if(ts.isEmpty()){ AmbiguityResolution res=resolveAmbiguity("setData.topic.noSelected","No topic in selected layer"); if(res==AmbiguityResolution.addToSelected){ t=copyStubTo(layerStack.getSelectedLayer().getTopicMap()); if(t==null){ ambiguity("Cannot copy topic to selected layer"); return; } } else throw new RuntimeException("Not implemented"); } else { if(ts.size()>1) ambiguity("Several topics in selected layer (setData)"); t=ts.iterator().next(); } Collection<Topic> ltype=lt.getTopicsForSelectedLayer(); Topic stype=null; if(ltype.isEmpty()){ AmbiguityResolution res=resolveAmbiguity("setData.type.noSelected","No type in selected layer"); if(res==AmbiguityResolution.addToSelected){ stype=lt.copyStubTo(layerStack.getSelectedLayer().getTopicMap()); if(stype==null){ ambiguity("Cannot copy topic to selected layer"); return; } } else throw new RuntimeException("Not implemented"); } else { if(ltype.size()>1) ambiguity("Several types in selected layer (setData)"); stype=ltype.iterator().next(); } Collection<Topic> lversion=lv.getTopicsForSelectedLayer(); Topic sversion=null; if(lversion.isEmpty()){ AmbiguityResolution res=resolveAmbiguity("setData.version.noSelected","No version in selected layer"); if(res==AmbiguityResolution.addToSelected){ sversion=lv.copyStubTo(layerStack.getSelectedLayer().getTopicMap()); if(sversion==null){ ambiguity("Cannot copy topic to selected layer"); return; } } else throw new RuntimeException("Not implemented"); } else { if(lversion.size()>1) ambiguity("Several versions in selected layer (setData)"); sversion=lversion.iterator().next(); } t.setData(stype,sversion,value); } @Override public void removeData(Topic type,Topic version) throws TopicMapException { if(layerStack.isReadOnly()) throw new TopicMapReadOnlyException(); LayeredTopic lt=(LayeredTopic)type; LayeredTopic lv=(LayeredTopic)version; boolean removed=false; for(Topic selectedTopic : getTopicsForSelectedLayer()){ for(Topic st : lt.getTopicsForSelectedLayer()){ for(Topic sv : lv.getTopicsForSelectedLayer()){ String d=selectedTopic.getData(st,sv); if(d!=null && d.length()>0) { if(removed){ ambiguity("Several type and version matches (removeData)"); return; } selectedTopic.removeData(st,sv); removed=true; } } } } } @Override public void removeData(Topic type) throws TopicMapException { if(layerStack.isReadOnly()) throw new TopicMapReadOnlyException(); LayeredTopic lt=(LayeredTopic)type; boolean removed=false; for(Topic selectedTopic : getTopicsForSelectedLayer()){ for(Topic st : lt.getTopicsForSelectedLayer()){ Hashtable<Topic,String> ht=selectedTopic.getData(st); if(ht!=null && !ht.isEmpty()){ if(removed){ ambiguity("several type matches (removeData)"); return; } selectedTopic.removeData(st); removed=true; } } } } public Topic getSubjectLocatorSource() throws TopicMapException { for(Topic t : topics){ Locator l=t.getSubjectLocator(); if(l!=null){ // return layerStack.getLayer(t); return t; } } return null; } @Override public Locator getSubjectLocator() throws TopicMapException { Locator ret=null; for(Topic t : topics){ Locator l=t.getSubjectLocator(); if(l!=null) { if(ret!=null && !ret.equals(l)){ ambiguity("Several locators (getSubjectLocator)"); return ret; } ret=l; } } return ret; } @Override public void setSubjectLocator(Locator l) throws TopicMapException { if(layerStack.isReadOnly()) throw new TopicMapReadOnlyException(); Collection<Topic> ts=getTopicsForSelectedLayer(); Topic t=null; if(ts.isEmpty()) { AmbiguityResolution res=resolveAmbiguity("setSubjectLocator.noSelected","No topic in selected layer"); if(res==AmbiguityResolution.addToSelected){ t=copyStubTo(layerStack.getSelectedLayer().getTopicMap()); if(t==null){ ambiguity("Cannot copy topic to selected layer"); return; } } else throw new RuntimeException("Not implemented"); } else { if(ts.size()>1) ambiguity("Several topics in selected layer (setSubjectLocator"); t=ts.iterator().next(); } if(t.getSubjectLocator()==null || !t.getSubjectLocator().equals(l)){ t.setSubjectLocator(l); remakeLayered(t); } } @Override public TopicMap getTopicMap(){ return layerStack; } public LayerStack getLayerStack(){ return layerStack; } /** * Adds LayeredAssociations into associations set based on the possible players * for each role given in the players map. When converting individual associations * into LayeredAssociations, each role may have several possible * players because roles may have been merged. This method is used to create * LayeredAssociations with all possible player assignments. The getAssociations * methods construct the players map and call this method with chosen and roles * parameters as null and an empty associations set. When the method returns associations * set will contain all possible LayeredAssociations. * * The method works recursively by choosing one player for each role at a time. * The chosen players are stored in the chosen Vector. When one player has * been chosen for each player, a LayeredAssociation is created and added to * the set which is later returned. * */ private void _addAssociations(Set<Association> associations,Map<LayeredTopic,Vector<LayeredTopic>> players,Vector<LayeredTopic> roles,Vector<LayeredTopic> chosen,LayeredTopic type) throws TopicMapException{ if(chosen==null) chosen=new Vector<LayeredTopic>(); if(roles==null){ roles=new Vector<LayeredTopic>(); roles.addAll(players.keySet()); } if(chosen.size()==roles.size()){ LayeredAssociation la=new LayeredAssociation(layerStack,type); int counter=0; for(LayeredTopic role : roles){ la.addLayeredPlayer(chosen.elementAt(counter++),role); } associations.add(la); } else{ int chosenSize=chosen.size(); Topic role=roles.elementAt(chosenSize); Vector<LayeredTopic> ps=players.get(role); for(LayeredTopic p : ps){ while(chosen.size()>chosenSize){ chosen.remove(chosen.size()-1); } chosen.add(p); _addAssociations(associations,players,roles,chosen,type); } } } /** * Returns associations of this topic. Note that because roles may get * merged, one individual association may become multiple LayeredAssociations. */ @Override public Collection<Association> getAssociations() throws TopicMapException { Set<Association> associations=new LinkedHashSet<>(); Map<Topic,LayeredTopic> layeredTopics=new KeyedHashMap<Topic,LayeredTopic>(layerStack.new TopicAndLayerKeyMaker()); for(Topic t : topics){ Collection<Association> c=t.getAssociations(); for(Association a : c ){ LayeredTopic lt=layerStack.getLayeredTopic(a.getType(),layeredTopics); // LayeredAssociation la=new LayeredAssociation(layerStack,lt); Collection<Topic> roles=a.getRoles(); Map<LayeredTopic,Vector<LayeredTopic>> players=new KeyedHashMap<LayeredTopic,Vector<LayeredTopic>>(new TopicKeyMaker()); for(Topic role : roles){ LayeredTopic lrole=layerStack.getLayeredTopic(role,layeredTopics); Topic player=a.getPlayer(role); LayeredTopic lplayer=layerStack.getLayeredTopic(player,layeredTopics); Vector<LayeredTopic> ps=players.get(lrole); if(ps==null){ ps=new Vector<LayeredTopic>(); players.put(lrole,ps); } ps.add(lplayer); // la.addLayeredPlayer(lplayer,lrole); } // associations.add(la); _addAssociations(associations,players,null,null,lt); } } return associations; } /** * See notes in getAssociations(). */ @Override public Collection<Association> getAssociations(Topic type) throws TopicMapException { Map<Topic,LayeredTopic> layeredTopics=new KeyedHashMap<Topic,LayeredTopic>(layerStack.new TopicAndLayerKeyMaker()); Set<Association> associations=new LinkedHashSet<Association>(); LayeredTopic lt=(LayeredTopic)type; for(Topic t : topics){ for(Topic st : lt.getTopicsForLayer(layerStack.getLayer(t))){ Collection<Association> c=t.getAssociations(st); for(Association a : c ){ // LayeredAssociation la=new LayeredAssociation(layerStack,lt); Collection<Topic> roles=a.getRoles(); Map<LayeredTopic,Vector<LayeredTopic>> players=new KeyedHashMap<LayeredTopic,Vector<LayeredTopic>>(new TopicKeyMaker()); for(Topic role : roles){ LayeredTopic lrole=layerStack.getLayeredTopic(role,layeredTopics); Topic player=a.getPlayer(role); LayeredTopic lplayer=layerStack.getLayeredTopic(player,layeredTopics); Vector<LayeredTopic> ps=players.get(lrole); if(ps==null){ ps=new Vector<LayeredTopic>(); players.put(lrole,ps); } ps.add(lplayer); // la.addLayeredPlayer(lplayer,lrole); } // associations.add(la); _addAssociations(associations,players,null,null,lt); } } } return associations; } /** * See notes in getAssociations(). */ @Override public Collection<Association> getAssociations(Topic type,Topic role) throws TopicMapException { LayeredTopic lt=(LayeredTopic)type; LayeredTopic lr=(LayeredTopic)role; Map<Topic,LayeredTopic> layeredTopics=new KeyedHashMap<>(layerStack.new TopicAndLayerKeyMaker()); Set<Association> associations=new LinkedHashSet<>(); for(Topic t : topics){ for(Topic st : lt.getTopicsForLayer(layerStack.getLayer(t))){ for(Topic sr : lr.getTopicsForLayer(layerStack.getLayer(t))){ Collection<Association> c=t.getAssociations(st,sr); for(Association a : c ){ // LayeredAssociation la=new LayeredAssociation(layerStack,lt); Collection<Topic> roles=a.getRoles(); KeyedHashMap<LayeredTopic,Vector<LayeredTopic>> players=new KeyedHashMap<LayeredTopic,Vector<LayeredTopic>>(new TopicKeyMaker()); for(Topic arole : roles){ LayeredTopic lrole=layerStack.getLayeredTopic(arole,layeredTopics); Topic player=a.getPlayer(arole); LayeredTopic lplayer=layerStack.getLayeredTopic(player,layeredTopics); Vector<LayeredTopic> ps=players.get(lrole); if(ps==null){ ps=new Vector<LayeredTopic>(); players.put(lrole,ps); } ps.add(lplayer); // la.addLayeredPlayer(lplayer,lrole); } // associations.add(la); _addAssociations(associations,players,null,null,lt); } } } } return associations; } @Override public void remove() throws TopicMapException { if(layerStack.isReadOnly()) throw new TopicMapReadOnlyException(); Collection<Topic> ts=getTopicsForSelectedLayer(); if(ts.isEmpty()){ ambiguity("no topic in selected layer (remove)"); return; } else if(ts.size()>1) ambiguity("several topics in selected layer (remove)"); // layerStack.removeTopicFromIndex(getOneSubjectIdentifier()); ts.iterator().next().remove(); } @Override public long getEditTime() throws TopicMapException { long max=-1; for(Topic t : topics){ long time=t.getEditTime(); if(time>max) max=time; } return max; } @Override public void setEditTime(long time) throws TopicMapException { // TODO: edit time of what? for(Topic t : getTopicsForSelectedLayer()){ t.setEditTime(time); } } @Override public long getDependentEditTime() throws TopicMapException { long max=-1; for(Topic t : topics){ long time=t.getDependentEditTime(); if(time>max) max=time; } return max; } @Override public void setDependentEditTime(long time) throws TopicMapException { // TODO: edit time of what? for(Topic t : getTopicsForSelectedLayer()){ t.setDependentEditTime(time); } } @Override public boolean isRemoved() throws TopicMapException { // TODO: how should this work? if(topics.isEmpty()) return true; Collection<Topic> ts=getTopicsForSelectedLayer(); if(ts.isEmpty()){ ambiguity("no topic in selected layer (isRemoved)"); return false; } else if(ts.size()>1) ambiguity("several topics in selected layer (isRemoved)"); return ts.iterator().next().isRemoved(); } @Override public boolean isDeleteAllowed() throws TopicMapException { Collection<Topic> ts=getTopicsForSelectedLayer(); if(ts.isEmpty()){ ambiguity("no topic in selected layer (isDeleteAllowed)"); return false; } else if(ts.size()>1) ambiguity("several topics in selected layer (isDeleteAllowed)"); return ts.iterator().next().isDeleteAllowed(); } @Override public Collection<Topic> getTopicsWithDataType() throws TopicMapException { Map<Topic,LayeredTopic> layeredTopics=new KeyedHashMap<>(layerStack.new TopicAndLayerKeyMaker()); Set<Topic> ret=new LinkedHashSet<>(); for(Topic t : topics){ Collection<Topic> c=t.getTopicsWithDataType(); for(Topic to : c){ LayeredTopic lt=layerStack.getLayeredTopic(to,layeredTopics); ret.add(lt); } } return ret; } @Override public Collection<Association> getAssociationsWithType() throws TopicMapException { Map<Topic,LayeredTopic> layeredTopics=new KeyedHashMap<>(layerStack.new TopicAndLayerKeyMaker()); Set<Association> associations=new LinkedHashSet<>(); for(Topic t : topics){ Collection<Association> c=t.getAssociationsWithType(); for(Association a : c ){ LayeredTopic lt=layerStack.getLayeredTopic(a.getType(),layeredTopics); LayeredAssociation la=new LayeredAssociation(layerStack,lt); Collection<Topic> roles=a.getRoles(); for(Topic role : roles){ LayeredTopic lrole=layerStack.getLayeredTopic(role,layeredTopics); Topic player=a.getPlayer(role); LayeredTopic lplayer=layerStack.getLayeredTopic(player,layeredTopics); la.addLayeredPlayer(lplayer,lrole); } associations.add(la); } } return associations; } @Override public Collection<Association> getAssociationsWithRole() throws TopicMapException { Map<Topic,LayeredTopic> layeredTopics=new KeyedHashMap<>(layerStack.new TopicAndLayerKeyMaker()); Set<Association> associations=new LinkedHashSet<>(); for(Topic t : topics){ Collection<Association> c=t.getAssociationsWithRole(); for(Association a : c ){ LayeredTopic lt=layerStack.getLayeredTopic(a.getType(),layeredTopics); LayeredAssociation la=new LayeredAssociation(layerStack,lt); Collection<Topic> roles=a.getRoles(); for(Topic role : roles){ LayeredTopic lrole=layerStack.getLayeredTopic(role,layeredTopics); Topic player=a.getPlayer(role); LayeredTopic lplayer=layerStack.getLayeredTopic(player,layeredTopics); la.addLayeredPlayer(lplayer,lrole); } associations.add(la); } } return associations; } @Override public Collection<Topic> getTopicsWithDataVersion() throws TopicMapException { Map<Topic,LayeredTopic> layeredTopics=new KeyedHashMap<>(layerStack.new TopicAndLayerKeyMaker()); Set<Topic> ret=new LinkedHashSet<>(); for(Topic t : topics){ Collection<Topic> c=t.getTopicsWithDataVersion(); for(Topic to : c){ LayeredTopic lt=layerStack.getLayeredTopic(to,layeredTopics); ret.add(lt); } } return ret; } @Override public Collection<Topic> getTopicsWithVariantScope() throws TopicMapException { Map<Topic,LayeredTopic> layeredTopics=new KeyedHashMap<>(layerStack.new TopicAndLayerKeyMaker()); Set<Topic> ret=new LinkedHashSet<>(); for(Topic t : topics){ Collection<Topic> c=t.getTopicsWithVariantScope(); for(Topic to : c){ LayeredTopic lt=layerStack.getLayeredTopic(to,layeredTopics); ret.add(lt); } } return ret; } @Override public boolean mergesWithTopic(Topic topic) throws TopicMapException { if(topic == null) return false; for(Topic t : topics){ if(t.getBaseName()!=null && topic.getBaseName()!=null && t.getBaseName().equals(topic.getBaseName())) return true; for(Locator l : t.getSubjectIdentifiers()) { if(topic.getSubjectIdentifiers().contains(l)) return true; } if(t.getSubjectLocator()!=null && topic.getSubjectLocator()!=null && t.getSubjectLocator().equals(topic.getSubjectLocator())) return true; } return false; } public static class TopicKeyMaker implements Delegate<String,LayeredTopic> { public String invoke(LayeredTopic t){ String min=null; try{ for(Locator l : t.getSubjectIdentifiers()) { String s=l.toExternalForm(); if(min==null) min=s; else if(s.compareTo(min)<0) min=s; } } catch(TopicMapException tme){ tme.printStackTrace(); // TODO EXCEPTION } return min; } } }
52,440
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ContainerTopicMap.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/layered/ContainerTopicMap.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.topicmap.layered; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.undowrapper.UndoTopicMap; /** * * @author olli */ public abstract class ContainerTopicMap extends TopicMap { protected ArrayList<ContainerTopicMapListener> containerListeners; public ContainerTopicMap(){ containerListeners=new ArrayList<ContainerTopicMapListener>(); } public List<ContainerTopicMapListener> getContainerListeners(){ return containerListeners; } public void addContainerListener(ContainerTopicMapListener listener){ if(!containerListeners.contains(listener)) containerListeners.add(listener); } public void removeContainerListener(ContainerTopicMapListener listener){ containerListeners.remove(listener); } public void addContainerListeners(List<ContainerTopicMapListener> listeners){ for(ContainerTopicMapListener l : listeners){ addContainerListener(l); } } protected void fireLayerAdded(Layer layer){ for(ContainerTopicMapListener l : containerListeners){ l.layerAdded(layer); } } protected void fireLayerRemoved(Layer layer){ for(ContainerTopicMapListener l : containerListeners){ l.layerRemoved(layer); } } protected void fireLayerStructureChanged(){ for(ContainerTopicMapListener l : containerListeners){ l.layerStructureChanged(); } } protected void fireLayerChanged(Layer oldLayer,Layer newLayer){ for(ContainerTopicMapListener l : containerListeners){ l.layerChanged(oldLayer, newLayer); } } public void fireLayerVisibilityChanged(Layer layer){ for(ContainerTopicMapListener l : containerListeners){ l.layerVisibilityChanged(layer); } } /** * Gets the number of layers in this container. Default implementation * return getLayers().size(). */ public int getNumLayers(){ return getLayers().size(); } public abstract Collection<Topic> getTopicsForLayer(Layer l,Topic t); public Topic getTopicForLayer(Layer l,Topic t){ Collection<Topic> c=getTopicsForLayer(l,t); if(c==null || c.isEmpty()) return null; else return c.iterator().next(); } public Collection<Topic> getTopicsForTreeLayer(Layer l,Topic t){ ContainerTopicMap tm=(ContainerTopicMap)t.getTopicMap(); ArrayList<Layer> path=getTreeLayerPath(l,tm); HashSet<Topic> topics=new HashSet<Topic>(); topics.add(t); for(Layer p : path){ HashSet<Topic> nextTopics=new HashSet<Topic>(); for(Topic to : topics){ nextTopics.addAll(tm.getTopicsForLayer(p, to)); } TopicMap nexttm=p.getTopicMap(); if(nexttm instanceof ContainerTopicMap) // if not instanceof, for loop will terminate tm=(ContainerTopicMap)nexttm; topics=nextTopics; if(topics.isEmpty()) break; } return topics; } public boolean getTreeLayerPath(Layer l,ContainerTopicMap root,ArrayList<Layer> stack){ List<Layer> layers=root.getLayers(); for(Layer layer : layers){ stack.add(layer); if(layer==l) return true; else { TopicMap tm=layer.getTopicMap(); if(tm instanceof ContainerTopicMap){ if(getTreeLayerPath(l,(ContainerTopicMap)tm,stack)) return true; } } stack.remove(stack.size()-1); } return false; } /** * Finds a layer tree path from root to the given layer. Returned path * is a list of layers that must be followed to reach the given layer. Return * value will not include a layer for the root. If no path was found, i.e. * given layer is not in the layer tree or not under the given root map, * returns null. */ public ArrayList<Layer> getTreeLayerPath(Layer l,ContainerTopicMap root){ ArrayList<Layer> ret=new ArrayList<Layer>(); if(getTreeLayerPath(l,root,ret)) return ret; else return null; } /** * Gets all topics in leaf layer tree layers that merge with the given * topic. */ public Collection<Topic> getTopicsForAllLeafLayers(Topic t){ List<Layer> leaves=getLeafLayers(); ArrayList<Topic> ret=new ArrayList<Topic>(); for(Layer l : leaves){ ret.addAll(getTopicsForTreeLayer(l,t)); } return ret; } /** * Gets the leaf layer that the specifiec topic belongs to. That is, the given * topic should not be a layered topic of this topic map but a topic of one of * the leaf layers of the layer tree of which this topic map is the root. */ public Layer getLeafLayer(Topic t){ for(Layer l : getLeafLayers()){ if(t.getTopicMap()==l.getTopicMap()) return l; } return null; } public Topic getTopicForSelectedTreeLayer(Topic t){ Collection<Topic> c=getTopicsForSelectedTreeLayer(t); if(c==null || c.isEmpty()) return null; else return c.iterator().next(); } /** * Get all topics in the selected tree layer topic map that merge with the * given topic. See getSelectedTreeLayer about the definition of * selected tree layer. */ public Collection<Topic> getTopicsForSelectedTreeLayer(Topic t){ Layer sl=getSelectedLayer(); if(sl==null) return new ArrayList<Topic>(); Collection<Topic> ts=getTopicsForLayer(sl,t); if(sl.getTopicMap() instanceof ContainerTopicMap && ts.size()>0){ ContainerTopicMap tm=(ContainerTopicMap)sl.getTopicMap(); HashSet<Topic> ret=new HashSet<Topic>(); for(Topic t2 : ts){ ret.addAll(tm.getTopicsForSelectedTreeLayer(t2)); } return ret; } else return ts; } public void getLeafLayers(ArrayList<Layer> list){ for(Layer l : getLayers()){ if(l.getTopicMap() instanceof ContainerTopicMap){ ContainerTopicMap c=(ContainerTopicMap)l.getTopicMap(); c.getLeafLayers(list); } else{ list.add(l); } } } /** * Returns all leaf layers in the layer tree. Leaf layers are layers that * are not container topic maps. */ public List<Layer> getLeafLayers(){ ArrayList<Layer> ret=new ArrayList<Layer>(); getLeafLayers(ret); return ret; } public Layer getTreeLayer(TopicMap tm) { for(Layer l : getTreeLayers()){ TopicMap ltm = l.getTopicMap(); if(ltm != null) { if(ltm == tm) return l; if(ltm instanceof UndoTopicMap) { TopicMap iltm = ((UndoTopicMap) ltm).getWrappedTopicMap(); if(iltm == tm) return l; } } } return null; } public Layer getTreeLayer(String name){ for(Layer l : getTreeLayers()){ if(l.getName().equals(name)) return l; } return null; } public void getTreeLayers(ArrayList<Layer> list){ for(Layer l : getLayers()){ list.add(l); if(l.getTopicMap() instanceof ContainerTopicMap){ ContainerTopicMap c=(ContainerTopicMap)l.getTopicMap(); c.getTreeLayers(list); } } } /** * Gets all layers in the layer tree. This includes this container topic mapand * any layers under possible other container topic maps in any of the layers of this * topic map. */ public List<Layer> getTreeLayers(){ ArrayList<Layer> ret=new ArrayList<Layer>(); getTreeLayers(ret); return ret; } /** * Gets the selected layer in the layer tree. If topic map in selected layer in this * topic map is another container topic map, then returns the selected tree layer * in that container. Otherwise returns the selected layer in this container. * In other words, recursively follows selected layers in container topic maps as * deep as possible. * * Note that the returned layer is not necessarily the same user has selected in the * layer tree GUI. This will be the case when user selects a nonleaf layer, that is * a container topic map. */ public Layer getSelectedTreeLayer(){ Layer l=getSelectedLayer(); if(l==null) return null; if(l.getTopicMap() instanceof ContainerTopicMap) return ((ContainerTopicMap)l.getTopicMap()).getSelectedTreeLayer(); else return l; } /** * Gets all layers in the order they are in the container. */ public abstract List<Layer> getLayers(); public abstract void notifyLayersChanged(); /** * Gets layer position in the container. Layer with index 0 is at the top. */ public abstract int getLayerZPos(Layer l); /** * Adds a layer at the bottom of the container. */ public void addLayer(Layer l) { addLayer(l,getNumLayers()); } /** * Sets layer in the specified position removing old layer at that position. */ public abstract void setLayer(Layer l, int pos) ; /** * Inserts a layer at the specified position in the container. Layers after * that index are moved one position down. */ public abstract void addLayer(Layer l,int index) ; /** * Removes the specified layer. Layers after the removed layer are * moved one position up. */ public abstract boolean removeLayer(Layer l) ; /** * Moves the specified layer in another position. Moves other layers to * make room and to remove the resulting empty position. */ public void moveLayer(Layer l,int pos) { if(getNumLayers()<pos) pos=getNumLayers(); if(removeLayer(l)){ addLayer(l,pos); } } /** * Gets the layer with the specified name. */ public abstract Layer getLayer(String name); /** * Gets the selected layer. */ public abstract Layer getSelectedLayer(); /** * Gets the selected layer position in the stack. */ public abstract int getSelectedIndex(); /** * Makes the specified layer the selected layer. */ public abstract void selectLayer(Layer layer); public abstract void reverseLayerOrder(); /** * Gets all visible layers in the order they are in the container. */ public abstract List<Layer> getVisibleLayers(); }
11,821
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ContainerTopicMapListener.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/layered/ContainerTopicMapListener.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.topicmap.layered; /** * * @author olli */ public interface ContainerTopicMapListener { public void layerRemoved(Layer l); public void layerAdded(Layer l); public void layerChanged(Layer oldLayer,Layer newLayer); public void layerStructureChanged(); public void layerVisibilityChanged(Layer l); }
1,142
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
LayeredTopicMapType.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/layered/LayeredTopicMapType.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * LayeredTopicMapType.java * * Created on 17. maaliskuuta 2006, 14:50 * */ package org.wandora.topicmap.layered; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import javax.swing.Icon; import org.wandora.application.Wandora; import org.wandora.application.gui.UIBox; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapConfigurationPanel; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicMapLogger; import org.wandora.topicmap.TopicMapType; import org.wandora.topicmap.TopicMapTypeManager; import org.wandora.topicmap.packageio.PackageInput; import org.wandora.topicmap.packageio.PackageOutput; import org.wandora.topicmap.undowrapper.UndoTopicMap; import org.wandora.utils.Options; /** * * @author olli */ public class LayeredTopicMapType implements TopicMapType { public static boolean USE_UNDO_WRAPPED_TOPICMAPS = true; /** Creates a new instance of LayeredTopicMapType */ public LayeredTopicMapType() { } @Override public void packageTopicMap(TopicMap tm, PackageOutput out, String path, TopicMapLogger logger) throws IOException,TopicMapException { LayerStack ls = (LayerStack) tm; Options options = new Options(); int lcounter = 0; Layer selectedLayer = ls.getSelectedLayer(); for(Layer l : ls.getLayers()) { options.put("layer"+lcounter+".name",l.getName()); TopicMap ltm = getWrappedTopicMap(l.getTopicMap()); options.put("layer"+lcounter+".type",ltm.getClass().getName()); options.put("layer"+lcounter+".visiblity", l.isVisible() ? "true" : "false"); options.put("layer"+lcounter+".readonly", l.isReadOnly() ? "true" : "false"); if(selectedLayer == l) { options.put("layer"+lcounter+".selected", "true"); } lcounter++; } out.nextEntry(path, "options.xml"); // save options before everything else because we will need it before other files options.save(new OutputStreamWriter(out.getOutputStream())); lcounter = 0; for(Layer l : ls.getLayers()) { TopicMap ltm = getWrappedTopicMap(l.getTopicMap()); TopicMapType tmtype = TopicMapTypeManager.getType(ltm); logger.log("Saving layer '" + l.getName() + "'."); tmtype.packageTopicMap(ltm,out, out.joinPath(path, "layer"+lcounter), logger); lcounter++; } for(int i=lcounter; i<lcounter+99; i++) { out.removeEntry(path, "layer"+lcounter); } } private TopicMap getWrappedTopicMap(TopicMap tm) { if(tm != null) { if(tm.getClass().equals(UndoTopicMap.class)) { tm = ((UndoTopicMap) tm).getWrappedTopicMap(); } } return tm; } @Override public TopicMap createTopicMap(Object params) { return new LayerStack(); } @Override public TopicMap modifyTopicMap(TopicMap tm,Object params) throws TopicMapException { return tm; } @Override public TopicMap unpackageTopicMap(TopicMap topicmap, PackageInput in, String path, TopicMapLogger logger,Wandora wandora) throws IOException,TopicMapException { if(topicmap != null && !(topicmap instanceof LayerStack)) { return topicmap; } if(topicmap == null) { topicmap = new LayerStack(); } if(!in.gotoEntry(path, "options.xml")) { logger.log("Can't find options.xml in the package."); logger.log("Aborting."); return null; } Options options = new Options(); options.parseOptions(new BufferedReader(new InputStreamReader(in.getInputStream()))); LayerStack ls = (LayerStack) topicmap; Layer selectedLayer = null; int counter = 0; while(true) { String layerName = options.get("layer"+counter+".name"); if(layerName == null) break; String proposedLayerName = layerName; int layerCount = 1; while(ls.getLayer(proposedLayerName) != null) { proposedLayerName = layerName + " ("+layerCount+")"; layerCount++; } layerName = proposedLayerName; String typeClass=options.get("layer"+counter+".type"); try { Class c = Class.forName(typeClass); TopicMapType type = TopicMapTypeManager.getType((Class<? extends TopicMap>)c); logger.log("Preparing layer '" + layerName + "'."); TopicMap tm = type.unpackageTopicMap(in, in.joinPath(path, "layer"+counter), logger, wandora); Layer l = new Layer(tm,layerName,ls); ls.addLayer(l); String layerVisibility = options.get("layer"+counter+".visiblity"); String layerReadonly = options.get("layer"+counter+".readonly"); String isSelected = options.get("layer"+counter+".selected"); if("true".equalsIgnoreCase(layerVisibility)) l.setVisible(true); else l.setVisible(false); if("true".equalsIgnoreCase(layerReadonly)) l.setReadOnly(true); else l.setReadOnly(false); if("true".equalsIgnoreCase(isSelected)) selectedLayer = l; } catch(ClassNotFoundException cnfe) { logger.log("Can't find class '"+typeClass+"', skipping layer."); } counter++; } if(selectedLayer != null) { ls.selectLayer(selectedLayer); } return ls; } @Override public TopicMap unpackageTopicMap(PackageInput in, String path, TopicMapLogger logger, Wandora wandora) throws IOException,TopicMapException { if(!in.gotoEntry(path, "options.xml")) { if(logger != null) { logger.log("Can't find options.xml in the package."); logger.log("Aborting."); } else { System.out.println("Can't find options.xml in the package."); System.out.println("Aborting."); } return null; } Options options = new Options(); options.parseOptions(new BufferedReader(new InputStreamReader(in.getInputStream()))); LayerStack ls = new LayerStack(); Layer selectedLayer = null; if(logger == null) logger = ls; int counter = 0; while(true && counter < 9999) { String layerName = options.get("layer"+counter+".name"); if(layerName == null) break; String typeClass = options.get("layer"+counter+".type"); try { Class c = Class.forName(typeClass); TopicMapType type = TopicMapTypeManager.getType((Class<? extends TopicMap>)c); logger.log("Loading layer '" + layerName + "'."); TopicMap tm = type.unpackageTopicMap(in, in.joinPath(path, "layer"+counter), logger, wandora); Layer l = new Layer(tm,layerName,ls); ls.addLayer(l); String layerVisibility = options.get("layer"+counter+".visiblity"); String layerReadonly = options.get("layer"+counter+".readonly"); String isSelected = options.get("layer"+counter+".selected"); if("true".equalsIgnoreCase(layerVisibility)) l.setVisible(true); else l.setVisible(false); if("true".equalsIgnoreCase(layerReadonly)) l.setReadOnly(true); else l.setReadOnly(false); if("true".equalsIgnoreCase(isSelected)) selectedLayer = l; } catch(ClassNotFoundException cnfe){ logger.log("Can't find topic map class '"+typeClass+"', skipping layer."); } counter++; } if(selectedLayer != null) { ls.selectLayer(selectedLayer); } return ls; } @Override public String getTypeName() { return "Layered"; } @Override public String toString() { return getTypeName(); } @Override public TopicMapConfigurationPanel getConfigurationPanel(Wandora wandora, Options options) { return new TopicMapConfigurationPanel() { @Override public Object getParameters() { return new Object(); } }; } @Override public TopicMapConfigurationPanel getModifyConfigurationPanel(Wandora wandora, Options options, TopicMap tm) { return null; } @Override public javax.swing.JMenuItem[] getTopicMapMenu(TopicMap tm, Wandora wandora) { return null; } @Override public Icon getTypeIcon() { //return UIBox.getIcon("gui/icons/layerinfo/layer_type_layered.png"); return UIBox.getIcon(0xf1b3); } }
10,106
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Layer.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/layered/Layer.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * Layer.java * * Created on 8. syyskuuta 2005, 11:38 */ package org.wandora.topicmap.layered; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.undowrapper.UndoTopicMap; /** * The Layer class represents one layer in a LayerStack. Each Layer contains * the topic map of that layer and in addition to that, the name of the layer, * boolean flags to indicate visibility and read only states and a colour for * the layer. * * @author olli */ public class Layer { protected ContainerTopicMap container; protected TopicMap topicMap; protected boolean visible; protected int color; protected String name; protected boolean broken=false; /** Creates a new instance of Layer */ public Layer(TopicMap topicMap,String name,ContainerTopicMap container) throws TopicMapException { this.topicMap=topicMap; this.container=container; setName(name); setVisible(true); setColor(0x000000); if(!topicMap.isConnected()){ this.broken=true; } } public void wrapInUndo(){ if(!(topicMap instanceof LayerStack) && !(topicMap instanceof UndoTopicMap)){ topicMap=new UndoTopicMap(topicMap); } } public ContainerTopicMap getContainer(){return container;} public TopicMap getTopicMap(){return topicMap;} public boolean isVisible(){return visible;} public void setVisible(boolean visible){ this.visible=visible; if(container!=null) container.notifyLayersChanged(); if(container!=null) container.fireLayerVisibilityChanged(this); // layerStack.visibilityChanged(this); } public boolean isReadOnly(){ if(topicMap != null) { return topicMap.isReadOnly(); } return true; } public void setReadOnly(boolean readOnly) { if(topicMap != null) { topicMap.setReadOnly(readOnly); } } public int getColor(){return color;} public void setColor(int color){this.color=color;} public String getName(){return name;} public void setName(String name){this.name=name;} public int getZPos(){ return container.getLayerZPos(this); } public void setBroken(boolean broken){this.broken=broken;} public boolean getBroken(){return broken;} }
3,234
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AmbiguityResolver.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/layered/AmbiguityResolver.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * AmbiguityResolver.java * * Created on 26. lokakuuta 2005, 13:52 */ package org.wandora.topicmap.layered; /** * * @author olli */ public interface AmbiguityResolver { public void ambiguity(String s); public AmbiguityResolution resolveAmbiguity(String event); public AmbiguityResolution resolveAmbiguity(String event,String msg); }
1,170
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
LayeredAssociation.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/layered/LayeredAssociation.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * LayeredAssociation.java * * Created on 8. syyskuuta 2005, 11:30 */ package org.wandora.topicmap.layered; import java.util.Collection; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.Vector; import org.wandora.topicmap.Association; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicMapReadOnlyException; import org.wandora.utils.KeyedHashMap; /** * * Unlike LayeredTopic, LayeredAssociation is not a collection of individual * associations of different layers. Of course it can still be treated like * this but the implementation does not keep a collection of associations the * way LayeredTopic does. Instead the association simply has a LayeredTopic * for association type and a map that maps roles to players, both * LayeredTopics. * * Whenever LayeredAssociation is being modified an association of the * selected layer that matches this layered association needs to be searched for. * If such an association is found, it can be used for the modification. Finding * the matching association is made difficult by the fact that role topics of an * individual association may have merged. In this case two (or more) roles are showing as * only one role in LayeredAssociation. Although these kind of topic merges * might be rare, they are still possible and may have clever practical uses. * * In cases where role topics have merged, several LayeredAssociations are * created in the layer stack, one for each possible combination of roles. For * example, suppose that an association has roles named 1,2,3 and 4 with players * A,B,C and D respectively. Suppose that in the layer stack roles 1 and 2 merge * and roles 3 and 4 merge. Then the individual association is showing as four * associations in the layer stack. (1:A,3:C), (1:B,3:C), (1:A,3:D) and (1:B,3:D). * Each of these (and only these) matches the individual association. Editing * any of them will affect all of the LayeredAssociations because they all * originate from the same association. * * @author olli */ public class LayeredAssociation implements Association { protected LayeredTopic type; protected LayerStack layerStack; // role ,player protected Map<LayeredTopic,LayeredTopic> players; /** Creates a new instance of LayeredAssociation */ public LayeredAssociation(LayerStack layerStack, LayeredTopic type) { this.layerStack=layerStack; this.type=type; this.players=new KeyedHashMap<>(new LayeredTopic.TopicKeyMaker()); } public boolean equals(Object o){ if(o instanceof LayeredAssociation){ if(hashCode()!=((LayeredAssociation)o).hashCode()) return false; return type.equals(((LayeredAssociation)o).type) && players.equals(((LayeredAssociation)o).players); } else return false; } private Integer hashCode=null;; public int hashCode(){ if(hashCode==null) hashCode=players.hashCode()+type.hashCode(); return hashCode; } protected void ambiguity(String s){ layerStack.ambiguity(s); } public Topic getType(){ return type; } @Override public void setType(Topic t) throws TopicMapException { if(layerStack.isReadOnly()) throw new TopicMapReadOnlyException(); Collection<Topic> types=((LayeredTopic)t).getTopicsForSelectedLayer(); if(types.size()==0){ ambiguity("No type for selected layer (setType)"); return; } else if(types.size()>1) ambiguity("Several types for selected layer (setType)"); hashCode=null; Association a=findAssociationForLayer(layerStack.getSelectedLayer()); if(a != null) { a.setType(types.iterator().next()); type=(LayeredTopic)t; } } @Override public Topic getPlayer(Topic role){ return players.get((LayeredTopic)role); } /** * Checks if the given non layered association matches this association. */ public boolean associationMatchesThis(Association a) throws TopicMapException { // if(a.getRoles().size()!=getRoles().size()) return false; Layer l=layerStack.getLayer(a.getTopicMap()); Collection<Topic> typeTopics=type.getTopicsForLayer(l); Set<LayeredTopic> usedRole=new LinkedHashSet<>(); for( Topic role : a.getRoles() ){ Topic player=a.getPlayer(role); boolean found=false; for( Map.Entry<LayeredTopic,LayeredTopic> e : players.entrySet() ){ // if(usedRole.contains(e.getKey())) continue; if(!e.getKey().mergesWithTopic(role)) continue; found=true; if(!e.getValue().mergesWithTopic(player)) continue; usedRole.add(e.getKey()); break; } if(!found) return false; } if(usedRole.size()==players.size()) return true; else return false; } /** * Finds an association in the given layer that matches this LayredAssociation. * Returns null if no such association is found. */ public Association findAssociationForLayer(Layer l) throws TopicMapException { for(Map.Entry<LayeredTopic,LayeredTopic> e : players.entrySet()){ LayeredTopic p=e.getValue(); LayeredTopic r=e.getKey(); for(Topic sp : p.getTopicsForLayer(l)){ for(Topic sr : r.getTopicsForLayer(l)){ for(Topic st : type.getTopicsForLayer(l)){ for(Association a : sp.getAssociations(st, sr)){ if(associationMatchesThis(a)){ return a; } } } } } break; } return null; } /** * Finds all associations in the given layer that match this LayeredAssociation. */ public Collection<Association> findAssociationsForLayer(Layer l) throws TopicMapException { Set<Association> ret=new LinkedHashSet<>(); for(Map.Entry<LayeredTopic,LayeredTopic> e : players.entrySet()){ LayeredTopic p=e.getValue(); LayeredTopic r=e.getKey(); for(Topic sp : p.getTopicsForLayer(l)){ for(Topic sr : r.getTopicsForLayer(l)){ for(Topic st : type.getTopicsForLayer(l)){ for(Association a : sp.getAssociations(st, sr)){ if(associationMatchesThis(a)){ ret.add(a); } } } } } break; } return ret; } public Association findAssociationForSelectedLayer() throws TopicMapException { return findAssociationForLayer(layerStack.getSelectedLayer()); } /** * Adds a player to this LayeredAssociation object. Does not actually modify * the association, this method is used to construct LayeredAssociation objects * that will later be returned outside the topic map implementation when they * are fully constructed. */ void addLayeredPlayer(LayeredTopic player,LayeredTopic role){ hashCode=null; players.put(role,player); } /** * Adds a player to the association and modifies the appropriate individual * association accordingly. Note that if this association isn't already * in the selected layer, it will be copied there. Also any roles and players * (the ones being added or existing ones) will be copied to the selected * layer if they aren't there already. */ @Override public void addPlayer(Topic player,Topic role) throws TopicMapException { if(layerStack.isReadOnly()) throw new TopicMapReadOnlyException(); Collection<Topic> lplayer=((LayeredTopic)player).getTopicsForSelectedLayer(); Topic splayer=null; if(lplayer.isEmpty()){ AmbiguityResolution res=layerStack.resolveAmbiguity("addPlayer.player.noSelected","No player in selected layer"); if(res==AmbiguityResolution.addToSelected){ splayer=((LayeredTopic)player).copyStubTo(layerStack.getSelectedLayer().getTopicMap()); if(splayer==null){ ambiguity("Cannot copy topic to selected layer"); throw new TopicMapException("Cannot copy topic to selected layer"); } } else throw new RuntimeException("Not implemented"); } else { if(lplayer.size()>1) ambiguity("Several players in selected layer (addPlayer)"); splayer=lplayer.iterator().next(); } Collection<Topic> lrole=((LayeredTopic)role).getTopicsForSelectedLayer(); Topic srole=null; if(lrole.isEmpty()){ AmbiguityResolution res=layerStack.resolveAmbiguity("addPlayer.role.noSelected","No role in selected layer"); if(res==AmbiguityResolution.addToSelected){ srole=((LayeredTopic)role).copyStubTo(layerStack.getSelectedLayer().getTopicMap()); if(srole==null){ ambiguity("Cannot copy topic to selected layer"); throw new TopicMapException("Cannot copy topic to selected layer"); } } else throw new RuntimeException("Not implemented"); } else { if(lrole.size()>1) ambiguity("Several roles in selected layer (addPlayer)"); srole=lrole.iterator().next(); } // TODO: doesn't handle multiple association matches Association a=null; if(players.isEmpty()){ Layer l=layerStack.getSelectedLayer(); Collection<Topic> c=type.getTopicsForSelectedLayer(); Topic st=null; if(c.isEmpty()){ AmbiguityResolution res=layerStack.resolveAmbiguity("addPlayer.type.noSelected","No type in selected layer"); if(res==AmbiguityResolution.addToSelected){ st=((LayeredTopic)type).copyStubTo(layerStack.getSelectedLayer().getTopicMap()); if(st==null){ ambiguity("Cannot copy topic to selected layer"); throw new TopicMapException("Cannot copy topic to selected layer"); } } else throw new RuntimeException("Not implemented"); } else{ if(c.size()>1) ambiguity("Multiple possible types in layer (createAssociation)"); st=c.iterator().next(); } a=l.getTopicMap().createAssociation(st); } else a=findAssociationForLayer(layerStack.getSelectedLayer()); if(a!=null) { a.addPlayer(splayer,srole); hashCode=null; players.put((LayeredTopic)role,(LayeredTopic)player); } else ambiguity("No matching association found in selected layer (addPlayer)"); } @Override public void addPlayers(Map<Topic,Topic> players) throws TopicMapException { for(Map.Entry<Topic,Topic> e : players.entrySet()){ addPlayer(e.getValue(), e.getKey()); // PARAMETER ORDER: PLAYER, ROLE } } @Override public void removePlayer(Topic role) throws TopicMapException { if(layerStack.isReadOnly()) throw new TopicMapReadOnlyException(); Collection<Topic> lrole=((LayeredTopic)role).getTopicsForSelectedLayer(); if(lrole.isEmpty()){ ambiguity("No role in selected layer, nothing done (removePlayer)"); return; } else if(lrole.size()>1) ambiguity("Several roles in selected layer (removePlayer)"); for(Map.Entry<LayeredTopic,LayeredTopic> e : players.entrySet()){ LayeredTopic p=e.getValue(); LayeredTopic r=e.getKey(); for(Topic sp : p.getTopicsForSelectedLayer()){ for(Topic sr : r.getTopicsForSelectedLayer()){ for(Topic st : type.getTopicsForSelectedLayer()){ for(Association a : sp.getAssociations(st, sr)){ if(associationMatchesThis(a)){ for(Topic lr : lrole){ if(a.getPlayer(lr)!=null){ a.removePlayer(lr); hashCode=null; players.remove((LayeredTopic)role); return; // TODO: doesn't handle multiple matches } } } } } } } } ambiguity("No matching association found in selected layer (removePlayer)"); } @Override public Collection<Topic> getRoles(){ Vector<Topic> v=new Vector<>(); v.addAll(players.keySet()); return v; } @Override public TopicMap getTopicMap(){ return layerStack; } @Override public void remove() throws TopicMapException { if(layerStack.isReadOnly()) throw new TopicMapReadOnlyException(); // TODO: doesn't handle multiple matches Association a=findAssociationForLayer(layerStack.getSelectedLayer()); if(a==null) ambiguity("No matching assaciation found in selected layer (remove)"); else a.remove(); } @Override public boolean isRemoved() throws TopicMapException { // TODO: doesn't handle multiple matches Association a=findAssociationForLayer(layerStack.getSelectedLayer()); if(a==null) { ambiguity("No matching assaciation found in selected layer (isRemoved)"); return false; } else return a.isRemoved(); } }
15,190
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AmbiguityDebugger.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/layered/ambiguity/AmbiguityDebugger.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * AmbiguityDebugger.java * * Created on 11. joulukuuta 2006, 12:15 * */ package org.wandora.topicmap.layered.ambiguity; import org.wandora.topicmap.layered.AmbiguityResolution; import org.wandora.topicmap.layered.AmbiguityResolver; /** * * @author akivela */ public class AmbiguityDebugger implements AmbiguityResolver { /** Creates a new instance of AmbiguityDebugger */ public AmbiguityDebugger() { } @Override public void ambiguity(String s) { System.out.println(s); } @Override public AmbiguityResolution resolveAmbiguity(String event) { return resolveAmbiguity(event,null); } @Override public AmbiguityResolution resolveAmbiguity(String event,String msg) { ambiguity(event+(msg==null?"":(" "+msg))); return AmbiguityResolution.addToSelected; } }
1,678
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ZipPackageInput.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/packageio/ZipPackageInput.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * ZipPackageInput.java * * Created on 17. maaliskuuta 2006, 13:51 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package org.wandora.topicmap.packageio; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; /** * <p> * Reads entries from a zip file. Entries are stored in ZIP file in the same * order they were entered with ZipPackageOutput. Searching entries is relatively * smart, gotoEntry will scan the file from the current position for the requested * entry, unless the entry has been seen already and it is known to be before * the current file position. However it is always best to read entries * in the order they appear in the file if possible. This avoids opening * the file several times which in the case of a remote file means transferring * the file several times over network.</p> * * @author olli */ public class ZipPackageInput implements PackageInput { private URL url; private ZipInputStream zis; private List<String> entries=null; private List<String> passedEntries=null; private int currentEntry=-1; /** Creates a new instance of ZipPackageInput */ public ZipPackageInput(File file) throws IOException { this(file.toURI().toURL()); } public ZipPackageInput(String file) throws IOException { this(new File(file).toURI().toURL()); } public ZipPackageInput(URL url) throws IOException { this.url=url; } private void openStream() throws IOException { if(zis!=null) zis.close(); zis=new ZipInputStream(url.openStream()); currentEntry=-1; passedEntries=new ArrayList<String>(); } /** * Moves to the entry with the specified name. Returns true if that entry was * found, false otherwise. */ @Override public boolean gotoEntry(String name) throws IOException { if(zis==null) currentEntry=-1; boolean findFromStart=false; if(entries!=null) { int ind=entries.indexOf(name); if(ind==-1) return false; if(ind<=currentEntry) findFromStart=true; } else if(passedEntries!=null && passedEntries.contains(name)) { findFromStart=true; } if( (findFromStart && currentEntry>=0) || zis==null) { openStream(); } String e=null; while(true) { e=gotoNextEntry(); if(e==null) return false; if(e.equals(name)) return true; } } @Override public boolean gotoEntry(String path, String name) throws IOException { return gotoEntry(joinPath(path, name)); } /** * Goes to next entry in the file. * * @return String * @throws java.io.IOException */ @Override public String gotoNextEntry() throws IOException{ if(zis==null) { openStream(); } currentEntry++; ZipEntry e=zis.getNextEntry(); if(e==null) { return null; } passedEntries.add(e.getName()); return e.getName(); } /** * Gets the input stream for current entry. * * @return InputStream * @throws java.io.IOException */ @Override public InputStream getInputStream() throws IOException { return new InputStream(){ @Override public int available() throws IOException { return zis.available(); } public int read() throws IOException { return zis.read(); } @Override public int read(byte[] b) throws IOException { return zis.read(b); } @Override public int read(byte[] b,int off,int len) throws IOException { return zis.read(b,off,len); } @Override public long skip(long n) throws IOException { return zis.skip(n); } }; } /** * Gets the names of all entries in the file. This requires scanning * of the entire file and then reopening the file after the entries * are later actually read when gotoEntry or gotoNextEntry is called. */ @Override public Collection<String> getEntries() throws IOException { if(entries!=null) return entries; if(zis!=null) openStream(); ZipEntry e=null; entries=new ArrayList<String>(); while( (e=zis.getNextEntry())!=null ){ entries.add(e.getName()); } zis.close(); zis=null; return entries; } /** * Closes the file. */ @Override public void close() throws IOException { zis.close(); zis=null; } @Override public String getSeparator() { return "/"; } @Override public String joinPath(String path, String name) { if(path != null && path.length()>0) { return path + getSeparator() + name; } else { return name; } } }
6,208
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ZipPackageOutput.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/packageio/ZipPackageOutput.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * ZipPackageOutput.java * * Created on 17. maaliskuuta 2006, 13:31 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package org.wandora.topicmap.packageio; import java.io.IOException; import java.io.OutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * <p> * This class provides methods to write a ZIP file. Each entry is started with * nextEntry method that needs the next entry name (file name). Closing * entries is not needed, previous entry is closed when nextEntry is called * or the entire file is closed with close method. * </p> * @author olli */ public class ZipPackageOutput implements PackageOutput { private OutputStream out; private ZipOutputStream zos; /** Creates a new instance of ZipPackageOutput */ public ZipPackageOutput(OutputStream out) { this.out=out; zos=new ZipOutputStream(out); } /** * Starts next entry with the specified name. */ @Override public void nextEntry(String name) throws IOException { zos.putNextEntry(new ZipEntry(name)); } @Override public void nextEntry(String path, String name) throws IOException { nextEntry(joinPath(path, name)); } @Override public void removeEntry(String name) throws IOException { } @Override public void removeEntry(String path, String name) throws IOException { } /** * Gets the output stream for current entry. */ @Override public OutputStream getOutputStream() throws IOException { return new OutputStream(){ public void write(int b) throws IOException { zos.write(b); } @Override public void write(byte[] b,int off,int len) throws IOException { zos.write(b,off,len); } @Override public void write(byte[] b) throws IOException { zos.write(b); } }; } /** * Closes the file. */ @Override public void close() throws IOException{ zos.finish(); out.close(); } @Override public String getSeparator() { return "/"; } @Override public String joinPath(String path, String name) { if(path != null && path.length()>0) { return path + getSeparator() + name; } else { return name; } } }
3,388
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
PackageOutput.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/packageio/PackageOutput.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * PackageOutput.java * * Created on 17. maaliskuuta 2006, 13:30 * */ package org.wandora.topicmap.packageio; import java.io.IOException; import java.io.OutputStream; /** * A package is a collection of data consisting of entries. Each entry has a name * and data. Data is written with OutputStream to allow binary entries. A new entry * is started by calling nextEntry with the entry name. After that an OutputStream * that can be used to write the entry can be retrieved with getOutputStream. A new * getOutputStream must be used once for each entry. See notes about order of entries * in PackageInput. * * @author olli */ public interface PackageOutput { /** * Start a new entry in the package with the given name. * * @param name * @throws java.io.IOException */ public void nextEntry(String name) throws IOException; /** * Start a new entry in the package with the given path and name. * * @param path * @param name * @throws java.io.IOException */ public void nextEntry(String path, String name) throws IOException; /** * Closes the package. * * @throws java.io.IOException */ public void close() throws IOException; /** * Gets the output stream for current entry. * * @return * @throws java.io.IOException */ public OutputStream getOutputStream() throws IOException; /** * Ensure entry will be removed. * * @param name * @throws java.io.IOException */ public void removeEntry(String name) throws IOException; /** * Ensure entry will be removed. * * @param path * @param name * @throws java.io.IOException */ public void removeEntry(String path, String name) throws IOException; /** * Returns file separator used by the PackageOutput. * * @return */ public String getSeparator(); /** * Joins path and name. * * @param path * @param name * @return */ public String joinPath(String path, String name); }
3,018
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DirectoryPackageInput.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/packageio/DirectoryPackageInput.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.topicmap.packageio; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * * @author akikivela */ public class DirectoryPackageInput implements PackageInput { private File directory; private List<String> entries=null; private int currentEntry=-1; private InputStream inputStream; public DirectoryPackageInput(File dir) throws FileNotFoundException { directory = dir; initializePackageInput(); } public DirectoryPackageInput(String dir) throws FileNotFoundException { directory = new File(dir); initializePackageInput(); } private void initializePackageInput() throws FileNotFoundException { currentEntry=-1; entries = new ArrayList<String>(); collectEntries(directory); } private void collectEntries(File d) throws FileNotFoundException { if(entries.size() < 999) { for (final File fileEntry : d.listFiles()) { if (fileEntry.isDirectory()) { collectEntries(fileEntry); } else { entries.add(getEntryName(fileEntry)); } } } } private String getEntryName(File fileEntry) { String fileEntryName = fileEntry.getAbsolutePath(); String entryName = fileEntryName.substring(directory.getAbsolutePath().length()); if(entryName.startsWith(File.separator)) { entryName = entryName.substring(File.separator.length()); } return entryName; } @Override public boolean gotoEntry(String name) throws IOException { if(entries.contains(name)) { closeCurrentInputStream(); currentEntry = entries.indexOf(name); return true; } return false; } @Override public boolean gotoEntry(String path, String name) throws IOException { return gotoEntry(joinPath(path, name)); } @Override public String gotoNextEntry() throws IOException { currentEntry++; if(currentEntry < entries.size()) { closeCurrentInputStream(); return entries.get(currentEntry); } else { return null; } } @Override public InputStream getInputStream() throws IOException { return new InputStream(){ @Override public int available() throws IOException { return getCurrentInputStream().available(); } public int read() throws IOException { return getCurrentInputStream().read(); } @Override public int read(byte[] b) throws IOException { return getCurrentInputStream().read(b); } @Override public int read(byte[] b,int off,int len) throws IOException { return getCurrentInputStream().read(b,off,len); } @Override public long skip(long n) throws IOException { return getCurrentInputStream().skip(n); } }; } @Override public void close() throws IOException { closeCurrentInputStream(); } @Override public Collection<String> getEntries() throws IOException { return entries; } // ------------------------------------------------------------------------- private void closeCurrentInputStream() throws IOException { if(inputStream != null) { inputStream.close(); inputStream = null; } } private InputStream getCurrentInputStream() throws FileNotFoundException { if(inputStream == null && currentEntry < entries.size()) { String fileEntry = entries.get(currentEntry); if(fileEntry != null) { inputStream = new FileInputStream(new File(directory.getAbsolutePath() + File.separator + fileEntry)); } } if(inputStream != null) { return inputStream; } return null; } // ------------------------------------------------------------------------- @Override public String getSeparator() { return File.separator; } @Override public String joinPath(String path, String name) { if(path != null && path.length()>0) { return path + getSeparator() + name; } else { return name; } } }
5,624
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
PackageInput.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/packageio/PackageInput.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * PackageInput.java * * Created on 17. maaliskuuta 2006, 13:41 * */ package org.wandora.topicmap.packageio; import java.io.IOException; import java.io.InputStream; import java.util.Collection; /** * <p> * A package is a collection of data consisting of entries. Each entry has a name * and data. Data is read with InputStream to allow binary entries. * </p><p> * Most implementations will probably have entries in some order (such as order * of data in a file). Thus it would be best if data is read in the same order * it is returned by gotoNextEntry. If gotoEntry method is used, the implementation * may need to read the file multiple times to find the required entries. However, * because often entries will need to be read in a specific order, care should be * taken when the package is created. To get best possible performance, entries * should be stored in the order they are needed when unpackaging. The performance * may suffer significantly if packages stored remotely instead of locally. * </p> * @author olli */ public interface PackageInput { /** * Moves to the entry that has the given name. * * @param name * @return * @throws java.io.IOException */ public boolean gotoEntry(String name) throws IOException; /** * Moves to the entry that has the given path and name. * * @param path * @param name * @return * @throws java.io.IOException */ public boolean gotoEntry(String path, String name) throws IOException; /** * Moves to next entry and returns it's name. * * @return * @throws java.io.IOException */ public String gotoNextEntry() throws IOException; /** * Gets input stream for current entry. * * @return * @throws java.io.IOException */ public InputStream getInputStream() throws IOException; /** * Closes the package. * * @throws java.io.IOException */ public void close() throws IOException; /** * Get list of entries in the package. * * @return Collection of entries in the package. * @throws java.io.IOException */ public Collection<String> getEntries() throws IOException; /** * Returns file separator used by the PackageInput. * * @return */ public String getSeparator(); /** * Joins path and name, and returns joined resource name. Usually * Package input adds a separator string between the path and the name. * For example, DirectoryPackageInput adds File.separator string * between the path and the name. * * @param path * @param name * @return */ public String joinPath(String path, String name); }
3,675
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DirectoryPackageOutput.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/packageio/DirectoryPackageOutput.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.topicmap.packageio; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import org.wandora.utils.IObox; /** * * @author akikivela */ public class DirectoryPackageOutput implements PackageOutput { private String directory = null; private OutputStream out; public DirectoryPackageOutput(String directory) { this.directory = directory; } @Override public void nextEntry(String name) throws IOException { if(out != null) { out.flush(); out.close(); } String entryName = this.directory + getSeparator() + name; File file = new File(entryName); IObox.createPathFor(file.getParentFile()); out = new FileOutputStream(file); } @Override public void nextEntry(String path, String name) throws IOException { nextEntry(joinPath(path, name)); } @Override public void removeEntry(String name) throws IOException { String entryName = this.directory + getSeparator() + name; File file = new File(entryName); if(file.exists()) { deleteRecursive(file); } } @Override public void removeEntry(String path, String name) throws IOException { removeEntry(joinPath(path, name)); } private boolean deleteRecursive(File path) throws FileNotFoundException{ if(!path.exists()) return false; boolean ret = true; if(path.isDirectory()){ for (File f : path.listFiles()){ ret = ret && deleteRecursive(f); } } return ret && path.delete(); } @Override public void close() throws IOException { if(out != null) { out.flush(); out.close(); } } @Override public OutputStream getOutputStream() throws IOException { return new OutputStream() { @Override public void write(int b) throws IOException { out.write(b); } @Override public void write(byte[] b,int off,int len) throws IOException { out.write(b,off,len); } @Override public void write(byte[] b) throws IOException { out.write(b); } }; } @Override public String getSeparator() { return File.separator; } @Override public String joinPath(String path, String name) { if(path != null && path.length()>0) { return path + getSeparator() + name; } else { return name; } } }
3,644
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
OpenTopicNotSupportedException.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/exceptions/OpenTopicNotSupportedException.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.exceptions; /** * * @author akivela */ public class OpenTopicNotSupportedException extends WandoraException { private static final long serialVersionUID = 1L; @Override public String getMessage() { return "The topic panel can't open a topic."; } }
1,114
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
WandoraException.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/exceptions/WandoraException.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * WandoraException.java * * Created on June 7, 2004, 3:15 PM */ package org.wandora.exceptions; /** * * @author olli */ public class WandoraException extends Exception { private static final long serialVersionUID = 1L; /** Creates a new instance of WandoraException */ public WandoraException() { } public WandoraException(String s) { super(s); } public WandoraException(Throwable cause){ super(cause); } public WandoraException(String s,Throwable cause){ super(s,cause); } }
1,380
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ConcurrentEditingException.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/exceptions/ConcurrentEditingException.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * ConcurrentEditingException.java * * Created on June 17, 2004, 10:30 AM */ package org.wandora.exceptions; import java.util.Set; import org.wandora.topicmap.Topic; /** * * @author olli */ public class ConcurrentEditingException extends WandoraException { private static final long serialVersionUID = 1L; private Set<Topic> failedTopics; private Set<Topic> removedTopics; public ConcurrentEditingException(Set<Topic> failedTopics, Set<Topic> removedTopics) { this.failedTopics=failedTopics; this.removedTopics=removedTopics; } public Set<Topic> getFailedTopics() { return failedTopics; } public Set<Topic> getRemovedTopics() { return removedTopics; } public void setFailedTopics(Set<Topic> s) { failedTopics=s; } public void setRemovedTopics(Set<Topic> s) { removedTopics=s; } }
1,716
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Of.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/Of.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * Compare.java * */ package org.wandora.query2; import java.util.ArrayList; /** * * @author olli */ public class Of extends Directive implements DirectiveUIHints.Provider { private String role; public Of(){} public Of(String role){ this.role=role; } public String getRole(){ return role; } @Override public DirectiveUIHints getUIHints() { DirectiveUIHints ret=new DirectiveUIHints(Of.class,new DirectiveUIHints.Constructor[]{ new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(String.class, false, "role"), }, "") }, Directive.getStandardAddonHints(), "Of", "Framework"); return ret; } @Override public ResultIterator queryIterator(QueryContext context,ResultRow input) throws QueryException { ArrayList<String> roles=new ArrayList<String>(input.getRoles()); ArrayList<Object> values=new ArrayList<Object>(input.getValues()); int i=roles.indexOf(role); if(i==-1) throw new QueryException("Role \""+role+"\" not found"); return new ResultRow(roles,values,i,true).toIterator(); } public String debugStringParams(){return "\""+role+"\"";} }
2,145
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
And.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/And.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * And.java * * */ package org.wandora.query2; /** * * @author olli */ public class And extends WhereDirective implements DirectiveUIHints.Provider { private WhereDirective[] directives; public And(){} public And(WhereDirective[] directives){ this.directives=directives; } public And(WhereDirective d1,WhereDirective d2){ this(new WhereDirective[]{d1,d2}); } public And(WhereDirective d1,WhereDirective d2,WhereDirective d3){ this(new WhereDirective[]{d1,d2,d3}); } public And(WhereDirective d1,WhereDirective d2,WhereDirective d3,WhereDirective d4){ this(new WhereDirective[]{d1,d2,d3,d4}); } @Override public DirectiveUIHints getUIHints() { DirectiveUIHints ret=new DirectiveUIHints(And.class,new DirectiveUIHints.Constructor[]{ new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(Directive.class, true, "whereDirective") }, "") }, Directive.getStandardAddonHints(), "And", "Where directive"); return ret; } @Override public void endQuery(QueryContext context) throws QueryException { for(int i=0;i<directives.length;i++){directives[i].endQuery(context);} } @Override public boolean startQuery(QueryContext context) throws QueryException { boolean r=true; for(int i=0;i<directives.length;i++){r&=directives[i].startQuery(context);} return r; } @Override public boolean includeRow(QueryContext context, ResultRow input) throws QueryException { for(int i=0;i<directives.length;i++){ if(!directives[i].includeRow(context, input)) return false; } return true; } @Override public String debugStringParams(String indent) { return debugStringInner(directives,indent); } }
2,775
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Not.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/Not.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * Not.java * * */ package org.wandora.query2; /** * * @author olli */ public class Not extends WhereDirective implements DirectiveUIHints.Provider { private WhereDirective directive; public Not(){} public Not(WhereDirective directive){ this.directive=directive; } @Override public DirectiveUIHints getUIHints() { DirectiveUIHints ret=new DirectiveUIHints(Not.class,new DirectiveUIHints.Constructor[]{ new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(Directive.class, false, "whereDirective") }, "") }, Directive.getStandardAddonHints(), "Not", "Where directive"); return ret; } @Override public void endQuery(QueryContext context) throws QueryException { directive.endQuery(context); } @Override public boolean startQuery(QueryContext context) throws QueryException { return directive.startQuery(context); } @Override public boolean includeRow(QueryContext context, ResultRow input) throws QueryException { return !directive.includeRow(context, input); } @Override public String debugStringParams(String indent) { return debugStringInner(directive,indent); } }
2,177
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Variant.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/Variant.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * Variant.java * * */ package org.wandora.query2; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public class Variant extends Directive implements DirectiveUIHints.Provider { private TopicOperand lang; private TopicOperand type; public Variant(){ this(null,null); } public Variant(Object type){ this(type,null); } public Variant(Object type,Object lang){ this.type=(type==null?null:new TopicOperand(type)); this.lang=(lang==null?null:new TopicOperand(lang)); } @Override public DirectiveUIHints getUIHints() { DirectiveUIHints ret=new DirectiveUIHints(Variant.class,new DirectiveUIHints.Constructor[]{ new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{}, ""), new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(TopicOperand.class, false, "type"), }, ""), new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(TopicOperand.class, false, "type"), new DirectiveUIHints.Parameter(TopicOperand.class, false, "lang"), }, "") }, Directive.getStandardAddonHints(), "Variant", "Topic map"); return ret; } @Override public boolean startQuery(QueryContext context) throws QueryException { boolean ret=true; if(type!=null) ret&=type.startQuery(context); if(lang!=null) ret&=lang.startQuery(context); return ret; } @Override public void endQuery(QueryContext context) throws QueryException { if(type!=null) type.endQuery(context); if(lang!=null) lang.endQuery(context); } @Override public ResultIterator queryIterator(QueryContext context, ResultRow input) throws QueryException { Object o=input.getActiveValue(); if(o==null) return new ResultIterator.EmptyIterator(); try{ if(!(o instanceof Topic)){ TopicMap tm=context.getTopicMap(); o=tm.getTopic(o.toString()); if(o==null) return new ResultIterator.EmptyIterator(); } if(type!=null && lang!=null){ Topic typeT=type.getOperandTopic(context, input); Topic langT=lang.getOperandTopic(context, input); if(typeT==null || langT==null) return input.addValue(DEFAULT_COL, null).toIterator(); HashSet<Topic> scope=new HashSet<Topic>(); scope.add(typeT); scope.add(langT); String name=((Topic)o).getVariant(scope); return input.addValue(DEFAULT_COL, name).toIterator(); } else{ Topic typeT=(type==null?null:type.getOperandTopic(context,input)); Topic langT=(lang==null?null:lang.getOperandTopic(context,input)); if(type!=null && typeT==null) return new ResultIterator.EmptyIterator(); if(lang!=null && langT==null) return new ResultIterator.EmptyIterator(); Set<Set<Topic>> scopes=((Topic)o).getVariantScopes(); ArrayList<ResultRow> ret=new ArrayList<ResultRow>(); Topic langType=context.getTopicMap().getTopic(TMBox.LANGUAGE_SI); Topic typeType=context.getTopicMap().getTopic(TMBox.VARIANT_NAME_VERSION_SI); if(langType==null || typeType==null) return new ResultIterator.EmptyIterator(); for(Set<Topic> scope : scopes){ Topic variantLang=null; Topic variantType=null; for(Topic t : scope){ if(t.isOfType(langType)) variantLang=t; if(t.isOfType(typeType)) variantType=t; } if( variantType!=null && variantLang!=null && ( (lang==null && type==null) || (lang!=null && langT.mergesWithTopic(variantLang)) || (type!=null && typeT.mergesWithTopic(variantType)) ) ){ String v=((Topic)o).getVariant(scope); if(lang==null && type==null) ret.add(input.addValues(new String[]{DEFAULT_NS+"variant_type",DEFAULT_NS+"variant_lang",DEFAULT_COL}, new Object[]{variantType,variantLang,v})); else if(lang==null) ret.add(input.addValues(new String[]{DEFAULT_NS+"variant_lang",DEFAULT_COL}, new Object[]{variantLang,v})); else ret.add(input.addValues(new String[]{DEFAULT_NS+"variant_type",DEFAULT_COL}, new Object[]{variantType,v})); } } return new ResultIterator.ListIterator(ret); } }catch(TopicMapException tme){ throw new QueryException(tme); } } }
6,114
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
BaseName.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/BaseName.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * BaseName.java * * */ package org.wandora.query2; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public class BaseName extends Directive implements DirectiveUIHints.Provider { public BaseName(){ } @Override public DirectiveUIHints getUIHints() { DirectiveUIHints ret=new DirectiveUIHints(BaseName.class,new DirectiveUIHints.Constructor[]{ new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ }, "") }, Directive.getStandardAddonHints(), "BaseName", "Topic map"); return ret; } @Override public ResultIterator queryIterator(QueryContext context, ResultRow input) throws QueryException { Object o=input.getActiveValue(); if(o==null) return new ResultIterator.EmptyIterator(); try{ if(!(o instanceof Topic)){ TopicMap tm=context.getTopicMap(); o=tm.getTopic(o.toString()); if(o==null) return new ResultIterator.EmptyIterator(); } return input.addValue(Directive.DEFAULT_COL, ((Topic)o).getBaseName()).toIterator(); }catch(TopicMapException tme){ throw new QueryException(tme); } } }
2,182
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
QueryRunner.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/QueryRunner.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.query2; import java.io.PrintWriter; import java.io.StringWriter; import java.util.ArrayList; import java.util.Collection; import javax.script.ScriptEngine; import javax.script.ScriptException; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.utils.ScriptManager; /** * * This is a utility class to help with running queries read from a query * script in a String. The CatchException versions are mostly meant for Velocity * where catching exceptions is impossible in the template code. Instead you * can just check for an exception in the result after the method finishes. * * @author olli */ public class QueryRunner { protected String scriptEngineName = null; static protected ScriptManager scriptManager = new ScriptManager(); protected ScriptEngine scriptEngine; /** * Initialize the runner with the specified scripting engine. Give the * string "none" as scripting engine name to not initialize any engine. In * this case, you may only use the runQuery methods that take a directive * directly instead of a query script. * * @param scriptEngineName */ public QueryRunner(String scriptEngineName){ this.scriptEngineName=scriptEngineName; if(this.scriptEngineName==null || !this.scriptEngineName.trim().equals("none")) { if(scriptEngineName==null) this.scriptEngine=scriptManager.getScriptEngine(ScriptManager.getDefaultScriptEngine()); else this.scriptEngine=scriptManager.getScriptEngine(scriptEngineName); if(this.scriptEngine==null) throw new RuntimeException("Couldn't find a suitable script engine"); } } /** * Initialize the runner with the default scripting engine. */ public QueryRunner(){ this(null); } public ArrayList<ResultRow> runQuery(String query, Topic contextTopic) throws ScriptException, QueryException { ArrayList<Topic> context=new ArrayList<Topic>(); context.add(contextTopic); return runQuery(query,context); } public QueryResult runQueryCatchException(String query, Topic contextTopic) { try{ return new QueryResult(runQuery(query,contextTopic)); } catch(Exception e){ return new QueryResult(e); } } public ArrayList<ResultRow> runQuery(Directive directive, Topic contextTopic) throws QueryException { ArrayList<Topic> context=new ArrayList<Topic>(); context.add(contextTopic); return runQuery(directive,context); } public QueryResult runQueryCatchException(Directive directive, Topic contextTopic) { try{ return new QueryResult(runQuery(directive,contextTopic)); } catch(Exception e){ return new QueryResult(e); } } public ArrayList<ResultRow> runQuery(String query, Collection<Topic> contextTopics) throws ScriptException, QueryException { if(this.scriptEngine==null) throw new RuntimeException("No scripting engine initialised"); Directive directive = null; Object o=scriptEngine.eval(query); if(o==null) o=scriptEngine.get("query"); if(o!=null && o instanceof Directive) { directive = (Directive)o; } if(directive==null) throw new RuntimeException("Couldn't get directive from script"); return runQuery(directive,contextTopics); } public QueryResult runQueryCatchException(String query, Collection<Topic> contextTopics) { try{ return new QueryResult(runQuery(query,contextTopics)); } catch(Exception e){ return new QueryResult(e); } } public ArrayList<ResultRow> runQuery(Directive directive, Collection<Topic> contextTopics) throws QueryException { TopicMap tm=null; ArrayList<ResultRow> context=new ArrayList<ResultRow>(); for(Topic t : contextTopics){ if(tm==null) tm=t.getTopicMap(); context.add(new ResultRow(t)); } if(tm==null) return new ArrayList<ResultRow>(); // no topics in contextTopics QueryContext queryContext=new QueryContext(tm, "en"); if(context.isEmpty()){ return new ArrayList<ResultRow>(); } else if(context.size()==1){ return directive.doQuery(queryContext, context.get(0)); } else{ return directive.from(new Static(context)).doQuery(queryContext, context.get(0)); } } public QueryResult runQueryCatchException(Directive directive,Collection<Topic> contextTopics) { try{ return new QueryResult(runQuery(directive,contextTopics)); } catch(Exception e){ return new QueryResult(e); } } public static class QueryResult { public ArrayList<ResultRow> rows; public Throwable exception; public QueryResult(ArrayList<ResultRow> rows){ this.rows=rows; } public QueryResult(Throwable exception){ this.exception=exception; } public ArrayList<ResultRow> getRows() { return rows; } public boolean isException() { return exception!=null; } public Throwable getException() { return exception; } public String getStackTrace() { if(exception==null) return ""; StringWriter sw=new StringWriter(); exception.printStackTrace(new PrintWriter(sw)); return sw.toString(); } public Object[][] getData() { String[] columns = getColumns(); Object[][] data = new Object[rows.size()][columns.length]; for(int i=0; i<rows.size(); i++){ ResultRow row=rows.get(i); ArrayList<String> roles=row.getRoles(); for(int j=0; j<columns.length; j++){ String r=columns[j]; int ind=roles.indexOf(r); if(ind!=-1) data[i][j]=row.getValue(ind); else data[i][j]=null; } } return data; } public String[] getColumns() { ArrayList<String> columns=new ArrayList<>(); for(ResultRow row : rows) { for(int i=0;i<row.getNumValues();i++){ String l=row.getRole(i); if(!columns.contains(l)) columns.add(l); } } return columns.toArray( new String[] {} ); } } }
7,453
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Concat.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/Concat.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * Concat.java * */ package org.wandora.query2; /** * * @author olli */ public class Concat extends Directive implements DirectiveUIHints.Provider { private Directive directive; private String delim="; "; public Concat(){} public Concat(Directive directive,String delim){ this.directive=directive; this.delim=delim; } public Concat(Directive directive){ this(directive,"; "); } @Override public DirectiveUIHints getUIHints() { DirectiveUIHints ret=new DirectiveUIHints(Concat.class,new DirectiveUIHints.Constructor[]{ new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(Directive.class, false, "directive") }, ""), new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(Directive.class, false, "directive"), new DirectiveUIHints.Parameter(String.class, false, "delim") }, "") }, Directive.getStandardAddonHints(), "Concat", "Aggregate"); return ret; } @Override public boolean startQuery(QueryContext context) throws QueryException { return directive.startQuery(context); } @Override public void endQuery(QueryContext context) throws QueryException { directive.endQuery(context); } @Override public ResultIterator queryIterator(QueryContext context, ResultRow input) throws QueryException { ResultIterator iter=directive.queryIterator(context, input); StringBuilder sb=new StringBuilder(); boolean first=true; while(iter.hasNext()) { if(!first) sb.append(delim); else first=false; ResultRow row=iter.next(); Object v=row.getActiveValue(); if(v==null) continue; String s=v.toString(); sb.append(s); } return input.addValue(DEFAULT_COL, sb.toString()).toIterator(); } @Override public String debugStringParams(String indent) { return debugStringInner(directive,indent); } }
3,056
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
From.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/From.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * From.java * */ package org.wandora.query2; import java.util.NoSuchElementException; /** * * @author olli */ public class From extends Directive implements DirectiveUIHints.Provider { private Directive to; private Directive from; public From(){} public From(Directive to,Directive from){ this.to=to; this.from=from; } @Override public DirectiveUIHints getUIHints() { DirectiveUIHints ret=new DirectiveUIHints(From.class,new DirectiveUIHints.Constructor[]{ new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(Directive.class, false, "to"), new DirectiveUIHints.Parameter(Directive.class, false, "from") }, "") }, Directive.getStandardAddonHints(), "From", "Framework"); return ret; } /* @Override public ArrayList<ResultRow> query(QueryContext context,ResultRow input,String as) throws QueryException { ArrayList<ResultRow> res=from.query(context,input,null); ArrayList<ResultRow> ret=new ArrayList<ResultRow>(); for(ResultRow row : res){ ArrayList<ResultRow> res2=to.query(context,row,null); for(ResultRow row2 : res2){ ret.add(row2); } } return ret; }*/ @Override public boolean startQuery(QueryContext context) throws QueryException { boolean r=to.startQuery(context); r&=from.startQuery(context); return r; } @Override public void endQuery(QueryContext context) throws QueryException { to.endQuery(context); from.endQuery(context); } @Override public ResultIterator queryIterator(QueryContext context,ResultRow input) throws QueryException { return new FromIterator(context,input); } @Override public boolean isStatic(){ return from.isStatic(); } public String debugStringParams(String indent){ return debugStringInner(new Directive[]{to,from},indent); } private class FromIterator extends ResultIterator { public ResultIterator fromIter; public ResultIterator toIter; public QueryContext context; public ResultRow input; public ResultRow nextRow; public FromIterator(QueryContext context,ResultRow input) throws QueryException { this.context=context; this.input=input; this.fromIter=from.queryIterator(context, input); /* if( !(fromIter instanceof ResultIterator.BufferedIterator) && !(fromIter instanceof ResultIterator.ListIterator) && !(fromIter instanceof ResultIterator.EmptyIterator) && !(fromIter instanceof ResultIterator.SingleIterator) ) fromIter=new ResultIterator.BufferedIterator(fromIter);*/ // this.fromIter=new ResultIterator.ListIterator(from.query(context,input,null)); } public boolean hasNext() throws QueryException { if(nextRow!=null) return true; if(context.checkInterrupt()) throw new QueryException("Execution interrupted"); while( (toIter==null || !toIter.hasNext()) && fromIter.hasNext() ){ ResultRow row=fromIter.next(); toIter=to.queryIterator(context, row); } if(toIter!=null && toIter.hasNext()) { nextRow=toIter.next(); return true; } else return false; } public ResultRow next() throws QueryException, NoSuchElementException { if(hasNext()) { ResultRow temp=nextRow; nextRow=null; return temp; } else throw new NoSuchElementException(); } public void dispose() throws QueryException { fromIter.dispose(); if(toIter!=null) toIter.dispose(); } public void reset() throws QueryException { fromIter=from.queryIterator(context, input); toIter=null; nextRow=null; } } }
5,053
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/query2/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 * */ package org.wandora.query2; /** * * @author olli */ public abstract class FilterDirective extends Directive { public abstract ResultRow processRow(QueryContext context,ResultRow input) throws QueryException; @Override public ResultIterator queryIterator(QueryContext context,ResultRow input) throws QueryException { ResultRow res=processRow(context,input); if(res==null) return new ResultIterator.EmptyIterator(); else return res.toIterator(); } }
1,328
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Eval.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/Eval.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * Eval.java * * */ package org.wandora.query2; import java.util.ArrayList; import java.util.HashMap; import javax.script.Bindings; import javax.script.Compilable; import javax.script.CompiledScript; import javax.script.ScriptEngine; import javax.script.ScriptException; import org.wandora.application.WandoraScriptManager; /** * * @author olli */ public class Eval extends Directive { protected String script; protected ScriptEngine scriptEngine; protected CompiledScript compiled; protected HashMap<String,Object> objects; protected Object constructorParam; protected boolean clearHashMapBetweenJoins=true; public Eval(){ } public Eval(String script,Object param){ this.script=script; this.constructorParam=param; scriptEngine=new WandoraScriptManager().getScriptEngine(WandoraScriptManager.getDefaultScriptEngine()); } public Eval(String script){ this(script,null); } @Override public void endQuery(QueryContext context) throws QueryException { compiled=null; } @Override public boolean startQuery(QueryContext context) throws QueryException { objects=new HashMap<String,Object>(); if(scriptEngine instanceof Compilable){ try{ compiled=((Compilable)scriptEngine).compile(script); return true; }catch(ScriptException se){ throw new QueryException(se); } } else return true; } @Override public String debugStringParams() { return "\""+script.replace("\\", "\\\\").replace("\"","\\\"")+"\""; } protected ResultRow input; protected QueryContext context; public Object eval(Object val) throws QueryException { return val; } public Object get(String key){return objects.get(key);} public Object set(String key,Object value){return objects.put(key,value);} public ResultIterator empty(){return new ResultIterator.EmptyIterator();} @Override public ResultIterator queryIterator(QueryContext context, ResultRow input) throws QueryException { if(clearHashMapBetweenJoins) objects.clear(); Object o=null; if(script!=null){ Bindings bindings=scriptEngine.createBindings(); bindings.put("input", input); bindings.put("context", context); bindings.put("val", input.getActiveValue()); bindings.put("dir", this); bindings.put("param",constructorParam); try{ if(compiled!=null) o=compiled.eval(bindings); else o=scriptEngine.eval(script, bindings); }catch(ScriptException se){ throw new QueryException(se); } } else{ this.input=input; this.context=context; o=eval(input.getActiveValue()); } if(o!=null && o instanceof ResultIterator){ return (ResultIterator)o; } else if(o!=null && o instanceof ResultRow){ return ((ResultRow)o).toIterator(); } else if(o!=null && o instanceof ArrayList){ return new ResultIterator.ListIterator((ArrayList<ResultRow>)o); } else { return input.addValue(DEFAULT_COL, o).toIterator(); } } }
4,180
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
QueryException.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/QueryException.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * QueryException.java * */ package org.wandora.query2; /** * * @author olli */ public class QueryException extends Exception { public QueryException(){ super(); } public QueryException(String message){ super(message); } public QueryException(String message,Throwable cause){ super(message,cause); } public QueryException(Throwable cause){ super(cause); } }
1,232
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/query2/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 * */ package org.wandora.query2; import java.util.HashMap; import org.wandora.topicmap.TopicMap; /** * * @author olli */ public class QueryContext { private String lang; private TopicMap tm; private HashMap<String,Object> parameters; private boolean interrupt; /** Creates a new instance of QueryContext */ public QueryContext(TopicMap tm,String lang,HashMap<String,Object> parameters) { this.tm=tm; this.lang=lang; this.parameters=parameters; interrupt=false; } public QueryContext(String lang,HashMap<String,Object> parameters) { this.lang=lang; this.parameters=parameters; interrupt=false; } public QueryContext(String lang) { this(null,lang,new HashMap<String,Object>()); } public QueryContext(TopicMap tm,String lang) { this(tm,lang,new HashMap<String,Object>()); } public boolean checkInterrupt(){ return interrupt; } public void interrupt(){ interrupt=true; } public Object getParameter(String key){ return parameters.get(key); } public void setParameter(String key,Object o){ parameters.put(key,o); } public String getContextLanguage(){ return lang; } public void setTopicMap(TopicMap tm){ this.tm=tm; } public TopicMap getTopicMap(){ return tm; } }
2,235
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Contains.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/Contains.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.query2; /** * * @author olli */ public class Contains extends WhereDirective implements DirectiveUIHints.Provider { private Operand operand1; private Operand operand2; private boolean caseInsensitive=true; public Contains(){} public Contains(Object operand2){ this(new Identity(),operand2); } public Contains(Object operand1,Object operand2){ this(operand1, operand2, true); } public Contains(Object operand1,Object operand2,boolean caseInsensitive){ this.operand1=Operand.makeOperand(operand1); this.operand2=Operand.makeOperand(operand2); this.caseInsensitive=caseInsensitive; } @Override public DirectiveUIHints getUIHints() { DirectiveUIHints ret=new DirectiveUIHints(Contains.class,new DirectiveUIHints.Constructor[]{ new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(Operand.class, false, "text"), new DirectiveUIHints.Parameter(Operand.class, false, "searchFor") }, ""), new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(Operand.class, false, "text"), new DirectiveUIHints.Parameter(Operand.class, false, "searchFor"), new DirectiveUIHints.Parameter(Boolean.class, false, "caseInsensitive") }, ""), new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(Operand.class, false, "searchFor") }, "") }, Directive.getStandardAddonHints(), "Contains", "Where directive"); return ret; } @Override public void endQuery(QueryContext context) throws QueryException { operand1.endQuery(context); operand2.endQuery(context); } @Override public boolean startQuery(QueryContext context) throws QueryException { return operand1.startQuery(context) & operand2.startQuery(context); } @Override public boolean includeRow(QueryContext context,ResultRow row) throws QueryException { Object v1=operand1.getOperandObject(context, row); Object v2=operand2.getOperandObject(context, row); if(v1==null && v2==null) return false; else if(v1==null && v2!=null) return false; else if(v1!=null && v2==null) return false; else { String s1=v1.toString(); String s2=v2.toString(); if(caseInsensitive) { s1=s1.toLowerCase(); s2=s2.toLowerCase(); } return s1.indexOf(s2)>=0; } } }
3,664
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AllTopics.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/AllTopics.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * AllTopics.java * * */ package org.wandora.query2; import java.util.Iterator; import java.util.NoSuchElementException; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicIterator; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public class AllTopics extends Directive implements DirectiveUIHints.Provider { public AllTopics(){ } @Override public DirectiveUIHints getUIHints() { DirectiveUIHints ret=new DirectiveUIHints(AllTopics.class,new DirectiveUIHints.Constructor[]{ new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ }, "") }, Directive.getStandardAddonHints(), "AllTopics", "Topic map"); return ret; } @Override public boolean isStatic() { return true; } @Override public ResultIterator queryIterator(QueryContext context, ResultRow input) throws QueryException { return new AllTopicsIterator(context); } private static class AllTopicsIterator extends ResultIterator { public QueryContext context; public Iterator<Topic> iter; public AllTopicsIterator(QueryContext context) throws QueryException { this.context=context; try{ this.iter=context.getTopicMap().getTopics(); }catch(TopicMapException tme){ throw new QueryException(tme); } } public boolean hasNext() throws QueryException { if(context.checkInterrupt()) throw new QueryException("Execution interrupted"); return iter.hasNext(); } public ResultRow next() throws NoSuchElementException,QueryException { Topic t=iter.next(); return new ResultRow(t); } public void dispose() throws QueryException { // see notes in TopicIterator about disposing of the iterator properly if(iter instanceof TopicIterator) ((TopicIterator)iter).dispose(); else while(iter.hasNext()) {iter.next();} } public void reset() throws QueryException { dispose(); // see note in dispose try{ this.iter=context.getTopicMap().getTopics(); }catch(TopicMapException tme){ throw new QueryException(tme); } } } }
3,236
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Topics.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/Topics.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * Topics.java */ package org.wandora.query2; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public class Topics extends Directive implements DirectiveUIHints.Provider { protected boolean useBN; public Topics(boolean baseName){ useBN=baseName; } public Topics(){ this(false); } @Override public DirectiveUIHints getUIHints() { DirectiveUIHints ret=new DirectiveUIHints(Topics.class,new DirectiveUIHints.Constructor[]{ new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{}, ""), new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(Boolean.class, false, "baseName"), }, "") }, Directive.getStandardAddonHints(), "Topics", "Topic map"); return ret; } @Override public ResultIterator queryIterator(QueryContext context, ResultRow input) throws QueryException { Object o=input.getActiveValue(); if(o!=null){ try{ Topic t; if(useBN) t=context.getTopicMap().getTopicWithBaseName(o.toString()); else t=context.getTopicMap().getTopic(o.toString()); if(t!=null){ return input.addValue(Directive.DEFAULT_COL, t).toIterator(); } } catch(TopicMapException tme){ throw new QueryException(tme); } } return new ResultIterator.EmptyIterator(); } }
2,466
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Variant2.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/Variant2.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * Variant2.java * * */ package org.wandora.query2; import java.util.HashSet; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * Alternative version of Variant directive that can be used to get * variants of any scope, not just variants of the type + language scheme. * * @author olli */ public class Variant2 extends Directive implements DirectiveUIHints.Provider { private TopicOperand[] scope; public Variant2(){} public Variant2(Object ... scope){ this.scope=new TopicOperand[scope.length]; for(int i=0;i<scope.length;i++) this.scope[i]=new TopicOperand(scope[i]); } @Override public DirectiveUIHints getUIHints() { DirectiveUIHints ret=new DirectiveUIHints(Variant2.class,new DirectiveUIHints.Constructor[]{ new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(TopicOperand.class, true, "scope"), }, "") }, Directive.getStandardAddonHints(), "Variant2", "Topic map"); return ret; } @Override public boolean startQuery(QueryContext context) throws QueryException { boolean ret=true; for(int i=0;i<scope.length;i++){ ret&=scope[i].startQuery(context); } return ret; } @Override public void endQuery(QueryContext context) throws QueryException { for(int i=0;i<scope.length;i++){ scope[i].endQuery(context); } } @Override public ResultIterator queryIterator(QueryContext context, ResultRow input) throws QueryException { Object o=input.getActiveValue(); if(o==null) return new ResultIterator.EmptyIterator(); try{ if(!(o instanceof Topic)){ TopicMap tm=context.getTopicMap(); o=tm.getTopic(o.toString()); if(o==null) return new ResultIterator.EmptyIterator(); } HashSet<Topic> scope=new HashSet<Topic>(); for(int i=0;i<this.scope.length;i++){ scope.add(this.scope[i].getOperandTopic(context, input)); } String name=((Topic)o).getVariant(scope); return input.addValue(DEFAULT_COL, name).toIterator(); }catch(TopicMapException tme){ throw new QueryException(tme); } } }
3,298
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Players.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/Players.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * Players.java * * */ package org.wandora.query2; import java.util.ArrayList; import java.util.Collection; import org.wandora.query2.DirectiveUIHints.Addon; import org.wandora.query2.DirectiveUIHints.Constructor; import org.wandora.query2.DirectiveUIHints.Parameter; import org.wandora.topicmap.Association; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.utils.Tuples.T2; /** * * @author olli */ public class Players extends Directive implements DirectiveUIHints.Provider { private TopicOperand associationType; private TopicOperand[] roles; private TopicOperand inputRole; private String[] columns=null; public Players(){ this(null,null); } public Players(Object associationType){ this(associationType,null); } public Players(Object associationType,Object[] roles){ this.associationType=(associationType==null?null:TopicOperand.makeTopicOperand(associationType)); this.roles=(roles==null?null:TopicOperand.makeTopicOperands(roles)); this.inputRole=null; } public Players(Object associationType,Object r1){ this(associationType,new Object[]{r1});} public Players(Object associationType,Object r1,Object r2){ this(associationType,new Object[]{r1,r2});} public Players(Object associationType,Object r1,Object r2,Object r3){ this(associationType,new Object[]{r1,r2,r3});} public Players(Object associationType,Object r1,Object r2,Object r3,Object r4){ this(associationType,new Object[]{r1,r2,r3,r4});} @Override public DirectiveUIHints getUIHints() { DirectiveUIHints ret=new DirectiveUIHints(Players.class,new Constructor[]{ new Constructor(new Parameter[]{new Parameter(TopicOperand.class, Object.class, false, "association type")}, ""), new Constructor(new Parameter[]{ new Parameter(TopicOperand.class, Object.class, false, "association type"), new Parameter(TopicOperand.class, Object[].class, true, "players") }, "") }, Directive.getStandardAddonHints( new Addon[]{ new Addon("usingColumns", new Parameter[]{new Parameter(String.class, true, "column")}, "usingColumns") , new Addon("whereInputIs", new Parameter[]{new Parameter(TopicOperand.class, Object.class, false, "role")}, "whereInputIs") } ), "Players", "Topic map"); return ret; } public Players usingColumns(Object[] cols){ this.columns=new String[cols.length]; for(int i=0;i<cols.length;i++) this.columns[i]=cols[i].toString(); return this; } public Players usingColumns(Object c1){ return usingColumns(new Object[]{c1}); } public Players usingColumns(Object c1,Object c2){ return usingColumns(new Object[]{c1,c2}); } public Players usingColumns(Object c1,Object c2,Object c3){ return usingColumns(new Object[]{c1,c2,c3}); } public Players usingColumns(Object c1,Object c2,Object c3,Object c4){ return usingColumns(new Object[]{c1,c2,c3,c4}); } public Players whereInputIs(Object role){ inputRole=TopicOperand.makeTopicOperand(role); return this; } @Override public void endQuery(QueryContext context) throws QueryException { if(associationType!=null) associationType.endQuery(context); if(roles!=null) Operand.endOperands(context, roles); } @Override public boolean startQuery(QueryContext context) throws QueryException { boolean ret=true; if(associationType!=null) ret&=associationType.startQuery(context); if(roles!=null) ret&=Operand.startOperands(context, roles); return ret; } @Override public ResultIterator queryIterator(QueryContext context, ResultRow input) throws QueryException { TopicMap tm=context.getTopicMap(); try{ Object o=input.getActiveValue(); if(o==null) return new ResultIterator.EmptyIterator(); if(!(o instanceof Topic)){ o=tm.getTopic(o.toString()); if(o==null) return new ResultIterator.EmptyIterator(); } Topic t=(Topic)o; ArrayList<ResultRow> ret=new ArrayList<ResultRow>(); Topic atype=null; if(associationType!=null) atype=associationType.getOperandTopic(context, input); Topic inputRoleTopic=null; if(inputRole!=null) inputRoleTopic=inputRole.getOperandTopic(context, input); Topic[] roleTopics=null; String[] roleStrings=null; if(roles!=null){ if(columns!=null) roleStrings=columns; boolean setRoleStrings=(roleStrings==null); roleTopics=new Topic[roles.length]; if(setRoleStrings) roleStrings=new String[roles.length]; for(int i=0;i<roles.length;i++){ T2<Topic,String> oper=roles[i].getOperandTopicAndSI(context, input); if(oper.e2==null) continue; roleTopics[i]=oper.e1; if(setRoleStrings) roleStrings[i]=oper.e2; } } Collection<Association> associations; if(associationType!=null) associations=t.getAssociations(atype); else associations=t.getAssociations(); for(Association a : associations){ if(context.checkInterrupt()) throw new QueryException("Execution interrupted"); if(inputRoleTopic!=null){ Topic p=a.getPlayer(inputRoleTopic); if(p==null) continue; if(!p.mergesWithTopic(t)) continue; } if(roles!=null){ Object[] newValues=new Object[roles.length]; for(int i=0;i<roleTopics.length;i++){ if(roleTopics[i]==null){ newValues[i]=null; } else{ Topic p=a.getPlayer(roleTopics[i]); newValues[i]=p; } } ret.add(input.addValues(roleStrings, newValues)); } else { Object[] newValues=null; int counter=0; if(associationType==null){ roleStrings=new String[a.getRoles().size()+1]; newValues=new Object[a.getRoles().size()+1]; roleStrings[0]=Directive.DEFAULT_NS+"association_type"; newValues[0]=a.getType(); counter=1; } else{ roleStrings=new String[a.getRoles().size()]; newValues=new Object[a.getRoles().size()]; } for(Topic role : a.getRoles()){ roleStrings[counter]=role.getOneSubjectIdentifier().toString(); newValues[counter]=a.getPlayer(role); counter++; } ret.add(input.addValues(roleStrings, newValues)); } } if(ret.size()==0) return new ResultIterator.EmptyIterator(); else if(ret.size()==1) return new ResultIterator.SingleIterator(ret.get(0)); else return new ResultIterator.ListIterator(ret); }catch(TopicMapException tme){ throw new QueryException(tme); } } }
8,626
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DirectiveManager.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/DirectiveManager.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.query2; import java.io.File; import java.io.IOException; import java.lang.reflect.Modifier; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import org.wandora.application.Wandora; /** * This class can be used to get a list of directives, possible other similar * services in the future. It'll automatically find every directive in the * org.wandora.query2 package. Other directives need to register themselves. * * @author olli */ public class DirectiveManager { private static DirectiveManager instance; public static synchronized DirectiveManager getDirectiveManager(){ if(instance==null) instance=new DirectiveManager(); return instance; } private final ArrayList<Class<? extends Directive>> scannedDirectives; private final ArrayList<Class<? extends Directive>> registeredDirectives; private DirectiveManager(){ scannedDirectives=new ArrayList<>(); scanDirectives(); registeredDirectives=new ArrayList<>(); } public void registerDirective(Class<? extends Directive> cls){ synchronized(registeredDirectives){ registeredDirectives.add(cls); } } private void scanDirectives() { try { String pkg="org.wandora.query2"; String path = pkg.replace('.', File.separatorChar); Enumeration<URL> toolResources = ClassLoader.getSystemResources(path); while(toolResources.hasMoreElements()) { URL url=toolResources.nextElement(); if(!url.getProtocol().equals("file")) continue; try{ File dir=new File(url.toURI()); if(!dir.isDirectory()) continue; for(File f : dir.listFiles()){ String file=f.getAbsolutePath(); if(!file.endsWith(".class")) continue; int ind=file.lastIndexOf(path); if(ind<0) continue; String cls=file.substring(ind,file.length()-6); if(cls.startsWith(""+File.separatorChar)) cls=cls.substring(1); cls=cls.replace(File.separatorChar, '.'); try { Class<?> c=Class.forName(cls); if(Directive.class.isAssignableFrom(c)){ if(!Modifier.isAbstract(c.getModifiers())){ scannedDirectives.add((Class<? extends Directive>)c); } } } catch (ClassNotFoundException ex) { // Wandora.getWandora().handleError(ex); // ignore } } } catch(URISyntaxException use){ // Wandora.getWandora().handleError(use); // ignore } } } catch (IOException ex) { Wandora.getWandora().handleError(ex); } } public List<Class<? extends Directive>> getDirectives(){ List<Class<? extends Directive>> ret=new ArrayList<>(scannedDirectives.size()+registeredDirectives.size()); ret.addAll(scannedDirectives); synchronized(registeredDirectives){ ret.addAll(registeredDirectives); } return ret; } }
4,456
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Instances.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/Instances.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * Instances.java * * */ package org.wandora.query2; import java.util.ArrayList; import java.util.Collection; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public class Instances extends Directive implements DirectiveUIHints.Provider { public Instances(){ } @Override public DirectiveUIHints getUIHints() { DirectiveUIHints ret=new DirectiveUIHints(Instances.class,new DirectiveUIHints.Constructor[]{ new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ }, "") }, Directive.getStandardAddonHints(), "Instances", "Topic map"); return ret; } @Override public ArrayList<ResultRow> query(QueryContext context, ResultRow input) throws QueryException { Object o=input.getActiveValue(); if(o==null) return new ArrayList<ResultRow>(); try{ if(!(o instanceof Topic)){ TopicMap tm=context.getTopicMap(); o=tm.getTopic(o.toString()); if(o==null) return new ArrayList<ResultRow>(); } Collection<Topic> instances=((Topic)o).getTopicMap().getTopicsOfType(((Topic)o)); ArrayList<ResultRow> ret=new ArrayList<ResultRow>(); for(Topic t : instances){ ret.add(input.addValue(Directive.DEFAULT_COL, t)); } return ret; }catch(TopicMapException tme){ throw new QueryException(tme); } } }
2,438
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DirectiveUIHints.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/DirectiveUIHints.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.query2; import java.io.Serializable; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Objects; import org.wandora.application.Wandora; import com.fasterxml.jackson.annotation.JsonIgnore; /** * * @author olli */ public class DirectiveUIHints implements Serializable { protected String label; protected String category; protected Constructor[] constructors; protected Addon[] addons; protected Class<? extends Directive> cls; public DirectiveUIHints(Class<? extends Directive> cls) { this.cls=cls; } public DirectiveUIHints(Class<? extends Directive> cls,Constructor[] constructors) { this(cls); this.constructors = constructors; } public DirectiveUIHints(Class<? extends Directive> cls,Constructor[] constructors, Addon[] addons) { this(cls); this.constructors = constructors; this.addons = addons; } public DirectiveUIHints(Class<? extends Directive> cls,Constructor[] constructors, Addon[] addons, String label, String category) { this(cls); this.constructors = constructors; this.addons = addons; this.label = label; this.category = category; } public Class<? extends Directive> getDirectiveClass(){ return cls; } public String getCategory(){ return category; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public void setCategory(String s){ this.category=s; } public Constructor[] getConstructors(){ return constructors; } public Addon[] getAddons(){ return addons; } @Override public String toString(){ return label; } public static void cleanConstructorArray(ArrayList<Constructor> constructors){ // TODO: remove redundant constructors. For example, if we have // one which takes a directive array and then for convenience we also // have versions which take one, or two, or three directives, remove all // but the array version. // // At the moment, pretty much all Directives implement DirectiveUIHInts.Provider // and will give a sensible constructor array through that mechanism. // Ideally the above should still be added to this method for Directives // that don't implement the Provider but it's not essential at the moment. } public static DirectiveUIHints guessHints(Class<? extends Directive> cls){ ArrayList<Constructor> constructors=new ArrayList<Constructor>(); Outer: for(java.lang.reflect.Constructor<?> c : cls.getConstructors()){ ArrayList<Parameter> ps=new ArrayList<Parameter>(); Class<?>[] params=c.getParameterTypes(); for (Class<?> param : params) { boolean multiple=false; if(param.isArray()) { multiple=true; param=param.getComponentType(); if(param.isArray()) { // multidimensional array continue Outer; } } String label=param.getSimpleName(); if(multiple) label+="[]"; Parameter p=new Parameter(param, multiple, label); ps.add(p); } String label=c.getName(); constructors.add(new Constructor(ps.toArray(new Parameter[ps.size()]),label)); } cleanConstructorArray(constructors); DirectiveUIHints ret=new DirectiveUIHints(cls,constructors.toArray(new Constructor[constructors.size()])); ret.setLabel(cls.getSimpleName()); return ret; } public static DirectiveUIHints getDirectiveUIHints(Class<? extends Directive> cls){ if(Provider.class.isAssignableFrom(cls)) { try{ Method m=cls.getMethod("getUIHints"); if(Modifier.isStatic(m.getModifiers())){ return (DirectiveUIHints)m.invoke(null); } else { return ((Provider)cls.newInstance()).getUIHints(); } }catch( IllegalAccessException | InstantiationException | NoSuchMethodException| InvocationTargetException e){ Wandora.getWandora().handleError(e); } } return guessHints(cls); } public static class Parameter implements Serializable { /** * Type of the parameter. Use Directive, Operand, String, Integer or * whatever else is suitable. Do not make this an array type though, * use the multiple flag for that. */ @JsonIgnore protected Class<?> type; /** * Sometimes the type used in a method or constructor can be different * to the type used in the UI. For example, the UI might be expecting a * TopicOperand type, but the method takes just Objects. In such a case, * the type used by the actual method is stored here. If it is an array, * type, make this an actual array type in addition to using the multiple * boolean flag. */ @JsonIgnore protected Class<?> reflectType; /** * Is this parameter an array? */ protected boolean multiple; /** * Label to show in the UI. */ protected String label; public Parameter(){} public Parameter(Class<?> type, boolean multiple, String label) { this(type,null,multiple,label); } public Parameter(Class<?> type, Class<?> reflectType, boolean multiple, String label) { this.type = type; this.reflectType = reflectType; this.multiple = multiple; this.label = label; } @Override public int hashCode() { int hash = 3; hash = 23 * hash + Objects.hashCode(this.type); hash = 23 * hash + (this.multiple ? 1 : 0); hash = 23 * hash + Objects.hashCode(this.label); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Parameter other = (Parameter) obj; if (!Objects.equals(this.type, other.type)) { return false; } if (this.multiple != other.multiple) { return false; } if (!Objects.equals(this.label, other.label)) { return false; } return true; } public String getTypeName(){ if(type==null) return null; else return type.getName(); } public void setTypeName(String s){ if(s==null) type=null; else { try{ type=Class.forName(s); } catch(ClassNotFoundException cnfe){ throw new RuntimeException(cnfe); } } } public String getReflectTypeName(){ if(reflectType==null) return null; else return reflectType.getName(); } public void setReflectTypeName(String s){ if(s==null) reflectType=null; else { try{ if(s.startsWith("[L")){ reflectType=Class.forName(s.substring(2,s.length()-1)); reflectType=Array.newInstance(reflectType, 0).getClass(); } else{ reflectType=Class.forName(s); } } catch(ClassNotFoundException cnfe){ throw new RuntimeException(cnfe); } } } @JsonIgnore public Class<?> getType() { return type; } @JsonIgnore public void setType(Class<?> type) { this.type = type; } public boolean isMultiple() { return multiple; } public void setMultiple(boolean multiple) { this.multiple = multiple; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } @JsonIgnore public Class<?> getReflectType(){ if(reflectType!=null) return reflectType; else { Class<?> ret=type; if(multiple) ret=Array.newInstance(ret, 0).getClass(); return ret; } } } public static String indent(String s,int amount){ StringBuilder sb=new StringBuilder(); String[] ss=s.split("\n"); for(int i=0;i<ss.length;i++){ for(int j=0;j<amount;j++) sb.append(" "); sb.append(ss[i]); sb.append("\n"); } return sb.toString(); } public static class Constructor implements Serializable { protected Parameter[] parameters; protected String label; public Constructor(){} public Constructor(Parameter[] params,String label){ this.parameters=params; this.label=label; } @Override public int hashCode() { int hash = 7; hash = 53 * hash + Arrays.deepHashCode(this.parameters); hash = 53 * hash + Objects.hashCode(this.label); return hash; } @Override public boolean equals(Object obj) { if (obj == null) return false; if (getClass() != obj.getClass()) return false; final Constructor other = (Constructor) obj; if (!Arrays.deepEquals(this.parameters, other.parameters)) { return false; } if (!Objects.equals(this.label, other.label)) { return false; } return true; } public Parameter[] getParameters() { return parameters; } public void setParameters(Parameter[] parameters) { this.parameters = parameters; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } @JsonIgnore public <D> java.lang.reflect.Constructor<D> getReflectConstructor(Class<D> cls) throws NoSuchMethodException { return resolveConstructor(cls); } @JsonIgnore public <D> java.lang.reflect.Constructor<D> resolveConstructor(Class<D> cls) throws NoSuchMethodException { Class[] params=new Class[parameters.length]; for(int i=0;i<params.length;i++){ params[i]=parameters[i].getReflectType(); } java.lang.reflect.Constructor<D> c=cls.getConstructor(params); return c; } } public static class Addon implements Serializable { protected Parameter[] parameters; protected String method; protected String label; public Addon(){} public Addon(String method, Parameter[] params,String label){ this.method=method; this.parameters=params; this.label=label; } @Override public int hashCode() { int hash = 7; hash = 89 * hash + Arrays.deepHashCode(this.parameters); hash = 89 * hash + Objects.hashCode(this.method); hash = 89 * hash + Objects.hashCode(this.label); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Addon other = (Addon) obj; if (!Arrays.deepEquals(this.parameters, other.parameters)) { return false; } if (!Objects.equals(this.method, other.method)) { return false; } if (!Objects.equals(this.label, other.label)) { return false; } return true; } public String getMethod() { return method; } public void setMethod(String method) { this.method = method; } public Parameter[] getParameters() { return parameters; } public void setParameters(Parameter[] parameters) { this.parameters = parameters; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } @JsonIgnore public java.lang.reflect.Method resolveMethod(Class<?> cls) throws NoSuchMethodException { Class[] params=new Class[parameters.length]; for(int i=0;i<params.length;i++){ params[i]=parameters[i].getReflectType(); } java.lang.reflect.Method m=cls.getMethod(method, params); Class<?> ret=m.getReturnType(); if(ret==null || !Directive.class.isAssignableFrom(ret)) { throw new RuntimeException("Addon method doesn't return a directive"); } return m; } } public static interface Provider { public DirectiveUIHints getUIHints(); } }
15,162
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Count.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/Count.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * Count.java * * */ package org.wandora.query2; /** * * @author olli */ public class Count extends Directive implements DirectiveUIHints.Provider { private Directive directive; public Count(){} public Count(Directive directive){ this.directive=directive; } @Override public DirectiveUIHints getUIHints() { DirectiveUIHints ret=new DirectiveUIHints(Count.class,new DirectiveUIHints.Constructor[]{ new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(Directive.class, false, "directive") }, "") }, Directive.getStandardAddonHints(), "Count", "Aggregate"); return ret; } @Override public void endQuery(QueryContext context) throws QueryException { directive.endQuery(context); } @Override public boolean startQuery(QueryContext context) throws QueryException { return directive.startQuery(context); } @Override public ResultIterator queryIterator(QueryContext context, ResultRow input) throws QueryException { ResultIterator iter=directive.queryIterator(context, input); int count=0; while(iter.hasNext()) { iter.next(); count++; } return input.addValue(DEFAULT_COL, ""+count).toIterator(); } @Override public String debugStringParams(String indent) { return debugStringInner(directive,indent); } }
2,371
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Identity.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/Identity.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * Identity.java * * */ package org.wandora.query2; /** * * @author olli */ public class Identity extends Directive implements DirectiveUIHints.Provider { public Identity(){ } @Override public DirectiveUIHints getUIHints() { DirectiveUIHints ret=new DirectiveUIHints(Identity.class,new DirectiveUIHints.Constructor[]{ new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{}, "") }, Directive.getStandardAddonHints(), "Identity", "Primitive"); return ret; } @Override public ResultIterator queryIterator(QueryContext context, ResultRow input) throws QueryException { return input.toIterator(); } }
1,553
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/query2/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 * */ package org.wandora.query2; import java.util.ArrayList; import java.util.List; /** * * @author olli */ public class ResultRow { private ArrayList<String> roles; private ArrayList<Object> values; private int activeColumn; private int hashCode=-1; public ResultRow(){ this(new ArrayList<String>(),new ArrayList<Object>(),-1,true); } public ResultRow(List<String> roles,List<Object> values,int activeColumn,boolean reuse) { if(reuse && roles instanceof ArrayList && values instanceof ArrayList){ this.roles=(ArrayList)roles; this.values=(ArrayList)values; } else{ this.roles=new ArrayList<String>(roles); this.values=new ArrayList<Object>(values); } this.activeColumn=activeColumn; } public ResultRow(List<String> roles,List<Object> values,int activeColumn) { this(roles,values,activeColumn,false); } public ResultRow(List<String> roles,List<Object> values) { this(roles,values,0); } public ResultRow(Object value){ this.roles=new ArrayList<String>(); this.values=new ArrayList<Object>(); roles.add(Directive.DEFAULT_COL); values.add(value); activeColumn=0; } public int getNumValues(){return values.size();} public Object getValue(int index){return values.get(index);} public String getRole(int index){return roles.get(index);} public int getActiveColumn(){return activeColumn;} public Object getActiveValue(){return values.get(activeColumn);} public String getActiveRole(){return roles.get(activeColumn);} public ArrayList<Object> getValues() { return values; } public Object get(String role) { int ind=roles.indexOf(role); if(ind==-1) return null; return values.get(ind); } public Object getValue(String role) throws QueryException { int ind=roles.indexOf(role); if(ind==-1) throw new QueryException("Role \""+role+"\" not in result row."); return values.get(ind); } public ArrayList<String> getRoles() { return roles; } public ResultRow join(ResultRow row) throws QueryException { ArrayList<String> newRoles=new ArrayList<String>(this.roles); ArrayList<Object> newValues=new ArrayList<Object>(this.values); for(int i=0;i<row.getNumValues();i++){ String role=row.getRole(i); Object val=row.getValue(i); int ind=newRoles.indexOf(role); if(ind>=0) { // if(!role.equals(Directive.DEFAULT_COL)) throw new QueryException("Role \""+role+"\" already exists in result row."); newValues.set(ind, val); } else { newRoles.add(role); newValues.add(val); } } return new ResultRow(newRoles,newValues,this.activeColumn,true); } public int hashCode(){ if(hashCode==-1) 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.roles.equals(this.roles) && r.values.equals(this.values); } public ArrayList<ResultRow> toList(){ ArrayList<ResultRow> ret=new ArrayList<ResultRow>(); ret.add(this); return ret; } public ResultIterator toIterator(){ return new ResultIterator.SingleIterator(this); } public ResultRow addValue(Object value) throws QueryException { return addValue(Directive.DEFAULT_COL,value); } public ResultRow addValue(String role,Object value) throws QueryException { return addValues(new String[]{role},new Object[]{value}); } public ResultRow addValues(String[] roles,Object[] values) throws QueryException { ArrayList<String> newRoles=new ArrayList<String>(this.roles); ArrayList<Object> newValues=new ArrayList<Object>(this.values); int ind=0; for(int i=0;i<roles.length;i++){ String role=roles[i]; Object value=values[i]; ind=newRoles.indexOf(role); if(ind>=0){ // if(!role.equals(Directive.DEFAULT_COL)) throw new QueryException("Role \""+role+"\" already exists in result row."); newValues.set(ind, value); } else { ind=newRoles.size(); newRoles.add(role); newValues.add(value); } } return new ResultRow(newRoles,newValues,ind,true); } }
5,580
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Occurrence.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/Occurrence.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * Occurrence.java * * */ package org.wandora.query2; import java.util.ArrayList; import java.util.Hashtable; import java.util.Map; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public class Occurrence extends Directive implements DirectiveUIHints.Provider { private TopicOperand type; private TopicOperand version; public Occurrence(){ this(null,null); } public Occurrence(Object type){ this(type,null); } public Occurrence(Object type,Object version){ this.type=(type==null?null:new TopicOperand(type)); this.version=(version==null?null:new TopicOperand(version)); } @Override public DirectiveUIHints getUIHints() { DirectiveUIHints ret=new DirectiveUIHints(Occurrence.class,new DirectiveUIHints.Constructor[]{ new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{}, ""), new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(TopicOperand.class, false, "type"), }, ""), new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(TopicOperand.class, false, "type"), new DirectiveUIHints.Parameter(TopicOperand.class, false, "version"), }, "") }, Directive.getStandardAddonHints(), "Occurrence", "Topic map"); return ret; } @Override public boolean startQuery(QueryContext context) throws QueryException { boolean ret=true; if(type!=null) ret&=type.startQuery(context); if(version!=null) ret&=type.startQuery(context); return ret; } @Override public void endQuery(QueryContext context) throws QueryException { if(type!=null) type.endQuery(context); if(version!=null) type.endQuery(context); } @Override public ResultIterator queryIterator(QueryContext context, ResultRow input) throws QueryException { Object o=input.getActiveValue(); if(o==null) return new ResultIterator.EmptyIterator(); try{ if(!(o instanceof Topic)){ TopicMap tm=context.getTopicMap(); o=tm.getTopic(o.toString()); if(o==null) return new ResultIterator.EmptyIterator(); } if(type!=null && version!=null){ Topic typeT=type.getOperandTopic(context, input); Topic versionT=version.getOperandTopic(context, input); if(typeT==null || versionT==null) return input.addValue(DEFAULT_COL, null).toIterator(); String occ=((Topic)o).getData(typeT, versionT); return input.addValue(DEFAULT_COL, occ).toIterator(); } else if(type!=null){ Topic typeT=type.getOperandTopic(context,input); if(typeT==null) return new ResultIterator.EmptyIterator(); Hashtable<Topic,String> data=((Topic)o).getData(typeT); ArrayList<ResultRow> ret=new ArrayList<ResultRow>(); if(data!=null){ for(Map.Entry<Topic,String> e : data.entrySet()){ ret.add(input.addValues(new String[]{DEFAULT_NS+"occurrence_version",DEFAULT_COL}, new Object[]{e.getKey(),e.getValue()})); } } return new ResultIterator.ListIterator(ret); } else { ArrayList<ResultRow> ret=new ArrayList<ResultRow>(); for(Topic typeT : ((Topic)o).getDataTypes()){ Hashtable<Topic,String> data=((Topic)o).getData(typeT); if(data!=null){ for(Map.Entry<Topic,String> e : data.entrySet()){ ret.add(input.addValues(new String[]{DEFAULT_NS+"occurrence_type",DEFAULT_NS+"occurrence_version",DEFAULT_COL}, new Object[]{typeT,e.getKey(),e.getValue()})); } } } return new ResultIterator.ListIterator(ret); } }catch(TopicMapException tme){ throw new QueryException(tme); } } }
5,270
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z