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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
DeleteSymmetricAssociation.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/associations/DeleteSymmetricAssociation.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* DeleteSymmetricAssociation.java
*
* Created on 16. elokuuta 2008, 18:41
*
*/
package org.wandora.application.tools.associations;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.AssociationContext;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.table.AssociationTable;
import org.wandora.application.tools.AbstractWandoraTool;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
/**
* <p>
* Deletes symmetric association for a given association. Symmetric
* association is an association where two players have been swapped. For example
* [P1:R1, P2:R2, P3:R3]'s symmetric association is [P2:R1, P1:R2, P3:R3].
* </p>
* <p>
* If tool is given both symmetric associations then both associations will be
* removed.
* </p>
*
* @see SwapPlayers
* @see CreateSymmetricAssociation
*
* @author akivela
*/
public class DeleteSymmetricAssociation extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
private boolean requiresRefresh = false;
public DeleteSymmetricAssociation() {
setContext(new AssociationContext());
}
public DeleteSymmetricAssociation(Context preferredContext) {
setContext(preferredContext);
}
@Override
public String getName() {
return "Delete symmetric associations";
}
@Override
public String getDescription() {
return "Deletes symmetric associations where players have been swapped. "+
"if selection contains both symmetric associations then both assosiations "+
"will be removed.";
}
@Override
public boolean requiresRefresh() {
return requiresRefresh;
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
requiresRefresh = false;
Iterator associations = context.getContextObjects();
Association association = null;
int count = 0;
Set<Topic> symmetricRoles = new HashSet<Topic>();
Collection<Topic> roles = null;
Topic role;
Topic[] symmetricRoleArray = null;
Collection<Association> allAssociations = null;
TopicMap topicMap = null;
Topic atype = null;
try {
if(associations != null && associations.hasNext()) {
int i = 0;
int ac = 0;
// First collect all roles in context associations.
while(associations.hasNext() && !forceStop()) {
association = (Association) associations.next();
if(association != null && !association.isRemoved()) {
ac++;
roles = association.getRoles();
for(Iterator<Topic> it = roles.iterator(); it.hasNext(); ) {
role = it.next();
if(!symmetricRoles.contains(role)) {
symmetricRoles.add(role);
}
}
}
}
// Check if decent logging is required.
if(ac > 100) {
setDefaultLogger();
log("Deleting symmetric associations.");
setProgressMax(ac);
}
// Ok, all selected associations are binary. Easy job.
if(symmetricRoles.size() == 2) {
symmetricRoleArray = symmetricRoles.toArray( new Topic[] {} );
associations = context.getContextObjects();
while(associations.hasNext() && !forceStop()) {
association = (Association) associations.next();
if(association != null && !association.isRemoved()) {
topicMap = association.getTopicMap();
atype = association.getType();
allAssociations = topicMap.getAssociationsOfType(atype);
count += deleteSymmetricAssociation(association, symmetricRoleArray[0], symmetricRoleArray[1], allAssociations);
setProgress(count);
}
}
log("Total " + count + " associations deleted.");
}
// Associations are not binary. Have to investigate more detailed which players to use as symmetry pair.
else if(symmetricRoles.size() > 2) {
AssociationTable associationTable = null;
Object contextSource = context.getContextSource();
if(contextSource instanceof AssociationTable) {
associationTable = (AssociationTable) context.getContextSource();
}
if(associationTable != null) {
Map<Association,List<Topic>> associationsWithSelectedRoles = associationTable.getSelectedAssociationsWithSelectedRoles();
Set<Association> associationKeys = associationsWithSelectedRoles.keySet();
Iterator<Association> associationKeyIterator = associationKeys.iterator();
List<Topic> symmetricRoleArrayList = null;
while(associationKeyIterator.hasNext() && !forceStop()) {
association = (Association) associationKeyIterator.next();
if(association != null && !association.isRemoved()) {
symmetricRoleArrayList = associationsWithSelectedRoles.get(association);
if(symmetricRoleArrayList != null && symmetricRoleArrayList.size() == 2) {
symmetricRoleArray = symmetricRoleArrayList.toArray( new Topic[] {} );
topicMap = association.getTopicMap();
atype = association.getType();
allAssociations = topicMap.getAssociationsOfType(atype);
count += deleteSymmetricAssociation(association, symmetricRoleArray[0], symmetricRoleArray[1], allAssociations);
setProgress(count);
}
else {
log("Number of selected players is less than two or greater than two. Skipping association.");
}
}
}
log("Total " + count + " associations deleted.");
}
}
else {
log("Number of association players is less than two. Aborting.");
}
}
}
catch(Exception e) {
singleLog(e);
}
}
public int deleteSymmetricAssociation(Association association, Topic role1, Topic role2, Collection<Association> allAssociations) {
int deleteCount = 0;
try {
if(association == null || association.isRemoved()) return 0;
if(role1 == null && role2 == null) return 0;
if(role1.isRemoved() || role2.isRemoved()) return 0;
if(allAssociations == null || allAssociations.isEmpty()) return 0;
Topic player1 = association.getPlayer(role1);
Topic player2 = association.getPlayer(role2);
if(player1 != null && player2 != null) {
if(!player1.isRemoved() && !player2.isRemoved()) {
requiresRefresh = true;
Topic type = association.getType();
Collection<Topic> originalRoles = association.getRoles();
for(Association otherAssociation : allAssociations) {
boolean isSymmetric = true;
if(otherAssociation == null || otherAssociation.isRemoved()) continue;
for(Topic originalRole : originalRoles) {
if(role1.mergesWithTopic(originalRole)) {
if(!player2.mergesWithTopic(otherAssociation.getPlayer(role1))) {
isSymmetric = false;
break;
}
}
else if(role2.mergesWithTopic(originalRole)) {
if(!player1.mergesWithTopic(otherAssociation.getPlayer(role2))) {
isSymmetric = false;
break;
}
}
else {
Topic originalPlayer = association.getPlayer(originalRole);
Topic otherPlayer = otherAssociation.getPlayer(originalRole);
if(!originalPlayer.mergesWithTopic(otherPlayer)) {
isSymmetric = false;
break;
}
}
}
if(isSymmetric) {
otherAssociation.remove();
deleteCount++;
}
}
}
else {
log("Association contains removed topics. Skipping!");
}
}
}
catch (Exception e) {
log(e);
}
return deleteCount;
}
}
| 10,994 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
StealAssociations.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/associations/StealAssociations.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* StealAssociations.java
*
* Created on 13.7.2006, 17:09
*
*/
package org.wandora.application.tools.associations;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.AssociationContext;
import org.wandora.application.contexts.Context;
import org.wandora.application.tools.AbstractWandoraTool;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
/**
* <code>StealAssociations</code> tool swaps one player in association.
* The effect is an association robbery where new player steals association
* from the old player. Old player topic is deleted. Association between
* old player and the thief topic is not stoled. Examples:
*
* c c
* / /
* (a# -- b) -- d ==> a -- d , [b]
* \ \
* e e
*
*
* c c
* / /
* a# , (b) -- d ==> a -- d , [b]
* \ \
* e e
*
*
* x = topic
* [x] = topic x is removed
* (x) = topic x is in context
* (x -- y) = association is in context
* x# = topic is open in topic panel
*
* @author akivela
*/
public class StealAssociations extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
private boolean requiresRefresh = false;
private boolean deleteOld = true;
private boolean askForThief = false;
public StealAssociations() {
setContext(new AssociationContext());
}
public StealAssociations(Context preferredContext) {
setContext(preferredContext);
}
@Override
public String getName() {
return "Steal associations";
}
@Override
public String getDescription() {
return "Swaps one player in associations and deletes old player topic.";
}
@Override
public boolean requiresRefresh() {
return requiresRefresh;
}
@Override
public void execute(Wandora wandora, Context context) {
try {
requiresRefresh = false;
Iterator associations = null;
Topic thief = null;
Topic victim = null;
Association a = null;
int counter = 0;
if(context instanceof AssociationContext) { // ASSOCIATION CONTEXT!!
List<Topic> victims = null;
Iterator<Topic> victimIterator = null;
associations = context.getContextObjects();
Iterator<Topic> roles = null;
Topic role = null;
Topic player = null;
thief = wandora.getOpenTopic();
if(thief == null) return;
while(associations.hasNext() && !forceStop()) {
a = (Association) associations.next();
if(a != null && !a.isRemoved()) {
victims = new ArrayList<Topic>();
roles = a.getRoles().iterator();
while(roles.hasNext()) {
role = roles.next();
player = a.getPlayer(role);
if(!player.mergesWithTopic(thief)) {
victims.add(player);
}
}
a.remove();
victimIterator = victims.iterator();
while(victimIterator.hasNext()) {
victim = victimIterator.next();
stealAssociations(thief, victim);
if(deleteOld) victim.remove();
}
counter++;
}
}
log("Total "+counter+" associations processed.");
}
else { // TOPIC CONTEXT!!
if(askForThief) thief = wandora.showTopicFinder("Select new player topic...");
else thief = wandora.getOpenTopic();
if(thief == null) return;
Iterator victims = context.getContextObjects();
long startTime = System.currentTimeMillis();
while(victims.hasNext() && !forceStop()) {
victim = (Topic) victims.next();
if(victim != null && !victim.isRemoved()) {
stealAssociations(thief, victim);
victim.remove();
}
}
long endTime = System.currentTimeMillis();
log("Execution took "+((endTime-startTime)/1000)+" seconds.");
}
}
catch(Exception e) {
log(e);
}
setState(WAIT);
}
public void stealAssociations(Topic thief, Topic victim) {
try {
Iterator<Association> associations = victim.getAssociations().iterator();
stealAssociations(thief, victim, associations);
}
catch(Exception e) {
log(e);
}
}
public void stealAssociations(Topic thief, Topic victim, Iterator<Association> associations) {
try {
while(associations.hasNext() && !forceStop()) {
Association a = associations.next();
Iterator<Topic> roles = a.getRoles().iterator();
while(roles.hasNext()) {
Topic role = roles.next();
Topic player = a.getPlayer(role);
if(player.mergesWithTopic(victim)) {
requiresRefresh = true;
a.removePlayer(role);
a.addPlayer(thief, role);
}
}
}
}
catch(Exception e) {
log(e);
}
}
}
| 6,961 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
RemovePlayer.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/associations/RemovePlayer.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* RemovePlayer.java
*
* Created on 2. marraskuuta 2007, 10:18
*/
package org.wandora.application.tools.associations;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.AssociationContext;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.WandoraOptionPane;
import org.wandora.application.gui.table.AssociationTable;
import org.wandora.application.tools.AbstractWandoraTool;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
/**
*
* @see InsertPlayer
* @author akivela
*/
public class RemovePlayer extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
private boolean requiresRefresh = false;
private boolean shouldContinue = true;
/** Creates a new instance of RemovePlayer */
public RemovePlayer() {
setContext(new AssociationContext());
}
public RemovePlayer(Context preferredContext) {
setContext(preferredContext);
}
@Override
public boolean requiresRefresh() {
return requiresRefresh;
}
@Override
public String getName() {
return "Remove player in association";
}
@Override
public String getDescription() {
return "Removes players in associations";
}
@Override
public void execute(Wandora wandora, Context context) {
try {
requiresRefresh = false;
Map<Association,List<Topic>> associationsWithRoles = null;
Topic role = null;
Association a = null;
int aCounter = 0;
int removeCounter = 0;
shouldContinue = true;
yesToAll = false;
setDefaultLogger();
if(context instanceof AssociationContext) { // ASSOCIATION CONTEXT!!
Iterator associations = context.getContextObjects();
AssociationTable associationTable = null;
Object contextSource = context.getContextSource();
if(contextSource instanceof AssociationTable) {
associationTable = (AssociationTable) context.getContextSource();
}
if(associationTable != null) {
associationsWithRoles = associationTable.getSelectedAssociationsWithSelectedRoles();
}
if(associationsWithRoles != null && associationsWithRoles.size() > 0) {
Set<Association> associationSet = associationsWithRoles.keySet();
Iterator<Association> associationIterator = associationSet.iterator();
while(associationIterator.hasNext() && !forceStop() && shouldContinue) {
a = associationIterator.next();
if(a != null) {
aCounter++;
List<Topic> roles = associationsWithRoles.get(a);
Iterator<Topic> roleIterator = roles.iterator();
while(roleIterator.hasNext() && !forceStop() && shouldContinue) {
role = roleIterator.next();
if(role != null) {
try {
if(confirmRemove(wandora, a, role)) {
requiresRefresh = true;
a.removePlayer(role);
removeCounter++;
}
}
catch(Exception e) {
log(e);
}
}
}
}
}
log("Total "+aCounter+" associations processed!");
log("Total "+removeCounter+" players removed in associations!");
}
else {
log("No associations found in context!");
}
}
else {
log("Illegal context found! Expecting association context!");
}
}
catch(Exception e) {
log(e);
}
setState(WAIT);
}
private boolean yesToAll = false;
public boolean confirmRemove(Wandora wandora, Association association, Topic role) throws TopicMapException {
if(association == null || association.getType() == null || role == null) return false;
if(yesToAll) return true;
String typeName = getTopicName(association.getType());
String roleName = getTopicName(role);
String confirmMessage = "Would you like remove player in role '" + roleName + "' from association of type '" + typeName + "'?";
int answer = WandoraOptionPane.showConfirmDialog(wandora, confirmMessage,"Confirm player remove", WandoraOptionPane.YES_TO_ALL_NO_CANCEL_OPTION );
if(answer == WandoraOptionPane.YES_OPTION) {
return true;
}
if(answer == WandoraOptionPane.YES_TO_ALL_OPTION) {
yesToAll = true;
return true;
}
else if(answer == WandoraOptionPane.CANCEL_OPTION) {
shouldContinue = false;
}
return false;
}
}
| 6,552 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
MakeSuperclassOf.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/associations/MakeSuperclassOf.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* MakeSuperclassOf.java
*
* Created on 28.7.2006, 15:41
*
*/
package org.wandora.application.tools.associations;
import java.util.Iterator;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.Context;
import org.wandora.application.tools.AbstractWandoraTool;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
/**
*
* @see MakeSubclassOf
* @author akivela
*/
public class MakeSuperclassOf extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
private boolean requiresRefresh = false;
public MakeSuperclassOf() {
}
public MakeSuperclassOf(Context preferredContext) {
setContext(preferredContext);
}
@Override
public String getName() {
return "Make superclass of";
}
@Override
public String getDescription() {
return "Makes context topic superclass of the topic open in topic panel.";
}
@Override
public boolean requiresRefresh() {
return requiresRefresh;
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
requiresRefresh = false;
Iterator topics = context.getContextObjects();
int count = 0;
boolean shouldContinue = true;
try {
Topic subTopic = null;
Topic superTopic = wandora.getOpenTopic();
if(superTopic == null) return;
TopicMap topicmap = superTopic.getTopicMap();
Association newSuperAssociation = null;
Topic superClassType = getOrCreateTopic("http://www.topicmaps.org/xtm/1.0/core.xtm#superclass-subclass", topicmap);
Topic superClassRole = getOrCreateTopic("http://www.topicmaps.org/xtm/1.0/core.xtm#subclass", topicmap);
Topic subClassRole = getOrCreateTopic("http://www.topicmaps.org/xtm/1.0/core.xtm#superclass", topicmap);
setDefaultLogger();
if(topics != null && topics.hasNext()) {
while(topics.hasNext() && shouldContinue && !forceStop()) {
subTopic = (Topic) topics.next();
if(subTopic != null && !subTopic.isRemoved()) {
log("Making topic '"+getTopicName(subTopic)+"' superclass of '"+getTopicName(superTopic)+"'.");
requiresRefresh = true;
newSuperAssociation = topicmap.createAssociation(superClassType);
newSuperAssociation.addPlayer( superTopic, superClassRole );
newSuperAssociation.addPlayer( subTopic, subClassRole );
}
}
}
setState(WAIT);
}
catch(Exception e) {
log(e);
}
}
public Topic getOrCreateTopic(String locator, TopicMap topicmap) throws TopicMapException {
Topic topic = null;
if(locator != null) {
topic = topicmap.getTopic(locator);
}
if(topic == null) {
topic = topicmap.createTopic();
topic.addSubjectIdentifier(new Locator(locator));
}
return topic;
}
}
| 4,273 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
InsertPlayer.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/associations/InsertPlayer.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* InsertPlayer.java
*
* Created on 2. marraskuuta 2007, 13:29
*
*/
package org.wandora.application.tools.associations;
import java.util.Iterator;
import java.util.Map;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.AssociationContext;
import org.wandora.application.contexts.Context;
import org.wandora.application.tools.AbstractWandoraTool;
import org.wandora.application.tools.GenericOptionsDialog;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
/**
* <p>
* Insert new player to given associations. Tool requests
* player and role topics, and adds them to given associations. Same
* player-role pair is added to every association.
* </p>
*
* @author akivela
*/
public class InsertPlayer extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
private boolean requiresRefresh = false;
public InsertPlayer() {
setContext(new AssociationContext());
}
public InsertPlayer(Context preferredContext) {
setContext(preferredContext);
}
@Override
public boolean requiresRefresh() {
return requiresRefresh;
}
@Override
public String getName() {
return "Insert player to association(s)";
}
@Override
public String getDescription() {
return "Insert new player to given association(s)";
}
@Override
public void execute(Wandora wandora, Context context) {
try {
requiresRefresh = false;
Topic player = null;
Topic role = null;
Association a = null;
int counter = 0;
setDefaultLogger();
if(context instanceof AssociationContext) { // ASSOCIATION CONTEXT!!
Iterator associations = context.getContextObjects();
if(associations.hasNext()) {
//System.out.println("wandora == "+wandora);
GenericOptionsDialog god=new GenericOptionsDialog(wandora,"Select player and role","Select player and it's role in associations. Selecting existing role overrides old player.",true,new String[][]{
new String[]{"Role","topic",null},
new String[]{"Player","topic",null},
},wandora);
setState(INVISIBLE);
god.setVisible(true);
if(!god.wasCancelled()) {
Map<String,String> values=god.getValues();
String roleSI = values.get("Role");
String playerSI = values.get("Player");
TopicMap topicmap = wandora.getTopicMap();
role = topicmap.getTopic(roleSI);
player = topicmap.getTopic(playerSI);
}
setState(VISIBLE);
if(role == null) {
log("Intended role topic not found!");
}
if(player == null) {
log("Intended player topic not found!");
}
if(role != null && player != null) {
log("Inserting player '"+getTopicName(player)+"' in role '"+getTopicName(role)+"' to associations.");
while(associations.hasNext() && !forceStop()) {
a = (Association) associations.next();
if(a != null && !a.isRemoved()) {
try {
counter++;
a.addPlayer(player, role);
requiresRefresh = true;
}
catch(Exception e) {
log(e);
}
}
else {
log("Found association is null. Rejecting association.");
}
}
log("Total "+counter+" players inserted to associations!");
}
}
else {
log("Selection contains no associations!");
}
}
else {
log("Illegal context found. Expecting association context.");
}
}
catch(Exception e) {
log(e);
}
setState(WAIT);
}
} | 5,546 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
MakeSubclassOf.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/associations/MakeSubclassOf.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* MakeSubclassOf.java
*
* Created on 28.7.2006, 15:41
*
*/
package org.wandora.application.tools.associations;
import java.util.Iterator;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.Context;
import org.wandora.application.tools.AbstractWandoraTool;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
/**
*
* @see MakeSuperclassOf
* @author akivela
*/
public class MakeSubclassOf extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
private boolean requiresRefresh = false;
public MakeSubclassOf() {
}
public MakeSubclassOf(Context preferredContext) {
setContext(preferredContext);
}
@Override
public String getName() {
return "Make subclass of";
}
@Override
public String getDescription() {
return "Makes context topic subclass of the topic open in topic panel.";
}
@Override
public boolean requiresRefresh() {
return requiresRefresh;
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
requiresRefresh = false;
Iterator topics = context.getContextObjects();
int count = 0;
boolean shouldContinue = true;
try {
Topic superTopic = null;
Topic subTopic = wandora.getOpenTopic();
if(subTopic == null) {
return;
}
TopicMap topicmap = subTopic.getTopicMap();
Association newSuperAssociation = null;
Topic superClassType = getOrCreateTopic("http://www.topicmaps.org/xtm/1.0/core.xtm#superclass-subclass", topicmap);
Topic superClassRole = getOrCreateTopic("http://www.topicmaps.org/xtm/1.0/core.xtm#subclass", topicmap);
Topic subClassRole = getOrCreateTopic("http://www.topicmaps.org/xtm/1.0/core.xtm#superclass", topicmap);
setDefaultLogger();
if(topics != null && topics.hasNext()) {
while(topics.hasNext() && shouldContinue && !forceStop()) {
superTopic = (Topic) topics.next();
if(superTopic != null && !superTopic.isRemoved()) {
log("Making topic '"+getTopicName(superTopic)+"' subclass of '"+getTopicName(subTopic)+"'.");
requiresRefresh = true;
newSuperAssociation = topicmap.createAssociation(superClassType);
newSuperAssociation.addPlayer( superTopic, superClassRole );
newSuperAssociation.addPlayer( subTopic, subClassRole );
}
}
}
setState(WAIT);
}
catch(Exception e) {
log(e);
}
}
public Topic getOrCreateTopic(String locator, TopicMap topicmap) throws TopicMapException {
Topic topic = null;
if(locator != null) {
topic = topicmap.getTopic(locator);
}
if(topic == null) {
topic = topicmap.createTopic();
topic.addSubjectIdentifier(new Locator(locator));
}
return topic;
}
}
| 4,295 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
CreateSymmetricAssociation.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/associations/CreateSymmetricAssociation.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* CreateSymmetricAssociation.java
*
* Created on 16. elokuuta 2008, 18:41
*
*/
package org.wandora.application.tools.associations;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.AssociationContext;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.table.AssociationTable;
import org.wandora.application.tools.AbstractWandoraTool;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
/**
* <p>
* Creates symmetric associations for given associations. Symmetric association
* has two players swapped. For example association's [P1:R1, P2:R2, P3:R3] symmetric
* pairs are [P2:R1, P1:R2, P3:R3].
* </p>
* <p>
* If given association contains more than two players, only selected players
* are swapped. If selection contains more or less than two players, tool
* aborts without changes.
* </p>
*
* @see DeleteSymmetricAssociation
* @see SwapPlayers
*
* @author akivela
*/
public class CreateSymmetricAssociation extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
private boolean requiresRefresh = false;
public CreateSymmetricAssociation() {
setContext(new AssociationContext());
}
public CreateSymmetricAssociation(Context preferredContext) {
setContext(preferredContext);
}
@Override
public String getName() {
return "Create symmetric associations";
}
@Override
public String getDescription() {
return "Creates symmetric association where players have been swapped.";
}
@Override
public boolean requiresRefresh() {
return requiresRefresh;
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
requiresRefresh = false;
Iterator associations = context.getContextObjects();
Association association = null;
int count = 0;
Set<Topic> symmetricRoles = new HashSet<Topic>();
Collection<Topic> roles = null;
Topic role;
Topic[] symmetricRoleArray = null;
try {
if(associations != null && associations.hasNext()) {
int i = 0;
int ac = 0;
// First collect all roles in context associations.
while(associations.hasNext() && !forceStop()) {
association = (Association) associations.next();
if(association != null && !association.isRemoved()) {
ac++;
roles = association.getRoles();
for(Iterator<Topic> it = roles.iterator(); it.hasNext(); ) {
role = it.next();
if(!symmetricRoles.contains(role)) {
symmetricRoles.add(role);
}
}
}
}
// Check if decent logging is required.
if(ac > 100) {
setDefaultLogger();
log("Creating symmetric associations.");
setProgressMax(ac);
}
// Ok, all selected associations are binary. Easy job.
if(symmetricRoles.size() == 2) {
symmetricRoleArray = symmetricRoles.toArray( new Topic[] {} );
associations = context.getContextObjects();
while(associations.hasNext() && !forceStop()) {
association = (Association) associations.next();
if(association != null && !association.isRemoved()) {
count += createSymmetricAssociation(association, symmetricRoleArray[0], symmetricRoleArray[1]);
setProgress(count);
}
}
log("Total " + count + " associations created.");
}
// Associations are not binary. Have to investigate more detailed which players to use as symmetry pair.
else if(symmetricRoles.size() > 2) {
AssociationTable associationTable = null;
Object contextSource = context.getContextSource();
if(contextSource instanceof AssociationTable) {
associationTable = (AssociationTable) context.getContextSource();
}
if(associationTable != null) {
Map<Association,List<Topic>> associationsWithSelectedRoles = associationTable.getSelectedAssociationsWithSelectedRoles();
Set<Association> associationKeys = associationsWithSelectedRoles.keySet();
Iterator<Association> associationKeyIterator = associationKeys.iterator();
List<Topic> symmetricRoleArrayList = null;
while(associationKeyIterator.hasNext() && !forceStop()) {
association = associationKeyIterator.next();
if(association != null && !association.isRemoved()) {
symmetricRoleArrayList = associationsWithSelectedRoles.get(association);
if(symmetricRoleArrayList != null && symmetricRoleArrayList.size() == 2) {
symmetricRoleArray = symmetricRoleArrayList.toArray( new Topic[] {} );
count += createSymmetricAssociation(association, symmetricRoleArray[0], symmetricRoleArray[1]);
setProgress(count);
}
else {
log("Number of selected players is less than two or greater than two. Skipping association.");
}
}
}
log("Total " + count + " associations created.");
}
else {
log("The number of association players is greater than two. Aborting.");
}
}
else {
log("The number of association players is less than two. Aborting.");
}
}
}
catch(Exception e) {
singleLog(e);
}
}
public int createSymmetricAssociation(Association association, Topic role1, Topic role2) {
int createCount = 0;
try {
if(association == null || association.isRemoved()) return 0;
if(role1 == null || role2 == null) return 0;
if(role1.isRemoved() || role2.isRemoved()) return 0;
Topic player1 = association.getPlayer(role1);
Topic player2 = association.getPlayer(role2);
if(player1 != null && player2 != null) {
if(!player1.isRemoved() && !player2.isRemoved()) {
requiresRefresh = true;
TopicMap topicMap = association.getTopicMap();
Topic type = association.getType();
Association symmetricAssociation = topicMap.createAssociation(type);
createCount++;
symmetricAssociation.addPlayer(player1, role2);
symmetricAssociation.addPlayer(player2, role1);
Collection<Topic> originalRoles = association.getRoles();
for(Topic originalRole : originalRoles) {
if(role1.mergesWithTopic(originalRole)) continue;
else if(role2.mergesWithTopic(originalRole)) continue;
else {
symmetricAssociation.addPlayer(association.getPlayer(originalRole), originalRole);
}
}
}
else {
log("Association contains removed topics. Skipping.");
}
}
}
catch (Exception e) {
log(e);
}
return createCount;
}
}
| 9,447 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TransposeAssociations.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/associations/TransposeAssociations.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* TransposeAssociations.java
*
* Created on 7. marraskuuta 2007, 14:51
*
*/
package org.wandora.application.tools.associations;
import java.util.Collection;
import java.util.Iterator;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.AssociationContext;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.WandoraOptionPane;
import org.wandora.application.gui.table.AssociationTable;
import org.wandora.application.tools.AbstractWandoraTool;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
/**
* <p>
* This rather complicated tool modifies given associations by rotating association
* matrix (i.e. association table) 90 degrees clockwise. For example, lets think
* association matrix:
* </p>
* <code>
*
* atype
* r1 r2
* pa1 pa2
* pb1 pb2
* pc1 pc2
*
* </code>
* <p>
* Here atype is association type, r? are role topics and p?? are player topics.
* Transposing these three association generates association matrix:
* </p>
* <code>
*
* atype
* r1 pa1 pb1 pc1
* r2 pa2 pb2 pc2
*
* </code>
* <p>
* where three binary associations have turned into one 4-ary association with
* players r2, pa2, pb2, and pc2. Roles are r1, pa1, pb1, and pc1. Association type
* remains.
* </p>
*
* @author akivela
*/
public class TransposeAssociations extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
public TransposeAssociations() {
setContext(new AssociationContext());
}
public TransposeAssociations(Context preferredContext) {
setContext(preferredContext);
}
@Override
public String getName() {
return "Transpose associations";
}
@Override
public String getDescription() {
return "Rotates associations 90 degrees clockwise. "+
"First players of associations are new roles while old roles become new players.";
}
@Override
public void execute(Wandora wandora, Context context) {
try {
TopicMap topicmap = wandora.getTopicMap();
int a = WandoraOptionPane.showConfirmDialog(wandora, "Transposing association interprets selected associations as a topic matrix and rotates the matrix 90 degrees counter clock wise. New associations will be created using rotated matrix. First row of rotated matrix is interpreted as role topics and old roles will become association player. Finally old associations will be deleted. Are you sure you want transpose selected associations?", "Transpose associations?");
if(a != WandoraOptionPane.YES_OPTION) return;
setDefaultLogger();
if(context instanceof AssociationContext) { // ASSOCIATION CONTEXT!!
AssociationTable associationTable = (AssociationTable) context.getContextSource();
Collection associations = associationTable.getSelectedAssociations();
Topic associationType = ((Association) associations.iterator().next()).getType();
Topic[][] newAssociations = new Topic[associationTable.getColumnCount()][associations.size()+1];
int width = associationTable.getColumnCount();
int height = associations.size()+1;
// BUILDING TOPIC MATRIX FROM ASSOCIATIONS
log("Building topic map matrix...");
for(int x=0; x<width && !forceStop(); x++) {
Object o=associationTable.getColumnAt(associationTable.convertColumnIndexToModel(x));
if(o instanceof Topic) newAssociations[x][0] = (Topic)o;
else newAssociations[x][0] = null;
}
for(int y=1; y<height && !forceStop(); y++) {
for(int x=0; x<width; x++) {
newAssociations[x][y] = associationTable.getTopicAt(y-1,x);
//log(" ("+x+","+y+")="+newAssociations[x][y].getBaseName());
}
}
// CREATING ASSOCIATIONS WITH TOPIC MATRIX
if(!forceStop()) {
log("Creating new transposed associations...");
int createCount = 0;
Topic role = null;
Topic player = null;
Association association = null;
for(int x=1; x<width && !forceStop(); x++) {
try {
createCount++;
association = topicmap.createAssociation(associationType);
for(int y=0; y<height && !forceStop(); y++) {
role = newAssociations[0][y];
player = newAssociations[x][y];
association.addPlayer(player,role);
}
}
catch(Exception e) {
log(e);
}
}
log("Created "+createCount+" associations.");
}
if(!forceStop()) {
int removeCount = 0;
log("Removing old associations...");
Association association = null;
Iterator associationIterator = associations.iterator();
while(associationIterator.hasNext() && !forceStop()) {
try {
association = (Association) associationIterator.next();
association.remove();
removeCount++;
}
catch(Exception e) {
log(e);
}
}
log("Removed "+removeCount+" associations.");
}
}
else {
log("Illegal context found. Expecting association context.");
}
}
catch(Exception e) {
log(e);
}
setState(WAIT);
}
}
| 7,269 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
FindAssociationsInOccurrence.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/associations/FindAssociationsInOccurrence.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* FindAssociationsInOccurrence.java
*
* Created on 9. maaliskuuta 2007, 12:07
*
*/
package org.wandora.application.tools.associations;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.topicstringify.TopicToString;
import org.wandora.application.tools.AbstractWandoraTool;
import org.wandora.application.tools.GenericOptionsDialog;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicTools;
/**
* Iterates selected topics and recognizes base names in topic's
* occurrence, and associates topic of the recognized base name to the iterated
* one.
*
* @author akivela
*/
public class FindAssociationsInOccurrence extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
public static int MAXLEN = 256;
public String replacement = "";
public String SITemplate = "http://wandora.org/si/occurrence/%OCCURRENCE%";
private boolean createNewTopics = false;
private boolean askTemplate = true;
private boolean requiresRefresh = false;
/** Creates a new instance of FindAssociationsInOccurrence */
public FindAssociationsInOccurrence() {
}
public FindAssociationsInOccurrence(Context preferredContext) {
setContext(preferredContext);
}
@Override
public String getName() {
return "Find associations in occurrence";
}
@Override
public String getDescription() {
return "Iterates through selected topics and recognizes base names in topic's occurrence, and associates topic of the recognized base name to the iterated one.";
}
@Override
public boolean requiresRefresh() {
return requiresRefresh;
}
@Override
public void execute(Wandora wandora, Context context) {
try {
requiresRefresh = false;
GenericOptionsDialog god=new GenericOptionsDialog(wandora,"Find associations options","Find associations options",true,new String[][]{
new String[]{"Occurrence type","topic"},
new String[]{"Occurrence scope","topic"},
new String[]{"Topic role","topic"},
new String[]{"Link pattern","string","\\[\\[(.+?)\\]\\]","The regular expression pattern for base names? First capture group in the pattern marks the base name."},
new String[]{"SI template","string","http://wandora.org/si/occurrence/%OCCURRENCE%"},
new String[]{"Create topics","boolean","true","Should new topics be created for non existing base names"},
},wandora);
god.setVisible(true);
if(god.wasCancelled()) return;
Map<String,String> values=god.getValues();
SITemplate = values.get("SI template");
Topic occurrenceType=wandora.getTopicMap().getTopic(values.get("Occurrence type"));
if(occurrenceType==null) return;
Topic occurrenceScope=wandora.getTopicMap().getTopic(values.get("Occurrence scope"));
if(occurrenceScope==null) return;
Topic topicRole=wandora.getTopicMap().getTopic(values.get("Topic role"));
if(topicRole==null) return;
String recognizePatternString=values.get("Link pattern");
createNewTopics=Boolean.parseBoolean(values.get("Create topics"));
Iterator topics = context.getContextObjects();
if(topics == null || !topics.hasNext()) return;
Locator occurrenceTypeLocator = occurrenceType.getSubjectIdentifiers().iterator().next();
Locator occurrenceScopeLocator = occurrenceScope.getSubjectIdentifiers().iterator().next();
// Finally ready to roll...
setDefaultLogger();
setLogTitle("Finding associations from occurrences");
log("Finding associations from occurrences");
TopicMap map = wandora.getTopicMap();
Topic topic = null;
String topicName = null;
Association a = null;
String occurrence = null;
int progress = 0;
int acount = 0;
int ocount = 0;
Pattern recognizePattern = Pattern.compile(recognizePatternString);
String recognizedTopicName = null;
Topic recognizedTopic = null;
//log("recognizePatternString == '"+recognizePatternString+"'");
ArrayList<Topic> dtopics = new ArrayList<Topic>();
while(topics.hasNext() && !forceStop()) {
dtopics.add((Topic) topics.next());
}
topics = dtopics.iterator();
// Iterate through selected topics...
while(topics.hasNext() && !forceStop()) {
try {
topic = (Topic) topics.next();
if(topic != null && !topic.isRemoved()) {
progress++;
// Topic name for gui use...
topicName = TopicToString.toString(topic);
hlog("Inspecting topic '"+topicName+"'");
occurrenceType = topic.getTopicMap().getTopic(occurrenceTypeLocator);
occurrenceScope = topic.getTopicMap().getTopic(occurrenceScopeLocator);
occurrence = topic.getData(occurrenceType, occurrenceScope);
// Ok, if topic has sufficient occurrence descent deeper...
if(occurrence != null && occurrence.length() > 0) {
ocount++;
hlog("Found occurrence in topic '"+topicName+"'");
Matcher m = recognizePattern.matcher(occurrence);
while(m.find() && !forceStop()) {
for(int i=0; i<m.groupCount(); i++) {
recognizedTopicName = m.group(i);
Matcher m2 = recognizePattern.matcher(recognizedTopicName);
if(m2.find()) {
recognizedTopicName = m2.replaceAll("$1");
}
log("Recognized '"+recognizedTopicName+"' in occurrence");
// Check if required topic already exists
recognizedTopic = map.getTopicWithBaseName(recognizedTopicName);
// No. It didn't. Create new topic?
if(recognizedTopic == null && createNewTopics) {
// Creating new topic for the occurrence...
recognizedTopic = map.createTopic();
// Giving new topic SI and base name
hlog("Creating new topic for '"+recognizedTopicName+"'");
recognizedTopic.addSubjectIdentifier(TopicTools.createDefaultLocator());
recognizedTopic.setBaseName(recognizedTopicName);
}
if(recognizedTopic != null) {
// Creating new association between old and new topic
hlog("Creating association between '"+recognizedTopicName+"' and '"+topicName+"'.");
requiresRefresh = true;
a = map.createAssociation(occurrenceType);
a.addPlayer(topic, topicRole);
a.addPlayer(recognizedTopic, occurrenceType);
acount++;
}
}
}
}
}
}
catch(Exception e) {
log(e);
}
}
log("Total "+progress+" topics investigated.");
log("Total "+ocount+" occurrences found.");
log("Total "+acount+" associations created.");
setState(WAIT);
}
catch (Exception e) {
log(e);
}
}
}
| 9,751 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
DeleteAssociations.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/associations/DeleteAssociations.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* DeleteAssociations.java
*
* Created on 23. huhtikuuta 2006, 15:23
*
*/
package org.wandora.application.tools.associations;
import java.util.Iterator;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.AssociationContext;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.WandoraOptionPane;
import org.wandora.application.tools.AbstractWandoraTool;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
/**
* <p>
* Deletes given associations. Wandora user must confirm deletion.
* </p>
*
* @author akivela
*/
public class DeleteAssociations extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
public boolean forceDelete = true;
public boolean confirm = true;
public boolean shouldContinue = true;
protected Wandora wandora = null;
private boolean requiresRefresh = false;
public DeleteAssociations() {
setContext(new AssociationContext());
}
public DeleteAssociations(Context preferredContext) {
setContext(preferredContext);
}
@Override
public String getName() {
return "Delete associations";
}
@Override
public String getDescription() {
return "Deletes context associations.";
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
this.wandora = wandora;
Iterator associations = context.getContextObjects();
Association association = null;
int count = 0;
shouldContinue = true;
confirm = true;
requiresRefresh = false;
yesToAll = false;
if(associations != null && associations.hasNext()) {
while(associations.hasNext() && shouldContinue) {
association = (Association) associations.next();
if(association != null && !association.isRemoved()) {
if(shouldDelete(association)) {
try {
association.remove();
count++;
requiresRefresh = true;
if(count == 50) {
setDefaultLogger();
}
}
catch(Exception e2) {
log(e2);
}
}
}
}
}
if(count > 10) log("Total " + count + " associations deleted!");
if(count >= 50) setState(WAIT);
}
public boolean shouldDelete(Association association) throws TopicMapException {
if(confirm) {
return confirmDelete(association);
}
else {
return true;
}
}
public boolean yesToAll = false;
public boolean confirmDelete(Association association) throws TopicMapException {
if(yesToAll) return true;
if(association != null) {
String typeName = association.getType() != null ? association.getType().getBaseName() : "";
Iterator<Topic> roleIterator = association.getRoles().iterator();
StringBuilder playerDescription = new StringBuilder("");
while(roleIterator.hasNext()) {
Topic role = (Topic) roleIterator.next();
Topic player = association.getPlayer(role);
playerDescription.append("'").append(getTopicName(player)).append("'");
if(roleIterator.hasNext()) playerDescription.append(" and ");
}
String confirmMessage = "Would you like delete '" + typeName + "' association between\n" + playerDescription.toString() + "?";
int answer = WandoraOptionPane.showConfirmDialog(wandora, confirmMessage,"Confirm delete", WandoraOptionPane.YES_TO_ALL_NO_CANCEL_OPTION );
if(answer == WandoraOptionPane.YES_OPTION) {
return true;
}
if(answer == WandoraOptionPane.YES_TO_ALL_OPTION) {
yesToAll = true;
return true;
}
else if(answer == WandoraOptionPane.CANCEL_OPTION) {
shouldContinue = false;
}
}
return false;
}
@Override
public boolean requiresRefresh() {
return requiresRefresh;
}
}
| 5,374 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
DeleteAssociationsInTopicWithType.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/associations/DeleteAssociationsInTopicWithType.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* DeleteAssociationsInTopicWithType.java
*
* Created on 20.7.2006, 21:41
*
*/
package org.wandora.application.tools.associations;
import java.util.ArrayList;
import java.util.Collection;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.Context;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author akivela
*/
public class DeleteAssociationsInTopicWithType extends DeleteAssociationsInTopic implements WandoraTool {
private static final long serialVersionUID = 1L;
private Topic associationType = null;
public DeleteAssociationsInTopicWithType() {
}
public DeleteAssociationsInTopicWithType(Context preferredContext) {
setContext(preferredContext);
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
associationType=null;
associationType=wandora.showTopicFinder("Select type of association to be removed from topics...");
if(associationType != null) {
super.execute(wandora, context);
}
}
@Override
public Collection<Association> solveTopicAssociations(Topic topic) throws TopicMapException {
TopicMap tm = topic.getTopicMap();
ArrayList<Association> associations = new ArrayList<>();
Topic at = null;
for(Locator l : associationType.getSubjectIdentifiers()) {
at = tm.getTopic(l);
if(at != null && !at.isRemoved()) {
associations.addAll( topic.getAssociations(at) );
}
}
return associations;
}
}
| 2,643 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
DetectCycles.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/associations/DetectCycles.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*/
package org.wandora.application.tools.associations;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.AssociationContext;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.WandoraOptionPane;
import org.wandora.application.gui.table.AssociationTable;
import org.wandora.application.gui.topicstringify.TopicToString;
import org.wandora.application.tools.AbstractWandoraTool;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicTools;
/**
*
* @author akivela
*/
public class DetectCycles extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
public DetectCycles() {
setContext(new AssociationContext());
}
public DetectCycles(Context preferredContext) {
setContext(preferredContext);
}
@Override
public String getName() {
return "Detect cycle";
}
@Override
public String getDescription() {
return "Find cycles in addressed association path. Tool doesn't necessarily return all existing cycles.";
}
@Override
public boolean requiresRefresh() {
return false;
}
@Override
public void execute(Wandora wandora, Context context) {
try {
Map<Association,List<Topic>> associationsWithRoles = null;
Topic role = null;
Association a = null;
if(context instanceof AssociationContext) { // ASSOCIATION CONTEXT!!
AssociationTable associationTable = null;
Object contextSource = context.getContextSource();
if(contextSource instanceof AssociationTable) {
associationTable = (AssociationTable) context.getContextSource();
}
if(associationTable != null) {
associationsWithRoles = associationTable.getSelectedAssociationsWithSelectedRoles();
}
if(associationsWithRoles != null && associationsWithRoles.size() > 0) {
Set<Association> associationSet = associationsWithRoles.keySet();
Iterator<Association> associationIterator = associationSet.iterator();
if(associationIterator.hasNext() && !forceStop()) {
a = (Association) associationIterator.next();
if(a != null) {
List<Topic> roles = associationsWithRoles.get(a);
Iterator<Topic> roleIterator = roles.iterator();
if(roleIterator.hasNext() && !forceStop()) {
role = roleIterator.next();
if(role != null) {
try {
Topic outRole = findOtherRole(a, role, wandora);
if(outRole != null) {
Topic player = a.getPlayer(role);
setDefaultLogger();
log("Seeking cycles in associations of type '"+TopicToString.toString(a.getType())+"'.");
log("Seeking direction is from role '"+TopicToString.toString(role)+"' to role '"+TopicToString.toString(outRole)+"'.");
log("Starting from player '"+TopicToString.toString(player)+"'.");
List<List<Topic>> cycles = TopicTools.getCyclePaths(player, a.getType(), role, outRole);
if(cycles.isEmpty()) {
log("Found no cycles in addressed association path.");
}
else {
if(cycles.size() == 1) log("Found at least "+cycles.size()+" cycle in addressed association path.");
else log("Found at least "+cycles.size()+" cycles in addressed association path.");
for(int i=0;i<cycles.size(); i++) {
List<Topic> cycle = cycles.get(i);
log("Cycle "+(i+1)+", length "+(cycle.size()-1)+":");
for(Topic t : cycle) {
log(" "+TopicToString.toString(t));
}
}
}
}
log("Ready.");
setState(WAIT);
}
catch(Exception e) {
singleLog(e);
}
}
}
}
}
}
else {
singleLog("No associations found in context.");
}
}
else {
singleLog("Illegal context found. Expecting association context.");
}
}
catch(Exception e) {
singleLog(e);
}
}
private Topic findOtherRole(Association a, Topic r, Wandora wandora) {
Topic otherRole = null;
try {
Collection<Topic> allRoles = a.getRoles();
if(allRoles.size() < 3) {
for(Iterator<Topic> roleIterator = allRoles.iterator(); roleIterator.hasNext(); ) {
otherRole = roleIterator.next();
if(otherRole != null && !otherRole.isRemoved()) {
if(!otherRole.mergesWithTopic(r)) {
return otherRole;
}
}
}
}
else {
allRoles.remove(r);
Object answer = WandoraOptionPane.showOptionDialog(wandora, "Select second role for association travelsal", "Select second role", WandoraOptionPane.OK_CANCEL_OPTION, allRoles.toArray(), allRoles.iterator().next());
if(answer instanceof Topic) {
return (Topic) answer;
}
}
}
catch(Exception e) {
singleLog(e);
}
return null;
}
}
| 7,743 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
ChangeAssociationRoles.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/associations/ChangeAssociationRoles.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* ChangeAssociationRole.java
*
* Created on 10. elokuuta 2006, 16:25
*
*/
package org.wandora.application.tools.associations;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.AssociationContext;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.table.AssociationTable;
import org.wandora.application.tools.AbstractWandoraTool;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
/**
* <p>
* The tool is used to change role topics in given associations. Multiple roles and associations
* can be modified at once. Tool looks at the *selected* roles in association table and
* assumes all selected roles should be changed. Tool requests new role using a topic
* selection dialog.
* </p>
*
* @author akivela
*/
public class ChangeAssociationRoles extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
private boolean requiresRefresh = false;
public ChangeAssociationRoles() {
setContext(new AssociationContext());
}
public ChangeAssociationRoles(Context preferredContext) {
setContext(preferredContext);
}
@Override
public String getName() {
return "Change association roles";
}
@Override
public String getDescription() {
return "Changes multiple role topics in associations at once.";
}
@Override
public boolean requiresRefresh() {
return requiresRefresh;
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
requiresRefresh = false;
Map<Association, List<Topic>> associationsWithOldRoles = null;
try {
Object contextSource = context.getContextSource();
if(contextSource instanceof AssociationTable) {
AssociationTable associationTable = (AssociationTable) contextSource;
associationsWithOldRoles = associationTable.getSelectedAssociationsWithSelectedRoles();
}
if(associationsWithOldRoles == null || associationsWithOldRoles.isEmpty()) {
log("Associations not selected. Aborting.");
return;
}
Topic newRole = wandora.showTopicFinder("Select new role type...");
if(newRole == null) {
log("New role not selected. Aborting.");
return;
}
if(associationsWithOldRoles.size() > 1000) {
setDefaultLogger();
log("Changing roles in associations.");
setProgressMax(associationsWithOldRoles.size());
}
// Finally do the change.
int count = 0;
Topic player = null;
for(Association association : associationsWithOldRoles.keySet()) {
if(forceStop()) break;
if(association != null && !association.isRemoved()) {
List<Topic> oldRoles = associationsWithOldRoles.get(association);
for(Topic oldRole : oldRoles) {
System.out.println("oldrole == "+oldRole);
player = association.getPlayer(oldRole);
System.out.println(" player == "+player);
if(player != null) {
requiresRefresh = true;
association.addPlayer(player, newRole);
association.removePlayer(oldRole);
}
count++;
setProgress(count);
}
}
}
log("Total " + count + " role topics changed.");
}
catch(Exception e) {
singleLog(e);
}
}
}
| 4,843 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
DuplicateAssociations.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/associations/DuplicateAssociations.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
* DuplicateAssociations.java
*
* Created on 21. joulukuuta 2004, 12:52
*/
package org.wandora.application.tools.associations;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.AssociationContext;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.WandoraOptionPane;
import org.wandora.application.tools.AbstractWandoraTool;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
/**
* Duplicates context associations. New associations are given a new association
* type addressed by Wandora user.
*
* @author akivela
*/
public class DuplicateAssociations extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
private Topic oldAssociationType = null;
public boolean wasCancelled = false;
public boolean changeRoles = false;
public boolean removeAssociations = false;
private Map<Topic,Object> roleMap = new LinkedHashMap<>();
public DuplicateAssociations() {
setContext(new AssociationContext());
}
@Override
public String getName() {
return "Duplicate associations";
}
public void makeRoleMap(Wandora wandora) throws TopicMapException {
Iterator contextAssociations = getContext().getContextObjects();
if(contextAssociations == null || !contextAssociations.hasNext()) return;
if(roleMap == null) roleMap = new LinkedHashMap<>();
//BaseNamePrompt prompt=new BaseNamePrompt(wandora.getManager(), wandora, true);
//Topic topicOpen = wandora.getOpenTopic();
//Collection associations = topicOpen.getAssociations(oldAssociationType);
Association association = null;
Topic role = null;
while(contextAssociations.hasNext()) {
association = (Association) contextAssociations.next();
Collection<Topic> roles = association.getRoles();
for(Iterator<Topic> i2 = roles.iterator(); i2.hasNext(); ) {
role = (Topic) i2.next();
if(!roleMap.containsKey(role)) {
if(changeRoles) {
/* prompt.setTitle("Map role '" + getTopicName(role) + "' to...");
prompt.setVisible(true);
Topic newRole=prompt.getTopic();*/
Topic newRole=wandora.showTopicFinder("Map role '" + getTopicName(role) + "' to...");
if(newRole != null) {
roleMap.put(role, newRole);
}
else {
int answer = WandoraOptionPane.showConfirmDialog(wandora ,
"Would you like exclude players of role " + getTopicName(role) + " from the association? " +
"Press Yes to exclude players! "+
"Press No to use existing role topic!",
"Exclude role players or use existing role?",
WandoraOptionPane.YES_NO_OPTION);
if(answer == WandoraOptionPane.NO_OPTION) {
roleMap.put(role, role); // Don't change roles!
}
else {
roleMap.put(role, "EXCLUDE");
}
}
}
else {
roleMap.put(role, role); // Don't change roles!
}
}
}
}
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
wasCancelled = false;
/* BaseNamePrompt prompt=new BaseNamePrompt(wandora.getManager(), wandora, true);
prompt.setTitle("Select new association type...");
prompt.setVisible(true);
Topic newAssociationType=prompt.getTopic();*/
Topic newAssociationType=wandora.showTopicFinder("Select new association type...");
if (newAssociationType != null) {
makeRoleMap(wandora);
Topic topicOpen = wandora.getOpenTopic();
if(topicOpen != null) {
if(oldAssociationType != null) {
Collection<Association> ass = topicOpen.getAssociations();
TopicMap topicMap = wandora.getTopicMap();
List<Association> atemp = new ArrayList<>();
for(Iterator<Association> asi = ass.iterator(); asi.hasNext();) {
atemp.add(asi.next());
}
for(int i=0; i<atemp.size(); i++) {
Association a = (Association) atemp.get(i);
if(a.getType().equals(oldAssociationType)) {
Association ca = topicMap.createAssociation(topicOpen);
ca.setType(newAssociationType);
Collection<Topic> aRoles = a.getRoles();
for(Iterator<Topic> aRoleIter = aRoles.iterator(); aRoleIter.hasNext(); ) {
Topic role = (Topic) aRoleIter.next();
Topic player = a.getPlayer(role);
if(roleMap != null) {
if(roleMap.get(role) instanceof Topic) {
Topic mappedRole =(Topic) roleMap.get(role);
if(mappedRole != null && mappedRole instanceof Topic) {
//log("mapped role == " + mappedRole.getBaseName());
ca.addPlayer(player, mappedRole);
}
}
}
else {
//log("role == " + role.getBaseName());
ca.addPlayer(player, role);
}
}
if(! ca.equals(a) && removeAssociations) {
a.remove();
}
}
}
wandora.openTopic(topicOpen);
}
else {
log("Can't solve old association type!");
}
}
else {
log("Can't solve open topic!");
}
}
else {
wasCancelled = true;
}
}
}
| 7,955 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
ChangeAssociationRole.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/associations/ChangeAssociationRole.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* ChangeAssociationRole.java
*
* Created on 10. elokuuta 2006, 16:25
*
*/
package org.wandora.application.tools.associations;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.AssociationContext;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.WandoraOptionPane;
import org.wandora.application.tools.AbstractWandoraTool;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
/**
* <p>
* Tool is used to change role topic in given associations. Multiple associations
* can be modified at once. Tool requests both old role topic and new role topic.
* </p>
*
* @author akivela
*/
public class ChangeAssociationRole extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
private boolean requiresRefresh = false;
public ChangeAssociationRole() {
setContext(new AssociationContext());
}
public ChangeAssociationRole(Context preferredContext) {
setContext(preferredContext);
}
@Override
public String getName() {
return "Change association role";
}
@Override
public String getDescription() {
return "Changes one role topic in associations.";
}
@Override
public boolean requiresRefresh() {
return requiresRefresh;
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
requiresRefresh = false;
Iterator<Association> associations = context.getContextObjects();
Association association = null;
int count = 0;
Collection<Topic> oldRoles = new ArrayList<Topic>();
Collection<Topic> roles;
Topic role;
try {
if(associations != null && associations.hasNext()) {
int i = 0;
int ac = 0;
// First collect all roles in context associations.
while(associations.hasNext() && !forceStop()) {
association = (Association) associations.next();
if(association != null) {
ac++;
roles = association.getRoles();
for(Iterator<Topic> it = roles.iterator(); it.hasNext(); ) {
role = it.next();
if(!oldRoles.contains(role)) {
oldRoles.add(role);
}
}
}
}
// Then solve names of the roles. Notice duplicate removal....
ArrayList<String> oldRoleNames = new ArrayList<String>();
role = null;
String roleName = null;
for(Iterator<Topic> it=oldRoles.iterator(); it.hasNext(); ) {
role = it.next();
if(role != null && !role.isRemoved()) {
if(role.getBaseName() != null) roleName = role.getBaseName();
else roleName = role.getOneSubjectIdentifier().toExternalForm();
if(roleName != null && !oldRoleNames.contains(roleName)) {
oldRoleNames.add(roleName);
}
}
}
String[] oldRoleNameArray = oldRoleNames.toArray(new String[] {});
// Ask user about the old and new role.
String oldRoleBasename = WandoraOptionPane.showOptionDialog(wandora, "Select role to be changed", "Changed role", WandoraOptionPane.OK_CANCEL_OPTION, oldRoleNameArray, oldRoleNameArray[0]);
if(oldRoleBasename == null) return;
Topic oldRole = wandora.getTopicMap().getTopicWithBaseName(oldRoleBasename);
if(oldRole == null) {
// SI instead of Basename
oldRole = wandora.getTopicMap().getTopic(oldRoleBasename);
}
if(oldRole == null) {
log("Old role not selected. Aborting.");
return;
}
Topic newRole = wandora.showTopicFinder("Select new role type...");
if(newRole == null) {
log("New role not selected. Aborting.");
return;
}
if(oldRole.mergesWithTopic(newRole)) {
log("New role merges with the old role. Operation has no effect. Aborting.");
return;
}
// Finally do the change.
if(ac > 1000) {
setDefaultLogger();
log("Changing role in associations.");
setProgressMax(ac);
}
associations = context.getContextObjects();
Topic player = null;
while(associations.hasNext() && !forceStop()) {
association = (Association) associations.next();
if(association != null) {
player = association.getPlayer(oldRole);
if(player != null) {
requiresRefresh = true;
association.addPlayer(player, newRole);
association.removePlayer(oldRole);
}
count++;
setProgress(count);
}
}
}
log("Total " + count + " role topics changed.");
}
catch(Exception e) {
singleLog(e);
}
}
}
| 6,754 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
DeleteAssociationsInTopic.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/associations/DeleteAssociationsInTopic.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* DeleteAssociationsInTopic.java
*
* Created on 20.7.2006, 20:55
*
*/
package org.wandora.application.tools.associations;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.ConfirmResult;
import org.wandora.application.gui.WandoraOptionPane;
import org.wandora.application.tools.AbstractWandoraTool;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
import org.wandora.topicmap.layered.LayeredTopic;
/**
* Deletes associations in a certain topic i.e. associations where this player
* plays a role.
*
* @author akivela
*/
public class DeleteAssociationsInTopic extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
public boolean forceDelete = true;
public boolean confirm = true;
public boolean shouldContinue = true;
protected Wandora wandora = null;
private String associationName = null;
/** Creates a new instance of DeleteAssociationsInTopic */
public DeleteAssociationsInTopic() {
}
public DeleteAssociationsInTopic(Context preferredContext) {
setContext(preferredContext);
}
@Override
public String getName() {
return "Delete Association(s)";
}
@Override
public String getDescription() {
return "Deletes associations between topics.";
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
this.wandora = wandora;
ArrayList<Association> associationsToDelete = new ArrayList<Association>();
Iterator topics = getContext().getContextObjects();
Collection<Association> associations = null;
Iterator<Association> ai = null;
Association association = null;
Topic topic = null;
Topic ltopic = null;
String topicName = null;
int count = 0;
ConfirmResult r_all = null;
ConfirmResult r = null;
yesToAll = false;
shouldContinue = true;
setDefaultLogger();
if(topics != null && topics.hasNext()) {
while(topics.hasNext() && shouldContinue && !forceStop()) {
topic = (Topic) topics.next();
if(topic != null && !topic.isRemoved()) {
if(topic instanceof LayeredTopic) {
ltopic = ((LayeredTopic) topic).getTopicForSelectedLayer();
if(ltopic == null || ltopic.isRemoved()) {
setState(INVISIBLE);
int answer = WandoraOptionPane.showConfirmDialog(wandora,"Topic '"+getTopicName(topic)+"' doesn't exist in selected layer.", "Topic not in selected layer", WandoraOptionPane.OK_CANCEL_OPTION);
setState(VISIBLE);
if(answer == WandoraOptionPane.CANCEL_OPTION) shouldContinue = false;
continue;
}
else {
topic = ltopic;
}
}
topicName = getTopicName(topic);
hlog("Investigating associations of a topic '" + topicName + "'.");
associations = solveTopicAssociations(topic);
if(associations != null && associations.size() > 0) {
ai = associations.iterator();
while(ai.hasNext()) {
association = ai.next();
if(association != null && !association.isRemoved()) {
if(shouldDelete(topic, association)) {
associationsToDelete.add(association);
count++;
}
}
}
}
}
}
hlog(count + " association to delete.");
ai = associationsToDelete.iterator();
int i = 0;
while(ai.hasNext()) {
i++;
association = ai.next();
if(association != null && !association.isRemoved()) {
association.remove();
if((i % 100) == 0) hlog((count-i) + " association to delete.");
}
}
}
log("Total " + count + " associations deleted.");
setState(WAIT);
associationsToDelete = null;
}
public Collection<Association> solveTopicAssociations(Topic topic) throws TopicMapException {
return topic.getAssociations();
}
public boolean shouldDelete(Topic topic, Association association) throws TopicMapException {
if(confirm) {
return confirmDelete(association);
}
else {
return true;
}
}
public boolean yesToAll = false;
public boolean confirmDelete(Association association) throws TopicMapException {
if(yesToAll) {
hlog("Found association to delete.");
return true;
}
else {
setState(INVISIBLE);
associationName = buildAssociationName(association);
String confirmMessage = "Would you like delete "+associationName+"?";
int answer = WandoraOptionPane.showConfirmDialog(wandora, confirmMessage,"Confirm delete", WandoraOptionPane.YES_TO_ALL_NO_CANCEL_OPTION);
setState(VISIBLE);
if(answer == WandoraOptionPane.YES_OPTION) {
return true;
}
if(answer == WandoraOptionPane.YES_TO_ALL_OPTION) {
yesToAll = true;
return true;
}
else if(answer == WandoraOptionPane.CANCEL_OPTION) {
shouldContinue = false;
}
return false;
}
}
public String buildAssociationName(Association association) throws TopicMapException {
if(association == null) return "[null]";
String typeName = getTopicName(association.getType());
Iterator roleIterator = association.getRoles().iterator();
StringBuilder playerDescription = new StringBuilder("");
while(roleIterator.hasNext()) {
Topic role = (Topic) roleIterator.next();
Topic player = association.getPlayer(role);
playerDescription.append("'").append(getTopicName(player)).append("'");
if(roleIterator.hasNext()) playerDescription.append(" and ");
}
return "'" + typeName + "' association between " + playerDescription.toString();
}
}
| 7,819 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
FindAssociationsInOccurrenceSimple.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/associations/FindAssociationsInOccurrenceSimple.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* FindAssociationsInOccurrenceSimple.java
*
* Created on 27.12.2008, 10:57
*
*/
package org.wandora.application.tools.associations;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.WandoraOptionPane;
import org.wandora.application.gui.texteditor.OccurrenceTextEditor;
import org.wandora.application.tools.AbstractWandoraTool;
import org.wandora.application.tools.GenericOptionsDialog;
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 akivela
*/
public class FindAssociationsInOccurrenceSimple extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
public static final String OPTIONS_PREFIX = "options.occurrence.findassociations.";
private boolean requiresRefresh = false;
public static boolean LOOK_BASE_NAME = true;
public static boolean LOOK_VARIANT_NAMES = true;
public static boolean LOOK_SIS = false;
public static boolean CASE_INSENSITIVE = true;
public static String BASE_SI = "http://wandora.org/si/schema/";
/** Creates a new instance of FindAssociationsInOccurrenceSimple */
public FindAssociationsInOccurrenceSimple() {
}
public FindAssociationsInOccurrenceSimple(Context preferredContext) {
setContext(preferredContext);
}
@Override
public String getName() {
return "Find associations in occurrence";
}
@Override
public String getDescription() {
return "Recognize topics in occurrence text and associate occurrence's topic to recognized topics.";
}
@Override
public boolean requiresRefresh() {
return requiresRefresh;
}
@Override
public void initialize(Wandora wandora, org.wandora.utils.Options options,String prefix) throws TopicMapException {
try {
LOOK_BASE_NAME = options.getBoolean(OPTIONS_PREFIX+"checkbasename", true);
LOOK_VARIANT_NAMES = options.getBoolean(OPTIONS_PREFIX+"checkvariantnames", true);
LOOK_SIS = options.getBoolean(OPTIONS_PREFIX+"checksis", false);
}
catch(Exception e) {
wandora.handleError(e);
}
}
@Override
public boolean isConfigurable(){
return true;
}
@Override
public void configure(Wandora wandora, org.wandora.utils.Options options, String prefix) throws TopicMapException {
try {
initialize(wandora, options, prefix);
GenericOptionsDialog god=new GenericOptionsDialog(wandora,"Configurable options for find associations in occurrence","Find associations in occurrence options",true,new String[][]{
new String[]{"Look in base names","boolean", LOOK_BASE_NAME ? "true" : "false", null},
new String[]{"Look in variant names","boolean", LOOK_VARIANT_NAMES ? "true" : "false", null},
new String[]{"Look in subject identifiers","boolean", LOOK_SIS ? "true" : "false", null},
},wandora);
god.setVisible(true);
if(god.wasCancelled()) return;
// ---- ok ----
Map<String,String> values=god.getValues();
LOOK_BASE_NAME = ("true".equals(values.get("Look in base names")));
LOOK_VARIANT_NAMES = ("true".equals(values.get("Look in variant names")));
LOOK_SIS = ("true".equals(values.get("Look in subject identifiers")));
writeOptions(wandora, options, prefix);
}
catch(Exception e) {
wandora.handleError(e);
}
}
@Override
public void writeOptions(Wandora wandora, org.wandora.utils.Options options, String prefix){
options.put(OPTIONS_PREFIX+"checkbasename", LOOK_BASE_NAME ? "true" : "false" );
options.put(OPTIONS_PREFIX+"checkvariantnames", LOOK_VARIANT_NAMES ? "true" : "false");
options.put(OPTIONS_PREFIX+"checksis", LOOK_SIS ? "true" : "false");
}
@Override
public void execute(Wandora wandora, Context context) {
try {
int associationCount = 0;
Iterator topics = context.getContextObjects();
if(topics == null || !topics.hasNext()) return;
String occurrence = null;
Topic occurrenceType = null;
Topic occurrenceScope = null;
Locator occurrenceTypeLocator = null;
Locator occurrenceScopeLocator = null;
Object source = getContext().getContextSource();
if(source != null && source instanceof OccurrenceTextEditor) {
OccurrenceTextEditor editor = (OccurrenceTextEditor) source;
occurrenceType = editor.getOccurrenceType();
occurrenceScope = editor.getOccurrenceVersion();
Topic occurrenceTopic = editor.getOccurrenceTopic();
String newOccurrence = editor.getText();
occurrence = occurrenceTopic.getData(occurrenceType, occurrenceScope);
if(!newOccurrence.equals(occurrence)) {
int a = WandoraOptionPane.showConfirmDialog(wandora, "You have changed occurrence in editor. Would you like to save changes to topic map before association seek? If you decide not to save changes, old occurrence text is used.", "Save changes?", WandoraOptionPane.QUESTION_MESSAGE);
if(a == WandoraOptionPane.OK_OPTION) {
occurrenceTopic.setData(occurrenceType, occurrenceScope, newOccurrence);
}
}
}
// Ensure occurrence type and scope are really ok...
if(occurrenceType == null) {
occurrenceType=wandora.showTopicFinder("Select occurrence type...");
if(occurrenceType == null) return;
}
occurrenceTypeLocator = occurrenceType.getSubjectIdentifiers().iterator().next();
if(occurrenceScope == null) {
occurrenceScope=wandora.showTopicFinder("Select occurrence scope...");
if(occurrenceScope == null) return;
}
occurrenceScopeLocator = occurrenceScope.getSubjectIdentifiers().iterator().next();
// Initialize tool logger and variable...
setDefaultLogger();
setLogTitle("Find associations in occurrence");
log("Find associations in occurrence");
Topic occurrenceTopic = null;
Topic oldTopic = null;
int progress = 0;
TopicMap map = wandora.getTopicMap();
Association a = null;
ArrayList<Topic> dtopics = new ArrayList<Topic>();
while(topics.hasNext() && !forceStop()) {
dtopics.add((Topic) topics.next());
}
topics = dtopics.iterator();
// Iterate through selected topics...
while(topics.hasNext() && !forceStop()) {
try {
occurrenceTopic = (Topic) topics.next();
if(occurrenceTopic != null && !occurrenceTopic.isRemoved()) {
progress++;
hlog("Inspecting topic's '"+getTopicName(occurrenceTopic)+"' occurrence");
occurrenceType = occurrenceTopic.getTopicMap().getTopic(occurrenceTypeLocator);
occurrenceScope = occurrenceTopic.getTopicMap().getTopic(occurrenceScopeLocator);
if(occurrenceType != null && occurrenceScope != null) {
occurrence = occurrenceTopic.getData(occurrenceType, occurrenceScope);
// Ok, if topic has sufficient occurrence descent deeper...
if(occurrence != null && occurrence.length() > 0) {
Iterator<Topic> allTopics = map.getTopics();
requiresRefresh = false;
while(allTopics.hasNext() && !forceStop()) {
oldTopic = allTopics.next();
if(oldTopic != null && !oldTopic.isRemoved()) {
if(isMatch(occurrence, oldTopic)) {
requiresRefresh = true;
break;
}
}
}
if(requiresRefresh) {
Topic associationType = getOrCreateTopic(map, "Occurrence association", BASE_SI+"occurrence-association");
Topic topicInOccurrenceRole = getOrCreateTopic(map, "Topic in occurrence", BASE_SI+"topic-in-occurrence");
Topic occurrenceContainerRole = getOrCreateTopic(map, "Occurrence container", BASE_SI+"occurrence-container");
allTopics = map.getTopics();
while(allTopics.hasNext() && !forceStop()) {
oldTopic = allTopics.next();
if(oldTopic != null && !oldTopic.isRemoved()) {
if(isMatch(occurrence, oldTopic)) {
// Creating new association between occurrencce container and found topic
log("Creating association between '"+getTopicName(occurrenceTopic)+"' and '"+getTopicName(oldTopic)+"'.");
a = map.createAssociation(associationType);
a.addPlayer(oldTopic, topicInOccurrenceRole);
a.addPlayer(occurrenceTopic, occurrenceContainerRole);
associationCount++;
}
}
}
}
}
}
else {
log("Can't find occurrence type or scope topic in the occurrence topic.");
}
}
}
catch(Exception e) {
log(e);
}
}
if(!requiresRefresh) {
log("No associations found in occurrence(s).");
}
else {
log("Total "+associationCount+" associations created.");
}
setState(WAIT);
}
catch (Exception e) {
log(e);
}
}
public boolean isMatch(String occurrence, Topic t) {
boolean associate = false;
try {
if(occurrence != null && t != null && !t.isRemoved()) {
if(LOOK_BASE_NAME) {
String topicName = t.getBaseName();
if(contains(occurrence, topicName)) {
associate = true;
}
}
if(!associate && LOOK_VARIANT_NAMES) {
String name = null;
Set<Set<Topic>> scopes = t.getVariantScopes();
Iterator<Set<Topic>> scopeIterator = scopes.iterator();
Set<Topic> scope = null;
while(scopeIterator.hasNext()) {
scope = scopeIterator.next();
if(scope != null) {
name = t.getVariant(scope);
if(name != null && name.length() > 0) {
if(contains(occurrence, name)) {
associate = true;
break;
}
}
}
}
}
if(!associate && LOOK_SIS) {
Collection<Locator> sis = t.getSubjectIdentifiers();
Iterator<Locator> sisIterator = sis.iterator();
Locator si = null;
String siStr = null;
while(sisIterator.hasNext()) {
si = sisIterator.next();
siStr = si.toExternalForm();
if(contains(occurrence, siStr)) {
associate = true;
break;
}
else {
}
}
}
}
}
catch(Exception e) { log(e); }
return associate;
}
public boolean contains(String s1, String s2) {
if(s1 == null || s2 == null) return false;
if(CASE_INSENSITIVE) {
return s1.toLowerCase().contains(s2.toLowerCase());
}
else {
return s1.contains(s2);
}
}
public Topic getOrCreateTopic(TopicMap tm, String basename, String si) throws TopicMapException {
if(tm == null || si == null) return null;
Topic t = tm.getTopic(si);
if(t == null) {
t = tm.createTopic();
t.addSubjectIdentifier(new Locator(si));
t.setBaseName(basename);
}
return t;
}
}
| 14,832 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AddSchemalessAssociation.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/associations/AddSchemalessAssociation.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* AddFreeAssociation.java
*
* Created on 14.6.2006, 10:04
*/
package org.wandora.application.tools.associations;
import java.util.Iterator;
import org.wandora.application.Wandora;
import org.wandora.application.contexts.Context;
import org.wandora.application.contexts.LayeredTopicContext;
import org.wandora.application.gui.FreeAssociationPrompt;
import org.wandora.application.tools.AbstractWandoraTool;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author olli
*/
public class AddSchemalessAssociation extends AbstractWandoraTool {
private static final long serialVersionUID = 1L;
/** Creates a new instance of AddFreeAssociation */
public AddSchemalessAssociation() {
setContext(new LayeredTopicContext());
}
public AddSchemalessAssociation(Context preferredContext) {
setContext(preferredContext);
}
@Override
public String getName() {
return "Add associations";
}
@Override
public String getDescription() {
return "Open association editor. "+
"Association editor is used to add and edit associations.";
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
Iterator contextTopics = context.getContextObjects();
if(contextTopics == null || !contextTopics.hasNext()) return;
Topic topic = (Topic) contextTopics.next();
if( !contextTopics.hasNext() ) {
if(topic != null && !topic.isRemoved()) {
FreeAssociationPrompt d=new FreeAssociationPrompt(wandora,topic);
d.setVisible(true);
}
}
else {
log("Context contains more than one topic! Unable to decide topic to add associations to.");
}
}
}
| 2,645 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
CollectBinaryToNary.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/associations/CollectBinaryToNary.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* CollectBinaryToNary.java
*
* Created on 7. huhtikuuta 2006, 10:53
*
*/
package org.wandora.application.tools.associations;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.AssociationContext;
import org.wandora.application.contexts.Context;
import org.wandora.application.tools.AbstractWandoraTool;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicInUseException;
import org.wandora.topicmap.TopicMapException;
/**
* <p>
* Tool builds single n-association from n binary associations.
* Number of association topics is reduced by one. Examples:
* </p>
*
* <code>
* c
* /
* (a -- b) -- d ==> a -- c -- d -- f , [b]
* \
* f
*
*
* c
* /
* (a) -- b -- d ==> a -- c -- d -- f , [b]
* \
* f
*
* x = topic
* [x] = topic x is removed
* (x) = topic x is in context
* (x -- y) = association is in context
* </code>
*
*
* Note: Default context of this tool is <code>AssociationContext</code>!
*
* @author akivela
*/
public class CollectBinaryToNary extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
private boolean deleteOld = false;
private boolean askNewAssociationType = true;
private boolean requiresRefresh = false;
public CollectBinaryToNary() {
setContext(new AssociationContext());
}
public CollectBinaryToNary(Context preferredContext) {
setContext(preferredContext);
}
@Override
public String getName() {
return "Collect binary to n-ary";
}
@Override
public String getDescription() {
return "Builds single n-association from n binary associations.";
}
@Override
public boolean requiresRefresh() {
return requiresRefresh;
}
@Override
public void execute(Wandora wandora, Context context) {
try {
requiresRefresh = false;
Iterator<Association> associations = null;
Topic baseTopic = null;
Association association = null;
int counter = 0;
if(context instanceof AssociationContext) { // ASSOCIATION CONTEXT!!
associations = context.getContextObjects();
Topic newAssociationType = null;
if(askNewAssociationType) {
wandora.showTopicFinder("Select new type of associations...");
if(newAssociationType == null) return;
}
baseTopic = wandora.getOpenTopic();
while(associations.hasNext() && !forceStop()) {
association = (Association) associations.next();
if(association != null && !association.isRemoved()) {
if(!askNewAssociationType) newAssociationType=association.getType();
breakAssociation(association, baseTopic, newAssociationType);
counter++;
}
}
if(deleteOld) {
associations = context.getContextObjects();
while(associations.hasNext() && !forceStop()) {
association = (Association) associations.next();
if(association != null && !association.isRemoved()) {
deletePlayers(association, baseTopic);
}
}
}
}
else { // TOPIC CONTEXT!!
Topic addressedAssociationType = wandora.showTopicFinder("Select type of processed associations...");
if(addressedAssociationType == null) return;
Topic newAssociationType = addressedAssociationType;
if(askNewAssociationType) {
wandora.showTopicFinder("Select new type of associations...");
if(newAssociationType == null) return;
}
Iterator<Topic> baseTopics = context.getContextObjects();
baseTopic = null;
associations = null;
Collection associationCollection = null;
setDefaultLogger();
long startTime = System.currentTimeMillis();
while(baseTopics.hasNext() && !forceStop()) {
baseTopic = (Topic) baseTopics.next();
if(baseTopic != null && !baseTopic.isRemoved()) {
hlog("Processing associations of '"+getTopicName(baseTopic)+"'.");
associationCollection = baseTopic.getAssociations(addressedAssociationType);
if(associationCollection != null) {
associations = associationCollection.iterator();
while(associations.hasNext() && !forceStop()) {
association = (Association) associations.next();
if(association != null && !association.isRemoved()) {
breakAssociation(association, baseTopic, newAssociationType);
counter++;
}
}
if(deleteOld && !forceStop()) {
associations = associationCollection.iterator();
while(associations.hasNext() && !forceStop()) {
association = (Association) associations.next();
if(association != null && !association.isRemoved()) {
deletePlayers(association, baseTopic);
}
}
}
}
}
}
long endTime = System.currentTimeMillis();
log("Execution took "+((endTime-startTime)/1000)+" seconds.");
}
log("Total "+counter+" associations processed.");
}
catch(Exception e) {
log(e);
}
setState(WAIT);
}
public void breakAssociation(Association association, Topic baseTopic, Topic newAssociationType) {
Topic roleTopic = null;
Topic playerTopic = null;
Association newAssociation = null;
Collection<Association> playerAssociations = null;
Iterator<Association> playerAssociationIterator = null;
Association playerAssociation = null;
Collection<Topic> playerAssociationRoles = null;
Iterator<Topic> playerAssociationRoleIterator = null;
Topic playerAssociationRole = null;
Topic playerAssociationPlayer = null;
Collection<Topic> roles = null;
Iterator<Topic> roleIterator = null;
Topic baseRole = null;
Topic associationType = null;
HashMap<Topic, Topic> newMembers = new HashMap<Topic, Topic>();
System.out.println("-------------in");
try {
if(association != null && baseTopic != null) {
ArrayList<Topic> playerTopics = new ArrayList<Topic>();
roles = association.getRoles();
roleIterator = roles.iterator();
associationType = association.getType();
// First finding baseTopic's role topic in the association
while(roleIterator.hasNext()) {
roleTopic = roleIterator.next();
if(roleTopic != null) {
playerTopic = association.getPlayer(roleTopic);
if(playerTopic.mergesWithTopic(baseTopic)) {
baseRole = roleTopic;
System.out.println("1 Adding player '"+getTopicName(baseTopic)+"' with role '"+roleTopic.getBaseName()+"'.");
newMembers.put(roleTopic, baseTopic);
}
else {
playerTopics.add(playerTopic);
System.out.println("3 Investigating player: " + getTopicName(playerTopic));
}
}
}
Iterator<Topic> playerIterator = playerTopics.iterator();
while(playerIterator.hasNext()) {
playerTopic = playerIterator.next();
System.out.println("4 Investigating player: " + getTopicName(playerTopic));
playerAssociations = playerTopic.getAssociations();
playerAssociationIterator = playerAssociations.iterator();
while(playerAssociationIterator.hasNext()) {
playerAssociation = playerAssociationIterator.next();
if(playerAssociation != null && !associationType.mergesWithTopic(playerAssociation.getType())) {
playerAssociationRoles = playerAssociation.getRoles();
playerAssociationRoleIterator = playerAssociationRoles.iterator();
while(playerAssociationRoleIterator.hasNext()) {
playerAssociationRole = playerAssociationRoleIterator.next();
if(!playerAssociationRole.mergesWithTopic(baseRole) && !playerAssociationRole.mergesWithTopic(roleTopic)) {
playerAssociationPlayer = playerAssociation.getPlayer(playerAssociationRole);
//System.out.println("2 Checking '"+getTopicName(playerAssociationPlayer)+"' with role '"+getTopicName(playerAssociationRole)+"'.");
if(!playerAssociationPlayer.mergesWithTopic(playerTopic) && !playerAssociationPlayer.mergesWithTopic(baseTopic)) {
//System.out.println("2 Adding player '"+getTopicName(playerAssociationPlayer)+"' with role '"+getTopicName(playerAssociationRole)+"'.");
newMembers.put(playerAssociationRole, playerAssociationPlayer);
}
}
}
}
}
}
if(newMembers.size() > 1) {
newAssociation = baseTopic.getTopicMap().createAssociation(newAssociationType);
newAssociation.addPlayers(newMembers);
requiresRefresh = true;
//if(deleteOld) topicsToDelete.add(playerTopic);
}
}
}
catch(TopicInUseException tiue) {
try {
log("Topic '"+getTopicName(playerTopic)+"' is used as an association or occurrence type and can not be removed!");
}
catch(Exception e) {
log(e);
}
}
catch(Exception e) {
log(e);
}
System.out.println("-------------out");
}
public void deletePlayers(Association association, Topic baseTopic) throws TopicMapException {
Collection<Topic> roles = association.getRoles();
Iterator<Topic> roleIterator = roles.iterator();
Topic playerTopic = null;
Topic roleTopic = null;
ArrayList<Topic> topicsToDelete = new ArrayList<Topic>();
while(roleIterator.hasNext()) {
roleTopic = roleIterator.next();
if(roleTopic != null) {
playerTopic = association.getPlayer(roleTopic);
if(!playerTopic.mergesWithTopic(baseTopic)) {
topicsToDelete.add(playerTopic);
}
}
}
Iterator<Topic> deleteIterator = topicsToDelete.iterator();
Topic topic = null;
while(deleteIterator.hasNext()) {
topic = deleteIterator.next();
if(!topic.isRemoved()) {
//hlog("Deleting topic '"+getTopicName(topic)+"'.");
topic.remove();
requiresRefresh = true;
}
}
}
}
| 13,496 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
ModifySchemalessAssociation.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/associations/ModifySchemalessAssociation.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
* ModifySchemalessAssociation.java
*
* Created on 18. helmikuuta 2008, 12:18
*
*/
package org.wandora.application.tools.associations;
import java.util.Iterator;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.AssociationContext;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.FreeAssociationPrompt;
import org.wandora.application.tools.AbstractWandoraTool;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author olli
*/
public class ModifySchemalessAssociation extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
/** Creates a new instance of ModifySchemalessAssociation */
public ModifySchemalessAssociation() {
setContext(new AssociationContext());
}
public ModifySchemalessAssociation(Context preferredContext) {
setContext(preferredContext);
}
@Override
public String getName() {
return "Modify Schemaless Association";
}
@Override
public String getDescription() {
return "Opens association editor. "+
"Editor is used to add and modify associations in Wandora.";
}
public void execute(Wandora wandora, Context context) throws TopicMapException {
Iterator contextAssociations = context.getContextObjects();
if(contextAssociations == null || !contextAssociations.hasNext()) return;
Association association = (Association) contextAssociations.next();
if( !contextAssociations.hasNext() ) {
if(association != null) {
//Topic topic = wandora.getOpenTopic();
//FreeAssociationPrompt prompt = new FreeAssociationPrompt(wandora,topic,association);
FreeAssociationPrompt prompt = new FreeAssociationPrompt(wandora, association);
prompt.setVisible(true);
}
}
else {
log("Context contains more than one association! Unable to decide association to modify.");
}
}
}
| 2,973 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
StoredQuery.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/sqlconsole/StoredQuery.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* StoredQuery.java
*
* Created on 28. joulukuuta 2004, 15:54
*/
package org.wandora.application.tools.sqlconsole;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Map;
import java.util.TreeMap;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
*
* @author olli
*/
public class StoredQuery {
private String name;
private String description;
private String query;
/** Creates a new instance of StoredQuery */
public StoredQuery(String name,String description,String query) {
this.name=name;
this.description=description;
this.query=query;
}
public String getName(){return name;}
public String getDescription(){return description;}
public String getQuery(){return query;}
public void setName(String name){this.name=name;}
public void setDescription(String description){this.description=description;}
public void setQuery(String query){this.query=query;}
private static String cleanXML(String s){
return s.replaceAll("&","&").replaceAll("<","<");
}
private static String getElementContents(Element e){
return org.wandora.utils.XMLParamProcessor.getElementContents(e);
}
public String getXML(){
return "\t\t<name>"+cleanXML(name)+"</name>\n"+
"\t\t<description>"+cleanXML(description)+"</description>\n"+
"\t\t<query>"+cleanXML(query)+"</query>";
}
public static StoredQuery parseXML(Element element){
String name="";
String description="";
String query="";
NodeList nl=element.getChildNodes();
for(int i=0;i<nl.getLength();i++){
Node n=nl.item(i);
if(n instanceof Element){
Element e=(Element)n;
String nodename=e.getNodeName();
if(nodename.equals("name")){
name=getElementContents(e);
}
else if(nodename.equals("description")){
description=getElementContents(e);
}
else if(nodename.equals("query")){
query=getElementContents(e);
}
}
}
return new StoredQuery(name,description,query);
}
public static Map<String,StoredQuery> loadStoredQueries(String file) throws Exception {
Map<String,StoredQuery> storedQueries=new TreeMap<String,StoredQuery>();
Document doc=org.wandora.utils.XMLParamProcessor.parseDocument(file);
NodeList nl=doc.getDocumentElement().getChildNodes();
for(int i=0;i<nl.getLength();i++){
Node n=nl.item(i);
if(n instanceof Element){
Element e=(Element)n;
if(e.getNodeName().equals("storedquery")){
StoredQuery sq=StoredQuery.parseXML(e);
storedQueries.put(sq.getName(),sq);
}
}
}
return storedQueries;
}
public static void saveStoredQueries(Map<String,StoredQuery> storedQueries,String file) throws IOException {
FileOutputStream fos=new FileOutputStream(file);
PrintWriter writer=new PrintWriter(new OutputStreamWriter(fos,"UTF-8"));
writer.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
writer.println("<storedqueries>");
for(Map.Entry<String,StoredQuery> e : storedQueries.entrySet() ){
writer.println("\t<storedquery>");
StoredQuery sq=e.getValue();
writer.println(sq.getXML());
writer.println("\t</storedquery>");
}
writer.println("</storedqueries>");
writer.close();
}
}
| 4,679 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SQLConsolePanel.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/sqlconsole/SQLConsolePanel.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* SQLConsolePanel.java
*
* Created on 28. joulukuuta 2004, 15:09
*/
package org.wandora.application.tools.sqlconsole;
import java.io.IOException;
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.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.Vector;
import org.wandora.application.tools.sqlconsole.data.PatternFilteredTableView;
import org.wandora.application.tools.sqlconsole.data.RowTable;
import org.wandora.application.tools.sqlconsole.data.TableView;
import org.wandora.application.tools.sqlconsole.gui.SQLTablePanel;
import org.wandora.utils.Delegate;
import org.wandora.utils.Options;
/**
*
* @author olli
*/
public class SQLConsolePanel extends javax.swing.JPanel {
private static final long serialVersionUID = 1L;
private Map<String,StoredQuery> storedQueries=new TreeMap<String,StoredQuery>();
private Connection connection;
private int resultMaxRows;
private Options options;
private boolean isSimpleView;
/** Creates new form SQLConsolePanel */
public SQLConsolePanel(Options options) {
this.options=options;
initComponents();
switchToSimple(null);
resultMaxRows=500;
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
private void initComponents() {//GEN-BEGIN:initComponents
splitPane = new javax.swing.JSplitPane();
queryPanelContainer = new javax.swing.JPanel();
queryPanel = new javax.swing.JPanel();
resultScrollPane = new javax.swing.JScrollPane();
resultContainer = new javax.swing.JPanel();
resultPanel = new javax.swing.JPanel();
setLayout(new java.awt.BorderLayout());
splitPane.setDividerLocation(200);
splitPane.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
queryPanelContainer.setLayout(new java.awt.BorderLayout());
queryPanelContainer.add(queryPanel, java.awt.BorderLayout.CENTER);
splitPane.setLeftComponent(queryPanelContainer);
resultContainer.setLayout(new java.awt.BorderLayout());
resultContainer.add(resultPanel, java.awt.BorderLayout.CENTER);
resultScrollPane.setViewportView(resultContainer);
splitPane.setRightComponent(resultScrollPane);
add(splitPane, java.awt.BorderLayout.CENTER);
}//GEN-END:initComponents
public static Connection getConnection(String driver,String connectString,String user,String password)
throws ClassNotFoundException,SQLException {
System.out.println("Opening DB connection with driver " + driver);
Class.forName(driver);
return DriverManager.getConnection(connectString,user,password);
}
public void connect(String driver,String connectString,String user,String password) {
try{
connection=getConnection(driver,connectString,user,password);
}catch(ClassNotFoundException cnfe){
SQLConsole.reportException(cnfe);
}catch(SQLException sqlException){
SQLConsole.reportException(sqlException);
}
}
public void setResultMaxRows(int count){resultMaxRows=count;}
public int getResultMaxRows(){return resultMaxRows;}
public void executeQuery(String query){
SQLQueryResult result=executeQueryLowLevel(query);
if(result==null) return;
if(result.resultIsRows){
int h=splitPane.getDividerLocation();
TableView tableView=new PatternFilteredTableView(new RowTable(result.columnNames,result.rows));
resultPanel=new SQLTablePanel(tableView);
resultContainer.removeAll();
resultContainer.add(resultPanel);
((SQLTablePanel)resultPanel).setHeaderVisible(false);
javax.swing.table.JTableHeader tableHeader=((SQLTablePanel)resultPanel).getTableHeader();
resultPanel.setPreferredSize(new java.awt.Dimension((int)tableHeader.getPreferredSize().getWidth(),(int)resultPanel.getPreferredSize().getHeight()));
resultScrollPane.setColumnHeaderView(tableHeader);
splitPane.setDividerLocation(h);
resultPanel.validate();
resultPanel.repaint();
if(result.rowCountOverFlow){
javax.swing.JOptionPane.showMessageDialog(this,"Näytetään vain ensimmäiset "+result.rows.size()+" rivi�.");
}
}
else{
javax.swing.JOptionPane.showMessageDialog(this,"Statement executed. "+result.count+" rows updated.");
}
}
public static SQLQueryResult executeQueryLowLevel(String query,Connection connection,int resultMaxRows) throws SQLException {
return executeQueryLowLevel(query,connection,resultMaxRows,null);
}
public static SQLQueryResult executeQueryLowLevel(String query,Connection connection,int resultMaxRows,Delegate<Integer,Integer> onOverflow) throws SQLException {
System.out.println("Excecuting query "+query);
Statement statement=connection.createStatement();
query=query.trim();
boolean type=statement.execute(query);
if(type){
ResultSet resultSet=statement.getResultSet();
ResultSetMetaData metaData=resultSet.getMetaData();
int columns=metaData.getColumnCount();
String[] columnNames=new String[columns];
for(int i=0;i<columns;i++){
columnNames[i]=metaData.getColumnName(i+1);
}
int count=0;
Vector<Object[]> rows=new Vector<>();
boolean hasNext = resultSet.next();
while(hasNext) {
try {
if(resultMaxRows!=-1 && count>=resultMaxRows){
if(onOverflow==null) break;
resultMaxRows=onOverflow.invoke(resultMaxRows);
if(resultMaxRows==0) break;
}
Object[] row=new Object[columns];
for(int i=0;i<columns;i++){
row[i]=resultSet.getObject(i+1);
}
rows.add(row);
count++;
hasNext = resultSet.next();
System.out.println("count == " + count);
}
catch (Exception e) {
e.printStackTrace();
hasNext = true;
}
}
boolean overflow=resultSet.next();
resultSet.close();
statement.close();
return new SQLQueryResult(rows,columnNames,overflow);
}
else{
int updateCount=statement.getUpdateCount();
statement.close();
return new SQLQueryResult(updateCount);
}
}
public SQLQueryResult executeQueryLowLevel(String query){
try{
return executeQueryLowLevel(query,connection,resultMaxRows);
}catch(SQLException sqlException){
SQLConsole.reportException(sqlException);
return null;
}
}
public void saveQuery(StoredQuery query){
storedQueries.put(query.getName(),query);
}
public void switchToSimple(String name){
queryPanelContainer.removeAll();
queryPanel=new StoredQueryPanel(this,storedQueries);
queryPanelContainer.add(queryPanel);
if(name!=null){
((StoredQueryPanel)queryPanel).selectQuery(name);
}
setSimpleSize();
isSimpleView=true;
}
public void setSimpleSize(){
if(!(queryPanel instanceof StoredQueryPanel)) return;
int h=((StoredQueryPanel)queryPanel).getPreferredHeight();
splitPane.setDividerLocation(h+splitPane.getDividerSize());
this.validate();
this.repaint();
}
public void switchToEdit(StoredQuery query){
queryPanelContainer.removeAll();
queryPanel=new EditQueryPanel(this,query);
queryPanelContainer.add(queryPanel);
splitPane.setDividerLocation(300);
// this.validateTree(); // TRIGGERS EXCEPTION IN JAVA 1.7
this.repaint();
isSimpleView=false;
}
public void updateSimpleView(){
if(isSimpleView){
switchToSimple(null);
}
}
public void clearStoredQueries(){
storedQueries=new HashMap<>();
updateSimpleView();
}
public void loadStoredQueries() throws Exception {
storedQueries=StoredQuery.loadStoredQueries(options.get("options.sqlconsole.storefile"));
updateSimpleView();
}
public void saveStoredQueries() throws IOException {
StoredQuery.saveStoredQueries(storedQueries,options.get("options.sqlconsole.storefile"));
updateSimpleView();
}
public void importQueries(Map<String,StoredQuery> queries){
for(String key : queries.keySet()){
storedQueries.put(key,queries.get(key));
}
}
public Map<String,StoredQuery> getStoredQueries(){
return storedQueries;
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel queryPanel;
private javax.swing.JPanel queryPanelContainer;
private javax.swing.JPanel resultContainer;
private javax.swing.JPanel resultPanel;
private javax.swing.JScrollPane resultScrollPane;
private javax.swing.JSplitPane splitPane;
// End of variables declaration//GEN-END:variables
}
| 10,654 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
StoredQueryPanel.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/sqlconsole/StoredQueryPanel.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* StoredQueryPanel.java
*
* Created on 28. joulukuuta 2004, 15:13
*/
package org.wandora.application.tools.sqlconsole;
import java.util.Map;
import java.util.TreeMap;
import javax.swing.text.JTextComponent;
/**
*
* @author olli
*/
public class StoredQueryPanel extends javax.swing.JPanel {
private static final long serialVersionUID = 1L;
private Map<String,StoredQuery> storedQueries;
private Map<String,JTextComponent> paramMap=new TreeMap<String,JTextComponent>();
private SQLConsolePanel parent;
/** Creates new form StoredQueryPanel */
public StoredQueryPanel(SQLConsolePanel parent,Map<String,StoredQuery> storedQueries) {
this.storedQueries=storedQueries;
this.parent=parent;
initComponents();
queryComboBox.setEditable(false);
setupQueryComboBox();
}
private void setupQueryComboBox(){
queryComboBox.removeAllItems();
for(String q : storedQueries.keySet()){
queryComboBox.addItem(q);
}
}
public void selectQuery(String name){
queryComboBox.setSelectedItem(name);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
private void initComponents() {//GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
scrollPane = new javax.swing.JScrollPane();
jPanel2 = new javax.swing.JPanel();
queryComboBox = new javax.swing.JComboBox();
parameterLabelsPanel = new javax.swing.JPanel();
jPanel1 = new javax.swing.JPanel();
jPanel3 = new javax.swing.JPanel();
editButton = new javax.swing.JButton();
newButton = new javax.swing.JButton();
deleteButton = new javax.swing.JButton();
jPanel4 = new javax.swing.JPanel();
executeButton = new javax.swing.JButton();
descriptionPane = new javax.swing.JTextPane();
parameterFieldsPanel = new javax.swing.JPanel();
setLayout(new java.awt.BorderLayout());
jPanel2.setLayout(new java.awt.GridBagLayout());
queryComboBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
queryComboBoxActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10);
jPanel2.add(queryComboBox, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10);
jPanel2.add(parameterLabelsPanel, gridBagConstraints);
jPanel1.setLayout(new java.awt.GridBagLayout());
editButton.setText("Muokkaa");
editButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
editButtonActionPerformed(evt);
}
});
jPanel3.add(editButton);
newButton.setText("Uusi");
newButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
newButtonActionPerformed(evt);
}
});
jPanel3.add(newButton);
deleteButton.setText("Poista");
deleteButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
deleteButtonActionPerformed(evt);
}
});
jPanel3.add(deleteButton);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
jPanel1.add(jPanel3, gridBagConstraints);
executeButton.setText("Suorita");
executeButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
executeButtonActionPerformed(evt);
}
});
jPanel4.add(executeButton);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.weightx = 1.0;
jPanel1.add(jPanel4, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10);
jPanel2.add(jPanel1, gridBagConstraints);
descriptionPane.setEditable(false);
descriptionPane.setFocusable(false);
descriptionPane.setOpaque(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(10, 0, 10, 10);
jPanel2.add(descriptionPane, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(10, 0, 10, 10);
jPanel2.add(parameterFieldsPanel, gridBagConstraints);
scrollPane.setViewportView(jPanel2);
add(scrollPane, java.awt.BorderLayout.CENTER);
}//GEN-END:initComponents
private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed
String q=(String)queryComboBox.getSelectedItem();
if(q!=null){
storedQueries.remove(q);
parent.switchToSimple(null);
}
}//GEN-LAST:event_deleteButtonActionPerformed
private void newButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newButtonActionPerformed
StoredQuery query=new StoredQuery("","","");
parent.switchToEdit(query);
}//GEN-LAST:event_newButtonActionPerformed
private void editButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editButtonActionPerformed
String q=(String)queryComboBox.getSelectedItem();
StoredQuery query=new StoredQuery("","","");
if(q!=null){
StoredQuery qu=(StoredQuery)storedQueries.get(q);
if(qu!=null) query=qu;
}
parent.switchToEdit(query);
}//GEN-LAST:event_editButtonActionPerformed
private void executeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_executeButtonActionPerformed
String q=(String)queryComboBox.getSelectedItem();
if(q==null) return;
StoredQuery query=storedQueries.get(q);
if(query==null) return;
String replaced=QueryProcessor.replaceParams(query.getQuery(),paramMap);
parent.executeQuery(replaced);
}//GEN-LAST:event_executeButtonActionPerformed
private void queryComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_queryComboBoxActionPerformed
String q=(String)queryComboBox.getSelectedItem();
if(q==null) return;
StoredQuery query=storedQueries.get(q);
if(query==null) return;
descriptionPane.setText(query.getDescription());
String[] params=QueryProcessor.parseParemeterFields(query.getQuery());
paramMap=QueryProcessor.fillQueryFields(params, parameterLabelsPanel,parameterFieldsPanel);
parent.setSimpleSize();
}//GEN-LAST:event_queryComboBoxActionPerformed
public int getPreferredHeight(){
return (int)scrollPane.getViewport().getPreferredSize().getHeight();
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton deleteButton;
private javax.swing.JTextPane descriptionPane;
private javax.swing.JButton editButton;
private javax.swing.JButton executeButton;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JButton newButton;
private javax.swing.JPanel parameterFieldsPanel;
private javax.swing.JPanel parameterLabelsPanel;
private javax.swing.JComboBox queryComboBox;
private javax.swing.JScrollPane scrollPane;
// End of variables declaration//GEN-END:variables
}
| 10,069 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
QuerySelector.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/sqlconsole/QuerySelector.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* QuerySelector.java
*
* Created on 30. joulukuuta 2004, 10:45
*/
package org.wandora.application.tools.sqlconsole;
import java.util.Map;
import java.util.TreeMap;
import java.util.Vector;
import javax.swing.JList;
import javax.swing.ListSelectionModel;
/**
*
* @author olli
*/
public class QuerySelector extends javax.swing.JDialog {
private static final long serialVersionUID = 1L;
private Vector<String> queryNames;
private Map<String,StoredQuery> storedQueries;
private Map<String,StoredQuery> selection=null;;
/** Creates new form QuerySelector */
public QuerySelector(boolean modal,Map<String,StoredQuery> storedQueries,String message) {
//super(parent, modal);
this.storedQueries=storedQueries;
queryNames=new Vector<String>(storedQueries.keySet());
initComponents();
this.setTitle(message);
messageLabel.setText(message);
queryList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
queryList.setSelectionInterval(0,storedQueries.size()-1);
//this.setLocation(parent.getX()+parent.getWidth()/2-this.getWidth()/2,parent.getY()+parent.getHeight()/2-this.getHeight()/2);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
jScrollPane1 = new javax.swing.JScrollPane();
queryList = new JList(queryNames);
jPanel1 = new javax.swing.JPanel();
selectButton = new javax.swing.JButton();
cancelButton = new javax.swing.JButton();
messageLabel = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
getContentPane().setLayout(new java.awt.GridBagLayout());
jScrollPane1.setViewportView(queryList);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(9, 9, 9, 9);
getContentPane().add(jScrollPane1, gridBagConstraints);
jPanel1.setLayout(new java.awt.GridBagLayout());
selectButton.setText("Select");
selectButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
selectButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
jPanel1.add(selectButton, gridBagConstraints);
cancelButton.setText("Cancel");
cancelButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new java.awt.Insets(10, 0, 0, 0);
jPanel1.add(cancelButton, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
gridBagConstraints.insets = new java.awt.Insets(10, 0, 10, 10);
getContentPane().add(jPanel1, gridBagConstraints);
messageLabel.setText("jLabel1");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 0, 10);
getContentPane().add(messageLabel, gridBagConstraints);
setBounds(0, 0, 369, 370);
}// </editor-fold>//GEN-END:initComponents
private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
selection=null;
this.setVisible(false);
}//GEN-LAST:event_cancelButtonActionPerformed
private void selectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectButtonActionPerformed
int[] selected=queryList.getSelectedIndices();
selection=new TreeMap<String,StoredQuery>();
for(int i=0;i<selected.length;i++){
String q=queryNames.get(selected[i]);
StoredQuery sq=storedQueries.get(q);
selection.put(q,sq);
}
this.setVisible(false);
}//GEN-LAST:event_selectButtonActionPerformed
public Map<String,StoredQuery> getSelection(){
return selection;
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton cancelButton;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel messageLabel;
private javax.swing.JList queryList;
private javax.swing.JButton selectButton;
// End of variables declaration//GEN-END:variables
}
| 6,448 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
QueryProcessor.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/sqlconsole/QueryProcessor.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* QueryProcessor.java
*
* Created on 28. joulukuuta 2004, 15:35
*/
package org.wandora.application.tools.sqlconsole;
import java.awt.Container;
import java.awt.GridLayout;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.text.JTextComponent;
/**
*
* @author olli
*/
public class QueryProcessor {
/** Creates a new instance of QueryProcessor */
public QueryProcessor() {
}
public static String[] parseParemeterFields(String query){
System.out.println("Finding params from "+query);
Vector<String> params=new Vector<>();
Pattern pattern=Pattern.compile("(^|[^\\{])((\\{\\{)*)\\{([^\\{\\}]+)\\}");
Matcher matcher=pattern.matcher(query);
int ptr=0;
while(matcher.find(ptr)){
String param=matcher.group(4);
if(!params.contains(param)) params.add(param);
ptr=matcher.start()+1;
}
System.out.println("Found parameters "+params);
return (String[])params.toArray(new String[0]);
}
public static String replaceParams(String query,String[] params){
if(params!=null) {
for(int i=0;i+1<params.length;i+=2){
String rep=params[i+1].replaceAll("\\\\","\\\\\\\\");
rep=rep.replaceAll("\\$","\\\\\\$");
Pattern pattern=Pattern.compile("(^|[^\\{])((\\{\\{)*)\\{"+params[i]+"\\}");
Matcher matcher=pattern.matcher(query);
query=matcher.replaceAll("$1$2"+rep);
}
}
query=query.replaceAll("\\{\\{","{");
return query;
}
public static String replaceParams(String query,Map<String,JTextComponent> params){
String[] p=new String[params.size()*2];
int ptr=0;
for(Map.Entry<String,JTextComponent> e : params.entrySet()){
p[ptr++]=e.getKey();
p[ptr++]=e.getValue().getText();
}
return replaceParams(query,p);
}
public static HashMap<String,JTextComponent> fillQueryFields(String[] params,Container labelContainer,Container fieldContainer){
HashMap<String,JTextComponent> fieldMap=new HashMap<String,JTextComponent>();
labelContainer.removeAll();
fieldContainer.removeAll();
// labelContainer.setLayout(new GridBagLayout());
// fieldContainer.setLayout(new GridBagLayout());
if(params.length>0) {
labelContainer.setLayout(new GridLayout(params.length,0,0,3));
fieldContainer.setLayout(new GridLayout(params.length,0,0,3));
for(int i=0;i<params.length;i++){
JLabel label=new JLabel(params[i]);
JTextField field=new JTextField();//new JTextField();
/* GridBagConstraints gbc=new GridBagConstraints();
gbc.gridx=0;
gbc.gridy=i;
gbc.weightx=1.0;
gbc.fill=gbc.HORIZONTAL;
gbc.insets.bottom=10;
labelContainer.add(label,gbc);*/
label.setVerticalAlignment(SwingConstants.TOP);
labelContainer.add(label);
/* gbc=new GridBagConstraints();
gbc.gridx=0;
gbc.gridy=i;
gbc.weightx=1.0;
gbc.fill=gbc.HORIZONTAL;
gbc.insets.bottom=10;
fieldContainer.add(field,gbc);*/
fieldContainer.add(field);
fieldMap.put(params[i],field);
}
}
labelContainer.validate();
labelContainer.repaint();
fieldContainer.validate();
fieldContainer.repaint();
return fieldMap;
}
}
| 4,648 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SQLQueryResult.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/sqlconsole/SQLQueryResult.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* SQLQueryResult.java
*
* Created on 29. joulukuuta 2004, 11:31
*/
package org.wandora.application.tools.sqlconsole;
import java.io.StringWriter;
import java.util.Collection;
import java.util.Formatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
/**
*
* @author olli
*/
public class SQLQueryResult {
public List<Object[]> rows;
public int count;
public boolean resultIsRows;
public boolean rowCountOverFlow;
public String[] columnNames;
public Map<String,Integer> columnIndex;
/** Creates a new instance of SQLQueryResult */
public SQLQueryResult(List<Object[]> rows,String[] columnNames,boolean rowCountOverFlow) {
this.rows=rows;
this.columnNames=columnNames;
this.rowCountOverFlow=rowCountOverFlow;
resultIsRows=true;
makeColumnIndex();
}
public SQLQueryResult(int count){
this.count=count;
resultIsRows=false;
}
private void makeColumnIndex(){
columnIndex=new HashMap<>();
for(int i=0;i<columnNames.length;i++){
columnIndex.put(columnNames[i],i);
}
}
public Object get(int row,String columnName){
return get(rows.get(row),columnName);
}
public Object get(Object[] row,String columnName){
return row[columnIndex.get(columnName)];
}
/**
* Constructs a Collection<String> from the rows in this SQLQueryResult.
* Each row is formatted into a single String with the given formatString.
* The formatString is passed to java.util.Formatter.format, with the
* row as the rest of the parameters.
*/
public Collection<String> makeStringCollection(String formatString){
Collection<String> ss=new Vector<>();
for(Object[] row : rows){
StringWriter w=new StringWriter();
Formatter formatter=new Formatter(w);
formatter.format(formatString,row);
ss.add(w.toString());
}
return ss;
}
}
| 2,833 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
EditQueryPanel.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/sqlconsole/EditQueryPanel.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* EditQueryPanel.java
*
* Created on 28. joulukuuta 2004, 15:13
*/
package org.wandora.application.tools.sqlconsole;
import java.util.HashMap;
/**
*
* @author olli
*/
public class EditQueryPanel extends javax.swing.JPanel {
private static final long serialVersionUID = 1L;
private SQLConsolePanel parent;
private HashMap paramMap=new HashMap();
/** Creates new form EditQueryPanel */
public EditQueryPanel(SQLConsolePanel parent,StoredQuery query) {
this.parent=parent;
initComponents();
queryTextPane.setText(query.getQuery());
descriptionTextPane.setText(query.getDescription());
nameTextField.setText(query.getName());
parseParams();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
scrollPane = new javax.swing.JScrollPane();
jPanel3 = new javax.swing.JPanel();
nameTextField = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
saveButton = new javax.swing.JButton();
cancelButton = new javax.swing.JButton();
executeButton = new javax.swing.JButton();
jPanel2 = new javax.swing.JPanel();
parseParamsButton = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
descriptionTextPane = new javax.swing.JTextPane();
jScrollPane2 = new javax.swing.JScrollPane();
queryTextPane = new javax.swing.JTextPane();
paramLabelsPanel = new javax.swing.JPanel();
paramFieldsPanel = new javax.swing.JPanel();
setLayout(new java.awt.BorderLayout());
jPanel3.setLayout(new java.awt.GridBagLayout());
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(9, 10, 3, 10);
jPanel3.add(nameTextField, gridBagConstraints);
jLabel1.setText("Name");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(9, 10, 3, 10);
jPanel3.add(jLabel1, gridBagConstraints);
jLabel2.setText("Description");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 3, 10);
jPanel3.add(jLabel2, gridBagConstraints);
jLabel3.setText("SQL query");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 10, 10);
jPanel3.add(jLabel3, gridBagConstraints);
jPanel1.setLayout(new java.awt.GridBagLayout());
saveButton.setText("Save");
saveButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
saveButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 0);
jPanel1.add(saveButton, gridBagConstraints);
cancelButton.setText("Cancel");
cancelButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 0);
jPanel1.add(cancelButton, gridBagConstraints);
executeButton.setText("Execute");
executeButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
executeButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
jPanel1.add(executeButton, gridBagConstraints);
jPanel2.setLayout(new java.awt.GridBagLayout());
parseParamsButton.setText("Get params");
parseParamsButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
parseParamsButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 10);
jPanel2.add(parseParamsButton, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
jPanel1.add(jPanel2, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10);
jPanel3.add(jPanel1, gridBagConstraints);
descriptionTextPane.setMinimumSize(new java.awt.Dimension(6, 60));
descriptionTextPane.setPreferredSize(new java.awt.Dimension(7, 60));
jScrollPane1.setViewportView(descriptionTextPane);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 0.3;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 3, 10);
jPanel3.add(jScrollPane1, gridBagConstraints);
queryTextPane.setMinimumSize(new java.awt.Dimension(6, 80));
queryTextPane.setPreferredSize(new java.awt.Dimension(7, 80));
jScrollPane2.setViewportView(queryTextPane);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 0.7;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 10, 10);
jPanel3.add(jScrollPane2, gridBagConstraints);
paramLabelsPanel.setLayout(new java.awt.GridBagLayout());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 10);
jPanel3.add(paramLabelsPanel, gridBagConstraints);
paramFieldsPanel.setLayout(new java.awt.GridBagLayout());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 10);
jPanel3.add(paramFieldsPanel, gridBagConstraints);
scrollPane.setViewportView(jPanel3);
add(scrollPane, java.awt.BorderLayout.CENTER);
}// </editor-fold>//GEN-END:initComponents
private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
StoredQuery query=new StoredQuery(nameTextField.getText(),descriptionTextPane.getText(),queryTextPane.getText());
parent.saveQuery(query);
parent.switchToSimple(query.getName());
}//GEN-LAST:event_saveButtonActionPerformed
private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
parent.switchToSimple(null);
}//GEN-LAST:event_cancelButtonActionPerformed
private void executeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_executeButtonActionPerformed
String replaced=QueryProcessor.replaceParams(queryTextPane.getText(),paramMap);
parent.executeQuery(replaced);
}//GEN-LAST:event_executeButtonActionPerformed
private void parseParams(){
String[] params=QueryProcessor.parseParemeterFields(queryTextPane.getText());
paramMap=QueryProcessor.fillQueryFields(params,paramLabelsPanel,paramFieldsPanel);
this.validate();
this.repaint();
}
private void parseParamsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_parseParamsButtonActionPerformed
parseParams();
}//GEN-LAST:event_parseParamsButtonActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton cancelButton;
private javax.swing.JTextPane descriptionTextPane;
private javax.swing.JButton executeButton;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
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.JPanel paramFieldsPanel;
private javax.swing.JPanel paramLabelsPanel;
private javax.swing.JButton parseParamsButton;
private javax.swing.JTextPane queryTextPane;
private javax.swing.JButton saveButton;
private javax.swing.JScrollPane scrollPane;
// End of variables declaration//GEN-END:variables
}
| 12,145 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SQLConsole.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/sqlconsole/SQLConsole.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* SQLConsole.java
*
* Created on 29. joulukuuta 2004, 14:56
*/
package org.wandora.application.tools.sqlconsole;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import javax.swing.JFileChooser;
import org.wandora.application.gui.UIBox;
import org.wandora.utils.Options;
import org.wandora.utils.RegexFileChooser;
/**
*
* @author olli
*/
public class SQLConsole extends javax.swing.JDialog {
private static final long serialVersionUID = 1L;
private Options options;
/** Creates new form SQLConsole */
public SQLConsole(Options options) {
//super(parent, modal);
this.options=options;
initComponents();
menuBar.add(UIBox.makeMenu(new Object[]{
"SQL-Konsoli",new Object[]{
"Tuo",
"Tallenna nimell�",
"---",
"Exit"
}
},
new java.awt.event.ActionListener(){
public void actionPerformed(java.awt.event.ActionEvent e){
String cmd=e.getActionCommand();
if(cmd.equalsIgnoreCase("Tuo")){
importQueries();
}
else if(cmd.equalsIgnoreCase("Tallenna nimell�")){
exportQueries();
}
else if(cmd.equalsIgnoreCase("Exit")){
setVisible(false);
}
}
}));
try{
((SQLConsolePanel)consolePanel).loadStoredQueries();
}catch(Exception e){
SQLConsole.reportException(e);
}
//this.setLocation(kirjava.getX()+kirjava.getWidth()/2-this.getWidth()/2,kirjava.getY()+kirjava.getHeight()/2-this.getHeight()/2);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
private void initComponents() {//GEN-BEGIN:initComponents
consolePanel = new SQLConsolePanel(options);
menuBar = new javax.swing.JMenuBar();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("SQL-Konsoli");
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
getContentPane().add(consolePanel, java.awt.BorderLayout.CENTER);
setJMenuBar(menuBar);
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
setBounds((screenSize.width-680)/2, (screenSize.height-567)/2, 680, 567);
}//GEN-END:initComponents
public void exportQueries(){
QuerySelector querySelector=new QuerySelector(true,((SQLConsolePanel)consolePanel).getStoredQueries(),"Valitse tallennettavat lausekkeet");
querySelector.setVisible(true);
Map<String,StoredQuery> selectedQueries=querySelector.getSelection();
if(selectedQueries!=null){
JFileChooser fc=new JFileChooser();
fc.addChoosableFileFilter(RegexFileChooser.suffixChooser("xml","XML files(*.xml)"));
String path=(String)options.get("options.sqlconsole.export.path");
if(path!=null){
File f=new File(path);
if(f.exists()) fc.setCurrentDirectory(f);
}
if(fc.showSaveDialog(this)==JFileChooser.APPROVE_OPTION){
File dir=fc.getCurrentDirectory();
options.put("options.sqlconsole.export.path",dir.getAbsolutePath());
try{
StoredQuery.saveStoredQueries(selectedQueries, fc.getSelectedFile().getAbsolutePath());
}catch(IOException ioe){
SQLConsole.reportException(ioe);
}
}
}
}
public void importQueries(){
JFileChooser fc=new JFileChooser();
fc.addChoosableFileFilter(RegexFileChooser.suffixChooser("xml","XML files(*.xml)"));
String path=(String)options.get("options.sqlconsole.import.path");
if(path!=null){
File f=new File(path);
if(f.exists()) fc.setCurrentDirectory(f);
}
if(fc.showOpenDialog(this)==JFileChooser.APPROVE_OPTION){
File dir=fc.getCurrentDirectory();
options.put("options.sqlconsole.import.path",dir.getAbsolutePath());
try{
Map<String,StoredQuery> loadedQueries=StoredQuery.loadStoredQueries(fc.getSelectedFile().getAbsolutePath());
QuerySelector querySelector=new QuerySelector(true,loadedQueries,"Valitse tuotavat lausekkeet");
querySelector.setVisible(true);
Map<String,StoredQuery> selectedQueries=querySelector.getSelection();
if(selectedQueries!=null){
((SQLConsolePanel)consolePanel).importQueries(selectedQueries);
((SQLConsolePanel)consolePanel).updateSimpleView();
}
}catch(Exception e){
SQLConsole.reportException(e);
}
}
}
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
try{
((SQLConsolePanel)consolePanel).saveStoredQueries();
}catch(java.io.IOException ioe){
SQLConsole.reportException(ioe);
}
}//GEN-LAST:event_formWindowClosing
public void connect(String driver,String connectString,String user,String password){
((SQLConsolePanel)consolePanel).connect(driver,connectString,user,password);
}
public static void reportException(Exception e){
e.printStackTrace();
//new KirjavaExceptionDialog(parent,true,e).setVisible(true);
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel consolePanel;
private javax.swing.JMenuBar menuBar;
// End of variables declaration//GEN-END:variables
}
| 6,905 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SQLConsoleFrame.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/sqlconsole/SQLConsoleFrame.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* SQLConsole.java
*
* Created on 28. joulukuuta 2004, 15:09
*/
package org.wandora.application.tools.sqlconsole;
import org.wandora.utils.Options;
/**
*
* @author olli
*/
public class SQLConsoleFrame extends javax.swing.JFrame {
private static final long serialVersionUID = 1L;
//private Kirjava kirjava;
public Options options = null;
/** Creates new form SQLConsole */
public SQLConsoleFrame(String[] args) {
//this.kirjava=kirjava;
String optionsFileName = "conf/sqlconsole_options.xml";
options = new Options(optionsFileName);
initComponents();
try{
connect((String)options.get("options.sqlconsole.driver"),
(String)options.get("options.sqlconsole.connectstring"),
(String)options.get("options.sqlconsole.user"),
(String)options.get("options.sqlconsole.password"));
} catch(Exception e) {
e.printStackTrace();
}
try {
((SQLConsolePanel)consolePanel).loadStoredQueries();
} catch(Exception e){
e.printStackTrace();
}
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
private void initComponents() {//GEN-BEGIN:initComponents
consolePanel = new SQLConsolePanel(options);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
exitForm(evt);
}
});
getContentPane().add(consolePanel, java.awt.BorderLayout.CENTER);
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
setBounds((screenSize.width-585)/2, (screenSize.height-486)/2, 585, 486);
}//GEN-END:initComponents
/** Exit the Application */
private void exitForm(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_exitForm
try{
((SQLConsolePanel)consolePanel).saveStoredQueries();
}catch(java.io.IOException ioe){
ioe.printStackTrace();
}
}//GEN-LAST:event_exitForm
public void connect(String driver,String connectString,String user,String password){
((SQLConsolePanel)consolePanel).connect(driver,connectString,user,password);
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
new SQLConsoleFrame(args).show();
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel consolePanel;
// End of variables declaration//GEN-END:variables
}
| 3,592 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
MappedTableView.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/sqlconsole/data/MappedTableView.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* TableView.java
*
* Created on 3. joulukuuta 2004, 14:18
*/
package org.wandora.application.tools.sqlconsole.data;
import java.awt.Point;
/**
*
* @author akivela
*/
public class MappedTableView implements TableView {
protected TableView table;
protected int[] rowMap;
protected int[] columnMap;
/** Creates a new instance of TableView */
public MappedTableView(TableView t) {
table = t;
rowMap = new int[table.getRowCount()];
columnMap = new int[table.getColumnCount()];
}
public void setRowMap(int[] map) {
rowMap = map;
}
public void setColunmMap(int[] map) {
columnMap = map;
}
public void resetView() {
rowMap = new int[table.getRowCount()];
for(int i=0; i<rowMap.length; i++) rowMap[i] = i;
columnMap = new int[table.getColumnCount()];
for(int i=0; i<columnMap.length; i++) columnMap[i] = i;
}
// -------------------------------------------------------------------------
public String[][] getView() {
String[][] view = new String[rowMap.length][columnMap.length];
//Logger.println("filtered rows = " + rowMap.length + ", filtered columns " + columnMap.length);
for(int j=0; j<rowMap.length; j++) {
for(int i=0; i<columnMap.length; i++) {
view[j][i] = getAt(j,i);
}
}
return view;
}
public String[] getColumnNames() {
String[] colunmNames = table.getColumnNames();
String[] view = new String[columnMap.length];
for(int i=0; i<columnMap.length; i++) {
view[i] = colunmNames[columnMap[i]];
}
return colunmNames;
}
public boolean isColumnEditable(int col){
return table.isColumnEditable(convertColunmIndex(col));
}
public void setColumnEditable(int col,boolean editable){
table.setColumnEditable(convertColunmIndex(col),editable);
}
public String getAt(Point p) {
return getAt(p.x, p.y);
}
public Object[] getHiddenData(int r){
return table.getHiddenData(convertRowIndex(r));
}
public String getAt(int r, int c) {
return table.getAt(convertRowIndex(r), convertColunmIndex(c));
}
public void setAt(Point p, String val) {
setAt(p.x, p.y, val);
}
public void setAt(int r, int c, String val) {
table.setAt(convertRowIndex(r), convertColunmIndex(c), val);
}
public String[] getRow(int r) {
return table.getRow(convertRowIndex(r));
}
public String[][] getRows(int[] rs) {
int[] crs = new int[rs.length];
for(int i=0; i<rs.length; i++) {
crs[i] = convertRowIndex(rs[i]);
}
return table.getRows(crs);
}
public String[] getColumn(int c) {
return table.getColumn(convertColunmIndex(c));
}
public String[][] getColumns(int[] cs) {
int[] ccs = new int[cs.length];
for(int i=0; i<cs.length; i++) {
ccs[i] = convertColunmIndex(cs[i]);
}
return table.getColumns(ccs);
}
public int getColumnCount() {
return columnMap.length;
}
public int getRowCount() {
return rowMap.length;
}
// -------------------------------------------------------------------------
private int convertRowIndex(int i) {
return rowMap[i];
}
private int[] convertRowIndexes(int[] indexes) {
int[] mappedIndexes = new int[indexes.length];
for(int i=0; i<indexes.length; i++) {
mappedIndexes[i] = convertRowIndex(indexes[i]);
}
return mappedIndexes;
}
private int convertColunmIndex(int i) {
return columnMap[i];
}
public void deleteRows(int[] rowsToDelete) {
int[] mappedRows = convertRowIndexes(rowsToDelete);
table.deleteRows(mappedRows);
resetView();
}
public void hideRows(int [] rowsToHide) {
int[] newRowMap = new int[rowMap.length - rowsToHide.length];
int p=0;
for(int i=0; i<rowMap.length; i++) {
if(p < rowsToHide.length && i == rowsToHide[p]) {
p++;
}
else {
newRowMap[i-p] = rowMap[i];
}
}
rowMap = newRowMap;
}
public void insertRows(int pos, int number) {
table.insertRows(convertRowIndex(pos), number);
resetView();
}
// -------------------------------------------------------------------------
}
| 5,628 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TableView.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/sqlconsole/data/TableView.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* TableView.java
*
* Created on 3. joulukuuta 2004, 15:59
*/
package org.wandora.application.tools.sqlconsole.data;
import java.awt.Point;
/**
*
* @author akivela
*/
public interface TableView {
void resetView();
String[] getColumnNames();
String[] getRow(int r);
String[][] getRows(int[] r);
String[] getColumn(int c);
String[][] getColumns(int[] c);
String[][] getView();
public Object[] getHiddenData(int r);
public String getAt(Point p);
public String getAt(int r, int c);
public void setAt(Point p, String val);
public void setAt(int r, int c, String val);
public int getRowCount();
public int getColumnCount();
public void insertRows(int pos, int number);
public void deleteRows(int[] rowsToDelete);
public boolean isColumnEditable(int col);
public void setColumnEditable(int col,boolean editable);
//public TableViewUpdater getUpdater();
//public void setUpdater(TableViewUpdater updater);
}
| 1,849 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
Row.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/sqlconsole/data/Row.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* Viite.java
*
* Created on November 1, 2004, 4:49 PM
*/
package org.wandora.application.tools.sqlconsole.data;
/**
*
* @author akivela
*/
public class Row {
public String[] data;
public Object[] hiddenData;
/** Creates a new instance of Viite */
public Row(int columns) {
data = new String[columns];
}
public Row(Object[] data){
this(data,data.length);
}
public Row(Object[] data,int visibleColumns){
this.data=new String[visibleColumns];
for(int i=0;i<visibleColumns;i++){
if(data[i]==null) this.data[i]="";//"<NULL>";
else this.data[i]=data[i].toString();
}
if(visibleColumns!=data.length){
hiddenData=new Object[data.length-visibleColumns];
for(int i=visibleColumns;i<data.length;i++){
hiddenData[i-visibleColumns]=data[i];
}
}
}
public String getColumn(int c) {
try { return data[c]; }
catch (Exception e) { return null; }
}
public void setColumn(int c, String v) {
try { data[c] = v; }
catch (Exception e) {}
}
// -------------------------------------------------------------------------
public String[] getColumns() {
return data;
}
public Object[] getHiddenData(){
return hiddenData;
}
}
| 2,224 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
RowTable.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/sqlconsole/data/RowTable.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* AbstractTable.java
*
* Created on 30. marraskuuta 2004, 17:40
*/
package org.wandora.application.tools.sqlconsole.data;
import java.awt.Point;
import java.util.StringTokenizer;
import java.util.Vector;
import org.wandora.utils.Tuples.T2;
/**
*
* @author akivela
*/
public class RowTable implements TableView {
private Row[] rows;
private String[] columns;
private boolean[] columnsEditable;
private TableViewUpdater updater;
/** Creates a new instance of AbstractTable */
public RowTable(String[] c) {
columns = c;
columnsEditable=new boolean[columns.length];
for(int i=0;i<columnsEditable.length;i++) columnsEditable[i]=false;
rows = null;
}
public RowTable(String[] columns,java.util.List<Object[]> rows){
this.columns=columns;
this.rows=new Row[rows.size()];
int ptr=0;
columnsEditable=new boolean[columns.length];
for(int i=0;i<columnsEditable.length;i++) columnsEditable[i]=false;
for(Object[] r : rows){
Row row=new Row(r,columns.length);
this.rows[ptr++]=row;
}
}
/** @param columns Column name and editable flag. */
public RowTable(T2<String,Boolean>[] columns,java.util.List<Object[]> rows){
this.columns=new String[columns.length];
columnsEditable=new boolean[columns.length];
for(int i=0;i<columns.length;i++){
this.columns[i]=columns[i].e1;
this.columnsEditable[i]=columns[i].e2;
}
this.rows=new Row[rows.size()];
int ptr=0;
for(Object[] r : rows){
Row row=new Row(r,columns.length);
this.rows[ptr++]=row;
}
}
public TableViewUpdater getUpdater(){
return updater;
}
public void setUpdater(TableViewUpdater updater){
this.updater=updater;
}
public void resetView() {
// DO NOTHING!
}
public String getAt(Point p) {
return getAt(p.x, p.y);
}
public String getAt(int r, int c) {
Row row = rows[r];
return row.getColumn(c);
}
public Object[] getHiddenData(int r){
return rows[r].getHiddenData();
}
public void setAt(Point p, String val) {
setAt(p.x, p.y, val);
}
public void setAt(int r, int c, String val) {
Row row = rows[r];
row.setColumn(c, val);
}
// -------------------------------------------------------------------------
public int getRowCount() {
return rows.length;
}
public int getColumnCount() {
return columns.length;
}
// -------------------------------------------------------------------------
public void insertRows(int pos, int number) {
Row[] newRows = new Row[rows.length + number];
int endpos = pos + number;
for(int i=0; i<newRows.length; i++) {
if(i<pos) newRows[i] = rows[i];
else if(i>=pos && i<endpos) newRows[i] = new Row(columns.length);
else newRows[i] = rows[i-number];
}
rows = newRows;
}
public void deleteRows(int[] rowsToDelete) {
int p = 0;
Row[] newRows = new Row[rows.length - rowsToDelete.length];
for(int i=0; i<rows.length; i++) {
if(p < rowsToDelete.length && i == rowsToDelete[p]) {
p++;
}
else {
//Logger.println(" index " + (i-p) + " == " + i);
newRows[i-p] = rows[i];
}
}
rows = newRows;
}
// -------------------------------------------------------------------------
public String[][] getView() {
String[][] table = new String[rows.length][columns.length];
String[] row;
for(int i=0; i<rows.length; i++) {
row = rows[i].getColumns();
for(int j=0; j<row.length; j++) {
table[i][j] = row[j];
}
}
return table;
}
public String[][] getRows(int[] rs) {
String[][] subtable = new String[rs.length][columns.length];
String[] row;
for(int i=0; i<rs.length; i++) {
row = rows[rs[i]].getColumns();
for(int j=0; j<row.length; j++) {
subtable[i][j] = row[j];
}
}
return subtable;
}
public String[] getRow(int r) {
Row row = rows[r];
return row.getColumns();
}
public String[] getColumn(int c) {
int size = rows.length;
String[] column = new String[rows.length];
for(int i=0; i<rows.length; i++) {
column[i] = rows[i].getColumn(c);
}
return column;
}
public String[][] getColumns(int[] cs) {
String[][] subtable = new String[rows.length][cs.length];
String[] row;
for(int i=0; i<rows.length; i++) {
row = rows[i].getColumns();
for(int j=0; j<cs.length; j++) {
subtable[i][cs[j]] = row[j];
}
}
return subtable;
}
public String[] getColumnNames() {
return columns;
}
public Row findRowWithColumn(int c, String colunmContent) {
Row row;
for(int i=0; i<rows.length; i++) {
row = rows[i];
if(colunmContent.equals(row.getColumn(c))) return row;
}
return null;
}
public boolean isColumnEditable(int col){
return columnsEditable[col];
}
public void setColumnEditable(int col,boolean editable){
columnsEditable[col]=editable;
}
// -------------------------------------------------------------------------
public void importFromFile(String resourceName, String importOrder) {
try {
Vector<Row> rowVector = new Vector<>();
if(importOrder == null || importOrder.length() < 1) importOrder="0123456789";
if(resourceName != null) {
String s = ""; // IObox.loadResource(resourceName);
StringTokenizer lines = new StringTokenizer(s, "\n");
while(lines.hasMoreTokens()) {
String line = lines.nextToken();
StringTokenizer parts = new StringTokenizer(line, "\t");
int currentPart = 0;
Row row = new Row(columns.length);
while(parts.hasMoreTokens()) {
String part = parts.nextToken();
if(part != null && part.length() > 0) {
int p = currentPart;
try { p = Integer.parseInt(importOrder.substring(currentPart, currentPart+1)); }
catch(Exception e) { e.printStackTrace(); }
//Logger.println("column " + p + " part " + part);
row.setColumn(p, part);
}
currentPart++;
}
if(currentPart > 0) {
rowVector.add(row);
}
else {
//Logger.println("Rejecting line!");
}
}
rows = (Row[]) rowVector.toArray(new Row[rowVector.size()]);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
| 8,547 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TableViewUpdater.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/sqlconsole/data/TableViewUpdater.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* TableViewUpdater.java
*
* Created on 11. tammikuuta 2005, 11:34
*/
package org.wandora.application.tools.sqlconsole.data;
/**
*
* @author olli
*/
public interface TableViewUpdater {
//public void update(KirjavaTablePage table) throws Exception;
}
| 1,079 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
PatternFilteredTableView.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/sqlconsole/data/PatternFilteredTableView.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* FilteredTableView.java
*
* Created on 3. joulukuuta 2004, 17:18
*/
package org.wandora.application.tools.sqlconsole.data;
import org.wandora.application.tools.sqlconsole.data.utils.SQLPattern;
/**
*
* @author akivela
*/
public class PatternFilteredTableView extends MappedTableView implements TableView {
public static final int OR_MODE = 0;
public static final int AND_MODE = 1;
public static SQLPattern DEFAULT_PATTERN = null;
int mode;
SQLPattern[] patterns;
/** Creates a new instance of FilteredTableView */
public PatternFilteredTableView(TableView t) {
super(t);
mode = OR_MODE;
resetView();
}
// -------------------------------------------------------------------------
public String[] getColumnNames() {
String[] columnNames = super.getColumnNames();
String[] newColumnNames = new String[columnNames.length];
for(int i=0; i<columnNames.length ; i++) {
newColumnNames[i] = columnNames[i];
if(columnHasPattern(i)) {
SQLPattern pattern = getPattern(i);
String patternString = pattern.getPatternString();
newColumnNames[i] = "" + newColumnNames[i] + " [" + patternString + "]";
//Logger.println("newColumnNames[i] == " + newColumnNames[i]);
}
}
return newColumnNames;
}
// -------------------------------------------------------------------------
public void setPattern(int column, String f) {
setPattern(column, null, f, true, true);
}
public void setPattern(int column, String name, String f, boolean findInstead, boolean caseInsensitivity) {
if(f != null) {
try {
patterns[column] = new SQLPattern(name, f, findInstead, caseInsensitivity);
}
catch (Exception e) {
//Logger.println(e);
}
}
else patterns[column] = DEFAULT_PATTERN;
updateRowIndex();
}
public void setPattern(int column, SQLPattern p) {
if(p != null) {
patterns[column] = p;
}
else patterns[column] = DEFAULT_PATTERN;
updateRowIndex();
}
public SQLPattern getPattern(int column) {
try { return patterns[column]; }
catch (Exception e) {}
return null;
}
// -------------------------------------------------------------------------
public boolean columnHasPattern(int column) {
if(patterns[column] == null || patterns[column] == DEFAULT_PATTERN) return false;
else return true;
}
// -------------------------------------------------------------------------
public void setMode(boolean andMode) {
if(andMode) mode = AND_MODE;
else mode = OR_MODE;
}
public void setMode(int newMode) {
mode = newMode;
}
public int getMode() {
return mode;
}
// -------------------------------------------------------------------------
public void resetView() {
super.resetView();
patterns = new SQLPattern[table.getColumnCount()];
for(int i=0; i<patterns.length; i++) {
patterns[i] = DEFAULT_PATTERN;
}
}
public void updateRowIndex() {
super.resetView();
String[][] data = super.getView();
int[] rowMap = new int[data.length];
int count=0;
for(int r=0; r<data.length; r++) {
String[] row = data[r];
if(rowMatches(row, patterns)) {
rowMap[count++] = r;
//Logger.println("accepting row " + r );
}
}
int[] tightRowMap = new int[count];
for(int r=0; r<count; r++) {
tightRowMap[r] = rowMap[r];
}
setRowMap(tightRowMap);
}
public boolean rowMatches(String[] row, SQLPattern[] ps) {
switch(mode) {
case OR_MODE: { // OR
//Logger.println("or mode");
boolean noPatterns = true;
for(int j=0; j<ps.length; j++) {
if(ps[j] != null) {
noPatterns = false;
if(ps[j].matches(row[j])) return true;
}
}
return false || noPatterns;
}
case AND_MODE: { // AND
//Logger.println("and mode");
boolean noPatterns = true;
for(int j=0; j<ps.length; j++) {
if(ps[j] != null) {
noPatterns = false;
if(!ps[j].matches(row[j])) return false;
}
}
return true || noPatterns;
}
}
return false;
}
// -------------------------------------------------------------------------
public void deleteRows(int[] rowsToDelete) {
super.deleteRows(rowsToDelete);
resetView();
}
public void insertRows(int pos, int number) {
super.insertRows(pos, number);
resetView();
}
}
| 6,132 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SQLPattern.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/sqlconsole/data/utils/SQLPattern.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* SQLPattern.java
*
* Created on 5. joulukuuta 2004, 14:14
*/
package org.wandora.application.tools.sqlconsole.data.utils;
import java.util.regex.Pattern;
/**
*
* @author akivela, olli
*/
public class SQLPattern {
boolean isCaseInsensitive;
boolean findInsteadMatch;
Pattern pattern;
String name;
/** Creates a new instance of KirjavaPattern
*
* @param n
* @param ps
* @param findInstead
* @param caseInsensitive
*/
public SQLPattern(String n, String ps, boolean findInstead, boolean caseInsensitive) {
try {
name = n;
isCaseInsensitive = caseInsensitive;
if(isCaseInsensitive) pattern = Pattern.compile(ps, Pattern.CASE_INSENSITIVE);
else pattern = Pattern.compile(ps);
findInsteadMatch = findInstead;
}
catch (Exception e) {
//Logger.println(e);
}
}
public SQLPattern(String n, Pattern p, boolean findInstead, boolean caseInsensitive) {
try {
name = n;
isCaseInsensitive = caseInsensitive;
if(isCaseInsensitive) pattern = Pattern.compile(p.toString(), Pattern.CASE_INSENSITIVE);
else pattern = Pattern.compile(p.toString());
findInsteadMatch = findInstead;
}
catch (Exception e) {
//Logger.println(e);
}
}
public boolean matches(String s) {
if(pattern != null && s != null) {
if(findInsteadMatch) return pattern.matcher(s).find();
else return pattern.matcher(s).matches();
}
return false;
}
public Pattern getPattern() {
return pattern;
}
public String getPatternString() {
if(pattern != null) return pattern.toString();
return "";
}
public boolean findInsteadMatch() {
return findInsteadMatch;
}
public boolean isCaseInsensitive() {
return isCaseInsensitive;
}
public String getName() {
return name;
}
}
| 2,927 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
PatternEditor.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/sqlconsole/gui/PatternEditor.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* PatternEditor.java
*
* Created on 2. joulukuuta 2004, 11:49
*/
package org.wandora.application.tools.sqlconsole.gui;
import java.awt.Color;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import org.wandora.application.gui.UIConstants;
import org.wandora.application.gui.simple.SimpleFileChooser;
import org.wandora.application.tools.sqlconsole.data.utils.SQLPattern;
/**
*
* @author akivela
*/
public class PatternEditor extends javax.swing.JDialog implements ActionListener {
private static final long serialVersionUID = 1L;
public static final String DEFAULT_PATTERN_NAME = "käyttäjän lauseke";
public static Color TEST_ERROR = new Color(255,220,220);
public static Color TEST_MATCH = new Color(220,255,220);
public static Color TEST_MISMATCH = new Color(240,220,220);
File currentDirectory;
Hashtable<String,SQLPattern> patterns;
public boolean approve;
Object owner;
SQLPattern originalPattern;
int currentColumn;
public PatternEditor() {
patterns = new Hashtable<>();
//importPatterns(kirjava.getOptions().get("options.patterns.file"));
//setIconImage(kirjava.getIconImage());
owner = null;
originalPattern = null;
currentColumn = 0;
initGui();
refresh();
}
public void initGui() {
initComponents();
nameComboBox.setEditable(false);
//((KirjavaComboBox) nameComboBox).setOptions(patterns.keys());
}
public void refresh() {
/*
if(kirjava != null) {
int x = kirjava.getX()+kirjava.getWidth()/2-getWidth()/2;
x = x > 0 ? x : 0;
int y = kirjava.getY()+kirjava.getHeight()/2-getHeight()/2;
y = y > 0 ? y : 0;
setLocation(x,y);
}
*/
}
public Container getParent() {
return null;
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
private void initComponents() {//GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
javax.swing.JButton testButton;
jPanel1 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
matchCheckBox = new javax.swing.JCheckBox();
caseSensitivityCheckBox = new javax.swing.JCheckBox();
andCheckBox = new javax.swing.JCheckBox();
jPanel4 = new javax.swing.JPanel();
nameLabel = new javax.swing.JLabel();
nameComboBox = new javax.swing.JComboBox();
patternLabel = new javax.swing.JLabel();
patternScrollPane = new javax.swing.JScrollPane();
patternPane = new javax.swing.JTextPane();
buttonPanel = new javax.swing.JPanel();
readyButton = new javax.swing.JButton();
applyButton = new javax.swing.JButton();
cancelButton = new javax.swing.JButton();
testPanel = new javax.swing.JPanel();
testStringLabel = new javax.swing.JLabel();
testStringScrollPane = new javax.swing.JScrollPane();
testStringPane = new javax.swing.JTextPane();
testButtonPanel = new javax.swing.JPanel();
testButton = new javax.swing.JButton();
testResultLabel = new javax.swing.JLabel();
testResultScrollPane = new javax.swing.JScrollPane();
testResultPane = new javax.swing.JTextPane();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
sailytaMenuItem = new javax.swing.JMenuItem();
jSeparator1 = new javax.swing.JSeparator();
loadMenuItem = new javax.swing.JMenuItem();
saveMenuItem = new javax.swing.JMenuItem();
jSeparator2 = new javax.swing.JSeparator();
peruutaMenuItem = new javax.swing.JMenuItem();
getContentPane().setLayout(new java.awt.GridBagLayout());
setTitle("Suodatin Editori");
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
exitForm(evt);
}
});
jPanel1.setLayout(new java.awt.GridBagLayout());
jPanel2.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT, 0, 5));
jPanel2.setPreferredSize(new java.awt.Dimension(400, 30));
matchCheckBox.setText("Vahva suodatus");
matchCheckBox.setToolTipText("Sarakkeen arvon pit\u00e4\u00e4 sopia t\u00e4sm\u00e4lleen suodattimeen (Match / Find)");
matchCheckBox.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
jPanel2.add(matchCheckBox);
caseSensitivityCheckBox.setText("Erota isot ja pienet");
caseSensitivityCheckBox.setToolTipText("Erota isot ja pienet kirjaimet (Case Sensitive / Case Insensitive)");
caseSensitivityCheckBox.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
jPanel2.add(caseSensitivityCheckBox);
andCheckBox.setText("Suodattimien leikkaus");
andCheckBox.setToolTipText("Eri sarakkeissa olevien suodattimien leikkaus (AND / OR)");
andCheckBox.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
jPanel2.add(andCheckBox);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridy = 0;
jPanel1.add(jPanel2, gridBagConstraints);
jPanel4.setLayout(new java.awt.GridBagLayout());
nameLabel.setText("Lausekkeen nimi");
nameLabel.setPreferredSize(new java.awt.Dimension(400, 14));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridy = 0;
jPanel4.add(nameLabel, gridBagConstraints);
nameComboBox.setPreferredSize(new java.awt.Dimension(400, 20));
nameComboBox.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
nameComboBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
comboBoxActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridy = 1;
jPanel4.add(nameComboBox, gridBagConstraints);
patternLabel.setText("S\u00e4\u00e4nn\u00f6llinen lauseke");
patternLabel.setPreferredSize(new java.awt.Dimension(400, 14));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(10, 0, 0, 0);
jPanel4.add(patternLabel, gridBagConstraints);
patternScrollPane.setPreferredSize(new java.awt.Dimension(400, 100));
patternScrollPane.setViewportView(patternPane);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridy = 3;
jPanel4.add(patternScrollPane, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridy = 1;
jPanel1.add(jPanel4, gridBagConstraints);
buttonPanel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT));
buttonPanel.setPreferredSize(new java.awt.Dimension(400, 33));
readyButton.setText("Valitse");
readyButton.addActionListener(this);
buttonPanel.add(readyButton);
applyButton.setText("Sovella");
applyButton.addActionListener(this);
buttonPanel.add(applyButton);
cancelButton.setText("Peruuta");
cancelButton.addActionListener(this);
buttonPanel.add(cancelButton);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridy = 2;
jPanel1.add(buttonPanel, gridBagConstraints);
testPanel.setLayout(new java.awt.GridBagLayout());
testPanel.setBorder(new javax.swing.border.EtchedBorder());
testPanel.setPreferredSize(new java.awt.Dimension(384, 210));
testStringLabel.setText("Testattava merkkijono");
testStringLabel.setPreferredSize(new java.awt.Dimension(380, 14));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(10, 0, 0, 0);
testPanel.add(testStringLabel, gridBagConstraints);
testStringScrollPane.setPreferredSize(new java.awt.Dimension(380, 50));
testStringScrollPane.setViewportView(testStringPane);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridy = 2;
testPanel.add(testStringScrollPane, gridBagConstraints);
testButtonPanel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT));
testButtonPanel.setPreferredSize(new java.awt.Dimension(380, 33));
testButton.setText("Testaa");
testButton.setMargin(new java.awt.Insets(2, 15, 2, 15));
testButton.addActionListener(this);
testButtonPanel.add(testButton);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridy = 3;
testPanel.add(testButtonPanel, gridBagConstraints);
testResultLabel.setText("Testauksen tulos");
testResultLabel.setPreferredSize(new java.awt.Dimension(380, 14));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridy = 4;
gridBagConstraints.insets = new java.awt.Insets(5, 0, 0, 0);
testPanel.add(testResultLabel, gridBagConstraints);
testResultScrollPane.setPreferredSize(new java.awt.Dimension(380, 70));
testResultScrollPane.setViewportView(testResultPane);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridy = 5;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 10, 0);
testPanel.add(testResultScrollPane, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridy = 3;
gridBagConstraints.ipadx = 10;
gridBagConstraints.insets = new java.awt.Insets(15, 0, 0, 0);
jPanel1.add(testPanel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.ipadx = 15;
gridBagConstraints.ipady = 15;
getContentPane().add(jPanel1, gridBagConstraints);
jMenu1.setText("Tiedostot");
sailytaMenuItem.setText("S\u00e4ilyt\u00e4 lauseke...");
sailytaMenuItem.addActionListener(this);
jMenu1.add(sailytaMenuItem);
jMenu1.add(jSeparator1);
loadMenuItem.setText("Lataa lausekkeet...");
loadMenuItem.addActionListener(this);
jMenu1.add(loadMenuItem);
saveMenuItem.setText("Talleta lausekkeet...");
saveMenuItem.addActionListener(this);
jMenu1.add(saveMenuItem);
jMenu1.add(jSeparator2);
peruutaMenuItem.setText("Sulje");
peruutaMenuItem.addActionListener(this);
jMenu1.add(peruutaMenuItem);
jMenuBar1.add(jMenu1);
setJMenuBar(jMenuBar1);
pack();
}//GEN-END:initComponents
private void comboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboBoxActionPerformed
selectPattern();
}//GEN-LAST:event_comboBoxActionPerformed
/** Exit the Application */
private void exitForm(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_exitForm
tryExit();
}//GEN-LAST:event_exitForm
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
new PatternEditor().setVisible(true);
}
public void actionPerformed(java.awt.event.ActionEvent actionEvent) {
String c = actionEvent.getActionCommand();
//Logger.println("PatternEditor action command: " +c);
if("Peruuta".equalsIgnoreCase(c) || "Sulje".equalsIgnoreCase(c)) {
approve = false;
if(owner instanceof SQLTablePanel) {
SQLTablePanel o = (SQLTablePanel) owner;
o.applyPattern(currentColumn, getCurrentPattern(), andCheckBox.isSelected());
}
tryExit();
}
else if("Valitse".equalsIgnoreCase(c)) {
approve = true;
if(owner instanceof SQLTablePanel) {
SQLTablePanel o = (SQLTablePanel) owner;
o.applyPattern(currentColumn, getCurrentPattern(), andCheckBox.isSelected());
}
tryExit();
}
else if("Sovella".equalsIgnoreCase(c)) {
approve = true;
if(owner instanceof SQLTablePanel) {
SQLTablePanel o = (SQLTablePanel) owner;
//Logger.println("andCheckBox.isSelected() == " + andCheckBox.isSelected());
o.applyPattern(currentColumn, getCurrentPattern(), andCheckBox.isSelected());
}
}
else if("S�ilyt� lauseke...".equalsIgnoreCase(c)) {
savePattern();
}
else if("Testaa".equalsIgnoreCase(c)) {
testPattern();
}
else if("Lataa lausekkeet...".equalsIgnoreCase(c)) {
importPatterns();
}
else if("Talleta lausekkeet...".equalsIgnoreCase(c)) {
exportPatterns();
}
}
public void tryExit() {
this.setVisible(false);
}
public void show(Object o, int column, SQLPattern pattern, boolean isAnd) {
owner = o;
originalPattern = pattern;
currentColumn = column;
approve = false;
if(pattern != null) {
String name = pattern.getName();
if(name == null) name = DEFAULT_PATTERN_NAME;
if(patterns.size() == 0 || !patterns.containsKey(name)) {
patterns.put(name, pattern);
//((KirjavaComboBox) nameComboBox).setOptions(patterns.keys());
}
nameComboBox.setSelectedItem(name);
caseSensitivityCheckBox.setSelected(!pattern.isCaseInsensitive());
matchCheckBox.setSelected(!pattern.findInsteadMatch());
patternPane.setText(pattern.getPatternString());
}
andCheckBox.setSelected(isAnd);
super.setVisible(true);
}
public boolean findInsteadMatch() {
if(matchCheckBox.isSelected()) return false;
else return true;
}
// --- HANDLE PATTERNS -----------------------------------------------------
public SQLPattern getCurrentPattern() {
if(approve == true) {
try {
Pattern p = Pattern.compile(patternPane.getText()); // TRYING
String name = (String) nameComboBox.getSelectedItem();
if(name == null) name = DEFAULT_PATTERN_NAME;
return new SQLPattern((String) nameComboBox.getSelectedItem(), patternPane.getText(), !matchCheckBox.isSelected(), !caseSensitivityCheckBox.isSelected()); }
catch (Exception e) {
testResultPane.setBackground(TEST_ERROR);
testResultPane.setText("Virhe s��nn�llisess� lausekkeessa!\n\n" + e.toString());
return null; }
}
else {
return originalPattern;
}
}
public void selectPattern() {
try {
if(nameComboBox.getSelectedItem() != null) {
SQLPattern currentPattern = (SQLPattern) patterns.get(nameComboBox.getSelectedItem());
if(currentPattern != null) {
patternPane.setText(currentPattern.getPatternString());
matchCheckBox.setSelected(!currentPattern.findInsteadMatch());
caseSensitivityCheckBox.setSelected(!currentPattern.isCaseInsensitive());
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
public void savePattern() {
String patternNameString=JOptionPane.showInputDialog(this, "Anna säännöllisen lausekkeen nimi", nameComboBox.getSelectedItem());
String patternString = patternPane.getText();
if(patternNameString != null && patternNameString.length() > 0) {
if(patternString != null && patternString.length() > 0) {
try {
Pattern p = Pattern.compile(patternPane.getText()); // TESTING!
SQLPattern kp = new SQLPattern(patternNameString, patternPane.getText(), !matchCheckBox.isSelected(), !caseSensitivityCheckBox.isSelected());
patterns.put(patternNameString, kp);
//((KirjavaComboBox) nameComboBox).setOptions(patterns.keys());
nameComboBox.setSelectedItem(patternNameString);
}
catch (Exception e) {
testResultPane.setBackground(TEST_ERROR);
testResultPane.setText("Säilytys epäonnistui! Virhe säännöllisessä lausekkeessa!\n\n" + e.toString());
}
}
else {
if(patterns.get(patternString) != null) patterns.remove(patternString);
}
}
}
public void testPattern() {
String patternString = patternPane.getText();
String testString = testStringPane.getText();
if(patternString != null && patternString.length() > 0) {
if(testString != null && testString.length() > 0) {
try {
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(testString);
boolean match = false;
if(findInsteadMatch() == true) {
match = matcher.find();
}
else {
match = matcher.matches();
}
if(match) {
testResultPane.setBackground(TEST_MATCH);
testResultPane.setText("Ok! Testattava merkkijono on säännöllisen lausekkeen mukainen!");
}
else {
testResultPane.setBackground(TEST_MISMATCH);
testResultPane.setText("Testattava merkkijono ei ole säännöllisen lausekkeen mukainen!");
}
}
catch (PatternSyntaxException pse) {
testResultPane.setBackground(TEST_ERROR);
StringWriter sw = new StringWriter();
pse.printStackTrace(new PrintWriter(sw));
testResultPane.setBackground(TEST_ERROR);
testResultPane.setText("Virhe säännöllisessä lausekkeessa!\n\n" + sw.toString());
}
catch (Exception e) {
testResultPane.setBackground(TEST_ERROR);
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
testResultPane.setText(sw.toString());
}
}
else {
testResultPane.setBackground(TEST_ERROR);
testResultPane.setText("Testattava merkkijono on tyhjä!");
}
}
else {
testResultPane.setBackground(TEST_ERROR);
testResultPane.setText("Säännöllinen lauseke on tyhjä!");
}
}
// --- IMPORT PATTERNS -----------------------------------------------------
public void importPatterns() {
SimpleFileChooser chooser=UIConstants.getFileChooser();
chooser.setDialogTitle("Open regular expressions");
chooser.setApproveButtonText("Open");
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
if(currentDirectory != null) {
chooser.setCurrentDirectory(currentDirectory);
}
if(chooser.open(this) == SimpleFileChooser.APPROVE_OPTION) {
importPatterns(chooser.getSelectedFile());
}
}
public void importPatterns(File file) {
patterns = new Hashtable<>();
mergePatterns(file);
}
public void mergePatterns(File file) {
if(file != null) {
patterns = new Hashtable<>();
try {
String s = ""; // IObox.loadFile(file);
parsePatterns(s);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
public void importPatterns(String resourceName) {
patterns = new Hashtable<>();
mergePatterns(resourceName);
}
public void mergePatterns(String resourceName) {
if(resourceName != null) {
try {
String s = ""; // IObox.loadResource(resourceName);
parsePatterns(s);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
public void parsePatterns(String s) {
if(s != null) {
try {
StringTokenizer lines = new StringTokenizer(s, "\n");
while(lines.hasMoreTokens()) {
String line = lines.nextToken();
StringTokenizer parts = new StringTokenizer(line, "\t");
if(parts.countTokens()>3) {
String name = parts.nextToken();
String pattern = parts.nextToken();
String findInstead = parts.nextToken();
String caseSensitivity = parts.nextToken();
if(name != null && name.length() > 0 && pattern != null && pattern.length() > 0) {
patterns.put(name, new SQLPattern(name, pattern, "true".equalsIgnoreCase(findInstead), "true".equalsIgnoreCase(caseSensitivity)));
}
}
else {
//Logger.println("Rejecting pattern!");
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
// --- EXPORT PATTERNS -----------------------------------------------------
public void exportPatterns() {
JFileChooser chooser=new javax.swing.JFileChooser();
chooser.setDialogTitle("Talletetaan s��nn�lliset lausekkeet");
chooser.setApproveButtonText("Talleta");
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
if(currentDirectory != null) {
chooser.setCurrentDirectory(currentDirectory);
}
if(chooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
currentDirectory = chooser.getCurrentDirectory();
exportPatterns(chooser.getSelectedFile());
}
}
public void exportPatterns(File file) {
try {
//IObox.saveFile(file, patterns2String());
}
catch (Exception e) {
//Logger.println(e);
}
}
public String patterns2String() {
StringBuffer sb = new StringBuffer("");
String key;
for(Enumeration<String> keys=patterns.keys(); keys.hasMoreElements();) {
try {
key = (String) keys.nextElement();
SQLPattern kp = (SQLPattern) patterns.get(key);
sb.append(key + "\t" + kp.getPatternString() + "\t" + kp.findInsteadMatch() + "\t" + kp.isCaseInsensitive());
sb.append("\n");
}
catch (Exception ex) {
//Logger.println(ex);
}
}
return sb.toString();
}
// -------------------------------------------------------------------------
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JCheckBox andCheckBox;
private javax.swing.JButton applyButton;
private javax.swing.JPanel buttonPanel;
private javax.swing.JButton cancelButton;
private javax.swing.JCheckBox caseSensitivityCheckBox;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel4;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JSeparator jSeparator2;
private javax.swing.JMenuItem loadMenuItem;
private javax.swing.JCheckBox matchCheckBox;
private javax.swing.JComboBox nameComboBox;
private javax.swing.JLabel nameLabel;
private javax.swing.JLabel patternLabel;
private javax.swing.JTextPane patternPane;
private javax.swing.JScrollPane patternScrollPane;
private javax.swing.JMenuItem peruutaMenuItem;
private javax.swing.JButton readyButton;
private javax.swing.JMenuItem sailytaMenuItem;
private javax.swing.JMenuItem saveMenuItem;
private javax.swing.JPanel testButtonPanel;
private javax.swing.JPanel testPanel;
private javax.swing.JLabel testResultLabel;
private javax.swing.JTextPane testResultPane;
private javax.swing.JScrollPane testResultScrollPane;
private javax.swing.JLabel testStringLabel;
private javax.swing.JTextPane testStringPane;
private javax.swing.JScrollPane testStringScrollPane;
// End of variables declaration//GEN-END:variables
}
| 26,877 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SQLTable.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/sqlconsole/gui/SQLTable.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* SQLTable.java
*
* Created on 1. joulukuuta 2004, 19:25
*/
package org.wandora.application.tools.sqlconsole.gui;
import java.awt.Color;
import java.awt.Component;
import java.awt.Point;
import java.util.Collection;
import java.util.HashSet;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import org.wandora.utils.Textbox;
import org.wandora.utils.swing.TableSorter;
/**
*
* @author akivela
*/
public class SQLTable extends JTable implements TableCellRenderer {
private static final long serialVersionUID = 1L;
boolean[] columnEditable;
String[][] data;
String[] columnNames;
Color[] columnBackground;
Color[] columnForeground;
boolean tableChanged;
TableCellRenderer cellRenderer;
TableSorter sorter;
private KirjavaTableModel kirjavaModel;
public SQLTable(String[][] data, String[] columnNames) {
super(data, columnNames);
this.data = data;
this.columnNames = columnNames;
this.tableChanged = false;
this.columnBackground = new Color[columnNames.length];
this.columnForeground = new Color[columnNames.length];
columnEditable=new boolean[columnNames.length];
for(int i=0;i<columnEditable.length;i++) columnEditable[i]=true;
/*
for(int i=0; i<columnNames.length;i++) {
TableColumn column = getColumnModel().getColumn(i);
//column.setCellEditor(new DefaultCellEditor());
column.setCellRenderer(new DefaultTableCellRenderer());
}
**/
kirjavaModel=new KirjavaTableModel();
this.sorter = new TableSorter(kirjavaModel);
setModel(sorter);
// setPreferredSize(new java.awt.Dimension(640, getRowCount()*getRowHeight()));
// setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
setRowSelectionAllowed(true);
setColumnSelectionAllowed(true);
setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
JTableHeader header = getTableHeader();
sorter.setTableHeader(header);
}
// -------------------------------------------------------------------------
public void setColumnEditable(int c,boolean editable){
columnEditable[c]=editable;
}
public TableCellRenderer getCellRenderer(int row, int column) {
return this;
}
public int convertRowIndexToModel(int row){
return sorter.modelIndex(row);
}
public int convertRowIndexToView(int row){
return 0;
//return sorter.viewIndex(row);
}
public Component getTableCellRendererComponent(javax.swing.JTable table, Object color, boolean isSelected, boolean hasFocus,int row, int column) {
TableCellRenderer defaultRenderer = super.getCellRenderer(row, column);
Component c = defaultRenderer.getTableCellRendererComponent(table, color, isSelected, hasFocus, row, column);
if(!isSelected && !hasFocus) {
c.setBackground(Color.WHITE);
c.setForeground(Color.BLACK);
int rc = convertColumnIndexToModel(column);
if(columnBackground[rc] != null) {
c.setBackground(columnBackground[rc]);
}
if(columnForeground[rc] != null) {
c.setForeground(columnForeground[rc]);
}
}
return c;
}
// -------------------------------------------------------------------------
public void setColumnBackground(int column, Color color) {
columnBackground[column] = color;
}
public void setColumnForeground(int column, Color color) {
columnForeground[column] = color;
}
// -------------------------------------------------------------------------
public String getToolTipText(java.awt.event.MouseEvent e){
try {
java.awt.Point p=getTablePoint(e);
return (String) getModel().getValueAt(p.x, p.y);
}
catch(Exception ex) {
return null;
}
}
public Point getTablePoint(java.awt.event.MouseEvent e) {
try {
java.awt.Point p=e.getPoint();
int row=rowAtPoint(p);
int col=columnAtPoint(p);
//int realCol=convertColumnIndexToModel(col);
return new Point(row, col);
}
catch (Exception ex) {
return null;
}
}
public String[] getRow(int r){
return data[r];
}
public Collection<Integer> getEditedRows(){
return kirjavaModel.getEditedRows();
}
public boolean isCellEditable(int row,int col){
return kirjavaModel.isCellEditable(row,col);
}
// -------------------------------------------------------------------------
private class KirjavaTableModel extends AbstractTableModel {
private static final long serialVersionUID = 1L;
private HashSet<Integer> editedRows=new HashSet<Integer>();
private Collection<Integer> getEditedRows(){
return editedRows;
}
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
return data.length;
}
public String getColumnName(int columnIndex){
return columnNames[columnIndex];
}
public boolean isCellEditable(int row,int col){
return columnEditable[col];
}
// ----
public Object getValueAt(int rowIndex, int columnIndex) {
return data[rowIndex][columnIndex];
}
public void setValueAt(Object value, int row, int col) {
try {
String oldValue = data[row][col];
String newValue = Textbox.trimExtraSpaces((String) value);
if(oldValue == null || !oldValue.equals(newValue)) {
data[row][col] = newValue;
fireTableCellUpdated(row, col);
editedRows.add(row);
tableChanged = true;
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
| 7,295 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SQLTablePanel.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/sqlconsole/gui/SQLTablePanel.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* SQLTablePanel.java
*
* Created on November 12, 2004, 3:43 PM
*/
package org.wandora.application.tools.sqlconsole.gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Vector;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.ListSelectionModel;
import javax.swing.Scrollable;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import org.wandora.application.gui.UIBox;
//import com.gripstudios.applications.sqlconsole.beanshell.*;
import org.wandora.application.tools.sqlconsole.data.PatternFilteredTableView;
import org.wandora.application.tools.sqlconsole.data.TableView;
import org.wandora.application.tools.sqlconsole.data.utils.SQLPattern;
import org.wandora.utils.ClipboardBox;
import org.wandora.utils.Delegate;
import org.wandora.utils.Textbox;
/**
*
* @author akivela
*/
public class SQLTablePanel extends JPanel implements MouseListener, ActionListener, Scrollable {
private static final long serialVersionUID = 1L;
private static Color PATTERN_BACKGROUND = new Color(250, 245, 245);
private static Color PATTERN_FOREGROUND = new Color(10, 0, 0);
private SQLTable guiTable;
private PatternFilteredTableView dataTable;
private boolean tableChanged;
private JTableHeader header;
private MouseEvent mouseEvent;
//private Kirjava kirjava;
private JPopupMenu headerPopup;
private String componentid;
private Delegate<?,JTableHeader> headerListener;
private boolean headerVisible=true;
private Object[] headerPopupStruct = new Object[] {
"Muokkaa sarakkeen suodatinta...",
"Poista sarakkeen suodatin",
"Poista kaikki suodattimet",
"---",
"Valitse suodatusten leikkaus (and)",
"Valitse suodatusten unioni (or)",
};
private Object[] popupStruct = new Object[] {
"Muokkaa",
new Object[] {
"Muokkaa...",
"---",
"Kopioi",
"Leikkaa",
"Liit�",
"---",
"Valitse kaikki",
"Valitse rivi(t)",
"Valitse sarake(et)",
"---",
"Laske rivit...",
},
"Suodattimet",
new Object[] {
"Muokkaa sarakkeen suodatinta...",
"Poista sarakkeen suodatin",
"Poista kaikki suodattimet",
"---",
"Valitse suodatusten leikkaus",
"Valitse suodatusten unioni",
}
};
public SQLTablePanel(TableView table) {
this(table,null);
}
public SQLTablePanel(TableView table, String componentid) {
this.componentid = componentid;
changeTable(table);
}
public Collection<Integer> getEditedRows(){
Vector<Integer> converted=new Vector<Integer>();
Collection<Integer> original=guiTable.getEditedRows();
for(int e : original){
converted.add(guiTable.convertRowIndexToView(e));
}
return converted;
}
public String[] getRowData(int r){
return guiTable.getRow(guiTable.convertRowIndexToModel(r));
}
public Object[] getHiddenData(int r){
return dataTable.getHiddenData(guiTable.convertRowIndexToModel(r));
}
public int convertRowIndexToModel(int r){
return guiTable.convertRowIndexToModel(r);
}
// -------------------------------------------------------------------------
public JTableHeader getTableHeader(){
return header;
}
public void setHeaderVisible(boolean value){
if(headerVisible==value) return;
headerVisible=value;
if(value){
add(header, BorderLayout.PAGE_START);
}
else{
remove(header);
}
}
public void setHeaderListener(Delegate<?,JTableHeader> headerChanged){
this.headerListener=headerChanged;
}
public void changeTable(TableView newTable) {
if(! (newTable instanceof PatternFilteredTableView)) {
dataTable = new PatternFilteredTableView(newTable);
}
else {
dataTable = (PatternFilteredTableView) newTable;
}
initGui();
}
public void initGui() {
TableColumnModel columnModel = null;
if(guiTable != null) {
columnModel = guiTable.getColumnModel();
remove(guiTable);
remove(header);
}
setLayout(new BorderLayout());
String[] columnNames = dataTable.getColumnNames();
guiTable = new SQLTable(dataTable.getView(), columnNames);
guiTable.addMouseListener(this);
//guiTable.addFocusListener(this);
guiTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
for(int i=0;i<columnNames.length;i++){
guiTable.setColumnEditable(i,dataTable.isColumnEditable(i));
}
header = guiTable.getTableHeader();
headerPopup= UIBox.makePopupMenu(headerPopupStruct, this);
header.addMouseListener(this);
if(headerListener!=null) headerListener.invoke(header);
if(headerVisible) add(header, BorderLayout.PAGE_START);
add(guiTable, BorderLayout.CENTER);
// setBorder(new javax.swing.border.EtchedBorder());
JPopupMenu popup = UIBox.makePopupMenu(popupStruct, this);
/*
if(componentid!=null){
HashMap<String,JMenu> subMenus=new HashMap();
final KirjavaTablePanel thisf=this;
BSHLibrary bshLibrary = kirjava.getBSHLibrary();
if(bshLibrary != null) {
popup.add(new JSeparator());
Vector<BSHComponent> components = bshLibrary.getComponentsByName(componentid+".table");
for(BSHComponent bshc : components) {
Object o=bshc.makeNew(kirjava);
Collection<TableContextMenuTool> tools=null;
if(o instanceof Collection) tools=(Collection<TableContextMenuTool>)o;
else if(o instanceof TableContextMenuTool) {tools=new Vector(); tools.add((TableContextMenuTool)o);}
for(TableContextMenuTool tool_ : tools){
final TableContextMenuTool tool=tool_;
String[] labels=tool.getLabel().split("/");
JMenu menu=null;
String path="";
for(int i=0;i<labels.length-1;i++){
path+=labels[i];
JMenu m=subMenus.get(path);
if(m==null){
m=new JMenu();
m.setFont(Kirjava.menuFont);
m.setText(labels[i]);
subMenus.put(path,m);
if(menu==null) popup.add(m);
else menu.add(m);
}
menu=m;
}
String label=labels[labels.length-1];
if(label.equals("---")){
if(menu==null) popup.add(new JSeparator());
else menu.add(new JSeparator());
}
else{
JMenuItem menuItem=new JMenuItem();
menuItem.setFont(kirjava.menuFont);
menuItem.setText(label);
menuItem.setActionCommand(label);
menuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent actionEvent){
tool.actionPerformed(kirjava,thisf);
}
});
if(menu==null) popup.add(menuItem);
else menu.add(menuItem);
}
}
}
}
}
*/
guiTable.setComponentPopupMenu(popup);
tableChanged = false;
for(int i=0; i<dataTable.getColumnCount(); i++) {
if(dataTable.columnHasPattern(i)) {
guiTable.setColumnBackground(i, PATTERN_BACKGROUND);
guiTable.setColumnForeground(i, PATTERN_FOREGROUND);
}
}
if(columnModel != null) {
guiTable.setColumnModel(columnModel);
for(Enumeration<TableColumn> e = columnModel.getColumns(); e.hasMoreElements(); ) {
TableColumn column = (TableColumn) e.nextElement();
column.setHeaderValue(columnNames[column.getModelIndex()]);
}
}
//if(kirjava != null) kirjava.refresh();
}
// -------------------------------------------------------------------------
public Vector<String> getHiddenColumnFromSelectedRows(int hiddenColumn) {
if(getSelectedRow() != -1) {
try {
int[] r=getSelectedRows();
Vector<String> colData=new Vector<>();
for(int i=0;i<r.length;i++){
Object[] hidden=getHiddenData(r[i]);
colData.add(hidden[hiddenColumn].toString());
}
return colData;
}
catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
public int[] getSelectedRows(){
return guiTable.getSelectedRows();
}
public int getSelectedRow(){
return guiTable.getSelectedRow();
}
public int getCurrentColumn() {
int col;
if(guiTable.getSelectedColumn() != -1) {
col = guiTable.getSelectedColumn();
}
else {
col = guiTable.columnAtPoint(mouseEvent.getPoint());
}
col = guiTable.convertColumnIndexToModel(col);
return col;
}
// -------------------------------------------------------------------------
public void setValueAt(Point p, String newValue) {
setValueAt(p.x, p.y, newValue);
}
public void setValueAt(int x, int y, String newValue) {
if( guiTable.isCellEditable(x,y) ){
try { guiTable.getModel().setValueAt(newValue, x, y); }
catch (Exception e) {}
}
}
public String getValueAt(Point p) {
return getValueAt(p.x, p.y);
}
public String getValueAt(int x, int y) {
try { return (String) guiTable.getModel().getValueAt(x, guiTable.convertColumnIndexToModel(y)); }
catch (Exception e) {}
return null;
}
// -------------------------------------------------------------------------
public void addRows() {
int[] rows = guiTable.getSelectedRows();
int number = rows.length > 0 ? rows.length : 1;
int pos = rows.length > 0 ? rows[0] : guiTable.getTablePoint(mouseEvent).x;
int p;
if(number > 0) {
dataTable.insertRows(pos, number);
initGui();
}
}
public void deleteRows() {
int[] rows = guiTable.getSelectedRows();
if(rows == null || rows.length == 0) rows = new int[] { guiTable.getTablePoint(mouseEvent).x };
dataTable.deleteRows(rows);
initGui();
}
// -------------------------------------------------------------------------
public void cut() {
copy(true);
}
public void copy() {
copy(false);
}
public void copy(boolean doCut) {
int[] cols = guiTable.getSelectedColumns();
int[] rows = guiTable.getSelectedRows();
String cellContent;
if(cols.length > 0 && rows.length > 0) {
StringBuffer sb = new StringBuffer();
for(int j=0; j<rows.length; j++) {
for(int i=0; i<cols.length; i++) {
cellContent = getValueAt(rows[j],cols[i]);
if(cellContent == null) cellContent = "";
sb.append(cellContent);
if(i < cols.length-1) sb.append("\t");
if(doCut) setValueAt(rows[j],cols[i], "");
}
if(j < rows.length-1) sb.append("\n");
}
ClipboardBox.setClipboard(sb.toString());
}
else {
Point loc = guiTable.getTablePoint(mouseEvent);
cellContent = getValueAt(loc);
if(cellContent == null) cellContent = "";
ClipboardBox.setClipboard(cellContent);
if(doCut) setValueAt(loc, "");
}
}
public void paste() {
String s = ClipboardBox.getClipboard();
int[] cols = guiTable.getSelectedColumns();
int[] rows = guiTable.getSelectedRows();
if(cols.length > 0 && rows.length > 0) {
String[][] st = Textbox.makeStringTable(s);
for(int j=0; j<rows.length && j < st.length; j++) {
for(int i=0; i<cols.length && i < st[0].length; i++) {
try {
setValueAt(rows[j], cols[i], st[j][i]);
}
catch (Exception ex) {}
}
}
}
else {
Point loc = guiTable.getTablePoint(mouseEvent);
String clipboardContent = ClipboardBox.getClipboard();
if(clipboardContent != null) {
setValueAt(loc, clipboardContent);
}
}
}
public void selectColumn() {
if(guiTable.getSelectedRow() != -1) {
guiTable.setRowSelectionInterval(0, guiTable.getRowCount()-1);
}
}
public String[][] copyToStringArray(boolean doCut) {
int[] cols = guiTable.getSelectedColumns();
int[] rows = guiTable.getSelectedRows();
String[][] copied = new String[rows.length][cols.length];
String cellContent;
if(cols.length > 0 && rows.length > 0) {
for(int j=0; j<rows.length; j++) {
for(int i=0; i<cols.length; i++) {
cellContent = getValueAt(rows[j],cols[i]);
if(cellContent == null) cellContent = "";
copied[j][i] = cellContent;
if(doCut) setValueAt(rows[j],cols[i], "");
}
}
}
else {
copied = new String[1][1];
Point loc = guiTable.getTablePoint(mouseEvent);
cellContent = getValueAt(loc);
if(cellContent == null) cellContent = "";
copied[0][0] = cellContent;
if(doCut) setValueAt(loc, "");
}
return copied;
}
// -------------------------------------------------------------------------
public void editPattern() {
int col = getCurrentColumn();
PatternEditor pe = new PatternEditor();
pe.show(this, col, getPatternForColumn(col), isAnd());
}
public void applyPattern(int col, SQLPattern pattern, boolean mode) {
dataTable.setMode(mode);
dataTable.setPattern(col, pattern);
//Logger.println("new pattern set " + pattern);
initGui();
}
public void resetPattern() {
int col = getCurrentColumn();
dataTable.setPattern(col, (SQLPattern) null);
}
public void resetPatterns() {
dataTable.resetView();
}
public SQLPattern getPatternForColumn(int col) {
return dataTable.getPattern(col);
}
public void andPatterns() {
dataTable.setMode(PatternFilteredTableView.AND_MODE);
dataTable.updateRowIndex();
initGui();
//Logger.println("and mode!");
}
public void orPatterns() {
dataTable.setMode(PatternFilteredTableView.OR_MODE);
dataTable.updateRowIndex();
initGui();
//Logger.println("or mode!");
}
public boolean isAnd() {
if(dataTable.getMode()==PatternFilteredTableView.AND_MODE) return true;
return false;
}
// -------------------------------------------------------------------------
public void actionPerformed(java.awt.event.ActionEvent actionEvent) {
try {
String command = actionEvent.getActionCommand();
Point loc = guiTable.getTablePoint(mouseEvent);
if("Muokkaa...".equalsIgnoreCase(command)) {
int[] cols = guiTable.getSelectedColumns();
int[] rows = guiTable.getSelectedRows();
if(cols.length > 0 && rows.length > 0) {
guiTable.editCellAt(cols[0], rows[0]);
}
else guiTable.editCellAt(loc.x, loc.y);
}
// ----- leikep�yt� ------
else if("Kopioi".equalsIgnoreCase(command)) {
copy();
}
else if("Leikkaa".equalsIgnoreCase(command)) {
cut();
}
else if("Liit�".equalsIgnoreCase(command)) {
paste();
}
else if("Laske rivit...".equalsIgnoreCase(command)) {
int rowsCounter = guiTable.getRowCount();
String message = "Taulussa on " + rowsCounter + " rivi�!";
JOptionPane.showMessageDialog(this, message, "Taulussa rivej�", JOptionPane.INFORMATION_MESSAGE);
}
/*
else if("Lis�� rivi...".equalsIgnoreCase(command)) {
addRows();
}
else if("Poista rivi...".equalsIgnoreCase(command)) {
deleteRows();
}
*/
// ------ valinnat ------
else if("Valitse kaikki".equalsIgnoreCase(command)) {
guiTable.selectAll();
}
else if("Valitse rivi(t)".equalsIgnoreCase(command)) {
if(guiTable.getSelectedRow() != -1)
guiTable.setColumnSelectionInterval(0, guiTable.getColumnCount()-1);
}
else if("Valitse sarake(et)".equalsIgnoreCase(command)) {
selectColumn();
}
// ----- hahmot (regexp) ------
else if("Muokkaa sarakkeen suodatinta...".equalsIgnoreCase(command)) {
editPattern();
}
else if("Poista sarakkeen suodatin".equalsIgnoreCase(command)) {
resetPattern();
initGui();
}
else if("Poista kaikki suodattimet".equalsIgnoreCase(command)) {
resetPatterns();
initGui();
}
else if("Valitse suodatusten leikkaus".equalsIgnoreCase(command)) {
andPatterns();
}
else if("Valitse suodatusten unioni".equalsIgnoreCase(command)) {
orPatterns();
}
}
catch(Exception e) {
e.printStackTrace();
}
}
public void mouseClicked(java.awt.event.MouseEvent mouseEvent) {
this.mouseEvent = mouseEvent;
//Logger.println("mouse clicked at table panel!" + mouseEvent.getButton());
Point hitCell = guiTable.getTablePoint(mouseEvent);
if(hitCell != null) {
if(hitCell.x == 0 && mouseEvent.getButton() == MouseEvent.BUTTON3) {
headerPopup.show(mouseEvent.getComponent(),mouseEvent.getX(), mouseEvent.getY());
mouseEvent.consume();
}
}
}
public void mouseEntered(java.awt.event.MouseEvent mouseEvent) {
this.mouseEvent = mouseEvent;
}
public void mouseExited(java.awt.event.MouseEvent mouseEvent) {
this.mouseEvent = mouseEvent;
}
public void mousePressed(java.awt.event.MouseEvent mouseEvent) {
this.mouseEvent = mouseEvent;
}
public void mouseReleased(java.awt.event.MouseEvent mouseEvent) {
this.mouseEvent = mouseEvent;
}
// --- Kirjava component! --------------------------------------------------
// -------------------------------------------------------------------------
public Dimension getPreferredScrollableViewportSize(){
return super.getPreferredSize();
}
public int getScrollableBlockIncrement(Rectangle visibleRect,int orientation, int direction){
return getScrollableUnitIncrement(visibleRect,orientation,direction);
}
public boolean getScrollableTracksViewportHeight(){
return false;
}
public boolean getScrollableTracksViewportWidth(){
return true;
}
public int getScrollableUnitIncrement(Rectangle visibleRect,int orientation,int derection){
return 20;
}
}
| 22,490 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SQLTablePage.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/sqlconsole/gui/SQLTablePage.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* SQLTablePage.java
*
* Created on 1. joulukuuta 2004, 15:01
*/
package org.wandora.application.tools.sqlconsole.gui;
import java.awt.BorderLayout;
import java.awt.Point;
import java.util.Collection;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import org.wandora.application.tools.sqlconsole.data.TableView;
import org.wandora.utils.Delegate;
/**
*
* @author akivela
*/
public class SQLTablePage extends JPanel {
private static final long serialVersionUID = 1L;
private long refreshTime;
//Kirjava kirjava = null;
//Kirjasto kirjasto = null;
TableView dataTable = null;
SQLTablePanel guiTable;
JScrollPane scrollPane;
//KirjavaAntialisedLabel pageTitleLabel;
String titleText = "";
private String componentid;
private Delegate<TableView,Delegate.Void> tableMaker;
//private Bookmark currentBookmark;
/*
* Note: kirjasto should always be kirjava.getKirjasto()
*/
public SQLTablePage(TableView dataTable, String title) {
this.dataTable = dataTable;
initComponents();
tableMaker=null;
setTitle(title);
tableMaker=null;
}
/*
public KirjavaTablePage(String componentid,Delegate<TableView,Delegate.Void> tableMaker,Bookmark bm,Kirjava kirjava, Kirjasto kirjasto, String title){
this(componentid,tableMaker,kirjava,kirjasto,title);
this.setBookmark(bm);
}
public KirjavaTablePage(String componentid,Delegate<TableView,Delegate.Void> tableMaker,Bookmark bm,Kirjava kirjava,String title){
this(componentid,tableMaker,kirjava,null,title);
this.setBookmark(bm);
}
public KirjavaTablePage(String componentid,Delegate<TableView,Delegate.Void> tableMaker,Kirjava kirjava,String title){
this(componentid,tableMaker,kirjava,null,title);
}
public KirjavaTablePage(String componentid,Delegate<TableView,Delegate.Void> tableMaker,Kirjava kirjava,Kirjasto kirjasto,String title){
this.componentid=componentid;
this.kirjava=kirjava;
this.kirjasto = kirjasto;
this.tableMaker=tableMaker;
refreshTime=System.currentTimeMillis();
this.dataTable = tableMaker.invoke(Delegate.VOID);
initComponents();
setTitle(title);
}
public KirjavaTablePage(String componentid,Kirjava kirjava,String title,String dialogTitle){
this(componentid, kirjava, null, title, dialogTitle);
}
public KirjavaTablePage(String componentid,Kirjava kirjava, Kirjasto kirjasto, String title,String dialogTitle){
this.componentid=componentid;
this.kirjava=kirjava;
this.kirjasto = kirjasto;
showSelectDialog(dialogTitle);
setTitle(title);
}
*/
// -------------------------------------------------------------------------
/*
public void showSelectDialog(String dialogTitle) {
final QueryDialog d=new QueryDialog(kirjava,kirjasto,true,componentid);
d.setTitle(dialogTitle);
d.setVisible(true);
final String query=d.getQuery();
final String countQuery=d.getCountQuery();
if(query!=null){
tableMaker=new Delegate<TableView,Delegate.Void>(){
public TableView invoke(Delegate.Void v){
T2<String,Boolean>[] columns=null;
SQLQueryResult result=kirjava.executeQuery(query,countQuery);
columns=d.getColumns();
if(columns==null) {
columns=new T2[result.columnNames.length];
for(int i=0;i<columns.length;i++){
columns[i]=t2(result.columnNames[i],false);
}
}
TableView tv=new PatternFilteredTableView(new RowTable(columns,result.rows));
tv.setUpdater(d.getUpdater());
return tv;
}
};*/
/* this.dataTable=new PatternFilteredTableView(new RowTable(columns,result.rows));
this.dataTable.setUpdater(d.getUpdater());*/
/*
refreshTime=System.currentTimeMillis();
if(d != null) {
tableMaker=d.getTableViewMaker();
setBookmark(d.getBookmark());
if(tableMaker != null) {
this.dataTable=tableMaker.invoke(Delegate.VOID);
}
}
else {
dataTable=null;
}
/* }
else{
tableMaker=null;
this.dataTable=null;
} */
/*
removeAll();
initComponents();
}
*/
public long getRefreshTime(){
return refreshTime;
}
public void refreshQuery(){
refreshTable();
}
public void refreshTable(){
Point pos=scrollPane.getViewport().getViewPosition();
refreshTime=System.currentTimeMillis();
if(tableMaker!=null){
dataTable=tableMaker.invoke(Delegate.VOID);
}
else dataTable=null;
setTable();
scrollPane.getViewport().setViewPosition(pos);
}
private void setTable(){
if(dataTable!=null){
guiTable=new SQLTablePanel(dataTable,componentid);
guiTable.setHeaderVisible(false);
javax.swing.table.JTableHeader tableHeader=guiTable.getTableHeader();
guiTable.setHeaderListener(new Delegate<Object,javax.swing.table.JTableHeader>(){
public Object invoke(javax.swing.table.JTableHeader header){
scrollPane.setColumnHeaderView(header);
return null;
}
});
scrollPane.setViewportView(guiTable);
scrollPane.setColumnHeaderView(tableHeader);
}
else{
scrollPane.setViewportView(new JPanel());
}
}
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
setLayout(new java.awt.GridBagLayout());
JPanel pageTitlePanel = new javax.swing.JPanel();
JLabel pageTitleLabel = new JLabel();
pageTitlePanel.setLayout(new BorderLayout(0,0));
pageTitlePanel.setPreferredSize(new java.awt.Dimension(640, 25));
pageTitleLabel.setText(titleText);
pageTitlePanel.add(pageTitleLabel, BorderLayout.WEST);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor=java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(4, 10, 2, 10);
add(pageTitlePanel, gridBagConstraints);
// -------
gridBagConstraints.insets = new java.awt.Insets(2, 10, 2, 10);
gridBagConstraints.gridy = 4;
gridBagConstraints.fill=gridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx=1.0;
gridBagConstraints.anchor=java.awt.GridBagConstraints.NORTHWEST;
scrollPane=new JScrollPane();//guiTable);
/* javax.swing.table.JTableHeader tableHeader=guiTable.getTableHeader();
guiTable.setHeaderListener(new Delegate<Object,javax.swing.table.JTableHeader>(){
public Object invoke(javax.swing.table.JTableHeader header){
scrollPane.setColumnHeaderView(header);
return null;
}
});*/
gridBagConstraints.weighty=1.0;
gridBagConstraints.fill=gridBagConstraints.BOTH;
add(scrollPane,gridBagConstraints);
// if(dataTable!=null){
/* guiTable = new KirjavaTablePanel(dataTable, kirjava,componentid);
guiTable.setHeaderVisible(false);
scrollPane.setColumnHeaderView(tableHeader);*/
setTable();
// }
// -------
gridBagConstraints.insets = new java.awt.Insets(2, 10, 7, 10);
gridBagConstraints.weighty=0;
gridBagConstraints.anchor=java.awt.GridBagConstraints.SOUTHEAST;
gridBagConstraints.fill=gridBagConstraints.BOTH;
gridBagConstraints.gridy = 5;
final SQLTablePage thisf=this;
/*
add(UIBox.createSavePanel(new ActionListener(){
public void actionPerformed(java.awt.event.ActionEvent actionEvent) {
TableViewUpdater updater=null;
if(updater != null) {
try{
if(getEditedRows().size() > 0) {
updater.update(kirjava,thisf);
JOptionPane.showMessageDialog(kirjava, "Tallennettu taulukon muutokset!", "Tallennus!", JOptionPane.INFORMATION_MESSAGE);
}
else {
JOptionPane.showMessageDialog(kirjava, "Taulukon rivej� ei ole muutettu!", "Ei talletettavaa!", JOptionPane.INFORMATION_MESSAGE);
}
}catch(Exception e){
e.printStackTrace();
JOptionPane.showMessageDialog(kirjava, "Muutosten tallennus keskeytyi virheeseen\n" + e.toString(), "Tallennus ep�onnistui!", JOptionPane.ERROR_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(kirjava, "Taulukko on tyhj�, eik� sis�ll� muutettuja tietoja!", "Ei talletettavaa!", JOptionPane.INFORMATION_MESSAGE);
}
}
}), gridBagConstraints);
**/
}
public Collection<Integer> getEditedRows(){
return guiTable.getEditedRows();
}
public String[] getRowData(int r){
return guiTable.getRowData(r);
}
public Object[] getHiddenData(int r){
return dataTable.getHiddenData(r);
}
public void setTitle(String newTitle) {
//if(pageTitleLabel != null) pageTitleLabel.setText(newTitle);
}
} | 10,932 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AddWebLocationAsOccurrence.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/webview/AddWebLocationAsOccurrence.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.application.tools.webview;
import java.util.Map;
import org.wandora.application.Wandora;
import org.wandora.application.contexts.Context;
import org.wandora.application.tools.GenericOptionsDialog;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
/**
* This tool should be executed in context of the WebViewTopicPanel.
* Adds current web location as an occurrence to the current topic.
*
* @author akivela
*/
public class AddWebLocationAsOccurrence extends AbstractWebViewTool {
private static final long serialVersionUID = 1L;
public static final boolean REUSE_TOPIC_SELECTION_DIALOG = true;
private static GenericOptionsDialog god = null;
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
try {
String location = getWebLocation(context);
if(location != null && location.length() > 0) {
Topic topic = getTopic(context);
if(topic != null && !topic.isRemoved()) {
Topic otype = null;
Topic oversion = null;
TopicMap tm = wandora.getTopicMap();
if(!REUSE_TOPIC_SELECTION_DIALOG || god == null) {
god = new GenericOptionsDialog(
wandora,
"Select occurrence type and scope","Select occurrence type and scope",
true,
new String[][]{
new String[] { "Occurrence type topic","topic","","Select occurrence type topic." },
new String[] { "Occurrence scope topic","topic","","Select occurrence scope topic ie. language" },
},
wandora
);
}
god.setVisible(true);
if(god.wasCancelled()) return;
Map<String,String> values=god.getValues();
otype = tm.getTopic(values.get("Occurrence type topic"));
oversion = tm.getTopic(values.get("Occurrence scope topic"));
if(otype != null && oversion != null) {
topic.setData(otype, oversion, location);
}
}
}
else {
log("Unable to solve web location, aborting.");
}
}
catch(Exception ex) {
log(ex);
}
}
@Override
public String getDescription() {
return "Adds current web location as an occurrence to the current topic.";
}
@Override
public String getName() {
return "Create occurrence out of web location";
}
}
| 3,702 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AddWebLocationAsSubjectLocator.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/webview/AddWebLocationAsSubjectLocator.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.application.tools.webview;
import org.wandora.application.Wandora;
import org.wandora.application.contexts.Context;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
/**
* This tool should be executed in context of the WebViewTopicPanel.
* Adds current web location as a subject locator to the current topic.
*
* @author akivela
*/
public class AddWebLocationAsSubjectLocator extends AbstractWebViewTool {
private static final long serialVersionUID = 1L;
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
String location = getWebLocation(context);
Topic topic = getTopic(context);
//System.out.println("@AddWebLocationAsSubjectLocator");
//System.out.println(" location="+location);
//System.out.println(" topic="+topic);
if(topic != null && !topic.isRemoved()) {
if(location != null && location.length() > 0) {
topic.setSubjectLocator(new Locator(location));
}
}
}
@Override
public String getDescription() {
return "Adds current web location as a subject locator to the current topic.";
}
@Override
public String getName() {
return "Create subject locator out of web location";
}
}
| 2,216 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
OpenWebLocationInExternalBrowser.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/webview/OpenWebLocationInExternalBrowser.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.application.tools.webview;
import java.awt.Desktop;
import java.net.URI;
import org.wandora.application.Wandora;
import org.wandora.application.contexts.Context;
import org.wandora.topicmap.TopicMapException;
/**
* This tool should be executed in context of the WebViewTopicPanel.
* Open current web location in external web browser application.
*
* @author akivela
*/
public class OpenWebLocationInExternalBrowser extends AbstractWebViewTool {
private static final long serialVersionUID = 1L;
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
try {
String location = getWebLocation(context);
if(location != null && location.length() > 0) {
Desktop desktop = Desktop.getDesktop();
desktop.browse(new URI(location));
}
}
catch(Exception ex) {
log(ex);
}
}
@Override
public String getDescription() {
return "Open current web location in external web browser application.";
}
@Override
public String getName() {
return "Open web location in external browser.";
}
}
| 2,034 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AddWebSelectionAsBasename.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/webview/AddWebSelectionAsBasename.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.application.tools.webview;
import org.wandora.application.Wandora;
import org.wandora.application.contexts.Context;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
/**
* This tool should be executed in context of the WebViewTopicPanel.
* Adds selected text as a basename to the current topic.
*
* @author akivela
*/
public class AddWebSelectionAsBasename extends AbstractWebViewTool {
private static final long serialVersionUID = 1L;
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
try {
String selection = getSelectedText(context);
if(selection != null && selection.length() > 0) {
Topic topic = getTopic(context);
if(topic != null && !topic.isRemoved()) {
selection = selection.replace('\n', ' ');
selection = selection.replace('\r', ' ');
selection = selection.replace('\b', ' ');
selection = selection.replace('\t', ' ');
topic.setBaseName(selection);
}
}
else {
log("No text selected, aborting.");
}
}
catch(Exception ex) {
log(ex);
}
}
@Override
public String getDescription() {
return "Adds selected text as a basename to the current topic.";
}
@Override
public String getName() {
return "Create basename out of selection";
}
}
| 2,389 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
ExecuteJavascript.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/webview/ExecuteJavascript.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.application.tools.webview;
import org.wandora.application.Wandora;
import org.wandora.application.contexts.Context;
import org.wandora.topicmap.TopicMapException;
/**
* This tool should be executed in context of the WebViewTopicPanel.
* Executes some Javascript code in WebViewPanel. This tool is abstract and
* provides an extension point for a tool that wishes to run Javascript code
* in the WebViewPanel. For an example, see OpenFirebugInWebView.
*
* @author akivela
*/
public abstract class ExecuteJavascript extends AbstractWebViewTool {
private static final long serialVersionUID = 1L;
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
try {
Object r = executeJavascript(context, getJavascript());
}
catch(Exception ex) {
log(ex);
}
}
@Override
public String getDescription() {
return "Executes some Javascript code in WebViewPanel.";
}
@Override
public String getName() {
return "Execute Javascript";
}
protected abstract String getJavascript();
}
| 1,970 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AddWebSelectionAsOccurrence.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/webview/AddWebSelectionAsOccurrence.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.application.tools.webview;
import java.util.Map;
import org.wandora.application.Wandora;
import org.wandora.application.contexts.Context;
import org.wandora.application.tools.GenericOptionsDialog;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
/**
* This tool should be executed in context of the WebViewTopicPanel.
* Adds selected text as an occurrence to the current topic.
*
* @author akivela
*/
public class AddWebSelectionAsOccurrence extends AbstractWebViewTool {
private static final long serialVersionUID = 1L;
public static final boolean REUSE_TOPIC_SELECTION_DIALOG = true;
private static GenericOptionsDialog god = null;
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
try {
String selection = getSelectedText(context);
if(selection != null && selection.length() > 0) {
Topic topic = getTopic(context);
if(topic != null && !topic.isRemoved()) {
Topic otype = null;
Topic oversion = null;
TopicMap tm = wandora.getTopicMap();
if(!REUSE_TOPIC_SELECTION_DIALOG || god == null) {
god = new GenericOptionsDialog(
wandora,
"Select occurrence type and scope","Select occurrence type and scope",
true,
new String[][]{
new String[] { "Occurrence type topic","topic","","Select occurrence type topic." },
new String[] { "Occurrence scope topic","topic","","Select occurrence scope topic ie. language" },
},
wandora
);
}
god.setVisible(true);
if(god.wasCancelled()) return;
Map<String,String> values=god.getValues();
otype = tm.getTopic(values.get("Occurrence type topic"));
oversion = tm.getTopic(values.get("Occurrence scope topic"));
if(otype != null && oversion != null) {
topic.setData(otype, oversion, selection);
}
}
}
else {
log("No text selected, aborting.");
}
}
catch(Exception ex) {
log(ex);
}
}
@Override
public String getDescription() {
return "Adds selected text as an occurrence to the current topic.";
}
@Override
public String getName() {
return "Create occurrence out of selection";
}
}
| 3,664 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AddWebLocationAsSubjectIdentifier.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/webview/AddWebLocationAsSubjectIdentifier.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.application.tools.webview;
import org.wandora.application.Wandora;
import org.wandora.application.contexts.Context;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
/**
* This tool should be executed in context of the WebViewTopicPanel.
* Adds current web location as a subject identifier to the current topic.
*
* @author akivela
*/
public class AddWebLocationAsSubjectIdentifier extends AbstractWebViewTool {
private static final long serialVersionUID = 1L;
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
String location = getWebLocation(context);
Topic topic = getTopic(context);
if(topic != null && !topic.isRemoved()) {
if(location != null && location.length() > 0) {
topic.addSubjectIdentifier(new Locator(location));
}
}
}
@Override
public String getDescription() {
return "Adds current web location as a subject identifier to the current topic.";
}
@Override
public String getName() {
return "Create subject identifier out of web location";
}
}
| 2,059 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
CreateWebLocationTopic.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/webview/CreateWebLocationTopic.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.application.tools.webview;
import org.wandora.application.Wandora;
import org.wandora.application.contexts.Context;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.SchemaBox;
import org.wandora.topicmap.TMBox;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.topicmap.XTMPSI;
/**
* This tool should be executed in context of the WebViewTopicPanel.
* Create topic using the web location and add web location to the created topic
* as a subject identifier. Depending on the configuration, the tool associates
* the created topic with the current topic. Association may be
* instance-class, subclass-superclass or document-relation.
*
* @author akivela
*/
public class CreateWebLocationTopic extends AbstractWebViewTool {
private static final long serialVersionUID = 1L;
public boolean MAKE_INSTANCE_OF_CURRENT = false;
public boolean MAKE_SUBCLASS_OF_CURRENT = false;
public boolean MAKE_INSTANCE_OF_DOCUMENT_TOPIC = true;
public boolean ASSOCIATE_WITH_CURRENT = true;
public CreateWebLocationTopic(boolean p1, boolean p2, boolean p3, boolean p4) {
MAKE_INSTANCE_OF_CURRENT = p1;
MAKE_SUBCLASS_OF_CURRENT = p2;
MAKE_INSTANCE_OF_DOCUMENT_TOPIC = p3;
ASSOCIATE_WITH_CURRENT = p4;
}
public CreateWebLocationTopic() {
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
try {
String location = getWebLocation(context);
if(location != null && location.length() > 0) {
TopicMap tm = wandora.getTopicMap();
Topic locationTopic = tm.getTopic(location);
if(locationTopic == null) {
locationTopic = tm.createTopic();
locationTopic.addSubjectIdentifier(new Locator(location));
}
if(MAKE_INSTANCE_OF_CURRENT) {
Topic currentTopic = getTopic(context);
if(currentTopic != null) {
locationTopic.addType(currentTopic);
}
}
if(MAKE_SUBCLASS_OF_CURRENT) {
Topic currentTopic = getTopic(context);
if(currentTopic != null) {
Topic superClassTopic = tm.getTopic(XTMPSI.SUPERCLASS);
Topic subClassTopic = tm.getTopic(XTMPSI.SUBCLASS);
Topic superSubClassTopic = tm.getTopic(XTMPSI.SUPERCLASS_SUBCLASS);
if(superClassTopic != null && subClassTopic != null && superSubClassTopic != null) {
Association a = tm.createAssociation(superSubClassTopic);
a.addPlayer(locationTopic, subClassTopic);
a.addPlayer(currentTopic, superClassTopic);
}
}
}
if(MAKE_INSTANCE_OF_DOCUMENT_TOPIC) {
Topic documentTopic = getDocumentTopic(tm);
if(documentTopic != null) {
locationTopic.addType(documentTopic);
}
}
if(ASSOCIATE_WITH_CURRENT) {
Topic associationType = tm.getTopic(SchemaBox.DEFAULT_ASSOCIATION_SI);
if(associationType == null) {
associationType = tm.createTopic();
associationType.addSubjectIdentifier(new Locator(SchemaBox.DEFAULT_ASSOCIATION_SI));
}
Topic role1 = tm.getTopic("http://wandora.org/si/core/default-role-1");
if(role1 == null) {
role1 = tm.createTopic();
role1.addSubjectIdentifier(new Locator("http://wandora.org/si/core/default-role-1"));
}
Topic role2 = tm.getTopic("http://wandora.org/si/core/default-role-2");
if(role2 == null) {
role2 = tm.createTopic();
role2.addSubjectIdentifier(new Locator("http://wandora.org/si/core/default-role-2"));
}
Topic currentTopic = getTopic(context);
if(currentTopic != null) {
Association a = tm.createAssociation(associationType);
a.addPlayer(currentTopic, role1);
a.addPlayer(locationTopic, role2);
}
}
}
else {
log("No location available, aborting.");
}
}
catch(Exception ex) {
log(ex);
}
}
private static final String DOCUMENT_SI = "http://wandora.org/si/document";
private Topic getDocumentTopic(TopicMap tm) {
if(tm != null) {
try {
Topic documentTopic = tm.getTopic(DOCUMENT_SI);
if(documentTopic == null) {
documentTopic = tm.createTopic();
documentTopic.addSubjectIdentifier(new Locator(DOCUMENT_SI));
documentTopic.setBaseName("Document");
Topic wandoraTopic = tm.getTopic(TMBox.WANDORACLASS_SI);
Topic superClassTopic = tm.getTopic(XTMPSI.SUPERCLASS);
Topic subClassTopic = tm.getTopic(XTMPSI.SUBCLASS);
Topic superSubClassTopic = tm.getTopic(XTMPSI.SUPERCLASS_SUBCLASS);
if(wandoraTopic != null && superClassTopic != null && subClassTopic != null && superSubClassTopic != null) {
Association a = tm.createAssociation(superSubClassTopic);
a.addPlayer(documentTopic, subClassTopic);
a.addPlayer(wandoraTopic, superClassTopic);
}
}
return documentTopic;
}
catch(Exception e) {}
}
return null;
}
@Override
public String getDescription() {
return "Creates topic and sets the current web location as topic's subject identifier." +
(MAKE_INSTANCE_OF_CURRENT ? " Make the topic instance of current topic." : "") +
(MAKE_SUBCLASS_OF_CURRENT ? " Make the topic subclass of current topic." : "") +
(MAKE_INSTANCE_OF_DOCUMENT_TOPIC ? " Make the topic instance of specific document topic." : "") +
(ASSOCIATE_WITH_CURRENT ? " Associate the topic with current topic." : "");
}
@Override
public String getName() {
return "Create topic using the web location";
}
}
| 7,684 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AbstractWebViewTool.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/webview/AbstractWebViewTool.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.application.tools.webview;
import javax.swing.Icon;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.UIBox;
import org.wandora.application.gui.topicpanels.webview.WebViewPanel;
import org.wandora.application.tools.AbstractWandoraTool;
import org.wandora.topicmap.Topic;
import javafx.scene.web.WebEngine;
/**
* This tool should be executed in context of the WebViewTopicPanel.
*
* @author akivela
*/
public abstract class AbstractWebViewTool extends AbstractWandoraTool {
private static final long serialVersionUID = 1L;
public AbstractWebViewTool() {
}
@Override
public String getName() {
return "Abstract web view tool";
}
@Override
public String getDescription() {
return "Abstract web view tool is used as a basis of various WebViewPanel tools.";
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/topic_panel_webview.png");
}
// -------------------------------------------------------- WebViewPanel ---
protected WebViewPanel getWebViewPanel(Context context) {
if(context != null) {
Object source = context.getContextSource();
if(source != null && source instanceof WebViewPanel) {
return (WebViewPanel) source;
}
else {
System.out.println("Invalid context source. Expecting WebViewPanel but found "+source.getClass());
}
}
return null;
}
protected WebEngine getWebEngine(Context context) {
WebViewPanel webViewPanel = getWebViewPanel(context);
if(webViewPanel != null) {
return webViewPanel.getWebEngine();
}
return null;
}
protected String getWebLocation(Context context) {
WebViewPanel webViewPanel = getWebViewPanel(context);
if(webViewPanel != null) {
return webViewPanel.getWebLocation();
}
return null;
}
protected String getSource(Context context) {
WebViewPanel webViewPanel = getWebViewPanel(context);
if(webViewPanel != null) {
return webViewPanel.getSource();
}
return null;
}
protected String getSelectedSource(Context context) {
WebViewPanel webViewPanel = getWebViewPanel(context);
if(webViewPanel != null) {
return webViewPanel.getSelectedSource();
}
return null;
}
protected String getSelectedText(Context context) {
WebViewPanel webViewPanel = getWebViewPanel(context);
if(webViewPanel != null) {
return webViewPanel.getSelectedText();
}
return null;
}
protected Topic getTopic(Context context) {
WebViewPanel webViewPanel = getWebViewPanel(context);
if(webViewPanel != null) {
try {
return webViewPanel.getTopic();
}
catch(Exception e) {
// IGNORE SILENTLY
}
}
return null;
}
protected Object executeJavascript(Context context, String script) {
WebViewPanel webViewPanel = getWebViewPanel(context);
if(webViewPanel != null) {
return webViewPanel.executeSynchronizedScript(script);
}
return null;
}
}
| 4,285 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
OpenOccurrenceInWebView.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/webview/OpenOccurrenceInWebView.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.application.tools.webview;
import org.wandora.application.Wandora;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.topicpanels.webview.WebViewPanel;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
/**
* This tool should be executed in context of the WebViewTopicPanel.
* View occurrence in the WebView. Occurrence type and scope are
* set with the constructor arguments.
*
* @author akivela
*/
public class OpenOccurrenceInWebView extends AbstractWebViewTool {
private static final long serialVersionUID = 1L;
private Topic otopic;
private Topic otype;
private Topic oscope;
public OpenOccurrenceInWebView(Topic topic, Topic type, Topic scope) {
otopic = topic;
otype = type;
oscope = scope;
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
try {
if(otopic != null && otype != null && oscope != null) {
String o = otopic.getData(otype, oscope);
if(o != null) {
WebViewPanel webViewPanel = getWebViewPanel(context);
if(webViewPanel != null) {
webViewPanel.openContent(o);
}
}
}
}
catch(Exception ex) {
log(ex);
}
}
@Override
public String getDescription() {
return "View occurrence in the WebView.";
}
@Override
public String getName() {
return "View occurrence in the WebView";
}
}
| 2,482 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AddWebSourceAsOccurrence.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/webview/AddWebSourceAsOccurrence.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.application.tools.webview;
import java.util.Map;
import org.wandora.application.Wandora;
import org.wandora.application.contexts.Context;
import org.wandora.application.tools.GenericOptionsDialog;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
/**
* This tool should be executed in context of the WebViewTopicPanel.
* Create occurrence out of selection. If USE_SELECTION_SOURCE is set the
* tool creates occurrence out of selection's HTML source code instead of
* visible text.
*
* @author akivela
*/
public class AddWebSourceAsOccurrence extends AbstractWebViewTool {
private static final long serialVersionUID = 1L;
public boolean USE_SELECTION_SOURCE = false;
public static final boolean REUSE_TOPIC_SELECTION_DIALOG = true;
private static GenericOptionsDialog god = null;
public AddWebSourceAsOccurrence() {}
public AddWebSourceAsOccurrence(boolean selectionSource) {
USE_SELECTION_SOURCE = selectionSource;
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
try {
String source = null;
if(USE_SELECTION_SOURCE) {
source = getSelectedSource(context);
}
else {
source = getSource(context);
}
if(source != null && source.length() > 0) {
Topic topic = getTopic(context);
if(topic != null && !topic.isRemoved()) {
Topic otype = null;
Topic oversion = null;
TopicMap tm = wandora.getTopicMap();
if(!REUSE_TOPIC_SELECTION_DIALOG || god == null) {
god = new GenericOptionsDialog(
wandora,
"Select occurrence type and scope","Select occurrence type and scope",
true,
new String[][]{
new String[] { "Occurrence type topic","topic","","Select occurrence type topic." },
new String[] { "Occurrence scope topic","topic","","Select occurrence scope topic ie. language" },
},
wandora
);
}
god.setVisible(true);
if(god.wasCancelled()) return;
Map<String,String> values=god.getValues();
otype = tm.getTopic(values.get("Occurrence type topic"));
oversion = tm.getTopic(values.get("Occurrence scope topic"));
if(otype != null && oversion != null) {
topic.setData(otype, oversion, source);
}
}
}
else {
log("Unable to solve web source, aborting.");
}
}
catch(Exception ex) {
log(ex);
}
}
@Override
public String getDescription() {
if(USE_SELECTION_SOURCE) {
return "Add selection source to the current topic as an occurrence.";
}
else {
return "Add source to the current topic as an occurrence.";
}
}
@Override
public String getName() {
return "Create occurrence out of selection";
}
} | 4,318 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
OpenFirebugInWebView.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/webview/OpenFirebugInWebView.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.application.tools.webview;
/**
* This tool should be executed in context of the WebViewTopicPanel.
* Executes Javascript code in the WebView. The code loads and views
* Firebug Javascript debugger.
*
* @author akivela
*/
public class OpenFirebugInWebView extends ExecuteJavascript {
private static final long serialVersionUID = 1L;
@Override
protected String getJavascript() {
return "if (!document.getElementById('FirebugLite')){E = document['createElement' + 'NS'] && document.documentElement.namespaceURI;E = E ? document['createElement' + 'NS'](E, 'script') : document['createElement']('script');E['setAttribute']('id', 'FirebugLite');E['setAttribute']('src', 'https://getfirebug.com/' + 'firebug-lite.js' + '#startOpened');E['setAttribute']('FirebugLite', '4');(document['getElementsByTagName']('head')[0] || document['getElementsByTagName']('body')[0]).appendChild(E);E = new Image;E['setAttribute']('src', 'https://getfirebug.com/' + '#startOpened');}";
}
@Override
public String getDescription() {
return "Open Firebug Javascript and HTML debugging tool from http://getfirebug.com.";
}
@Override
public String getName() {
return "Open Firebug";
}
}
| 2,066 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SimpleRDFTurtleImport.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/importers/SimpleRDFTurtleImport.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* SimpleRDFTurtleImport.java
*
* Created on 2009-11-20
*
*/
package org.wandora.application.tools.importers;
import java.io.InputStream;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.wandora.topicmap.TopicMap;
/**
*
* @author akivela
*/
public class SimpleRDFTurtleImport extends SimpleRDFImport {
private static final long serialVersionUID = 1L;
/**
* Creates a new instance of SimpleRDFTurtleImport
*/
public SimpleRDFTurtleImport() {
}
public SimpleRDFTurtleImport(int options) {
setOptions(options);
}
@Override
public String getName() {
return "Simple RDF TURTLE import";
}
@Override
public String getDescription() {
return "Tool imports RDF TURTLE file and merges triplets to current topic map.";
}
@Override
public void importRDF(InputStream in, TopicMap map) {
if(in != null) {
// create an empty model
Model model = ModelFactory.createDefaultModel();
// read the RDF/XML file
model.read(in, "", "TURTLE");
RDF2TopicMap(model, map);
}
}
}
| 1,988 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SimpleN3Import.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/importers/SimpleN3Import.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* SimpleN3Import.java
*
* Created on 6.7.2006, 10:29
*
*/
package org.wandora.application.tools.importers;
import java.io.InputStream;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.wandora.topicmap.TopicMap;
/**
*
* @author akivela
*/
public class SimpleN3Import extends SimpleRDFImport {
private static final long serialVersionUID = 1L;
/**
* Creates a new instance of SimpleN3Import
*/
public SimpleN3Import() {
}
public SimpleN3Import(int options) {
setOptions(options);
}
@Override
public String getName() {
return "Simple RDF N3 import";
}
@Override
public String getDescription() {
return "Tool imports RDF N3 file and merges triplets to current topic map.";
}
@Override
public void importRDF(InputStream in, TopicMap map) {
if(in != null) {
// create an empty model
Model model = ModelFactory.createDefaultModel();
// read the RDF/XML file
model.read(in, "", "N3");
RDF2TopicMap(model, map);
}
}
}
| 1,966 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
OBOImport.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/importers/OBOImport.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* OBOImport.java
*
* Created on 22. elokuuta 2007, 19:17
*
*/
package org.wandora.application.tools.importers;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.Icon;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.gui.UIBox;
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.TopicMapReadOnlyException;
import org.wandora.topicmap.XTMPSI;
import org.wandora.utils.Tuples.T2;
/**
* OBOImport imports OBO flat file ontology, converts it to a topic map and merges
* the result to current topic map.
*
* @author akivela
*/
public class OBOImport extends AbstractImportTool implements WandoraTool {
private static final long serialVersionUID = 1L;
protected ArrayList<String> namespaces = null;
/** Creates a new instance of OBOImport */
public OBOImport() {
}
public OBOImport(int options) {
setOptions(options);
}
@Override
public void initialize(Wandora wandora, org.wandora.utils.Options options, String prefix) throws TopicMapException {
String o=options.get(OBO.optionPrefix+"options");
if(o!=null){
int i=Integer.parseInt(o);
OBO.setOptions(i);
}
}
@Override
public boolean isConfigurable(){
return true;
}
@Override
public void configure(Wandora wandora, org.wandora.utils.Options options, String prefix) throws TopicMapException {
//System.out.println(prefix);
OBOConfiguration dialog=new OBOConfiguration(wandora,true);
dialog.setOptions(OBO.getOptions());
dialog.setVisible(true);
if(!dialog.wasCancelled()){
int i=dialog.getOptions();
OBO.setOptions(i);
options.put(OBO.optionPrefix+"options",""+i);
}
}
@Override
public void writeOptions(Wandora wandora, org.wandora.utils.Options options, String prefix){
options.put(OBO.optionPrefix+"options",""+OBO.getOptions());
}
@Override
public String getName() {
return "OBO import";
}
@Override
public String getDescription() {
return "Imports OBO flat file ontology, converts it to a topic map and merges the result to current topic map.";
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/import_obo.png");
}
public ArrayList<String> getNamespaces() {
return namespaces;
}
protected void addNamespace(String newNamespace) {
if(namespaces == null) namespaces = new ArrayList<String>();
if(!namespaces.contains(newNamespace)) {
namespaces.add(newNamespace);
}
}
@Override
public void importStream(Wandora wandora, String streamName, InputStream inputStream) {
try {
try {
wandora.getTopicMap().clearTopicMapIndexes();
}
catch(Exception e) {
log(e);
}
TopicMap map = null;
if(directMerge) {
map = solveContextTopicMap(wandora, getContext());
}
else {
map = new org.wandora.topicmap.memory.TopicMapImpl();
}
importOBO(inputStream, map);
if(!directMerge) {
if(newLayer) {
createNewLayer(map, streamName, wandora);
}
else {
log("Merging '" + streamName + "'.");
solveContextTopicMap(wandora, getContext()).mergeIn(map);
}
}
}
catch(TopicMapReadOnlyException tmroe) {
log("Topic map is write protected. Import failed.");
}
catch(Exception e) {
log("Reading '" + streamName + "' failed!", e);
}
}
public void importOBO(InputStream in, TopicMap map) {
if(in != null) {
namespaces = null;
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
long startTime = System.currentTimeMillis();
OBOParser oboParser = new OBOParser(reader, map, this);
oboParser.parse();
long endTime = System.currentTimeMillis();
long importTime = Math.round((endTime-startTime)/1000);
if(importTime > 1) log("Import took "+importTime+" seconds.");
}
}
// -------------------------------------------------------------------------
// ---------------------------------------------------------- OBO PARSER ---
// -------------------------------------------------------------------------
/**
* OBOParser class implements parser for OBO flat file format. OBOImport
* uses the parser to convert OBO flat files to Topic Maps.
*/
public class OBOParser {
public boolean debug = true;
public int deprecationMsgLimit = 1000;
private TopicMap tm;
private OBOImport parent;
private BufferedReader in;
private Header header = null;
private Stanza stanza = null;
private int stanzaCounter = 0;
Topic root = null;
Topic wandoraClass = null;
/**
* Constructor for OBOParser.
*
* @param in is the BufferedReader for OBO flat format file.
* @param tm is the Topic Map object where conversion is stored.
* @param parent is the OBOImport callback interface.
*/
public OBOParser(BufferedReader in, TopicMap tm, OBOImport parent) {
this.tm=tm;
this.parent=parent;
this.in=in;
deprecationMsgLimit = 1000;
initializeTopicMap(tm);
}
/**
* Creates frequently used topics into the Topic Map before
* conversion starts.
*
* @param tm is the Topic Map where initialization is targeted.
*/
public void initializeTopicMap(TopicMap tm) {
wandoraClass = getOrCreateTopic(TMBox.WANDORACLASS_SI, "Wandora class");
getOrCreateTopic(XTMPSI.getLang(OBO.LANG));
getOrCreateTopic(XTMPSI.DISPLAY, "Scope Display");
}
/**
* Starts the parse.
*/
public void parse() {
try {
parent.setProgressMax(1000);
stanzaCounter = 0;
stanza = null;
header = new Header();
boolean headerProcessed = false;
String line = null;
String tag = null;
String value = null;
String comment = null;
int splitPoint = -1;
line = in.readLine();
while(line!=null && !parent.forceStop()) {
line = line.trim();
if(line!=null && line.length()>0) {
if(line.startsWith("[")) {
String stanzaType = line.substring(1);
if(stanzaType.endsWith("]")) {
stanzaType = stanzaType.substring(0,stanzaType.length()-1);
}
if(!headerProcessed) {
processHeader(header);
headerProcessed = true;
}
if(stanza!=null) {
// Process previous stanza....
// The idea is to collect stanza lines until next stanza title is found and
// then just before new stanza is initialized process the collected stanza.
stanzaCounter++;
processStanza(stanza);
parent.setProgress(stanzaCounter);
}
stanza = new Stanza(stanzaType);
}
else {
//System.out.println("parsing line: " + line);
/*
comment = null;
splitPoint = line.indexOf('!');
if(splitPoint > -1) {
comment = line.substring(splitPoint+1).trim();
line = line.substring(0, splitPoint);
}
*/
comment = null;
String preline = null;
boolean precedesBackslash = true;
splitPoint = line.indexOf('!');
while(splitPoint > -1) {
preline = line.substring(0, splitPoint);
precedesBackslash = (splitPoint > 0 ? line.charAt(splitPoint-1) == '\\' : false);
if(!precedesBackslash) {
int quoteCounter = 0;
int findPoint = preline.indexOf("\"");
while(findPoint > -1) {
precedesBackslash = (findPoint > 0 ? line.charAt(findPoint-1) == '\\' : false);
if(!precedesBackslash) quoteCounter++;
findPoint = preline.indexOf("\"", findPoint+1);
}
if(((quoteCounter % 2) == 0)) {
comment = line.substring(splitPoint+1).trim();
line = preline;
break;
}
}
splitPoint = line.indexOf('!', splitPoint+1);
}
splitPoint = line.indexOf(':');
if(splitPoint > -1) {
tag = line.substring(0, splitPoint).trim();
value = line.substring(splitPoint+1).trim();
if(stanza != null) {
stanza.addTagValuePair(tag, value, comment);
}
else {
header.addTagValuePair(tag, value, comment);
}
}
}
}
line = in.readLine();
}
if(stanza != null) {
// Process last stanza....
stanzaCounter++;
processStanza(stanza);
}
if(parent.forceStop()) parent.log("Import interrupted by user!");
parent.log("Total "+stanzaCounter+" stanzas processed!");
}
catch(Exception e) {
parent.log(e);
}
/*
// **** POST PROCESS ****
parent.log("Solving is-a root topics.");
try {
Topic supersubClassTopic = tm.getTopic(XTMPSI.SUPERCLASS_SUBCLASS);
Topic subclassTopic = tm.getTopic(XTMPSI.SUBCLASS);
Topic superclassTopic = tm.getTopic(XTMPSI.SUPERCLASS);
if(supersubClassTopic != null && subclassTopic != null && superclassTopic != null) {
Iterator<Topic> typeIter = namespace.iterator();
Topic type = null;
while(typeIter.hasNext()) {
type = typeIter.next();
ArrayList<Topic> edges = new ArrayList<Topic>();
ArrayList<Topic> alone = new ArrayList<Topic>();
if(type != null && !type.isRemoved()) {
Collection<Topic> instances = tm.getTopicsOfType(type);
Iterator<Topic> instanceIterator = instances.iterator();
Topic instance = null;
while(instanceIterator.hasNext()) {
instance = instanceIterator.next();
if(instance != null && !instance.isRemoved()) {
Collection<Association> supersubAssociations = instance.getAssociations(supersubClassTopic);
if(supersubAssociations.size() > 0) {
if( instance.getAssociations(supersubClassTopic, superclassTopic).size() > 0 && instance.getAssociations(supersubClassTopic, subclassTopic).size() == 0) {
edges.add(instance);
}
}
else {
alone.add(instance);
}
}
}
if(edges.size() > 0) {
Topic isaRoot = OBO.createISARootTopic(tm, header.getDefaultNameSpace());
Topic t = null;
Iterator<Topic> edgeIterator = edges.iterator();
while(edgeIterator.hasNext()) {
t = edgeIterator.next();
if(t != null && !t.isRemoved())
t.addType(isaRoot);
}
}
* /
/*
if(alone.size() > 0) {
Topic typeRoot = getOrCreateTopic(type.getOneSubjectIdentifier().toExternalForm()+"/alone", type.getBaseName()+" alone");
Topic t = null;
makeSubclassOf(typeRoot, root);
Iterator<Topic> aloneIterator = alone.iterator();
while(aloneIterator.hasNext()) {
t = aloneIterator.next();
t.addType(typeRoot);
}
}
* */ /*
}
}
}
}
catch(Exception e) {
parent.log(e);
}
* */
}
/**
* Handles header of the OBO flat format file.
* @param header
*/
private void processHeader(Header header) {
if(tm == null) return;
try {
String namespace = header.getDefaultNameSpace();
parent.addNamespace(namespace);
root = OBO.createRootTopic(tm, namespace);
Topic headerTopic = OBO.createHeaderTopic(tm, namespace);
makeSubclassOf(headerTopic, root);
String tag = null;
String value = null;
ArrayList<T2<String, String>> modifiers = null;
String comment = null;
TagValuePair tagValue = null;
ArrayList<TagValuePair> tagValuePairs = header.getTagValuePairs();
for(Iterator<TagValuePair> i=tagValuePairs.iterator(); i.hasNext() && !parent.forceStop(); ) {
try {
tagValue = i.next();
tag = tagValue.getTag();
value = tagValue.getValueWithoutModifiers();
modifiers = tagValue.getModifiers();
comment = tagValue.getComment();
if(false && debug) {
System.out.println("---------------------------------");
System.out.println("header");
System.out.println("tag: "+ tag);
System.out.println("value: "+ value);
System.out.println("modifiers:");
for(Iterator<T2<String,String>> mi=modifiers.iterator(); mi.hasNext();) {
T2<String,String> mo = mi.next();
System.out.println(" "+mo.e1+":"+mo.e2);
}
System.out.println("comment: "+ comment);
}
if("subsetdef".equals(tag)) {
Category category = new Category(value);
String categoryName = category.getId();
String description = category.getDescription();
Topic categoryTopic = OBO.createTopicForCategory(tm, categoryName, description);
Topic categoryTypeTopic = OBO.createCategoryTopic(tm, namespace);
categoryTopic.addType(categoryTypeTopic);
}
else {
if(("import".equals(tag) || "typeref".equals(tag)) && OBO.PROCESS_HEADER_IMPORTS) {
if("typeref".equals(tag)) this.logDeprecation(tag, "header", "import");
try {
BufferedReader reader = null;
if(value.startsWith("http:")) {
URL url = new URL(value);
URLConnection urlConnection = url.openConnection();
Wandora.initUrlConnection(urlConnection);
reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
}
else {
reader = new BufferedReader(new FileReader(value));
}
OBOParser oboParser = new OBOParser(reader, tm, parent);
oboParser.parse();
}
catch(Exception e) {
parent.log(e);
}
}
Topic tagTopic = OBO.createTopicForSchemaTerm(tm, tag);
String oldData = headerTopic.getData(tagTopic, OBO.LANG);
if(oldData == null)
setData(headerTopic, tagTopic, OBO.LANG, value);
else
setData(headerTopic, tagTopic, OBO.LANG, oldData+"\n"+value);
}
}
catch(Exception e) {
parent.log(e);
}
}
}
catch(Exception e) {
parent.log(e);
}
}
private void processStanza(Stanza stanza) {
String st = stanza.getType();
if("Term".equalsIgnoreCase(st))
processTermStanza(stanza);
else if("Typedef".equalsIgnoreCase(st))
processTypedefStanza(stanza);
else if("Instance".equalsIgnoreCase(st))
processInstanceStanza(stanza);
else
parent.log("Unsupported stanza type '"+st+"' used.");
}
private void processTypedefStanza(Stanza stanza) {
if(tm == null || stanza == null) return;
try {
String id = stanza.getId();
String name = stanza.getName();
String namespace = solveNamespace(stanza, id, header, "obo-rel");
parent.addNamespace(namespace);
Topic stanzaTopic = OBO.createTopicForTypedef(tm, id, name, namespace);
String tag = null;
String value = null;
ArrayList<T2<String, String>> modifiers = null;
String comment = null;
TagValuePair tagValue = null;
ArrayList<TagValuePair> tagValuePairs = stanza.getTagValuePairs();
int defCount = 0;
int commentCount = 0;
for(Iterator<TagValuePair> i=tagValuePairs.iterator(); i.hasNext() && !parent.forceStop(); ) {
try {
tagValue = i.next();
tag = tagValue.getTag();
value = tagValue.getValueWithoutModifiers();
modifiers = tagValue.getModifiers();
comment = tagValue.getComment();
if(false && debug) {
System.out.println("---------------------------------");
System.out.println("id: "+ id);
System.out.println("tag: "+ tag);
System.out.println("value: "+ value);
System.out.println("modifiers:");
for(Iterator<T2<String,String>> mi=modifiers.iterator(); mi.hasNext();) {
T2<String,String> mo = mi.next();
System.out.println(" "+mo.e1+":"+mo.e2);
}
System.out.println("comment: "+ comment);
}
// **** PROCESS CURRENT TAG AND VALUE ****
if("alt_id".equals(tag)) {
if(OBO.MAKE_SIS_FROM_ALT_IDS) {
try {
stanzaTopic.addSubjectIdentifier(OBO.makeLocator(value));
}
catch(Exception e) {
parent.log(e);
}
}
else {
createAssociation(OBO.SCHEMA_TERM_ALTERNATIVE_ID, stanzaTopic, OBO.SCHEMA_TERM_TYPEDEF, OBO.createTopicForTerm(tm,value), OBO.SCHEMA_TERM_ALTERNATIVE_ID);
}
}
// ***** XREFS *****
else if("xref_unknown".equals(tag)) {
logDeprecation(tag, id, "xref");
processXref(stanzaTopic, "UNKNOWN", value, null, OBO.SCHEMA_TERM_TYPEDEF);
}
else if("xref_analog".equals(tag)) {
logDeprecation(tag, id, "xref");
processXref(stanzaTopic, "ANALOG", value, null, OBO.SCHEMA_TERM_TYPEDEF);
}
else if("xref".equals(tag)) {
processXref(stanzaTopic, null, value, null, OBO.SCHEMA_TERM_TYPEDEF);
}
// ********** SUPERCLASS-SUBCLASS *********
else if("is_a".equals(tag)) {
createAssociation(OBO.SCHEMA_TERM_SUPERCLASS_SUBCLASS, stanzaTopic, OBO.SCHEMA_TERM_SUBCLASS, OBO.createTopicForTerm(tm, value), OBO.SCHEMA_TERM_SUPERCLASS);
}
// ****** RELATIONSHIP ********
else if("relationship".equals(tag)) {
RelatedTerm relatedTerm = new RelatedTerm(value);
if(relatedTerm.getTerm() != null && relatedTerm.getModifier() != null ) {
createAssociation(relatedTerm.getModifier(), stanzaTopic, OBO.SCHEMA_TERM_TYPEDEF, OBO.createTopicForTerm(tm,relatedTerm.getTerm()), OBO.SCHEMA_TERM_RELATED_TO);
}
else if(relatedTerm.getTerm() != null) {
createAssociation(OBO.SCHEMA_TERM_RELATIONSHIP, stanzaTopic, OBO.SCHEMA_TERM_TYPEDEF, OBO.createTopicForTerm(tm,relatedTerm.getTerm()), OBO.SCHEMA_TERM_RELATED_TO);
}
}
// ******** SUBSET - CATEGORY *********
else if("subset".equals(tag)) {
processSubset(stanzaTopic, value);
}
// ******** NAMESPACE *********
else if("namespace".equals(tag)) {
createAssociation(OBO.SCHEMA_TERM_NAMESPACE, stanzaTopic, OBO.SCHEMA_TERM_TYPEDEF, OBO.createTopicForSchemaTerm(tm,value), OBO.SCHEMA_TERM_NAMESPACE);
}
// ***** SYNONYMS *****
else if("narrow_synonym".equals(tag)) {
logDeprecation(tag, id, "synonym");
processSynonym(stanzaTopic, "NARROW", value, namespace);
}
else if("broad_synonym".equals(tag)) {
logDeprecation(tag, id, "synonym");
processSynonym(stanzaTopic, "BROAD", value, namespace);
}
else if("exact_synonym".equals(tag)) {
logDeprecation(tag, id, "synonym");
processSynonym(stanzaTopic, "EXACT", value, namespace);
}
else if("related_synonym".equals(tag)) {
logDeprecation(tag, id, "synonym");
processSynonym(stanzaTopic, "RELATED", value, namespace);
}
else if("synonym".equals(tag)) {
processSynonym(stanzaTopic, value, namespace);
}
// ******** CONSIDER USING ********
else if("consider".equals(tag)) {
createAssociation(OBO.SCHEMA_TERM_CONSIDER_USING, stanzaTopic, OBO.SCHEMA_TERM_TYPEDEF, OBO.createTopicForTerm(tm, value), OBO.SCHEMA_TERM_CONSIDER_USING);
}
else if("use_term".equals(tag)) {
logDeprecation(tag, id, "consider");
createAssociation(OBO.SCHEMA_TERM_CONSIDER_USING, stanzaTopic, OBO.SCHEMA_TERM_TYPEDEF, OBO.createTopicForTerm(tm, value), OBO.SCHEMA_TERM_CONSIDER_USING);
}
else if("replaced_by".equals(tag)) {
createAssociation(OBO.SCHEMA_TERM_REPLACED_BY, stanzaTopic, OBO.SCHEMA_TERM_TYPEDEF, OBO.createTopicForTerm(tm, value), OBO.SCHEMA_TERM_REPLACED_BY);
}
// ****** OCCURRENCES ******
else if("def".equals(tag)) {
defCount++;
if(defCount > 1) {
parent.log("Error: More that one definition in '"+id+"'.");
}
else {
processDefinition(stanzaTopic, value, OBO.SCHEMA_TERM_TERM, namespace);
}
}
else if("comment".equals(tag)) {
commentCount++;
if(commentCount > 1) {
parent.log("Error: More that one comment in '"+id+"'.");
}
else {
Topic commentType = OBO.createTopicForSchemaTerm(tm, OBO.SCHEMA_TERM_COMMENT);
setData(stanzaTopic, commentType, OBO.LANG, OBO.OBO2Java(value));
}
}
// ***** TYPEDEF SPECIFIC RELATIONS *******
else if("domain".equals(tag)) {
createAssociation(OBO.SCHEMA_TERM_DOMAIN, stanzaTopic, OBO.SCHEMA_TERM_TYPEDEF, OBO.createTopicForSchemaTerm(tm,value), OBO.SCHEMA_TERM_DOMAIN);
}
else if("range".equals(tag)) {
createAssociation(OBO.SCHEMA_TERM_RANGE, stanzaTopic, OBO.SCHEMA_TERM_TYPEDEF, OBO.createTopicForSchemaTerm(tm,value), OBO.SCHEMA_TERM_RANGE);
}
else if("inverse_of".equals(tag)) {
createAssociation(OBO.SCHEMA_TERM_INVERSE_OF, stanzaTopic, OBO.SCHEMA_TERM_TYPEDEF, OBO.createTopicForSchemaTerm(tm,value), OBO.SCHEMA_TERM_INVERSE_OF);
}
else if("is_transitive".equals(tag)) {
createAssociation(OBO.SCHEMA_TERM_IS_TRANSITIVE, stanzaTopic, OBO.SCHEMA_TERM_TYPEDEF, OBO.createTopicForSchemaTerm(tm,value), OBO.SCHEMA_TERM_IS_TRANSITIVE);
}
else if("is_transitive_over".equals(tag)) {
createAssociation(OBO.SCHEMA_TERM_IS_TRANSITIVE_OVER, stanzaTopic, OBO.SCHEMA_TERM_TYPEDEF, OBO.createTopicForSchemaTerm(tm,value), OBO.SCHEMA_TERM_IS_TRANSITIVE_OVER);
}
else if("transitive_over".equals(tag)) {
createAssociation(OBO.SCHEMA_TERM_IS_TRANSITIVE_OVER, stanzaTopic, OBO.SCHEMA_TERM_TYPEDEF, OBO.createTopicForSchemaTerm(tm,value), OBO.SCHEMA_TERM_IS_TRANSITIVE_OVER);
}
else if("is_reflexive".equals(tag)) {
createAssociation(OBO.SCHEMA_TERM_IS_REFLEXIVE, stanzaTopic, OBO.SCHEMA_TERM_TYPEDEF, OBO.createTopicForSchemaTerm(tm,value), OBO.SCHEMA_TERM_IS_REFLEXIVE);
}
else if("is_cyclic".equals(tag)) {
createAssociation(OBO.SCHEMA_TERM_IS_CYCLIC, stanzaTopic, OBO.SCHEMA_TERM_TYPEDEF, OBO.createTopicForSchemaTerm(tm,value), OBO.SCHEMA_TERM_IS_CYCLIC);
}
else if("is_symmetric".equals(tag)) {
createAssociation(OBO.SCHEMA_TERM_IS_SYMMETRIC, stanzaTopic, OBO.SCHEMA_TERM_TYPEDEF, OBO.createTopicForSchemaTerm(tm,value), OBO.SCHEMA_TERM_IS_SYMMETRIC);
}
else if("is_anti_symmetric".equals(tag)) {
createAssociation(OBO.SCHEMA_TERM_IS_ANTISYMMETRIC, stanzaTopic,OBO.SCHEMA_TERM_TYPEDEF, OBO.createTopicForSchemaTerm(tm,value), OBO.SCHEMA_TERM_IS_ANTISYMMETRIC);
}
else if("is_metadata_tag".equals(tag)) {
createAssociation(OBO.SCHEMA_TERM_IS_METADATA_TAG, stanzaTopic, OBO.SCHEMA_TERM_TYPEDEF, OBO.createTopicForSchemaTerm(tm,value), OBO.SCHEMA_TERM_IS_METADATA_TAG);
}
else if("is_class_level".equals(tag)) {
createAssociation(OBO.SCHEMA_TERM_IS_CLASS_LEVEL, stanzaTopic, OBO.SCHEMA_TERM_TYPEDEF, OBO.createTopicForSchemaTerm(tm,value), OBO.SCHEMA_TERM_IS_CLASS_LEVEL);
}
else if("holds_over_chain".equals(tag)) {
createAssociation(OBO.SCHEMA_TERM_HOLS_CHAIN_OVER, stanzaTopic, OBO.SCHEMA_TERM_TYPEDEF, OBO.createTopicForSchemaTerm(tm,value), OBO.SCHEMA_TERM_HOLS_CHAIN_OVER);
}
else if("expand_assertion_to".equals(tag)) {
createAssociation(OBO.SCHEMA_TERM_EXPAND_ASSERTION, stanzaTopic, OBO.SCHEMA_TERM_TYPEDEF, OBO.createTopicForAssertionExpansion(tm,value), OBO.SCHEMA_TERM_EXPAND_ASSERTION);
}
// ******** IS_ANONYMOUS *********
else if("is_anonymous".equals(tag)) {
createAssociation(OBO.SCHEMA_TERM_IS_ANONYMOUS, stanzaTopic, OBO.SCHEMA_TERM_TYPEDEF, OBO.createTopicForSchemaTerm(tm,value), OBO.SCHEMA_TERM_IS_ANONYMOUS);
}
// ******** OBSOLETE *********
else if("is_obsolete".equals(tag)) {
if("true".equalsIgnoreCase(value) || "1".equalsIgnoreCase(value)) {
stanzaTopic.addType(OBO.createObsoleteTopic(tm, namespace));
}
}
else {
parent.log("Unprocessed typedef tag found!\n tag: '"+tag+"'\n value: '"+value+"'");
}
}
catch(Exception ei) {
parent.log("Exception while processing '"+tag+"' and value '"+value+"'.");
parent.log(ei);
}
}
// **** POSTPROCESS ****
}
catch(Exception e) {
parent.log(e);
}
}
private void processTermStanza(Stanza stanza) {
if(tm == null || stanza == null) return;
try {
String id = stanza.getId();
String name = stanza.getName();
String namespace = solveNamespace(stanza, id, header, "obo-term");
parent.addNamespace(namespace);
Topic stanzaTopic = OBO.createTopicForTerm(tm, id, name, namespace);
ArrayList<TagValuePair> tagValuePairs = stanza.getTagValuePairs();
TagValuePair tagValue = null;
String tag = null;
String value = null;
ArrayList<T2<String, String>> modifiers = null;
String comment = null;
int defCount = 0;
int commentCount = 0;
for(Iterator<TagValuePair> i=tagValuePairs.iterator(); i.hasNext() && !parent.forceStop(); ) {
try {
tagValue = i.next();
tag = tagValue.getTag();
value = tagValue.getValueWithoutModifiers();
modifiers = tagValue.getModifiers();
comment = tagValue.getComment();
if(false && debug) {
System.out.println("---------------------------------");
System.out.println("id: "+ id);
System.out.println("tag: "+ tag);
System.out.println("value: "+ value);
System.out.println("modifiers:");
for(Iterator<T2<String,String>> mi=modifiers.iterator(); mi.hasNext();) {
T2<String,String> mo = mi.next();
System.out.println(" "+mo.e1+":"+mo.e2);
}
System.out.println("comment: "+ comment);
}
// **** PROCESS CURRENT TAG AND VALUE ****
if("alt_id".equals(tag)) {
if(OBO.MAKE_SIS_FROM_ALT_IDS) {
try {
stanzaTopic.addSubjectIdentifier(OBO.makeLocator(value));
}
catch(Exception e) {
parent.log(e);
}
}
else {
createAssociation(OBO.SCHEMA_TERM_ALTERNATIVE_ID, stanzaTopic, OBO.SCHEMA_TERM_TERM, OBO.createTopicForTerm(tm,value), OBO.SCHEMA_TERM_ALTERNATIVE_ID);
}
}
// ***** XREFS *****
else if("xref_unknown".equals(tag)) {
logDeprecation(tag, id, "xref");
processXref(stanzaTopic, "UNKNOWN", value, namespace, OBO.SCHEMA_TERM_TERM);
}
else if("xref_analog".equals(tag)) {
logDeprecation(tag, id, "xref");
processXref(stanzaTopic, "ANALOG", value, namespace, OBO.SCHEMA_TERM_TERM);
}
else if("xref".equals(tag)) {
processXref(stanzaTopic, null, value, namespace, OBO.SCHEMA_TERM_TERM);
}
// ***** SYNONYMS *****
else if("narrow_synonym".equals(tag)) {
logDeprecation(tag, id, "synonym");
processSynonym(stanzaTopic, "NARROW", value, namespace);
}
else if("broad_synonym".equals(tag)) {
logDeprecation(tag, id, "synonym");
processSynonym(stanzaTopic, "BROAD", value, namespace);
}
else if("exact_synonym".equals(tag)) {
logDeprecation(tag, id, "synonym");
processSynonym(stanzaTopic, "EXACT", value, namespace);
}
else if("related_synonym".equals(tag)) {
logDeprecation(tag, id, "synonym");
processSynonym(stanzaTopic, "RELATED", value, namespace);
}
else if("synonym".equals(tag)) {
processSynonym(stanzaTopic, value, namespace);
}
// ********* ISA *********
else if("is_a".equals(tag)) {
createAssociation(OBO.SCHEMA_TERM_SUPERCLASS_SUBCLASS, stanzaTopic, OBO.SCHEMA_TERM_SUBCLASS, OBO.createTopicForTerm(tm,value), OBO.SCHEMA_TERM_SUPERCLASS);
}
// ********* SUBSET *********
else if("subset".equals(tag)) {
processSubset(stanzaTopic, value);
}
// ******** NAMESPACE *********
else if("namespace".equals(tag)) {
createAssociation(OBO.SCHEMA_TERM_NAMESPACE, stanzaTopic, OBO.SCHEMA_TERM_TERM, OBO.createTopicForSchemaTerm(tm,value), OBO.SCHEMA_TERM_NAMESPACE);
}
// ****** RELATIONSHIP ********
else if("relationship".equals(tag)) {
RelatedTerm relatedTerm = new RelatedTerm(value);
if(relatedTerm.getTerm() != null && relatedTerm.getModifier() != null ) {
createAssociation(relatedTerm.getModifier(), stanzaTopic, OBO.SCHEMA_TERM_TERM, OBO.createTopicForTerm(tm,relatedTerm.getTerm()), OBO.SCHEMA_TERM_RELATED_TO);
}
else if(relatedTerm.getTerm() != null) {
createAssociation(OBO.SCHEMA_TERM_RELATIONSHIP, stanzaTopic, OBO.SCHEMA_TERM_TERM, OBO.createTopicForTerm(tm,relatedTerm.getTerm()), OBO.SCHEMA_TERM_RELATED_TO);
}
}
// ****** PROPERTY_VALUE ********
else if("property_value".equals(tag)) {
processProperty(stanzaTopic, OBO.createTopicForSchemaTerm(tm, OBO.SCHEMA_TERM_TERM), value);
}
// ****** INTERSECTION OF ********
else if("intersection_of".equals(tag)) {
RelatedTerm relatedTerm = new RelatedTerm(value);
if(relatedTerm.getTerm() != null && relatedTerm.getModifier() != null ) {
createAssociation(OBO.SCHEMA_TERM_INTERSECTION_OF, stanzaTopic, OBO.SCHEMA_TERM_TERM, OBO.createTopicForTerm(tm,relatedTerm.getTerm()), OBO.SCHEMA_TERM_RELATED_TO, OBO.createTopicForModifier(tm,relatedTerm.getModifier()), OBO.SCHEMA_TERM_MODIFIER);
}
else if(relatedTerm.getTerm() != null) {
createAssociation(OBO.SCHEMA_TERM_INTERSECTION_OF, stanzaTopic, OBO.SCHEMA_TERM_TERM, OBO.createTopicForTerm(tm,relatedTerm.getTerm()), OBO.SCHEMA_TERM_RELATED_TO);
}
}
// ****** UNION OF ********
else if("union_of".equals(tag)) {
RelatedTerm relatedTerm = new RelatedTerm(value);
if(relatedTerm.getTerm() != null && relatedTerm.getModifier() != null ) {
createAssociation(OBO.SCHEMA_TERM_UNION_OF, stanzaTopic, OBO.SCHEMA_TERM_TERM, OBO.createTopicForTerm(tm,relatedTerm.getTerm()), OBO.SCHEMA_TERM_RELATED_TO, OBO.createTopicForModifier(tm,relatedTerm.getModifier()), OBO.SCHEMA_TERM_MODIFIER);
}
else if(relatedTerm.getTerm() != null) {
createAssociation(OBO.SCHEMA_TERM_UNION_OF, stanzaTopic, OBO.SCHEMA_TERM_TERM, OBO.createTopicForTerm(tm,relatedTerm.getTerm()), OBO.SCHEMA_TERM_RELATED_TO);
}
}
// ****** DISJOINT FROM ********
else if("disjoint_from".equals(tag)) {
RelatedTerm relatedTerm = new RelatedTerm(value);
if(relatedTerm.getTerm() != null && relatedTerm.getModifier() != null ) {
createAssociation(OBO.SCHEMA_TERM_DISJOINT_FROM, stanzaTopic, OBO.SCHEMA_TERM_TERM, OBO.createTopicForTerm(tm,relatedTerm.getTerm()), OBO.SCHEMA_TERM_RELATED_TO, OBO.createTopicForModifier(tm,relatedTerm.getModifier()), OBO.SCHEMA_TERM_MODIFIER);
}
else if(relatedTerm.getTerm() != null) {
createAssociation(OBO.SCHEMA_TERM_DISJOINT_FROM, stanzaTopic, OBO.SCHEMA_TERM_TERM, OBO.createTopicForTerm(tm,relatedTerm.getTerm()), OBO.SCHEMA_TERM_RELATED_TO);
}
}
// ****** PART-OF *******
else if("part_of".equals(tag)) {
RelatedTerm relatedTerm = new RelatedTerm(value);
if(relatedTerm.getTerm() != null && relatedTerm.getModifier() != null ) {
createAssociation(OBO.SCHEMA_TERM_PART_OF, stanzaTopic, OBO.SCHEMA_TERM_TERM, OBO.createTopicForTerm(tm,value), OBO.SCHEMA_TERM_RELATED_TO, OBO.createTopicForModifier(tm,relatedTerm.getModifier()), OBO.SCHEMA_TERM_MODIFIER);
}
else if(relatedTerm.getTerm() != null) {
createAssociation(OBO.SCHEMA_TERM_PART_OF, stanzaTopic, OBO.SCHEMA_TERM_TERM, OBO.createTopicForTerm(tm,value), OBO.SCHEMA_TERM_RELATED_TO);
}
}
else if("has_part".equals(tag)) {
RelatedTerm relatedTerm = new RelatedTerm(value);
if(relatedTerm.getTerm() != null && relatedTerm.getModifier() != null ) {
createAssociation(OBO.SCHEMA_TERM_PART_OF, stanzaTopic, OBO.SCHEMA_TERM_RELATED_TO, OBO.createTopicForTerm(tm,value), OBO.SCHEMA_TERM_TERM, OBO.createTopicForModifier(tm,relatedTerm.getModifier()), OBO.SCHEMA_TERM_MODIFIER);
}
else if(relatedTerm.getTerm() != null) {
createAssociation(OBO.SCHEMA_TERM_PART_OF, stanzaTopic, OBO.SCHEMA_TERM_RELATED_TO, OBO.createTopicForTerm(tm,value), OBO.SCHEMA_TERM_TERM);
}
}
else if("integral_part_of".equals(tag)) {
logDeprecation(tag, id, "part_of");
createAssociation(OBO.SCHEMA_TERM_PART_OF, stanzaTopic, OBO.SCHEMA_TERM_TERM, OBO.createTopicForTerm(tm,value), OBO.SCHEMA_TERM_RELATED_TO, OBO.createTopicForModifier(tm,"INTEGRAL"), OBO.SCHEMA_TERM_MODIFIER);
}
else if("proper_part_of".equals(tag)) {
logDeprecation(tag, id, "part_of");
createAssociation(OBO.SCHEMA_TERM_PART_OF, stanzaTopic, OBO.SCHEMA_TERM_TERM, OBO.createTopicForTerm(tm,value), OBO.SCHEMA_TERM_RELATED_TO, OBO.createTopicForModifier(tm,"PROPER"), OBO.SCHEMA_TERM_MODIFIER);
}
else if("improper_part_of".equals(tag)) {
logDeprecation(tag, id, "part_of");
createAssociation(OBO.SCHEMA_TERM_PART_OF, stanzaTopic, OBO.SCHEMA_TERM_TERM, OBO.createTopicForTerm(tm,value), OBO.SCHEMA_TERM_RELATED_TO, OBO.createTopicForModifier(tm,"IMPROPER"), OBO.SCHEMA_TERM_MODIFIER);
}
else if("has_improper_part".equals(tag)) {
logDeprecation(tag, id, "part_of");
createAssociation(OBO.SCHEMA_TERM_PART_OF, stanzaTopic, OBO.SCHEMA_TERM_RELATED_TO, OBO.createTopicForTerm(tm,value), OBO.SCHEMA_TERM_TERM, OBO.createTopicForModifier(tm,"IMPROPER"), OBO.SCHEMA_TERM_MODIFIER);
}
else if("adjacent_to".equals(tag)) {
createAssociation(OBO.SCHEMA_TERM_ADJACENT_TO, stanzaTopic, OBO.SCHEMA_TERM_TERM, OBO.createTopicForTerm(tm,value), OBO.SCHEMA_TERM_RELATED_TO);
}
// ******** LOCATION_OF *******
else if("located_in".equals(tag)) {
createAssociation(OBO.SCHEMA_TERM_LOCATED_IN, stanzaTopic, OBO.SCHEMA_TERM_TERM, OBO.createTopicForTerm(tm,value), OBO.SCHEMA_TERM_RELATED_TO);
}
else if("location_of".equals(tag)) {
createAssociation(OBO.SCHEMA_TERM_LOCATED_IN, stanzaTopic, OBO.SCHEMA_TERM_RELATED_TO, OBO.createTopicForTerm(tm,value), OBO.SCHEMA_TERM_TERM);
}
// ******** CONTAINS *******
else if("contained_in".equals(tag)) {
createAssociation(OBO.SCHEMA_TERM_CONTAINS, stanzaTopic, OBO.SCHEMA_TERM_TERM, OBO.createTopicForTerm(tm,value), OBO.SCHEMA_TERM_RELATED_TO);
}
else if("contains".equals(tag)) {
createAssociation(OBO.SCHEMA_TERM_CONTAINS, stanzaTopic, OBO.SCHEMA_TERM_RELATED_TO, OBO.createTopicForTerm(tm,value), OBO.SCHEMA_TERM_TERM);
}
// ******** TRANSFORMATION *******
else if("transformation_of".equals(tag)) {
createAssociation(OBO.SCHEMA_TERM_TRANSFORMATION_OF, stanzaTopic, OBO.SCHEMA_TERM_TERM, OBO.createTopicForTerm(tm,value), OBO.SCHEMA_TERM_RELATED_TO);
}
else if("transformed_into".equals(tag)) {
logDeprecation(tag, id, "transformation_of");
createAssociation(OBO.SCHEMA_TERM_TRANSFORMATION_OF, stanzaTopic, OBO.SCHEMA_TERM_RELATED_TO, OBO.createTopicForTerm(tm,value), OBO.SCHEMA_TERM_TERM);
}
// ******** DERIVES *******
else if("derives_from".equals(tag)) {
createAssociation(OBO.SCHEMA_TERM_DERIVES_FROM, stanzaTopic, OBO.SCHEMA_TERM_TERM, OBO.createTopicForTerm(tm,value), OBO.SCHEMA_TERM_RELATED_TO);
}
else if("derives_into".equals(tag)) {
createAssociation(OBO.SCHEMA_TERM_DERIVES_FROM, stanzaTopic, OBO.SCHEMA_TERM_RELATED_TO, OBO.createTopicForTerm(tm,value), OBO.SCHEMA_TERM_TERM);
}
// ******* PRECEDES ********
else if("preceded_by".equals(tag)) {
createAssociation(OBO.SCHEMA_TERM_PRECEDED_BY, stanzaTopic, OBO.SCHEMA_TERM_TERM, OBO.createTopicForTerm(tm,value), OBO.SCHEMA_TERM_RELATED_TO);
}
else if("precedes".equals(tag)) {
createAssociation(OBO.SCHEMA_TERM_PRECEDED_BY, stanzaTopic, OBO.SCHEMA_TERM_RELATED_TO, OBO.createTopicForTerm(tm,value), OBO.SCHEMA_TERM_TERM);
}
// ******* PARTICIPATES *******
else if("has_participant".equals(tag)) {
createAssociation(OBO.SCHEMA_TERM_PARTICIPATES_IN, stanzaTopic, OBO.SCHEMA_TERM_TERM, OBO.createTopicForTerm(tm,value), OBO.SCHEMA_TERM_RELATED_TO);
}
else if("participates_in".equals(tag)) {
createAssociation(OBO.SCHEMA_TERM_PARTICIPATES_IN, stanzaTopic, OBO.SCHEMA_TERM_RELATED_TO, OBO.createTopicForTerm(tm,value), OBO.SCHEMA_TERM_TERM);
}
// ******* AGENT-IN ******
else if("has_agent".equals(tag)) {
createAssociation(OBO.SCHEMA_TERM_AGENT_IN, stanzaTopic, OBO.SCHEMA_TERM_TERM, OBO.createTopicForTerm(tm,value), OBO.SCHEMA_TERM_RELATED_TO);
}
else if("agent_in".equals(tag)) {
createAssociation(OBO.SCHEMA_TERM_AGENT_IN, stanzaTopic, OBO.SCHEMA_TERM_RELATED_TO, OBO.createTopicForTerm(tm,value), OBO.SCHEMA_TERM_TERM);
}
// ****** CONSIDER ******
else if("consider".equals(tag)) {
createAssociation(OBO.SCHEMA_TERM_CONSIDER_USING, stanzaTopic, OBO.SCHEMA_TERM_TERM, OBO.createTopicForTerm(tm,value), OBO.SCHEMA_TERM_CONSIDER_USING);
}
else if("use_term".equals(tag)) {
logDeprecation(tag, id, "consider");
createAssociation(OBO.SCHEMA_TERM_CONSIDER_USING, stanzaTopic, OBO.SCHEMA_TERM_TERM, OBO.createTopicForTerm(tm,value), OBO.SCHEMA_TERM_CONSIDER_USING);
}
else if("replaced_by".equals(tag)) {
createAssociation(OBO.SCHEMA_TERM_REPLACED_BY, stanzaTopic, OBO.SCHEMA_TERM_TERM, OBO.createTopicForTerm(tm,value), OBO.SCHEMA_TERM_REPLACED_BY);
}
// ****** OCCURRENCES ******
else if("def".equals(tag)) {
defCount++;
if(defCount > 1) {
parent.log("Error: More that one definition in '"+id+"'.");
}
else {
processDefinition(stanzaTopic, value, OBO.SCHEMA_TERM_TERM, namespace);
}
}
else if("comment".equals(tag)) {
commentCount++;
if(commentCount > 1) {
parent.log("Error: More that one comment in '"+id+"'.");
}
else {
Topic commentType = OBO.createTopicForSchemaTerm(tm,"comment");
setData(stanzaTopic, commentType, OBO.LANG, OBO.OBO2Java(value));
}
}
// ******** IS_ANONYMOUS *********
else if("is_anonymous".equals(tag)) {
createAssociation(OBO.SCHEMA_TERM_IS_ANONYMOUS, stanzaTopic, OBO.SCHEMA_TERM_TERM, OBO.createTopicForSchemaTerm(tm,value), OBO.SCHEMA_TERM_IS_ANONYMOUS);
}
// ******** OBSOLETE TERM *********
else if("is_obsolete".equals(tag)) {
if("true".equalsIgnoreCase(value) || "1".equalsIgnoreCase(value)) {
stanzaTopic.addType(OBO.createObsoleteTopic(tm, namespace));
}
}
// ******** CREATED *********
else if("created_by".equals(tag)) {
createAssociation(OBO.SCHEMA_TERM_CREATED_BY, stanzaTopic, OBO.SCHEMA_TERM_TERM, OBO.createTopicForAuthor(tm,value,namespace), OBO.SCHEMA_TERM_CREATED_BY);
}
else if("creation_date".equals(tag)) {
Topic creationDateType = OBO.createTopicForSchemaTerm(tm,"creation_date");
setData(stanzaTopic, creationDateType, OBO.LANG, OBO.OBO2Java(value));
}
else {
parent.log("Unprocessed term tag found!\n tag: '"+tag+"'\n value: '"+value+"'");
}
}
catch(Exception ei) {
parent.log("Exception while processing '"+tag+"' and value '"+value+"'.");
parent.log(ei);
}
}
// **** POSTPROCESS ****
}
catch(Exception e) {
parent.log(e);
}
}
private void processInstanceStanza(Stanza stanza) {
if(tm == null || stanza == null) return;
try {
String id = stanza.getId();
String name = stanza.getName();
String namespace = solveNamespace(stanza, id, header, "obo-instance");
parent.addNamespace(namespace);
Topic stanzaTopic = OBO.createTopicForInstance(tm,id, name, namespace);
String tag = null;
String value = null;
ArrayList<T2<String, String>> modifiers = null;
String comment = null;
TagValuePair tagValue = null;
ArrayList<TagValuePair> tagValuePairs = stanza.getTagValuePairs();
int commentCount = 0;
for(Iterator<TagValuePair> i=tagValuePairs.iterator(); i.hasNext() && !parent.forceStop(); ) {
try {
tagValue = i.next();
tag = tagValue.getTag();
value = tagValue.getValueWithoutModifiers();
modifiers = tagValue.getModifiers();
comment = tagValue.getComment();
if(false && debug) {
System.out.println("---------------------------------");
System.out.println("id: "+ id);
System.out.println("tag: "+ tag);
System.out.println("value: "+ value);
System.out.println("modifiers:");
for(Iterator<T2<String,String>> mi=modifiers.iterator(); mi.hasNext();) {
T2<String,String> mo = mi.next();
System.out.println(" "+mo.e1+":"+mo.e2);
}
System.out.println("comment: "+ comment);
}
// **** PROCESS CURRENT TAG AND VALUE ****
if("alt_id".equals(tag)) {
if(OBO.MAKE_SIS_FROM_ALT_IDS) {
try {
stanzaTopic.addSubjectIdentifier(OBO.makeLocator(value));
}
catch(Exception e) {
parent.log(e);
}
}
else {
createAssociation(OBO.SCHEMA_TERM_ALTERNATIVE_ID, stanzaTopic, OBO.SCHEMA_TERM_INSTANCE, OBO.createTopicForTerm(tm,value), OBO.SCHEMA_TERM_ALTERNATIVE_ID);
}
}
// ******** NAMESPACE *********
else if("namespace".equals(tag)) {
createAssociation(OBO.SCHEMA_TERM_NAMESPACE, stanzaTopic, OBO.SCHEMA_TERM_INSTANCE, OBO.createTopicForSchemaTerm(tm,value), OBO.SCHEMA_TERM_NAMESPACE);
}
// ****** INSTANCE OF *******
else if("instance_of".equals(tag)) {
createAssociation(OBO.SCHEMA_TERM_INSTANCE_OF, stanzaTopic, OBO.SCHEMA_TERM_INSTANCE, OBO.createTopicForTerm(tm,value), OBO.SCHEMA_TERM_TERM);
}
// ******* PROPERTY VALUE *******
else if("property_value".equals(tag)) {
processProperty(stanzaTopic, OBO.createTopicForSchemaTerm(tm, OBO.SCHEMA_TERM_INSTANCE), value);
}
// ***** XREFS *****
else if("xref_unknown".equals(tag)) {
logDeprecation(tag, id, "xref");
processXref(stanzaTopic, "UNKNOWN", value, namespace, OBO.SCHEMA_TERM_INSTANCE);
}
else if("xref_analog".equals(tag)) {
logDeprecation(tag, id, "xref");
processXref(stanzaTopic, "ANALOG", value, namespace, OBO.SCHEMA_TERM_INSTANCE);
}
else if("xref".equals(tag)) {
processXref(stanzaTopic, null, value, namespace, OBO.SCHEMA_TERM_INSTANCE);
}
// ***** SYNONYMS *****
else if("narrow_synonym".equals(tag)) {
logDeprecation(tag, id, "synonym");
processSynonym(stanzaTopic, "NARROW", value, namespace);
}
else if("broad_synonym".equals(tag)) {
logDeprecation(tag, id, "synonym");
processSynonym(stanzaTopic, "BROAD", value, namespace);
}
else if("exact_synonym".equals(tag)) {
logDeprecation(tag, id, "synonym");
processSynonym(stanzaTopic, "EXACT", value, namespace);
}
else if("related_synonym".equals(tag)) {
logDeprecation(tag, id, "synonym");
processSynonym(stanzaTopic, "RELATED", value, namespace);
}
else if("synonym".equals(tag)) {
processSynonym(stanzaTopic, value, namespace);
}
// ******** CONSIDER INSTANCE **********
else if("consider".equals(tag)) {
createAssociation(OBO.SCHEMA_TERM_CONSIDER_USING, stanzaTopic, OBO.SCHEMA_TERM_INSTANCE, OBO.createTopicForTerm(tm,value), OBO.SCHEMA_TERM_CONSIDER_USING);
}
else if("use_term".equals(tag)) {
logDeprecation(tag, id, "consider");
createAssociation(OBO.SCHEMA_TERM_CONSIDER_USING, stanzaTopic, OBO.SCHEMA_TERM_INSTANCE, OBO.createTopicForTerm(tm,value), OBO.SCHEMA_TERM_CONSIDER_USING);
}
else if("replaced_by".equals(tag)) {
createAssociation(OBO.SCHEMA_TERM_REPLACED_BY, stanzaTopic, OBO.SCHEMA_TERM_INSTANCE, OBO.createTopicForTerm(tm,value), OBO.SCHEMA_TERM_REPLACED_BY);
}
// ****** OCCURRENCES ******
else if("comment".equals(tag)) {
commentCount++;
if(commentCount > 1) {
parent.log("Error: More that one comment in '"+id+"'.");
}
else {
Topic commentType = OBO.createTopicForSchemaTerm(tm,"comment");
setData(stanzaTopic, commentType, OBO.LANG, OBO.OBO2Java(value));
}
}
// ******** IS_ANONYMOUS *********
else if("is_anonymous".equals(tag)) {
createAssociation(OBO.SCHEMA_TERM_IS_ANONYMOUS, stanzaTopic, OBO.SCHEMA_TERM_INSTANCE, OBO.createTopicForSchemaTerm(tm,value), OBO.SCHEMA_TERM_IS_ANONYMOUS);
}
// ******* IS OBSOLE *********
else if("is_obsolete".equals(tag)) {
if("true".equalsIgnoreCase(value) || "1".equalsIgnoreCase(value)) {
stanzaTopic.addType(OBO.createObsoleteTopic(tm, namespace));
}
}
else {
parent.log("Unprocessed instance tag found!\n tag: '"+tag+"'\n value: '"+value+"'");
}
}
catch(Exception ei) {
parent.log("Exception while processing '"+tag+"' and value '"+value+"'.");
parent.log(ei);
}
}
// **** POSTPROCESS ****
}
catch(Exception e) {
parent.log(e);
}
}
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
private String solveNamespace(Stanza stanza, String id, Header header, String defaultNamespace) {
String namespace = null;
if(stanza != null) namespace = stanza.getNameSpace();
if(namespace == null && header != null) namespace = header.getDefaultNameSpace();
if(namespace == null && id != null) {
String[] idParts = id.split(":");
if(idParts.length > 1) namespace = idParts[0].toLowerCase();
}
if(namespace == null) namespace = defaultNamespace;
return namespace;
}
public void logDeprecation(String tag, String id) {
logDeprecation(tag, id, null);
}
public void logDeprecation(String tag, String id, String replacingTag) {
if(deprecationMsgLimit > 0) {
deprecationMsgLimit--;
if(replacingTag != null) {
parent.log("Warning: Deprecated tag '"+tag+"' used in '"+id+"'. Use '"+replacingTag+"' instead.");
}
else {
parent.log("Warning: Deprecated tag '"+tag+"' used in '"+id+"'.");
}
if(deprecationMsgLimit == 0) {
parent.log("Supressing further deprecation messages.");
}
}
}
public void processSubset(Topic stanzaTopic, String value) {
if(value != null) {
try {
String category = value.trim();
Topic categoryTopic = OBO.createTopicForCategory(tm, category);
createAssociation(OBO.SCHEMA_TERM_CATEGORY, stanzaTopic, OBO.SCHEMA_TERM_MEMBER, categoryTopic, OBO.SCHEMA_TERM_CATEGORY);
if(!header.isSubset(category)) {
parent.log("Error: Subset category '"+value+"' not defined in header!");
}
}
catch(Exception e) {
parent.log(e);
}
}
}
public void processDefinition(Topic stanzaTopic, String value, String stanzatype, String namespace) {
try {
Definition definition = new Definition(value);
Dbxrefs dbxrefs = definition.getOrigins();
if(dbxrefs != null) {
Dbxref[] origins = dbxrefs.toDbxrefArray();
if(origins != null && origins.length > 0) {
for(int k=0; k<origins.length; k++) {
Dbxref origin = origins[k];
if(origin != null) {
String description = origin.getDescription();
if(OBO.MAKE_DESCRIPTION_TOPICS && description != null && description.length() > 0) {
createAssociation(OBO.SCHEMA_TERM_DEFINITION_ORIGIN, stanzaTopic, stanzatype, OBO.createTopicForDbxref(tm,origin.getId()), OBO.SCHEMA_TERM_DEFINITION_ORIGIN, OBO.createTopicForDescription(tm,description, namespace), OBO.SCHEMA_TERM_DESCRIPTION);
}
else {
createAssociation(OBO.SCHEMA_TERM_DEFINITION_ORIGIN, stanzaTopic, stanzatype, OBO.createTopicForDbxref(tm,origin.getId(),origin.getDescription()), OBO.SCHEMA_TERM_DEFINITION_ORIGIN);
}
}
}
}
}
Topic definitionType = OBO.createTopicForSchemaTerm(tm, OBO.SCHEMA_TERM_DEFINITION);
setData(stanzaTopic, definitionType, OBO.LANG, OBO.OBO2Java(definition.getDefinition()));
}
catch(Exception e) {
parent.log(e);
}
}
public void processXref(Topic stanzaTopic, String scope, String everything, String namespace, String stanzatype) {
Dbxrefs dbxrefs = new Dbxrefs(everything);
Dbxref[] xrefs = dbxrefs.toDbxrefArray();
if(stanzatype == null) stanzatype = "term";
for(int i=0; i<xrefs.length; i++) {
try {
Association a = null;
String description = xrefs[i].getDescription();
if(OBO.MAKE_DESCRIPTION_TOPICS && description != null && description.length() > 0) {
a = createAssociation(OBO.SCHEMA_TERM_XREF, stanzaTopic, stanzatype, OBO.createTopicForDbxref(tm, xrefs[i].getId()), OBO.SCHEMA_TERM_XREF, OBO.createTopicForDescription(tm, description, namespace), OBO.SCHEMA_TERM_DESCRIPTION);
}
else {
a = createAssociation(OBO.SCHEMA_TERM_XREF, stanzaTopic, stanzatype, OBO.createTopicForDbxref(tm, xrefs[i].getId(), xrefs[i].getDescription()), OBO.SCHEMA_TERM_XREF);
}
if(OBO.USE_SCOPED_XREFS && scope != null && a != null) {
a.addPlayer(OBO.createTopicForSchemaTerm(tm,scope), OBO.createTopicForSchemaTerm(tm,OBO.SCHEMA_TERM_XREF_SCOPE));
}
}
catch(Exception e) {
parent.log(e);
}
}
}
public void processSynonym(Topic base, String everything, String namespace) {
processSynonym(base, null, everything, namespace);
}
public void processSynonym(Topic base, String synonymScope, String everything, String namespace) {
try {
String synonymType = null;
Synonym synonym = new Synonym(everything);
if(synonymScope == null) synonymScope = synonym.getScope();
if(synonymType == null) synonymType = synonym.getType();
//if(synonymType == null) synonymType = header.getDefaultSynonymType();
if(synonym.getSynonym() != null) {
Dbxrefs originDbxrefs = synonym.getOrigins();
Dbxref[] origins = null;
if(originDbxrefs != null) origins = originDbxrefs.toDbxrefArray();
if(origins == null || origins.length == 0) origins = new Dbxref[] { new Dbxref("", null) };
for(int o=0; o<origins.length; o++) {
Dbxref origin = origins[o];
Topic associationTypeTypeTopic = OBO.createTopicForSchemaTerm(tm, OBO.SCHEMA_TERM_ASSOCIATION_TYPE);
Topic associationType = OBO.createTopicForSchemaTerm(tm, OBO.SCHEMA_TERM_SYNONYM);
associationType.addType(associationTypeTypeTopic);
Association a = tm.createAssociation(associationType);
a.addPlayer(base, OBO.createTopicForSchemaTerm(tm,OBO.SCHEMA_TERM_TERM));
Topic nameTopic = OBO.createTopicForSynonym(tm,synonym.getSynonym(), namespace);
a.addPlayer(nameTopic, OBO.createTopicForSchemaTerm(tm,OBO.SCHEMA_TERM_SYNONYM));
Topic nameTypeTopic = OBO.createSynonymTopic(tm, namespace);
nameTopic.addType(nameTypeTopic);
if(synonymType != null) {
Topic synonymTypeTopic = OBO.createTopicForSchemaTerm(tm,synonymType);
String typeDescription = header.getDefaultSynonymDescription(synonymType);
if(header.getDefaultSynonymScope(synonymType) != null) {
synonymScope = header.getDefaultSynonymScope(synonymType);
}
if(typeDescription != null && typeDescription.length() > 0) {
Topic descriptionType = OBO.createTopicForSchemaTerm(tm,OBO.SCHEMA_TERM_DESCRIPTION);
this.setData(synonymTypeTopic, descriptionType, OBO.LANG, typeDescription);
}
a.addPlayer(synonymTypeTopic, OBO.createTopicForSchemaTerm(tm,OBO.SCHEMA_TERM_SYNONYM_TYPE));
}
if(synonymScope != null) {
a.addPlayer(OBO.createTopicForSchemaTerm(tm,synonymScope), OBO.createTopicForSchemaTerm(tm,OBO.SCHEMA_TERM_SYNONYM_SCOPE));
}
if(origin != null && origin.getId() != null && origin.getId().length() > 0) {
String odescription = origin.getDescription();
if(OBO.MAKE_DESCRIPTION_TOPICS && odescription != null && odescription.length() > 0) {
a.addPlayer(OBO.createTopicForDbxref(tm,origin.getId()), OBO.createTopicForSchemaTerm(tm,OBO.SCHEMA_TERM_SYNONYM_ORIGIN));
a.addPlayer(OBO.createTopicForDescription(tm, odescription, namespace), OBO.createTopicForSchemaTerm(tm,OBO.SCHEMA_TERM_DESCRIPTION));
}
else {
a.addPlayer(OBO.createTopicForDbxref(tm,origin.getId(), odescription), OBO.createTopicForSchemaTerm(tm,OBO.SCHEMA_TERM_SYNONYM_ORIGIN));
}
}
}
}
}
catch(Exception e) {
parent.log(e);
}
}
public void processProperty(Topic base, Topic baseType, String everything) {
PropertyValue property = new PropertyValue(everything);
if(property.getRelationship() != null && property.getValue() != null) {
try {
Topic propertyRelationshipTopic = OBO.createTopicForPropertyRelationship(tm, property.getRelationship());
Topic propertyRelationshipType = OBO.createPropertyRelationshipTopic(tm);
Topic propertyValueTopic = OBO.createTopicForPropertyValue(tm, property.getValue());
Topic propertyValueType = OBO.createPropertyValueTopic(tm);
Association a = tm.createAssociation(propertyRelationshipType);
a.addPlayer(propertyRelationshipTopic, propertyRelationshipType);
a.addPlayer(base, baseType);
a.addPlayer(propertyValueTopic, propertyValueType);
if(property.getDatatype() != null) {
Topic propertyDatatypeTopic = OBO.createTopicForPropertyDatatype(tm, property.getDatatype());
Topic propertyDatatypeType = OBO.createPropertyDatatypeTopic(tm);
a.addPlayer(propertyDatatypeTopic, propertyDatatypeType);
}
}
catch(Exception e) {
parent.log(e);
}
}
}
// ---------------------------------------------------------------------
// ---------------------------------------------- TOPIC MAP HELPERS ----
// ---------------------------------------------------------------------
public Association createAssociation(String associationType, Topic player1Topic, String role1, Topic player2Topic, String role2) throws TopicMapException {
Topic associationTypeTopic = OBO.createTopicForSchemaTerm(tm,associationType);
Association association = tm.createAssociation(associationTypeTopic);
Topic associationTypeTypeTopic = OBO.createTopicForSchemaTerm(tm, OBO.SCHEMA_TERM_ASSOCIATION_TYPE);
associationTypeTopic.addType(associationTypeTypeTopic);
Topic role1Topic = OBO.createTopicForSchemaTerm(tm,role1);
Topic role2Topic = OBO.createTopicForSchemaTerm(tm,role2);
association.addPlayer(player1Topic, role1Topic);
association.addPlayer(player2Topic, role2Topic);
return association;
}
public Association createAssociation(String associationType, Topic player1Topic, String role1, Topic player2Topic, String role2, Topic player3Topic, String role3) throws TopicMapException {
Topic associationTypeTopic = OBO.createTopicForSchemaTerm(tm,associationType);
Association association = tm.createAssociation(associationTypeTopic);
Topic associationTypeTypeTopic = OBO.createTopicForSchemaTerm(tm, OBO.SCHEMA_TERM_ASSOCIATION_TYPE);
associationTypeTopic.addType(associationTypeTypeTopic);
Topic role1Topic = OBO.createTopicForSchemaTerm(tm,role1);
Topic role2Topic = OBO.createTopicForSchemaTerm(tm,role2);
Topic role3Topic = OBO.createTopicForSchemaTerm(tm,role3);
association.addPlayer(player1Topic, role1Topic);
association.addPlayer(player2Topic, role2Topic);
association.addPlayer(player3Topic, role3Topic);
return association;
}
public Association createAssociation(String associationType, Topic player1Topic, String role1, Topic player2Topic, String role2, Topic player3Topic, String role3, Topic player4Topic, String role4) throws TopicMapException {
Topic associationTypeTopic = OBO.createTopicForSchemaTerm(tm,associationType);
Association association = tm.createAssociation(associationTypeTopic);
Topic associationTypeTypeTopic = OBO.createTopicForSchemaTerm(tm, OBO.SCHEMA_TERM_ASSOCIATION_TYPE);
associationTypeTopic.addType(associationTypeTypeTopic);
Topic role1Topic = OBO.createTopicForSchemaTerm(tm,role1);
Topic role2Topic = OBO.createTopicForSchemaTerm(tm,role2);
Topic role3Topic = OBO.createTopicForSchemaTerm(tm,role3);
Topic role4Topic = OBO.createTopicForSchemaTerm(tm,role4);
association.addPlayer(player1Topic, role1Topic);
association.addPlayer(player2Topic, role2Topic);
association.addPlayer(player3Topic, role3Topic);
association.addPlayer(player4Topic, role4Topic);
return association;
}
// ---------------------------------------------------------------------
private Topic getOrCreateTopic(String si, String basename) {
return getOrCreateTopic(new Locator(si), basename);
}
private Topic getOrCreateTopic(String si) {
return getOrCreateTopic(new Locator(si), null);
}
private Topic getOrCreateTopic(Locator si, String basename) {
if(tm == null) return null;
Topic topic = null;
try {
topic = tm.getTopic(si);
if(topic == null) {
topic = tm.createTopic();
topic.addSubjectIdentifier(si);
if(basename != null) topic.setBaseName(OBO.OBO2Java(basename));
}
}
catch(Exception e) {
parent.log(e);
}
return topic;
}
private void setData(Topic t, Topic type, String lang, String text) throws TopicMapException {
if(t != null & type != null && lang != null && text != null) {
String langsi=XTMPSI.getLang("en");
Topic langT=t.getTopicMap().getTopic(langsi);
if(langT == null) {
langT = t.getTopicMap().createTopic();
langT.addSubjectIdentifier(new Locator(langsi));
try {
langT.setBaseName("Language " + lang.toUpperCase());
}
catch (Exception e) {
langT.setBaseName("Language " + langsi);
}
}
t.setData(type, langT, text);
}
}
private void makeSubclassOf(Topic t, Topic superclass) {
try {
Topic supersubClassTopic = getOrCreateTopic(XTMPSI.SUPERCLASS_SUBCLASS, OBO.SCHEMA_TERM_SUPERCLASS_SUBCLASS);
Topic subclassTopic = getOrCreateTopic(XTMPSI.SUBCLASS, OBO.SCHEMA_TERM_SUBCLASS);
Topic superclassTopic = getOrCreateTopic(XTMPSI.SUPERCLASS, OBO.SCHEMA_TERM_SUPERCLASS);
Association ta = tm.createAssociation(supersubClassTopic);
ta.addPlayer(t, subclassTopic);
ta.addPlayer(superclass, superclassTopic);
}
catch(Exception e) {
parent.log(e);
}
}
}
// -------------------------------------------------------------------------
// ----------------------------------------------------- HELPER CLASSES ----
// -------------------------------------------------------------------------
protected class Header {
private String defaultNameSpace = null;
private HashMap<String,String> idMapping = new HashMap<String,String>();
private HashMap<String,String[]> idSpaceMapping = new HashMap<String,String[]>();
private HashMap<String,String[]> synonymTypes = new HashMap<String,String[]>();
private String defaultRelationshipIdPrefix = null;
private HashMap<String,Category> subsets = new HashMap<String,Category>();
private ArrayList<TagValuePair> tagValuePairs = new ArrayList<TagValuePair>();
private ArrayList<String> comments = new ArrayList<String>();
public Header() {
defaultNameSpace = "obo";
}
public void addTagValuePair(String tag, String value, String comment) {
if("default-namespace".equals(tag)) {
defaultNameSpace = value;
}
else if("id-mapping".equals(tag)) {
if(value != null) {
value = value.trim();
String[] mapping = value.split(" ");
if(mapping.length == 2) {
idMapping.put(mapping[0], mapping[1]);
}
else {
}
}
}
else if("idspace".equals(tag)) {
if(value != null) {
value = value.trim();
int splitpoint = value.indexOf(" ");
if(splitpoint != -1) {
String source = value.substring(0, splitpoint);
String target = value.substring(splitpoint);
String description = null;
splitpoint = target.indexOf(" ");
if(splitpoint != -1) {
target = target.substring(0, splitpoint);
description = target.substring(splitpoint);
}
idSpaceMapping.put(source, new String[] { target, description });
}
else {
idSpaceMapping.put(value, new String[] { null, null });
}
}
}
else if("synonymtypedef".equals(tag)) {
if(value != null) {
value = value.trim();
Pattern synonymTypeDefinitionPattern = Pattern.compile("(\\S+)(\\s+"+OBO.QUOTE_STRING_PATTERN+"(\\s+(\\S+))?)?");
Matcher m = synonymTypeDefinitionPattern.matcher(value);
String defaultSynonymType = value;
String defaultSynonymTypeDescription = null;
String defaultSynonymTypeScope = null;
if(m.matches()) {
if(m.groupCount() > 0) {
defaultSynonymType = m.group(1);
}
if(m.groupCount() > 2) {
defaultSynonymTypeDescription = m.group(3);
}
if(m.groupCount() > 4) {
defaultSynonymTypeScope = m.group(5);
}
}
synonymTypes.put(defaultSynonymType, new String[] { defaultSynonymTypeDescription, defaultSynonymTypeScope } );
}
}
else if("default-relationship-id-prefix".equals(tag)) {
defaultRelationshipIdPrefix = value;
}
else if("subsetdef".equals(tag)) {
Category subset = new Category(value);
subsets.put(subset.getId(), subset);
}
// STORE ALL TAG-VALUES
tagValuePairs.add(new TagValuePair(tag, value, comment));
}
public void addComment(String comment) {
comments.add(comment);
}
public int size() {
return tagValuePairs.size();
}
public ArrayList<TagValuePair> getTagValuePairs() {
return tagValuePairs;
}
public String getDefaultNameSpace() {
return defaultNameSpace;
}
public String getMapping(String source) {
String target = idMapping.get(source);
if(target != null) return target;
else return source;
}
public String getDefaultSynonymType() {
Set<String> types = synonymTypes.keySet();
if(types != null && !types.isEmpty()) {
return (String) types.iterator().next();
}
return null;
}
public String getDefaultSynonymDescription(String type) {
String description = synonymTypes.get(type)[0];
return description;
}
public String getDefaultSynonymScope(String type) {
String scope = synonymTypes.get(type)[1];
return scope;
}
public String getDefaultRelationshipIdPrefix() {
return defaultRelationshipIdPrefix;
}
public boolean isSubset(String key) {
Set<String> keys = subsets.keySet();
if(keys != null) return keys.contains(key);
return false;
}
public String[] getSubsets() {
Set<String> keys = subsets.keySet();
if(keys != null) return keys.toArray( new String[] {} );
return new String[] {};
}
public String getSubsetDescription(String key) {
Category c = subsets.get(key);
if(c != null) return c.getDescription();
return null;
}
}
// -------------------------------------------------------------------------
protected class Stanza {
private String type = "";
private String nameSpace = null;
private String id = null;
private String name = null;
private boolean isObsolete = false;
private ArrayList<TagValuePair> tagValuePairs = new ArrayList<TagValuePair>();
private ArrayList<String> comments = new ArrayList<String>();
public Stanza(String type) {
this.type = type;
}
public void addTagValuePair(String tag, String value, String comment) {
if("id".equals(tag)) id = value;
else if("name".equals(tag)) name = value;
else {
if("namespace".equals(tag)) nameSpace = value;
else if("is_obsolete".equals(tag) && "true".equalsIgnoreCase(value)) isObsolete = true;
tagValuePairs.add(new TagValuePair(tag, value, comment));
}
}
public void addComment(String comment) {
comments.add(comment);
}
public int size() {
return tagValuePairs.size();
}
public String getType() {
return type;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getNameSpace() {
return nameSpace;
}
public ArrayList<TagValuePair> getTagValuePairs() {
return tagValuePairs;
}
public boolean isObsolete() {
return isObsolete;
}
}
// -------------------------------------------------------------------------
protected class TagValuePair {
private String tag = null;
private String value = null;
private String comment = null;
public TagValuePair(String tag, String value, String comment) {
this.tag = tag;
this.value = value;
this.comment = comment;
}
public String getTag() {
return tag;
}
public String getValue() {
return value;
}
public String getComment() {
return comment;
}
public String getValueWithoutModifiers() {
if(value == null) return null;
String valueWithoutModifiers = value;
/*
int modifierIndex = valueWithoutModifiers.indexOf('{');
if(modifierIndex != -1) {
valueWithoutModifiers = valueWithoutModifiers.substring(0, modifierIndex);
valueWithoutModifiers = valueWithoutModifiers.trim();
}
*/
String preModifierString = null;
boolean precedesBackslash = true;
int splitPoint = valueWithoutModifiers.indexOf('{');
while(splitPoint > -1) {
preModifierString = value.substring(0, splitPoint);
precedesBackslash = (splitPoint > 0 ? value.charAt(splitPoint-1) == '\\' : false);
if(!precedesBackslash) {
int quoteCounter = 0;
int findPoint = preModifierString.indexOf("\"");
while(findPoint > -1) {
precedesBackslash = (findPoint > 0 ? value.charAt(findPoint-1) == '\\' : false);
if(!precedesBackslash) quoteCounter++;
findPoint = preModifierString.indexOf("\"", findPoint+1);
}
if(((quoteCounter % 2) == 0)) {
//modifierString = value.substring(splitPoint+1).trim();
valueWithoutModifiers = preModifierString;
break;
}
}
splitPoint = valueWithoutModifiers.indexOf('{', splitPoint+1);
}
return valueWithoutModifiers;
}
public ArrayList<T2<String, String>> getModifiers() {
if(value == null) return null;
ArrayList<T2<String, String>> modifiers = new ArrayList<T2<String, String>>();
String modifierString = null;
/*
int modifierIndex = value.indexOf('{');
if(modifierIndex != -1) {
modifierString = value.substring(modifierIndex);
}
*/
String preModifierString = null;
boolean precedesBackslash = true;
int splitPoint = value.indexOf('{');
while(splitPoint > -1) {
preModifierString = value.substring(0, splitPoint);
precedesBackslash = (splitPoint > 0 ? value.charAt(splitPoint-1) == '\\' : false);
if(!precedesBackslash) {
int quoteCounter = 0;
int findPoint = preModifierString.indexOf("\"");
while(findPoint > -1) {
precedesBackslash = (findPoint > 0 ? value.charAt(findPoint-1) == '\\' : false);
if(!precedesBackslash) quoteCounter++;
findPoint = preModifierString.indexOf("\"", findPoint+1);
}
if(((quoteCounter % 2) == 0)) {
modifierString = value.substring(splitPoint+1).trim();
value = preModifierString;
break;
}
}
splitPoint = value.indexOf('{', splitPoint+1);
}
if(modifierString != null && modifierString.length() > 0) {
int i = modifierString.indexOf('=');
String modName = null;
String modValue = null;
while(i > 0 && i < modifierString.length()) {
modName = modifierString.substring(0, i).trim();
modValue = null;
StringBuilder modValueBuffer = new StringBuilder("");
// ***** Pass preceeding spaces!
i++;
while(i<modifierString.length() && Character.isSpaceChar(modifierString.charAt(i))) {
i++;
}
// ***** Check if the value is "String" or just value.
if(i<modifierString.length() && (modifierString.charAt(i) == '\"' || modifierString.charAt(i) == '\'')) {
char startChar = modifierString.charAt(i);
i++;
while(i<modifierString.length() && (modifierString.charAt(i) != startChar || modifierString.charAt(i) == '\\')) {
modValueBuffer.append(modifierString.charAt(i));
i++;
}
while(i<modifierString.length() && modifierString.charAt(i) == ',' && modifierString.charAt(i) == '}' ) {
i++;
}
modValue = modValueBuffer.toString();
}
// ***** Found just value!
else {
while(i<modifierString.length() && modifierString.charAt(i) == ',' && modifierString.charAt(i) == '}' ) {
modValueBuffer.append(modifierString.charAt(i));
i++;
}
modValue = modValueBuffer.toString().trim();
}
// ***** Finally add the modifier if name is reasonable!
if(modName != null) {
modifiers.add(new T2<String, String>(modName, modValue) );
}
modifierString = modifierString.substring(i);
i = modifierString.indexOf('=');
}
}
return modifiers;
}
}
// -------------------------------------------------------------------------
protected class RelatedTerm {
private String term = null;
private String modifier = null;
private Pattern withModifierPattern = Pattern.compile("(.+)\\s+(.+\\:.+)");
private Pattern withUncertainModifierPattern = Pattern.compile("(.+)\\s+(.+)");
public RelatedTerm(String everything) {
parseRelatedTerm(everything);
}
public void parseRelatedTerm(String str) {
str = str.trim();
boolean parsed = false;
if(!parsed) {
Matcher m = withModifierPattern.matcher(str);
if(m.matches()) {
if(m.group(1) != null && m.group(1).length() > 0) modifier = m.group(1);
if(m.group(2) != null && m.group(2).length() > 0) term = m.group(2);
parsed = true;
}
}
if(!parsed) {
Matcher m = withUncertainModifierPattern.matcher(str);
if(m.matches()) {
if(m.group(1) != null && m.group(1).length() > 0) modifier = m.group(1);
if(m.group(2) != null && m.group(2).length() > 0) term = m.group(2);
parsed = true;
}
}
if(!parsed) {
term = str;
}
}
public String getTerm() {
return term;
}
public String getModifier() {
return modifier;
}
}
// -------------------------------------------------------------------------
protected class Synonym {
private String synonym = null;
private String type = null;
private String scope = null;
private Dbxrefs origins = null;
private Pattern STOSynonymPattern = Pattern.compile(OBO.QUOTE_STRING_PATTERN+"\\s+(\\w+\\S*)\\s+(\\w+\\S*)\\s+\\[(.*)\\]");
private Pattern SOSynonymPattern = Pattern.compile(OBO.QUOTE_STRING_PATTERN+"\\s+(\\w+\\S*)\\s+\\[(.*)\\]");
private Pattern STSynonymPattern = Pattern.compile(OBO.QUOTE_STRING_PATTERN+"\\s+(\\w+\\S*)\\s+(\\w+\\S*)");
private Pattern SSynonymPattern = Pattern.compile(OBO.QUOTE_STRING_PATTERN+"\\s+(\\w+\\S*)");
private Pattern OSynonymPattern = Pattern.compile(OBO.QUOTE_STRING_PATTERN+"\\s+\\[(.*)\\]");
private Pattern plainStringPattern = Pattern.compile(OBO.QUOTE_STRING_PATTERN);
public Synonym(String everything) {
parseSynonym(everything);
}
public void parseSynonym(String str) {
str = str.trim();
//System.out.println("parsing synonym: "+str);
boolean parsed = false;
if(!parsed) {
Matcher m = STOSynonymPattern.matcher(str);
if(m.matches()) {
if(m.group(1) != null && m.group(1).length() > 0) synonym = m.group(1);
if(m.group(2) != null && m.group(2).length() > 0) scope = m.group(2);
if(m.group(3) != null && m.group(3).length() > 0) type = m.group(3);
if(m.group(4) != null && m.group(4).length() > 0) origins = new Dbxrefs(m.group(4));
//System.out.println("found synonym 1: "+synonym);
parsed = true;
}
}
if(!parsed) {
Matcher m = SOSynonymPattern.matcher(str);
if(m.matches()) {
if(m.group(1) != null && m.group(1).length() > 0) synonym = m.group(1);
if(m.group(2) != null && m.group(2).length() > 0) scope = m.group(2);
if(m.group(3) != null && m.group(3).length() > 0) origins = new Dbxrefs(m.group(3));
//System.out.println("found synonym 2: "+synonym);
parsed = true;
}
}
if(!parsed) {
Matcher m = STSynonymPattern.matcher(str);
if(m.matches()) {
if(m.group(1) != null && m.group(1).length() > 0) synonym = m.group(1);
if(m.group(2) != null && m.group(2).length() > 0) scope = m.group(2);
if(m.group(3) != null && m.group(3).length() > 0) type = m.group(3);
//System.out.println("found synonym 3: "+synonym);
parsed = true;
}
}
if(!parsed) {
Matcher m = SSynonymPattern.matcher(str);
if(m.matches()) {
if(m.group(1) != null && m.group(1).length() > 0) synonym = m.group(1);
if(m.group(2) != null && m.group(2).length() > 0) scope = m.group(2);
//System.out.println("found synonym 4: "+synonym);
parsed = true;
}
}
if(!parsed) {
Matcher m = OSynonymPattern.matcher(str);
if(m.matches()) {
if(m.group(1) != null && m.group(1).length() > 0) synonym = m.group(1);
if(m.group(2) != null && m.group(2).length() > 0) origins = new Dbxrefs(m.group(2));
//System.out.println("found synonym 5: "+synonym);
parsed = true;
}
}
if(!parsed) {
Matcher m = plainStringPattern.matcher(str);
if(m.matches()) {
//System.out.println("found synonym 6: "+synonym);
if(m.group(1) != null && m.group(1).length() > 0) synonym = m.group(1);
parsed = true;
}
}
if(!parsed) {
synonym = str;
//System.out.println("found synonym 7: "+synonym);
}
}
public String getSynonym() {
return synonym;
}
public String getType() {
return type;
}
public String getScope() {
return scope;
}
public Dbxrefs getOrigins() {
return origins;
}
}
// -------------------------------------------------------------------------
protected class Definition {
private String definition = null;
private Dbxrefs origins = null;
//private Pattern definitionPattern = Pattern.compile(OBO.QUOTE_STRING_PATTERN+"\\s+\\[(.*)\\]");
//private Pattern textPattern = Pattern.compile(OBO.QUOTE_STRING_PATTERN);
//private Pattern definitionPattern = Pattern.compile("\"(.*)\""+"\\s+\\[(.*)\\]");
//private Pattern textPattern = Pattern.compile("\"(.*)\"");
public Definition(String everything) {
parse(everything);
}
public void parse(String str) {
str = str.trim();
boolean parsed = false;
if(!parsed) {
Pattern definitionPattern = Pattern.compile(OBO.QUOTE_STRING_PATTERN+"\\s+\\[(.*)\\]");
Matcher m = definitionPattern.matcher(str);
if(m.matches()) {
if(m.group(1) != null && m.group(1).length() > 0) definition = m.group(1);
if(m.group(2) != null && m.group(2).length() > 0) origins = new Dbxrefs(m.group(2));
parsed = true;
}
}
if(!parsed) {
Pattern textPattern = Pattern.compile(OBO.QUOTE_STRING_PATTERN);
Matcher m = textPattern.matcher(str);
if(m.matches()) {
if(m.group(1) != null && m.group(1).length() > 0) definition = m.group(1);
parsed = true;
}
}
if(!parsed) {
definition = str;
}
}
public String getDefinition() {
return definition;
}
public Dbxrefs getOrigins() {
return origins;
}
}
// -------------------------------------------------------------------------
protected class Category {
private String id = null;
private String description = null;
public Category(String everything) {
parse(everything);
}
Pattern fullCategoryPattern = Pattern.compile("(\\S+)\\s+"+OBO.QUOTE_STRING_PATTERN);
public void parse(String str) {
str = str.trim();
boolean parsed = false;
if(!parsed) {
Matcher m = fullCategoryPattern.matcher(str);
if(m.matches()) {
if(m.group(1) != null && m.group(1).length() > 0) id = m.group(1);
if(m.group(2) != null && m.group(2).length() > 0) description = m.group(2);
parsed = true;
}
}
if(!parsed) {
id = str;
}
}
public String getDescription() {
return description;
}
public String getId() {
return id;
}
}
// -------------------------------------------------------------------------
protected class Dbxrefs {
private ArrayList<Dbxref> xrefs = new ArrayList<Dbxref>();
//private Pattern dbxrefPattern = Pattern.compile("(\\w+[^\\,]+)(\\s+\"([^\"]*)\")?");
private Pattern dbxrefPattern = Pattern.compile("((?:[^\\,\"]|(?<=\\\\)\\,|(?<=\\\\)\")+)(\\s*"+OBO.QUOTE_STRING_PATTERN+")?");
public Dbxrefs(String everything) {
parse(everything);
}
public void parse(String str){
Matcher om = dbxrefPattern.matcher(str);
int startpoint = 0;
while(om.find(startpoint)) {
if(om.group(0) != null && om.group(0).length() > 0) {
Dbxref dbxref = null;
if(om.groupCount() > 2) {
dbxref = new Dbxref(om.group(1), om.group(3));
}
else {
dbxref = new Dbxref(om.group(1), null);
}
xrefs.add(dbxref);
startpoint = om.end(0);
}
}
}
public Dbxref[] toDbxrefArray() {
return xrefs.toArray(new Dbxref[] {} );
}
public ArrayList<Dbxref> getDbxrefs() {
return xrefs;
}
}
// -------------------------------------------------------------------------
protected class Dbxref {
private String id = null;
private String description = null;
public Dbxref(String id, String description) {
this.id = (id != null ? id.trim() : id);
this.description = description;
}
public String getDescription() {
return description;
}
public String getId() {
return id;
}
}
protected class PropertyValue {
private String relationship = null;
private String value = null;
private String datatype = null;
private Pattern propertyPattern1 = Pattern.compile("(\\w+[^\\s]+)\\s+"+OBO.QUOTE_STRING_PATTERN+"\\s*(\\w+[^\\s]+)?");
private Pattern propertyPattern2 = Pattern.compile("(\\w+[^\\s]+)\\s+(\\w+[^\\s]+)\\s*?");
public PropertyValue(String everything) {
parse(everything);
}
public void parse(String str){
Matcher m = propertyPattern1.matcher(str);
if(m.matches()) {
if(m.group(1) != null && m.group(1).length() > 0) relationship = m.group(1);
if(m.group(2) != null && m.group(2).length() > 0) value = m.group(2);
if(m.group(3) != null && m.group(3).length() > 0) datatype = m.group(3);
}
else {
m = propertyPattern2.matcher(str);
if(m.matches()) {
if(m.group(0) != null && m.group(0).length() > 0) relationship = m.group(0);
if(m.group(1) != null && m.group(1).length() > 0) value = m.group(1);
}
}
}
public String getRelationship() {
return relationship;
}
public String getValue() {
return value;
}
public String getDatatype() {
return datatype;
}
}
}
| 112,407 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SimpleRDFImport.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/importers/SimpleRDFImport.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* SimpleRDFLocalImport.java
*
* Created on 24. toukokuuta 2006, 20:38
*/
package org.wandora.application.tools.importers;
import java.io.InputStream;
import java.util.List;
import javax.swing.Icon;
import org.apache.jena.rdf.model.AnonId;
import org.apache.jena.rdf.model.Literal;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.Property;
import org.apache.jena.rdf.model.RDFList;
import org.apache.jena.rdf.model.RDFNode;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.rdf.model.Statement;
import org.apache.jena.rdf.model.StmtIterator;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.gui.UIBox;
import org.wandora.application.tools.extractors.rdf.rdfmappings.RDFMapping;
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.TopicMapReadOnlyException;
import org.wandora.topicmap.TopicTools;
import org.wandora.topicmap.XTMPSI;
/**
* <p>
* SimpleRDFImport is used to import and convert RDF files (including RDFS and
* OWL files) to topic maps.
* </p>
*
* @author akivela
*/
public class SimpleRDFImport extends AbstractImportTool implements WandoraTool {
private static final long serialVersionUID = 1L;
public static final String anonSIPrefix="http://wandora.org/si/rdf/anon/";
/**
* Creates a new instance of SimpleRDFLocalImport
*/
public SimpleRDFImport() {
}
public SimpleRDFImport(int options) {
setOptions(options);
}
@Override
public void initialize(Wandora wandora,org.wandora.utils.Options options,String prefix) throws TopicMapException {
String o=options.get(prefix+"options");
if(o!=null){
int i=Integer.parseInt(o);
setOptions(i);
}
}
@Override
public boolean isConfigurable(){
return true;
}
@Override
public void configure(Wandora wandora,org.wandora.utils.Options options,String prefix) throws TopicMapException {
System.out.println(prefix);
ImportConfiguration dialog=new ImportConfiguration(wandora,true);
dialog.setOptions(getOptions());
dialog.setVisible(true);
if(!dialog.wasCancelled()){
int i=dialog.getOptions();
setOptions(i);
options.put(prefix+"options",""+i);
}
}
@Override
public void writeOptions(Wandora wandora,org.wandora.utils.Options options,String prefix){
options.put(prefix+"options",""+getOptions());
}
@Override
public String getName() {
return "Simple RDF XML import";
}
@Override
public String getDescription() {
return "Tool imports RDF XML file and merges RDF triplets to current topic map. \n"+
"Used schema is very simple: Resources are mapped to topics, literals are \n"+
"mapped to occurrences and triplets to binary associations.";
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/import_rdf.png");
}
@Override
public void importStream(Wandora wandora, String streamName, InputStream inputStream) {
try {
try {
wandora.getTopicMap().clearTopicMapIndexes();
}
catch(Exception e) {
log(e);
}
TopicMap map = null;
if(directMerge) {
map = solveContextTopicMap(wandora, getContext());
}
else {
map = new org.wandora.topicmap.memory.TopicMapImpl();
}
importRDF(inputStream, map);
if(!directMerge) {
if(newLayer) {
createNewLayer(map, streamName, wandora);
}
else {
log("Merging '" + streamName + "'.");
solveContextTopicMap(wandora, getContext()).mergeIn(map);
}
}
}
catch(TopicMapReadOnlyException tmroe) {
log("Topic map is write protected. Import failed.");
}
catch(Exception e) {
log("Reading '" + streamName + "' failed.", e);
}
}
public void importRDF(InputStream in, TopicMap map) {
if(in != null) {
// create an empty model
Model model = ModelFactory.createDefaultModel();
// read the RDF/XML file
model.read(in, "");
RDF2TopicMap(model, map);
}
}
public static final String occurrenceScopeSI = TMBox.LANGINDEPENDENT_SI;
public static final String subjectTypeSI = "http://wandora.org/si/core/rdf-subject";
public static final String objectTypeSI = "http://wandora.org/si/core/rdf-object";
public static final String predicateTypeSI = "http://wandora.org/si/core/rdf-predicate";
public static final String RDF_LIST_ORDER="http://wandora.org/si/rdf/list_order";
public void handleStatement(Statement stmt,TopicMap map,Topic subjectType,Topic predicateType,Topic objectType) throws TopicMapException {
Resource subject = stmt.getSubject(); // get the subject
Property predicate = stmt.getPredicate(); // get the predicate
RDFNode object = stmt.getObject(); // get the object
String lan = null;
String predicateS=predicate.toString();
if(predicateS!=null && (
predicateS.equals(RDFMapping.RDF_NS+"first") ||
predicateS.equals(RDFMapping.RDF_NS+"rest") ) ) {
// skip broken down list statements, the list
// should be handled properly when they are the object
// of some other statement
return;
}
Topic subjectTopic = getOrCreateTopic(map, subject);
Topic predicateTopic = getOrCreateTopic(map, predicate);
subjectTopic.addType(subjectType);
predicateTopic.addType(predicateType);
if(object.isLiteral()) {
try { lan = stmt.getLanguage(); } catch(Exception e) { /*NOTHING!*/ }
if(lan==null || lan.length()==0) {
subjectTopic.setData(predicateTopic, getOrCreateTopic(map, occurrenceScopeSI), ((Literal) object).getString());
}
else {
subjectTopic.setData(predicateTopic, getOrCreateTopic(map, XTMPSI.getLang(lan)), ((Literal) object).getString());
}
}
else if(object.isResource()) {
if(object.canAs(RDFList.class)){
List<RDFNode> list=((RDFList)object.as(RDFList.class)).asJavaList();
int counter=1;
Topic orderRole = getOrCreateTopic(map, RDF_LIST_ORDER);
for(RDFNode listObject : list){
if(!listObject.isResource()){
log("List element is not a resource, skipping.");
continue;
}
Topic objectTopic = getOrCreateTopic(map, listObject.toString());
objectTopic.addType(objectType);
Topic orderTopic = getOrCreateTopic(map, RDF_LIST_ORDER+"/"+counter);
if(orderTopic.getBaseName()==null) orderTopic.setBaseName(""+counter);
Association association = map.createAssociation(predicateTopic);
association.addPlayer(subjectTopic, subjectType);
association.addPlayer(objectTopic, objectType);
association.addPlayer(orderTopic, orderRole);
counter++;
}
}
else {
Topic objectTopic = getOrCreateTopic(map, (Resource)object);
Association association = map.createAssociation(predicateTopic);
association.addPlayer(subjectTopic, subjectType);
association.addPlayer(objectTopic, objectType);
objectTopic.addType(objectType);
}
}
else if(object.isURIResource()) {
log("URIResource found but not handled!");
}
}
public void RDF2TopicMap(Model model, TopicMap map) {
// list the statements in the Model
StmtIterator iter = model.listStatements();
// Topic subjectTopic = null;
// Topic predicateTopic = null;
// Topic objectTopic = null;
// Association association = null;
Statement stmt = null;
// Resource subject = null;
// Property predicate = null;
// RDFNode object = null;
int counter = 0;
Topic subjectType = getOrCreateTopic(map, subjectTypeSI);
Topic predicateType = getOrCreateTopic(map, predicateTypeSI);
Topic objectType = getOrCreateTopic(map, objectTypeSI);
// print out the predicate, subject and object of each statement
while (iter.hasNext() && !forceStop()) {
try {
stmt = iter.nextStatement(); // get next statement
handleStatement(stmt,map,subjectType,predicateType,objectType);
}
catch(Exception e) {
e.printStackTrace();
}
counter++;
setProgress((counter/1000) % 100);
if(counter % 1000 == 0) hlog("RDF statements processed: " + counter);
/*
System.out.print(subject.toString());
System.out.print(" " + predicate.toString() + " ");
if (object instanceof Resource) {
System.out.print(object.toString());
} else {
// object is a literal
System.out.print(" \"" + object.toString() + "\"");
}
System.out.println(" .");
**/
}
log("Total RDF statements processed: " + counter);
}
// -------------------------------------------------------------------------
public Topic getOrCreateTopic(TopicMap map, Resource res) {
String uri=res.getURI();
if(uri==null) {
try{
AnonId id=res.getId();
uri=anonSIPrefix+TopicTools.cleanDirtyLocator(id.toString());
}catch(Exception e){}
}
if(uri==null) {
log("Warning, can't resolve uri for resource "+res.toString()+". Making random uri.");
uri=map.makeSubjectIndicator();
}
return getOrCreateTopic(map,uri);
}
public Topic getOrCreateTopic(TopicMap map, String si) {
Topic topic = null;
try {
topic = map.getTopic(si);
if(topic == null) {
topic = map.createTopic();
topic.addSubjectIdentifier(new Locator(si));
}
}
catch(Exception e) {
e.printStackTrace();
}
return topic;
}
@Override
public String getGUIText(int textType) {
switch(textType) {
case FILE_DIALOG_TITLE_TEXT: {
return "Select RDF(S) or OWL file to import";
}
case URL_DIALOG_MESSAGE_TEXT: {
return "Type internet address of a RDF(S) or OWL document to be imported";
}
}
return "";
}
}
| 12,563 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
OBO.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/importers/OBO.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*/
package org.wandora.application.tools.importers;
import java.io.File;
import java.io.FileInputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import org.wandora.application.tools.exporters.OBOExport;
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.TopicTools;
import org.wandora.topicmap.XTMPSI;
import org.wandora.utils.IObox;
/**
* This class is a static library for OBOImport, OBOExport, and OBORoundtrip
* tools. Library contains shared constants and services used to
* map OBO (Open Biological Ontologies) elements to Topic Maps and vice versa.
*
* @author akivela
*/
public class OBO {
public static final String optionPrefix = "obo.";
public static boolean COLLATE_SIMILAR_SYNONYMS = true;
public static boolean MAKE_DESCRIPTION_TOPICS = true;
public static boolean MAKE_SIS_FROM_ALT_IDS = false;
public static boolean USE_SCOPED_XREFS = true;
public static boolean PROCESS_HEADER_IMPORTS = true;
public static final String QUOTE_STRING_PATTERN = "\"([^\"\\\\]*(?:\\\\.[^\"\\\\]*)*)\"";
//public static final String QUOTE_STRING_PATTERN = "\"((?:[^\"]|(?<=\\\\)\")*)\"";
public static String LANG = "en";
public static final String SI = "http://wandora.org/si/obo/";
public static final String SCHEMA_SI = SI + "schema/";
public static final String HEADER_SI = SI + "header/";
public static final String DBXREF_SI = SI + "dbxref/";
public static final String SCHEMA_TERM_ID = "obo-id";
public static final String SCHEMA_TERM_ALTERNATIVE_ID = "alternative-id";
//public static final String SCHEMA_TERM_DBXREF_DESCRIPTION = "dbxref-description";
public static final String SCHEMA_TERM_DEFINITION = "definition";
public static final String SCHEMA_TERM_DEFINITION_ORIGIN = "definition-origin";
public static final String SCHEMA_TERM_COMMENT = "comment";
public static final String SCHEMA_TERM_ASSOCIATION_TYPE = "association-type";
public static final String SCHEMA_TERM_DESCRIPTION = "dbxref-description";
public static final String SCHEMA_TERM_MEMBER = "member";
public static final String SCHEMA_TERM_CATEGORY = "category";
public static final String SCHEMA_TERM_SUPERCLASS_SUBCLASS = "superclass-subclass";
public static final String SCHEMA_TERM_SUPERCLASS = "superclass";
public static final String SCHEMA_TERM_SUBCLASS = "subclass";
public static final String SCHEMA_TERM_TERM = "term";
public static final String SCHEMA_TERM_TYPEDEF = "typedef";
public static final String SCHEMA_TERM_INSTANCE = "instance";
public static final String SCHEMA_TERM_NAMESPACE = "namespace";
public static final String SCHEMA_TERM_IS_ANONYMOUS = "is-anonymous";
public static final String SCHEMA_TERM_CONSIDER_USING = "consider-using";
public static final String SCHEMA_TERM_REPLACED_BY = "replaced-by";
public static final String SCHEMA_TERM_RELATIONSHIP = "relationship";
public static final String SCHEMA_TERM_RELATED_TO = "related-to";
public static final String SCHEMA_TERM_INTERSECTION_OF ="intersection-of";
public static final String SCHEMA_TERM_PART_OF = "part-of";
public static final String SCHEMA_TERM_HAS_PART = "has-part";
public static final String SCHEMA_TERM_AGENT_IN = "agent-in";
public static final String SCHEMA_TERM_HAS_AGENT = "has-agent";
public static final String SCHEMA_TERM_PARTICIPATES_IN = "participates-in";
public static final String SCHEMA_TERM_HAS_PARTICIPANT = "has-participant";
public static final String SCHEMA_TERM_PRECEDED_BY = "preceded-by";
public static final String SCHEMA_TERM_PRECEDES = "precedes";
public static final String SCHEMA_TERM_DERIVES_FROM = "derives-from";
public static final String SCHEMA_TERM_DERIVES_INTO = "derives-into";
public static final String SCHEMA_TERM_TRANSFORMATION_OF = "transformation-of";
public static final String SCHEMA_TERM_TRANSFORMATION_INTO = "transformed-into";
public static final String SCHEMA_TERM_CONTAINS = "contains";
public static final String SCHEMA_TERM_CONTAINED_IN = "contained-in";
public static final String SCHEMA_TERM_LOCATION_OF = "location-of";
public static final String SCHEMA_TERM_LOCATED_IN = "located-in";
public static final String SCHEMA_TERM_DISJOINT_FROM = "disjoint-from";
public static final String SCHEMA_TERM_ADJACENT_TO = "adjacent-to";
public static final String SCHEMA_TERM_UNION_OF = "union-of";
public static final String SCHEMA_TERM_MODIFIER = "modifier";
// **** TYPE-DEF ****
public static final String SCHEMA_TERM_DOMAIN = "domain";
public static final String SCHEMA_TERM_RANGE = "range";
public static final String SCHEMA_TERM_INVERSE_OF = "inverse-of";
public static final String SCHEMA_TERM_IS_TRANSITIVE = "is-transitive";
public static final String SCHEMA_TERM_IS_TRANSITIVE_OVER = "is-transitive-over";
public static final String SCHEMA_TERM_IS_REFLEXIVE = "is-reflexive";
public static final String SCHEMA_TERM_IS_CYCLIC = "is-cyclic";
public static final String SCHEMA_TERM_IS_SYMMETRIC = "is-symmetric";
public static final String SCHEMA_TERM_IS_ANTISYMMETRIC = "is-antisymmetric";
public static final String SCHEMA_TERM_IS_METADATA_TAG = "is-metadata-tag";
// **** INSTANCE ****
public static final String SCHEMA_TERM_INSTANCE_OF = "instance-of";
// **** PROPERTY-VALUES *****
public static final String SCHEMA_TERM_PROPERTY_VALUE ="property-value";
public static final String SCHEMA_TERM_PROPERTY_VALUE_TYPE ="property-value-type";
// ***** SYNONYMS ******
public static final String SCHEMA_TERM_SYNONYM = "synonym";
public static final String SCHEMA_TERM_SYNONYM_TEXT = "synonym-text";
public static final String SCHEMA_TERM_SYNONYM_TYPE = "synonym-type";
public static final String SCHEMA_TERM_SYNONYM_SCOPE = "synonym-scope";
public static final String SCHEMA_TERM_SYNONYM_ORIGIN = "synonym-origin";
// ***** XREFS ********
public static final String SCHEMA_TERM_XREF = "xref";
public static final String SCHEMA_TERM_XREF_SCOPE = "xref-scope";
// ***** CREATED ******
public static final String SCHEMA_TERM_CREATED_BY = "created_by";
public static final String SCHEMA_TERM_CREATION_DATE = "creation_date";
public static final String SCHEMA_TERM_EXPAND_ASSERTION = "expand_assertion_to";
public static final String SCHEMA_TERM_IS_CLASS_LEVEL = "is_class_level";
public static final String SCHEMA_TERM_HOLS_CHAIN_OVER = "holds_over_chain";
public static void setOptions(boolean collateSysnonyms, boolean descriptionTopics, boolean altIdSIs, boolean scopedXrefs, String lang) {
COLLATE_SIMILAR_SYNONYMS = collateSysnonyms;
MAKE_DESCRIPTION_TOPICS = descriptionTopics;
MAKE_SIS_FROM_ALT_IDS = altIdSIs;
USE_SCOPED_XREFS = scopedXrefs;
LANG = lang;
}
public static void setOptions(int options) {
COLLATE_SIMILAR_SYNONYMS = ((options&1)!=0);
MAKE_DESCRIPTION_TOPICS = ((options&2)!=0);
MAKE_SIS_FROM_ALT_IDS = ((options&4)!=0);
USE_SCOPED_XREFS = ((options&8)!=0);
PROCESS_HEADER_IMPORTS = ((options&16)!=0);
}
public static int getOptions() {
int options=0;
if(COLLATE_SIMILAR_SYNONYMS) options+=1;
if(MAKE_DESCRIPTION_TOPICS) options+=2;
if(MAKE_SIS_FROM_ALT_IDS) options+=4;
if(USE_SCOPED_XREFS) options+=8;
if(PROCESS_HEADER_IMPORTS) options+=16;
return options;
}
// -------------------------------------------------------------------------
public static Topic createRootTopic(TopicMap tm, String namespace) throws TopicMapException {
String si = OBO.SI+namespace;
Topic root = tm.getTopic(si);
if(root == null) {
root = getOrCreateTopic(tm, si, "obo ("+namespace+")");
Topic wandoraClass = getOrCreateTopic(tm, TMBox.WANDORACLASS_SI, "Wandora class");
makeSubclassOf(tm, root, wandoraClass);
}
return root;
}
public static Topic createHeaderTopic(TopicMap tm, String namespace) throws TopicMapException {
String si = OBO.SI+namespace+"/header";
Topic headerTopic = tm.getTopic(si);
if(headerTopic == null) {
headerTopic = getOrCreateTopic(tm, si, "header ("+namespace+")");
Topic root = createRootTopic(tm, namespace);
makeSubclassOf(tm, headerTopic, root);
}
return headerTopic;
}
public static Topic createTermTopic(TopicMap tm, String namespace) throws TopicMapException {
String si = OBO.SI+namespace+"/term";
Topic termTopic = tm.getTopic(si);
if(termTopic == null) {
termTopic = getOrCreateTopic(tm, si, "term ("+namespace+")");
Topic root = createRootTopic(tm, namespace);
makeSubclassOf(tm, termTopic, root);
}
return termTopic;
}
public static Topic createTypedefTopic(TopicMap tm, String namespace) throws TopicMapException {
String si = OBO.SI+"/typedef";
Topic termTopic = tm.getTopic(si);
if(termTopic == null) {
termTopic = getOrCreateTopic(tm, si, "typedef");
Topic root = createRootTopic(tm, namespace);
makeSubclassOf(tm, termTopic, root);
}
return termTopic;
}
public static Topic createInstanceTopic(TopicMap tm, String namespace) throws TopicMapException {
String si = OBO.SI+namespace+"/instance";
Topic termTopic = tm.getTopic(si);
if(termTopic == null) {
termTopic = getOrCreateTopic(tm, si, "instance ("+namespace+")");
Topic root = createRootTopic(tm, namespace);
makeSubclassOf(tm, termTopic, root);
}
return termTopic;
}
public static Topic createObsoleteTopic(TopicMap tm, String namespace) throws TopicMapException {
String si = OBO.SI+namespace+"/obsolete";
Topic obsoleteTopic = tm.getTopic(si);
if(obsoleteTopic == null) {
obsoleteTopic = getOrCreateTopic(tm, si, "obsolete ("+namespace+")");
Topic root = createRootTopic(tm, namespace);
makeSubclassOf(tm, obsoleteTopic, root);
}
return obsoleteTopic;
}
public static Topic createCategoryTopic(TopicMap tm, String namespace) throws TopicMapException {
String si = OBO.SI+namespace+"/category";
Topic categoryTypeTopic = tm.getTopic(si);
if(categoryTypeTopic == null) {
categoryTypeTopic = getOrCreateTopic(tm, si, "category ("+namespace+")");
Topic root = createRootTopic(tm, namespace);
makeSubclassOf(tm, categoryTypeTopic, root);
}
return categoryTypeTopic;
}
public static Topic createDescriptionTopic(TopicMap tm, String namespace) throws TopicMapException {
String si = OBO.SI+namespace+"/description";
Topic categoryTypeTopic = tm.getTopic(si);
if(categoryTypeTopic == null) {
categoryTypeTopic = getOrCreateTopic(tm, si, "description ("+namespace+")");
Topic root = createRootTopic(tm, namespace);
makeSubclassOf(tm, categoryTypeTopic, root);
}
return categoryTypeTopic;
}
public static Topic createSynonymTopic(TopicMap tm, String namespace) throws TopicMapException {
String si = OBO.SI+namespace+"/synonym";
Topic synonymTopic = tm.getTopic(si);
if(synonymTopic == null) {
synonymTopic = getOrCreateTopic(tm, si, "synonym ("+namespace+")");
Topic root = createRootTopic(tm, namespace);
makeSubclassOf(tm, synonymTopic, root);
}
return synonymTopic;
}
public static Topic createSchemaTopic(TopicMap tm) throws TopicMapException {
String si = OBO.SI+"schema";
Topic synonymTopic = tm.getTopic(si);
if(synonymTopic == null) {
synonymTopic = getOrCreateTopic(tm, si, "obo-schema");
Topic wandoraClass = getOrCreateTopic(tm, TMBox.WANDORACLASS_SI, "Wandora class");
makeSubclassOf(tm, synonymTopic, wandoraClass);
}
return synonymTopic;
}
public static Topic createISARootTopic(TopicMap tm, String namespace) throws TopicMapException {
String si = OBO.SI+namespace+"/is-a-root";
Topic isaRootTopic = tm.getTopic(si);
if(isaRootTopic == null) {
isaRootTopic = getOrCreateTopic(tm, si, "is-a-root ("+namespace+")");
Topic root = createRootTopic(tm, namespace);
makeSubclassOf(tm, isaRootTopic, root);
}
return isaRootTopic;
}
public static Topic createAuthorTopic(TopicMap tm, String namespace) throws TopicMapException {
String si = OBO.SI+namespace+"/author";
Topic authorTopic = tm.getTopic(si);
if(authorTopic == null) {
authorTopic = getOrCreateTopic(tm, si, "author ("+namespace+")");
Topic root = createRootTopic(tm, namespace);
makeSubclassOf(tm, authorTopic, root);
}
return authorTopic;
}
// ******
public static Topic getRootTopic(TopicMap tm, String namespace) throws TopicMapException {
Topic root = getTopic(tm, OBO.SI+namespace);
return root;
}
public static Topic getHeaderTopic(TopicMap tm, String namespace) throws TopicMapException {
Topic headerTopic = getTopic(tm, OBO.SI+namespace+"/header");
return headerTopic;
}
public static Topic getTermTopic(TopicMap tm, String namespace) throws TopicMapException {
Topic termTopic = getTopic(tm, OBO.SI+namespace+"/term");
return termTopic;
}
public static Topic getTypedefTopic(TopicMap tm, String namespace) throws TopicMapException {
Topic termTopic = getTopic(tm, OBO.SI+"/typedef");
return termTopic;
}
public static Topic getInstanceTopic(TopicMap tm, String namespace) throws TopicMapException {
Topic termTopic = getTopic(tm, OBO.SI+namespace+"/instance");
return termTopic;
}
public static Topic getObsoleteTopic(TopicMap tm, String namespace) throws TopicMapException {
Topic obsoleteTopic = getTopic(tm, OBO.SI+namespace+"/obsolete");
return obsoleteTopic;
}
public static Topic getCategoryTopic(TopicMap tm, String namespace) throws TopicMapException {
Topic categoryTypeTopic = getTopic(tm, OBO.SI+namespace+"/category");
return categoryTypeTopic;
}
public static Topic getDescriptionTopic(TopicMap tm, String namespace) throws TopicMapException {
Topic categoryTypeTopic = getTopic(tm, OBO.SI+namespace+"/description");
return categoryTypeTopic;
}
// ********
public static String solveOBOId(Topic t) throws TopicMapException {
Topic idType = OBO.getTopicForSchemaTerm(t.getTopicMap(), SCHEMA_TERM_ID);
String id = null;
if(idType != null) {
id = t.getData(idType, LANG);
}
if(id==null) {
id = solveOBOId(t.getOneSubjectIdentifier());
}
return id;
}
public static String solveOBOName(Topic t) throws TopicMapException {
String name = t.getDisplayName(LANG);
return name;
}
public static String solveOBODescription(Association a, Topic t) throws TopicMapException {
Topic descriptionType = OBO.getTopicForSchemaTerm(t.getTopicMap(), SCHEMA_TERM_DESCRIPTION);
String description = null;
if(descriptionType != null) {
if(MAKE_DESCRIPTION_TOPICS && a != null) {
Topic t2 = a.getPlayer(descriptionType);
if(t2 != null && !t2.isRemoved()) {
description = t2.getData(descriptionType, LANG);
}
}
if(description == null) {
description = t.getData(descriptionType, LANG);
if(description == null && a != null) {
Topic t2 = a.getPlayer(descriptionType);
if(t2 != null && !t2.isRemoved()) {
description = t2.getData(descriptionType, LANG);
}
}
}
}
return description;
}
public static String solveOBODescription(Topic t) throws TopicMapException {
Topic descriptionType = OBO.getTopicForSchemaTerm(t.getTopicMap(), SCHEMA_TERM_DESCRIPTION);
String description = null;
if(descriptionType != null) {
description = t.getData(descriptionType, LANG);
}
return description;
}
public static Topic createTopicForTypedef(TopicMap tm, String id) throws TopicMapException {
if(tm == null || id == null || id.length() == 0) return null;
Locator si = makeLocator(id);
Topic topic = tm.getTopic(si);
if(topic == null) {
topic = tm.createTopic();
topic.addSubjectIdentifier(si);
Topic idType = OBO.createTopicForSchemaTerm(tm, SCHEMA_TERM_ID);
setData(topic, idType, LANG, id);
}
return topic;
}
public static Topic createTopicForTypedef(TopicMap tm, String id, String name, String namespace) throws TopicMapException {
if(tm == null || id == null || id.length() == 0) return null;
Locator si = makeLocator(id);
Topic topic = tm.getTopic(si);
if(topic == null) {
topic = tm.createTopic();
topic.addSubjectIdentifier(si);
Topic idType = OBO.createTopicForSchemaTerm(tm, SCHEMA_TERM_ID);
setData(topic, idType, LANG, id);
}
if(name != null) {
topic.setBaseName(id);
topic.setDisplayName(LANG, name);
}
topic.addType(createTypedefTopic(tm, namespace));
return topic;
}
// *******
public static Topic createTopicForTerm(TopicMap tm, String id) throws TopicMapException {
if(tm == null || id == null || id.length() == 0) return null;
Locator si = makeLocator(id);
Topic topic = tm.getTopic(si);
if(topic == null) {
topic = tm.createTopic();
topic.addSubjectIdentifier(si);
Topic idType = OBO.createTopicForSchemaTerm(tm, SCHEMA_TERM_ID);
setData(topic, idType, LANG, id);
}
return topic;
}
public static Topic createTopicForTerm(TopicMap tm, String id, String name, String namespace) throws TopicMapException {
if(tm == null || id == null || id.length() == 0) return null;
Locator si = makeLocator(id);
Topic topic = tm.getTopic(si);
if(topic == null) {
topic = tm.createTopic();
topic.addSubjectIdentifier(si);
Topic idType = OBO.createTopicForSchemaTerm(tm, SCHEMA_TERM_ID);
setData(topic, idType, LANG, id);
}
if(name != null) {
topic.setBaseName(name+" ("+id+")");
topic.setDisplayName(LANG, name);
}
Topic termType = createTermTopic(tm, namespace);
if(!topic.isOfType(termType)) topic.addType(termType);
return topic;
}
public static Topic createTopicForInstance(TopicMap tm, String id) throws TopicMapException {
if(tm == null || id == null || id.length() == 0) return null;
Locator si = makeLocator(id);
Topic topic = tm.getTopic(si);
if(topic == null) {
topic = tm.createTopic();
topic.addSubjectIdentifier(si);
Topic idType = OBO.createTopicForSchemaTerm(tm, SCHEMA_TERM_ID);
setData(topic, idType, LANG, id);
}
return topic;
}
public static Topic createTopicForInstance(TopicMap tm, String id, String name, String namespace) throws TopicMapException {
if(tm == null || id == null || id.length() == 0) return null;
Locator si = makeLocator(id);
Topic topic = tm.getTopic(si);
if(topic == null) {
topic = tm.createTopic();
topic.addSubjectIdentifier(si);
Topic idType = OBO.createTopicForSchemaTerm(tm, SCHEMA_TERM_ID);
setData(topic, idType, LANG, id);
}
if(name != null) {
topic.setBaseName(name+" ("+id+")");
topic.setDisplayName(LANG, name);
}
topic.addType(createInstanceTopic(tm, namespace));
return topic;
}
public static Topic createTopicForAssertionExpansion(TopicMap tm, String exp) throws TopicMapException {
if(tm == null) return null;
exp = OBO2Java(exp);
Locator si = new Locator(makeSI("assertion-expansion/",exp));
Topic topic = tm.getTopic(si);
if(topic == null) {
topic = tm.createTopic();
//topicCounter++;
topic.addSubjectIdentifier(si);
topic.setBaseName(exp + " (assertion-expansion)");
topic.setDisplayName(LANG, exp);
}
return topic;
}
public static Topic createTopicForAuthor(TopicMap tm, String name, String namespace) throws TopicMapException {
if(tm == null) return null;
name = OBO2Java(name);
Locator si = new Locator(makeSI("author/",name));
Topic topic = tm.getTopic(si);
if(topic == null) {
topic = tm.createTopic();
//topicCounter++;
topic.addSubjectIdentifier(si);
topic.setBaseName(name + " (author)");
topic.setDisplayName(LANG, name);
topic.addType(createAuthorTopic(tm, namespace));
}
return topic;
}
public static Topic createTopicForSynonym(TopicMap tm, String name, String namespace) throws TopicMapException {
if(tm == null) return null;
name = OBO2Java(name);
Locator si = new Locator(makeSI("synonym/",name));
Topic topic = tm.getTopic(si);
if(topic == null) {
topic = tm.createTopic();
//topicCounter++;
topic.addSubjectIdentifier(si);
topic.setBaseName(name + " (synonym)");
topic.setDisplayName(LANG, name);
}
return topic;
}
public static Topic createTopicForDescription(TopicMap tm, String description, String namespace) throws TopicMapException {
if(tm == null) return null;
description = OBO2Java(description);
Locator si = new Locator(makeSI("description/",description));
Topic topic = tm.getTopic(si);
if(topic == null) {
topic = tm.createTopic();
topic.addSubjectIdentifier(si);
topic.setBaseName(description + " (description)");
topic.setDisplayName(LANG, description);
Topic type = createDescriptionTopic(tm, namespace);
setData(topic, createTopicForSchemaTerm(tm, SCHEMA_TERM_DESCRIPTION), LANG, description);
topic.addType(type);
}
return topic;
}
public static Topic createTopicForRelation(TopicMap tm, String id, String namespace) throws TopicMapException {
return createTopicForRelation(tm, id, null, namespace);
}
public static Topic createTopicForRelation(TopicMap tm, String id, String name, String namespace) throws TopicMapException {
if(tm == null) return null;
Locator si = new Locator(makeSI(id));
Topic topic = tm.getTopic(si);
if(topic == null) {
topic = tm.createTopic();
//topicCounter++;
topic.addSubjectIdentifier(si);
if(name != null) {
topic.setBaseName(name);
topic.setDisplayName(LANG, name);
}
else {
topic.setBaseName(id);
}
}
return topic;
}
public static Topic createTopicForModifier(TopicMap tm, String id) throws TopicMapException {
return createTopicForRelation(tm, id, null);
}
public static Topic createTopicForModifier(TopicMap tm, String id, String name) throws TopicMapException {
if(tm == null) return null;
Locator si = new Locator(makeSI(id));
Topic topic = tm.getTopic(si);
if(topic == null) {
topic = tm.createTopic();
//topicCounter++;
topic.addSubjectIdentifier(si);
if(name != null) {
topic.setBaseName(name);
topic.setDisplayName(LANG, name);
}
else {
topic.setBaseName(id);
}
}
return topic;
}
public static Topic getTopicForSchemaTerm(TopicMap tm, String schemaTerm) throws TopicMapException {
if(schemaTerm == null) return null;
String si = OBO.SCHEMA_SI+schemaTerm;
return getTopic(tm, TopicTools.cleanDirtyLocator(si));
}
public static Topic createTopicForSchemaTerm(TopicMap tm, String schemaTerm) throws TopicMapException {
if(schemaTerm == null) return null;
String si = OBO.SCHEMA_SI+schemaTerm;
Topic schemaTermTopic = tm.getTopic(si);
if(schemaTermTopic == null) {
schemaTermTopic = getOrCreateTopic(tm, new Locator(TopicTools.cleanDirtyLocator(si)), schemaTerm);
Topic schemaType = createSchemaTopic(tm);
schemaTermTopic.addType(schemaType);
// Topic idType = OBO.createTopicForSchemaTerm(tm, SCHEMA_TERM_ID);
// setData(schemaTermTopic, idType, LANG, schemaTerm);
}
return schemaTermTopic;
}
public static Topic createTopicForDbxref(TopicMap tm, String id) throws TopicMapException {
return createTopicForDbxref(tm, id, null);
}
public static Topic createTopicForDbxref(TopicMap tm, String id, String description) throws TopicMapException {
if(tm == null || id == null) return null;
Topic dbxrefTopic = null;
if(id.startsWith("http:")) {
dbxrefTopic = getOrCreateTopic(tm, new Locator(id), id);
}
else {
String si = makeSI(id);
dbxrefTopic = getOrCreateTopic(tm, new Locator(si), id);
Topic idType = OBO.createTopicForSchemaTerm(tm, SCHEMA_TERM_ID);
setData(dbxrefTopic, idType, LANG, id);
}
if(description != null && description.length() > 0) {
Topic descriptionTopic = createTopicForSchemaTerm(tm, SCHEMA_TERM_DESCRIPTION);
setData(dbxrefTopic, descriptionTopic, LANG, description);
}
return dbxrefTopic;
}
public static Topic createTopicForCategory(TopicMap tm, String id) throws TopicMapException {
return createTopicForCategory(tm, id, null);
}
public static Topic createTopicForCategory(TopicMap tm, String id, String description) throws TopicMapException {
if(tm == null || id == null) return null;
Topic categoryTopic = null;
if(id.startsWith("http:")) {
categoryTopic = getOrCreateTopic(tm, new Locator(id), id);
}
else {
String si = makeSI(id);
String categoryName = id;
if(description!=null) categoryName =description+" ("+id+")";
categoryTopic = getOrCreateTopic(tm, new Locator(si), categoryName);
}
if(description != null && description.length() > 0) {
Topic descriptionTopic = createTopicForSchemaTerm(tm, SCHEMA_TERM_DESCRIPTION);
setData(categoryTopic, descriptionTopic, LANG, description);
categoryTopic.setDisplayName(LANG, description);
}
return categoryTopic;
}
public static Topic createTopicForPropertyRelationship(TopicMap tm, String id) throws TopicMapException {
if(tm == null || id == null) return null;
Topic propertyTopic = null;
if(id.startsWith("http:")) {
propertyTopic = getOrCreateTopic(tm, new Locator(id), id);
propertyTopic.addType(createPropertyRelationshipTopic(tm));
}
else {
String si = makeSI(id);
String propertyName = id;
propertyTopic = getOrCreateTopic(tm, new Locator(si), propertyName);
propertyTopic.addType(createPropertyRelationshipTopic(tm));
}
return propertyTopic;
}
public static Topic createPropertyRelationshipTopic(TopicMap tm) throws TopicMapException {
String si = OBO.SI+"property-relationship";
Topic authorTopic = tm.getTopic(si);
if(authorTopic == null) {
authorTopic = getOrCreateTopic(tm, si, "property-relationship");
}
return authorTopic;
}
public static Topic createTopicForPropertyValue(TopicMap tm, String value) throws TopicMapException {
if(tm == null || value == null) return null;
Topic propertyTopic = null;
if(value.startsWith("http:")) {
propertyTopic = getOrCreateTopic(tm, new Locator(value), value);
}
else {
String si = makeSI(value);
String name = value;
propertyTopic = getOrCreateTopic(tm, new Locator(si), name);
}
return propertyTopic;
}
public static Topic createPropertyValueTopic(TopicMap tm) throws TopicMapException {
String si = OBO.SI+"/property-value";
Topic valueTopic = tm.getTopic(si);
if(valueTopic == null) {
valueTopic = getOrCreateTopic(tm, si, "property-value");
}
return valueTopic;
}
public static Topic createTopicForPropertyDatatype(TopicMap tm, String str) throws TopicMapException {
if(tm == null || str == null) return null;
Topic t = null;
if(str.startsWith("http:")) {
t = getOrCreateTopic(tm, new Locator(str), str);
t.addType(createPropertyDatatypeTopic(tm));
}
else {
String si = makeSI(str);
String name = str;
t = getOrCreateTopic(tm, new Locator(si), name);
t.addType(createPropertyDatatypeTopic(tm));
}
return t;
}
public static Topic createPropertyDatatypeTopic(TopicMap tm) throws TopicMapException {
String si = OBO.SI+"/property-datatype";
Topic valueTopic = tm.getTopic(si);
if(valueTopic == null) {
valueTopic = getOrCreateTopic(tm, si, "property-datatype");
}
return valueTopic;
}
// -------------------------------------------------------------------------
private static Topic getOrCreateTopic(TopicMap tm, String si, String basename) throws TopicMapException {
return getOrCreateTopic(tm, new Locator(si), basename);
}
private static Topic getOrCreateTopic(TopicMap tm, String si) throws TopicMapException {
return getOrCreateTopic(tm, new Locator(si), null);
}
private static Topic getOrCreateTopic(TopicMap tm, Locator si, String basename) throws TopicMapException {
if(tm == null) return null;
Topic topic = tm.getTopic(si);
if(topic == null) {
topic = tm.createTopic();
topic.addSubjectIdentifier(si);
if(basename != null) topic.setBaseName(OBO2Java(basename));
}
return topic;
}
private static Topic getTopic(TopicMap tm, String si) throws TopicMapException {
if(tm == null) return null;
Topic topic = tm.getTopic(si);
return topic;
}
private static void setData(Topic t, Topic type, String lang, String text) throws TopicMapException {
if(t != null & type != null && lang != null && text != null) {
String langsi=XTMPSI.getLang(LANG);
Topic langT=t.getTopicMap().getTopic(langsi);
if(langT == null) {
langT = t.getTopicMap().createTopic();
langT.addSubjectIdentifier(new Locator(langsi));
try {
langT.setBaseName("Language " + lang.toUpperCase());
}
catch (Exception e) {
langT.setBaseName("Language " + langsi);
}
}
t.setData(type, langT, text);
}
}
private static void makeSubclassOf(TopicMap tm, Topic t, Topic superclass) throws TopicMapException {
Topic supersubClassTopic = getOrCreateTopic(tm, XTMPSI.SUPERCLASS_SUBCLASS, "superclass-subclass");
Topic subclassTopic = getOrCreateTopic(tm, XTMPSI.SUBCLASS, "subclass");
Topic superclassTopic = getOrCreateTopic(tm, XTMPSI.SUPERCLASS, "superclass");
Association ta = tm.createAssociation(supersubClassTopic);
ta.addPlayer(t, subclassTopic);
ta.addPlayer(superclass, superclassTopic);
}
// -------------------------------------------------------------------------
public static String solveOBOId(Locator l) throws TopicMapException {
if(l == null) return null;
String id = l.toExternalForm();
if(id.startsWith(SCHEMA_SI) && id.length()>SCHEMA_SI.length()) {
id = id.substring(SCHEMA_SI.length());
try { id = URLDecoder.decode(id, "UTF-8"); } catch(Exception e) {}
//id = id.replace('/', ':');
}
else if(id.startsWith(SI) && id.length()>SI.length()) {
id = id.substring(SI.length());
try { id = URLDecoder.decode(id, "UTF-8"); } catch(Exception e) {}
//id = id.replace('/', ':');
}
return id;
}
public static Locator makeLocator(String id) {
return new Locator(makeSI(id));
}
public static String makeSI(String id) {
if(id == null) return null;
id = OBO2Java(id);
String si = OBO.SI + id; // WAS: id.replace(':', '/');
return si;
}
public static String makeSICarefully(String id) {
if(id == null) return null;
id = OBO2Java(id);
try {
String si = OBO.SI + URLEncoder.encode(id, "UTF-8");
return si;
}
catch(Exception e) { }
return OBO.SI + id;
}
public static String makeSI(String prefix, String str) {
if(str == null) return null;
str = OBO2Java(str);
try {
String si = OBO.SI + prefix + URLEncoder.encode(str, "UTF-8");
return si;
}
catch(Exception e) { }
return OBO.SI + prefix + str;
}
public static String makeTermSI(String termId) {
String termSI = makeSI(termId);
String[] termIdParts = termId.split(":");
if(termIdParts.length > 1) {
String prefix = termIdParts[0].trim();
String id = termIdParts[1].trim();
if("Wikipedia".equalsIgnoreCase(prefix))
termSI = "http://en.wikipedia.org/wiki/"+id;
else if("AGI_LacusCode".equalsIgnoreCase(prefix))
termSI = "http://arabidopsis.org/servlets/TairObject?type=locus&name="+id;
else if("AGI_LacusCode".equalsIgnoreCase(prefix))
termSI = "http://www.plasmodb.org/gene/"+id;
else if("AraCyc".equalsIgnoreCase(prefix))
termSI = "http://www.arabidopsis.org:1555/ARA/NEW-IMAGE?type=NIL&object="+id;
else if("BIOMD".equalsIgnoreCase(prefix))
termSI = "http://www.ebi.ac.uk/compneur-srv/biomodels-main/publ-model.do?mid="+id;
else if("BRENDA".equalsIgnoreCase(prefix))
termSI = "http://www.brenda.uni-koeln.de/php/result_flat.php4?ecno="+id;
else if("Broad_MGG".equalsIgnoreCase(prefix))
termSI = "http://www.broad.mit.edu/annotation/genome/magnaporthe_grisea/GeneLocus.html?sp=S"+id;
else if("CAS_SPC".equalsIgnoreCase(prefix))
termSI = "http://research.calacademy.org/research/ichthyology/catalog/getname.asp?rank=Species&id="+id;
else if("CBS".equalsIgnoreCase(prefix))
termSI = "http://www.cbs.dtu.dk/services/"+id+"/";
else if("CDD".equalsIgnoreCase(prefix))
termSI = "http://www.ncbi.nlm.nih.gov/Structure/cdd/cddsrv.cgi?uid="+id+"";
else if("CGD".equalsIgnoreCase(prefix))
termSI = "http://www.candidagenome.org/cgi-bin/locus.pl?dbid="+id+"";
else if("CGD_LOCUS".equalsIgnoreCase(prefix))
termSI = "http://www.candidagenome.org/cgi-bin/locus.pl?locus="+id+"";
else if("CGD_REF".equalsIgnoreCase(prefix))
termSI = "http://www.candidagenome.org/cgi-bin/reference/reference.pl?refNo="+id+"";
else if("CGSC".equalsIgnoreCase(prefix))
termSI = "http://cgsc.biology.yale.edu/Site.php?ID="+id+"";
else if("ChEBI".equalsIgnoreCase(prefix))
termSI = "http://www.ebi.ac.uk/chebi/searchId.do?chebiId=CHEBI:"+id+"";
else if("CL".equalsIgnoreCase(prefix)) {
;//termSI = ""+id+"";
}
else if("COG_Cluster".equalsIgnoreCase(prefix))
termSI = "http://www.ncbi.nlm.nih.gov/COG/new/release/cow.cgi?cog="+id+"";
else if("COG_Function".equalsIgnoreCase(prefix))
termSI = "http://www.ncbi.nlm.nih.gov/COG/grace/shokog.cgi?fun="+id+"";
else if("COG_Pathway".equalsIgnoreCase(prefix))
termSI = "http://www.ncbi.nlm.nih.gov/COG/new/release/coglist.cgi?pathw="+id+"";
else if("dictyBase".equalsIgnoreCase(prefix))
termSI = "http://dictybase.org/db/cgi-bin/gene_page.pl?dictybaseid="+id+"";
else if("dictyBase_gene_name".equalsIgnoreCase(prefix))
termSI = "http://dictybase.org/db/cgi-bin/gene_page.pl?gene_name="+id+"";
else if("dictyBase_REF".equalsIgnoreCase(prefix))
termSI = "http://dictybase.org/db/cgi-bin/dictyBase/reference/reference.pl?refNo="+id+"";
else if("DOI".equalsIgnoreCase(prefix))
termSI = "http://dx.doi.org/"+id+"";
else if("EC".equalsIgnoreCase(prefix))
termSI = "http://www.expasy.org/enzyme/"+id+"";
else if("ECK".equalsIgnoreCase(prefix))
termSI = "http://www.ecogene.org/geneInfo.php?eck_id="+id+"";
else if("EcoCyc".equalsIgnoreCase(prefix))
termSI = "http://biocyc.org/ECOLI/NEW-IMAGE?type=PATHWAY&object="+id+"";
else if("EcoCyc_REF".equalsIgnoreCase(prefix))
termSI = "http://biocyc.org/ECOLI/reference.html?type=CITATION-FRAME&object="+id+"";
else if("ECOGENE".equalsIgnoreCase(prefix))
termSI = "http://www.ecogene.org/geneInfo.php?eg_id="+id+"";
else if("EMBL".equalsIgnoreCase(prefix))
termSI = "http://www.ebi.ac.uk/cgi-bin/emblfetch?style=html&Submit=Go&id="+id+"";
else if("DDBJ".equalsIgnoreCase(prefix))
termSI = "http://arsa.ddbj.nig.ac.jp/arsa/ddbjSplSearch?KeyWord="+id+"";
else if("GenBank".equalsIgnoreCase(prefix))
termSI = "http://www.ncbi.nlm.nih.gov/entrez/viewer.fcgi?db=nucleotide&val="+id+"";
else if("ENSEMBL".equalsIgnoreCase(prefix))
termSI = "http://www.ensembl.org/perl/protview?peptide="+id+"";
else if("ENZYME".equalsIgnoreCase(prefix))
termSI = "http://www.expasy.ch/cgi-bin/nicezyme.pl?"+id+"";
else if("FB".equalsIgnoreCase(prefix))
termSI = "http://flybase.org/reports/"+id+".html";
else if("GDB".equalsIgnoreCase(prefix))
termSI = "http://www.gdb.org/gdb-bin/genera/accno?accessionNum=GDB:"+id+"";
else if("GeneDB_Gmorsitans".equalsIgnoreCase(prefix))
termSI = "http://www.genedb.org/genedb/Search?organism=glossina&name="+id+"";
else if("GeneDB_Lmajor".equalsIgnoreCase(prefix))
termSI = "http://www.genedb.org/genedb/Search?organism=leish&name="+id+"";
else if("GeneDB_Pfalciparum".equalsIgnoreCase(prefix))
termSI = "http://www.genedb.org/genedb/Search?organism=malaria&name="+id+"";
else if("GeneDB_Spombe".equalsIgnoreCase(prefix))
termSI = "http://www.genedb.org/genedb/Search?organism=pombe&name="+id+"";
else if("GeneDB_Tbrucei".equalsIgnoreCase(prefix))
termSI = "http://www.genedb.org/genedb/Search?organism=pombe&name="+id+"";
else if("GO".equalsIgnoreCase(prefix))
termSI = "http://amigo.geneontology.org/cgi-bin/amigo/term-details.cgi?term="+id+"";
else if("GO_REF".equalsIgnoreCase(prefix))
termSI = "http://www.geneontology.org/cgi-bin/references.cgi#GO_REF:"+id+"";
else if("GR".equalsIgnoreCase(prefix))
termSI = "http://www.gramene.org/db/searches/browser?search_type=All&RGN=on&query="+id+"";
else if("GR_GENE".equalsIgnoreCase(prefix))
termSI = "http://www.gramene.org/db/genes/search_gene?acc="+id+"";
else if("GR_PROTEIN".equalsIgnoreCase(prefix))
termSI = "http://www.gramene.org/db/protein/protein_search?acc="+id+"";
else if("GR_QTL".equalsIgnoreCase(prefix))
termSI = "http://www.gramene.org/db/qtl/qtl_display?qtl_accession_id="+id+"";
else if("GR_REF".equalsIgnoreCase(prefix))
termSI = "http://www.gramene.org/db/literature/pub_search?ref_id="+id+"";
else if("H-invDB_cDNA".equalsIgnoreCase(prefix))
termSI = "http://www.h-invitational.jp/hinv/spsoup/transcript_view?acc_id="+id+"";
else if("H-invDB_locus".equalsIgnoreCase(prefix))
termSI = "http://www.h-invitational.jp/hinv/spsoup/locus_view?hix_id="+id+"";
else if("HAMAP".equalsIgnoreCase(prefix))
termSI = "http://us.expasy.org/unirules/"+id+"";
else if("HGNC".equalsIgnoreCase(prefix))
termSI = "http://www.genenames.org/data/hgnc_data.php?hgnc_id=HGNC:"+id+"";
else if("HGNC_gene".equalsIgnoreCase(prefix))
termSI = "http://www.genenames.org/data/hgnc_data.php?app_sym="+id+"";
else if("IMG".equalsIgnoreCase(prefix))
termSI = "http://img.jgi.doe.gov/cgi-bin/pub/main.cgi?section=GeneDetail&page=geneDetail&gene_oid="+id+"";
else if("IntAct".equalsIgnoreCase(prefix))
termSI = "http://www.ebi.ac.uk/intact/search/do/search?searchString="+id+"";
else if("InterPro".equalsIgnoreCase(prefix))
termSI = "http://www.ebi.ac.uk/interpro/DisplayIproEntry?ac="+id+"";
else if("ISBN".equalsIgnoreCase(prefix))
termSI = "http://my.linkbaton.com/get?lbCC=q&nC=q&genre=book&item="+id+"";
else if("IUPHAR_GPCR".equalsIgnoreCase(prefix))
termSI = "http://www.iuphar-db.org/GPCR/ChapterMenuForward?chapterID="+id+"";
else if("IUPHAR_RECEPTOR".equalsIgnoreCase(prefix))
termSI = "http://www.iuphar-db.org/GPCR/ReceptorDisplayForward?receptorID="+id+"";
else if("KEGG_PATHWAY".equalsIgnoreCase(prefix))
termSI = "http://www.genome.ad.jp/dbget-bin/www_bget?path:"+id+"";
else if("KEGG_LIGAND".equalsIgnoreCase(prefix))
termSI = "http://www.genome.ad.jp/dbget-bin/www_bget?cpd:"+id+"";
else if("LIFEdb".equalsIgnoreCase(prefix))
termSI = "http://www.dkfz.de/LIFEdb/LIFEdb.aspx?ID="+id+"";
else if("MA".equalsIgnoreCase(prefix))
termSI = "http://www.informatics.jax.org/searches/AMA.cgi?id=MA:"+id+"";
else if("MaizeGDB".equalsIgnoreCase(prefix))
termSI = "http://www.maizegdb.org/cgi-bin/id_search.cgi?id="+id+"";
else if("MaizeGDB_Locus".equalsIgnoreCase(prefix))
termSI = "http://www.maizegdb.org/cgi-bin/displaylocusresults.cgi?term="+id+"";
else if("MEROPS".equalsIgnoreCase(prefix))
termSI = "http://merops.sanger.ac.uk/cgi-bin/pepsum?mid="+id+"";
else if("MEROPS_fam".equalsIgnoreCase(prefix))
termSI = "http://merops.sanger.ac.uk/cgi-bin/famsum?family="+id+"";
else if("MeSH".equalsIgnoreCase(prefix))
termSI = "http://www.nlm.nih.gov/cgi/mesh/2005/MB_cgi?mode=&term="+id+"";
else if("MetaCyc".equalsIgnoreCase(prefix))
termSI = "http://biocyc.org/META/NEW-IMAGE?type=NIL&object="+id+"";
else if("MGI".equalsIgnoreCase(prefix))
termSI = "http://www.informatics.jax.org/searches/accession_report.cgi?id=MGI:"+id+"";
else if("MIPS_funcat".equalsIgnoreCase(prefix))
termSI = "http://mips.gsf.de/cgi-bin/proj/funcatDB/search_advanced.pl?action=2&wert="+id+"";
else if("MO".equalsIgnoreCase(prefix))
termSI = "http://mged.sourceforge.net/ontologies/MGEDontology.php#"+id+"";
else if("NASC_code".equalsIgnoreCase(prefix))
termSI = "http://seeds.nottingham.ac.uk/NASC/stockatidb.lasso?code="+id+"";
else if("NCBI".equalsIgnoreCase(prefix))
termSI = "http://www.ncbi.nlm.nih.gov/entrez/viewer.fcgi?val="+id+"";
else if("NCBI_Gene".equalsIgnoreCase(prefix))
termSI = "http://www.ncbi.nlm.nih.gov/sites/entrez?cmd=Retrieve&db=gene&list_uids="+id+"";
else if("NCBI_gi".equalsIgnoreCase(prefix))
termSI = "http://www.ncbi.nlm.nih.gov/entrez/viewer.fcgi?val="+id+"";
else if("NCBI_GP".equalsIgnoreCase(prefix))
termSI = "http://www.ncbi.nlm.nih.gov/entrez/viewer.fcgi?db=protein&val="+id+"";
else if("NMPDR".equalsIgnoreCase(prefix))
termSI = "http://www.nmpdr.org/linkin.cgi?id="+id+"";
else if("OMIM".equalsIgnoreCase(prefix))
termSI = "http://www.ncbi.nlm.nih.gov/entrez/dispomim.cgi?id="+id+"";
else if("PAMGO".equalsIgnoreCase(prefix))
termSI = "http://agro.vbi.vt.edu/public/servlet/GeneEdit?&Search=Search&level=2&genename="+id+"";
else if("PAMGO_MGG".equalsIgnoreCase(prefix))
termSI = "http://scotland.fgl.ncsu.edu/cgi-bin/adHocQuery.cgi?adHocQuery_dbName=smeng_goannotation&Action=Data&QueryName=Functional+Categorization+of+MGG+GO+Annotation&P_DBObjectSymbol=&P_EvidenceCode=&P_Aspect=&P_DBObjectSynonym=&P_KeyWord="+id+"";
else if("PAMGO_VMD".equalsIgnoreCase(prefix))
termSI = "http://vmd.vbi.vt.edu/cgi-bin/browse/go_detail.cgi?gene_id="+id+"";
else if("PDB".equalsIgnoreCase(prefix))
termSI = "http://www.rcsb.org/pdb/cgi/explore.cgi?pid=223051005992697&pdbId="+id+"";
else if("Pfam".equalsIgnoreCase(prefix))
termSI = "http://www.sanger.ac.uk/cgi-bin/Pfam/getacc?"+id+"";
else if("PharmGKB_PA".equalsIgnoreCase(prefix))
termSI = "http://www.pharmgkb.org/do/serve?objId="+id+"";
else if("PharmGKB_PGKB".equalsIgnoreCase(prefix))
termSI = "http://www.pharmgkb.org/do/serve?objId="+id+"";
else if("PIR".equalsIgnoreCase(prefix))
termSI = "http://pir.georgetown.edu/cgi-bin/pirwww/nbrfget?uid="+id+"";
else if("PIRSF".equalsIgnoreCase(prefix))
termSI = "http://pir.georgetown.edu/cgi-bin/ipcSF?id="+id+"";
else if("PMID".equalsIgnoreCase(prefix))
termSI = "http://www.ncbi.nlm.nih.gov/pubmed/"+id+"";
else if("PO".equalsIgnoreCase(prefix))
termSI = "http://www.plantontology.org/amigo/go.cgi?action=query&view=query&search_constraint=terms&query="+id+"";
else if("PRINTS".equalsIgnoreCase(prefix))
termSI = "http://www.bioinf.manchester.ac.uk/cgi-bin/dbbrowser/sprint/searchprintss.cgi?display_opts=Prints&category=None&queryform=false®expr=off&prints_accn="+id+"";
else if("ProDom".equalsIgnoreCase(prefix))
termSI = "http://prodes.toulouse.inra.fr/prodom/current/cgi-bin/request.pl?question=DBEN&query="+id+"";
else if("Prosite".equalsIgnoreCase(prefix))
termSI = "http://www.expasy.ch/cgi-bin/prosite-search-ac?"+id+"";
else if("PseudoCAP".equalsIgnoreCase(prefix))
termSI = "http://v2.pseudomonas.com/getAnnotation.do?locusID="+id+"";
else if("PSI-MOD".equalsIgnoreCase(prefix))
termSI = "http://www.ebi.ac.uk/ontology-lookup/?termId=MOD:"+id+"";
else if("PubChem_BioAssay".equalsIgnoreCase(prefix))
termSI = "http://pubchem.ncbi.nlm.nih.gov/assay/assay.cgi?aid="+id+"";
else if("PubChem_Compound".equalsIgnoreCase(prefix))
termSI = "http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?CMD=search&DB=pccompound&term="+id+"";
else if("PubChem_Substance".equalsIgnoreCase(prefix))
termSI = "http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?CMD=search&DB=pcsubstance&term="+id+"";
else if("Reactome".equalsIgnoreCase(prefix))
termSI = "http://www.reactome.org/cgi-bin/eventbrowser_st_id?ST_ID="+id+"";
else if("REBASE".equalsIgnoreCase(prefix))
termSI = "http://rebase.neb.com/rebase/enz/"+id+".html";
else if("RefSeq".equalsIgnoreCase(prefix))
termSI = "http://www.ncbi.nlm.nih.gov/entrez/viewer.fcgi?val="+id+"";
else if("RefSeq_NA".equalsIgnoreCase(prefix))
termSI = "http://www.ncbi.nlm.nih.gov/entrez/viewer.fcgi?val="+id+"";
else if("RefSeq_Prot".equalsIgnoreCase(prefix))
termSI = "http://www.ncbi.nlm.nih.gov/entrez/viewer.fcgi?val="+id+"";
else if("RGD".equalsIgnoreCase(prefix))
termSI = "http://rgd.mcw.edu/generalSearch/RgdSearch.jsp?quickSearch=1&searchKeyword="+id+"";
else if("RNAmods".equalsIgnoreCase(prefix))
termSI = "http://medlib.med.utah.edu/cgi-bin/rnashow.cgi?"+id+"";
else if("SEED".equalsIgnoreCase(prefix))
termSI = "http://www.theseed.org/linkin.cgi?id="+id+"";
else if("SGD".equalsIgnoreCase(prefix))
termSI = "http://db.yeastgenome.org/cgi-bin/locus.pl?dbid="+id+"";
else if("SGD_LOCUS".equalsIgnoreCase(prefix))
termSI = "http://db.yeastgenome.org/cgi-bin/locus.pl?locus="+id+"";
else if("SGD_REF".equalsIgnoreCase(prefix))
termSI = "http://db.yeastgenome.org/cgi-bin/reference/reference.pl?dbid="+id+"";
else if("SGN".equalsIgnoreCase(prefix))
termSI = "http://www.sgn.cornell.edu/phenome/locus_display.pl?locus_id="+id+"";
else if("SGN_ref".equalsIgnoreCase(prefix))
termSI = "http://www.sgn.cornell.edu/chado/publication.pl?pub_id="+id+"";
else if("SMART".equalsIgnoreCase(prefix))
termSI = "http://smart.embl-heidelberg.de/smart/do_annotation.pl?BLAST=DUMMY&DOMAIN="+id+"";
else if("SO".equalsIgnoreCase(prefix))
termSI = "http://song.sourceforge.net/SOterm_tables.html#"+id+"";
else if("SP_KW".equalsIgnoreCase(prefix))
termSI = "http://www.expasy.org/cgi-bin/get-entries?KW="+id+"";
else if("Swiss-Prot".equalsIgnoreCase(prefix))
termSI = "http://www.ebi.uniprot.org/entry/"+id+"";
else if("TAIR".equalsIgnoreCase(prefix))
termSI = "http://arabidopsis.org/servlets/TairObject?accession="+id+"";
else if("taxon".equalsIgnoreCase(prefix))
termSI = "http://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?id="+id+"";
else if("TC".equalsIgnoreCase(prefix))
termSI = "http://www.tcdb.org/tcdb/index.php?tc="+id+"";
else if("TGD_LOCUS".equalsIgnoreCase(prefix))
termSI = "http://db.ciliate.org/cgi-bin/locus.pl?locus="+id+"";
else if("TGD_REF".equalsIgnoreCase(prefix))
termSI = "http://db.ciliate.org/cgi-bin/reference/reference.pl?dbid="+id+"";
else if("TIGR_CMR".equalsIgnoreCase(prefix))
termSI = "http://cmr.jcvi.org/tigr-scripts/CMR/shared/GenePage.cgi?locus="+id+"";
else if("TIGR_Ath1".equalsIgnoreCase(prefix))
termSI = "http://www.tigr.org/tigr-scripts/euk_manatee/shared/ORF_infopage.cgi?db=ath1&orf="+id+"";
else if("TIGR_Pfa1".equalsIgnoreCase(prefix))
termSI = "http://www.tigr.org/tigr-scripts/euk_manatee/shared/ORF_infopage.cgi?db=pfa1&orf="+id+"";
else if("TIGR_Tba1".equalsIgnoreCase(prefix))
termSI = "http://www.tigr.org/tigr-scripts/euk_manatee/shared/ORF_infopage.cgi?db=tba1&orf="+id+"";
else if("TIGR_TIGRFAMS".equalsIgnoreCase(prefix))
termSI = "http://cmr.jcvi.org/cgi-bin/CMR/HmmReport.cgi?hmm_acc="+id+"";
else if("TIGR_EGAD".equalsIgnoreCase(prefix))
termSI = "http://www.tigr.org/tigr-scripts/CMR2/ht_report.spl?prot_id="+id+"";
else if("TIGR_GenProp".equalsIgnoreCase(prefix))
termSI = "http://www.tigr.org/tigr-scripts/CMR2/genome_property_def.spl?prop_acc="+id+"";
else if("TrEMBL".equalsIgnoreCase(prefix))
termSI = "http://www.ebi.uniprot.org/entry/"+id+"";
else if("UM-BBD_enzymeID".equalsIgnoreCase(prefix))
termSI = "http://umbbd.msi.umn.edu/servlets/pageservlet?ptype=ep&enzymeID="+id+"";
else if("UM-BBD_reactionID".equalsIgnoreCase(prefix))
termSI = "http://umbbd.msi.umn.edu/servlets/pageservlet?ptype=r&reacID="+id+"";
else if("UM-BBD_ruleID".equalsIgnoreCase(prefix))
termSI = "http://umbbd.msi.umn.edu/servlets/rule.jsp?rule="+id+"";
else if("UniParc".equalsIgnoreCase(prefix))
termSI = "http://www.ebi.ac.uk/cgi-bin/dbfetch?db=uniparc&id="+id+"";
else if("UniProtKB".equalsIgnoreCase(prefix))
termSI = "http://www.ebi.uniprot.org/entry/"+id+"";
else if("VEGA".equalsIgnoreCase(prefix))
termSI = "http://vega.sanger.ac.uk/perl/searchview?species=all&idx=All&q="+id+"";
else if("VMD".equalsIgnoreCase(prefix))
termSI = "http://vmd.vbi.vt.edu/cgi-bin/browse/browserDetail_new.cgi?gene_id="+id+"";
else if("WB".equalsIgnoreCase(prefix))
termSI = "http://www.wormbase.org/db/gene/gene?name="+id+"";
else if("WB_REF".equalsIgnoreCase(prefix))
termSI = "http://www.wormbase.org/db/misc/paper?name="+id+"";
else if("WP".equalsIgnoreCase(prefix))
termSI = "http://www.wormbase.org/db/get?class=Protein;name=WP:"+id+"";
else if("ZFIN".equalsIgnoreCase(prefix))
termSI = "http://zfin.org/cgi-bin/ZFIN_jump?record="+id+"";
}
return termSI;
}
public static String makeBasename(String termid) {
if(termid == null) return null;
String basename = OBO2Java(termid);
return basename;
}
public static String OBO2Java(String str) {
if(str == null) return null;
str = str.replace("\\n", "\n");
str = str.replace("\\W", " ");
str = str.replace("\\t", "\t");
str = str.replace("\\:", ":");
str = str.replace("\\,", ",");
str = str.replace("\\\"", "\"");
str = str.replace("\\(", "(");
str = str.replace("\\)", ")");
str = str.replace("\\{", "{");
str = str.replace("\\}", "}");
str = str.replace("\\[", "[");
str = str.replace("\\]", "]");
str = str.replace("\\!", "!");
str = str.replaceAll("\\\\(.)", "$1");
//str = str.replace("\\\\", "\\");
return str;
}
public static String Java2OBO(String str) {
if(str == null) return null;
str = str.replace("\\", "\\\\");
str = str.replace("\"", "\\\"");
str = str.replace("\n", "\\n");
//str = str.replace(" ", "\\W");
str = str.replace("\t", "\\t");
str = str.replace(":", "\\:");
str = str.replace(",", "\\,");
str = str.replace("!", "\\!");
//str = str.replace("(", "\\(");
//str = str.replace(")", "\\)");
//str = str.replace("[", "\\[");
//str = str.replace("]", "\\]");
return str;
}
public static String Java2OBOLite(String str) {
if(str == null) return null;
str = str.replace("\\", "\\\\");
str = str.replace("\"", "\\\"");
str = str.replace("\n", "\\n");
//str = str.replace(" ", "\\W");
str = str.replace("\t", "\\t");
//str = str.replace(":", "\\:");
//str = str.replace(",", "\\,");
str = str.replace("!", "\\!");
//str = str.replace("(", "\\(");
//str = str.replace(")", "\\)");
//str = str.replace("[", "\\[");
//str = str.replace("]", "\\]");
return str;
}
// -------------------------------------------------------------------------
public static void importExport(String dir) {
File[] importFiles = IObox.getFiles(dir, ".+\\.obo", 1, 999);
importExport(importFiles);
}
public static void importExport(File[] importFiles) {
if(importFiles != null && importFiles.length > 0) {
for(int i=0; i<importFiles.length; i++) {
try {
TopicMap map = new org.wandora.topicmap.memory.TopicMapImpl();
File importFile = importFiles[i];
OBOImport importer = new OBOImport();
importer.importOBO(new FileInputStream(importFile), map);
OBOExport exporter = new OBOExport();
String exportFileName = importFile.getAbsolutePath();
exportFileName = exportFileName.substring(exportFileName.length()-4)+"_wandoraexport.obo";
File exportFile = new File(exportFileName);
ArrayList<String> namespaces = importer.getNamespaces();
if(namespaces != null && namespaces.size() >0) {
exporter.exportOBO(exportFile, namespaces.toArray( new String[] {} ), map);
}
}
catch(Exception e) {
e.printStackTrace();
}
}
}
else {
System.out.println("No OBO files to import!");
}
}
}
| 60,594 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
OBOConfiguration.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/importers/OBOConfiguration.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* OBOConfiguration.java
*
* Created on 10.7.2006, 12:39
*/
package org.wandora.application.tools.importers;
import org.wandora.application.gui.simple.SimpleButton;
import org.wandora.application.gui.simple.SimpleCheckBox;
import org.wandora.utils.swing.GuiTools;
/**
* OBOConfiguration is a simple dialog used to acquire configuration for OBOImport and
* OBOExport tools.
*
* @author akivela, olli
*/
public class OBOConfiguration extends javax.swing.JDialog {
private static final long serialVersionUID = 1L;
private boolean cancelled=true;
/** Creates new form ImportConfiguration */
public OBOConfiguration(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
this.setTitle("OBO configuration");
GuiTools.centerWindow(this,parent);
}
/** 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;
collateSynonymsCheckBox = new SimpleCheckBox();
descriptionTopicsCheckBox = new SimpleCheckBox();
altIdSIsCheckBox = new SimpleCheckBox();
scopedXrefsCheckBox = new SimpleCheckBox();
processImports = new SimpleCheckBox();
jPanel1 = new javax.swing.JPanel();
okButton = new SimpleButton();
cancelButton = new SimpleButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
getContentPane().setLayout(new java.awt.GridBagLayout());
collateSynonymsCheckBox.setText("Collate similar synonyms (export)");
collateSynonymsCheckBox.setMargin(new java.awt.Insets(0, 0, 0, 0));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 0, 10);
getContentPane().add(collateSynonymsCheckBox, gridBagConstraints);
descriptionTopicsCheckBox.setText("Make DBXref description topics (import)");
descriptionTopicsCheckBox.setMargin(new java.awt.Insets(0, 0, 0, 0));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 10, 0, 10);
getContentPane().add(descriptionTopicsCheckBox, gridBagConstraints);
altIdSIsCheckBox.setText("Make SI from alternative Id (import)");
altIdSIsCheckBox.setActionCommand("Make SIs from alternative Ids (import)");
altIdSIsCheckBox.setMargin(new java.awt.Insets(0, 0, 0, 0));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 10, 0, 10);
getContentPane().add(altIdSIsCheckBox, gridBagConstraints);
scopedXrefsCheckBox.setText("Make scoped Xrefs (import)");
scopedXrefsCheckBox.setMargin(new java.awt.Insets(0, 0, 0, 0));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 10, 0, 10);
getContentPane().add(scopedXrefsCheckBox, gridBagConstraints);
processImports.setText("Process header imports (import)");
processImports.setMargin(new java.awt.Insets(0, 0, 0, 0));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10);
getContentPane().add(processImports, gridBagConstraints);
jPanel1.setLayout(new java.awt.GridBagLayout());
okButton.setText("OK");
okButton.setMargin(new java.awt.Insets(2, 5, 2, 5));
okButton.setPreferredSize(new java.awt.Dimension(70, 23));
okButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
okButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5);
jPanel1.add(okButton, gridBagConstraints);
cancelButton.setText("Cancel");
cancelButton.setMargin(new java.awt.Insets(2, 5, 2, 5));
cancelButton.setPreferredSize(new java.awt.Dimension(70, 23));
cancelButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5);
jPanel1.add(cancelButton, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.insets = new java.awt.Insets(5, 10, 10, 10);
getContentPane().add(jPanel1, gridBagConstraints);
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
setBounds((screenSize.width-329)/2, (screenSize.height-228)/2, 329, 228);
}// </editor-fold>//GEN-END:initComponents
private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
cancelled=true;
this.setVisible(false);
}//GEN-LAST:event_cancelButtonActionPerformed
private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
cancelled=false;
this.setVisible(false);
}//GEN-LAST:event_okButtonActionPerformed
public boolean wasCancelled(){return cancelled;}
public int getOptions(){
int options=0;
if(collateSynonymsCheckBox.isSelected()) options+=1;
if(descriptionTopicsCheckBox.isSelected()) options+=2;
if(altIdSIsCheckBox.isSelected()) options+=4;
if(scopedXrefsCheckBox.isSelected()) options+=8;
if(processImports.isSelected()) options+=16;
return options;
}
public void setOptions(int options){
collateSynonymsCheckBox.setSelected((options&1)!=0);
descriptionTopicsCheckBox.setSelected((options&2)!=0);
altIdSIsCheckBox.setSelected((options&4)!=0);
scopedXrefsCheckBox.setSelected((options&8)!=0);
processImports.setSelected((options&16)!=0);
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JCheckBox altIdSIsCheckBox;
private javax.swing.JButton cancelButton;
private javax.swing.JCheckBox collateSynonymsCheckBox;
private javax.swing.JCheckBox descriptionTopicsCheckBox;
private javax.swing.JPanel jPanel1;
private javax.swing.JButton okButton;
private javax.swing.JCheckBox processImports;
private javax.swing.JCheckBox scopedXrefsCheckBox;
// End of variables declaration//GEN-END:variables
}
| 8,739 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
GOAImport.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/importers/GOAImport.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* GOAImport.java
*
* Created on 22. elokuuta 2007, 19:17
*
*/
package org.wandora.application.tools.importers;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.swing.Icon;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.gui.UIBox;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.TMBox;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.topicmap.TopicMapReadOnlyException;
import org.wandora.topicmap.TopicTools;
import org.wandora.topicmap.XTMPSI;
/**
* Gene Ontology Annotation file format import.
*
* See http://www.geneontology.org/GO.format.annotation.shtml
*
* @author akivela
*/
public class GOAImport extends AbstractImportTool implements WandoraTool {
private static final long serialVersionUID = 1L;
public GOAImport() {
}
@Override
public String getName() {
return "GOA import";
}
@Override
public String getDescription() {
return "Import Gene Ontology Annotation file, convert file to a topic map and merge it to current layer.";
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/import_goa.png");
}
@Override
public void importStream(Wandora wandora, String streamName, InputStream inputStream) {
try {
try {
wandora.getTopicMap().clearTopicMapIndexes();
}
catch(Exception e) {
log(e);
}
TopicMap map = null;
if(directMerge) {
map = solveContextTopicMap(wandora, getContext());
}
else {
map = new org.wandora.topicmap.memory.TopicMapImpl();
}
importGOA(inputStream, map);
if(!directMerge) {
if(newLayer) {
createNewLayer(map, streamName, wandora);
}
else {
log("Merging '" + streamName + "'.");
solveContextTopicMap(wandora, getContext()).mergeIn(map);
}
}
}
catch(TopicMapReadOnlyException tmroe) {
log("Topic map is write protected. Import failed.");
}
catch(Exception e) {
log("Reading '" + streamName + "' failed!", e);
}
}
public void importGOA(InputStream in, TopicMap map) {
if(in != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
long startTime = System.currentTimeMillis();
GOAParser goaParser = new GOAParser(reader, map, this);
goaParser.parse();
long endTime = System.currentTimeMillis();
long importTime = Math.round((endTime-startTime)/1000);
if(importTime > 1) log("Import took "+importTime+" seconds.");
}
}
@Override
public String getGUIText(int textType) {
switch(textType) {
case FILE_DIALOG_TITLE_TEXT: {
return "Select Gene Ontology Annotation file to import";
}
case URL_DIALOG_MESSAGE_TEXT: {
return "Type internet address of a Gene Ontology Annotation document to be imported";
}
}
return "";
}
// -------------------------------------------------------------------------
// ---------------------------------------------------------- OBO PARSER ---
// -------------------------------------------------------------------------
/**
* OBOParser class implements parser for OBO flat file format. OBOImport
* uses the parser to convert OBO flat files to Topic Maps.
*/
public class GOAParser {
public static final String SCHEMA_SI = "http://wandora.org/si/goa/schema";
public static final String GOA_SI = "http://wandora.org/si/goa/";
public static final String GOA_OBJECT_SI = GOA_SI + "object";
public static final String GOA_DATABASE_SI = GOA_SI + "db";
public static final String GOA_SYMBOL_SI = GOA_SI + "symbol";
public static final String GOA_QUALIFIER_SI = GOA_SI + "qualifier";
public static final String GOA_REFERENCE_SI = GOA_SI + "reference";
public static final String GOA_EVIDENCECODE_SI = GOA_SI + "reference";
public static final String GOA_WITHORFROM_SI = GOA_SI + "withorfrom";
public static final String GOA_ASPECT_SI = GOA_SI + "aspect";
public static final String GOA_SYNONYM_SI = GOA_SI + "synonym";
public static final String GOA_OBJECTTYPE_SI = GOA_SI + "object-type";
public static final String GOA_TAXON_SI = GOA_SI + "taxon";
public static final String GOA_DATE_SI = GOA_SI + "date";
public static final String GOA_ASSIGNEDBY_SI = GOA_SI + "assigned-by";
public static final String GOA_ORDER_SI = GOA_SI + "order";
public boolean debug = true;
private TopicMap tm;
private GOAImport parent;
private BufferedReader in;
private Topic root = null;
private Topic wandoraClass = null;
/**
* Constructor for GOAParser.
*
* @param in is the BufferedReader for GOA formatted file.
* @param tm is the Topic Map object where conversion is stored.
* @param parent is the GOAImport callback interface.
*/
public GOAParser(BufferedReader in, TopicMap tm, GOAImport parent) {
this.tm=tm;
this.parent=parent;
this.in=in;
initializeTopicMap(tm);
}
/**
* Creates frequently used topics into the Topic Map before
* conversion starts.
*
* @param tm is the Topic Map where initialization is targeted.
*/
public void initializeTopicMap(TopicMap tm) {
wandoraClass = getOrCreateTopic(TMBox.WANDORACLASS_SI, "Wandora class");
getOrCreateTopic(XTMPSI.getLang(OBO.LANG));
getOrCreateTopic(XTMPSI.DISPLAY, "Scope Display");
}
public void parse() {
parent.setProgressMax(1000);
try {
int lineCounter = 0;
String line = in.readLine();
String[] fields = null;
while(line!=null && !parent.forceStop()) {
if(!line.startsWith("!")) {
parent.setProgress(lineCounter++);
fields = line.split("\t");
if(fields.length > 0 && fields.length != 15) {
parent.log("Warning: Line "+lineCounter+" has illegal number of fields ("+fields.length+")");
parent.log(" Line: "+line);
}
else {
processFields(fields);
}
}
line = in.readLine();
}
}
catch(Exception e) {
parent.log(e);
}
}
private void processFields(String[] fields) {
String db = fields[0];
String objectID = fields[1];
String objectSymbol = fields[2];
String qualifiers = fields[3];
String goID = fields[4];
String references = fields[5];
String evidenceCode = fields[6];
String withOrFrom = fields[7];
String aspect = fields[8];
String objectName = fields[9];
String objectSynonyms = fields[10];
String objectType = fields[11];
String taxons = fields[12];
String date = fields[13];
String assignedBy = fields[14];
Topic annotationTopic = null;
try {
if(objectID != null && objectID.trim().length() > 0) {
annotationTopic = tm.createTopic();
annotationTopic.addSubjectIdentifier(TopicTools.createDefaultLocator());
Topic objectTopic = getOrCreateTopic(GOA_OBJECT_SI+"/"+objectID, objectID);
createAssociation("annotation-object", annotationTopic, "annotation", objectTopic, "object");
// ***** DB *****
if(db != null && db.trim().length() > 0) {
Topic dbTopic = getOrCreateTopic(GOA_DATABASE_SI+"/"+db, db);
createAssociation("database-object", objectTopic, "object", dbTopic, "database");
}
else {
parent.log("Warning: GOA has no valid database id (field 1)");
}
// ***** OBJECT SYMBOL *****
if(objectSymbol != null && objectSymbol.trim().length() > 0) {
if(!objectSymbol.equals(objectID)) {
objectTopic.setBaseName(objectSymbol + " ("+objectID+")");
}
}
else {
parent.log("Warning: GOA has no valid object symbol (field 3)");
}
// ***** QUALIFIERS *****
if(qualifiers != null && qualifiers.trim().length() > 0) {
String[] qs = null;
if(qualifiers.indexOf("|") != -1) {
qs = qualifiers.split("|");
}
else {
qs = new String[] { qualifiers };
}
for(int i=0; i<qs.length; i++) {
String q = qs[i];
if(q != null && q.trim().length() > 0) {
Topic qualifierTopic = getOrCreateTopic(GOA_QUALIFIER_SI+"/"+q, q);
createAssociation("annotation-qualifier", annotationTopic, "annotation", qualifierTopic, "qualifier");
}
}
}
// ***** GO ID *****
if(goID != null && goID.trim().length() > 0) {
Topic goTopic = OBO.createTopicForTerm(tm, goID);
createAssociation("annotation-go term", annotationTopic, "annotation", goTopic, "go term");
}
else {
parent.log("Warning: GOA has no valid go id (field 5)");
}
// ***** REFERENCES *****
if(references != null && references.trim().length() > 0) {
String[] rs = null;
if(references.indexOf("|") != -1) {
rs = references.split("|");
}
else {
rs = new String[] { references };
}
for(int i=0; i<rs.length; i++) {
String r = rs[i];
if(r != null && r.trim().length() > 0) {
Topic refTopic = getOrCreateTopic(GOA_REFERENCE_SI+"/"+r, r);
createAssociation("annotation-references", annotationTopic, "annotation", refTopic, "reference");
}
}
}
else {
parent.log("Warning: GOA has no valid references (field 6)");
}
// ***** EVIDENCE CODE *****
if(evidenceCode != null && evidenceCode.trim().length() > 0) {
Topic evidenceTopic = getOrCreateTopic(GOA_EVIDENCECODE_SI+"/"+evidenceCode, evidenceCode);
createAssociation("annotation-evidence", annotationTopic, "annotation", evidenceTopic, "evidence-code");
}
else {
parent.log("Warning: GOA has no valid evidence code (field 7)");
}
// ***** WITH (OR) FROM *****
if(withOrFrom != null && withOrFrom.trim().length() > 0) {
String[] p = null;
if(withOrFrom.indexOf("|") != -1) {
p = withOrFrom.split("|");
}
else {
p = new String[] { withOrFrom };
}
for(int i=0; i<p.length; i++) {
String r = p[i];
if(r != null && r.trim().length() > 0) {
Topic withOrFromTopic = getOrCreateTopic(GOA_WITHORFROM_SI+"/"+r, r);
createAssociation("annotation-evidence-addons", annotationTopic, "annotation", withOrFromTopic, "evidence-addon");
}
}
}
// ***** ASPECT *****
if(aspect != null && aspect.trim().length() > 0) {
Topic aspectTopic = getOrCreateTopic(GOA_ASPECT_SI+"/"+aspect, aspect);
createAssociation("annotation-aspect", annotationTopic, "annotation", aspectTopic, "aspect");
}
else {
parent.log("Warning: GOA has no valid aspect (field 9)");
}
// ***** OBJECT NAME *****
if(objectName != null && objectName.trim().length() > 0) {
objectTopic.setDisplayName("en", objectName);
}
// ***** SYNONYMS *****
if(objectSynonyms != null && objectSynonyms.trim().length() > 0) {
String[] ss = null;
if(objectSynonyms.indexOf("|") != -1) {
ss = objectSynonyms.split("|");
}
else {
ss = new String[] { objectSynonyms };
}
for(int i=0; i<ss.length; i++) {
String s = ss[i];
if(s != null && s.trim().length() > 0) {
Topic synonymTopic = getOrCreateTopic(GOA_SYNONYM_SI+"/"+s, s);
createAssociation("object-synonym", objectTopic, "object", synonymTopic, "synonym");
}
}
}
// ***** OBJECT TYPE *****
if(objectType != null && objectType.trim().length() > 0) {
Topic objectTypeTopic = getOrCreateTopic(GOA_OBJECTTYPE_SI+"/"+objectType, objectType);
createAssociation("object-type", objectTopic, "object", objectTypeTopic, "type");
}
else {
parent.log("Warning: GOA has no valid object type (field 12)");
}
// ***** TAXONS *****
if(taxons != null && taxons.trim().length() > 0) {
String[] ts = null;
if(objectSynonyms.indexOf("|") != -1) {
ts = taxons.split("|");
}
else {
ts = new String[] { taxons };
}
for(int i=0; i<ts.length; i++) {
String t = ts[i];
if(t != null && t.trim().length() > 0) {
Topic taxonTopic = getOrCreateTopic(GOA_TAXON_SI+"/"+t, t);
if(ts.length > 1) {
Topic orderTopic = getOrCreateTopic(GOA_ORDER_SI+"/"+i, ""+i);
createAssociation("annotation-taxon", annotationTopic, "annotation", taxonTopic, "taxon", orderTopic, "order");
}
else {
createAssociation("annotation-taxon", annotationTopic, "annotation", taxonTopic, "taxon");
}
}
}
}
else {
parent.log("Warning: GOA has no valid taxon (field 13)");
}
// ***** DATE *****
if(date != null && date.trim().length() > 0) {
Topic dateTopic = getOrCreateTopic(GOA_DATE_SI+"/"+date, date);
createAssociation("annotation-date", annotationTopic, "annotation", dateTopic, "date");
}
else {
parent.log("Warning: GOA has no valid date (field 14)");
}
// ***** ASSIGNED BY *****
if(assignedBy != null && assignedBy.trim().length() > 0) {
Topic assignedByTopic = getOrCreateTopic(GOA_ASSIGNEDBY_SI+"/"+assignedBy, assignedBy);
createAssociation("annotation-assigned-by", annotationTopic, "annotation", assignedByTopic, "assigned-by");
}
else {
parent.log("Warning: GOA has no valid assigned by field (field 15)");
}
}
else {
parent.log("Warning: GOA has no valid database object id (field 1). Rejecting GOA.");
}
}
catch(Exception e) {
parent.log(e);
}
}
// ---------------------------------------------------------------------
// ---------------------------------------------- TOPIC MAP HELPERS ----
// ---------------------------------------------------------------------
public Association createAssociation(String associationType, Topic player1Topic, String role1, Topic player2Topic, String role2, Topic player3Topic, String role3) throws TopicMapException {
Topic associationTypeTopic = createTopicForSchemaTerm(tm,associationType);
Association association = tm.createAssociation(associationTypeTopic);
Topic associationTypeTypeTopic = createSchemaTypeTopic(tm);
associationTypeTopic.addType(associationTypeTypeTopic);
Topic role1Topic = createTopicForSchemaTerm(tm,role1);
Topic role2Topic = createTopicForSchemaTerm(tm,role2);
Topic role3Topic = createTopicForSchemaTerm(tm,role3);
association.addPlayer(player1Topic, role1Topic);
association.addPlayer(player2Topic, role2Topic);
association.addPlayer(player3Topic, role3Topic);
player1Topic.addType(role1Topic);
player2Topic.addType(role2Topic);
player3Topic.addType(role3Topic);
return association;
}
public Association createAssociation(String associationType, Topic player1Topic, String role1, Topic player2Topic, String role2) throws TopicMapException {
Topic associationTypeTopic = createTopicForSchemaTerm(tm,associationType);
Association association = tm.createAssociation(associationTypeTopic);
Topic associationTypeTypeTopic = createSchemaTypeTopic(tm);
associationTypeTopic.addType(associationTypeTypeTopic);
Topic role1Topic = createTopicForSchemaTerm(tm,role1);
Topic role2Topic = createTopicForSchemaTerm(tm,role2);
association.addPlayer(player1Topic, role1Topic);
association.addPlayer(player2Topic, role2Topic);
player1Topic.addType(role1Topic);
player2Topic.addType(role2Topic);
return association;
}
public Topic createSchemaTypeTopic(TopicMap tm) throws TopicMapException {
String si = SCHEMA_SI;
Topic typeTopic = tm.getTopic(si);
if(typeTopic == null) {
typeTopic = getOrCreateTopic(si, "goa-schema");
Topic wandoraClass = getOrCreateTopic(TMBox.WANDORACLASS_SI, "Wandora class");
makeSubclassOf(typeTopic, wandoraClass);
}
return typeTopic;
}
public Topic createTopicForSchemaTerm(TopicMap tm, String schemaTerm) throws TopicMapException {
if(schemaTerm == null) return null;
String si = SCHEMA_SI+"/"+schemaTerm;
Topic schemaTermTopic = tm.getTopic(si);
if(schemaTermTopic == null) {
schemaTermTopic = getOrCreateTopic(new Locator(TopicTools.cleanDirtyLocator(si)), schemaTerm);
Topic schemaType = createSchemaTypeTopic(tm);
schemaTermTopic.addType(schemaType);
// Topic idType = OBO.createTopicForSchemaTerm(tm, SCHEMA_TERM_ID);
// setData(schemaTermTopic, idType, LANG, schemaTerm);
}
return schemaTermTopic;
}
private Topic getOrCreateTopic(String si, String basename) {
return getOrCreateTopic(new Locator(si), basename);
}
private Topic getOrCreateTopic(String si) {
return getOrCreateTopic(new Locator(si), null);
}
private Topic getOrCreateTopic(Locator si, String basename) {
if(tm == null) return null;
Topic topic = null;
try {
topic = tm.getTopic(si);
if(topic == null) {
topic = tm.createTopic();
topic.addSubjectIdentifier(si);
if(basename != null) topic.setBaseName(basename);
}
}
catch(Exception e) {
parent.log(e);
}
return topic;
}
private void setData(Topic t, Topic type, String lang, String text) throws TopicMapException {
if(t != null & type != null && lang != null && text != null) {
String langsi=XTMPSI.getLang("en");
Topic langT=t.getTopicMap().getTopic(langsi);
if(langT == null) {
langT = t.getTopicMap().createTopic();
langT.addSubjectIdentifier(new Locator(langsi));
try {
langT.setBaseName("Language " + lang.toUpperCase());
}
catch (Exception e) {
langT.setBaseName("Language " + langsi);
}
}
t.setData(type, langT, text);
}
}
private void makeSubclassOf(Topic t, Topic superclass) {
try {
Topic supersubClassTopic = getOrCreateTopic(XTMPSI.SUPERCLASS_SUBCLASS, OBO.SCHEMA_TERM_SUPERCLASS_SUBCLASS);
Topic subclassTopic = getOrCreateTopic(XTMPSI.SUBCLASS, OBO.SCHEMA_TERM_SUBCLASS);
Topic superclassTopic = getOrCreateTopic(XTMPSI.SUPERCLASS, OBO.SCHEMA_TERM_SUPERCLASS);
Association ta = tm.createAssociation(supersubClassTopic);
ta.addPlayer(t, subclassTopic);
ta.addPlayer(superclass, superclassTopic);
}
catch(Exception e) {
parent.log(e);
}
}
}
}
| 25,682 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AbstractImportTool.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/importers/AbstractImportTool.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* AbstractImportTool.java
*
* Created on 24. toukokuuta 2006, 13:15
*/
package org.wandora.application.tools.importers;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import javax.swing.Icon;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.WandoraToolType;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.UIBox;
import org.wandora.application.tools.AbstractWandoraTool;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.topicmap.layered.Layer;
import org.wandora.topicmap.layered.LayerStack;
import org.wandora.utils.HttpAuthorizer;
/**
*
* @author akivela
*/
public abstract class AbstractImportTool extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
// Importer types...
public final static int CUSTOM_IMPORTER = 1;
public final static int RAW_IMPORTER = 2;
public final static int FILE_IMPORTER = 4;
public final static int URL_IMPORTER = 8;
private AbstractImportDialog importSourceDialog;
private int selectedImportSource = FILE_IMPORTER;
public static final int TOPICMAP_RESET_FIRST = 1; // First bit
public static final int TOPICMAP_DIRECT_MERGE = 2; // Second bit
public static final int TOPICMAP_MAKE_NEW_LAYER = 4; // Third bit
public static final int WEB_IMPORT = 256; // Eight bit
public static final int ASK_SOURCE = 512; // SOURCE == INTERNET | LOCAL FILE SYSTEM
public static final int CLOSE_LOGS = 1024;
public static final int FILE_DIALOG_TITLE_TEXT = 100;
public static final int URL_DIALOG_MESSAGE_TEXT = 110;
/**
* Should the application reset everything before the import takes place.
*/
protected boolean resetWandoraFirst = false;
/**
* Are imported topics and associations added directly into the current topic map.
* If not, imported topics and associations are added into a temporary topic
* map first, and the temporary topic map is then merged into the current
* topic map.
*/
protected boolean directMerge = false;
/**
* Should the application create a new layer for the imported topic map.
*/
protected boolean newLayer = true;
protected boolean webImport = false;
protected boolean askSource = false;
protected boolean closeLogs = false;
public Object forceFiles = null;
/** Creates a new instance of AbstractImportTool */
public AbstractImportTool() {
}
public AbstractImportTool(int options) {
setOptions(options);
}
public void setOptions(int options) {
resetWandoraFirst = (options & TOPICMAP_RESET_FIRST) != 0;
directMerge = (options & TOPICMAP_DIRECT_MERGE) != 0;
newLayer = (options & TOPICMAP_MAKE_NEW_LAYER) != 0;
webImport = (options & WEB_IMPORT) != 0;
askSource = (options & ASK_SOURCE) != 0;
closeLogs = (options & CLOSE_LOGS) != 0;
}
public int getOptions(){
int options=0;
if(resetWandoraFirst) options|=TOPICMAP_RESET_FIRST;
if(directMerge) options|=TOPICMAP_DIRECT_MERGE;
if(newLayer) options|=TOPICMAP_MAKE_NEW_LAYER;
if(webImport) options|=WEB_IMPORT;
if(askSource) options|=ASK_SOURCE;
if(closeLogs) options|=CLOSE_LOGS;
return options;
}
@Override
public WandoraToolType getType(){
return WandoraToolType.createImportType();
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/import.png");
}
@Override
public void execute(Wandora wandora, Context context) {
if(forceFiles != null && forceFiles instanceof File) {
importFile(wandora, (File) forceFiles);
}
else if(forceFiles != null && forceFiles instanceof File[]) {
importFiles(wandora, (File []) forceFiles);
}
else if(forceFiles != null && forceFiles instanceof URL) {
importUrl(wandora, (URL) forceFiles);
}
else {
requestImports(wandora);
}
}
public void requestImports(Wandora wandora) {
importSourceDialog = new AbstractImportDialog(wandora, true);
importSourceDialog.initialize(this);
importSourceDialog.registerFileSource();
importSourceDialog.registerUrlSource();
importSourceDialog.registerRawSource();
if(webImport) {
importSourceDialog.registerUrlSource();
}
importSourceDialog.setVisible(true);
if(!importSourceDialog.wasAccepted()) return;
selectedImportSource = importSourceDialog.getSelectedSource();
if(selectedImportSource == URL_IMPORTER) {
String[] urlSources = importSourceDialog.getURLSources();
if(urlSources != null && urlSources.length > 0 ) {
String urlSource = null;
for(int i=0; i<urlSources.length; i++) {
urlSource = urlSources[i];
if(urlSource != null && urlSource.length() > 0) {
try {
importUrl(wandora, new URL(urlSource));
}
catch(Exception e) {
log(e);
closeLogs = false;
}
}
}
}
}
else if(selectedImportSource == FILE_IMPORTER) {
File[] fileSources = importSourceDialog.getFileSources();
if(fileSources != null && fileSources.length > 0) {
importFiles(wandora, fileSources);
}
}
else if(selectedImportSource == RAW_IMPORTER) {
String stringSource = importSourceDialog.getContent();
if(stringSource != null && stringSource.length() > 0) {
try {
InputStream streamSource = new ByteArrayInputStream(stringSource.getBytes());
importStream(wandora, "Raw data", streamSource);
}
catch(Exception e) {
log(e);
closeLogs = false;
}
}
}
else {
System.out.println("Illegal import source: "+selectedImportSource);
}
}
public void importUrl(Wandora wandora, URL forceURL) {
initializeImport(wandora);
try {
URLConnection urlConnection = null;
HttpAuthorizer httpAuthorizer = wandora.wandoraHttpAuthorizer;
if(httpAuthorizer != null) {
urlConnection = httpAuthorizer.getAuthorizedAccess(forceURL);
}
else {
urlConnection = forceURL.openConnection();
Wandora.initUrlConnection(urlConnection);
}
String contentType = urlConnection.getContentType();
String filename = forceURL.getFile();
int index = filename.lastIndexOf('/');
if(index > -1 && index < filename.length()) {
filename = filename.substring(index+1);
}
log("Reading URL '" + filename + "'.");
importStream(wandora, filename, urlConnection.getInputStream());
}
catch(Exception e) {
log(e);
closeLogs = false;
}
finalizeImport(wandora);
}
public void importFile(Wandora wandora, File file) {
initializeImport(wandora);
if(file.exists() && file.canRead()) {
try {
String filename = file.getName();
log("Reading file '" + filename + "'.");
InputStream in=new FileInputStream(file);
importStream(wandora, filename, in);
in.close();
}
catch(Exception e) {
closeLogs = false;
}
}
else {
log("File '" + file.getPath() + "' doesn't exists or can not be read!");
}
finalizeImport(wandora);
}
public void importFiles(Wandora wandora, File[] files) {
initializeImport(wandora);
int count = 0;
for(int i=0; i<files.length && !forceStop(); i++) {
if(files[i] != null) {
String filename = files[i].getName();
log("Reading file '" + filename + "'.");
if(files[i].exists() && files[i].canRead()) {
try {
InputStream in=new FileInputStream(files[i]);
importStream(wandora, files[i].getPath(), in);
count++;
in.close();
}
catch(Exception e) {
closeLogs = false;
}
}
else {
log("File '" + files[i].getPath() + "' doesn't exists or can not be read!");
closeLogs = false;
}
}
}
if(count > 1) {
log("Imported " + count + " files.");
}
finalizeImport(wandora);
}
// -------------------------------------------------------------------------
// --- EXTENDING CLASS SHOULD OVERWRITE THIS METHOD!!! ---------------------
// -------------------------------------------------------------------------
public abstract void importStream(Wandora admin, String streamName, InputStream inputStream);
public void initializeImport(Wandora wandora) {
setDefaultLogger();
if(resetWandoraFirst) {
log("Resetting Wandora!");
wandora.resetWandora();
resetWandoraFirst = false;
}
}
public void finalizeImport(Wandora wandora) {
log("Ready.");
if(closeLogs) setState(AbstractWandoraTool.CLOSE);
else setState(AbstractWandoraTool.WAIT);
}
public String getGUIText(int textType) {
switch(textType) {
case FILE_DIALOG_TITLE_TEXT: {
return "Select file to import";
}
case URL_DIALOG_MESSAGE_TEXT: {
return "Type the internet address of a document to be imported";
}
}
return "";
}
protected void createNewLayer(TopicMap topicMap, String streamName, Wandora wandora) throws TopicMapException {
if(topicMap != null) {
if(wandora != null) {
LayerStack layerStack = wandora.getTopicMap();
String layerName = getLayerNameFor(streamName, wandora);
log("Creating new layer '" + layerName + "'.");
Layer importedLayer = new Layer(topicMap,layerName,layerStack);
layerStack.addLayer(importedLayer);
wandora.layerTree.resetLayers();
wandora.layerTree.selectLayer(importedLayer);
}
}
}
protected String getLayerNameFor(String streamName, Wandora wandora) {
String layerName = ""+System.currentTimeMillis();
if(streamName != null) {
if(streamName.contains("/")) {
String streamNamePart = streamName.substring(streamName.lastIndexOf("/")+1);
if(streamNamePart.length() > 0) layerName = streamNamePart;
}
else if(streamName.contains("\\")) {
String streamNamePart = streamName.substring(streamName.lastIndexOf("\\")+1);
if(streamNamePart.length() > 0) layerName = streamNamePart;
}
else if(streamName.length() > 0) {
layerName = streamName;
}
}
LayerStack layerStack = wandora.getTopicMap();
if(layerStack.getLayer(layerName) != null) {
int c = 2;
String nextLayerName;
do {
nextLayerName = layerName + " " + c;
c++;
}
while(layerStack.getLayer(nextLayerName) != null);
layerName = nextLayerName;
}
return layerName;
}
}
| 13,439 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
XSLImportDialog.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/importers/XSLImportDialog.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* XSLImportDialog.java
*
* Created on October 4, 2004, 3:22 PM
*/
package org.wandora.application.tools.importers;
import java.io.File;
import org.wandora.application.Wandora;
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.SimpleFileChooser;
import org.wandora.application.gui.simple.SimpleLabel;
import org.wandora.utils.Options;
/**
*
* @author olli
*/
public class XSLImportDialog extends javax.swing.JDialog {
private static final long serialVersionUID = 1L;
private Wandora wandora;
public boolean accept = false;
/**
* Creates new form XSLImportDialog
*/
public XSLImportDialog(Wandora w, boolean modal) {
super(w, modal);
this.wandora=w;
initComponents();
Options options = w.getOptions();
String previousXML = options.get("XSLImport.xml");
if(previousXML != null) {
xmlTextField.setText(previousXML);
}
String previousXSL = options.get("XSLImport.xsl");
if(previousXSL != null) {
xslTextField.setText(previousXSL);
}
wandora.centerWindow(this);
setVisible(true);
}
public String getXML() {
return xmlTextField.getText();
}
public String getXSL() {
return xslTextField.getText();
}
/** 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;
jPanel2 = new javax.swing.JPanel();
jLabel1 = new SimpleLabel();
xmlTextField = new org.wandora.application.gui.simple.SimpleField();
xmlBrowseButton = new SimpleButton();
jPanel3 = new javax.swing.JPanel();
jLabel2 = new SimpleLabel();
xslTextField = new org.wandora.application.gui.simple.SimpleField();
xslBrowseButton = new SimpleButton();
jPanel1 = new javax.swing.JPanel();
okButton = new SimpleButton();
cancelButton = new SimpleButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Transform and merge XML");
getContentPane().setLayout(new java.awt.GridBagLayout());
jPanel2.setLayout(new java.awt.GridBagLayout());
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabel1.setText("XML file or URL");
jLabel1.setMaximumSize(new java.awt.Dimension(140, 14));
jLabel1.setMinimumSize(new java.awt.Dimension(140, 14));
jLabel1.setPreferredSize(new java.awt.Dimension(140, 14));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5);
jPanel2.add(jLabel1, gridBagConstraints);
xmlTextField.setMinimumSize(new java.awt.Dimension(450, 25));
xmlTextField.setPreferredSize(new java.awt.Dimension(450, 25));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
jPanel2.add(xmlTextField, gridBagConstraints);
xmlBrowseButton.setFont(org.wandora.application.gui.UIConstants.buttonLabelFont);
xmlBrowseButton.setText("Browse");
xmlBrowseButton.setMargin(new java.awt.Insets(2, 4, 2, 4));
xmlBrowseButton.setMinimumSize(new java.awt.Dimension(70, 25));
xmlBrowseButton.setPreferredSize(new java.awt.Dimension(70, 25));
xmlBrowseButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
xmlBrowseButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 0);
jPanel2.add(xmlBrowseButton, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 10, 0, 10);
getContentPane().add(jPanel2, gridBagConstraints);
jPanel3.setLayout(new java.awt.GridBagLayout());
jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabel2.setText("Stylesheet file or URL");
jLabel2.setMaximumSize(new java.awt.Dimension(140, 14));
jLabel2.setMinimumSize(new java.awt.Dimension(140, 14));
jLabel2.setPreferredSize(new java.awt.Dimension(140, 14));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5);
jPanel3.add(jLabel2, gridBagConstraints);
xslTextField.setMinimumSize(new java.awt.Dimension(450, 25));
xslTextField.setPreferredSize(new java.awt.Dimension(450, 25));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
jPanel3.add(xslTextField, gridBagConstraints);
xslBrowseButton.setFont(org.wandora.application.gui.UIConstants.buttonLabelFont);
xslBrowseButton.setText("Browse");
xslBrowseButton.setMargin(new java.awt.Insets(2, 4, 2, 4));
xslBrowseButton.setMinimumSize(new java.awt.Dimension(70, 25));
xslBrowseButton.setPreferredSize(new java.awt.Dimension(70, 25));
xslBrowseButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
xslBrowseButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 0);
jPanel3.add(xslBrowseButton, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(2, 10, 0, 10);
getContentPane().add(jPanel3, gridBagConstraints);
jPanel1.setMinimumSize(new java.awt.Dimension(165, 27));
jPanel1.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 5, 2));
okButton.setText("OK");
okButton.setMargin(new java.awt.Insets(2, 2, 2, 2));
okButton.setPreferredSize(new java.awt.Dimension(75, 23));
okButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
okButtonActionPerformed(evt);
}
});
jPanel1.add(okButton);
cancelButton.setText("Cancel");
cancelButton.setMargin(new java.awt.Insets(2, 2, 2, 2));
cancelButton.setPreferredSize(new java.awt.Dimension(75, 23));
cancelButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelButtonActionPerformed(evt);
}
});
jPanel1.add(cancelButton);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.insets = new java.awt.Insets(8, 5, 0, 5);
getContentPane().add(jPanel1, gridBagConstraints);
setSize(new java.awt.Dimension(631, 165));
}// </editor-fold>//GEN-END:initComponents
private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
String xmlInString = getXML();
if(!(xmlInString.startsWith("http:/") || xmlInString.startsWith("https:/") || xmlInString.startsWith("ftp:/") || xmlInString.startsWith("ftps:/"))) {
File xmlIn=new File(xmlInString);
if(!xmlIn.exists()) {
WandoraOptionPane.showMessageDialog(wandora, "XML source not found.", WandoraOptionPane.ERROR_MESSAGE);
return;
}
}
String xslInString = getXSL();
if(!(xmlInString.startsWith("http:/") || xmlInString.startsWith("https:/") || xmlInString.startsWith("ftp:/") || xmlInString.startsWith("ftps:/"))) {
File xslIn=new File(xslInString);
if(!xslIn.exists()) {
WandoraOptionPane.showMessageDialog(wandora,"Stylesheet source not found.", WandoraOptionPane.ERROR_MESSAGE);
return;
}
}
try {
wandora.getOptions().put("XSLImport.xml", getXML());
wandora.getOptions().put("XSLImport.xsl", getXSL());
}
catch(Exception e) {
e.printStackTrace();
}
accept = true;
setVisible(false);
}//GEN-LAST:event_okButtonActionPerformed
private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
accept = false;
this.setVisible(false);
}//GEN-LAST:event_cancelButtonActionPerformed
private void xslBrowseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_xslBrowseButtonActionPerformed
SimpleFileChooser chooser=UIConstants.getFileChooser();
if(chooser.open(wandora)==SimpleFileChooser.APPROVE_OPTION){
xslTextField.setText(chooser.getSelectedFile().getAbsolutePath());
}
}//GEN-LAST:event_xslBrowseButtonActionPerformed
private void xmlBrowseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_xmlBrowseButtonActionPerformed
SimpleFileChooser chooser=UIConstants.getFileChooser();
if(chooser.open(wandora)==SimpleFileChooser.APPROVE_OPTION){
xmlTextField.setText(chooser.getSelectedFile().getAbsolutePath());
}
}//GEN-LAST:event_xmlBrowseButtonActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton cancelButton;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JButton okButton;
private javax.swing.JButton xmlBrowseButton;
private javax.swing.JTextField xmlTextField;
private javax.swing.JButton xslBrowseButton;
private javax.swing.JTextField xslTextField;
// End of variables declaration//GEN-END:variables
}
| 11,861 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SQLTopicMapImport.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/importers/SQLTopicMapImport.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* SQLTopicMapImport.java
*
* Created on 20.6.2006, 10:24
*
*/
package org.wandora.application.tools.importers;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.LayerTree;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.database.DatabaseTopicMap;
import org.wandora.topicmap.undowrapper.UndoTopicMap;
/**
* @author akivela
*/
public class SQLTopicMapImport extends AbstractImportTool implements WandoraTool {
private static final long serialVersionUID = 1L;
/** Creates a new instance of SQLTopicMapImport */
public SQLTopicMapImport() {
}
public SQLTopicMapImport(int options) {
setOptions(options);
}
@Override
public String getDescription() {
return "Injects SQL statements in given file(s) into a database topic map. "+
"The statements should respect the schema of Wandora's database topic map.";
}
@Override
public String getName() {
return "SQL topic map import";
}
@Override
public void execute(Wandora admin, Context context) {
TopicMap topicMap = solveContextTopicMap(admin, context);
if(topicMap instanceof DatabaseTopicMap) {
super.execute(admin, context);
}
else if(topicMap instanceof org.wandora.topicmap.database2.DatabaseTopicMap) {
super.execute(admin, context);
}
else {
log("Selected topic map is not a database topic map! Unable to import SQL file.");
System.out.println("topicMap:"+topicMap);
}
}
@Override
public void importStream(Wandora wandora, String streamName, InputStream inputStream) {
BufferedReader reader = new BufferedReader( new InputStreamReader(inputStream) );
TopicMap topicMap = solveContextTopicMap(wandora, getContext());
if(topicMap instanceof DatabaseTopicMap) {
setDefaultLogger();
int count = 0;
int errorCount = 0;
DatabaseTopicMap dbTopicMap = (DatabaseTopicMap) topicMap;
try {
Connection connection = dbTopicMap.getConnection();
String query = reader.readLine();
while(query != null && query.length() > 0 && !forceStop()) {
try {
dbTopicMap.executeUpdate(query, connection);
query = reader.readLine();
count++;
}
catch(Exception e) {
log(e);
errorCount++;
}
}
}
catch(Exception e) {
log(e);
}
dbTopicMap.clearTopicMapIndexes();
wandora.getTopicMap().clearTopicIndex();
log("Injected " + count + " SQL lines into the database topic map.");
if(errorCount > 0) log("Encountered " + errorCount + " errors during inject.");
setState(WAIT);
}
else if(topicMap instanceof org.wandora.topicmap.database2.DatabaseTopicMap) {
setDefaultLogger();
int count = 0;
int errorCount = 0;
org.wandora.topicmap.database2.DatabaseTopicMap dbTopicMap =
(org.wandora.topicmap.database2.DatabaseTopicMap) topicMap;
try {
String query = reader.readLine();
while(query != null && query.length() > 0 && !forceStop()) {
try {
dbTopicMap.executeUpdate(query);
query = reader.readLine();
count++;
}
catch(Exception e) {
log(e);
errorCount++;
}
}
}
catch(Exception e) {
log(e);
}
dbTopicMap.clearTopicMapIndexes();
wandora.getTopicMap().clearTopicIndex();
log("Injected " + count + " SQL lines into the database topic map.");
if(errorCount > 0) log("Encountered " + errorCount + " errors during the inject.");
setState(WAIT);
}
else {
log("Selected topic map is not a database topic map. Can't import SQL file.");
}
}
@Override
public String getGUIText(int textType) {
switch(textType) {
case FILE_DIALOG_TITLE_TEXT: {
return "Select SQL file to import";
}
case URL_DIALOG_MESSAGE_TEXT: {
return "Type the internet address of a SQL document to be imported";
}
}
return "";
}
@Override
public TopicMap solveContextTopicMap(Wandora wandora, Context context) {
LayerTree layerTree = wandora.layerTree;
TopicMap topicMap = layerTree.getSelectedLayer().getTopicMap();
if(topicMap instanceof UndoTopicMap) {
return ((UndoTopicMap) topicMap).getWrappedTopicMap();
}
return topicMap;
}
@Override
public boolean requiresRefresh() {
return true;
}
}
| 6,292 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
BasicN3Import.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/importers/BasicN3Import.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* BasicN3Import.java
*
* Created on 10.7.2006, 16:06
*
*/
package org.wandora.application.tools.importers;
import java.io.InputStream;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.wandora.topicmap.TopicMap;
/**
*
* @author olli, akivela
*/
public class BasicN3Import extends BasicRDFImport {
private static final long serialVersionUID = 1L;
/** Creates a new instance of BasicN3Import */
public BasicN3Import() {
}
public BasicN3Import(int options){
super(options);
}
@Override
public String getName() {
return "Basic N3 import";
}
@Override
public String getDescription() {
return "Tool imports N3 file and merges RDF triplets to current topic map. \n"+
"Used schema is slightly more advanced than Simple RDF XML import. Topic \n"+
"base names are set when rdfs:label predicates are used and topic types \n"+
"with rdf:type predicates.";
}
@Override
public void importRDF(InputStream in, TopicMap map) {
if(in != null) {
// create an empty model
Model model = ModelFactory.createDefaultModel();
// read the RDF/XML file
model.read(in, "", "N3");
RDF2TopicMap(model, map);
}
}
}
| 2,171 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TopicMapImport.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/importers/TopicMapImport.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* TopicMapImport.java
*
* Created on June 18, 2004, 9:37 AM
*/
package org.wandora.application.tools.importers;
import java.io.InputStream;
import javax.swing.Icon;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.gui.UIBox;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.topicmap.TopicMapReadOnlyException;
/**
* <p>
* TopicMapImport is used to import JTM, LTM and XTM topic maps to Wandora.
* </p>
*
* @author olli & ak
*/
public class TopicMapImport extends AbstractImportTool implements WandoraTool {
private static final long serialVersionUID = 1L;
/**
* Creates a new instance of TopicMapImport
*/
public TopicMapImport() {
}
public TopicMapImport(int options) {
setOptions(options);
}
@Override
public String getName() {
return "Import topic map";
}
@Override
public String getDescription() {
return "Reads XTM, LTM or JTM topic map file and merges it to current layer or "+
"creates new layer for the topic map.";
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/merge_topicmap.png");
}
// -------------------------------------------------------------------------
@Override
public void initialize(Wandora wandora,org.wandora.utils.Options options,String prefix) throws TopicMapException {
}
@Override
public boolean isConfigurable(){
return true;
}
@Override
public void configure(Wandora wandora,org.wandora.utils.Options options,String prefix) throws TopicMapException {
//System.out.println(prefix);
TopicMapImportConfiguration dialog=new TopicMapImportConfiguration(wandora);
dialog.openDialog();
if(!dialog.wasAccepted()){
dialog.saveConfiguration();
}
}
@Override
public void writeOptions(Wandora wandora,org.wandora.utils.Options options,String prefix){
}
// -------------------------------------------------------------------------
@Override
public void importStream(Wandora wandora, String streamName, InputStream inputStream) {
try {
try {
wandora.getTopicMap().clearTopicMapIndexes();
}
catch(Exception e) {
log(e);
}
TopicMap map = null;
boolean checkConsistency = false;
if(directMerge) {
map = solveContextTopicMap(wandora, getContext());
checkConsistency = true;
}
else {
map = new org.wandora.topicmap.memory.TopicMapImpl();
}
if(streamName.toLowerCase().endsWith(".ltm")) {
map.importLTM(inputStream, getCurrentLogger());
}
else if(streamName.toLowerCase().endsWith(".jtm")) {
map.importJTM(inputStream, getCurrentLogger());
}
else {
map.importXTM(inputStream, getCurrentLogger(), checkConsistency);
}
if(!directMerge) {
if(newLayer) {
createNewLayer(map, streamName, wandora);
}
else {
TopicMap contextTopicMap = solveContextTopicMap(wandora, getContext());
log("Merging '"+ streamName +"'.");
contextTopicMap.mergeIn(map);
}
}
}
catch(TopicMapReadOnlyException tmroe) {
log("Topic map is write protected. Merge failed.");
}
catch(Exception e) {
log("Reading '" + streamName + "' failed after an exception", e);
}
}
@Override
public String getGUIText(int textType) {
switch(textType) {
case FILE_DIALOG_TITLE_TEXT: {
return "Select XTM, LTM or JTM file to import";
}
case URL_DIALOG_MESSAGE_TEXT: {
return "Type the internet address of imported XTM, LTM or JTM document";
}
}
return "";
}
}
| 5,132 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
BasicRDFJsonLDImport.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/importers/BasicRDFJsonLDImport.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.application.tools.importers;
import java.io.InputStream;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.wandora.topicmap.TopicMap;
/**
*
* @author olli
*/
public class BasicRDFJsonLDImport extends BasicRDFImport {
private static final long serialVersionUID = 1L;
public BasicRDFJsonLDImport() {
}
public BasicRDFJsonLDImport(int options) {
setOptions(options);
}
@Override
public String getName() {
return "Basic JSON-LD import";
}
@Override
public String getDescription() {
return "Tool imports JSON-LD file and merges RDF triplets to current topic map. \n"+
"Used schema is slightly more advanced than Simple RDF XML import. Topic \n"+
"base names are set when rdfs:label predicates are used and topic types \n"+
"with rdf:type predicates.";
}
@Override
public void importRDF(InputStream in, TopicMap map) {
if(in != null) {
// create an empty model
Model model = ModelFactory.createDefaultModel();
// read the RDF json-ld file
model.read(in, "", "JSON-LD");
RDF2TopicMap(model, map);
}
}
}
| 2,089 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
ImportConfiguration.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/importers/ImportConfiguration.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* ImportConfiguration.java
*
* Created on 10.7.2006, 12:39
*/
package org.wandora.application.tools.importers;
import org.wandora.application.gui.simple.SimpleButton;
import org.wandora.application.gui.simple.SimpleCheckBox;
import org.wandora.utils.swing.GuiTools;
/**
*
* @author olli
*/
public class ImportConfiguration extends javax.swing.JDialog {
private static final long serialVersionUID = 1L;
private boolean cancelled=true;
/** Creates new form ImportConfiguration */
public ImportConfiguration(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
this.setTitle("OBO configuration");
GuiTools.centerWindow(this,parent);
}
/** 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;
resetFirstCheckBox = new SimpleCheckBox();
directMergeCheckBox = new SimpleCheckBox();
newLayerCheckBox = new SimpleCheckBox();
webImportCheckBox = new SimpleCheckBox();
askSourceCheckBox = new SimpleCheckBox();
jPanel1 = new javax.swing.JPanel();
okButton = new SimpleButton();
cancelButton = new SimpleButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
getContentPane().setLayout(new java.awt.GridBagLayout());
resetFirstCheckBox.setText("Reset topic map before import");
resetFirstCheckBox.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
resetFirstCheckBox.setMargin(new java.awt.Insets(0, 0, 0, 0));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 5, 10);
getContentPane().add(resetFirstCheckBox, gridBagConstraints);
directMergeCheckBox.setText("Merge directly to topic map");
directMergeCheckBox.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
directMergeCheckBox.setMargin(new java.awt.Insets(0, 0, 0, 0));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10);
getContentPane().add(directMergeCheckBox, gridBagConstraints);
newLayerCheckBox.setText("Make new layer for imported topic map");
newLayerCheckBox.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
newLayerCheckBox.setMargin(new java.awt.Insets(0, 0, 0, 0));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10);
getContentPane().add(newLayerCheckBox, gridBagConstraints);
webImportCheckBox.setText("Import from web");
webImportCheckBox.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
webImportCheckBox.setMargin(new java.awt.Insets(0, 0, 0, 0));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10);
getContentPane().add(webImportCheckBox, gridBagConstraints);
askSourceCheckBox.setText("Ask import source");
askSourceCheckBox.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
askSourceCheckBox.setMargin(new java.awt.Insets(0, 0, 0, 0));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10);
getContentPane().add(askSourceCheckBox, gridBagConstraints);
jPanel1.setLayout(new java.awt.GridBagLayout());
okButton.setText("OK");
okButton.setMargin(new java.awt.Insets(2, 5, 2, 5));
okButton.setPreferredSize(new java.awt.Dimension(70, 23));
okButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
okButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5);
jPanel1.add(okButton, gridBagConstraints);
cancelButton.setText("Cancel");
cancelButton.setMargin(new java.awt.Insets(2, 5, 2, 5));
cancelButton.setPreferredSize(new java.awt.Dimension(70, 23));
cancelButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5);
jPanel1.add(cancelButton, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.insets = new java.awt.Insets(5, 10, 10, 10);
getContentPane().add(jPanel1, gridBagConstraints);
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
setBounds((screenSize.width-311)/2, (screenSize.height-210)/2, 311, 210);
}// </editor-fold>//GEN-END:initComponents
private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
cancelled=true;
this.setVisible(false);
}//GEN-LAST:event_cancelButtonActionPerformed
private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
cancelled=false;
this.setVisible(false);
}//GEN-LAST:event_okButtonActionPerformed
public boolean wasCancelled(){return cancelled;}
public int getOptions(){
int options=0;
if(resetFirstCheckBox.isSelected()) options|=AbstractImportTool.TOPICMAP_RESET_FIRST;
if(directMergeCheckBox.isSelected()) options|=AbstractImportTool.TOPICMAP_DIRECT_MERGE;
if(newLayerCheckBox.isSelected()) options|=AbstractImportTool.TOPICMAP_MAKE_NEW_LAYER;
if(webImportCheckBox.isSelected()) options|=AbstractImportTool.WEB_IMPORT;
if(askSourceCheckBox.isSelected()) options|=AbstractImportTool.ASK_SOURCE;
return options;
}
public void setOptions(int options){
resetFirstCheckBox.setSelected((options&AbstractImportTool.TOPICMAP_RESET_FIRST)!=0);
directMergeCheckBox.setSelected((options&AbstractImportTool.TOPICMAP_DIRECT_MERGE)!=0);
newLayerCheckBox.setSelected((options&AbstractImportTool.TOPICMAP_MAKE_NEW_LAYER)!=0);
webImportCheckBox.setSelected((options&AbstractImportTool.WEB_IMPORT)!=0);
askSourceCheckBox.setSelected((options&AbstractImportTool.ASK_SOURCE)!=0);
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JCheckBox askSourceCheckBox;
private javax.swing.JButton cancelButton;
private javax.swing.JCheckBox directMergeCheckBox;
private javax.swing.JPanel jPanel1;
private javax.swing.JCheckBox newLayerCheckBox;
private javax.swing.JButton okButton;
private javax.swing.JCheckBox resetFirstCheckBox;
private javax.swing.JCheckBox webImportCheckBox;
// End of variables declaration//GEN-END:variables
}
| 9,560 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AbstractImportDialog.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/importers/AbstractImportDialog.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
* AbstractImportDialog.java
*
* Created on 21.1.2009, 13:14
*/
package org.wandora.application.tools.importers;
import java.awt.Component;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.UIConstants;
import org.wandora.application.gui.simple.SimpleFileChooser;
import org.wandora.application.gui.simple.SimpleTextPane;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.Topic;
import org.wandora.utils.IObox;
/**
*
* @author akivela
*/
public class AbstractImportDialog extends javax.swing.JDialog {
private static final long serialVersionUID = 1L;
private Wandora wandora = null;
private WandoraTool parentTool = null;
private boolean wasAccepted = false;
private HashMap<Component,Integer> registeredSources = null;
/** Creates new form AbstractImportDialog */
public AbstractImportDialog(Wandora wandora, boolean modal) {
super(wandora, modal);
this.wandora = wandora;
initComponents();
initialize(null);
}
public void initialize(WandoraTool parentTool) {
this.parentTool = parentTool;
wasAccepted = false;
((SimpleTextPane) fileTextPane).dropFileNames(true);
((SimpleTextPane) fileTextPane).setLineWrap(false);
((SimpleTextPane) urlTextPane).setLineWrap(false);
if(parentTool != null) setTitle(parentTool.getName());
else setTitle("Select imported resources");
setSize(640,400);
if(wandora != null) wandora.centerWindow(this);
registeredSources = new HashMap<Component,Integer>();
}
public boolean wasAccepted() {
return wasAccepted;
}
public int getSelectedSource() {
Component selectedComponent = tabbedSourcePane.getSelectedComponent();
Integer source = registeredSources.get(selectedComponent);
return source.intValue();
}
public void registerSource(String name, Component component, int id) {
if(component == null) return;
if(registeredSources.get(component) == null) {
registeredSources.put(component, Integer.valueOf(id));
tabbedSourcePane.addTab(name, component);
}
}
public void registerUrlSource() {
registerSource("Urls", urlPanel, AbstractImportTool.URL_IMPORTER);
}
public void registerFileSource() {
registerSource("Files", filePanel, AbstractImportTool.FILE_IMPORTER);
}
public void registerRawSource() {
registerSource("Raw", rawPanel, AbstractImportTool.RAW_IMPORTER);
}
public void selectUrlSource() {
tabbedSourcePane.setSelectedComponent(urlPanel);
}
// --- CONTENT ---
public String getContent() {
return rawTextPane.getText();
}
// --- FILE SOURCE ---
public File[] getFileSources() {
String input = fileTextPane.getText();
String[] filenames = splitText(input);
ArrayList<File> files = new ArrayList<File>();
File f = null;
for(int i=0; i<filenames.length; i++) {
if(filenames[i] != null && filenames[i].trim().length() > 0) {
f = new File(filenames[i]);
if(f.exists()) files.add(f);
else {
if(parentTool != null) parentTool.log("File '"+filenames[i]+"' not found!");
}
}
}
return files.toArray( new File[] {} );
}
// --- URL SOURCE ---
public String[] getURLSources() {
String input = urlTextPane.getText();
String[] urls = splitText(input);
return urls;
}
private String[] splitText(String str) {
if(str == null) return null;
if(str.indexOf("\n") != -1) {
String[] s = str.split("\n");
for(int i=0; i<s.length; i++) {
s[i] = s[i].trim();
}
return s;
}
else {
return new String[] { str.trim() };
}
}
// -------------------------------------------------------------------------
private void selectFiles() {
SimpleFileChooser chooser = UIConstants.getFileChooser();
chooser.setMultiSelectionEnabled(true);
chooser.setDialogTitle("Import");
chooser.setApproveButtonText("Select");
chooser.setFileSelectionMode(SimpleFileChooser.FILES_AND_DIRECTORIES);
//if(accessoryPanel != null) { chooser.setAccessory(accessoryPanel); }
if(chooser.open(wandora, SimpleFileChooser.OPEN_DIALOG)==SimpleFileChooser.APPROVE_OPTION) {
File[] files = chooser.getSelectedFiles();
File f = null;
String fs = "";
for(int i=0; i<files.length; i++) {
f = files[i];
fs = fs + f.getAbsolutePath();
if(i<files.length-1) fs = fs + "\n";
}
String s = fileTextPane.getText();
if(s == null || s.length() == 0) s = fs;
else s = s + "\n" + fs;
fileTextPane.setText(s);
}
}
private void selectContextSLFiles() {
if(parentTool == null) return;
Context context = parentTool.getContext();
Iterator iter = context.getContextObjects();
Object o = null;
Topic t = null;
Locator locator = null;
StringBuilder sb = new StringBuilder("");
while(iter.hasNext()) {
try {
o = iter.next();
if(o == null) continue;
if(o instanceof Topic) {
t = (Topic) o;
if(!t.isRemoved()) {
locator = t.getSubjectLocator();
if(locator != null) {
String locatorStr = locator.toExternalForm();
if(locatorStr.startsWith("file:")) {
locatorStr = IObox.getFileFromURL(locatorStr);
sb.append(locatorStr).append("\n");
}
}
}
}
}
catch(Exception e) {
parentTool.log(e);
}
}
String s = urlTextPane.getText();
if(s == null || s.length() == 0) s = sb.toString();
else s = s + "\n" + sb.toString();
fileTextPane.setText(s);
}
private void selectContextSLs() {
if(parentTool == null) return;
Context context = parentTool.getContext();
Iterator iter = context.getContextObjects();
Object o = null;
Topic t = null;
Locator locator = null;
StringBuilder sb = new StringBuilder("");
while(iter.hasNext()) {
try {
o = iter.next();
if(o == null) continue;
if(o instanceof Topic) {
t = (Topic) o;
if(!t.isRemoved()) {
locator = t.getSubjectLocator();
if(locator != null) {
String locatorStr = locator.toExternalForm();
sb.append(locatorStr).append("\n");
}
}
}
}
catch(Exception e) {
parentTool.log(e);
}
}
String s = urlTextPane.getText();
if(s == null || s.length() == 0) s = sb.toString();
else s = s + "\n" + sb.toString();
urlTextPane.setText(s);
}
private void selectContextSIs() {
if(parentTool == null) return;
Context context = parentTool.getContext();
Iterator iter = context.getContextObjects();
Object o = null;
Topic t = null;
Locator locator = null;
StringBuilder sb = new StringBuilder("");
while(iter.hasNext()) {
try {
o = iter.next();
if(o == null) continue;
if(o instanceof Topic) {
t = (Topic) o;
if(!t.isRemoved()) {
Collection<Locator> ls = t.getSubjectIdentifiers();
Iterator<Locator> ils = ls.iterator();
while(ils.hasNext()) {
locator = ils.next();
if(locator != null) {
String locatorStr = locator.toExternalForm();
sb.append(locatorStr).append("\n");
}
}
}
}
}
catch(Exception e) {
parentTool.log(e);
}
}
String s = urlTextPane.getText();
if(s == null || s.length() == 0) s = sb.toString();
else s = s + "\n" + sb.toString();
urlTextPane.setText(s);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
urlPanel = new javax.swing.JPanel();
urlLabel = new org.wandora.application.gui.simple.SimpleLabel();
urlScrollPane = new javax.swing.JScrollPane();
urlTextPane = new org.wandora.application.gui.simple.SimpleTextPane();
urlButtonPanel = new javax.swing.JPanel();
urlGetSIButton = new org.wandora.application.gui.simple.SimpleButton();
urlGetSLButton = new org.wandora.application.gui.simple.SimpleButton();
urlClearButton = new org.wandora.application.gui.simple.SimpleButton();
filePanel = new javax.swing.JPanel();
fileLabel = new org.wandora.application.gui.simple.SimpleLabel();
fileScrollPane = new javax.swing.JScrollPane();
fileTextPane = new org.wandora.application.gui.simple.SimpleTextPane();
fileButtonPanel = new javax.swing.JPanel();
fileBrowseButton = new org.wandora.application.gui.simple.SimpleButton();
fileGetSLButton = new org.wandora.application.gui.simple.SimpleButton();
fileClearButton = new org.wandora.application.gui.simple.SimpleButton();
rawPanel = new javax.swing.JPanel();
rawLabel = new org.wandora.application.gui.simple.SimpleLabel();
rawScrollPane = new javax.swing.JScrollPane();
rawTextPane = new org.wandora.application.gui.simple.SimpleTextPane();
tabbedSourcePane = new org.wandora.application.gui.simple.SimpleTabbedPane();
buttonPanel = new javax.swing.JPanel();
fillerPanel = new javax.swing.JPanel();
importButton = new org.wandora.application.gui.simple.SimpleButton();
cancelButton = new org.wandora.application.gui.simple.SimpleButton();
urlPanel.setLayout(new java.awt.GridBagLayout());
urlLabel.setText("<html>Select URL resources to be imported. Enter URLs below or get subject identifiers or subject locators from context topics.</html>");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
urlPanel.add(urlLabel, gridBagConstraints);
urlScrollPane.setPreferredSize(new java.awt.Dimension(10, 100));
urlScrollPane.setViewportView(urlTextPane);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 5);
urlPanel.add(urlScrollPane, gridBagConstraints);
urlButtonPanel.setLayout(new java.awt.GridBagLayout());
urlGetSIButton.setText("Get subject identifiers");
urlGetSIButton.setMargin(new java.awt.Insets(1, 6, 1, 6));
urlGetSIButton.setPreferredSize(new java.awt.Dimension(140, 21));
urlGetSIButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
urlGetSIButtonMouseReleased(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 1);
urlButtonPanel.add(urlGetSIButton, gridBagConstraints);
urlGetSLButton.setText("Get subject locators");
urlGetSLButton.setMargin(new java.awt.Insets(1, 6, 1, 6));
urlGetSLButton.setPreferredSize(new java.awt.Dimension(140, 21));
urlGetSLButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
urlGetSLButtonMouseReleased(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 1);
urlButtonPanel.add(urlGetSLButton, gridBagConstraints);
urlClearButton.setText("Clear");
urlClearButton.setMargin(new java.awt.Insets(1, 6, 1, 6));
urlClearButton.setPreferredSize(new java.awt.Dimension(60, 21));
urlClearButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
urlClearButtonMouseReleased(evt);
}
});
urlButtonPanel.add(urlClearButton, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
urlPanel.add(urlButtonPanel, gridBagConstraints);
filePanel.setLayout(new java.awt.GridBagLayout());
fileLabel.setText("<html>Select files to be imported. Enter or browse or get subject locator files. Text area accepts file drops too.</html>");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
filePanel.add(fileLabel, gridBagConstraints);
fileScrollPane.setPreferredSize(new java.awt.Dimension(10, 100));
fileScrollPane.setViewportView(fileTextPane);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 5);
filePanel.add(fileScrollPane, gridBagConstraints);
fileButtonPanel.setLayout(new java.awt.GridBagLayout());
fileBrowseButton.setText("Browse");
fileBrowseButton.setMargin(new java.awt.Insets(1, 6, 1, 6));
fileBrowseButton.setPreferredSize(new java.awt.Dimension(70, 21));
fileBrowseButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
fileBrowseButtonMouseReleased(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 1);
fileButtonPanel.add(fileBrowseButton, gridBagConstraints);
fileGetSLButton.setText("Get subject locators");
fileGetSLButton.setMargin(new java.awt.Insets(1, 6, 1, 6));
fileGetSLButton.setPreferredSize(new java.awt.Dimension(130, 21));
fileGetSLButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
fileGetSLButtonMouseReleased(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 1);
fileButtonPanel.add(fileGetSLButton, gridBagConstraints);
fileClearButton.setText("Clear");
fileClearButton.setMargin(new java.awt.Insets(1, 6, 1, 6));
fileClearButton.setPreferredSize(new java.awt.Dimension(60, 21));
fileClearButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
fileClearButtonMouseReleased(evt);
}
});
fileButtonPanel.add(fileClearButton, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
filePanel.add(fileButtonPanel, gridBagConstraints);
rawPanel.setLayout(new java.awt.GridBagLayout());
rawLabel.setText("<html>Enter, paste or drop the actual content for the importer.</html>");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rawPanel.add(rawLabel, gridBagConstraints);
rawScrollPane.setPreferredSize(new java.awt.Dimension(10, 100));
rawScrollPane.setViewportView(rawTextPane);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 5, 5, 5);
rawPanel.add(rawScrollPane, gridBagConstraints);
getContentPane().setLayout(new java.awt.GridBagLayout());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 4, 0);
getContentPane().add(tabbedSourcePane, gridBagConstraints);
buttonPanel.setLayout(new java.awt.GridBagLayout());
fillerPanel.setPreferredSize(new java.awt.Dimension(100, 10));
javax.swing.GroupLayout fillerPanelLayout = new javax.swing.GroupLayout(fillerPanel);
fillerPanel.setLayout(fillerPanelLayout);
fillerPanelLayout.setHorizontalGroup(
fillerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 270, Short.MAX_VALUE)
);
fillerPanelLayout.setVerticalGroup(
fillerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 10, Short.MAX_VALUE)
);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
buttonPanel.add(fillerPanel, gridBagConstraints);
importButton.setText("Import");
importButton.setMargin(new java.awt.Insets(2, 2, 2, 2));
importButton.setPreferredSize(new java.awt.Dimension(70, 23));
importButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
importButtonMouseReleased(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3);
buttonPanel.add(importButton, gridBagConstraints);
cancelButton.setText("Cancel");
cancelButton.setMargin(new java.awt.Insets(2, 2, 2, 2));
cancelButton.setPreferredSize(new java.awt.Dimension(70, 23));
cancelButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
cancelButtonMouseReleased(evt);
}
});
buttonPanel.add(cancelButton, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 4);
getContentPane().add(buttonPanel, gridBagConstraints);
pack();
}// </editor-fold>//GEN-END:initComponents
private void urlClearButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_urlClearButtonMouseReleased
this.urlTextPane.setText("");
}//GEN-LAST:event_urlClearButtonMouseReleased
private void fileClearButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_fileClearButtonMouseReleased
this.fileTextPane.setText("");
}//GEN-LAST:event_fileClearButtonMouseReleased
private void cancelButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cancelButtonMouseReleased
wasAccepted = false;
setVisible(false);
}//GEN-LAST:event_cancelButtonMouseReleased
private void importButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_importButtonMouseReleased
wasAccepted = true;
setVisible(false);
}//GEN-LAST:event_importButtonMouseReleased
private void fileBrowseButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_fileBrowseButtonMouseReleased
selectFiles();
}//GEN-LAST:event_fileBrowseButtonMouseReleased
private void fileGetSLButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_fileGetSLButtonMouseReleased
selectContextSLFiles();
}//GEN-LAST:event_fileGetSLButtonMouseReleased
private void urlGetSLButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_urlGetSLButtonMouseReleased
selectContextSLs();
}//GEN-LAST:event_urlGetSLButtonMouseReleased
private void urlGetSIButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_urlGetSIButtonMouseReleased
selectContextSIs();
}//GEN-LAST:event_urlGetSIButtonMouseReleased
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel buttonPanel;
private javax.swing.JButton cancelButton;
private javax.swing.JButton fileBrowseButton;
private javax.swing.JPanel fileButtonPanel;
private javax.swing.JButton fileClearButton;
private javax.swing.JButton fileGetSLButton;
private javax.swing.JLabel fileLabel;
private javax.swing.JPanel filePanel;
private javax.swing.JScrollPane fileScrollPane;
private javax.swing.JTextPane fileTextPane;
private javax.swing.JPanel fillerPanel;
private javax.swing.JButton importButton;
private javax.swing.JLabel rawLabel;
private javax.swing.JPanel rawPanel;
private javax.swing.JScrollPane rawScrollPane;
private javax.swing.JTextPane rawTextPane;
private javax.swing.JTabbedPane tabbedSourcePane;
private javax.swing.JPanel urlButtonPanel;
private javax.swing.JButton urlClearButton;
private javax.swing.JButton urlGetSIButton;
private javax.swing.JButton urlGetSLButton;
private javax.swing.JLabel urlLabel;
private javax.swing.JPanel urlPanel;
private javax.swing.JScrollPane urlScrollPane;
private javax.swing.JTextPane urlTextPane;
// End of variables declaration//GEN-END:variables
}
| 25,463 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
BasicRDFImport.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/importers/BasicRDFImport.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* BasicRDFImport.java
*
* Created on 10.7.2006, 11:39
*
*/
package org.wandora.application.tools.importers;
import java.util.List;
import org.apache.jena.rdf.model.Literal;
import org.apache.jena.rdf.model.Property;
import org.apache.jena.rdf.model.RDFList;
import org.apache.jena.rdf.model.RDFNode;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.rdf.model.Statement;
import org.apache.jena.vocabulary.RDF;
import org.apache.jena.vocabulary.RDFS;
import org.wandora.application.tools.extractors.rdf.rdfmappings.RDFMapping;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.topicmap.XTMPSI;
/**
*
* @author olli
*/
public class BasicRDFImport extends SimpleRDFImport {
private static final long serialVersionUID = 1L;
/** Creates a new instance of BasicRDFImport */
public BasicRDFImport() {
}
public BasicRDFImport(int options){
super(options);
}
@Override
public String getName() {
return "Basic RDF import";
}
@Override
public String getDescription() {
return "Tool imports RDF XML file and merges RDF triplets to current topic map. \n"+
"Used schema is slightly more advanced than Simple RDF XML import. Topic \n"+
"base names are set when rdfs:label predicates are used and topic types \n"+
"with rdf:type predicates.";
}
public static String BASENAME_LOCATOR=RDFS.label.toString();
public static String TYPE_LOCATOR=RDF.type.toString();
@Override
public void handleStatement(Statement stmt,TopicMap map,Topic subjectType,Topic predicateType,Topic objectType) throws TopicMapException {
Resource subject = stmt.getSubject(); // get the subject
Property predicate = stmt.getPredicate(); // get the predicate
RDFNode object = stmt.getObject(); // get the object
String lan = null;
String predicateS=predicate.toString();
if(predicateS!=null && (
predicateS.equals(RDFMapping.RDF_NS+"first") ||
predicateS.equals(RDFMapping.RDF_NS+"rest") ) ) {
// skip broken down list statements, the list
// should be handled properly when they are the object
// of some other statement
return;
}
try {
lan = stmt.getLanguage();
}
catch(Exception e) { /*NOTHING!*/ }
Topic subjectTopic = getOrCreateTopic(map, subject);
Topic predicateTopic = getOrCreateTopic(map, predicate);
subjectTopic.addType(subjectType);
predicateTopic.addType(predicateType);
if(object.isLiteral()) {
if(predicate.toString().equals(BASENAME_LOCATOR)){
subjectTopic.setBaseName(((Literal)object).getString()+" ("+subject.toString()+")");
}
else {
if(lan == null) {
subjectTopic.setData(predicateTopic, getOrCreateTopic(map, occurrenceScopeSI), ((Literal) object).getString());
}
else {
subjectTopic.setData(predicateTopic, getOrCreateTopic(map, XTMPSI.getLang(lan)), ((Literal) object).getString());
}
}
}
else if(object.isResource()) {
if(object.canAs(RDFList.class)){
List<RDFNode> list=((RDFList)object.as(RDFList.class)).asJavaList();
int counter=1;
Topic orderRole = getOrCreateTopic(map, RDF_LIST_ORDER);
for(RDFNode listObject : list){
if(!listObject.isResource()){
log("List element is not a resource, skipping.");
continue;
}
Topic objectTopic = getOrCreateTopic(map, listObject.toString());
objectTopic.addType(objectType);
Topic orderTopic = getOrCreateTopic(map, RDF_LIST_ORDER+"/"+counter);
if(orderTopic.getBaseName()==null) orderTopic.setBaseName(""+counter);
Association association = map.createAssociation(predicateTopic);
association.addPlayer(subjectTopic, subjectType);
association.addPlayer(objectTopic, objectType);
association.addPlayer(orderTopic, orderRole);
counter++;
}
}
else {
Topic objectTopic = getOrCreateTopic(map, (Resource)object);
if(predicate.toString().equals(TYPE_LOCATOR)){
subjectTopic.addType(objectTopic);
}
else {
Association association = map.createAssociation(predicateTopic);
association.addPlayer(subjectTopic, subjectType);
association.addPlayer(objectTopic, objectType);
objectTopic.addType(objectType);
}
}
}
else if(object.isURIResource()) {
log("URIResource found but not handled!");
}
}
}
| 6,148 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
XSLImport.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/importers/XSLImport.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* XSLImport.java
*
* Created on October 4, 2004, 3:18 PM
*/
package org.wandora.application.tools.importers;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.net.URL;
import javax.swing.Icon;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.UIBox;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapReadOnlyException;
/**
*
* @author olli, akivela
*/
public class XSLImport extends AbstractImportTool implements WandoraTool {
private static final long serialVersionUID = 1L;
String forceXSL = null;
String forceXML = null;
/**
* Creates a new instance of XSLImport
*/
public XSLImport() {
}
public XSLImport(int options) {
setOptions(options);
}
public XSLImport(String xsl, String xml) {
forceXSL = xsl;
forceXML = xml;
}
@Override
public void execute(Wandora wandora, Context context) {
String xmlIn = null;
String xslIn = null;
XSLImportDialog d = null;
if(forceXSL == null || forceXML == null) {
d = new XSLImportDialog(wandora,true);
xmlIn = d.getXML();
xslIn = d.getXSL();
}
else {
xmlIn = forceXML;
xslIn = forceXSL;
}
if(d == null || d.accept) {
setDefaultLogger();
if(resetWandoraFirst) {
log("Resetting Wandora!");
wandora.resetWandora();
}
final Wandora fadmin = wandora;
final String fxmlIn = xmlIn;
final String fxslIn = xslIn;
try {
final Transformer trans=TransformerFactory.newInstance().newTransformer(new StreamSource(createInputStreamFor(xslIn)));
final Source xmlSource=new StreamSource(createInputStreamFor(xmlIn));
final PipedOutputStream pout=new PipedOutputStream();
final PipedInputStream pin=new PipedInputStream(pout);
final XSLImport thisf = this;
// --- TRANSFORMING ---
Thread transformThread=new Thread(){
public void run() {
try {
thisf.log("Transforming XML '" + fxmlIn + "'." );
trans.transform(xmlSource, new StreamResult(pout));
pout.close();
thisf.log("Transformation succeeded!" );
}
catch(Exception e) {
thisf.log("Transformation fails!" );
thisf.log(e);
}
}
};
transformThread.start();
// --- PARSING ---
Thread parserThread=new Thread(){
public void run(){
try {
try {
fadmin.getTopicMap().clearTopicMapIndexes();
}
catch(Exception e) {
log(e);
}
String filename = fxmlIn;
TopicMap map = null;
if(directMerge) {
map = thisf.solveContextTopicMap(fadmin, getContext());
}
else {
map = new org.wandora.topicmap.memory.TopicMapImpl();
}
map.importXTM(pin);
if(!directMerge) {
if(newLayer) {
createNewLayer(map, filename, fadmin);
}
else {
thisf.log("Merging '" + filename + "'.");
solveContextTopicMap(fadmin, getContext()).mergeIn(map);
}
}
pin.close();
thisf.log("Ready.");
}
catch(TopicMapReadOnlyException tmroe) {
thisf.log("Topic map is write protected. Import failed.");
}
catch(Exception e){
thisf.log(e);
}
}
};
parserThread.start();
}
catch(Exception e){
log(e);
}
}
}
@Override
public String getName() {
return "XSL transformer Topic Maps import";
}
@Override
public String getDescription() {
return "Apply XSL transformation to loaded XML file and merge resulting XTM topic map "+
"to current layer.";
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/merge_xml.png");
}
@Override
public void importStream(Wandora admin, String streamName, InputStream inputStream) {
// --- XSL IMPORT HAS NO STREAM IMPORT! --------------------------------
}
private InputStream createInputStreamFor(String streamSource) {
if(streamSource == null) return null;
if(streamSource.startsWith("http:/") || streamSource.startsWith("https:/") || streamSource.startsWith("ftp:/") || streamSource.startsWith("ftps:/")) {
try {
URL sourceURL = new URL(streamSource);
return sourceURL.openStream();
}
catch(Exception e) {
e.printStackTrace();
}
}
try {
File sourceFile = new File(streamSource);
return new FileInputStream(sourceFile);
}
catch(Exception e) {
e.printStackTrace();
}
return null;
}
}
| 7,480 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TopicMapImportConfiguration.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/importers/TopicMapImportConfiguration.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* TopicMapImportConfiguration.java
*
* Created on 6.10.2011, 17:26:29
*/
package org.wandora.application.tools.importers;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import org.wandora.application.Wandora;
import org.wandora.application.gui.UIBox;
import org.wandora.application.gui.simple.SimpleButton;
import org.wandora.application.gui.simple.SimpleCheckBox;
import org.wandora.application.gui.simple.SimpleLabel;
import org.wandora.application.gui.simple.SimpleTabbedPane;
import org.wandora.topicmap.parser.LTMParser;
import org.wandora.topicmap.parser.XTMParser2;
import org.wandora.utils.Options;
/**
*
* @author akivela
*/
public class TopicMapImportConfiguration extends javax.swing.JPanel {
private static final long serialVersionUID = 1L;
private Wandora wandora = null;
private boolean wasAccepted = false;
private JDialog myDialog = null;
/** Creates new form TopicMapImportConfiguration */
public TopicMapImportConfiguration(Wandora w) {
wandora = w;
initComponents();
}
public boolean wasAccepted() {
return wasAccepted;
}
public void openDialog() {
wasAccepted = false;
if(myDialog == null) {
myDialog = new JDialog(wandora, true);
myDialog.add(this);
myDialog.setSize(440,440);
myDialog.setTitle("Topic map import options");
UIBox.centerWindow(myDialog, wandora);
}
loadConfiguration();
myDialog.setVisible(true);
}
public void loadConfiguration() {
Options o = wandora.getOptions();
// XTM2
xtm2OccurrenceCheckBox.setSelected(o.getBoolean(XTMParser2.OCCURRENCE_RESOURCE_REF_KEY, false));
xtm2ImportIdentifiersCheckBox.setSelected(o.getBoolean(XTMParser2.IMPORT_XML_IDENTIFIERS_KEY, false));
xtm2EnsureUniqueBasenamesCheckBox.setSelected(o.getBoolean(XTMParser2.ENSURE_UNIQUE_BASENAMES_KEY, false));
// LTM
ltmAllowSpecialCharsInQNamesCheckBox.setSelected(o.getBoolean(LTMParser.OPTIONS_KEY_ALLOW_SPECIAL_CHARS_IN_QNAMES, LTMParser.ALLOW_SPECIAL_CHARS_IN_QNAMES));
ltmNewOccurrenceForEachScopeTopicCheckBox.setSelected(o.getBoolean(LTMParser.OPTIONS_KEY_NEW_OCCURRENCE_FOR_EACH_SCOPE, LTMParser.NEW_OCCURRENCE_FOR_EACH_SCOPE));
ltmRejectTypelessAssociationPlayersCheckBox.setSelected(o.getBoolean(LTMParser.OPTIONS_KEY_REJECT_ROLELESS_MEMBERS, LTMParser.REJECT_ROLELESS_MEMBERS));
ltmPreferClassAsRoleCheckBox.setSelected( o.getBoolean(LTMParser.OPTIONS_KEY_PREFER_CLASS_AS_ROLE, LTMParser.PREFER_CLASS_AS_ROLE));
ltmForceUniqueBaseNamesCheckBox.setSelected(o.getBoolean(LTMParser.OPTIONS_KEY_FORCE_UNIQUE_BASENAMES, LTMParser.FORCE_UNIQUE_BASENAMES));
ltmTrimBasenamesCheckBox.setSelected(o.getBoolean(LTMParser.OPTIONS_KEY_TRIM_BASENAMES, LTMParser.TRIM_BASENAMES));
ltmOverwriteVariantNamesCheckBox.setSelected(o.getBoolean(LTMParser.OPTIONS_KEY_OVERWRITE_VARIANTS, LTMParser.OVERWRITE_VARIANTS));
ltmOverwriteBasenamesCheckBox.setSelected(o.getBoolean(LTMParser.OPTIONS_KEY_OVERWRITE_BASENAME, LTMParser.OVERWRITE_BASENAME));
ltmDebugCheckBox.setSelected(o.getBoolean(LTMParser.OPTIONS_KEY_DEBUG, LTMParser.debug));
ltmMakeSIfromIDCheckBox.setSelected(o.getBoolean(LTMParser.OPTIONS_KEY_MAKE_SUBJECT_IDENTIFIER_FROM_ID, LTMParser.MAKE_SUBJECT_IDENTIFIER_FROM_ID));
ltmMakeTopicIDfromIDCheckBox.setSelected(o.getBoolean(LTMParser.OPTIONS_KEY_MAKE_TOPIC_ID_FROM_ID, LTMParser.MAKE_TOPIC_ID_FROM_ID));
}
public void saveConfiguration() {
Options o = wandora.getOptions();
// XTM2
o.put(XTMParser2.OCCURRENCE_RESOURCE_REF_KEY, boxVal(xtm2OccurrenceCheckBox));
o.put(XTMParser2.IMPORT_XML_IDENTIFIERS_KEY, boxVal(xtm2ImportIdentifiersCheckBox));
o.put(XTMParser2.ENSURE_UNIQUE_BASENAMES_KEY, boxVal(xtm2EnsureUniqueBasenamesCheckBox));
// LTM
o.put(LTMParser.OPTIONS_KEY_ALLOW_SPECIAL_CHARS_IN_QNAMES, boxVal(ltmAllowSpecialCharsInQNamesCheckBox));
o.put(LTMParser.OPTIONS_KEY_NEW_OCCURRENCE_FOR_EACH_SCOPE, boxVal(ltmNewOccurrenceForEachScopeTopicCheckBox));
o.put(LTMParser.OPTIONS_KEY_REJECT_ROLELESS_MEMBERS, boxVal(ltmRejectTypelessAssociationPlayersCheckBox));
o.put(LTMParser.OPTIONS_KEY_PREFER_CLASS_AS_ROLE, boxVal(ltmPreferClassAsRoleCheckBox));
o.put(LTMParser.OPTIONS_KEY_FORCE_UNIQUE_BASENAMES, boxVal(ltmForceUniqueBaseNamesCheckBox));
o.put(LTMParser.OPTIONS_KEY_TRIM_BASENAMES, boxVal(ltmTrimBasenamesCheckBox));
o.put(LTMParser.OPTIONS_KEY_OVERWRITE_VARIANTS, boxVal(ltmOverwriteVariantNamesCheckBox));
o.put(LTMParser.OPTIONS_KEY_OVERWRITE_BASENAME, boxVal(ltmOverwriteBasenamesCheckBox));
o.put(LTMParser.OPTIONS_KEY_DEBUG, boxVal(ltmDebugCheckBox));
o.put(LTMParser.OPTIONS_KEY_MAKE_SUBJECT_IDENTIFIER_FROM_ID, boxVal(ltmMakeSIfromIDCheckBox));
o.put(LTMParser.OPTIONS_KEY_MAKE_TOPIC_ID_FROM_ID, boxVal(ltmMakeTopicIDfromIDCheckBox));
}
private String boxVal(JCheckBox cb) {
return cb.isSelected() ? "true" : "false";
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
formatTabbedPane = new SimpleTabbedPane();
xtm2Panel = new javax.swing.JPanel();
xtm2PanelInner = new javax.swing.JPanel();
xtm2Label = new SimpleLabel();
xtm2OccurrenceCheckBox = new SimpleCheckBox();
xtm2ImportIdentifiersCheckBox = new SimpleCheckBox();
xtm2EnsureUniqueBasenamesCheckBox = new SimpleCheckBox();
xtm1Panel = new javax.swing.JPanel();
xtm1PanelInner = new javax.swing.JPanel();
xtm1Label = new SimpleLabel();
ltmPanel = new javax.swing.JPanel();
ltmPanelInner = new javax.swing.JPanel();
ltmLabel = new SimpleLabel();
ltmPreferClassAsRoleCheckBox = new SimpleCheckBox();
ltmForceUniqueBaseNamesCheckBox = new SimpleCheckBox();
ltmRejectTypelessAssociationPlayersCheckBox = new SimpleCheckBox();
ltmNewOccurrenceForEachScopeTopicCheckBox = new SimpleCheckBox();
ltmOverwriteVariantNamesCheckBox = new SimpleCheckBox();
ltmOverwriteBasenamesCheckBox = new SimpleCheckBox();
ltmAllowSpecialCharsInQNamesCheckBox = new SimpleCheckBox();
ltmTrimBasenamesCheckBox = new SimpleCheckBox();
ltmDebugCheckBox = new SimpleCheckBox();
ltmMakeSIfromIDCheckBox = new SimpleCheckBox();
ltmMakeTopicIDfromIDCheckBox = new SimpleCheckBox();
jtmPanel = new javax.swing.JPanel();
jtmPanelInner = new javax.swing.JPanel();
jtmLabel = new SimpleLabel();
buttonPanel = new javax.swing.JPanel();
buttonFillerPanel = new javax.swing.JPanel();
okButton = new SimpleButton();
cancelButton = new SimpleButton();
setLayout(new java.awt.GridBagLayout());
xtm2Panel.setLayout(new java.awt.GridBagLayout());
xtm2PanelInner.setLayout(new java.awt.GridBagLayout());
xtm2Label.setText("<html>XTM 2.0 format configuration options.</html>");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 10, 0);
xtm2PanelInner.add(xtm2Label, gridBagConstraints);
xtm2OccurrenceCheckBox.setText("<html>Convert resource reference occurrences to resource data occurrences. If unchecked Wandora converts resource reference occurrences to topics and associations.</html>");
xtm2OccurrenceCheckBox.setVerticalTextPosition(javax.swing.SwingConstants.TOP);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
gridBagConstraints.weightx = 1.0;
xtm2PanelInner.add(xtm2OccurrenceCheckBox, gridBagConstraints);
xtm2ImportIdentifiersCheckBox.setText("<html>Import XML identifiers. If checked the parser injects XML id attributes into the topic's identifiers.</html>");
xtm2ImportIdentifiersCheckBox.setVerticalTextPosition(javax.swing.SwingConstants.TOP);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
gridBagConstraints.weightx = 1.0;
xtm2PanelInner.add(xtm2ImportIdentifiersCheckBox, gridBagConstraints);
xtm2EnsureUniqueBasenamesCheckBox.setText("<html>Ensure unique basenames. If checked the parser adjusts topic's basename if the basename already exists in the topic map.</html>");
xtm2EnsureUniqueBasenamesCheckBox.setVerticalTextPosition(javax.swing.SwingConstants.TOP);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
gridBagConstraints.weightx = 1.0;
xtm2PanelInner.add(xtm2EnsureUniqueBasenamesCheckBox, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(8, 8, 8, 8);
xtm2Panel.add(xtm2PanelInner, gridBagConstraints);
formatTabbedPane.addTab("XTM2", xtm2Panel);
xtm1Panel.setLayout(new java.awt.GridBagLayout());
xtm1PanelInner.setLayout(new java.awt.GridBagLayout());
xtm1Label.setText("<html>XTM 1.0 format has no configuration options.</html>");
xtm1PanelInner.add(xtm1Label, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
xtm1Panel.add(xtm1PanelInner, gridBagConstraints);
formatTabbedPane.addTab("XTM1", xtm1Panel);
ltmPanel.setLayout(new java.awt.GridBagLayout());
ltmPanelInner.setLayout(new java.awt.GridBagLayout());
ltmLabel.setText("<html>LTM import options are</html>");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 10, 0);
ltmPanelInner.add(ltmLabel, gridBagConstraints);
ltmPreferClassAsRoleCheckBox.setText("Prefer class (type) as role.");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
ltmPanelInner.add(ltmPreferClassAsRoleCheckBox, gridBagConstraints);
ltmForceUniqueBaseNamesCheckBox.setText("Force unique base names.");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
ltmPanelInner.add(ltmForceUniqueBaseNamesCheckBox, gridBagConstraints);
ltmRejectTypelessAssociationPlayersCheckBox.setText("Reject typeless association players.");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
ltmPanelInner.add(ltmRejectTypelessAssociationPlayersCheckBox, gridBagConstraints);
ltmNewOccurrenceForEachScopeTopicCheckBox.setText("New occurrence for each scope topic.");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
ltmPanelInner.add(ltmNewOccurrenceForEachScopeTopicCheckBox, gridBagConstraints);
ltmOverwriteVariantNamesCheckBox.setText("Overwrite existing variant names.");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
ltmPanelInner.add(ltmOverwriteVariantNamesCheckBox, gridBagConstraints);
ltmOverwriteBasenamesCheckBox.setText("Overwrite existing basenames.");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
ltmPanelInner.add(ltmOverwriteBasenamesCheckBox, gridBagConstraints);
ltmAllowSpecialCharsInQNamesCheckBox.setText("Allow special characters in QNames.");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
ltmPanelInner.add(ltmAllowSpecialCharsInQNamesCheckBox, gridBagConstraints);
ltmTrimBasenamesCheckBox.setText("Trim base names.");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
ltmPanelInner.add(ltmTrimBasenamesCheckBox, gridBagConstraints);
ltmDebugCheckBox.setText("Output additional debugging logs.");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
ltmPanelInner.add(ltmDebugCheckBox, gridBagConstraints);
ltmMakeSIfromIDCheckBox.setText("Make subject identifier from QName.");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
ltmPanelInner.add(ltmMakeSIfromIDCheckBox, gridBagConstraints);
ltmMakeTopicIDfromIDCheckBox.setText("Make topic ID from QName.");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
ltmPanelInner.add(ltmMakeTopicIDfromIDCheckBox, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(8, 8, 8, 8);
ltmPanel.add(ltmPanelInner, gridBagConstraints);
formatTabbedPane.addTab("LTM", ltmPanel);
jtmPanel.setLayout(new java.awt.GridBagLayout());
jtmPanelInner.setLayout(new java.awt.GridBagLayout());
jtmLabel.setText("<html>JTM format has no configuration options.</html>");
jtmPanelInner.add(jtmLabel, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
jtmPanel.add(jtmPanelInner, gridBagConstraints);
formatTabbedPane.addTab("JTM", jtmPanel);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(formatTabbedPane, gridBagConstraints);
buttonPanel.setLayout(new java.awt.GridBagLayout());
buttonFillerPanel.setLayout(new java.awt.GridBagLayout());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
buttonPanel.add(buttonFillerPanel, gridBagConstraints);
okButton.setText("OK");
okButton.setPreferredSize(new java.awt.Dimension(75, 23));
okButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
okButtonMouseReleased(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4);
buttonPanel.add(okButton, gridBagConstraints);
cancelButton.setText("Cancel");
cancelButton.setPreferredSize(new java.awt.Dimension(75, 23));
cancelButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
cancelButtonMouseReleased(evt);
}
});
buttonPanel.add(cancelButton, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
add(buttonPanel, gridBagConstraints);
}// </editor-fold>//GEN-END:initComponents
private void cancelButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cancelButtonMouseReleased
wasAccepted = false;
if(myDialog != null) {
myDialog.setVisible(false);
}
}//GEN-LAST:event_cancelButtonMouseReleased
private void okButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_okButtonMouseReleased
wasAccepted = false;
if(myDialog != null) {
myDialog.setVisible(false);
}
}//GEN-LAST:event_okButtonMouseReleased
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel buttonFillerPanel;
private javax.swing.JPanel buttonPanel;
private javax.swing.JButton cancelButton;
private javax.swing.JTabbedPane formatTabbedPane;
private javax.swing.JLabel jtmLabel;
private javax.swing.JPanel jtmPanel;
private javax.swing.JPanel jtmPanelInner;
private javax.swing.JCheckBox ltmAllowSpecialCharsInQNamesCheckBox;
private javax.swing.JCheckBox ltmDebugCheckBox;
private javax.swing.JCheckBox ltmForceUniqueBaseNamesCheckBox;
private javax.swing.JLabel ltmLabel;
private javax.swing.JCheckBox ltmMakeSIfromIDCheckBox;
private javax.swing.JCheckBox ltmMakeTopicIDfromIDCheckBox;
private javax.swing.JCheckBox ltmNewOccurrenceForEachScopeTopicCheckBox;
private javax.swing.JCheckBox ltmOverwriteBasenamesCheckBox;
private javax.swing.JCheckBox ltmOverwriteVariantNamesCheckBox;
private javax.swing.JPanel ltmPanel;
private javax.swing.JPanel ltmPanelInner;
private javax.swing.JCheckBox ltmPreferClassAsRoleCheckBox;
private javax.swing.JCheckBox ltmRejectTypelessAssociationPlayersCheckBox;
private javax.swing.JCheckBox ltmTrimBasenamesCheckBox;
private javax.swing.JButton okButton;
private javax.swing.JLabel xtm1Label;
private javax.swing.JPanel xtm1Panel;
private javax.swing.JPanel xtm1PanelInner;
private javax.swing.JCheckBox xtm2EnsureUniqueBasenamesCheckBox;
private javax.swing.JCheckBox xtm2ImportIdentifiersCheckBox;
private javax.swing.JLabel xtm2Label;
private javax.swing.JCheckBox xtm2OccurrenceCheckBox;
private javax.swing.JPanel xtm2Panel;
private javax.swing.JPanel xtm2PanelInner;
// End of variables declaration//GEN-END:variables
}
| 21,279 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SimpleRDFJsonLDImport.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/importers/SimpleRDFJsonLDImport.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.application.tools.importers;
import java.io.InputStream;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.wandora.topicmap.TopicMap;
/**
*
* @author olli
*/
public class SimpleRDFJsonLDImport extends SimpleRDFImport {
private static final long serialVersionUID = 1L;
public SimpleRDFJsonLDImport() {
}
public SimpleRDFJsonLDImport(int options) {
setOptions(options);
}
@Override
public String getName() {
return "Simple JSON-LD import";
}
@Override
public String getDescription() {
return "Tool imports JSON-LD file and merges RDF triplets to current topic map.";
}
@Override
public void importRDF(InputStream in, TopicMap map) {
if(in != null) {
// create an empty model
Model model = ModelFactory.createDefaultModel();
// read the RDF json-ld file
model.read(in, "", "JSON-LD");
RDF2TopicMap(model, map);
}
}
}
| 1,861 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AdjacencyMatrixImport.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/importers/graphs/AdjacencyMatrixImport.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* AdjacencyMatrixImport.java
*
* Created on 2009-12-27, 17:42
*
*/
package org.wandora.application.tools.importers.graphs;
import java.util.ArrayList;
import javax.swing.Icon;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.WandoraToolType;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.UIBox;
import org.wandora.application.tools.AbstractWandoraTool;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.utils.Tuples.T2;
/**
*
* @author akivela
*/
public class AdjacencyMatrixImport extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
public final static String SI_PREFIX = "http://wandora.org/si/topic/";
private boolean cellValueToPlayer = false;
/** Creates a new instance of AdjacencyMatrixImport */
public AdjacencyMatrixImport() {
}
@Override
public String getName() {
return "Adjacency matrix import";
}
@Override
public String getDescription() {
return "Generates topics and associations from given adjacency matrix.";
}
@Override
public void execute(Wandora admin, Context context) throws TopicMapException {
TopicMap topicmap = solveContextTopicMap(admin, context);
AdjacencyMatrixImportDialog matrixSourceDialog = new AdjacencyMatrixImportDialog(admin, this, true);
matrixSourceDialog.setVisible(true);
if(!matrixSourceDialog.wasAccepted()) return;
setDefaultLogger();
setLogTitle("Adjacency matrix import");
log("Reading adjacency matrix.");
String matrixData = matrixSourceDialog.getContent();
log("Parsing...");
MatrixParser matrixParser = new MatrixParser(matrixData, topicmap);
cellValueToPlayer = matrixSourceDialog.cellValueToPlayer();
matrixParser.parse();
log("Created "+matrixParser.counter+" associations.");
log("Ready.");
setState(WAIT);
}
protected void createEdgeAssociation(ArrayList<T2<String,String>> nodes, TopicMap topicmap) {
try {
if(topicmap != null && nodes != null && nodes.size() > 0) {
hlog("Processing association "+nodes);
Topic atype = getOrCreateTopic(topicmap, SI_PREFIX+"edge", "edge");
Association a = null;
Topic player = null;
Topic role = null;
a = topicmap.createAssociation(atype);
int rc = 0;
for(T2<String,String> node : nodes) {
if(node != null) {
player = getOrCreateTopic(topicmap, SI_PREFIX+node.e1, node.e1);
role = getOrCreateTopic(topicmap, SI_PREFIX+node.e2, node.e2);
if(player != null && !player.isRemoved()) {
if(role != null && !role.isRemoved()) {
a.addPlayer(player, role);
}
}
rc++;
}
}
}
}
catch(Exception e) {
log(e);
}
}
public Topic getOrCreateTopic(TopicMap map, String si, String basename) {
Topic topic = null;
try {
topic = map.getTopic(si);
if(topic == null) {
topic = map.createTopic();
topic.addSubjectIdentifier(new Locator(si));
if(basename != null && basename.length() > 0) topic.setBaseName(basename);
}
}
catch(Exception e) {
log(e);
e.printStackTrace();
}
return topic;
}
@Override
public WandoraToolType getType() {
return WandoraToolType.createImportType();
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/import_adjacency_matrix.png");
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
private class MatrixParser {
private String rowRegex = "[\n\r]+";
private String colRegex = "[\\s]+";
private String data = null;
private int len = 0;
private TopicMap topicmap = null;
public int counter = 0;
public MatrixParser(String data, TopicMap topicmap) {
this.data = data;
this.topicmap = topicmap;
this.len = data.length();
setProgressMax(len);
}
private void parse() {
String[] rows = data.split(rowRegex);
for(int row=0; row<rows.length; row++) {
if(rows[row] != null && rows[row].length() > 0) {
String[] cols = rows[row].split(colRegex);
for(int col=0; col<cols.length; col++) {
if(cols[col] != null && cols[col].length() > 0) {
String cell = cols[col].trim();
if(cellValueToPlayer) {
ArrayList<T2<String,String>> nodes = new ArrayList<T2<String,String>>();
nodes.add(new T2<String,String>(""+col, "col"));
nodes.add(new T2<String,String>(""+row, "row"));
nodes.add(new T2<String,String>(""+cell, "cell"));
createEdgeAssociation(nodes, topicmap);
counter++;
}
else {
if(!"0".equals(cell)) {
ArrayList<T2<String,String>> nodes = new ArrayList<T2<String,String>>();
nodes.add(new T2<String,String>(""+col, "col"));
nodes.add(new T2<String,String>(""+row, "row"));
createEdgeAssociation(nodes, topicmap);
counter++;
}
}
}
}
}
}
}
}
}
| 7,368 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
IncidenceMatrixImportDialog.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/importers/graphs/IncidenceMatrixImportDialog.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
* IncidenceMatrixImportDialog.java
*
* Created on 2009-12-27, 18:14
*/
package org.wandora.application.tools.importers.graphs;
import java.awt.Component;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.UIConstants;
import org.wandora.application.gui.simple.SimpleFileChooser;
import org.wandora.application.gui.simple.SimpleTextPane;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.Topic;
import org.wandora.utils.IObox;
/**
*
* @author akivela
*/
public class IncidenceMatrixImportDialog extends javax.swing.JDialog {
private static final long serialVersionUID = 1L;
private Wandora parent = null;
private WandoraTool parentTool = null;
private boolean wasAccepted = false;
/** Creates new form IncidenceMatrixImportDialog */
public IncidenceMatrixImportDialog(Wandora admin, WandoraTool parentTool, boolean modal) {
super(admin, modal);
this.parent = admin;
initComponents();
initialize(parentTool);
}
public void initialize(WandoraTool parentTool) {
this.parentTool = parentTool;
wasAccepted = false;
((SimpleTextPane) fileTextPane).dropFileNames(true);
((SimpleTextPane) fileTextPane).setLineWrap(false);
((SimpleTextPane) urlTextPane).setLineWrap(false);
setTitle("Import incidence matrix");
setSize(640,400);
if(parent != null) parent.centerWindow(this);
}
public boolean wasAccepted() {
return wasAccepted;
}
// --- CONTENT ---
public String getContent() {
Component selectedComponent = tabbedSourcePane.getSelectedComponent();
if(rawPanel.equals(selectedComponent)) {
return rawTextPane.getText();
}
else if(filePanel.equals(selectedComponent)) {
File[] files = getFileSources();
StringBuilder sb = new StringBuilder("");
for(File file : files) {
try {
sb.append(IObox.loadFile(file));
}
catch(Exception e) {
parentTool.log(e);
}
}
}
else if(urlPanel.equals(selectedComponent)) {
String[] urls = getURLSources();
StringBuilder sb = new StringBuilder("");
for (String url : urls) {
try {
sb.append(IObox.doUrl(new URL(url)));
}
catch(Exception e) {
parentTool.log(e);
}
}
}
return null;
}
// --- FILE SOURCE ---
public File[] getFileSources() {
String input = fileTextPane.getText();
String[] filenames = splitText(input);
ArrayList<File> files = new ArrayList<File>();
File f = null;
for(String filename : filenames) {
f = new File(filename);
if (f.exists()) {
files.add(f);
}
else {
if (parentTool != null) {
parentTool.log("File '" + filename + "' not found!");
}
}
}
return files.toArray( new File[] {} );
}
// --- URL SOURCE ---
public String[] getURLSources() {
String input = urlTextPane.getText();
String[] urls = splitText(input);
return urls;
}
private String[] splitText(String str) {
if(str == null) return null;
if(str.contains("\n")) {
String[] s = str.split("\n");
for(int i=0; i<s.length; i++) {
s[i] = s[i].trim();
}
return s;
}
else {
return new String[] { str.trim() };
}
}
// -------------------------------------------------------------------------
private void selectFiles() {
SimpleFileChooser chooser = UIConstants.getFileChooser();
chooser.setMultiSelectionEnabled(true);
//chooser.setDialogTitle(getGUIText(SELECT_DIALOG_TITLE));
chooser.setApproveButtonText("Select");
chooser.setFileSelectionMode(SimpleFileChooser.FILES_AND_DIRECTORIES);
//if(accessoryPanel != null) { chooser.setAccessory(accessoryPanel); }
if(chooser.open(parent, SimpleFileChooser.OPEN_DIALOG)==SimpleFileChooser.APPROVE_OPTION) {
File[] files = chooser.getSelectedFiles();
File f = null;
String fs = "";
for(int i=0; i<files.length; i++) {
f = files[i];
fs = fs + f.getAbsolutePath();
if(i<files.length-1) fs = fs + "\n";
}
String s = fileTextPane.getText();
if(s == null || s.length() == 0) s = fs;
else s = s + "\n" + fs;
fileTextPane.setText(s);
}
}
private void selectContextSLFiles() {
if(parentTool == null) return;
Context context = parentTool.getContext();
Iterator iter = context.getContextObjects();
Object o = null;
Topic t = null;
Locator locator = null;
StringBuilder sb = new StringBuilder("");
while(iter.hasNext()) {
try {
o = iter.next();
if(o == null) continue;
if(o instanceof Topic) {
t = (Topic) o;
if(!t.isRemoved()) {
locator = t.getSubjectLocator();
if(locator != null) {
String locatorStr = locator.toExternalForm();
if(locatorStr.startsWith("file:")) {
locatorStr = IObox.getFileFromURL(locatorStr);
sb.append(locatorStr + "\n");
}
}
}
}
}
catch(Exception e) {
parentTool.log(e);
}
}
String s = urlTextPane.getText();
if(s == null || s.length() == 0) s = sb.toString();
else s = s + "\n" + sb.toString();
fileTextPane.setText(s);
}
private void selectContextSLs() {
if(parentTool == null) return;
Context context = parentTool.getContext();
Iterator iter = context.getContextObjects();
Object o = null;
Topic t = null;
Locator locator = null;
StringBuilder sb = new StringBuilder("");
while(iter.hasNext()) {
try {
o = iter.next();
if(o == null) continue;
if(o instanceof Topic) {
t = (Topic) o;
if(!t.isRemoved()) {
locator = t.getSubjectLocator();
if(locator != null) {
String locatorStr = locator.toExternalForm();
sb.append(locatorStr).append("\n");
}
}
}
}
catch(Exception e) {
parentTool.log(e);
}
}
String s = urlTextPane.getText();
if(s == null || s.length() == 0) s = sb.toString();
else s = s + "\n" + sb.toString();
urlTextPane.setText(s);
}
private void selectContextSIs() {
if(parentTool == null) return;
Context context = parentTool.getContext();
Iterator iter = context.getContextObjects();
Object o = null;
Topic t = null;
Locator locator = null;
StringBuilder sb = new StringBuilder("");
while(iter.hasNext()) {
try {
o = iter.next();
if(o == null) continue;
if(o instanceof Topic) {
t = (Topic) o;
if(!t.isRemoved()) {
Collection<Locator> ls = t.getSubjectIdentifiers();
Iterator<Locator> ils = ls.iterator();
while(ils.hasNext()) {
locator = ils.next();
if(locator != null) {
String locatorStr = locator.toExternalForm();
sb.append(locatorStr).append("\n");
}
}
}
}
}
catch(Exception e) {
parentTool.log(e);
}
}
String s = urlTextPane.getText();
if(s == null || s.length() == 0) s = sb.toString();
else s = s + "\n" + sb.toString();
urlTextPane.setText(s);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
tabbedSourcePane = new org.wandora.application.gui.simple.SimpleTabbedPane();
rawPanel = new javax.swing.JPanel();
rawLabel = new org.wandora.application.gui.simple.SimpleLabel();
rawScrollPane = new javax.swing.JScrollPane();
rawTextPane = new org.wandora.application.gui.simple.SimpleTextPane();
filePanel = new javax.swing.JPanel();
fileLabel = new org.wandora.application.gui.simple.SimpleLabel();
fileScrollPane = new javax.swing.JScrollPane();
fileTextPane = new org.wandora.application.gui.simple.SimpleTextPane();
fileButtonPanel = new javax.swing.JPanel();
fileBrowseButton = new org.wandora.application.gui.simple.SimpleButton();
fileGetSLButton = new org.wandora.application.gui.simple.SimpleButton();
fileClearButton = new org.wandora.application.gui.simple.SimpleButton();
urlPanel = new javax.swing.JPanel();
urlLabel = new org.wandora.application.gui.simple.SimpleLabel();
urlScrollPane = new javax.swing.JScrollPane();
urlTextPane = new org.wandora.application.gui.simple.SimpleTextPane();
urlButtonPanel = new javax.swing.JPanel();
urlGetSIButton = new org.wandora.application.gui.simple.SimpleButton();
urlGetSLButton = new org.wandora.application.gui.simple.SimpleButton();
urlClearButton = new org.wandora.application.gui.simple.SimpleButton();
buttonPanel = new javax.swing.JPanel();
fillerPanel = new javax.swing.JPanel();
importButton = new org.wandora.application.gui.simple.SimpleButton();
cancelButton = new org.wandora.application.gui.simple.SimpleButton();
getContentPane().setLayout(new java.awt.GridBagLayout());
rawPanel.setLayout(new java.awt.GridBagLayout());
rawLabel.setText("<html>This tab is used to inject actual incidence matrix to the importer. Paste or drag'n'drop raw content to the field below. Use space character to separate values in matrix and new line character to separate matrix rows. Non-zero value represents a connection in the matrix. Value '0' represents no connection in the matrix.</html>");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rawPanel.add(rawLabel, gridBagConstraints);
rawScrollPane.setPreferredSize(new java.awt.Dimension(10, 100));
rawScrollPane.setViewportView(rawTextPane);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 5, 5, 5);
rawPanel.add(rawScrollPane, gridBagConstraints);
tabbedSourcePane.addTab("Raw", rawPanel);
filePanel.setLayout(new java.awt.GridBagLayout());
fileLabel.setText("<html>This tab is used to address files containing incidence matrix. Please browse files or get subject locator files.</html>");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
filePanel.add(fileLabel, gridBagConstraints);
fileScrollPane.setPreferredSize(new java.awt.Dimension(10, 100));
fileScrollPane.setViewportView(fileTextPane);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 5);
filePanel.add(fileScrollPane, gridBagConstraints);
fileButtonPanel.setLayout(new java.awt.GridBagLayout());
fileBrowseButton.setText("Browse");
fileBrowseButton.setMargin(new java.awt.Insets(1, 6, 1, 6));
fileBrowseButton.setPreferredSize(new java.awt.Dimension(60, 21));
fileBrowseButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
fileBrowseButtonMouseReleased(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 1);
fileButtonPanel.add(fileBrowseButton, gridBagConstraints);
fileGetSLButton.setText("Get SLs");
fileGetSLButton.setMargin(new java.awt.Insets(1, 6, 1, 6));
fileGetSLButton.setPreferredSize(new java.awt.Dimension(60, 21));
fileGetSLButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
fileGetSLButtonMouseReleased(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 1);
fileButtonPanel.add(fileGetSLButton, gridBagConstraints);
fileClearButton.setText("Clear");
fileClearButton.setMargin(new java.awt.Insets(1, 6, 1, 6));
fileClearButton.setPreferredSize(new java.awt.Dimension(60, 21));
fileClearButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
fileClearButtonMouseReleased(evt);
}
});
fileButtonPanel.add(fileClearButton, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
filePanel.add(fileButtonPanel, gridBagConstraints);
tabbedSourcePane.addTab("Files", filePanel);
urlPanel.setLayout(new java.awt.GridBagLayout());
urlLabel.setText("<html>This tab is used to address URL resources containing incidence matrix data. Please write URL addresses or get subject identifiers of context topics.</html>");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
urlPanel.add(urlLabel, gridBagConstraints);
urlScrollPane.setPreferredSize(new java.awt.Dimension(10, 100));
urlScrollPane.setViewportView(urlTextPane);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 5);
urlPanel.add(urlScrollPane, gridBagConstraints);
urlButtonPanel.setLayout(new java.awt.GridBagLayout());
urlGetSIButton.setText("Get SIs");
urlGetSIButton.setMargin(new java.awt.Insets(1, 6, 1, 6));
urlGetSIButton.setPreferredSize(new java.awt.Dimension(60, 21));
urlGetSIButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
urlGetSIButtonMouseReleased(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 1);
urlButtonPanel.add(urlGetSIButton, gridBagConstraints);
urlGetSLButton.setText("Get SLs");
urlGetSLButton.setMargin(new java.awt.Insets(1, 6, 1, 6));
urlGetSLButton.setPreferredSize(new java.awt.Dimension(60, 21));
urlGetSLButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
urlGetSLButtonMouseReleased(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 1);
urlButtonPanel.add(urlGetSLButton, gridBagConstraints);
urlClearButton.setText("Clear");
urlClearButton.setMargin(new java.awt.Insets(1, 6, 1, 6));
urlClearButton.setPreferredSize(new java.awt.Dimension(60, 21));
urlClearButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
urlClearButtonMouseReleased(evt);
}
});
urlButtonPanel.add(urlClearButton, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
urlPanel.add(urlButtonPanel, gridBagConstraints);
tabbedSourcePane.addTab("URLs", urlPanel);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 4, 0);
getContentPane().add(tabbedSourcePane, gridBagConstraints);
tabbedSourcePane.getAccessibleContext().setAccessibleName("");
buttonPanel.setLayout(new java.awt.GridBagLayout());
fillerPanel.setPreferredSize(new java.awt.Dimension(100, 10));
javax.swing.GroupLayout fillerPanelLayout = new javax.swing.GroupLayout(fillerPanel);
fillerPanel.setLayout(fillerPanelLayout);
fillerPanelLayout.setHorizontalGroup(
fillerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 270, Short.MAX_VALUE)
);
fillerPanelLayout.setVerticalGroup(
fillerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 10, Short.MAX_VALUE)
);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
buttonPanel.add(fillerPanel, gridBagConstraints);
importButton.setText("Import");
importButton.setMargin(new java.awt.Insets(2, 2, 2, 2));
importButton.setPreferredSize(new java.awt.Dimension(70, 23));
importButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
importButtonMouseReleased(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3);
buttonPanel.add(importButton, gridBagConstraints);
cancelButton.setText("Cancel");
cancelButton.setMargin(new java.awt.Insets(2, 2, 2, 2));
cancelButton.setPreferredSize(new java.awt.Dimension(70, 23));
cancelButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
cancelButtonMouseReleased(evt);
}
});
buttonPanel.add(cancelButton, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 4);
getContentPane().add(buttonPanel, gridBagConstraints);
pack();
}// </editor-fold>//GEN-END:initComponents
private void urlClearButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_urlClearButtonMouseReleased
this.urlTextPane.setText("");
}//GEN-LAST:event_urlClearButtonMouseReleased
private void fileClearButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_fileClearButtonMouseReleased
this.fileTextPane.setText("");
}//GEN-LAST:event_fileClearButtonMouseReleased
private void cancelButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cancelButtonMouseReleased
wasAccepted = false;
setVisible(false);
}//GEN-LAST:event_cancelButtonMouseReleased
private void importButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_importButtonMouseReleased
wasAccepted = true;
setVisible(false);
}//GEN-LAST:event_importButtonMouseReleased
private void fileBrowseButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_fileBrowseButtonMouseReleased
selectFiles();
}//GEN-LAST:event_fileBrowseButtonMouseReleased
private void fileGetSLButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_fileGetSLButtonMouseReleased
selectContextSLFiles();
}//GEN-LAST:event_fileGetSLButtonMouseReleased
private void urlGetSLButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_urlGetSLButtonMouseReleased
selectContextSLs();
}//GEN-LAST:event_urlGetSLButtonMouseReleased
private void urlGetSIButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_urlGetSIButtonMouseReleased
selectContextSIs();
}//GEN-LAST:event_urlGetSIButtonMouseReleased
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel buttonPanel;
private javax.swing.JButton cancelButton;
private javax.swing.JButton fileBrowseButton;
private javax.swing.JPanel fileButtonPanel;
private javax.swing.JButton fileClearButton;
private javax.swing.JButton fileGetSLButton;
private javax.swing.JLabel fileLabel;
private javax.swing.JPanel filePanel;
private javax.swing.JScrollPane fileScrollPane;
private javax.swing.JTextPane fileTextPane;
private javax.swing.JPanel fillerPanel;
private javax.swing.JButton importButton;
private javax.swing.JLabel rawLabel;
private javax.swing.JPanel rawPanel;
private javax.swing.JScrollPane rawScrollPane;
private javax.swing.JTextPane rawTextPane;
private javax.swing.JTabbedPane tabbedSourcePane;
private javax.swing.JPanel urlButtonPanel;
private javax.swing.JButton urlClearButton;
private javax.swing.JButton urlGetSIButton;
private javax.swing.JButton urlGetSLButton;
private javax.swing.JLabel urlLabel;
private javax.swing.JPanel urlPanel;
private javax.swing.JScrollPane urlScrollPane;
private javax.swing.JTextPane urlTextPane;
// End of variables declaration//GEN-END:variables
}
| 25,738 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AdjacencyMatrixImportDialog.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/importers/graphs/AdjacencyMatrixImportDialog.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
* AdjacencyMatrixImportDialog.java
*
* Created on 2009-12-27, 18:14
*/
package org.wandora.application.tools.importers.graphs;
import java.awt.Component;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.UIConstants;
import org.wandora.application.gui.simple.SimpleCheckBox;
import org.wandora.application.gui.simple.SimpleFileChooser;
import org.wandora.application.gui.simple.SimpleTextPane;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.Topic;
import org.wandora.utils.IObox;
/**
*
* @author akivela
*/
public class AdjacencyMatrixImportDialog extends javax.swing.JDialog {
private static final long serialVersionUID = 1L;
private Wandora parent = null;
private WandoraTool parentTool = null;
private boolean wasAccepted = false;
/** Creates new form AdjacencyMatrixImportDialog */
public AdjacencyMatrixImportDialog(Wandora admin, WandoraTool parentTool, boolean modal) {
super(admin, modal);
this.parent = admin;
initComponents();
initialize(parentTool);
}
public void initialize(WandoraTool parentTool) {
this.parentTool = parentTool;
wasAccepted = false;
((SimpleTextPane) fileTextPane).dropFileNames(true);
((SimpleTextPane) fileTextPane).setLineWrap(false);
((SimpleTextPane) urlTextPane).setLineWrap(false);
setTitle("Import adjacency matrix");
setSize(640,400);
if(parent != null) parent.centerWindow(this);
}
public boolean wasAccepted() {
return wasAccepted;
}
public boolean cellValueToPlayer() {
return cellValueToPlayerCheckBox.isSelected();
}
// --- CONTENT ---
public String getContent() {
Component selectedComponent = tabbedSourcePane.getSelectedComponent();
if(rawPanel.equals(selectedComponent)) {
return rawTextPane.getText();
}
else if(filePanel.equals(selectedComponent)) {
File[] files = getFileSources();
StringBuilder sb = new StringBuilder("");
for(int i=0; i<files.length; i++) {
try {
sb.append(IObox.loadFile(files[i]));
}
catch(Exception e) {
parentTool.log(e);
}
}
}
else if(urlPanel.equals(selectedComponent)) {
String[] urls = getURLSources();
StringBuilder sb = new StringBuilder("");
for(String url : urls) {
try {
sb.append(IObox.doUrl(new URL(url)));
}
catch(Exception e) {
parentTool.log(e);
}
}
}
return null;
}
// --- FILE SOURCE ---
public File[] getFileSources() {
String input = fileTextPane.getText();
String[] filenames = splitText(input);
ArrayList<File> files = new ArrayList<File>();
File f = null;
for (String filename : filenames) {
f = new File(filename);
if(f.exists()) {
files.add(f);
}
else {
if(parentTool != null) {
parentTool.log("File '" + filename + "' not found!");
}
}
}
return files.toArray( new File[] {} );
}
// --- URL SOURCE ---
public String[] getURLSources() {
String input = urlTextPane.getText();
String[] urls = splitText(input);
return urls;
}
private String[] splitText(String str) {
if(str == null) return null;
if(str.contains("\n")) {
String[] s = str.split("\n");
for(int i=0; i<s.length; i++) {
s[i] = s[i].trim();
}
return s;
}
else {
return new String[] { str.trim() };
}
}
// -------------------------------------------------------------------------
private void selectFiles() {
SimpleFileChooser chooser = UIConstants.getFileChooser();
chooser.setMultiSelectionEnabled(true);
//chooser.setDialogTitle(getGUIText(SELECT_DIALOG_TITLE));
chooser.setApproveButtonText("Select");
chooser.setFileSelectionMode(SimpleFileChooser.FILES_AND_DIRECTORIES);
//if(accessoryPanel != null) { chooser.setAccessory(accessoryPanel); }
if(chooser.open(parent, SimpleFileChooser.OPEN_DIALOG)==SimpleFileChooser.APPROVE_OPTION) {
File[] files = chooser.getSelectedFiles();
File f = null;
String fs = "";
for(int i=0; i<files.length; i++) {
f = files[i];
fs = fs + f.getAbsolutePath();
if(i<files.length-1) fs = fs + "\n";
}
String s = fileTextPane.getText();
if(s == null || s.length() == 0) s = fs;
else s = s + "\n" + fs;
fileTextPane.setText(s);
}
}
private void selectContextSLFiles() {
if(parentTool == null) return;
Context context = parentTool.getContext();
Iterator iter = context.getContextObjects();
Object o = null;
Topic t = null;
Locator locator = null;
StringBuilder sb = new StringBuilder("");
while(iter.hasNext()) {
try {
o = iter.next();
if(o == null) continue;
if(o instanceof Topic) {
t = (Topic) o;
if(!t.isRemoved()) {
locator = t.getSubjectLocator();
if(locator != null) {
String locatorStr = locator.toExternalForm();
if(locatorStr.startsWith("file:")) {
locatorStr = IObox.getFileFromURL(locatorStr);
sb.append(locatorStr + "\n");
}
}
}
}
}
catch(Exception e) {
parentTool.log(e);
}
}
String s = urlTextPane.getText();
if(s == null || s.length() == 0) s = sb.toString();
else s = s + "\n" + sb.toString();
fileTextPane.setText(s);
}
private void selectContextSLs() {
if(parentTool == null) return;
Context context = parentTool.getContext();
Iterator iter = context.getContextObjects();
Object o = null;
Topic t = null;
Locator locator = null;
StringBuilder sb = new StringBuilder("");
while(iter.hasNext()) {
try {
o = iter.next();
if(o == null) continue;
if(o instanceof Topic) {
t = (Topic) o;
if(!t.isRemoved()) {
locator = t.getSubjectLocator();
if(locator != null) {
String locatorStr = locator.toExternalForm();
sb.append(locatorStr).append("\n");
}
}
}
}
catch(Exception e) {
parentTool.log(e);
}
}
String s = urlTextPane.getText();
if(s == null || s.length() == 0) s = sb.toString();
else s = s + "\n" + sb.toString();
urlTextPane.setText(s);
}
private void selectContextSIs() {
if(parentTool == null) return;
Context context = parentTool.getContext();
Iterator iter = context.getContextObjects();
Object o = null;
Topic t = null;
Locator locator = null;
StringBuilder sb = new StringBuilder("");
while(iter.hasNext()) {
try {
o = iter.next();
if(o == null) continue;
if(o instanceof Topic) {
t = (Topic) o;
if(!t.isRemoved()) {
Collection<Locator> ls = t.getSubjectIdentifiers();
Iterator<Locator> ils = ls.iterator();
while(ils.hasNext()) {
locator = ils.next();
if(locator != null) {
String locatorStr = locator.toExternalForm();
sb.append(locatorStr).append("\n");
}
}
}
}
}
catch(Exception e) {
parentTool.log(e);
}
}
String s = urlTextPane.getText();
if(s == null || s.length() == 0) s = sb.toString();
else s = s + "\n" + sb.toString();
urlTextPane.setText(s);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
tabbedSourcePane = new org.wandora.application.gui.simple.SimpleTabbedPane();
rawPanel = new javax.swing.JPanel();
rawLabel = new org.wandora.application.gui.simple.SimpleLabel();
rawScrollPane = new javax.swing.JScrollPane();
rawTextPane = new org.wandora.application.gui.simple.SimpleTextPane();
filePanel = new javax.swing.JPanel();
fileLabel = new org.wandora.application.gui.simple.SimpleLabel();
fileScrollPane = new javax.swing.JScrollPane();
fileTextPane = new org.wandora.application.gui.simple.SimpleTextPane();
fileButtonPanel = new javax.swing.JPanel();
fileBrowseButton = new org.wandora.application.gui.simple.SimpleButton();
fileGetSLButton = new org.wandora.application.gui.simple.SimpleButton();
fileClearButton = new org.wandora.application.gui.simple.SimpleButton();
urlPanel = new javax.swing.JPanel();
urlLabel = new org.wandora.application.gui.simple.SimpleLabel();
urlScrollPane = new javax.swing.JScrollPane();
urlTextPane = new org.wandora.application.gui.simple.SimpleTextPane();
urlButtonPanel = new javax.swing.JPanel();
urlGetSIButton = new org.wandora.application.gui.simple.SimpleButton();
urlGetSLButton = new org.wandora.application.gui.simple.SimpleButton();
urlClearButton = new org.wandora.application.gui.simple.SimpleButton();
buttonPanel = new javax.swing.JPanel();
cellValueToPlayerCheckBox = new SimpleCheckBox();
fillerPanel = new javax.swing.JPanel();
importButton = new org.wandora.application.gui.simple.SimpleButton();
cancelButton = new org.wandora.application.gui.simple.SimpleButton();
getContentPane().setLayout(new java.awt.GridBagLayout());
rawPanel.setLayout(new java.awt.GridBagLayout());
rawLabel.setText("<html>This tab is used to inject actual adjacency matrix to the importer. Paste or drag'n'drop raw content to the field below. Use space character as a matrix value separator and new line character as a matrix row separator. Non-zero value represents a connection in the matrix. Value '0' represents no connection between row and column topics.</html>");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rawPanel.add(rawLabel, gridBagConstraints);
rawScrollPane.setPreferredSize(new java.awt.Dimension(10, 100));
rawScrollPane.setViewportView(rawTextPane);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 5, 5, 5);
rawPanel.add(rawScrollPane, gridBagConstraints);
tabbedSourcePane.addTab("Raw", rawPanel);
filePanel.setLayout(new java.awt.GridBagLayout());
fileLabel.setText("<html>This tab is used to address files containing adjacency matrixes. Please browse files or get subject locator files.</html>");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
filePanel.add(fileLabel, gridBagConstraints);
fileScrollPane.setPreferredSize(new java.awt.Dimension(10, 100));
fileScrollPane.setViewportView(fileTextPane);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 5);
filePanel.add(fileScrollPane, gridBagConstraints);
fileButtonPanel.setLayout(new java.awt.GridBagLayout());
fileBrowseButton.setText("Browse");
fileBrowseButton.setMargin(new java.awt.Insets(1, 6, 1, 6));
fileBrowseButton.setPreferredSize(new java.awt.Dimension(60, 21));
fileBrowseButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
fileBrowseButtonMouseReleased(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 1);
fileButtonPanel.add(fileBrowseButton, gridBagConstraints);
fileGetSLButton.setText("Get SLs");
fileGetSLButton.setMargin(new java.awt.Insets(1, 6, 1, 6));
fileGetSLButton.setPreferredSize(new java.awt.Dimension(60, 21));
fileGetSLButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
fileGetSLButtonMouseReleased(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 1);
fileButtonPanel.add(fileGetSLButton, gridBagConstraints);
fileClearButton.setText("Clear");
fileClearButton.setMargin(new java.awt.Insets(1, 6, 1, 6));
fileClearButton.setPreferredSize(new java.awt.Dimension(60, 21));
fileClearButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
fileClearButtonMouseReleased(evt);
}
});
fileButtonPanel.add(fileClearButton, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
filePanel.add(fileButtonPanel, gridBagConstraints);
tabbedSourcePane.addTab("Files", filePanel);
urlPanel.setLayout(new java.awt.GridBagLayout());
urlLabel.setText("<html>This tab is used to address URL resources containing adjacency matrix data. Please write URL addresses or get subject identifiers from context topics.</html>");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
urlPanel.add(urlLabel, gridBagConstraints);
urlScrollPane.setPreferredSize(new java.awt.Dimension(10, 100));
urlScrollPane.setViewportView(urlTextPane);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 5);
urlPanel.add(urlScrollPane, gridBagConstraints);
urlButtonPanel.setLayout(new java.awt.GridBagLayout());
urlGetSIButton.setText("Get SIs");
urlGetSIButton.setMargin(new java.awt.Insets(1, 6, 1, 6));
urlGetSIButton.setPreferredSize(new java.awt.Dimension(60, 21));
urlGetSIButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
urlGetSIButtonMouseReleased(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 1);
urlButtonPanel.add(urlGetSIButton, gridBagConstraints);
urlGetSLButton.setText("Get SLs");
urlGetSLButton.setMargin(new java.awt.Insets(1, 6, 1, 6));
urlGetSLButton.setPreferredSize(new java.awt.Dimension(60, 21));
urlGetSLButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
urlGetSLButtonMouseReleased(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 1);
urlButtonPanel.add(urlGetSLButton, gridBagConstraints);
urlClearButton.setText("Clear");
urlClearButton.setMargin(new java.awt.Insets(1, 6, 1, 6));
urlClearButton.setPreferredSize(new java.awt.Dimension(60, 21));
urlClearButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
urlClearButtonMouseReleased(evt);
}
});
urlButtonPanel.add(urlClearButton, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
urlPanel.add(urlButtonPanel, gridBagConstraints);
tabbedSourcePane.addTab("URLs", urlPanel);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 5, 0);
getContentPane().add(tabbedSourcePane, gridBagConstraints);
tabbedSourcePane.getAccessibleContext().setAccessibleName("");
buttonPanel.setLayout(new java.awt.GridBagLayout());
cellValueToPlayerCheckBox.setText("Cell value to player");
cellValueToPlayerCheckBox.setToolTipText("If selected, adds the matrix cell value as a third player to the association.");
buttonPanel.add(cellValueToPlayerCheckBox, new java.awt.GridBagConstraints());
fillerPanel.setPreferredSize(new java.awt.Dimension(100, 10));
javax.swing.GroupLayout fillerPanelLayout = new javax.swing.GroupLayout(fillerPanel);
fillerPanel.setLayout(fillerPanelLayout);
fillerPanelLayout.setHorizontalGroup(
fillerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 153, Short.MAX_VALUE)
);
fillerPanelLayout.setVerticalGroup(
fillerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 10, Short.MAX_VALUE)
);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
buttonPanel.add(fillerPanel, gridBagConstraints);
importButton.setText("Import");
importButton.setMargin(new java.awt.Insets(2, 2, 2, 2));
importButton.setPreferredSize(new java.awt.Dimension(70, 23));
importButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
importButtonMouseReleased(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3);
buttonPanel.add(importButton, gridBagConstraints);
cancelButton.setText("Cancel");
cancelButton.setMargin(new java.awt.Insets(2, 2, 2, 2));
cancelButton.setPreferredSize(new java.awt.Dimension(70, 23));
cancelButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
cancelButtonMouseReleased(evt);
}
});
buttonPanel.add(cancelButton, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 4);
getContentPane().add(buttonPanel, gridBagConstraints);
pack();
}// </editor-fold>//GEN-END:initComponents
private void urlClearButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_urlClearButtonMouseReleased
this.urlTextPane.setText("");
}//GEN-LAST:event_urlClearButtonMouseReleased
private void fileClearButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_fileClearButtonMouseReleased
this.fileTextPane.setText("");
}//GEN-LAST:event_fileClearButtonMouseReleased
private void cancelButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cancelButtonMouseReleased
wasAccepted = false;
setVisible(false);
}//GEN-LAST:event_cancelButtonMouseReleased
private void importButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_importButtonMouseReleased
wasAccepted = true;
setVisible(false);
}//GEN-LAST:event_importButtonMouseReleased
private void fileBrowseButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_fileBrowseButtonMouseReleased
selectFiles();
}//GEN-LAST:event_fileBrowseButtonMouseReleased
private void fileGetSLButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_fileGetSLButtonMouseReleased
selectContextSLFiles();
}//GEN-LAST:event_fileGetSLButtonMouseReleased
private void urlGetSLButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_urlGetSLButtonMouseReleased
selectContextSLs();
}//GEN-LAST:event_urlGetSLButtonMouseReleased
private void urlGetSIButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_urlGetSIButtonMouseReleased
selectContextSIs();
}//GEN-LAST:event_urlGetSIButtonMouseReleased
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel buttonPanel;
private javax.swing.JButton cancelButton;
private javax.swing.JCheckBox cellValueToPlayerCheckBox;
private javax.swing.JButton fileBrowseButton;
private javax.swing.JPanel fileButtonPanel;
private javax.swing.JButton fileClearButton;
private javax.swing.JButton fileGetSLButton;
private javax.swing.JLabel fileLabel;
private javax.swing.JPanel filePanel;
private javax.swing.JScrollPane fileScrollPane;
private javax.swing.JTextPane fileTextPane;
private javax.swing.JPanel fillerPanel;
private javax.swing.JButton importButton;
private javax.swing.JLabel rawLabel;
private javax.swing.JPanel rawPanel;
private javax.swing.JScrollPane rawScrollPane;
private javax.swing.JTextPane rawTextPane;
private javax.swing.JTabbedPane tabbedSourcePane;
private javax.swing.JPanel urlButtonPanel;
private javax.swing.JButton urlClearButton;
private javax.swing.JButton urlGetSIButton;
private javax.swing.JButton urlGetSLButton;
private javax.swing.JLabel urlLabel;
private javax.swing.JPanel urlPanel;
private javax.swing.JScrollPane urlScrollPane;
private javax.swing.JTextPane urlTextPane;
// End of variables declaration//GEN-END:variables
}
| 26,336 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
IncidenceMatrixImport.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/importers/graphs/IncidenceMatrixImport.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* IncidenceMatrixImport.java
*
* Created on 2009-12-27, 17:42
*
*/
package org.wandora.application.tools.importers.graphs;
import java.util.ArrayList;
import javax.swing.Icon;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.WandoraToolType;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.UIBox;
import org.wandora.application.tools.AbstractWandoraTool;
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 akivela
*/
public class IncidenceMatrixImport extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
public final static String SI_PREFIX = "http://wandora.org/si/topic/";
/** Creates a new instance of IncidenceMatrixImport */
public IncidenceMatrixImport() {
}
@Override
public String getName() {
return "Incidence matrix import";
}
@Override
public String getDescription() {
return "Generates topics and associations from given incidence matrix.";
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
TopicMap topicmap = solveContextTopicMap(wandora, context);
IncidenceMatrixImportDialog matrixSourceDialog = new IncidenceMatrixImportDialog(wandora, this, true);
matrixSourceDialog.setVisible(true);
if(!matrixSourceDialog.wasAccepted()) return;
setDefaultLogger();
setLogTitle("Incidence matrix import");
log("Reading incidence matrix.");
String matrixData = matrixSourceDialog.getContent();
log("Parsing...");
MatrixParser matrixParser = new MatrixParser(matrixData, topicmap);
matrixParser.parse();
log("Created "+matrixParser.counter+" associations.");
log("Ready.");
setState(WAIT);
}
public Topic getOrCreateTopic(TopicMap map, String si, String basename) {
Topic topic = null;
try {
topic = map.getTopic(si);
if(topic == null) {
topic = map.createTopic();
topic.addSubjectIdentifier(new Locator(si));
if(basename != null && basename.length() > 0) topic.setBaseName(basename);
}
}
catch(Exception e) {
log(e);
e.printStackTrace();
}
return topic;
}
@Override
public WandoraToolType getType() {
return WandoraToolType.createImportType();
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/import_incidence_matrix.png");
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
private class MatrixParser {
private String rowRegex = "[\n\r]+";
private String colRegex = "[\\s]+";
private String data = null;
private int len = 0;
private TopicMap topicmap = null;
public int counter = 0;
ArrayList<String>[] associations = null;
public MatrixParser(String data, TopicMap topicmap) {
this.data = data;
this.topicmap = topicmap;
this.len = data.length();
setProgressMax(len);
}
private void parse() {
String[] rows = data.split(rowRegex);
associations = new ArrayList[rows.length];
ArrayList<String> a = null;
for(int row=0; row<rows.length; row++) {
if(rows[row] != null && rows[row].length() > 0) {
String[] cols = rows[row].split(colRegex);
for(int col=0; col<cols.length; col++) {
if(cols[col] != null && cols[col].length() > 0) {
String cell = cols[col].trim();
if(!"0".equals(cell)) {
try {
a = associations[col];
if(a == null) {
a = new ArrayList<String>();
associations[col] = a;
}
if(a != null) {
a.add(""+row);
}
}
catch(Exception e) {
e.printStackTrace();
}
}
}
}
}
}
for(ArrayList<String> associationStruct : associations) {
try {
Topic atype = getOrCreateTopic(topicmap, SI_PREFIX+"edge", "edge");
Association realAssociation = topicmap.createAssociation(atype);
//System.out.println("Creating asso: ");
int roleCount = 0;
for(String playerStr : associationStruct) {
Topic player = getOrCreateTopic(topicmap, SI_PREFIX+playerStr, ""+playerStr);
Topic role = getOrCreateTopic(topicmap, SI_PREFIX+"role-"+roleCount, "role-"+roleCount);
//System.out.println(" player: "+player+", role: "+role);
realAssociation.addPlayer(player, role);
roleCount++;
}
counter++;
}
catch(Exception e) {
e.printStackTrace();
}
}
}
}
}
| 6,800 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AdjacencyListImportDialog.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/importers/graphs/AdjacencyListImportDialog.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
* AdjacencyListImportDialog.java
*
* Created on 2008-09-22, 13:14
*/
package org.wandora.application.tools.importers.graphs;
import java.awt.Component;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.UIConstants;
import org.wandora.application.gui.simple.SimpleFileChooser;
import org.wandora.application.gui.simple.SimpleTextPane;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.Topic;
import org.wandora.utils.IObox;
/**
*
* @author akivela
*/
public class AdjacencyListImportDialog extends javax.swing.JDialog {
private static final long serialVersionUID = 1L;
private Wandora parent = null;
private WandoraTool parentTool = null;
private boolean wasAccepted = false;
/** Creates new form AdjacencyListImportDialog */
public AdjacencyListImportDialog(Wandora admin, WandoraTool parentTool, boolean modal) {
super(admin, modal);
this.parent = admin;
initComponents();
initialize(parentTool);
}
public void initialize(WandoraTool parentTool) {
this.parentTool = parentTool;
wasAccepted = false;
((SimpleTextPane) fileTextPane).dropFileNames(true);
((SimpleTextPane) fileTextPane).setLineWrap(false);
((SimpleTextPane) urlTextPane).setLineWrap(false);
setTitle("Import adjacency list");
setSize(640,400);
if(parent != null) parent.centerWindow(this);
}
public boolean wasAccepted() {
return wasAccepted;
}
// --- CONTENT ---
public String getContent() {
Component selectedComponent = tabbedSourcePane.getSelectedComponent();
if(rawPanel.equals(selectedComponent)) {
return rawTextPane.getText();
}
else if(filePanel.equals(selectedComponent)) {
File[] files = getFileSources();
StringBuilder sb = new StringBuilder("");
for(File file : files) {
try {
sb.append(IObox.loadFile(file));
}
catch(Exception e) {
parentTool.log(e);
}
}
}
else if(urlPanel.equals(selectedComponent)) {
String[] urls = getURLSources();
StringBuilder sb = new StringBuilder("");
for(String url : urls) {
try {
sb.append(IObox.doUrl(new URL(url)));
}
catch(Exception e) {
parentTool.log(e);
}
}
}
return null;
}
// --- FILE SOURCE ---
public File[] getFileSources() {
String input = fileTextPane.getText();
String[] filenames = splitText(input);
ArrayList<File> files = new ArrayList<File>();
File f = null;
for(String filename : filenames) {
f = new File(filename);
if(f.exists()) {
files.add(f);
}
else {
if (parentTool != null) {
parentTool.log("File '" + filename + "' not found!");
}
}
}
return files.toArray( new File[] {} );
}
// --- URL SOURCE ---
public String[] getURLSources() {
String input = urlTextPane.getText();
String[] urls = splitText(input);
return urls;
}
private String[] splitText(String str) {
if(str == null) return null;
if(str.contains("\n")) {
String[] s = str.split("\n");
for(int i=0; i<s.length; i++) {
s[i] = s[i].trim();
}
return s;
}
else {
return new String[] { str.trim() };
}
}
// -------------------------------------------------------------------------
private void selectFiles() {
SimpleFileChooser chooser = UIConstants.getFileChooser();
chooser.setMultiSelectionEnabled(true);
//chooser.setDialogTitle(getGUIText(SELECT_DIALOG_TITLE));
chooser.setApproveButtonText("Select");
chooser.setFileSelectionMode(SimpleFileChooser.FILES_AND_DIRECTORIES);
//if(accessoryPanel != null) { chooser.setAccessory(accessoryPanel); }
if(chooser.open(parent, SimpleFileChooser.OPEN_DIALOG)==SimpleFileChooser.APPROVE_OPTION) {
File[] files = chooser.getSelectedFiles();
File f = null;
String fs = "";
for(int i=0; i<files.length; i++) {
f = files[i];
fs = fs + f.getAbsolutePath();
if(i<files.length-1) fs = fs + "\n";
}
String s = fileTextPane.getText();
if(s == null || s.length() == 0) s = fs;
else s = s + "\n" + fs;
fileTextPane.setText(s);
}
}
private void selectContextSLFiles() {
if(parentTool == null) return;
Context context = parentTool.getContext();
Iterator iter = context.getContextObjects();
Object o = null;
Topic t = null;
Locator locator = null;
StringBuilder sb = new StringBuilder("");
while(iter.hasNext()) {
try {
o = iter.next();
if(o == null) continue;
if(o instanceof Topic) {
t = (Topic) o;
if(!t.isRemoved()) {
locator = t.getSubjectLocator();
if(locator != null) {
String locatorStr = locator.toExternalForm();
if(locatorStr.startsWith("file:")) {
locatorStr = IObox.getFileFromURL(locatorStr);
sb.append(locatorStr).append("\n");
}
}
}
}
}
catch(Exception e) {
parentTool.log(e);
}
}
String s = urlTextPane.getText();
if(s == null || s.length() == 0) s = sb.toString();
else s = s + "\n" + sb.toString();
fileTextPane.setText(s);
}
private void selectContextSLs() {
if(parentTool == null) return;
Context context = parentTool.getContext();
Iterator iter = context.getContextObjects();
Object o = null;
Topic t = null;
Locator locator = null;
StringBuilder sb = new StringBuilder("");
while(iter.hasNext()) {
try {
o = iter.next();
if(o == null) continue;
if(o instanceof Topic) {
t = (Topic) o;
if(!t.isRemoved()) {
locator = t.getSubjectLocator();
if(locator != null) {
String locatorStr = locator.toExternalForm();
sb.append(locatorStr + "\n");
}
}
}
}
catch(Exception e) {
parentTool.log(e);
}
}
String s = urlTextPane.getText();
if(s == null || s.length() == 0) s = sb.toString();
else s = s + "\n" + sb.toString();
urlTextPane.setText(s);
}
private void selectContextSIs() {
if(parentTool == null) return;
Context context = parentTool.getContext();
Iterator iter = context.getContextObjects();
Object o = null;
Topic t = null;
Locator locator = null;
StringBuilder sb = new StringBuilder("");
while(iter.hasNext()) {
try {
o = iter.next();
if(o == null) continue;
if(o instanceof Topic) {
t = (Topic) o;
if(!t.isRemoved()) {
Collection<Locator> ls = t.getSubjectIdentifiers();
Iterator<Locator> ils = ls.iterator();
while(ils.hasNext()) {
locator = ils.next();
if(locator != null) {
String locatorStr = locator.toExternalForm();
sb.append(locatorStr).append("\n");
}
}
}
}
}
catch(Exception e) {
parentTool.log(e);
}
}
String s = urlTextPane.getText();
if(s == null || s.length() == 0) s = sb.toString();
else s = s + "\n" + sb.toString();
urlTextPane.setText(s);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
tabbedSourcePane = new org.wandora.application.gui.simple.SimpleTabbedPane();
rawPanel = new javax.swing.JPanel();
rawLabel = new org.wandora.application.gui.simple.SimpleLabel();
rawScrollPane = new javax.swing.JScrollPane();
rawTextPane = new org.wandora.application.gui.simple.SimpleTextPane();
filePanel = new javax.swing.JPanel();
fileLabel = new org.wandora.application.gui.simple.SimpleLabel();
fileScrollPane = new javax.swing.JScrollPane();
fileTextPane = new org.wandora.application.gui.simple.SimpleTextPane();
fileButtonPanel = new javax.swing.JPanel();
fileBrowseButton = new org.wandora.application.gui.simple.SimpleButton();
fileGetSLButton = new org.wandora.application.gui.simple.SimpleButton();
fileClearButton = new org.wandora.application.gui.simple.SimpleButton();
urlPanel = new javax.swing.JPanel();
urlLabel = new org.wandora.application.gui.simple.SimpleLabel();
urlScrollPane = new javax.swing.JScrollPane();
urlTextPane = new org.wandora.application.gui.simple.SimpleTextPane();
urlButtonPanel = new javax.swing.JPanel();
urlGetSIButton = new org.wandora.application.gui.simple.SimpleButton();
urlGetSLButton = new org.wandora.application.gui.simple.SimpleButton();
urlClearButton = new org.wandora.application.gui.simple.SimpleButton();
buttonPanel = new javax.swing.JPanel();
fillerPanel = new javax.swing.JPanel();
importButton = new org.wandora.application.gui.simple.SimpleButton();
cancelButton = new org.wandora.application.gui.simple.SimpleButton();
getContentPane().setLayout(new java.awt.GridBagLayout());
rawPanel.setLayout(new java.awt.GridBagLayout());
rawLabel.setText("<html>This tab is used to inject actual adjacency list to the importer. Paste or drag'n'drop raw content to the field below.</html>");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rawPanel.add(rawLabel, gridBagConstraints);
rawScrollPane.setPreferredSize(new java.awt.Dimension(10, 100));
rawScrollPane.setViewportView(rawTextPane);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 5, 5, 5);
rawPanel.add(rawScrollPane, gridBagConstraints);
tabbedSourcePane.addTab("Raw", rawPanel);
filePanel.setLayout(new java.awt.GridBagLayout());
fileLabel.setText("<html>This tab is used to address files containing adjacency lists. Please browse files or get subject locator files.</html>");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
filePanel.add(fileLabel, gridBagConstraints);
fileScrollPane.setPreferredSize(new java.awt.Dimension(10, 100));
fileScrollPane.setViewportView(fileTextPane);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 5);
filePanel.add(fileScrollPane, gridBagConstraints);
fileButtonPanel.setLayout(new java.awt.GridBagLayout());
fileBrowseButton.setText("Browse");
fileBrowseButton.setMargin(new java.awt.Insets(1, 6, 1, 6));
fileBrowseButton.setPreferredSize(new java.awt.Dimension(60, 21));
fileBrowseButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
fileBrowseButtonMouseReleased(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 1);
fileButtonPanel.add(fileBrowseButton, gridBagConstraints);
fileGetSLButton.setText("Get SLs");
fileGetSLButton.setMargin(new java.awt.Insets(1, 6, 1, 6));
fileGetSLButton.setPreferredSize(new java.awt.Dimension(60, 21));
fileGetSLButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
fileGetSLButtonMouseReleased(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 1);
fileButtonPanel.add(fileGetSLButton, gridBagConstraints);
fileClearButton.setText("Clear");
fileClearButton.setMargin(new java.awt.Insets(1, 6, 1, 6));
fileClearButton.setPreferredSize(new java.awt.Dimension(60, 21));
fileClearButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
fileClearButtonMouseReleased(evt);
}
});
fileButtonPanel.add(fileClearButton, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
filePanel.add(fileButtonPanel, gridBagConstraints);
tabbedSourcePane.addTab("Files", filePanel);
urlPanel.setLayout(new java.awt.GridBagLayout());
urlLabel.setText("<html>This tab is used to address URL resources containing adjacency list data. Please write URL addresses below or get subject identifiers from context topics.</html>");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
urlPanel.add(urlLabel, gridBagConstraints);
urlScrollPane.setPreferredSize(new java.awt.Dimension(10, 100));
urlScrollPane.setViewportView(urlTextPane);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 5);
urlPanel.add(urlScrollPane, gridBagConstraints);
urlButtonPanel.setLayout(new java.awt.GridBagLayout());
urlGetSIButton.setText("Get SIs");
urlGetSIButton.setMargin(new java.awt.Insets(1, 6, 1, 6));
urlGetSIButton.setPreferredSize(new java.awt.Dimension(60, 21));
urlGetSIButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
urlGetSIButtonMouseReleased(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 1);
urlButtonPanel.add(urlGetSIButton, gridBagConstraints);
urlGetSLButton.setText("Get SLs");
urlGetSLButton.setMargin(new java.awt.Insets(1, 6, 1, 6));
urlGetSLButton.setPreferredSize(new java.awt.Dimension(60, 21));
urlGetSLButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
urlGetSLButtonMouseReleased(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 1);
urlButtonPanel.add(urlGetSLButton, gridBagConstraints);
urlClearButton.setText("Clear");
urlClearButton.setMargin(new java.awt.Insets(1, 6, 1, 6));
urlClearButton.setPreferredSize(new java.awt.Dimension(60, 21));
urlClearButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
urlClearButtonMouseReleased(evt);
}
});
urlButtonPanel.add(urlClearButton, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
urlPanel.add(urlButtonPanel, gridBagConstraints);
tabbedSourcePane.addTab("URLs", urlPanel);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 4, 0);
getContentPane().add(tabbedSourcePane, gridBagConstraints);
tabbedSourcePane.getAccessibleContext().setAccessibleName("");
buttonPanel.setLayout(new java.awt.GridBagLayout());
fillerPanel.setPreferredSize(new java.awt.Dimension(100, 10));
javax.swing.GroupLayout fillerPanelLayout = new javax.swing.GroupLayout(fillerPanel);
fillerPanel.setLayout(fillerPanelLayout);
fillerPanelLayout.setHorizontalGroup(
fillerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 270, Short.MAX_VALUE)
);
fillerPanelLayout.setVerticalGroup(
fillerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 10, Short.MAX_VALUE)
);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
buttonPanel.add(fillerPanel, gridBagConstraints);
importButton.setText("Import");
importButton.setMargin(new java.awt.Insets(2, 2, 2, 2));
importButton.setPreferredSize(new java.awt.Dimension(70, 23));
importButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
importButtonMouseReleased(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3);
buttonPanel.add(importButton, gridBagConstraints);
cancelButton.setText("Cancel");
cancelButton.setMargin(new java.awt.Insets(2, 2, 2, 2));
cancelButton.setPreferredSize(new java.awt.Dimension(70, 23));
cancelButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
cancelButtonMouseReleased(evt);
}
});
buttonPanel.add(cancelButton, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 4);
getContentPane().add(buttonPanel, gridBagConstraints);
pack();
}// </editor-fold>//GEN-END:initComponents
private void urlClearButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_urlClearButtonMouseReleased
this.urlTextPane.setText("");
}//GEN-LAST:event_urlClearButtonMouseReleased
private void fileClearButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_fileClearButtonMouseReleased
this.fileTextPane.setText("");
}//GEN-LAST:event_fileClearButtonMouseReleased
private void cancelButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cancelButtonMouseReleased
wasAccepted = false;
setVisible(false);
}//GEN-LAST:event_cancelButtonMouseReleased
private void importButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_importButtonMouseReleased
wasAccepted = true;
setVisible(false);
}//GEN-LAST:event_importButtonMouseReleased
private void fileBrowseButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_fileBrowseButtonMouseReleased
selectFiles();
}//GEN-LAST:event_fileBrowseButtonMouseReleased
private void fileGetSLButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_fileGetSLButtonMouseReleased
selectContextSLFiles();
}//GEN-LAST:event_fileGetSLButtonMouseReleased
private void urlGetSLButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_urlGetSLButtonMouseReleased
selectContextSLs();
}//GEN-LAST:event_urlGetSLButtonMouseReleased
private void urlGetSIButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_urlGetSIButtonMouseReleased
selectContextSIs();
}//GEN-LAST:event_urlGetSIButtonMouseReleased
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel buttonPanel;
private javax.swing.JButton cancelButton;
private javax.swing.JButton fileBrowseButton;
private javax.swing.JPanel fileButtonPanel;
private javax.swing.JButton fileClearButton;
private javax.swing.JButton fileGetSLButton;
private javax.swing.JLabel fileLabel;
private javax.swing.JPanel filePanel;
private javax.swing.JScrollPane fileScrollPane;
private javax.swing.JTextPane fileTextPane;
private javax.swing.JPanel fillerPanel;
private javax.swing.JButton importButton;
private javax.swing.JLabel rawLabel;
private javax.swing.JPanel rawPanel;
private javax.swing.JScrollPane rawScrollPane;
private javax.swing.JTextPane rawTextPane;
private javax.swing.JTabbedPane tabbedSourcePane;
private javax.swing.JPanel urlButtonPanel;
private javax.swing.JButton urlClearButton;
private javax.swing.JButton urlGetSIButton;
private javax.swing.JButton urlGetSLButton;
private javax.swing.JLabel urlLabel;
private javax.swing.JPanel urlPanel;
private javax.swing.JScrollPane urlScrollPane;
private javax.swing.JTextPane urlTextPane;
// End of variables declaration//GEN-END:variables
}
| 25,524 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AdjacencyListImport.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/importers/graphs/AdjacencyListImport.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* AdjacencyListImport.java
*
* Created on 2008-09-20, 16:42
*
*/
package org.wandora.application.tools.importers.graphs;
import java.util.ArrayList;
import javax.swing.Icon;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.WandoraToolType;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.UIBox;
import org.wandora.application.tools.AbstractWandoraTool;
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 akivela
*/
public class AdjacencyListImport extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
public final static String SI_PREFIX = "http://wandora.org/si/topic/";
public static String nodeDelimiter = ",";
public static String edgeDelimiter = "";
/** Creates a new instance of AdjacencyListImport */
public AdjacencyListImport() {
}
@Override
public String getName() {
return "Adjacency list import";
}
@Override
public String getDescription() {
return "Generates topics and associations from given adjacency list.";
}
@Override
public void execute(Wandora admin, Context context) throws TopicMapException {
TopicMap topicmap = solveContextTopicMap(admin, context);
AdjacencyListImportDialog edgeSourceDialog = new AdjacencyListImportDialog(admin, this, true);
edgeSourceDialog.setVisible(true);
if(!edgeSourceDialog.wasAccepted()) return;
setDefaultLogger();
setLogTitle("Adjacency list import");
log("Reading adjacency list.");
String edgeData = edgeSourceDialog.getContent();
log("Parsing...");
EdgeParser edgeParser = new EdgeParser(edgeData, topicmap);
edgeParser.parse();
log("Created "+edgeParser.counter+" associations.");
log("Ready.");
setState(WAIT);
}
protected void createEdgeAssociation(ArrayList<String> edge, TopicMap topicmap) {
try {
if(topicmap != null && edge != null && edge.size() > 0) {
hlog("Processing association "+edge);
Topic atype = getOrCreateTopic(topicmap, SI_PREFIX+"edge", "edge");
Association a = null;
Topic player = null;
Topic role = null;
a = topicmap.createAssociation(atype);
int rc = 0;
for(String node : edge) {
if(node != null && node.length() > 0) {
player = getOrCreateTopic(topicmap, SI_PREFIX+node, node);
role = getOrCreateTopic(topicmap, SI_PREFIX+"role"+rc, "role"+rc);
if(player != null && !player.isRemoved()) {
if(role != null && !role.isRemoved()) {
a.addPlayer(player, role);
}
}
rc++;
}
}
}
}
catch(Exception e) {
log(e);
}
}
public Topic getOrCreateTopic(TopicMap map, String si, String basename) {
Topic topic = null;
try {
topic = map.getTopic(si);
if(topic == null) {
topic = map.createTopic();
topic.addSubjectIdentifier(new Locator(si));
if(basename != null && basename.length() > 0) topic.setBaseName(basename);
}
}
catch(Exception e) {
log(e);
e.printStackTrace();
}
return topic;
}
@Override
public WandoraToolType getType() {
return WandoraToolType.createImportType();
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/import_adjacency_list.png");
}
private class EdgeParser {
private String data = null;
private int index = 0;
private int len = 0;
private TopicMap topicmap = null;
public int counter = 0;
public EdgeParser(String data, TopicMap topicmap) {
this.data = data;
this.topicmap = topicmap;
this.index = 0;
this.len = data.length();
setProgressMax(len);
}
private void parse() {
ArrayList<String> edge = null;
while(index < len && !forceStop()) {
eatSpaces();
while(index < len && !Character.isLetterOrDigit(data.charAt(index))) {
index++;
eatSpaces();
}
edge = parseEdge();
if(edge != null && edge.size() > 0) {
createEdgeAssociation(edge, topicmap);
counter++;
}
eatSpaces();
setProgress(len);
}
}
private ArrayList<String> parseEdge() {
ArrayList<String> edge = new ArrayList<String>();
String node = null;
do {
eatSpaces();
node = parseNode();
if(node != null && node.length() > 0) {
edge.add(node);
}
parseNodeDelimiter();
}
while(!parseEdgeDelimiter() && !forceStop());
return edge;
}
private String parseNode() {
StringBuilder node = new StringBuilder("");
while(index < len && Character.isLetterOrDigit(data.charAt(index)) && !forceStop()) {
node.append(data.charAt((index)));
index++;
}
return node.toString();
}
private boolean parseNodeDelimiter() {
index++;
eatJustSpaces();
if(index < len && ",-|\t".indexOf(data.charAt(index)) != -1) {
index++;
return true;
}
return false;
}
private boolean parseEdgeDelimiter() {
eatJustSpaces();
boolean delimiterFound = false;
while(index < len && "\n\r;:()[]{}<>/".indexOf(data.charAt(index)) != -1) {
index++;
delimiterFound=true;
}
if(index >= len) delimiterFound = true;
return delimiterFound;
}
private void eatSpaces() {
if(data == null) return;
while(index < len && Character.isSpaceChar(data.charAt(index))) {
index++;
}
}
private void eatJustSpaces() {
if(data == null) return;
while(index < len && data.charAt(index)==' ') {
index++;
}
}
}
} | 8,098 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
ExportTopicMap.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/exporters/ExportTopicMap.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* ExportTopicMap.java
*
* Created on 2. helmikuuta 2006, 15:05
*
*/
package org.wandora.application.tools.exporters;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import javax.swing.Icon;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.UIBox;
import org.wandora.application.gui.filechooser.JTMFileFilter;
import org.wandora.application.gui.filechooser.LTMFileFilter;
import org.wandora.application.gui.filechooser.TopicMapFileChooser;
import org.wandora.application.gui.filechooser.XTM1FileFilter;
import org.wandora.topicmap.TopicMap;
import org.wandora.utils.IObox;
/**
*
* @author akivela
*/
public class ExportTopicMap extends AbstractExportTool implements WandoraTool {
private static final long serialVersionUID = 1L;
public boolean EXPORT_SELECTION_INSTEAD_TOPIC_MAP = false;
public ExportTopicMap() {
}
public ExportTopicMap(boolean exportSelection) {
EXPORT_SELECTION_INSTEAD_TOPIC_MAP = exportSelection;
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/export_topicmap.png");
}
@Override
public void execute(Wandora wandora, Context context) {
TopicMap tm = null;
String topicMapName = null;
String exportInfo = "";
// --- Solve first topic map to be exported
if(EXPORT_SELECTION_INSTEAD_TOPIC_MAP) {
tm = makeTopicMapWith(context);
exportInfo = "Exporting selected topics as topic map";
}
else {
tm = solveContextTopicMap(wandora, context);
topicMapName = this.solveNameForTopicMap(wandora, tm);
if(topicMapName != null) {
exportInfo = "Exporting topic map in layer '" + topicMapName + "'";
}
else {
exportInfo = "Exporting topic map";
}
}
// --- Then solve target file (and format)
TopicMapFileChooser chooser=new TopicMapFileChooser();
chooser.setDialogTitle(exportInfo+"...");
if(chooser.open(wandora, "Export")==TopicMapFileChooser.APPROVE_OPTION){
setDefaultLogger();
File file = chooser.getSelectedFile();
String fileName = file.getName();
String fileNameUpper = file.getName().toUpperCase();
javax.swing.filechooser.FileFilter fileFilter = chooser.getFileFilter();
// --- Finally write topicmap to chosen file
try {
OutputStream out=null;
if(fileFilter instanceof JTMFileFilter || fileNameUpper.endsWith(".JTM")) {
file=IObox.forceFileExtension(file, "jtm");
fileName = file.getName();
out=new FileOutputStream(file);
log(exportInfo+" in JTM format to '"+fileName+"'.");
tm.exportJTM(out, getCurrentLogger());
}
else if(fileFilter instanceof LTMFileFilter || fileNameUpper.endsWith(".LTM")) {
file=IObox.forceFileExtension(file, "ltm");
fileName = file.getName();
out=new FileOutputStream(file);
log(exportInfo+" in LTM format to '"+fileName+"'.");
tm.exportLTM(out, getCurrentLogger());
}
else if(fileFilter instanceof XTM1FileFilter || fileNameUpper.endsWith(".XTM1") || fileNameUpper.endsWith(".XTM10")){
file=IObox.forceFileExtension(file, "xtm1");
fileName = file.getName();
out=new FileOutputStream(file);
log(exportInfo+" in XTM 1.0 format to '"+fileName+"'.");
tm.exportXTM10(out, getCurrentLogger());
}
else {
file=IObox.addFileExtension(file, "xtm"); // Ensure file extension exists!
fileName = file.getName(); // Updating filename if file has changed!
out=new FileOutputStream(file);
log(exportInfo+" in XTM 2.0 format to '"+fileName+"'.");
//System.out.println("tm == "+ tm);
tm.exportXTM20(out, getCurrentLogger());
}
if(out != null) out.close();
log("Ready.");
}
catch(Exception e) {
log(e);
}
setState(WAIT);
}
}
@Override
public String getName() {
return "Export Topic Map";
}
@Override
public String getDescription() {
return "Exports a topic map file. " +
"Wandora supports XTM 1.0, XTM 2.0, LTM and JTM topic map file formats.";
}
}
| 5,733 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
GXLExport.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/exporters/GXLExport.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*/
package org.wandora.application.tools.exporters;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import javax.swing.Icon;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.WandoraToolLogger;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.UIBox;
import org.wandora.application.gui.UIConstants;
import org.wandora.application.gui.simple.SimpleFileChooser;
import org.wandora.application.tools.GenericOptionsDialog;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.utils.IObox;
/**
*
* @author akivela
*/
public class GXLExport extends AbstractExportTool implements WandoraTool {
private static final long serialVersionUID = 1L;
public boolean EXPORT_SELECTION_INSTEAD_TOPIC_MAP = false;
public boolean EXPORT_CLASSES = true;
public boolean EXPORT_OCCURRENCES = false;
public boolean PREFER_EDGES = true;
public boolean BASE_NAMES_AS_IDS = true;
public GXLExport() {
}
public GXLExport(boolean exportSelection) {
EXPORT_SELECTION_INSTEAD_TOPIC_MAP = exportSelection;
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/export_graph.png");
}
@Override
public boolean requiresRefresh() {
return false;
}
@Override
public boolean isConfigurable(){
return true;
}
@Override
public void configure(Wandora wandora,org.wandora.utils.Options options,String prefix) throws TopicMapException {
GenericOptionsDialog god=new GenericOptionsDialog(wandora,"GXL Export options","GXL Export options",true,new String[][]{
new String[]{"Export classes","boolean",(EXPORT_CLASSES ? "true" : "false"),"Should Wandora export also topic types (class-instance relations)?"},
new String[]{"Export occurrences","boolean",(EXPORT_OCCURRENCES ? "true" : "false"),"Should topic occurrences also export?"},
new String[]{"Use base name as id","boolean",(BASE_NAMES_AS_IDS ? "true" : "false"), "Use topic's base name as XML node id" },
new String[]{"Prefer edges instead of rels","boolean",(PREFER_EDGES ? "true" : "false"),"Prefer edge elements instead of rel elements in XML?"},
},wandora);
god.setVisible(true);
if(god.wasCancelled()) return;
Map<String, String> values = god.getValues();
EXPORT_OCCURRENCES = ("true".equals(values.get("Export occurrences")) ? true : false );
EXPORT_CLASSES = ("true".equals(values.get("Export classes")) ? true : false );
BASE_NAMES_AS_IDS = ("true".equals(values.get("Use base name as id")) ? true : false );
PREFER_EDGES = ("true".equals(values.get("Prefer edges instead of rels")) ? true : false );
}
@Override
public void execute(Wandora wandora, Context context) {
String topicMapName = null;
String exportInfo = null;
// --- Solve first topic map to be exported
TopicMap tm = null;
if(EXPORT_SELECTION_INSTEAD_TOPIC_MAP) {
tm = makeTopicMapWith(context);
exportInfo = "Exporting selected topics as GXL (Graph eXchange Language) graph";
topicMapName = "selection_in_wandora";
}
else {
tm = solveContextTopicMap(wandora, context);
topicMapName = this.solveNameForTopicMap(wandora, tm);
if(topicMapName != null) {
exportInfo = "Exporting topic map in layer '" + topicMapName + "' as GXL (Graph eXchange Language) graph";
}
else {
exportInfo = "Exporting topic map as GXL (Graph eXchange Language) graph";
topicMapName = "no_name_topic_map";
}
}
// --- Then solve target file
SimpleFileChooser chooser=UIConstants.getFileChooser();
chooser.setDialogTitle(exportInfo+"...");
if(chooser.open(wandora, "Export")==SimpleFileChooser.APPROVE_OPTION){
setDefaultLogger();
File file = chooser.getSelectedFile();
String fileName = file.getName();
// --- Finally write topicmap as GXL to chosen file
OutputStream out = null;
try {
file = IObox.addFileExtension(file, "gxl"); // Ensure file extension exists!
fileName = file.getName(); // Updating filename if file has changed!
out = new FileOutputStream(file);
log(exportInfo+" to '"+fileName+"'.");
exportGraphML(out, tm, topicMapName, getCurrentLogger());
out.close();
log("Ready.");
}
catch(Exception e) {
log(e);
try { if(out != null) out.close(); }
catch(Exception e2) { log(e2); }
}
}
setState(WAIT);
}
@Override
public String getName() {
return "Export GXL graph";
}
@Override
public String getDescription() {
return "Exports topic map layer as GXL (Graph eXchange Language) file.";
}
public void exportGraphML(OutputStream out, TopicMap topicMap, String graphName, WandoraToolLogger logger) throws TopicMapException {
if(logger == null) logger = this;
PrintWriter writer = null;
try {
writer = new PrintWriter(new OutputStreamWriter(out, "UTF-8"));
}
catch (UnsupportedEncodingException ex) {
log("Exception while instantiating PrintWriter with UTF-8 character encoding. Using default encoding.");
writer = new PrintWriter(new OutputStreamWriter(out));
}
int totalCount = 2*topicMap.getNumTopics() + topicMap.getNumAssociations();
logger.setProgressMax(totalCount);
int count = 0;
println(writer, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
println(writer, "<gxl xmlns:xlink=\"http://www.w3.org/1999/xlink\">");
print(writer, " <graph id=\"WandoraExport"+makeID(graphName)+"\"");
print(writer, " edgemode=\"defaultundirected\"");
print(writer, " hypergraph=\"true\"");
println(writer, ">");
Iterator<Topic> iter=topicMap.getTopics();
while(iter.hasNext() && !logger.forceStop()) {
Topic t=(Topic)iter.next();
if(t.isRemoved()) continue;
logger.setProgress(count++);
echoNode(t, writer);
}
// Topic types....
if(EXPORT_CLASSES && !logger.forceStop()) {
iter=topicMap.getTopics();
while(iter.hasNext() && !logger.forceStop()) {
logger.setProgress(count++);
Topic t=(Topic)iter.next();
if(t.isRemoved()) continue;
Iterator<Topic> iter2=t.getTypes().iterator();
while(iter2.hasNext()) {
Topic t2=(Topic)iter2.next();
if(t2.isRemoved()) continue;
echoEdge(t2, t, "class-instance", "class", "instance", writer);
}
}
}
// Associations....
if(!logger.forceStop()) {
Iterator<Association> associationIter=topicMap.getAssociations();
icount=0;
while(associationIter.hasNext() && !logger.forceStop()) {
logger.setProgress(count++);
Association a=associationIter.next();
echoEdge(a, writer);
}
}
println(writer, " </graph>"); // graph
println(writer, "</gxl>"); // graphml
writer.flush();
writer.close();
}
// --------------------------------------------------------------- ECHOS ---
protected void echoNode(Topic t, PrintWriter writer) throws TopicMapException {
if(t == null || writer == null) return;
String label = t.getBaseName();
if(label == null) label = t.getOneSubjectIdentifier().toExternalForm();
println(writer, " <node id=\""+makeID(t)+"\">");
if(t.getBaseName() != null) {
println(writer, " <attr name=\"basename\"><string>"+makeString(t.getBaseName())+"</string></attr>");
}
String sl = t.getSubjectLocator() == null ? null : t.getSubjectLocator().toExternalForm();
if(sl != null) {
println(writer, " <attr name=\"sl\"><string>"+makeString(sl)+"</string></attr>");
}
int siCount = 0;
for(Iterator<Locator> siIter = t.getSubjectIdentifiers().iterator(); siIter.hasNext(); ) {
Locator si = siIter.next();
if(si != null) {
println(writer, " <attr name=\"si"+(siCount>0?siCount:"")+"\"><string>"+makeString(si.toExternalForm())+"</string></attr>");
siCount++;
}
}
// Topic occurrences....
if(EXPORT_OCCURRENCES && t.getDataTypes().size()>0) {
Collection<Topic> types=t.getDataTypes();
Iterator<Topic> iter2=types.iterator();
while(iter2.hasNext()){
Topic type=(Topic)iter2.next();
String typeName = type.getBaseName();
Hashtable<Topic,String> ht=t.getData(type);
Iterator<Map.Entry<Topic,String>> iter3=ht.entrySet().iterator();
while(iter3.hasNext()){
Map.Entry<Topic,String> e=iter3.next();
String data=(String)e.getValue();
println(writer, " <attr name=\"occurrence-"+typeName+"\"><string>"+makeString(data)+"</string></attr>");
}
}
}
println(writer, " </node>");
}
int icount = 0;
protected void echoEdge(Association a, PrintWriter writer) throws TopicMapException {
if(PREFER_EDGES) {
Collection<Topic> roles = a.getRoles();
if(roles.size() < 2) return;
else if(roles.size() == 2) {
Topic[] roleArray = (Topic[]) roles.toArray(new Topic[2]);
Topic source = a.getPlayer(roleArray[0]);
Topic target = a.getPlayer(roleArray[1]);
println(writer, " <edge from=\""+makeID(source)+"\" to=\""+makeID(target)+"\">");
println(writer, " <type xlink:href=\""+makeID(a.getType())+"\"/>");
println(writer, " </edge>");
}
else {
icount++;
String target="nameless-intermediator-node-"+icount;
println(writer, " <node id=\""+target+"\">");
Iterator<Topic> iter2 = roles.iterator();
while(iter2.hasNext()) {
Topic role=(Topic)iter2.next();
println(writer, " <edge from=\""+makeID(a.getPlayer(role))+"\" to=\""+target+"\">");
println(writer, " </edge>");
}
}
}
else {
println(writer, " <rel>");
println(writer, " <type xlink:href=\""+makeID(a.getType())+"\"/>");
for(Iterator<Topic> roleIter=a.getRoles().iterator(); roleIter.hasNext(); ) {
Topic role = roleIter.next();
Topic player = a.getPlayer(role);
print(writer, " <relend");
print(writer, " role=\""+makeID(role)+"\"");
print(writer, " target=\""+makeID(player)+"\"");
println(writer, "/>");
}
println(writer, " </rel>");
}
}
protected void echoEdge(Topic source, Topic target, String type, String sourceRole, String targetRole, PrintWriter writer) throws TopicMapException {
if(PREFER_EDGES) {
println(writer, " <edge from=\""+makeID(source)+"\" to=\""+makeID(target)+"\">");
println(writer, " <type xlink:href=\""+type+"\"/>");
println(writer, " </edge>");
}
else {
println(writer, " <rel>");
println(writer, " <type xlink:href=\""+type+"\"/>");
println(writer, " <relend role=\""+sourceRole+"\" target=\""+makeID(source)+"\"/>");
println(writer, " <relend role=\""+targetRole+"\" target=\""+makeID(target)+"\"/>");
println(writer, " </rel>");
}
}
protected String makeID(Topic t) throws TopicMapException {
if(t.getBaseName() != null) {
String bn = t.getBaseName();
bn = makeID(bn);
return bn;
}
return ""+t.getID();
}
protected String makeID(String s) {
if(s != null && s.length() > 0) {
StringBuilder sb = new StringBuilder("");
for(int i=0; i<s.length(); i++) {
if(Character.isJavaIdentifierPart(s.charAt(i))) {
sb.append(s.charAt(i));
}
else {
sb.append('_');
}
}
return sb.toString();
}
return s;
}
protected String makeString(String s) {
if(s == null) return null;
//s = s.substring(0,Math.min(s.length(), 240));
s = s.replaceAll("<", "<");
s = s.replaceAll(">", ">");
s = s.replaceAll("\\&", "&");
s = s.replaceAll("\"", "'");
return s;
}
protected String makeString(Topic t) throws TopicMapException {
if(t == null) return null;
String s = t.getBaseName();
if(s == null) s = t.getOneSubjectIdentifier().toExternalForm();
return makeString(s);
}
// -------------------------------------------------------------------------
// Elementary print methods are used to ensure output is UTF-8
protected void print(PrintWriter writer, String str) {
writer.print(str);
}
protected void println(PrintWriter writer, String str) {
writer.println(str);
}
}
| 15,170 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
XTMRoundTrip.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/exporters/XTMRoundTrip.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*/
package org.wandora.application.tools.exporters;
import java.io.File;
import java.io.FileInputStream;
import javax.swing.Icon;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.WandoraToolType;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.UIBox;
import org.wandora.application.gui.UIConstants;
import org.wandora.application.gui.simple.SimpleFileChooser;
import org.wandora.application.tools.AbstractWandoraTool;
import org.wandora.topicmap.TopicMap;
import org.wandora.utils.IObox;
/**
*
* @author akivela
*/
public class XTMRoundTrip extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
@Override
public String getName() {
return "XTM round trip";
}
@Override
public String getDescription() {
return "Imports XTM topic map file, and exports topic map back to XTM file. "+
"Exported XTM files are saved to 'wandora_round_trip' folder with same file name leaving original files untouched.";
}
@Override
public WandoraToolType getType(){
return WandoraToolType.createImportExportType();
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/import_export_xtm.png");
}
@Override
public boolean requiresRefresh() {
return false;
}
@Override
public void execute(Wandora wandora, Context context) {
try {
SimpleFileChooser chooser=UIConstants.getFileChooser();
chooser.setMultiSelectionEnabled(true);
chooser.setDialogTitle("Select XTM files to round trip");
if(chooser.open(wandora)==SimpleFileChooser.APPROVE_OPTION) {
setDefaultLogger();
importExport(chooser.getSelectedFiles());
}
}
catch(Exception e) {
log(e);
}
setState(WAIT);
}
private void importExport(File[] importFiles) {
if(importFiles != null && importFiles.length > 0) {
long starttime = System.currentTimeMillis();
for(int i=0; i<importFiles.length && !forceStop(); i++) {
try {
TopicMap map = new org.wandora.topicmap.memory.TopicMapImpl();
File importFile = importFiles[i];
setLogTitle("Importing '"+importFile.getName()+"'");
log("Importing '"+importFile.getName()+"'");
map.importXTM(new FileInputStream(importFile), getCurrentLogger());
String exportPath = importFile.getParent()+File.separator+"wandora_round_trip";
IObox.createPathFor(new File(exportPath));
String exportFileName = exportPath+File.separator+importFile.getName();
File exportFile = new File(exportFileName);
log("Exporting '"+exportFile.getName()+"'");
setLogTitle("Exporting '"+exportFile.getName()+"'");
map.exportXTM(exportFileName, this);
}
catch(Exception e) {
e.printStackTrace();
}
}
long endtime = System.currentTimeMillis();
long duration = (Math.round(((endtime-starttime)/1000)));
if(duration > 1) {
log("Round tripping XTM files took "+duration+" seconds.");
}
log("Ready.");
}
else {
log("No XTM files to import!");
}
}
}
| 4,490 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
IncidenceMatrixExport.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/exporters/IncidenceMatrixExport.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* IncidenceMatrixExport.java
*
*/
package org.wandora.application.tools.exporters;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.swing.Icon;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.WandoraToolLogger;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.UIBox;
import org.wandora.application.gui.UIConstants;
import org.wandora.application.gui.simple.SimpleFileChooser;
import org.wandora.application.tools.GenericOptionsDialog;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.TMBox;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.utils.IObox;
/**
*
* @author akivela
*/
public class IncidenceMatrixExport extends AbstractExportTool implements WandoraTool {
private static final long serialVersionUID = 1L;
public static boolean LABEL_MATRIX = true;
public static boolean EXPORT_AS_HTML_TABLE = true;
public static boolean SORT = true;
public boolean EXPORT_SELECTION_INSTEAD_TOPIC_MAP = false;
public IncidenceMatrixExport() {
}
public IncidenceMatrixExport(boolean exportSelection) {
EXPORT_SELECTION_INSTEAD_TOPIC_MAP = exportSelection;
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/export_incidence_matrix.png");
}
@Override
public boolean requiresRefresh() {
return false;
}
@Override
public boolean isConfigurable(){
return true;
}
@Override
public void configure(Wandora wandora,org.wandora.utils.Options options,String prefix) throws TopicMapException {
GenericOptionsDialog god=new GenericOptionsDialog(wandora,"Incidence matrix export options","Incidence matrix export options",true,new String[][]{
new String[]{"Label matrix columns and rows","boolean",(LABEL_MATRIX ? "true" : "false"), "Should Wandora label matrix columns and rows using topic names?"},
new String[]{"Export as HTML table","boolean",(EXPORT_AS_HTML_TABLE ? "true" : "false"), "Export HTML table instead of tab text?"},
},wandora);
god.setVisible(true);
if(god.wasCancelled()) return;
Map<String, String> values = god.getValues();
LABEL_MATRIX = ("true".equals(values.get("Label matrix columns and rows")) ? true : false );
EXPORT_AS_HTML_TABLE = ("true".equals(values.get("Export as HTML table")) ? true : false );
}
@Override
public void execute(Wandora wandora, Context context) {
Iterator<Topic> topics = null;
Iterator<Association> associations = null;
String exportInfo = "";
try {
if(EXPORT_SELECTION_INSTEAD_TOPIC_MAP) {
topics = context.getContextObjects();
HashSet<Association> as = new HashSet<Association>();
while(topics.hasNext()) {
Topic t = topics.next();
as.addAll( t.getAssociations() );
}
associations = as.iterator();
exportInfo = "selected topics";
}
else {
// --- Solve first topic map to be exported
TopicMap tm = solveContextTopicMap(wandora, context);
String topicMapName = this.solveNameForTopicMap(wandora, tm);
topics = tm.getTopics();
associations = tm.getAssociations();
if(topicMapName == null) exportInfo = "LayerStack";
if(topicMapName != null) exportInfo = "topic map in layer '" + topicMapName + "'";
}
// --- Then solve target file (and format)
SimpleFileChooser chooser=UIConstants.getFileChooser();
chooser.setDialogTitle("Export "+exportInfo+" as incidence matrix...");
if(chooser.open(wandora, "Export")==SimpleFileChooser.APPROVE_OPTION){
setDefaultLogger();
File file = chooser.getSelectedFile();
String fileName = file.getName();
// --- Finally write topic map to chosen file
OutputStream out=null;
try {
if(EXPORT_AS_HTML_TABLE)
file=IObox.addFileExtension(file, "html");
else
file=IObox.addFileExtension(file, "txt");
fileName = file.getName(); // Updating filename if file has changed!
out=new FileOutputStream(file);
log("Exporting topics as incidence matrix to '"+fileName+"'.");
exportMatrix(out, associations, topics, getCurrentLogger());
out.close();
log("OK");
}
catch(Exception e) {
log(e);
try { if(out != null) out.close(); }
catch(Exception e2) { log(e2); }
}
}
}
catch(Exception e) {
log(e);
}
setState(WAIT);
}
@Override
public String getName() {
return "Export incidence matrix";
}
@Override
public String getDescription() {
return "Exports topic map as incidence matrix.";
}
public void exportMatrix(OutputStream out, Iterator<Association> associationIterator, Iterator<Topic> topicIterator, WandoraToolLogger logger) throws TopicMapException {
if(logger == null) logger = this;
PrintWriter writer = null;
try {
writer = new PrintWriter(new OutputStreamWriter(out, "ISO-8859-1"));
}
catch (UnsupportedEncodingException ex) {
log("Exception while instantiating PrintWriter with character encoding ISO-8859-1. Using default encoding.");
writer = new PrintWriter(new OutputStreamWriter(out));
}
int totalCount = 0;
List<Topic> topics = new ArrayList<Topic>();
List<Association> associations = new ArrayList<Association>();
Topic t = null;
Association a = null;
log("Collecting associations...");
while(associationIterator.hasNext() && !logger.forceStop()) {
a = associationIterator.next();
if(a != null && !a.isRemoved()) {
associations.add(a);
totalCount++;
}
}
log("Collecting topics...");
while(topicIterator.hasNext() && !logger.forceStop()) {
t = topicIterator.next();
if(t != null && !t.isRemoved()) {
topics.add(t);
totalCount++;
}
}
if(SORT) {
log("Sorting topics...");
Collections.sort(topics, new TMBox.TopicNameComparator(null));
log("Sorting associations...");
Collections.sort(associations, new TMBox.AssociationTypeComparator((String) null));
}
logger.setProgressMax(totalCount);
// And finally export....
log("Exporting incidence matrix...");
if(EXPORT_AS_HTML_TABLE) {
exportMatrixAsHTMLTable(writer, associations, topics, logger);
}
else {
exportMatrixAsTabText(writer, associations, topics, logger);
}
writer.flush();
writer.close();
}
public void exportMatrixAsTabText(PrintWriter writer, List<Association> associations, List<Topic> topics, WandoraToolLogger logger) throws TopicMapException {
int progress = 0;
Association a = null;
Topic t = null;
int connections = 0;
for(int i=0; i<topics.size() && !logger.forceStop(); i++) {
t=topics.get(i);
if(LABEL_MATRIX) {
print(writer, makeString(t)+"\t");
}
for(int j=0; j<associations.size() && !logger.forceStop(); j++) {
a=associations.get(j);
connections = hasConnections(a, t);
print(writer, connections+"\t");
setProgress(progress++);
}
print(writer, "\n");
}
}
public void exportMatrixAsHTMLTable(PrintWriter writer, List<Association> associations, List<Topic> topics, WandoraToolLogger logger) throws TopicMapException {
int progress = 0;
Association a = null;
Topic t = null;
int connections = 0;
print(writer, "<table border=1>");
for(int i=0; i<topics.size() && !logger.forceStop(); i++) {
print(writer, "<tr>");
t=topics.get(i);
if(LABEL_MATRIX) {
print(writer, "<td>"+makeString(t)+"</td>");
}
for(int j=0; j<associations.size() && !logger.forceStop(); j++) {
a=associations.get(j);
connections = hasConnections(a, t);
print(writer, "<td>"+connections+"</td>");
setProgress(progress++);
}
print(writer, "</tr>\n");
}
print(writer, "</table>");
}
// -------------------------------------------------------------------------
public int hasConnections(Association a, Topic t) {
int count = 0;
try {
Collection<Topic> roles = a.getRoles();
Topic role = null;
Topic player = null;
for(Iterator<Topic> roleIterator = roles.iterator(); roleIterator.hasNext(); ) {
role = roleIterator.next();
player = a.getPlayer(role);
if(player != null) {
if(player.mergesWithTopic(t)) {
count++;
}
}
}
}
catch(Exception e) {
log(e);
}
return count;
}
protected String makeString(Topic t) throws TopicMapException {
if(t == null) return null;
String s = t.getBaseName();
if(s == null) s = t.getOneSubjectIdentifier().toExternalForm();
return s;
}
// -------------------------------------------------------------------------
// Elementary print methods are used to ensure output is ISO-8859-1
protected void print(PrintWriter writer, String str) {
writer.print(str);
}
protected void println(PrintWriter writer, String str) {
writer.println(str);
}
} | 11,677 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TopicMapRoundTrip.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/exporters/TopicMapRoundTrip.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*/
package org.wandora.application.tools.exporters;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.Icon;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.WandoraToolType;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.UIBox;
import org.wandora.application.gui.UIConstants;
import org.wandora.application.gui.simple.SimpleFileChooser;
import org.wandora.application.tools.AbstractWandoraTool;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.utils.IObox;
/**
*
* @author akivela
*/
public class TopicMapRoundTrip extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
@Override
public String getName() {
return "Topic map round trip";
}
@Override
public String getDescription() {
return "Imports topic map file, and exports topic map back to another file. "+
"Exported files are saved to 'wandora_round_trip' folder with same file name leaving original files untouched.";
}
@Override
public WandoraToolType getType(){
return WandoraToolType.createImportExportType();
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/import_export.png");
}
@Override
public boolean requiresRefresh() {
return false;
}
@Override
public void execute(Wandora wandora, Context context) {
try {
SimpleFileChooser chooser=UIConstants.getFileChooser();
chooser.setMultiSelectionEnabled(true);
chooser.setDialogTitle("Select topic map files to round trip");
if(chooser.open(wandora)==SimpleFileChooser.APPROVE_OPTION) {
setDefaultLogger();
importExport(chooser.getSelectedFiles());
}
}
catch(Exception e) {
log(e);
}
setState(WAIT);
}
private void importExport(File[] importFiles) {
if(importFiles != null && importFiles.length > 0) {
long starttime = System.currentTimeMillis();
for(int i=0; i<importFiles.length && !forceStop(); i++) {
try {
TopicMap map = new org.wandora.topicmap.memory.TopicMapImpl();
File importFile = importFiles[i];
importTopicMap(importFile, map);
String exportPath = importFile.getParent()+File.separator+"wandora_round_trip";
IObox.createPathFor(new File(exportPath));
String exportFileName = exportPath+File.separator+importFile.getName();
File exportFile = new File(exportFileName);
exportTopicMap(exportFile, map);
}
catch(FileNotFoundException fnfe) {
log("Topic map file not found.");
log(fnfe);
fnfe.printStackTrace();
}
catch(IOException ioe) {
log("Exception occurred while accessing file.");
log(ioe);
ioe.printStackTrace();
}
catch(TopicMapException tme) {
log("Topic map error.");
log(tme);
tme.printStackTrace();
}
catch(Exception e) {
e.printStackTrace();
}
}
long endtime = System.currentTimeMillis();
long duration = (Math.round(((endtime-starttime)/1000)));
if(duration > 1) {
log("Round tripping topic map files took "+duration+" seconds.");
}
log("Ready.");
}
else {
log("No topic map files to import!");
}
}
private void importTopicMap(File file, TopicMap map) throws IOException, FileNotFoundException, TopicMapException {
String filename = file.getName();
setLogTitle("Importing '"+filename+"'");
log("Importing '"+filename+"'");
String lowercaseFilename = filename.toLowerCase();
if(lowercaseFilename.endsWith(".xtm")
|| lowercaseFilename.endsWith(".xtm1")
|| lowercaseFilename.endsWith(".xtm2")) {
map.importXTM(new FileInputStream(file), getCurrentLogger());
}
else if(lowercaseFilename.endsWith(".ltm")) {
map.importLTM(new FileInputStream(file), getCurrentLogger());
}
else if(lowercaseFilename.endsWith(".jtm")) {
map.importJTM(new FileInputStream(file), getCurrentLogger());
}
else {
throw new TopicMapException("Topic map file format not recognized exception.");
}
}
private void exportTopicMap(File file, TopicMap map) throws IOException, FileNotFoundException, TopicMapException {
String filename = file.getName();
log("Exporting '"+filename+"'");
setLogTitle("Exporting '"+filename+"'");
String lowercaseFilename = filename.toLowerCase();
if(lowercaseFilename.endsWith(".xtm") || lowercaseFilename.endsWith(".xtm2")) {
map.exportXTM20(new FileOutputStream(file), getCurrentLogger());
}
else if(lowercaseFilename.endsWith(".xtm1")) {
map.exportXTM10(new FileOutputStream(file), getCurrentLogger());
}
else if(lowercaseFilename.endsWith(".ltm")) {
map.exportLTM(new FileOutputStream(file), getCurrentLogger());
}
else if(lowercaseFilename.endsWith(".jtm")) {
map.exportJTM(new FileOutputStream(file), getCurrentLogger());
}
else {
throw new TopicMapException("Topic map file format not recognized exception.");
}
}
}
| 6,959 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
RDFExport.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/exporters/RDFExport.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* RDFExport.java
*
* Created on 4.7.2006, 13:16
*
*/
package org.wandora.application.tools.exporters;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Collections;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Vector;
import javax.swing.Icon;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraToolLogger;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.UIBox;
import org.wandora.application.gui.UIConstants;
import org.wandora.application.gui.simple.SimpleFileChooser;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.utils.XMLbox;
/**
*
* @author olli
*/
public class RDFExport extends AbstractExportTool {
private static final long serialVersionUID = 1L;
public boolean EXPORT_SELECTION_INSTEAD_TOPIC_MAP = false;
public RDFExport() {
}
public RDFExport(boolean exportSelection) {
EXPORT_SELECTION_INSTEAD_TOPIC_MAP = exportSelection;
}
@Override
public String getName() {
return "RDF Export";
}
@Override
public String getDescription() {
return "Exports topic map in RDF N3 format. Association roles nor topic names are not exported as RDF has no similar structures.";
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/export_rdf.png");
}
@Override
public boolean requiresRefresh() {
return false;
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
SimpleFileChooser chooser=UIConstants.getFileChooser();
chooser.setDialogTitle("RDF N3 Export");
if(chooser.open(wandora, "Export")==SimpleFileChooser.APPROVE_OPTION){
setDefaultLogger();
File file = chooser.getSelectedFile();
TopicMap tm = null;
// --- Solve first topic map to be exported
if(EXPORT_SELECTION_INSTEAD_TOPIC_MAP) {
tm = makeTopicMapWith(context);
}
else {
tm = solveContextTopicMap(wandora, context);
}
try {
OutputStream out = new FileOutputStream(file);
exportRDF(out, tm, this);
out.flush();
out.close();
log("Ready.");
setState(WAIT);
}
catch(Exception e){
e.printStackTrace();
}
}
}
public void exportRDF(OutputStream out, TopicMap tm, WandoraToolLogger logger) throws TopicMapException, IOException {
if(logger == null) logger = this;
PrintStream writer = new PrintStream(out);
exportHeader(writer);
logger.log("Exporting topics.");
Iterator<Topic> topics=tm.getTopics();
while(topics.hasNext()){
Topic t=topics.next();
exportTopic(writer,t);
}
logger.log("Exporting associations.");
Iterator<Association> associations=tm.getAssociations();
while(associations.hasNext()){
Association a=associations.next();
exportAssociation(writer,a,null);
}
exportFooter(writer);
writer.flush();
writer.close();
}
public static String attribute(String s){
return XMLbox.cleanForAttribute(s);
}
public static String clean(String s){
// return XMLbox.cleanForXML(s);
return s.replace("\"","\\\"");
}
public static Locator getTopicLocator(Topic t) throws TopicMapException {
Locator si=t.getSubjectLocator();
if(si==null) si=t.getOneSubjectIdentifier();
return si;
}
public static void exportHeader(PrintStream out) throws IOException {
/* out.println("<?xml version=\"1.0\"?>");
out.println("<rdf:RDF ");
out.println(" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"");
out.println(" xmlns:rdfs=\"http://www.w3.org/2000/02/rdf-schema#\">");*/
out.println("@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .");
out.println("@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .");
}
public static void exportFooter(PrintStream out) throws IOException {
// out.println("</rdf:RDF>");
}
public static void exportTopic(PrintStream out,Topic t) throws IOException,TopicMapException {
Locator si=getTopicLocator(t);
String id=t.getID();
// out.println(" <rdf:Description rdf:about=\""+attribute(si.toExternalForm())+"\">");
if(t.getBaseName()!=null)
// out.println(" <rdfs:label>"+clean(t.getBaseName())+"</rdfs:label>");
out.println("<"+si.toExternalForm()+"> rdfs:label \""+clean(t.getBaseName())+"\" .");
for(Topic type : t.getTypes()){
// out.println(" <rdf:type rdf:resource=\""+getTopicLocator(type).toExternalForm()+"\"/>");
out.println("<"+si.toExternalForm()+"> rdf:type <"+getTopicLocator(type).toExternalForm()+"> .");
}
for(Topic dataType : t.getDataTypes()){
Hashtable<Topic,String> data=t.getData(dataType);
for(Map.Entry<Topic,String> e : data.entrySet()){
String value=e.getValue();
if(value!=null && value.length()>0){
/* out.println(" <rdf:Statement> ");
out.println(" <rdf:subject rdf:resource=\""+attribute(si.toExternalForm())+"\"/>");
out.println(" <rdf:predicate rdf:resource=\""+attribute(getTopicLocator(dataType).toExternalForm())+"\"/>");
out.println(" <rdf:object>"+clean(value)+"</rdf:object>");
out.println(" </rdf:Statement>");*/
out.println("<"+si.toExternalForm()+"> <"+getTopicLocator(dataType).toExternalForm()+"> \""+clean(value)+"\" .");
break;
}
}
}
// out.println(" </rdf:Description>");
}
public static int associationCounter=0;
public static void exportAssociation(PrintStream out,Association a,Topic subjectRole) throws IOException,TopicMapException{
if(a.getRoles().size()==2){
if(subjectRole==null){
Vector<Topic> v=new Vector<Topic>();
v.addAll(a.getRoles());
Collections.sort(v,new Comparator<Topic>(){
@Override
public int compare(Topic a,Topic b){
try {
String ab=a.getBaseName();
String bb=b.getBaseName();
if(ab==null) ab="";
if(bb==null) bb="";
return ab.compareTo(bb);
}
catch(TopicMapException tme){
return 0;
}
}
});
subjectRole=v.firstElement();
}
Topic subject=a.getPlayer(subjectRole);
Topic predicate=a.getType();
Topic object=null;
for(Topic t : a.getRoles()){
if(t!=subjectRole){
object=a.getPlayer(t);
break;
}
}
/* out.println(" <rdf:Statement> ");
out.println(" <rdf:subject rdf:resource=\""+attribute(getTopicLocator(subject).toExternalForm())+"\"/>");
out.println(" <rdf:predicate rdf:resource=\""+attribute(getTopicLocator(predicate).toExternalForm())+"\"/>");
out.println(" <rdf:object rdf:resource=\""+attribute(getTopicLocator(object).toExternalForm())+"\"/>");
out.println(" </rdf:Statement>");*/
out.println("<"+getTopicLocator(subject).toExternalForm()+"> <"+
getTopicLocator(predicate).toExternalForm()+"> <"+
getTopicLocator(object).toExternalForm()+"> .");
}
else{
String about="http://wandora.org/si/rdfexport/association/"+(associationCounter++);
for(Topic t : a.getRoles()){
/* out.println(" <rdf:Statement> ");
out.println(" <rdf:subject rdf:resource=\""+attribute(about)+"\"/>");
out.println(" <rdf:predicate rdf:resource=\""+attribute(getTopicLocator(t).toExternalForm())+"\"/>");
out.println(" <rdf:object rdf:resource=\""+attribute(getTopicLocator(a.getPlayer(t)).toExternalForm())+"\"/>");
out.println(" </rdf:Statement>");*/
out.println("<"+about+"> <"+
getTopicLocator(t).toExternalForm()+"> <"+
getTopicLocator(a.getPlayer(t)).toExternalForm()+"> .");
}
}
}
}
| 10,272 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
OccurrenceSummaryReport.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/exporters/OccurrenceSummaryReport.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.application.tools.exporters;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import javax.swing.Icon;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraToolLogger;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.UIBox;
import org.wandora.application.gui.UIConstants;
import org.wandora.application.gui.simple.SimpleFileChooser;
import org.wandora.application.gui.topicstringify.TopicToString;
import org.wandora.topicmap.TMBox;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.utils.IObox;
/**
*
* @author akivela
*/
public class OccurrenceSummaryReport extends AbstractExportTool {
private static final long serialVersionUID = 1L;
public boolean EXPORT_SELECTION_INSTEAD_TOPIC_MAP = false;
public static final String TAB_FORMAT = "Tabulator separated plain text";
public static final String HTML_FORMAT = "HTML table";
private String outputFormat = TAB_FORMAT;
/** Creates a new instance of OccurrenceSummaryReport */
public OccurrenceSummaryReport() {
}
public OccurrenceSummaryReport(boolean exportSelection) {
EXPORT_SELECTION_INSTEAD_TOPIC_MAP = exportSelection;
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/summary_report.png");
}
@Override
public String getName() {
return "Occurrence summary report";
}
@Override
public String getDescription() {
return "Occurrence summary report.";
}
@Override
public boolean requiresRefresh() {
return false;
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
String topicMapName = null;
String exportInfo = null;
// --- Solve first topic map to be exported
TopicMap tm = null;
if(EXPORT_SELECTION_INSTEAD_TOPIC_MAP) {
tm = makeTopicMapWith(context);
exportInfo = "Exporting occurrence summary of selected topics";
}
else {
tm = solveContextTopicMap(wandora, context);
topicMapName = this.solveNameForTopicMap(wandora, tm);
if(topicMapName != null) {
exportInfo = "Exporting occurrence summary of layer '" + topicMapName + "'";
}
else {
exportInfo = "Exporting occurrence summary";
}
}
if(tm == null) return;
Iterator<Topic> topics = tm.getTopics();
SimpleFileChooser chooser=UIConstants.getFileChooser();
chooser.setDialogTitle(exportInfo+"...");
if(chooser.open(wandora, "Export")==SimpleFileChooser.APPROVE_OPTION) {
setDefaultLogger();
File file = chooser.getSelectedFile();
String fileName = file.getName();
// --- Finally write topic map to chosen file
OutputStream out=null;
try {
if(HTML_FORMAT.equals(outputFormat))
file=IObox.addFileExtension(file, "html");
else
file=IObox.addFileExtension(file, "txt");
fileName = file.getName(); // Updating filename if file has changed!
out = new FileOutputStream(file);
log("Exporting occurrence summary report to '"+fileName+"'.");
exportReport(out, topics, tm, getCurrentLogger());
out.close();
log("OK");
}
catch(Exception e) {
log(e);
try { if(out != null) out.close(); }
catch(Exception e2) { log(e2); }
}
setState(WAIT);
}
}
public void exportReport(OutputStream out, Iterator<Topic> topicIterator, TopicMap tm, WandoraToolLogger logger) throws TopicMapException {
if(logger == null) logger = this;
PrintWriter writer = null;
try {
writer = new PrintWriter(new OutputStreamWriter(out));
}
catch (Exception ex) {
log("Exception while instantiating default PrintWriter. Aborting.");
return;
}
int totalCount = 0;
List<Topic> topics = new ArrayList<Topic>();
Topic t = null;
log("Collecting topics...");
while(topicIterator.hasNext() && !logger.forceStop()) {
t = topicIterator.next();
if(t != null && !t.isRemoved()) {
topics.add(t);
totalCount++;
}
}
Collections.sort(topics, new TMBox.TopicNameComparator(null));
logger.setProgressMax(totalCount);
// And finally export....
log("Exporting report...");
exportReportAsTabText(writer, topics, tm, logger);
writer.flush();
writer.close();
}
public void exportReportAsTabText(PrintWriter writer, List<Topic> topics, TopicMap tm, WandoraToolLogger logger) throws TopicMapException {
List<Topic> occurrenceTypes = getOccurrenceTypes(tm);
int occurrenceTypeCount = occurrenceTypes.size();
for(Topic occurrenceType : occurrenceTypes) {
writer.print("\t");
writer.print(TopicToString.toString(occurrenceType));
}
writer.println();
for(Topic t : topics) {
writer.print(TopicToString.toString(t));
for(int i=0; i<occurrenceTypeCount; i++) {
writer.print("\t");
Topic otype = occurrenceTypes.get(i);
Hashtable<Topic,String> occurrence = t.getData(otype);
if(occurrence != null && occurrence.size() > 0) {
boolean isFirst = true;
for(Topic scope : occurrence.keySet()) {
String occurrenceStr = occurrence.get(scope);
occurrenceStr = occurrenceStr.replace('\t', ' ');
occurrenceStr = occurrenceStr.replace('\n', ' ');
occurrenceStr = occurrenceStr.replace('\r', ' ');
writer.print(occurrenceStr);
if(!isFirst) writer.print("||||");
isFirst = false;
}
}
}
writer.println();
if(forceStop()) break;
}
if(forceStop()) {
log("Operation cancelled!");
}
}
private List<Topic> getOccurrenceTypes(TopicMap tm) throws TopicMapException {
Set<Topic> occurrenceTypes = new LinkedHashSet<>();
if(tm != null) {
Topic t = null;
Iterator<Topic> topics = tm.getTopics();
while(topics.hasNext() && !forceStop()) {
t = topics.next();
if(t != null && !t.isRemoved()) {
occurrenceTypes.addAll(t.getDataTypes());
}
}
}
List<Topic> ot = new ArrayList<>();
ot.addAll(occurrenceTypes);
return ot;
}
} | 8,440 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
OBORoundTrip.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/exporters/OBORoundTrip.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*/
package org.wandora.application.tools.exporters;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import javax.swing.Icon;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.WandoraToolType;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.UIBox;
import org.wandora.application.gui.UIConstants;
import org.wandora.application.gui.simple.SimpleFileChooser;
import org.wandora.application.tools.AbstractWandoraTool;
import org.wandora.application.tools.importers.OBO;
import org.wandora.application.tools.importers.OBOConfiguration;
import org.wandora.application.tools.importers.OBOImport;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.utils.IObox;
/**
*
* @author akivela
*/
public class OBORoundTrip extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
@Override
public String getName() {
return "OBO round trip";
}
@Override
public String getDescription() {
return "Imports OBO file, converts it to a topic map, and exports topic map back to OBO file. "+
"Separate topic maps are used for round trip. Wandora's topic map is not modified. "+
"Exported OBO files are saved to 'wandora_round_trip' folder with same file name leaving original files untouched.";
}
@Override
public WandoraToolType getType(){
return WandoraToolType.createExportType();
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/import_export_obo.png");
}
// **** Configuration ****
@Override
public void initialize(Wandora wandora,org.wandora.utils.Options options,String prefix) throws TopicMapException {
String o=options.get(OBO.optionPrefix+"options");
if(o!=null){
int i=Integer.parseInt(o);
OBO.setOptions(i);
System.out.println("oboroundtrip init:"+i);
}
}
@Override
public boolean isConfigurable(){
return true;
}
@Override
public void configure(Wandora wandora,org.wandora.utils.Options options,String prefix) throws TopicMapException {
//System.out.println(prefix);
OBOConfiguration dialog=new OBOConfiguration(wandora,true);
dialog.setOptions(OBO.getOptions());
dialog.setVisible(true);
if(!dialog.wasCancelled()){
int i=dialog.getOptions();
OBO.setOptions(i);
options.put(OBO.optionPrefix+"options",""+i);
//System.out.println("oboroundtrip configure:"+i);
}
}
@Override
public void writeOptions(Wandora wandora,org.wandora.utils.Options options,String prefix){
options.put(OBO.optionPrefix+"options",""+OBO.getOptions());
}
public void execute(Wandora wandora, Context context) {
try {
SimpleFileChooser chooser=UIConstants.getFileChooser();
chooser.setMultiSelectionEnabled(true);
chooser.setDialogTitle("Select OBO files to round trip");
if(chooser.open(wandora)==SimpleFileChooser.APPROVE_OPTION) {
setDefaultLogger();
importExport(chooser.getSelectedFiles());
}
}
catch(Exception e) {
log(e);
}
setState(WAIT);
}
private void importExport(File[] importFiles) {
if(importFiles != null && importFiles.length > 0) {
long starttime = System.currentTimeMillis();
for(int i=0; i<importFiles.length && !forceStop(); i++) {
try {
TopicMap map = new org.wandora.topicmap.memory.TopicMapImpl();
File importFile = importFiles[i];
setLogTitle("Importing '"+importFile.getName()+"'");
log("Importing '"+importFile.getName()+"'");
OBOImport importer = new OBOImport();
importer.setToolLogger(this.getCurrentLogger());
importer.importOBO(new FileInputStream(importFile), map);
OBOExport exporter = new OBOExport();
exporter.setToolLogger(this.getCurrentLogger());
String exportPath = importFile.getParent()+File.separator+"wandora_round_trip";
IObox.createPathFor(new File(exportPath));
String exportFileName = exportPath+File.separator+importFile.getName();
File exportFile = new File(exportFileName);
ArrayList<String> namespaces = importer.getNamespaces();
if(namespaces != null && namespaces.size() >0) {
log("Exporting '"+exportFile.getName()+"'");
setLogTitle("Exporting '"+exportFile.getName()+"'");
exporter.exportOBO(exportFile, namespaces.toArray( new String[] {} ), map);
}
else {
log("No valid namespaces found in imported OBO file. Export failed.");
}
}
catch(Exception e) {
e.printStackTrace();
}
}
long endtime = System.currentTimeMillis();
long duration = (Math.round(((endtime-starttime)/1000)));
if(duration > 1) {
log("Round tripping OBO files took "+duration+" seconds.");
}
log("Ready.");
}
else {
System.out.println("No OBO files to import!");
}
}
}
| 6,675 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
GephiExport.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/exporters/GephiExport.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*/
package org.wandora.application.tools.exporters;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.swing.Icon;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.WandoraToolLogger;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.UIBox;
import org.wandora.application.gui.UIConstants;
import org.wandora.application.gui.simple.SimpleFileChooser;
import org.wandora.application.tools.GenericOptionsDialog;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.utils.IObox;
/**
*
* @author akivela
*/
public class GephiExport extends AbstractExportTool implements WandoraTool {
private static final long serialVersionUID = 1L;
public boolean EXPORT_SELECTION_INSTEAD_TOPIC_MAP = false;
public boolean EXPORT_CLASSES = true;
public boolean EXPORT_OCCURRENCES = true;
public boolean EXPORT_ALL_ASSOCIATIONS = true;
private List<AttributeColumn> nodeAttributes;
private List<AttributeColumn> edgeAttributes;
private int edgeCounter = 0;
private int nodeCounter = 0;
private Map<String, DataNode> dataNodes;
private List<DataEdge> dataEdges;
public GephiExport() {
}
public GephiExport(boolean exportSelection) {
EXPORT_SELECTION_INSTEAD_TOPIC_MAP = exportSelection;
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/export_graph.png");
}
@Override
public boolean requiresRefresh() {
return false;
}
@Override
public boolean isConfigurable(){
return true;
}
@Override
public void configure(Wandora wandora,org.wandora.utils.Options options,String prefix) throws TopicMapException {
GenericOptionsDialog genOptDiag=new GenericOptionsDialog(wandora,"Gephi","Gephi Export options",true,new String[][]{
new String[]{"Export classes","boolean",(EXPORT_CLASSES ? "true" : "false"),"Should Wandora export also topic types (class-instance relations)?"},
new String[]{"Export occurrences","boolean",(EXPORT_OCCURRENCES ? "true" : "false"),"Should topic occurrences also export?"},
new String[]{"Export all associations","boolean",(EXPORT_ALL_ASSOCIATIONS ? "true" : "false"),"Should associations with multiple roles be exported?"},
},wandora);
genOptDiag.setVisible(true);
if(genOptDiag.wasCancelled()) return;
Map<String, String> values = genOptDiag.getValues();
EXPORT_OCCURRENCES = ("true".equals(values.get("Export occurrences")) ? true : false );
EXPORT_CLASSES = ("true".equals(values.get("Export classes")) ? true : false );
EXPORT_ALL_ASSOCIATIONS = ("true".equals(values.get("Export all associations")) ? true : false );
}
static final int BUFFER = 2048;
@Override
public void execute(Wandora wandora, Context context) {
String topicMapName = null;
String exportInfo = null;
nodeAttributes = new ArrayList<AttributeColumn>();
edgeAttributes = new ArrayList<AttributeColumn>();
edgeCounter = 0;
nodeCounter = 0;
dataNodes = new LinkedHashMap<String, DataNode>();
dataEdges = new ArrayList<DataEdge>();
// --- Solve first topic map to be exported
TopicMap tm = null;
if(EXPORT_SELECTION_INSTEAD_TOPIC_MAP) {
tm = makeTopicMapWith(context);
exportInfo = "Exporting selected topics as Gephi graph";
topicMapName = "selection_in_wandora";
}
else {
tm = solveContextTopicMap(wandora, context);
topicMapName = this.solveNameForTopicMap(wandora, tm);
if(topicMapName != null) {
exportInfo = "Exporting topic map in layer '" + topicMapName + "' as Gephi graph";
}
else {
exportInfo = "Exporting topic map as Gephi graph";
topicMapName = "no_name_topic_map";
}
}
// --- Then solve target file
SimpleFileChooser chooser=UIConstants.getFileChooser();
chooser.setDialogTitle(exportInfo+"...");
File file;
if(chooser.open(wandora, "Export")==SimpleFileChooser.APPROVE_OPTION){
setDefaultLogger();
file = chooser.getSelectedFile();
String fileName = file.getName();
// --- Finally write topicmap as Gephi to chosen file
OutputStream out=null;
File fileXML = null;
try {
file=IObox.addFileExtension(file, "gephi"); // Ensure file extension exists!
fileXML = File.createTempFile(file.getName(), "gephi");
fileName = file.getName(); // Updating filename if file has changed!
out=new FileOutputStream(fileXML);
log(exportInfo+" to '"+fileName+"'.");
exportGephi(out, tm, topicMapName, getCurrentLogger());
out.flush();
out.close();
}
catch(Exception e) {
log(e);
try { if(out != null) out.close(); }
catch(Exception e2) { log(e2); }
}
// Lets read and archive the file we just created
try {
FileInputStream fi = new FileInputStream(fileXML);
BufferedInputStream origin = new BufferedInputStream(fi, BUFFER);
FileOutputStream dest = new FileOutputStream(file);
ZipOutputStream zout = new ZipOutputStream(new BufferedOutputStream(dest));
byte data[] = new byte[BUFFER];
zout.putNextEntry(new ZipEntry(file.getName()));
int count;
while((count = origin.read(data, 0, BUFFER)) != -1) {
zout.write(data, 0, count);
}
zout.flush();
zout.close();
}
catch(Exception e) {
Logger.getLogger(GephiExport.class.getName()).log(Level.SEVERE, null, e);
}
log("Ready.");
}
setState(WAIT);
nodeAttributes = null;
edgeAttributes = null;
edgeCounter = 0;
nodeCounter = 0;
dataNodes = null;
dataEdges = null;
}
@Override
public String getName() {
return "Export Gephi graph";
}
@Override
public String getDescription() {
return "Exports topic map layer as Gephi file.";
}
WandoraToolLogger logger;
public void exportGephi(OutputStream out, TopicMap topicMap, String graphName, WandoraToolLogger logger) throws TopicMapException {
if(logger == null) logger = this;
PrintWriter writer = null;
try {
writer = new PrintWriter(new OutputStreamWriter(out, "UTF-8"));
}
catch (UnsupportedEncodingException ex) {
log("Exception while instantiating PrintWriter with UTF-8 character encoding. Using default encoding.");
writer = new PrintWriter(new OutputStreamWriter(out));
}
//int totalCount = 2*topicMap.getNumTopics() + topicMap.getNumAssociations();
logger.setProgressMax(100); // For now I have to "fake" the real progress count
int count = 0;
println(writer, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
println(writer, "<gephiFile version=\"0.7\">"); // Should this be versionless?
println(writer, "<core tasks=\"0\">");
Date date = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
df.format(date);
println(writer, "<lastModifiedDate>"+df.format(date)+"</lastModifiedDate>");
println(writer, "</core>");
println(writer, "<project name=\"Wandora Project\">"); // TODO Get real project name here, if even one exists
println(writer, "<metadata>");
println(writer, "<title/>"); // TODO See if you can put something reasonable here.
println(writer, "<author>Wandora</author>"); // TODO Real author or just leave it as "Wandora"
println(writer, "<keywords/>");
println(writer, "<description/>");
println(writer, "</metadata>");
println(writer, "<workspaces>");
println(writer, "<workspace name=\"Default workspace\" status=\"open\">");
collectNodesAndEdges(topicMap); // 50
logger.setProgress(50);
echoAttributeModel(writer); // 10
logger.setProgress(60);
echoDhns(writer); // 10
logger.setProgress(70);
echoAttributeRows(writer); // 10 This can be done only after echoAttributeModel
logger.setProgress(80);
echoGraphData(writer); // 10
logger.setProgress(90);
echoEmptyTables(writer); // 10
logger.setProgress(100);
// Finally write closing tags for the xml
println(writer, "</workspace>");
println(writer, "</workspaces>");
println(writer, "</project>");
println(writer, "</gephiFile>");
writer.flush();
writer.close();
}
private void collectNodesAndEdges(TopicMap topicMap) throws TopicMapException {
Iterator<Topic> ti = topicMap.getTopics();
int assosNum = topicMap.getNumAssociations();
// First nodes, then edges
while(ti.hasNext())
{
Topic topic = ti.next();
DataNode dNode = new DataNode(makeString(topic.getBaseName()), makeString(topic.getOneSubjectIdentifier().toString()));
StringBuilder occurences = new StringBuilder("");
if(EXPORT_OCCURRENCES) {
Collection<Topic> types=topic.getDataTypes();
Iterator<Topic> iter2=types.iterator();
while(iter2.hasNext()){
Topic type=(Topic)iter2.next();
String typeName = type.getBaseName();
Hashtable<Topic,String> ht=topic.getData(type);
Iterator<Map.Entry<Topic, String>> iter3=ht.entrySet().iterator();
while(iter3.hasNext()){
Map.Entry<Topic,String> e=iter3.next();
String data=(String)e.getValue();
String occurence = makeString(typeName)+" : "+makeString(data)+",";
occurences.append(occurence);
}
}
}
if(occurences.length() > 1) {
occurences.deleteCharAt(occurences.length()-1);
}
dNode.setOccurences(occurences.toString());
dataNodes.put(topic.getOneSubjectIdentifier().toExternalForm(), dNode);
}
Iterator<Topic> iter;
// Classes
if(EXPORT_CLASSES) {
iter=topicMap.getTopics();
while(iter.hasNext()) {
Topic t=(Topic)iter.next();
if(t.isRemoved()) continue;
Iterator<Topic> iter2=t.getTypes().iterator();
while(iter2.hasNext()) {
Topic t2=(Topic)iter2.next();
if(t2.isRemoved()) continue;
DataEdge de = new DataEdge(dataNodes.get(t2.getOneSubjectIdentifier().toExternalForm()), dataNodes.get(t.getOneSubjectIdentifier().toExternalForm()), "class-instance", "class", "instance");
dataEdges.add(de);
}
}
}
// Associations
Iterator<Association> iter2=topicMap.getAssociations();
while( iter2.hasNext() ) {
Association a=(Association)iter2.next();
Collection<Topic> roles = a.getRoles();
if(roles.size() < 2) continue;
else if(roles.size() == 2) {
Topic[] roleArray = (Topic[]) roles.toArray(new Topic[2]);
Topic source = a.getPlayer(roleArray[0]);
Topic target = a.getPlayer(roleArray[1]);
DataEdge de = new DataEdge(dataNodes.get(source.getOneSubjectIdentifier().toExternalForm()), dataNodes.get(target.getOneSubjectIdentifier().toExternalForm()),
makeString(a.getType().getBaseName()), makeString(roleArray[0].getBaseName()),
makeString(roleArray[1].getBaseName()));
dataEdges.add(de);
}
else if (EXPORT_ALL_ASSOCIATIONS && roles.size() > 2){
// TODO multiple roles association
DataNode dumNode = createDummyNode();
for (Topic role : roles) {
Topic targetTopic = a.getPlayer(role);
DataEdge de = new DataEdge(dumNode, dataNodes.get(targetTopic.getOneSubjectIdentifier().toExternalForm()),
makeString(a.getType().getBaseName())+" - "+makeString(role.getBaseName()),
"", makeString(role.getBaseName()));
dataEdges.add(de);
}
}
}
Collections.sort(dataEdges, new sortByEdgeId());
}
private int dummyCounter = 0;
private DataNode createDummyNode() {
DataNode dNode = new DataNode("", "", true);
String key = "empty_dummy_node_association_"+dummyCounter;
dataNodes.put(key, dNode);
dummyCounter++;
return dNode;
}
/*private ArrayList<Topic> addAssociations(Topic topic) throws TopicMapException
{
ArrayList<Topic> subTopics = new ArrayList<Topic>();
ArrayList<Association> associations = new ArrayList<Association>(topic.getAssociations());
for (Association assoc : associations) {
ArrayList<Topic> roles = new ArrayList<Topic>(assoc.getRoles());
Topic playerRole = null;
for (Topic role : roles)
{
Topic player = assoc.getPlayer(role);
if(player != topic)
{
playerRole = player;
addTopic(player, false);
subTopics.add(player);
break;
//Node noud = topicNodes.get(inst);
}
}
if(playerRole != null &&
!topicNodes.get(topic).isConnectedTo(topicNodes.get(playerRole), ConnectionEdge.Type.ASSOCIATION, assoc) ) {
createConnection(topic, playerRole, ConnectionEdge.Type.ASSOCIATION, assoc);
}
}
return subTopics;
}*/
// --------------------------------------------------------------- ECHOS ---
protected void echoAttributeRows(PrintWriter writer) {
println(writer, "<attributerows>");
// Nodes
//Collection<DataNode> nodeColl = dataNodes.values();
ArrayList<DataNode> nodeList = new ArrayList<DataNode>(dataNodes.values());
Collections.sort(nodeList, new sortByNodeId());
//for (DataNode dataNode : nodeColl) {
for (int i=0;i<nodeList.size();i++) {
DataNode dataNode = nodeList.get(i);
println(writer, "<noderow for=\""+dataNode.id+"\" version=\"6\">");
for (int j = 0; j < nodeAttributes.size(); j++) {
AttributeColumn attCol = nodeAttributes.get(j);
String value = ""; // TODO warning! in future this value might different type
if(attCol.id.equals("id"))
{
value = Integer.toString(dataNode.id);
} else if(attCol.id.equals("label")) {
value = dataNode.label;
} else if(attCol.id.equals("si")) {
value = dataNode.si;
} else if(attCol.id.equals("basename")) {
value = dataNode.baseName;
} else if(attCol.id.equals("occurences")) {
value = dataNode.occurences;
}
println(writer, "<attvalue index=\""+attCol.index+"\">"+makeString(value)+"</attvalue>");
}
println(writer, "</noderow>");
}
// Edges
for (int i=0;i<dataEdges.size();i++) {
DataEdge dataEdge = dataEdges.get(i);
println(writer, "<edgerow for=\""+dataEdge.id+"\" version=\"3\">");
for (int j = 0; j < edgeAttributes.size(); j++) {
AttributeColumn attCol = edgeAttributes.get(j);
String value = ""; // TODO warning! in future this value might different type
if(attCol.id.equals("id"))
{
value = Integer.toString(dataEdge.id);
} else if(attCol.id.equals("label")) {
value = dataEdge.label;
} else if(attCol.id.equals("type"))
{
value = dataEdge.type;
} else if(attCol.id.equals("role1"))
{
value = dataEdge.role1;
} else if(attCol.id.equals("role2"))
{
value = dataEdge.role2;
}
println(writer, "<attvalue index=\""+attCol.index+"\">"+value+"</attvalue>");
}
println(writer, "</edgerow>");
}
println(writer, "</attributerows>");
}
protected void echoAttributeModel(PrintWriter writer) {
nodeAttributes = new ArrayList<AttributeColumn>();
edgeAttributes = new ArrayList<AttributeColumn>();
println(writer, "<attributemodel>");
println(writer, "<table edgetable=\"false\" name=\"Nodes\" nodetable=\"true\" version=\"2\">");
nodeAttributes.add(echoAttributeColumn(writer, 0, "id", "Id"));
nodeAttributes.add(echoAttributeColumn(writer, 1, "label", "Label"));
nodeAttributes.add(echoAttributeColumn(writer, 2, "si", "Subject identifier"));
nodeAttributes.add(echoAttributeColumn(writer, 3, "basename", "Basename"));
nodeAttributes.add(echoAttributeColumn(writer, 4, "occurences", "Occurences", "LIST_STRING","DATA"));
println(writer, "</table>");
println(writer, "<table edgetable=\"true\" name=\"Edges\" nodetable=\"false\" version=\"2\">");
edgeAttributes.add(echoAttributeColumn(writer, 0, "id", "Id"));
edgeAttributes.add(echoAttributeColumn(writer, 1, "label", "Label"));
edgeAttributes.add(echoAttributeColumn(writer, 2, "role1", "Source role"));
edgeAttributes.add(echoAttributeColumn(writer, 3, "role2", "Target role"));
edgeAttributes.add(echoAttributeColumn(writer, 4, "type", "Type"));
println(writer, "</table>");
println(writer, "</attributemodel>");
}
protected AttributeColumn echoAttributeColumn(PrintWriter writer, int index, String id, String title, String type, String origin)
{
println(writer, "<column>");
println(writer, "<index>"+index+"</index>");
println(writer, "<id>"+id+"</id>");
println(writer, "<title>"+title+"</title>");
println(writer, "<type>"+type+"</type>");
println(writer, "<origin>"+origin+"</origin>");
println(writer, "<default/>");
println(writer, "</column>");
return new AttributeColumn(index, id, title, type, origin);
}
protected AttributeColumn echoAttributeColumn(PrintWriter writer, int index, String id, String title)
{
return echoAttributeColumn(writer, index, id, title, "STRING", "PROPERTY");
}
protected void echoGraphData(PrintWriter writer) {
writer.println("<Data>");
// Nodes
Collection<DataNode> nodeColl = dataNodes.values();
int maxArea = nodeColl.size() * 2;
if(maxArea > 5000)
{
maxArea = 5000;
}
ArrayList<DataNode> nodeList = new ArrayList<DataNode>(dataNodes.values());
Collections.sort(nodeList, new sortByNodeId());
// Lets make just a simple grid, nothing fancy.
double nodesPerLine = Math.floor(Math.sqrt(nodeColl.size()));
double lineXCounter = 1;
double lineYCounter = 1;
//for (DataNode dataNode : nodeColl) {
for (int i=0;i<nodeList.size();i++) {
DataNode dataNode = nodeList.get(i);
double randomX = (maxArea/2)-maxArea*(lineXCounter/nodesPerLine);
double randomY = (maxArea/2)-maxArea*(lineYCounter/nodesPerLine);
lineXCounter++;
if(lineXCounter >= nodesPerLine){
lineXCounter = 1;
lineYCounter++;
}
//randomX = (i+1)*2;
NumberFormat nf = NumberFormat.getNumberInstance(Locale.US);
DecimalFormat formatter = (DecimalFormat)nf;
formatter.applyPattern("#.##");
String ranX = formatter.format(randomX);
String ranY = formatter.format(randomY);
println(writer, "<nodedata nodepre=\""+dataNode.pre+"\">");
println(writer, "<position x=\""+ranX+"\" y=\""+ranY+"\" z=\"0.0\"/>");
if(dataNode.isDummy) {
println(writer, "<color a=\"1.0\" b=\"0.7\" g=\"0.7\" r=\"0.7\"/>");
} else {
println(writer, "<color a=\"1.0\" b=\"0.61568628\" g=\"0.39411766\" r=\"0.31176471\"/>");
}
println(writer, "<size value=\"5.0\"/>");
println(writer, "</nodedata>");
}
// Edges
//for (DataEdge dataEdge : dataEdges) {
for (int i=0;i<dataEdges.size();i++) {
DataEdge dataEdge = dataEdges.get(i);
println(writer, "<edgedata sourcepre=\""+dataEdge.node1.pre+"\" targetpre=\""+dataEdge.node2.pre+"\">");
println(writer, "<color a=\"1.0\" b=\"0.0\" g=\"0.0\" r=\"-1.0\"/>");
println(writer, "</edgedata>");
}
writer.println("</Data>");
}
protected void echoEmptyTables(PrintWriter writer) {
// Attributes
println(writer, "<attributemodel/>");
// Attributes
println(writer, "<attributerows/>");
// Filter model
println(writer, "<filtermodel>");
println(writer, "<queries/>");
println(writer, "</filtermodel>");
// Text data
println(writer, "<textdata/>");
// Statistics
println(writer, "<statistics/>");
// Partition model
println(writer, "<partitionmodel/>");
// Layout model
println(writer, "<layoutmodel>");
println(writer, "<properties/>");
println(writer, "</layoutmodel>");
// Partition model
println(writer, "<partitionmodel/>");
// Viz model
//println(writer, "<vizmodel/>");
// Preview model
println(writer, "<previewmodel/>");
}
private class sortByNodeId implements java.util.Comparator<DataNode> {
public int compare(DataNode o1, DataNode o2) {
int sdif = o1.id - o2.id;
return sdif;
}
}
private class sortByEdgeId implements java.util.Comparator<DataEdge> {
public int compare(DataEdge o1, DataEdge o2) {
int sdif = o1.id - o2.id;
return sdif;
}
}
protected void echoDhns(PrintWriter writer) {
//topicTotal = topicMap.getNumTopics();
println(writer, "<Dhns>");
println(writer, "<Status directed=\"true\" hierarchical=\"false\" mixed=\"false\" undirected=\"false\"/>");
println(writer, "<IDGen edge=\""+dataEdges.size()+"\" node=\""+dataNodes.size()+"\"/>");
println(writer, "<Settings></Settings>"); // Lets try without settings...
println(writer, "<GraphVersion edge=\""+dataEdges.size()+"\" node=\""+dataNodes.size()+"\"/>");
// First nodes
println(writer, "<TreeStructure edgesenabled=\""+dataEdges.size()+"\" edgestotal=\""+dataEdges.size()+"\" nodesenabled=\""+dataNodes.size()+"\" mutualedgesenabled=\"0\" mutualedgestotal=\"0\">");
println(writer, "<Tree>");
//Collection<DataNode> nodeColl = dataNodes.values();
ArrayList<DataNode> nodeList = new ArrayList<DataNode>(dataNodes.values());
Collections.sort(nodeList, new sortByNodeId());
//for (DataNode dataNode : nodeColl) {
for (int i=0;i<nodeList.size();i++) {
DataNode dataNode = nodeList.get(i);
println(writer, "<Node enabled=\"true\" id=\""+dataNode.id+"\" parent=\"0\" pre=\""+dataNode.pre+"\" enabledindegree=\"1\" enabledmutualdegree=\"0\" enabledoutdegree=\"0\"/>");
}
println(writer, "</Tree>");
println(writer, "</TreeStructure>");
// Then edges
println(writer, "<Edges>");
//ArrayList<DataEdge> edgeList = new ArrayList<DataEdge>(dataEdges.values());
//for (DataEdge dataEdge : dataEdges) {
for (int i=0;i<dataEdges.size();i++) {
DataEdge dataEdge = dataEdges.get(i);
if(dataEdge.node1.pre == dataEdge.node2.pre)
{
println(writer, "<SelfLoop id=\""+dataEdge.id+"\" source=\""+dataEdge.node1.pre+"\" target=\""+dataEdge.node2.pre+"\" weight=\"2.0\"/>");
} else {
println(writer, "<MixedEdge directed=\"true\" id=\""+dataEdge.id+"\" source=\""+dataEdge.node1.pre+"\" target=\""+dataEdge.node2.pre+"\" weight=\"2.0\"/>");
}
}
println(writer, "</Edges>");
// End
println(writer, "</Dhns>");
}
protected String makeID(Topic t) throws TopicMapException {
if(t.getBaseName() != null) {
String bn = t.getBaseName();
bn = makeID(bn);
return bn;
}
return ""+t.getID();
}
protected String makeID(String s) {
if(s != null && s.length() > 0) {
StringBuilder sb = new StringBuilder("");
for(int i=0; i<s.length(); i++) {
if(Character.isJavaIdentifierPart(s.charAt(i))) {
sb.append(s.charAt(i));
}
else {
sb.append('_');
}
}
return sb.toString();
}
return s;
}
protected String makeString(String s) {
if(s == null) return null;
//s = s.substring(0,Math.min(s.length(), 240));
s = s.replaceAll("<", "<");
s = s.replaceAll(">", ">");
s = s.replaceAll("\\&", "&");
s = s.replaceAll("\"", "'");
return s;
}
protected String makeString(Topic t) throws TopicMapException {
if(t == null) return null;
String s = t.getBaseName();
if(s == null) s = t.getOneSubjectIdentifier().toExternalForm();
return makeString(s);
}
// -------------------------------------------------------------------------
// Elementary print methods are used to ensure output is UTF-8
protected void print(PrintWriter writer, String str) {
writer.print(str);
}
protected void println(PrintWriter writer, String str) {
writer.println(str);
}
private class DataNode {
int pre;
int id;
String label;
String baseName;
String si;
String occurences = "";
boolean isDummy = false;
public DataNode(String label, String si) {
this.id = nodeCounter;
this.pre = nodeCounter+1;
//this.id = id;
//this.pre = id+1;
this.label = label;
this.si = si;
this.baseName = label;
if(label == null || label.length() < 1) {
this.label = si;
this.baseName = si;
}
nodeCounter++;
}
public DataNode(String label, String si, boolean isDummy) {
this(label, si);
this.isDummy = isDummy;
}
public void setOccurences(String occurences) {
this.occurences = occurences;
}
}
private class DataEdge {
DataNode node1;
DataNode node2;
String label;
String type;
String role1;
String role2;
int id;
public DataEdge(DataNode node1, DataNode node2, String type, String role1, String role2) {
this.node1 = node1;
this.node2 = node2;
this.label = type;
this.label = type;
this.type = type;
this.role1 = role1;
this.role2 = role2;
this.id = edgeCounter;
edgeCounter++;
}
}
private class AttributeColumn {
int index;
String id;
String title;
String type;
String origin;
public AttributeColumn(int index, String id, String title, String type, String origin) {
this.index = index;
this.id = id;
this.title = title;
this.type = type;
this.origin = origin;
}
}
}
| 30,779 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
DOTExport.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/exporters/DOTExport.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* DOTExport.java
*
*/
package org.wandora.application.tools.exporters;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import javax.swing.Icon;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.WandoraToolLogger;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.UIBox;
import org.wandora.application.gui.UIConstants;
import org.wandora.application.gui.simple.SimpleFileChooser;
import org.wandora.application.tools.GenericOptionsDialog;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author akivela
*/
import org.wandora.utils.IObox;
public class DOTExport extends AbstractExportTool implements WandoraTool {
private static final long serialVersionUID = 1L;
public boolean EXPORT_SELECTION_INSTEAD_TOPIC_MAP = false;
public static boolean LABEL_NODES = true;
public static boolean EXPORT_CLASSES = true;
public static boolean EXPORT_OCCURRENCES = true;
public static boolean EXPORT_N_ASSOCIATIONS = true;
public DOTExport() {
}
public DOTExport(boolean exportSelection) {
EXPORT_SELECTION_INSTEAD_TOPIC_MAP = exportSelection;
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/export_graph.png");
}
@Override
public boolean requiresRefresh() {
return false;
}
@Override
public boolean isConfigurable(){
return true;
}
@Override
public void configure(Wandora wandora,org.wandora.utils.Options options,String prefix) throws TopicMapException {
GenericOptionsDialog god=new GenericOptionsDialog(wandora,"DOT Export options","DOT Export options",true,new String[][]{
new String[]{"Export classes","boolean",(EXPORT_CLASSES ? "true" : "false"),"Should topic classes also export?"},
new String[]{"Export occurrences","boolean",(EXPORT_OCCURRENCES ? "true" : "false"),"Should topic occurrences also export?"},
new String[]{"Export n associations","boolean",(EXPORT_N_ASSOCIATIONS ? "true" : "false"), "Should associations with more than 2 players also export?"},
},wandora);
god.setVisible(true);
if(god.wasCancelled()) return;
Map<String, String> values = god.getValues();
EXPORT_CLASSES = ("true".equals(values.get("Export classes")) ? true : false );
EXPORT_OCCURRENCES = ("true".equals(values.get("Export occurrences")) ? true : false );
EXPORT_N_ASSOCIATIONS = ("true".equals(values.get("Export n associations")) ? true : false );
}
@Override
public void execute(Wandora wandora, Context context) {
String topicMapName = null;
String exportInfo = null;
// --- Solve first topic map to be exported
TopicMap tm = null;
if(EXPORT_SELECTION_INSTEAD_TOPIC_MAP) {
tm = makeTopicMapWith(context);
exportInfo = "Exporting selected topics as DOT graph";
topicMapName = "selection_in_wandora";
}
else {
tm = solveContextTopicMap(wandora, context);
topicMapName = this.solveNameForTopicMap(wandora, tm);
if(topicMapName != null) {
exportInfo = "Exporting topic map in layer '" + topicMapName + "' as DOT graph";
}
else {
exportInfo = "Exporting topic map as DOT graph";
topicMapName = "no_name_topic_map";
}
}
// --- Then solve target file (and format)
SimpleFileChooser chooser=UIConstants.getFileChooser();
chooser.setDialogTitle(exportInfo+"...");
if(chooser.open(wandora, "Export")==SimpleFileChooser.APPROVE_OPTION){
setDefaultLogger();
File file = chooser.getSelectedFile();
String fileName = file.getName();
// --- Finally write topicmap as GML to chosen file
OutputStream out=null;
try {
file=IObox.addFileExtension(file, "dot"); // Ensure file extension exists!
fileName = file.getName(); // Updating filename if file has changed!
out=new FileOutputStream(file);
log(exportInfo+" to '"+fileName+"'.");
//System.out.println("tm == "+ tm);
exportGraph(out, tm, topicMapName, getCurrentLogger());
out.close();
log("Ready.");
}
catch(Exception e) {
log(e);
try { if(out != null) out.close(); }
catch(Exception e2) { log(e2); }
}
}
setState(WAIT);
}
@Override
public String getName() {
return "Export DOT graph";
}
@Override
public String getDescription() {
return "Exports topic map layer as DOT file.";
}
public void exportGraph(OutputStream out, TopicMap topicMap, String graphName, WandoraToolLogger logger) throws TopicMapException {
if(logger == null) logger = this;
PrintWriter writer = null;
try {
writer = new PrintWriter(new OutputStreamWriter(out, "ISO-8859-1"));
}
catch (UnsupportedEncodingException ex) {
log("Exception while trying ISO-8859-1 character encoding. Using default encoding");
writer = new PrintWriter(new OutputStreamWriter(out));
}
int totalCount = 2*topicMap.getNumTopics() + topicMap.getNumAssociations();
logger.setProgressMax(totalCount);
int count = 0;
println(writer, "graph wandora_export {");
if(LABEL_NODES) {
Iterator iter=topicMap.getTopics();
while(iter.hasNext() && !logger.forceStop()) {
Topic t=(Topic)iter.next();
if(t.isRemoved()) continue;
logger.setProgress(count++);
echoNode(t, writer);
}
}
if(EXPORT_OCCURRENCES && !logger.forceStop()) {
Iterator iter=topicMap.getTopics();
while(iter.hasNext() && !logger.forceStop()) {
Topic t=(Topic)iter.next();
if(t.isRemoved()) continue;
logger.setProgress(count++);
// Topic occurrences....
if(t.getDataTypes().size()>0){
Collection<Topic> types=t.getDataTypes();
Iterator<Topic> iter2=types.iterator();
while(iter2.hasNext()) {
Topic type=(Topic)iter2.next();
Hashtable<Topic,String> ht=t.getData(type);
Iterator<Map.Entry<Topic,String>> iter3=ht.entrySet().iterator();
while(iter3.hasNext()) {
Map.Entry<Topic,String> e=iter3.next();
String data=(String)e.getValue();
echoNode(data, writer);
}
}
}
}
iter=topicMap.getTopics();
while(iter.hasNext() && !logger.forceStop()) {
Topic t=(Topic)iter.next();
if(t.isRemoved()) continue;
logger.setProgress(count++);
// Topic occurrences....
if(t.getDataTypes().size()>0){
Collection<Topic> types=t.getDataTypes();
Iterator<Topic> iter2=types.iterator();
while(iter2.hasNext()){
Topic type=iter2.next();
Hashtable<Topic,String> ht=t.getData(type);
Iterator<Map.Entry<Topic,String>> iter3=ht.entrySet().iterator();
while(iter3.hasNext()){
Map.Entry<Topic,String> e=iter3.next();
String data=(String)e.getValue();
echoEdge(t, data, type, writer);
}
}
}
}
}
// Topic types....
if(EXPORT_CLASSES && !logger.forceStop()) {
Iterator iter=topicMap.getTopics();
while(iter.hasNext() && !logger.forceStop()) {
Topic t=(Topic)iter.next();
if(t.isRemoved()) continue;
logger.setProgress(count++);
if(!t.getTypes().isEmpty()){
for (Topic t2 : t.getTypes()) {
if(t2.isRemoved()) continue;
echoEdge(t2, t, "class_instance", writer);
}
}
}
}
// Associations....
if(!logger.forceStop()) {
Iterator iter=topicMap.getAssociations();
int icount=0;
while(iter.hasNext() && !logger.forceStop()) {
logger.setProgress(count++);
Association a=(Association)iter.next();
Collection<Topic> roles = a.getRoles();
if(roles.size() < 2) continue;
else if(roles.size() == 2) {
Topic[] roleArray = (Topic[]) roles.toArray(new Topic[2]);
echoEdge(a.getPlayer(roleArray[0]), a.getPlayer(roleArray[1]), a.getType(), writer);
}
else {
if(EXPORT_N_ASSOCIATIONS) {
icount++;
String target="nameless_intermediator_node-"+icount;
echoNode(target, writer);
Iterator<Topic> iter2 = roles.iterator();
while(iter2.hasNext()) {
Topic role=(Topic)iter2.next();
echoEdge(a.getPlayer(role), target, a.getType(), writer);
}
}
}
}
}
println(writer, "}");
writer.flush();
writer.close();
}
// --------------------------------------------------------------- ECHOS ---
protected void echoNode(Topic t, PrintWriter writer) throws TopicMapException {
String label = t.getBaseName();
if(label == null) label = t.getOneSubjectIdentifier().toExternalForm();
echoNode(makeID(t), null, label, writer);
}
protected void echoNode(String data, PrintWriter writer) {
echoNode(makeID(data), null, data, writer);
}
protected void echoNode(String id, String name, String label, PrintWriter writer) {
if(writer == null || id == null) return;
if(label != null) println(writer, " "+id+" [label=\""+makeString(label)+"\"]");
}
protected void echoEdge(Topic source, Topic target, String label, PrintWriter writer) throws TopicMapException {
if(label != null) {
println(writer, " "+makeID(source)+" -- "+makeID(target)+" [label=\""+makeString(label)+"\"]");
}
else {
println(writer, " "+makeID(source)+" -- "+makeID(target)+"");
}
}
protected void echoEdge(String source, String target, String label, PrintWriter writer) {
if(label != null) {
println(writer, " "+makeID(source)+" -- "+makeID(target)+" [label=\""+makeString(label)+"\"]");
}
else {
println(writer, " "+makeID(source)+" -- "+makeID(target)+"");
}
}
protected void echoEdge(Topic source, String target, Topic label, PrintWriter writer) throws TopicMapException {
String l = label.getBaseName();
if(l == null) l = label.getOneSubjectIdentifier().toExternalForm();
if(l != null) {
println(writer, " "+makeID(source)+" -- "+makeID(target)+" [label=\""+makeString(l)+"\"]");
}
else {
println(writer, " "+makeID(source)+" -- "+makeID(target)+"");
}
}
protected void echoEdge(Topic source, Topic target, Topic label, PrintWriter writer) throws TopicMapException {
String l = label.getBaseName();
if(l == null) l = label.getOneSubjectIdentifier().toExternalForm();
echoEdge(source, target, l, writer);
}
protected String makeID(Topic t) throws TopicMapException {
String id = ""+t.getID();
id = id.replace("-", "");
return id;
}
protected String makeID(String s) {
long h = s.hashCode();
if(h > 0) return "ID"+(Math.abs(h)*2);
else return "ID"+((Math.abs(h)*2)+1);
}
protected String makeString(String s) {
if(s == null) return null;
//s = s.substring(0,Math.min(s.length(), 240));
s = s.replaceAll("\"", "\\\"");
s = s.replaceAll("\n", " ");
s = s.replaceAll("\t", " ");
s = s.replaceAll("\r", " ");
return s;
}
protected String makeString(Topic t) throws TopicMapException {
if(t == null) return null;
String s = t.getBaseName();
if(s == null) s = t.getOneSubjectIdentifier().toExternalForm();
return makeString(s);
}
// -------------------------------------------------------------------------
// Elementary print methods are used to ensure output is ISO-8859-1
protected void print(PrintWriter writer, String str) {
writer.print(str);
}
protected void println(PrintWriter writer, String str) {
writer.println(str);
}
} | 14,769 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
OBOExport.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/exporters/OBOExport.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* */
package org.wandora.application.tools.exporters;
import java.io.File;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import javax.swing.Icon;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraToolType;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.UIBox;
import org.wandora.application.gui.UIConstants;
import org.wandora.application.gui.WandoraOptionPane;
import org.wandora.application.gui.simple.SimpleFileChooser;
import org.wandora.application.tools.importers.OBO;
import org.wandora.application.tools.importers.OBOConfiguration;
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.TopicTools;
/**
*
* @author akivela
*/
public class OBOExport extends AbstractExportTool {
private static final long serialVersionUID = 1L;
/** Creates a new instance of RDFExport */
public OBOExport() {
}
@Override
public String getName() {
return "OBO Export";
}
@Override
public String getDescription() {
return "Exports specific topic map structures in OBO flat file format.";
}
@Override
public boolean requiresRefresh() {
return false;
}
@Override
public WandoraToolType getType(){
return WandoraToolType.createExportType();
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/export_obo.png");
}
@Override
public void initialize(Wandora wandora,org.wandora.utils.Options options,String prefix) throws TopicMapException {
String o=options.get(OBO.optionPrefix+"options");
if(o!=null){
int i=Integer.parseInt(o);
OBO.setOptions(i);
}
}
@Override
public boolean isConfigurable(){
return true;
}
@Override
public void configure(Wandora wandora,org.wandora.utils.Options options,String prefix) throws TopicMapException {
//System.out.println(prefix);
OBOConfiguration dialog=new OBOConfiguration(wandora,true);
dialog.setOptions(OBO.getOptions());
dialog.setVisible(true);
if(!dialog.wasCancelled()){
int i=dialog.getOptions();
OBO.setOptions(i);
options.put(OBO.optionPrefix+"options",""+i);
}
}
@Override
public void writeOptions(Wandora wandora,org.wandora.utils.Options options,String prefix){
options.put(prefix+"OBO.optionPrefix",""+OBO.getOptions());
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
String namespace = WandoraOptionPane.showInputDialog(wandora, "Give OBO namespace to export", "", "OBO namespace");
if(namespace == null || namespace.trim().length() == 0) return;
String[] namespaces = null;
if(namespace.indexOf(",") != -1) {
namespaces = namespace.split(",");
for(int i=0; i<namespaces.length; i++) {
namespaces[i] = namespaces[i].trim();
}
}
else {
namespaces = new String[] { namespace };
}
SimpleFileChooser chooser=UIConstants.getFileChooser();
chooser.setDialogTitle("OBO Export");
if(chooser.open(wandora, "Export")==SimpleFileChooser.APPROVE_OPTION){
setDefaultLogger();
File file = chooser.getSelectedFile();
TopicMap tm=solveContextTopicMap(wandora,context);
exportOBO(file, namespaces, tm);
setState(WAIT);
}
}
public void exportOBO(File file, String[] namespaces, TopicMap tm) {
try{
PrintStream out=new PrintStream(file);
exportHeader(out, namespaces, tm);
exportTypedefs(out, namespaces, tm);
exportTerms(out, namespaces, tm);
exportInstances(out, namespaces, tm);
out.close();
log("Ready.");
}
catch(Exception e){
log(e);
}
}
public void exportHeader(PrintStream out, String[] namespaces, TopicMap tm) {
int headerCount = 0;
try {
for(int i=0; i<namespaces.length; i++) {
String namespace = namespaces[i];
if(namespace != null && namespace.length() > 0) {
Topic headerTopic = OBO.getHeaderTopic(tm, namespace);
if(headerTopic != null) {
if(headerCount==0) {
log("Exporting header for namespace '"+namespace+"'.");
headerCount++;
ArrayList<String> orederedTags = new ArrayList<String>();
orederedTags.add("format-version");
orederedTags.add("data-version");
orederedTags.add("date");
orederedTags.add("saved-by");
orederedTags.add("auto-generated-by");
orederedTags.add("import");
ArrayList<String> orederedTags2 = new ArrayList<String>();
orederedTags2.add("synonymtypedef");
orederedTags2.add("default-namespace");
orederedTags2.add("remark");
String tag = null;
String value = null;
for(String otag : orederedTags) {
Topic tagTopic = OBO.getTopicForSchemaTerm(tm, otag);
if(tagTopic != null) {
value = headerTopic.getData(tagTopic, OBO.LANG);
exportHeaderTagValue(out, otag, value);
}
}
Topic cetegoryTopic = OBO.getCategoryTopic(tm, namespace);
if(cetegoryTopic != null) {
Collection<Topic> categories = tm.getTopicsOfType(cetegoryTopic);
if(categories != null && categories.size() > 0) {
for(Topic category : categories) {
if(category != null && !category.isRemoved()) {
String cid = OBO.solveOBOId(category);
String description = OBO.solveOBODescription(category);
if(cid != null && cid.length() > 0) {
out.print("subsetdef: "+cid);
if(description != null && description.length() >0) {
out.print(" \""+description+"\"");
}
out.println();
}
}
}
}
}
for(String otag : orederedTags2) {
Topic tagTopic = OBO.getTopicForSchemaTerm(tm, otag);
if(tagTopic != null) {
value = headerTopic.getData(tagTopic, OBO.LANG);
exportHeaderTagValue(out, otag, value);
}
}
Collection<Topic> occurrenceTypes = headerTopic.getDataTypes();
for(Topic occurrenceType : occurrenceTypes) {
tag = occurrenceType.getBaseName();
if(tag != null && tag.length() > 0 && !orederedTags.contains(tag) && !orederedTags2.contains(tag)) {
value = headerTopic.getData(occurrenceType, OBO.LANG);
exportHeaderTagValue(out, tag, value);
}
}
}
else {
log("Header already processed! More than one header available! Only first header exported.");
}
}
else {
log("Can't find header for namespace '"+namespace+"'.");
}
}
}
}
catch(Exception e) {
log(e);
}
}
public void exportTerms(PrintStream out, String[] namespaces, TopicMap tm) {
try {
HashSet<String> processedIds = new HashSet<String>();
Topic definitionType = OBO.getTopicForSchemaTerm(tm, OBO.SCHEMA_TERM_DEFINITION);
for(int i=0; i<namespaces.length; i++) {
String namespace = namespaces[i];
Topic termtype = OBO.getTermTopic(tm, namespace);
if(termtype != null) {
log("Exporting terms in namespace '"+namespace+"'.");
String id = null;
String name = null;
String definition = null;
Collection<Topic> terms = tm.getTopicsOfType(termtype);
Collection<Topic> sortedTerms = TMBox.sortTopicsByData(terms,OBO.getTopicForSchemaTerm(tm, OBO.SCHEMA_TERM_ID),OBO.LANG);
int count = sortedTerms.size();
int c = 0;
for(Topic term : sortedTerms) {
try {
setProgress((++c * 100) / count);
if(term != null && !term.isRemoved()) {
id = OBO.solveOBOId(term);
if(processedIds.contains(id)) continue;
processedIds.add(id);
name = OBO.solveOBOName(term);
if(id != null && id.length() > 0) {
out.println();
out.println("[Term]");
out.println("id: "+id);
exportRelations(out, tm, term, OBO.SCHEMA_TERM_IS_ANONYMOUS, "is_anonymous");
// ******* NAME ********
if(name != null && name.length() > 0) {
out.println("name: "+name);
}
exportRelations(out, tm, term, OBO.SCHEMA_TERM_NAMESPACE, "namespace");
// ***** ALT-IDS ******
exportAltIds(out, tm, term, id);
// ******* DEFINITION ********
exportDefinition(out, tm, term);
// ***** COMMENT *****
exportComment(out, tm, term);
// ******* SUBSETS *******
exportRelations(out, tm, term, OBO.SCHEMA_TERM_CATEGORY, OBO.SCHEMA_TERM_CATEGORY, "subset");
// ****** SYNONYMS ******
exportSynonyms(out, tm, term);
//******* XREFS ********
exportXrefs(out, tm, term);
// ****** RELATIONS ******
exportRelations(out, tm, term, OBO.SCHEMA_TERM_SUPERCLASS_SUBCLASS, OBO.SCHEMA_TERM_SUPERCLASS, "is_a");
exportRelations(out, tm, term, OBO.SCHEMA_TERM_INTERSECTION_OF, OBO.SCHEMA_TERM_RELATED_TO, "intersection_of");
exportRelations(out, tm, term, OBO.SCHEMA_TERM_UNION_OF, OBO.SCHEMA_TERM_RELATED_TO, "union_of");
exportRelations(out, tm, term, OBO.SCHEMA_TERM_DISJOINT_FROM, OBO.SCHEMA_TERM_RELATED_TO, "disjoint_from");
exportRelations(out, tm, term, OBO.SCHEMA_TERM_RELATIONSHIP, OBO.SCHEMA_TERM_RELATED_TO, "relationship");
exportRelations(out, tm, term, OBO.SCHEMA_TERM_PART_OF, OBO.SCHEMA_TERM_RELATED_TO, "part_of");
exportRelations(out, tm, term, OBO.SCHEMA_TERM_ADJACENT_TO, OBO.SCHEMA_TERM_RELATED_TO, "adjacent_to");
exportRelations(out, tm, term, OBO.SCHEMA_TERM_LOCATED_IN, OBO.SCHEMA_TERM_RELATED_TO, "located_in");
exportRelations(out, tm, term, OBO.SCHEMA_TERM_CONTAINS, OBO.SCHEMA_TERM_RELATED_TO, "contains");
exportRelations(out, tm, term, OBO.SCHEMA_TERM_TRANSFORMATION_OF, OBO.SCHEMA_TERM_RELATED_TO, "transformation_of");
exportRelations(out, tm, term, OBO.SCHEMA_TERM_DERIVES_FROM, OBO.SCHEMA_TERM_RELATED_TO, "derives_from");
exportRelations(out, tm, term, OBO.SCHEMA_TERM_AGENT_IN, OBO.SCHEMA_TERM_RELATED_TO, "agent_in");
// ******* REST OF RELATIONSHIPS *******
Topic typedefType = OBO.getTypedefTopic(tm, namespace);
if(typedefType != null) {
Collection<Topic> typedefs = tm.getTopicsOfType(typedefType);
if(typedefs != null && typedefs.size() > 0) {
for(Topic typedef : typedefs) {
exportRelationships(out, tm, term, typedef.getBaseName(), OBO.SCHEMA_TERM_RELATED_TO, typedef.getBaseName());
}
}
}
// ***** IS OBSOLETE *****
Topic isObsoleteType = OBO.getObsoleteTopic(tm, namespace);
if(isObsoleteType != null) {
if(term.isOfType(isObsoleteType)) {
out.println("is_obsolete: true");
}
}
exportRelations(out, tm, term, OBO.SCHEMA_TERM_REPLACED_BY, OBO.SCHEMA_TERM_REPLACED_BY, "replaced_by");
exportRelations(out, tm, term, OBO.SCHEMA_TERM_CONSIDER_USING, OBO.SCHEMA_TERM_CONSIDER_USING, "consider");
exportCreatorAndCreationDate(out, tm, term);
}
}
if(forceStop()) {
return;
}
}
catch(Exception e) {
log(e);
}
}
}
else {
log("Can't find terms for namespace '"+namespace+"'.");
}
}
}
catch(Exception e) {
log(e);
}
}
public void exportInstances(PrintStream out, String[] namespaces, TopicMap tm) {
try {
if(namespaces != null && namespaces.length > 0) {
HashSet<String> processedIds = new HashSet<String>();
for(int i=0; i<namespaces.length; i++) {
String namespace = namespaces[i];
if(namespace != null && namespace.length() > 0) {
Topic typeTopic = OBO.getInstanceTopic(tm, namespace);
if(typeTopic != null) {
log("Exporting instances in namespace '"+namespace+"'.");
String id = null;
String name = null;
String definition = null;
Topic definitionType = OBO.getTopicForSchemaTerm(tm, OBO.SCHEMA_TERM_DEFINITION);
Collection<Topic> terms = tm.getTopicsOfType(typeTopic);
Collection<Topic> sortedTerms = TMBox.sortTopicsByData(terms,OBO.getTopicForSchemaTerm(tm, OBO.SCHEMA_TERM_ID),OBO.LANG);
int count = terms.size();
int c = 0;
for(Topic term : sortedTerms) {
try {
setProgress((++c * 100) / count);
if(term != null && !term.isRemoved()) {
id = OBO.solveOBOId(term);
if(processedIds.contains(id)) continue;
processedIds.add(id);
name = OBO.solveOBOName(term);
if(id != null && id.length() > 0) {
out.println();
out.println("[Instance]");
out.println("id: "+id);
exportRelations(out, tm, term, OBO.SCHEMA_TERM_IS_ANONYMOUS, "is_anonymous");
// ****** NAME *******
if(name != null && name.length() > 0) {
out.println("name: "+name);
}
exportRelations(out, tm, term, OBO.SCHEMA_TERM_NAMESPACE, "namespace");
// ***** ALT-IDS ******
exportAltIds(out, tm, term, id);
// ******* DEFINITION ********
exportDefinition(out, tm, term);
// ***** COMMENT *****
exportComment(out, tm, term);
exportRelations(out, tm, term, OBO.SCHEMA_TERM_CATEGORY, OBO.SCHEMA_TERM_CATEGORY, "subset");
// ****** SYNONYMS ******
exportSynonyms(out, tm, term);
//******* XREFS ********
exportXrefs(out, tm, term);
// ****** RELATIONS ******
exportRelations(out, tm, term, OBO.SCHEMA_TERM_INSTANCE_OF, "instance_of");
exportRelations(out, tm, term, OBO.SCHEMA_TERM_PROPERTY_VALUE, "property_value");
// ***** IS OBSOLETE *****
Topic isObsoleteType = OBO.getObsoleteTopic(tm, namespace);
if(isObsoleteType != null) {
if(term.isOfType(isObsoleteType)) {
out.println("is_obsolete: true");
}
}
exportRelations(out, tm, term, OBO.SCHEMA_TERM_REPLACED_BY, "replaced_by");
exportRelations(out, tm, term, OBO.SCHEMA_TERM_CONSIDER_USING, "consider");
//******* PROPERTIES ********
exportProperties(out, tm, term);
}
}
if(forceStop()) {
return;
}
}
catch(Exception e) {
log(e);
}
}
}
else {
log("Can't find instances for namespace '"+namespace+"'.");
}
}
}
}
}
catch(Exception e) {
log(e);
}
}
public void exportTypedefs(PrintStream out, String[] namespaces, TopicMap tm) {
try {
if(namespaces != null && namespaces.length > 0) {
HashSet<String> processedIds = new HashSet<String>();
for(int i=0; i<namespaces.length; i++) {
String namespace = namespaces[i];
if(namespace!=null && namespace.length() >0) {
Topic typeTopic = OBO.getTypedefTopic(tm, namespace);
if(typeTopic != null) {
log("Exporting typedefs in namespace '"+namespace+"'.");
String id = null;
String name = null;
String definition = null;
Topic definitionType = OBO.getTopicForSchemaTerm(tm, OBO.SCHEMA_TERM_DEFINITION);
Collection<Topic> terms = tm.getTopicsOfType(typeTopic);
Collection<Topic> sortedTerms = TMBox.sortTopicsByData(terms,OBO.getTopicForSchemaTerm(tm, OBO.SCHEMA_TERM_ID),OBO.LANG);
int c = 0;
int count = sortedTerms.size();
for(Topic term : sortedTerms) {
try {
setProgress((++c * 100) / count);
if(term != null && !term.isRemoved()) {
id = OBO.solveOBOId(term);
if(processedIds.contains(id)) continue;
processedIds.add(id);
name = OBO.solveOBOName(term);
if(id != null && id.length() > 0) {
out.println();
out.println("[Typedef]");
out.println("id: "+id);
exportRelations(out, tm, term, OBO.SCHEMA_TERM_IS_ANONYMOUS, "is_anonymous");
if(name != null && name.length() > 0) {
out.println("name: "+name);
}
exportRelations(out, tm, term, OBO.SCHEMA_TERM_NAMESPACE, OBO.SCHEMA_TERM_NAMESPACE, "namespace");
// ***** ALT-IDS ******
exportAltIds(out, tm, term, id);
// ******* DEFINITION ********
exportDefinition(out, tm, term);
// ***** COMMENT *****
exportComment(out, tm, term);
exportRelations(out, tm, term, OBO.SCHEMA_TERM_CATEGORY, "subset");
// ****** SYNONYMS ******
exportSynonyms(out, tm, term);
//******* XREFS ********
exportXrefs(out, tm, term);
// ****** RELATIONS ******
exportRelations(out, tm, term, OBO.SCHEMA_TERM_DOMAIN, "domain");
exportRelations(out, tm, term, OBO.SCHEMA_TERM_RANGE, "range");
exportRelations(out, tm, term, OBO.SCHEMA_TERM_IS_ANTISYMMETRIC, "is_anti_symmetric");
exportRelations(out, tm, term, OBO.SCHEMA_TERM_IS_CYCLIC, "is_cyclic");
exportRelations(out, tm, term, OBO.SCHEMA_TERM_IS_REFLEXIVE, "is_reflexive");
exportRelations(out, tm, term, OBO.SCHEMA_TERM_IS_SYMMETRIC, "is_symmetric");
exportRelations(out, tm, term, OBO.SCHEMA_TERM_IS_TRANSITIVE, "is_transitive");
exportRelations(out, tm, term, OBO.SCHEMA_TERM_IS_METADATA_TAG, "is_metadata_tag");
exportRelations(out, tm, term, OBO.SCHEMA_TERM_SUPERCLASS_SUBCLASS, OBO.SCHEMA_TERM_SUPERCLASS, "is_a");
exportRelations(out, tm, term, OBO.SCHEMA_TERM_INVERSE_OF, "inverse_of");
exportRelations(out, tm, term, OBO.SCHEMA_TERM_IS_TRANSITIVE_OVER, "transitive_over");
/*
exportRelations(out, tm, term, OBO.SCHEMA_TERM_RELATIONSHIP, OBO.SCHEMA_TERM_RELATED_TERM, "relationship");
exportRelations(out, tm, term, OBO.SCHEMA_TERM_INTERSECTION_OF, OBO.SCHEMA_TERM_INTERSECTION_OF, "intersection_of");
exportRelations(out, tm, term, OBO.SCHEMA_TERM_PART_OF, OBO.SCHEMA_TERM_HAS_PART, "part_of");
exportRelations(out, tm, term, OBO.SCHEMA_TERM_DISJOINT_FROM, OBO.SCHEMA_TERM_DISJOINT_FROM, "disjoint_from");
exportRelations(out, tm, term, OBO.SCHEMA_TERM_ADJACENT_TO, OBO.SCHEMA_TERM_ADJACENT_TO, "adjacent_to");
exportRelations(out, tm, term, OBO.SCHEMA_TERM_LOCATED_IN, OBO.SCHEMA_TERM_LOCATED_IN, "located_in");
exportRelations(out, tm, term, OBO.SCHEMA_TERM_CONTAINS, OBO.SCHEMA_TERM_CONTAINED_IN, "contains");
exportRelations(out, tm, term, OBO.SCHEMA_TERM_TRANSFORMATION_OF, OBO.SCHEMA_TERM_TRANSFORMATION_OF, "transformation_of");
exportRelations(out, tm, term, OBO.SCHEMA_TERM_DERIVES_FROM, OBO.SCHEMA_TERM_DERIVES_FROM, "derives_from");
exportRelations(out, tm, term, OBO.SCHEMA_TERM_AGENT_IN, OBO.SCHEMA_TERM_AGENT_IN, "agent_in");
*/
// ******* REST OF RELATIONSHIPS *******
/*
Topic typedefType = OBO.getTypedefTopic(tm, namespace);
if(typedefType != null) {
Collection<Topic> typedefs = tm.getTopicsOfType(typedefType);
if(typedefs != null && typedefs.size() > 0) {
for(Topic typedef : typedefs) {
exportRelationships(out, tm, term, typedef.getBaseName(), OBO.SCHEMA_TERM_RELATED_TERM, typedef.getBaseName());
}
}
}
*/
// ***** IS OBSOLETE *****
Topic isObsoleteType = OBO.getObsoleteTopic(tm, namespace);
if(isObsoleteType != null) {
if(term.isOfType(isObsoleteType)) {
out.println("is_obsolete: true");
}
}
exportRelations(out, tm, term, OBO.SCHEMA_TERM_REPLACED_BY, OBO.SCHEMA_TERM_REPLACED_BY, "replaced_by");
exportRelations(out, tm, term, OBO.SCHEMA_TERM_CONSIDER_USING, OBO.SCHEMA_TERM_CONSIDER_USING, "consider");
}
}
if(forceStop()) {
return;
}
}
catch(Exception e) {
log(e);
}
}
}
else {
log("Can't find typedefs for namespace '"+namespace+"'.");
}
}
}
}
}
catch(Exception e) {
log(e);
}
}
// -------------------------------------------------------------------------
protected void exportRelationships(PrintStream out, TopicMap tm, Topic term, String atype, String arole, String modifier) {
try {
Topic atypeTopic = OBO.getTopicForSchemaTerm(tm, atype);
Topic atypeRole = OBO.getTopicForSchemaTerm(tm, arole);
if(atypeTopic != null && atypeRole != null) {
Collection<Topic> relatedTerms = TopicTools.getPlayers(term, atypeTopic, atypeRole);
if(relatedTerms != null && relatedTerms.size() > 0) {
String id = null;
String name = null;
for(Topic relatedTerm : relatedTerms) {
if(!term.mergesWithTopic(relatedTerm)) {
id = OBO.solveOBOId(relatedTerm);
name = OBO.solveOBOName(relatedTerm);
if(id != null && id.length() > 0) {
out.print("relationship: "+modifier+" "+id);
if(name != null && name.length() > 0) {
out.print(" ! "+name);
}
out.println();
}
}
}
}
}
}
catch(Exception e) {
log(e);
}
}
protected void exportRelations(PrintStream out, TopicMap tm, Topic term, String atype, String oboTerm) {
exportRelations(out, tm, term, atype, atype, oboTerm);
}
protected void exportRelations(PrintStream out, TopicMap tm, Topic term, String atype, String arole, String oboTerm) {
try {
Topic atypeTopic = OBO.getTopicForSchemaTerm(tm, atype);
Topic aroleTopic = OBO.getTopicForSchemaTerm(tm, arole);
Topic modifierRole = OBO.getTopicForSchemaTerm(tm, OBO.SCHEMA_TERM_MODIFIER);
if(atypeTopic != null && aroleTopic != null) {
Collection<Association> relations = term.getAssociations(atypeTopic);
if(relations != null && relations.size() > 0) {
String id = null;
String name = null;
String modifier = null;
if(modifierRole != null) relations = TMBox.sortAssociations(relations, OBO.LANG, modifierRole);
for(Association relation : relations) {
Topic relatedTerm = relation.getPlayer(aroleTopic);
if(relatedTerm != null && !term.mergesWithTopic(relatedTerm)) {
id = OBO.solveOBOId(relatedTerm);
name = OBO.solveOBOName(relatedTerm);
if(id != null && id.length() > 0) {
out.print(oboTerm+": ");
if(modifierRole != null) {
Topic modifierTopic = relation.getPlayer(modifierRole);
if(modifierTopic != null) {
out.print(modifierTopic.getBaseName()+" ");
}
}
out.print(id);
if(name != null && name.length() > 0) {
out.print(" ! "+name);
}
out.println();
}
}
}
}
}
}
catch(Exception e) {
log(e);
}
}
protected void exportHeaderTagValue(PrintStream out, String tag, String value) {
String values[] = null;
if(value != null && value.length() > 0) {
if(value.indexOf('\n') > -1) {
values = value.split("\n");
for(int i=0; i<values.length; i++) {
value = values[i];
if(value != null && value.length() > 0) {
out.println(tag+": "+value);
}
}
}
else {
out.println(tag+": "+value);
}
}
}
protected void exportXrefs(PrintStream out, TopicMap tm, Topic term) {
try {
if(OBO.USE_SCOPED_XREFS) {
Topic xrefType = OBO.getTopicForSchemaTerm(tm, OBO.SCHEMA_TERM_XREF);
Topic xrefScope = OBO.getTopicForSchemaTerm(tm, OBO.SCHEMA_TERM_XREF_SCOPE);
if(xrefType != null) {
Collection<Association> xrefAssociations = term.getAssociations(xrefType);
String xrefId = null;
String xrefDescription = null;
for(Association xrefAssociation : xrefAssociations) {
if(xrefAssociation != null) {
Topic xref = xrefAssociation.getPlayer(xrefType);
Topic scope = (xrefScope != null ? xrefAssociation.getPlayer(xrefScope) : null );
if(xref != null && !xref.isRemoved()) {
if(!term.mergesWithTopic(xref)) {
xrefId = OBO.solveOBOId(xref);
xrefDescription = OBO.solveOBODescription(xrefAssociation, xref);
if(xrefId != null && xrefId.length() > 0) {
boolean scopeUsed = false;
if(scope != null) {
if("ANALOG".equals(scope.getBaseName())) {
out.print("xref_analog: "+xrefId);
scopeUsed = true;
}
else if("UNKNOWN".equals(scope.getBaseName())) {
out.print("xref_unknown: "+xrefId);
scopeUsed = true;
}
}
if(!scopeUsed) {
out.print("xref: "+xrefId);
}
if(xrefDescription != null && xrefDescription.length() > 0) {
out.print(" \""+xrefDescription+"\"");
}
out.println();
}
}
}
}
}
}
}
else {
Topic xrefType = OBO.getTopicForSchemaTerm(tm, OBO.SCHEMA_TERM_XREF);
if(xrefType != null) {
Collection<Association> xrefs = term.getAssociations(xrefType); //TopicTools.getPlayers(term, OBO.getTopicForSchemaTerm(tm, OBO.SCHEMA_TERM_XREF), OBO.getTopicForSchemaTerm(tm, OBO.SCHEMA_TERM_XREF));
if(xrefs != null && xrefs.size() > 0) {
String xrefId = null;
String xrefDescription = null;
Topic xref = null;
for(Association xrefAssociation : xrefs) {
xref = xrefAssociation.getPlayer(xrefType);
if(!term.mergesWithTopic(xref)) {
xrefId = OBO.solveOBOId(xref);
xrefDescription = OBO.solveOBODescription(xrefAssociation, xref);
if(xrefId != null && xrefId.length() > 0) {
out.print("xref: "+xrefId);
if(xrefDescription != null && xrefDescription.length() > 0) {
out.print(" \""+xrefDescription+"\"");
}
out.println();
}
}
}
}
}
}
}
catch(Exception e) {
log(e);
}
}
protected void exportSynonyms(PrintStream out, TopicMap tm, Topic term) {
try {
Topic synonymAssociationType = OBO.getTopicForSchemaTerm(tm, OBO.SCHEMA_TERM_SYNONYM);
if(synonymAssociationType != null) {
Collection<Association> synonymAssociations = term.getAssociations(synonymAssociationType);
if(synonymAssociations != null && synonymAssociations.size() > 0) {
Topic synonymTypeRole = OBO.getTopicForSchemaTerm(tm, OBO.SCHEMA_TERM_SYNONYM_TYPE);
Topic synonymScopeRole = OBO.getTopicForSchemaTerm(tm, OBO.SCHEMA_TERM_SYNONYM_SCOPE);
Topic synonymTextRole = OBO.getTopicForSchemaTerm(tm, OBO.SCHEMA_TERM_SYNONYM);
Topic synonymOriginRole = OBO.getTopicForSchemaTerm(tm, OBO.SCHEMA_TERM_SYNONYM_ORIGIN);
if(OBO.COLLATE_SIMILAR_SYNONYMS) {
HashMap<String,ArrayList<Association>> groupedSynonyms = new HashMap<String,ArrayList<Association>>();
for(Association synonymAssociation : synonymAssociations) {
Topic synonymText = (synonymTextRole != null ? synonymAssociation.getPlayer(synonymTextRole) : null);
Topic synonymType = (synonymTypeRole != null ? synonymAssociation.getPlayer(synonymTypeRole) : null);
Topic synonymScope = (synonymScopeRole != null ? synonymAssociation.getPlayer(synonymScopeRole) : null);
String key = synonymText+":::"+synonymType+"::::"+synonymScope;
ArrayList<Association> synonymGroup = groupedSynonyms.get(key);
if(synonymGroup == null) {
synonymGroup = new ArrayList<Association>();
synonymGroup.add(synonymAssociation);
groupedSynonyms.put(key,synonymGroup);
}
else {
synonymGroup.add(synonymAssociation);
}
}
for(Iterator<String> groupKeys = groupedSynonyms.keySet().iterator(); groupKeys.hasNext(); ) {
HashSet usedOrigins = new HashSet();
String groupKey = groupKeys.next();
ArrayList<Association> synonymGroup = groupedSynonyms.get(groupKey);
boolean isFirst = true;
boolean scopeAndTypeProcessed = false;
boolean isFirstOrigin = true;
for(Association synonymAssociation : synonymGroup) {
Topic synonymText = (synonymTextRole != null ? synonymAssociation.getPlayer(synonymTextRole) : null);
Topic synonymType = (synonymTypeRole != null ? synonymAssociation.getPlayer(synonymTypeRole) : null);
Topic synonymScope = (synonymScopeRole != null ? synonymAssociation.getPlayer(synonymScopeRole) : null);
Topic synonymOrigin = (synonymOriginRole != null ? synonymAssociation.getPlayer(synonymOriginRole) : null);
if(isFirst) {
out.print("synonym: \""+OBO.Java2OBO(synonymText.getDisplayName(OBO.LANG))+"\"");
isFirst = false;
}
if(!scopeAndTypeProcessed) {
if(synonymScope != null) {
out.print(" "+synonymScope.getBaseName());
}
if(synonymType != null) {
out.print(" "+synonymType.getBaseName());
}
scopeAndTypeProcessed = true;
out.print(" [");
}
if(synonymOrigin != null) {
String oid = OBO.solveOBOId(synonymOrigin);
if(!usedOrigins.contains(oid)) {
usedOrigins.add(oid);
String odescription = OBO.solveOBODescription(synonymAssociation, synonymOrigin);
if(oid != null && oid.length() > 0) {
if(isFirstOrigin) {
isFirstOrigin = false;
}
else {
out.print(", ");
}
out.print(oid);
if(odescription != null && odescription.length() > 0) {
out.print(" \""+odescription+"\"");
}
}
}
}
}
out.print("]");
out.println();
}
}
else {
synonymAssociations = TMBox.sortAssociations(synonymAssociations, OBO.LANG, synonymOriginRole);
synonymAssociations = TMBox.sortAssociations(synonymAssociations, OBO.LANG, synonymTextRole);
for(Association synonymAssociation : synonymAssociations) {
Topic synonymType = (synonymTypeRole != null ? synonymAssociation.getPlayer(synonymTypeRole) : null);
Topic synonymScope = (synonymScopeRole != null ? synonymAssociation.getPlayer(synonymScopeRole) : null);
Topic synonymText = (synonymTextRole != null ? synonymAssociation.getPlayer(synonymTextRole) : null);
Topic synonymOrigin = (synonymOriginRole != null ? synonymAssociation.getPlayer(synonymOriginRole) : null);
if(synonymText != null) {
out.print("synonym: \""+OBO.Java2OBO(synonymText.getDisplayName(OBO.LANG))+"\"");
if(synonymScope != null) {
out.print(" "+synonymScope.getBaseName());
}
if(synonymType != null) {
out.print(" "+synonymType.getBaseName());
}
out.print(" [");
boolean isFirst = true;
if(synonymOrigin != null) {
String oid = OBO.solveOBOId(synonymOrigin);
String odescription = OBO.solveOBODescription(synonymAssociation, synonymOrigin);
if(oid != null && oid.length() > 0) {
if(isFirst) {
isFirst = false;
}
else {
out.print(", ");
}
out.print(oid);
if(odescription != null && odescription.length() > 0) {
out.print(" \""+odescription+"\"");
}
}
}
out.print("]");
out.println();
}
}
}
}
}
}
catch(Exception e) {
log(e);
}
}
protected void exportCreatorAndCreationDate(PrintStream out, TopicMap tm, Topic term) {
try {
Topic creatorTypeTopic = OBO.getTopicForSchemaTerm(tm, OBO.SCHEMA_TERM_CREATED_BY);
if(creatorTypeTopic != null) {
Collection<Association> creatorRelations = term.getAssociations(creatorTypeTopic);
if(creatorRelations != null) {
for(Association creatorRelation : creatorRelations) {
Topic creatorTopic = creatorRelation.getPlayer(creatorTypeTopic);
if(creatorTopic != null) {
String creatorName = OBO.solveOBOName(creatorTopic);
if(creatorName != null && creatorName.trim().length() > 0) {
out.println("created_by: "+creatorName+ " ! " +creatorName);
}
}
}
}
}
Topic creationDateType = OBO.getTopicForSchemaTerm(tm, OBO.SCHEMA_TERM_CREATION_DATE);
if(creationDateType != null) {
String creationDate = term.getData(creationDateType, OBO.LANG);
if(creationDate != null) {
creationDate = OBO.Java2OBOLite(creationDate);
out.println("creation_date: "+creationDate);
}
}
}
catch(Exception e) {
log(e);
}
}
protected void exportComment(PrintStream out, TopicMap tm, Topic term) {
try {
Topic commentType = OBO.getTopicForSchemaTerm(tm, OBO.SCHEMA_TERM_COMMENT);
if(commentType != null) {
String comment = term.getData(commentType, OBO.LANG);
if(comment != null) {
comment = OBO.Java2OBOLite(comment);
out.println("comment: "+comment);
}
}
}
catch(Exception e) {
log(e);
}
}
protected void exportAltIds(PrintStream out, TopicMap tm, Topic term, String id) {
try {
if(OBO.MAKE_SIS_FROM_ALT_IDS) {
Collection<Locator> sis = term.getSubjectIdentifiers();
if(sis != null && sis.size() > 1) {
String ls = null;
String altId = null;
for(Locator l : sis) {
altId = OBO.solveOBOId(l);
if(altId != null && altId.length() > 0) {
if(!altId.equals(id))
out.println("alt_id: "+altId);
}
}
}
}
else {
exportRelations(out, tm, term, OBO.SCHEMA_TERM_ALTERNATIVE_ID, "alt_id");
}
}
catch(Exception e) {
log(e);
}
}
protected void exportDefinition(PrintStream out, TopicMap tm, Topic term) {
try {
Topic definitionType = OBO.getTopicForSchemaTerm(tm, OBO.SCHEMA_TERM_DEFINITION);
if(definitionType != null) {
String definition = term.getData(definitionType, OBO.LANG);
if(definition != null) {
definition = OBO.Java2OBOLite(definition);
out.print("def: \""+definition+"\"");
Topic defOriginType = OBO.getTopicForSchemaTerm(tm, OBO.SCHEMA_TERM_DEFINITION_ORIGIN);
out.print(" [");
if(defOriginType != null) {
Collection<Association> definitionOrigins = term.getAssociations(defOriginType); // TopicTools.getPlayers(term, , OBO.getTopicForSchemaTerm(tm, OBO.SCHEMA_TERM_DEFINITION_ORIGIN)).toArray( new Topic[] {} );
if(definitionOrigins.size()>0) {
boolean isFirst = true;
Topic dot = null;
String doid = null;
String dodescription = null;
for(Association defOrigin : definitionOrigins) {
dot = defOrigin.getPlayer(defOriginType);
doid = OBO.solveOBOId(dot);
dodescription = OBO.solveOBODescription(defOrigin, dot);
if(doid != null && doid.length() > 0) {
if(isFirst) {
isFirst = false;
}
else {
out.print(", ");
}
out.print(doid);
if(dodescription != null && dodescription.length() > 0) {
dodescription = OBO.Java2OBOLite(dodescription);
out.print(" \""+dodescription+"\"");
}
}
}
}
}
out.print("]");
out.println();
}
}
}
catch(Exception e) {
log(e);
}
}
protected void exportProperties(PrintStream out, TopicMap tm, Topic term) {
try {
}
catch(Exception e) {
log(e);
}
}
}
| 54,420 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
GMLExport.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/exporters/GMLExport.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* GMLExport.java
*
* Created on 21.4.2008, 11:05
*
*/
package org.wandora.application.tools.exporters;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import javax.swing.Icon;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.WandoraToolLogger;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.UIBox;
import org.wandora.application.gui.UIConstants;
import org.wandora.application.gui.simple.SimpleFileChooser;
import org.wandora.application.tools.GenericOptionsDialog;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.utils.IObox;
/**
* <p>Exports selected topic map in Wandora as GML (Graph Modelling Language) graph file. See
* http://www.infosun.fim.uni-passau.de/Graphlet/GML/ or
* http://en.wikipedia.org/wiki/Graph_Modelling_Language
* for more info about GML graph format.</p>
* <p>
* Note that GML graph file format is rather simple and can't represent all
* details of Topic maps. Export converts all topics and occurrences as graph
* nodes. All associations are exported as graph edges. If association has more
* than two players, an itermediator node is added to link all players.
* </p>
* <p>
* Lots of Topic map information is lost in export. Export doesn't convert
* subject locators, subject identifiers, different variant names, association
* roles, occurrence scopes etc.
* </p>
* <p>
* Purpose of the export feature is to enable topic map visualization in GML
* supporting applications such as Cytoscape or yEd.
* </p>
*
* @author akivela
*/
public class GMLExport extends AbstractExportTool implements WandoraTool {
private static final long serialVersionUID = 1L;
public boolean EXPORT_SELECTION_INSTEAD_TOPIC_MAP = false;
public static boolean EXPORT_CLASSES = true;
public static boolean EXPORT_OCCURRENCES = true;
public static boolean EXPORT_N_ASSOCIATIONS = true;
public static boolean EXPORT_DIRECTED = false;
public GMLExport() {
}
public GMLExport(boolean exportSelection) {
EXPORT_SELECTION_INSTEAD_TOPIC_MAP = exportSelection;
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/export_graph.png");
}
@Override
public boolean requiresRefresh() {
return false;
}
@Override
public boolean isConfigurable(){
return true;
}
@Override
public void configure(Wandora wandora,org.wandora.utils.Options options,String prefix) throws TopicMapException {
GenericOptionsDialog god=new GenericOptionsDialog(wandora,"GML export options","GML export options",true,new String[][]{
new String[]{"Export classes","boolean",(EXPORT_CLASSES ? "true" : "false"),"Should Wandora export also topic types (class-instance relations)?"},
new String[]{"Export occurrences","boolean",(EXPORT_OCCURRENCES ? "true" : "false"),"Should topic occurrences also export?"},
new String[]{"Export n associations","boolean",(EXPORT_N_ASSOCIATIONS ? "true" : "false"), "Should associations with more than 2 players also export?"},
new String[]{"Is directed","boolean",(EXPORT_DIRECTED ? "true" : "false"), "Export directed or undirected graph" },
},wandora);
god.setVisible(true);
if(god.wasCancelled()) return;
Map<String, String> values = god.getValues();
EXPORT_CLASSES = ("true".equals(values.get("Export classes")) ? true : false );
EXPORT_OCCURRENCES = ("true".equals(values.get("Export occurrences")) ? true : false );
EXPORT_N_ASSOCIATIONS = ("true".equals(values.get("Export n associations")) ? true : false );
EXPORT_DIRECTED = ("true".equals(values.get("Is directed")) ? true : false );
}
@Override
public void execute(Wandora wandora, Context context) {
String topicMapName = null;
String exportInfo = null;
// --- Solve first topic map to be exported
TopicMap tm = null;
if(EXPORT_SELECTION_INSTEAD_TOPIC_MAP) {
tm = makeTopicMapWith(context);
exportInfo = "Exporting selected topics as GML graph";
topicMapName = "selection_in_wandora";
}
else {
tm = solveContextTopicMap(wandora, context);
topicMapName = this.solveNameForTopicMap(wandora, tm);
if(topicMapName != null) {
exportInfo = "Exporting topic map in layer '" + topicMapName + "' as GML graph";
}
else {
exportInfo = "Exporting topic map as GML graph";
topicMapName = "no_name_topic_map";
}
}
// --- Then solve target file (and format)
SimpleFileChooser chooser=UIConstants.getFileChooser();
chooser.setDialogTitle(exportInfo+"...");
if(chooser.open(wandora, "Export")==SimpleFileChooser.APPROVE_OPTION){
setDefaultLogger();
File file = chooser.getSelectedFile();
String fileName = file.getName();
// --- Finally write topicmap as GML to chosen file
OutputStream out = null;
try {
file = IObox.addFileExtension(file, "gml"); // Ensure file extension exists!
fileName = file.getName(); // Updating filename if file has changed!
out = new FileOutputStream(file);
log(exportInfo+" to '"+fileName+"'.");
exportGTM(out, tm, topicMapName, getCurrentLogger());
out.close();
log("Ready.");
}
catch(Exception e) {
log(e);
try { if(out != null) out.close(); }
catch(Exception e2) { log(e2); }
}
}
setState(WAIT);
}
@Override
public String getName() {
return "Export GML graph";
}
@Override
public String getDescription() {
return "Exports topic map layer as Graph Modelling Language (GML) file.";
}
public void exportGTM(OutputStream out, TopicMap topicMap, String graphName, WandoraToolLogger logger) throws TopicMapException {
if(logger == null) logger = this;
PrintWriter writer = null;
try {
writer=new PrintWriter(new OutputStreamWriter(out, "ISO-8859-1"));
}
catch(Exception e) {
log("Unable to use ISO-8859-1 charset. Using default charset.");
writer=new PrintWriter(new OutputStreamWriter(out));
}
int totalCount = 2*topicMap.getNumTopics() + topicMap.getNumAssociations();
logger.setProgressMax(totalCount);
int count = 0;
writer.println("Creator \"Wandora GTM Export\"");
writer.println("graph [");
writer.println(" label "+makeString(graphName));
writer.println(" directed "+(EXPORT_DIRECTED ? 0 : 1));
Iterator<Topic> topicIter=topicMap.getTopics();
while(topicIter.hasNext() && !logger.forceStop()) {
Topic t=(Topic)topicIter.next();
if(t.isRemoved()) continue;
logger.setProgress(count++);
echoNode(t, writer);
// Topic occurrences....
if(EXPORT_OCCURRENCES && t.getDataTypes().size()>0){
Collection<Topic> types=t.getDataTypes();
Iterator<Topic> typeTopicIter=types.iterator();
while(typeTopicIter.hasNext()){
Topic type=(Topic)typeTopicIter.next();
Hashtable<Topic,String> ht=t.getData(type);
Iterator<Map.Entry<Topic, String>> occurrenceEntryIter=ht.entrySet().iterator();
while(occurrenceEntryIter.hasNext()){
Map.Entry<Topic,String> e=occurrenceEntryIter.next();
String data=(String)e.getValue();
echoNode(data, writer);
echoEdge(t, data, type, writer);
//System.out.println("occurrence:"+data);
}
}
}
}
// Topic types....
if(EXPORT_CLASSES && !logger.forceStop()) {
topicIter=topicMap.getTopics();
while(topicIter.hasNext() && !logger.forceStop()) {
Topic t=(Topic)topicIter.next();
if(t.isRemoved()) continue;
logger.setProgress(count++);
if(t.getTypes().size()>0){
Iterator<Topic> typeTopicIter=t.getTypes().iterator();
while(typeTopicIter.hasNext()){
Topic t2=(Topic)typeTopicIter.next();
if(t2.isRemoved()) continue;
echoEdge(t2, t, "class-instance", writer);
}
}
}
}
// Associations....
if(!logger.forceStop()) {
Iterator<Association> associationIter=topicMap.getAssociations();
int icount=0;
while(associationIter.hasNext() && !logger.forceStop()) {
logger.setProgress(count++);
Association a=(Association)associationIter.next();
Collection<Topic> roles = a.getRoles();
if(roles.size() < 2) continue;
else if(roles.size() == 2) {
Topic[] roleArray = (Topic[]) roles.toArray(new Topic[2]);
echoEdge(a.getPlayer(roleArray[0]), a.getPlayer(roleArray[1]), a.getType(), writer);
}
else {
if(EXPORT_N_ASSOCIATIONS) {
icount++;
String target="nameless-intermediator-node-"+icount;
echoNode(target, writer);
Iterator<Topic> roleTopicIter = roles.iterator();
while(roleTopicIter.hasNext()) {
Topic role=(Topic)roleTopicIter.next();
echoEdge(a.getPlayer(role), target, a.getType(), writer);
}
}
}
}
}
writer.println("]"); // graph
writer.flush();
writer.close();
}
// --------------------------------------------------------------- ECHOS ---
protected void echoNode(Topic t, PrintWriter writer) throws TopicMapException {
String label = t.getBaseName();
if(label == null) label = t.getOneSubjectIdentifier().toExternalForm();
echoNode(makeID(t), null, label, writer);
}
protected void echoNode(String data, PrintWriter writer) {
echoNode(makeID(data), null, data, writer);
}
protected void echoNode(int id, String name, String label, PrintWriter writer) {
if(writer == null || (id <= 0 && name == null)) return;
writer.println(" node [");
if(id > 0) writer.println(" id "+id);
if(name != null) writer.println(" name "+makeString(name));
if(label != null) writer.println(" label "+makeString(label));
writer.println(" ]");
}
protected void echoEdge(Topic source, Topic target, String label, PrintWriter writer) throws TopicMapException {
writer.println(" edge [");
if(label != null) writer.println(" label "+makeString(label));
writer.println(" source "+makeID(source));
writer.println(" target "+makeID(target));
writer.println(" ]");
}
protected void echoEdge(String source, String target, String label, PrintWriter writer) {
writer.println(" edge [");
if(label != null) writer.println(" label "+makeString(label));
writer.println(" source "+makeID(source));
writer.println(" target "+makeID(target));
writer.println(" ]");
}
protected void echoEdge(Topic source, String target, Topic label, PrintWriter writer) throws TopicMapException {
String l = label.getBaseName();
if(l == null) l = label.getOneSubjectIdentifier().toExternalForm();
writer.println(" edge [");
if(l != null) writer.println(" label "+makeString(l));
writer.println(" source "+makeID(source));
writer.println(" target "+makeID(target));
writer.println(" ]");
}
protected void echoEdge(Topic source, Topic target, Topic label, PrintWriter writer) throws TopicMapException {
String l = label.getBaseName();
if(l == null) l = label.getOneSubjectIdentifier().toExternalForm();
echoEdge(source, target, l, writer);
}
protected int makeID(Topic t) {
int id = t.hashCode();
if(id < 0) return 2*Math.abs(id)+1;
else return 2*Math.abs(id);
}
protected int makeID(String s) {
int id = s.hashCode();
if(id < 0) return 2*Math.abs(id)+1;
else return 2*Math.abs(id);
}
protected String makeString(String s) {
if(s == null) return null;
s = s.substring(0,Math.min(s.length(), 240));
s = s.replaceAll("\\\n", " ");
s = s.replaceAll("\\\r", "");
s = s.replaceAll("\\&", "&");
s = s.replaceAll("\\\"", """);
return "\""+s+"\"";
}
}
| 14,575 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
ExportSchemaMap.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/exporters/ExportSchemaMap.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* ExportSchemaMap.java
*
* Created on August 26, 2004, 2:59 PM
*/
package org.wandora.application.tools.exporters;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import javax.swing.Icon;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.UIBox;
import org.wandora.application.gui.UIConstants;
import org.wandora.application.gui.simple.SimpleFileChooser;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.SchemaBox;
import org.wandora.topicmap.TMBox;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicInUseException;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.topicmap.XTMPSI;
import org.wandora.utils.IObox;
/**
*
* @author olli
*/
public class ExportSchemaMap extends AbstractExportTool implements WandoraTool {
private static final long serialVersionUID = 1L;
public static String[] exportTypes=new String[]{
SchemaBox.CONTENTTYPE_SI,
SchemaBox.ASSOCIATIONTYPE_SI,
SchemaBox.OCCURRENCETYPE_SI,
SchemaBox.ROLE_SI,
SchemaBox.ROLECLASS_SI,
XTMPSI.LANGUAGE,
XTMPSI.SUPERCLASS_SUBCLASS,
XTMPSI.DISPLAY,
XTMPSI.OCCURRENCE,
XTMPSI.SORT,
XTMPSI.TOPIC,
XTMPSI.SUPERCLASS,
XTMPSI.SUBCLASS,
XTMPSI.CLASS,
XTMPSI.CLASS_INSTANCE,
XTMPSI.INSTANCE
};
/**
* Creates a new instance of ExportSchemaMap
*/
public ExportSchemaMap() {
}
@Override
public String getName() {
return "Export schema topic map";
}
@Override
public String getDescription() {
return "Export schema topic map";
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/export_topicmap_schema.png");
}
@Override
public boolean requiresRefresh() {
return false;
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
SimpleFileChooser chooser = UIConstants.getFileChooser();
chooser.setDialogTitle("Export Wandora schema...");
if(chooser.open(wandora, "Export")==SimpleFileChooser.APPROVE_OPTION){
setDefaultLogger();
File file = chooser.getSelectedFile();
try{
file = IObox.addFileExtension(file, "xtm"); // Ensure file extension exists!
TopicMap topicMap = solveContextTopicMap(wandora, context);
TopicMap schemaTopicMap = exportTypeDefs(topicMap);
String name = solveNameForTopicMap(wandora, topicMap);
if(name != null) {
log("Exporting Wandora schema topics of layer '"+ name +"' to '"+ file.getName() + "'.");
}
else {
log("Exporting Wandora schema topics to '"+ file.getName() + "'.");
}
OutputStream out = new FileOutputStream(file);
schemaTopicMap.exportXTM(out);
out.close();
log("Ready.");
}
catch(IOException e) {
log(e);
}
setState(WAIT);
}
}
public static TopicMap exportTypeDefs(TopicMap tm) throws TopicMapException {
TopicMap export=new org.wandora.topicmap.memory.TopicMapImpl();
Set<Topic> copyTypes=new LinkedHashSet<>();
for(int i=0;i<exportTypes.length;i++){
Topic t=tm.getTopic(exportTypes[i]);
if(t==null) {
continue;
}
copyTypes.add(t);
}
Set<Topic> copied=new LinkedHashSet<>();
Iterator<Topic> iter=copyTypes.iterator();
while(iter.hasNext()){
Topic type=iter.next();
Iterator<Topic> iter2=tm.getTopicsOfType(type).iterator();
while(iter2.hasNext()){
Topic topic=iter2.next();
if(!copied.contains(topic)){
export.copyTopicIn(topic,false);
Iterator<Association> iter3=topic.getAssociations().iterator();
while(iter3.hasNext()){
Association a=iter3.next();
if(copyTypes.contains(a.getType())){
export.copyAssociationIn(a);
}
}
copied.add(topic);
}
}
}
copyTypes=new LinkedHashSet<>();
for(int i=0;i<exportTypes.length;i++){
Topic t=export.getTopic(exportTypes[i]);
if(t==null) {
continue;
}
copyTypes.add(t);
}
Topic wandoraClass=export.getTopic(TMBox.WANDORACLASS_SI);
Topic hideLevel=export.getTopic(TMBox.HIDELEVEL_SI);
iter=export.getTopics();
while(iter.hasNext()){
Topic t=(Topic)iter.next();
Iterator<Set<Topic>> iter2=new ArrayList<>(t.getVariantScopes()).iterator();
while(iter2.hasNext()){
Set<Topic> scope=iter2.next();
t.removeVariant(scope);
}
Iterator<Topic> iter2b=new ArrayList<>(t.getDataTypes()).iterator();
while(iter2b.hasNext()){
Topic type=iter2b.next();
if(type!=hideLevel){
t.removeData(type);
}
}
Iterator<Topic> iter2c=new ArrayList<>(t.getTypes()).iterator();
while(iter2c.hasNext()){
Topic type=iter2c.next();
if(!copyTypes.contains(type) && type!=wandoraClass) {
t.removeType(type);
}
}
}
iter=export.getTopics();
List<Topic> v=new ArrayList<>();
while(iter.hasNext()){
Topic t=iter.next();
if(t.getAssociations().isEmpty() && export.getTopicsOfType(t).isEmpty()){
v.add(t);
}
}
iter=v.iterator();
while(iter.hasNext()){
Topic t=iter.next();
try{
t.remove();
}catch(TopicInUseException tiue){}
}
TMBox.getOrCreateTopic(export,XTMPSI.getLang("fi"));
TMBox.getOrCreateTopic(export,XTMPSI.getLang("en"));
TMBox.getOrCreateTopic(export,XTMPSI.DISPLAY);
TMBox.getOrCreateTopic(export,XTMPSI.SORT);
TMBox.getOrCreateTopic(export,TMBox.LANGINDEPENDENT_SI);
return export;
}
}
| 7,728 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AdjacencyMatrixExport.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/exporters/AdjacencyMatrixExport.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* AdjacencyMatrixExport.java
*
*/
package org.wandora.application.tools.exporters;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import javax.swing.Icon;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.WandoraToolLogger;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.UIBox;
import org.wandora.application.gui.UIConstants;
import org.wandora.application.gui.simple.SimpleFileChooser;
import org.wandora.application.tools.GenericOptionsDialog;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.TMBox;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.utils.IObox;
/**
*
* @author akivela
*/
public class AdjacencyMatrixExport extends AbstractExportTool implements WandoraTool {
private static final long serialVersionUID = 1L;
public static boolean COUNT_CLASSES = true;
public static boolean COUNT_INSTANCES = true;
public static boolean COUNT_ASSOCIATIONS = true;
public static boolean LABEL_MATRIX = true;
public static boolean BINARY_CELL_VALUE = false;
public static boolean EXPORT_AS_HTML_TABLE = true;
public static boolean SORT_COLUMNS = true;
public boolean EXPORT_SELECTION_INSTEAD_TOPIC_MAP = false;
public AdjacencyMatrixExport() {
}
public AdjacencyMatrixExport(boolean exportSelection) {
EXPORT_SELECTION_INSTEAD_TOPIC_MAP = exportSelection;
}
@Override
public boolean requiresRefresh() {
return false;
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/export_adjacency_matrix.png");
}
@Override
public boolean isConfigurable(){
return true;
}
@Override
public void configure(Wandora wandora,org.wandora.utils.Options options,String prefix) throws TopicMapException {
GenericOptionsDialog god=new GenericOptionsDialog(wandora,"Adjacency matrix export options","Adjacency matrix export options",true,new String[][]{
new String[]{"Count classes","boolean",(COUNT_CLASSES ? "true" : "false"),"Should Wandora count classes?"},
new String[]{"Count instances","boolean",(COUNT_INSTANCES ? "true" : "false"),"Should Wandora count instances?"},
new String[]{"Count associations","boolean",(COUNT_ASSOCIATIONS ? "true" : "false"), "Should Wandora count associations?"},
new String[]{"Label matrix columns and rows","boolean",(LABEL_MATRIX ? "true" : "false"), "Should Wandora label matrix columns and rows using topic names?"},
new String[]{"Export as HTML table","boolean",(EXPORT_AS_HTML_TABLE ? "true" : "false"), "Export HTML table instead of tab text?"},
},wandora);
god.setVisible(true);
if(god.wasCancelled()) return;
Map<String, String> values = god.getValues();
COUNT_CLASSES = ("true".equals(values.get("Count classes")) ? true : false );
COUNT_INSTANCES = ("true".equals(values.get("Count instances")) ? true : false );
COUNT_ASSOCIATIONS = ("true".equals(values.get("Count associations")) ? true : false );
LABEL_MATRIX = ("true".equals(values.get("Label matrix columns and rows")) ? true : false );
BINARY_CELL_VALUE = ("true".equals(values.get("Binary (0 or 1) matrix cell values")) ? true : false );
EXPORT_AS_HTML_TABLE = ("true".equals(values.get("Export as HTML table")) ? true : false );
}
@Override
public void execute(Wandora wandora, Context context) {
Iterator<Topic> topics = null;
String exportInfo = "";
try {
if(EXPORT_SELECTION_INSTEAD_TOPIC_MAP) {
topics = context.getContextObjects();
exportInfo = "selected topics";
}
else {
// --- Solve first topic map to be exported
TopicMap tm = solveContextTopicMap(wandora, context);
String topicMapName = this.solveNameForTopicMap(wandora, tm);
topics = tm.getTopics();
if(topicMapName == null) exportInfo = "LayerStack";
if(topicMapName != null) exportInfo = "topic map in layer '" + topicMapName + "'";
}
// --- Then solve target file (and format)
SimpleFileChooser chooser=UIConstants.getFileChooser();
chooser.setDialogTitle("Export "+exportInfo+" as adjacency matrix...");
if(chooser.open(wandora, "Export")==SimpleFileChooser.APPROVE_OPTION){
setDefaultLogger();
File file = chooser.getSelectedFile();
String fileName = file.getName();
// --- Finally write topic map to chosen file
OutputStream out=null;
try {
if(EXPORT_AS_HTML_TABLE)
file=IObox.addFileExtension(file, "html");
else
file=IObox.addFileExtension(file, "txt");
fileName = file.getName(); // Updating filename if file has changed!
out=new FileOutputStream(file);
log("Exporting topics as adjacency matrix to '"+fileName+"'.");
exportMatrix(out, topics, getCurrentLogger());
out.close();
log("OK");
}
catch(Exception e) {
log(e);
try { if(out != null) out.close(); }
catch(Exception e2) { log(e2); }
}
}
}
catch(Exception e) {
log(e);
}
setState(WAIT);
}
@Override
public String getName() {
return "Export adjacency matrix";
}
@Override
public String getDescription() {
return "Exports topic map as adjacency matrix.";
}
public void exportMatrix(OutputStream out, Iterator<Topic> topicIterator, WandoraToolLogger logger) throws TopicMapException {
if(logger == null) logger = this;
PrintWriter writer = null;
try {
writer = new PrintWriter(new OutputStreamWriter(out, "ISO-8859-1"));
}
catch (UnsupportedEncodingException ex) {
log("Exception while trying ISO-8859-1 character encoding. Using default encoding");
writer = new PrintWriter(new OutputStreamWriter(out));
}
int totalCount = 0;
ArrayList<Topic> topics = new ArrayList<Topic>();
Topic t = null;
log("Collecting topics...");
while(topicIterator.hasNext() && !logger.forceStop()) {
t = topicIterator.next();
if(t != null && !t.isRemoved()) {
topics.add(t);
totalCount++;
}
}
if(SORT_COLUMNS) {
log("Sorting topic collection...");
Collections.sort(topics, new TMBox.TopicNameComparator(null));
}
totalCount = totalCount * totalCount;
logger.setProgressMax(totalCount);
// And finally export....
log("Exporting adjacency matrix...");
if(EXPORT_AS_HTML_TABLE) {
exportMatrixAsHTMLTable(writer, topics, logger);
}
else {
exportMatrixAsTabText(writer, topics, logger);
}
writer.flush();
writer.close();
}
public void exportMatrixAsTabText(PrintWriter writer, ArrayList<Topic> topics, WandoraToolLogger logger) throws TopicMapException {
int progress = 0;
Topic t1 = null;
Topic t2 = null;
int connections = 0;
if(LABEL_MATRIX) {
print(writer, "\t");
for(int i=0; i<topics.size() && !logger.forceStop(); i++) {
print(writer, makeString(topics.get(i))+"\t");
}
print(writer, "\n");
}
for(int i=0; i<topics.size() && !logger.forceStop(); i++) {
t1=topics.get(i);
if(LABEL_MATRIX) {
print(writer, makeString(topics.get(i))+"\t");
}
for(int j=0; j<topics.size() && !logger.forceStop(); j++) {
t2=topics.get(j);
if(BINARY_CELL_VALUE) {
connections = hasConnections(t1, t2);
}
else {
connections = countAllConnections(t1, t2);
}
print(writer, connections+"\t");
setProgress(progress++);
}
print(writer, "\n");
}
}
public void exportMatrixAsHTMLTable(PrintWriter writer, ArrayList<Topic> topics, WandoraToolLogger logger) throws TopicMapException {
int progress = 0;
Topic t1 = null;
Topic t2 = null;
int connections = 0;
print(writer, "<table border=1>");
if(LABEL_MATRIX) {
print(writer, "<tr><td> </td>");
for(int i=0; i<topics.size() && !logger.forceStop(); i++) {
print(writer, "<td>"+makeString(topics.get(i))+"</td>");
}
print(writer, "</tr>\n");
}
for(int i=0; i<topics.size() && !logger.forceStop(); i++) {
print(writer, "<tr>");
t1=topics.get(i);
if(LABEL_MATRIX) {
print(writer, "<td>"+makeString(topics.get(i))+"</td>");
}
for(int j=0; j<topics.size() && !logger.forceStop(); j++) {
t2=topics.get(j);
if(BINARY_CELL_VALUE) {
connections = hasConnections(t1, t2);
}
else {
connections = countAllConnections(t1, t2);
}
print(writer, "<td>"+connections+"</td>");
setProgress(progress++);
}
print(writer, "</tr>\n");
}
print(writer, "</table>");
}
// -------------------------------------------------------------------------
public int countAllConnections(Topic t1, Topic t2) {
int count = 0;
try {
// Class...
if(COUNT_CLASSES && t1.isOfType(t2)) count++;
// Instance...
if(COUNT_INSTANCES && t2.isOfType(t1)) count++;
// Associations...
if(COUNT_ASSOCIATIONS) {
Collection<Association> as = t1.getAssociations();
Association a = null;
for(Iterator<Association> asIterator=as.iterator(); asIterator.hasNext(); ) {
a = asIterator.next();
Collection<Topic> roles = a.getRoles();
Topic role = null;
Topic player = null;
int countA = 0;
for(Iterator<Topic> roleIterator = roles.iterator(); roleIterator.hasNext(); ) {
role = roleIterator.next();
player = a.getPlayer(role);
if(player != null) {
if(player.mergesWithTopic(t2)) {
countA++;
}
}
}
if(t1.mergesWithTopic(t2) && countA > 0) countA--;
count += countA;
}
}
}
catch(Exception e) {
log(e);
}
return count;
}
public int hasConnections(Topic t1, Topic t2) {
try {
// Class...
if(COUNT_CLASSES && t1.isOfType(t2)) return 1;
// Instance...
if(COUNT_INSTANCES && t2.isOfType(t1)) return 1;
// Associations...
if(COUNT_ASSOCIATIONS) {
Collection<Association> as = t1.getAssociations();
Association a = null;
for(Iterator<Association> asIterator=as.iterator(); asIterator.hasNext(); ) {
a = asIterator.next();
Collection<Topic> roles = a.getRoles();
Topic role = null;
Topic player = null;
for(Iterator<Topic> roleIterator = roles.iterator(); roleIterator.hasNext(); ) {
role = roleIterator.next();
player = a.getPlayer(role);
if(player != null) {
if(player.mergesWithTopic(t2)) {
return 1;
}
}
}
}
}
}
catch(Exception e) {
log(e);
}
return 0;
}
protected String makeString(Topic t) throws TopicMapException {
if(t == null) return null;
String s = t.getBaseName();
if(s == null) s = t.getOneSubjectIdentifier().toExternalForm();
return s;
}
// -------------------------------------------------------------------------
// Elementary print methods are used to ensure output is ISO-8859-1
protected void print(PrintWriter writer, String str) {
writer.print(str);
}
protected void println(PrintWriter writer, String str) {
writer.println(str);
}
}
| 14,468 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
GraphMLExport.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/exporters/GraphMLExport.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* GraphMLExport.java
*
*/
package org.wandora.application.tools.exporters;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import javax.swing.Icon;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.WandoraToolLogger;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.UIBox;
import org.wandora.application.gui.UIConstants;
import org.wandora.application.gui.simple.SimpleFileChooser;
import org.wandora.application.tools.GenericOptionsDialog;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.utils.IObox;
/**
* <p>Exports selected topic map in Wandora as GraphML file. See
* http://graphml.graphdrawing.org/ or
* http://en.wikipedia.org/wiki/GraphML
* for more info about GraphML format.</p>
* <p>
* Note that the GraphML file format is rather simple and can't represent all
* details of Topic Maps. Export converts all topics and occurrences as graph
* nodes. All associations are exported as graph edges. If association has more
* than two players, an intermediator node is added to link all players.
* </p>
* <p>
* Export doesn't convert subject locators, subject identifiers, different
* variant names, association roles, occurrence scopes etc.
* </p>
* <p>
* Purpose of the export feature is to enable topic map visualization in GraphML
* supporting applications such as yEd.
* </p>
*
* @author akivela
*/
public class GraphMLExport extends AbstractExportTool implements WandoraTool {
private static final long serialVersionUID = 1L;
public boolean EXPORT_SELECTION_INSTEAD_TOPIC_MAP = false;
public static boolean EXPORT_CLASSES = true;
public static boolean EXPORT_OCCURRENCES = true;
public static boolean EXPORT_N_ASSOCIATIONS = true;
public static boolean EXPORT_DIRECTED = false;
public GraphMLExport() {
}
public GraphMLExport(boolean exportSelection) {
EXPORT_SELECTION_INSTEAD_TOPIC_MAP = exportSelection;
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/export_graph.png");
}
@Override
public boolean requiresRefresh() {
return false;
}
@Override
public boolean isConfigurable(){
return true;
}
@Override
public void configure(Wandora wandora,org.wandora.utils.Options options,String prefix) throws TopicMapException {
GenericOptionsDialog god=new GenericOptionsDialog(wandora,"GraphML Export options","GraphML Export options",true,new String[][]{
new String[]{"Export classes","boolean",(EXPORT_CLASSES ? "true" : "false"),"Should topic classes also export?"},
new String[]{"Export occurrences","boolean",(EXPORT_OCCURRENCES ? "true" : "false"),"Should topic occurrences also export?"},
new String[]{"Export n associations","boolean",(EXPORT_N_ASSOCIATIONS ? "true" : "false"), "Should associations with more than 2 players also export?"},
new String[]{"Is directed","boolean",(EXPORT_DIRECTED ? "true" : "false"), "Export directed or undirected graph" },
},wandora);
god.setVisible(true);
if(god.wasCancelled()) return;
Map<String, String> values = god.getValues();
EXPORT_CLASSES = ("true".equals(values.get("Export classes")) ? true : false );
EXPORT_OCCURRENCES = ("true".equals(values.get("Export occurrences")) ? true : false );
EXPORT_N_ASSOCIATIONS = ("true".equals(values.get("Export n associations")) ? true : false );
EXPORT_DIRECTED = ("true".equals(values.get("Is directed")) ? true : false );
}
@Override
public void execute(Wandora wandora, Context context) {
String topicMapName = null;
String exportInfo = null;
// --- Solve first topic map to be exported
TopicMap tm = null;
if(EXPORT_SELECTION_INSTEAD_TOPIC_MAP) {
tm = makeTopicMapWith(context);
exportInfo = "Exporting selected topics as GraphML graph";
topicMapName = "selection_in_wandora";
}
else {
tm = solveContextTopicMap(wandora, context);
topicMapName = this.solveNameForTopicMap(wandora, tm);
if(topicMapName != null) {
exportInfo = "Exporting topic map in layer '" + topicMapName + "' as GraphML graph";
}
else {
exportInfo = "Exporting topic map as GraphML graph";
topicMapName = "no_name_topic_map";
}
}
// --- Then solve target file (and format)
SimpleFileChooser chooser=UIConstants.getFileChooser();
chooser.setDialogTitle(exportInfo+"...");
if(chooser.open(wandora, "Export")==SimpleFileChooser.APPROVE_OPTION){
setDefaultLogger();
File file = chooser.getSelectedFile();
String fileName = file.getName();
// --- Finally write topicmap as GML to chosen file
OutputStream out = null;
try {
file = IObox.addFileExtension(file, "graphml"); // Ensure file extension exists!
fileName = file.getName(); // Updating filename if file has changed!
out = new FileOutputStream(file);
log(exportInfo+" to '"+fileName+"'.");
exportGraphML(out, tm, topicMapName, getCurrentLogger());
out.close();
log("Ready.");
}
catch(Exception e) {
log(e);
try { if(out != null) out.close(); }
catch(Exception e2) { log(e2); }
}
}
setState(WAIT);
}
@Override
public String getName() {
return "Export GraphML graph";
}
@Override
public String getDescription() {
return "Exports topic map layer as GraphML file.";
}
public void exportGraphML(OutputStream out, TopicMap topicMap, String graphName, WandoraToolLogger logger) throws TopicMapException {
if(logger == null) logger = this;
PrintWriter writer = null;
try {
writer = new PrintWriter(new OutputStreamWriter(out, "ISO-8859-1"));
}
catch (UnsupportedEncodingException ex) {
log("Exception while instantiating PrintWriter with ISO-8859-1 character encoding. Using default encoding.");
writer = new PrintWriter(new OutputStreamWriter(out));
}
int totalCount = 2*topicMap.getNumTopics() + topicMap.getNumAssociations();
logger.setProgressMax(totalCount);
int count = 0;
println(writer, "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
println(writer, "<graphml xmlns=\"http://graphml.graphdrawing.org/xmlns\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://graphml.graphdrawing.org/xmlns http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd\">");
println(writer, " <key id=\"d0\" for=\"all\" attr.name=\"label\" attr.type=\"string\"/>");
println(writer, " <key id=\"d1\" for=\"all\" attr.name=\"name\" attr.type=\"string\"/>");
println(writer, " <graph id=\""+makeID(graphName)+"\" edgedefault=\""+(EXPORT_DIRECTED ? "directed" : "undirected")+"\">");
Iterator<Topic> topicIter=topicMap.getTopics();
while(topicIter.hasNext() && !logger.forceStop()) {
Topic t=(Topic)topicIter.next();
if(t.isRemoved()) continue;
logger.setProgress(count++);
echoNode(t, writer);
// Topic occurrences....
if(EXPORT_OCCURRENCES && t.getDataTypes().size()>0){
Collection<Topic> types=t.getDataTypes();
Iterator<Topic> typeTopicIter=types.iterator();
while(typeTopicIter.hasNext()){
Topic type=(Topic)typeTopicIter.next();
Hashtable<Topic,String> ht=(Hashtable)t.getData(type);
Iterator<Map.Entry<Topic,String>> iter3=ht.entrySet().iterator();
while(iter3.hasNext()){
Map.Entry<Topic,String> e=iter3.next();
String data=(String)e.getValue();
echoNode(data, writer);
echoEdge(t, data, type, writer);
}
}
}
}
// Topic types....
if(EXPORT_CLASSES) {
topicIter=topicMap.getTopics();
while(topicIter.hasNext() && !logger.forceStop()) {
Topic t=(Topic)topicIter.next();
if(t.isRemoved()) continue;
logger.setProgress(count++);
if(t.getTypes().size()>0){
Iterator<Topic> typeTopicIter=t.getTypes().iterator();
while(typeTopicIter.hasNext()){
Topic t2=(Topic)typeTopicIter.next();
if(t2.isRemoved()) continue;
echoEdge(t2, t, "class-instance", writer);
}
}
}
}
// Associations....
if(!logger.forceStop()) {
Iterator<Association> associationIter=topicMap.getAssociations();
int icount=0;
while(associationIter.hasNext() && !logger.forceStop()) {
logger.setProgress(count++);
Association a=(Association)associationIter.next();
Collection<Topic> roles = a.getRoles();
if(roles.size() < 2) continue;
else if(roles.size() == 2) {
Topic[] roleArray = (Topic[]) roles.toArray(new Topic[2]);
echoEdge(a.getPlayer(roleArray[0]), a.getPlayer(roleArray[1]), a.getType(), writer);
}
else {
if(EXPORT_N_ASSOCIATIONS) {
icount++;
String target="nameless-intermediator-node-"+icount;
echoNode(target, writer);
Iterator<Topic> roleTopicIter = roles.iterator();
while(roleTopicIter.hasNext()) {
Topic role=(Topic)roleTopicIter.next();
echoEdge(a.getPlayer(role), target, a.getType(), writer);
}
}
}
}
}
println(writer, " </graph>"); // graph
println(writer, "</graphml>"); // graphml
writer.flush();
writer.close();
}
// --------------------------------------------------------------- ECHOS ---
protected void echoNode(Topic t, PrintWriter writer) throws TopicMapException {
String label = t.getBaseName();
if(label == null) label = t.getOneSubjectIdentifier().toExternalForm();
echoNode(makeID(t), null, label, writer);
}
protected void echoNode(String data, PrintWriter writer) {
echoNode(makeID(data), null, data, writer);
}
protected void echoNode(String id, String name, String label, PrintWriter writer) {
if(writer == null || id == null) return;
println(writer, " <node id=\""+id+"\">");
if(name != null) println(writer, " <data key=\"d0\">"+makeString(name)+"</data>");
if(label != null) println(writer, " <data key=\"d1\">"+makeString(label)+"</data>");
println(writer, " </node>");
}
protected void echoEdge(Topic source, Topic target, String label, PrintWriter writer) throws TopicMapException {
print(writer, " <edge");
print(writer, " source=\""+makeID(source)+"\"");
print(writer, " target=\""+makeID(target)+"\"");
println(writer, ">");
if(label != null) println(writer, " <data key=\"d1\">"+makeString(label)+"</data>");
println(writer, " </edge>");
}
protected void echoEdge(String source, String target, String label, PrintWriter writer) {
print(writer, " <edge");
print(writer, " source=\""+makeID(source)+"\"");
print(writer, " target=\""+makeID(target)+"\"");
println(writer, ">");
if(label != null) println(writer, " <data key=\"d1\">"+makeString(label)+"</data>");
println(writer, " </edge>");
}
protected void echoEdge(Topic source, String target, Topic label, PrintWriter writer) throws TopicMapException {
String l = label.getBaseName();
if(l == null) l = label.getOneSubjectIdentifier().toExternalForm();
print(writer, " <edge");
print(writer, " source=\""+makeID(source)+"\"");
print(writer, " target=\""+makeID(target)+"\"");
println(writer, ">");
if(label != null) println(writer, " <data key=\"d1\">"+makeString(label)+"</data>");
println(writer, " </edge>");
}
protected void echoEdge(Topic source, Topic target, Topic label, PrintWriter writer) throws TopicMapException {
String l = label.getBaseName();
if(l == null) l = label.getOneSubjectIdentifier().toExternalForm();
echoEdge(source, target, l, writer);
}
protected String makeID(Topic t) throws TopicMapException {
return ""+t.getID();
}
protected String makeID(String s) {
int id = s.hashCode();
if(id < 0) id = 2*Math.abs(id)+1;
else id = 2*Math.abs(id);
return ""+id;
}
protected String makeString(String s) {
if(s == null) return null;
//s = s.substring(0,Math.min(s.length(), 240));
s = s.replaceAll("<", "<");
s = s.replaceAll(">", ">");
s = s.replaceAll("\\&", "&");
return s;
}
protected String makeString(Topic t) throws TopicMapException {
if(t == null) return null;
String s = t.getBaseName();
if(s == null) s = t.getOneSubjectIdentifier().toExternalForm();
return makeString(s);
}
// -------------------------------------------------------------------------
// Elementary print methods are used to ensure output is ISO-8859-1
protected void print(PrintWriter writer, String str) {
writer.print(str);
}
protected void println(PrintWriter writer, String str) {
writer.println(str);
}
}
| 15,683 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AbstractExportTool.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/exporters/AbstractExportTool.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* AbstractExportTool.java
*
* Created on 24. toukokuuta 2006, 19:02
*
*/
package org.wandora.application.tools.exporters;
import java.util.Iterator;
import javax.swing.Icon;
import org.wandora.application.WandoraTool;
import org.wandora.application.WandoraToolType;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.UIBox;
import org.wandora.application.tools.AbstractWandoraTool;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.memory.TopicMapImpl;
/**
*
* @author akivela
*/
public abstract class AbstractExportTool extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
/** Creates a new instance of AbstractExportTool */
public AbstractExportTool() {
}
@Override
public WandoraToolType getType(){
return WandoraToolType.createExportType();
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/export.png");
}
// -------------------------------------------------------------------------
protected TopicMap makeTopicMapWith(Context context) {
return makeTopicMapWith(context, false);
}
protected TopicMap makeTopicMapWith(Context context, boolean deepCopy) {
TopicMap tm = new TopicMapImpl();
try {
Iterator contextObjects = context.getContextObjects();
Object contextObject = null;
Topic contextTopic = null;
while(contextObjects.hasNext()) {
contextObject = contextObjects.next();
if(contextObject != null && contextObject instanceof Topic) {
contextTopic = (Topic) contextObject;
tm.copyTopicIn(contextTopic, deepCopy);
tm.copyTopicAssociationsIn(contextTopic);
}
}
}
catch(Exception e) {
log(e);
}
return tm;
}
}
| 2,834 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SQLDumpExport.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/exporters/SQLDumpExport.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.wandora.application.tools.exporters;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.wandora.application.Wandora;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.UIConstants;
import org.wandora.application.gui.simple.SimpleFileChooser;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.SimpleTopicMapLogger;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.topicmap.TopicMapLogger;
import org.wandora.topicmap.parser.XTMParser2;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
/**
*
* @author olli
*/
public class SQLDumpExport extends AbstractExportTool {
private static final long serialVersionUID = 1L;
public static final int I_TOPIC=0;
public static final int I_ASSOCIATION=1;
public static final int I_MEMBER=2;
public static final int I_SUBJECTIDENTIFIER=3;
public static final int I_TOPICTYPE=4;
public static final int I_DATA=5;
public static final int I_VARIANT=6;
public static final int I_VARIANTSCOPE=7;
@Override
public String getName() {
return "Topic map SQL export";
}
@Override
public String getDescription() {
return "Export topic map as a series of SQL insert statements. "+
"Exported SQL statements can be imported into an empty SQL database and "+
"Wandora can use the SQL database as a database topic map.";
}
@Override
public boolean requiresRefresh() {
return false;
}
private static int idcounter=0;
protected static synchronized String makeID(String prefix){
if(idcounter>=100000) idcounter=0;
return prefix+System.currentTimeMillis()+"-"+(idcounter++);
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
SimpleFileChooser chooser=UIConstants.getFileChooser();
chooser.setDialogTitle("Topic map SQL dump export");
if(chooser.open(wandora, "Export")==SimpleFileChooser.APPROVE_OPTION){
setDefaultLogger();
File file = chooser.getSelectedFile();
// TopicMap tm=wandora.getTopicMap();
TopicMap tm = solveContextTopicMap(wandora,context);
try{
String filePath=file.getAbsolutePath();
File[] tempFiles=new File[8];
for(int i=0;i<tempFiles.length;i++){
tempFiles[i]=File.createTempFile("wandora_",".sql");
}
PrintStream[] out=new PrintStream[tempFiles.length];
for(int i=0;i<out.length;i++){
out[i]=new PrintStream(tempFiles[i]);
}
log("Exporting database topic map as SQL.");
log("Exporting topics.");
int progress = 0;
setProgressMax(tm.getNumTopics());
Iterator<Topic> iter=tm.getTopics();
while(iter.hasNext()) {
setProgress(progress++);
Topic t=iter.next();
writeTopic(t.getID(), t.getBaseName(), t.getSubjectLocator(), out);
for(Topic type : t.getTypes()){
writeTopicType(t.getID(),type.getID(),out);
}
for(org.wandora.topicmap.Locator l : t.getSubjectIdentifiers()){
writeSubjectIdentifier(t.getID(), l.toString(), out);
}
for(Set<Topic> scope : t.getVariantScopes()){
String variantid=makeID("V");
String value=t.getVariant(scope);
writeVariant(variantid,t.getID(),value,out);
for(Topic s : scope){
writeVariantScope(variantid, s.getID(), out);
}
}
for(Topic type : t.getDataTypes()){
Hashtable<Topic,String> data=t.getData(type);
for(Map.Entry<Topic,String> e : data.entrySet()){
writeData(t.getID(), type.getID(), e.getKey().getID(), e.getValue(), out);
}
}
}
Iterator<Association> iter2=tm.getAssociations();
log("Exporting associations.");
progress = 0;
setProgressMax(tm.getNumAssociations());
while(iter2.hasNext()) {
setProgress(progress++);
Association a=iter2.next();
String associationid=makeID("A");
writeAssociation(associationid, a.getType().getID(), out);
for(Topic role : a.getRoles()){
Topic player=a.getPlayer(role);
writeMember(associationid, player.getID(), role.getID(), out);
}
}
closeStreams(out);
for(PrintStream outStream : out) {
outStream.close();
}
log("Creating output file.");
OutputStream outs=new FileOutputStream(file);
for(File tempFile : tempFiles) {
appendFile(outs, tempFile);
tempFile.delete();
}
outs.close();
log("Ready.");
setState(SQLDumpExport.WAIT);
}
catch(Exception e) {
e.printStackTrace();
log(e);
}
}
}
public void appendFile(OutputStream out,File in) throws IOException {
InputStream ins=new FileInputStream(in);
appendFile(out,ins);
ins.close();
}
public void appendFile(OutputStream out,InputStream in) throws IOException {
byte[] buf=new byte[4096];
int read=-1;
while( (read=in.read(buf))!= -1){
out.write(buf,0,read);
}
}
public String sqlEscape(String s){
if(s==null) return "null";
return "'"+s.replaceAll("'", "''")+"'";
}
public void disableForeignKeys(PrintStream out) throws IOException {
// not tested, mysql on default settings doesn't seem to care about foreign keys anyway
out.print("alter table TOPICTYPE disable keys;\n");
out.print("alter table DATA disable keys;\n");
out.print("alter table VARIANTSCOPE disable keys;\n");
out.print("alter table VARIANT disable keys;\n");
out.print("alter table MEMBER disable keys;\n");
out.print("alter table ASSOCIATION disable keys;\n");
out.print("alter table SUBJECTIDENTIFIER disabl keys;\n");
}
public void enableForeignKeys(PrintStream out) throws IOException {
// not tested, mysql on default settings doesn't seem to care about foreign keys anyway
out.print("alter table TOPICTYPE enable keys;\n");
out.print("alter table DATA enable keys;\n");
out.print("alter table VARIANTSCOPE enable keys;\n");
out.print("alter table VARIANT enable keys;\n");
out.print("alter table MEMBER enable keys;\n");
out.print("alter table ASSOCIATION enable keys;\n");
out.print("alter table SUBJECTIDENTIFIER enable keys;\n");
}
/*
public void writeTopic(String topicid,String baseName,org.wandora.topicmap.Locator subjectLocator,PrintStream out) throws IOException{
writeTopic(topicid,baseName,(subjectLocator==null)?null:(subjectLocator.toString()),out);
}
public void writeTopic(String topicid,String baseName,String subjectLocator,PrintStream out) throws IOException{
out.print("insert into TOPIC (TOPICID,BASENAME,SUBJECTLOCATOR) values ("+sqlEscape(topicid)+","+sqlEscape(baseName)+","+sqlEscape(subjectLocator)+");\n");
}
public void writeTopicType(String topicid,String typeid,PrintStream out) throws IOException {
out.print("insert into TOPICTYPE (TOPIC,TYPE) values ("+sqlEscape(topicid)+","+sqlEscape(typeid)+");\n");
}
public void writeAssociation(String associationid,String typeid,PrintStream out) throws IOException {
out.print("insert into ASSOCIATION (ASSOCIATIONID,TYPE) values ("+sqlEscape(associationid)+","+sqlEscape(typeid)+");\n");
}
public void writeMember(String associationid,String playerid,String roleid,PrintStream out) throws IOException {
out.print("insert into MEMBER (ASSOCIATION,PLAYER,ROLE) values ("+sqlEscape(associationid)+","+sqlEscape(playerid)+","+sqlEscape(roleid)+");\n");
}
public void writeSubjectIdentifier(String topicid,String si,PrintStream out) throws IOException {
out.print("insert into SUBJECTIDENTIFIER (TOPIC,SI) values ("+sqlEscape(topicid)+","+sqlEscape(si)+");\n");
}
public void writeData(String topicid,String typeid,String versionid,String data,PrintStream out) throws IOException {
out.print("insert into DATA (TOPIC,TYPE,VERSION,DATA) values ("+sqlEscape(topicid)+","+sqlEscape(typeid)+","+sqlEscape(versionid)+","+sqlEscape(data)+");\n");
}
public void writeVariantScope(String variantid,String topicid,PrintStream out) throws IOException {
out.print("insert into VARIANTSCOPE (VARIANT,TOPIC) values ("+sqlEscape(variantid)+","+sqlEscape(topicid)+");\n");
}
public void writeVariant(String variantid,String topicid,String value,PrintStream out) throws IOException {
out.print("insert into VARIANT (VARIANTID,TOPIC,VALUE) values ("+sqlEscape(variantid)+","+sqlEscape(topicid)+","+sqlEscape(value)+");\n");
}*/
public void closeStream(int count,PrintStream out) throws IOException {
if(count!=0) out.print(";\n");
}
public void closeStreams(PrintStream[] out) throws IOException {
closeStream(topicCount,out[I_TOPIC]);
closeStream(topicTypeCount,out[I_TOPICTYPE]);
closeStream(associationCount,out[I_ASSOCIATION]);
closeStream(memberCount,out[I_MEMBER]);
closeStream(subjectIdentifierCount,out[I_SUBJECTIDENTIFIER]);
closeStream(dataCount,out[I_DATA]);
closeStream(variantScopeCount,out[I_VARIANTSCOPE]);
closeStream(variantCount,out[I_VARIANT]);
}
protected int writeLimit=1;
protected int topicCount=0;
public void writeTopic(String topicid,String baseName,org.wandora.topicmap.Locator subjectLocator,PrintStream[] out) throws IOException{
writeTopic(topicid, baseName, subjectLocator, out[I_TOPIC]);
}
public void writeTopic(String topicid,String baseName,String subjectLocator,PrintStream[] out) throws IOException{
writeTopic(topicid, baseName, subjectLocator, out[I_TOPIC]);
}
public void writeTopic(String topicid,String baseName,org.wandora.topicmap.Locator subjectLocator,PrintStream out) throws IOException{
writeTopic(topicid,baseName,(subjectLocator==null)?null:(subjectLocator.toString()),out);
}
public void writeTopic(String topicid,String baseName,String subjectLocator,PrintStream out) throws IOException{
if(topicCount==0) out.print("insert into TOPIC (TOPICID,BASENAME,SUBJECTLOCATOR) values ");
else out.print(",\n");
out.print("("+sqlEscape(topicid)+","+sqlEscape(baseName)+","+sqlEscape(subjectLocator)+")");
topicCount++;
if(topicCount>=writeLimit){
topicCount=0;
out.print(";\n");
}
}
protected int topicTypeCount=0;
public void writeTopicType(String topicid,String typeid,PrintStream[] out) throws IOException {
writeTopicType(topicid, typeid, out[I_TOPICTYPE]);
}
public void writeTopicType(String topicid,String typeid,PrintStream out) throws IOException {
if(topicTypeCount==0) out.print("insert into TOPICTYPE (TOPIC,TYPE) values ");
else out.print(",\n");
out.print("("+sqlEscape(topicid)+","+sqlEscape(typeid)+")");
topicTypeCount++;
if(topicTypeCount>=writeLimit){
topicTypeCount=0;
out.print(";\n");
}
}
protected int associationCount=0;
public void writeAssociation(String associationid,String typeid,PrintStream[] out) throws IOException {
writeAssociation(associationid, typeid, out[I_ASSOCIATION]);
}
public void writeAssociation(String associationid,String typeid,PrintStream out) throws IOException {
if(associationCount==0) out.print("insert into ASSOCIATION (ASSOCIATIONID,TYPE) values ");
else out.print(",\n");
out.print("("+sqlEscape(associationid)+","+sqlEscape(typeid)+")");
associationCount++;
if(associationCount>=writeLimit){
associationCount=0;
out.print(";\n");
}
}
protected int memberCount=0;
public void writeMember(String associationid,String playerid,String roleid,PrintStream[] out) throws IOException {
writeMember(associationid, playerid, roleid, out[I_MEMBER]);
}
public void writeMember(String associationid,String playerid,String roleid,PrintStream out) throws IOException {
if(memberCount==0) out.print("insert into MEMBER (ASSOCIATION,PLAYER,ROLE) values ");
else out.print(",\n");
out.print("("+sqlEscape(associationid)+","+sqlEscape(playerid)+","+sqlEscape(roleid)+")");
memberCount++;
if(memberCount>=writeLimit){
memberCount=0;
out.print(";\n");
}
}
protected int subjectIdentifierCount=0;
public void writeSubjectIdentifier(String topicid,String si,PrintStream[] out) throws IOException {
writeSubjectIdentifier(topicid, si, out[I_SUBJECTIDENTIFIER]);
}
public void writeSubjectIdentifier(String topicid,String si,PrintStream out) throws IOException {
if(subjectIdentifierCount==0) out.print("insert into SUBJECTIDENTIFIER (TOPIC,SI) values ");
else out.print(",\n");
out.print("("+sqlEscape(topicid)+","+sqlEscape(si)+")");
subjectIdentifierCount++;
if(subjectIdentifierCount>=writeLimit){
subjectIdentifierCount=0;
out.print(";\n");
}
}
protected int dataCount=0;
public void writeData(String topicid,String typeid,String versionid,String data,PrintStream[] out) throws IOException {
writeData(topicid, typeid, versionid, data, out[I_DATA]);
}
public void writeData(String topicid,String typeid,String versionid,String data,PrintStream out) throws IOException {
if(dataCount==0) out.print("insert into DATA (TOPIC,TYPE,VERSION,DATA) values ");
else out.print(",\n");
out.print("("+sqlEscape(topicid)+","+sqlEscape(typeid)+","+sqlEscape(versionid)+","+sqlEscape(data)+")");
dataCount++;
if(dataCount>=writeLimit){
dataCount=0;
out.print(";\n");
}
}
protected int variantScopeCount=0;
public void writeVariantScope(String variantid,String topicid,PrintStream[] out) throws IOException {
writeVariantScope(variantid, topicid, out[I_VARIANTSCOPE]);
}
public void writeVariantScope(String variantid,String topicid,PrintStream out) throws IOException {
if(variantScopeCount==0) out.print("insert into VARIANTSCOPE (VARIANT,TOPIC) values ");
else out.print(",\n");
out.print("("+sqlEscape(variantid)+","+sqlEscape(topicid)+")");
variantScopeCount++;
if(variantScopeCount>=writeLimit){
variantScopeCount=0;
out.print(";\n");
}
}
protected int variantCount=0;
public void writeVariant(String variantid,String topicid,String value,PrintStream[] out) throws IOException {
writeVariant(variantid, topicid, value, out[I_VARIANT]);
}
public void writeVariant(String variantid,String topicid,String value,PrintStream out) throws IOException {
if(variantCount==0) out.print("insert into VARIANT (VARIANTID,TOPIC,VALUE) values ");
else out.print(",\n");
out.print("("+sqlEscape(variantid)+","+sqlEscape(topicid)+","+sqlEscape(value)+")");
variantCount++;
if(variantCount>=writeLimit){
variantCount=0;
out.print(";\n");
}
}
// -------------------------------------------------------------------------
public void convertXTM2ToSQL(InputStream in,PrintStream outs,TopicMapLogger logger){
try{
File[] tempFiles=new File[8];
for(int i=0;i<tempFiles.length;i++){
tempFiles[i]=File.createTempFile("wandora_",".sql");
}
PrintStream[] out=new PrintStream[tempFiles.length];
for(int i=0;i<out.length;i++){
out[i]=new PrintStream(tempFiles[i]);
}
javax.xml.parsers.SAXParserFactory factory=javax.xml.parsers.SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(false);
javax.xml.parsers.SAXParser parser=factory.newSAXParser();
XMLReader reader=parser.getXMLReader();
XTM2toSQL parserHandler=new XTM2toSQL(logger,out);
reader.setContentHandler(parserHandler);
reader.setErrorHandler(parserHandler);
reader.parse(new InputSource(in));
closeStreams(out);
for(int i=0;i<out.length;i++) out[i].close();
for(int i=0;i<tempFiles.length;i++){
appendFile(outs,tempFiles[i]);
tempFiles[i].delete();
}
outs.close();
}
catch(org.xml.sax.SAXParseException se) {
logger.log("Position "+se.getLineNumber()+":"+se.getColumnNumber(), se);
}
catch(org.xml.sax.SAXException saxe) {
if(! "user_interrupt".equals(saxe.getMessage())) {
logger.log(saxe);
}
}
catch(Exception e){
logger.log(e);
}
}
public static void main(String[] args) throws Exception {
TopicMapLogger logger=new SimpleTopicMapLogger(System.err);
SQLDumpExport d=new SQLDumpExport();
d.convertXTM2ToSQL(System.in, System.out, logger);
}
public class XTM2toSQL extends XTMParser2 {
protected PrintStream[] out;
public XTM2toSQL(TopicMapLogger logger,PrintStream[] out){
// the topic map is not used for anything since all process methods have been overridden
super(new org.wandora.topicmap.memory.TopicMapImpl(),logger);
this.out=out;
}
protected String hrefToID(String s){
if(s.startsWith("#")) return s.substring(1);
else logger.log("Don't know how to convert href \""+s+"\" to ID");
return s;
}
public void writeVariant(String topicid,Collection<String> scope,String value,PrintStream[] out) throws IOException {
String variantid=makeID("V");
SQLDumpExport.this.writeVariant(variantid,topicid,value,out);
for(String s : scope){
writeVariantScope(variantid,hrefToID(s),out);
}
}
@Override
protected void processTopic(){
try{
if(parsedTopic.id==null) parsedTopic.id=makeID("T");
if(parsedTopic.subjectLocators.size()>1)
logger.log("Warning, more than one subject locator found, ignoring all but one");
String baseName=null;
String subjectLocator=null;
if(parsedTopic.subjectLocators.size()>0) subjectLocator=parsedTopic.subjectLocators.get(0).toString();
for(ParsedName name : parsedTopic.names){
if(name.type!=null) {
logger.log("Warning, name has type, moving to scope");
if(name.scope==null) name.scope=new ArrayList<String>();
name.scope.add(name.type);
}
if(name.value!=null){
if(name.scope==null || name.scope.isEmpty()){
baseName=name.value;
}
else {
writeVariant(parsedTopic.id,name.scope,name.value,out);
}
}
for(ParsedVariant v : name.variants) {
ArrayList<String> s=new ArrayList<String>();
if(name.scope!=null) s.addAll(name.scope);
if(v.scope!=null) s.addAll(v.scope);
writeVariant(parsedTopic.id,s,v.data,out);
}
}
writeTopic(parsedTopic.id,baseName,subjectLocator,out);
if(parsedTopic.types!=null){
for(String type : parsedTopic.types){
writeTopicType(parsedTopic.id,hrefToID(type),out);
}
}
for(String si : parsedTopic.subjectIdentifiers){
writeSubjectIdentifier(parsedTopic.id, si, out);
}
if(parsedTopic.itemIdentities.size()>0){
logger.log("Warning, ignoring item identities");
}
for(ParsedOccurrence o : parsedTopic.occurrences){
if(o.type==null){
logger.log("Warning, occurrence has no type, skipping.");
continue;
}
if(o.ref!=null){
logger.log("Warning, skipping resource ref occurrence");
continue;
}
else if(o.data==null){
logger.log("Warning, occurrence has no data, skipping.");
continue;
}
else{
if(o.scope==null || o.scope.isEmpty()) {
logger.log("Warning, occurrence has no scope, skipping");
continue;
}
if(o.scope.size()>1) logger.log("Warning, variant scope has more than one topic, ignoring all but one.");
String version=hrefToID(o.scope.get(0));
writeData(parsedTopic.id, hrefToID(o.type), version, o.data, out);
}
}
}
catch(IOException ioe){
logger.log(ioe);
}
}
@Override
protected void processAssociation(){
try{
if(parsedAssociation.type==null) logger.log("No type in association");
else if(parsedAssociation.roles.isEmpty()) logger.log("No players in association");
else {
String associationid=makeID("A");
writeAssociation(associationid,hrefToID(parsedAssociation.type),out);
for(ParsedRole r : parsedAssociation.roles){
writeMember(associationid,hrefToID(r.topic),hrefToID(r.type),out);
}
}
}catch(IOException ioe){
logger.log(ioe);
}
}
@Override
protected void postProcessTopicMap(){
// do nothing
}
}
}
| 25,194 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SimilarityMatrixExport.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/exporters/SimilarityMatrixExport.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* SimilarityMatrixExport.java
*
*/
package org.wandora.application.tools.exporters;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import javax.swing.Icon;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.WandoraToolLogger;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.UIBox;
import org.wandora.application.gui.UIConstants;
import org.wandora.application.gui.simple.SimpleFileChooser;
import org.wandora.topicmap.TMBox;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.topicmap.similarity.TopicSimilarity;
import org.wandora.utils.IObox;
/**
*
* @author akivela
*/
public class SimilarityMatrixExport extends AbstractExportTool implements WandoraTool {
private static final long serialVersionUID = 1L;
public static final String TAB_FORMAT = "Tabulator separated plain text";
public static final String HTML_FORMAT = "HTML table";
private SimilarityMatrixExportDialog similarityDialog = null;
private boolean labelMatrix = true;
private String outputFormat = null;
private boolean sortColumns = true;
private int numberOfDecimals = 3;
private double filterBelow = 0;
private double maximizeAbove = 1;
private boolean outputZeros = false;
private boolean exportSelectionInsteadOfTopicMap = false;
private TopicSimilarity currentSimilarityMeasure = null;
public SimilarityMatrixExport() {
}
public SimilarityMatrixExport(boolean exportSelection) {
exportSelectionInsteadOfTopicMap = exportSelection;
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/export_similarity_matrix.png");
}
@Override
public boolean requiresRefresh() {
return false;
}
@Override
public void execute(Wandora wandora, Context context) {
Iterator<Topic> topics = null;
String exportInfo = "";
try {
if(exportSelectionInsteadOfTopicMap) {
topics = context.getContextObjects();
exportInfo = "selected topics";
}
else {
// --- Solve first topic map to be exported
TopicMap tm = solveContextTopicMap(wandora, context);
String topicMapName = this.solveNameForTopicMap(wandora, tm);
topics = tm.getTopics();
if(topicMapName == null) exportInfo = "LayerStack";
if(topicMapName != null) exportInfo = "topic map in layer '" + topicMapName + "'";
}
if(similarityDialog == null) {
similarityDialog = new SimilarityMatrixExportDialog();
}
similarityDialog.open();
// WAITING FOR USER...
if(similarityDialog.wasAccepted()) {
labelMatrix = similarityDialog.shouldAddLabels();
outputFormat = similarityDialog.getOutputFormat();
currentSimilarityMeasure = similarityDialog.getSimilarityMeasure();
numberOfDecimals = similarityDialog.getNumberOfDecimals();
filterBelow = similarityDialog.getFilterBelow();
maximizeAbove = similarityDialog.getMaximizeAbove();
outputZeros = similarityDialog.getOutputZeros();
// --- Then solve target file (and format)
SimpleFileChooser chooser=UIConstants.getFileChooser();
chooser.setDialogTitle("Export "+exportInfo+" as similarity matrix...");
if(chooser.open(wandora, "Export")==SimpleFileChooser.APPROVE_OPTION){
setDefaultLogger();
File file = chooser.getSelectedFile();
String fileName = file.getName();
// --- Finally write topic map to chosen file
OutputStream out=null;
try {
if(HTML_FORMAT.equals(outputFormat))
file=IObox.addFileExtension(file, "html");
else
file=IObox.addFileExtension(file, "txt");
fileName = file.getName(); // Updating filename if file has changed!
out=new FileOutputStream(file);
log("Exporting topics as similarity matrix to '"+fileName+"'.");
exportMatrix(out, topics, getCurrentLogger());
out.close();
log("OK");
}
catch(Exception e) {
log(e);
try { if(out != null) out.close(); }
catch(Exception e2) { log(e2); }
}
}
}
}
catch(Exception e) {
log(e);
}
setState(WAIT);
}
@Override
public String getName() {
return "Export similarity matrix";
}
@Override
public String getDescription() {
return "Exports topic map as similarity matrix.";
}
public void exportMatrix(OutputStream out, Iterator<Topic> topicIterator, WandoraToolLogger logger) throws TopicMapException {
if(logger == null) logger = this;
PrintWriter writer = null;
try {
writer = new PrintWriter(new OutputStreamWriter(out, "ISO-8859-1"));
}
catch (UnsupportedEncodingException ex) {
log("Exception while trying ISO-8859-1 character encoding. Using default encoding.");
writer = new PrintWriter(new OutputStreamWriter(out));
}
int totalCount = 0;
ArrayList<Topic> topics = new ArrayList<Topic>();
Topic t = null;
log("Collecting topics...");
while(topicIterator.hasNext() && !logger.forceStop()) {
t = topicIterator.next();
if(t != null && !t.isRemoved()) {
topics.add(t);
totalCount++;
}
}
if(sortColumns) {
log("Sorting topic collection...");
Collections.sort(topics, new TMBox.TopicNameComparator(null));
}
totalCount = totalCount * totalCount;
logger.setProgressMax(totalCount);
// And finally export....
log("Exporting similarity matrix...");
if(HTML_FORMAT.equals(outputFormat)) {
exportMatrixAsHTMLTable(writer, topics, logger);
}
else {
exportMatrixAsTabText(writer, topics, logger);
}
writer.flush();
writer.close();
}
public void exportMatrixAsTabText(PrintWriter writer, ArrayList<Topic> topics, WandoraToolLogger logger) throws TopicMapException {
int progress = 0;
Topic t1 = null;
Topic t2 = null;
double similarity = 0;
if(labelMatrix) {
print(writer, "\t");
for(int i=0; i<topics.size() && !logger.forceStop(); i++) {
print(writer, makeString(topics.get(i))+"\t");
}
print(writer, "\n");
}
for(int i=0; i<topics.size() && !logger.forceStop(); i++) {
t1=topics.get(i);
if(labelMatrix) {
print(writer, makeString(topics.get(i))+"\t");
}
for(int j=0; j<topics.size() && !logger.forceStop(); j++) {
t2=topics.get(j);
similarity = calculateSimilarity(t1, t2);
if(similarity != 0 || outputZeros) print(writer, ""+similarity);
print(writer, "\t");
setProgress(progress++);
}
print(writer, "\n");
}
}
public void exportMatrixAsHTMLTable(PrintWriter writer, ArrayList<Topic> topics, WandoraToolLogger logger) throws TopicMapException {
int progress = 0;
Topic t1 = null;
Topic t2 = null;
double similarity = 0;
print(writer, "<table border=1>");
if(labelMatrix) {
print(writer, "<tr><td> </td>");
for(int i=0; i<topics.size() && !logger.forceStop(); i++) {
print(writer, "<td>"+makeString(topics.get(i))+"</td>");
}
print(writer, "</tr>\n");
}
for(int i=0; i<topics.size() && !logger.forceStop(); i++) {
print(writer, "<tr>");
t1=topics.get(i);
if(labelMatrix) {
print(writer, "<td>"+makeString(topics.get(i))+"</td>");
}
for(int j=0; j<topics.size() && !logger.forceStop(); j++) {
t2=topics.get(j);
similarity = calculateSimilarity(t1, t2);
print(writer, "<td>");
if(similarity != 0 || outputZeros) print(writer, ""+similarity);
print(writer, "</td>");
setProgress(progress++);
}
print(writer, "</tr>\n");
}
print(writer, "</table>");
}
// -------------------------------------------------------------------------
public double calculateSimilarity(Topic t1, Topic t2) {
double s = -1;
try {
s = currentSimilarityMeasure.similarity(t1, t2);
s = roundSimilarity(s, numberOfDecimals);
if(s < filterBelow) s = 0;
if(s > maximizeAbove) s = 1;
}
catch(Exception e) {
log(e);
}
return s;
}
protected double roundSimilarity(double s, int n) {
double r = Math.pow(10, n);
double ns = s * r;
long ins = Math.round(ns);
ns = ins / r;
return ns;
}
protected String makeString(Topic t) throws TopicMapException {
if(t == null) return null;
String s = t.getBaseName();
if(s == null) s = t.getOneSubjectIdentifier().toExternalForm();
return s;
}
// -------------------------------------------------------------------------
// Elementary print methods are used to ensure output is ISO-8859-1
protected void print(PrintWriter writer, String str) {
writer.print(str);
}
protected void println(PrintWriter writer, String str) {
writer.println(str);
}
}
| 11,457 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SimilarityMatrixExportDialog.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/exporters/SimilarityMatrixExportDialog.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* SimilarityMatrixExportDialog.java
*
* Created on Sep 9, 2011, 10:19:27 PM
*/
package org.wandora.application.tools.exporters;
import java.util.ArrayList;
import javax.swing.JDialog;
import org.wandora.application.Wandora;
import org.wandora.application.gui.UIBox;
import org.wandora.application.gui.simple.SimpleButton;
import org.wandora.application.gui.simple.SimpleCheckBox;
import org.wandora.application.gui.simple.SimpleComboBox;
import org.wandora.application.gui.simple.SimpleField;
import org.wandora.application.gui.simple.SimpleLabel;
import org.wandora.topicmap.similarity.TopicSimilarity;
import org.wandora.topicmap.similarity.TopicSimilarityHelper;
/**
*
* @author akivela
*/
public class SimilarityMatrixExportDialog extends javax.swing.JPanel {
private static final long serialVersionUID = 1L;
private boolean wasAccepted = false;
private JDialog myDialog = null;
private ArrayList<TopicSimilarity> similarityMeasures = null;
/** Creates new form SimilarityMatrixExportDialog */
public SimilarityMatrixExportDialog() {
initComponents();
similarityTypeComboBox.setEditable(false);
outputFormatComboBox.setEditable(false);
similarityMeasures = TopicSimilarityHelper.getTopicSimilarityMeasures();
for(TopicSimilarity similarityMeasure : similarityMeasures) {
similarityTypeComboBox.addItem(similarityMeasure.getName());
}
outputFormatComboBox.addItem(SimilarityMatrixExport.TAB_FORMAT);
outputFormatComboBox.addItem(SimilarityMatrixExport.HTML_FORMAT);
}
public boolean wasAccepted() {
return wasAccepted;
}
public void open() {
myDialog = new JDialog(Wandora.getWandora(), true);
myDialog.add(this);
myDialog.setSize(600,320);
myDialog.setTitle("Similarity matrix export options");
UIBox.centerWindow(myDialog, Wandora.getWandora());
wasAccepted = false;
myDialog.setVisible(true);
}
public boolean shouldAddLabels() {
return addLabelsCheckBox.isSelected();
}
public String getOutputFormat() {
return outputFormatComboBox.getItemAt(outputFormatComboBox.getSelectedIndex()).toString();
}
public TopicSimilarity getSimilarityMeasure() {
int index = similarityTypeComboBox.getSelectedIndex();
if(index >= 0 && index < similarityMeasures.size()) {
return similarityMeasures.get(index);
}
return null;
}
public int getNumberOfDecimals() {
int d = 3;
try {
d = Integer.parseInt(noDecimalsTextField.getText());
if(d > 10) d = 10;
}
catch(Exception e) {
// DO NOTHING
}
return d;
}
public double getMaximizeAbove() {
double m = 1.0;
try {
String mstr = maximizeAboveTextField.getText();
if(mstr != null && mstr.trim().length() > 0) {
m = Double.parseDouble(mstr);
}
}
catch(Exception e) {
// DO NOTHING
}
return m;
}
public double getFilterBelow() {
double m = 0.0;
try {
String mstr = filterBelowTextField.getText();
if(mstr != null && mstr.trim().length() > 0) {
m = Double.parseDouble(mstr);
}
}
catch(Exception e) {
// DO NOTHING
}
return m;
}
public boolean getOutputZeros() {
return outputZerosCheckBox.isSelected();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
optionsPanel = new javax.swing.JPanel();
infoLabel = new SimpleLabel();
similarityTypeComboBox = new SimpleComboBox();
outputFormatComboBox = new SimpleComboBox();
additionsPanel = new javax.swing.JPanel();
noDecimalsLabel = new SimpleLabel();
noDecimalsTextField = new SimpleField();
filterBelowLabel = new SimpleLabel();
filterBelowTextField = new SimpleField();
maximizeAboveLabel = new SimpleLabel();
maximizeAboveTextField = new SimpleField();
additions2Panel = new javax.swing.JPanel();
addLabelsCheckBox = new SimpleCheckBox();
outputZerosCheckBox = new SimpleCheckBox();
buttonPanel = new javax.swing.JPanel();
buttonFillerPanel = new javax.swing.JPanel();
exportButton = new SimpleButton();
cancelButton = new SimpleButton();
setLayout(new java.awt.GridBagLayout());
optionsPanel.setLayout(new java.awt.GridBagLayout());
infoLabel.setText("<html>This tools is used to export similarity matrix. Similarity matrix is an adjacency matrix where each row and column represent single topic. Matrix cell holds a number representing similarity of the row-topic and the column-topic. Similarity value 1 means topics are maximally similar. Similarity value 0 means topics are maximally different. Select used similarity metric, used output format and other options below. To begin export, click Export button.</html>");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 10, 0);
optionsPanel.add(infoLabel, gridBagConstraints);
similarityTypeComboBox.setMinimumSize(new java.awt.Dimension(300, 23));
similarityTypeComboBox.setPreferredSize(new java.awt.Dimension(300, 23));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 10, 0);
optionsPanel.add(similarityTypeComboBox, gridBagConstraints);
outputFormatComboBox.setMinimumSize(new java.awt.Dimension(300, 23));
outputFormatComboBox.setPreferredSize(new java.awt.Dimension(300, 23));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 10, 0);
optionsPanel.add(outputFormatComboBox, gridBagConstraints);
additionsPanel.setLayout(new java.awt.GridBagLayout());
noDecimalsLabel.setText("Number of decimals");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 4);
additionsPanel.add(noDecimalsLabel, gridBagConstraints);
noDecimalsTextField.setHorizontalAlignment(javax.swing.JTextField.CENTER);
noDecimalsTextField.setText("3");
noDecimalsTextField.setMinimumSize(new java.awt.Dimension(40, 23));
noDecimalsTextField.setPreferredSize(new java.awt.Dimension(40, 23));
additionsPanel.add(noDecimalsTextField, new java.awt.GridBagConstraints());
filterBelowLabel.setText("Filter values below");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 4);
additionsPanel.add(filterBelowLabel, gridBagConstraints);
filterBelowTextField.setMinimumSize(new java.awt.Dimension(40, 23));
filterBelowTextField.setPreferredSize(new java.awt.Dimension(40, 23));
additionsPanel.add(filterBelowTextField, new java.awt.GridBagConstraints());
maximizeAboveLabel.setText("Maximize values above");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 4);
additionsPanel.add(maximizeAboveLabel, gridBagConstraints);
maximizeAboveTextField.setMinimumSize(new java.awt.Dimension(40, 23));
maximizeAboveTextField.setPreferredSize(new java.awt.Dimension(40, 23));
additionsPanel.add(maximizeAboveTextField, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
optionsPanel.add(additionsPanel, gridBagConstraints);
additions2Panel.setLayout(new java.awt.GridBagLayout());
addLabelsCheckBox.setSelected(true);
addLabelsCheckBox.setText("Add labels");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 8);
additions2Panel.add(addLabelsCheckBox, gridBagConstraints);
outputZerosCheckBox.setSelected(true);
outputZerosCheckBox.setText("Write zeros");
additions2Panel.add(outputZerosCheckBox, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(8, 0, 0, 0);
optionsPanel.add(additions2Panel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10);
add(optionsPanel, gridBagConstraints);
buttonPanel.setLayout(new java.awt.GridBagLayout());
buttonFillerPanel.setLayout(new java.awt.BorderLayout());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
buttonPanel.add(buttonFillerPanel, gridBagConstraints);
exportButton.setText("Export");
exportButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
exportButtonMouseReleased(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3);
buttonPanel.add(exportButton, gridBagConstraints);
cancelButton.setText("Cancel");
cancelButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
cancelButtonMouseReleased(evt);
}
});
buttonPanel.add(cancelButton, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 10, 10);
add(buttonPanel, gridBagConstraints);
}// </editor-fold>//GEN-END:initComponents
private void exportButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_exportButtonMouseReleased
wasAccepted = true;
if(myDialog != null) myDialog.setVisible(false);
}//GEN-LAST:event_exportButtonMouseReleased
private void cancelButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cancelButtonMouseReleased
wasAccepted = false;
if(myDialog != null) myDialog.setVisible(false);
}//GEN-LAST:event_cancelButtonMouseReleased
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JCheckBox addLabelsCheckBox;
private javax.swing.JPanel additions2Panel;
private javax.swing.JPanel additionsPanel;
private javax.swing.JPanel buttonFillerPanel;
private javax.swing.JPanel buttonPanel;
private javax.swing.JButton cancelButton;
private javax.swing.JButton exportButton;
private javax.swing.JLabel filterBelowLabel;
private javax.swing.JTextField filterBelowTextField;
private javax.swing.JLabel infoLabel;
private javax.swing.JLabel maximizeAboveLabel;
private javax.swing.JTextField maximizeAboveTextField;
private javax.swing.JLabel noDecimalsLabel;
private javax.swing.JTextField noDecimalsTextField;
private javax.swing.JPanel optionsPanel;
private javax.swing.JComboBox outputFormatComboBox;
private javax.swing.JCheckBox outputZerosCheckBox;
private javax.swing.JComboBox similarityTypeComboBox;
// End of variables declaration//GEN-END:variables
}
| 14,045 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
GraphXMLExport.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/exporters/GraphXMLExport.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*/
package org.wandora.application.tools.exporters;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import javax.swing.Icon;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.WandoraToolLogger;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.UIBox;
import org.wandora.application.gui.UIConstants;
import org.wandora.application.gui.simple.SimpleFileChooser;
import org.wandora.application.tools.GenericOptionsDialog;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.utils.IObox;
/**
* <p>Exports selected topic map in Wandora as GraphXML file. GraphXML
* format files can be used with HyperGraph application for example. See
* http://hypergraph.sourceforge.net/simple_graphs.html
* for more info about GraphXML format.
* </p>
* <p>
* Note that the GraphXML file format is rather simple and can't represent all
* details of Topic Maps. Export converts all topics and occurrences as graph
* nodes. All associations are exported as graph edges. If association has more
* than two players, an itermediator node is added to link all players.
* </p>
* <p>
* Export doesn't convert subject locators, subject identifiers, different
* variant names, association roles, occurrence scopes etc.
* </p>
*
* @author akivela
*/
public class GraphXMLExport extends AbstractExportTool implements WandoraTool {
private static final long serialVersionUID = 1L;
public boolean EXPORT_SELECTION_INSTEAD_TOPIC_MAP = false;
public boolean EXPORT_CLASSES = true;
public boolean EXPORT_OCCURRENCES = false;
public boolean EXPORT_N_ASSOCIATIONS = true;
public boolean EXPORT_DIRECTED = false;
public boolean LABEL_EDGES = false;
public boolean EXPORT_SUBJECT_LOCATORS = false;
public boolean MARK_AS_FOREST = true;
public GraphXMLExport() {
}
public GraphXMLExport(boolean exportSelection) {
EXPORT_SELECTION_INSTEAD_TOPIC_MAP = exportSelection;
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/export_graph.png");
}
@Override
public boolean requiresRefresh() {
return false;
}
@Override
public boolean isConfigurable(){
return true;
}
@Override
public void configure(Wandora wandora,org.wandora.utils.Options options,String prefix) throws TopicMapException {
GenericOptionsDialog god=new GenericOptionsDialog(wandora,"GraphXML Export options","GraphXML Export options",true,new String[][]{
new String[]{"Export classes","boolean",(EXPORT_CLASSES ? "true" : "false"),"Should topic classes also export?"},
new String[]{"Export occurrences","boolean",(EXPORT_OCCURRENCES ? "true" : "false"),"Should topic occurrences also export?"},
new String[]{"Export n associations","boolean",(EXPORT_N_ASSOCIATIONS ? "true" : "false"), "Should associations with more than 2 players also export?"},
new String[]{"Is directed","boolean",(EXPORT_DIRECTED ? "true" : "false"), "Export directed or undirected graph" },
new String[]{"Label edges","boolean",(LABEL_EDGES ? "true" : "false"), "Label edges with association type?" },
new String[]{"Export subject locators","boolean",(EXPORT_SUBJECT_LOCATORS ? "true" : "false"), "Export subject locators as node links?" },
new String[]{"Mark as forest","boolean",(MARK_AS_FOREST ? "true" : "false"), "Export subject locators as node links?" },
},wandora);
god.setVisible(true);
if(god.wasCancelled()) return;
Map<String, String> values = god.getValues();
EXPORT_CLASSES = ("true".equals(values.get("Export classes")) ? true : false );
EXPORT_OCCURRENCES = ("true".equals(values.get("Export occurrences")) ? true : false );
EXPORT_N_ASSOCIATIONS = ("true".equals(values.get("Export n associations")) ? true : false );
EXPORT_DIRECTED = ("true".equals(values.get("Is directed")) ? true : false );
LABEL_EDGES = ("true".equals(values.get("Label edges")) ? true : false );
EXPORT_SUBJECT_LOCATORS = ("true".equals(values.get("Export subject locators")) ? true : false );
MARK_AS_FOREST = ("true".equals(values.get("Mark as forest")) ? true : false );
}
@Override
public void execute(Wandora wandora, Context context) {
String topicMapName = null;
String exportInfo = null;
// --- Solve first topic map to be exported
TopicMap tm = null;
if(EXPORT_SELECTION_INSTEAD_TOPIC_MAP) {
tm = makeTopicMapWith(context);
exportInfo = "Exporting selected topics as GraphXML graph";
topicMapName = "selection_in_wandora";
}
else {
tm = solveContextTopicMap(wandora, context);
topicMapName = this.solveNameForTopicMap(wandora, tm);
if(topicMapName != null) {
exportInfo = "Exporting topic map in layer '" + topicMapName + "' as GraphXML graph";
}
else {
exportInfo = "Exporting topic map as GraphXML graph";
topicMapName = "no_name_topic_map";
}
}
// --- Then solve target file
SimpleFileChooser chooser=UIConstants.getFileChooser();
chooser.setDialogTitle(exportInfo+"...");
if(chooser.open(wandora, "Export")==SimpleFileChooser.APPROVE_OPTION){
setDefaultLogger();
File file = chooser.getSelectedFile();
String fileName = file.getName();
// --- Finally write topicmap as GraphXML to chosen file
OutputStream out=null;
try {
file=IObox.addFileExtension(file, "xml"); // Ensure file extension exists!
fileName = file.getName(); // Updating filename if file has changed!
out=new FileOutputStream(file);
log(exportInfo+" to '"+fileName+"'.");
exportGraphML(out, tm, topicMapName, getCurrentLogger());
out.close();
log("Saved GraphXML file has a reference to a local GraphXML.dtd.");
log("Download GraphXML.dtd type definition file from http://hypergraph.sourceforge.net/graphs/GraphXML.dtd");
log("Ready.");
}
catch(Exception e) {
log(e);
try { if(out != null) out.close(); }
catch(Exception e2) { log(e2); }
}
}
setState(WAIT);
}
@Override
public String getName() {
return "Export GraphXML graph";
}
@Override
public String getDescription() {
return "Exports topic map layer as GraphXML file.";
}
public void exportGraphML(OutputStream out, TopicMap topicMap, String graphName, WandoraToolLogger logger) throws TopicMapException {
if(logger == null) logger = this;
PrintWriter writer = null;
try {
writer = new PrintWriter(new OutputStreamWriter(out, "UTF-8"));
}
catch (UnsupportedEncodingException ex) {
log("Exception while instantiating PrintWriter with UTF-8 character encoding. Using default encoding.");
writer = new PrintWriter(new OutputStreamWriter(out));
}
int totalCount = 2*topicMap.getNumTopics() + topicMap.getNumAssociations();
logger.setProgressMax(totalCount);
println(writer, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
println(writer, "<!DOCTYPE GraphXML SYSTEM \"GraphXML.dtd\">");
println(writer, "<GraphXML>");
print(writer, " <graph id=\"WandoraExport"+makeID(graphName)+"\"");
if(EXPORT_DIRECTED)
print(writer, " isDirected=\"true\"");
else
print(writer, " isDirected=\"false\"");
if(MARK_AS_FOREST)
print(writer, " isForest=\"true\"");
else
print(writer, " isForest=\"false\"");
println(writer, ">");
// First round... topic nodes
int count = 0;
Iterator iter=topicMap.getTopics();
while(iter.hasNext() && !logger.forceStop()) {
Topic t=(Topic)iter.next();
if(t.isRemoved()) continue;
logger.setProgress(count++);
echoNode(t, writer);
}
// Second round... class-instance edges and occurrences....
iter=topicMap.getTopics();
while(iter.hasNext() && !logger.forceStop()) {
Topic t=(Topic)iter.next();
if(t.isRemoved()) continue;
logger.setProgress(count++);
// Topic types....
if(EXPORT_CLASSES && t.getTypes().size()>0) {
Iterator iter2=t.getTypes().iterator();
while(iter2.hasNext()){
Topic t2=(Topic)iter2.next();
if(t2.isRemoved()) continue;
echoEdge(t2, t, "class-instance", writer);
}
}
// Topic occurrences....
if(EXPORT_OCCURRENCES && t.getDataTypes().size()>0) {
Collection types=t.getDataTypes();
Iterator iter2=types.iterator();
while(iter2.hasNext()){
Topic type=(Topic)iter2.next();
Hashtable ht=(Hashtable)t.getData(type);
Iterator iter3=ht.entrySet().iterator();
while(iter3.hasNext()){
Map.Entry e=(Map.Entry)iter3.next();
String data=(String)e.getValue();
echoNode(data, writer);
echoEdge(t, data, type, writer);
}
}
}
}
// Third round and association edges....
if(!logger.forceStop()) {
iter=topicMap.getAssociations();
int icount=0;
while(iter.hasNext() && !logger.forceStop()) {
logger.setProgress(count++);
Association a=(Association)iter.next();
Collection roles = a.getRoles();
if(roles.size() < 2) continue;
else if(roles.size() == 2) {
Topic[] roleArray = (Topic[]) roles.toArray(new Topic[2]);
echoEdge(a.getPlayer(roleArray[0]), a.getPlayer(roleArray[1]), a.getType(), writer);
}
else {
if(EXPORT_N_ASSOCIATIONS) {
icount++;
String target="nameless-intermediator-node-"+icount;
echoNode(target, writer);
Iterator iter2 = roles.iterator();
while(iter2.hasNext()) {
Topic role=(Topic)iter2.next();
echoEdge(a.getPlayer(role), target, a.getType(), writer);
}
}
}
}
}
println(writer, " </graph>"); // graph
println(writer, "</GraphXML>"); // graphml
writer.flush();
writer.close();
}
// --------------------------------------------------------------- ECHOS ---
protected void echoNode(Topic t, PrintWriter writer) throws TopicMapException {
String label = t.getBaseName();
if(label == null) label = t.getOneSubjectIdentifier().toExternalForm();
String sl = t.getSubjectLocator() == null ? null : t.getSubjectLocator().toExternalForm();
echoNode(makeID(t), sl, label, writer);
}
protected void echoNode(String data, PrintWriter writer) {
echoNode(makeID(data), null, data, writer);
}
protected void echoNode(String id, String sl, String label, PrintWriter writer) {
if(writer == null || id == null) return;
println(writer, " <node name=\""+id+"\">");
if(label != null) println(writer, " <label>"+makeString(label)+"</label>");
try {
if(EXPORT_SUBJECT_LOCATORS && sl != null)
println(writer, " <dataref><ref xlink:href=\""+makeString(sl)+"\"/></dataref>");
}
catch(Exception e) {
log(e);
}
println(writer, " </node>");
}
protected void echoEdge(Topic source, Topic target, String label, PrintWriter writer) throws TopicMapException {
print(writer, " <edge");
print(writer, " source=\""+makeID(source)+"\"");
print(writer, " target=\""+makeID(target)+"\"");
println(writer, ">");
if(LABEL_EDGES && label != null) writer.println(" <label>"+makeString(label)+"</label>");
println(writer, " </edge>");
}
protected void echoEdge(String source, String target, String label, PrintWriter writer) {
print(writer, " <edge");
print(writer, " source=\""+makeID(source)+"\"");
print(writer, " target=\""+makeID(target)+"\"");
println(writer, ">");
if(LABEL_EDGES && label != null) println(writer, " <label>"+makeString(label)+"</label>");
println(writer, " </edge>");
}
protected void echoEdge(Topic source, String target, Topic label, PrintWriter writer) throws TopicMapException {
String l = label.getBaseName();
if(l == null) l = label.getOneSubjectIdentifier().toExternalForm();
print(writer, " <edge");
print(writer, " source=\""+makeID(source)+"\"");
print(writer, " target=\""+makeID(target)+"\"");
println(writer, ">");
if(LABEL_EDGES && label != null) println(writer, " <label>"+makeString(label)+"</label>");
println(writer, " </edge>");
}
protected void echoEdge(Topic source, Topic target, Topic label, PrintWriter writer) throws TopicMapException {
String l = label.getBaseName();
if(l == null) l = label.getOneSubjectIdentifier().toExternalForm();
echoEdge(source, target, l, writer);
}
protected String makeID(Topic t) throws TopicMapException {
return ""+t.getID();
}
protected String makeID(String s) {
int id = s.hashCode();
if(id < 0) id = 2*Math.abs(id)+1;
else id = 2*Math.abs(id);
return ""+id;
}
protected String makeString(String s) {
if(s == null) return null;
//s = s.substring(0,Math.min(s.length(), 240));
s = s.replaceAll("<", "<");
s = s.replaceAll(">", ">");
s = s.replaceAll("\\&", "&");
s = s.replaceAll("\"", "'");
return s;
}
protected String makeString(Topic t) throws TopicMapException {
if(t == null) return null;
String s = t.getBaseName();
if(s == null) s = t.getOneSubjectIdentifier().toExternalForm();
return makeString(s);
}
// -------------------------------------------------------------------------
// Elementary print methods are used to ensure output is UTF-8
protected void print(PrintWriter writer, String str) {
writer.print(str);
}
protected void println(PrintWriter writer, String str) {
writer.println(str);
}
}
| 16,593 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
ModelTopic.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/exporters/simberg/ModelTopic.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.application.tools.exporters.simberg;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import org.wandora.application.tools.exporters.simberg.ModelField.Type;
/**
*
* @author olli
*/
public class ModelTopic {
private ModelClass cls;
private final HashMap<ModelField,Object> fields=new HashMap<ModelField,Object>();
public ModelTopic() {
}
public ModelTopic(ModelClass cls) {
this.cls = cls;
}
public ModelClass getCls() {
return cls;
}
public void setCls(ModelClass cls) {
this.cls = cls;
}
public Object getField(ModelField field){
return fields.get(field);
}
public void setField(String field,Object object){
if(cls==null) throw new RuntimeException("ModelTopic class is null, can't set field value.");
ModelField f=cls.findField(field);
if(f==null) throw new RuntimeException("ModelTopic class doesn't have a field "+field);
setField(f,object);
}
public void setField(ModelField field,Object object){
if(cls==null) throw new RuntimeException("ModelTopic class is null, can't set field value.");
if(!cls.hasField(field)) throw new RuntimeException("ModelTopic class doesn't have a field "+field.getName());
if(object==null){
fields.put(field,null);
}
else {
Type type=field.getType();
if(type==Type.String) {
fields.put(field,object.toString());
}
else if(type==Type.StringList) {
if(object instanceof Collection){
ArrayList<String> l=new ArrayList<String>();
for(Object o : (Collection)object){
if(o==null) l.add(null);
else l.add(o.toString());
}
fields.put(field,l);
}
else throw new ClassCastException("Field requires a String list but value is of type "+object.getClass().getName());
}
else if(type==Type.Topic){
if(object instanceof ModelTopic){
fields.put(field,object);
}
else throw new ClassCastException("Field requires a ModelTopic but value is of type "+object.getClass().getName());
}
else if(type==Type.TopicList){
if(object instanceof Collection){
for(Object o : (Collection)object){
if(!(o instanceof ModelTopic)){
throw new ClassCastException("Field requires a ModelTopic list but value list element is of type "+o.getClass().getName());
}
}
fields.put(field,new ArrayList<ModelTopic>((Collection)object));
}
else throw new ClassCastException("Field requires a ModelTopic list but value is of type "+object.getClass().getName());
}
else throw new RuntimeException("Unknown field type "+type);
}
}
}
| 3,964 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
ModelTools.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/exporters/simberg/ModelTools.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.application.tools.exporters.simberg;
import java.io.IOException;
import java.io.Writer;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import org.wandora.application.tools.exporters.simberg.ModelField.Type;
/**
*
* @author olli
*/
public class ModelTools {
private static void scanData(ModelTopic topic,LinkedHashMap<ModelTopic,Integer> topicIndex,LinkedHashMap<ModelClass,Integer> classIndex){
if(topic==null) return;
if(topicIndex.containsKey(topic)) return;
topicIndex.put(topic, topicIndex.size());
ModelClass cls=topic.getCls();
if(!classIndex.containsKey(cls)){
classIndex.put(cls,classIndex.size());
}
for(ModelField field : cls.getFields()){
Object o=topic.getField(field);
if(o==null) continue;
Type type=field.getType();
if(type==Type.Topic){
scanData((ModelTopic)o, topicIndex, classIndex);
}
else if(type==Type.TopicList){
for(ModelTopic t : (List<ModelTopic>)o){
scanData(t, topicIndex, classIndex);
}
}
}
}
private static void scanData(Collection<ModelTopic> topics,LinkedHashMap<ModelTopic,Integer> topicIndex,LinkedHashMap<ModelClass,Integer> classIndex){
for(ModelTopic t : topics){
scanData(t, topicIndex, classIndex);
}
}
private static String escapeJSON(String s){
return s.replace("\\", "\\\\").replace("\"","\\\"");
}
public static void exportJSON(Collection<ModelTopic> topics,Writer out) throws IOException {
LinkedHashMap<ModelTopic,Integer> topicIndex=new LinkedHashMap<ModelTopic,Integer>();
LinkedHashMap<ModelClass,Integer> classIndex=new LinkedHashMap<ModelClass,Integer>();
scanData(topics,topicIndex,classIndex);
out.write("imagesJsonpCallback({\n");
out.write("\"classes\":[\n");
boolean first=true;
for(ModelClass cls : classIndex.keySet()){
if(!first) out.write(",\n");
out.write("[\""+escapeJSON(cls.getName())+"\"");
for(ModelField field : cls.getFields()){
out.write(",");
out.write("[\""+escapeJSON(field.getName())+"\",\""+field.getType().toString()+"\"]");
}
out.write("]");
first=false;
}
out.write("\n],\n");
out.write("\"topics\":[\n");
first=true;
for(ModelTopic topic : topicIndex.keySet()){
if(!first) out.write(",\n");
out.write("[");
out.write(""+classIndex.get(topic.getCls()));
for(ModelField field : topic.getCls().getFields()){
out.write(","); // the class index is always first, no need for the flag varliable
Type type=field.getType();
Object o=topic.getField(field);
if(o==null){
out.write("null");
}
else if(type==Type.String){
out.write("\""+escapeJSON(o.toString())+"\"");
}
else if(type==Type.StringList){
out.write("[");
first=true;
for(String s : (List<String>)o){
if(!first) out.write(",");
first=false;
out.write("\""+escapeJSON(s)+"\"");
}
out.write("]");
}
else if(type==Type.Topic){
out.write(""+topicIndex.get((ModelTopic)o));
}
else if(type==Type.TopicList){
out.write("[");
first=true;
for(ModelTopic t : (List<ModelTopic>)o){
if(!first) out.write(",");
first=false;
out.write(""+topicIndex.get(t));
}
out.write("]");
}
else throw new RuntimeException("Unknown field type "+type);
}
out.write("]");
first=false;
}
out.write("\n],\n");
out.write("});");
}
}
| 5,206 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SimbergExport.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/exporters/simberg/SimbergExport.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*/
package org.wandora.application.tools.exporters.simberg;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.swing.Icon;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.UIBox;
import org.wandora.application.gui.UIConstants;
import org.wandora.application.gui.simple.SimpleFileChooser;
import org.wandora.application.tools.exporters.AbstractExportTool;
import org.wandora.query2.Directive;
import org.wandora.query2.Identity;
import org.wandora.query2.If;
import org.wandora.query2.Instances;
import org.wandora.query2.IsOfType;
import org.wandora.query2.Join;
import org.wandora.query2.Not;
import org.wandora.query2.Null;
import org.wandora.query2.Of;
import org.wandora.query2.OrderBy;
import org.wandora.query2.Players;
import org.wandora.query2.QueryContext;
import org.wandora.query2.QueryException;
import org.wandora.query2.ResultRow;
import org.wandora.query2.Variant2;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.utils.IObox;
import org.wandora.utils.Tuples;
import org.wandora.utils.Tuples.T2;
/**
*
* @author olli
*/
public class SimbergExport extends AbstractExportTool implements WandoraTool {
private static final long serialVersionUID = 1L;
@Override
public String getName() {
return "Simberg export";
}
@Override
public String getDescription() {
return "Exports topic map for Simberg.";
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/fng.png");
}
public static Topic getAssociatedTopic(Topic t,Topic atype,Topic role,HashMap<Topic,Topic> constraints,Topic orderT) throws TopicMapException {
ArrayList<Topic> ret=getAssociatedTopics(t, atype, role, constraints, orderT);
if(ret.isEmpty()) return null;
else return ret.get(0);
}
public static ArrayList<Association> getAssociations(Topic t,Topic atype,HashMap<Topic,Topic> constraints,Topic orderT) throws TopicMapException {
ArrayList<Tuples.T2<Association,Topic>> ret=new ArrayList<Tuples.T2<Association,Topic>>();
AS: for(Association a : t.getAssociations(atype)){
if(constraints!=null){
for(Map.Entry<Topic,Topic> e : constraints.entrySet()){
Topic p=a.getPlayer(e.getKey());
if(p==null || !p.mergesWithTopic(e.getValue())) continue AS;
}
}
Topic order=null;
if(orderT!=null) order=a.getPlayer(orderT);
ret.add(Tuples.t2(a,order));
}
Collections.sort(ret, new Comparator<Tuples.T2<Association,Topic>>(){
public int compare(Tuples.T2<Association, Topic> o1, Tuples.T2<Association, Topic> o2) {
if(o1.e2==null){
if(o2.e2==null) return 0;
else return -1;
}
else if(o2.e2==null) return 1;
else {
try{
if(o1.e2.getBaseName()==null){
if(o2.e2.getBaseName()==null) return 0;
else return -1;
}
else if(o2.e2.getBaseName()==null) return 1;
else return o1.e2.getBaseName().compareTo(o2.e2.getBaseName());
}catch(TopicMapException tme){
return 0;
}
}
}
});
ArrayList<Association> ret2=new ArrayList<Association>();
for(Tuples.T2<Association,Topic> tu : ret) ret2.add(tu.e1);
return ret2;
}
public static ArrayList<Topic> getAssociatedTopics(Topic t,Topic atype,Topic role,HashMap<Topic,Topic> constraints,Topic orderT) throws TopicMapException {
ArrayList<Association> as=getAssociations(t, atype, constraints, orderT);
ArrayList<Topic> ret=new ArrayList<Topic>();
for(Association a : as){
Topic player=a.getPlayer(role);
if(player!=null) ret.add(player);
}
return ret;
}
public static ArrayList<ModelTopic> getOrMakeTopics(Collection ts,ModelClass cls,String nameField,HashMap<T2<ModelClass,Object>,ModelTopic> modelTopics) throws TopicMapException {
return getOrMakeTopics(ts, cls, nameField, modelTopics, null);
}
public static ArrayList<ModelTopic> getOrMakeTopics(Collection ts,ModelClass cls,String nameField,HashMap<T2<ModelClass,Object>,ModelTopic> modelTopics, String lang) throws TopicMapException {
ArrayList<ModelTopic> ret=new ArrayList<ModelTopic>();
for(Object t : ts){
ModelTopic mt=getOrMakeTopic(t, cls, nameField, modelTopics,lang);
ret.add(mt);
}
return ret;
}
public static ModelTopic getOrMakeTopic(Object t,ModelClass cls,String nameField,HashMap<T2<ModelClass,Object>,ModelTopic> modelTopics) throws TopicMapException {
return getOrMakeTopic(t, cls, nameField, modelTopics, null);
}
public static ModelTopic getOrMakeTopic(Object t,ModelClass cls,String nameField,HashMap<T2<ModelClass,Object>,ModelTopic> modelTopics,String lang) throws TopicMapException {
if(t==null) return null;
ModelTopic mt=modelTopics.get(Tuples.t2(cls,t));
if(mt==null) {
mt=new ModelTopic(cls);
if(nameField!=null) {
if(t instanceof Topic){
if(lang!=null) mt.setField(nameField,((Topic)t).getDisplayName(lang));
else mt.setField(nameField, ((Topic)t).getBaseName());
}
else mt.setField(nameField,t.toString());
}
modelTopics.put(Tuples.t2(cls,t),mt);
}
return mt;
}
public static String makeFileName(Topic digikuva) throws TopicMapException {
if(digikuva.getBaseName()==null) return null;
return digikuva.getBaseName().replaceAll("[^a-zA-Z0-9,_-]", "_");
}
public static ArrayList<ResultRow> doQuery(Directive d,Topic context,TopicMap tm,String lang){
try{
return d.doQuery(new QueryContext(tm, lang), context!=null?new ResultRow(context):new ResultRow());
}catch(QueryException qe){
qe.printStackTrace();
return null;
}
}
private static Pattern numberPattern=Pattern.compile("(?:Number )?(\\d+)");
public static String parseMeasure(Object valueO,Object unitO){
if(valueO==null || unitO==null) return null;
String value=valueO.toString().trim();
String unit=unitO.toString().toLowerCase().trim();
if(unit.startsWith("type ")) unit=unit.substring(5).trim();
Matcher matcher=numberPattern.matcher(value);
if(!matcher.matches()) return null;
if(unit.startsWith("mm")) unit="mm";
else if(unit.startsWith("cm")) unit="cm";
else return null;
String fieldValue=matcher.group(1);
fieldValue+=" "+unit;
return fieldValue;
}
public static boolean parseNegative(Object o){
String s=o.toString().toLowerCase();
int pind=s.indexOf("positiivi");
int nind=s.indexOf("negatiivi");
if(pind<0 && nind>=0) return true;
else if(pind>=0 && nind<0) return false;
else if(pind<0 && nind<0) return true;
else {
if(s.substring(nind).startsWith("negatiivista")) return false;
else return true;
}
}
public static Object getResult(ArrayList<ResultRow> res,String role){
if(res.isEmpty()) return null;
return res.get(0).get(role);
}
public static Topic getTopicResult(ArrayList<ResultRow> rows,String role) {
if(rows.isEmpty()) return null;
try{
return (Topic)rows.get(0).getValue(role);
}catch(QueryException qe){ qe.printStackTrace(); return null;}
}
public static ArrayList<Topic> getTopicResults(ArrayList<ResultRow> rows,String role) {
ArrayList<Topic> ret=new ArrayList<Topic>();
for(ResultRow row : rows){
Object o;
try{
if(role!=null) o=row.getValue(role);
else o=row.getActiveValue();
if(o==null || !(o instanceof Topic)) continue;
else ret.add((Topic)o);
}catch(QueryException qe){ qe.printStackTrace(); }
}
return ret;
}
public static int[] levenshtein(String text,String query){
int[][] distance = new int[text.length() + 1][query.length() + 1];
for(int i=0;i<=text.length();i++) distance[i][0] = 0;
for(int i=1;i<=query.length();i++) distance[0][i] = i;
String ignoreChars=" \t.-";
for(int i=1;i<=text.length();i++)
for(int j=1;j<=query.length();j++)
distance[i][j]=Math.min(
distance[i-1][j]+(ignoreChars.indexOf((int)text.charAt(i-1))>=0?0:1),
Math.min(
distance[i][j-1]+(ignoreChars.indexOf((int)query.charAt(j-1))>=0?0:1),
distance[i-1][j-1]+((text.charAt(i-1)==query.charAt(j-1))?0:1)
)
);
int end=0;
int min=query.length();
for(int i=0;i<=text.length();i++){
if(distance[i][query.length()]<min) {
min=distance[i][query.length()];
end=i;
}
}
int j=query.length();
int start=end;
while(j>0){
int s1=query.length();
int s2=query.length();
int s3=distance[start][j-1];
if(start>0 && j>0) s1=distance[start-1][j-1];
if(start>0) s2=distance[start-1][j];
if(s1<=s2 && s1<=s3){
start--;
j--;
}
else if(s2<=s1 && s2<=s3){
start--;
}
else {
j--;
}
}
return new int[]{min,start,end};
}
public static ArrayList<String> readKeywords(File f) throws IOException {
ArrayList<String> ret=new ArrayList<String>();
BufferedReader reader=new BufferedReader(new InputStreamReader(new FileInputStream(f),"UTF-8"));
String line=null;
while((line=reader.readLine())!=null){
line=line.trim();
if(line.isEmpty()) continue;
ret.add(line);
}
return ret;
}
public static T2<ArrayList<String>,String> matchKeywords(String keywordString,ArrayList<String> keywordList){
String stopChars=" ,;.()[]";
Collections.sort(keywordList,new Comparator<String>(){
@Override
public int compare(String o1, String o2) {
int l1=o1.length();
int l2=o2.length();
if(l1!=l2){
if(l1>l2) return -1;
else return 1;
}
else return o1.compareTo(o2);
}
});
ArrayList<String> matched=new ArrayList<String>();
String keywordLinks=keywordString;
keywordString=keywordString.toLowerCase();
for(String keyword : keywordList){
int[] m=levenshtein(keywordString, keyword.toLowerCase());
if(m[0]<=Math.floor(keyword.length()/10)) {
int start=m[1];
int end=m[2];
for(;start>=0;start--) if(stopChars.indexOf(keywordString.charAt(start))>=0) break;
start++;
for(;end<keywordString.length();end++) if(stopChars.indexOf(keywordString.charAt(end))>=0) break;
// disable fuzzy matching for some very similar but distinct names
if(keyword.indexOf("Elma")>0 || keyword.indexOf("Elsa")>0 || keyword.indexOf("Elsi")>0){
if(m[0]!=0) continue;
}
if(keyword.indexOf(" ")==-1){ // skip these checks if the keyword itself consists of several words
if(end-m[2]>0 && m[1]-start>0) continue; // match strictly inside a word
if(keyword.length()<=4 && end-m[2]>1) continue; // a small keyword is a prefix of something big
if(keyword.length()<=4 && m[1]-start>0) continue; // a small keyword is a postfix of something
}
// Add the link to keywordLinks
// If matched word exactly matches the keyword, don't repeat the keyword, otherwise it must be included
// in the link so we know what to link to. Use wiki style links.
String link=keywordLinks.substring(start,end);
if(!link.equals(keyword)) link=link+"|"+keyword;
keywordLinks=keywordLinks.substring(0,start)+"["+link+"]"+keywordLinks.substring(end);
// blank out the matched area in keywordString and keep it aligned with keywordLinks
StringBuilder padding=new StringBuilder();
for(int i=0;i<link.length();i++) padding.append(" ");
keywordString=keywordString.substring(0,start)+"["+padding+"]"+keywordString.substring(end);
// add the matched keyword in the array
matched.add(keyword);
/*
if(start>end){
System.out.println("Matched "+keyword+" to "+
keywordString.substring(Math.max(0,start-10),m[1])+"|^|"+
keywordString.substring(end,Math.min(keywordString.length(),m[1]+10))
);
}
else{
System.out.println("Matched "+keyword+" to "+
keywordString.substring(Math.max(0,start-10),start)+"|"+
keywordString.substring(start,m[1])+"^"+
keywordString.substring(m[1],end)+"|"+
keywordString.substring(end,Math.min(keywordString.length(),end+10))
);
}*/
}
}
/*
Collections.sort(keywordsAndPos,new Comparator<T2<String,Integer>>(){
@Override
public int compare(T2<String, Integer> o1, T2<String, Integer> o2) {
if(o1.e2==o2.e2) return o1.e1.compareTo(o2.e1); // shouldn't really happen
else return o1.e2-o2.e2;
}
});
ArrayList<String> ret=new ArrayList<String>();
for(T2<String,Integer> e : keywordsAndPos){
ret.add(e.e1);
}
return ret;*/
return Tuples.t2(matched, keywordLinks);
}
// This reads the image dimensions without reading the whole file, which would take
// a lot of time for a big collection of big images.
public static int[] getImageDimensions(File f) throws IOException {
ImageInputStream in = ImageIO.createImageInputStream(f);
try{
final Iterator readers = ImageIO.getImageReaders(in);
if(readers.hasNext()){
ImageReader reader=(ImageReader)readers.next();
try{
reader.setInput(in);
return new int[]{reader.getWidth(0), reader.getHeight(0)};
}finally{
reader.dispose();
}
}
}finally {
if(in!=null) in.close();
}
return null;
}
public static Collection<ModelTopic> buildModel(TopicMap tm,String imagesDir,ArrayList<String> keywordList) throws TopicMapException {
String lang="fi";
ModelClass photoCls=new ModelClass("photograph");
photoCls.addField(new ModelField("leveys", ModelField.Type.String));
photoCls.addField(new ModelField("korkeus", ModelField.Type.String));
photoCls.addField(new ModelField("date", ModelField.Type.String));
photoCls.addField(new ModelField("dateRaw", ModelField.Type.String));
photoCls.addField(new ModelField("digital", ModelField.Type.Topic));
photoCls.addField(new ModelField("digitalneg", ModelField.Type.Topic));
photoCls.addField(new ModelField("technique", ModelField.Type.TopicList));
photoCls.addField(new ModelField("author", ModelField.Type.Topic));
photoCls.addField(new ModelField("identifier", ModelField.Type.String));
photoCls.addField(new ModelField("keywords", ModelField.Type.TopicList));
photoCls.addField(new ModelField("keywordText", ModelField.Type.String));
photoCls.addField(new ModelField("material", ModelField.Type.Topic));
ModelClass keywordCls=new ModelClass("keyword");
keywordCls.addField(new ModelField("name", ModelField.Type.String));
/* ModelClass pictureCls=new ModelClass("original");
pictureCls.addField(new ModelField("name", ModelField.Type.String));
pictureCls.addField(new ModelField("author", ModelField.Type.TopicList));
pictureCls.addField(new ModelField("keeper", ModelField.Type.Topic));
pictureCls.addField(new ModelField("time", ModelField.Type.String));
pictureCls.addField(new ModelField("material", ModelField.Type.TopicList));
pictureCls.addField(new ModelField("leveys", ModelField.Type.String));
pictureCls.addField(new ModelField("korkeus", ModelField.Type.String));
pictureCls.addField(new ModelField("nayttelytiedot", ModelField.Type.TopicList));
// pictureCls.addField(new ModelField("keywords", ModelField.Type.TopicList));
pictureCls.addField(new ModelField("identifier", ModelField.Type.String));*/
ModelClass digiCls=new ModelClass("digi");
digiCls.addField(new ModelField("file", ModelField.Type.String));
digiCls.addField(new ModelField("width", ModelField.Type.String));
digiCls.addField(new ModelField("height", ModelField.Type.String));
digiCls.addField(new ModelField("isnegative", ModelField.Type.String));
ModelClass personCls=new ModelClass("person");
personCls.addField(new ModelField("name", ModelField.Type.String));
personCls.addField(new ModelField("born", ModelField.Type.String));
personCls.addField(new ModelField("died", ModelField.Type.String));
/* ModelClass keeperCls=new ModelClass("keeper");
keeperCls.addField(new ModelField("name", ModelField.Type.String));
ModelClass materialCls=new ModelClass("material");
materialCls.addField(new ModelField("name", ModelField.Type.String));
ModelClass timeCls=new ModelClass("time");
timeCls.addField(new ModelField("name", ModelField.Type.String));
ModelClass activityCls=new ModelClass("activity");
activityCls.addField(new ModelField("name", ModelField.Type.String));*/
ModelClass techniqueCls=new ModelClass("technique");
techniqueCls.addField(new ModelField("name", ModelField.Type.String));
ModelClass materialCls=new ModelClass("material");
materialCls.addField(new ModelField("name", ModelField.Type.String));
Directive query=
new If(
new Variant2("http://www.muusa.net/E55.Type_sisaltokuvaus_"+lang).as("#nega"),
new If.COND(),
new Identity().join(new Null().as("#nega"))
)
.from(
new If(
new Players("http://www.muusa.net/P62.depicts"
,"http://www.muusa.net/Source")
.whereInputIs("http://www.muusa.net/Target")
.where(new Not(new IsOfType("http://www.muusa.net/Valokuva"))).as("#digikuva"),
new If.COND(),
new Identity().join(new Null().as("#digikuva"))
)
.from(
new Instances().from("http://www.muusa.net/Valokuva")
.as("#photograph")
)
)
// .where(new Of("#nega"),"!=",null)
;
ArrayList<ResultRow> res=doQuery(query, null, tm, lang);
Pattern datePattern=Pattern.compile("\\d\\d\\d\\d");
ModelTopic unknownAuthor=new ModelTopic(personCls);
unknownAuthor.setField("name","Tuntematon");
HashMap<T2<ModelClass,Object>,ModelTopic> modelTopics=new HashMap<T2<ModelClass,Object>,ModelTopic>();
for(ResultRow row : res ){
Topic digi=(Topic)row.get("#digikuva");
Topic photograph=(Topic)row.get("#photograph");
String negaInfo=(String)row.get("#nega");
if(photograph==null) continue;
ModelTopic photoM=modelTopics.get(Tuples.t2(photoCls,(Object)photograph));
if(photoM==null){
photoM=new ModelTopic(photoCls);
query=
new Join(new Directive[]{
new If(
new Players("http://www.muusa.net/P14.Production_carried_out_by","http://www.muusa.net/E39.Actor").as("#author"),
new If.COND(),
new Null().as("#author")
),
new Players("http://www.muusa.net/E52.Time-Span","http://www.muusa.net/E52.Time-Span").as("#timespan"),
new Players("http://www.muusa.net/P129.is_about",
"http://www.muusa.net/P129.is_about","http://www.muusa.net/E32.Authority_Document")
.usingColumns("#keyword","#keywordtype")
.where(new Of("#keywordtype"), "t=", "http://www.muusa.net/P71_lists_asiasanat"),
new If(
new Players("http://www.muusa.net/P43.has_dimension",
"http://www.muusa.net/P43.has_dimension_role_1",
"http://www.muusa.net/P43.has_dimension_role_3",
"http://www.muusa.net/P43.has_dimension_role_2")
.usingColumns("~dimtype","#leveysunit","#leveys")
.where(new Of("~dimtype"),"t=","http://www.muusa.net/E55.Type_leveys"),
new If.COND(),
new Join(new Null().as("#leveysunit"),new Null().as("#leveys"))
),
new If(
new Players("http://www.muusa.net/P43.has_dimension",
"http://www.muusa.net/P43.has_dimension_role_1",
"http://www.muusa.net/P43.has_dimension_role_3",
"http://www.muusa.net/P43.has_dimension_role_2")
.usingColumns("~dimtype","#korkeusunit","#korkeus")
.where(new Of("~dimtype"),"t=","http://www.muusa.net/E55.Type_korkeus"),
new If.COND(),
new Join(new Null().as("#korkeusunit"),new Null().as("#korkeus"))
),
new If(
new Players("http://www.muusa.net/P45.consists_of","http://www.muusa.net/P45.consists_of_role_0")
.as("#material"),
new If.COND(),
new Null().as("#material")
)
}).from(new Identity().as("#photograph"));
ArrayList<ResultRow> res2=doQuery(query,photograph,tm,lang);
photoM.setField("identifier", photograph.getBaseName());
photoM.setField("leveys", parseMeasure(getResult(res2,"#leveys"),getResult(res2,"#leveysunit")));
photoM.setField("korkeus", parseMeasure(getResult(res2,"#korkeus"),getResult(res2,"#korkeusunit")));
Object date=getResult(res2,"#timespan");
photoM.setField("dateRaw", date);
if(date!=null){
Matcher m=datePattern.matcher(date.toString());
String parsedDate=null;
if(m.find()) {
parsedDate=m.group();
}
photoM.setField("date", parsedDate);
}
else photoM.setField("date", null);
Topic author=(Topic)getResult(res2,"#author");
if(author!=null){
ModelTopic authorM=modelTopics.get(Tuples.t2(personCls,(Object)author));
if(authorM==null){
authorM=new ModelTopic(personCls);
authorM.setField("name",author.getBaseName());
modelTopics.put(Tuples.t2(personCls,(Object)author),authorM);
}
photoM.setField("author",authorM);
}
else {
photoM.setField("author",unknownAuthor);
}
if(keywordList!=null){
Topic keywordStringTopic=getTopicResult(res2,"#keyword");
String keywordString=null;
T2<ArrayList<String>,String> keywords=null;
if(keywordStringTopic!=null) keywordString=keywordStringTopic.getBaseName();
if(keywordString==null || keywordString.trim().length()==0) keywordString="valokuvat";
else keywordString="valokuvat, "+keywordString;
keywords=matchKeywords(keywordString, keywordList);
if(keywords!=null){
ArrayList<ModelTopic> keywordsM=getOrMakeTopics(keywords.e1, keywordCls, "name", modelTopics,lang);
photoM.setField("keywords",keywordsM);
photoM.setField("keywordText",keywords.e2);
}
else photoM.setField("keywords",new ArrayList<ModelTopic>());
}
else photoM.setField("keywords",new ArrayList<ModelTopic>());
/*
{
Topic keywordStringTopic=getTopicResult(res2,"#keyword");
if(keywordStringTopic!=null){
String keywords=keywordStringTopic.getBaseName().trim();
photoM.setField("keywords",keywords);
}
}
*/
Topic material=(Topic)getResult(res2,"#material");
if(material!=null){
ModelTopic materialM=modelTopics.get(Tuples.t2(materialCls,(Object)material));
if(materialM==null){
String name=material.getBaseName();
if(name.startsWith("valokuvamateriaali")) name=name.substring("valokuvamateriaali".length()).trim();
int ind=name.indexOf("vpakkane");
if(ind>=0) name=name.substring(0,ind).trim();
materialM=new ModelTopic(materialCls);
materialM.setField("name",name);
modelTopics.put(Tuples.t2(materialCls,(Object)material),materialM);
}
photoM.setField("material",materialM);
}
res2=doQuery(
new OrderBy(
new Players("http://www.muusa.net/P32.used_general_technique",
"http://www.muusa.net/P32.used_general_technique","http://www.muusa.net/Order")
.usingColumns("#technique","#order").to(new Of("#order"))
), photograph, tm, lang);
ArrayList<Topic> techniques=getTopicResults(res2, "#technique");
ArrayList<ModelTopic> techniquesM=getOrMakeTopics(techniques, techniqueCls, "name", modelTopics, lang);
photoM.setField("technique",techniquesM);
/*
res2=doQuery(
new OrderBy(
new Players("http://www.muusa.net/P129.is_about",
"http://www.muusa.net/P129.is_about","http://www.muusa.net/E32.Authority_Document")
.usingColumns("#keyword","#keywordtype")
.where(new Of("#keywordtype"), "t=", "http://www.muusa.net/P71_lists_asiasanat")
), photograph, tm, lang);
ArrayList<Topic> keywords=getTopicResults(res2, "#keyword");
ArrayList<ModelTopic> keywordsM=getOrMakeTopics(keywords, keywordCls, "name", modelTopics,lang);
photoM.setField("keywords",keywordsM);*/
modelTopics.put(Tuples.t2(photoCls,(Object)photograph), photoM);
}
if(digi!=null && negaInfo!=null){
boolean negative=parseNegative(negaInfo);
ModelTopic digiM=new ModelTopic(digiCls);
digiM.setField("isnegative",negative?"1":"0");
String imageFile=makeFileName(digi);
digiM.setField("file",imageFile);
int width=0;
int height=0;
if(imagesDir!=null){
File f=new File(imagesDir+imageFile+".jpg");
if(f.exists()){
try{
/* BufferedImage bi=ImageIO.read(f);
width=bi.getWidth();
height=bi.getHeight();*/
int[] dim=getImageDimensions(f);
if(dim!=null){
width=dim[0];
height=dim[1];
}
}
catch(IOException ioe){
}
}
}
digiM.setField("width",""+width);
digiM.setField("height",""+height);
if(negative) photoM.setField("digitalneg",digiM);
else photoM.setField("digital",digiM);
modelTopics.put(Tuples.t2(digiCls,(Object)digi),digiM);
}
}
return modelTopics.values();
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
TopicMap tm=Wandora.getWandora().getTopicMap();
SimpleFileChooser chooser=UIConstants.getFileChooser();
chooser.setDialogTitle("Export nyblin data as JSON");
if(chooser.open(wandora, "Export")==SimpleFileChooser.APPROVE_OPTION){
setDefaultLogger();
File file = chooser.getSelectedFile();
// --- Finally write topicmap as GXL to chosen file
OutputStream out=null;
try {
file=IObox.addFileExtension(file, "json"); // Ensure file extension exists!
String parentDir=file.getParent();
if(!(parentDir.endsWith("/") || parentDir.endsWith("\\"))) parentDir+="/";
ArrayList<String> keywords=null;
File keywordFile=new File(parentDir+"keywords.txt");
if(keywordFile.exists()) {
keywords=readKeywords(keywordFile);
if(keywords.indexOf("valokuvat")==-1) keywords.add("valokuvat");
}
out=new FileOutputStream(file);
OutputStreamWriter writer=new OutputStreamWriter(out,"UTF-8");
Collection<ModelTopic> modelTopics=buildModel(tm,parentDir+"images/",keywords);
ModelTools.exportJSON(modelTopics, writer);
writer.close();
}
catch(Exception e){
log(e);
try { if(out != null) out.close(); }
catch(Exception e2) { log(e2); }
}
}
setState(WAIT);
}
/*
public static void main(String[] args){
String test="taiteilija, Simberg-suku, kesäpaikka Niemenlautta, Säkkijärvi, ".toLowerCase();
int[] ret=levenshtein(test,"niemenlautta");
System.out.println(ret[0]+" "+ret[1]+" "+ret[2]);
System.out.println(test);
for(int i=0;i<test.length();i++){
if(i==ret[1] || i==ret[2]) System.out.print("^");
else System.out.print(" ");
}
System.out.println();
}*/
}
| 34,946 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.