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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
ArtistRelatedArtistsExtractor.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/audioscrobbler/ArtistRelatedArtistsExtractor.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* RelatedArtistsExtractor.java
*
* Created on 11. toukokuuta 2007, 18:15
*
*/
package org.wandora.application.tools.extractors.audioscrobbler;
import java.io.InputStream;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
/**
* Extractor reads specific XML feed from Audioscrobbler's web api and converts the
* XML feed to a topic map. Extractor reads the Related Artists feed. Example
* of Related Artists is found at
*
* http://ws.audioscrobbler.com/1.0/artist/Metallica/similar.xml
*
* Audioscrobber's web api documentation is found at
*
* http://www.audioscrobbler.net/data/webservices/
*
* @author akivela
*/
public class ArtistRelatedArtistsExtractor extends AbstractAudioScrobblerExtractor {
private static final long serialVersionUID = 1L;
/**
* Creates a new instance of ArtistRelatedArtistsExtractor
*/
public ArtistRelatedArtistsExtractor() {
}
@Override
public String getName() {
return "Audioscrobbler Artists: Related Artists extractor";
}
@Override
public String getDescription(){
return "Extractor reads the Related Artist XML feed from Audioscrobbler's web api and converts the XML feed to a topic map. "+
"See http://ws.audioscrobbler.com/1.0/artist/Metallica/similar.xml for an example of Related Artists XML feed.";
}
public boolean _extractTopicsFrom(InputStream in, TopicMap topicMap) throws Exception {
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();
ArtistRelatedArtistsParser parserHandler = new ArtistRelatedArtistsParser(topicMap,this);
reader.setContentHandler(parserHandler);
reader.setErrorHandler(parserHandler);
try{
reader.parse(new InputSource(in));
}catch(Exception e){
if(!(e instanceof SAXException) || !e.getMessage().equals("User interrupt")) log(e);
}
log("Total " + parserHandler.progress + " related artists found!");
return true;
}
private static class ArtistRelatedArtistsParser implements org.xml.sax.ContentHandler, org.xml.sax.ErrorHandler {
public ArtistRelatedArtistsParser(TopicMap tm,ArtistRelatedArtistsExtractor parent){
this.tm=tm;
this.parent=parent;
}
public int progress = 0;
private TopicMap tm;
private ArtistRelatedArtistsExtractor parent;
public static final String TAG_SIMILARARTISTS="similarartists";
public static final String TAG_ARTIST="artist";
public static final String TAG_ARTIST_NAME="name";
public static final String TAG_ARTIST_MBID="mbid";
public static final String TAG_ARTIST_MATCH="match";
public static final String TAG_ARTIST_URL="url";
public static final String TAG_ARTIST_IMAGE_SMALL="image_small";
public static final String TAG_ARTIST_IMAGE="image";
public static final String TAG_ARTIST_STREAMABLE="streamable";
private static final int STATE_START=0;
private static final int STATE_SIMILARARTISTS=1;
private static final int STATE_ARTIST=2;
private static final int STATE_ARTIST_NAME=3;
private static final int STATE_ARTIST_MBID=4;
private static final int STATE_ARTIST_MATCH=5;
private static final int STATE_ARTIST_URL=6;
private static final int STATE_ARTIST_IMAGE_SMALL=7;
private static final int STATE_ARTIST_IMAGE=8;
private static final int STATE_ARTIST_STREAMABLE=9;
private int state=STATE_START;
private String data_artist = "";
private String data_artist_name = "";
private String data_artist_mbid = "";
private String data_artist_match = "";
private String data_artist_url = "";
private String data_artist_image_small = "";
private String data_artist_image = "";
private String data_artist_streamable = "";
private Topic theArtist;
public void startDocument() throws SAXException {
}
public void endDocument() throws SAXException {
}
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
if(parent.forceStop()){
throw new SAXException("User interrupt");
}
switch(state){
case STATE_START:
if(qName.equals(TAG_SIMILARARTISTS)) {
state = STATE_SIMILARARTISTS;
String theName = atts.getValue("artist");
String theMBID = atts.getValue("mbid");
String theStreamable = atts.getValue("streamable");
String thePicture = atts.getValue("picture");
if(theName != null) {
try {
Topic artistType = getArtistTypeTopic(tm);
theArtist=getArtistTopic(tm, theName, null, theMBID);
if(theStreamable != null) {
Topic streamableType = getOrCreateTopic(tm, STREAMABLE_SI,"Streamable");
parent.setData(theArtist, streamableType, LANG, theStreamable);
//theArtist.setData(streamableType, langIndep, theStreamable);
}
if(thePicture != null) {
Topic imageType = getImageTypeTopic(tm);
Topic image = getImageTopic(tm, thePicture, "artist "+theName);
Association imagea = tm.createAssociation(imageType);
imagea.addPlayer(image, imageType);
imagea.addPlayer(theArtist, artistType);
}
theArtist.addType(artistType);
}
catch(Exception e) {
parent.log(e);
}
}
}
break;
case STATE_SIMILARARTISTS:
if(qName.equals(TAG_ARTIST)) {
state = STATE_ARTIST;
data_artist_name = "";
data_artist_mbid = "";
data_artist_match = "";
data_artist_url = "";
data_artist_image_small = "";
data_artist_image = "";
data_artist_streamable = "";
}
break;
case STATE_ARTIST:
if(qName.equals(TAG_ARTIST_NAME)) {
state = STATE_ARTIST_NAME;
data_artist_name = "";
}
else if(qName.equals(TAG_ARTIST_MBID)) {
state = STATE_ARTIST_MBID;
data_artist_mbid = "";
}
else if(qName.equals(TAG_ARTIST_MATCH)) {
state = STATE_ARTIST_MATCH;
data_artist_match = "";
}
else if(qName.equals(TAG_ARTIST_URL)) {
state = STATE_ARTIST_URL;
data_artist_url = "";
}
else if(qName.equals(TAG_ARTIST_IMAGE_SMALL)) {
state = STATE_ARTIST_IMAGE_SMALL;
data_artist_image_small = "";
}
else if(qName.equals(TAG_ARTIST_IMAGE)) {
state = STATE_ARTIST_IMAGE;
data_artist_image = "";
}
else if(qName.equals(TAG_ARTIST_STREAMABLE)) {
state = STATE_ARTIST_STREAMABLE;
data_artist_streamable = "";
}
break;
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
switch(state) {
case STATE_ARTIST: {
if(data_artist_mbid.length() > 0){
try {
Topic artistType=getArtistTypeTopic(tm);
Topic similarArtistType=getSimilarArtistsTypeTopic(tm);
Topic artistTopic=getArtistTopic(tm, data_artist_name, data_artist_url, data_artist_mbid);
if(data_artist_streamable.length() > 0) {
Topic streamableType = getStreamableTypeTopic(tm);
parent.setData(artistTopic, streamableType, LANG, data_artist_streamable);
}
artistTopic.addType(artistType);
if(theArtist != null) {
Association saa=tm.createAssociation(similarArtistType);
saa.addPlayer(theArtist, artistType);
saa.addPlayer(artistTopic, similarArtistType);
if(CONVERT_MATCH && data_artist_match.length() > 0) {
Topic matchTopic = getMatchTopic(tm, data_artist_match);
Topic matchType = getMatchTypeTopic(tm);
saa.addPlayer(matchTopic, matchType);
}
}
if(data_artist_image.length() > 0) {
Topic image = getImageTopic(tm, data_artist_image, "artist "+data_artist_name );
Topic imageType = getImageTypeTopic(tm);
Association imagea = tm.createAssociation(imageType);
imagea.addPlayer(image, imageType);
imagea.addPlayer(artistTopic, artistType);
}
parent.setProgress(++progress);
}
catch(TopicMapException tme){
parent.log(tme);
}
}
state=STATE_SIMILARARTISTS;
break;
}
case STATE_ARTIST_NAME: {
state=STATE_ARTIST;
break;
}
case STATE_ARTIST_MBID: {
state=STATE_ARTIST;
break;
}
case STATE_ARTIST_MATCH: {
state=STATE_ARTIST;
break;
}
case STATE_ARTIST_URL: {
state=STATE_ARTIST;
break;
}
case STATE_ARTIST_IMAGE_SMALL: {
state=STATE_ARTIST;
break;
}
case STATE_ARTIST_IMAGE: {
state=STATE_ARTIST;
break;
}
case STATE_ARTIST_STREAMABLE: {
state=STATE_ARTIST;
break;
}
}
}
public void characters(char[] ch, int start, int length) throws SAXException {
switch(state){
case STATE_ARTIST_NAME:
data_artist_name+=new String(ch,start,length);
break;
case STATE_ARTIST_MBID:
data_artist_mbid+=new String(ch,start,length);
break;
case STATE_ARTIST_MATCH:
data_artist_match+=new String(ch,start,length);
break;
case STATE_ARTIST_URL:
data_artist_url+=new String(ch,start,length);
break;
case STATE_ARTIST_IMAGE_SMALL:
data_artist_image_small+=new String(ch,start,length);
break;
case STATE_ARTIST_IMAGE:
data_artist_image+=new String(ch,start,length);
break;
case STATE_ARTIST_STREAMABLE:
data_artist_streamable+=new String(ch,start,length);
break;
}
}
public void warning(SAXParseException exception) throws SAXException {
}
public void error(SAXParseException exception) throws SAXException {
parent.log("Error parsing XML document at "+exception.getLineNumber()+","+exception.getColumnNumber(),exception);
}
public void fatalError(SAXParseException exception) throws SAXException {
parent.log("Fatal error parsing XML document at "+exception.getLineNumber()+","+exception.getColumnNumber(),exception);
}
public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {}
public void processingInstruction(String target, String data) throws SAXException {}
public void startPrefixMapping(String prefix, String uri) throws SAXException {}
public void endPrefixMapping(String prefix) throws SAXException {}
public void setDocumentLocator(org.xml.sax.Locator locator) {}
public void skippedEntity(String name) throws SAXException {}
}
}
| 15,175 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AbstractAudioScrobblerExtractor.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/audioscrobbler/AbstractAudioScrobblerExtractor.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* AbstractAudioScrobblerExtractor.java
*
*/
package org.wandora.application.tools.extractors.audioscrobbler;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import javax.swing.Icon;
import org.wandora.application.WandoraToolType;
import org.wandora.application.gui.UIBox;
import org.wandora.application.tools.extractors.AbstractExtractor;
import org.wandora.application.tools.extractors.ExtractHelper;
import org.wandora.topicmap.TMBox;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author akivela
*/
public abstract class AbstractAudioScrobblerExtractor extends AbstractExtractor {
private static final long serialVersionUID = 1L;
// Default language of occurrences and variant names.
public static String LANG = "en";
public static boolean CONVERT_COUNTS = false;
//
public static boolean CONVERT_REACH = false;
// Add match strength as a third player to the association between similar artists.
public static boolean CONVERT_MATCH = false;
// Add track index as a third player to the association between album and track.
public static boolean CONVERT_TRACK_INDEX = true;
// Convert tag usage counts as tag topic occurrences or topics associated to tag topics.
public static boolean OCCURRENCE_COUNTS = true;
/**
* Try to retrieve topic before new is created. Setting this true may speed
* the extraction but extraction may loose some data as topic is created only once.
*/
public static boolean USE_EXISTING_TOPICS = true;
public static final String SIPREFIX="http://www.last.fm/";
public static final String MUSIC_SI=SIPREFIX+"music";
public static final String ARTIST_SI=SIPREFIX+"artist";
public static final String SIMILAR_ARTIST_SI=ARTIST_SI+"/similar";
public static final String MATCH_SI=ARTIST_SI+"/match";
public static final String IMAGE_SI=SIPREFIX+"image";
public static final String MBID_SI=SIPREFIX+"mbid";
public static final String STREAMABLE_SI=SIPREFIX+"streamable";
public static final String ALBUM_SI=SIPREFIX+"album";
public static final String TRACK_SI=SIPREFIX+"track";
public static final String INDEX_SI=SIPREFIX+"index";
public static final String REACH_SI=SIPREFIX+"reach";
public static final String RELEASEDATE_SI=ALBUM_SI+"/releasedate";
public static final String TAG_SI=SIPREFIX+"tag";
public static final String COUNT_SI=SIPREFIX+"count";
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/extract_lastfm.png");
}
@Override
public WandoraToolType getType() {
return WandoraToolType.createExtractType();
}
@Override
public boolean useURLCrawler() {
return false;
}
private final String[] contentTypes=new String[] { "text/xml", "application/xml" };
@Override
public String[] getContentTypes() {
return contentTypes;
}
public boolean _extractTopicsFrom(URL url, TopicMap topicMap) throws Exception {
return _extractTopicsFrom(url.openStream(),topicMap);
}
public boolean _extractTopicsFrom(File file, TopicMap topicMap) throws Exception {
return _extractTopicsFrom(new FileInputStream(file),topicMap);
}
public boolean _extractTopicsFrom(String str, TopicMap topicMap) throws Exception {
return _extractTopicsFrom(new ByteArrayInputStream(str.getBytes()), topicMap);
}
public abstract boolean _extractTopicsFrom(InputStream inputStream, TopicMap topicMap) throws Exception;
// ******** TOPIC MAPS *********
protected static Topic getOrCreateTopic(TopicMap tm, String si) throws TopicMapException {
return getOrCreateTopic(tm, si,null);
}
protected static Topic getOrCreateTopic(TopicMap tm, String si, String bn) throws TopicMapException {
return ExtractHelper.getOrCreateTopic(si, bn, tm);
}
protected static void makeSubclassOf(TopicMap tm, Topic t, Topic superclass) throws TopicMapException {
ExtractHelper.makeSubclassOf(t, superclass, tm);
}
// ******** TYPE TOPICS **********
protected static Topic getArtistTypeTopic(TopicMap tm) throws TopicMapException {
Topic artistType = getOrCreateTopic(tm, ARTIST_SI, "last.fm artist");
Topic scClass = getScrobblerClassTopic(tm);
makeSubclassOf(tm, artistType, scClass);
return artistType;
}
protected static Topic getImageTypeTopic(TopicMap tm) throws TopicMapException {
Topic imageType = getOrCreateTopic(tm, IMAGE_SI, "last.fm image");
Topic scClass = getScrobblerClassTopic(tm);
makeSubclassOf(tm, imageType, scClass);
return imageType;
}
protected static Topic getAlbumTypeTopic(TopicMap tm) throws TopicMapException {
Topic albumType = getOrCreateTopic(tm, ALBUM_SI, "last.fm album");
Topic scClass = getScrobblerClassTopic(tm);
makeSubclassOf(tm, albumType, scClass);
return albumType;
}
protected static Topic getTrackTypeTopic(TopicMap tm) throws TopicMapException {
Topic trackType=getOrCreateTopic(tm, TRACK_SI, "last.fm track");
Topic scClass = getScrobblerClassTopic(tm);
makeSubclassOf(tm, trackType, scClass);
return trackType;
}
protected static Topic getTagTypeTopic(TopicMap tm) throws TopicMapException {
Topic tagType=getOrCreateTopic(tm, TAG_SI, "last.fm tag");
Topic scClass = getScrobblerClassTopic(tm);
makeSubclassOf(tm, tagType, scClass);
return tagType;
}
protected static Topic getIndexTypeTopic(TopicMap tm) throws TopicMapException {
Topic indexType=getOrCreateTopic(tm, INDEX_SI, "last.fm index");
return indexType;
}
protected static Topic getReachTypeTopic(TopicMap tm) throws TopicMapException {
Topic indexType=getOrCreateTopic(tm, REACH_SI, "last.fm reach");
return indexType;
}
protected static Topic getMatchTypeTopic(TopicMap tm) throws TopicMapException {
Topic matchType=getOrCreateTopic(tm, MATCH_SI, "last.fm match");
return matchType;
}
protected static Topic getCountTypeTopic(TopicMap tm) throws TopicMapException {
Topic countType=getOrCreateTopic(tm, COUNT_SI, "last.fm count");
return countType;
}
protected static Topic getStreamableTypeTopic(TopicMap tm) throws TopicMapException {
Topic countType=getOrCreateTopic(tm, STREAMABLE_SI, "last.fm streamable");
return countType;
}
protected static Topic getSimilarArtistsTypeTopic(TopicMap tm) throws TopicMapException {
Topic type=getOrCreateTopic(tm, SIMILAR_ARTIST_SI, "last.fm similar artists");
return type;
}
protected static Topic getScrobblerClassTopic(TopicMap tm) throws TopicMapException {
Topic t = getOrCreateTopic(tm, "http://www.last.fm", "Last.fm");
t.addType(getWandoraClassTopic(tm));
return t;
}
protected static Topic getWandoraClassTopic(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, TMBox.WANDORACLASS_SI,"Wandora class");
}
protected static Topic getMBIDTypeTopic(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, MBID_SI, "MBID");
}
protected static Topic getDefaultLangTopic(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, "http://www.topicmaps.org/xtm/1.0/language.xtm#en", "Language EN");
}
// *********** LASTFM TOPICS ***********
protected static Topic getArtistTopic(TopicMap tm, String theArtistString) throws TopicMapException {
String artistSI = MUSIC_SI + "/" + urlEncode(theArtistString);
Topic theArtist = null;
if(USE_EXISTING_TOPICS) theArtist = tm.getTopic(artistSI);
if(theArtist == null) {
Topic artistType = getArtistTypeTopic(tm);
theArtist=tm.createTopic();
theArtist.addSubjectIdentifier(tm.createLocator(artistSI));
theArtist.setBaseName(theArtistString + " (last.fm artist)");
theArtist.setDisplayName(LANG, theArtistString);
theArtist.addType(artistType);
}
return theArtist;
}
protected static Topic getArtistTopic(TopicMap tm, String theArtistString, String artistUrl, String artistMBID) throws TopicMapException {
Topic artistTopic = getArtistTopic(tm, theArtistString);
if(artistUrl != null && artistUrl.length() > 0) {
artistTopic.addSubjectIdentifier(tm.createLocator(artistUrl));
}
if(artistMBID != null && artistMBID.length() > 0) {
artistTopic.setData(getMBIDTypeTopic(tm), getDefaultLangTopic(tm), artistMBID);
}
return artistTopic;
}
protected static Topic getAlbumTopic(TopicMap tm, String theAlbumString, String theArtistString) throws TopicMapException {
String albumSI = MUSIC_SI + "/" + urlEncode(theArtistString) + "/" + urlEncode(theAlbumString);
Topic theAlbum = null;
if(USE_EXISTING_TOPICS) theAlbum = tm.getTopic(albumSI);
if(theAlbum == null) {
Topic albumType = getAlbumTypeTopic(tm);
theAlbum=tm.createTopic();
theAlbum.addSubjectIdentifier(tm.createLocator(albumSI));
theAlbum.setBaseName(theAlbumString + " (last.fm album)");
theAlbum.setDisplayName(LANG, theAlbumString);
theAlbum.addType(albumType);
}
return theAlbum;
}
protected static Topic getAlbumTopic(TopicMap tm, String theAlbumString, String theAlbumUrl, String theArtistString) throws TopicMapException {
Topic theAlbum = getAlbumTopic(tm, theAlbumString, theArtistString);
org.wandora.topicmap.Locator si = theAlbum.getOneSubjectIdentifier();
if(theAlbumUrl != null && theAlbumUrl.length() > 0) {
if(!theAlbumUrl.equals(si.toExternalForm())) {
theAlbum.addSubjectIdentifier(tm.createLocator(theAlbumUrl));
// REMOVE DEFAULT SI
theAlbum.removeSubjectIdentifier(si);
}
}
return theAlbum;
}
protected static Topic getAlbumTopic(TopicMap tm, String theAlbumString, String theAlbumUrl, String theAlbumMBID, String theArtistString) throws TopicMapException {
Topic theAlbum = getAlbumTopic(tm, theAlbumString, theAlbumUrl, theArtistString);
if(theAlbumMBID != null && theAlbumMBID.length() > 0) {
theAlbum.setData(getMBIDTypeTopic(tm), getDefaultLangTopic(tm), theAlbumMBID);
}
return theAlbum;
}
protected static Topic getTrackTopic(TopicMap tm, String theTrackString, String albumString, String artistString) throws TopicMapException {
String trackSI = MUSIC_SI + "/" + urlEncode(artistString) + "/" + urlEncode(albumString) + "/" + urlEncode(theTrackString);
Topic theTrack = null;
if(USE_EXISTING_TOPICS) theTrack = tm.getTopic(trackSI);
if(theTrack == null) {
Topic trackType=getTrackTypeTopic(tm);
theTrack=tm.createTopic();
theTrack.addSubjectIdentifier(tm.createLocator(trackSI));
theTrack.setBaseName(theTrackString+" (last.fm track)");
theTrack.setDisplayName(LANG, theTrackString);
theTrack.addType(trackType);
}
return theTrack;
}
protected static Topic getTrackTopic(TopicMap tm, String theTrackString, String theTrackUrl, String albumString, String artistString) throws TopicMapException {
Topic theTrack = getTrackTopic(tm, theTrackString, albumString, artistString);
if(theTrackUrl != null && theTrackUrl.length() > 0) {
theTrack.addSubjectIdentifier(tm.createLocator(theTrackUrl));
}
return theTrack;
}
protected static Topic getImageTopic(TopicMap tm, String imageUrl, String owner) throws TopicMapException {
Topic image = null;
if(USE_EXISTING_TOPICS) image = tm.getTopic(imageUrl);
if(image == null) {
image = tm.createTopic();
image.addSubjectIdentifier(tm.createLocator(imageUrl));
image.setSubjectLocator(tm.createLocator(imageUrl));
image.setBaseName("Image of " + owner);
Topic imageType = getImageTypeTopic(tm);
image.addType(imageType);
}
return image;
}
protected static Topic getTagTopic(TopicMap tm, String tag) throws TopicMapException {
String tagSI = TAG_SI + "/" + urlEncode(tag);
Topic tagTopic = null;
if(USE_EXISTING_TOPICS) tagTopic = tm.getTopic(tagSI);
if(tagTopic == null) {
tagTopic = tm.createTopic();
tagTopic.addSubjectIdentifier(tm.createLocator(tagSI));
tagTopic.setBaseName(tag+" (last.fm tag)");
tagTopic.setDisplayName(LANG, tag);
Topic tagType = getTagTypeTopic(tm);
tagTopic.addType(tagType);
}
return tagTopic;
}
protected static Topic getTagTopic(TopicMap tm, String tag, String tagUrl) throws TopicMapException {
Topic tagTopic = getTagTopic(tm, tag);
if(tagUrl != null && tagUrl.length() > 0) tagTopic.addSubjectIdentifier(tm.createLocator(tagUrl));
return tagTopic;
}
protected static Topic getIndexTopic(TopicMap tm, int index) throws TopicMapException {
String indexSI = INDEX_SI + "/" + index;
Topic indexTopic = null;
if(USE_EXISTING_TOPICS) indexTopic = tm.getTopic(indexSI);
if(indexTopic == null) {
indexTopic = tm.createTopic();
indexTopic.addSubjectIdentifier(tm.createLocator(indexSI));
indexTopic.setBaseName(index+" (last.fm)");
indexTopic.setDisplayName(LANG, index+"");
}
return indexTopic;
}
protected static Topic getReachTopic(TopicMap tm, String r) throws TopicMapException {
String reachSI = REACH_SI + "/" + urlEncode(r);
Topic reachTopic = null;
if(USE_EXISTING_TOPICS) reachTopic = tm.getTopic(reachSI);
if(reachTopic == null) {
reachTopic = tm.createTopic();
reachTopic.addSubjectIdentifier(tm.createLocator(reachSI));
reachTopic.setBaseName(r+" (last.fm)");
reachTopic.setDisplayName(LANG, r);
reachTopic.addType(getReachTypeTopic(tm));
}
return reachTopic;
}
protected static Topic getMatchTopic(TopicMap tm, String m) throws TopicMapException {
String matchSI = MATCH_SI + "/" + urlEncode(m);
Topic matchTopic = null;
if(USE_EXISTING_TOPICS) matchTopic = tm.getTopic(matchSI);
if(matchTopic == null) {
matchTopic = tm.createTopic();
matchTopic.addSubjectIdentifier(tm.createLocator(matchSI));
matchTopic.setBaseName(m+" (last.fm)");
matchTopic.setDisplayName(LANG, m);
Topic matchType = getMatchTypeTopic(tm);
matchTopic.addType(matchType);
}
return matchTopic;
}
protected static Topic getCountTopic(TopicMap tm, String c) throws TopicMapException {
String countSI =COUNT_SI + "/" + urlEncode(c);
Topic countTopic = null;
if(USE_EXISTING_TOPICS) countTopic = tm.getTopic(countSI);
if(countTopic == null) {
countTopic = tm.createTopic();
countTopic.addSubjectIdentifier(tm.createLocator(countSI));
countTopic.setBaseName(c+" (last.fm)");
countTopic.setDisplayName(LANG, c);
Topic countType = getCountTypeTopic(tm);
countTopic.addType(countType);
}
return countTopic;
}
}
| 17,089 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
ArtistTopAlbumsExtractor.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/audioscrobbler/ArtistTopAlbumsExtractor.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* TopAlbumsExtractor.java
*
* Created on 13. toukokuuta 2007, 16:44
*/
package org.wandora.application.tools.extractors.audioscrobbler;
import java.io.InputStream;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
/**
* Extractor reads specific XML feed from Audioscrobbler's web api and converts the
* XML feed to a topic map. Extractor reads the Top Albums feed. Example
* of Top Albums is found at
*
* http://ws.audioscrobbler.com/1.0/artist/Metallica/topalbums.xml
*
* Audioscrobber's web api documentation is found at
*
* http://www.audioscrobbler.net/data/webservices/
*
* @author akivela
*/
public class ArtistTopAlbumsExtractor extends AbstractAudioScrobblerExtractor {
private static final long serialVersionUID = 1L;
/** Creates a new instance of ArtistTopAlbumsExtractor */
public ArtistTopAlbumsExtractor() {
}
@Override
public String getName() {
return "Audioscrobbler Artists: Top Albums extractor";
}
@Override
public String getDescription(){
return "Extractor reads the Top Albums XML feed from Audioscrobbler's web api and converts the XML feed to a topic map. "+
"See http://ws.audioscrobbler.com/1.0/artist/Metallica/topalbums.xml for an example of Top Albums XML feed.";
}
public boolean _extractTopicsFrom(InputStream in, TopicMap topicMap) throws Exception {
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();
ArtistTopAlbumsParser parserHandler = new ArtistTopAlbumsParser(topicMap,this);
reader.setContentHandler(parserHandler);
reader.setErrorHandler(parserHandler);
try{
reader.parse(new InputSource(in));
}
catch(Exception e){
if(!(e instanceof SAXException) || !e.getMessage().equals("User interrupt")) log(e);
}
log("Total " + parserHandler.progress + " top albums found!");
return true;
}
private static class ArtistTopAlbumsParser implements org.xml.sax.ContentHandler, org.xml.sax.ErrorHandler {
public ArtistTopAlbumsParser(TopicMap tm,ArtistTopAlbumsExtractor parent){
this.tm=tm;
this.parent=parent;
}
public int progress=0;
private TopicMap tm;
private ArtistTopAlbumsExtractor parent;
public static final String TAG_TOPALBUMS="topalbums";
public static final String TAG_ALBUM="album";
public static final String TAG_NAME="name";
public static final String TAG_MBID="mbid";
public static final String TAG_REACH="reach";
public static final String TAG_URL="url";
public static final String TAG_IMAGE="image";
public static final String TAG_IMAGE_LARGE="large";
public static final String TAG_IMAGE_MEDIUM="medium";
public static final String TAG_IMAGE_SMALL="small";
private static final int STATE_START=0;
private static final int STATE_TOPALBUMS=1;
private static final int STATE_ALBUM=2;
private static final int STATE_NAME=3;
private static final int STATE_MBID=4;
private static final int STATE_REACH=5;
private static final int STATE_URL=6;
private static final int STATE_IMAGE=7;
private static final int STATE_IMAGE_LARGE=8;
private static final int STATE_IMAGE_MEDIUM=9;
private static final int STATE_IMAGE_SMALL=10;
private int state=STATE_START;
private String data_album_name = "";
private String data_album_mbid = "";
private String data_album_reach = "";
private String data_album_url = "";
private String data_album_image_large = "";
private String data_album_image_medium = "";
private String data_album_image_small = "";
private Topic theArtist;
private String theArtistString = "";
public void startDocument() throws SAXException {
}
public void endDocument() throws SAXException {
}
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
if(parent.forceStop()){
throw new SAXException("User interrupt");
}
switch(state){
case STATE_START:
if(qName.equals(TAG_TOPALBUMS)) {
state = STATE_TOPALBUMS;
theArtistString = atts.getValue("artist");
if(theArtistString != null) {
try {
theArtist = getArtistTopic(tm, theArtistString);
}
catch(Exception e) {
parent.log(e);
}
}
}
break;
case STATE_TOPALBUMS:
if(qName.equals(TAG_ALBUM)) {
state = STATE_ALBUM;
data_album_name = "";
data_album_mbid = "";
data_album_reach = "";
data_album_url = "";
data_album_image_large = "";
data_album_image_medium = "";
data_album_image_small = "";
}
break;
case STATE_ALBUM:
if(qName.equals(TAG_NAME)) {
state = STATE_NAME;
data_album_name = "";
}
else if(qName.equals(TAG_MBID)) {
state = STATE_MBID;
data_album_mbid = "";
}
else if(qName.equals(TAG_REACH)) {
state = STATE_REACH;
data_album_reach = "";
}
else if(qName.equals(TAG_URL)) {
state = STATE_URL;
data_album_url = "";
}
else if(qName.equals(TAG_IMAGE)) {
state = STATE_IMAGE;
data_album_image_large = "";
data_album_image_medium = "";
data_album_image_small = "";
}
break;
case STATE_IMAGE:
if(qName.equals(TAG_IMAGE_LARGE)) {
state = STATE_IMAGE_LARGE;
data_album_image_large = "";
}
else if(qName.equals(TAG_IMAGE_MEDIUM)) {
state = STATE_IMAGE_MEDIUM;
data_album_image_medium = "";
}
else if(qName.equals(TAG_IMAGE_SMALL)) {
state = STATE_IMAGE_SMALL;
data_album_image_small = "";
}
break;
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
switch(state) {
case STATE_ALBUM: {
if(data_album_name.length() > 0) {
try {
Topic albumType=getAlbumTypeTopic(tm);
Topic albumTopic=getAlbumTopic(tm, data_album_name, data_album_url, data_album_mbid, theArtistString);
Topic artistType = getArtistTypeTopic(tm);
Association ta=tm.createAssociation(albumType);
ta.addPlayer(theArtist, artistType);
ta.addPlayer(albumTopic, albumType);
parent.setProgress(++progress);
if(CONVERT_REACH && data_album_reach.length() > 0) {
try {
Topic reachTopic = getReachTopic(tm, data_album_reach);
Topic reachType = getReachTypeTopic(tm);
ta.addPlayer(reachTopic, reachType);
}
catch(Exception e) {
parent.log(e);
}
}
String data_album_image = "";
if(data_album_image_large.length() > 0) {
data_album_image = data_album_image_large;
}
else if(data_album_image_medium.length() > 0) {
data_album_image = data_album_image_medium;
}
else if(data_album_image_small.length() > 0) {
data_album_image = data_album_image_small;
}
if(data_album_image.length() > 0) {
try {
Topic image = getImageTopic(tm, data_album_image, "album "+data_album_name);
Topic imageType = getImageTypeTopic(tm);
Association imagea = tm.createAssociation(imageType);
imagea.addPlayer(image, imageType);
imagea.addPlayer(albumTopic, albumType);
}
catch(Exception e) {
parent.log(e);
}
}
}
catch(TopicMapException tme){
parent.log(tme);
}
}
state=STATE_TOPALBUMS;
break;
}
case STATE_NAME: {
state=STATE_ALBUM;
break;
}
case STATE_MBID: {
state=STATE_ALBUM;
break;
}
case STATE_REACH: {
state=STATE_ALBUM;
break;
}
case STATE_URL: {
state=STATE_ALBUM;
break;
}
case STATE_IMAGE: {
state=STATE_ALBUM;
break;
}
case STATE_IMAGE_LARGE: {
state=STATE_IMAGE;
break;
}
case STATE_IMAGE_MEDIUM: {
state=STATE_IMAGE;
break;
}
case STATE_IMAGE_SMALL: {
state=STATE_IMAGE;
break;
}
}
}
public void characters(char[] ch, int start, int length) throws SAXException {
switch(state){
case STATE_NAME:
data_album_name+=new String(ch,start,length);
break;
case STATE_MBID:
data_album_mbid+=new String(ch,start,length);
break;
case STATE_REACH:
data_album_reach+=new String(ch,start,length);
break;
case STATE_URL:
data_album_url+=new String(ch,start,length);
break;
case STATE_IMAGE_LARGE:
data_album_image_large+=new String(ch,start,length);
break;
case STATE_IMAGE_MEDIUM:
data_album_image_medium+=new String(ch,start,length);
break;
case STATE_IMAGE_SMALL:
data_album_image_small+=new String(ch,start,length);
break;
}
}
public void warning(SAXParseException exception) throws SAXException {
}
public void error(SAXParseException exception) throws SAXException {
parent.log("Error parsing XML document at "+exception.getLineNumber()+","+exception.getColumnNumber(),exception);
}
public void fatalError(SAXParseException exception) throws SAXException {
parent.log("Fatal error parsing XML document at "+exception.getLineNumber()+","+exception.getColumnNumber(),exception);
}
public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {}
public void processingInstruction(String target, String data) throws SAXException {}
public void startPrefixMapping(String prefix, String uri) throws SAXException {}
public void endPrefixMapping(String prefix) throws SAXException {}
public void setDocumentLocator(org.xml.sax.Locator locator) {}
public void skippedEntity(String name) throws SAXException {}
}
}
| 14,604 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TagTopAlbumsExtractor.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/audioscrobbler/TagTopAlbumsExtractor.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* TagTopAlbumsExtractor.java
*
* Created on 17. toukokuuta 2007, 18:19
*
*/
package org.wandora.application.tools.extractors.audioscrobbler;
import java.io.InputStream;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
/**
*
* @author akivela
*/
public class TagTopAlbumsExtractor extends AbstractAudioScrobblerExtractor {
private static final long serialVersionUID = 1L;
/** Creates a new instance of TagTopAlbumsExtractor */
public TagTopAlbumsExtractor() {
}
@Override
public String getName() {
return "Audioscrobbler Tags: Top Albums extractor";
}
@Override
public String getDescription(){
return "Extractor reads the Top Albums with Tag XML feed from Audioscrobbler's web api and converts the XML feed to a topic map. "+
"See http://ws.audioscrobbler.com/1.0/tag/Rock/topalbums.xml for an example of such an XML feed.";
}
public boolean _extractTopicsFrom(InputStream in, TopicMap topicMap) throws Exception {
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();
TagTopAlbumsParser parserHandler = new TagTopAlbumsParser(topicMap,this);
reader.setContentHandler(parserHandler);
reader.setErrorHandler(parserHandler);
try{
reader.parse(new InputSource(in));
}
catch(Exception e){
if(!(e instanceof SAXException) || !e.getMessage().equals("User interrupt")) log(e);
}
log("Total " + parserHandler.progress + " top albums found!");
return true;
}
private static class TagTopAlbumsParser implements org.xml.sax.ContentHandler, org.xml.sax.ErrorHandler {
public TagTopAlbumsParser(TopicMap tm, TagTopAlbumsExtractor parent){
this.tm=tm;
this.parent=parent;
}
public int progress=0;
private TopicMap tm;
private TagTopAlbumsExtractor parent;
public static final String TAG_TAG="tag";
public static final String TAG_ALBUM="album";
public static final String TAG_ARTIST="artist";
public static final String TAG_URL="url";
public static final String TAG_MBID="mbid";
public static final String TAG_COVERART="coverart";
public static final String TAG_COVERART_LARGE="large";
public static final String TAG_COVERART_MEDIUM="medium";
public static final String TAG_COVERART_SMALL="small";
private static final int STATE_START=0;
private static final int STATE_TAG=1;
private static final int STATE_ALBUM=2;
private static final int STATE_ALBUM_ARTIST=3;
private static final int STATE_ALBUM_ARTIST_MBID=4;
private static final int STATE_ALBUM_ARTIST_URL=5;
private static final int STATE_ALBUM_URL=6;
private static final int STATE_ALBUM_COVERART=8;
private static final int STATE_ALBUM_COVERART_LARGE=9;
private static final int STATE_ALBUM_COVERART_MEDIUM=10;
private static final int STATE_ALBUM_COVERART_SMALL=11;
private int state=STATE_START;
private String data_album_streamable;
private String data_album_count;
private String data_album_name;
private String data_album_url;
private String data_artist_mbid;
private String data_artist_url;
private String data_artist_name;
private String data_album_coverart_large;
private String data_album_coverart_medium;
private String data_album_coverart_small;
private Topic theTag;
public void startDocument() throws SAXException {
}
public void endDocument() throws SAXException {
}
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
if(parent.forceStop()){
throw new SAXException("User interrupt");
}
switch(state){
case STATE_START:
if(qName.equals(TAG_TAG)) {
state = STATE_TAG;
String theTagString = atts.getValue("tag");
String theCountString = atts.getValue("count");
if(theTagString != null && theTagString.length() > 0) {
try {
theTag=getTagTopic(tm, theTagString);
}
catch(Exception e) {
parent.log(e);
}
}
}
break;
case STATE_TAG:
if(qName.equals(TAG_ALBUM)) {
data_album_name = atts.getValue("name");
data_album_count = atts.getValue("count");
data_album_streamable = atts.getValue("streamable");
state = STATE_ALBUM;
}
break;
case STATE_ALBUM:
if(qName.equals(TAG_ARTIST)) {
state = STATE_ALBUM_ARTIST;
data_artist_name = atts.getValue("name");
data_artist_mbid = "";
data_artist_url = "";
}
else if(qName.equals(TAG_URL)) {
state = STATE_ALBUM_URL;
data_album_url = "";
}
else if(qName.equals(TAG_COVERART)) {
state = STATE_ALBUM_COVERART;
data_album_coverart_small = "";
data_album_coverart_medium = "";
data_album_coverart_large = "";
}
break;
case STATE_ALBUM_ARTIST:
if(qName.equals(TAG_MBID)) {
state = STATE_ALBUM_ARTIST_MBID;
data_artist_mbid = "";
}
else if(qName.equals(TAG_URL)) {
state = STATE_ALBUM_ARTIST_URL;
data_artist_url = "";
}
break;
case STATE_ALBUM_COVERART:
if(qName.equals(TAG_COVERART_SMALL)) {
state = STATE_ALBUM_COVERART_SMALL;
data_album_coverart_small = "";
}
else if(qName.equals(TAG_COVERART_MEDIUM)) {
state = STATE_ALBUM_COVERART_MEDIUM;
data_album_coverart_medium = "";
}
else if(qName.equals(TAG_COVERART_LARGE)) {
state = STATE_ALBUM_COVERART_LARGE;
data_album_coverart_large = "";
}
break;
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
switch(state) {
case STATE_ALBUM: {
if(data_album_name != null && data_album_name.length() > 0) {
try {
Topic albumTopic=getAlbumTopic(tm, data_album_name, data_album_url, data_artist_name);
Topic albumType=getAlbumTypeTopic(tm);
String data_album_coverart = "";
if(data_album_coverart_large.length() > 0) {
data_album_coverart = data_album_coverart_large;
}
else if(data_album_coverart_medium.length() > 0) {
data_album_coverart = data_album_coverart_medium;
}
else if(data_album_coverart_small.length() > 0) {
data_album_coverart = data_album_coverart_small;
}
if(data_album_coverart.length() > 0) {
try {
Topic imageType = getImageTypeTopic(tm);
Topic image = getImageTopic(tm, data_album_coverart, "album "+data_album_name);
Association imagea = tm.createAssociation(imageType);
imagea.addPlayer(image, imageType);
imagea.addPlayer(albumTopic, albumType);
}
catch(Exception e) {
parent.log(e);
}
}
if(theTag != null) {
Topic tagType = getTagTypeTopic(tm);
Association a = tm.createAssociation(tagType);
a.addPlayer(theTag, tagType);
a.addPlayer(albumTopic, albumType);
if(CONVERT_COUNTS && data_album_count != null && data_album_count.length() > 0) {
Topic countType = getCountTypeTopic(tm);
Topic countTopic = getCountTopic(tm,data_album_count);
a.addPlayer(countTopic, countType);
}
}
if(data_artist_name != null && data_artist_name.length() > 0) {
Topic artistType = getArtistTypeTopic(tm);
System.out.println("creating artist topic: "+data_artist_name+", "+data_artist_url);
Topic artistTopic = getArtistTopic(tm, data_artist_name, data_artist_url, data_artist_mbid);
Association a = tm.createAssociation(albumType);
a.addPlayer(artistTopic, artistType);
a.addPlayer(albumTopic, albumType);
}
parent.setProgress(++progress);
}
catch(TopicMapException tme){
parent.log(tme);
}
}
state=STATE_TAG;
break;
}
case STATE_ALBUM_ARTIST: {
state=STATE_ALBUM;
break;
}
// --- Closing album's inner ---
case STATE_ALBUM_COVERART: {
state=STATE_ALBUM;
break;
}
case STATE_ALBUM_URL: {
state=STATE_ALBUM;
break;
}
case STATE_ALBUM_ARTIST_URL: {
state=STATE_ALBUM_ARTIST;
break;
}
case STATE_ALBUM_ARTIST_MBID: {
state=STATE_ALBUM_ARTIST;
break;
}
// --- Closing cover art's ---
case STATE_ALBUM_COVERART_LARGE: {
state=STATE_ALBUM_COVERART;
break;
}
case STATE_ALBUM_COVERART_MEDIUM: {
state=STATE_ALBUM_COVERART;
break;
}
case STATE_ALBUM_COVERART_SMALL: {
state=STATE_ALBUM_COVERART;
break;
}
}
}
public void characters(char[] ch, int start, int length) throws SAXException {
switch(state){
case STATE_ALBUM_ARTIST_MBID:
data_artist_mbid+=new String(ch,start,length);
break;
case STATE_ALBUM_ARTIST_URL:
data_artist_url+=new String(ch,start,length);
break;
case STATE_ALBUM_URL:
// This is effectively same as artist's url.
// Not using as it causes artists and album merge!
//
// data_album_url+=new String(ch,start,length);
break;
case STATE_ALBUM_COVERART_LARGE:
data_album_coverart_large+=new String(ch,start,length);
break;
case STATE_ALBUM_COVERART_MEDIUM:
data_album_coverart_medium+=new String(ch,start,length);
break;
case STATE_ALBUM_COVERART_SMALL:
data_album_coverart_small+=new String(ch,start,length);
break;
}
}
public void warning(SAXParseException exception) throws SAXException {
}
public void error(SAXParseException exception) throws SAXException {
parent.log("Error parsing XML document at "+exception.getLineNumber()+","+exception.getColumnNumber(),exception);
}
public void fatalError(SAXParseException exception) throws SAXException {
parent.log("Fatal error parsing XML document at "+exception.getLineNumber()+","+exception.getColumnNumber(),exception);
}
public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {}
public void processingInstruction(String target, String data) throws SAXException {}
public void startPrefixMapping(String prefix, String uri) throws SAXException {}
public void endPrefixMapping(String prefix) throws SAXException {}
public void setDocumentLocator(org.xml.sax.Locator locator) {}
public void skippedEntity(String name) throws SAXException {}
}
}
| 15,508 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TagTopArtistsExtractor.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/audioscrobbler/TagTopArtistsExtractor.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* TagTopArtistsExtractor.java
*
* Created on 17. toukokuuta 2007, 17:22
*/
package org.wandora.application.tools.extractors.audioscrobbler;
import java.io.InputStream;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
/**
*
* @author akivela
*/
public class TagTopArtistsExtractor extends AbstractAudioScrobblerExtractor {
private static final long serialVersionUID = 1L;
/**
* Creates a new instance of TagTopArtistsExtractor
*/
public TagTopArtistsExtractor() {
}
@Override
public String getName() {
return "Audioscrobbler Tags: Top Artists extractor";
}
@Override
public String getDescription(){
return "Extractor reads the Top Artists with Tag XML feed from Audioscrobbler's web api and converts the XML feed to a topic map. "+
"See http://ws.audioscrobbler.com/1.0/tag/Rock/topartists.xml for an example of such an XML feed.";
}
public boolean _extractTopicsFrom(InputStream in, TopicMap topicMap) throws Exception {
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();
TagTopArtistParser parserHandler = new TagTopArtistParser(topicMap,this);
reader.setContentHandler(parserHandler);
reader.setErrorHandler(parserHandler);
try{
reader.parse(new InputSource(in));
}catch(Exception e){
if(!(e instanceof SAXException) || !e.getMessage().equals("User interrupt")) log(e);
}
log("Total " + parserHandler.progress + " top artists with the tag found!");
return true;
}
private static class TagTopArtistParser implements org.xml.sax.ContentHandler, org.xml.sax.ErrorHandler {
public TagTopArtistParser(TopicMap tm,TagTopArtistsExtractor parent){
this.tm=tm;
this.parent=parent;
}
public int progress = 0;
private TopicMap tm;
private TagTopArtistsExtractor parent;
public static final String TAG_TAG="tag";
public static final String TAG_ARTIST="artist";
public static final String TAG_ARTIST_MBID="mbid";
public static final String TAG_ARTIST_URL="url";
public static final String TAG_ARTIST_THUMBNAIL="thumbnail";
public static final String TAG_ARTIST_IMAGE="image";
private static final int STATE_START=0;
private static final int STATE_TAG=1;
private static final int STATE_ARTIST=2;
private static final int STATE_ARTIST_MBID=4;
private static final int STATE_ARTIST_URL=6;
private static final int STATE_ARTIST_THUMBNAIL=7;
private static final int STATE_ARTIST_IMAGE=8;
private int state=STATE_START;
private String data_artist_name = "";
private String data_artist_count = "";
private String data_artist_streamable = "";
private String data_artist_mbid = "";
private String data_artist_url = "";
private String data_artist_thumbnail = "";
private String data_artist_image = "";
private Topic theTag;
public void startDocument() throws SAXException {
}
public void endDocument() throws SAXException {
}
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
if(parent.forceStop()){
throw new SAXException("User interrupt");
}
switch(state){
case STATE_START:
if(qName.equals(TAG_TAG)) {
state = STATE_TAG;
String theTagName = atts.getValue("tag");
String theTagCount = atts.getValue("count");
if(theTagName != null) {
try {
theTag = getTagTopic(tm, theTagName);
}
catch(Exception e) {
parent.log(e);
}
}
}
break;
case STATE_TAG:
if(qName.equals(TAG_ARTIST)) {
state = STATE_ARTIST;
data_artist_name = atts.getValue("name");
data_artist_count = atts.getValue("count");
data_artist_streamable = atts.getValue("streamable");
data_artist_mbid = "";
data_artist_url = "";
data_artist_thumbnail = "";
data_artist_image = "";
}
break;
case STATE_ARTIST:
if(qName.equals(TAG_ARTIST_MBID)) {
state = STATE_ARTIST_MBID;
data_artist_mbid = "";
}
else if(qName.equals(TAG_ARTIST_URL)) {
state = STATE_ARTIST_URL;
data_artist_url = "";
}
else if(qName.equals(TAG_ARTIST_THUMBNAIL)) {
state = STATE_ARTIST_THUMBNAIL;
data_artist_thumbnail = "";
}
else if(qName.equals(TAG_ARTIST_IMAGE)) {
state = STATE_ARTIST_IMAGE;
data_artist_image = "";
}
break;
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
switch(state) {
case STATE_ARTIST: {
if(data_artist_name != null && data_artist_name.length() > 0){
try{
Topic artistType=getArtistTypeTopic(tm);
Topic tagType=getTagTypeTopic(tm);
Topic artistTopic=getArtistTopic(tm, data_artist_name, data_artist_url, data_artist_mbid);
if(data_artist_streamable.length() > 0) {
Topic streamableType = getStreamableTypeTopic(tm);
parent.setData(artistTopic, streamableType, LANG, data_artist_streamable);
}
if(artistTopic != null && theTag != null) {
Association a=tm.createAssociation(tagType);
a.addPlayer(artistTopic, artistType);
a.addPlayer(theTag, tagType);
if(CONVERT_COUNTS && data_artist_count.length() > 0) {
Topic countTopic = getCountTopic(tm, data_artist_count);
Topic countType = getCountTypeTopic(tm);
a.addPlayer(countTopic, countType);
}
}
if(data_artist_image == null || data_artist_image.length() == 0) {
if(data_artist_thumbnail != null && data_artist_thumbnail.length() > 0) {
data_artist_image = data_artist_thumbnail;
}
}
if(data_artist_image != null && data_artist_image.length() > 0) {
Topic imageType = getImageTypeTopic(tm);
Topic image = getImageTopic(tm, data_artist_image, "artist "+data_artist_name);
Association imagea = tm.createAssociation(imageType);
imagea.addPlayer(image, imageType);
imagea.addPlayer(artistTopic, artistType);
}
parent.setProgress(++progress);
}
catch(TopicMapException tme){
parent.log(tme);
}
}
state=STATE_TAG;
break;
}
case STATE_ARTIST_MBID: {
state=STATE_ARTIST;
break;
}
case STATE_ARTIST_URL: {
state=STATE_ARTIST;
break;
}
case STATE_ARTIST_THUMBNAIL: {
state=STATE_ARTIST;
break;
}
case STATE_ARTIST_IMAGE: {
state=STATE_ARTIST;
break;
}
}
}
public void characters(char[] ch, int start, int length) throws SAXException {
switch(state){
case STATE_ARTIST_MBID:
data_artist_mbid+=new String(ch,start,length);
break;
case STATE_ARTIST_URL:
data_artist_url+=new String(ch,start,length);
break;
case STATE_ARTIST_THUMBNAIL:
data_artist_thumbnail+=new String(ch,start,length);
break;
case STATE_ARTIST_IMAGE:
data_artist_image+=new String(ch,start,length);
break;
}
}
public void warning(SAXParseException exception) throws SAXException {
}
public void error(SAXParseException exception) throws SAXException {
parent.log("Error parsing XML document at "+exception.getLineNumber()+","+exception.getColumnNumber(),exception);
}
public void fatalError(SAXParseException exception) throws SAXException {
parent.log("Fatal error parsing XML document at "+exception.getLineNumber()+","+exception.getColumnNumber(),exception);
}
public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {}
public void processingInstruction(String target, String data) throws SAXException {}
public void startPrefixMapping(String prefix, String uri) throws SAXException {}
public void endPrefixMapping(String prefix) throws SAXException {}
public void setDocumentLocator(org.xml.sax.Locator locator) {}
public void skippedEntity(String name) throws SAXException {}
}
}
| 11,951 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
ArtistTopTracksExtractor.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/audioscrobbler/ArtistTopTracksExtractor.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* TopTracksExtractor.java
*
* Created on 12. toukokuuta 2007, 19:14
*
*/
package org.wandora.application.tools.extractors.audioscrobbler;
import java.io.InputStream;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
/**
* Extractor reads specific XML feed from Audioscrobbler's web api and converts the
* XML feed to a topic map. Extractor reads the Top Tracks feed. Example
* of Top Tracks is found at
*
* http://ws.audioscrobbler.com/1.0/artist/Metallica/toptracks.xml
*
* Audioscrobber's web api documentation is found at
*
* http://www.audioscrobbler.net/data/webservices/
*
* @author akivela
*/
public class ArtistTopTracksExtractor extends AbstractAudioScrobblerExtractor {
private static final long serialVersionUID = 1L;
/** Creates a new instance of ArtistTopTracksExtractor */
public ArtistTopTracksExtractor() {
}
@Override
public String getName() {
return "Audioscrobbler Artists: Top Tracks extractor";
}
@Override
public String getDescription(){
return "Extractor reads the Top Tracks XML feed from Audioscrobbler's web api and converts the XML feed to a topic map. "+
"See http://ws.audioscrobbler.com/1.0/artist/Metallica/toptracks.xml for an example of Top Tracks XML feed.";
}
public boolean _extractTopicsFrom(InputStream in, TopicMap topicMap) throws Exception {
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();
ArtistTopTracksParser parserHandler = new ArtistTopTracksParser(topicMap,this);
reader.setContentHandler(parserHandler);
reader.setErrorHandler(parserHandler);
try{
reader.parse(new InputSource(in));
}
catch(Exception e){
if(!(e instanceof SAXException) || !e.getMessage().equals("User interrupt")) log(e);
}
log("Total " + parserHandler.progress + " top tracks found!");
return true;
}
private static class ArtistTopTracksParser implements org.xml.sax.ContentHandler, org.xml.sax.ErrorHandler {
public ArtistTopTracksParser(TopicMap tm,ArtistTopTracksExtractor parent){
this.tm=tm;
this.parent=parent;
}
public int progress=0;
private TopicMap tm;
private ArtistTopTracksExtractor parent;
public static final String TAG_MOSTKNOWNTRACKS="mostknowntracks";
public static final String TAG_TRACK="track";
public static final String TAG_NAME="name";
public static final String TAG_MBID="mbid";
public static final String TAG_REACH="reach";
public static final String TAG_URL="url";
private static final int STATE_START=0;
private static final int STATE_MOSTKNOWNTRACKS=1;
private static final int STATE_TRACK=2;
private static final int STATE_NAME=3;
private static final int STATE_MBID=4;
private static final int STATE_REACH=5;
private static final int STATE_URL=6;
private int state=STATE_START;
private String data_track_name = "";
private String data_track_mbid = "";
private String data_track_reach = "";
private String data_track_url = "";
private Topic theArtist;
private String theArtistString = "_";
private String theAlbumString = "_";
public void startDocument() throws SAXException {
}
public void endDocument() throws SAXException {
}
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
if(parent.forceStop()){
throw new SAXException("User interrupt");
}
switch(state){
case STATE_START:
if(qName.equals(TAG_MOSTKNOWNTRACKS)) {
state = STATE_MOSTKNOWNTRACKS;
theAlbumString = "_";
theArtistString = atts.getValue("artist");
if(theArtistString != null) {
try {
theArtist=getArtistTopic(tm, theArtistString);
}
catch(Exception e) {
parent.log(e);
}
}
}
break;
case STATE_MOSTKNOWNTRACKS:
if(qName.equals(TAG_TRACK)) {
state = STATE_TRACK;
data_track_name = "";
data_track_mbid = "";
data_track_reach = "";
data_track_url = "";
}
break;
case STATE_TRACK:
if(qName.equals(TAG_NAME)) {
state = STATE_NAME;
data_track_name = "";
}
else if(qName.equals(TAG_MBID)) {
state = STATE_MBID;
data_track_mbid = "";
}
else if(qName.equals(TAG_REACH)) {
state = STATE_REACH;
data_track_reach = "";
}
else if(qName.equals(TAG_URL)) {
state = STATE_URL;
data_track_url = "";
}
break;
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
switch(state) {
case STATE_TRACK: {
if(data_track_name.length() > 0) {
try {
Topic trackType=getTrackTypeTopic(tm);
Topic trackTopic=getTrackTopic(tm, data_track_name, data_track_mbid, theAlbumString, theArtistString);
Topic artistType=getArtistTypeTopic(tm);
Association ta=tm.createAssociation(trackType);
ta.addPlayer(theArtist, artistType);
ta.addPlayer(trackTopic, trackType);
if(CONVERT_REACH && data_track_reach.length() > 0) {
try {
Topic reachTopic = getReachTopic(tm, data_track_reach);
Topic reachType = getReachTypeTopic(tm);
ta.addPlayer(reachTopic, reachType);
}
catch(Exception e) {
parent.log(e);
}
}
parent.setProgress(++progress);
}
catch(TopicMapException tme){
parent.log(tme);
}
}
state=STATE_MOSTKNOWNTRACKS;
break;
}
case STATE_NAME: {
state=STATE_TRACK;
break;
}
case STATE_MBID: {
state=STATE_TRACK;
break;
}
case STATE_REACH: {
state=STATE_TRACK;
break;
}
case STATE_URL: {
state=STATE_TRACK;
break;
}
}
}
public void characters(char[] ch, int start, int length) throws SAXException {
switch(state){
case STATE_NAME:
data_track_name+=new String(ch,start,length);
break;
case STATE_MBID:
data_track_mbid+=new String(ch,start,length);
break;
case STATE_REACH:
data_track_reach+=new String(ch,start,length);
break;
case STATE_URL:
data_track_url+=new String(ch,start,length);
break;
}
}
public void warning(SAXParseException exception) throws SAXException {
}
public void error(SAXParseException exception) throws SAXException {
parent.log("Error parsing XML document at "+exception.getLineNumber()+","+exception.getColumnNumber(),exception);
}
public void fatalError(SAXParseException exception) throws SAXException {
parent.log("Fatal error parsing XML document at "+exception.getLineNumber()+","+exception.getColumnNumber(),exception);
}
public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {}
public void processingInstruction(String target, String data) throws SAXException {}
public void startPrefixMapping(String prefix, String uri) throws SAXException {}
public void endPrefixMapping(String prefix) throws SAXException {}
public void setDocumentLocator(org.xml.sax.Locator locator) {}
public void skippedEntity(String name) throws SAXException {}
}
}
| 10,764 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TagTopTagsExtractor.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/audioscrobbler/TagTopTagsExtractor.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* TagTopTagsExtractor.java
*
* Created on 17. toukokuuta 2007, 14:00
*
*/
package org.wandora.application.tools.extractors.audioscrobbler;
import java.io.InputStream;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
/**
*
* @author akivela
*/
public class TagTopTagsExtractor extends AbstractAudioScrobblerExtractor {
private static final long serialVersionUID = 1L;
/** Creates a new instance of TagTopTagsExtractor */
public TagTopTagsExtractor() {
}
@Override
public String getName() {
return "Audioscrobbler Tags: Top Tags extractor";
}
@Override
public String getDescription(){
return "Extractor reads the Top Tags XML feed from Audioscrobbler's web api and converts the XML feed to a topic map. "+
"See http://ws.audioscrobbler.com/1.0/tag/toptags.xml for an example of Top Tags XML feed.";
}
public boolean _extractTopicsFrom(InputStream in, TopicMap topicMap) throws Exception {
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();
TagTopTagsParser parserHandler = new TagTopTagsParser(topicMap,this);
reader.setContentHandler(parserHandler);
reader.setErrorHandler(parserHandler);
try{
reader.parse(new InputSource(in));
}
catch(Exception e){
if(!(e instanceof SAXException) || !e.getMessage().equals("User interrupt")) log(e);
}
log("Total " + parserHandler.progress + " top tags found!");
return true;
}
private static class TagTopTagsParser implements org.xml.sax.ContentHandler, org.xml.sax.ErrorHandler {
public TagTopTagsParser(TopicMap tm, TagTopTagsExtractor parent){
this.tm=tm;
this.parent=parent;
}
public int progress=0;
private TopicMap tm;
private TagTopTagsExtractor parent;
public static final String TAG_TOPTAGS="toptags";
public static final String TAG_TAG="tag";
private static final int STATE_START=0;
private static final int STATE_TOPTAGS=1;
private static final int STATE_TAG=2;
private int state=STATE_START;
private String data_tag_name = "";
private String data_tag_count = "";
private String data_tag_url = "";
private Topic theTag;
public void startDocument() throws SAXException {
}
public void endDocument() throws SAXException {
}
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
if(parent.forceStop()){
throw new SAXException("User interrupt");
}
switch(state){
case STATE_START: {
if(qName.equals(TAG_TOPTAGS)) {
state = STATE_TOPTAGS;
}
//parent.log("start");
break;
}
case STATE_TOPTAGS: {
if(qName.equals(TAG_TAG)) {
state = STATE_TAG;
data_tag_name = atts.getValue("name");
data_tag_count = atts.getValue("count");
data_tag_url = atts.getValue("url");
if(data_tag_name != null && data_tag_name.length() > 0) {
try {
Topic tagTopic=getTagTopic(tm, data_tag_name, data_tag_url);
if(CONVERT_COUNTS && data_tag_count != null && data_tag_count.length() > 0) {
Topic tagType=getTagTypeTopic(tm);
Topic countType=getCountTypeTopic(tm);
if(OCCURRENCE_COUNTS) {
parent.setData(tagTopic, countType, LANG, data_tag_count);
}
else {
Topic countTopic=getCountTopic(tm, data_tag_count);
Association a = tm.createAssociation(countType);
a.addPlayer(countTopic, countType);
a.addPlayer(tagTopic, tagType);
}
}
progress++;
}
catch(Exception e) {
parent.log(e);
}
}
}
break;
}
case STATE_TAG: {
break;
}
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
switch(state) {
case STATE_TAG: {
state=STATE_TOPTAGS;
break;
}
}
}
public void characters(char[] ch, int start, int length) throws SAXException {
// NOTHING HERE...
}
public void warning(SAXParseException exception) throws SAXException {
}
public void error(SAXParseException exception) throws SAXException {
parent.log("Error parsing XML document at "+exception.getLineNumber()+","+exception.getColumnNumber(),exception);
}
public void fatalError(SAXParseException exception) throws SAXException {
parent.log("Fatal error parsing XML document at "+exception.getLineNumber()+","+exception.getColumnNumber(),exception);
}
public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {}
public void processingInstruction(String target, String data) throws SAXException {}
public void startPrefixMapping(String prefix, String uri) throws SAXException {}
public void endPrefixMapping(String prefix) throws SAXException {}
public void setDocumentLocator(org.xml.sax.Locator locator) {}
public void skippedEntity(String name) throws SAXException {}
}
}
| 7,652 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AudioScrobblerExtractorSelector.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/audioscrobbler/AudioScrobblerExtractorSelector.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* AudioScrobblerExtractor.java
*
* Created on 21. toukokuuta 2008, 13:28
*/
package org.wandora.application.tools.extractors.audioscrobbler;
import java.awt.Component;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.JDialog;
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.Topic;
/**
*
* @author akivela
*/
public class AudioScrobblerExtractorSelector extends JDialog {
private static final long serialVersionUID = 1L;
public static String BASE_URL = "http://ws.audioscrobbler.com/1.0/";
private Wandora wandora = null;
private Context context = null;
private boolean accepted = false;
/** Creates new form AudioScrobblerExtractor */
public AudioScrobblerExtractorSelector(Wandora wandora) {
super(wandora, true);
setSize(450,300);
setTitle("Audioscrobbler extractors");
wandora.centerWindow(this);
this.wandora = wandora;
accepted = false;
initComponents();
}
public void setWandora(Wandora wandora) {
this.wandora = wandora;
}
public void setContext(Context context) {
this.context = context;
}
public boolean wasAccepted() {
return accepted;
}
public void setAccepted(boolean b) {
accepted = b;
}
public WandoraTool getWandoraTool(WandoraTool parentTool) {
Component component = scrobblerTabbedPane.getSelectedComponent();
WandoraTool wt = null;
// ***** ALBUM INFO *****
if(albumInfoPanel.equals(component)) {
String artist = albumInfoArtistField.getText();
String album = albumInfoAlbumField.getText();
if(artist == null || artist.length() == 0) {
parentTool.log("No artist name given.");
return null;
}
if(album == null || album.length() == 0) {
parentTool.log("No album name given.");
return null;
}
String[] artists=urlEncode(commaSplitter(artist));
String[] albums=urlEncode(commaSplitter(album));
String[] urls=completeString(BASE_URL+"album/__1__/__2__/info.xml",artists,albums);
AlbumInfoExtractor aie = new AlbumInfoExtractor();
aie.setForceUrls( urls );
// aie.setForceUrls( new String[] { BASE_URL+"album/"+urlEncode(artist)+"/"+urlEncode(album)+"/info.xml" } );
wt = aie;
}
// ***** SIMILAR ARTISTS *****
else if(similarArtistsPanel.equals(component)) {
String artist = similarArtistsField.getText();
if(artist == null || artist.length() == 0) {
parentTool.log("No artist name given.");
return null;
}
String[] artists = urlEncode(commaSplitter(artist));
String[] artistUrls = completeString(BASE_URL+"artist/__1__/similar.xml", artists);
ArtistRelatedArtistsExtractor arae = new ArtistRelatedArtistsExtractor();
arae.setForceUrls(artistUrls);
wt = arae;
}
// ***** OVERALL TOP TAGS *****
else if(topTagPanel.equals(component)) {
TagTopTagsExtractor ex = new TagTopTagsExtractor();
ex.setForceUrls( new String[] { BASE_URL+"tag/toptags.xml" } );
wt = ex;
}
// ***** TOP ALBUMS WITH GIVEN TAG *******
else if(topAlbumsWTag.equals(component)) {
String tag = topAlbumsWTagField.getText();
String[] tags = urlEncode(commaSplitter(tag));
String[] tagUrls = completeString(BASE_URL+"tag/__1__/topalbums.xml", tags);
TagTopAlbumsExtractor ex = new TagTopAlbumsExtractor();
ex.setForceUrls( tagUrls );
wt = ex;
}
// ***** TOP ARTISTS WITH GIVEN TAG *******
else if(topArtistsWTag.equals(component)) {
String tag = topArtistWTagField.getText();
String[] tags = urlEncode(commaSplitter(tag));
String[] tagUrls = completeString(BASE_URL+"tag/__1__/topartists.xml", tags);
TagTopArtistsExtractor ex = new TagTopArtistsExtractor();
ex.setForceUrls(tagUrls);
wt = ex;
}
// ***** ARTIST'S TOP ALBUMS *******
else if(artistsTopAlbumsPanel.equals(component)) {
String artist = artistsTopAlbumsField.getText();
String[] artists = urlEncode(commaSplitter(artist));
String[] artistUrls = completeString(BASE_URL+"artist/__1__/topalbums.xml", artists);
ArtistTopAlbumsExtractor ex = new ArtistTopAlbumsExtractor();
ex.setForceUrls(artistUrls);
wt = ex;
}
// ***** ARTIST'S TOP TRACKS *******
else if(artistsTopTracksPanel.equals(component)) {
String artist = artistsTopTracksField.getText();
String[] artists = urlEncode(commaSplitter(artist));
String[] artistUrls = completeString(BASE_URL+"artist/__1__/toptracks.xml", artists);
ArtistTopTracksExtractor ex = new ArtistTopTracksExtractor();
ex.setForceUrls(artistUrls);
wt = ex;
}
// ***** ARTIST'S TOP TAGS *******
else if(artistsTopTagsPanel.equals(component)) {
String artist = artistsTopTagsField.getText();
String[] artists = urlEncode(commaSplitter(artist));
String[] artistUrls = completeString(BASE_URL+"artist/__1__/toptags.xml", artists);
ArtistTopTagsExtractor ex = new ArtistTopTagsExtractor();
ex.setForceUrls(artistUrls);
wt = ex;
}
return wt;
}
public String[] commaSplitter(String str) {
ArrayList<String> strList=new ArrayList<String>();
int startPos=0;
for(int i=0;i<str.length()+1;i++){
if(i<str.length()-1 && str.charAt(i)==',' && str.charAt(i+1)==','){
i++;
continue;
}
if(i==str.length() || str.charAt(i)==','){
String s=str.substring(startPos,i).trim().replace(",,", ",");
if(s.length()>0) strList.add(s);
startPos=i+1;
}
}
return strList.toArray(new String[strList.size()]);
/*
if(str.indexOf(',') != -1) {
String[] strs = str.split(",");
ArrayList<String> strList = new ArrayList<String>();
String s = null;
for(int i=0; i<strs.length; i++) {
s = strs[i];
s = s.trim();
if(s.length() > 0) {
strList.add(s);
}
}
return strList.toArray( new String[] {} );
}
else {
return new String[] { str };
}
*/
}
public String[] completeString(String template, String[] strs) {
if(strs == null || template == null) return null;
String[] completed = new String[strs.length];
for(int i=0; i<strs.length; i++) {
completed[i] = template.replaceAll("__1__", strs[i]);
}
return completed;
}
public String[] completeString(String template, String[] strs1, String[] strs2) {
if(strs1 == null || strs2 == null || template == null) return null;
if(strs1.length != strs2.length) return null;
String[] completed = new String[strs1.length];
for(int i=0; i<strs1.length; i++) {
completed[i] = template.replaceAll("__1__", strs1[i]);
completed[i] = completed[i].replaceAll("__2__", strs2[i]);
}
return completed;
}
public String[] urlEncode(String[] urls) {
if(urls == null) return null;
String[] cleanUrls = new String[urls.length];
for(int i=0; i<urls.length; i++) {
cleanUrls[i] = urlEncode(urls[i]);
}
return cleanUrls;
}
public String urlEncode(String url) {
try {
return URLEncoder.encode(url, "UTF-8");
}
catch(Exception e) {
return url;
}
}
public String getContextArtistsAsString() {
StringBuffer sb = new StringBuffer("");
Topic albumType=null;
Topic artistType=null;
if(context != null) {
try {
Iterator contextObjects = context.getContextObjects();
String str = null;
Object o = null;
while(contextObjects.hasNext()) {
str = null;
o = contextObjects.next();
if(o instanceof Topic) {
Topic t = (Topic) o;
if(albumType==null || artistType==null){
albumType=t.getTopicMap().getTopic(AbstractAudioScrobblerExtractor.ALBUM_SI);
artistType=t.getTopicMap().getTopic(AbstractAudioScrobblerExtractor.ARTIST_SI);
if(albumType==null || artistType==null) break;
}
Topic artist=null;
for(Association a : t.getAssociations(albumType, albumType)){
artist=a.getPlayer(artistType);
if(artist!=null) break;
}
if(artist!=null){
str = artist.getDisplayName(AbstractAudioScrobblerExtractor.LANG);
if(str != null) {
str = str.trim();
}
}
}
if(str != null && str.length() > 0) {
sb.append(escapeCommas(str));
if(contextObjects.hasNext()) {
sb.append(", ");
}
}
}
}
catch(Exception e) {
e.printStackTrace();
}
}
return sb.toString();
}
public String getContextAsString() {
StringBuffer sb = new StringBuffer("");
if(context != null) {
try {
Iterator contextObjects = context.getContextObjects();
String str = null;
Object o = null;
while(contextObjects.hasNext()) {
str = null;
o = contextObjects.next();
if(o instanceof Topic) {
Topic t = (Topic) o;
str = t.getDisplayName(AbstractAudioScrobblerExtractor.LANG);
if(str != null) {
str = str.trim();
}
}
if(str != null && str.length() > 0) {
sb.append(escapeCommas(str));
if(contextObjects.hasNext()) {
sb.append(", ");
}
}
}
}
catch(Exception e) {
e.printStackTrace();
}
}
return sb.toString();
}
private String escapeCommas(String s){
return s.replace(",", ",,");
}
/** 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;
scrobblerTabbedPane = new org.wandora.application.gui.simple.SimpleTabbedPane();
topTagPanel = new javax.swing.JPanel();
topTagInnerPanel = new javax.swing.JPanel();
overallTopTagsLabel = new org.wandora.application.gui.simple.SimpleLabel();
topAlbumsWTag = new javax.swing.JPanel();
topAlbumsWTagInnerPanel = new javax.swing.JPanel();
topAlbumsWTagLabel = new org.wandora.application.gui.simple.SimpleLabel();
topAlbumsWTagField = new org.wandora.application.gui.simple.SimpleField();
topAlbumsWTagGetButton = new org.wandora.application.gui.simple.SimpleButton();
topArtistsWTag = new javax.swing.JPanel();
topArtistWTagInnerPanel = new javax.swing.JPanel();
topArtistWTagLabel = new org.wandora.application.gui.simple.SimpleLabel();
topArtistWTagField = new org.wandora.application.gui.simple.SimpleField();
topArtistsWTagGetButton = new org.wandora.application.gui.simple.SimpleButton();
albumInfoPanel = new javax.swing.JPanel();
albumInfoInnerPanel = new javax.swing.JPanel();
albumInfoLabel = new org.wandora.application.gui.simple.SimpleLabel();
albumInfoArtistLabel = new org.wandora.application.gui.simple.SimpleLabel();
albumInfoArtistField = new org.wandora.application.gui.simple.SimpleField();
albumInfoAlbumLabel = new org.wandora.application.gui.simple.SimpleLabel();
albumInfoAlbumField = new org.wandora.application.gui.simple.SimpleField();
albumInfoGetButton = new org.wandora.application.gui.simple.SimpleButton();
similarArtistsPanel = new javax.swing.JPanel();
similarArtistsInnerPanel = new javax.swing.JPanel();
similarArtistsLabel = new org.wandora.application.gui.simple.SimpleLabel();
similarArtistsField = new org.wandora.application.gui.simple.SimpleField();
similarArtistsGetButton = new org.wandora.application.gui.simple.SimpleButton();
artistsTopAlbumsPanel = new javax.swing.JPanel();
artistsTopAlbumsInnerPanel = new javax.swing.JPanel();
artistsTopAlbumsLabel = new org.wandora.application.gui.simple.SimpleLabel();
artistsTopAlbumsField = new org.wandora.application.gui.simple.SimpleField();
artistsTopAlbumsGetButton = new org.wandora.application.gui.simple.SimpleButton();
artistsTopTagsPanel = new javax.swing.JPanel();
artistsTopTagsInnerPanel = new javax.swing.JPanel();
artistsTopTagsLabel = new org.wandora.application.gui.simple.SimpleLabel();
artistsTopTagsField = new org.wandora.application.gui.simple.SimpleField();
artistsTopTagsGetButton = new org.wandora.application.gui.simple.SimpleButton();
artistsTopTracksPanel = new javax.swing.JPanel();
artistsTopTracksInnerPanel = new javax.swing.JPanel();
artistsTopTracksLabel = new org.wandora.application.gui.simple.SimpleLabel();
artistsTopTracksField = new org.wandora.application.gui.simple.SimpleField();
artistsTopTracksGetButton = new org.wandora.application.gui.simple.SimpleButton();
buttonPanel = new javax.swing.JPanel();
emptyPanel = new javax.swing.JPanel();
okButton = new org.wandora.application.gui.simple.SimpleButton();
cancelButton = new org.wandora.application.gui.simple.SimpleButton();
getContentPane().setLayout(new java.awt.GridBagLayout());
topTagPanel.setLayout(new java.awt.GridBagLayout());
topTagInnerPanel.setLayout(new java.awt.GridBagLayout());
overallTopTagsLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
overallTopTagsLabel.setText("<html>Fetch most used tags. This extractor doesn't require input.</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);
topTagInnerPanel.add(overallTopTagsLabel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10);
topTagPanel.add(topTagInnerPanel, gridBagConstraints);
scrobblerTabbedPane.addTab("Overall top tags", topTagPanel);
topAlbumsWTag.setLayout(new java.awt.GridBagLayout());
topAlbumsWTagInnerPanel.setLayout(new java.awt.GridBagLayout());
topAlbumsWTagLabel.setText("<html>Fetch albums tagged with given keyword. Please write keywords below or get the context. Use comma (,) character to separate different keywords.</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);
topAlbumsWTagInnerPanel.add(topAlbumsWTagLabel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
topAlbumsWTagInnerPanel.add(topAlbumsWTagField, gridBagConstraints);
topAlbumsWTagGetButton.setLabel("Get context");
topAlbumsWTagGetButton.setMargin(new java.awt.Insets(0, 6, 1, 6));
topAlbumsWTagGetButton.setMaximumSize(new java.awt.Dimension(75, 20));
topAlbumsWTagGetButton.setMinimumSize(new java.awt.Dimension(75, 20));
topAlbumsWTagGetButton.setPreferredSize(new java.awt.Dimension(80, 20));
topAlbumsWTagGetButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
topAlbumsWTagGetButtonMouseReleased(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.insets = new java.awt.Insets(10, 5, 0, 0);
topAlbumsWTagInnerPanel.add(topAlbumsWTagGetButton, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10);
topAlbumsWTag.add(topAlbumsWTagInnerPanel, gridBagConstraints);
scrobblerTabbedPane.addTab("Top albums with tag", topAlbumsWTag);
topArtistsWTag.setLayout(new java.awt.GridBagLayout());
topArtistWTagInnerPanel.setLayout(new java.awt.GridBagLayout());
topArtistWTagLabel.setText("<html>Fetch artists tagged with given keyword. Please write keywords below or get the context. Use comma (,) character to separate different keywords.</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);
topArtistWTagInnerPanel.add(topArtistWTagLabel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
topArtistWTagInnerPanel.add(topArtistWTagField, gridBagConstraints);
topArtistsWTagGetButton.setLabel("Get context");
topArtistsWTagGetButton.setMargin(new java.awt.Insets(0, 6, 1, 6));
topArtistsWTagGetButton.setMaximumSize(new java.awt.Dimension(75, 20));
topArtistsWTagGetButton.setMinimumSize(new java.awt.Dimension(75, 20));
topArtistsWTagGetButton.setPreferredSize(new java.awt.Dimension(80, 20));
topArtistsWTagGetButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
topArtistsWTagGetButtonMouseReleased(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.insets = new java.awt.Insets(10, 5, 0, 0);
topArtistWTagInnerPanel.add(topArtistsWTagGetButton, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10);
topArtistsWTag.add(topArtistWTagInnerPanel, gridBagConstraints);
scrobblerTabbedPane.addTab("Top artists with tag", topArtistsWTag);
albumInfoPanel.setLayout(new java.awt.GridBagLayout());
albumInfoInnerPanel.setLayout(new java.awt.GridBagLayout());
albumInfoLabel.setText("<html>Fetch information about specific album of given artists. Please write both artist and album name below.<html>");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 10, 0);
albumInfoInnerPanel.add(albumInfoLabel, gridBagConstraints);
albumInfoArtistLabel.setText("Artist name");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 5, 5);
albumInfoInnerPanel.add(albumInfoArtistLabel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 5, 0);
albumInfoInnerPanel.add(albumInfoArtistField, gridBagConstraints);
albumInfoAlbumLabel.setText("Album name");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5);
albumInfoInnerPanel.add(albumInfoAlbumLabel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
albumInfoInnerPanel.add(albumInfoAlbumField, gridBagConstraints);
albumInfoGetButton.setLabel("Get context");
albumInfoGetButton.setMargin(new java.awt.Insets(0, 6, 1, 6));
albumInfoGetButton.setMaximumSize(new java.awt.Dimension(75, 20));
albumInfoGetButton.setMinimumSize(new java.awt.Dimension(75, 20));
albumInfoGetButton.setPreferredSize(new java.awt.Dimension(80, 20));
albumInfoGetButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
albumInfoGetButtonMouseReleased(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.insets = new java.awt.Insets(10, 5, 0, 0);
albumInfoInnerPanel.add(albumInfoGetButton, 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);
albumInfoPanel.add(albumInfoInnerPanel, gridBagConstraints);
scrobblerTabbedPane.addTab("Album info", albumInfoPanel);
similarArtistsPanel.setLayout(new java.awt.GridBagLayout());
similarArtistsInnerPanel.setLayout(new java.awt.GridBagLayout());
similarArtistsLabel.setText("<html>Fetch related artists for given artist name. Please write artist's name below or get the context. Use comma character (,) to separate different artist names.</html>");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 10, 0);
similarArtistsInnerPanel.add(similarArtistsLabel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
similarArtistsInnerPanel.add(similarArtistsField, gridBagConstraints);
similarArtistsGetButton.setLabel("Get context");
similarArtistsGetButton.setMargin(new java.awt.Insets(0, 6, 1, 6));
similarArtistsGetButton.setMaximumSize(new java.awt.Dimension(75, 20));
similarArtistsGetButton.setMinimumSize(new java.awt.Dimension(75, 20));
similarArtistsGetButton.setPreferredSize(new java.awt.Dimension(80, 20));
similarArtistsGetButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
similarArtistsGetButtonMouseReleased(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.insets = new java.awt.Insets(10, 5, 0, 0);
similarArtistsInnerPanel.add(similarArtistsGetButton, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10);
similarArtistsPanel.add(similarArtistsInnerPanel, gridBagConstraints);
scrobblerTabbedPane.addTab("Similar artists", similarArtistsPanel);
artistsTopAlbumsPanel.setLayout(new java.awt.GridBagLayout());
artistsTopAlbumsInnerPanel.setLayout(new java.awt.GridBagLayout());
artistsTopAlbumsLabel.setText("<html>Fetch artist's top albums. Please write artist's name below or get the context. Use comma (,) character to separate different artist names.</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);
artistsTopAlbumsInnerPanel.add(artistsTopAlbumsLabel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
artistsTopAlbumsInnerPanel.add(artistsTopAlbumsField, gridBagConstraints);
artistsTopAlbumsGetButton.setLabel("Get context");
artistsTopAlbumsGetButton.setMargin(new java.awt.Insets(0, 6, 1, 6));
artistsTopAlbumsGetButton.setMaximumSize(new java.awt.Dimension(75, 20));
artistsTopAlbumsGetButton.setMinimumSize(new java.awt.Dimension(75, 20));
artistsTopAlbumsGetButton.setPreferredSize(new java.awt.Dimension(80, 20));
artistsTopAlbumsGetButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
artistsTopAlbumsGetButtonMouseReleased(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.insets = new java.awt.Insets(10, 5, 0, 0);
artistsTopAlbumsInnerPanel.add(artistsTopAlbumsGetButton, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10);
artistsTopAlbumsPanel.add(artistsTopAlbumsInnerPanel, gridBagConstraints);
scrobblerTabbedPane.addTab("Artist's top albums", artistsTopAlbumsPanel);
artistsTopTagsPanel.setLayout(new java.awt.GridBagLayout());
artistsTopTagsInnerPanel.setLayout(new java.awt.GridBagLayout());
artistsTopTagsLabel.setText("<html>Fetch tags attached to the given artist. Please write artist's name below or get the context. Use comma (,) character to separate different artist names.</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);
artistsTopTagsInnerPanel.add(artistsTopTagsLabel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
artistsTopTagsInnerPanel.add(artistsTopTagsField, gridBagConstraints);
artistsTopTagsGetButton.setLabel("Get context");
artistsTopTagsGetButton.setMargin(new java.awt.Insets(0, 6, 1, 6));
artistsTopTagsGetButton.setMaximumSize(new java.awt.Dimension(75, 20));
artistsTopTagsGetButton.setMinimumSize(new java.awt.Dimension(75, 20));
artistsTopTagsGetButton.setPreferredSize(new java.awt.Dimension(80, 20));
artistsTopTagsGetButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
artistsTopTagsGetButtonMouseReleased(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.insets = new java.awt.Insets(10, 5, 0, 0);
artistsTopTagsInnerPanel.add(artistsTopTagsGetButton, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10);
artistsTopTagsPanel.add(artistsTopTagsInnerPanel, gridBagConstraints);
scrobblerTabbedPane.addTab("Artist's top tags", artistsTopTagsPanel);
artistsTopTracksPanel.setLayout(new java.awt.GridBagLayout());
artistsTopTracksInnerPanel.setLayout(new java.awt.GridBagLayout());
artistsTopTracksLabel.setText("<html>Fetch most popular tracks of given artist. Please write artist's name below or get the context. Use comma (,) character to separate different artist names.</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);
artistsTopTracksInnerPanel.add(artistsTopTracksLabel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
artistsTopTracksInnerPanel.add(artistsTopTracksField, gridBagConstraints);
artistsTopTracksGetButton.setLabel("Get context");
artistsTopTracksGetButton.setMargin(new java.awt.Insets(0, 6, 1, 6));
artistsTopTracksGetButton.setMaximumSize(new java.awt.Dimension(75, 20));
artistsTopTracksGetButton.setMinimumSize(new java.awt.Dimension(75, 20));
artistsTopTracksGetButton.setPreferredSize(new java.awt.Dimension(80, 20));
artistsTopTracksGetButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
artistsTopTracksGetButtonMouseReleased(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.insets = new java.awt.Insets(10, 5, 0, 0);
artistsTopTracksInnerPanel.add(artistsTopTracksGetButton, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10);
artistsTopTracksPanel.add(artistsTopTracksInnerPanel, gridBagConstraints);
scrobblerTabbedPane.addTab("Artist's top tracks", artistsTopTracksPanel);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
getContentPane().add(scrobblerTabbedPane, gridBagConstraints);
scrobblerTabbedPane.getAccessibleContext().setAccessibleName("audioscrobbler");
buttonPanel.setLayout(new java.awt.GridBagLayout());
emptyPanel.setPreferredSize(new java.awt.Dimension(100, 10));
javax.swing.GroupLayout emptyPanelLayout = new javax.swing.GroupLayout(emptyPanel);
emptyPanel.setLayout(emptyPanelLayout);
emptyPanelLayout.setHorizontalGroup(
emptyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 219, Short.MAX_VALUE)
);
emptyPanelLayout.setVerticalGroup(
emptyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 10, Short.MAX_VALUE)
);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
buttonPanel.add(emptyPanel, gridBagConstraints);
okButton.setText("Extract");
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.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3);
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);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridy = 0;
buttonPanel.add(cancelButton, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
getContentPane().add(buttonPanel, gridBagConstraints);
}// </editor-fold>//GEN-END:initComponents
private void okButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_okButtonMouseReleased
accepted = true;
setVisible(false);
}//GEN-LAST:event_okButtonMouseReleased
private void cancelButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cancelButtonMouseReleased
accepted = false;
setVisible(false);
}//GEN-LAST:event_cancelButtonMouseReleased
private void topAlbumsWTagGetButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_topAlbumsWTagGetButtonMouseReleased
topAlbumsWTagField.setText(getContextAsString());
}//GEN-LAST:event_topAlbumsWTagGetButtonMouseReleased
private void topArtistsWTagGetButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_topArtistsWTagGetButtonMouseReleased
topArtistWTagField.setText(getContextAsString());
}//GEN-LAST:event_topArtistsWTagGetButtonMouseReleased
private void artistsTopTracksGetButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_artistsTopTracksGetButtonMouseReleased
artistsTopTracksField.setText(getContextAsString());
}//GEN-LAST:event_artistsTopTracksGetButtonMouseReleased
private void artistsTopTagsGetButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_artistsTopTagsGetButtonMouseReleased
artistsTopTagsField.setText(getContextAsString());
}//GEN-LAST:event_artistsTopTagsGetButtonMouseReleased
private void artistsTopAlbumsGetButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_artistsTopAlbumsGetButtonMouseReleased
artistsTopAlbumsField.setText(getContextAsString());
}//GEN-LAST:event_artistsTopAlbumsGetButtonMouseReleased
private void similarArtistsGetButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_similarArtistsGetButtonMouseReleased
similarArtistsField.setText(getContextAsString());
}//GEN-LAST:event_similarArtistsGetButtonMouseReleased
private void albumInfoGetButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_albumInfoGetButtonMouseReleased
albumInfoArtistField.setText(getContextArtistsAsString());
albumInfoAlbumField.setText(getContextAsString());
}//GEN-LAST:event_albumInfoGetButtonMouseReleased
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextField albumInfoAlbumField;
private javax.swing.JLabel albumInfoAlbumLabel;
private javax.swing.JTextField albumInfoArtistField;
private javax.swing.JLabel albumInfoArtistLabel;
private javax.swing.JButton albumInfoGetButton;
private javax.swing.JPanel albumInfoInnerPanel;
private javax.swing.JLabel albumInfoLabel;
private javax.swing.JPanel albumInfoPanel;
private javax.swing.JTextField artistsTopAlbumsField;
private javax.swing.JButton artistsTopAlbumsGetButton;
private javax.swing.JPanel artistsTopAlbumsInnerPanel;
private javax.swing.JLabel artistsTopAlbumsLabel;
private javax.swing.JPanel artistsTopAlbumsPanel;
private javax.swing.JTextField artistsTopTagsField;
private javax.swing.JButton artistsTopTagsGetButton;
private javax.swing.JPanel artistsTopTagsInnerPanel;
private javax.swing.JLabel artistsTopTagsLabel;
private javax.swing.JPanel artistsTopTagsPanel;
private javax.swing.JTextField artistsTopTracksField;
private javax.swing.JButton artistsTopTracksGetButton;
private javax.swing.JPanel artistsTopTracksInnerPanel;
private javax.swing.JLabel artistsTopTracksLabel;
private javax.swing.JPanel artistsTopTracksPanel;
private javax.swing.JPanel buttonPanel;
private javax.swing.JButton cancelButton;
private javax.swing.JPanel emptyPanel;
private javax.swing.JButton okButton;
private javax.swing.JLabel overallTopTagsLabel;
private javax.swing.JTabbedPane scrobblerTabbedPane;
private javax.swing.JTextField similarArtistsField;
private javax.swing.JButton similarArtistsGetButton;
private javax.swing.JPanel similarArtistsInnerPanel;
private javax.swing.JLabel similarArtistsLabel;
private javax.swing.JPanel similarArtistsPanel;
private javax.swing.JPanel topAlbumsWTag;
private javax.swing.JTextField topAlbumsWTagField;
private javax.swing.JButton topAlbumsWTagGetButton;
private javax.swing.JPanel topAlbumsWTagInnerPanel;
private javax.swing.JLabel topAlbumsWTagLabel;
private javax.swing.JTextField topArtistWTagField;
private javax.swing.JPanel topArtistWTagInnerPanel;
private javax.swing.JLabel topArtistWTagLabel;
private javax.swing.JPanel topArtistsWTag;
private javax.swing.JButton topArtistsWTagGetButton;
private javax.swing.JPanel topTagInnerPanel;
private javax.swing.JPanel topTagPanel;
// End of variables declaration//GEN-END:variables
}
| 42,772 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AudioScrobblerExtractor.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/audioscrobbler/AudioScrobblerExtractor.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Created on 21. toukokuuta 2008, 13:28
*/
package org.wandora.application.tools.extractors.audioscrobbler;
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;
/**
*
* @author akivela
*/
public class AudioScrobblerExtractor extends AbstractWandoraTool {
private static final long serialVersionUID = 1L;
private static AudioScrobblerExtractorSelector selector = null;
@Override
public String getName() {
return "Audio scrobbler extractor...";
}
@Override
public String getDescription(){
return "Convert various audio scrobbler XML feeds to topic maps";
}
@Override
public WandoraToolType getType() {
return WandoraToolType.createExtractType();
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/extract_lastfm.png");
}
public void execute(Wandora wandora, Context context) {
int counter = 0;
try {
if(selector == null) {
selector = new AudioScrobblerExtractorSelector(wandora);
}
selector.setAccepted(false);
selector.setWandora(wandora);
selector.setContext(context);
selector.setVisible(true);
setDefaultLogger();
if(selector.wasAccepted()) {
WandoraTool extractor = selector.getWandoraTool(this);
if(extractor != null) {
extractor.setToolLogger(getDefaultLogger());
extractor.execute(wandora, context);
}
}
else {
log("User cancelled the extraction!");
}
}
catch(Exception e) {
singleLog(e);
}
if(selector != null && selector.wasAccepted()) setState(WAIT);
else setState(CLOSE);
}
}
| 2,905 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
PropertyTableExtractor.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/table/PropertyTableExtractor.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* PropertyTableExtractor.java
*
* Created on 1. marraskuuta 2007, 10:42
*
*/
package org.wandora.application.tools.extractors.table;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import javax.swing.Icon;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.gui.UIBox;
import org.wandora.application.tools.browserextractors.BrowserExtractRequest;
import org.wandora.application.tools.extractors.AbstractExtractor;
import org.wandora.application.tools.extractors.ExtractHelper;
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;
/**
* Converts property-table to a set of topics and *one* association. Property-table is
* a HTML table structure with two columns. First column contains property names.
* Second column of property table contains property values. Each property name will
* be mapped to a role, and each property value to a role player.
*
* @author akivela
*/
public class PropertyTableExtractor extends AbstractExtractor implements WandoraTool {
private static final long serialVersionUID = 1L;
private URL basePath = null;
public static String SI_PREFIX = "http://wandora.org/si/table";
/** Creates a new instance of PropertyTableExtractor */
public PropertyTableExtractor() {
}
@Override
public String getName() {
return "Property table extractor";
}
@Override
public String getDescription() {
return "Converts HTML tables to associations. "+
"Extractor assumes each row in the table has two cells, containing "+
"association role and association player. First table column contains association roles and second column association players.";
}
@Override
public Icon getIcon() {
return UIBox.getIcon(0xf121);
}
@Override
public boolean useTempTopicMap(){
return false;
}
public static final String[] contentTypes=new String[] { "text/html" };
@Override
public String[] getContentTypes() {
return contentTypes;
}
@Override
public String doBrowserExtract(BrowserExtractRequest request, Wandora wandora) throws TopicMapException {
try {
basePath = new URL(request.getSource());
}
catch(Exception e) { e.printStackTrace(); }
String s = super.doBrowserExtract(request, wandora);
basePath = null;
return s;
}
@Override
public boolean _extractTopicsFrom(URL url, TopicMap topicMap) throws Exception {
basePath = url;
boolean r = _extractTopicsFrom(url.openStream(),topicMap);
basePath = null;
return r;
}
@Override
public boolean _extractTopicsFrom(File file, TopicMap topicMap) throws Exception {
basePath = file.toURI().toURL();
boolean r = _extractTopicsFrom(new FileInputStream(file),topicMap);
basePath = null;
return r;
}
@Override
public boolean _extractTopicsFrom(String str, TopicMap topicMap) throws Exception {
return _extractTopicsFrom(new ByteArrayInputStream(str.getBytes()), topicMap);
}
public boolean _extractTopicsFrom(InputStream in, TopicMap topicMap) throws Exception {
HTMLDocument htmlDoc = new HTMLDocument();
HTMLEditorKit.Parser parser = new HTMLParse().getParser();
htmlDoc.setParser(parser);
PropertyTableParseListener parserListener = new PropertyTableParseListener(topicMap, this);
parser.parse(new InputStreamReader(in), parserListener, true);
log("Total " + parserListener.associationCount + " associations and " + parserListener.playerCount + " association players created.");
return true;
}
private String getSubjectFor(String str) {
if(str != null) {
if(str.startsWith("http:") || str.startsWith("https:") || str.startsWith("ftp:") || str.startsWith("ftps:")) {
return str;
}
if(basePath != null) {
if(str.startsWith("/")) {
return basePath.toExternalForm().substring(0, basePath.toExternalForm().indexOf(basePath.getPath()))+str;
}
return basePath.toExternalForm() + str;
}
if(SI_PREFIX.endsWith("/") && str.startsWith("/")) {
str = str.substring(1);
}
String subjectPath = str;
if(subjectPath.length() > 50) {
subjectPath = subjectPath.substring(0,50);
subjectPath = subjectPath + "-" + str.hashCode();
}
try {
return SI_PREFIX + "/cell/" + URLEncoder.encode(subjectPath, "UTF-8");
}
catch(Exception e) {
return SI_PREFIX + "/cell/" + subjectPath;
}
}
return SI_PREFIX + "/cell/" + System.currentTimeMillis() + "-" + Math.round(Math.random() * 9999);
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
private static class HTMLParse extends HTMLEditorKit {
/**
* Call to obtain a HTMLEditorKit.Parser object.
* @return A new HTMLEditorKit.Parser object.
*/
@Override
public HTMLEditorKit.Parser getParser() {
HTMLEditorKit.Parser parser = super.getParser();
return parser;
}
}
// -------------------------------------------------------------------------
private class PropertyTableParseListener extends HTMLEditorKit.ParserCallback {
public int associationCount = 0;
public int playerCount = 0;
private TopicMap tm;
private PropertyTableExtractor parent;
private TableState state;
private ArrayList<TableState> stateStack;
private static final int STATE_OTHER=9999;
private static final int STATE_TABLE=0;
private static final int STATE_TBODY=1; // Not used at the moment
private static final int STATE_TH=2; // Not used at the moment
private static final int STATE_TR=3;
private static final int STATE_TD=4;
// -------------------------------------------------------------------------
public PropertyTableParseListener(TopicMap tm, PropertyTableExtractor parent){
this.tm = tm;
this.parent = parent;
this.state = null;
this.stateStack = new ArrayList();
}
// -------------------------------------------------------------------------
@Override
public void handleStartTag(HTML.Tag t,MutableAttributeSet a,int pos) {
if(t == HTML.Tag.TR) {
if(state == null) state = new TableState();
state.state = STATE_TR;
}
else if(t == HTML.Tag.TD) {
if(state == null) state = new TableState();
state.currentCell = null;
state.currentLink = null;
state.state = STATE_TD;
}
else if(t == HTML.Tag.TABLE) {
if(state != null) stateStack.add(state);
state = new TableState();
state.state = STATE_TABLE;
}
else if(t == HTML.Tag.A) {
if(a != null) {
if(state != null) {
state.currentLink = (String) a.getAttribute(HTML.Attribute.HREF);
}
}
}
}
@Override
public void handleEndTag(HTML.Tag t,int pos) {
if(t == HTML.Tag.TR) {
if(state != null) {
if(state.cells != null && state.cells.size() > 1) {
try {
if(state.association == null) {
Topic associationTypeTopic = parent.createTopic(tm, getSubjectFor(state.associationTypeLink), state.associationType);
Topic tableRoot = tm.getTopic(new Locator(SI_PREFIX));
if(tableRoot == null) {
tableRoot = tm.createTopic();
tableRoot.addSubjectIdentifier(new Locator(SI_PREFIX));
tableRoot.setBaseName("Table");
Topic wandoraClass = parent.createTopic(tm, TMBox.WANDORACLASS_SI, "Wandora Class");
ExtractHelper.makeSubclassOf(tableRoot, wandoraClass, tm);
}
associationTypeTopic.addType(tableRoot);
state.association = tm.createAssociation(associationTypeTopic);
associationCount++;
}
Topic propertyNameTopic = parent.createTopic(tm, getSubjectFor(state.links.get(0)), state.cells.get(0));
Topic propertyValueTopic = parent.createTopic(tm, getSubjectFor(state.links.get(1)), state.cells.get(1));
state.association.addPlayer(propertyValueTopic, propertyNameTopic);
playerCount++;
state.cells = new ArrayList();
state.links = new ArrayList();
}
catch(Exception e) {
parent.log(e);
}
}
else if(state.cells.size() == 1) {
state.associationType = state.cells.get(0);
state.associationTypeLink = state.links.get(0);
state.cells = new ArrayList();
state.links = new ArrayList();
}
state.state = STATE_TABLE;
}
}
else if(t == HTML.Tag.TD) {
if(state != null) {
state.cells.add(state.currentCell);
state.links.add(state.currentLink);
state.currentCell = null;
state.currentLink = null;
state.state = STATE_TR;
}
}
else if(t == HTML.Tag.TABLE) {
if(state != null) {
state.association = null;
state.cells = new ArrayList();
state.links = new ArrayList();
state.state = STATE_OTHER;
if(!stateStack.isEmpty()) {
state = stateStack.remove(stateStack.size()-1);
}
else {
state = null;
}
}
}
}
@Override
public void handleSimpleTag(HTML.Tag t,MutableAttributeSet a,int pos) {
}
@Override
public void handleText(char[] data, int pos) {
if(state != null) {
switch(state.state) {
case STATE_TD: {
if(state.currentCell == null) state.currentCell = "";
state.currentCell = state.currentCell + new String(data);
break;
}
}
}
}
@Override
public void handleError(String errorMsg,int pos) {
// System.out.println("PropertyTableExtractor: " + errorMsg);
}
// ---------------------------------------------------------------------
private class TableState {
public ArrayList<String> cells = new ArrayList();
public ArrayList<String> links = new ArrayList();
private String associationTypeSeed = System.currentTimeMillis() + "-" + Math.round(Math.random()*9999);
public String associationType = "Table-"+associationTypeSeed;
public String associationTypeLink = SI_PREFIX + "/" + associationTypeSeed;
public String currentCell = null;
public String currentLink = null;
public int state = STATE_OTHER;
public Association association = null;
}
}
}
| 14,213 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
JsoupPropertyTableExtractor.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/table/JsoupPropertyTableExtractor.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.extractors.table;
import java.util.List;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.wandora.application.WandoraTool;
import org.wandora.application.tools.browserextractors.BrowserPluginExtractor;
import org.wandora.application.tools.extractors.AbstractJsoupExtractor;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
/**
*
* @author Eero
*/
public class JsoupPropertyTableExtractor extends AbstractJsoupExtractor
implements WandoraTool, BrowserPluginExtractor {
private static final long serialVersionUID = 1L;
private TopicMap tm;
private Topic wandoraClass;
@Override
public boolean extractTopicsFrom(Document d, String u, TopicMap t) throws Exception {
this.tm = t;
this.wandoraClass = getWandoraClassTopic(tm);
Elements tables = d.select("table");
if(tables.isEmpty()) throw new Exception("No table found!");
return parseTable(tables.first());
}
private boolean parseTable(Element table) throws Exception{
Elements rows = table.select("tr");
Element masterRow = rows.first();
Element masterCell = masterRow.select("td").first();
if(masterCell == null) throw new Exception("No master row!");
String masterValue = masterCell.text();
Topic masterTopic = getOrCreateTopic(tm, null, masterValue);
Association assoc = tm.createAssociation(masterTopic);
List<Element> playerRows = rows.subList(1, rows.size());
for(Element playerRow: playerRows) {
try {
handleAssoc(assoc, playerRow);
} catch (Exception e) {
log(e);
}
}
return true;
}
private void handleAssoc(Association assoc, Element playerRow) throws Exception {
Elements playerCells = playerRow.select("td");
if(playerCells.size() != 2) throw new Exception("Invalid player row");
String roleValue = playerCells.first().text();
String playerValue = playerCells.last().text();
Topic roleTopic = getOrCreateTopic(tm, null, roleValue);
Topic playerTopic = getOrCreateTopic(tm, null, playerValue);
assoc.addPlayer(playerTopic, roleTopic);
}
}
| 3,337 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
JsoupAssociationRowTableExtractor.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/table/JsoupAssociationRowTableExtractor.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.extractors.table;
import java.util.ArrayList;
import java.util.List;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.wandora.application.WandoraTool;
import org.wandora.application.tools.browserextractors.BrowserPluginExtractor;
import org.wandora.application.tools.extractors.AbstractJsoupExtractor;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
/**
*
* @author Eero
*/
public class JsoupAssociationRowTableExtractor extends AbstractJsoupExtractor
implements WandoraTool, BrowserPluginExtractor {
private static final long serialVersionUID = 1L;
private TopicMap tm;
@Override
public boolean extractTopicsFrom(Document d, String u, TopicMap t) throws Exception {
this.tm = t;
Elements tables = d.select("table");
for(Element table: tables) parseTable(table);
return true;
}
private void parseTable(Element table) throws Exception{
Elements rows = table.select("tr");
Element headerRow = rows.first();
ArrayList<Topic> roles = new ArrayList<Topic>();
for(Element headerCell: headerRow.select("th")){
String roleValue = headerCell.text().trim();
if(roleValue.length() == 0) continue;
Topic role = getOrCreateTopic(tm, null, roleValue);
roles.add(role);
}
List<Element> playerRows = rows.subList(1,rows.size());
for(Element playerRow: playerRows){
try {
handlePlayerRow(playerRow, roles);
} catch (Exception e) {
log(e.getMessage());
}
}
}
private void handlePlayerRow(Element playerRow, ArrayList<Topic> roles) throws Exception{
Elements playerCells = playerRow.select("td");
if(playerCells.size() != roles.size())
throw new Exception("Invalid row!");
Topic assocType = getOrCreateTopic(tm, null);
Association a = tm.createAssociation(assocType);
for(int i = 0; i < roles.size(); i++){
Topic role = roles.get(i);
Element playerCell = playerCells.get(i);
String playerValue = playerCell.text();
Topic playerTopic = getOrCreateTopic(tm, null, playerValue);
a.addPlayer(playerTopic, role);
}
}
}
| 3,411 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AssociationRowTableExtractor.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/table/AssociationRowTableExtractor.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* AssociationRowTableExtractor.java
*
* Created on 7. marraskuuta 2007, 12:54
*
*/
package org.wandora.application.tools.extractors.table;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import javax.swing.Icon;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.gui.UIBox;
import org.wandora.application.tools.browserextractors.BrowserExtractRequest;
import org.wandora.application.tools.extractors.AbstractExtractor;
import org.wandora.application.tools.extractors.ExtractHelper;
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;
/**
* Converts an HTML table to a set of associations. Each table row (except first row)
* represents one association. First row defines role topics used in associations.
*
* @author akivela
*/
public class AssociationRowTableExtractor extends AbstractExtractor implements WandoraTool {
private static final long serialVersionUID = 1L;
private URL basePath = null;
public static String SI_PREFIX = "http://wandora.org/si/table";
/** Creates a new instance of AssociationRowTableExtractor */
public AssociationRowTableExtractor() {
}
@Override
public String getName() {
return "Association tow table extractor";
}
@Override
public String getDescription() {
return "Converts HTML tables to associations. "+
"Extractor creates one association for each table row. "+
"First row contains association roles.";
}
@Override
public Icon getIcon() {
return UIBox.getIcon(0xf121);
}
@Override
public boolean useTempTopicMap(){
return false;
}
public static final String[] contentTypes=new String[] { "text/html" };
@Override
public String[] getContentTypes() {
return contentTypes;
}
@Override
public String doBrowserExtract(BrowserExtractRequest request, Wandora wandora) throws TopicMapException {
try {
basePath = new URL(request.getSource());
}
catch(Exception e) { e.printStackTrace(); }
String s = super.doBrowserExtract(request, wandora);
basePath = null;
return s;
}
@Override
public boolean _extractTopicsFrom(URL url, TopicMap topicMap) throws Exception {
basePath = url;
boolean r = _extractTopicsFrom(url.openStream(),topicMap);
basePath = null;
return r;
}
@Override
public boolean _extractTopicsFrom(File file, TopicMap topicMap) throws Exception {
basePath = file.toURI().toURL();
boolean r = _extractTopicsFrom(new FileInputStream(file),topicMap);
basePath = null;
return r;
}
@Override
public boolean _extractTopicsFrom(String str, TopicMap topicMap) throws Exception {
return _extractTopicsFrom(new ByteArrayInputStream(str.getBytes()), topicMap);
}
public boolean _extractTopicsFrom(InputStream in, TopicMap topicMap) throws Exception {
HTMLDocument htmlDoc = new HTMLDocument();
HTMLEditorKit.Parser parser = new HTMLParse().getParser();
htmlDoc.setParser(parser);
AssociationRowTableParseListener parserListener = new AssociationRowTableParseListener(topicMap, this);
parser.parse(new InputStreamReader(in), parserListener, true);
log("Total " + parserListener.associationCount + " associations created for " + parserListener.tableCount + " tables.");
return true;
}
private String getSubjectFor(String str) {
if(str != null) {
if(str.startsWith("http:") || str.startsWith("https:") || str.startsWith("ftp:") || str.startsWith("ftps:")) {
return str;
}
if(basePath != null) {
if(str.startsWith("/")) {
return basePath.toExternalForm().substring(0, basePath.toExternalForm().indexOf(basePath.getPath()))+str;
}
return basePath.toExternalForm() + str;
}
if(SI_PREFIX.endsWith("/") && str.startsWith("/")) {
str = str.substring(1);
}
String subjectPath = str;
if(subjectPath.length() > 50) {
subjectPath = subjectPath.substring(0,50);
subjectPath = subjectPath + "-" + str.hashCode();
}
try {
return SI_PREFIX + "/cell/" + URLEncoder.encode(subjectPath, "UTF-8");
}
catch(Exception e) {
return SI_PREFIX + "/cell/" + subjectPath;
}
}
return SI_PREFIX + "/cell/" + System.currentTimeMillis() + "-" + Math.round(Math.random() * 9999);
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
private static class HTMLParse extends HTMLEditorKit {
private static final long serialVersionUID = 1L;
/**
* Call to obtain a HTMLEditorKit.Parser object.
* @return A new HTMLEditorKit.Parser object.
*/
@Override
public HTMLEditorKit.Parser getParser() {
return super.getParser();
}
}
// -------------------------------------------------------------------------
private class AssociationRowTableParseListener extends HTMLEditorKit.ParserCallback {
public boolean ADD_TABLE_AS_PLAYER = false;
public boolean USE_TABLE_AS_TYPE = true;
public boolean FIRST_ROW_CONTAINS_ROLES = true;
public int tableCount = 0;
public int associationCount = 0;
private TopicMap tm;
private AssociationRowTableExtractor parent;
private TableState state;
private ArrayList<TableState> stateStack;
private static final int STATE_OTHER=9999;
private static final int STATE_TABLE=0;
private static final int STATE_TBODY=1;
private static final int STATE_TH=2;
private static final int STATE_TR=3;
private static final int STATE_TD=4;
private String defaultAssociationType;
// -------------------------------------------------------------------------
public AssociationRowTableParseListener(TopicMap tm, AssociationRowTableExtractor parent){
this.tm = tm;
this.parent = parent;
defaultAssociationType = "default-association-type";
state = null;
stateStack = new ArrayList<>();
}
// -------------------------------------------------------------------------
@Override
public void handleStartTag(HTML.Tag t, MutableAttributeSet a, int pos) {
if(t == HTML.Tag.TR) {
if(state == null) {
tableCount++;
state = new TableState();
}
state.cellCount = 0;
state.state = STATE_TR;
}
else if(t == HTML.Tag.TH) {
if(state == null) {
tableCount++;
state = new TableState();
}
state.cellString = "";
state.cellLink = "";
state.state = STATE_TH;
}
else if(t == HTML.Tag.TD) {
if(state == null) {
tableCount++;
state = new TableState();
}
state.cellString="";
state.cellLink="";
state.state = STATE_TD;
}
else if(t == HTML.Tag.TABLE) {
if(state != null) {
stateStack.add(state);
}
tableCount++;
state = new TableState();
state.state = STATE_TABLE;
}
else if(t == HTML.Tag.A) {
if(state!= null && a != null) {
state.cellLink = (String) a.getAttribute(HTML.Attribute.HREF);
}
}
}
@Override
public void handleEndTag(HTML.Tag t,int pos) {
if(t == HTML.Tag.TR) {
if(state != null) {
state.rowCount++;
state.state = STATE_TABLE;
if(FIRST_ROW_CONTAINS_ROLES && state.rowCount == 1) { // FIRST ROW!
state.roles = state.row;
state.roleLinks = state.links;
state.row = new ArrayList<>();
state.links = new ArrayList<>();
return;
}
if(state.row.size() > 0) {
try {
Association association = null;
Topic tableRole = tm.getTopic(new Locator(SI_PREFIX));
if(tableRole == null) {
tableRole = tm.createTopic();
tableRole.addSubjectIdentifier(new Locator(SI_PREFIX));
tableRole.setBaseName("Table");
Topic wandoraClass = parent.createTopic(tm, TMBox.WANDORACLASS_SI, "Wandora Class");
ExtractHelper.makeSubclassOf(tableRole, wandoraClass, tm);
}
Topic tableTopic = tm.getTopic(new Locator(SI_PREFIX + "/" + state.tableIdentifier));
if(tableTopic == null) {
tableTopic = tm.createTopic();
tableTopic.addSubjectIdentifier(new Locator(SI_PREFIX + "/" + state.tableIdentifier));
tableTopic.setBaseName("Table-"+state.tableIdentifier);
tableTopic.addType(tableRole);
}
if(USE_TABLE_AS_TYPE) {
association = tm.createAssociation(tableTopic);
associationCount++;
}
else {
Topic associationTypeTopic = TMBox.getOrCreateTopic(tm, defaultAssociationType);
association = tm.createAssociation(associationTypeTopic);
associationCount++;
}
if(ADD_TABLE_AS_PLAYER) {
association.addPlayer(tableTopic, tableRole);
}
int c=0;
for(String player : state.row) {
try {
String link = tm.makeSubjectIndicatorAsLocator().toExternalForm();
String role = "table-role-" + state.tableIdentifier + "-" + (c+1);
String roleLink = SI_PREFIX + "/" + state.tableIdentifier + "/role-" + (c+1);
// Next we solve name of the role topic.
if(state.roles != null && state.roles.size() > c) {
String proposedRole = state.roles.get(c);
if(proposedRole != null && proposedRole.length() > 0) {
role = proposedRole;
}
}
// Next we solve the subject identifier for the role topic
if(state.roleLinks != null && state.roleLinks.size() > c) {
String proposedRoleLink = state.roleLinks.get(c);
if(proposedRoleLink != null && proposedRoleLink.length() > 0) {
roleLink = parent.getSubjectFor(proposedRoleLink);
}
}
// Next we are going to solve the subject identifier if possible
if(state.links != null && state.links.size() > c) {
String proposedLink = state.links.get(c);
if(proposedLink != null && proposedLink.length() > 0) {
link = parent.getSubjectFor(proposedLink);
}
}
// If both role and player are valid lets create an association
if(role != null && role.length() > 0 && player != null && player.length() > 0) {
Topic roleTopic = parent.createTopic(tm, roleLink, role);
Topic playerTopic = parent.createTopic(tm, link, player);
association.addPlayer(playerTopic, roleTopic);
}
c++;
}
catch(Exception e) {
parent.log(e);
}
}
state.row = new ArrayList<>();
state.links = new ArrayList<>();
}
catch(Exception e) {
parent.log(e);
}
}
}
}
else if(t == HTML.Tag.TD || t == HTML.Tag.TH) {
if(state != null) {
state.row.add(state.cellString);
state.links.add(state.cellLink);
state.cellString = "";
state.cellLink = "";
state.cellCount++;
state.state = STATE_TR;
}
}
else if(t == HTML.Tag.TABLE) {
state.state = STATE_OTHER;
if(!stateStack.isEmpty()) {
state = stateStack.remove(stateStack.size()-1);
}
else {
state = null;
}
}
}
@Override
public void handleSimpleTag(HTML.Tag t,MutableAttributeSet a,int pos) {
}
@Override
public void handleText(char[] data,int pos) {
if(state != null) {
switch(state.state) {
case STATE_TD: {
state.cellString = state.cellString + new String(data);
break;
}
case STATE_TH: {
state.cellString = state.cellString + new String(data);
break;
}
}
}
}
@Override
public void handleError(String errorMsg,int pos) {
System.out.println("TableExtractor: " + errorMsg);
}
private class TableState {
public int state = STATE_OTHER;
public List<String> roles = new ArrayList<>();
public List<String> roleLinks = new ArrayList<>();
public List<String> row = new ArrayList<>();
public List<String> links = new ArrayList<>();
public String cellString = "";
public String cellLink = "";
public int cellCount = 0;
public int rowCount = 0;
public String tableIdentifier = System.currentTimeMillis() + "-" + Math.round(Math.random()*9999);
}
}
}
| 17,676 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
GuardianExtractorUI.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/guardian/GuardianExtractorUI.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.extractors.guardian;
import java.awt.Component;
import java.awt.event.ItemEvent;
import java.net.URLEncoder;
import java.util.ArrayList;
import javax.swing.JDialog;
import javax.swing.ListModel;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.UIBox;
import org.wandora.application.gui.WandoraOptionPane;
import org.wandora.application.gui.simple.SimpleButton;
import org.wandora.application.gui.simple.SimpleField;
import org.wandora.application.gui.simple.SimpleLabel;
import org.wandora.application.gui.simple.SimpleList;
import org.wandora.application.gui.simple.SimpleTabbedPane;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author Eero
*/
public class GuardianExtractorUI extends javax.swing.JPanel {
private static final long serialVersionUID = 1L;
private Wandora wandora = null;
private boolean accepted = false;
private JDialog dialog = null;
private Context context = null;
private static final String GUARDIAN_CONTENT_API_BASE = "http://content.guardianapis.com/search?format=json";
private static final String GUARDIAN_TAG_API_BASE = "http://content.guardianapis.com/tags?format=json";
/*
* Creates new form GuardianExtractorUI
*/
public GuardianExtractorUI() {
initComponents();
}
public boolean wasAccepted() {
return accepted;
}
public void setAccepted(boolean b) {
accepted = b;
}
public void open(Wandora w, Context c) {
context = c;
accepted = false;
dialog = new JDialog(w, true);
dialog.setSize(550, 500);
dialog.add(this);
dialog.setTitle("The Guardian API extractor");
UIBox.centerWindow(dialog, w);
if (apikey != null) {
forgetButton.setEnabled(true);
} else {
forgetButton.setEnabled(false);
}
dialog.setVisible(true);
}
public WandoraTool[] getExtractors(GuardianExtractor tool) throws TopicMapException {
Component component = guardianTabbedPane.getSelectedComponent();
WandoraTool wt = null;
ArrayList<WandoraTool> wts = new ArrayList<>();
if (contentSearchPanel.equals(component)) {
String query = searchQueryTextField.getText();
String key = solveAPIKey();
if (key == null) {
return null;
}
String extractUrl = GUARDIAN_CONTENT_API_BASE + "&q=" + urlEncode(query);
if (allFieldsCheckBox.isSelected()) {
extractUrl += "&show-fields=all";
} else {
int[] fieldIndexes = fieldsList.getSelectedIndices();
ListModel listModel = fieldsList.getModel();
StringBuilder fieldValues = new StringBuilder("");
for (int i = 0; i < fieldIndexes.length; i++) {
if (i > 0) {
fieldValues.append(",");
}
fieldValues.append(listModel.getElementAt(fieldIndexes[i]));
}
if (fieldValues.length() > 0) {
extractUrl += "&show-fields=" + urlEncode(fieldValues.toString());
}
}
if (allTagsCheckBox.isSelected()) {
extractUrl += "&show-tags=all";
}
else {
int[] tagIndexes = tagsList.getSelectedIndices();
ListModel tagListModel = tagsList.getModel();
StringBuilder tagValues = new StringBuilder("");
for (int i = 0; i < tagIndexes.length; i++) {
if (i > 0) {
tagValues.append(",");
}
tagValues.append(tagListModel.getElementAt(tagIndexes[i]));
}
if (tagValues.length() > 0) {
extractUrl += "&show-tags=" + urlEncode(tagValues.toString());
}
}
String beginDate = beginDateTextField.getText().trim();
if (beginDate != null && beginDate.length() > 0) {
extractUrl += "&from-date=" + urlEncode(beginDate);
}
String endDate = endDateTextField.getText().trim();
if (endDate != null && endDate.length() > 0) {
extractUrl += "&to-date=" + urlEncode(endDate);
}
String tags = tagQueryTextField.getText().trim();
if (tags != null && tags.length() > 0) {
extractUrl += "&tags=" + urlEncode(tags);
}
String sections = sectionQueryTextField.getText().trim();
if (sections != null && sections.length() > 0) {
extractUrl += "§ion" + urlEncode(sections);
}
String order = rankComboBox.getSelectedItem().toString();
if (order != null && order.length() > 0) {
extractUrl += "&order-by=" + urlEncode(order);
}
extractUrl += "&page=1&api-key=" + key;
System.out.println("URL: " + extractUrl);
GuardianContentSearchExtractor ex = new GuardianContentSearchExtractor();
ex.setForceUrls(new String[] { extractUrl });
wt = ex;
wts.add(wt);
}
else if (tagSearchPanel.equals(component)) {
String query = tagSearchQueryTextField.getText();
String key = solveAPIKey();
if (key == null) {
return null;
}
String extractUrl = GUARDIAN_TAG_API_BASE + "&q=" + urlEncode(query);
if (allTagsCheckBox.isSelected()) {
extractUrl += "&type=all";
}
else {
int[] typeIndexes = typesList.getSelectedIndices();
ListModel listModel = typesList.getModel();
StringBuilder typeValues = new StringBuilder("");
for (int i = 0; i < typeIndexes.length; i++) {
if (i > 0) {
typeValues.append(",");
}
typeValues.append(listModel.getElementAt(typeIndexes[i]));
}
if (typeValues.length() > 0) {
extractUrl += "&type=" + urlEncode(typeValues.toString());
}
extractUrl += "&page=1&api-key=" + key;
System.out.println(extractUrl);
GuardianTagSearchExtractor ex = new GuardianTagSearchExtractor();
ex.setForceUrls(new String[] { extractUrl });
wt = ex;
wts.add(wt);
}
}
return wts.toArray(new WandoraTool[] {});
}
protected static String urlEncode(String str) {
try {
str = URLEncoder.encode(str, "utf-8");
} catch (Exception e) {
}
return str;
}
// ------------------------------------------------------------ API-KEY ----
private static String apikey = null;
public String solveAPIKey(Wandora wandora) {
return solveAPIKey();
}
public String solveAPIKey() {
if (apikey == null) {
apikey = "";
apikey = WandoraOptionPane.showInputDialog(Wandora.getWandora(),
"Please give an api-key for the Guardian API. You can register your api-key at http://www.guardian.co.uk/open-platform",
apikey, "the Guardian api-key", WandoraOptionPane.QUESTION_MESSAGE);
if (apikey != null)
apikey = apikey.trim();
}
forgetButton.setEnabled(true);
return apikey;
}
public void forgetAuthorization() {
apikey = null;
forgetButton.setEnabled(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;
guardianTabbedPane = new SimpleTabbedPane();
contentSearchPanel = new javax.swing.JPanel();
contentSearchInnerPanel = new javax.swing.JPanel();
searchLabel = new SimpleLabel();
searchQueryTextField = new SimpleField();
optionalSearchFieldsPanel = new javax.swing.JPanel();
tagLabel = new SimpleLabel();
tagQueryTextField = new SimpleField();
sectionLabel = new SimpleLabel();
sectionQueryTextField = new SimpleField();
beginDateLabel = new SimpleLabel();
beginDateTextField = new SimpleField();
endDateLabel = new SimpleLabel();
endDateTextField = new SimpleField();
orderByLabel = new SimpleLabel();
rankComboBox = new javax.swing.JComboBox();
fieldToReturnPanel = new javax.swing.JPanel();
FieldsToReturnLabel = new SimpleLabel();
fieldsScrollPanel = new javax.swing.JScrollPane();
fieldsList = new SimpleList();
tagsToReturnLabel = new SimpleLabel();
tagsScrollPanel = new javax.swing.JScrollPane();
tagsList = new SimpleList();
allFieldsCheckBox = new javax.swing.JCheckBox();
allTagsCheckBox = new javax.swing.JCheckBox();
tagSearchPanel = new javax.swing.JPanel();
tagSearchInnerPanel = new javax.swing.JPanel();
tagSearchLabel = new SimpleLabel();
tagSearchQueryTextField = new SimpleField();
optionaTagSearchFieldsPanel = new javax.swing.JPanel();
TypesList = new SimpleLabel();
typesScrollPanel = new javax.swing.JScrollPane();
typesList = new SimpleList();
allTypesCheckBox = new javax.swing.JCheckBox();
buttonPanel = new javax.swing.JPanel();
forgetButton = new SimpleButton();
buttonFillerPanel = new javax.swing.JPanel();
okButton = new SimpleButton();
cancelButton = new SimpleButton();
setLayout(new java.awt.GridBagLayout());
guardianTabbedPane.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
guardianTabbedPaneStateChanged(evt);
}
});
contentSearchPanel.setLayout(new java.awt.GridBagLayout());
contentSearchInnerPanel.setLayout(new java.awt.GridBagLayout());
searchLabel.setText("Search query");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
contentSearchInnerPanel.add(searchLabel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
contentSearchInnerPanel.add(searchQueryTextField, gridBagConstraints);
optionalSearchFieldsPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Optional params"));
optionalSearchFieldsPanel.setLayout(new java.awt.GridBagLayout());
tagLabel.setText("Tags (comma separated list)");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2);
optionalSearchFieldsPanel.add(tagLabel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
optionalSearchFieldsPanel.add(tagQueryTextField, gridBagConstraints);
sectionLabel.setText("Sections (comma separated list)");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2);
optionalSearchFieldsPanel.add(sectionLabel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
optionalSearchFieldsPanel.add(sectionQueryTextField, gridBagConstraints);
beginDateLabel.setText("Begin date (YYYY-MM-DD)");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
optionalSearchFieldsPanel.add(beginDateLabel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 6, 4);
optionalSearchFieldsPanel.add(beginDateTextField, gridBagConstraints);
endDateLabel.setText("End date (YYYY-MM-DD)");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
optionalSearchFieldsPanel.add(endDateLabel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 6, 4);
optionalSearchFieldsPanel.add(endDateTextField, gridBagConstraints);
orderByLabel.setText("Order by");
orderByLabel
.setToolTipText("Use the rank parameter to set the order of the results. The default rank is newest.");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 6;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4);
optionalSearchFieldsPanel.add(orderByLabel, gridBagConstraints);
rankComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "newest", "oldest", "relevance" }));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 6;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
optionalSearchFieldsPanel.add(rankComboBox, gridBagConstraints);
fieldToReturnPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Additional properties to return"));
fieldToReturnPanel.setLayout(new java.awt.GridBagLayout());
FieldsToReturnLabel.setText("Fields");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2);
fieldToReturnPanel.add(FieldsToReturnLabel, gridBagConstraints);
fieldsList.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "headline", "byline", "body", "standfirst", "strap", "short-url", "thumbnail",
"publication" };
public int getSize() {
return strings.length;
}
public Object getElementAt(int i) {
return strings[i];
}
});
fieldsScrollPanel.setViewportView(fieldsList);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.gridheight = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(2, 2, 4, 4);
fieldToReturnPanel.add(fieldsScrollPanel, gridBagConstraints);
tagsToReturnLabel.setText("Tags");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2);
fieldToReturnPanel.add(tagsToReturnLabel, gridBagConstraints);
tagsList.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "keyword", "contributor", "tone", "type" };
public int getSize() {
return strings.length;
}
public Object getElementAt(int i) {
return strings[i];
}
});
tagsScrollPanel.setViewportView(tagsList);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.gridheight = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(2, 2, 4, 4);
fieldToReturnPanel.add(tagsScrollPanel, gridBagConstraints);
allFieldsCheckBox.setText("all");
allFieldsCheckBox.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);
allFieldsCheckBox.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
allFieldsCheckBoxItemStateChanged(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
fieldToReturnPanel.add(allFieldsCheckBox, gridBagConstraints);
allTagsCheckBox.setText("all");
allTagsCheckBox.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);
allTagsCheckBox.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
allTagsCheckBoxItemStateChanged(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 0;
fieldToReturnPanel.add(allTagsCheckBox, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridheight = 8;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 5.0;
gridBagConstraints.weighty = 1.0;
optionalSearchFieldsPanel.add(fieldToReturnPanel, 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(8, 0, 0, 0);
contentSearchInnerPanel.add(optionalSearchFieldsPanel, 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(4, 4, 4, 4);
contentSearchPanel.add(contentSearchInnerPanel, gridBagConstraints);
guardianTabbedPane.addTab("Content search", contentSearchPanel);
tagSearchPanel.setLayout(new java.awt.GridBagLayout());
tagSearchInnerPanel.setLayout(new java.awt.GridBagLayout());
tagSearchLabel.setText("Search query");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
tagSearchInnerPanel.add(tagSearchLabel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
tagSearchInnerPanel.add(tagSearchQueryTextField, gridBagConstraints);
optionaTagSearchFieldsPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Optional params"));
optionaTagSearchFieldsPanel.setLayout(new java.awt.GridBagLayout());
TypesList.setText("Filter types");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2);
optionaTagSearchFieldsPanel.add(TypesList, gridBagConstraints);
typesList.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "keyword", "contributor", "tone", "series" };
public int getSize() {
return strings.length;
}
public Object getElementAt(int i) {
return strings[i];
}
});
typesScrollPanel.setViewportView(typesList);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
optionaTagSearchFieldsPanel.add(typesScrollPanel, gridBagConstraints);
allTypesCheckBox.setText("all");
allTypesCheckBox.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);
allTypesCheckBox.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
allTypesCheckBoxItemStateChanged(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
optionaTagSearchFieldsPanel.add(allTypesCheckBox, 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(8, 0, 0, 0);
tagSearchInnerPanel.add(optionaTagSearchFieldsPanel, 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(4, 4, 4, 4);
tagSearchPanel.add(tagSearchInnerPanel, gridBagConstraints);
guardianTabbedPane.addTab("Tag search", tagSearchPanel);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 1.0;
add(guardianTabbedPane, gridBagConstraints);
buttonPanel.setLayout(new java.awt.GridBagLayout());
forgetButton.setText("Forget api-key");
forgetButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
forgetButtonActionPerformed(evt);
}
});
buttonPanel.add(forgetButton, new java.awt.GridBagConstraints());
buttonFillerPanel.setLayout(new java.awt.GridBagLayout());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
buttonPanel.add(buttonFillerPanel, gridBagConstraints);
okButton.setText("Extract");
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, 2);
buttonPanel.add(okButton, gridBagConstraints);
cancelButton.setText("Cancel");
cancelButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelButtonActionPerformed(evt);
}
});
buttonPanel.add(cancelButton, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2);
add(buttonPanel, gridBagConstraints);
}// </editor-fold>//GEN-END:initComponents
private void forgetButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_forgetButtonActionPerformed
apikey = null;
forgetButton.setEnabled(false);
}// GEN-LAST:event_forgetButtonActionPerformed
private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_okButtonActionPerformed
accepted = true;
if (this.dialog != null) {
this.dialog.setVisible(false);
}
}// GEN-LAST:event_okButtonActionPerformed
private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_cancelButtonActionPerformed
accepted = false;
if (this.dialog != null) {
this.dialog.setVisible(false);
}
}// GEN-LAST:event_cancelButtonActionPerformed
private void allFieldsCheckBoxItemStateChanged(java.awt.event.ItemEvent evt) {// GEN-FIRST:event_allFieldsCheckBoxItemStateChanged
if (evt.getStateChange() == ItemEvent.SELECTED)
fieldsList.setEnabled(false);
else
fieldsList.setEnabled(true);
}// GEN-LAST:event_allFieldsCheckBoxItemStateChanged
private void allTagsCheckBoxItemStateChanged(java.awt.event.ItemEvent evt) {// GEN-FIRST:event_allTagsCheckBoxItemStateChanged
if (evt.getStateChange() == ItemEvent.SELECTED)
tagsList.setEnabled(false);
else
tagsList.setEnabled(true);
}// GEN-LAST:event_allTagsCheckBoxItemStateChanged
private void allTypesCheckBoxItemStateChanged(java.awt.event.ItemEvent evt) {// GEN-FIRST:event_allTypesCheckBoxItemStateChanged
// TODO add your handling code here:
}// GEN-LAST:event_allTypesCheckBoxItemStateChanged
private void guardianTabbedPaneStateChanged(javax.swing.event.ChangeEvent evt) {// GEN-FIRST:event_guardianTabbedPaneStateChanged
}// GEN-LAST:event_guardianTabbedPaneStateChanged
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel FieldsToReturnLabel;
private javax.swing.JLabel TypesList;
private javax.swing.JCheckBox allFieldsCheckBox;
private javax.swing.JCheckBox allTagsCheckBox;
private javax.swing.JCheckBox allTypesCheckBox;
private javax.swing.JLabel beginDateLabel;
private javax.swing.JTextField beginDateTextField;
private javax.swing.JPanel buttonFillerPanel;
private javax.swing.JPanel buttonPanel;
private javax.swing.JButton cancelButton;
private javax.swing.JPanel contentSearchInnerPanel;
private javax.swing.JPanel contentSearchPanel;
private javax.swing.JLabel endDateLabel;
private javax.swing.JTextField endDateTextField;
private javax.swing.JPanel fieldToReturnPanel;
private javax.swing.JList fieldsList;
private javax.swing.JScrollPane fieldsScrollPanel;
private javax.swing.JButton forgetButton;
private javax.swing.JTabbedPane guardianTabbedPane;
private javax.swing.JButton okButton;
private javax.swing.JPanel optionaTagSearchFieldsPanel;
private javax.swing.JPanel optionalSearchFieldsPanel;
private javax.swing.JLabel orderByLabel;
private javax.swing.JComboBox rankComboBox;
private javax.swing.JLabel searchLabel;
private javax.swing.JTextField searchQueryTextField;
private javax.swing.JLabel sectionLabel;
private javax.swing.JTextField sectionQueryTextField;
private javax.swing.JLabel tagLabel;
private javax.swing.JTextField tagQueryTextField;
private javax.swing.JPanel tagSearchInnerPanel;
private javax.swing.JLabel tagSearchLabel;
private javax.swing.JPanel tagSearchPanel;
private javax.swing.JTextField tagSearchQueryTextField;
private javax.swing.JList tagsList;
private javax.swing.JScrollPane tagsScrollPanel;
private javax.swing.JLabel tagsToReturnLabel;
private javax.swing.JList typesList;
private javax.swing.JScrollPane typesScrollPanel;
// End of variables declaration//GEN-END:variables
}
| 28,077 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
GuardianTagSearchExtractor.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/guardian/GuardianTagSearchExtractor.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.extractors.guardian;
import java.io.File;
import java.net.URL;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.wandora.application.Wandora;
import org.wandora.application.gui.WandoraOptionPane;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.utils.IObox;
/**
*
* @author Eero
*/
public class GuardianTagSearchExtractor extends AbstractGuardianExtractor {
private static final long serialVersionUID = 1L;
private static String defaultLang = "en";
private static String currentURL = null;
@Override
public String getName() {
return "The Guardian Tag Search API extractor";
}
@Override
public String getDescription() {
return "Extractor performs an tag search using The Guardian API and "
+ "transforms results to topics and associations.";
}
// -------------------------------------------------------------------------
@Override
public boolean _extractTopicsFrom(File f, TopicMap tm) throws Exception {
currentURL = null;
String in = IObox.loadFile(f);
JSONObject json = new JSONObject(in);
parse(json, tm);
return true;
}
@Override
public boolean _extractTopicsFrom(URL u, TopicMap tm) throws Exception {
currentURL = u.toExternalForm();
log("Tag search extraction with " + currentURL);
String in = IObox.doUrl(u);
System.out.println(
"The Guardian API returned-------------------------\n" + in
+ "\n----------------------------------------------------");
JSONObject json = new JSONObject(in);
if (json.has("response")) {
try {
JSONObject response = json.getJSONObject("response");
int nResults = response.getJSONArray("results").length();
if (response.has("didYouMean") && nResults == 0) {
String dym = response.getString("didYouMean");
int didMean = WandoraOptionPane.showConfirmDialog(Wandora.getWandora(),
"Did you mean \"" + dym + "\"", "Did you mean", WandoraOptionPane.YES_NO_OPTION);
if (didMean == 1100) {
URL newUrl = new URL(currentURL.replaceAll("&q=[^&]*", "&q=" + dym));
System.out.println(newUrl.toString());
this._extractTopicsFrom(newUrl, tm);
} else {
parse(response, tm);
}
} else {
parse(response, tm);
}
} catch (Exception e) {
System.out.println(e);
}
}
return true;
}
@Override
public boolean _extractTopicsFrom(String str, TopicMap tm) throws Exception {
currentURL = null;
JSONObject json = new JSONObject(str);
if (json.has("response")) {
System.out.println("json has response!");
JSONObject response = json.getJSONObject("response");
parse(response, tm);
}
return true;
}
// -------------------------------------------------------------------------
public void parse(JSONObject json, TopicMap tm) throws TopicMapException {
if (json.has("results")) {
try {
JSONArray resultsArray = json.getJSONArray("results");
for (int i = 0; i < resultsArray.length(); i++) {
JSONObject result = resultsArray.getJSONObject(i);
parseResult(result, tm);
}
} catch (JSONException ex) {
System.out.println(ex);
log(ex);
}
}
handlePagination(json, tm);
}
private boolean shouldHandlePagination = true;
private String defaultPagingOption = null;
private void handlePagination(JSONObject json, TopicMap tm) {
if (!shouldHandlePagination || forceStop())
return;
if (json.has("pages")) {
try {
int page = json.getInt("currentPage");
int total = json.getInt("pages");
if (page < total) {
if (currentURL != null) {
String[] pagingOptions = new String[] {
"Do not extract any more pages",
"Extract only next page",
"Extract next page",
"Extract 10 next pages",
"Extract all next pages" };
String message = "You have just extracted page " + page + ". There is total " + total
+ " pages available. What would you like to do? "
+ "Remember The Guardian APIs limit daily requests. Extracting one page takes one request.";
if (defaultPagingOption == null) {
defaultPagingOption = pagingOptions[0];
}
String a = WandoraOptionPane.showOptionDialog(Wandora.getWandora(), message, "Found more pages",
WandoraOptionPane.OK_CANCEL_OPTION, pagingOptions, defaultPagingOption);
defaultPagingOption = a;
if (a != null) {
String originalURL = currentURL;
try {
if (pagingOptions[1].equals(a)) {
System.out.println("Selected to extract only next page");
String newURL = originalURL.replace("page=" + page, "page=" + (page + 1));
shouldHandlePagination = false;
_extractTopicsFrom(new URL(newURL), tm);
}
else if (pagingOptions[2].equals(a)) {
System.out.println("Selected to extract next page");
String newURL = originalURL.replace("page=" + page, "page=" + (page + 1));
_extractTopicsFrom(new URL(newURL), tm);
}
else if (pagingOptions[3].equals(a)) {
System.out.println("Selected to extract 10 next pages");
shouldHandlePagination = false;
setProgress(1);
setProgressMax(10);
int progress = 1;
for (int p = page + 1; p <= Math.min(page + 10, total) && !forceStop(); p++) {
String newURL = originalURL.replace("page=" + page, "page=" + p);
if (p == page + 10)
shouldHandlePagination = true;
_extractTopicsFrom(new URL(newURL), tm);
setProgress(progress++);
nap();
}
}
else if (pagingOptions[4].equals(a)) {
System.out.println("Selected to extract all pages");
shouldHandlePagination = false;
setProgress(1);
setProgressMax((int) (total));
int progress = 1;
for (int p = page + 1; p <= total && !forceStop(); p++) {
String newURL = originalURL.replace("page=" + page, "page=" + p);
_extractTopicsFrom(new URL(newURL), tm);
setProgress(progress++);
nap();
}
shouldHandlePagination = true;
}
} catch (Exception e) {
log(e);
}
}
}
}
} catch (JSONException ex) {
log(ex);
}
}
}
private void nap() {
try {
Thread.sleep(200);
} catch (Exception e) {
// WAKE UP
}
}
public void parseResult(JSONObject tag, TopicMap tm) throws JSONException, TopicMapException {
String tagId = tag.getString("id");
String tagUrl = tag.getString("webUrl");
String tagTitle = tag.has("webTitle") ? tag.getString("webTitle") : null;
String tagTtype = tag.has("type") ? tag.getString("type") : null;
String tagSectId = tag.has("sectionId") ? tag.getString("sectionId") : null;
String tagSectName = tag.has("sectionName") ? tag.getString("sectionName") : null;
Topic tagTopic = getOrCreateTopic(tm, TAG_BASE_SI + tagId);
Topic tagTopicType = getTagTopicType(tm);
tagTopic.addType(tagTopicType);
tagTopic.addSubjectIdentifier(new Locator(tagUrl));
tagTopic.setBaseName(tagId);
if (tagTtype != null) {
parseTagAssociation(tag, "type", tm, tagTopic, tagTopicType);
}
if (tagSectId != null) {
parseTagAssociation(tag, "sectionId", tm, tagTopic, tagTopicType);
}
if (tagSectName != null) {
parseTagAssociation(tag, "sectionName", tm, tagTopic, tagTopicType);
}
}
private void parseTagAssociation(JSONObject result, String jsonObjectName, TopicMap tm, Topic ct, Topic cty) {
try {
String s = result.getString(jsonObjectName);
if (s != null && s.length() > 0) {
Topic t = getTagTopic(tm, jsonObjectName, s);
Topic ty = getTagType(tm, jsonObjectName);
Association a = tm.createAssociation(ty);
a.addPlayer(ct, cty);
a.addPlayer(t, ty);
}
} catch (Exception ex) {
log(ex);
}
}
}
| 8,836 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
GuardianExtractor.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/guardian/GuardianExtractor.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.extractors.guardian;
import java.io.File;
import java.net.URL;
import javax.swing.Icon;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.UIBox;
import org.wandora.application.tools.extractors.AbstractExtractor;
import org.wandora.topicmap.TopicMap;
/**
*
* @author
* Eero Lehtonen
*/
public class GuardianExtractor extends AbstractExtractor{
private static final long serialVersionUID = 1L;
private GuardianExtractorUI ui = null;
@Override
public String getName() {
return "The Guardian API Extractor";
}
@Override
public String getDescription(){
return "Extracts topics and associations from The Guardian API. "+
"A personal api-key is required for the API access.";
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/extract_guardian.png");
}
private final String[] contentTypes=new String[] { "text/plain", "text/json", "application/json" };
@Override
public String[] getContentTypes() {
return contentTypes;
}
@Override
public boolean useURLCrawler() {
return false;
}
@Override
public void execute(Wandora wandora, Context context) {
try {
if(ui == null) {
ui = new GuardianExtractorUI();
}
ui.open(wandora, context);
if(ui.wasAccepted()) {
WandoraTool[] extrs = null;
try{
extrs = ui.getExtractors(this);
} catch(Exception e) {
log(e.getMessage());
return;
}
if(extrs != null && extrs.length > 0) {
setDefaultLogger();
int c = 0;
log("Performing The Guardian API query...");
for(int i=0; i<extrs.length && !forceStop(); i++) {
try {
log(extrs[i].toString());
WandoraTool e = extrs[i];
e.setToolLogger(getDefaultLogger());
e.execute(wandora);
c++;
}
catch(Exception e) {
log(e);
}
}
log("Ready.");
}
else {
log("Couldn't find a suitable subextractor to perform or there was an error with an extractor.");
}
}
}
catch(Exception e) {
singleLog(e);
}
if(ui != null && ui.wasAccepted()) setState(WAIT);
else setState(CLOSE);
}
// -------------------------------------------------------------------------
@Override
public boolean _extractTopicsFrom(File f, TopicMap t) throws Exception {
throw new UnsupportedOperationException("This extractor is a frontend for other extractors for The Guardian. It doesn't perform extration it self.");
}
@Override
public boolean _extractTopicsFrom(URL u, TopicMap t) throws Exception {
throw new UnsupportedOperationException("This extractor is a frontend for other extractors for The Guardian. It doesn't perform extration it self.");
}
@Override
public boolean _extractTopicsFrom(String str, TopicMap t) throws Exception {
throw new UnsupportedOperationException("This extractor is a frontend for other extractors for The Guardian. It doesn't perform extration it self.");
}
}
| 4,557 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AbstractGuardianExtractor.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/guardian/AbstractGuardianExtractor.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.extractors.guardian;
import java.util.HashMap;
import javax.swing.Icon;
import org.wandora.application.gui.UIBox;
import org.wandora.application.tools.extractors.AbstractExtractor;
import org.wandora.application.tools.extractors.ExtractHelper;
import org.wandora.topicmap.TMBox;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author
* Eero Lehtonen
*/
public abstract class AbstractGuardianExtractor extends AbstractExtractor {
private static final long serialVersionUID = 1L;
@Override
public String getName() {
return "Abstract The Guardian API extractor";
}
@Override
public String getDescription(){
return "Abstract extractor for The Guardian API.";
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/extract_nyt.png");
}
private final String[] contentTypes=new String[] { "text/plain", "text/json", "application/json" };
@Override
public String[] getContentTypes() {
return contentTypes;
}
@Override
public boolean useURLCrawler() {
return false;
}
@Override
public boolean runInOwnThread() {
return false;
}
// -------------------------------------------------------------------------
public static final String GUARDIAN_BASE_SI = "http://wandora.org/si/theguardian/";
public static final String FIELD_BASE_SI = GUARDIAN_BASE_SI + "field/";
public static final String TAG_BASE_SI = GUARDIAN_BASE_SI + "tag/";
public static final String CONTENT_SI = GUARDIAN_BASE_SI + "content";
public static final String DATE_SI = GUARDIAN_BASE_SI + "date";
public static final String ID_SI = GUARDIAN_BASE_SI + "ID";
public static final String TITLE_SI = GUARDIAN_BASE_SI + "title";
public static final String PUBLICATION_TIME_SI = GUARDIAN_BASE_SI + "pubtime";
public static final String SECTION_ID_SI = GUARDIAN_BASE_SI + "sectionid";
public static final String SECTION_NAME_SI = GUARDIAN_BASE_SI + "sectionname";
public static final String WEB_URL_SI = GUARDIAN_BASE_SI + "web_url";
public static final String API_URL_SI = GUARDIAN_BASE_SI + "api_url";
public static final String LANG_SI = "http://www.topicmaps.org/xtm/1.0/language.xtm#en";
private static HashMap<String,String> fieldNames = new HashMap<String, String>() {{
put("trailText","trail text");
put("showInRelatedContent","show in related content");
put("lastModified","last modified");
put("hasStoryPackage","has story package");
put("standFirst","stand first");
put("shortUrl","short URL");
put("shouldHideAdverts","should hide adverts");
put("liveBloggingNow","live blogging now");
put("newspaperEditionDate","newspaper edition date");
put("newspaperPageNumber","newspaper page number");
}};
public static Topic getIDType(TopicMap tm) throws TopicMapException{
Topic type = getOrCreateTopic(tm, ID_SI, "content ID (The Guardian API)");
Topic guardianTopic = getGuardianType(tm);
makeSubclassOf(tm, type, guardianTopic);
return type;
}
public static Topic getTitleType(TopicMap tm) throws TopicMapException{
Topic type = getOrCreateTopic(tm, TITLE_SI, "content title (The Guardian API)");
Topic guardianTopic = getGuardianType(tm);
makeSubclassOf(tm, type, guardianTopic);
return type;
}
public static Topic getDateType(TopicMap tm) throws TopicMapException{
Topic type = getOrCreateTopic(tm, DATE_SI, "content date (The Guardian API)");
Topic guardianTopic = getGuardianType(tm);
makeSubclassOf(tm, type, guardianTopic);
return type;
}
public static Topic getDateTopic(TopicMap tm, String date) throws TopicMapException{
Topic dateTopic = getOrCreateTopic(tm, DATE_SI+"/"+urlEncode(date), date + " (The Guardian API)");
dateTopic.addType(getDateType(tm));
return dateTopic;
}
public static Topic getPubTimeType(TopicMap tm) throws TopicMapException{
Topic type = getOrCreateTopic(tm, PUBLICATION_TIME_SI, "content publication time (The Guardian API)");
Topic guardianTopic = getGuardianType(tm);
makeSubclassOf(tm, type, guardianTopic);
return type;
}
public static Topic getContentType(TopicMap tm) throws TopicMapException{
Topic type = getOrCreateTopic(tm, CONTENT_SI, "content (The Guardian API)");
Topic guardianTopic = getGuardianType(tm);
makeSubclassOf(tm, type, guardianTopic);
return type;
}
public static Topic getFieldType(TopicMap tm, String siExt){
Topic t = null;
String desc = fieldNames.containsKey(siExt) ? fieldNames.get(siExt) : siExt;
try {
t = getOrCreateTopic(tm, FIELD_BASE_SI + siExt, desc + " (The Guardian API / Field)");
Topic fieldTopicType = getFieldTopicType(tm);
makeSubclassOf(tm, t, fieldTopicType);
} catch (TopicMapException e) {
e.printStackTrace();
}
return t;
}
public static Topic getFieldTopic(TopicMap tm, String siExt, String id){
Topic t = null;
String siEnd = urlEncode(id);
try {
t = getOrCreateTopic(tm, FIELD_BASE_SI+siExt+"/" + siEnd,id + " (The Guardian API / Field)");
} catch (TopicMapException e) {
e.printStackTrace();
}
return t;
}
public static Topic getTagType(TopicMap tm, String siExt){
Topic t = null;
String desc = fieldNames.containsKey(siExt) ? fieldNames.get(siExt) : siExt;
try {
t = getOrCreateTopic(tm, TAG_BASE_SI + siExt, desc + " (The Guardian API / Tag)");
Topic tagTopicType = getTagTopicType(tm);
t.addType(tagTopicType);
} catch (TopicMapException e) {
e.printStackTrace();
}
return t;
}
public static Topic getTagTopic(TopicMap tm, String siExt, String id){
Topic t = null;
String siEnd = urlEncode(id);
try {
t = getOrCreateTopic(tm, TAG_BASE_SI+siExt+"/" + siEnd,id + " (The Guardian API / Tag)");
} catch (TopicMapException e) {
e.printStackTrace();
}
return t;
}
public static Topic getGuardianType(TopicMap tm) throws TopicMapException {
Topic type=getOrCreateTopic(tm, GUARDIAN_BASE_SI, "The Guardian API");
Topic wandoraClass = getWandoraClassTopic(tm);
makeSubclassOf(tm, type, wandoraClass);
return type;
}
public static Topic getFieldTopicType(TopicMap tm) throws TopicMapException {
Topic type=getOrCreateTopic(tm, FIELD_BASE_SI, "Field (The Guardian API)");
Topic guardianType = getGuardianType(tm);
makeSubclassOf(tm, type, guardianType);
return type;
}
public static Topic getTagTopicType(TopicMap tm) throws TopicMapException {
Topic type=getOrCreateTopic(tm, TAG_BASE_SI, "Tag (The Guardian API)");
Topic guardianType = getGuardianType(tm);
makeSubclassOf(tm, type, guardianType);
return type;
}
protected static Topic getWandoraClassTopic(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, TMBox.WANDORACLASS_SI, "Wandora class");
}
protected static Topic getLangTopic(TopicMap tm) throws TopicMapException {
Topic lang = getOrCreateTopic(tm, LANG_SI);
return lang;
}
protected static Topic getOrCreateTopic(TopicMap tm, String si) throws TopicMapException {
return getOrCreateTopic(tm, si,null);
}
protected static Topic getOrCreateTopic(TopicMap tm, String si, String bn) throws TopicMapException {
return ExtractHelper.getOrCreateTopic(si, bn, tm);
}
protected static void makeSubclassOf(TopicMap tm, Topic t, Topic superclass) throws TopicMapException {
ExtractHelper.makeSubclassOf(t, superclass, tm);
}
}
| 8,962 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
GuardianContentSearchExtractor.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/guardian/GuardianContentSearchExtractor.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.extractors.guardian;
import java.io.File;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.wandora.application.Wandora;
import org.wandora.application.gui.WandoraOptionPane;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.utils.IObox;
/**
*
* @author Eero
*/
public class GuardianContentSearchExtractor extends AbstractGuardianExtractor {
private static final long serialVersionUID = 1L;
private static String defaultLang = "en";
private static String currentURL = null;
@Override
public String getName() {
return "The Guardian Content Search API extractor";
}
@Override
public String getDescription() {
return "Extractor performs an content search using The Guardian API and "
+ "transforms results to topics and associations.";
}
// -------------------------------------------------------------------------
@Override
public boolean _extractTopicsFrom(File f, TopicMap tm) throws Exception {
currentURL = null;
String in = IObox.loadFile(f);
JSONObject json = new JSONObject(in);
parse(json, tm);
return true;
}
@Override
public boolean _extractTopicsFrom(URL u, TopicMap tm) throws Exception {
currentURL = u.toExternalForm();
log("Content search extraction with " + currentURL);
String in = IObox.doUrl(u);
System.out.println(
"The Guardian API returned-------------------------\n" + in
+ "\n----------------------------------------------------");
JSONObject json = new JSONObject(in);
if (json.has("response")) {
try {
JSONObject response = json.getJSONObject("response");
int nResults = response.getJSONArray("results").length();
if (response.has("didYouMean") && nResults == 0) {
String dym = response.getString("didYouMean");
int didMean = WandoraOptionPane.showConfirmDialog(
Wandora.getWandora(),
"Did you mean \"" + dym + "\"",
"Did you mean",
WandoraOptionPane.YES_NO_OPTION);
if (didMean == WandoraOptionPane.YES_OPTION) {
URL newUrl = new URL(currentURL.replaceAll("&q=[^&]*", "&q=" + dym));
System.out.println(newUrl.toString());
this._extractTopicsFrom(newUrl, tm);
}
else {
parse(response, tm);
}
}
else {
parse(response, tm);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
return true;
}
@Override
public boolean _extractTopicsFrom(String str, TopicMap tm) throws Exception {
currentURL = null;
JSONObject json = new JSONObject(str);
if (json.has("response")) {
JSONObject response = json.getJSONObject("response");
parse(response, tm);
}
return true;
}
// -------------------------------------------------------------------------
public void parse(JSONObject json, TopicMap tm) throws TopicMapException {
if (json.has("results")) {
try {
JSONArray resultsArray = json.getJSONArray("results");
for (int i = 0; i < resultsArray.length(); i++) {
JSONObject result = resultsArray.getJSONObject(i);
parseResult(result, tm);
}
} catch (JSONException ex) {
System.out.println(ex);
log(ex);
}
}
handlePagination(json, tm);
}
private boolean shouldHandlePagination = true;
private String defaultPagingOption = null;
private void handlePagination(JSONObject json, TopicMap tm) {
if (!shouldHandlePagination || forceStop())
return;
if (json.has("pages")) {
try {
int page = json.getInt("currentPage");
int total = json.getInt("pages");
if (page < total) {
if (currentURL != null) {
String[] pagingOptions = new String[] { "Do not extract any more pages",
"Extract only next page", "Extract next page", "Extract 10 next pages",
"Extract all next pages" };
String message = "You have just extracted page " + page + ". There is total " + total
+ " pages available. What would you like to do? "
+ "Remember The Guardian APIs limit daily requests. Extracting one page takes one request.";
if (defaultPagingOption == null)
defaultPagingOption = pagingOptions[0];
String a = WandoraOptionPane.showOptionDialog(Wandora.getWandora(), message, "Found more pages",
WandoraOptionPane.OK_CANCEL_OPTION, pagingOptions, defaultPagingOption);
defaultPagingOption = a;
if (a != null) {
String originalURL = currentURL;
try {
if (pagingOptions[1].equals(a)) {
System.out.println("Selected to extract only next page");
String newURL = originalURL.replace("page=" + page, "page=" + (page + 1));
shouldHandlePagination = false;
_extractTopicsFrom(new URL(newURL), tm);
}
else if (pagingOptions[2].equals(a)) {
System.out.println("Selected to extract next page");
String newURL = originalURL.replace("page=" + page, "page=" + (page + 1));
_extractTopicsFrom(new URL(newURL), tm);
}
else if (pagingOptions[3].equals(a)) {
System.out.println("Selected to extract 10 next pages");
shouldHandlePagination = false;
setProgress(1);
setProgressMax(10);
int progress = 1;
for (int p = page + 1; p <= Math.min(page + 10, total) && !forceStop(); p++) {
String newURL = originalURL.replace("page=" + page, "page=" + p);
if (p == page + 10)
shouldHandlePagination = true;
_extractTopicsFrom(new URL(newURL), tm);
setProgress(progress++);
nap();
}
}
else if (pagingOptions[4].equals(a)) {
System.out.println("Selected to extract all pages");
shouldHandlePagination = false;
setProgress(1);
setProgressMax((int) (total));
int progress = 1;
for (int p = page + 1; p <= total && !forceStop(); p++) {
String newURL = originalURL.replace("page=" + page, "page=" + p);
_extractTopicsFrom(new URL(newURL), tm);
setProgress(progress++);
nap();
}
shouldHandlePagination = true;
}
}
catch (Exception e) {
log(e);
}
}
}
}
} catch (JSONException ex) {
log(ex);
}
}
}
private void nap() {
try {
Thread.sleep(200);
} catch (Exception e) {
// WAKE UP
}
}
public void parseResult(JSONObject result, TopicMap tm) throws JSONException, TopicMapException {
ArrayList<String> toAsso = new ArrayList<String>();
toAsso.add("shouldHideAdverts");
toAsso.add("commentable");
toAsso.add("showInRelatedContent");
toAsso.add("liveBloggingNow");
toAsso.add("hasStoryPackage");
toAsso.add("publication");
if (result.has("id")) {
String id = result.getString("id");
Topic contentTopic = tm.createTopic();
contentTopic.addSubjectIdentifier(new Locator(GUARDIAN_BASE_SI + id));
contentTopic.addType(getContentType(tm));
if (result.has("webTitle")) {
Topic titleTypeTopic = getTitleType(tm);
contentTopic.setBaseName(result.getString("webTitle"));
contentTopic.setDisplayName("en", result.getString("webTitle"));
parseOccurrence(result, "webTitle", tm, contentTopic, titleTypeTopic);
}
if (result.has("webPublicationDate")) {
Topic pubDateTypeTopic = getPubTimeType(tm);
parseOccurrence(result, "webPublicationDate", tm, contentTopic, pubDateTypeTopic);
SimpleDateFormat dfin = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
SimpleDateFormat dfout = new SimpleDateFormat("yyyy-MM-dd");
try {
Date d = dfin.parse(result.getString("webPublicationDate"));
String shortDate = dfout.format(d);
Association a = tm.createAssociation(getDateType(tm));
Topic dateTopic = getDateTopic(tm, shortDate);
a.addPlayer(contentTopic, getContentType(tm));
a.addPlayer(dateTopic, getDateType(tm));
} catch (Exception e) {
log(e);
}
}
if (result.has("fields")) {
JSONObject fields = result.getJSONObject("fields");
Iterator keys = fields.keys();
while (keys.hasNext()) {
String key = keys.next().toString();
Topic type = getFieldType(tm, key);
if (toAsso.contains(key)) {
parseFieldAssociation(fields, key, tm, contentTopic, type);
} else {
parseOccurrence(fields, key, tm, contentTopic, type);
}
}
}
if (result.has("tags")) {
JSONArray tags = result.getJSONArray("tags");
for (int i = 0; i < tags.length(); i++) {
JSONObject tag = tags.getJSONObject(i);
String tagId = tag.getString("id");
String tagUrl = tag.getString("webUrl");
String tagTitle = tag.has("webTitle") ? tag.getString("webTitle") : null;
String tagTtype = tag.has("type") ? tag.getString("type") : null;
String tagSectId = tag.has("sectionId") ? tag.getString("sectionId") : null;
String tagSectName = tag.has("sectionName") ? tag.getString("sectionName") : null;
Topic tagTopic = getOrCreateTopic(tm, TAG_BASE_SI + tagId);
Topic tagTopicType = getTagTopicType(tm);
tagTopic.addType(tagTopicType);
tagTopic.addSubjectIdentifier(new Locator(tagUrl));
Association a = tm.createAssociation(tagTopicType);
a.addPlayer(tagTopic, tagTopicType);
a.addPlayer(contentTopic, getContentType(tm));
tagTopic.setBaseName(tagId);
String displayName = tagTitle == null ? tagId : tagTitle;
tagTopic.setDisplayName(displayName, defaultLang);
if (tagTtype != null) {
parseTagAssociation(tag, "type", tm, tagTopic, tagTopicType);
}
if (tagSectId != null) {
parseTagAssociation(tag, "sectionId", tm, tagTopic, tagTopicType);
}
if (tagSectName != null) {
parseTagAssociation(tag, "sectionName", tm, tagTopic, tagTopicType);
}
}
}
}
}
private void parseOccurrence(JSONObject result, String jsonObjectName, TopicMap tm, Topic t, Topic ty) {
try {
Topic langTopic = getLangTopic(tm);
String s = result.getString(jsonObjectName);
if (s != null && s.length() > 0) {
t.setData(ty, langTopic, s);
}
} catch (Exception ex) {
log(ex);
}
}
private void parseFieldAssociation(JSONObject result, String jsonObjectName, TopicMap tm, Topic ct, Topic ty) {
try {
String s = result.getString(jsonObjectName);
if (s != null && s.length() > 0) {
Topic t = getFieldTopic(tm, jsonObjectName, s);
Topic cty = getContentType(tm);
Association a = tm.createAssociation(ty);
a.addPlayer(t, ty);
a.addPlayer(ct, cty);
}
} catch (Exception ex) {
log(ex);
}
}
private void parseTagAssociation(JSONObject result, String jsonObjectName, TopicMap tm, Topic ct, Topic cty) {
try {
String s = result.getString(jsonObjectName);
if (s != null && s.length() > 0) {
Topic t = getTagTopic(tm, jsonObjectName, s);
Topic ty = getTagType(tm, jsonObjectName);
Association a = tm.createAssociation(ty);
a.addPlayer(ct, cty);
a.addPlayer(t, ty);
}
} catch (Exception ex) {
log(ex);
}
}
}
| 12,154 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
RISReference.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/ris/RISReference.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* RISReference.java
*
* Created on March 3, 2008, 1:49 PM
*/
package org.wandora.application.tools.extractors.ris;
import static org.wandora.utils.Tuples.t2;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.BufferUnderflowException;
import java.nio.CharBuffer;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.wandora.application.WandoraToolLogger;
import org.wandora.utils.Tuples.T2;
/**
*
* @author anttirt
*/
public class RISReference {
public String refID = null,
titleTag = null,
secondaryTitleTag = null,
seriesTag = null,
publicationCity = null,
publisher = null,
serial = null,
address = null, // ISSN/ISBN
availability = null,
issue = null,
startPage = null,
endPage = null;
public ArrayList<URL> mainURL = new ArrayList<URL>(),
pdfURL = new ArrayList<URL>(),
fullTextURL = new ArrayList<URL>();
public Integer volumeNumber = null;
public ReferenceType refType = null;
public ArrayList<T2<Types, String>> miscTags = new ArrayList<T2<Types, String>>(),
unknownTags = new ArrayList<T2<Types, String>>(),
authorTags = new ArrayList<T2<Types, String>>(),
noteTags = new ArrayList<T2<Types, String>>(),
userTags = new ArrayList<T2<Types, String>>();
public Date dateTag = null;
public ArrayList<T2<ReprintType, Date>> reprintInfo = null;
public String periodicalName = null;
public ArrayList<String> periodicalAbbr = new ArrayList<String>(),
keyWords = new ArrayList<String>(),
relatedRecords = new ArrayList<String>();
public DOI doi;
private WandoraToolLogger mLog;
public static String getWart(ReferenceType type)
{
String baseStr = "";
switch(type)
{
case ABST: baseStr = "abstract"; break;
case ADVS: baseStr = "audiovisual"; break;
case ART: baseStr = "artwork"; break;
case BILL: baseStr = "bill/resolution"; break;
case BOOK: baseStr = "book"; break;
case CASE: baseStr = "case"; break;
case CHAP: baseStr = "chapter"; break;
case COMP: baseStr = "computer program"; break;
case CONF: baseStr = "conference proceeding"; break;
case CTLG: baseStr = "catalog"; break;
case DATA: baseStr = "data file"; break;
case ELEC: baseStr = "electronic citation"; break;
//case GEN: baseStr = "generic"; break;
case HEAR: baseStr = "hearing"; break;
case ICOMM: baseStr = "internet communication"; break;
case INPR: baseStr = "in press"; break;
case JFULL: baseStr = "journal"; break;
case JOUR: baseStr = "article"; break;
case MAP: baseStr = "map"; break;
case MGZN: baseStr = "article"; break;
case MPCT: baseStr = "motion picture"; break;
case MUSIC: baseStr = "music score"; break;
case NEWS: baseStr = "newspaper"; break;
case PAMP: baseStr = "pamphlet"; break;
case PAT: baseStr = "patent"; break;
case PCOMM: baseStr = "personal communication"; break;
case RPRT: baseStr = "report"; break;
case SER: baseStr = "serial"; break;
case SLIDE: baseStr = "slide"; break;
case SOUND: baseStr = "recording"; break;
case STAT: baseStr = "statute"; break;
case THES: baseStr = "thesis"; break;
case UNBILL: baseStr = "unenacted bill/resolution"; break;
case UNPB: baseStr = "unpublished work"; break;
case VIDEO: baseStr = "video recording"; break;
default:
baseStr = "title";
}
return " (" + baseStr + ")";
}
public static class DOI
{
public int DirectoryCode;
public int PublisherID;
public String Suffix;
public DOI(int dirCode, int pubID, String suffix)
{
DirectoryCode = dirCode;
PublisherID = pubID;
Suffix = suffix;
}
public String toString()
{
return String.valueOf(DirectoryCode) + '.' + String.valueOf(PublisherID) + '/' + Suffix;
}
public static String getPublisherName(int publisherID)
{
switch(publisherID)
{
case 1002:
return "Wiley";
case 1006:
return "Academic Press";
case 1007:
return "Springer Verlag";
case 1016:
return "Elsevier Science";
case 1017:
return "Cambridge University Press";
case 1038:
return "American Chemical Society";
case 1039:
return "NATURE";
case 1046:
return "Royal Society of Chemistry";
case 1055:
return "Blackwell Publishers";
case 1063:
return "G. Thieme Verlag";
case 1073:
return "American Institute of Physics";
case 1074:
return "Proceedings of the National Academy of Sciences";
case 1080:
return "Journal of Biological Chemistry";
case 1083:
return "Taylor and Francis";
case 1092:
return "Laser Pages Publishing";
case 1093:
return "Oxford University Press";
case 1103:
return "American Physical Society";
case 1107:
return "International Union of Crystallography";
case 1126:
return "SCIENCE magazine";
case 1161:
return "American Heart Association";
case 1182:
return "American Society of hematology";
}
return null;
}
}
public RISReference(CharBuffer buffer, WandoraToolLogger log) throws IllegalArgumentException {
mLog = log;
try
{
Pattern firstPattern = Pattern.compile("TY - ");
{
CharSequence seq = buffer.subSequence(0, buffer.remaining());
Matcher findFirst = firstPattern.matcher(seq);
if(!findFirst.find())
throw new IllegalArgumentException("Unable to find start tag");
buffer.position(buffer.position() + findFirst.start());
}
Types firstTag = Types.INVALID;
/*
try
{
*/
firstTag = readTag(buffer);
/*
}
catch(IllegalArgumentException e)
{
// If the first tag read failed, readString to get any extra stuff and try again until we run out of characters
readString(buffer);
firstTag = readTag(buffer);
}
switch(firstTag)
{
case TY:
try
{
*/
refType = ReferenceType.valueOf(readString(buffer));
/*
}
catch(IllegalArgumentException e)
{
if(log != null) log.log("Unrecognized reference category. " + e.toString());
}
break;
default:
throw new IllegalArgumentException("Invalid tag: " + firstTag.toString() + " (expected TY)");
}
*/
Pattern datePattern = Pattern.compile("(\\d+)");
// this either returns on ER or throws on invalid data
for(;;)
{
Types type = readTag(buffer);
String contents = type == Types.ER ? ignoreCRLF(buffer) : readString(buffer);
switch(type)
{
// authors
case A1: case AU: case A2: case ED: case A3:
// TODO: Function for parsing names from format: LastName, FirstName[, Suffix]
authorTags.add(t2(type, contents));
break;
// primary title
case T1: case TI: case CT:
titleTag = contents;
break;
// ???
case BT:
if(refType == ReferenceType.BOOK || refType == ReferenceType.UNPB)
titleTag = contents;
else
secondaryTitleTag = contents;
break;
// secondary title:
case T2:
secondaryTitleTag = contents;
break;
// title series:
case T3:
seriesTag = contents;
break;
// dates
case Y1: case PY: case Y2: {
Matcher m = datePattern.matcher(contents);
Integer year = null, month = null, day = null;
if(m.find(0))
{
year = Integer.parseInt(m.group());
if(m.find())
{
month = Integer.parseInt(m.group());
if(m.find())
{
day = Integer.parseInt(m.group());
}
}
}
dateTag = new Date(year, month, day, "");
break;
}
// notes
case N1: case AB: case N2:
noteTags.add(t2(type, contents));
break;
// keywords
case KW:
keyWords.add(contents);
break;
// periodical name and abbr.
case JF: case JO:
periodicalName = contents;
break;
case JA: case J1: case J2:
periodicalAbbr.add(contents);
break;
// reference id
case ID:
refID = contents;
break;
case VL: case IS: case CP:
issue = contents;
break;
case SP:
startPage = contents;
break;
case EP:
endPage = contents;
break;
case CY:
publicationCity = contents;
break;
case PB:
publisher = contents;
break;
case SN:
serial = contents;
break;
case AD:
address = contents;
break;
case AV: // availability
availability = contents;
break;
case UR: // url
try
{
mainURL.add(new URI(contents).toURL());
}
catch(URISyntaxException e) { if(log != null) log.log("Invalid URI syntax for web link: " + e.toString()); }
catch(MalformedURLException e) { if(log != null) log.log("Malformed URL for web link: " + e.toString()); }
break;
case L1: // link(s) to pdf
try
{
pdfURL.add(new URI(contents).toURL());
}
catch(URISyntaxException e) { if(log != null) log.log("Invalid URI syntax for pdf link: " + e.toString()); }
catch(MalformedURLException e) { if(log != null) log.log("Malformed URL for pdf link: " + e.toString()); }
break;
case L2: // link(s) to full-text
try
{
fullTextURL.add(new URI(contents).toURL());
}
catch(URISyntaxException e) { if(log != null) log.log("Invalid URI syntax for full-text link: " + e.toString()); }
catch(MalformedURLException e) { if(log != null) log.log("Malformed URL for full-text link: " + e.toString()); }
break;
case L3: // related record(s)
break;
case L4: // image(s)
break;
case M1: case M2: case M3:
if(!tryInterpret(contents))
miscTags.add(t2(type, contents));
break;
case U1: case U2: case U3: case U4: case U5:
userTags.add(t2(type, contents));
break;
// done, discard any extra stuff that might be left (newlines etc non-tag data - will stop on first tag)
case ER:
{
CharSequence seq = buffer.subSequence(0, buffer.remaining());
Matcher findFirst = firstPattern.matcher(seq);
if(!findFirst.find())
buffer.position(buffer.position() + buffer.remaining());
}
return;
default:
unknownTags.add(t2(type, contents));
break;
}
}
}
catch(BufferUnderflowException e)
{
throw new IllegalArgumentException("Unable to find terminating tag (ER).");
}
}
private Pattern ElsevierDOI = Pattern.compile("s(\\d{4}-\\d{4})\\((\\d{2})\\)\\d{5}-\\d");
private void importDOI(DOI doi)
{
this.doi = doi;
Matcher matcher;
switch(doi.PublisherID)
{
case 1016: case 1107:
matcher = ElsevierDOI.matcher(doi.Suffix);
if(matcher.matches())
{
serial = matcher.group(1); // ISSN
if(dateTag == null) dateTag = new Date(null, null, null, null);
if(dateTag.Year == null)
{
int year = Integer.decode(matcher.group(2));
if(year > 90)
year += 1900;
else
year += 2000;
dateTag.Year = year;
}
}
break;
default:
break;
}
}
private Pattern DOIPattern = Pattern.compile("(?:doi:)?(\\d\\d).(\\d\\d\\d\\d)/(.+)");
private boolean tryInterpret(String data)
{
Matcher matcher;
matcher = DOIPattern.matcher(data);
if(matcher.matches())
{
importDOI(new DOI(Integer.valueOf(matcher.group(1)), Integer.valueOf(matcher.group(2)), matcher.group(3)));
return true;
}
return false;
}
private String ignoreCRLF(CharBuffer buffer)
{
String ret = "";
try
{
char next = buffer.get();
if(next == '\r' || next == '\n')
{
ret = null;
if(next == '\r')
{
next = buffer.get();
if(next != '\n')
{
buffer.position(buffer.position() - 1);
}
}
}
else
{
buffer.position(buffer.position() - 1);
}
}
catch(BufferUnderflowException e)
{
}
return ret;
}
private String readString(CharBuffer buffer)
{
StringBuilder bldr = new StringBuilder();
try
{
try
{
int pos = buffer.position();
readTag(buffer);
buffer.position(pos);
return "";
}
catch(IllegalArgumentException e)
{
}
for(;;)
{
char next = buffer.get();
if(next == '\r' || next == '\n') // newline?
{
if(next == '\r') // win / mac, else posix
{
next = buffer.get();
if(next != '\n') // mac, else win
{
buffer.position(buffer.position() - 1);
}
}
try
{
// if the next line starts with a tag, we're done
int pos = buffer.position();
readTag(buffer);
buffer.position(pos);
return bldr.toString();
}
catch(IllegalArgumentException e)
{
// otherwise continue, replacing newline with space
bldr.append(' ');
}
}
else
{
bldr.append(next);
}
}
}
catch(BufferUnderflowException e)
{
return bldr.toString();
}
}
private Types readTag(CharBuffer buffer) throws IllegalArgumentException, BufferUnderflowException
{
while(ignoreCRLF(buffer) == null);
char[] readBuf = new char[6];
readBuf[0] = buffer.get();
readBuf[1] = buffer.get();
readBuf[2] = buffer.get();
readBuf[3] = buffer.get();
readBuf[4] = buffer.get();
String str = String.valueOf(readBuf, 0, 5);
if(str.equals("ER -"))
{
try
{
readBuf[5] = buffer.get();
if(readBuf[5] != ' ')
buffer.position(buffer.position() - 1);
}
catch(BufferUnderflowException e) { }
return Types.ER;
}
readBuf[5] = buffer.get();
if(!" - ".equals(String.valueOf(readBuf, 2, 4)))
{
buffer.position(buffer.position() - 6); // rewind to before read
throw new IllegalArgumentException("Invalid format: " + String.valueOf(readBuf) + " (expected \"TY - \"");
}
return Types.valueOf(String.valueOf(readBuf, 0, 2));
}
public static class Date
{
public Integer Year;
public Integer Month;
public Integer Day;
public String Info;
public Date(Integer year, Integer month, Integer day, String info)
{
Year = year;
Month = month;
Day = day;
Info = info;
}
}
public static class JournalInfo
{
public String Issue;
public Integer StartPage, EndPage;
public JournalInfo(String issue, Integer startPage, Integer endPage)
{
Issue = issue;
StartPage = startPage;
EndPage = endPage;
}
}
public static enum ReprintType
{
ON_REQUEST,
NOT_IN_FILE,
IN_FILE,
}
public static enum ReferenceType
{
ABST,
ADVS,
ART,
BILL,
BOOK,
CASE,
CHAP,
CHAPTER,
COMP,
CONF,
CTLG,
DATA,
ELEC,
GEN,
HEAR,
ICOMM,
INPR,
JFULL,
JOUR,
MAP,
MGZN,
MPCT,
MUSIC,
NEWS,
PAMP,
PAT,
PCOMM,
RPRT,
SER,
SLIDE,
SOUND,
STAT,
THES,
UNBILL,
UNPB,
VIDEO,
}
public static enum Types
{
// Title and Reference Type Tags
TY,
ER,
ID,
T1,
TI,
CT,
BT,
T2,
T3,
// Authors
A1,
AU,
A2,
ED,
A3,
// Year and Free Text Fields
Y1,
PY,
Y2,
N1,
AB,
N2,
// Keywords and Reprint Status
KW,
RP,
// Periodical Tags
JF,
JO,
JA,
J1,
J2,
// Periodical and Publisher Tags
VL,
IS,
CP,
SP,
EP,
CY,
PB,
SN,
AD,
// Misc. Tags
AV,
M1,
M2,
M3,
U1,
U2,
U3,
U4,
U5,
UR,
L1,
L2,
L3,
L4,
INVALID,
}
} | 24,412 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
RISExtractor.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/ris/RISExtractor.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* RISExtractor.java
*
* Created on March 3, 2008, 1:45 PM
*/
package org.wandora.application.tools.extractors.ris;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.ArrayList;
import org.wandora.application.Wandora;
import org.wandora.application.gui.WandoraOptionPane;
import org.wandora.application.tools.extractors.AbstractExtractor;
import org.wandora.application.tools.extractors.ris.RISReference.Date;
import org.wandora.application.tools.extractors.ris.RISReference.ReferenceType;
import org.wandora.application.tools.extractors.ris.RISReference.Types;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.TMBox;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.topicmap.XTMPSI;
import org.wandora.utils.IObox;
import org.wandora.utils.Tuples.T2;
/**
*
* @author anttirt
*/
public class RISExtractor extends AbstractExtractor {
private static final long serialVersionUID = 1L;
@Override
public String getName()
{
return "RIS bibliography extractor";
}
@Override
public String getDescription()
{
return "Extracts data from RIS bibliography format files";
}
@Override
public Topic createTopic(TopicMap topicMap, String baseString) throws TopicMapException {
return createTopic(topicMap, baseString, "", baseString, new Topic[] { });
}
@Override
public Topic createTopic(TopicMap topicMap, String siString, String baseString) throws TopicMapException {
return createTopic(topicMap, siString, "", baseString, new Topic[] { });
}
@Override
public Topic createTopic(TopicMap topicMap, String siString, String baseString, Topic type) throws TopicMapException {
return createTopic(topicMap, siString, "", baseString, new Topic[] { type });
}
@Override
public Topic createTopic(TopicMap topicMap, String baseString, Topic type) throws TopicMapException {
return createTopic(topicMap, baseString, "", baseString, new Topic[] { type });
}
@Override
public Topic createTopic(TopicMap topicMap, String siString, String baseNameString, String baseString) throws TopicMapException {
return createTopic(topicMap, siString, baseNameString, baseString, new Topic[] { });
}
@Override
public Topic createTopic(TopicMap topicMap, String siString, String baseNameString, String baseString, Topic type) throws TopicMapException {
return createTopic(topicMap, siString, baseNameString, baseString, new Topic[] { type });
}
@Override
public Topic createTopic(TopicMap topicMap, String siString, String baseNameString, String baseString, Topic[] types) throws TopicMapException {
if(baseString != null && baseString.length() > 0) {
Locator si = buildSI(siString);
Topic t = topicMap.getTopic(si);
if(t == null) {
t = topicMap.getTopicWithBaseName(baseString + baseNameString);
if(t == null) {
t = topicMap.createTopic();
t.setBaseName(baseString + baseNameString);
}
t.addSubjectIdentifier(si);
}
//setDisplayName(t, "fi", baseString);
setDisplayName(t, "en", baseString);
for(int i=0; i<types.length; i++) {
Topic typeTopic = types[i];
if(typeTopic != null) {
t.addType(typeTopic);
}
}
return t;
}
System.out.println("Failed to create topic!");
return null;
}
@Override
public boolean useTempTopicMap()
{
return true;
}
private void makeSubClass(TopicMap map, Topic subClass, Topic superClass)
{
try
{
Topic supersubClassTopic = null;
Topic subClassTopic = null;
Topic superClassTopic = null;
Locator l = new Locator(XTMPSI.SUPERCLASS_SUBCLASS);
if((supersubClassTopic = map.getTopic(l)) == null)
{
supersubClassTopic = map.createTopic();
supersubClassTopic.addSubjectIdentifier(l);
}
l = new Locator(XTMPSI.SUBCLASS);
if((subClassTopic = map.getTopic(l)) == null)
{
subClassTopic = map.createTopic();
subClassTopic.addSubjectIdentifier(l);
}
l = new Locator(XTMPSI.SUPERCLASS);
if((superClassTopic = map.getTopic(l)) == null)
{
superClassTopic = map.createTopic();
superClassTopic.addSubjectIdentifier(l);
}
Association as = map.createAssociation(supersubClassTopic);
as.addPlayer(subClass, subClassTopic);
as.addPlayer(superClass, superClassTopic);
}
catch(TopicMapException e)
{
log(e);
}
}
@Override
public boolean isConfigurable()
{
return true;
}
private String mEncoding = "UTF-8";
@Override
public void configure(Wandora admin,org.wandora.utils.Options options,String prefix) throws TopicMapException
{
mEncoding = WandoraOptionPane.showInputDialog(admin, "Please enter default encoding", "UTF-8", "Select encoding");
}
private String url(String str)
{
try
{
return URLEncoder.encode(str, "UTF-8");
}
catch(Exception e)
{
return "";
}
}
private boolean extract(CharBuffer cb, TopicMap map)
{
log("Starting RIS extract");
boolean gotsome = false;
try
{
Topic wandoraClass = map.createTopic();
wandoraClass.addSubjectIdentifier(new Locator(TMBox.WANDORACLASS_SI));
wandoraClass.setBaseName("Wandora class");
Topic RISClass = map.createTopic();
RISClass.addSubjectIdentifier(new Locator("http://wandora.org/si/ris/"));
RISClass.setBaseName("RIS");
RISClass.addType(wandoraClass);
/**
* Central player
*/
Topic tyTitle = createTopic(map, "title", RISClass);
Topic tyBook = createTopic(map, "book", RISClass);
/**
* Key players
*/
Topic tyAuthor = createTopic(map, "author", RISClass);
Topic tyKeyword = createTopic(map, "keyword", RISClass);
Topic tyPage = createTopic(map, "page", RISClass);
Topic tyPeriodical = createTopic(map, "periodical", RISClass);
Topic tySeries = createTopic(map, "series", RISClass);
Topic tyDate = createTopic(map, "date", RISClass);
Topic tySerial = createTopic(map, "isbn/issn", RISClass);
Topic tyCity = createTopic(map, "city", RISClass);
Topic tyPublisher = createTopic(map, "publisher", RISClass);
Topic tyIssue = createTopic(map, "issue", RISClass);
Topic tyProceeding = createTopic(map, "proceeding", RISClass);
Topic tyArticle = createTopic(map, "article", RISClass);
Topic tyReport = createTopic(map, "report", RISClass);
/**
* Presentation context (conference, magazine, hearing, etc)
*/
Topic tyPresentationContext = createTopic(map, "presentationContext", RISClass);
/**
* Contexts with specialized processing
*/
Topic tyJournal = createTopic(map, "journal", RISClass);
makeSubClass(map, tyJournal, tyPresentationContext);
Topic tyMagazine = createTopic(map, "magazine", RISClass);
makeSubClass(map, tyMagazine, tyPresentationContext);
Topic tyConference = createTopic(map, "conference", RISClass);
makeSubClass(map, tyConference, tyPresentationContext);
Topic tyNewspaper = createTopic(map, "newspaper", RISClass);
makeSubClass(map, tyNewspaper, tyPresentationContext);
/**
* Occurrence types
*/
Topic tyAbstract = createTopic(map, "abstract", RISClass);
Topic tyNotes = createTopic(map, "notes", RISClass);
Topic tyWebURL = createTopic(map, "webURL", RISClass);
Topic tyPDFURL = createTopic(map, "PDFURL", RISClass);
Topic tyFullTextURL = createTopic(map, "fullTextURL", RISClass);
Topic tyMiscInfo = createTopic(map, "miscInfo", RISClass);
Topic tyUserInfo = createTopic(map, "userInfo", RISClass);
Topic tyUnknownInfo = createTopic(map, "unknownInfo", RISClass);
Topic tyDOI = createTopic(map, "DOI", RISClass);
/**
* Associations
*/
Topic asKeyword = createTopic(map, "isKeyword", RISClass);
Topic asPrimaryAuthor = createTopic(map, "isPrimaryAuthor", RISClass);
Topic asSecondaryAuthor = createTopic(map, "isSecondaryAuthor", RISClass);
Topic asContains = createTopic(map, "contains", RISClass);
Topic asPublished = createTopic(map, "published", RISClass);
Topic asPublisher = createTopic(map, "publisher", RISClass);
Topic asInSeries = createTopic(map, "inSeries", RISClass);
Topic asPeriodical = createTopic(map, "isPeriodical", RISClass);
/**
* Roles
*/
Topic roStartPage = createTopic(map, "startPage", RISClass);
Topic roEndPage = createTopic(map, "endPage", RISClass);
Topic roPublication = createTopic(map, "publication", RISClass);
/**
* languages
*/
Topic lanT = map.getTopic(XTMPSI.getLang(null));
if(lanT == null)
{
lanT = map.createTopic();
lanT.addSubjectIdentifier(new Locator(XTMPSI.getLang(null)));
lanT.setBaseName("");
}
Topic enLangT = map.getTopic(XTMPSI.getLang("en"));
if(enLangT == null)
{
enLangT = map.createTopic();
enLangT.addSubjectIdentifier(new Locator(XTMPSI.getLang("en")));
enLangT.setBaseName("");
}
while(cb.hasRemaining())
{
RISReference ref = new RISReference(cb, this);
gotsome = true;
log("Extracting " + ref.titleTag);
// Title
Topic titleT;
// Publication info
switch(ref.refType)
{
case JOUR: case MGZN: // the title is an article in a magazine or journal
{
titleT = createTopic(map, url(ref.titleTag), " (article)", ref.titleTag, tyTitle);
String issueStr = ref.periodicalName + " " + (ref.issue == null ? "[unknown issue]" : ref.issue);
Topic issueT = createTopic(map, url(issueStr), " (issue)", issueStr, tyIssue);
Topic periodicalT = ref.refType == ReferenceType.MGZN ?
createTopic(map, url(ref.periodicalName), " (magazine)", ref.periodicalName, tyMagazine) :
createTopic(map, url(ref.periodicalName), " (journal)", ref.periodicalName, tyJournal);
createAssociation(map, asPeriodical, new Topic[] { issueT, periodicalT });
if(ref.startPage != null && ref.endPage != null)
{
Topic spT = createTopic(map, url(ref.startPage), " (page)", ref.startPage, tyPage);
Topic epT = createTopic(map, url(ref.endPage), " (page)", ref.endPage, tyPage);
createAssociation(map, asContains, new Topic[]{ issueT, titleT, spT, epT }, new Topic[]{ roPublication, tyTitle, roStartPage, roEndPage });
}
else
{
createAssociation(map, asContains, new Topic[]{ issueT, titleT }, new Topic[]{ roPublication, tyTitle });
}
break;
}
case BOOK: // the title is a book
{
titleT = createTopic(map, url(ref.titleTag), " (book)", ref.titleTag, tyTitle);
titleT.addType(tyBook);
break;
}
case CHAP: case CHAPTER: // the title is a chapter in a book
{
titleT = createTopic(map, url(ref.titleTag), " (chapter)", ref.titleTag, tyTitle);
Topic bookT = createTopic(map, url(ref.periodicalName), " (book)", ref.periodicalName, tyBook);
if(ref.startPage != null && ref.endPage != null)
{
Topic spT = createTopic(map, url(ref.startPage), " (page)", ref.startPage, tyPage);
Topic epT = createTopic(map, url(ref.endPage), " (page)", ref.endPage, tyPage);
createAssociation(map, asContains, new Topic[]{ bookT, titleT, spT, epT }, new Topic[]{ roPublication, tyTitle, roStartPage, roEndPage });
}
else
{
createAssociation(map, asContains, new Topic[]{ bookT, titleT }, new Topic[]{ roPublication, tyTitle });
}
break;
}
case CONF:
{
titleT = createTopic(map, url(ref.titleTag), " (conference proceeding)", ref.titleTag, tyProceeding);
Topic confT = createTopic(map, url(ref.seriesTag), " (conference)", ref.seriesTag, tyConference);
if(ref.startPage != null && ref.endPage != null)
{
Topic spT = createTopic(map, url(ref.startPage), " (page)", ref.startPage, tyPage);
Topic epT = createTopic(map, url(ref.endPage), " (page)", ref.endPage, tyPage);
createAssociation(map, asContains, new Topic[]{ confT, titleT, spT, epT }, new Topic[]{ tyConference, tyProceeding, roStartPage, roEndPage });
}
else
{
createAssociation(map, asContains, new Topic[]{ confT, titleT });
}
break;
}
case NEWS:
{
titleT = createTopic(map, url(ref.titleTag), " (article)", ref.titleTag, tyArticle);
Topic paperT = createTopic(map, url(ref.periodicalName), " (newspaper)", ref.periodicalName, tyNewspaper);
if(ref.startPage != null && ref.endPage != null)
{
Topic spT = createTopic(map, url(ref.startPage), " (page)", ref.startPage, tyPage);
Topic epT = createTopic(map, url(ref.endPage), " (page)", ref.endPage, tyPage);
createAssociation(map, asContains, new Topic[]{ paperT, titleT, spT, epT }, new Topic[]{ roPublication, tyArticle, roStartPage, roEndPage });
}
else
{
createAssociation(map, asContains, new Topic[]{ paperT, titleT });
}
break;
}
case INPR: // "The section "Articles in Press" contains peer reviewed accepted articles to be published in this journal."
{
titleT = createTopic(map, url(ref.titleTag), " (article)", ref.titleTag, tyArticle);
Topic journalT = createTopic(map, url(ref.periodicalName), " (journal)", ref.periodicalName, tyJournal);
createAssociation(map, asContains, new Topic[]{ journalT, titleT });
break;
}
case RPRT:
{
titleT = createTopic(map, url(ref.titleTag), " (report)", ref.titleTag, tyReport);
Topic contextT = createTopic(map, url(ref.periodicalName), "", ref.periodicalName, tyPresentationContext);
if(ref.startPage != null && ref.endPage != null)
{
Topic spT = createTopic(map, url(ref.startPage), " (page)", ref.startPage, tyPage);
Topic epT = createTopic(map, url(ref.endPage), " (page)", ref.endPage, tyPage);
createAssociation(map, asContains, new Topic[]{ contextT, titleT, spT, epT }, new Topic[]{ roPublication, tyReport, roStartPage, roEndPage });
}
else
{
createAssociation(map, asContains, new Topic[]{ contextT, titleT });
}
break;
}
default:
titleT = createTopic(map, url(ref.titleTag), RISReference.getWart(ref.refType), ref.titleTag, tyTitle);
break;
}
// Publishing info
{
Topic
publisherT = ref.publisher == null ? null : createTopic(map, url(ref.publisher), " (publisher)", ref.publisher, tyPublisher),
cityT = ref.publicationCity == null ? null : createTopic(map, url(ref.publicationCity), " (city)", ref.publicationCity, tyCity),
serialT = ref.serial == null ? null : createTopic(map, url(ref.serial), " (serial)", ref.serial, tySerial),
dateT = null;
if(ref.dateTag != null)
{
String dateStr = getDateString(ref.dateTag);
dateT = createTopic(map, url(dateStr), " (date)", dateStr, tyDate);
}
ArrayList<Topic> players = new ArrayList<Topic>();
if(publisherT != null) players.add(publisherT);
if(cityT != null) players.add(cityT);
if(serialT != null) players.add(serialT);
if(dateT != null) players.add(dateT);
if(players.size() != 0)
{
players.add(titleT);
createAssociation(map, asPublished, players.toArray(new Topic[players.size()]));
}
if(ref.doi != null)
{
final String doiString = ref.doi.toString();
titleT.setData(tyDOI, lanT, doiString);
if(ref.mainURL.size() == 0)
titleT.setData(tyWebURL, lanT, "http://dx.doi.org/" + doiString);
titleT.addSubjectIdentifier(new Locator("http://dx.doi.org/" + doiString));
}
}
// Authors
for(T2<Types, String> author : ref.authorTags)
{
Topic authorT = createTopic(map, url(author.e2), " (author)", author.e2, tyAuthor);
switch(author.e1)
{
case A1: case AU:
createAssociation(map, asPrimaryAuthor, new Topic[] { authorT, titleT });
break;
case A2: case ED: case A3:
createAssociation(map, asSecondaryAuthor, new Topic[] { authorT, titleT });
break;
default:
break;
}
}
// Keywords
for(String keyword : ref.keyWords)
{
Topic keywordT = createTopic(map, url(keyword), " (keyword)", keyword, tyKeyword);
createAssociation(map, asKeyword, new Topic[] { titleT, keywordT });
}
// Notes/abstract
for(T2<Types, String> note : ref.noteTags)
{
switch(note.e1)
{
case N1: case AB:
titleT.setData(tyNotes, enLangT, note.e2);
break;
case N2:
titleT.setData(tyAbstract, enLangT, note.e2);
break;
}
}
// URLs
{
ArrayList<String> urls = new ArrayList<String>();
for(URL url : ref.mainURL) urls.add(url.toString());
if(urls.size() != 0) titleT.setData(tyWebURL, lanT, implode(urls.toArray(new String[urls.size()]), ";"));
urls.clear();
for(URL url : ref.pdfURL) urls.add(url.toString());
if(urls.size() != 0) titleT.setData(tyPDFURL, lanT, implode(urls.toArray(new String[urls.size()]), ";"));
urls.clear();
for(URL url : ref.fullTextURL) urls.add(url.toString());
if(urls.size() != 0) titleT.setData(tyFullTextURL, lanT, implode(urls.toArray(new String[urls.size()]), ";"));
}
// Miscellanea
for(T2<Types, String> userInfo : ref.userTags)
{
Topic userInfoT = createTopic(map, url(userInfo.e1.toString()), " (user info)", userInfo.e1.toString(), tyUserInfo);
titleT.setData(userInfoT, lanT, userInfo.e2);
}
for(T2<Types, String> miscInfo : ref.userTags)
{
Topic miscInfoT = createTopic(map, url(miscInfo.e1.toString()), " (user info)", miscInfo.e1.toString(), tyMiscInfo);
titleT.setData(miscInfoT, lanT, miscInfo.e2);
}
for(T2<Types, String> unknownInfo : ref.userTags)
{
Topic unknownInfoT = createTopic(map, url(unknownInfo.e1.toString()), " (user info)", unknownInfo.e1.toString(), tyUnknownInfo);
titleT.setData(unknownInfoT, lanT, unknownInfo.e2);
}
}
}
catch(TopicMapException e)
{
log(e);
}
catch(IllegalArgumentException e)
{
log(e);
}
return gotsome;
}
@Override
public boolean _extractTopicsFrom(File f, TopicMap map) throws Exception {
CharBuffer cb = null;
{
FileInputStream fis = null;
MappedByteBuffer mbb = null;
Charset cs = Charset.forName(mEncoding);
CharsetDecoder decoder = cs.newDecoder();
try
{
fis = new FileInputStream(f);
FileChannel fc = fis.getChannel();
int fs = (int)fc.size();
mbb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fs);
cb = decoder.decode(mbb);
}
catch(FileNotFoundException e) { log(e); return false; }
catch(CharacterCodingException e) { log(e); return false; }
catch(IOException e) { log(e); return false; }
}
return extract(cb, map);
}
public final String[] risContentTypes = { "text/html", "text/plain", "application/x-Research-Info-Systems", "application/xhtml+xml" };
@Override
public String[] getContentTypes()
{
return risContentTypes;
}
private String implode(String[] vals, String sep)
{
StringBuilder bldr = new StringBuilder();
for(int i = 0; i < vals.length - 1; ++i)
{
bldr.append(vals[i]);
bldr.append(sep);
}
bldr.append(vals[vals.length - 1]);
return bldr.toString();
}
@Override
public boolean _extractTopicsFrom(URL u, TopicMap t) throws Exception {
CharBuffer cb = null;
String s = IObox.doUrl(u);
cb = CharBuffer.wrap(s);
return extract(cb, t);
}
public boolean _extractTopicsFrom(String str, TopicMap topicMap) throws Exception {
return extract(CharBuffer.wrap(str), topicMap);
}
public static void main(String[] args) throws Exception {
Charset cs = Charset.forName("UTF-8");
CharsetDecoder decoder = cs.newDecoder();
FileInputStream fis = new FileInputStream("C:\\test.ris");
FileChannel fc = fis.getChannel();
int fs = (int)fc.size();
MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fs);
CharBuffer cb = decoder.decode(mbb);
try
{
for(;;)
{
RISReference ref = new RISReference(cb, null);
String refName = ref.titleTag;
String bar = refName + ".";
}
}
catch(IllegalArgumentException e)
{
System.out.println("foobar");
}
}
/**
* ISO 8601
* @param date
* @return
*/
protected String getDateString(final Date date) {
String dateString = date.Year == null ? "0" : String.valueOf(date.Year);
if (date.Month != null) {
dateString += "-" + String.valueOf(date.Month);
if (date.Day != null) {
dateString += "-" + String.valueOf(date.Day);
}
}
return dateString;
}
}
| 28,194 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
RekognitionSceneDetector.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/rekognition/RekognitionSceneDetector.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.extractors.rekognition;
import java.net.URL;
import java.util.HashMap;
import javax.swing.Icon;
import org.json.JSONException;
import org.json.JSONObject;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraToolLogger;
import org.wandora.application.gui.UIBox;
import org.wandora.application.tools.extractors.rekognition.RekognitionConfiguration.AUTH_KEY;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
/**
*
* @author Eero Lehtonen
*/
public class RekognitionSceneDetector extends AbstractRekognitionExtractor{
private static final long serialVersionUID = 1L;
@Override
public int getExtractorType() {
return URL_EXTRACTOR | RAW_EXTRACTOR;
}
private static final String[] contentTypes=new String[] {
"text/plain", "text/json", "application/json"
};
@Override
public String[] getContentTypes() {
return contentTypes;
}
@Override
public boolean useURLCrawler() {
return false;
}
@Override
public String getName() {
return "ReKognition scene detector";
}
@Override
public String getDescription() {
return "Detects a scene out of given image using ReKognition API. "
+ "Creates topics and associations out of ReKognition scene "
+ "detection. Read more about ReKognition at http://rekognition.com/";
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/extract_rekognition.png");
}
@Override
public boolean isConfigurable(){
return true;
}
@Override
public void configure(Wandora wandora, org.wandora.utils.Options options, String prefix) throws TopicMapException {
RekognitionConfigurationUI configurationUI = new RekognitionConfigurationUI(null);
configurationUI.open(wandora,100);
configurationUI.setVisible(true);
}
@Override
protected HashMap<String,ValueHandler> createHandlerMap(){
HashMap<String,ValueHandler> handlerMap = new HashMap<>();
handlerMap.put("matches", new MatchHandler(SI_ROOT + "scene_match", "Scene Match"));
return handlerMap;
}
/**
* Parse the URL as a string and pass it to _extractTopicsFrom(String ...)
* @param u the image URL to extract
* @param tm the current TopicMap
* @return whether the extraction was a success.
* @throws Exception propagated from _extracTopicsFrom(String ...)
*/
@Override
public boolean _extractTopicsFrom(URL u, TopicMap tm) throws Exception {
String currentURL = u.toExternalForm();
return _extractTopicsFrom(currentURL, tm);
}
/**
*
* The method used for actual extraction.
*
* @param imageUrl the image URL for extraction
* @param tm the current TopicMap
* @return true if the extraction was successful, false otherwise
* @throws Exception if the supplied URL is invalid or Topic Map
* manipulation fails
*/
@Override
public boolean _extractTopicsFrom(String imageUrl, TopicMap tm) throws Exception {
WandoraToolLogger logger = getCurrentLogger();
if(imageUrl == null)
throw new Exception("No valid Image URL found.");
/**
* Fetch the configuration.
*/
RekognitionConfiguration conf = getConfiguration();
/**
* Prompt for authentication if we're still lacking it. Return if we still
* didn't get it
*/
if(!conf.hasAuth()){
if(!conf.askForAuth()) return false;
}
String extractUrl = API_ROOT +
"?api_key=" + conf.auth.get(AUTH_KEY.KEY) +
"&api_secret=" + conf.auth.get(AUTH_KEY.SECRET) +
"&jobs=scene_understanding_3"+
"&urls=" + imageUrl;
logger.log("GETting \"" + extractUrl + "\"");
HttpResponse<JsonNode> resp = Unirest.get(extractUrl).asJson();
JSONObject respNode = resp.getBody().getObject();
HashMap<String,ValueHandler> handlerMap = createHandlerMap();
try {
logUsage(respNode);
String imageURL = respNode.getString("url");
Topic imageTopic = getImageTopic(tm, imageURL);
JSONObject detectionJSON = respNode.getJSONObject("scene_understanding");
Topic detectionTopic = getDetectionTopic(tm);
associateImageWithDetection(tm, imageTopic, detectionTopic);
for(String featureKey : handlerMap.keySet()) {
if (detectionJSON.has(featureKey)) {
Object feature = detectionJSON.get(featureKey);
handlerMap.get(featureKey).handleValue(tm, detectionTopic, feature);
}
}
}
catch (JSONException e) {
logger.log("Failed to parse response. (" + e.getMessage() + ")");
return false;
}
return true;
}
private void logUsage(JSONObject respNode) throws JSONException{
JSONObject usage = respNode.getJSONObject("usage");
log("Response status: " + usage.getString("status"));
log("Quota status: " + Integer.toString(usage.getInt("quota")));
}
}
| 6,487 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
RekognitionConfigurationUI.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/rekognition/RekognitionConfigurationUI.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.extractors.rekognition;
import java.awt.Component;
import java.util.ArrayList;
import java.util.HashMap;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import org.wandora.application.Wandora;
import org.wandora.application.gui.UIBox;
import org.wandora.application.gui.UIConstants;
import org.wandora.application.gui.simple.SimpleButton;
import org.wandora.application.gui.simple.SimpleCheckBox;
import org.wandora.application.gui.simple.SimpleLabel;
import org.wandora.application.gui.simple.SimpleTabbedPane;
import org.wandora.application.tools.extractors.rekognition.RekognitionConfiguration.AUTH_KEY;
/**
*
* @author Eero Lehtonen
*/
class RekognitionConfigurationUI extends javax.swing.JPanel {
private static final long serialVersionUID = 1L;
private Wandora wandora = null;
private JDialog dialog = null;
private RekognitionConfiguration configuration;
private final HashMap<String,JCheckBox> faceJobs;
/**
* Constructs a configuration UI, with the active tab identified by tab. A
* null value hides the tab pane.
* @param tab
*/
public RekognitionConfigurationUI(String tab){
initComponents();
if(tab == null){
rekognitionTabs.setVisible(false);
} else {
switch(tab){
case "face":
rekognitionTabs.setSelectedComponent(faceDetectorTab);
}
}
faceCelebrityTresholdLabel.setFont(UIConstants.buttonLabelFont);
//Hook up checkboxes
faceJobs = new HashMap<>();
faceJobs.put("age", faceJobCheckAge);
faceJobs.put("aggressive", faceJobCheckAggressive);
faceJobs.put("beauty", faceJobCheckBeauty);
faceJobs.put("emotion", faceJobCheckEmotion);
faceJobs.put("eye_closed", faceJobCheckEyeClosed);
faceJobs.put("gender", faceJobCheckGender);
faceJobs.put("glass", faceJobCheckGlass);
faceJobs.put("mouth_open_wide",faceJobCheckMouthOpenWide);
faceJobs.put("part", faceJobCheckPart);
faceJobs.put("part_detail", faceJobCheckPartDetail);
faceJobs.put("race", faceJobCheckRace);
faceJobs.put("celebrity", faceJobCheckCelebrity);
configuration = AbstractRekognitionExtractor.getConfiguration();
if(configuration.auth == null){
this.forgetButton.setEnabled(false);
}
for(String key: faceJobs.keySet()){
if(configuration.jobs.contains(key))
faceJobs.get(key).setSelected(true);
else
faceJobs.get(key).setSelected(false);
}
faceAssociateCelebrity.setSelected(configuration.celebrityNaming);
faceCelebrityTreshold.setValue(Double.valueOf(configuration.celebrityTreshold));
}
public void open(Wandora w, int height){
wandora = w;
dialog = new JDialog(w, true);
dialog.setSize(400, height);
dialog.add(this);
dialog.setTitle("ReKognition API extractor configuration");
UIBox.centerWindow(dialog, w);
faceCelebrityDetails.setVisible(faceJobCheckCelebrity.isSelected());
dialog.setVisible(true);
}
private void writeConfiguration(){
RekognitionConfiguration c = null;
HashMap<AUTH_KEY,String> auth = (configuration.auth == null) ?
this.getAPIKeys() : configuration.auth;
Component selectedTab = rekognitionTabs.getSelectedComponent();
if (selectedTab.equals(faceDetectorTab)){
ArrayList<String> jobs = this.getFaceJobs();
boolean celebrityNaming;
double celebrityTreshold;
try {
celebrityNaming = faceAssociateCelebrity.isSelected();
celebrityTreshold = ((Number)faceCelebrityTreshold.getValue()).floatValue();
} catch (NumberFormatException e) {
celebrityNaming = false;
celebrityTreshold = 0;
}
c = new RekognitionConfiguration(jobs, celebrityNaming, celebrityTreshold, auth);
}
AbstractRekognitionExtractor.setConfiguration(c);
}
private ArrayList<String> getFaceJobs() {
ArrayList<String> jobs = new ArrayList<>();
for (String jobName : faceJobs.keySet()) {
if (faceJobs.get(jobName).isSelected()) {
jobs.add(jobName);
}
}
return jobs;
}
private HashMap<AUTH_KEY,String> getAPIKeys() {
RekognitionAuthenticationDialog authDialog = new RekognitionAuthenticationDialog();
authDialog.open(wandora);
forgetButton.setEnabled(true);
return authDialog.getAuth();
}
public void forgetAuthorization() {
configuration.auth = null;
AbstractRekognitionExtractor.setConfiguration(configuration);
forgetButton.setEnabled(false);
}
void hideTabs() {
rekognitionTabs.setVisible(false);
dialog.setSize(400, 100);
}
/**
* 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;
rekognitionTabs = new SimpleTabbedPane();
faceDetectorTab = new javax.swing.JPanel();
faceDetectorJobsPanel = new javax.swing.JPanel();
faceJobCheckAggressive = new SimpleCheckBox();
faceJobCheckPart = new SimpleCheckBox();
faceJobCheckPartDetail = new SimpleCheckBox();
faceJobCheckGender = new SimpleCheckBox();
faceJobCheckEmotion = new SimpleCheckBox();
faceJobCheckRace = new SimpleCheckBox();
faceJobCheckAge = new SimpleCheckBox();
faceJobCheckGlass = new SimpleCheckBox();
faceJobCheckMouthOpenWide = new SimpleCheckBox();
faceJobCheckEyeClosed = new SimpleCheckBox();
faceJobCheckBeauty = new SimpleCheckBox();
faceJobCheckCelebrity = new SimpleCheckBox();
faceCelebrityDetails = new javax.swing.JPanel();
faceAssociateCelebrity = new SimpleCheckBox();
faceCelebrityTreshold = new javax.swing.JFormattedTextField();
faceCelebrityTresholdLabel = new SimpleLabel();
buttonPanel = new javax.swing.JPanel();
buttonFillerPanel = new javax.swing.JPanel();
okButton = new SimpleButton();
cancelButton = new SimpleButton();
forgetButton = new SimpleButton();
setLayout(new java.awt.GridBagLayout());
faceDetectorTab.setLayout(new java.awt.GridBagLayout());
faceDetectorJobsPanel.setLayout(new java.awt.GridBagLayout());
faceJobCheckAggressive.setText("Aggressive");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
faceDetectorJobsPanel.add(faceJobCheckAggressive, gridBagConstraints);
faceJobCheckPart.setText("Part Positions");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
faceDetectorJobsPanel.add(faceJobCheckPart, gridBagConstraints);
faceJobCheckPartDetail.setText("Part Details");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
faceDetectorJobsPanel.add(faceJobCheckPartDetail, gridBagConstraints);
faceJobCheckGender.setText("Gender");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
faceDetectorJobsPanel.add(faceJobCheckGender, gridBagConstraints);
faceJobCheckEmotion.setSelected(true);
faceJobCheckEmotion.setText("Emotion");
faceJobCheckEmotion.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
faceJobCheckEmotionActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
faceDetectorJobsPanel.add(faceJobCheckEmotion, gridBagConstraints);
faceJobCheckRace.setText("Race");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
faceDetectorJobsPanel.add(faceJobCheckRace, gridBagConstraints);
faceJobCheckAge.setText("Age");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
faceDetectorJobsPanel.add(faceJobCheckAge, gridBagConstraints);
faceJobCheckGlass.setText("Glasses");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
faceDetectorJobsPanel.add(faceJobCheckGlass, gridBagConstraints);
faceJobCheckMouthOpenWide.setText("Mouth Open");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
faceDetectorJobsPanel.add(faceJobCheckMouthOpenWide, gridBagConstraints);
faceJobCheckEyeClosed.setText("Eyes Closed");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
faceDetectorJobsPanel.add(faceJobCheckEyeClosed, gridBagConstraints);
faceJobCheckBeauty.setText("Beauty");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
faceDetectorJobsPanel.add(faceJobCheckBeauty, gridBagConstraints);
faceJobCheckCelebrity.setSelected(true);
faceJobCheckCelebrity.setText("Celebrity");
faceJobCheckCelebrity.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
faceJobCheckCelebrityActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
faceDetectorJobsPanel.add(faceJobCheckCelebrity, gridBagConstraints);
faceCelebrityDetails.setLayout(new java.awt.GridBagLayout());
faceAssociateCelebrity.setSelected(true);
faceAssociateCelebrity.setText("Attempt Celebrity Naming");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
faceCelebrityDetails.add(faceAssociateCelebrity, gridBagConstraints);
faceCelebrityTreshold.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0.00"))));
faceCelebrityTreshold.setText("0.50");
faceCelebrityTreshold.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
faceCelebrityTresholdActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 0.1;
faceCelebrityDetails.add(faceCelebrityTreshold, gridBagConstraints);
faceCelebrityTresholdLabel.setText("Treshold");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
gridBagConstraints.weightx = 0.1;
gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 3);
faceCelebrityDetails.add(faceCelebrityTresholdLabel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new java.awt.Insets(0, 24, 0, 0);
faceDetectorJobsPanel.add(faceCelebrityDetails, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
faceDetectorTab.add(faceDetectorJobsPanel, gridBagConstraints);
rekognitionTabs.addTab("Face Detector", faceDetectorTab);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 0.1;
gridBagConstraints.weighty = 0.1;
add(rekognitionTabs, 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("Save");
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, 2);
buttonPanel.add(okButton, gridBagConstraints);
cancelButton.setText("Cancel");
cancelButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelButtonActionPerformed(evt);
}
});
buttonPanel.add(cancelButton, new java.awt.GridBagConstraints());
forgetButton.setText("Forget API credentials");
forgetButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
forgetButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
gridBagConstraints.weightx = 0.1;
buttonPanel.add(forgetButton, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.1;
gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2);
add(buttonPanel, gridBagConstraints);
}// </editor-fold>//GEN-END:initComponents
private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
if (this.dialog != null) {
this.dialog.setVisible(false);
}
}//GEN-LAST:event_cancelButtonActionPerformed
private void forgetButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_forgetButtonActionPerformed
forgetAuthorization();
forgetButton.setEnabled(false);
}//GEN-LAST:event_forgetButtonActionPerformed
private void faceJobCheckCelebrityActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_faceJobCheckCelebrityActionPerformed
boolean b = faceJobCheckCelebrity.isSelected();
faceCelebrityDetails.setVisible(b);
if(!b){
faceAssociateCelebrity.setSelected(false);
}
}//GEN-LAST:event_faceJobCheckCelebrityActionPerformed
private void faceCelebrityTresholdActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_faceCelebrityTresholdActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_faceCelebrityTresholdActionPerformed
private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
this.writeConfiguration();
if (this.dialog != null) {
this.dialog.setVisible(false);
}
}//GEN-LAST:event_okButtonActionPerformed
private void faceJobCheckEmotionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_faceJobCheckEmotionActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_faceJobCheckEmotionActionPerformed
// 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.JCheckBox faceAssociateCelebrity;
private javax.swing.JPanel faceCelebrityDetails;
private javax.swing.JFormattedTextField faceCelebrityTreshold;
private javax.swing.JLabel faceCelebrityTresholdLabel;
private javax.swing.JPanel faceDetectorJobsPanel;
private javax.swing.JPanel faceDetectorTab;
private javax.swing.JCheckBox faceJobCheckAge;
private javax.swing.JCheckBox faceJobCheckAggressive;
private javax.swing.JCheckBox faceJobCheckBeauty;
private javax.swing.JCheckBox faceJobCheckCelebrity;
private javax.swing.JCheckBox faceJobCheckEmotion;
private javax.swing.JCheckBox faceJobCheckEyeClosed;
private javax.swing.JCheckBox faceJobCheckGender;
private javax.swing.JCheckBox faceJobCheckGlass;
private javax.swing.JCheckBox faceJobCheckMouthOpenWide;
private javax.swing.JCheckBox faceJobCheckPart;
private javax.swing.JCheckBox faceJobCheckPartDetail;
private javax.swing.JCheckBox faceJobCheckRace;
private javax.swing.JButton forgetButton;
private javax.swing.JButton okButton;
private javax.swing.JTabbedPane rekognitionTabs;
// End of variables declaration//GEN-END:variables
}
| 20,216 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
RekognitionConfiguration.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/rekognition/RekognitionConfiguration.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.extractors.rekognition;
import java.util.ArrayList;
import java.util.HashMap;
import org.wandora.application.Wandora;
/**
*
* @author Eero Lehtonen
*/
class RekognitionConfiguration {
protected static enum AUTH_KEY{
KEY,
SECRET
};
protected ArrayList<String> jobs;
protected double celebrityTreshold;
protected boolean celebrityNaming;
protected HashMap<AUTH_KEY,String> auth;
protected RekognitionConfiguration(ArrayList<String> jobs, boolean naming,
double treshold, HashMap<AUTH_KEY,String> auth){
this.jobs = jobs;
this.celebrityNaming = naming;
this.celebrityTreshold = treshold;
this.auth = auth;
}
//Defaults
protected RekognitionConfiguration(){
this.jobs = new ArrayList<>();
jobs.add("celebrity");
jobs.add("emotion");
this.celebrityNaming = false;
this.celebrityTreshold = 0;
this.auth = null;
}
protected boolean hasAuth(){
return this.auth != null;
}
/**
* Prompt for credentials if we don't have any
*/
protected boolean askForAuth(){
RekognitionAuthenticationDialog d = new RekognitionAuthenticationDialog();
d.open(Wandora.getWandora());
if(d.wasAccepted()){
this.auth = d.getAuth();
return true;
}
return false;
}
}
| 2,283 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
RekognitionAuthenticationDialog.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/rekognition/RekognitionAuthenticationDialog.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.extractors.rekognition;
import java.util.HashMap;
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.SimpleField;
import org.wandora.application.gui.simple.SimpleLabel;
import org.wandora.application.tools.extractors.rekognition.RekognitionConfiguration.AUTH_KEY;
/**
*
* @author Eero Lehtonen
*/
public class RekognitionAuthenticationDialog extends javax.swing.JPanel {
private static final long serialVersionUID = 1L;
private JDialog dialog;
private HashMap<AUTH_KEY,String> auth;
private boolean wasAccepted = false;
/**
* Creates new form RekognitionAuthenticationDialog
*/
public RekognitionAuthenticationDialog() {
initComponents();
}
public void open(Wandora w){
dialog = new JDialog(w, true);
dialog.setSize(400, 180);
dialog.setResizable(false);
dialog.add(this);
dialog.setTitle("Rekognition API key and secret");
UIBox.centerWindow(dialog, w);
wasAccepted = false;
dialog.setVisible(true);
}
//Populate auth params and hide dialog on submit
private void submit() {
wasAccepted = true;
this.auth = new HashMap<>();
this.auth.put(AUTH_KEY.KEY,this.keyField.getText());
this.auth.put(AUTH_KEY.SECRET,this.secretField.getText());
this.dialog.setVisible(false);
}
private void cancel() {
wasAccepted = false;
this.dialog.setVisible(false);
}
public boolean wasAccepted() {
return wasAccepted;
}
//Let the main UI get the auth params
protected HashMap<AUTH_KEY,String> getAuth(){
return this.auth;
}
/**
* 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;
keyLabel = new SimpleLabel();
secretLabel = new SimpleLabel();
descriptionLabel = new SimpleLabel();
keyField = new SimpleField();
secretField = new SimpleField();
buttonPanel = new javax.swing.JPanel();
submitButton = new SimpleButton();
cancelButton = new SimpleButton();
setLayout(new java.awt.GridBagLayout());
keyLabel.setText("API key");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 4);
add(keyLabel, gridBagConstraints);
secretLabel.setText("API secret");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 4);
add(secretLabel, gridBagConstraints);
descriptionLabel.setText("<html>Please input the API key and API secret associated with your Rekognition account.</html>");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(8, 4, 8, 4);
add(descriptionLabel, gridBagConstraints);
keyField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
keyFieldActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 0.1;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4);
add(keyField, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 0.1;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4);
add(secretField, gridBagConstraints);
buttonPanel.setLayout(new java.awt.GridBagLayout());
submitButton.setText("Submit");
submitButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
submitButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 4);
buttonPanel.add(submitButton, gridBagConstraints);
cancelButton.setText("Cancel");
cancelButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelButtonActionPerformed(evt);
}
});
buttonPanel.add(cancelButton, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
add(buttonPanel, gridBagConstraints);
}// </editor-fold>//GEN-END:initComponents
private void keyFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_keyFieldActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_keyFieldActionPerformed
private void submitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_submitButtonActionPerformed
this.submit();
}//GEN-LAST:event_submitButtonActionPerformed
private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
this.cancel();
}//GEN-LAST:event_cancelButtonActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel buttonPanel;
private javax.swing.JButton cancelButton;
private javax.swing.JLabel descriptionLabel;
private javax.swing.JTextField keyField;
private javax.swing.JLabel keyLabel;
private javax.swing.JTextField secretField;
private javax.swing.JLabel secretLabel;
private javax.swing.JButton submitButton;
// End of variables declaration//GEN-END:variables
}
| 8,186 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AbstractRekognitionExtractor.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/rekognition/AbstractRekognitionExtractor.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.extractors.rekognition;
import java.io.File;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.UUID;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.wandora.application.tools.extractors.AbstractExtractor;
import org.wandora.application.tools.extractors.ExtractHelper;
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;
/**
*
* @author Eero Lehtonen
*/
abstract class AbstractRekognitionExtractor extends AbstractExtractor {
private static final long serialVersionUID = 1L;
private static boolean MAKE_DISTINCT_CONFIDENCE_TOPICS = false;
protected static final String API_ROOT = "http://rekognition.com/func/api/";
protected enum JSON {KEY, NAME, VALUE, ERROR};
protected static final String FLATTENING_DELIMETER = ".";
//Face detection data is language independent
private static final String LANG_SI = "http://wandora.org/si/core/lang-independent";
protected static final String SI_ROOT = "http://wandora.org/si/rekognition/";
protected static final String IMAGE_SI = SI_ROOT + "image/";
protected static final String DETECTION_SI = SI_ROOT + "detection/";
protected static final String FACE_SI_ROOT = SI_ROOT + "face/";
protected static final String SCENE_SI_ROOT = SI_ROOT + "scene/";
protected static final String FEATURE_SI_ROOT = FACE_SI_ROOT + "feature/";
protected abstract HashMap<String,ValueHandler> createHandlerMap();
// -------------------------------------------------------------------------
private static final String EXTRACT_ERROR =
"This extractor is a frontend for other ReKognition extractors. "
+ "It doesn't perform extraction itself.";
@Override
public boolean _extractTopicsFrom(File f, TopicMap t) throws Exception {
throw new UnsupportedOperationException(EXTRACT_ERROR);
}
@Override
public boolean _extractTopicsFrom(URL u, TopicMap t) throws Exception {
throw new UnsupportedOperationException(EXTRACT_ERROR);
}
@Override
public boolean _extractTopicsFrom(String str, TopicMap t) throws Exception {
throw new UnsupportedOperationException(EXTRACT_ERROR);
}
// -------------------------------------------------------------------------
protected static RekognitionConfiguration conf = new RekognitionConfiguration();
protected static void setConfiguration(RekognitionConfiguration c){
conf = c;
}
protected static RekognitionConfiguration getConfiguration(){
return conf;
}
// -------------------------------------------------------------------------
protected static Topic getImageTopic(TopicMap tm, String url) throws TopicMapException{
Topic image = getOrCreateTopic(tm, url);
Topic imageClass = getImageClass(tm);
image.addType(imageClass);
return image;
}
protected static Topic getDetectionTopic(TopicMap tm) throws TopicMapException {
String id = UUID.randomUUID().toString();
Topic detection = getOrCreateTopic(tm, DETECTION_SI + id);
Topic detectionClass = getDetectionClass(tm);
detection.addType(detectionClass);
return detection;
}
protected static void associateImageWithDetection(TopicMap tm, Topic image, Topic detection) throws TopicMapException {
Topic imageClass = getImageClass(tm);
Topic detectionClass = getDetectionClass(tm);
Association a = tm.createAssociation(detectionClass);
a.addPlayer(image, imageClass);
a.addPlayer(detection, detectionClass);
}
protected static void addFeatureToDetection(TopicMap tm, Topic Detection, String featureType, String featureData) throws TopicMapException{
Topic langTopic = getLangTopic(tm);
Topic featureTypeTopic = getFeatureTypeTopic(tm, featureType);
Detection.setData(featureTypeTopic, langTopic, featureData);
}
protected static Topic getFeatureTypeTopic(TopicMap tm, String featureType) throws TopicMapException {
Topic featureTypeTopic = getOrCreateTopic(tm, FEATURE_SI_ROOT + featureType, featureType);
Topic featureClass = getFeatureClass(tm);
makeSubclassOf(tm, featureTypeTopic, featureClass);
return featureTypeTopic;
}
protected static Topic getImageClass(TopicMap tm) throws TopicMapException {
Topic imageClass = getOrCreateTopic(tm, IMAGE_SI, "Image");
makeSubclassOf(tm, imageClass, getRekognitionClass(tm));
return imageClass;
}
protected static Topic getDetectionClass(TopicMap tm) throws TopicMapException {
Topic detectionClass = getOrCreateTopic(tm, DETECTION_SI, "Rekognition Detection");
makeSubclassOf(tm, detectionClass, getRekognitionClass(tm));
return detectionClass;
}
protected static Topic getFeatureClass(TopicMap tm) throws TopicMapException{
Topic featureClass = getOrCreateTopic(tm, FEATURE_SI_ROOT, "Face Detection Feature");
makeSubclassOf(tm, featureClass, getRekognitionClass(tm));
return featureClass;
}
// ------------------------------------------------------ HELPERS ----------
protected static Topic getRekognitionClass(TopicMap tm) throws TopicMapException {
Topic rekognition = getOrCreateTopic(tm, SI_ROOT, "ReKognition");
makeSubclassOf(tm, rekognition, getWandoraClassTopic(tm));
return rekognition;
}
protected static Topic getWandoraClassTopic(TopicMap tm)
throws TopicMapException {
return getOrCreateTopic(tm, TMBox.WANDORACLASS_SI, "Wandora class");
}
protected static Topic getOrCreateTopic(TopicMap tm, String si)
throws TopicMapException {
return getOrCreateTopic(tm, si, null);
}
protected static Topic getOrCreateTopic(TopicMap tm, String si, String bn)
throws TopicMapException {
return ExtractHelper.getOrCreateTopic(si, bn, tm);
}
protected static void makeSubclassOf(TopicMap tm, Topic t, Topic superclass)
throws TopicMapException {
ExtractHelper.makeSubclassOf(t, superclass, tm);
}
protected static Topic getLangTopic(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, LANG_SI);
}
// -------------------------------------------------------------------------
protected String getBestMatch(JSONObject obj, double treshold) throws JSONException{
JSONArray matches = obj.getJSONArray("matches");
double best = treshold;
String matchedName = null;
for (int i = 0; i < matches.length(); i++) {
JSONObject match = matches.getJSONObject(i);
try {
double score = Double.parseDouble(match.getString("score"));
if(score > best){
String tag = match.getString("tag");
matchedName = tag.replace("_", " ");
best = score;
}
} catch (NumberFormatException | JSONException e) {
}
}
if(matchedName == null) throw new JSONException("Failed to match name");
return matchedName;
}
/**
* A value handler is used to create and associate topics from face detection
* data return as JSON. Implementations use constructors to initialize
* feature types etc. handleValue is used to create the individual feature
* Topics.
*/
interface ValueHandler{
public void handleValue(TopicMap tm, Topic detection, Object value) throws Exception;
}
/**
* AbstractValueHandler implements common functionality for extending
* ValueHandlers.
*/
abstract class AbstractValueHandler{
protected static final String COORDINATE_SI = SI_ROOT + "coordinate/";
protected static final String COORDINATE_NAME = "Coordinate";
protected static final String CONFIDENCE_SI = FEATURE_SI_ROOT + "confidence/";
protected static final String CONFIDENCE_NAME = "Confidence";
protected String TYPE_SI;
protected String TYPE_NAME;
protected Topic getTypeTopic(TopicMap tm) throws TopicMapException{
Topic typeTopic = getOrCreateTopic(tm, TYPE_SI, TYPE_NAME);
return typeTopic;
}
protected Topic getCoordinateTypeTopic(TopicMap tm) throws TopicMapException{
Topic typeTopic = getOrCreateTopic(tm, COORDINATE_SI, COORDINATE_NAME);
return typeTopic;
}
protected Topic getConfidenceTypeTopic(TopicMap tm) throws TopicMapException{
Topic typeTopic = getOrCreateTopic(tm, CONFIDENCE_SI, CONFIDENCE_NAME);
return typeTopic;
}
protected Topic[] getCoordinateTypeTopics(TopicMap tm) throws TopicMapException{
Topic coordinateType = getCoordinateTypeTopic(tm);
Topic x = getOrCreateTopic(tm, COORDINATE_SI + "x", "x");
Topic y = getOrCreateTopic(tm, COORDINATE_SI + "y", "y");
x.addType(coordinateType);
y.addType(coordinateType);
return new Topic[]{x,y};
}
}
/**
* NumericValueHandler creates simple occurrence data representing numeric
* (double) values. siBase and name are used to differentiate numeric values.
* Valid value for handleValue should be able to be casted to integer or double.
*/
class NumericValueHandler extends AbstractValueHandler implements ValueHandler{
NumericValueHandler(String si, String name){
this.TYPE_SI = si;
this.TYPE_NAME = name;
}
@Override
public void handleValue(TopicMap tm, Topic detection, Object value) throws Exception {
Topic typeTopic = this.getTypeTopic(tm);
Topic langTopic = getLangTopic(tm);
detection.setData(typeTopic, langTopic, String.valueOf(value));
}
}
/**
* NumericValuesHandler creates a series of Topics from a JSONObject where
* the keys are used as Topics to be associated with the detection and
* a numeric value describing the confidence of the association. For example
* the JSONObject with a key "emotion"
*
* {
* "happy" : 0.98,
* "surprised" : 0.05,
* "calm" : 0.02
* }
*
* will create three associations with the detection, emotion and respective
* confidence as players.
*/
class NumericValuesHandler extends AbstractValueHandler implements ValueHandler{
NumericValuesHandler(String si, String name){
this.TYPE_SI = si;
this.TYPE_NAME = name;
}
@Override
public void handleValue(TopicMap tm, Topic detection, Object values) throws Exception {
if(!(values instanceof JSONObject)){
throw new IllegalArgumentException("Argument supplied to "
+ "NumericValuesHandler is not a JSONObject.");
}
Topic typeTopic = this.getTypeTopic(tm);
Topic confidenceTypeTopic = getConfidenceTypeTopic(tm);
Topic detectionTypeTopic = getDetectionClass(tm);
JSONObject numericValues = (JSONObject)values;
Iterator keys = numericValues.keys();
while(keys.hasNext()) {
String key = (String)keys.next();
Topic keyTopic = getOrCreateTopic(tm, TYPE_SI + "/" + key, key);
keyTopic.addType(typeTopic);
Object value = numericValues.get(key);
Topic confidenceTopic = null;
if(MAKE_DISTINCT_CONFIDENCE_TOPICS) {
String confidenceID = UUID.randomUUID().toString();
confidenceTopic = getOrCreateTopic(tm, CONFIDENCE_SI + confidenceID);
confidenceTopic.setData(confidenceTypeTopic, getLangTopic(tm), String.valueOf(value));
}
else {
confidenceTopic = getOrCreateTopic(tm, CONFIDENCE_SI + String.valueOf(value));
confidenceTopic.setBaseName(String.valueOf(value));
}
confidenceTopic.addType(confidenceTypeTopic);
Association a = tm.createAssociation(typeTopic);
a.addPlayer(keyTopic, typeTopic);
a.addPlayer(confidenceTopic, confidenceTypeTopic);
a.addPlayer(detection, detectionTypeTopic);
}
}
}
/**
* CoordinateHandler creates a coordinate topic with simple occurrences of
* x and y from a JSONObject looking like:
*
* {
* "x":<double>
* "y":<double>
* }
*/
class CoordinateHandler extends AbstractValueHandler implements ValueHandler{
CoordinateHandler(String si, String name){
this.TYPE_SI = si;
this.TYPE_NAME = name;
}
@Override
public void handleValue(TopicMap tm, Topic detection, Object value) throws Exception {
if(!(value instanceof JSONObject)){
throw new IllegalArgumentException("Argument supplied to "
+ "CoordinateHandler is not a JSONObject.");
}
JSONObject coordinates = (JSONObject)value;
if(!(coordinates.has("x") && coordinates.has("y"))){
throw new IllegalArgumentException("Argument supplied to "
+ "CoordinateHandler doesn't have required keys.");
}
Topic[] coordinateTypes = getCoordinateTypeTopics(tm);
Topic typeTopic = this.getTypeTopic(tm);
Topic langTopic = getLangTopic(tm);
Topic detectionTypeTopic = getDetectionClass(tm);
String coordinatesID = UUID.randomUUID().toString();
Topic coordinatesTopic = getOrCreateTopic(tm, TYPE_SI + coordinatesID);
coordinatesTopic.addType(typeTopic);
coordinatesTopic.setData(coordinateTypes[0], langTopic, String.valueOf(coordinates.get("x")));
coordinatesTopic.setData(coordinateTypes[1], langTopic, String.valueOf(coordinates.get("y")));
Association a = tm.createAssociation(typeTopic);
a.addPlayer(detection, detectionTypeTopic);
a.addPlayer(coordinatesTopic, typeTopic);
}
}
/**
* BoundingBoxHandler creates a Topic structure representing a "boundingbox"
* structure from the response data. The expected response structure is like:
*
* {
* "tl":{
* "x":<double>,
* "y":<double>
* },
* "size":{
* "width":<double>,
* "height":<double>
* }
* }
*
* Here "tl" is interpreted as a coordinate Topic and "size" as a size
* Topic.
*/
class BoundingBoxHandler extends AbstractValueHandler implements ValueHandler{
private static final String SIZE_SI = SI_ROOT + "size/";
private static final String SIZE_NAME = "Size";
private static final String TL_SI = SI_ROOT + "tl/";
private static final String TL_NAME = "Top Left";
private Topic getSizeTypeTopic(TopicMap tm) throws TopicMapException{
Topic typeTopic = getOrCreateTopic(tm, SIZE_SI, SIZE_NAME);
return typeTopic;
}
private Topic getTLTypeTopic(TopicMap tm) throws TopicMapException{
Topic typeTopic = getOrCreateTopic(tm, TL_SI, TL_NAME);
return typeTopic;
}
protected Topic[] getSizeTypeTopics(TopicMap tm) throws TopicMapException{
Topic sizeType = getSizeTypeTopic(tm);
Topic width = getOrCreateTopic(tm, SIZE_SI + "width", "Width");
Topic height = getOrCreateTopic(tm, SIZE_SI + "height", "Height");
width.addType(sizeType);
height.addType(sizeType);
return new Topic[]{width,height};
}
BoundingBoxHandler(String si, String name){
this.TYPE_SI = si;
this.TYPE_NAME = name;
}
private void handleCoordinates(TopicMap tm, Topic boundingBox, JSONObject tl) throws Exception{
Topic[] coordinateTypes = getCoordinateTypeTopics(tm);
Topic typeTopic = this.getCoordinateTypeTopic(tm);
Topic tlTypeTopic = this.getTLTypeTopic(tm);
Topic langTopic = getLangTopic(tm);
Topic boundingboxTypeTopic = this.getTypeTopic(tm);
String coordinatesID = UUID.randomUUID().toString();
Topic coordinatesTopic = getOrCreateTopic(tm, COORDINATE_SI + coordinatesID);
coordinatesTopic.addType(typeTopic);
coordinatesTopic.setData(coordinateTypes[0], langTopic, String.valueOf(tl.get("x")));
coordinatesTopic.setData(coordinateTypes[1], langTopic, String.valueOf(tl.get("y")));
Association a = tm.createAssociation(tlTypeTopic);
a.addPlayer(boundingBox, boundingboxTypeTopic);
a.addPlayer(coordinatesTopic, typeTopic);
}
private void handleSize(TopicMap tm, Topic boundingBox, JSONObject size) throws Exception{
Topic[] sizeTypes = getSizeTypeTopics(tm);
Topic typeTopic = this.getSizeTypeTopic(tm);
Topic langTopic = getLangTopic(tm);
Topic boundingboxTypeTopic = this.getTypeTopic(tm);
String sizeID = UUID.randomUUID().toString();
Topic sizeTopic = getOrCreateTopic(tm, SIZE_SI + sizeID);
sizeTopic.addType(typeTopic);
sizeTopic.setData(sizeTypes[0], langTopic, String.valueOf(size.get("width")));
sizeTopic.setData(sizeTypes[1], langTopic, String.valueOf(size.get("height")));
Association a = tm.createAssociation(typeTopic);
a.addPlayer(boundingBox, boundingboxTypeTopic);
a.addPlayer(sizeTopic, typeTopic);
}
@Override
public void handleValue(TopicMap tm, Topic detection, Object value) throws Exception {
if(!(value instanceof JSONObject)){
throw new IllegalArgumentException("Argument supplied to "
+ "BoundingBoxHandler is not a JSONObject.");
}
JSONObject boundingbox = (JSONObject)value;
if(!(boundingbox.has("tl") && boundingbox.has("size"))){
throw new IllegalArgumentException("Argument supplied to "
+ "BoundingBoxHandler doesn't have required keys.");
}
JSONObject tl = boundingbox.getJSONObject("tl");
JSONObject size = boundingbox.getJSONObject("size");
Topic typeTopic = this.getTypeTopic(tm);
String boundingboxID = UUID.randomUUID().toString();
Topic boundingboxTopic = getOrCreateTopic(tm, TYPE_SI + boundingboxID);
boundingboxTopic.addType(typeTopic);
this.handleCoordinates(tm, boundingboxTopic, tl);
this.handleSize(tm, boundingboxTopic, size);
Association a = tm.createAssociation(typeTopic);
a.addPlayer(boundingboxTopic, typeTopic);
a.addPlayer(detection, getDetectionClass(tm));
}
}
/**
* PoseHandler creates a Topic representing a "pose" structure from the
* response data. The expected response structure is like:
*
* {
* "roll":<double>,
* "pitch":<double>,
* "yaw":<double>
* }
*
*/
class PoseHandler extends AbstractValueHandler implements ValueHandler{
private static final String ROLL_SI = FEATURE_SI_ROOT + "roll/";
private static final String ROLL_NAME = "Roll";
private static final String YAW_SI = FEATURE_SI_ROOT + "yaw/";
private static final String YAW_NAME = "Yaw";
private static final String PITCH_SI = FEATURE_SI_ROOT + "pitch/";
private static final String PITCH_NAME = "Pitch";
private Topic getRollTypeTopic(TopicMap tm) throws TopicMapException{
Topic typeTopic = getOrCreateTopic(tm, ROLL_SI, ROLL_NAME);
return typeTopic;
}
private Topic getYawTypeTopic(TopicMap tm) throws TopicMapException{
Topic typeTopic = getOrCreateTopic(tm, YAW_SI, YAW_NAME);
return typeTopic;
}
private Topic getPitchTypeTopic(TopicMap tm) throws TopicMapException{
Topic typeTopic = getOrCreateTopic(tm, PITCH_SI, PITCH_NAME);
return typeTopic;
}
PoseHandler(String si, String name){
this.TYPE_SI = si;
this.TYPE_NAME = name;
}
@Override
public void handleValue(TopicMap tm, Topic detection, Object value) throws Exception {
if(!(value instanceof JSONObject)){
throw new IllegalArgumentException("Argument supplied to "
+ "PoseHandler is not a JSONObject.");
}
JSONObject pose = (JSONObject)value;
if(!(pose.has("roll") && pose.has("yaw") && pose.has("pitch"))){
throw new IllegalArgumentException("Argument supplied to "
+ "PoseHandler doesn't have required keys.");
}
String poseID = UUID.randomUUID().toString();
Topic typeTopic = this.getTypeTopic(tm);
Topic poseTopic = getOrCreateTopic(tm, TYPE_SI + poseID);
poseTopic.addType(typeTopic);
Topic langTopic = getLangTopic(tm);
poseTopic.setData(getRollTypeTopic(tm), langTopic, String.valueOf(pose.get("roll")));
poseTopic.setData(getYawTypeTopic(tm), langTopic, String.valueOf(pose.get("yaw")));
poseTopic.setData(getPitchTypeTopic(tm), langTopic, String.valueOf(pose.get("pitch")));
Topic detectionTypeTopic = getDetectionClass(tm);
Association a = tm.createAssociation(typeTopic);
a.addPlayer(poseTopic, typeTopic);
a.addPlayer(detection,detectionTypeTopic);
}
}
/**
* MatchHandler creates a Topic representing a celebrity match from the
* response data. The expected response structure is like:
*
* [{
* "tag":<String>,
* "score":<double>
* },...]
*
* Here tag has snake case and is converted to a nicer format.
* Example: "Gwyneth_Paltrow" -> "Gwyneth Paltrow"
*/
protected class MatchHandler extends AbstractValueHandler implements ValueHandler{
MatchHandler(String si, String name){
this.TYPE_SI = si;
this.TYPE_NAME = name;
}
@Override
public void handleValue(TopicMap tm, Topic detection, Object values) throws Exception {
if(!(values instanceof JSONArray)){
throw new IllegalArgumentException("Argument supplied to "
+ "MatchHandler is not a JSONArray.");
}
Topic typeTopic = this.getTypeTopic(tm);
Topic confidenceTypeTopic = getConfidenceTypeTopic(tm);
Topic detectionTypeTopic = getDetectionClass(tm);
JSONArray matches = (JSONArray)values;
for(int i=0;i<matches.length();i++){
JSONObject match = matches.getJSONObject(i);
String matchName = match.getString("tag");
Topic matchTopic = getOrCreateTopic(tm, TYPE_SI + "/" + matchName, matchName.replace("_", " "));
Double confidenceValue = match.getDouble("score");
String confidenceID = UUID.randomUUID().toString();
Topic confidenceTopic = getOrCreateTopic(tm, CONFIDENCE_SI + confidenceID, confidenceValue.toString());
confidenceTopic.setData(confidenceTypeTopic, getLangTopic(tm), String.valueOf(confidenceValue));
confidenceTopic.addType(confidenceTypeTopic);
Association a = tm.createAssociation(typeTopic);
a.addPlayer(matchTopic, typeTopic);
a.addPlayer(confidenceTopic,confidenceTypeTopic);
a.addPlayer(detection,detectionTypeTopic);
}
}
}
}
| 26,289 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
RekognitionFaceDetector.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/rekognition/RekognitionFaceDetector.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.extractors.rekognition;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import javax.swing.Icon;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraToolLogger;
import org.wandora.application.gui.UIBox;
import org.wandora.application.tools.extractors.rekognition.RekognitionConfiguration.AUTH_KEY;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
/**
*
* @author Eero Lehtonen
*/
public class RekognitionFaceDetector extends AbstractRekognitionExtractor{
private static final long serialVersionUID = 1L;
@Override
public int getExtractorType() {
return URL_EXTRACTOR | RAW_EXTRACTOR;
}
private static final String[] contentTypes=new String[] {
"text/plain", "text/json", "application/json"
};
@Override
public String[] getContentTypes() {
return contentTypes;
}
@Override
public boolean useURLCrawler() {
return false;
}
@Override
public String getName() {
return "ReKognition face detector";
}
@Override
public String getDescription() {
return "Detects face out of given image using ReKognition API. "+
"Creates topics and associations out of ReKognition face detection. "+
"Read more about ReKognition at http://rekognition.com/";
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/extract_rekognition.png");
}
@Override
protected HashMap<String,ValueHandler> createHandlerMap() {
HashMap<String,ValueHandler> handlerMap = new HashMap<>();
handlerMap.put("matches", new MatchHandler(SI_ROOT + "celeb_match", "Celebrity Match"));
handlerMap.put("boundingbox", new BoundingBoxHandler(FEATURE_SI_ROOT + "boundingbox/", "Boundingbox"));
handlerMap.put("pose", new PoseHandler(FEATURE_SI_ROOT + "pose/", "Pose"));
handlerMap.put("confidence", new NumericValueHandler(FEATURE_SI_ROOT + "confidence/", "Confidence"));
handlerMap.put("emotion", new NumericValuesHandler(FEATURE_SI_ROOT + "emotion/", "Emotion"));
handlerMap.put("eye_left", new CoordinateHandler(FEATURE_SI_ROOT + "eye_left/", "Left Eye"));
handlerMap.put("eye_right", new CoordinateHandler(FEATURE_SI_ROOT + "eye_right/", "Right Eye"));
handlerMap.put("nose", new CoordinateHandler(FEATURE_SI_ROOT + "nose/", "Nose"));
handlerMap.put("mouth_l", new CoordinateHandler(FEATURE_SI_ROOT + "mouth_left", "Mouth (left)"));
handlerMap.put("mouth_r", new CoordinateHandler(FEATURE_SI_ROOT + "mouth_right", "Mouth (right)"));
handlerMap.put("b_ll", new CoordinateHandler(FEATURE_SI_ROOT+ "brow_left_left/", "Left Brow (left)"));
handlerMap.put("b_lm", new CoordinateHandler(FEATURE_SI_ROOT+ "brow_left_middle/", "Left Brow (middle)"));
handlerMap.put("b_lr", new CoordinateHandler(FEATURE_SI_ROOT+ "brow_left_right/", "Left Bro (right)"));
handlerMap.put("b_rl", new CoordinateHandler(FEATURE_SI_ROOT+ "brow_right_left/", "Right Brow (left)"));
handlerMap.put("b_rm", new CoordinateHandler(FEATURE_SI_ROOT+ "brow_right_middle/","Right Brow (middle)"));
handlerMap.put("b_rr", new CoordinateHandler(FEATURE_SI_ROOT+ "brow_right_right/", "Right Bro (right)"));
handlerMap.put("e_ld", new CoordinateHandler(FEATURE_SI_ROOT+ "eye_left_down/", "Left Eye (down)"));
handlerMap.put("e_ll", new CoordinateHandler(FEATURE_SI_ROOT+ "eye_left_left/", "Left Eye (left)"));
handlerMap.put("e_lu", new CoordinateHandler(FEATURE_SI_ROOT+ "eye_left_up/", "Left Eye (up)"));
handlerMap.put("e_lr", new CoordinateHandler(FEATURE_SI_ROOT+ "eye_left_right/", "Left Eye (right)"));
handlerMap.put("e_rd", new CoordinateHandler(FEATURE_SI_ROOT+ "eye_right_down/", "Right Eye (down)"));
handlerMap.put("e_rl", new CoordinateHandler(FEATURE_SI_ROOT+ "eye_right_left/", "Right Eye (left)"));
handlerMap.put("e_ru", new CoordinateHandler(FEATURE_SI_ROOT+ "eye_right_up/", "Right Eye (up)"));
handlerMap.put("e_rr", new CoordinateHandler(FEATURE_SI_ROOT+ "eye_right_right/", "Right Eye (right)"));
handlerMap.put("m_d", new CoordinateHandler(FEATURE_SI_ROOT+ "mouth_down/", "Mouth (down)"));
handlerMap.put("m_u", new CoordinateHandler(FEATURE_SI_ROOT+ "mouth_up/", "Mouth (up)"));
handlerMap.put("n_l", new CoordinateHandler(FEATURE_SI_ROOT+ "nose_left/", "Nose (left)"));
handlerMap.put("n_r", new CoordinateHandler(FEATURE_SI_ROOT+ "nose_right/", "Nose (right)"));
handlerMap.put("tl", new CoordinateHandler(FEATURE_SI_ROOT+ "top_left/", "Nose (left)"));
return handlerMap;
}
/**
* Parse the URL as a string and pass it to _extractTopicsFrom(String ...)
* @param u the image URL to extract
* @param tm the current TopicMap
* @return whether the extraction was a success.
* @throws Exception propagated from _extracTopicsFrom(String ...)
*/
@Override
public boolean _extractTopicsFrom(URL u, TopicMap tm) throws Exception {
String currentURL = u.toExternalForm();
return _extractTopicsFrom(currentURL, tm);
}
/**
*
* The method used for actual extraction.
*
* @param imageUrl the image URL for extraction
* @param tm the current TopicMap
* @return true if the extraction was successful, false otherwise
* @throws Exception if the supplied URL is invalid or Topic Map
* manipulation fails
*/
@Override
public boolean _extractTopicsFrom(String imageUrl, TopicMap tm) throws Exception {
WandoraToolLogger logger = getCurrentLogger();
if(imageUrl == null)
throw new Exception("No valid Image URL found.");
/**
* Prompt for authentication if we're still lacking it. Return if we still
* didn't get it
*/
if(!conf.hasAuth()){
if(!conf.askForAuth()) return false;
}
/**
* Construct the extraction URL based on the configuration and image URL
*/
String extractUrl = API_ROOT +
"?api_key=" + conf.auth.get(AUTH_KEY.KEY) +
"&api_secret=" + conf.auth.get(AUTH_KEY.SECRET) +
"&jobs=" + "face_" + getJobsString(conf.jobs) +
"&urls=" + imageUrl;
logger.log("Getting \"" + extractUrl + "\"");
try {
HttpResponse<JsonNode> resp = Unirest.get(extractUrl).asJson();
JSONObject respNode = resp.getBody().getObject();
HashMap<String,ValueHandler> handlerMap = createHandlerMap();
logUsage(respNode);
String imageURL = respNode.getString("url");
Topic imageTopic = getImageTopic(tm, imageURL);
JSONArray detections = respNode.getJSONArray("face_detection");
logger.log("Detected " + detections.length() + " faces");
for(int i = 0; i < detections.length(); i++){
logger.log("Parsing detection #" + (i+1));
JSONObject detectionJSON = detections.getJSONObject(i);
Topic detectionTopic = getDetectionTopic(tm);
if(conf.celebrityNaming) {
try {
String bestMatch = getBestMatch(detectionJSON, conf.celebrityTreshold);
detectionTopic.setBaseName(bestMatch);
}
catch (JSONException | TopicMapException e) {
logger.log("Failed to match name for detection");
}
}
associateImageWithDetection(tm, imageTopic, detectionTopic);
for(String featureKey : handlerMap.keySet()) {
if (detectionJSON.has(featureKey)) {
Object feature = detectionJSON.get(featureKey);
handlerMap.get(featureKey).handleValue(tm, detectionTopic, feature);
}
}
}
}
catch (JSONException e) {
logger.log("Failed to parse response. (" + e.getMessage() + ")");
return false;
}
return true;
}
private String getJobsString(ArrayList<String> jobs){
if(jobs == null) return "";
StringBuilder sb = new StringBuilder();
for(String job: jobs){
sb.append('_');
sb.append(job);
}
return sb.toString();
}
private void logUsage(JSONObject respNode) throws JSONException{
JSONObject usage = respNode.getJSONObject("usage");
log("Response status: " + usage.getString("status"));
log("Quota status: " + Integer.toString(usage.getInt("quota")));
}
// ----------------------------------------------------------- CONFIGURE ---
@Override
public boolean isConfigurable(){
return true;
}
@Override
public void configure(Wandora wandora, org.wandora.utils.Options options, String prefix) throws TopicMapException {
RekognitionConfigurationUI configurationUI = new RekognitionConfigurationUI("face");
configurationUI.open(wandora,600);
configurationUI.setVisible(true);
}
@Override
public void writeOptions(Wandora wandora,org.wandora.utils.Options options,String prefix){
}
}
| 10,895 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TagtheExtractor.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/tagthe/TagtheExtractor.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.extractors.tagthe;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.StringReader;
import java.net.URL;
import java.net.URLEncoder;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.utils.IObox;
import org.wandora.utils.XMLbox;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
/**
*
* @author akivela
*/
public class TagtheExtractor extends AbstractTagtheExtractor {
private static final long serialVersionUID = 1L;
@Override
public String getName() {
return "Tagthe Extractor";
}
@Override
public String getDescription(){
return "Extracts terms out of given text using Tagthe web service. Read more at http://www.tagthe.net.";
}
public boolean _extractTopicsFrom(URL url, TopicMap topicMap) throws Exception {
return _extractTopicsFrom(url.openStream(),topicMap);
}
public boolean _extractTopicsFrom(File file, TopicMap topicMap) throws Exception {
return _extractTopicsFrom(new FileInputStream(file),topicMap);
}
public boolean _extractTopicsFrom(InputStream in, TopicMap topicMap) throws Exception {
String data = IObox.loadFile(in, defaultEncoding);
return _extractTopicsFrom(data, topicMap);
}
public boolean _extractTopicsFrom(String data, TopicMap topicMap) throws Exception {
if(data != null && data.length() > 0) {
String content = null;
try {
content = XMLbox.cleanUp(data);
if(content == null || content.length() < 1) {
// Tidy failed to fix the file...
content = data;
//contentType = "text/html";
}
else {
// Ok, Tidy fixed the html/xml document
content = XMLbox.getAsText(content, defaultEncoding);
//System.out.println("content after getAsText: "+content);
//contentType = "text/txt";
}
}
catch(Exception e) {
e.printStackTrace();
content = data;
//contentType = "text/raw";
}
String extractURL = WEB_SERVICE_URL+"?text="+URLEncoder.encode(content, "utf-8");
String result = IObox.doUrl(new URL(extractURL));
//System.out.println("Tagthe returned == "+result);
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();
TagtheExtractorParser parserHandler = new TagtheExtractorParser(getMasterSubject(), content, topicMap, this);
reader.setContentHandler(parserHandler);
reader.setErrorHandler(parserHandler);
try {
reader.parse(new InputSource(new StringReader(result)));
}
catch(Exception e){
if(!(e instanceof SAXException) || !e.getMessage().equals("User interrupt")) log(e);
}
log("Total " + parserHandler.progress + " terms found by Tagthe");
}
else {
log("No valid data given! Aborting!");
}
return true;
}
// -------------------------------------------------------------------------
private class TagtheExtractorParser implements org.xml.sax.ContentHandler, org.xml.sax.ErrorHandler {
public TagtheExtractorParser(String term, String data, TopicMap tm, TagtheExtractor parent){
this.tm=tm;
this.parent=parent;
try {
if(term != null) {
masterTopic = tm.getTopicWithBaseName(term);
if(masterTopic == null) masterTopic = tm.getTopic(term);
}
}
catch(Exception e) {
parent.log(e);
}
if(masterTopic == null && data != null && data.length() > 0) {
try {
masterTopic = tm.createTopic();
masterTopic.addSubjectIdentifier(tm.makeSubjectIndicatorAsLocator());
parent.fillDocumentTopic(masterTopic, tm, data);
}
catch(Exception e) {
parent.log(e);
}
}
this.tm=tm;
this.parent=parent;
}
Topic masterTopic = null;
public int progress=0;
private TopicMap tm;
private TagtheExtractor parent;
public static final String TAG_MEMES="memes";
public static final String TAG_MEME="meme";
public static final String TAG_DIM="dim";
public static final String TAG_ITEM="item";
private static final String ATTRIBUTE_TYPE = "type";
private static final int STATE_START=0;
private static final int STATE_MEMES=1;
private static final int STATE_MEMES_MEME=11;
private static final int STATE_MEMES_MEME_DIM=111;
private static final int STATE_MEMES_MEME_DIM_ITEM=1111;
private int state=STATE_START;
private String data_item = "";
private String data_type = "";
public void startDocument() throws SAXException {
}
public void endDocument() throws SAXException {
}
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
if(parent.forceStop()){
throw new SAXException("User interrupt");
}
switch(state){
case STATE_START:
if(qName.equals(TAG_MEMES)) {
state = STATE_MEMES;
}
break;
case STATE_MEMES:
if(qName.equals(TAG_MEME)) {
state = STATE_MEMES_MEME;
}
break;
case STATE_MEMES_MEME:
if(qName.equals(TAG_DIM)) {
data_type = atts.getValue(ATTRIBUTE_TYPE);
state = STATE_MEMES_MEME_DIM;
}
break;
case STATE_MEMES_MEME_DIM:
if(qName.equals(TAG_ITEM)) {
data_item = "";
state = STATE_MEMES_MEME_DIM_ITEM;
}
break;
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
// System.out.println(" "+state);
switch(state) {
case STATE_MEMES_MEME_DIM_ITEM:
if(qName.equals(TAG_ITEM)) {
parent.setProgress( progress++ );
if(data_item != null && data_item.length() > 0) {
try {
if(parent.getCurrentLogger() != null) parent.log("Tagthe found term '"+data_item+"'.");
Topic termTopic = parent.getTermTopic(data_item, data_type, tm);
if(masterTopic != null && termTopic != null) {
Topic termType = parent.getTermTypeType(tm);
Association a = tm.createAssociation(termType);
a.addPlayer(masterTopic, parent.getTopicType(tm));
a.addPlayer(termTopic, termType);
}
}
catch(Exception e) {
parent.log(e);
}
}
else {
parent.log("Zero length term text found! Rejecting!");
}
state = STATE_MEMES_MEME_DIM;
}
break;
case STATE_MEMES_MEME_DIM:
if(qName.equals(TAG_DIM)) {
state = STATE_MEMES_MEME;
}
break;
case STATE_MEMES_MEME:
if(qName.equals(TAG_MEME)) {
state = STATE_MEMES;
}
break;
case STATE_MEMES:
if(qName.equals(TAG_MEMES)) {
state = STATE_START;
}
break;
}
}
public void characters(char[] ch, int start, int length) throws SAXException {
switch(state){
case STATE_MEMES_MEME_DIM_ITEM:
data_item+=new String(ch,start,length);
break;
}
}
public void warning(SAXParseException exception) throws SAXException {
}
public void error(SAXParseException exception) throws SAXException {
parent.log("Error parsing XML document at "+exception.getLineNumber()+","+exception.getColumnNumber(),exception);
}
public void fatalError(SAXParseException exception) throws SAXException {
parent.log("Fatal error parsing XML document at "+exception.getLineNumber()+","+exception.getColumnNumber(),exception);
}
public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {}
public void processingInstruction(String target, String data) throws SAXException {}
public void startPrefixMapping(String prefix, String uri) throws SAXException {}
public void endPrefixMapping(String prefix) throws SAXException {}
public void setDocumentLocator(org.xml.sax.Locator locator) {}
public void skippedEntity(String name) throws SAXException {}
}
}
| 11,181 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AbstractTagtheExtractor.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/tagthe/AbstractTagtheExtractor.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.extractors.tagthe;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import javax.swing.Icon;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraToolType;
import org.wandora.application.gui.UIBox;
import org.wandora.application.tools.browserextractors.BrowserExtractRequest;
import org.wandora.application.tools.extractors.AbstractExtractor;
import org.wandora.application.tools.extractors.ExtractHelper;
import org.wandora.topicmap.TMBox;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.utils.Textbox;
/**
*
* @author akivela
*/
public abstract class AbstractTagtheExtractor extends AbstractExtractor {
private static final long serialVersionUID = 1L;
protected String defaultEncoding = "UTF-8";
// Default language of occurrences and variant names.
public static String LANG = "en";
public static final String WEB_SERVICE_URL = "http://tagthe.net/api/";
public static final String SOURCE_SI = "http://wandora.org/si/source";
public static final String DOCUMENT_SI = "http://wandora.org/si/document";
public static final String TOPIC_SI = "http://wandora.org/si/topic";
public static final String TAGTHE_SI = "http://tagthe.net";
public static final String TAGTHE_TERM_SI = "http://tagthe.net/term";
public static final String TAGTHE_TERM_TYPE_SI = "http://tagthe.net/type";
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/extract_tagthe.png");
}
@Override
public WandoraToolType getType() {
return WandoraToolType.createExtractType();
}
private final String[] contentTypes=new String[] { "text/plain", "text/html" };
@Override
public String[] getContentTypes() {
return contentTypes;
}
@Override
public boolean useURLCrawler() {
return false;
}
// -------------------------------------------------------------------------
@Override
public boolean isConfigurable(){
return false;
}
// -------------------------------------------------------------------------
@Override
public String doBrowserExtract(BrowserExtractRequest request, Wandora wandora) throws TopicMapException {
setWandora(wandora);
return ExtractHelper.doBrowserExtractForClassifiers(this, request, wandora, defaultEncoding);
}
// -------------------------------------------------------------------------
public abstract boolean _extractTopicsFrom(InputStream in, TopicMap topicMap) throws Exception;
public String solveTitle(String content) {
if(content == null || content.length() == 0) return "empty-document";
boolean forceTrim = false;
String title = null;
int i = content.indexOf("\n");
if(i > 0) title = content.substring(0, i);
else {
title = content.substring(0, Math.min(80, content.length()));
forceTrim = true;
}
if(title != null && (forceTrim || title.length() > 80)) {
title = title.substring(0, Math.min(80, title.length()));
while(!title.endsWith(" ") && title.length()>10) {
title = title.substring(0, title.length()-1);
}
title = Textbox.trimExtraSpaces(title) + "...";
}
return title;
}
public void fillDocumentTopic(Topic textTopic, TopicMap topicMap, String content) {
try {
String trimmedText = Textbox.trimExtraSpaces(content);
if(trimmedText != null && trimmedText.length() > 0) {
Topic contentType = createTopic(topicMap, "document-text");
setData(textTopic, contentType, "en", trimmedText);
}
String title = solveTitle(trimmedText);
if(title != null) {
textTopic.setBaseName(title + " (" + content.hashCode() + ")");
textTopic.setDisplayName("en", title);
}
Topic documentType = getDocumentType(topicMap);
textTopic.addType(documentType);
}
catch(Exception e) {
log(e);
}
}
// ******** TOPIC MAPS *********
public Topic getTermTypeType(TopicMap tm) throws TopicMapException {
Topic t = getOrCreateTopic(tm, TAGTHE_TERM_TYPE_SI, "Tagthe Term");
t.addType(getTagtheClass(tm));
return t;
}
public Topic getTermType(String type, TopicMap tm) throws TopicMapException {
Topic t = getOrCreateTopic(tm, TAGTHE_TERM_TYPE_SI+"/"+type, type);
t.addType(getTermTypeType(tm));
return t;
}
public Topic getTermTopic(String term, String type, TopicMap tm) throws TopicMapException {
if(term != null) {
term = term.trim();
if(term.length() > 0) {
Topic entityTopic=getOrCreateTopic(tm, TAGTHE_TERM_SI+"/"+term, term);
if(type != null && type.length() > 0) {
Topic entityTypeTopic = getTermType(type, tm);
entityTopic.addType(entityTypeTopic);
}
return entityTopic;
}
}
return null;
}
public Topic getTagtheClass(TopicMap tm) throws TopicMapException {
Topic t = getOrCreateTopic(tm, TAGTHE_SI,"Tagthe.net");
makeSubclassOf(tm, t, getWandoraClass(tm));
//t.addType(getWandoraClass(tm));
return t;
}
public Topic getWandoraClass(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, TMBox.WANDORACLASS_SI,"Wandora class");
}
public Topic getTopicType(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, TOPIC_SI, "Topic");
}
public Topic getSourceType(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, SOURCE_SI, "Source");
}
public Topic getDocumentType(TopicMap tm) throws TopicMapException {
Topic type = getOrCreateTopic(tm, DOCUMENT_SI, "Document");
Topic wandoraClass = getWandoraClass(tm);
makeSubclassOf(tm, type, wandoraClass);
return type;
}
// --------
protected Topic getOrCreateTopic(TopicMap tm, String si) throws TopicMapException {
return getOrCreateTopic(tm, si,null);
}
protected Topic getOrCreateTopic(TopicMap tm, String si,String bn) throws TopicMapException {
return ExtractHelper.getOrCreateTopic(si, bn, tm);
}
protected void makeSubclassOf(TopicMap tm, Topic t, Topic superclass) throws TopicMapException {
ExtractHelper.makeSubclassOf(t, superclass, tm);
}
// -------------------------------------------------------------------------
protected String getStringFromDocument(Document doc) {
try {
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
return writer.toString();
}
catch(TransformerException ex) {
ex.printStackTrace();
return null;
}
}
// utility function
protected String getFileContents(File file) throws IOException, FileNotFoundException {
StringBuilder contents = new StringBuilder();
BufferedReader input = new BufferedReader(new FileReader(file));
try {
String line = null;
while ((line = input.readLine()) != null) {
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
}
finally {
input.close();
}
return contents.toString();
}
}
| 9,271 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
DefinitionExtractor.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/stands4/DefinitionExtractor.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.extractors.stands4;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.XTMPSI;
import org.wandora.utils.IObox;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
/**
*
* @author akivela
*/
public class DefinitionExtractor extends AbstractStands4Extractor {
private static final long serialVersionUID = 1L;
private String queryTerm = null;
/** Creates a new instance of DefinitionsExtractor */
public DefinitionExtractor() {
}
@Override
public String getName() {
return "Stands4 definitions extractor";
}
@Override
public String getDescription(){
return "Finds definitions for a given word using Stands4 web service. Definition service provided by www.definitions.net. "+
"Extractor reads a feed from the web service and converts it to a topic map.";
}
public String getTermBase() {
return DEFINITIONS_TERM_BASE;
}
public String getTermType() {
return DEFINITIONS_BASE+"type";
}
public boolean _extractTopicsFrom(URL url, TopicMap topicMap) throws Exception {
try {
queryTerm = solveQueryTerm(url);
}
catch(Exception e) {
log(e);
}
String in = IObox.doUrl(url);
return _extractTopicsFrom(in, topicMap);
}
public boolean _extractTopicsFrom(File file, TopicMap topicMap) throws Exception {
return _extractTopicsFrom(new FileInputStream(file),topicMap);
}
public boolean _extractTopicsFrom(InputStream in, TopicMap topicMap) throws Exception {
String str = IObox.loadFile(in, defaultEncoding);
return _extractTopicsFrom(str, topicMap);
}
public boolean _extractTopicsFrom(String in, TopicMap topicMap) throws Exception {
try {
String result = in;
//System.out.println("Result = "+result);
// ---- Parse results ----
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();
DefinitionResultParser parserHandler = new DefinitionResultParser(getMasterSubject(), queryTerm, topicMap, this);
reader.setContentHandler(parserHandler);
reader.setErrorHandler(parserHandler);
try{
reader.parse(new InputSource(new ByteArrayInputStream(result.getBytes())));
}
catch(Exception e){
if(!(e instanceof SAXException) || !e.getMessage().equals("User interrupt")) log(e);
}
String msg = null;
if(parserHandler.progress == 0) {
msg = "Found no terms.";
}
else {
msg = "Found "+parserHandler.progress+" (complex) terms.";
}
if(msg != null) log(msg);
}
catch (Exception ex) {
log(ex);
}
queryTerm = null;
return true;
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
private class DefinitionResultParser implements org.xml.sax.ContentHandler, org.xml.sax.ErrorHandler {
public int progress=0;
private TopicMap tm;
private DefinitionExtractor parent;
private Topic aTermTopic = null;
private Topic masterTopic = null;
public DefinitionResultParser(String master, String term, TopicMap tm, DefinitionExtractor parent) {
this.tm=tm;
this.parent=parent;
try {
if(term != null) {
term = term.trim();
if(term.length() > 0) {
aTermTopic = getTermTopic(term, tm);
}
}
}
catch(Exception e) {
parent.log(e);
}
try {
if(master != null) {
masterTopic = tm.getTopicWithBaseName(master);
if(masterTopic == null) masterTopic = tm.getTopic(master);
}
}
catch(Exception e) {
parent.log(e);
}
if(masterTopic != null && aTermTopic != null) {
try {
Association a = tm.createAssociation(getTermType(tm));
a.addPlayer(aTermTopic, getTermType(tm));
a.addPlayer(masterTopic, getSourceType(tm));
}
catch(Exception e) {
parent.log(e);
}
}
}
public static final String TAG_RESULTS = "results";
public static final String TAG_RESULT = "result";
public static final String TAG_TERM = "term";
public static final String TAG_DEFINITION = "definition";
public static final String TAG_PARTOFSPEECH = "partofspeach";
public static final String TAG_EXAMPLE = "example";
public static final String TAG_SYNONYMS = "synonyms";
private static final int STATE_START=0;
private static final int STATE_RESULTS=2;
private static final int STATE_RESULTS_RESULT=4;
private static final int STATE_RESULTS_RESULT_TERM=5;
private static final int STATE_RESULTS_RESULT_DEFINITION=6;
private static final int STATE_RESULTS_RESULT_PARTOFSPEECH=7;
private static final int STATE_RESULTS_RESULT_EXAMPLE=8;
private static final int STATE_RESULTS_RESULT_SYNONYMS=9;
private int state=STATE_START;
private String data_term = null;
private String data_definition = null;
private String data_partofspeech = null;
private String data_example = null;
private String data_synonyms = null;
public void startDocument() throws SAXException {
}
public void endDocument() throws SAXException {
}
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
if(parent.forceStop()){
throw new SAXException("User interrupt");
}
switch(state){
case STATE_START:
if(qName.equals(TAG_RESULTS)) {
state = STATE_RESULTS;
}
break;
case STATE_RESULTS:
if(qName.equals(TAG_RESULT)) {
data_term = "";
data_definition = "";
data_partofspeech = "";
data_example = "";
data_synonyms = "";
state = STATE_RESULTS_RESULT;
}
break;
case STATE_RESULTS_RESULT:
if(qName.equals(TAG_TERM)) {
data_term = "";
state = STATE_RESULTS_RESULT_TERM;
}
else if(qName.equals(TAG_DEFINITION)) {
data_definition = "";
state = STATE_RESULTS_RESULT_DEFINITION;
}
else if(qName.equals(TAG_PARTOFSPEECH)) {
data_partofspeech = "";
state = STATE_RESULTS_RESULT_PARTOFSPEECH;
}
else if(qName.equals(TAG_EXAMPLE)) {
data_example = "";
state = STATE_RESULTS_RESULT_EXAMPLE;
}
else if(qName.equals(TAG_SYNONYMS)) {
data_synonyms = "";
state = STATE_RESULTS_RESULT_SYNONYMS;
}
break;
case STATE_RESULTS_RESULT_TERM:
break;
case STATE_RESULTS_RESULT_DEFINITION:
break;
case STATE_RESULTS_RESULT_PARTOFSPEECH:
break;
case STATE_RESULTS_RESULT_EXAMPLE:
break;
case STATE_RESULTS_RESULT_SYNONYMS:
break;
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
switch(state) {
case STATE_RESULTS: {
if(qName.equals(TAG_RESULTS)) {
state = STATE_START;
}
break;
}
case STATE_RESULTS_RESULT: {
if(qName.equals(TAG_RESULT)) {
try {
if(data_term != null && data_term.length() > 0) {
parent.log("Found term complex '"+data_term+"'.");
parent.setProgress(progress++);
Topic termTopic = getTermComplexTopic(data_term, data_definition, tm);
if(termTopic != null) {
if(data_definition != null && data_definition.length() > 0) {
data_definition = data_definition.trim();
Topic definitionType = getDefinitionType(tm);
Topic langTopic = getOrCreateTopic(tm, XTMPSI.getLang(defaultLang));
termTopic.setData(definitionType, langTopic, data_definition);
}
if(data_example != null && data_example.length() > 0) {
data_example = data_example.trim();
Topic exampleType = getExampleType(tm);
Topic langTopic = getOrCreateTopic(tm, XTMPSI.getLang(defaultLang));
termTopic.setData(exampleType, langTopic, data_example);
}
if(data_partofspeech != null && data_partofspeech.length() > 0) {
Topic partOfSpeedTopic = getPartOfSpeechTopic(data_partofspeech, tm);
Topic partOfSpeedType = getPartOfSpeechType(tm);
Topic termType = getTermType(tm);
Association pofs = tm.createAssociation(partOfSpeedType);
pofs.addPlayer(partOfSpeedTopic, partOfSpeedType);
pofs.addPlayer(termTopic, termType);
}
if(data_synonyms != null && data_synonyms.length() > 0) {
String[] synonyms = data_synonyms.split(",");
for(int i=0; i<synonyms.length ; i++) {
String synonym = synonyms[i].trim();
if(synonym.length() > 0) {
Topic synonymTerm = getTermTopic( synonym, tm );
Topic synonymTermType = getSynonymTermType(tm);
Topic termType = getTermType(tm);
Association sa = tm.createAssociation(synonymTermType);
sa.addPlayer(termTopic, termType);
sa.addPlayer(synonymTerm, synonymTermType);
}
}
}
}
}
}
catch(Exception e) {
parent.log(e);
}
state = STATE_RESULTS;
}
break;
}
case STATE_RESULTS_RESULT_TERM: {
if(qName.equals(TAG_TERM)) {
state = STATE_RESULTS_RESULT;
}
break;
}
case STATE_RESULTS_RESULT_DEFINITION: {
if(qName.equals(TAG_DEFINITION)) {
state = STATE_RESULTS_RESULT;
}
break;
}
case STATE_RESULTS_RESULT_PARTOFSPEECH: {
if(qName.equals(TAG_PARTOFSPEECH)) {
state = STATE_RESULTS_RESULT;
}
break;
}
case STATE_RESULTS_RESULT_EXAMPLE: {
if(qName.equals(TAG_EXAMPLE)) {
state = STATE_RESULTS_RESULT;
}
break;
}
case STATE_RESULTS_RESULT_SYNONYMS: {
if(qName.equals(TAG_SYNONYMS)) {
state = STATE_RESULTS_RESULT;
}
break;
}
}
}
public void characters(char[] ch, int start, int length) throws SAXException {
switch(state) {
case STATE_RESULTS_RESULT_TERM: {
data_term += new String(ch,start,length);
break;
}
case STATE_RESULTS_RESULT_DEFINITION: {
data_definition += new String(ch,start,length);
break;
}
case STATE_RESULTS_RESULT_PARTOFSPEECH: {
data_partofspeech += new String(ch,start,length);
break;
}
case STATE_RESULTS_RESULT_EXAMPLE: {
data_example += new String(ch,start,length);
break;
}
case STATE_RESULTS_RESULT_SYNONYMS: {
data_synonyms += new String(ch,start,length);
break;
}
default:
break;
}
}
public void warning(SAXParseException exception) throws SAXException {
}
public void error(SAXParseException exception) throws SAXException {
parent.log("Error parsing XML document at "+exception.getLineNumber()+","+exception.getColumnNumber(),exception);
}
public void fatalError(SAXParseException exception) throws SAXException {
parent.log("Fatal error parsing XML document at "+exception.getLineNumber()+","+exception.getColumnNumber(),exception);
}
public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {}
public void processingInstruction(String target, String data) throws SAXException {}
public void startPrefixMapping(String prefix, String uri) throws SAXException {}
public void endPrefixMapping(String prefix) throws SAXException {}
public void setDocumentLocator(org.xml.sax.Locator locator) {}
public void skippedEntity(String name) throws SAXException {}
}
}
| 16,853 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AbbreviationExtractor.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/stands4/AbbreviationExtractor.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.extractors.stands4;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.utils.IObox;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
/**
*
* @author akivela
*/
public class AbbreviationExtractor extends AbstractStands4Extractor {
private static final long serialVersionUID = 1L;
private String queryTerm = null;
/** Creates a new instance of AbbreviationsExtractor */
public AbbreviationExtractor() {
}
@Override
public String getName() {
return "Stands4 abbreviations extractor";
}
@Override
public String getDescription(){
return "Finds words for given acronym using Stands4 web service available at www.abbreviations.com. "+
"Extractor reads a feed from the web service and converts it to a topic map.";
}
public String getTermBase() {
return ABBREVIATIONS_TERM_BASE;
}
public String getTermType() {
return ABBREVIATIONS_BASE+"type";
}
public boolean _extractTopicsFrom(URL url, TopicMap topicMap) throws Exception {
try {
//log(url.toExternalForm());
queryTerm = solveQueryTerm(url);
}
catch(Exception e) {
log(e);
}
String in = IObox.doUrl(url);
return _extractTopicsFrom(in, topicMap);
}
public boolean _extractTopicsFrom(File file, TopicMap topicMap) throws Exception {
return _extractTopicsFrom(new FileInputStream(file),topicMap);
}
public boolean _extractTopicsFrom(InputStream in, TopicMap topicMap) throws Exception {
String str = IObox.loadFile(in, defaultEncoding);
return _extractTopicsFrom(str, topicMap);
}
public boolean _extractTopicsFrom(String in, TopicMap topicMap) throws Exception {
try {
String result = in;
//System.out.println("Result = "+result);
// ---- Parse results ----
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();
AbbreviationResultParser parserHandler = new AbbreviationResultParser(getMasterSubject(), queryTerm, topicMap, this);
reader.setContentHandler(parserHandler);
reader.setErrorHandler(parserHandler);
try {
reader.parse(new InputSource(new ByteArrayInputStream(result.getBytes(defaultEncoding))));
}
catch(Exception e){
if(!(e instanceof SAXException) || !e.getMessage().equals("User interrupt")) log(e);
}
String msg = null;
if(parserHandler.progress == 0) {
msg = "Found no words for acronym.";
}
else {
msg = "Found "+parserHandler.progress+" word(s) for acronym.";
}
if(msg != null) log(msg);
}
catch (Exception ex) {
log(ex);
}
queryTerm = null;
return true;
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
private class AbbreviationResultParser implements org.xml.sax.ContentHandler, org.xml.sax.ErrorHandler {
public int progress=0;
private TopicMap tm;
private AbbreviationExtractor parent;
private Topic termTopic = null;
private Topic masterTopic = null;
public AbbreviationResultParser(String master, String term, TopicMap tm, AbbreviationExtractor parent) {
this.tm=tm;
this.parent=parent;
try {
if(term != null) {
term = term.trim();
if(term.length() > 0) {
termTopic = getTermTopic(term, tm);
}
}
}
catch(Exception e) {
parent.log(e);
}
try {
if(master != null) {
masterTopic = tm.getTopicWithBaseName(master);
if(masterTopic == null) masterTopic = tm.getTopic(master);
}
}
catch(Exception e) {
parent.log(e);
}
if(masterTopic != null && termTopic != null) {
try {
Association a = tm.createAssociation(getTermType(tm));
a.addPlayer(termTopic, getTermType(tm));
a.addPlayer(masterTopic, getSourceType(tm));
}
catch(Exception e) {
parent.log(e);
}
}
}
public static final String TAG_RESULTS = "results";
public static final String TAG_RESULT = "result";
public static final String TAG_TERM = "term";
public static final String TAG_DEFINITION = "definition";
public static final String TAG_CATEGORY = "category";
private static final int STATE_START=0;
private static final int STATE_RESULTS=2;
private static final int STATE_RESULTS_RESULT=4;
private static final int STATE_RESULTS_RESULT_TERM=5;
private static final int STATE_RESULTS_RESULT_DEFINITION=6;
private static final int STATE_RESULTS_RESULT_CATEGORY=7;
private int state=STATE_START;
private String data_term = null;
private String data_definition = null;
private String data_category = null;
public void startDocument() throws SAXException {
}
public void endDocument() throws SAXException {
}
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
if(parent.forceStop()){
throw new SAXException("User interrupt");
}
switch(state){
case STATE_START:
if(qName.equals(TAG_RESULTS)) {
state = STATE_RESULTS;
}
break;
case STATE_RESULTS:
if(qName.equals(TAG_RESULT)) {
data_term = "";
data_definition = "";
data_category = "";
state = STATE_RESULTS_RESULT;
}
break;
case STATE_RESULTS_RESULT:
if(qName.equals(TAG_TERM)) {
data_term = "";
state = STATE_RESULTS_RESULT_TERM;
}
else if(qName.equals(TAG_DEFINITION)) {
data_definition = "";
state = STATE_RESULTS_RESULT_DEFINITION;
}
else if(qName.equals(TAG_CATEGORY)) {
data_category = "";
state = STATE_RESULTS_RESULT_CATEGORY;
}
break;
case STATE_RESULTS_RESULT_TERM:
break;
case STATE_RESULTS_RESULT_DEFINITION:
break;
case STATE_RESULTS_RESULT_CATEGORY:
break;
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
switch(state) {
case STATE_RESULTS: {
if(qName.equals(TAG_RESULTS)) {
state = STATE_START;
}
break;
}
case STATE_RESULTS_RESULT: {
if(qName.equals(TAG_RESULT)) {
try {
if(data_term != null && data_term.length() > 0) {
data_term = data_term.trim();
Topic termTopic = getTermTopic(data_term, tm);
parent.setProgress(progress++);
if(termTopic != null) {
Topic abbreviationType = getAbbreviationType(tm);
Association a = tm.createAssociation(abbreviationType);
a.addPlayer(termTopic, getTermType(tm));
if(data_category != null) {
Topic categoryType = getCategoryType(tm);
Topic categoryTopic = getCategoryTopic(data_category, tm);
a.addPlayer(categoryTopic, categoryType);
}
if(data_definition != null) {
Topic definitionType = getDefinitionType(tm);
Topic definitionTopic = getDefinitionTopic(data_definition, tm);
a.addPlayer(definitionTopic, definitionType);
}
}
}
}
catch(Exception e) {
parent.log(e);
}
state = STATE_RESULTS;
}
break;
}
case STATE_RESULTS_RESULT_TERM: {
if(qName.equals(TAG_TERM)) {
state = STATE_RESULTS_RESULT;
}
break;
}
case STATE_RESULTS_RESULT_DEFINITION: {
if(qName.equals(TAG_DEFINITION)) {
state = STATE_RESULTS_RESULT;
}
break;
}
case STATE_RESULTS_RESULT_CATEGORY: {
if(qName.equals(TAG_CATEGORY)) {
state = STATE_RESULTS_RESULT;
}
break;
}
}
}
public void characters(char[] ch, int start, int length) throws SAXException {
switch(state) {
case STATE_RESULTS_RESULT_TERM: {
data_term += new String(ch,start,length);
break;
}
case STATE_RESULTS_RESULT_DEFINITION: {
data_definition += new String(ch,start,length);
break;
}
case STATE_RESULTS_RESULT_CATEGORY: {
data_category += new String(ch,start,length);
break;
}
default:
break;
}
}
public void warning(SAXParseException exception) throws SAXException {
}
public void error(SAXParseException exception) throws SAXException {
parent.log("Error parsing XML document at "+exception.getLineNumber()+","+exception.getColumnNumber(),exception);
}
public void fatalError(SAXParseException exception) throws SAXException {
parent.log("Fatal error parsing XML document at "+exception.getLineNumber()+","+exception.getColumnNumber(),exception);
}
public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {}
public void processingInstruction(String target, String data) throws SAXException {}
public void startPrefixMapping(String prefix, String uri) throws SAXException {}
public void endPrefixMapping(String prefix) throws SAXException {}
public void setDocumentLocator(org.xml.sax.Locator locator) {}
public void skippedEntity(String name) throws SAXException {}
}
} | 13,306 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SynonymExtractor.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/stands4/SynonymExtractor.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.extractors.stands4;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.XTMPSI;
import org.wandora.utils.IObox;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
/**
*
* @author akivela
*/
public class SynonymExtractor extends AbstractStands4Extractor {
private static final long serialVersionUID = 1L;
private String queryTerm = null;
private boolean excludeSynonyms = false;
private boolean excludeAntonyms = false;
private boolean excludePartOfSpeech = false;
private boolean excludeDefinition = false;
/** Creates a new instance of SynonymExtractor */
public SynonymExtractor() {
}
@Override
public String getName() {
return "Stands4 synonyms extractor";
}
@Override
public String getDescription(){
return "Finds synonyms for a given word using Stands4 web service. Synonyms service is provided by www.synonyms.net. "+
"Extractor reads a feed from the web service and converts it to a topic map.";
}
public String getTermBase() {
return SYNONYMS_TERM_BASE;
}
public String getTermType() {
return SYNONYMS_BASE+"type";
}
// -------------------------------------------------------------------------
public void excludeSynonyms(boolean value) {
excludeSynonyms = value;
}
public void excludeAntonyms(boolean value) {
excludeAntonyms = value;
}
public void excludePartOfSpeech(boolean value) {
excludePartOfSpeech = value;
}
public void excludeDefinition(boolean value) {
excludeDefinition = value;
}
// -------------------------------------------------------------------------
public boolean _extractTopicsFrom(URL url, TopicMap topicMap) throws Exception {
try {
queryTerm = solveQueryTerm(url);
}
catch(Exception e) {
log(e);
}
String in = IObox.doUrl(url);
return _extractTopicsFrom(in, topicMap);
}
public boolean _extractTopicsFrom(File file, TopicMap topicMap) throws Exception {
return _extractTopicsFrom(new FileInputStream(file),topicMap);
}
public boolean _extractTopicsFrom(InputStream in, TopicMap topicMap) throws Exception {
String str = IObox.loadFile(in, defaultEncoding);
return _extractTopicsFrom(str, topicMap);
}
public boolean _extractTopicsFrom(String in, TopicMap topicMap) throws Exception {
try {
String result = in;
//System.out.println("Result = "+result);
// ---- Parse results ----
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();
SynonymResultParser parserHandler = new SynonymResultParser(getMasterSubject(), queryTerm, topicMap, this);
reader.setContentHandler(parserHandler);
reader.setErrorHandler(parserHandler);
try{
reader.parse(new InputSource(new ByteArrayInputStream(result.getBytes())));
}
catch(Exception e){
if(!(e instanceof SAXException) || !e.getMessage().equals("User interrupt")) log(e);
}
String msg = null;
if(parserHandler.progress == 0) {
msg = "Found no terms.";
}
else {
msg = "Found "+parserHandler.progress+" (complex) terms.";
}
if(msg != null) log(msg);
}
catch (Exception ex) {
log(ex);
}
queryTerm = null;
return true;
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
private class SynonymResultParser implements org.xml.sax.ContentHandler, org.xml.sax.ErrorHandler {
public int progress=0;
private TopicMap tm;
private SynonymExtractor parent;
private Topic aTermTopic = null;
private Topic masterTopic = null;
public SynonymResultParser(String master, String term, TopicMap tm, SynonymExtractor parent) {
this.tm=tm;
this.parent=parent;
try {
if(term != null) {
term = term.trim();
if(term.length() > 0) {
aTermTopic = getTermTopic(term, tm);
}
}
}
catch(Exception e) {
parent.log(e);
}
try {
if(master != null) {
masterTopic = tm.getTopicWithBaseName(master);
if(masterTopic == null) masterTopic = tm.getTopic(master);
}
}
catch(Exception e) {
parent.log(e);
}
if(masterTopic != null && aTermTopic != null) {
try {
Association a = tm.createAssociation(getTermType(tm));
a.addPlayer(aTermTopic, getTermType(tm));
a.addPlayer(masterTopic, getSourceType(tm));
}
catch(Exception e) {
parent.log(e);
}
}
}
public static final String TAG_RESULTS = "results";
public static final String TAG_RESULT = "result";
public static final String TAG_TERM = "term";
public static final String TAG_DEFINITION = "definition";
public static final String TAG_PARTOFSPEECH = "partofspeach";
public static final String TAG_EXAMPLE = "example";
public static final String TAG_SYNONYMS = "synonyms";
public static final String TAG_ANTONYMS = "antonyms";
private static final int STATE_START=0;
private static final int STATE_RESULTS=2;
private static final int STATE_RESULTS_RESULT=4;
private static final int STATE_RESULTS_RESULT_TERM=5;
private static final int STATE_RESULTS_RESULT_DEFINITION=6;
private static final int STATE_RESULTS_RESULT_PARTOFSPEECH=7;
private static final int STATE_RESULTS_RESULT_EXAMPLE=8;
private static final int STATE_RESULTS_RESULT_SYNONYMS=9;
private static final int STATE_RESULTS_RESULT_ANTONYMS=10;
private int state=STATE_START;
private String data_term = null;
private String data_definition = null;
private String data_partofspeech = null;
private String data_example = null;
private String data_synonyms = null;
private String data_antonyms = null;
public void startDocument() throws SAXException {
}
public void endDocument() throws SAXException {
}
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
if(parent.forceStop()){
throw new SAXException("User interrupt");
}
switch(state){
case STATE_START:
if(qName.equals(TAG_RESULTS)) {
state = STATE_RESULTS;
}
break;
case STATE_RESULTS:
if(qName.equals(TAG_RESULT)) {
data_term = "";
data_definition = "";
data_partofspeech = "";
data_example = "";
data_synonyms = "";
data_antonyms = "";
state = STATE_RESULTS_RESULT;
}
break;
case STATE_RESULTS_RESULT:
if(qName.equals(TAG_TERM)) {
data_term = "";
state = STATE_RESULTS_RESULT_TERM;
}
else if(qName.equals(TAG_DEFINITION)) {
data_definition = "";
state = STATE_RESULTS_RESULT_DEFINITION;
}
else if(qName.equals(TAG_PARTOFSPEECH)) {
data_partofspeech = "";
state = STATE_RESULTS_RESULT_PARTOFSPEECH;
}
else if(qName.equals(TAG_EXAMPLE)) {
data_example = "";
state = STATE_RESULTS_RESULT_EXAMPLE;
}
else if(qName.equals(TAG_SYNONYMS)) {
data_synonyms = "";
state = STATE_RESULTS_RESULT_SYNONYMS;
}
else if(qName.equals(TAG_ANTONYMS)) {
data_antonyms = "";
state = STATE_RESULTS_RESULT_ANTONYMS;
}
break;
case STATE_RESULTS_RESULT_TERM:
break;
case STATE_RESULTS_RESULT_DEFINITION:
break;
case STATE_RESULTS_RESULT_PARTOFSPEECH:
break;
case STATE_RESULTS_RESULT_EXAMPLE:
break;
case STATE_RESULTS_RESULT_SYNONYMS:
break;
case STATE_RESULTS_RESULT_ANTONYMS:
break;
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
switch(state) {
case STATE_RESULTS: {
if(qName.equals(TAG_RESULTS)) {
state = STATE_START;
}
break;
}
case STATE_RESULTS_RESULT: {
if(qName.equals(TAG_RESULT)) {
try {
if(data_term != null && data_term.length() > 0) {
parent.log("Found term complex '"+data_term+"'.");
parent.setProgress(progress++);
Topic termTopic = getTermComplexTopic(data_term, data_definition, tm);
if(termTopic != null) {
if(!excludeDefinition && data_definition != null && data_definition.length() > 0) {
data_definition = data_definition.trim();
Topic definitionType = getDefinitionType(tm);
Topic langTopic = getOrCreateTopic(tm, XTMPSI.getLang(defaultLang));
termTopic.setData(definitionType, langTopic, data_definition);
}
if(!excludeDefinition && data_example != null && data_example.length() > 0) {
data_example = data_example.trim();
Topic exampleType = getExampleType(tm);
Topic langTopic = getOrCreateTopic(tm, XTMPSI.getLang(defaultLang));
termTopic.setData(exampleType, langTopic, data_example);
}
if(!excludePartOfSpeech && data_partofspeech != null && data_partofspeech.length() > 0) {
Topic partOfSpeedTopic = getPartOfSpeechTopic(data_partofspeech, tm);
Topic partOfSpeedType = getPartOfSpeechType(tm);
Topic termComplexType = getTermComplexType(tm);
Association pofs = tm.createAssociation(partOfSpeedType);
pofs.addPlayer(partOfSpeedTopic, partOfSpeedType);
pofs.addPlayer(termTopic, termComplexType);
}
if(!excludeSynonyms && data_synonyms != null && data_synonyms.length() > 0) {
String[] synonyms = data_synonyms.split(",");
for(int i=0; i<synonyms.length ; i++) {
String synonym = synonyms[i].trim();
if(synonym.length() > 0) {
Topic synonymTerm = getTermTopic( synonym, tm );
Topic synonymTermType = getSynonymTermType(tm);
Topic termComplexType = getTermComplexType(tm);
Association sa = tm.createAssociation(synonymTermType);
sa.addPlayer(termTopic, termComplexType);
sa.addPlayer(synonymTerm, synonymTermType);
}
}
}
if(!excludeAntonyms && data_antonyms != null && data_antonyms.length() > 0) {
String[] antonyms = data_antonyms.split(",");
for(int i=0; i<antonyms.length ; i++) {
String antonym = antonyms[i].trim();
if(antonym.length() > 0) {
Topic antonymTerm = getTermTopic( antonym, tm );
Topic antonymTermType = getAntonymTermType(tm);
Topic termComplexType = getTermComplexType(tm);
Association sa = tm.createAssociation(antonymTermType);
sa.addPlayer(termTopic, termComplexType);
sa.addPlayer(antonymTerm, antonymTermType);
}
}
}
}
}
}
catch(Exception e) {
parent.log(e);
}
state = STATE_RESULTS;
}
break;
}
case STATE_RESULTS_RESULT_TERM: {
if(qName.equals(TAG_TERM)) {
state = STATE_RESULTS_RESULT;
}
break;
}
case STATE_RESULTS_RESULT_DEFINITION: {
if(qName.equals(TAG_DEFINITION)) {
state = STATE_RESULTS_RESULT;
}
break;
}
case STATE_RESULTS_RESULT_PARTOFSPEECH: {
if(qName.equals(TAG_PARTOFSPEECH)) {
state = STATE_RESULTS_RESULT;
}
break;
}
case STATE_RESULTS_RESULT_EXAMPLE: {
if(qName.equals(TAG_EXAMPLE)) {
state = STATE_RESULTS_RESULT;
}
break;
}
case STATE_RESULTS_RESULT_SYNONYMS: {
if(qName.equals(TAG_SYNONYMS)) {
state = STATE_RESULTS_RESULT;
}
break;
}
case STATE_RESULTS_RESULT_ANTONYMS: {
if(qName.equals(TAG_ANTONYMS)) {
state = STATE_RESULTS_RESULT;
}
break;
}
}
}
public void characters(char[] ch, int start, int length) throws SAXException {
switch(state) {
case STATE_RESULTS_RESULT_TERM: {
data_term += new String(ch,start,length);
break;
}
case STATE_RESULTS_RESULT_DEFINITION: {
data_definition += new String(ch,start,length);
break;
}
case STATE_RESULTS_RESULT_PARTOFSPEECH: {
data_partofspeech += new String(ch,start,length);
break;
}
case STATE_RESULTS_RESULT_EXAMPLE: {
data_example += new String(ch,start,length);
break;
}
case STATE_RESULTS_RESULT_SYNONYMS: {
data_synonyms += new String(ch,start,length);
break;
}
case STATE_RESULTS_RESULT_ANTONYMS: {
data_antonyms += new String(ch,start,length);
break;
}
default:
break;
}
}
public void warning(SAXParseException exception) throws SAXException {
}
public void error(SAXParseException exception) throws SAXException {
parent.log("Error parsing XML document at "+exception.getLineNumber()+","+exception.getColumnNumber(),exception);
}
public void fatalError(SAXParseException exception) throws SAXException {
parent.log("Fatal error parsing XML document at "+exception.getLineNumber()+","+exception.getColumnNumber(),exception);
}
public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {}
public void processingInstruction(String target, String data) throws SAXException {}
public void startPrefixMapping(String prefix, String uri) throws SAXException {}
public void endPrefixMapping(String prefix) throws SAXException {}
public void setDocumentLocator(org.xml.sax.Locator locator) {}
public void skippedEntity(String name) throws SAXException {}
}
}
| 19,686 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
Stands4Extractor.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/stands4/Stands4Extractor.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
* Stands4Extractor.java
*
* Created on 25.3.2010
*/
package org.wandora.application.tools.extractors.stands4;
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;
/**
*
* @author akivela
*/
public class Stands4Extractor extends AbstractWandoraTool {
private static final long serialVersionUID = 1L;
private static Stands4Selector selector = null;
@Override
public String getName() {
return "Stands4 word describer";
}
@Override
public String getDescription(){
return "Describes given words using Stands4 web api.";
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/extract_stands4.png");
}
@Override
public WandoraToolType getType() {
return WandoraToolType.createExtractType();
}
public void execute(Wandora wandora, Context context) {
int counter = 0;
try {
if(selector == null) {
selector = new Stands4Selector(wandora);
}
selector.setAccepted(false);
selector.setWandora(wandora);
selector.setContext(context);
selector.setVisible(true);
if(selector.wasAccepted()) {
setDefaultLogger();
WandoraTool extractor = selector.getWandoraTool(this);
if(extractor != null) {
extractor.setToolLogger(getDefaultLogger());
extractor.execute(wandora, context);
}
}
else {
//log("User cancelled the extraction!");
}
}
catch(Exception e) {
singleLog(e);
}
if(selector != null && selector.wasAccepted()) setState(WAIT);
}
}
| 2,815 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
Stands4Selector.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/stands4/Stands4Selector.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
* Stands4Selector.java
*
* Created on 25.3.2010
*/
package org.wandora.application.tools.extractors.stands4;
import java.awt.Component;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import javax.swing.JDialog;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.simple.SimpleButton;
import org.wandora.application.gui.simple.SimpleCheckBox;
import org.wandora.application.gui.simple.SimpleField;
import org.wandora.application.gui.simple.SimpleLabel;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.Topic;
/**
*
* @author akivela
*/
public class Stands4Selector extends JDialog {
private static final long serialVersionUID = 1L;
public static String defaultLanguage = "en";
private static final String acronymsAPIURL = "http://www.abbreviations.com/services/v1/abbr.aspx?tokenid=__2__&term=__1__";
private static final String synonymsAPIURL = "http://www.abbreviations.com/services/v1/syno.aspx?tokenid=__2__&word=__1__";
private static final String definitionsAPIURL = "http://www.abbreviations.com/services/v1/defs.aspx?tokenid=__2__&word=__1__";
private Wandora wandora = null;
private Context context = null;
private boolean accepted = false;
/** Creates new form Stands4Selector */
public Stands4Selector(Wandora wandora) {
super(wandora, true);
initComponents();
setTitle("Stands4 extractor");
setSize(550,310);
wandora.centerWindow(this);
this.wandora = wandora;
accepted = false;
}
public void setWandora(Wandora wandora) {
this.wandora = wandora;
}
public void setContext(Context context) {
this.context = context;
}
public boolean wasAccepted() {
return accepted;
}
public void setAccepted(boolean b) {
accepted = b;
}
public WandoraTool getWandoraTool(WandoraTool parentTool) {
Component component = stands4TabbedPane.getSelectedComponent();
WandoraTool wt = null;
// ***** DESCRIBE *****
if(defineTab.equals(component)) {
String wordsAll = wordTextField.getText();
String[] words = urlEncode(newlineSplitter(wordsAll));
String apibase = null;
AbstractStands4Extractor ex = null;
if(acronymsCheckBox.isSelected()) {
apibase = acronymsAPIURL;
AbbreviationExtractor abex = new AbbreviationExtractor();
ex = abex;
parentTool.log("Selecting Abbreviation Extractor");
}
else {
parentTool.log("Selecting Synonym Extractor");
apibase = synonymsAPIURL;
SynonymExtractor syex = new SynonymExtractor();
if(!synonymsCheckBox.isSelected()) syex.excludeSynonyms(true);
if(!antonymsCheckBox.isSelected()) syex.excludeAntonyms(true);
if(!partOfSpeechCheckBox.isSelected()) syex.excludePartOfSpeech(true);
if(!definitionCheckBox.isSelected()) syex.excludeDefinition(true);
ex = syex;
}
if(apibase != null && ex != null) {
String apikey = ex.solveAPIKey(wandora);
if(apikey != null && apikey.length() > 0) {
String[] wordsUrls = completeString(apibase, words, apikey);
ex.setForceUrls( wordsUrls );
wt = ex;
}
else {
parentTool.log("Invalid api key. Aborting...");
}
}
}
// ***** EXACT URL *****
else if(urlTab.equals(component)) {
String url = urlField.getText();
AbstractStands4Extractor ex = null;
if(url.indexOf("abbr.aspx") != -1) {
ex = new AbbreviationExtractor();
}
else if(url.indexOf("syno.aspx") != -1) {
ex = new SynonymExtractor();
}
else if(url.indexOf("defs.aspx") != -1) {
ex = new DefinitionExtractor();
}
else {
ex = new AbbreviationExtractor();
}
ex.setForceUrls( new String[] { url } );
wt = ex;
}
return wt;
}
public String[] newlineSplitter(String str) {
if(str.indexOf('\n') != -1) {
String[] strs = str.split("\n");
ArrayList<String> strList = new ArrayList<String>();
String s = null;
for(int i=0; i<strs.length; i++) {
s = strs[i];
s = s.trim();
if(s.length() > 0) {
strList.add(s);
}
}
return strList.toArray( new String[] {} );
}
else {
return new String[] { str };
}
}
public String[] commaSplitter(String str) {
if(str.indexOf(',') != -1) {
String[] strs = str.split(",");
ArrayList<String> strList = new ArrayList<String>();
String s = null;
for(int i=0; i<strs.length; i++) {
s = strs[i];
s = s.trim();
if(s.length() > 0) {
strList.add(s);
}
}
return strList.toArray( new String[] {} );
}
else {
return new String[] { str };
}
}
public String[] completeString(String template, String[] strs) {
if(strs == null || template == null) return null;
String[] completed = new String[strs.length];
for(int i=0; i<strs.length; i++) {
completed[i] = template.replaceAll("__1__", strs[i]);
}
return completed;
}
public String[] completeString(String template, String[] strs1, String[] strs2) {
if(strs1 == null || strs2 == null || template == null) return null;
if(strs1.length != strs2.length) return null;
String[] completed = new String[strs1.length];
for(int i=0; i<strs1.length; i++) {
completed[i] = template.replaceAll("__1__", strs1[i]);
completed[i] = completed[i].replaceAll("__2__", strs2[i]);
}
return completed;
}
public String[] completeString(String template, String[] strs1, String strs2) {
if(strs1 == null || strs2 == null || template == null) return null;
String[] completed = new String[strs1.length];
for(int i=0; i<strs1.length; i++) {
completed[i] = template.replaceAll("__1__", strs1[i]);
completed[i] = completed[i].replaceAll("__2__", strs2);
}
return completed;
}
public String[] completeString(String template, String[] strs1, String strs2, String strs3) {
if(strs1 == null || strs2 == null || template == null) return null;
String[] completed = new String[strs1.length];
for(int i=0; i<strs1.length; i++) {
completed[i] = template.replaceAll("__1__", strs1[i]);
completed[i] = completed[i].replaceAll("__2__", strs2);
completed[i] = completed[i].replaceAll("__3__", strs3);
}
return completed;
}
public String[] urlEncode(String[] urls) {
if(urls == null) return null;
String[] cleanUrls = new String[urls.length];
for(int i=0; i<urls.length; i++) {
cleanUrls[i] = urlEncode(urls[i]);
}
return cleanUrls;
}
public String urlEncode(String url) {
try {
return URLEncoder.encode(url, "UTF-8");
}
catch(Exception e) {
return url;
}
}
public String getContextAsString() {
StringBuilder sb = new StringBuilder("");
if(context != null) {
try {
Iterator contextObjects = context.getContextObjects();
String str = null;
Object o = null;
while(contextObjects.hasNext()) {
str = null;
o = contextObjects.next();
if(o instanceof Topic) {
Topic t = (Topic) o;
//str = t.getBaseName();
str = t.getDisplayName("en");
if(str != null) {
str = str.trim();
}
}
if(str != null && str.length() > 0) {
sb.append(str);
if(contextObjects.hasNext()) {
sb.append(", ");
}
}
}
}
catch(Exception e) {
e.printStackTrace();
}
}
return sb.toString();
}
public String getContextAsSIs(String delim) {
StringBuffer sb = new StringBuffer("");
if(context != null) {
try {
Iterator contextObjects = context.getContextObjects();
String str = null;
Object o = null;
while(contextObjects.hasNext()) {
str = null;
o = contextObjects.next();
if(o instanceof Topic) {
Topic t = (Topic) o;
Collection<Locator> identifiers = t.getSubjectIdentifiers();
for( Iterator<Locator> iter = identifiers.iterator() ; iter.hasNext(); ) {
Locator identifier = iter.next();
if(identifier != null) {
str = identifier.toExternalForm().trim();
sb.append(str);
if(iter.hasNext()) sb.append(delim);
}
}
}
}
}
catch(Exception e) {
e.printStackTrace();
}
}
return sb.toString();
}
public String getContextAsSI() {
if(context != null) {
try {
Iterator contextObjects = context.getContextObjects();
String str = null;
Object o = null;
while(contextObjects.hasNext()) {
str = null;
o = contextObjects.next();
if(o instanceof Topic) {
Topic t = (Topic) o;
Collection<Locator> identifiers = t.getSubjectIdentifiers();
for( Iterator<Locator> iter = identifiers.iterator() ; iter.hasNext(); ) {
Locator identifier = iter.next();
if(identifier != null) {
str = identifier.toExternalForm().trim();
return str;
}
}
}
}
}
catch(Exception e) {
e.printStackTrace();
}
}
return "";
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
stands4TabbedPane = new org.wandora.application.gui.simple.SimpleTabbedPane();
defineTab = new javax.swing.JPanel();
defineInnerPanel = new javax.swing.JPanel();
defineLabel = new SimpleLabel();
definePanel = new javax.swing.JPanel();
wordLabel = new SimpleLabel();
wordTextField = new SimpleField();
acronymsCheckBox = new SimpleCheckBox();
jSeparator1 = new javax.swing.JSeparator();
definitionCheckBox = new SimpleCheckBox();
synonymsCheckBox = new SimpleCheckBox();
antonymsCheckBox = new SimpleCheckBox();
partOfSpeechCheckBox = new SimpleCheckBox();
jPanel1 = new javax.swing.JPanel();
defineButtonPanel = new javax.swing.JPanel();
getContextButton2Identifiers = new SimpleButton();
urlTab = new javax.swing.JPanel();
urlInnerPanel = new javax.swing.JPanel();
urlLabel = new org.wandora.application.gui.simple.SimpleLabel();
urlField = new org.wandora.application.gui.simple.SimpleField();
urlGetButton = new org.wandora.application.gui.simple.SimpleButton();
buttonPanel = new javax.swing.JPanel();
emptyPanel = new javax.swing.JPanel();
okButton = new org.wandora.application.gui.simple.SimpleButton();
cancelButton = new org.wandora.application.gui.simple.SimpleButton();
getContentPane().setLayout(new java.awt.GridBagLayout());
defineTab.setLayout(new java.awt.GridBagLayout());
defineInnerPanel.setLayout(new java.awt.GridBagLayout());
defineLabel.setText("<html>Describe given words using Stands4 web services.</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, 5, 0);
defineInnerPanel.add(defineLabel, gridBagConstraints);
definePanel.setLayout(new java.awt.GridBagLayout());
wordLabel.setText("Word");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 3, 5);
definePanel.add(wordLabel, gridBagConstraints);
wordTextField.setMinimumSize(new java.awt.Dimension(6, 21));
wordTextField.setPreferredSize(new java.awt.Dimension(6, 21));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 3, 0);
definePanel.add(wordTextField, gridBagConstraints);
acronymsCheckBox.setText("Word is an acronym, expand it. Selecting this option excludes other options.");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
definePanel.add(acronymsCheckBox, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
definePanel.add(jSeparator1, gridBagConstraints);
definitionCheckBox.setSelected(true);
definitionCheckBox.setText("Get definition for the word.");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
definePanel.add(definitionCheckBox, gridBagConstraints);
synonymsCheckBox.setSelected(true);
synonymsCheckBox.setText("Get synonyms for the word.");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
definePanel.add(synonymsCheckBox, gridBagConstraints);
antonymsCheckBox.setSelected(true);
antonymsCheckBox.setText("Get antonyms for the word.");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
definePanel.add(antonymsCheckBox, gridBagConstraints);
partOfSpeechCheckBox.setSelected(true);
partOfSpeechCheckBox.setText("Get part-of-speech for the word.");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
definePanel.add(partOfSpeechCheckBox, gridBagConstraints);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL;
gridBagConstraints.weighty = 1.0;
definePanel.add(jPanel1, 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(0, 0, 3, 0);
defineInnerPanel.add(definePanel, gridBagConstraints);
defineButtonPanel.setLayout(new java.awt.GridBagLayout());
getContextButton2Identifiers.setText("Get context");
getContextButton2Identifiers.setMargin(new java.awt.Insets(0, 6, 1, 6));
getContextButton2Identifiers.setMaximumSize(new java.awt.Dimension(90, 20));
getContextButton2Identifiers.setMinimumSize(new java.awt.Dimension(90, 20));
getContextButton2Identifiers.setPreferredSize(new java.awt.Dimension(90, 20));
getContextButton2Identifiers.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
getContextButton2MouseReleased(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 0);
defineButtonPanel.add(getContextButton2Identifiers, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
defineInnerPanel.add(defineButtonPanel, 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(6, 6, 6, 6);
defineTab.add(defineInnerPanel, gridBagConstraints);
stands4TabbedPane.addTab("Describe", defineTab);
urlTab.setLayout(new java.awt.GridBagLayout());
urlInnerPanel.setLayout(new java.awt.GridBagLayout());
urlLabel.setText("<html>Read given Stands4 web service feed. Given URL should resolve the feed.</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);
urlInnerPanel.add(urlLabel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
urlInnerPanel.add(urlField, gridBagConstraints);
urlGetButton.setLabel("Get context");
urlGetButton.setMargin(new java.awt.Insets(0, 2, 1, 2));
urlGetButton.setMaximumSize(new java.awt.Dimension(90, 20));
urlGetButton.setMinimumSize(new java.awt.Dimension(90, 20));
urlGetButton.setPreferredSize(new java.awt.Dimension(90, 20));
urlGetButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
urlGetButtonMouseReleased(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.insets = new java.awt.Insets(10, 5, 0, 0);
urlInnerPanel.add(urlGetButton, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10);
urlTab.add(urlInnerPanel, gridBagConstraints);
stands4TabbedPane.addTab("URL", urlTab);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
getContentPane().add(stands4TabbedPane, gridBagConstraints);
buttonPanel.setLayout(new java.awt.GridBagLayout());
emptyPanel.setPreferredSize(new java.awt.Dimension(100, 10));
javax.swing.GroupLayout emptyPanelLayout = new javax.swing.GroupLayout(emptyPanel);
emptyPanel.setLayout(emptyPanelLayout);
emptyPanelLayout.setHorizontalGroup(
emptyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 405, Short.MAX_VALUE)
);
emptyPanelLayout.setVerticalGroup(
emptyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 10, Short.MAX_VALUE)
);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
buttonPanel.add(emptyPanel, gridBagConstraints);
okButton.setText("Extract");
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);
}
});
okButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
okButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3);
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);
}
});
cancelButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridy = 0;
buttonPanel.add(cancelButton, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
getContentPane().add(buttonPanel, gridBagConstraints);
pack();
}// </editor-fold>//GEN-END:initComponents
private void okButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_okButtonMouseReleased
accepted = true;
setVisible(false);
}//GEN-LAST:event_okButtonMouseReleased
private void cancelButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cancelButtonMouseReleased
accepted = false;
setVisible(false);
}//GEN-LAST:event_cancelButtonMouseReleased
private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
accepted = true;
setVisible(false);
}//GEN-LAST:event_okButtonActionPerformed
private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
accepted = false;
setVisible(false);
}//GEN-LAST:event_cancelButtonActionPerformed
private void urlGetButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_urlGetButtonMouseReleased
urlField.setText(getContextAsSIs(", "));
}//GEN-LAST:event_urlGetButtonMouseReleased
private void getContextButton2MouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_getContextButton2MouseReleased
wordTextField.setText(getContextAsString());
}//GEN-LAST:event_getContextButton2MouseReleased
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JCheckBox acronymsCheckBox;
private javax.swing.JCheckBox antonymsCheckBox;
private javax.swing.JPanel buttonPanel;
private javax.swing.JButton cancelButton;
private javax.swing.JPanel defineButtonPanel;
private javax.swing.JPanel defineInnerPanel;
private javax.swing.JLabel defineLabel;
private javax.swing.JPanel definePanel;
private javax.swing.JPanel defineTab;
private javax.swing.JCheckBox definitionCheckBox;
private javax.swing.JPanel emptyPanel;
private javax.swing.JButton getContextButton2Identifiers;
private javax.swing.JPanel jPanel1;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JButton okButton;
private javax.swing.JCheckBox partOfSpeechCheckBox;
private javax.swing.JTabbedPane stands4TabbedPane;
private javax.swing.JCheckBox synonymsCheckBox;
private javax.swing.JTextField urlField;
private javax.swing.JButton urlGetButton;
private javax.swing.JPanel urlInnerPanel;
private javax.swing.JLabel urlLabel;
private javax.swing.JPanel urlTab;
private javax.swing.JLabel wordLabel;
private javax.swing.JTextField wordTextField;
// End of variables declaration//GEN-END:variables
}
| 28,185 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AbstractStands4Extractor.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/stands4/AbstractStands4Extractor.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.extractors.stands4;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import javax.swing.Icon;
import org.wandora.application.Wandora;
import org.wandora.application.gui.UIBox;
import org.wandora.application.gui.WandoraOptionPane;
import org.wandora.application.tools.extractors.AbstractExtractor;
import org.wandora.application.tools.extractors.ExtractHelper;
import org.wandora.topicmap.TMBox;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author akivela
*/
public abstract class AbstractStands4Extractor extends AbstractExtractor {
private static final long serialVersionUID = 1L;
protected String STANDS4_SI = "http://www.abbreviations.com/api.asp";
protected String SYNONYMS_BASE = "http://www.synonyms.net/";
protected String SYNONYMS_TERM_BASE = SYNONYMS_BASE+"synonym/";
protected String DEFINITIONS_BASE = "http://www.definitions.net/";
protected String DEFINITIONS_TERM_BASE = DEFINITIONS_BASE+"definition/";
protected String ABBREVIATIONS_BASE = "http://www.abbreviations.com/";
protected String ABBREVIATIONS_TERM_BASE = "http://www.abbreviations.com/bs.aspx?st=";
protected String CATEGORY_BASE = "http://www.abbreviations.com/acronyms/";
protected String ABBREVIATION_SI = ABBREVIATIONS_BASE;
protected String DEFINITION_SI = DEFINITIONS_BASE;
protected String CATEGORY_SI = CATEGORY_BASE+"category";
protected String PARTOFSPEECH_SI = SYNONYMS_BASE+"part-of-speech";
protected String EXAMPLE_SI = DEFINITIONS_BASE+"example";
protected String SIMILARTERM_SI = SYNONYMS_BASE+"similar-term";
protected String SYNONYMTERM_SI = SYNONYMS_BASE+"synonym-term";
protected String ANTONYMTERM_SI = SYNONYMS_BASE+"antonym-term";
protected String SOURCE_SI = "http://wandora.org/si/source";
protected String TERM_COMPLEX_BASE = "http://wandora.org/si/term-complex/";
protected String defaultEncoding = "ISO-8859-1";
protected String defaultLang = "en";
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/extract_stands4.png");
}
private final String[] contentTypes=new String[] { "text/xml", "application/xml" };
@Override
public String[] getContentTypes() {
return contentTypes;
}
@Override
public boolean useURLCrawler() {
return false;
}
// -------------------------------------------------------------------------
protected String solveQueryTerm( URL url ) {
String queryTerm = null;
String urlStr = url.toExternalForm();
int i = urlStr.indexOf("term=");
if(i != -1) {
urlStr = urlStr.substring(0, i);
i = urlStr.lastIndexOf("&");
if(i != -1) {
queryTerm = urlStr.substring(i+1);
try {
queryTerm = URLDecoder.decode(queryTerm, defaultEncoding);
}
catch(Exception e) {
// DO NOTHING...
}
}
}
return queryTerm;
}
// -------------------------------------------------------------------------
public abstract String getTermBase();
public abstract String getTermType();
public Topic getStands4Type(TopicMap tm) throws TopicMapException {
Topic type=getOrCreateTopic(tm, STANDS4_SI, "Stands4");
Topic wandoraClass = getWandoraClass(tm);
makeSubclassOf(tm, type, wandoraClass);
return type;
}
public Topic getAbbreviationType(TopicMap tm) throws TopicMapException {
Topic type = getOrCreateTopic(tm, ABBREVIATION_SI, "Abbreviation");
Topic superType = getStands4Type(tm);
makeSubclassOf(tm, type, superType);
return type;
}
// -------
public Topic getSimilarTermType(TopicMap tm) throws TopicMapException {
Topic type=getOrCreateTopic(tm, SIMILARTERM_SI, "Similar term");
Topic superType = getStands4Type(tm);
makeSubclassOf(tm, type, superType);
return type;
}
// -------
public Topic getExampleType(TopicMap tm) throws TopicMapException {
Topic type=getOrCreateTopic(tm, EXAMPLE_SI, "Example");
Topic superType = getStands4Type(tm);
makeSubclassOf(tm, type, superType);
return type;
}
// -------
public Topic getPartOfSpeechTopic(String p, TopicMap tm) throws TopicMapException {
if(p != null) {
p = p.trim();
if(p.length() > 0) {
Topic partOfSpeechTopic=getOrCreateTopic(tm, PARTOFSPEECH_SI+"/"+p, p);
Topic partOfSpeechTypeTopic = getPartOfSpeechType(tm);
partOfSpeechTopic.addType(partOfSpeechTypeTopic);
return partOfSpeechTopic;
}
}
return null;
}
public Topic getPartOfSpeechType(TopicMap tm) throws TopicMapException {
Topic type=getOrCreateTopic(tm, PARTOFSPEECH_SI, "Part of speech");
Topic superType = getStands4Type(tm);
makeSubclassOf(tm, type, superType);
return type;
}
// -------
public Topic getSynonymTermType(TopicMap tm) throws TopicMapException {
Topic type=getOrCreateTopic(tm, SYNONYMTERM_SI, "Synonym");
Topic superType = getStands4Type(tm);
makeSubclassOf(tm, type, superType);
return type;
}
// -------
public Topic getAntonymTermType(TopicMap tm) throws TopicMapException {
Topic type=getOrCreateTopic(tm, ANTONYMTERM_SI, "Antonym");
Topic superType = getStands4Type(tm);
makeSubclassOf(tm, type, superType);
return type;
}
// -------
public Topic getDefinitionTopic(String def, TopicMap tm) throws TopicMapException {
if(def != null) {
def = def.trim();
if(def.length() > 0) {
String si = null;
try {
si = DEFINITION_SI+"definition/"+URLEncoder.encode(def, defaultEncoding);
}
catch(Exception e) {
si = DEFINITION_SI+"definition/"+def;
}
Topic defTopic=getOrCreateTopic(tm, si, def);
Topic defTypeTopic = getDefinitionType(tm);
defTopic.addType(defTypeTopic);
return defTopic;
}
}
return null;
}
public Topic getDefinitionType(TopicMap tm) throws TopicMapException {
Topic type=getOrCreateTopic(tm, DEFINITION_SI, "Definition");
Topic superType = getStands4Type(tm);
makeSubclassOf(tm, type, superType);
return type;
}
// -------
public Topic getTermComplexTopic(String term, String def, TopicMap tm) throws TopicMapException {
if(term != null) {
term = term.trim();
if(def == null) def = "";
def = def.trim();
if(def.length()>50) def = def.substring(0,50)+"...";
if(term.length() > 0) {
String siTerm = term.replaceAll(", ", "_");
String si = null;
try {
si = TERM_COMPLEX_BASE+URLEncoder.encode(siTerm, defaultEncoding);
si = si + "#" + Math.abs(2*def.hashCode()+(def.hashCode()<0?1:0));
}
catch(Exception e) {
si = TERM_COMPLEX_BASE+siTerm+"#"+Math.abs(2*def.hashCode()+(def.hashCode()<0?1:0));
}
Topic termTopic=getOrCreateTopic(tm, si, term+" ("+def+")");
termTopic.setDisplayName("en", term);
Topic termTypeTopic = getTermComplexType(tm);
termTopic.addType(termTypeTopic);
return termTopic;
}
}
return null;
}
public Topic getTermComplexType(TopicMap tm) throws TopicMapException {
Topic type=getOrCreateTopic(tm, TERM_COMPLEX_BASE, "Term complex");
Topic superType = getStands4Type(tm);
makeSubclassOf(tm, type, superType);
return type;
}
// -------
// -------
public Topic getTermTopic(String term, TopicMap tm) throws TopicMapException {
if(term != null) {
term = term.trim();
if(term.length() > 0) {
String si = null;
try {
si = getTermBase()+URLEncoder.encode(term, defaultEncoding);
}
catch(Exception e) {
si = getTermBase()+term;
}
Topic termTopic=getOrCreateTopic(tm, si, term);
termTopic.setDisplayName("en", term);
Topic termTypeTopic = getTermType(tm);
termTopic.addType(termTypeTopic);
return termTopic;
}
}
return null;
}
public Topic getTermType(TopicMap tm) throws TopicMapException {
Topic type=getOrCreateTopic(tm, getTermType(), "Term");
Topic superType = getStands4Type(tm);
makeSubclassOf(tm, type, superType);
return type;
}
// -------
public Topic getCategoryType(TopicMap tm) throws TopicMapException {
Topic type=getOrCreateTopic(tm, CATEGORY_SI, "Category");
Topic superType = getStands4Type(tm);
makeSubclassOf(tm, type, superType);
return type;
}
public Topic getCategoryTopic(String cat, TopicMap tm) throws TopicMapException {
if(cat != null) {
cat = cat.trim();
if(cat.length() > 0) {
String si = null;
try {
si = CATEGORY_BASE+URLEncoder.encode(cat, defaultEncoding);
}
catch(Exception e) {
si = CATEGORY_BASE+cat;
}
Topic catTopic=getOrCreateTopic(tm, si, cat);
Topic catTypeTopic = getCategoryType(tm);
catTopic.addType(catTypeTopic);
return catTopic;
}
}
return null;
}
// ------------------------
public Topic getWandoraClass(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, TMBox.WANDORACLASS_SI,"Wandora class");
}
public Topic getSourceType(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, SOURCE_SI, "Source");
}
// --------
protected Topic getOrCreateTopic(TopicMap tm, String si) throws TopicMapException {
return getOrCreateTopic(tm, si, null);
}
protected Topic getOrCreateTopic(TopicMap tm, String si, String bn) throws TopicMapException {
return ExtractHelper.getOrCreateTopic(si, bn, tm);
}
protected void makeSubclassOf(TopicMap tm, Topic t, Topic superclass) throws TopicMapException {
ExtractHelper.makeSubclassOf(t, superclass, tm);
}
// -------------------------------------------------------------------------
private static String apikey = null;
protected String solveAPIKey(Wandora wandora) {
if(apikey == null) {
apikey = "";
apikey = WandoraOptionPane.showInputDialog(wandora, "Please give a valid apikey for Stands4. You can register your personal apikey at http://www.abbreviations.com/api.asp", apikey, "Stands4 apikey", WandoraOptionPane.QUESTION_MESSAGE);
}
return apikey;
}
public void forgetAuthorization() {
apikey = null;
}
}
| 12,438 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SparqlExtractorUI.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/sparql/SparqlExtractorUI.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* SparqlExtractorUI.java
*
* Created on 26.5.2011, 14:13:37
*/
package org.wandora.application.tools.extractors.sparql;
import java.awt.Component;
import java.awt.Desktop;
import java.net.URL;
import java.net.URLEncoder;
import javax.swing.JDialog;
import org.apache.jena.query.Query;
import org.apache.jena.query.QueryFactory;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.gui.UIBox;
import org.wandora.application.gui.WandoraOptionPane;
import org.wandora.application.gui.simple.SimpleButton;
import org.wandora.application.gui.simple.SimpleComboBox;
import org.wandora.application.gui.simple.SimpleField;
import org.wandora.application.gui.simple.SimpleLabel;
import org.wandora.application.gui.simple.SimpleScrollPane;
import org.wandora.application.gui.simple.SimpleTabbedPane;
import org.wandora.application.gui.simple.SimpleTextPane;
import org.wandora.utils.swing.TextLineNumber;
/**
*
* @author akivela
*/
public class SparqlExtractorUI extends javax.swing.JPanel {
private static final long serialVersionUID = 1L;
public static final String WIKIDATA_ENDPOINT = "https://query.wikidata.org/sparql";
public static final String EUROPEAN_OPEN_DATA_ENDPOINT = "http://open-data.europa.eu/sparqlep";
public static final String DBPEDIA_ENDPOINT = "http://dbpedia.org/sparql";
public static final String DATAGOVUK_ENDPOINT = "http://services.data.gov.uk/reference/sparql";
public static final String EUROPEANA_ENDPOINT = "http://europeana.ontotext.com/sparql.xml";
public String HRI_NAMESPACES = "PREFIX skos: <http://www.w3.org/2004/02/skos/core#>\n"+
"PREFIX dataset: <http://semantic.hri.fi/data/datasets#>\n"+
"PREFIX dc: <http://purl.org/dc/elements/1.1/>\n"+
"PREFIX stat: <http://data.mysema.com/schemas/stat#>\n"+
"PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n"+
"PREFIX dimension: <http://semantic.hri.fi/data/dimensions/>\n"+
"PREFIX geo: <http://www.w3.org/2003/01/geo/>\n"+
"PREFIX scv: <http://purl.org/NET/scovo#>\n"+
"PREFIX owl: <http://www.w3.org/2002/07/owl#>\n"+
"PREFIX dcterms: <http://purl.org/dc/terms/>\n"+
"PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>\n"+
"PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n"+
"PREFIX meta: <http://data.mysema.com/schemas/meta#>\n"+
"PREFIX rahoitusmuoto: <http://semantic.hri.fi/data/dimensions/Rahoitusmuoto#>\n"+
"PREFIX talotyyppi: <http://semantic.hri.fi/data/dimensions/Talotyyppi#>\n"+
"PREFIX alue: <http://semantic.hri.fi/data/dimensions/Alue#>\n"+
"PREFIX hallintaperuste: <http://semantic.hri.fi/data/dimensions/Hallintaperuste#>\n"+
"PREFIX vuosi: <http://semantic.hri.fi/data/dimensions/Vuosi#>\n"+
"PREFIX huoneistotyyppi: <http://semantic.hri.fi/data/dimensions/Huoneistotyyppi#>\n"+
"PREFIX yksikk�: <http://semantic.hri.fi/data/dimensions/Yksikk�#>\n"+
"PREFIX henkil�luku: <http://semantic.hri.fi/data/dimensions/Henkil�luku#>\n"+
"PREFIX ik�ryhm�: <http://semantic.hri.fi/data/dimensions/Ik�ryhm�#>\n"+
"PREFIX �idinkieli: <http://semantic.hri.fi/data/dimensions/�idinkieli#>\n"+
"PREFIX sukupuoli: <http://semantic.hri.fi/data/dimensions/Sukupuoli#>\n"+
"PREFIX ik�: <http://semantic.hri.fi/data/dimensions/Ik�#>\n"+
"PREFIX lasten_m��r�_perheess�_140-17v_15: <http://semantic.hri.fi/data/dimensions/Lasten_m��r�_perheess�_140-17v_15#>\n"+
"PREFIX perhetyyppi: <http://semantic.hri.fi/data/dimensions/Perhetyyppi#>\n"+
"PREFIX v�est�n_m��r�: <http://semantic.hri.fi/data/dimensions/V�est�n_m��r�#>\n"+
"PREFIX lasten_m��r�_perheess�: <http://semantic.hri.fi/data/dimensions/Lasten_m��r�_perheess�#>\n"+
"PREFIX muuttosuunta: <http://semantic.hri.fi/data/dimensions/Muuttosuunta#>\n"+
"PREFIX koulutusaste: <http://semantic.hri.fi/data/dimensions/Koulutusaste#>\n"+
"PREFIX toimiala: <http://semantic.hri.fi/data/dimensions/Toimiala#>\n"+
"PREFIX toimiala-1995: <http://semantic.hri.fi/data/dimensions/Toimiala-1995#>\n"+
"PREFIX ty�tt�myys: <http://semantic.hri.fi/data/dimensions/Ty�tt�myys#>\n"+
"PREFIX valmistumisvuosi: <http://semantic.hri.fi/data/dimensions/Valmistumisvuosi#>\n"+
"PREFIX k�yt�ss�olotilanne: <http://semantic.hri.fi/data/dimensions/K�yt�ss�olotilanne#>\n"+
"PREFIX k�ytt�tarkoitus_ja_kerrosluku: <http://semantic.hri.fi/data/dimensions/K�ytt�tarkoitus_ja_kerrosluku#>\n"+
"PREFIX tuloluokka: <http://semantic.hri.fi/data/dimensions/Tuloluokka#>\n"+
"PREFIX k�ytt�tarkoitus: <http://semantic.hri.fi/data/dimensions/K�ytt�tarkoitus#>\n"+
"PREFIX toimenpide: <http://semantic.hri.fi/data/dimensions/Toimenpide#>\n";
private static final String QUERY_MACRO = "__QUERY__";
private boolean accepted = false;
private JDialog dialog = null;
private Wandora wandora = null;
/** Creates new form SparqlExtractorUI */
public SparqlExtractorUI(Wandora w) {
wandora = w;
initComponents();
resultFormatComboBox.setEditable(false);
genericEncodingComboBox.setEditable(false);
// Add line number column to all query panels.
TextLineNumber wikidataLineNumbers = new TextLineNumber(wikidataQueryTextPane);
wikidataQueryScrollPane.setRowHeaderView( wikidataLineNumbers );
TextLineNumber datagovukLineNumbers = new TextLineNumber(datagovukQueryTextPane);
datagovukQueryScrollPane.setRowHeaderView( datagovukLineNumbers );
TextLineNumber europeanOpenDataLineNumbers = new TextLineNumber(europeanOpenDataQueryTextPane);
europeanOpenDataQueryScrollPane.setRowHeaderView( europeanOpenDataLineNumbers );
TextLineNumber dbpediaLineNumbers = new TextLineNumber(dbpediaQueryTextPane);
dbpediaQueryScrollPane.setRowHeaderView( dbpediaLineNumbers );
TextLineNumber genericLineNumbers = new TextLineNumber(genericQueryTextPane);
genericQueryScrollPane.setRowHeaderView( genericLineNumbers );
}
public boolean wasAccepted() {
return accepted;
}
public void setAccepted(boolean b) {
accepted = b;
}
public void open(Wandora w) {
accepted = false;
dialog = new JDialog(w, true);
dialog.setSize(800,500);
dialog.add(this);
dialog.setTitle("SPARQL extractor");
UIBox.centerWindow(dialog, w);
dialog.setVisible(true);
}
public String[] getQueryURLs(WandoraTool parentTool) {
return getQueryURLs();
}
public String[] getQueryURLs() {
Component component = tabbedPane.getSelectedComponent();
String[] q = null;
// ***** GENERIC *****
if(genericPanel.equals(component)) {
String query = prepareQuery(genericQueryTextPane.getText());
String queryURL = genericURLTextField.getText();
queryURL = queryURL.replace(QUERY_MACRO, query);
q = new String[] { queryURL };
}
// ***** DBPEDIA *****
else if(dbpediaPanel.equals(component)) {
String query = prepareQuery(dbpediaQueryTextPane.getText(), "UTF-8");
String queryURL = DBPEDIA_ENDPOINT+"?default-graph-uri=http%3A%2F%2Fdbpedia.org&query=__QUERY__&debug=on&timeout=&format=application%2Fsparql-results%2Bjson&save=display&fname=";
queryURL = queryURL.replace(QUERY_MACRO, query);
q = new String[] { queryURL };
}
// ***** HRI ***** / DEPRECATED
else if(hriPanel.equals(component)) {
String query = hriQueryTextPane.getText();
query = HRI_NAMESPACES + query;
query = prepareQuery(query, "UTF-8");
String queryURL = "http://semantic.hri.fi/sparql?query=__QUERY__";
queryURL = queryURL.replace(QUERY_MACRO, query);
q = new String[] { queryURL };
}
// ***** DATA.GOV.UK *****
else if(datagovukPanel.equals(component)) {
String query = datagovukQueryTextPane.getText();
query = prepareQuery(query, "UTF-8");
String queryURL = DATAGOVUK_ENDPOINT+"?query=__QUERY__";
queryURL = queryURL.replace(QUERY_MACRO, query);
q = new String[] { queryURL };
}
// ***** DATA.GOV ***** / DEPRECATED
else if(datagovPanel.equals(component)) {
String query = datagovQueryTextPane.getText();
query = prepareQuery(query, "UTF-8");
String queryURL = "http://services.data.gov/sparql?query=__QUERY__&format=application%2Fxml";
queryURL = queryURL.replace(QUERY_MACRO, query);
q = new String[] { queryURL };
}
// ***** EUROPEANA *****
else if(europeanaPanel.equals(component)) {
String query = europeanaQueryTextPane.getText();
query = prepareQuery(query, "UTF-8");
String queryURL = EUROPEANA_ENDPOINT+"?query=__QUERY__";
queryURL = queryURL.replace(QUERY_MACRO, query);
q = new String[] { queryURL };
}
// ***** EUROPEAN OPEN DATA *****
else if(europeanOpenDataPanel.equals(component)) {
String query = europeanOpenDataQueryTextPane.getText();
query = prepareQuery(query, "UTF-8");
String queryURL = EUROPEAN_OPEN_DATA_ENDPOINT+"?query=__QUERY__&format=application%2Fxml";
queryURL = queryURL.replace(QUERY_MACRO, query);
q = new String[] { queryURL };
}
// ***** WIKIDATA *****
else if(wikidataPanel.equals(component)) {
String query = wikidataQueryTextPane.getText();
query = prepareQuery(query, "UTF-8");
String queryURL = WIKIDATA_ENDPOINT+"?query=__QUERY__&format=json";
queryURL = queryURL.replace(QUERY_MACRO, query);
q = new String[] { queryURL };
}
return q;
}
public String getResultSetFormat() {
Component component = tabbedPane.getSelectedComponent();
if(genericPanel.equals(component)) {
return resultFormatComboBox.getSelectedItem().toString();
}
else if(dbpediaPanel.equals(component)) {
return "JSON";
}
else if(hriPanel.equals(component)) {
return "XML";
}
else if(datagovukPanel.equals(component)) {
return "XML";
}
else if(datagovPanel.equals(component)) {
return "XML";
}
else if(europeanaPanel.equals(component)) {
return "XML";
}
else if(europeanOpenDataPanel.equals(component)) {
return "XML";
}
return "JSON";
}
public String getHandleMethod() {
return "RESULTSET-TOPICMAP";
}
public String prepareQuery(String query) {
String encoding = genericEncodingComboBox.getSelectedItem().toString();
return prepareQuery(query, encoding);
}
public String prepareQuery(String query, String encoding) {
try {
//query = query.replace('\n', ' ');
//query = query.replace('\r', ' ');
//query = query.replace('\t', ' ');
if(!"no encoding".equalsIgnoreCase(encoding)) {
query = URLEncoder.encode(query, encoding);
}
}
catch(Exception e) {
e.printStackTrace();
}
return query;
}
public void checkSPARQLQuery(String query) {
try {
Query q = QueryFactory.create(query);
WandoraOptionPane.showMessageDialog(wandora, "SPARQL query successfully checked. Syntax OK.", "Syntax OK");
}
catch(Exception e) {
WandoraOptionPane.showMessageDialog(wandora, "Syntax Error: "+e.getMessage(), "Syntax Error");
//wandora.handleError(e);
}
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
disabledPanels = new javax.swing.JPanel();
hriPanel = new javax.swing.JPanel();
hriInnerPanel = new javax.swing.JPanel();
hriTitle = new SimpleLabel();
hriQueryScrollPane = new SimpleScrollPane();
hriQueryTextPane = new SimpleTextPane();
hriButtonPanel = new javax.swing.JPanel();
hriCheckButton = new SimpleButton();
datagovPanel = new javax.swing.JPanel();
datagovInnerPanel = new javax.swing.JPanel();
datagovTitle = new SimpleLabel();
datagovQueryScrollPane = new SimpleScrollPane();
datagovQueryTextPane = new SimpleTextPane();
datagovButtonPanel = new javax.swing.JPanel();
datagovCheckButton = new SimpleButton();
europeanaPanel = new javax.swing.JPanel();
europeanaInnerPanel = new javax.swing.JPanel();
europeanaTitle = new SimpleLabel();
europeanaQueryScrollPane = new SimpleScrollPane();
europeanaQueryTextPane = new SimpleTextPane();
europeanaButtonPanel = new javax.swing.JPanel();
europeanaCheckButton = new SimpleButton();
tabbedPane = new SimpleTabbedPane();
genericPanel = new javax.swing.JPanel();
genericPanelInner = new javax.swing.JPanel();
genericTitle = new SimpleLabel();
genericURLLabel = new SimpleLabel();
urlPanel = new javax.swing.JPanel();
genericURLTextField = new SimpleField();
genericQueryLabel = new SimpleLabel();
genericQueryScrollPane = new SimpleScrollPane();
genericQueryTextPane = new SimpleTextPane();
genericButtonPanel = new javax.swing.JPanel();
encodingLabel = new SimpleLabel();
genericEncodingComboBox = new SimpleComboBox();
resultFormatLabel = new SimpleLabel();
resultFormatComboBox = new SimpleComboBox();
jSeparator1 = new javax.swing.JSeparator();
showGenericButton = new SimpleButton();
checkGenericButton = new SimpleButton();
wikidataPanel = new javax.swing.JPanel();
wikidataInnerPanel = new javax.swing.JPanel();
wikidataTitle = new SimpleLabel();
wikidataQueryScrollPane = new SimpleScrollPane();
wikidataQueryTextPane = new SimpleTextPane();
wikidataButtonPanel = new javax.swing.JPanel();
wikidataCheckButton = new SimpleButton();
wikidataOpenEndPoint = new SimpleButton();
wikidataOpenQueryButton = new SimpleButton();
dbpediaPanel = new javax.swing.JPanel();
dbpediaInnerPanel = new javax.swing.JPanel();
dbpediaTitle = new SimpleLabel();
dbpediaQueryScrollPane = new SimpleScrollPane();
dbpediaQueryTextPane = new SimpleTextPane();
dbpediaButtonPanel = new javax.swing.JPanel();
dbpediaCheckButton = new SimpleButton();
dbpediaOpenEndPointButton = new SimpleButton();
dbpediaOpenQueryButton = new SimpleButton();
europeanOpenDataPanel = new javax.swing.JPanel();
europeanOpenDataInnerPanel = new javax.swing.JPanel();
europeanOpenDataTitle = new SimpleLabel();
europeanOpenDataQueryScrollPane = new SimpleScrollPane();
europeanOpenDataQueryTextPane = new SimpleTextPane();
europeanOpenDataButtonPanel = new javax.swing.JPanel();
europeanOpenDataCheckButton = new SimpleButton();
europeanOpenDataOpenEndPointButton = new SimpleButton();
europeanOpenDataOpenQueryButton = new SimpleButton();
datagovukPanel = new javax.swing.JPanel();
datagovukInnerPanel = new javax.swing.JPanel();
datagovukTitle = new SimpleLabel();
datagovukQueryScrollPane = new SimpleScrollPane();
datagovukQueryTextPane = new SimpleTextPane();
datagovukButtonPanel = new javax.swing.JPanel();
datagovukCheckButton = new SimpleButton();
datagovukOpenEndPointButton = new SimpleButton();
datagovukOpenQueryButton = new SimpleButton();
buttonPanel = new javax.swing.JPanel();
buttonFillerPanel = new javax.swing.JPanel();
okButton = new SimpleButton();
cancelButton = new SimpleButton();
hriPanel.setLayout(new java.awt.GridBagLayout());
hriInnerPanel.setLayout(new java.awt.GridBagLayout());
hriTitle.setText("<html>Write and send your SPARQL query to Helsinki Region Inforshare (HRI) SPARQL end point at http://semantic.hri.fi/sparql and transform result set to a topic map.</html>");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 8, 0);
hriInnerPanel.add(hriTitle, gridBagConstraints);
hriQueryTextPane.setText("SELECT ?area ?pred ?obj\nWHERE { \n ?area rdf:type dimension:Alue;\n ?pred ?obj.\n}");
hriQueryScrollPane.setViewportView(hriQueryTextPane);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
hriInnerPanel.add(hriQueryScrollPane, gridBagConstraints);
hriButtonPanel.setLayout(new java.awt.GridBagLayout());
hriCheckButton.setText("Check Query");
hriCheckButton.setMargin(new java.awt.Insets(0, 5, 0, 5));
hriCheckButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
hriCheckButtonMouseReleased(evt);
}
});
hriButtonPanel.add(hriCheckButton, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 0, 0, 0);
hriInnerPanel.add(hriButtonPanel, 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(4, 4, 4, 4);
hriPanel.add(hriInnerPanel, gridBagConstraints);
datagovPanel.setLayout(new java.awt.GridBagLayout());
datagovInnerPanel.setLayout(new java.awt.GridBagLayout());
datagovTitle.setText("Write and send SPARQL query to data.gov's SPARQL end point and transform result set to a topic map.");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 8, 0);
datagovInnerPanel.add(datagovTitle, gridBagConstraints);
datagovQueryTextPane.setText("select distinct ?Concept where {[] a ?Concept}");
datagovQueryScrollPane.setViewportView(datagovQueryTextPane);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
datagovInnerPanel.add(datagovQueryScrollPane, gridBagConstraints);
datagovButtonPanel.setLayout(new java.awt.GridBagLayout());
datagovCheckButton.setText("Check Query");
datagovCheckButton.setMargin(new java.awt.Insets(0, 5, 0, 5));
datagovCheckButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
datagovCheckButtonMouseReleased(evt);
}
});
datagovButtonPanel.add(datagovCheckButton, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 0, 0, 0);
datagovInnerPanel.add(datagovButtonPanel, 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(4, 4, 4, 4);
datagovPanel.add(datagovInnerPanel, gridBagConstraints);
europeanaPanel.setLayout(new java.awt.GridBagLayout());
europeanaInnerPanel.setLayout(new java.awt.GridBagLayout());
europeanaTitle.setText("<html>Write and send query to Europeana's SPARQL end point at http://europeana.ontotext.com/sparql and transform result set to a topic map.</html>");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 8, 0);
europeanaInnerPanel.add(europeanaTitle, gridBagConstraints);
europeanaQueryTextPane.setText("# Creators and collections of Europeana objects from Italy\n\nPREFIX dc: <http://purl.org/dc/elements/1.1/>\nPREFIX edm: <http://www.europeana.eu/schemas/edm/>\n\nSELECT DISTINCT ?EuropeanaObject ?Creator ?Collection\nWHERE {\n?EuropeanaObject dc:creator ?Creator ;\n edm:collectionName ?Collection ;\n edm:country \"italy\"\n}\nLIMIT 100");
europeanaQueryScrollPane.setViewportView(europeanaQueryTextPane);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
europeanaInnerPanel.add(europeanaQueryScrollPane, gridBagConstraints);
europeanaButtonPanel.setLayout(new java.awt.GridBagLayout());
europeanaCheckButton.setText("Check Query");
europeanaCheckButton.setMargin(new java.awt.Insets(0, 5, 0, 5));
europeanaCheckButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
europeanaCheckButtonMouseReleased(evt);
}
});
europeanaButtonPanel.add(europeanaCheckButton, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 0, 0, 0);
europeanaInnerPanel.add(europeanaButtonPanel, 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(4, 4, 4, 4);
europeanaPanel.add(europeanaInnerPanel, gridBagConstraints);
javax.swing.GroupLayout disabledPanelsLayout = new javax.swing.GroupLayout(disabledPanels);
disabledPanels.setLayout(disabledPanelsLayout);
disabledPanelsLayout.setHorizontalGroup(
disabledPanelsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
.addGroup(disabledPanelsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(disabledPanelsLayout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(hriPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 571, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
.addGroup(disabledPanelsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(disabledPanelsLayout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(datagovPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 571, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
.addGroup(disabledPanelsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(disabledPanelsLayout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(europeanaPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 571, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
);
disabledPanelsLayout.setVerticalGroup(
disabledPanelsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
.addGroup(disabledPanelsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(disabledPanelsLayout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(hriPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 311, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
.addGroup(disabledPanelsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(disabledPanelsLayout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(datagovPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 311, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
.addGroup(disabledPanelsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(disabledPanelsLayout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(europeanaPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 311, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
);
setLayout(new java.awt.GridBagLayout());
genericPanel.setLayout(new java.awt.GridBagLayout());
genericPanelInner.setLayout(new java.awt.GridBagLayout());
genericTitle.setText("<html>This tab is used to send SPARQL queries to a given endpoint and transform the result set to a topic map. Fill in the endpoint URL and the query. Use special keyword '__QUERY__' to mark the query location in the URL.</html>");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 8, 0);
genericPanelInner.add(genericTitle, gridBagConstraints);
genericURLLabel.setText("URL");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(4, 8, 4, 0);
genericPanelInner.add(genericURLLabel, gridBagConstraints);
urlPanel.setLayout(new java.awt.BorderLayout(4, 0));
genericURLTextField.setText("http://dbpedia.org/sparql?default-graph-uri=http%3A%2F%2Fdbpedia.org&query=__QUERY__&debug=on&timeout=&format=application%2Fsparql-results%2Bjson&save=display&fname=");
urlPanel.add(genericURLTextField, java.awt.BorderLayout.CENTER);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 2, 0);
genericPanelInner.add(urlPanel, gridBagConstraints);
genericQueryLabel.setText("Query");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(2, 8, 2, 0);
genericPanelInner.add(genericQueryLabel, gridBagConstraints);
genericQueryTextPane.setFont(new java.awt.Font("Monospaced", 0, 12)); // NOI18N
genericQueryTextPane.setText("SELECT DISTINCT ?Concept WHERE {[] a ?Concept}");
genericQueryScrollPane.setViewportView(genericQueryTextPane);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 2, 0);
genericPanelInner.add(genericQueryScrollPane, 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(4, 4, 4, 4);
genericPanel.add(genericPanelInner, gridBagConstraints);
genericButtonPanel.setLayout(new java.awt.GridBagLayout());
encodingLabel.setText("Encoding");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 8, 0, 2);
genericButtonPanel.add(encodingLabel, gridBagConstraints);
genericEncodingComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "UTF-8", "ISO-8859-1", "No encoding" }));
genericEncodingComboBox.setPreferredSize(new java.awt.Dimension(80, 23));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 8);
genericButtonPanel.add(genericEncodingComboBox, gridBagConstraints);
resultFormatLabel.setText("Result format");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 2);
genericButtonPanel.add(resultFormatLabel, gridBagConstraints);
resultFormatComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "JSON", "XML", "RDF/XML" }));
resultFormatComboBox.setPreferredSize(new java.awt.Dimension(80, 23));
genericButtonPanel.add(resultFormatComboBox, new java.awt.GridBagConstraints());
jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 10, 4, 10);
genericButtonPanel.add(jSeparator1, gridBagConstraints);
showGenericButton.setText("Open query URL");
showGenericButton.setMargin(new java.awt.Insets(2, 5, 2, 5));
showGenericButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
showGenericButtonMouseReleased(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4);
genericButtonPanel.add(showGenericButton, gridBagConstraints);
checkGenericButton.setText("Check query");
checkGenericButton.setMargin(new java.awt.Insets(2, 5, 2, 5));
checkGenericButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
checkGenericButtonMouseReleased(evt);
}
});
genericButtonPanel.add(checkGenericButton, 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);
genericPanel.add(genericButtonPanel, gridBagConstraints);
tabbedPane.addTab("Generic", genericPanel);
wikidataPanel.setLayout(new java.awt.GridBagLayout());
wikidataInnerPanel.setLayout(new java.awt.GridBagLayout());
wikidataTitle.setText("<html>Query the Wikidata's SPARQL endpoint at https://query.wikidata.org/sparql.</html>");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 8, 0);
wikidataInnerPanel.add(wikidataTitle, gridBagConstraints);
wikidataQueryTextPane.setFont(new java.awt.Font("Monospaced", 0, 12)); // NOI18N
wikidataQueryTextPane.setText("PREFIX wikibase: <http://wikiba.se/ontology#>\nPREFIX wd: <http://www.wikidata.org/entity/> \nPREFIX wdt: <http://www.wikidata.org/prop/direct/>\nPREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\nPREFIX p: <http://www.wikidata.org/prop/>\nPREFIX v: <http://www.wikidata.org/prop/statement/>\n\nSELECT ?p ?pLabel ?w ?wLabel WHERE {\n wd:Q30 p:P6/v:P6 ?p .\n ?p wdt:P26 ?w .\n SERVICE wikibase:label {\n bd:serviceParam wikibase:language \"en\" .\n }\n }");
wikidataQueryScrollPane.setViewportView(wikidataQueryTextPane);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
wikidataInnerPanel.add(wikidataQueryScrollPane, gridBagConstraints);
wikidataButtonPanel.setLayout(new java.awt.GridBagLayout());
wikidataCheckButton.setText("Check query");
wikidataCheckButton.setMargin(new java.awt.Insets(2, 8, 2, 8));
wikidataCheckButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
wikidataCheckButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 2);
wikidataButtonPanel.add(wikidataCheckButton, gridBagConstraints);
wikidataOpenEndPoint.setText("Open endpoint URL");
wikidataOpenEndPoint.setMargin(new java.awt.Insets(2, 8, 2, 8));
wikidataOpenEndPoint.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
wikidataOpenEndPointActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 2);
wikidataButtonPanel.add(wikidataOpenEndPoint, gridBagConstraints);
wikidataOpenQueryButton.setText("Open query URL");
wikidataOpenQueryButton.setMargin(new java.awt.Insets(2, 8, 2, 8));
wikidataOpenQueryButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
openQueryUrl(evt);
}
});
wikidataButtonPanel.add(wikidataOpenQueryButton, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 0, 0, 0);
wikidataInnerPanel.add(wikidataButtonPanel, 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(4, 4, 4, 4);
wikidataPanel.add(wikidataInnerPanel, gridBagConstraints);
tabbedPane.addTab("Wikidata", wikidataPanel);
dbpediaPanel.setLayout(new java.awt.GridBagLayout());
dbpediaInnerPanel.setLayout(new java.awt.GridBagLayout());
dbpediaTitle.setText("<html>Query the SPARQL endpoit of DBPedia at http://dbpedia.org/sparql.</html>");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 8, 0);
dbpediaInnerPanel.add(dbpediaTitle, gridBagConstraints);
dbpediaQueryTextPane.setFont(new java.awt.Font("Monospaced", 0, 12)); // NOI18N
dbpediaQueryTextPane.setText("SELECT DISTINCT ?Concept WHERE {[] a ?Concept}");
dbpediaQueryScrollPane.setViewportView(dbpediaQueryTextPane);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
dbpediaInnerPanel.add(dbpediaQueryScrollPane, gridBagConstraints);
dbpediaButtonPanel.setLayout(new java.awt.GridBagLayout());
dbpediaCheckButton.setText("Check query");
dbpediaCheckButton.setMargin(new java.awt.Insets(2, 8, 2, 8));
dbpediaCheckButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
dbpediaCheckButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 2);
dbpediaButtonPanel.add(dbpediaCheckButton, gridBagConstraints);
dbpediaOpenEndPointButton.setText("Open endpoint URL");
dbpediaOpenEndPointButton.setMargin(new java.awt.Insets(2, 8, 2, 8));
dbpediaOpenEndPointButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
dbpediaOpenEndPointButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 2);
dbpediaButtonPanel.add(dbpediaOpenEndPointButton, gridBagConstraints);
dbpediaOpenQueryButton.setText("Open query URL");
dbpediaOpenQueryButton.setMargin(new java.awt.Insets(2, 8, 2, 8));
dbpediaOpenQueryButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
openQueryUrl(evt);
}
});
dbpediaButtonPanel.add(dbpediaOpenQueryButton, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 0, 0, 0);
dbpediaInnerPanel.add(dbpediaButtonPanel, 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(4, 4, 4, 4);
dbpediaPanel.add(dbpediaInnerPanel, gridBagConstraints);
tabbedPane.addTab("DBPedia", dbpediaPanel);
europeanOpenDataPanel.setLayout(new java.awt.GridBagLayout());
europeanOpenDataInnerPanel.setLayout(new java.awt.GridBagLayout());
europeanOpenDataTitle.setText("<html>Query the European Union Open Data Portal SPARQL endpoint at http://open-data.europa.eu/sparqlep.</html>");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 8, 0);
europeanOpenDataInnerPanel.add(europeanOpenDataTitle, gridBagConstraints);
europeanOpenDataQueryTextPane.setFont(new java.awt.Font("Monospaced", 0, 12)); // NOI18N
europeanOpenDataQueryTextPane.setText("PREFIX dcat: <http://www.w3.org/ns/dcat#>\nPREFIX odp: <http://open-data.europa.eu/ontologies/ec-odp#>\nPREFIX dc: <http://purl.org/dc/terms/>\nPREFIX xsd: <http://www.w3.org/2001/XMLSchema#>\nPREFIX foaf: <http://xmlns.com/foaf/0.1/>\n\nSELECT DISTINCT ?g ?o WHERE { graph ?g {?s dc:title ?o. filter regex(?o, 'Statistics', 'i') } } LIMIT 10");
europeanOpenDataQueryScrollPane.setViewportView(europeanOpenDataQueryTextPane);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
europeanOpenDataInnerPanel.add(europeanOpenDataQueryScrollPane, gridBagConstraints);
europeanOpenDataButtonPanel.setLayout(new java.awt.GridBagLayout());
europeanOpenDataCheckButton.setText("Check query");
europeanOpenDataCheckButton.setMargin(new java.awt.Insets(2, 8, 2, 8));
europeanOpenDataCheckButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
europeanOpenDataCheckButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 2);
europeanOpenDataButtonPanel.add(europeanOpenDataCheckButton, gridBagConstraints);
europeanOpenDataOpenEndPointButton.setText("Open endpoint URL");
europeanOpenDataOpenEndPointButton.setMargin(new java.awt.Insets(2, 8, 2, 8));
europeanOpenDataOpenEndPointButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
europeanOpenDataOpenEndPointButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 2);
europeanOpenDataButtonPanel.add(europeanOpenDataOpenEndPointButton, gridBagConstraints);
europeanOpenDataOpenQueryButton.setText("Open query URL");
europeanOpenDataOpenQueryButton.setMargin(new java.awt.Insets(2, 8, 2, 8));
europeanOpenDataOpenQueryButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
openQueryUrl(evt);
}
});
europeanOpenDataButtonPanel.add(europeanOpenDataOpenQueryButton, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 0, 0, 0);
europeanOpenDataInnerPanel.add(europeanOpenDataButtonPanel, 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(4, 4, 4, 4);
europeanOpenDataPanel.add(europeanOpenDataInnerPanel, gridBagConstraints);
tabbedPane.addTab("open-data.europa.eu", europeanOpenDataPanel);
datagovukPanel.setLayout(new java.awt.GridBagLayout());
datagovukInnerPanel.setLayout(new java.awt.GridBagLayout());
datagovukTitle.setText("Query the SPARQL endpoint of data.gov.uk.");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 8, 0);
datagovukInnerPanel.add(datagovukTitle, gridBagConstraints);
datagovukQueryTextPane.setFont(new java.awt.Font("Monospaced", 0, 12)); // NOI18N
datagovukQueryTextPane.setText("PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\nPREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\nPREFIX xsd: <http://www.w3.org/2001/XMLSchema#>\nPREFIX owl: <http://www.w3.org/2002/07/owl#>\nPREFIX skos: <http://www.w3.org/2004/02/skos/core#>\n\nSELECT DISTINCT ?type\n WHERE {\n ?thing a ?type\n } LIMIT 10");
datagovukQueryScrollPane.setViewportView(datagovukQueryTextPane);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
datagovukInnerPanel.add(datagovukQueryScrollPane, gridBagConstraints);
datagovukButtonPanel.setLayout(new java.awt.GridBagLayout());
datagovukCheckButton.setText("Check query");
datagovukCheckButton.setMargin(new java.awt.Insets(2, 8, 2, 8));
datagovukCheckButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
datagovukCheckButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 2);
datagovukButtonPanel.add(datagovukCheckButton, gridBagConstraints);
datagovukOpenEndPointButton.setText("Open endpoint URL");
datagovukOpenEndPointButton.setMargin(new java.awt.Insets(2, 8, 2, 8));
datagovukOpenEndPointButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
datagovukOpenEndPointButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 2);
datagovukButtonPanel.add(datagovukOpenEndPointButton, gridBagConstraints);
datagovukOpenQueryButton.setText("Open query URL");
datagovukOpenQueryButton.setMargin(new java.awt.Insets(2, 8, 2, 8));
datagovukOpenQueryButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
openQueryUrl(evt);
}
});
datagovukButtonPanel.add(datagovukOpenQueryButton, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 0, 0, 0);
datagovukInnerPanel.add(datagovukButtonPanel, 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(4, 4, 4, 4);
datagovukPanel.add(datagovukInnerPanel, gridBagConstraints);
tabbedPane.addTab("data.gov.uk", datagovukPanel);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(tabbedPane, gridBagConstraints);
buttonPanel.setLayout(new java.awt.GridBagLayout());
buttonFillerPanel.setPreferredSize(new java.awt.Dimension(415, 20));
javax.swing.GroupLayout buttonFillerPanelLayout = new javax.swing.GroupLayout(buttonFillerPanel);
buttonFillerPanel.setLayout(buttonFillerPanelLayout);
buttonFillerPanelLayout.setHorizontalGroup(
buttonFillerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 430, Short.MAX_VALUE)
);
buttonFillerPanelLayout.setVerticalGroup(
buttonFillerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 20, Short.MAX_VALUE)
);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
buttonPanel.add(buttonFillerPanel, gridBagConstraints);
okButton.setText("Extract");
okButton.setMargin(new java.awt.Insets(2, 2, 2, 2));
okButton.setMaximumSize(new java.awt.Dimension(70, 23));
okButton.setMinimumSize(new java.awt.Dimension(70, 23));
okButton.setPreferredSize(new java.awt.Dimension(70, 23));
okButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
okButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3);
buttonPanel.add(okButton, gridBagConstraints);
cancelButton.setText("Close");
cancelButton.setMargin(new java.awt.Insets(2, 2, 2, 2));
cancelButton.setMaximumSize(new java.awt.Dimension(70, 23));
cancelButton.setMinimumSize(new java.awt.Dimension(70, 23));
cancelButton.setPreferredSize(new java.awt.Dimension(70, 23));
cancelButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelButtonActionPerformed(evt);
}
});
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 checkGenericButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_checkGenericButtonMouseReleased
checkSPARQLQuery(genericQueryTextPane.getText());
}//GEN-LAST:event_checkGenericButtonMouseReleased
private void showGenericButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_showGenericButtonMouseReleased
try {
String query = prepareQuery(genericQueryTextPane.getText());
String queryURL = genericURLTextField.getText();
queryURL = queryURL.replace(QUERY_MACRO, query);
Desktop.getDesktop().browse(new URL(queryURL).toURI());
}
catch(Exception e) {
WandoraOptionPane.showMessageDialog(wandora, "Error: "+e.getMessage(), "Error occurred");
}
}//GEN-LAST:event_showGenericButtonMouseReleased
private void hriCheckButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_hriCheckButtonMouseReleased
checkSPARQLQuery(hriQueryTextPane.getText());
}//GEN-LAST:event_hriCheckButtonMouseReleased
private void datagovCheckButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_datagovCheckButtonMouseReleased
checkSPARQLQuery(datagovQueryTextPane.getText());
}//GEN-LAST:event_datagovCheckButtonMouseReleased
private void europeanaCheckButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_europeanaCheckButtonMouseReleased
checkSPARQLQuery(europeanaQueryTextPane.getText());
}//GEN-LAST:event_europeanaCheckButtonMouseReleased
private void datagovukCheckButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_datagovukCheckButtonActionPerformed
checkSPARQLQuery(datagovukQueryTextPane.getText());
}//GEN-LAST:event_datagovukCheckButtonActionPerformed
private void datagovukOpenEndPointButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_datagovukOpenEndPointButtonActionPerformed
openUrl(DATAGOVUK_ENDPOINT);
}//GEN-LAST:event_datagovukOpenEndPointButtonActionPerformed
private void europeanOpenDataCheckButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_europeanOpenDataCheckButtonActionPerformed
checkSPARQLQuery(europeanOpenDataQueryTextPane.getText());
}//GEN-LAST:event_europeanOpenDataCheckButtonActionPerformed
private void europeanOpenDataOpenEndPointButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_europeanOpenDataOpenEndPointButtonActionPerformed
openUrl(EUROPEAN_OPEN_DATA_ENDPOINT);
}//GEN-LAST:event_europeanOpenDataOpenEndPointButtonActionPerformed
private void dbpediaCheckButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dbpediaCheckButtonActionPerformed
checkSPARQLQuery(dbpediaQueryTextPane.getText());
}//GEN-LAST:event_dbpediaCheckButtonActionPerformed
private void dbpediaOpenEndPointButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dbpediaOpenEndPointButtonActionPerformed
openUrl(DBPEDIA_ENDPOINT);
}//GEN-LAST:event_dbpediaOpenEndPointButtonActionPerformed
private void wikidataCheckButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_wikidataCheckButtonActionPerformed
checkSPARQLQuery(wikidataQueryTextPane.getText());
}//GEN-LAST:event_wikidataCheckButtonActionPerformed
private void wikidataOpenEndPointActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_wikidataOpenEndPointActionPerformed
openUrl(WIKIDATA_ENDPOINT);
}//GEN-LAST:event_wikidataOpenEndPointActionPerformed
private void openQueryUrl(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openQueryUrl
String[] queryUrls = getQueryURLs();
if(queryUrls != null) {
for(String url : queryUrls) {
if(url != null) {
openUrl(url);
}
}
}
}//GEN-LAST:event_openQueryUrl
private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
accepted = false;
if(dialog != null) dialog.setVisible(false);
}//GEN-LAST:event_cancelButtonActionPerformed
private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
accepted = true;
if(dialog != null) dialog.setVisible(false);
}//GEN-LAST:event_okButtonActionPerformed
private void openUrl(String url) {
try {
Desktop desktop = Desktop.getDesktop();
desktop.browse(new URL(url).toURI());
}
catch(Exception e) {
e.printStackTrace();
}
}
// 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.JButton checkGenericButton;
private javax.swing.JPanel datagovButtonPanel;
private javax.swing.JButton datagovCheckButton;
private javax.swing.JPanel datagovInnerPanel;
private javax.swing.JPanel datagovPanel;
private javax.swing.JScrollPane datagovQueryScrollPane;
private javax.swing.JTextPane datagovQueryTextPane;
private javax.swing.JLabel datagovTitle;
private javax.swing.JPanel datagovukButtonPanel;
private javax.swing.JButton datagovukCheckButton;
private javax.swing.JPanel datagovukInnerPanel;
private javax.swing.JButton datagovukOpenEndPointButton;
private javax.swing.JButton datagovukOpenQueryButton;
private javax.swing.JPanel datagovukPanel;
private javax.swing.JScrollPane datagovukQueryScrollPane;
private javax.swing.JTextPane datagovukQueryTextPane;
private javax.swing.JLabel datagovukTitle;
private javax.swing.JPanel dbpediaButtonPanel;
private javax.swing.JButton dbpediaCheckButton;
private javax.swing.JPanel dbpediaInnerPanel;
private javax.swing.JButton dbpediaOpenEndPointButton;
private javax.swing.JButton dbpediaOpenQueryButton;
private javax.swing.JPanel dbpediaPanel;
private javax.swing.JScrollPane dbpediaQueryScrollPane;
private javax.swing.JTextPane dbpediaQueryTextPane;
private javax.swing.JLabel dbpediaTitle;
private javax.swing.JPanel disabledPanels;
private javax.swing.JLabel encodingLabel;
private javax.swing.JPanel europeanOpenDataButtonPanel;
private javax.swing.JButton europeanOpenDataCheckButton;
private javax.swing.JPanel europeanOpenDataInnerPanel;
private javax.swing.JButton europeanOpenDataOpenEndPointButton;
private javax.swing.JButton europeanOpenDataOpenQueryButton;
private javax.swing.JPanel europeanOpenDataPanel;
private javax.swing.JScrollPane europeanOpenDataQueryScrollPane;
private javax.swing.JTextPane europeanOpenDataQueryTextPane;
private javax.swing.JLabel europeanOpenDataTitle;
private javax.swing.JPanel europeanaButtonPanel;
private javax.swing.JButton europeanaCheckButton;
private javax.swing.JPanel europeanaInnerPanel;
private javax.swing.JPanel europeanaPanel;
private javax.swing.JScrollPane europeanaQueryScrollPane;
private javax.swing.JTextPane europeanaQueryTextPane;
private javax.swing.JLabel europeanaTitle;
private javax.swing.JPanel genericButtonPanel;
private javax.swing.JComboBox genericEncodingComboBox;
private javax.swing.JPanel genericPanel;
private javax.swing.JPanel genericPanelInner;
private javax.swing.JLabel genericQueryLabel;
private javax.swing.JScrollPane genericQueryScrollPane;
private javax.swing.JTextPane genericQueryTextPane;
private javax.swing.JLabel genericTitle;
private javax.swing.JLabel genericURLLabel;
private javax.swing.JTextField genericURLTextField;
private javax.swing.JPanel hriButtonPanel;
private javax.swing.JButton hriCheckButton;
private javax.swing.JPanel hriInnerPanel;
private javax.swing.JPanel hriPanel;
private javax.swing.JScrollPane hriQueryScrollPane;
private javax.swing.JTextPane hriQueryTextPane;
private javax.swing.JLabel hriTitle;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JButton okButton;
private javax.swing.JComboBox resultFormatComboBox;
private javax.swing.JLabel resultFormatLabel;
private javax.swing.JButton showGenericButton;
private javax.swing.JTabbedPane tabbedPane;
private javax.swing.JPanel urlPanel;
private javax.swing.JPanel wikidataButtonPanel;
private javax.swing.JButton wikidataCheckButton;
private javax.swing.JPanel wikidataInnerPanel;
private javax.swing.JButton wikidataOpenEndPoint;
private javax.swing.JButton wikidataOpenQueryButton;
private javax.swing.JPanel wikidataPanel;
private javax.swing.JScrollPane wikidataQueryScrollPane;
private javax.swing.JTextPane wikidataQueryTextPane;
private javax.swing.JLabel wikidataTitle;
// End of variables declaration//GEN-END:variables
}
| 63,179 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SparqlExtractor.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/sparql/SparqlExtractor.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* SparqlExtractorUI.java
*/
package org.wandora.application.tools.extractors.sparql;
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 java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.swing.Icon;
import org.apache.jena.query.QuerySolution;
import org.apache.jena.query.ResultSet;
import org.apache.jena.query.ResultSetFactory;
// import com.hp.hpl.jena.sparql.resultset.JSONInput;
import org.apache.jena.rdf.model.Literal;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.Property;
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.apache.jena.sparql.resultset.RDFOutput;
/*
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.query.ResultSetFactory;
import com.hp.hpl.jena.query.ResultSetFormatter;
//import com.hp.hpl.jena.query.QuerySolution;
//import com.hp.hpl.jena.query.ResultSet;
//import com.hp.hpl.jena.query.ResultSetFactory;
//import com.hp.hpl.jena.query.ResultSetFormatter;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.StmtIterator;
//import com.hp.hpl.jena.sparql.resultset.JSONInput;
// import com.hp.hpl.jena.sparql.resultset.ResultsFormat;
//import com.hp.hpl.jena.sparql.resultset.ResultsFormat;
import com.hp.hpl.jena.sparql.resultset.JSONInput;
import com.hp.hpl.jena.sparql.resultset.ResultsFormat;
*/
import org.wandora.application.Wandora;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.UIBox;
import org.wandora.application.tools.extractors.AbstractExtractor;
import org.wandora.application.tools.extractors.rdf.rdfmappings.RDF2TopicMapsMapping;
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.Tuples.T2;
/**
*
* @author akivela
*/
public class SparqlExtractor extends AbstractExtractor {
private static final long serialVersionUID = 1L;
public static String DEFAULT_SI_ENCODING = "UTF-8";
public static String DEFAULT_RESULTSET_FORMAT = "JSON";
public static String DEFAULT_HANDLE_METHOD = "RESULTSET-TOPICMAP";
public static String RESULTSET_SI = "http://wandora.org/si/sparql/resultset";
public static String COLUMN_SI = "http://wandora.org/si/sparql/resultset/column";
public static String LITERAL_SI = "http://wandora.org/si/sparql/resultset/literal";
private SparqlExtractorUI ui = null;
public static final String defaultOccurrenceScopeSI = TMBox.LANGINDEPENDENT_SI;
@Override
public String getName() {
return "SPARQL extractor";
}
@Override
public String getDescription(){
return "Transforms SPARQL result set to a topic map. Extractor requires a SPARQL endpoint.";
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/extract_sparql.png");
}
private final String[] contentTypes=new String[] { "application/xml", "application/rdf+xml" };
@Override
public String[] getContentTypes() {
return contentTypes;
}
@Override
public boolean useURLCrawler() {
return false;
}
@Override
public void execute(Wandora wandora, Context context) {
try {
if(ui == null) {
ui = new SparqlExtractorUI(wandora);
}
ui.open(wandora);
if(ui.wasAccepted()) {
setDefaultLogger();
log("Requesting SPARQL result set...");
TopicMap tm = wandora.getTopicMap();
String[] urls = ui.getQueryURLs(this);
String format = ui.getResultSetFormat();
String handleMethod = ui.getHandleMethod();
int c = 0;
if(urls != null && urls.length > 0) {
for(int i=0; i<urls.length; i++) {
try {
URL u = new URL(urls[i]);
log("Extracting result set from '"+u.toExternalForm()+"'");
URLConnection uc = u.openConnection();
uc.setUseCaches(false);
ResultSet rs = importResultSet(uc.getInputStream(), format);
handleResultSet(rs, handleMethod, tm);
c++;
}
catch(Exception e) {
log(e);
}
}
if(c == 0) log("Failed to extract any of given feeds. Aborting.");
else log("Total " + c + " result set feeds extracted.");
}
}
else {
// log("User cancelled the extraction!");
}
}
catch(Exception e) {
singleLog(e);
}
if(ui != null && ui.wasAccepted()) setState(WAIT);
else setState(CLOSE);
}
// -----
@Override
public boolean _extractTopicsFrom(File f, TopicMap tm) throws Exception {
return _extractTopicsFrom(new FileInputStream(f), tm);
}
@Override
public boolean _extractTopicsFrom(String str, TopicMap tm) throws Exception {
return _extractTopicsFrom(new ByteArrayInputStream(str.getBytes()), tm);
}
public boolean _extractTopicsFrom(URL url, TopicMap tm) throws Exception {
URLConnection uc = url.openConnection();
uc.setUseCaches(false);
Wandora.initUrlConnection(uc);
boolean r = _extractTopicsFrom(uc.getInputStream(), tm);
return r;
}
public boolean _extractTopicsFrom(InputStream in, TopicMap tm) throws Exception {
try {
ResultSet rs = importResultSet(in, DEFAULT_RESULTSET_FORMAT);
handleResultSet(rs, DEFAULT_HANDLE_METHOD, tm);
return true;
}
catch(Exception e) {
log(e);
}
return false;
}
public ResultSet importResultSet(InputStream in, String format) {
ResultSet results = null;
if(in != null) {
if("JSON".equalsIgnoreCase(format)) {
System.out.println("Processing SPARQL results set as JSON");
results = ResultSetFactory.fromJSON(in);
}
else if("XML".equalsIgnoreCase(format)) {
System.out.println("Processing SPARQL results set as XML");
results = ResultSetFactory.fromXML(in);
}
else if("RDF/XML".equalsIgnoreCase(format)) {
System.out.println("Processing SPARQL results set as RDF/XML");
// results = ResultSetFactory.load(in, com.hp.hpl.jena.sparql.resultset.ResultsFormat.FMT_RDF_XML);
}
}
return results;
}
public void handleResultSet(ResultSet results, String method, TopicMap tm) throws Exception {
if(results != null) {
if("RESULTSET-RDF-TOPICMAP".equals(method)) {
Model model = RDFOutput.encodeAsModel(results);
RDF2TopicMap(model, tm);
}
else {
resultSet2TopicMap(results, tm);
}
}
else {
log("Warning: no result set available!");
}
}
// -------------------------------------------------------------------------
public void resultSet2TopicMap(ResultSet rs, TopicMap tm) throws Exception {
List<String> columns = rs.getResultVars();
int counter = 0;
while(rs.hasNext()) {
QuerySolution soln = rs.nextSolution();
if(soln != null) {
Map<Topic,Topic> roledPlayers = new LinkedHashMap<>();
for(String col : columns) {
RDFNode x = soln.get(col);
if(x == null) continue;
Topic role = getRoleTopic(col, tm);
Topic player = null;
if(x.isURIResource() || x.isResource()) {
Resource r = x.asResource();
String uri = r.getURI();
String name = r.getLocalName();
String basename = name + " ("+uri.hashCode()+")";
player = createTopic(tm, uri, basename);
}
else if(x.isLiteral()) {
Literal l = x.asLiteral();
String sif = l.getString();
if(sif.length() > 128) sif = sif.substring(0, 127)+"_"+sif.hashCode();
String uri = LITERAL_SI + "/" + encode(sif);
String name = l.getString();
String lang = l.getLanguage();
String datatype = l.getDatatypeURI();
player = createTopic(tm, uri, name);
player.setDisplayName(lang, name);
}
else {
log("Warning: Found illegal column value in SPARQL result set. Skipping.");
}
if(role != null && player != null) {
roledPlayers.put(role, player);
}
}
if(!roledPlayers.isEmpty()) {
Topic associationType = getAssociationType(rs, tm);
if(associationType != null) {
Association a = tm.createAssociation(associationType);
for( Topic role : roledPlayers.keySet() ) {
a.addPlayer(roledPlayers.get(role), role);
}
}
}
}
counter++;
setProgress(counter);
if(counter % 100 == 0) hlog("Result set rows processed: " + counter);
}
}
public Topic getAssociationType(ResultSet rs, TopicMap tm) throws Exception {
Topic atype = createTopic(tm, RESULTSET_SI+"/"+rs.hashCode(), "SPARQL Result Set "+rs.hashCode());
Topic settype = createTopic(tm, RESULTSET_SI, "SPARQL Result Set");
Topic wandoratype = createTopic(tm, TMBox.WANDORACLASS_SI, "Wandora class");
settype.addType(wandoratype);
atype.addType(settype);
return atype;
}
public Topic getRoleTopic(String role, TopicMap tm) throws Exception {
return createTopic(tm, COLUMN_SI+"/"+encode(role), role);
}
public String encode(String str) {
try {
return URLEncoder.encode(str, DEFAULT_SI_ENCODING);
}
catch(Exception e) {
return str;
}
}
// -------------------------------------------------------------------------
public void RDF2TopicMap(Model model, TopicMap map) {
// list the statements in the Model
StmtIterator iter = model.listStatements();
Statement stmt = null;
int counter = 0;
while (iter.hasNext() && !forceStop()) {
try {
stmt = iter.nextStatement(); // get next statement
handleStatement(stmt, map);
}
catch(Exception e) {
log(e);
}
counter++;
setProgress(counter);
if(counter % 100 == 0) hlog("RDF statements processed: " + counter);
}
log("Total RDF statements processed: " + counter);
}
public void handleStatement(Statement stmt, TopicMap map) throws TopicMapException {
Resource subject = stmt.getSubject(); // get the subject
Property predicate = stmt.getPredicate(); // get the predicate
RDFNode object = stmt.getObject(); // get the object
//System.out.println("statement:\n "+subject+"\n "+predicate+"\n "+object);
Topic subjectTopic = getOrCreateTopic(map, subject.toString());
if(object.isResource()) {
Topic objectTopic = getOrCreateTopic(map, object.toString());
Topic predicateTopic = getOrCreateTopic(map, predicate.toString());
Association association = map.createAssociation(predicateTopic);
association.addPlayer(subjectTopic, solveSubjectRoleFor(predicate, subject, map));
association.addPlayer(objectTopic, solveObjectRoleFor(predicate, object, map));
}
else if(object.isLiteral()) {
Topic predicateTopic = getOrCreateTopic(map, predicate.toString());
String occurrenceLang = defaultOccurrenceScopeSI;
String literal = ((Literal) object).getString();
try {
String lang = stmt.getLanguage();
if(lang != null) occurrenceLang = XTMPSI.getLang(lang);
}
catch(Exception e) {
/* PASSING BY */
}
String oldOccurrence = ""; // subjectTopic.getData(predicateTopic, occurrenceLang);
if(oldOccurrence != null && oldOccurrence.length() > 0) {
literal = oldOccurrence + "\n\n" + literal;
}
subjectTopic.setData(predicateTopic, getOrCreateTopic(map, occurrenceLang), literal);
}
else if(object.isURIResource()) {
log("URIResource found but not handled!");
}
}
public Topic solveSubjectRoleFor(Property predicate, Resource subject, TopicMap map) {
if(map == null) return null;
RDF2TopicMapsMapping[] mappings = null; // getMappings();
String predicateString = predicate.toString();
String subjectString = subject.toString();
String si = RDF2TopicMapsMapping.DEFAULT_SUBJECT_ROLE_SI;
String bn = RDF2TopicMapsMapping.DEFAULT_SUBJECT_ROLE_BASENAME;
T2<String, String> mapped = null;
if(mappings != null) {
for(int i=0; i<mappings.length; i++) {
mapped = mappings[i].solveSubjectRoleFor(predicateString, subjectString);
if(mapped.e1 != null && mapped.e2 != null) {
si = mapped.e1;
bn = mapped.e2;
break;
}
}
}
return getOrCreateTopic(map, si, bn);
}
public Topic solveObjectRoleFor(Property predicate, RDFNode object, TopicMap map) {
if(map == null) return null;
RDF2TopicMapsMapping[] mappings = null; // getMappings();
String predicateString = predicate.toString();
String objectString = object.toString();
String si = RDF2TopicMapsMapping.DEFAULT_OBJECT_ROLE_SI;
String bn = RDF2TopicMapsMapping.DEFAULT_OBJECT_ROLE_BASENAME;
T2<String, String> mapped = null;
if(mappings != null) {
for(int i=0; i<mappings.length; i++) {
mapped = mappings[i].solveObjectRoleFor(predicateString, objectString);
if(mapped.e1 != null && mapped.e2 != null) {
si = mapped.e1;
bn = mapped.e2;
break;
}
}
}
return getOrCreateTopic(map, si, bn);
}
// -------------------------------------------------------------------------
public String baseUrl = null;
public String getBaseUrl() {
return baseUrl;
}
public void setBaseUrl(String url) {
baseUrl = url;
if(baseUrl != null) {
int lindex = baseUrl.lastIndexOf("/");
int findex = baseUrl.indexOf("/");
//System.out.println("solving base url: "+lindex+", "+findex+", "+baseUrl);
if(1+findex < lindex) {
baseUrl = baseUrl.substring(0, lindex);
}
}
}
// -------------------------------------------------------------------------
public Topic getOrCreateTopic(TopicMap map, String si) {
return getOrCreateTopic(map, si, null);
}
public Topic getOrCreateTopic(TopicMap map, String si, String basename) {
Topic topic = null;
try {
if(si == null || si.length() == 0) {
si = TopicTools.createDefaultLocator().toExternalForm();
}
if(si.indexOf("://") == -1 && getBaseUrl() != null) {
si = getBaseUrl() + "/" + si;
}
topic = map.getTopic(si);
if(topic == null && basename != null) {
topic = map.getTopicWithBaseName(basename);
if(topic != null) {
topic.addSubjectIdentifier(new Locator(si));
}
}
if(topic == null) {
topic = map.createTopic();
topic.addSubjectIdentifier(new Locator(si));
if(basename != null) topic.setBaseName(basename);
}
}
catch(Exception e) {
e.printStackTrace();
}
return topic;
}
}
| 18,422 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
DublinCoreXMLExtractor.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/dublincore/DublinCoreXMLExtractor.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* DublinCoreXMLExtractor.java
*
* Created on 2010-06-30
*
*/
package org.wandora.application.tools.extractors.dublincore;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import javax.swing.Icon;
import org.wandora.application.gui.UIBox;
import org.wandora.application.tools.extractors.AbstractExtractor;
import org.wandora.application.tools.extractors.ExtractHelper;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.TMBox;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.topicmap.TopicTools;
import org.wandora.topicmap.XTMPSI;
import org.wandora.utils.IObox;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
/**
* Converts simple Dublin Core XML feed to a topic map.
*
* Unsupported XML elements:
*
* isVersionOf, hasVersion, isReplacedBy, replaces, isRequiredBy,
* requires, isPartOf, hasPart, isReferencedBy, references,
* isFormatOf, hasFormat, conformsTo, spatial, temporal, mediator,
* dateAccepted, dateCopyrighted, dateSubmitted, educationLevel,
* accessRights, bibliographicCitation, license, rightsHolder,
* provenance, instructionalMethod, accrualMethod, accrualPeriodicity,
* accrualPolicy, Agent, AgentClass, BibliographicResource, FileFormat,
* Frequency, Jurisdiction, LicenseDocument, LinguisticSystem, Location,
* LocationPeriodOrJurisdiction
*
* Also, XML element attribute support is very narrow.
*
* @author akivela
*
*
*/
public class DublinCoreXMLExtractor extends AbstractExtractor {
private static final long serialVersionUID = 1L;
public static boolean IDENTIFIER_AS_SI = true;
public static boolean DESCRIPTION_AS_PLAYER = false;
public static boolean DESCRIPTION_AS_OCCURRENCE = true;
public static boolean APPEND_OCCURRENCE_DESCRIPTION = true;
public static boolean APPEND_OCCURRENCE_ALTERNATIVE = true;
public static boolean APPEND_OCCURRENCE_TABLEOFCONTENTS = true;
public static boolean APPEND_OCCURRENCE_ABSTRACT = true;
protected String SI_BASE = "http://purl.org/dc/elements/1.1/";
protected String RECORD_SI = SI_BASE + "record";
protected String CREATOR_SI = SI_BASE + "creator";
protected String TYPE_SI = SI_BASE + "type";
protected String PUBLISHER_SI = SI_BASE + "publisher";
protected String CONTRIBUTOR_SI = SI_BASE + "contributor";
protected String DATE_SI = SI_BASE + "date";
protected String DESCRIPTION_SI = SI_BASE + "description";
protected String LANGUAGE_SI = SI_BASE + "language";
protected String SUBJECT_SI = SI_BASE + "subject";
protected String IDENTIFIER_SI = SI_BASE + "identifier";
protected String FORMAT_SI = SI_BASE + "format";
protected String SOURCE_SI = SI_BASE + "source";
protected String RELATION_SI = SI_BASE + "relation";
protected String COVERAGE_SI = SI_BASE + "coverage";
protected String RIGHTS_SI = SI_BASE + "rights";
protected String AUDIENCE_SI = SI_BASE + "audience";
protected String ALTERNATIVE_SI = SI_BASE + "alternative";
protected String TABLEOFCONTENTS_SI = SI_BASE + "tableOfContents";
protected String ABSTRACT_SI = SI_BASE + "abstract";
protected String CREATED_SI = SI_BASE + "created";
protected String VALID_SI = SI_BASE + "valid";
protected String AVAILABLE_SI = SI_BASE + "available";
protected String ISSUED_SI = SI_BASE + "issued";
protected String MODIFIED_SI = SI_BASE + "modified";
protected String EXTENT_SI = SI_BASE + "extent";
protected String MEDIUM_SI = SI_BASE + "medium";
private String defaultEncoding = "ISO-8859-1";
/** Creates a new instance of DublinCoreXMLExtractor */
public DublinCoreXMLExtractor() {
}
@Override
public String getName() {
return "Simple Dublin Core XML extractor";
}
@Override
public String getDescription(){
return "Converts simple Dublin Core XML documents to topics maps.";
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/extract_dc.png");
}
private final String[] contentTypes=new String[] { "text/xml", "application/xml" };
@Override
public String[] getContentTypes() {
return contentTypes;
}
@Override
public boolean useURLCrawler() {
return false;
}
@Override
public boolean _extractTopicsFrom(URL url, TopicMap topicMap) throws Exception {
String in = IObox.doUrl(url);
return _extractTopicsFrom(in, topicMap);
}
@Override
public boolean _extractTopicsFrom(File file, TopicMap topicMap) throws Exception {
return _extractTopicsFrom(new FileInputStream(file),topicMap);
}
public boolean _extractTopicsFrom(InputStream in, TopicMap topicMap) throws Exception {
String str = IObox.loadFile(in, defaultEncoding);
return _extractTopicsFrom(str, topicMap);
}
@Override
public boolean _extractTopicsFrom(String in, TopicMap topicMap) throws Exception {
try {
String result = in;
//System.out.println("Result = "+result);
// ---- Parse results ----
javax.xml.parsers.SAXParserFactory factory=javax.xml.parsers.SAXParserFactory.newInstance();
factory.setNamespaceAware(false);
factory.setValidating(false);
javax.xml.parsers.SAXParser parser=factory.newSAXParser();
XMLReader reader=parser.getXMLReader();
DublinCoreXMLParser parserHandler = new DublinCoreXMLParser(topicMap, this);
reader.setContentHandler(parserHandler);
reader.setErrorHandler(parserHandler);
try{
reader.parse(new InputSource(new ByteArrayInputStream(result.getBytes())));
}
catch(Exception e){
if(!(e instanceof SAXException) || !e.getMessage().equals("User interrupt")) log(e);
}
String msg = null;
if(parserHandler.progress == 0) {
msg = "Found no records.";
}
else {
msg = "Found "+parserHandler.progress+" records(s).";
}
if(msg != null) log(msg);
}
catch (Exception ex) {
log(ex);
}
return true;
}
// -------------------------------------------------------------------------
public Topic getDescriptionTopic(String description, TopicMap tm) throws TopicMapException {
if(description != null) {
description = description.trim();
if(description.length() > 0) {
String niceDescription = description.replace("\n", " ");
niceDescription = niceDescription.replace("\r", " ");
niceDescription = niceDescription.replace("\t", " ");
if(niceDescription.length() > 256) niceDescription = niceDescription.substring(0, 255);
Topic descriptionTopic=getOrCreateTopic(tm, TopicTools.createDefaultLocator().toExternalForm(), niceDescription);
Topic descriptionTypeTopic = getDescriptionType(tm);
Topic langTopic = tm.getTopic(XTMPSI.getLang("en"));
descriptionTopic.setData(descriptionTypeTopic, langTopic, description);
descriptionTopic.addType(descriptionTypeTopic);
return descriptionTopic;
}
}
return null;
}
public Topic getDescriptionType(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, DESCRIPTION_SI, "Description (DC)", getDCClass(tm));
}
// ---
public Topic getIdentifierTopic(String identifier, TopicMap tm) throws TopicMapException {
if(identifier != null) {
identifier = identifier.trim();
if(identifier.length() > 0) {
Topic identifierTopic=getOrCreateTopic(tm, identifier, identifier, getIdentifierType(tm));
return identifierTopic;
}
}
return null;
}
public Topic getIdentifierType(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, IDENTIFIER_SI, "Identifier (DC)", getDCClass(tm));
}
// ---
public Topic getSubjectTopic(String subject, TopicMap tm) throws TopicMapException {
return getTopic(tm, subject, SUBJECT_SI, getSubjectType(tm));
}
public Topic getSubjectType(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, SUBJECT_SI, "Subject (DC)", getDCClass(tm));
}
// ---
public Topic getTypeTopic(String type, TopicMap tm) throws TopicMapException {
return getTopic(tm, type, TYPE_SI, getTypeType(tm));
}
public Topic getTypeType(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, TYPE_SI, "Type (DC)", getDCClass(tm));
}
// ---
public Topic getFormatTopic(String format, TopicMap tm) throws TopicMapException {
return getTopic(tm, format, FORMAT_SI, getFormatType(tm));
}
public Topic getFormatType(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, FORMAT_SI, "Format (DC)", getDCClass(tm));
}
// ---
public Topic getDateTopic(String date, TopicMap tm) throws TopicMapException {
return getTopic(tm, date, DATE_SI, getDateType(tm));
}
public Topic getDateType(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, DATE_SI, "Date (DC)", getDCClass(tm));
}
// ---
public Topic getPublisherTopic(String publisher, TopicMap tm) throws TopicMapException {
return getTopic(tm, publisher, PUBLISHER_SI, getPublisherType(tm));
}
public Topic getPublisherType(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, PUBLISHER_SI, "Publisher (DC)", getDCClass(tm));
}
// ---
public Topic getContributorTopic(String contributor, TopicMap tm) throws TopicMapException {
return getTopic(tm, contributor, CONTRIBUTOR_SI, getContributorType(tm));
}
public Topic getContributorType(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, CONTRIBUTOR_SI, "Contributor (DC)", getDCClass(tm));
}
// ---
public Topic getLanguageTopic(String language, TopicMap tm) throws TopicMapException {
return getTopic(tm, language, LANGUAGE_SI, getLanguageType(tm));
}
public Topic getLanguageType(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, LANGUAGE_SI, "Language (DC)", getDCClass(tm));
}
// ----
public Topic getCreatorTopic(String creator, TopicMap tm) throws TopicMapException {
return getTopic(tm, creator, CREATOR_SI, getCreatorType(tm));
}
public Topic getCreatorType(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, CREATOR_SI, "Creator (DC)", getDCClass(tm));
}
// ----
public Topic getSourceTopic(String source, TopicMap tm) throws TopicMapException {
return getTopic(tm, source, SOURCE_SI, getSourceType(tm));
}
public Topic getSourceType(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, SOURCE_SI, "Source (DC)", getDCClass(tm));
}
// ----
public Topic getRelationTopic(String relation, TopicMap tm) throws TopicMapException {
return getTopic(tm, relation, RELATION_SI, getRelationType(tm));
}
public Topic getRelationType(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, RELATION_SI, "Relation (DC)", getDCClass(tm));
}
// ----
public Topic getCoverageTopic(String coverage, TopicMap tm) throws TopicMapException {
return getTopic(tm, coverage, COVERAGE_SI, getCoverageType(tm));
}
public Topic getCoverageType(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, COVERAGE_SI, "Coverage (DC)", getDCClass(tm));
}
// ----
public Topic getRightsTopic(String rights, TopicMap tm) throws TopicMapException {
return getTopic(tm, rights, RIGHTS_SI, getRightsType(tm));
}
public Topic getRightsType(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, RIGHTS_SI, "Rights (DC)", getDCClass(tm));
}
// ----
public Topic getAudienceTopic(String audience, TopicMap tm) throws TopicMapException {
return getTopic(tm, audience, AUDIENCE_SI, getAudienceType(tm));
}
public Topic getAudienceType(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, AUDIENCE_SI, "Audience (DC)", getDCClass(tm));
}
// ----
public Topic getAlternativeTopic(String alt, TopicMap tm) throws TopicMapException {
return getTopic(tm, alt, ALTERNATIVE_SI, getAlternativeType(tm));
}
public Topic getAlternativeType(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, ALTERNATIVE_SI, "Alternative (DC)", getDCClass(tm));
}
// ----
public Topic getTableOfContentsTopic(String toc, TopicMap tm) throws TopicMapException {
return getTopic(tm, toc, TABLEOFCONTENTS_SI, getTableOfContentsType(tm));
}
public Topic getTableOfContentsType(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, TABLEOFCONTENTS_SI, "TableOfContents (DC)", getDCClass(tm));
}
// ----
public Topic getAbstractTopic(String abst, TopicMap tm) throws TopicMapException {
return getTopic(tm, abst, ABSTRACT_SI, getAbstractType(tm));
}
public Topic getAbstractType(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, ABSTRACT_SI, "Abstract (DC)", getDCClass(tm));
}
// ----
public Topic getCreatedTopic(String created, TopicMap tm) throws TopicMapException {
return getTopic(tm, created, CREATED_SI, getCreatedType(tm));
}
public Topic getCreatedType(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, CREATED_SI, "Created (DC)", getDCClass(tm));
}
// ----
public Topic getValidTopic(String valid, TopicMap tm) throws TopicMapException {
return getTopic(tm, valid, VALID_SI, getValidType(tm));
}
public Topic getValidType(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, VALID_SI, "Valid (DC)", getDCClass(tm));
}
// ----
public Topic getAvailableTopic(String available, TopicMap tm) throws TopicMapException {
return getTopic(tm, available, AVAILABLE_SI, getAvailableType(tm));
}
public Topic getAvailableType(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, AVAILABLE_SI, "Available (DC)", getDCClass(tm));
}
// ----
public Topic getIssuedTopic(String issued, TopicMap tm) throws TopicMapException {
return getTopic(tm, issued, ISSUED_SI, getIssuedType(tm));
}
public Topic getIssuedType(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, ISSUED_SI, "Issued (DC)", getDCClass(tm));
}
// ----
public Topic getModifiedTopic(String modified, TopicMap tm) throws TopicMapException {
return getTopic(tm, modified, MODIFIED_SI, getModifiedType(tm));
}
public Topic getModifiedType(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, MODIFIED_SI, "Modified (DC)", getDCClass(tm));
}
// ----
public Topic getExtentTopic(String extent, TopicMap tm) throws TopicMapException {
return getTopic(tm, extent, EXTENT_SI, getExtentType(tm));
}
public Topic getExtentType(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, EXTENT_SI, "Extent (DC)", getDCClass(tm));
}
// ----
public Topic getMediumTopic(String medium, TopicMap tm) throws TopicMapException {
return getTopic(tm, medium, MEDIUM_SI, getMediumType(tm));
}
public Topic getMediumType(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, MEDIUM_SI, "Medium (DC)", getDCClass(tm));
}
// ---------------------------------------------
public Topic getRecordType(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, RECORD_SI, "Record (DC)", getDCClass(tm));
}
public Topic getDCClass(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, SI_BASE, "Dublin Core", getWandoraClass(tm));
}
public Topic getWandoraClass(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, TMBox.WANDORACLASS_SI,"Wandora class");
}
// --------
public Topic getTopic(TopicMap tm, String str, String SIBase, Topic type) throws TopicMapException {
if(str != null && SIBase != null) {
str = str.trim();
if(str.length() > 0) {
Topic strTopic=getOrCreateTopic(tm, makeSI(SIBase, str), str, type);
return strTopic;
}
}
return null;
}
protected Topic getOrCreateTopic(TopicMap tm, String si) throws TopicMapException {
return getOrCreateTopic(tm, si, null);
}
protected Topic getOrCreateTopic(TopicMap tm, String si, String bn) throws TopicMapException {
return getOrCreateTopic(tm, si, bn, null);
}
protected Topic getOrCreateTopic(TopicMap tm, String si, String bn, Topic type) throws TopicMapException {
return ExtractHelper.getOrCreateTopic(si, bn, type, tm);
}
protected void makeSubclassOf(TopicMap tm, Topic t, Topic superclass) throws TopicMapException {
ExtractHelper.makeSubclassOf(t, superclass, tm);
}
protected String makeSI(String base, String endPoint) {
String end = endPoint;
try {
end = URLEncoder.encode(endPoint, defaultEncoding);
}
catch(Exception e) {
log(e);
}
String si = base + "/" + end;
return si;
}
// -------------------------------------------------------------------------
private class DublinCoreXMLParser implements org.xml.sax.ContentHandler, org.xml.sax.ErrorHandler {
public DublinCoreXMLParser(TopicMap tm, DublinCoreXMLExtractor parent){
this.tm=tm;
this.parent=parent;
}
public int progress=0;
private TopicMap tm;
private DublinCoreXMLExtractor parent;
public static final String TAG_METADATA = "metadata";
public static final String TAG_DC = "dc";
public static final String TAG_RECORD = "record";
public static final String TAG_TITLE= "title";
public static final String TAG_CREATOR = "creator";
public static final String TAG_TYPE = "type";
public static final String TAG_PUBLISHER = "publisher";
public static final String TAG_DATE = "date";
public static final String TAG_LANGUAGE = "language";
public static final String TAG_DESCRIPTION = "description";
public static final String TAG_SUBJECT = "subject";
public static final String TAG_IDENTIFIER = "identifier";
public static final String TAG_CONTRIBUTOR = "contributor";
public static final String TAG_FORMAT = "format";
public static final String TAG_SOURCE = "source";
public static final String TAG_RELATION = "relation";
public static final String TAG_COVERAGE = "coverage";
public static final String TAG_RIGHTS = "rights";
public static final String TAG_AUDIENCE = "audience";
public static final String TAG_ALTERNATIVE = "alternative";
public static final String TAG_TABLEOFCONTENTS = "tableOfContents";
public static final String TAG_ABSTRACT = "abstract";
public static final String TAG_CREATED = "created";
public static final String TAG_VALID = "valid";
public static final String TAG_AVAILABLE = "available";
public static final String TAG_ISSUED = "issued";
public static final String TAG_MODIFIED = "modified";
public static final String TAG_EXTENT = "extent";
public static final String TAG_MEDIUM = "medium";
public static final String ATTR_LANG = "lang";
public static final String ATTR_TYPE = "type";
private static final int STATE_START=0;
private static final int STATE_DC=2;
private static final int STATE_DC_TITLE=21;
private static final int STATE_DC_CREATOR=22;
private static final int STATE_DC_TYPE=23;
private static final int STATE_DC_LANGUAGE=24;
private static final int STATE_DC_DATE=25;
private static final int STATE_DC_DESCRIPTION=26;
private static final int STATE_DC_SUBJECT=27;
private static final int STATE_DC_PUBLISHER=28;
private static final int STATE_DC_IDENTIFIER=29;
private static final int STATE_DC_CONTRIBUTOR=30;
private static final int STATE_DC_FORMAT=31;
private static final int STATE_DC_SOURCE = 32;
private static final int STATE_DC_RELATION = 33;
private static final int STATE_DC_COVERAGE = 34;
private static final int STATE_DC_RIGHTS = 35;
private static final int STATE_DC_AUDIENCE = 36;
private static final int STATE_DC_ALTERNATIVE = 37;
private static final int STATE_DC_TABLEOFCONTENTS = 38;
private static final int STATE_DC_ABSTRACT = 39;
private static final int STATE_DC_CREATED = 40;
private static final int STATE_DC_VALID = 41;
private static final int STATE_DC_AVAILABLE = 42;
private static final int STATE_DC_ISSUED = 43;
private static final int STATE_DC_MODIFIED = 44;
private static final int STATE_DC_EXTENT = 45;
private static final int STATE_DC_MEDIUM = 46;
private int state=STATE_START;
private String data_title = null;
private String data_title_lang = null;
private String data_title_type = null;
private String data_creator = null;
private String data_type = null;
private String data_publisher = null;
private String data_date = null;
private String data_language = null;
private String data_description = null;
private String data_description_lang = null;
private String data_subject = null;
private String data_identifier = null;
private String data_identifier_type = null;
private String data_contributor = null;
private String data_format = null;
private String data_source = null;
private String data_relation = null;
private String data_coverage = null;
private String data_rights = null;
private String data_audience = null;
private String data_alternative = null;
private String data_alternative_lang = null;
private String data_tableofcontents = null;
private String data_tableofcontents_lang = null;
private String data_abstract = null;
private String data_abstract_lang = null;
private String data_created = null;
private String data_valid = null;
private String data_available = null;
private String data_issued = null;
private String data_modified = null;
private String data_extent = null;
private String data_medium = null;
private Topic dcTopic = null;
private org.wandora.topicmap.Locator dcIdentifier = null;
private void associatiateWithRecord( TopicMap tm, Topic player, Topic role ) {
if(dcTopic != null) {
try {
if(player != null) {
Topic recordType = getRecordType( tm );
Association a = tm.createAssociation(role);
a.addPlayer(dcTopic, recordType);
a.addPlayer(player, role);
}
}
catch(Exception e) {
log(e);
}
}
}
@Override
public void startDocument() throws SAXException {
}
@Override
public void endDocument() throws SAXException {
}
@Override
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
//System.out.println("found tag: "+qName+", localName: "+localName);
if(parent.forceStop()){
throw new SAXException("User interrupt");
}
switch(state){
case STATE_START:
if(equalTags(qName,TAG_DC) || equalTags(qName,TAG_METADATA) || equalTags(qName,TAG_RECORD)) {
try {
dcTopic = tm.createTopic();
dcIdentifier = TopicTools.createDefaultLocator();
dcTopic.addSubjectIdentifier(dcIdentifier);
Topic recordType = getRecordType(tm);
dcTopic.addType(recordType);
}
catch(Exception e) {
log(e);
}
state = STATE_DC;
}
break;
case STATE_DC:
if(equalTags(qName,TAG_TITLE)) {
data_title = "";
data_title_lang = atts.getValue(ATTR_LANG);
if(data_title_lang == null) data_title_lang = atts.getValue("XML:lang");
data_title_type = atts.getValue(ATTR_TYPE);
state = STATE_DC_TITLE;
}
else if(equalTags(qName,TAG_CREATOR)) {
data_creator = "";
state = STATE_DC_CREATOR;
}
else if(equalTags(qName,TAG_TYPE)) {
data_type = "";
state = STATE_DC_TYPE;
}
else if(equalTags(qName,TAG_PUBLISHER)) {
data_publisher = "";
state = STATE_DC_PUBLISHER;
}
else if(equalTags(qName,TAG_DATE)) {
data_date = "";
state = STATE_DC_DATE;
}
else if(equalTags(qName,TAG_LANGUAGE)) {
data_language = "";
state = STATE_DC_LANGUAGE;
}
else if(equalTags(qName,TAG_DESCRIPTION)) {
data_description = "";
data_description_lang = atts.getValue(ATTR_LANG);
if(data_description_lang == null) data_description_lang = atts.getValue("XML:lang");
state = STATE_DC_DESCRIPTION;
}
else if(equalTags(qName,TAG_SUBJECT)) {
data_subject = "";
state = STATE_DC_SUBJECT;
}
else if(equalTags(qName,TAG_IDENTIFIER)) {
data_identifier = "";
data_identifier_type = atts.getValue(ATTR_TYPE);
state = STATE_DC_IDENTIFIER;
}
else if(equalTags(qName,TAG_CONTRIBUTOR)) {
data_contributor = "";
state = STATE_DC_CONTRIBUTOR;
}
else if(equalTags(qName,TAG_FORMAT)) {
data_format = "";
state = STATE_DC_FORMAT;
}
else if(equalTags(qName,TAG_SOURCE)) {
data_source = "";
state = STATE_DC_SOURCE;
}
else if(equalTags(qName,TAG_RELATION)) {
data_relation = "";
state = STATE_DC_RELATION;
}
else if(equalTags(qName,TAG_COVERAGE)) {
data_coverage = "";
state = STATE_DC_COVERAGE;
}
else if(equalTags(qName,TAG_RIGHTS)) {
data_rights = "";
state = STATE_DC_RIGHTS;
}
else if(equalTags(qName,TAG_AUDIENCE)) {
data_audience = "";
state = STATE_DC_AUDIENCE;
}
else if(equalTags(qName,TAG_ALTERNATIVE)) {
data_alternative = "";
data_alternative_lang = atts.getValue(ATTR_LANG);
if(data_alternative_lang == null) data_alternative_lang = atts.getValue("XML:lang");
state = STATE_DC_ALTERNATIVE;
}
else if(equalTags(qName,TAG_TABLEOFCONTENTS)) {
data_tableofcontents = "";
data_tableofcontents_lang = atts.getValue(ATTR_LANG);
if(data_tableofcontents_lang == null) data_tableofcontents_lang = atts.getValue("XML:lang");
state = STATE_DC_TABLEOFCONTENTS;
}
else if(equalTags(qName,TAG_ABSTRACT)) {
data_abstract = "";
data_abstract_lang = atts.getValue(ATTR_LANG);
if(data_abstract_lang == null) data_abstract_lang = atts.getValue("XML:lang");
state = STATE_DC_ABSTRACT;
}
else if(equalTags(qName,TAG_CREATED)) {
data_created = "";
state = STATE_DC_CREATED;
}
else if(equalTags(qName,TAG_VALID)) {
data_valid = "";
state = STATE_DC_VALID;
}
else if(equalTags(qName,TAG_AVAILABLE)) {
data_available = "";
state = STATE_DC_AVAILABLE;
}
else if(equalTags(qName,TAG_ISSUED)) {
data_issued = "";
state = STATE_DC_ISSUED;
}
else if(equalTags(qName,TAG_MODIFIED)) {
data_modified = "";
state = STATE_DC_MODIFIED;
}
else if(equalTags(qName,TAG_EXTENT)) {
data_extent = "";
state = STATE_DC_EXTENT;
}
else if(equalTags(qName,TAG_MEDIUM)) {
data_medium = "";
state = STATE_DC_MEDIUM;
}
break;
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
switch(state) {
case STATE_DC: {
if(equalTags(qName,TAG_DC) || equalTags(qName,TAG_METADATA) || equalTags(qName,TAG_RECORD)) {
progress++;
state = STATE_START;
}
break;
}
case STATE_DC_TITLE: {
if(equalTags(qName,TAG_TITLE)) {
if(dcTopic != null && data_title != null) {
data_title = data_title.trim();
if(data_title.length() > 0) {
try {
if(dcTopic.getBaseName() == null) {
dcTopic.setBaseName( data_title );
}
if(data_title_lang == null || data_title_lang.length() == 0) {
data_title_lang = "en";
}
dcTopic.setDisplayName(data_title_lang, data_title);
}
catch(Exception e) {
log(e);
}
}
}
state = STATE_DC;
}
break;
}
case STATE_DC_CREATOR: {
if(equalTags(qName,TAG_CREATOR)) {
if(dcTopic != null && data_creator != null && data_creator.length() > 0) {
try {
Topic creatorTopic = getCreatorTopic( data_creator, tm );
if(creatorTopic != null) {
Topic creatorType = getCreatorType( tm );
Topic recordType = getRecordType( tm );
Association a = tm.createAssociation(creatorType);
a.addPlayer(dcTopic, recordType);
a.addPlayer(creatorTopic, creatorType);
}
}
catch(Exception e) {
log(e);
}
}
state = STATE_DC;
}
break;
}
case STATE_DC_CONTRIBUTOR: {
if(equalTags(qName,TAG_CONTRIBUTOR)) {
if(dcTopic != null && data_contributor != null && data_contributor.length() > 0) {
try {
Topic contributorTopic = getContributorTopic( data_contributor, tm );
if(contributorTopic != null) {
Topic contributorType = getContributorType( tm );
Topic recordType = getRecordType( tm );
Association a = tm.createAssociation(contributorType);
a.addPlayer(dcTopic, recordType);
a.addPlayer(contributorTopic, contributorType);
}
}
catch(Exception e) {
log(e);
}
}
state = STATE_DC;
}
break;
}
case STATE_DC_TYPE: {
if(equalTags(qName,TAG_TYPE)) {
if(dcTopic != null && data_creator != null && data_creator.length() > 0) {
try {
String[] types = data_type.split(",");
String type = null;
for(int i=0; i<types.length; i++) {
type = types[i];
type = type.trim();
if(type.length() > 0) {
Topic typeTopic = getTypeTopic( type, tm );
dcTopic.addType(typeTopic);
}
}
}
catch(Exception e) {
log(e);
}
}
state = STATE_DC;
}
break;
}
case STATE_DC_PUBLISHER: {
if(equalTags(qName,TAG_PUBLISHER)) {
if(dcTopic != null && data_publisher != null && data_publisher.length() > 0) {
try {
Topic publisherTopic = getPublisherTopic( data_publisher, tm );
if(publisherTopic != null) {
Topic publisherType = getPublisherType( tm );
Topic recordType = getRecordType( tm );
Association a = tm.createAssociation(publisherType);
a.addPlayer(dcTopic, recordType);
a.addPlayer(publisherTopic, publisherType);
}
}
catch(Exception e) {
log(e);
}
}
state = STATE_DC;
}
break;
}
case STATE_DC_DATE: {
if(equalTags(qName,TAG_DATE)) {
if(dcTopic != null && data_date != null && data_date.length() > 0) {
try {
Topic dateTopic = getDateTopic( data_date, tm );
if(dateTopic != null) {
Topic dateType = getDateType( tm );
Topic recordType = getRecordType( tm );
Association a = tm.createAssociation(dateType);
a.addPlayer(dcTopic, recordType);
a.addPlayer(dateTopic, dateType);
}
}
catch(Exception e) {
log(e);
}
}
state = STATE_DC;
}
break;
}
case STATE_DC_LANGUAGE: {
if(equalTags(qName,TAG_LANGUAGE)) {
if(dcTopic != null && data_language != null && data_language.length() > 0) {
String[] languages = data_language.split(",");
for(int i=0; i<languages.length; i++) {
String lan = languages[i];
lan = lan.trim();
if( lan.length() > 0) {
try {
Topic languageTopic = getLanguageTopic( lan, tm );
if(languageTopic != null) {
Topic languageType = getLanguageType( tm );
Topic recordType = getRecordType( tm );
Association a = tm.createAssociation(languageType);
a.addPlayer(dcTopic, recordType);
a.addPlayer(languageTopic, languageType);
}
}
catch(Exception e) {
log(e);
}
}
}
}
state = STATE_DC;
}
break;
}
case STATE_DC_DESCRIPTION: {
if(equalTags(qName,TAG_DESCRIPTION)) {
if(dcTopic != null && data_description != null && data_description.length() > 0) {
try {
data_description = data_description.trim();
if(DESCRIPTION_AS_OCCURRENCE) {
Topic descriptionType = getDescriptionType(tm);
if(data_description_lang == null || data_description_lang.length() == 0) {
data_description_lang = "en";
}
Topic langTopic = tm.getTopic(XTMPSI.getLang(data_description_lang));
if(descriptionType != null && langTopic != null) {
String o = null;
if(APPEND_OCCURRENCE_DESCRIPTION) o = dcTopic.getData(descriptionType, langTopic);
if(o == null) o = data_description;
else o = o + "\n\n" + data_description;
dcTopic.setData(descriptionType, langTopic, o);
}
}
if(DESCRIPTION_AS_PLAYER) {
Topic recordType = getRecordType( tm );
Topic descriptionType = getDescriptionType(tm);
Topic descriptionTopic = getDescriptionTopic(data_description, tm);
Association a = tm.createAssociation(descriptionType);
a.addPlayer(dcTopic, recordType);
a.addPlayer(descriptionTopic, descriptionType);
}
}
catch(Exception e) {
log(e);
}
}
state = STATE_DC;
}
break;
}
case STATE_DC_SUBJECT: {
if(equalTags(qName,TAG_SUBJECT)) {
if(dcTopic != null && data_subject != null && data_subject.length() > 0) {
String[] subjects = data_subject.split(",");
for(int i=0; i<subjects.length; i++) {
String subject = subjects[i];
subject = subject.trim();
if( subject.length() > 0) {
try {
Topic subjectTopic = getSubjectTopic( subject, tm );
if(subjectTopic != null) {
Topic subjectType = getSubjectType( tm );
Topic recordType = getRecordType( tm );
Association a = tm.createAssociation(subjectType);
a.addPlayer(dcTopic, recordType);
a.addPlayer(subjectTopic, subjectType);
}
}
catch(Exception e) {
log(e);
}
}
}
}
state = STATE_DC;
}
break;
}
case STATE_DC_IDENTIFIER: {
if(equalTags(qName,TAG_IDENTIFIER)) {
if(dcTopic != null && data_identifier != null) {
try {
data_identifier = data_identifier.trim();
if(data_identifier.length() > 0) {
if(IDENTIFIER_AS_SI) {
dcTopic.addSubjectIdentifier(new org.wandora.topicmap.Locator(data_identifier));
}
else {
Topic identifierTopic = getIdentifierTopic( data_identifier, tm );
if(identifierTopic != null) {
Topic identifierType = getIdentifierType( tm );
Topic recordType = getRecordType( tm );
Association a = tm.createAssociation(identifierType);
a.addPlayer(dcTopic, recordType);
a.addPlayer(identifierTopic, identifierType);
}
}
}
}
catch(Exception e) {
log(e);
}
}
state = STATE_DC;
}
break;
}
case STATE_DC_FORMAT: {
if(equalTags(qName,TAG_FORMAT)) {
if(dcTopic != null && data_format != null && data_format.length() > 0) {
try { associatiateWithRecord( tm, getFormatTopic(data_format, tm), getFormatType(tm) ); }
catch(Exception e) { log(e); }
}
state = STATE_DC;
}
break;
}
case STATE_DC_SOURCE: {
if(equalTags(qName,TAG_SOURCE)) {
if(dcTopic != null && data_source != null && data_source.length() > 0) {
try { associatiateWithRecord( tm, getSourceTopic(data_source, tm), getSourceType(tm) ); }
catch(Exception e) { log(e); }
}
state = STATE_DC;
}
break;
}
case STATE_DC_RELATION: {
if(equalTags(qName,TAG_RELATION)) {
if(dcTopic != null && data_relation != null && data_relation.length() > 0) {
try { associatiateWithRecord( tm, getRelationTopic(data_relation, tm), getRelationType(tm) ); }
catch(Exception e) { log(e); }
}
state = STATE_DC;
}
break;
}
case STATE_DC_COVERAGE: {
if(equalTags(qName,TAG_COVERAGE)) {
if(dcTopic != null && data_coverage != null && data_coverage.length() > 0) {
try { associatiateWithRecord( tm, getCoverageTopic(data_coverage, tm), getCoverageType(tm) ); }
catch(Exception e) { log(e); }
}
state = STATE_DC;
}
break;
}
case STATE_DC_RIGHTS: {
if(equalTags(qName,TAG_RIGHTS)) {
if(dcTopic != null && data_rights != null && data_rights.length() > 0) {
try { associatiateWithRecord( tm, getRightsTopic(data_rights, tm), getRightsType(tm) ); }
catch(Exception e) { log(e); }
}
state = STATE_DC;
}
break;
}
case STATE_DC_AUDIENCE: {
if(equalTags(qName,TAG_AUDIENCE)) {
if(dcTopic != null && data_audience != null && data_audience.length() > 0) {
try { associatiateWithRecord( tm, getAudienceTopic(data_audience, tm), getAudienceType(tm) ); }
catch(Exception e) { log(e); }
}
state = STATE_DC;
}
break;
}
case STATE_DC_ALTERNATIVE: {
if(equalTags(qName,TAG_ALTERNATIVE)) {
if(dcTopic != null && data_alternative != null) {
data_alternative = data_alternative.trim();
if(data_alternative.length() > 0) {
try {
Topic alternativeType = getAlternativeType(tm);
if(data_alternative_lang == null || data_alternative_lang.length() == 0) {
data_alternative_lang = "en";
}
Topic langTopic = tm.getTopic(XTMPSI.getLang(data_alternative_lang));
if(alternativeType != null && langTopic != null) {
String o = null;
if(APPEND_OCCURRENCE_ALTERNATIVE) o = dcTopic.getData(alternativeType, langTopic);
if(o == null) o = data_alternative;
else o = o + "\n\n" + data_alternative;
dcTopic.setData(alternativeType, langTopic, o);
}
}
catch(Exception e) {
log(e);
}
}
}
state = STATE_DC;
}
break;
}
case STATE_DC_TABLEOFCONTENTS: {
if(equalTags(qName,TAG_TABLEOFCONTENTS)) {
if(dcTopic != null && data_tableofcontents != null) {
data_tableofcontents = data_tableofcontents.trim();
if(data_tableofcontents.length() > 0) {
try {
Topic tableofcontentsType = getTableOfContentsType(tm);
if(data_tableofcontents_lang == null || data_tableofcontents_lang.length() == 0) {
data_tableofcontents_lang = "en";
}
Topic langTopic = tm.getTopic(XTMPSI.getLang(data_tableofcontents_lang));
if(tableofcontentsType != null && langTopic != null) {
String o = null;
if(APPEND_OCCURRENCE_TABLEOFCONTENTS) o = dcTopic.getData(tableofcontentsType, langTopic);
if(o == null) o = data_tableofcontents;
else o = o + "\n\n" + data_tableofcontents;
System.out.println("Setting toc: "+o);
dcTopic.setData(tableofcontentsType, langTopic, o);
}
}
catch(Exception e) {
log(e);
}
}
}
state = STATE_DC;
}
break;
}
case STATE_DC_ABSTRACT: {
if(equalTags(qName,TAG_ABSTRACT)) {
if(dcTopic != null && data_abstract != null) {
data_abstract = data_abstract.trim();
if(data_abstract.length() > 0) {
try {
Topic abstractType = getAbstractType(tm);
if(data_abstract_lang == null || data_abstract_lang.length() == 0) {
data_abstract_lang = "en";
}
Topic langTopic = tm.getTopic(XTMPSI.getLang(data_abstract_lang));
if(abstractType != null && langTopic != null) {
String o = null;
if(APPEND_OCCURRENCE_ABSTRACT) o = dcTopic.getData(abstractType, langTopic);
if(o == null) o = data_abstract;
else o = o + "\n\n" + data_abstract;
dcTopic.setData(abstractType, langTopic, o);
}
}
catch(Exception e) {
log(e);
}
}
}
state = STATE_DC;
}
break;
}
case STATE_DC_CREATED: {
if(equalTags(qName,TAG_CREATED)) {
if(dcTopic != null && data_created != null && data_created.length() > 0) {
try { associatiateWithRecord( tm, getCreatedTopic(data_created, tm), getCreatedType(tm) ); }
catch(Exception e) { log(e); }
}
state = STATE_DC;
}
break;
}
case STATE_DC_VALID: {
if(equalTags(qName,TAG_VALID)) {
if(dcTopic != null && data_valid != null && data_valid.length() > 0) {
try { associatiateWithRecord( tm, getValidTopic(data_valid, tm), getValidType(tm) ); }
catch(Exception e) { log(e); }
}
state = STATE_DC;
}
break;
}
case STATE_DC_AVAILABLE: {
if(equalTags(qName,TAG_AVAILABLE)) {
if(dcTopic != null && data_available != null && data_available.length() > 0) {
try { associatiateWithRecord( tm, getAvailableTopic(data_available, tm), getAvailableType(tm) ); }
catch(Exception e) { log(e); }
}
state = STATE_DC;
}
break;
}
case STATE_DC_ISSUED: {
if(equalTags(qName,TAG_ISSUED)) {
if(dcTopic != null && data_issued != null && data_issued.length() > 0) {
try { associatiateWithRecord( tm, getIssuedTopic(data_issued, tm), getIssuedType(tm) ); }
catch(Exception e) { log(e); }
}
state = STATE_DC;
}
break;
}
case STATE_DC_MODIFIED: {
if(equalTags(qName,TAG_MODIFIED)) {
if(dcTopic != null && data_modified != null && data_modified.length() > 0) {
try { associatiateWithRecord( tm, getModifiedTopic(data_modified, tm), getModifiedType(tm) ); }
catch(Exception e) { log(e); }
}
state = STATE_DC;
}
break;
}
case STATE_DC_EXTENT: {
if(equalTags(qName,TAG_EXTENT)) {
if(dcTopic != null && data_extent != null && data_extent.length() > 0) {
try { associatiateWithRecord( tm, getExtentTopic(data_extent, tm), getExtentType(tm) ); }
catch(Exception e) { log(e); }
}
state = STATE_DC;
}
break;
}
case STATE_DC_MEDIUM: {
if(equalTags(qName,TAG_MEDIUM)) {
if(dcTopic != null && data_medium != null && data_medium.length() > 0) {
try { associatiateWithRecord( tm, getMediumTopic(data_medium, tm), getMediumType(tm) ); }
catch(Exception e) { log(e); }
}
state = STATE_DC;
}
break;
}
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
switch(state) {
case STATE_DC_TITLE: {
data_title += new String(ch,start,length);
break;
}
case STATE_DC_CREATOR: {
data_creator += new String(ch,start,length);
break;
}
case STATE_DC_TYPE: {
data_type += new String(ch,start,length);
break;
}
case STATE_DC_PUBLISHER: {
data_publisher += new String(ch,start,length);
break;
}
case STATE_DC_CONTRIBUTOR: {
data_contributor += new String(ch,start,length);
break;
}
case STATE_DC_DATE: {
data_date += new String(ch,start,length);
break;
}
case STATE_DC_LANGUAGE: {
data_language += new String(ch,start,length);
break;
}
case STATE_DC_DESCRIPTION: {
data_description += new String(ch,start,length);
break;
}
case STATE_DC_SUBJECT: {
data_subject += new String(ch,start,length);
break;
}
case STATE_DC_IDENTIFIER: {
data_identifier += new String(ch,start,length);
break;
}
case STATE_DC_FORMAT: {
data_format += new String(ch,start,length);
break;
}
case STATE_DC_SOURCE: {
data_source += new String(ch,start,length);
break;
}
case STATE_DC_RELATION: {
data_relation += new String(ch,start,length);
break;
}
case STATE_DC_COVERAGE: {
data_coverage += new String(ch,start,length);
break;
}
case STATE_DC_RIGHTS: {
data_rights += new String(ch,start,length);
break;
}
case STATE_DC_AUDIENCE: {
data_audience += new String(ch,start,length);
break;
}
case STATE_DC_ALTERNATIVE: {
data_alternative += new String(ch,start,length);
break;
}
case STATE_DC_TABLEOFCONTENTS: {
data_tableofcontents += new String(ch,start,length);
break;
}
case STATE_DC_ABSTRACT: {
data_abstract += new String(ch,start,length);
break;
}
case STATE_DC_CREATED: {
data_created += new String(ch,start,length);
break;
}
case STATE_DC_VALID: {
data_valid += new String(ch,start,length);
break;
}
case STATE_DC_AVAILABLE: {
data_available += new String(ch,start,length);
break;
}
case STATE_DC_ISSUED: {
data_issued += new String(ch,start,length);
break;
}
case STATE_DC_MODIFIED: {
data_modified += new String(ch,start,length);
break;
}
case STATE_DC_EXTENT: {
data_extent += new String(ch,start,length);
break;
}
case STATE_DC_MEDIUM: {
data_medium += new String(ch,start,length);
break;
}
default:
break;
}
}
@Override
public void warning(SAXParseException exception) throws SAXException {
}
@Override
public void error(SAXParseException exception) throws SAXException {
parent.log("Error parsing XML document at "+exception.getLineNumber()+","+exception.getColumnNumber(),exception);
}
@Override
public void fatalError(SAXParseException exception) throws SAXException {
parent.log("Fatal error parsing XML document at "+exception.getLineNumber()+","+exception.getColumnNumber(),exception);
}
@Override
public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {}
@Override
public void processingInstruction(String target, String data) throws SAXException {}
@Override
public void startPrefixMapping(String prefix, String uri) throws SAXException {}
@Override
public void endPrefixMapping(String prefix) throws SAXException {}
@Override
public void setDocumentLocator(org.xml.sax.Locator locator) {}
@Override
public void skippedEntity(String name) throws SAXException {}
}
private boolean equalTags(String t1, String t2) {
if(t1 == null || t2 == null) return false;
if(t1.indexOf(":") > -1) {
String[] t1s = t1.split(":");
t1 = t1s[t1s.length-1];
}
//System.out.println("Comparing: "+t1+" and "+t2);
return t1.equalsIgnoreCase(t2);
}
// -------------------------------------------------------------------------
}
| 63,725 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
UmbelSearchConcept.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/umbel/UmbelSearchConcept.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.extractors.umbel;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.wandora.application.Wandora;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.WandoraOptionPane;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.topicmap.XTMPSI;
/**
*
* @author akivela
*/
public class UmbelSearchConcept extends UmbelGetConcept {
private static final long serialVersionUID = 1L;
public static final String API_URL = "http://umbel.org/ws/search/";
public static final int MAX_PAGE_INDEX = 100;
@Override
public String getName(){
return "Umbel concept search";
}
@Override
public String getDescription(){
return "Search concepts from Umbel knowledge graph.";
}
@Override
public void execute(Wandora wandora, Context context) {
String query = WandoraOptionPane.showInputDialog(wandora, "Search for Umbel concepts with query", "", "Search for Umbel concepts", WandoraOptionPane.QUESTION_MESSAGE);
int pageIndex = 0;
int numberOfPages = 1;
ArrayList<JSONObject> allResults = new ArrayList<>();
if(query != null && query.length()>0) {
do {
String requestUrl = getApiRequestUrlFor(query);
requestUrl = requestUrl + "/page/" + pageIndex;
JSONObject response = performRequest(requestUrl, query);
if(response != null) {
if(response.has("nb-results")) {
try {
int numberOfResults = response.getInt("nb-results");
numberOfPages = (numberOfResults / 10) + 1;
}
catch(Exception e) {
e.printStackTrace();
}
}
if(response.has("results")) {
try {
JSONArray pageResults = response.getJSONArray("results");
for(int i=0; i<pageResults.length(); i++) {
allResults.add(pageResults.getJSONObject(i));
}
}
catch(Exception e) {
e.printStackTrace();
}
}
}
pageIndex++;
}
while(pageIndex < (numberOfPages-1) && pageIndex < MAX_PAGE_INDEX);
if(allResults.size() > 0) {
UmbelSearchConceptSelector selector = new UmbelSearchConceptSelector(allResults, wandora);
selector.open(wandora);
if(selector.wasAccepted()) {
ArrayList<JSONObject> selectedConcepts = selector.getSelection();
if(selectedConcepts != null && selectedConcepts.size() > 0) {
TopicMap tm = wandora.getTopicMap();
for(JSONObject conceptJSON : selectedConcepts) {
try {
System.out.println("selected concept: "+conceptJSON.getString("uri"));
String uri = conceptJSON.getString("uri");
String prefLabel = conceptJSON.getString("pref-label");
Topic conceptTopic = getConceptTopic(uri, prefLabel, tm);
if(conceptJSON.has("description")) {
String description = conceptJSON.getString("description");
if(description != null && description.length() > 0) {
Topic descriptionTypeTopic = getTopic(UMBEL_DEFINITION_URI, tm);
conceptTopic.setData(descriptionTypeTopic, getTopic(XTMPSI.getLang(LANG), tm), description);
}
}
if(conceptJSON.has("type")) {
ArrayList<String> typeUris = getAsStringArray(conceptJSON.get("type"));
for(String typeUri : typeUris) {
if(typeUri != null) {
Topic typeConceptTopic = conceptTopic;
if(!uri.equals(typeUri)) {
typeConceptTopic = getConceptTopic(typeUri, tm);
}
Topic typeTypeTopic = getTypeTypeTopic(tm);
Association a = tm.createAssociation(typeTypeTopic);
a.addPlayer(typeConceptTopic, typeTypeTopic);
a.addPlayer(conceptTopic, getConceptTypeTopic(tm));
}
}
}
if(conceptJSON.has("alt-labels")) {
ArrayList<String> labels = getAsStringArray(conceptJSON.get("alt-labels"));
StringBuilder labelsBuilder = new StringBuilder("");
boolean firstLabel = true;
for(String label : labels) {
if(label != null) {
if(!firstLabel) labelsBuilder.append(" ; ");
labelsBuilder.append(label);
firstLabel = false;
}
}
if(labelsBuilder.length() > 0) {
Topic altLabelTypeTopic = getTopic(UMBEL_ALT_LABEL_URI, tm);
conceptTopic.setData(altLabelTypeTopic, getTopic(XTMPSI.getLang(LANG), tm), labelsBuilder.toString());
}
}
}
catch(JSONException jsone) {
log(jsone);
}
catch(TopicMapException tme) {
log(tme);
}
catch(Exception e) {
log(e);
}
}
}
}
}
else {
log("Found no Umbel concepts with query '"+query+"'.");
}
}
}
private ArrayList<String> getAsStringArray(Object o) throws JSONException {
ArrayList<String> array = new ArrayList();
if(o != null) {
if(o instanceof String) {
array.add(o.toString());
}
else if(o instanceof JSONArray) {
JSONArray a = (JSONArray) o;
for(int i=0; i<a.length(); i++) {
String typeUri = a.getString(i);
array.add(typeUri);
}
}
}
return array;
}
@Override
protected JSONObject performRequest(String urlStr, String query) {
JSONObject response = null;
if(urlStr != null) {
try {
URL url = new URL(urlStr);
URLConnection urlConnection = url.openConnection();
urlConnection.addRequestProperty("Accept", "application/json");
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
if(urlConnection instanceof HttpURLConnection) {
((HttpURLConnection) urlConnection).setRequestMethod("GET");
}
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder inputBuffer = new StringBuilder("");
String inputLine;
while ((inputLine = in.readLine()) != null)
inputBuffer.append(inputLine);
in.close();
return new JSONObject(inputBuffer.toString());
}
catch(FileNotFoundException fnfe) {
log("Can't find Umbel query for '"+query+"'.");
}
catch(IOException fnfe) {
log("IOException occurred while reading URL "+urlStr+" . Skipping query '"+query+"'.");
}
catch (JSONException ex) {
log("Can't parse received Umbel JSON. Skipping concept '"+query+"'.");
}
catch(Exception e) {
log(e);
}
}
return response;
}
@Override
public String getApiRequestUrlFor(String str) {
return API_URL + urlEncode(str);
}
}
| 10,483 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
UmbelGetConcept.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/umbel/UmbelGetConcept.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.extractors.umbel;
import java.util.Iterator;
import org.json.JSONArray;
import org.json.JSONObject;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.XTMPSI;
import org.wandora.utils.Tuples;
/**
*
* @author akivela
*/
public class UmbelGetConcept extends AbstractUmbelExtractor {
private static final long serialVersionUID = 1L;
public static final String API_URL = "http://umbel.org/ws/concept/";
@Override
public String getName(){
return "Umbel concept extractor";
}
@Override
public String getDescription(){
return "Extract concepts from Umbel knowledge graph.";
}
@Override
public String getApiRequestUrlFor(String str) {
return API_URL + urlEncode(str);
}
@Override
public boolean _extractTopicsFrom(String str, TopicMap topicMap) throws Exception {
if(str != null && topicMap != null) {
String[] strs = str.split(UMBEL_CONCEPT_STRING_SPLITTER);
if(strs != null && strs.length > 0) {
for(String s : strs) {
if(s != null && s.length() > 0) {
String spiRequestUrl = getApiRequestUrlFor(s);
System.out.println("Trying: " + spiRequestUrl);
JSONObject response = performRequest(spiRequestUrl, s);
if(response != null) {
log("Getting concept '"+s+"'.");
if(response.has("resultset")) {
JSONObject resultSet = response.getJSONObject("resultset");
if(resultSet.has("subject")) {
JSONArray subjects = resultSet.getJSONArray("subject");
for(int i=0; i<subjects.length(); i++) {
JSONObject subject = subjects.getJSONObject(i);
String uri = robustGet(subject, "uri");
if(uri != null && uri.length() > 0) {
Topic conceptTopic = getConceptTopic(uri, topicMap);
if(subject.has("predicate")) {
JSONArray predicates = subject.getJSONArray("predicate");
for(int j=0; j<predicates.length(); j++) {
JSONObject predicate = predicates.getJSONObject(j);
Iterator keys = predicate.keys();
while(keys.hasNext()) {
Object key = keys.next();
if(key != null) {
String keyStr = key.toString();
if(UMBEL_PREF_LABEL_URI.equalsIgnoreCase(keyStr)) {
handleOccurrencePredicate(conceptTopic, predicate, keyStr, topicMap);
}
else if(UMBEL_ALT_LABEL_URI.equalsIgnoreCase(keyStr)) {
handleOccurrencePredicate(conceptTopic, predicate, keyStr, topicMap);
}
else if(UMBEL_DEFINITION_URI.equalsIgnoreCase(keyStr)) {
handleOccurrencePredicate(conceptTopic, predicate, keyStr, topicMap);
}
else {
handlePredicate(conceptTopic, predicate, keyStr, topicMap);
}
}
}
}
}
}
}
}
}
}
}
}
return true;
}
}
return false;
}
private void handlePredicate(Topic conceptTopic, JSONObject predicate, String predicateURI, TopicMap topicMap) {
try {
JSONObject relatedJSON = predicate.getJSONObject(predicateURI);
String relatedConceptURI = relatedJSON.getString("uri");
if(relatedConceptURI != null && relatedConceptURI.length() > 0) {
Topic relatedConceptTopic = getConceptTopic(relatedConceptURI, topicMap);
Tuples.T3<Topic,Topic,Topic> associationTopics = getAssociationTopicsForUmbelPredicate(predicateURI, topicMap);
if(associationTopics != null) {
Association a = topicMap.createAssociation(associationTopics.e1);
a.addPlayer(relatedConceptTopic, associationTopics.e2);
a.addPlayer(conceptTopic, associationTopics.e3);
}
if(relatedJSON.has("reify")) {
JSONArray detailsJSON = relatedJSON.getJSONArray("reify");
for(int i=0; i<detailsJSON.length(); i++) {
try {
JSONObject detailJSON = detailsJSON.getJSONObject(i);
if(detailJSON.has("type") && detailJSON.has("value")) {
String type = detailJSON.getString("type");
String value = detailJSON.getString("value");
if(type != null && value != null && type.length()>0 && value.length() > 0) {
if(type.equalsIgnoreCase("iron:prefLabel")) {
Topic occurrenceTypeTopic = getTopic(UMBEL_PREF_LABEL_URI, topicMap);
relatedConceptTopic.setData(occurrenceTypeTopic, getTopic(XTMPSI.getLang(LANG), topicMap), value);
}
}
}
}
catch(Exception de) {
log(de);
}
}
}
}
}
catch(Exception e) {
log(e);
}
}
private void handleOccurrencePredicate(Topic conceptTopic, JSONObject predicate, String key, TopicMap topicMap) {
try {
String value = predicate.getString(key);
if(value != null && value.length() > 0) {
Topic occurrenceTypeTopic = getTopic(key, topicMap);
conceptTopic.setData(occurrenceTypeTopic, getTopic(XTMPSI.getLang(LANG), topicMap), value);
}
}
catch(Exception e) {
log(e);
}
}
}
| 8,392 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
UmbelGetSuperType.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/umbel/UmbelGetSuperType.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.extractors.umbel;
/**
*
* @author akivela
*/
public class UmbelGetSuperType extends UmbelGetConcept {
private static final long serialVersionUID = 1L;
public static final String API_URL = "http://umbel.org/ws/super-type/";
@Override
public String getName(){
return "Umbel super type extractor";
}
@Override
public String getDescription(){
return "Extract super types from Umbel knowledge graph.";
}
@Override
public String getApiRequestUrlFor(String str) {
return API_URL + urlEncode(str);
}
}
| 1,429 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AbstractUmbelRelationExtractor.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/umbel/AbstractUmbelRelationExtractor.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.extractors.umbel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import org.json.JSONObject;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author akivela
*/
public abstract class AbstractUmbelRelationExtractor extends AbstractUmbelExtractor {
private static final long serialVersionUID = 1L;
@Override
public boolean _extractTopicsFrom(String str, TopicMap topicMap) throws Exception {
if(str != null && topicMap != null) {
String[] strs = str.split(UMBEL_CONCEPT_STRING_SPLITTER);
if(strs != null && strs.length > 0) {
for(String s : strs) {
if(s != null && s.length() > 0) {
String spiRequestUrl = getApiRequestUrlFor(s);
System.out.println("Trying: " + spiRequestUrl);
JSONObject response = performRequest(spiRequestUrl, s);
if(response != null) {
logApiRequest(s);
Topic baseConceptTopic = null; // getConceptTopic(getUmbelConceptURI(s), s, 0, topicMap);
ArrayList<Topic> conceptTopics = new ArrayList<>();
HashMap<Topic,Integer> distances = new HashMap<>();
Iterator concepts = response.keys();
while(concepts.hasNext() && !forceStop()) {
Object concept = concepts.next();
JSONObject conceptDetails = response.getJSONObject(concept.toString());
if(conceptDetails != null) {
String label = robustGet(conceptDetails, "pref-label");
int distance = robustGetInt(conceptDetails, "distance");
if(distance == 1) {
baseConceptTopic = getConceptTopic(concept.toString(), label, topicMap);
}
if(getOnlyImmediateNeighbours) {
if(distance == 2) {
Topic conceptTopic = getConceptTopic(concept.toString(), label, topicMap);
conceptTopics.add(conceptTopic);
distances.put(conceptTopic, distance);
}
}
else if(distance > filterDistancesBelow) {
Topic conceptTopic = getConceptTopic(concept.toString(), label, topicMap);
conceptTopics.add(conceptTopic);
distances.put(conceptTopic, distance);
}
}
}
if(baseConceptTopic != null && !baseConceptTopic.isRemoved() && conceptTopics.size() > 0) {
for(Topic conceptTopic : conceptTopics) {
if(forceStop()) break;
if(conceptTopic != null && !conceptTopic.isRemoved()) {
Association a = topicMap.createAssociation(getAssociationType(topicMap));
if(a != null) {
a.addPlayer(conceptTopic, getRoleTopicForConcept(topicMap));
a.addPlayer(baseConceptTopic, getRoleTopicForBaseConcept(topicMap));
if(ADD_DISTANCE_AS_PLAYER) {
int distance = distances.get(conceptTopic);
if(distance > 0) {
a.addPlayer(getDistanceTopic(distance,topicMap), getDistanceTypeTopic(topicMap));
}
}
}
}
}
}
}
}
}
return true;
}
}
return false;
}
public abstract void logApiRequest(String str);
public abstract Topic getAssociationType(TopicMap topicMap) throws TopicMapException;
public abstract Topic getRoleTopicForConcept(TopicMap topicMap) throws TopicMapException;
public abstract Topic getRoleTopicForBaseConcept(TopicMap topicMap) throws TopicMapException;
}
| 5,810 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
UmbelGetSubclasses.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/umbel/UmbelGetSubclasses.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.extractors.umbel;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author akivela
*/
public class UmbelGetSubclasses extends AbstractUmbelRelationExtractor {
private static final long serialVersionUID = 1L;
public static final String API_URL = "http://umbel.org/ws/sub-classes/ext/";
@Override
public String getName(){
return "Subclasses Umbel concept extractor";
}
@Override
public String getDescription(){
return "Extract subclass concepts from Umbel.";
}
@Override
public String getApiRequestUrlFor(String str) {
return API_URL + urlEncode(str);
}
@Override
public void logApiRequest(String str) {
log("Getting subclass concepts of '"+str+"'.");
}
@Override
public Topic getAssociationType(TopicMap topicMap) throws TopicMapException {
return getSuperclassSubclassTypeTopic(topicMap);
}
@Override
public Topic getRoleTopicForConcept(TopicMap topicMap) throws TopicMapException {
return getSuperclassTypeTopic(topicMap);
}
@Override
public Topic getRoleTopicForBaseConcept(TopicMap topicMap) throws TopicMapException {
return getSubclassTypeTopic(topicMap);
}
}
| 2,197 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
UmbelGetNarrower.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/umbel/UmbelGetNarrower.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.extractors.umbel;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author akivela
*/
public class UmbelGetNarrower extends AbstractUmbelRelationExtractor {
private static final long serialVersionUID = 1L;
public static final String API_URL = "http://umbel.org/ws/narrower-concepts/ext/";
@Override
public String getName(){
return "Narrower Umbel concept extractor";
}
@Override
public String getDescription(){
return "Extract narrower concepts from Umbel.";
}
@Override
public String getApiRequestUrlFor(String str) {
return API_URL + urlEncode(str);
}
@Override
public void logApiRequest(String str) {
log("Getting narrower concepts of '"+str+"'.");
}
@Override
public Topic getAssociationType(TopicMap topicMap) throws TopicMapException {
return getBroaderNarrowerTypeTopic(topicMap);
}
@Override
public Topic getRoleTopicForConcept(TopicMap topicMap) throws TopicMapException {
return getNarrowerTypeTopic(topicMap);
}
@Override
public Topic getRoleTopicForBaseConcept(TopicMap topicMap) throws TopicMapException {
return getBroaderTypeTopic(topicMap);
}
}
| 2,177 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
UmbelSearchConceptSelector.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/umbel/UmbelSearchConceptSelector.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.extractors.umbel;
import java.awt.Cursor;
import java.util.ArrayList;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import org.json.JSONObject;
import org.wandora.application.Wandora;
import org.wandora.application.gui.simple.SimpleButton;
import org.wandora.application.gui.simple.SimpleLabel;
/**
*
* @author akivela
*/
public class UmbelSearchConceptSelector extends javax.swing.JDialog {
private boolean wasAccepted = false;
private ArrayList<JSONObject> data = null;
private JTable dataTable = null;
private UmbelConceptTableModel dataModel = null;
/**
* Creates new form UmbelSearchConceptSelector
*/
public UmbelSearchConceptSelector(ArrayList<JSONObject> data, Wandora wandora) {
super(wandora, true);
this.data = data;
initComponents();
wasAccepted = false;
updateDataTable();
setTitle("Search and import Umbel concepts");
}
public void open(Wandora wandora) {
wasAccepted = false;
this.setSize(950, 500);
if(wandora != null) wandora.centerWindow(this);
this.setVisible(true);
}
private void updateDataTable() {
dataTable = new JTable();
dataTable.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
if(data != null) {
dataModel = new UmbelConceptTableModel(data);
dataTable.setModel(dataModel);
dataTable.setRowSorter(new TableRowSorter(dataModel));
dataTable.setColumnSelectionAllowed(false);
dataTable.setRowSelectionAllowed(true);
dataTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
TableColumn column = null;
for (int i=0; i < dataTable.getColumnCount(); i++) {
column = dataTable.getColumnModel().getColumn(i);
column.setPreferredWidth(dataModel.getColumnWidth(i));
}
tableScrollPane.setViewportView(dataTable);
}
}
public boolean wasAccepted() {
return wasAccepted;
}
public ArrayList<JSONObject> getSelection() {
ArrayList<JSONObject> selection = new ArrayList<JSONObject>();
int[] indexes = dataTable.getSelectedRows();
for(int i=0; i<indexes.length; i++) {
selection.add(data.get(dataTable.convertRowIndexToModel(indexes[i])));
}
return selection;
}
/**
* 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;
containerPanel = new javax.swing.JPanel();
headerPanel = new javax.swing.JPanel();
headerLabel = new SimpleLabel();
tablePanel = new javax.swing.JPanel();
tableScrollPane = new javax.swing.JScrollPane();
buttonPanel = new javax.swing.JPanel();
buttonFillerPanel = new javax.swing.JPanel();
importButton = new SimpleButton();
cancelButton = new SimpleButton();
getContentPane().setLayout(new java.awt.GridBagLayout());
containerPanel.setLayout(new java.awt.GridBagLayout());
headerPanel.setLayout(new java.awt.GridBagLayout());
headerLabel.setText("<html>Select which Umbel concepts you would like to import to Wandora. Keep SHIFT or CTRL key pressed to select multiple concepts. After selection press import button.</html>");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
gridBagConstraints.weightx = 1.0;
headerPanel.add(headerLabel, gridBagConstraints);
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;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 8, 0);
containerPanel.add(headerPanel, gridBagConstraints);
tablePanel.setLayout(new java.awt.GridBagLayout());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
tablePanel.add(tableScrollPane, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
containerPanel.add(tablePanel, gridBagConstraints);
buttonPanel.setLayout(new java.awt.GridBagLayout());
buttonFillerPanel.setPreferredSize(new java.awt.Dimension(254, 8));
javax.swing.GroupLayout buttonFillerPanelLayout = new javax.swing.GroupLayout(buttonFillerPanel);
buttonFillerPanel.setLayout(buttonFillerPanelLayout);
buttonFillerPanelLayout.setHorizontalGroup(
buttonFillerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 350, Short.MAX_VALUE)
);
buttonFillerPanelLayout.setVerticalGroup(
buttonFillerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 8, Short.MAX_VALUE)
);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
buttonPanel.add(buttonFillerPanel, gridBagConstraints);
importButton.setText("Import");
importButton.setMargin(new java.awt.Insets(2, 4, 2, 4));
importButton.setPreferredSize(new java.awt.Dimension(80, 23));
importButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
importButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 2);
buttonPanel.add(importButton, gridBagConstraints);
cancelButton.setText("Cancel");
cancelButton.setMargin(new java.awt.Insets(2, 4, 2, 4));
cancelButton.setPreferredSize(new java.awt.Dimension(80, 23));
cancelButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelButtonActionPerformed(evt);
}
});
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, 0, 0, 0);
containerPanel.add(buttonPanel, 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(4, 4, 4, 4);
getContentPane().add(containerPanel, gridBagConstraints);
pack();
}// </editor-fold>//GEN-END:initComponents
private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
wasAccepted = false;
this.setVisible(false);
}//GEN-LAST:event_cancelButtonActionPerformed
private void importButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_importButtonActionPerformed
wasAccepted = true;
this.setVisible(false);
}//GEN-LAST:event_importButtonActionPerformed
// 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.JPanel containerPanel;
private javax.swing.JLabel headerLabel;
private javax.swing.JPanel headerPanel;
private javax.swing.JButton importButton;
private javax.swing.JPanel tablePanel;
private javax.swing.JScrollPane tableScrollPane;
// End of variables declaration//GEN-END:variables
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
public class UmbelConceptTableModel extends DefaultTableModel implements TableModel {
ArrayList<JSONObject> d = null;
public UmbelConceptTableModel(ArrayList<JSONObject> m) {
d = m;
}
@Override
public int getRowCount() {
if(d == null) return 0;
return d.size();
}
@Override
public int getColumnCount() {
return 3;
}
@Override
public String getColumnName(int columnIndex) {
switch(columnIndex) {
case 0: return "uri";
case 1: return "pref-label";
case 2: return "description";
default: return "Illegal column";
}
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
if(d == null) return null;
if(rowIndex >= 0 && rowIndex < d.size()) {
if(columnIndex >= 0 && columnIndex < 6) {
try {
JSONObject v = d.get(rowIndex);
switch(columnIndex) {
case 0: return v.get("uri").toString();
case 1: return v.get("pref-label").toString();
case 2: return v.get("description").toString();
}
}
catch(Exception e) {
return "";
}
}
}
return null;
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
}
public int getColumnWidth(int col) {
switch(col) {
case 0: return 200;
case 1: return 100;
case 2: return 400;
default: return 100;
}
}
}
}
| 12,292 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
UmbelGetSuperclasses.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/umbel/UmbelGetSuperclasses.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.extractors.umbel;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author akivela
*/
public class UmbelGetSuperclasses extends AbstractUmbelRelationExtractor {
private static final long serialVersionUID = 1L;
public static final String API_URL = "http://umbel.org/ws/super-classes/ext/";
@Override
public String getName(){
return "Superclass Umbel concept extractor";
}
@Override
public String getDescription(){
return "Extract superclass concepts from Umbel.";
}
@Override
public String getApiRequestUrlFor(String str) {
return API_URL + urlEncode(str);
}
@Override
public void logApiRequest(String str) {
log("Getting superclass concepts of '"+str+"'.");
}
@Override
public Topic getAssociationType(TopicMap topicMap) throws TopicMapException {
return getSuperclassSubclassTypeTopic(topicMap);
}
@Override
public Topic getRoleTopicForConcept(TopicMap topicMap) throws TopicMapException {
return getSuperclassTypeTopic(topicMap);
}
@Override
public Topic getRoleTopicForBaseConcept(TopicMap topicMap) throws TopicMapException {
return getSubclassTypeTopic(topicMap);
}
}
| 2,205 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AbstractUmbelExtractor.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/umbel/AbstractUmbelExtractor.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.extractors.umbel;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import javax.swing.Icon;
import org.json.JSONException;
import org.json.JSONObject;
import org.wandora.application.gui.UIBox;
import org.wandora.application.tools.extractors.AbstractExtractor;
import org.wandora.application.tools.extractors.ExtractHelper;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.topicmap.XTMPSI;
import org.wandora.utils.CSVParser;
import org.wandora.utils.CSVParser.Row;
import org.wandora.utils.IObox;
import org.wandora.utils.Tuples.T3;
/**
*
* @author akivela
*/
public abstract class AbstractUmbelExtractor extends AbstractExtractor {
private static final long serialVersionUID = 1L;
public static final String UMBEL_CONCEPT_STRING_SPLITTER = "\\s+";
public static final int FILE_CONTAINS_UMBEL_CONCEPT_URLS = 2;
public static final int FILE_CONTAINS_PLAIN_UMBEL_CONCEPT = 4;
public static final int FILE_IS_CSV_OF_UMBEL_CONCEPTS = 8;
public static int fileProcessor = FILE_CONTAINS_UMBEL_CONCEPT_URLS;
public static boolean ADD_DISTANCE_AS_PLAYER = false;
public static int filterDistancesBelow = 1;
public static boolean getOnlyImmediateNeighbours = true;
public static boolean useXTMSuperclassSubclassTopics = true;
protected static char csvStringCharacter = '"';
protected static char csvLineSeparator = '\n';
protected static char csvValueSeparator = ',';
protected static String csvEncoding = "UTF-8";
// Default language of occurrences and variant names.
public static String LANG = "en";
public static final String UMBEL_CONCEPT_URI_BASE = "http://umbel.org/umbel/rc/";
public static final String UMBEL_SUPER_TYPE_URI_BASE = "http://umbel.org/umbel#";
public static final String UMBEL_TYPE_SI = "http://umbel.org";
public static final String UMBEL_TYPE_NAME = "Umbel";
public static final String UMBEL_CONCEPT_TYPE_SI = "http://wandora.org/si/umbel/concept";
public static final String UMBEL_CONCEPT_TYPE_NAME = "concept (umbel)";
public static final String UMBEL_BROADER_NARROWER_TYPE_SI = "http://wandora.org/si/umbel/broader-narrower";
public static final String UMBEL_BROADER_NARROWER_TYPE_NAME = "broader-narrower (umbel)";
public static final String UMBEL_NARROWER_TYPE_SI = "http://wandora.org/si/umbel/narrower";
public static final String UMBEL_NARROWER_TYPE_NAME = "narrower (umbel)";
public static final String UMBEL_BROADER_TYPE_SI = "http://wandora.org/si/umbel/broader";
public static final String UMBEL_BROADER_TYPE_NAME = "broader (umbel)";
public static final String UMBEL_SUPERCLASS_SUBCLASS_TYPE_SI = "http://wandora.org/si/umbel/superclass-subclass";
public static final String UMBEL_SUPERCLASS_SUBCLASS_TYPE_NAME = "superclass-subclass (umbel)";
public static final String UMBEL_SUBCLASS_TYPE_SI = "http://wandora.org/si/umbel/subclass";
public static final String UMBEL_SUBCLASS_TYPE_NAME = "subclass (umbel)";
public static final String UMBEL_SUPERCLASS_TYPE_SI = "http://wandora.org/si/umbel/superclass";
public static final String UMBEL_SUPERCLASS_TYPE_NAME = "superclass (umbel)";
public static final String UMBEL_TYPE_TYPE_SI = "http://wandora.org/si/umbel/type";
public static final String UMBEL_TYPE_TYPE_NAME = "type (umbel)";
public static final String UMBEL_DISTANCE_TYPE_SI = "http://wandora.org/si/umbel/distance";
public static final String UMBEL_DISTANCE_TYPE_NAME = "distance (umbel)";
public static final String UMBEL_DISJOINT_TYPE_SI = "http://wandora.org/si/umbel/disjoint";
public static final String UMBEL_DISJOINT_TYPE_NAME = "disjoint (umbel)";
// -------------------------------------------------------------------------
public static final String UMBEL_PREF_LABEL_URI = "http://www.w3.org/2004/02/skos/core#prefLabel";
public static final String UMBEL_ALT_LABEL_URI = "http://www.w3.org/2004/02/skos/core#altLabel";
public static final String UMBEL_DEFINITION_URI = "http://www.w3.org/2004/02/skos/core#definition";
public static final String[] UMBEL_SUBCLASS_URI = {
"http://umbel.org/umbel#subClassOf",
"http://www.w3.org/TR/rdf-schema#subClassOf",
"http://www.w3.org/2000/01/rdf-schema#subClassOf"
};
public static final String[] UMBEL_SUPERCLASS_URI = {
"http://umbel.org/umbel#superClassOf",
"http://www.w3.org/TR/rdf-schema#superClassOf",
"http://www.w3.org/2000/01/rdf-schema#superClassOf"
};
public static final String[] UMBEL_NARROWER_URI = {
"http://www.w3.org/2004/02/skos/core#narrower",
"http://www.w3.org/2004/02/skos/core#narrowerTransitive",
};
public static final String[] UMBEL_BROADER_URI = {
"http://www.w3.org/2004/02/skos/core#broader",
"http://www.w3.org/2004/02/skos/core#broaderTransitive",
};
public static final String[] UMBEL_TYPE_URI = {
"http://www.w3.org/1999/02/22-rdf-syntax-ns#type",
};
public static final String[] UMBEL_DISJOINT_URI = {
"http://www.w3.org/2002/07/owl#disjointWith"
};
@Override
public String getName(){
return "Abstract Umbel Extractor";
}
@Override
public String getDescription(){
return "AbstractUmbelExtractor is a base implementation for Umbel extractors.";
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/extract_umbel.png");
}
private final String[] contentTypes=new String[] { "application/json" };
@Override
public String[] getContentTypes() {
return contentTypes;
}
@Override
public boolean useURLCrawler() {
return false;
}
@Override
public int getExtractorType() {
return URL_EXTRACTOR | RAW_EXTRACTOR;
//return FILE_EXTRACTOR | URL_EXTRACTOR | RAW_EXTRACTOR;
}
public abstract String getApiRequestUrlFor(String str);
@Override
public boolean _extractTopicsFrom(URL url, TopicMap topicMap) throws Exception {
if(url != null) {
String str = url.toExternalForm();
if(str.startsWith(UMBEL_CONCEPT_URI_BASE) && str.length() > UMBEL_CONCEPT_URI_BASE.length()) {
str = str.substring(UMBEL_CONCEPT_URI_BASE.length());
}
if(str.startsWith(UMBEL_SUPER_TYPE_URI_BASE) && str.length() > UMBEL_SUPER_TYPE_URI_BASE.length()) {
str = str.substring(UMBEL_SUPER_TYPE_URI_BASE.length());
}
return _extractTopicsFrom(str, topicMap);
}
return false;
}
@Override
public boolean _extractTopicsFrom(File file, TopicMap topicMap) throws Exception {
if(fileProcessor == FILE_CONTAINS_UMBEL_CONCEPT_URLS) {
String input = IObox.loadFile(file);
int i = 0;
do {
i = input.indexOf(UMBEL_CONCEPT_URI_BASE, i);
if(i > 0) {
i = i + UMBEL_CONCEPT_URI_BASE.length();
StringBuilder conceptBuilder = new StringBuilder("");
while(i<input.length()-1 && Character.isJavaIdentifierPart(input.charAt(i))) {
conceptBuilder.append(input.charAt(i));
i++;
}
if(conceptBuilder.length() > 0) {
String conceptString = conceptBuilder.toString();
_extractTopicsFrom(conceptString, topicMap);
}
}
}
while(i > 0 && i<input.length()-1);
return true;
}
else if(fileProcessor == FILE_IS_CSV_OF_UMBEL_CONCEPTS) {
CSVParser parser = new CSVParser();
parser.setEncoding(csvEncoding);
parser.setLineSeparator(csvLineSeparator);
parser.setValueSeparator(csvValueSeparator);
parser.setStringCharacter(csvStringCharacter);
CSVParser.Table table = parser.parse(new ByteArrayInputStream(IObox.loadBFile(new FileInputStream(file))));
Iterator<Row> i = table.iterator();
while(i.hasNext()) {
Row r = i.next();
if(r != null) {
Iterator<Object> c = r.iterator();
while(c.hasNext()) {
Object o = c.next();
if(o != null) {
String conceptString = o.toString();
_extractTopicsFrom(conceptString, topicMap);
}
}
}
}
return true;
}
else {
String input = IObox.loadFile(file);
return _extractTopicsFrom(input, topicMap);
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
public String getUmbelConceptURI(String label) {
return UMBEL_CONCEPT_URI_BASE+label;
}
protected JSONObject performRequest(String urlStr, String concept) {
JSONObject response = null;
if(urlStr != null) {
try {
URL url = new URL(urlStr);
URLConnection urlConnection = url.openConnection();
urlConnection.addRequestProperty("Accept", "application/json");
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
if(urlConnection instanceof HttpURLConnection) {
((HttpURLConnection) urlConnection).setRequestMethod("GET");
}
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder inputBuffer = new StringBuilder("");
String inputLine;
while ((inputLine = in.readLine()) != null)
inputBuffer.append(inputLine);
in.close();
return new JSONObject(inputBuffer.toString());
}
catch(FileNotFoundException fnfe) {
log("Can't find Umbel concept for '"+concept+"'.");
}
catch(IOException fnfe) {
log("IOException occurred while reading URL "+urlStr+" . Skipping concept '"+concept+"'.");
}
catch (JSONException ex) {
log("Can't parse received Umbel JSON. Skipping concept '"+concept+"'.");
}
catch(Exception e) {
log(e);
}
}
return response;
}
protected String robustGet(JSONObject json, String key) {
if(json == null || key == null) return null;
if(json.has(key)) {
try {
return json.getString(key);
}
catch(Exception e) {}
}
return null;
}
protected int robustGetInt(JSONObject json, String key) {
if(json == null || key == null) return -1;
if(json.has(key)) {
try {
return json.getInt(key);
}
catch(Exception e) {}
}
return -1;
}
// -------------------------------------------------------------------------
protected Topic getConceptTopic(String si, TopicMap topicMap) {
return getConceptTopic(si, null, topicMap);
}
protected Topic getConceptTopic(String si, String label, TopicMap topicMap) {
if(si == null || topicMap == null) return null;
Topic t = null;
try {
t = topicMap.getTopic(si);
if(t == null && label != null) {
t = topicMap.getTopicWithBaseName(label);
}
if(t == null) {
t = topicMap.createTopic();
t.addSubjectIdentifier(new Locator(si));
t.addType(getConceptTypeTopic(topicMap));
}
if(t != null && label != null && label.length() > 0) {
Topic occurrenceTypeTopic = getTopic(UMBEL_PREF_LABEL_URI, topicMap);
t.setData(occurrenceTypeTopic, getTopic(XTMPSI.getLang(LANG), topicMap), label);
}
}
catch(Exception e) {}
return t;
}
protected boolean isURL(String u) {
try {
URL url = new URL(u);
return true;
}
catch(Exception e) {}
return false;
}
// -------------------------------------------------------------------------
protected Topic getUmbelTypeTopic(TopicMap topicMap) throws TopicMapException {
Topic t = getTopic(UMBEL_TYPE_SI, UMBEL_TYPE_NAME, topicMap);
this.makeSubclassOfWandoraClass(t, topicMap);
return t;
}
protected Topic getBroaderNarrowerTypeTopic(TopicMap topicMap) throws TopicMapException {
Topic t = getTopic(UMBEL_BROADER_NARROWER_TYPE_SI, UMBEL_BROADER_NARROWER_TYPE_NAME, topicMap);
ExtractHelper.makeSubclassOf(t, getUmbelTypeTopic(topicMap), topicMap);
return t;
}
protected Topic getNarrowerTypeTopic(TopicMap topicMap) throws TopicMapException {
Topic t = getTopic(UMBEL_NARROWER_TYPE_SI, UMBEL_NARROWER_TYPE_NAME, topicMap);
ExtractHelper.makeSubclassOf(t, getUmbelTypeTopic(topicMap), topicMap);
return t;
}
protected Topic getBroaderTypeTopic(TopicMap topicMap) throws TopicMapException {
Topic t = getTopic(UMBEL_BROADER_TYPE_SI, UMBEL_BROADER_TYPE_NAME, topicMap);
ExtractHelper.makeSubclassOf(t, getUmbelTypeTopic(topicMap), topicMap);
return t;
}
protected Topic getDisjointTypeTopic(TopicMap topicMap) throws TopicMapException {
Topic t = getTopic(UMBEL_DISJOINT_TYPE_SI, UMBEL_DISJOINT_TYPE_NAME, topicMap);
ExtractHelper.makeSubclassOf(t, getUmbelTypeTopic(topicMap), topicMap);
return t;
}
protected Topic getTypeTypeTopic(TopicMap topicMap) throws TopicMapException {
Topic t = getTopic(UMBEL_TYPE_TYPE_SI, UMBEL_TYPE_TYPE_NAME, topicMap);
ExtractHelper.makeSubclassOf(t, getUmbelTypeTopic(topicMap), topicMap);
return t;
}
protected Topic getSuperclassSubclassTypeTopic(TopicMap topicMap) throws TopicMapException {
Topic t = null;
if(useXTMSuperclassSubclassTopics) {
t = getTopic(XTMPSI.SUPERCLASS_SUBCLASS, topicMap);
}
else {
t = getTopic(UMBEL_SUPERCLASS_SUBCLASS_TYPE_SI, UMBEL_SUPERCLASS_SUBCLASS_TYPE_NAME, topicMap);
}
ExtractHelper.makeSubclassOf(t, getUmbelTypeTopic(topicMap), topicMap);
return t;
}
protected Topic getSubclassTypeTopic(TopicMap topicMap) throws TopicMapException {
Topic t = null;
if(useXTMSuperclassSubclassTopics) {
t = getTopic(XTMPSI.SUBCLASS, topicMap);
}
else {
t = getTopic(UMBEL_SUBCLASS_TYPE_SI, UMBEL_SUBCLASS_TYPE_NAME, topicMap);
}
ExtractHelper.makeSubclassOf(t, getUmbelTypeTopic(topicMap), topicMap);
return t;
}
protected Topic getSuperclassTypeTopic(TopicMap topicMap) throws TopicMapException {
Topic t = null;
if(useXTMSuperclassSubclassTopics) {
t = getTopic(XTMPSI.SUPERCLASS, topicMap);
}
else {
t = getTopic(UMBEL_SUPERCLASS_TYPE_SI, UMBEL_SUPERCLASS_TYPE_NAME, topicMap);
}
ExtractHelper.makeSubclassOf(t, getUmbelTypeTopic(topicMap), topicMap);
return t;
}
protected Topic getConceptTypeTopic(TopicMap topicMap) throws TopicMapException {
Topic t = getTopic(UMBEL_CONCEPT_TYPE_SI, UMBEL_CONCEPT_TYPE_NAME, topicMap);
ExtractHelper.makeSubclassOf(t, getUmbelTypeTopic(topicMap), topicMap);
return t;
}
protected Topic getDistanceTopic(int distance, TopicMap topicMap) throws TopicMapException {
Topic dt = getTopic(UMBEL_DISTANCE_TYPE_SI+"/"+distance, ""+distance, topicMap);
Topic dtt = getDistanceTypeTopic(topicMap);
dt.addType(dtt);
return dt;
}
protected Topic getDistanceTypeTopic(TopicMap topicMap) throws TopicMapException {
Topic t = getTopic(UMBEL_DISTANCE_TYPE_SI, UMBEL_DISTANCE_TYPE_NAME, topicMap);
ExtractHelper.makeSubclassOf(t, getUmbelTypeTopic(topicMap), topicMap);
return t;
}
protected Topic getTopic(String si, String name, TopicMap topicMap) {
Topic t = null;
if(si != null && topicMap != null) {
try {
t = topicMap.getTopic(si);
if(t == null && name != null) t = topicMap.getTopicWithBaseName(name);
if(t == null) {
t = topicMap.createTopic();
t.addSubjectIdentifier(new Locator(si));
if(name != null) t.setBaseName(name);
}
}
catch(Exception e) {}
}
return t;
}
protected Topic getTopic(String si, TopicMap topicMap) {
Topic t = null;
if(si != null && topicMap != null) {
try {
t = topicMap.getTopic(si);
if(t == null) {
t = topicMap.createTopic();
t.addSubjectIdentifier(new Locator(si));
}
}
catch(Exception e) {}
}
return t;
}
protected T3<Topic,Topic,Topic> getAssociationTopicsForUmbelPredicate(String predicate, TopicMap tm) {
if(predicate == null) return null;
try {
if(equalsAny(predicate, UMBEL_SUBCLASS_URI)) {
return new T3( getSuperclassSubclassTypeTopic(tm), getSuperclassTypeTopic(tm), getSubclassTypeTopic(tm) );
}
else if(equalsAny(predicate, UMBEL_SUPERCLASS_URI)) {
return new T3( getSuperclassSubclassTypeTopic(tm), getSubclassTypeTopic(tm), getSuperclassTypeTopic(tm) );
}
else if(equalsAny(predicate, UMBEL_BROADER_URI)) {
return new T3( getBroaderNarrowerTypeTopic(tm), getBroaderTypeTopic(tm), getNarrowerTypeTopic(tm) );
}
else if(equalsAny(predicate, UMBEL_NARROWER_URI)) {
return new T3( getBroaderNarrowerTypeTopic(tm), getNarrowerTypeTopic(tm), getBroaderTypeTopic(tm) );
}
else if(equalsAny(predicate, UMBEL_TYPE_URI)) {
return new T3( getTypeTypeTopic(tm), getTypeTypeTopic(tm), getConceptTypeTopic(tm) );
}
else if(equalsAny(predicate, UMBEL_DISJOINT_URI)) {
return new T3( getDisjointTypeTopic(tm), getDisjointTypeTopic(tm), getConceptTypeTopic(tm) );
}
else {
return new T3( getTopic(predicate, tm), getTopic(predicate, tm), getConceptTypeTopic(tm) );
}
}
catch(Exception e) {
e.printStackTrace();
}
return null;
}
protected boolean equalsAny(String a, String[] b) {
for(int i=0; i<b.length; i++) {
if(a.equalsIgnoreCase(b[i])) return true;
}
return false;
}
}
| 20,986 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
UmbelGetBroader.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/umbel/UmbelGetBroader.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.extractors.umbel;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author akivela
*/
public class UmbelGetBroader extends AbstractUmbelRelationExtractor {
private static final long serialVersionUID = 1L;
public static final String API_URL = "http://umbel.org/ws/broader-concepts/ext/";
@Override
public String getName(){
return "Broader Umbel concept extractor";
}
@Override
public String getDescription(){
return "Extract broader concepts from Umbel.";
}
@Override
public String getApiRequestUrlFor(String str) {
return API_URL + urlEncode(str);
}
@Override
public void logApiRequest(String str) {
log("Getting broader concepts of '"+str+"'.");
}
@Override
public Topic getAssociationType(TopicMap topicMap) throws TopicMapException {
return getBroaderNarrowerTypeTopic(topicMap);
}
@Override
public Topic getRoleTopicForConcept(TopicMap topicMap) throws TopicMapException {
return getBroaderTypeTopic(topicMap);
}
@Override
public Topic getRoleTopicForBaseConcept(TopicMap topicMap) throws TopicMapException {
return getNarrowerTypeTopic(topicMap);
}
}
| 2,187 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
StanfordNERClassifier.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/stanfordner/StanfordNERClassifier.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.extractors.stanfordner;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import javax.swing.Icon;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraToolType;
import org.wandora.application.gui.UIBox;
import org.wandora.application.tools.extractors.AbstractExtractor;
import org.wandora.application.tools.extractors.ExtractHelper;
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;
import org.wandora.utils.Options;
import org.wandora.utils.Textbox;
import org.wandora.utils.XMLbox;
import edu.stanford.nlp.ie.AbstractSequenceClassifier;
import edu.stanford.nlp.ie.crf.CRFClassifier;
import edu.stanford.nlp.ling.CoreAnnotations.AnswerAnnotation;
import edu.stanford.nlp.ling.CoreLabel;
/**
*
* @author akivela
*/
public class StanfordNERClassifier extends AbstractExtractor {
private static final long serialVersionUID = 1L;
public static final String SOURCE_SI = "http://wandora.org/si/source";
public static final String DOCUMENT_SI = "http://wandora.org/si/document";
public static final String TOPIC_SI = "http://wandora.org/si/topic";
public static final String ENTITY_SI = "http://wandora.org/si/stanford-ner/entity";
public static final String ENTITY_TYPE_SI = "http://wandora.org/si/stanford-ner/type";
public static final String STANFORD_NER_SI = "http://nlp.stanford.edu/software/CRF-NER.shtml";
public static final String classifierPath = "lib/stanford-ner/classifiers/";
public String defaultClassifier = classifierPath + "ner-eng-ie.crf-3-all2008.ser.gz";
private String selectedClassifier = defaultClassifier;
private String defaultEncoding = "UTF-8";
public String optionsPath = "stanfordNERclassifier";
@Override
public String getName() {
return "Stanford Named Entity Recognizer";
}
@Override
public String getDescription(){
return "Extracts topics out of given text using Stanford Named Entity Recognizer (NER). Read more at http://nlp.stanford.edu/software/CRF-NER.shtml";
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/extract_stanford_ner.png");
}
@Override
public WandoraToolType getType() {
return WandoraToolType.createExtractType();
}
private final String[] contentTypes=new String[] { "text/plain", "text/html" };
@Override
public String[] getContentTypes() {
return contentTypes;
}
@Override
public boolean useURLCrawler() {
return false;
}
// -------------------------------------------------------------------------
@Override
public boolean isConfigurable(){
return true;
}
@Override
public void configure(Wandora admin, Options options, String prefix) throws TopicMapException {
StanfordNERConfiguration dialog = new StanfordNERConfiguration(admin, options, this);
dialog.setVisible(true);
if(dialog.wasAccepted()) {
String classifier = dialog.getSuggestedClassifier();
if(classifier != null && classifier.trim().length() != 0) {
options.put(optionsPath, classifier);
selectedClassifier = classifier;
}
}
}
@Override
public void writeOptions(Wandora admin, Options options, String prefix) {
}
// -------------------------------------------------------------------------
public boolean _extractTopicsFrom(URL url, TopicMap topicMap) throws Exception {
return _extractTopicsFrom(url.openStream(),topicMap);
}
public boolean _extractTopicsFrom(File file, TopicMap topicMap) throws Exception {
return _extractTopicsFrom(new FileInputStream(file),topicMap);
}
public boolean _extractTopicsFrom(InputStream in, TopicMap topicMap) throws Exception {
String data = IObox.loadFile(in, defaultEncoding);
return _extractTopicsFrom(data, topicMap);
}
public boolean _extractTopicsFrom(String data, TopicMap topicMap) throws Exception {
if(data != null && data.length() > 0) {
data = XMLbox.naiveGetAsText(data); // Strip HTML
int entityCounter = 0;
String serializedClassifier = selectedClassifier;
AbstractSequenceClassifier<CoreLabel> classifier = null;
try {
classifier = CRFClassifier.getClassifierNoExceptions(serializedClassifier);
}
catch(Exception e) {
log(e);
}
catch(Error er) {
log(er);
}
if(classifier != null) {
Topic masterTopic = null;
String masterSubject = getMasterSubject();
if(masterSubject != null) {
try {
masterTopic = topicMap.getTopicWithBaseName(masterSubject);
if(masterTopic == null) masterTopic = topicMap.getTopic(masterSubject);
}
catch(Exception e) {
log(e);
}
}
if(masterTopic == null && data != null && data.length() > 0) {
try {
masterTopic = topicMap.createTopic();
masterTopic.addSubjectIdentifier(topicMap.makeSubjectIndicatorAsLocator());
fillDocumentTopic(masterTopic, topicMap, data);
}
catch(Exception e) {
log(e);
}
}
List<List<CoreLabel>> out = classifier.classify(data);
for(List<CoreLabel> sentence : out) {
if(forceStop()) break;
for (CoreLabel word : sentence) {
if(forceStop()) break;
Object an = word.get(AnswerAnnotation.class);
if(!"O".equals(an.toString())) {
try {
processNER(word.word(), an.toString(), masterTopic, topicMap);
log("Recognized entity type '"+an+"' for entity '"+word.word()+"'.");
}
catch(Exception e) {
log(e);
}
entityCounter++;
setProgress(entityCounter);
}
}
}
/*
out = classifier.classifyFile(args[1]);
for (List<CoreLabel> sentence : out) {
for (CoreLabel word : sentence) {
System.out.print(word.word() + '/' + word.get(AnswerAnnotation.class) + ' ');
}
System.out.println();
}
System.out.println(classifier.classifyToString(s1));
System.out.println(classifier.classifyWithInlineXML(s2));
System.out.println(classifier.classifyToString(s2, "xml", true));
*/
log("Total " + entityCounter + " entities found by Stanford Named Entity Recognizer.");
}
else {
log("Invalid classifier! Aborting!");
}
}
else {
log("No valid data given! Aborting!");
}
return true;
}
public void processNER(String word, String type, Topic masterTopic, TopicMap tm) throws TopicMapException {
Topic entityTopic = getEntityTopic(word, type, tm);
if(entityTopic != null && masterTopic != null) {
Topic entityType = getEntityTypeType(tm);
Association a = tm.createAssociation(entityType);
a.addPlayer(masterTopic, getTopicType(tm));
a.addPlayer(entityTopic, entityType);
}
}
// -------------------------------------------------------------------------
public Topic getEntityTypeType(TopicMap tm) throws TopicMapException {
Topic t = getOrCreateTopic(tm, ENTITY_TYPE_SI, "Stanford NER entity");
t.addType(getStanfordNERClass(tm));
return t;
}
public Topic getEntityType(String type, TopicMap tm) throws TopicMapException {
String encodedType = type;
try { encodedType = URLEncoder.encode(type, "utf-8"); }
catch(Exception e) {}
Topic t = getOrCreateTopic(tm, ENTITY_TYPE_SI+"/"+encodedType, type);
t.addType(getStanfordNERClass(tm));
return t;
}
public Topic getEntityTopic(String entity, String type, TopicMap tm) throws TopicMapException {
if(entity != null) {
entity = entity.trim();
if(entity.length() > 0) {
String encodedEntity = entity;
try { encodedEntity = URLEncoder.encode(entity, "utf-8"); }
catch(Exception e) {}
Topic entityTopic=getOrCreateTopic(tm, ENTITY_SI+"/"+encodedEntity, entity);
if(type != null && type.length() > 0) {
Topic entityTypeTopic = getEntityType(type, tm);
entityTopic.addType(entityTypeTopic);
entityTopic.addType(getEntityTypeType(tm));
}
return entityTopic;
}
}
return null;
}
public Topic getStanfordNERClass(TopicMap tm) throws TopicMapException {
Topic t = getOrCreateTopic(tm, STANFORD_NER_SI, "Stanford NER");
makeSubclassOf(tm, t, getWandoraClass(tm));
return t;
}
public Topic getWandoraClass(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, TMBox.WANDORACLASS_SI,"Wandora class");
}
public Topic getTopicType(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, TOPIC_SI, "Topic");
}
public Topic getSourceType(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, SOURCE_SI, "Source");
}
public Topic getDocumentType(TopicMap tm) throws TopicMapException {
Topic type = getOrCreateTopic(tm, DOCUMENT_SI, "Document");
Topic wandoraClass = getWandoraClass(tm);
makeSubclassOf(tm, type, wandoraClass);
return type;
}
// --------
protected Topic getOrCreateTopic(TopicMap tm, String si) throws TopicMapException {
return getOrCreateTopic(tm, si,null);
}
protected Topic getOrCreateTopic(TopicMap tm, String si,String bn) throws TopicMapException {
return ExtractHelper.getOrCreateTopic(si, bn, tm);
}
protected void makeSubclassOf(TopicMap tm, Topic t, Topic superclass) throws TopicMapException {
ExtractHelper.makeSubclassOf(t, superclass, tm);
}
// -------------------------------------------------------------------------
public String solveTitle(String content) {
if(content == null || content.length() == 0) return "empty-document";
boolean forceTrim = false;
String title = null;
int i = content.indexOf("\n");
if(i > 0) title = content.substring(0, i);
else {
title = content.substring(0, Math.min(80, content.length()));
forceTrim = true;
}
if(title != null && (forceTrim || title.length() > 80)) {
title = title.substring(0, Math.min(80, title.length()));
while(!title.endsWith(" ") && title.length()>10) {
title = title.substring(0, title.length()-1);
}
title = Textbox.trimExtraSpaces(title) + "...";
}
return title;
}
public void fillDocumentTopic(Topic textTopic, TopicMap topicMap, String content) {
try {
String trimmedText = Textbox.trimExtraSpaces(content);
if(trimmedText != null && trimmedText.length() > 0) {
Topic contentType = createTopic(topicMap, "document-text");
setData(textTopic, contentType, "en", trimmedText);
}
String title = solveTitle(trimmedText);
if(title != null) {
textTopic.setBaseName(title + " (" + content.hashCode() + ")");
textTopic.setDisplayName("en", title);
}
Topic documentType = getDocumentType(topicMap);
textTopic.addType(documentType);
}
catch(Exception e) {
log(e);
}
}
// -------------------------------------------------------------------------
@Override
public void log(String msg) {
if(getCurrentLogger() != null) super.log(msg);
}
}
| 13,824 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
StanfordNERConfiguration.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/stanfordner/StanfordNERConfiguration.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.extractors.stanfordner;
import java.io.File;
import org.wandora.application.Wandora;
import org.wandora.application.gui.UIConstants;
import org.wandora.application.gui.simple.SimpleButton;
import org.wandora.application.gui.simple.SimpleField;
import org.wandora.application.gui.simple.SimpleFileChooser;
import org.wandora.application.gui.simple.SimpleLabel;
import org.wandora.utils.Options;
/**
*
* @author akivela
*/
public class StanfordNERConfiguration extends javax.swing.JDialog {
private static final long serialVersionUID = 1L;
private boolean accepted = false;
private Wandora wandora = null;
private Options options = null;
private StanfordNERClassifier parent = null;
/** Creates new form StanfordNERConfiguration */
public StanfordNERConfiguration(Wandora w, Options o, StanfordNERClassifier p ) {
super(w, true);
wandora = w;
options = o;
parent = p;
initComponents();
if(o != null && p != null) {
fileTextField.setText(o.get(p.optionsPath));
}
setSize(600,170);
if(wandora != null) {
wandora.centerWindow(this);
}
}
public String getSuggestedClassifier() {
return fileTextField.getText();
}
public boolean wasAccepted() {
return accepted;
}
/** 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;
configurationPanel = new javax.swing.JPanel();
infoLabel = new SimpleLabel();
fieldsPanel = new javax.swing.JPanel();
fileTextField = new SimpleField();
buttonPanel = new javax.swing.JPanel();
buttonFillerPanel = new javax.swing.JPanel();
browseButton = new SimpleButton();
restoreButton = new SimpleButton();
jSeparator1 = new javax.swing.JSeparator();
okButton = new SimpleButton();
cancelButton = new SimpleButton();
setTitle("Stanford NER configuration");
getContentPane().setLayout(new java.awt.GridBagLayout());
configurationPanel.setLayout(new java.awt.GridBagLayout());
infoLabel.setText("<html>Stanford Named Entity Recognizer requires an external file containing sequence classifier. Wandora uses the classifier file addressed 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(0, 0, 12, 0);
configurationPanel.add(infoLabel, gridBagConstraints);
fieldsPanel.setLayout(new java.awt.GridBagLayout());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
fieldsPanel.add(fileTextField, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
configurationPanel.add(fieldsPanel, gridBagConstraints);
buttonPanel.setLayout(new java.awt.GridBagLayout());
javax.swing.GroupLayout buttonFillerPanelLayout = new javax.swing.GroupLayout(buttonFillerPanel);
buttonFillerPanel.setLayout(buttonFillerPanelLayout);
buttonFillerPanelLayout.setHorizontalGroup(
buttonFillerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
buttonFillerPanelLayout.setVerticalGroup(
buttonFillerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
buttonPanel.add(buttonFillerPanel, gridBagConstraints);
browseButton.setText("Browse");
browseButton.setMargin(new java.awt.Insets(2, 4, 2, 4));
browseButton.setPreferredSize(new java.awt.Dimension(70, 23));
browseButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
browseButtonMouseReleased(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4);
buttonPanel.add(browseButton, gridBagConstraints);
restoreButton.setText("Default");
restoreButton.setMargin(new java.awt.Insets(2, 4, 2, 4));
restoreButton.setPreferredSize(new java.awt.Dimension(70, 23));
restoreButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
restoreButtonMouseReleased(evt);
}
});
buttonPanel.add(restoreButton, new java.awt.GridBagConstraints());
jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 8, 0, 8);
buttonPanel.add(jSeparator1, gridBagConstraints);
okButton.setText("OK");
okButton.setPreferredSize(new java.awt.Dimension(70, 23));
okButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
okButtonMouseReleased(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4);
buttonPanel.add(okButton, gridBagConstraints);
cancelButton.setText("Cancel");
cancelButton.setMargin(new java.awt.Insets(2, 4, 2, 4));
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(15, 0, 0, 0);
configurationPanel.add(buttonPanel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10);
getContentPane().add(configurationPanel, gridBagConstraints);
pack();
}// </editor-fold>//GEN-END:initComponents
private void okButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_okButtonMouseReleased
accepted = true;
this.setVisible(false);
}//GEN-LAST:event_okButtonMouseReleased
private void restoreButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_restoreButtonMouseReleased
if(parent != null) {
fileTextField.setText(parent.defaultClassifier);
}
}//GEN-LAST:event_restoreButtonMouseReleased
private void browseButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_browseButtonMouseReleased
SimpleFileChooser fileChooser = UIConstants.getFileChooser();
if(fileChooser != null) {
String current = fileTextField.getText();
File currentF = new File(current);
File currentP = currentF;
if(!currentP.exists() || !currentP.isDirectory()) {
currentP = currentF.getParentFile();
}
if(currentP.exists()) {
fileChooser.setCurrentDirectory(currentP);
}
if( fileChooser.open(this, SimpleFileChooser.OPEN_DIALOG, "Select") == SimpleFileChooser.APPROVE_OPTION ) {
File file = fileChooser.getSelectedFile();
String fileName = file.getAbsolutePath();
fileTextField.setText(fileName);
}
}
}//GEN-LAST:event_browseButtonMouseReleased
private void cancelButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cancelButtonMouseReleased
accepted = false;
this.setVisible(false);
}//GEN-LAST:event_cancelButtonMouseReleased
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton browseButton;
private javax.swing.JPanel buttonFillerPanel;
private javax.swing.JPanel buttonPanel;
private javax.swing.JButton cancelButton;
private javax.swing.JPanel configurationPanel;
private javax.swing.JPanel fieldsPanel;
private javax.swing.JTextField fileTextField;
private javax.swing.JLabel infoLabel;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JButton okButton;
private javax.swing.JButton restoreButton;
// End of variables declaration//GEN-END:variables
}
| 10,971 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
OCRExtractor.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/ocr/OCRExtractor.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.extractors.ocr;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.Icon;
import org.apache.commons.io.IOUtils;
/* wandora */
import org.wandora.application.Wandora;
import org.wandora.application.gui.UIBox;
import org.wandora.application.tools.browserextractors.BrowserExtractRequest;
import org.wandora.application.tools.browserextractors.BrowserPluginExtractor;
import org.wandora.application.tools.extractors.AbstractExtractor;
import org.wandora.application.tools.extractors.ExtractHelper;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.TMBox;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.topicmap.XTMPSI;
import org.wandora.utils.language.LanguageBox;
/**
*
* @author Eero Lehtonen
*/
public class OCRExtractor extends AbstractExtractor {
private static final long serialVersionUID = 1L;
protected String SOURCE_SI = "http://wandora.org/si/source";
protected String DOCUMENT_SI = "http://wandora.org/si/document";
protected String TEXT_CONTENT_SI = "http://wandora.org/si/text_content";
protected String DATE_EXTRACTED_SI = "http://wandora.org/si/time_extracted";
protected String DATE_MODIFIED_SI = "http://wandora.org/si/date_modified";
protected String FILE_SIZE_SI = "http://wandora.org/si/file_size";
protected String TEMP_PATH = "temp"+File.separator+"ocr";
protected SimpleDateFormat dateFormatter;
@Override
public String getName() {
return "OCR Extractor";
}
@Override
public String getDescription(){
return "Extracts topics and associations from image text data. ";
}
@Override
public Icon getIcon() {
return UIBox.getIcon(0xf1c5);
}
private final String[] contentTypes=new String[] { "image/jpeg", "image/jpg" };
@Override
public String[] getContentTypes() {
return contentTypes;
}
@Override
public boolean useURLCrawler() {
return false;
}
@Override
public int getExtractorType() {
return FILE_EXTRACTOR | URL_EXTRACTOR;
}
// -------------------------------------------------------------------------
@Override
public boolean isConfigurable(){
return false;
}
@Override
public String doBrowserExtract(BrowserExtractRequest request, Wandora wandora) throws TopicMapException {
try {
setWandora(wandora);
String urlStr = request.getSource();
URL u = new URL(urlStr);
String mime = u.openConnection().getContentType();
if(mime != null && mime.indexOf("image") > -1){
_extractTopicsFrom(u, wandora.getTopicMap());
} else {
throw new Exception("incompatible mimetype");
}
} catch (Exception e) {
e.printStackTrace();
return BrowserPluginExtractor.RETURN_ERROR+e.getMessage();
}
return null;
}
@Override
public boolean acceptBrowserExtractRequest(BrowserExtractRequest request, Wandora wandora) throws TopicMapException {
return true;
}
@Override
public String getBrowserExtractorName() {
return getName();
}
@Override
public boolean _extractTopicsFrom(File f, TopicMap t) throws Exception {
this.dateFormatter = new SimpleDateFormat();
String si = f.toURI().toString();
String lang = System.getenv("TESSERACT_LANG");
if(lang == null) lang = "eng";
Locator l = new Locator(si);
Topic langTopic = this.getOrCreateLangTopic(t, lang);
Topic documentTopic = t.getTopic(si);
Topic dateModifiedType = this.getDateModifiedType(t);
if(documentTopic == null) documentTopic = t.createTopic();
documentTopic.addSubjectIdentifier(l);
documentTopic.setSubjectLocator(l);
documentTopic.setBaseName(f.getName());
documentTopic.setDisplayName("en",f.getName());
String modified = dateFormatter.format(new Date(f.lastModified()));
documentTopic.setData(dateModifiedType, langTopic, modified);
return this.processFile(f,t,documentTopic);
}
@Override
public boolean _extractTopicsFrom(URL u, TopicMap t) throws Exception {
boolean success = false;
URLConnection uc;
File f = new File(TEMP_PATH + "_temp.dat");
if(getWandora() != null){
uc = getWandora().wandoraHttpAuthorizer.getAuthorizedAccess(u);
} else {
uc = u.openConnection();
Wandora.initUrlConnection(uc);
}
String name = uc.getHeaderField("Content-Disposition");
InputStream is = uc.getInputStream();
try {
FileOutputStream fos = new FileOutputStream(f);
try{
byte[] buffer = new byte[4096];
for (int n; (n = is.read(buffer)) != -1; )
fos.write(buffer, 0, n);
} finally {
fos.close();
}
} catch(Exception e){
e.printStackTrace();
} finally {
is.close();
}
try{
String si = u.toString();
Locator l = new Locator(si);
Topic documentTopic = t.getTopic(si);
if(documentTopic == null) documentTopic = t.createTopic();
documentTopic.addSubjectIdentifier(l);
documentTopic.setSubjectLocator(l);
if(name != null) {
documentTopic.setBaseName(name);
documentTopic.setDisplayName("en",name);
}
documentTopic.addSubjectIdentifier(new Locator(si));
success = processFile(f,t, documentTopic);
} catch(Exception e){
e.printStackTrace();
} finally {
f.delete();
}
return success;
}
@Override
public boolean _extractTopicsFrom(String str, TopicMap t) throws Exception {
throw new UnsupportedOperationException("TODO");
}
private boolean processFile(File f, TopicMap tm, Topic documentTopic) throws TopicMapException{
boolean success = false;
this.dateFormatter = new SimpleDateFormat();
String text = "";
File tmp = new File(TEMP_PATH + ".txt");
/*
* Build the command to be executed in the form
* <path/to/tesseract> <path/to/input> <path/to/output> -l <lang>
* where the output file is temporary and is disposed of
* once it's contents are read.
*/
ArrayList<String> cmd = new ArrayList<String>();
String pathToTes = System.getenv("TESSERACT_PATH") + "tesseract";
String lang = System.getenv("TESSERACT_LANG");
cmd.add(pathToTes);
cmd.add(f.getAbsolutePath());
cmd.add(TEMP_PATH);
if(lang != null){
cmd.add("-l");
cmd.add(lang);
}
ProcessBuilder pb = new ProcessBuilder();
pb.command(cmd);
try {
Process p = pb.start();
StreamGobbler gobbler = new StreamGobbler(p.getInputStream());
StreamGobbler errorGobbler = new StreamGobbler((p.getErrorStream()));
gobbler.start();
errorGobbler.start();
int w = p.waitFor();
if(w == 0 && p.exitValue() == 0){ // Exited alright
FileInputStream is = new FileInputStream(TEMP_PATH + ".txt");
try{
text = IOUtils.toString(is);
} finally {
is.close();
}
} else { // Something got messed up
String error = errorGobbler.getMessage();
if(error.length() == 0){
error = gobbler.getMessage();
}
System.out.println(error);
throw new RuntimeException(error);
}
String extracted = dateFormatter.format(new Date());
Long size = f.length();
if(lang == null) lang = "eng";
Topic langTopic = getOrCreateLangTopic(tm, lang);
Topic documentType = createDocumentTypeTopic(tm);
Topic contentType = getContentType(tm);
Topic timeExtractedType = getTimeExtractedType(tm);
Topic fileSizeType = getSizeType(tm);
documentTopic.addType(documentType);
documentTopic.setData(contentType, langTopic, text);
documentTopic.setData(timeExtractedType,langTopic,extracted);
documentTopic.setData(fileSizeType,langTopic,""+size);
success = true;
} catch(RuntimeException rte){
log("The OCR runtime failed for " + f.getPath());
log(rte.getMessage());
} catch (TopicMapException tme) { // Adding the topic failed
log("Failed to add the file topic with the path " + f.getPath());
} catch (IOException ioe) { // A file operation failed
log(ioe.getMessage());
} catch(InterruptedException ie){
log("The OCR process failed for the file " + f.getPath());
} finally{ // Cleanup
tmp.delete();
}
return success;
}
public Topic getContentType(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm,TEXT_CONTENT_SI, "Text Content");
}
public Topic getDateModifiedType(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, DATE_MODIFIED_SI, "Date modified");
}
public Topic getTimeExtractedType(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, DATE_EXTRACTED_SI, "Time extracted");
}
public Topic getSizeType(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, FILE_SIZE_SI, "Filesize");
}
public Topic getSourceType(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, SOURCE_SI, "Source");
}
public Topic createDocumentTypeTopic(TopicMap tm) throws TopicMapException {
Topic t = createTopic(tm, "OCR processed document");
Topic w = getWandoraClass(tm);
makeSubclassOf(tm, t, w);
return t;
}
public Topic getWandoraClass(TopicMap tm) throws TopicMapException {
return createTopic(tm, TMBox.WANDORACLASS_SI, "Wandora class");
}
protected Topic getOrCreateTopic(TopicMap tm, String si) throws TopicMapException {
return getOrCreateTopic(tm, si, null);
}
protected Topic getOrCreateTopic(TopicMap tm, String si, String bn) throws TopicMapException {
return ExtractHelper.getOrCreateTopic(si, bn, tm);
}
protected void makeSubclassOf(TopicMap tm, Topic t, Topic superclass) throws TopicMapException {
ExtractHelper.makeSubclassOf(t, superclass, tm);
}
//lng in ISO 639-2 (three letters)
protected Topic getOrCreateLangTopic(TopicMap tm, String lng6392) throws TopicMapException{
String name = LanguageBox.getNameFor6392Code(lng6392);
String lng6391 = LanguageBox.get6391ForName(name);
Topic t = tm.getTopic(XTMPSI.getLang(lng6391));
if(t == null){
t = LanguageBox.createTopicForLanguageCode(lng6391, tm);
}
return t;
}
}
| 12,881 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
StreamGobbler.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/ocr/StreamGobbler.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.extractors.ocr;
/**
*http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=4
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
class StreamGobbler extends Thread {
InputStream is;
StringBuilder outputMessage = new StringBuilder();
StreamGobbler(InputStream is) {
this.is = is;
}
String getMessage() {
return outputMessage.toString();
}
@Override
public void run() {
try {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
outputMessage.append(line).append("\n");
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
} | 1,721 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
RedditThingExtractor.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/reddit/RedditThingExtractor.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.extractors.reddit;
import java.io.File;
import java.io.FileInputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import org.apache.commons.io.IOUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
/**
*
* @author Eero Lehtonen
* @author akivela
*/
public class RedditThingExtractor extends AbstractRedditExtractor {
private static final long serialVersionUID = 1L;
private HashMap<String,Boolean> crawlSettings;
public void setCrawlingSettings(HashMap<String,Boolean> crawls){
crawlSettings = crawls;
}
@Override
public boolean _extractTopicsFrom(File f, TopicMap tm) throws Exception {
FileInputStream is = new FileInputStream(f);
String fileContent = IOUtils.toString(is);
return _extractTopicsFrom(fileContent, tm);
}
@Override
public boolean _extractTopicsFrom(URL u, TopicMap tm) throws Exception {
if(u == null || tm == null) return false;
ParseCallback<JsonNode> callback = new ParseCallback<JsonNode>() {
@Override
public void run(HttpResponse<JsonNode> response) {
try {
TopicMap tm = getWandora().getTopicMap();
JSONArray respArray = response.getBody().getArray();
final HashMap<String, Topic> thingTypes = getThingTypes(tm);
for(int i=0; i<respArray.length(); i++) {
parseThing(respArray.getJSONObject(i),tm,thingTypes, crawlSettings);
}
}
catch (JSONException | TopicMapException e) {
log(e.getMessage());
}
}
@Override
protected void error(Exception e, String body) {
log(e.getMessage());
if(body != null){
log("Server responed with");
log(body);
}
}
};
resetExtracted();
requester.addRequest(Unirest.get(u.toExternalForm()), callback);
while(requester.hasRequests()) {
if(forceStop()) {
log("Aborting...");
log("Deleting "+requester.size()+" requests in run queue.");
requester.clear();
}
else {
if(requester.getRunCounter() > 0) {
hlog("Queue contains "+requester.size()+" requests. Running next request. Already processed "+requester.getRunCounter()+" requests.");
}
else {
hlog("Queue contains "+requester.size()+" requests. Running request.");
}
requester.runNext();
}
}
// Print some statistics of successful and failed requests.
int failCounter = requester.getFailCounter();
if(failCounter > 0) {
log("Failed to handle "+requester.getFailCounter()+" requests.");
}
else {
log("All API request were successful.");
}
int runCounter = requester.getRunCounter();
log("Handled successfully "+runCounter+" Reddit API requests.");
return true;
}
@Override
public boolean _extractTopicsFrom(String str, TopicMap tm) throws Exception {
if(str == null || tm == null) return false;
// We assume the string contains URLs that are separated with a new line
// character.
String[] urls = str.split("\n");
for(String urlString : urls) {
urlString = urlString.trim();
if(urlString.length() > 1) {
try {
URL url = new URL(urlString);
_extractTopicsFrom(url, tm);
}
catch(MalformedURLException mfue) {
log("Found malformed URL '"+urlString+"' in text processed by RedditThingExtractor.");
}
}
}
return true;
}
}
| 5,219 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AbstractRedditExtractor.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/reddit/AbstractRedditExtractor.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.extractors.reddit;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.swing.Icon;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.wandora.application.gui.UIBox;
import org.wandora.application.gui.WandoraOptionPane;
import org.wandora.application.tools.extractors.AbstractExtractor;
import org.wandora.application.tools.extractors.ExtractHelper;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Locator;
// import org.wandora.dep.json.*;
import org.wandora.topicmap.TMBox;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.request.body.MultipartBody;
/**
*
* @author Eero Lehtonen
* @author akivela
*/
public abstract class AbstractRedditExtractor extends AbstractExtractor {
private static final long serialVersionUID = 1L;
private static final String ERROR_MSG = "Reddit API error occurred:";
private static final String ERROR_RESPONSE_MSG = "API response follows:";
protected static final String apiRoot = "http://api.reddit.com/";
private static final String THING_TYPE_COMMENT = "t1";
private static final String THING_TYPE_ACCOUNT = "t2";
private static final String THING_TYPE_LINK = "t3";
private static final String THING_TYPE_MESSAGE = "t4";
private static final String THING_TYPE_SUBREDDIT = "t5";
private static final String THING_TYPE_AWARD = "t6";
private static final String THING_TYPE_PROMO = "t8";
private static final String THING_TYPE_MORE = "more";
private static final String LANG_SI = "http://www.topicmaps.org/xtm/1.0/language.xtm#en";
private static final String SI_ROOT = "http://wandora.org/si/reddit/";
private static final String COMMENT_SI = SI_ROOT + "comment";
private static final String LINK_SI = SI_ROOT + "link";
private static final String ACCOUNT_SI = SI_ROOT + "account";
private static final String MESSAGE_SI = SI_ROOT + "message";
private static final String SUBREDDIT_SI = SI_ROOT + "subreddit";
private static final String AWARD_SI = SI_ROOT + "award";
private static final String PROMO_SI = SI_ROOT + "promo";
private static final String PARENT_SI = SI_ROOT + "parent";
private static final String CHILD_SI = SI_ROOT + "child";
private static final String PAR_CHILD_SI = SI_ROOT + "parent_child";
private static final String DESTINATION_SI = SI_ROOT + "destination";
//Common
private static final String CREATED_SI = SI_ROOT + "created";
private static final String CREATED_U_SI = SI_ROOT + "created_utc";
//Link, Comment
private static final String BODY_SI = SI_ROOT + "body";
private static final String UP_SI = SI_ROOT + "upvotes";
private static final String DOWN_SI = SI_ROOT + "downvotes";
private static final String SCORE_SI = SI_ROOT + "score";
// Account
private static final String CKARMA_SI = SI_ROOT + "comment_karma";
private static final String LKARMA_SI = SI_ROOT + "link_karma";
// Subreddit
private static final String DESC_SI = SI_ROOT + "description";
private static final String PUB_DESC_SI = SI_ROOT + "public_description";
private static final String ACC_ACT_SI = SI_ROOT + "accounts_active";
private static final String SUBS_SI = SI_ROOT + "subscribers";
private static final String TITLE_SI = SI_ROOT + "title";
private static HashMap<String, Boolean> CRAWL_SETTINGS = null;
private static DateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
private static ArrayList<String> extracted;
private static int progress = 0;
protected Requester requester = new Requester();
@Override
public String getName() {
return "Abstract Reddit extractor";
}
@Override
public String getDescription() {
return "Abstract extractor for Reddit.";
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/extract_reddit.png");
}
private final String[] contentTypes = new String[]{
"text/plain", "text/json", "application/json"
};
@Override
public String[] getContentTypes() {
return contentTypes;
}
@Override
public boolean useURLCrawler() {
return false;
}
@Override
public boolean runInOwnThread() {
return false;
}
// -----------------------------------------------------------------
public static void resetExtracted() {
extracted = new ArrayList<>();
}
private static final Map<Integer, String> additionalPhrases;
static {
Map<Integer, String> map = new HashMap<>();
map.put(429, "Too many requests");
additionalPhrases = Collections.unmodifiableMap(map);
}
protected static String statusToPhrase(int status) {
String phrase = null; // WAS: HttpStatus.getStatusText(status);
if(phrase == null && additionalPhrases.containsKey(status)){
phrase = additionalPhrases.get(status);
}
return phrase;
}
// ------------------------------------------------------------- HELPERS ---
protected static Topic getRedditClass(TopicMap tm) throws TopicMapException {
Topic reddit = getOrCreateTopic(tm, SI_ROOT, "Reddit");
makeSubclassOf(tm, reddit, getWandoraClassTopic(tm));
return reddit;
}
protected static Topic getWandoraClassTopic(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, TMBox.WANDORACLASS_SI, "Wandora class");
}
protected static Topic getOrCreateTopic(TopicMap tm, String si) throws TopicMapException {
return getOrCreateTopic(tm, si, null);
}
protected static Topic getOrCreateTopic(TopicMap tm, String si, String bn) throws TopicMapException {
return ExtractHelper.getOrCreateTopic(si, bn, tm);
}
protected static void makeSubclassOf(TopicMap tm, Topic t, Topic superclass) throws TopicMapException {
ExtractHelper.makeSubclassOf(t, superclass, tm);
}
protected static Topic getLangTopic(TopicMap tm) throws TopicMapException {
return getOrCreateTopic(tm, LANG_SI);
}
protected static String unixToString(long unixTimeStamp) {
Date d = new Date(unixTimeStamp * 1000);
return dateTimeFormat.format(d);
}
// ------------------------------------------------------------------
protected static HashMap<String, Topic> getThingTypes(TopicMap tm) throws TopicMapException {
HashMap<String, Topic> types = new HashMap<>();
types.put(THING_TYPE_COMMENT, getOrCreateTopic(tm, COMMENT_SI, "Comment"));
types.put(THING_TYPE_LINK, getOrCreateTopic(tm, LINK_SI, "Link"));
types.put(THING_TYPE_ACCOUNT, getOrCreateTopic(tm, ACCOUNT_SI, "Account"));
types.put(THING_TYPE_MESSAGE, getOrCreateTopic(tm, MESSAGE_SI, "Message"));
types.put(THING_TYPE_SUBREDDIT, getOrCreateTopic(tm, SUBREDDIT_SI, "Subreddit"));
types.put(THING_TYPE_AWARD, getOrCreateTopic(tm, AWARD_SI, "Award"));
types.put(THING_TYPE_PROMO, getOrCreateTopic(tm, PROMO_SI, "Promo"));
Topic redditClass = getRedditClass(tm);
for (Topic type : types.values()) {
makeSubclassOf(tm, type, redditClass);
}
return types;
}
protected static HashMap<String, Topic> getAssociationTypes(TopicMap tm) throws TopicMapException {
HashMap<String, Topic> types = new HashMap<>();
types.put("Parent", getOrCreateTopic(tm, PARENT_SI, "Parent"));
types.put("Child", getOrCreateTopic(tm, CHILD_SI, "Child"));
types.put("Parent-Child", getOrCreateTopic(tm, PAR_CHILD_SI, "Parent-Child"));
types.put("Destination", getOrCreateTopic(tm, DESTINATION_SI, "Destination"));
types.put("Lang", getLangTopic(tm));
// Comment, Link
types.put("Body", getOrCreateTopic(tm, BODY_SI, "Body"));
types.put("Created", getOrCreateTopic(tm, CREATED_SI, "Created"));
types.put("Created UTC", getOrCreateTopic(tm, CREATED_U_SI, "Created UTC"));
types.put("Upvotes", getOrCreateTopic(tm, UP_SI, "Upvotes"));
types.put("Downvotes", getOrCreateTopic(tm, DOWN_SI, "Downvotes"));
types.put("Score", getOrCreateTopic(tm, SCORE_SI, "Score"));
// Account
types.put("Comment Karma", getOrCreateTopic(tm, CKARMA_SI, "Comment Karma"));
types.put("Link Karma", getOrCreateTopic(tm, LKARMA_SI, "Link Karma"));
// Subreddit
types.put("Description", getOrCreateTopic(tm, DESC_SI, "Description"));
types.put("Public Description", getOrCreateTopic(tm, PUB_DESC_SI, "Public Description"));
types.put("Accounts Active", getOrCreateTopic(tm, ACC_ACT_SI, "Accounts Active"));
types.put("Subscribers", getOrCreateTopic(tm, SUBS_SI, "Subscribers"));
types.put("Title", getOrCreateTopic(tm, TITLE_SI, "Title"));
Topic redditClass = getRedditClass(tm);
for(Topic type : types.values()){
type.addType(redditClass);
}
return types;
}
private void associateParent(TopicMap tm, Topic commentTopic, Topic parentTopic) throws TopicMapException {
HashMap<String, Topic> types = getAssociationTypes(tm);
Association a = tm.createAssociation(types.get("Parent-Child"));
a.addPlayer(parentTopic, types.get("Parent"));
a.addPlayer(commentTopic, types.get("Child"));
}
private void associateAccount(TopicMap tm, JSONObject thing, Topic account, HashMap<String, Topic> types) throws TopicMapException, JSONException {
if(account == null) return;
JSONObject thingData = thing.getJSONObject("data");
String thingKind = thing.getString("kind");
String thingId = thingData.getString("name");
Topic thingTopic = getOrCreateTopic(tm, SI_ROOT + thingId);
Association a = tm.createAssociation(types.get(THING_TYPE_ACCOUNT));
a.addPlayer(account, types.get(THING_TYPE_ACCOUNT));
a.addPlayer(thingTopic, types.get(thingKind));
}
private void associateSubreddit(TopicMap tm, JSONObject thing, Topic subreddit, HashMap<String, Topic> types) throws TopicMapException, JSONException {
JSONObject thingData = thing.getJSONObject("data");
String thingKind = thing.getString("kind");
String thingId = thingData.getString("name");
Topic thingTopic = getOrCreateTopic(tm, SI_ROOT + thingId);
Association a = tm.createAssociation(types.get(THING_TYPE_SUBREDDIT));
a.addPlayer(subreddit, types.get(THING_TYPE_SUBREDDIT));
a.addPlayer(thingTopic, types.get(thingKind));
}
private void addLinkOccurenceData(TopicMap tm, JSONObject linkData, Topic linkTopic) throws TopicMapException, JSONException {
HashMap<String, Topic> types = getAssociationTypes(tm);
Topic lang = types.get("Lang");
Long created = linkData.getLong("created");
String createdString = unixToString(created);
if(createdString != null) {
linkTopic.setData(types.get("Created"), lang, createdString);
}
Long createdUtc = linkData.getLong("created_utc");
String createdUtcString = unixToString(createdUtc);
if(createdUtcString != null) {
linkTopic.setData(types.get("Created UTC"), lang, createdUtcString);
}
}
private void addCommentOccurenceData(TopicMap tm, JSONObject commentData, Topic commentTopic) throws TopicMapException, JSONException {
HashMap<String, Topic> types = getAssociationTypes(tm);
Topic lang = types.get("Lang");
String body = commentData.getString("body");
if(body != null) {
commentTopic.setData(types.get("Body"), lang, body);
}
Long created = commentData.getLong("created");
String createdString = unixToString(created);
if(createdString != null) {
commentTopic.setData(types.get("Created"), lang, createdString);
}
String ups = Integer.toString(commentData.getInt("ups"));
if(ups != null) {
commentTopic.setData(types.get("Upvotes"), lang, ups);
}
String downs = Integer.toString(commentData.getInt("downs"));
if(downs != null) {
commentTopic.setData(types.get("Downvotes"), lang, downs);
}
//String score = commentData.getString("score");
//if(score != null) commentTopic.setData(types.get("Score"), lang, score);
}
private void addAccountOccurenceData(TopicMap tm, JSONObject accountData, Topic accountTopic) throws TopicMapException, JSONException {
HashMap<String, Topic> types = getAssociationTypes(tm);
Topic lang = types.get("Lang");
Long created = accountData.getLong("created");
String createdString = unixToString(created);
if(createdString != null) {
accountTopic.setData(types.get("Created"), lang, createdString);
}
Long createdUtc = accountData.getLong("created_utc");
String createdUtcString = unixToString(createdUtc);
if(createdUtcString != null) {
accountTopic.setData(types.get("Created UTC"), lang, createdUtcString);
}
String cKarma = Integer.toString(accountData.getInt("comment_karma"));
if(cKarma != null) {
accountTopic.setData(types.get("Comment Karma"), lang, cKarma);
}
String lKarma = Integer.toString(accountData.getInt("link_karma"));
if(lKarma != null) {
accountTopic.setData(types.get("Link Karma"), lang, lKarma);
}
}
private void addSubredditOccurrenceData(TopicMap tm, JSONObject subredditData, Topic subredditTopic) throws TopicMapException, JSONException {
HashMap<String, Topic> types = getAssociationTypes(tm);
Topic lang = types.get("Lang");
Long created = subredditData.getLong("created");
String createdString = unixToString(created);
if(createdString != null) {
subredditTopic.setData(types.get("Created"), lang, createdString);
}
Long createdUtc = subredditData.getLong("created_utc");
String createdUtcString = unixToString(createdUtc);
if(createdUtcString != null) {
subredditTopic.setData(types.get("Created UTC"), lang, createdUtcString);
}
String desc = subredditData.getString("description");
if(desc != null && desc.length() > 0) {
subredditTopic.setData(types.get("Description"), lang, desc);
}
String pubDesc = subredditData.getString("public_description");
if(pubDesc != null && pubDesc.length() > 0) {
subredditTopic.setData(types.get("Public Description"), lang, pubDesc);
}
String accAct = Integer.toString(subredditData.getInt("accounts_active"));
if(accAct != null) {
subredditTopic.setData(types.get("Accounts Active"), lang, accAct);
}
String subs = Integer.toString(subredditData.getInt("subscribers"));
if(subs != null) {
subredditTopic.setData(types.get("Subscribers"), lang, subs);
}
String title = subredditData.getString("title");
if(title != null && title.length() > 0) {
subredditTopic.setData(types.get("Title"), lang, title);
}
}
/*
This is being called from the RedditExtractorUI.
*/
protected static void getSubmissions(String q, ParseCallback<JsonNode> callback) {
String u = apiRoot + "search?q=" + urlEncode(q);
Requester tempRequester = new Requester();
tempRequester.addRequest(Unirest.get(u),callback);
tempRequester.runNext();
}
/*
This is being called from the RedditExtractorUI.
*/
protected static void getSubreddits(String q, ParseCallback<JsonNode> callback) {
String u = apiRoot + "subreddits/search?q=" + urlEncode(q);
Requester tempRequester = new Requester();
tempRequester.addRequest(Unirest.get(u),callback);
tempRequester.runNext();
}
// ---------------------------------------------------------------------- //
protected void parseThing(JSONObject thing, TopicMap tm, HashMap<String, Topic> thingTypes, HashMap<String, Boolean> crawlSettings) {
CRAWL_SETTINGS = crawlSettings;
parseThing(thing, tm, thingTypes);
}
protected void parseThing(JSONObject thing, TopicMap tm, HashMap<String, Topic> thingTypes) {
progress = (progress+1)%100;
getDefaultLogger().setProgress(progress);
if(forceStop()) {
return;
}
try {
if(thing.has("error")){
Object error = thing.get("error");
throw new JSONException("API error \"" + statusToPhrase((int)error) + "\"");
}
JSONObject data = thing.getJSONObject("data");
String kind = thing.getString("kind");
switch(kind) {
case THING_TYPE_COMMENT:
parseComment(thing, thingTypes, tm);
break;
case THING_TYPE_LINK:
parseLink(thing, thingTypes, tm);
break;
case THING_TYPE_ACCOUNT:
parseAccount(thing, thingTypes, tm);
break;
case THING_TYPE_SUBREDDIT:
parseSubreddit(thing, thingTypes, tm);
break;
}
if(data.has("children")) {
JSONArray children = data.getJSONArray("children");
for(int i = 0; i < children.length(); i++) {
JSONObject child;
try {
child = children.getJSONObject(i);
}
catch(JSONException jse) {
jse.printStackTrace();
continue;
}
parseThing(child, tm, thingTypes);
}
}
}
catch(JSONException jse) {
log("Parsing response failed: " + jse.getMessage());
try {
log("The JSON message in question was");
log(thing.toString(2));
}
catch(JSONException jsee) {
log("The message JSON was invalid.");
}
jse.printStackTrace();
}
catch (TopicMapException tme){
log(tme.getMessage());
}
}
private void parseMore(JSONObject commentData, JSONObject child, TopicMap tm, HashMap<String, Topic> thingTypes) throws JSONException, TopicMapException {
if(forceStop()) {
return;
}
String id = commentData.getString("name");
String link_id = commentData.getString("link_id");
StringBuilder childString = new StringBuilder();
JSONArray children = child.getJSONObject("data").getJSONArray("children");
int count = children.length();
for(int i=0; i<count; i++) {
childString.append(children.getString(i));
if(i < count - 1) {
childString.append(",");
}
}
MultipartBody r = Unirest.post(apiRoot + "api/morechildren")
.header("accept", "application/json")
.field("api_type", "json")
.field("id", id)
.field("link_id", link_id)
.field("children", childString.toString());
ParseCallback<JsonNode> callback = new ParseCallback<JsonNode>(tm, thingTypes) {
@Override
public void run(HttpResponse<JsonNode> response) {
try {
JSONObject respJSON = response.getBody().getObject();
if(respJSON.getJSONObject("json").getJSONArray("errors").length() == 0) {
JSONArray things = respJSON
.getJSONObject("json")
.getJSONObject("data")
.getJSONArray("things");
for(int i = 0; i < things.length(); i++) {
parseThing(things.getJSONObject(i), tm, thingTypes);
}
}
}
catch (Exception e) {
logParseCallbackRunError(e);
}
}
@Override
protected void error(Exception e, String body) {
logParseCallbackError(e, body);
}
};
requester.addRequest(r, callback);
}
private Topic parseLink(JSONObject l, HashMap<String, Topic> thingTypes, TopicMap tm) throws JSONException, TopicMapException {
if(forceStop()) {
return null;
}
final JSONObject link = l;
JSONObject linkData = link.getJSONObject("data");
String kind = link.getString("kind");
String id = linkData.getString("name");
String title = linkData.getString("title");
hlog("Parsing link " + title);
Topic linkTopic = getOrCreateTopic(tm, SI_ROOT + id);
linkTopic.setDisplayName("en", title);
linkTopic.setBaseName(title + " (" + id + ")");
if(!linkData.getBoolean("is_self")){ // Handle link
String linkUrl = linkData.getString("url");
Topic destinationTopic = getOrCreateTopic(tm, linkUrl);
destinationTopic.setSubjectLocator(new Locator(linkUrl));
HashMap<String,Topic> assTypes = getAssociationTypes(tm);
Association a = tm.createAssociation(assTypes.get("Destination"));
a.addPlayer(linkTopic, thingTypes.get(THING_TYPE_LINK));
a.addPlayer(destinationTopic, assTypes.get("Destination"));
}
linkTopic.addType(thingTypes.get(kind));
addLinkOccurenceData(tm, linkData, linkTopic);
if(linkData.has("author")) {
final String author = linkData.getString("author");
if(!extracted.contains(author) && CRAWL_SETTINGS.get("linkUser")) {
String authorUrl = apiRoot + "user/" + author + "/about.json";
ParseCallback<JsonNode> callback = new ParseCallback<JsonNode>(tm, thingTypes) {
@Override
public void run(HttpResponse<JsonNode> response) {
try {
JSONObject respObject = response.getBody().getObject();
Topic account = null;
if(respObject.has("kind") && respObject.getString("kind").equals(THING_TYPE_ACCOUNT)) {
extracted.add(author);
account = parseAccount(respObject, thingTypes, tm);
}
if (account != null) {
associateAccount(tm, link, account, thingTypes);
}
}
catch (JSONException | TopicMapException e) {
logParseCallbackRunError(e);
}
}
@Override
protected void error(Exception e, String body) {
logParseCallbackError(e, body);
}
};
requester.addRequest(Unirest.get(authorUrl), callback);
}
}
try {
if(linkData.has("subreddit")) {
String subredditId = linkData.getString("subreddit_id");
String subredditName = linkData.getString("subreddit");
Topic subredditTopic = getOrCreateTopic(tm, SI_ROOT + subredditId);
associateSubreddit(tm, link, subredditTopic, thingTypes);
final String subreddit = linkData.getString("subreddit");
if(!extracted.contains(subreddit) && CRAWL_SETTINGS.get("linkSubreddit")) {
String subredditUrl = apiRoot + "r/" + subreddit + "/about.json";
ParseCallback<JsonNode> callback = new ParseCallback<JsonNode>(tm, thingTypes) {
@Override
public void run(HttpResponse<JsonNode> response){
try {
JSONObject respObject = response.getBody().getObject();
Topic subredditTopic = null;
if (respObject.has("kind") && respObject.getString("kind").equals(THING_TYPE_SUBREDDIT)) {
extracted.add(subreddit);
subredditTopic = parseSubreddit(respObject, thingTypes, tm);
}
if (subredditTopic != null) {
associateSubreddit(tm, link, subredditTopic, thingTypes);
}
}
catch (JSONException | TopicMapException e) {
logParseCallbackRunError(e);
}
}
@Override
protected void error(Exception e, String body) {
logParseCallbackError(e, body);
}
};
requester.addRequest(Unirest.get(subredditUrl), callback);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
if(CRAWL_SETTINGS.get("linkComment")) {
String commentUrl = apiRoot + "comments/" + linkData.getString("id");
ParseCallback<JsonNode> callback = new ParseCallback<JsonNode>(tm, thingTypes) {
@Override
public void run(HttpResponse<JsonNode> response){
try {
JSONArray respArray = response.getBody().getArray();
// Object #0 is the link, which we skip here
parseThing(respArray.getJSONObject(1),tm,thingTypes);
}
catch (Exception e) {
logParseCallbackRunError(e);
}
}
@Override
protected void error(Exception e, String body) {
logParseCallbackError(e, body);
}
};
System.out.println("Requesting " + commentUrl);
requester.addRequest(Unirest.get(commentUrl), callback);
}
return linkTopic;
}
private Topic parseComment(JSONObject c, HashMap<String, Topic> thingTypes, TopicMap tm) throws JSONException, TopicMapException {
if(forceStop()) {
return null;
}
final JSONObject comment = c;
JSONObject commentData = comment.getJSONObject("data");
String kind = comment.getString("kind");
String id = commentData.getString("name");
hlog("Parsing comment " + id);
Topic commentTopic = getOrCreateTopic(tm, SI_ROOT + id);
commentTopic.setBaseName("Comment " + " (" + id + ")");
commentTopic.addType(thingTypes.get(kind));
addCommentOccurenceData(tm, commentData, commentTopic);
if(commentData.has("author")) {
String author = commentData.getString("author");
Topic account = tm.getTopic(SI_ROOT + author);
//Early return if we already scraped the url
if (account != null) {
associateAccount(tm, comment, account, thingTypes);
}
else if(!author.equals("[deleted]") && CRAWL_SETTINGS.get("commentUser")) {
hlog("Parsing user " + author);
String authorUrl = apiRoot + "user/" + author + "/about";
ParseCallback<JsonNode> callback = new ParseCallback<JsonNode>(tm, thingTypes) {
@Override
public void run(HttpResponse<JsonNode> response) {
try {
JSONObject respObject = response.getBody().getObject();
if (respObject.has("kind") && respObject.getString("kind").equals(THING_TYPE_ACCOUNT)) {
Topic account = parseAccount(respObject, thingTypes, tm);
associateAccount(tm, comment, account, thingTypes);
}
}
catch (JSONException | TopicMapException e) {
logParseCallbackRunError(e);
}
}
@Override
protected void error(Exception e, String body) {
logParseCallbackError(e, body);
}
};
requester.addRequest(Unirest.get(authorUrl), callback);
}
}
if(commentData.has("parent_id")) {
String parentId = commentData.getString("parent_id");
Topic parentTopic = getOrCreateTopic(tm, SI_ROOT + parentId);
associateParent(tm, commentTopic, parentTopic);
}
if(commentData.has("replies")) {
JSONArray children;
try {
children = commentData
.getJSONObject("replies")
.getJSONObject("data")
.getJSONArray("children");
}
catch(JSONException jse) {
children = new JSONArray();
}
for (int i = 0; i < children.length(); i++) {
JSONObject childData = children.getJSONObject(i);
String childKind = childData.getString("kind");
if (childKind.equals(THING_TYPE_MORE) && CRAWL_SETTINGS.get("more")) {
parseMore(commentData, childData, tm, thingTypes);
}
else {
parseThing(childData, tm, thingTypes);
}
}
}
if(commentData.has("link_id")) {
String link_id = commentData.getString("link_id");
Topic linkTopic = tm.getTopic(SI_ROOT + link_id);
if(linkTopic == null && CRAWL_SETTINGS.get("commentLink")) {
ParseCallback<JsonNode> callback = new ParseCallback<JsonNode>(tm, thingTypes) {
@Override
public void run(HttpResponse<JsonNode> response){
try {
JSONObject respObj = response.getBody().getObject();
parseThing(respObj, tm, thingTypes);
}
catch (Exception e) {
logParseCallbackRunError(e);
}
}
@Override
protected void error(Exception e, String body) {
logParseCallbackError(e, body);
}
};
requester.addRequest(Unirest.get(apiRoot + "api/info?id=" + link_id), callback);
}
}
return commentTopic;
}
private Topic parseAccount(JSONObject account, HashMap<String, Topic> thingTypes, TopicMap tm) throws JSONException, TopicMapException {
if (forceStop()) {
return null;
}
JSONObject accountData = account.getJSONObject("data");
String kind = account.getString("kind");
String id = accountData.getString("name");
hlog("Parsing account " + id);
Topic accountTopic = getOrCreateTopic(tm, SI_ROOT + id);
accountTopic.setDisplayName("en", id);
accountTopic.setBaseName(id);
addAccountOccurenceData(tm, accountData, accountTopic);
accountTopic.addType(thingTypes.get(kind));
if(CRAWL_SETTINGS.get("userLink")) {
ParseCallback<JsonNode> callback = new ParseCallback<JsonNode>(tm, thingTypes) {
@Override
public void run(HttpResponse<JsonNode> response) {
try {
JSONObject respObj = response.getBody().getObject();
parseThing(respObj, tm, thingTypes);
}
catch(Exception e) {
logParseCallbackRunError(e);
}
}
@Override
protected void error(Exception e, String body) {
logParseCallbackError(e, body);
}
};
requester.addRequest(Unirest.get(apiRoot + "user/" + id + "/submitted.json"), callback);
}
if(CRAWL_SETTINGS.get("userComment")) {
ParseCallback<JsonNode> callback = new ParseCallback<JsonNode>(tm, thingTypes) {
@Override
public void run(HttpResponse<JsonNode> response){
try {
JSONObject respObj = response.getBody().getObject();
parseThing(respObj, tm, thingTypes);
}
catch(Exception e) {
logParseCallbackRunError(e);
}
}
@Override
protected void error(Exception e, String body) {
logParseCallbackError(e, body);
}
};
requester.addRequest(Unirest.get(apiRoot + "user/" + id + "/comments.json"), callback);
}
return accountTopic;
}
private Topic parseSubreddit(JSONObject subreddit, HashMap<String, Topic> thingTypes, TopicMap tm) throws JSONException, TopicMapException {
if(forceStop()) {
return null;
}
JSONObject subredditData = subreddit.getJSONObject("data");
String kind = subreddit.getString("kind");
String id = subredditData.getString("name");
final String disp = subredditData.getString("display_name");
hlog("Parsing subreddit " + disp);
Topic subredditTopic = getOrCreateTopic(tm, SI_ROOT + id);
subredditTopic.setDisplayName("en",disp );
subredditTopic.setBaseName(disp + " (" + id + ")");
addSubredditOccurrenceData(tm, subredditData, subredditTopic);
subredditTopic.addType(thingTypes.get(kind));
if(CRAWL_SETTINGS.get("subredditLink")) {
ParseCallback<JsonNode> callback = new ParseCallback<JsonNode>(tm, thingTypes) {
@Override
public void run(HttpResponse<JsonNode> response){
try {
JSONObject respObj = response.getBody().getObject();
parseThing(respObj, tm, thingTypes);
if(WandoraOptionPane.showConfirmDialog(getWandora(),
"Load more links?","Load more links?",
WandoraOptionPane.YES_NO_OPTION) == WandoraOptionPane.YES_OPTION) {
String after = respObj.getJSONObject("data").getString("after");
requester.addRequest(Unirest.get(apiRoot + "r/" + disp + "/hot.json?after=" + after), this);
}
}
catch(Exception e) {
logParseCallbackRunError(e);
}
}
@Override
protected void error(Exception e, String body) {
logParseCallbackError(e, body);
}
};
requester.addRequest(Unirest.get(apiRoot + "r/" + disp + "/hot.json"), callback);
}
return subredditTopic;
}
/*
ParseCallBack objects use this method to log exceptions in error methods.
*/
protected void logParseCallbackError(Exception e, String body) {
if(e != null) {
e.printStackTrace();
log(ERROR_MSG);
log(e.getMessage());
if(body != null) {
log(ERROR_RESPONSE_MSG);
log(body);
}
}
}
/*
ParseCallBack objects use this method to log exceptions in run methods.
*/
protected void logParseCallbackRunError(Exception e) {
if(e != null) {
e.printStackTrace();
if(e instanceof JSONException) {
log("Exception occurred while processing JSON data in Reddit extractor. Details follow.");
log(e.getMessage());
}
else if(e instanceof TopicMapException) {
log("Exception occurred while accessing topic map in Reddit extractor. Details follow.");
log(e.getMessage());
}
else {
log("Exception occurred while processing API response in Reddit extractor. Details follow.");
log(e.getMessage());
}
}
}
}
| 38,829 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
RedditExtractor.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/reddit/RedditExtractor.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.extractors.reddit;
/**
*
* @author Eero Lehtonen
* @author akivela
*/
import javax.swing.Icon;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.UIBox;
import org.wandora.application.tools.AbstractWandoraTool;
public class RedditExtractor extends AbstractWandoraTool{
private static final long serialVersionUID = 1L;
private RedditExtractorUI ui = null;
@Override
public String getName() {
return "Reddit API Extractor";
}
@Override
public String getDescription(){
return "Extracts topics and associations from reddit API. "+
"A personal api-key is required for the API access.";
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/extract_reddit.png");
}
private final String[] contentTypes=new String[] {
"text/plain", "text/json", "application/json"
};
public String[] getContentTypes() {
return contentTypes;
}
public boolean useURLCrawler() {
return false;
}
@Override
public void execute(Wandora wandora, Context context) {
try {
if(ui == null) {
ui = new RedditExtractorUI();
}
ui.open(wandora, context);
if(ui.wasAccepted()) {
WandoraTool[] extrs = null;
try {
extrs = ui.getExtractors(this);
}
catch(Exception e) {
log("Failed to solve Reddit subextractors because of an exception: "+e.getMessage());
return;
}
if(extrs != null && extrs.length > 0) {
setDefaultLogger();
int c = 0;
if(extrs.length > 1) {
log("Requested operation requires "+extrs.length+" Reddit extractions.");
}
for(int i=0; i<extrs.length && !forceStop(); i++) {
try {
if(extrs.length > 1) {
log("Starting Reddit extraction "+(i+1)+".");
}
WandoraTool e = extrs[i];
e.setToolLogger(getDefaultLogger());
e.execute(wandora,context);
log("Finished extraction "+(i+1)+".");
c++;
}
catch(Exception e) {
log(e);
}
}
log("Ready.");
}
else {
log("Couldn't find a suitable subextractor to perform or "
+"there was an error with an extractor.");
}
}
}
catch(Exception e) {
e.printStackTrace();
singleLog(e);
}
finally {
if(ui != null && ui.wasAccepted()) setState(WAIT);
else setState(WAIT);
}
}
// -------------------------------------------------------------------------
}
| 4,168 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
ParseCallback.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/reddit/ParseCallback.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.extractors.reddit;
import java.util.HashMap;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
/**
*
* @author Eero Lehtonen
*/
abstract class ParseCallback<Object> {
TopicMap tm;
HashMap<String, Topic> thingTypes;
public ParseCallback(TopicMap tm, HashMap<String, Topic> thingTypes) {
this.tm = tm;
this.thingTypes = thingTypes;
}
public ParseCallback() {
this(null ,null);
}
abstract public void run(HttpResponse<JsonNode> response);
public void error(Exception e){
this.error(e, null);
}
abstract protected void error(Exception e, String body);
}
| 1,599 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
RedditExtractorUI.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/reddit/RedditExtractorUI.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.extractors.reddit;
import static org.wandora.application.tools.extractors.reddit.AbstractRedditExtractor.statusToPhrase;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.KeyEvent;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import javax.swing.DefaultListModel;
import javax.swing.JDialog;
import javax.swing.SwingUtilities;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.UIBox;
import org.wandora.application.gui.simple.SimpleButton;
import org.wandora.application.gui.simple.SimpleCheckBox;
import org.wandora.application.gui.simple.SimpleField;
import org.wandora.application.gui.simple.SimpleLabel;
import org.wandora.application.gui.simple.SimpleList;
import org.wandora.application.gui.simple.SimpleTabbedPane;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
/**
*
* @author Eero Lehtonen
*/
public class RedditExtractorUI extends javax.swing.JPanel {
private static final long serialVersionUID = 1L;
private Wandora wandora = null;
private boolean accepted = false;
private JDialog dialog = null;
private Context context = null;
private DateFormat dateFormat = DateFormat.getDateTimeInstance();
private String apiRoot = AbstractRedditExtractor.apiRoot;
private DefaultListModel linkModel;
private JSONArray threadResults = new JSONArray();
private JSONArray subredditResults = new JSONArray();
/**
* Creates new form RedditExtractorUI
*/
public RedditExtractorUI() {
initComponents();
}
public boolean wasAccepted() {
return accepted;
}
public void setAccepted(boolean b) {
accepted = b;
}
public void open(Wandora w, Context c) {
context = c;
wandora = w;
accepted = false;
dialog = new JDialog(w, true);
dialog.setSize(800, 500);
dialog.setMinimumSize(new Dimension(600, 400));
dialog.add(this);
threadSearchSubmit.setText("Search");
threadSearchSubmit.setEnabled(true);
dialog.setTitle("Reddit API extractor");
UIBox.centerWindow(dialog, w);
dialog.setVisible(true);
}
public WandoraTool[] getExtractors(RedditExtractor tool) throws TopicMapException {
ArrayList<WandoraTool> wts = new ArrayList();
String id;
String query = "";
String extractUrl = null;
Component selectedTab = redditTabs.getSelectedComponent();
try {
if (selectedTab.equals(commentSearchTab)) {
int[] selectedIndices = threadResList.getSelectedIndices();
for( int selectedIndex : selectedIndices) {
RedditThingExtractor ex = getRedditThingExtractor();
JSONObject selected = threadResults.getJSONObject(selectedIndex);
id = selected.getJSONObject("data").getString("id");
extractUrl = apiRoot + "comments/" + id;
ex.setForceUrls(new String[] { extractUrl } );
wts.add(ex);
}
}
else if (selectedTab.equals(accountSearchTab)) {
id = accountSearchField.getText();
if(id != null && id.trim().length() > 0) {
RedditThingExtractor ex = getRedditThingExtractor();
extractUrl = apiRoot + "user/" + id + "/about.json";
ex.setForceUrls(new String[]{extractUrl});
wts.add(ex);
}
}
else if (selectedTab.equals(subredditSearchTab)) {
int selectedIndex = subredditResList.getSelectedIndex();
JSONObject selected = subredditResults.getJSONObject(selectedIndex);
id = selected.getJSONObject("data").getString("display_name");
RedditThingExtractor ex = getRedditThingExtractor();
extractUrl = apiRoot +"r/"+ id + "/about.json";
ex.setForceUrls(new String[]{extractUrl});
wts.add(ex);
}
else if (selectedTab.equals(linkSearchTab)) {
for (int i = 0; i < linkModel.getSize(); i++) {
RedditThingExtractor ex = getRedditThingExtractor();
String url = apiRoot + "api/info?url=" + linkModel.get(i);
ex.setForceUrls(new String[]{url});
wts.add(ex);
}
}
}
catch (JSONException jse) {
jse.printStackTrace();
}
return wts.toArray(new WandoraTool[]{});
}
private RedditThingExtractor getRedditThingExtractor() {
RedditThingExtractor ex = new RedditThingExtractor();
HashMap<String, Boolean> crawling = new HashMap<>();
crawling.put("more", crawlToggle.isSelected());
crawling.put("linkSubreddit", crawlLinkSR.isSelected());
crawling.put("linkComment", crawlLinkComment.isSelected());
crawling.put("linkUser", crawlLinkUser.isSelected());
crawling.put("commentLink", crawlCommentLink.isSelected());
crawling.put("commentUser", crawlCommentUser.isSelected());
crawling.put("userLink", crawlUserLink.isSelected());
crawling.put("userComment", crawlUserComment.isSelected());
crawling.put("subredditLink", crawlSRLink.isSelected());
ex.setCrawlingSettings(crawling);
return ex;
}
protected static String urlEncode(String str) {
try {
str = URLEncoder.encode(str, "utf-8");
} catch (Exception e) {
System.out.println(e.getMessage());
}
return str;
}
private void threadPopulationCallback(HttpResponse<JsonNode> response) {
DefaultListModel model = new DefaultListModel();
try {
JSONObject resJson = response.getBody().getObject();
if(resJson.has("error")){
Object error = resJson.get("error");
throw new JSONException("API error: " + statusToPhrase((int)error));
}
threadResults = resJson
.getJSONObject("data")
.getJSONArray("children");
JSONObject r;
model = new DefaultListModel();
for (int i = 0; i < threadResults.length(); i++) {
r = threadResults.getJSONObject(i).getJSONObject("data");
StringBuilder titleBuilder = new StringBuilder();
titleBuilder
.append("[r/").append(r.getString("subreddit"))
.append("] ").append(r.getString("title"))
.append(" - ").append(r.getInt("score"));
model.add(i, titleBuilder.toString());
}
//threadResList.setModel(model);
}
catch (Exception e) {
model.add(0, e.getMessage());
}
finally {
threadResList.setModel(model);
threadSearchSubmit.setText("Search");
threadSearchSubmit.setEnabled(true);
}
}
private void populateThreadSearch() {
threadSearchSubmit.setText("Searching...");
threadSearchSubmit.setEnabled(false);
final String q = threadSearchField.getText();
final ParseCallback<JsonNode> callback = new ParseCallback<JsonNode>() {
@Override
public void run(HttpResponse<JsonNode> response) {
threadPopulationCallback(response);
}
@Override
protected void error(Exception e, String body) {
DefaultListModel model = new DefaultListModel();
model.add(0, e.getMessage());
threadResList.setModel(model);
threadSearchSubmit.setText("Search");
threadSearchSubmit.setEnabled(true);
}
};
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
AbstractRedditExtractor.getSubmissions(q, callback);
}
}
);
}
private void subredditPopulationCallback(HttpResponse<JsonNode> response) {
DefaultListModel model = new DefaultListModel();
try {
JSONObject resJson = response.getBody()
.getObject();
if(resJson.has("error")){
Object error = resJson.get("error");
throw new JSONException("API error: " + statusToPhrase((int)error));
}
subredditResults = resJson
.getJSONObject("data")
.getJSONArray("children");
JSONObject r;
model = new DefaultListModel();
for (int i = 0; i < subredditResults.length(); i++) {
r = subredditResults.getJSONObject(i).getJSONObject("data");
StringBuilder titleBuilder = new StringBuilder();
titleBuilder
.append("r/").append(r.getString("display_name"))
.append(": ").append(r.getString("title"));
model.add(i, titleBuilder.toString());
}
}
catch(Exception e) {
model.add(0, e.getMessage());
}
finally {
subredditResList.setModel(model);
subredditSearchSubmit.setText("Search");
subredditSearchSubmit.setEnabled(true);
}
}
private void populateSubredditSearch() {
subredditSearchSubmit.setText("Searching...");
subredditSearchSubmit.setEnabled(false);
final String q = subredditSearchField.getText();
final ParseCallback<JsonNode> callback = new ParseCallback<JsonNode>() {
@Override
public void run(HttpResponse<JsonNode> response) {
subredditPopulationCallback(response);
}
@Override
protected void error(Exception e, String body) {
DefaultListModel model = new DefaultListModel();
model.add(0, e.getMessage());
subredditResList.setModel(model);
subredditSearchSubmit.setText("Search");
subredditSearchSubmit.setEnabled(true);
}
};
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
AbstractRedditExtractor.getSubreddits(q, callback);
}
}
);
}
private void focusThread() {
int i = threadResList.getSelectedIndex();
try {
JSONObject r = threadResults.getJSONObject(i).getJSONObject("data");
StringBuilder sb = new StringBuilder();
Date d = new Date(1000 * r.getLong("created"));
String ds = dateFormat.format(d);
sb.append("<html><body style='width=180'>posted ").append(ds).append("<br/>")
.append("score: ").append(r.getInt("score")).append(" (")
.append(r.getInt("ups")).append("|").append(r.getInt("downs"))
.append(")<br/>").append(r.getInt("num_comments")).append(" comments")
.append("<body></html>");
threadSearchDetails.setText(sb.toString());
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
private void focusSubreddit() {
int i = subredditResList.getSelectedIndex();
try {
JSONObject r = subredditResults.getJSONObject(i).getJSONObject("data");
subredditTitleLabel.setText(r.getInt("subscribers") + " subscribers");
subredditDetailTextArea.setText(r.getString("public_description"));
subredditDetailTextArea.setLineWrap(true);
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
private void addContextSLs() {
Iterator iter = context.getContextObjects();
Object o;
Topic t;
Locator locator;
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();
linkModel.addElement(locatorStr);
}
}
}
} 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.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
redditTabs = new SimpleTabbedPane();
commentSearchTab = new javax.swing.JPanel();
threadSearchField = new SimpleField();
threadSearchSubmit = new SimpleButton();
threadResScrollPane = new javax.swing.JScrollPane();
threadResList = new SimpleList();
threadSearchDetails = new javax.swing.JLabel();
subredditSearchTab = new javax.swing.JPanel();
subredditSearchField = new SimpleField();
subredditSearchSubmit = new SimpleButton();
subredditResScrollPane = new javax.swing.JScrollPane();
subredditResList = new SimpleList();
subredditDetailTextArea = new javax.swing.JTextArea();
subredditTitleLabel = new javax.swing.JLabel();
linkSearchTab = new javax.swing.JPanel();
linkField = new SimpleField();
linkLabel = new SimpleLabel();
linkScrollpane = new javax.swing.JScrollPane();
linkSearchList = new javax.swing.JList();
linkAddUrlButton = new SimpleButton();
linkAddSLsButton = new SimpleButton();
linkClearButton = new SimpleButton();
accountSearchTab = new javax.swing.JPanel();
accountSearchField = new SimpleField();
jLabel3 = new SimpleLabel();
buttonPanel = new javax.swing.JPanel();
buttonFillerPanel = new javax.swing.JPanel();
okButton = new SimpleButton();
cancelButton = new SimpleButton();
crawlOptions = new javax.swing.JPanel();
crawlLinkSR = new SimpleCheckBox();
crawlLinkUser = new SimpleCheckBox();
crawlLinkComment = new SimpleCheckBox();
crawlUserComment = new SimpleCheckBox();
crawlUserLink = new SimpleCheckBox();
crawlSRLink = new SimpleCheckBox();
crawlCommentUser = new SimpleCheckBox();
crawlCommentLink = new SimpleCheckBox();
crawlToggle = new SimpleCheckBox();
setMinimumSize(new java.awt.Dimension(1500, 376));
setLayout(new java.awt.GridBagLayout());
commentSearchTab.setLayout(new java.awt.GridBagLayout());
threadSearchField.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
threadSearchFieldKeyPressed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 4, 4, 0);
commentSearchTab.add(threadSearchField, gridBagConstraints);
threadSearchSubmit.setText("Search");
threadSearchSubmit.setMaximumSize(new java.awt.Dimension(180, 23));
threadSearchSubmit.setMinimumSize(new java.awt.Dimension(180, 23));
threadSearchSubmit.setPreferredSize(new java.awt.Dimension(180, 23));
threadSearchSubmit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
threadSearchSubmitActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
gridBagConstraints.insets = new java.awt.Insets(3, 0, 3, 3);
commentSearchTab.add(threadSearchSubmit, gridBagConstraints);
threadResList.setMinimumSize(new java.awt.Dimension(200, 200));
threadResList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
threadResListValueChanged(evt);
}
});
threadResScrollPane.setViewportView(threadResList);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 10.0;
gridBagConstraints.weighty = 0.1;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 0);
commentSearchTab.add(threadResScrollPane, gridBagConstraints);
threadSearchDetails.setVerticalAlignment(javax.swing.SwingConstants.TOP);
threadSearchDetails.setBorder(javax.swing.BorderFactory.createTitledBorder("Details"));
threadSearchDetails.setMaximumSize(new java.awt.Dimension(180, 23));
threadSearchDetails.setMinimumSize(new java.awt.Dimension(180, 23));
threadSearchDetails.setPreferredSize(new java.awt.Dimension(180, 23));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
gridBagConstraints.weightx = 0.1;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3);
commentSearchTab.add(threadSearchDetails, gridBagConstraints);
redditTabs.addTab("Submission search", commentSearchTab);
subredditSearchTab.setLayout(new java.awt.GridBagLayout());
subredditSearchField.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
subredditSearchFieldKeyPressed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.PAGE_START;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 4, 4, 0);
subredditSearchTab.add(subredditSearchField, gridBagConstraints);
subredditSearchSubmit.setText("Search");
subredditSearchSubmit.setMaximumSize(new java.awt.Dimension(180, 23));
subredditSearchSubmit.setMinimumSize(new java.awt.Dimension(180, 23));
subredditSearchSubmit.setPreferredSize(new java.awt.Dimension(180, 23));
subredditSearchSubmit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
subredditSearchSubmitActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
gridBagConstraints.insets = new java.awt.Insets(3, 2, 3, 3);
subredditSearchTab.add(subredditSearchSubmit, gridBagConstraints);
subredditResList.setMinimumSize(new java.awt.Dimension(200, 200));
subredditResList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
subredditResListValueChanged(evt);
}
});
subredditResScrollPane.setViewportView(subredditResList);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridheight = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
gridBagConstraints.weightx = 10.0;
gridBagConstraints.weighty = 0.1;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 0);
subredditSearchTab.add(subredditResScrollPane, gridBagConstraints);
subredditDetailTextArea.setEditable(false);
subredditDetailTextArea.setColumns(2);
subredditDetailTextArea.setRows(5);
subredditDetailTextArea.setTabSize(4);
subredditDetailTextArea.setWrapStyleWord(true);
subredditDetailTextArea.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(153, 153, 153)));
subredditDetailTextArea.setMaximumSize(new java.awt.Dimension(180, 180));
subredditDetailTextArea.setMinimumSize(new java.awt.Dimension(180, 180));
subredditDetailTextArea.setPreferredSize(new java.awt.Dimension(180, 180));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(0, 3, 4, 4);
subredditSearchTab.add(subredditDetailTextArea, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
subredditSearchTab.add(subredditTitleLabel, gridBagConstraints);
redditTabs.addTab("Subreddit search", subredditSearchTab);
linkSearchTab.setLayout(new java.awt.GridBagLayout());
linkField.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
linkFieldKeyPressed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.PAGE_START;
gridBagConstraints.weightx = 0.1;
gridBagConstraints.insets = new java.awt.Insets(5, 4, 4, 4);
linkSearchTab.add(linkField, gridBagConstraints);
linkLabel.setText("Link URL");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_END;
gridBagConstraints.insets = new java.awt.Insets(9, 8, 8, 0);
linkSearchTab.add(linkLabel, gridBagConstraints);
linkModel = new DefaultListModel();
linkSearchList.setModel(linkModel);
linkScrollpane.setViewportView(linkSearchList);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.1;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 4);
linkSearchTab.add(linkScrollpane, gridBagConstraints);
linkAddUrlButton.setText("Add URL");
linkAddUrlButton.setMargin(new java.awt.Insets(2, 6, 2, 6));
linkAddUrlButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
linkAddUrlButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
linkSearchTab.add(linkAddUrlButton, gridBagConstraints);
linkAddSLsButton.setText("Add Context SLs");
linkAddSLsButton.setMargin(new java.awt.Insets(2, 6, 2, 6));
linkAddSLsButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
linkAddSLsButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 2);
linkSearchTab.add(linkAddSLsButton, gridBagConstraints);
linkClearButton.setText("Clear All");
linkClearButton.setMargin(new java.awt.Insets(2, 6, 2, 6));
linkClearButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
linkClearButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 4;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4);
linkSearchTab.add(linkClearButton, gridBagConstraints);
redditTabs.addTab("Link search", linkSearchTab);
accountSearchTab.setLayout(new java.awt.GridBagLayout());
accountSearchField.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
accountSearchFieldKeyPressed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.PAGE_START;
gridBagConstraints.weightx = 0.1;
gridBagConstraints.weighty = 0.1;
gridBagConstraints.insets = new java.awt.Insets(5, 4, 4, 4);
accountSearchTab.add(accountSearchField, gridBagConstraints);
jLabel3.setText("Account name");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.PAGE_START;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(9, 5, 4, 0);
accountSearchTab.add(jLabel3, gridBagConstraints);
redditTabs.addTab("Account search", accountSearchTab);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 0.1;
gridBagConstraints.weighty = 0.3;
add(redditTabs, 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("Extract");
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, 2);
buttonPanel.add(okButton, gridBagConstraints);
cancelButton.setText("Cancel");
cancelButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelButtonActionPerformed(evt);
}
});
buttonPanel.add(cancelButton, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.1;
gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2);
add(buttonPanel, gridBagConstraints);
crawlOptions.setBorder(javax.swing.BorderFactory.createTitledBorder("Crawling options"));
crawlOptions.setLayout(new java.awt.GridBagLayout());
crawlLinkSR.setText("Crawl Link Subreddit");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
crawlOptions.add(crawlLinkSR, gridBagConstraints);
crawlLinkUser.setText("Crawl Link Account");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
crawlOptions.add(crawlLinkUser, gridBagConstraints);
crawlLinkComment.setText("Crawl Link Comments");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
crawlOptions.add(crawlLinkComment, gridBagConstraints);
crawlUserComment.setText("Crawl Account Comments");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
crawlOptions.add(crawlUserComment, gridBagConstraints);
crawlUserLink.setText("Crawl Account Links");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
crawlOptions.add(crawlUserLink, gridBagConstraints);
crawlSRLink.setText("Crawl Subreddit Links");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
crawlOptions.add(crawlSRLink, gridBagConstraints);
crawlCommentUser.setText("Crawl Comment Account");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
crawlOptions.add(crawlCommentUser, gridBagConstraints);
crawlCommentLink.setText("Crawl Comment Link");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
crawlOptions.add(crawlCommentLink, gridBagConstraints);
crawlToggle.setText("Crawl Comment Tree");
crawlToggle.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
crawlToggleActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
crawlOptions.add(crawlToggle, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.1;
add(crawlOptions, gridBagConstraints);
}// </editor-fold>//GEN-END:initComponents
private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
accepted = true;
if (this.dialog != null) {
this.dialog.setVisible(false);
}
}//GEN-LAST:event_okButtonActionPerformed
private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
accepted = false;
if (this.dialog != null) {
this.dialog.setVisible(false);
}
}//GEN-LAST:event_cancelButtonActionPerformed
private void threadSearchSubmitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_threadSearchSubmitActionPerformed
this.populateThreadSearch();
}//GEN-LAST:event_threadSearchSubmitActionPerformed
private void threadResListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_threadResListValueChanged
this.focusThread();
}//GEN-LAST:event_threadResListValueChanged
private void threadSearchFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_threadSearchFieldKeyPressed
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
this.populateThreadSearch();
}
}//GEN-LAST:event_threadSearchFieldKeyPressed
private void accountSearchFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_accountSearchFieldKeyPressed
// TODO add your handling code here:
}//GEN-LAST:event_accountSearchFieldKeyPressed
private void crawlToggleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_crawlToggleActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_crawlToggleActionPerformed
private void subredditSearchFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_subredditSearchFieldKeyPressed
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
this.populateSubredditSearch();
}
}//GEN-LAST:event_subredditSearchFieldKeyPressed
private void linkFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_linkFieldKeyPressed
// TODO add your handling code here:
}//GEN-LAST:event_linkFieldKeyPressed
private void linkAddUrlButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_linkAddUrlButtonActionPerformed
String u = linkField.getText();
linkModel.addElement(u);
}//GEN-LAST:event_linkAddUrlButtonActionPerformed
private void linkClearButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_linkClearButtonActionPerformed
linkModel.clear();
}//GEN-LAST:event_linkClearButtonActionPerformed
private void linkAddSLsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_linkAddSLsButtonActionPerformed
addContextSLs();
}//GEN-LAST:event_linkAddSLsButtonActionPerformed
private void subredditSearchSubmitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_subredditSearchSubmitActionPerformed
this.populateSubredditSearch();
}//GEN-LAST:event_subredditSearchSubmitActionPerformed
private void subredditResListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_subredditResListValueChanged
this.focusSubreddit();
}//GEN-LAST:event_subredditResListValueChanged
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextField accountSearchField;
private javax.swing.JPanel accountSearchTab;
private javax.swing.JPanel buttonFillerPanel;
private javax.swing.JPanel buttonPanel;
private javax.swing.JButton cancelButton;
private javax.swing.JPanel commentSearchTab;
private javax.swing.JCheckBox crawlCommentLink;
private javax.swing.JCheckBox crawlCommentUser;
private javax.swing.JCheckBox crawlLinkComment;
private javax.swing.JCheckBox crawlLinkSR;
private javax.swing.JCheckBox crawlLinkUser;
private javax.swing.JPanel crawlOptions;
private javax.swing.JCheckBox crawlSRLink;
private javax.swing.JCheckBox crawlToggle;
private javax.swing.JCheckBox crawlUserComment;
private javax.swing.JCheckBox crawlUserLink;
private javax.swing.JLabel jLabel3;
private javax.swing.JButton linkAddSLsButton;
private javax.swing.JButton linkAddUrlButton;
private javax.swing.JButton linkClearButton;
private javax.swing.JTextField linkField;
private javax.swing.JLabel linkLabel;
private javax.swing.JScrollPane linkScrollpane;
private javax.swing.JList linkSearchList;
private javax.swing.JPanel linkSearchTab;
private javax.swing.JButton okButton;
private javax.swing.JTabbedPane redditTabs;
private javax.swing.JTextArea subredditDetailTextArea;
private javax.swing.JList subredditResList;
private javax.swing.JScrollPane subredditResScrollPane;
private javax.swing.JTextField subredditSearchField;
private javax.swing.JButton subredditSearchSubmit;
private javax.swing.JPanel subredditSearchTab;
private javax.swing.JLabel subredditTitleLabel;
private javax.swing.JList threadResList;
private javax.swing.JScrollPane threadResScrollPane;
private javax.swing.JLabel threadSearchDetails;
private javax.swing.JTextField threadSearchField;
private javax.swing.JButton threadSearchSubmit;
// End of variables declaration//GEN-END:variables
}
| 39,591 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
Requester.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/reddit/Requester.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.extractors.reddit;
import java.util.ArrayList;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.async.Callback;
import com.mashape.unirest.http.exceptions.UnirestException;
import com.mashape.unirest.request.BaseRequest;
/**
*
* A simple helper class to handle requests
*
* This class wraps the Unirest request API into a queue of requests, that
* are executed at most once per two seconds.
*
* @author Eero Lehtonen
* @author akivela
*/
public class Requester {
private static final int REQUEST_DELAY = 2000; // 1 req / 2 s
private static final int WAIT_DELAY = 200;
private ArrayList<Request> requestQueue;
private int runCounter = 0;
private int failCounter = 0;
public Requester() {
requestQueue = new ArrayList<>();
runCounter = 0;
failCounter = 0;
Unirest.clearDefaultHeaders();
setUserAgent();
}
public static void setUserAgent() {
Unirest.setDefaultHeader("User-Agent", "java:wandora:v20150708 (by /u/wandora_app)");
}
public static void setUserAgent(String userAgent) {
Unirest.setDefaultHeader("User-Agent", userAgent);
}
public void addRequest(BaseRequest hr, ParseCallback<JsonNode> callback) {
Request r = new Request(hr, callback);
requestQueue.add(r); // Queue up the request.
}
public void runNext() {
if(requestQueue.isEmpty()) return;
Request currentRequest = requestQueue.remove(0);
currentRequest.run();
// Wait for minimun REQUEST_DELAY milliseconds.
sleep(REQUEST_DELAY);
// Wait until currentRequest has finished. This is necessary as the
// currentRequest may add new requests to the queue. If we skip this wait,
// the extraction may stop before all request are processed. There is a
// maximum wait time of 100*WAIT_DELAY milliseconds to prevent infinite
// loops.
int waitCount = 0;
do {
sleep(WAIT_DELAY);
}
while(!currentRequest.runFinished && ++waitCount < 100);
}
private void sleep(int millis) {
try {
Thread.sleep(millis);
}
catch(Exception e) {
// WAKE UP
}
}
public void clear() {
requestQueue.clear();
}
public int size() {
return requestQueue.size();
}
public boolean hasRequests(){
return !requestQueue.isEmpty();
}
public int getRunCounter() {
return runCounter;
}
public int getFailCounter() {
return failCounter;
}
// -------------------------------------------------------------------------
public class Request {
private BaseRequest request;
private ParseCallback<JsonNode> callback;
public boolean runFinished = false;
Request(BaseRequest r, ParseCallback<JsonNode> callback) {
this.request = r;
this.callback = callback;
this.runFinished = false;
}
/*
Running the request is asynchronous. The method returns until the
request has been processed. Variable runFinished is used to keep
track of the finishing of the request. Requester can't proceed with
next request until the request has been completed, failed or
cancelled.
*/
public void run() {
this.request.asJsonAsync(new Callback<JsonNode>() {
@Override
public void completed(HttpResponse<JsonNode> response) {
callback.run(response);
runFinished = true;
runCounter++;
}
@Override
public void failed(UnirestException e) {
try {
HttpResponse<String> s = request.asString();
callback.error(e, s.getBody());
}
catch (Exception e2) {
callback.error(e2);
}
runFinished = true;
failCounter++;
}
@Override
public void cancelled() {
callback.error(new Exception("Request was cancelled"));
runFinished = true;
}
});
}
}
}
| 5,481 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
MergeMatrixCellRenderer.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/statistics/MergeMatrixCellRenderer.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* MergeMatrixCellRenderer.java
*
*/
package org.wandora.application.tools.statistics;
import java.awt.Color;
import java.awt.Component;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
/**
*
* @author
* Eero
*/
public class MergeMatrixCellRenderer extends DefaultTableCellRenderer implements TableCellRenderer{
private static final long serialVersionUID = 1L;
public MergeMatrixCellRenderer() {
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
try {
Color diagonalColor = new Color(230, 230, 230);
Color layerColor = new Color(192,192,192);
Color defaultColor = new Color(255,255,255);
if(row == 0 || column == 0){
this.setBackground(layerColor);
}
else if(row == column){
this.setBackground(diagonalColor);
} else {
this.setBackground(defaultColor);
}
this.setValue(value);
}
catch(Exception e){
e.printStackTrace(); // TODO EXCEPTION;
// uriLabel.setText("*** Exception occurred while initializing locator table label!");
}
return this;
}
}
| 2,319 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TopicMapDiameter.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/statistics/TopicMapDiameter.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* TopicMapDiameter.java
*
* Created on 1.6.2007, 12:41
*
*/
package org.wandora.application.tools.statistics;
import java.util.Iterator;
import javax.swing.Icon;
import org.wandora.application.Wandora;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.UIBox;
import org.wandora.application.gui.WandoraOptionPane;
import org.wandora.application.tools.AbstractWandoraTool;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicHashMap;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.topicmap.layered.LayerStack;
/**
*
* @author olli
*/
public class TopicMapDiameter extends AbstractWandoraTool {
private static final long serialVersionUID = 1L;
/** Creates a new instance of TopicMapDiameter */
public TopicMapDiameter() {
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/topicmap_diameter.png");
}
@Override
public String getName() {
return "Topic map diameter";
}
@Override
public String getDescription() {
return "Calculates diameter of a topic map, that is maximum shortest path between two topics. Also calculates average shortest path between all topic pairs. Not usable for topic maps of approximately more than 10000 topics.";
}
public void execute(Wandora admin, Context context) throws TopicMapException {
TopicMap tm = solveContextTopicMap(admin, context);
String tmTitle = solveNameForTopicMap(admin, tm);
boolean useHash = false;
int numTopics=-1;
if(!(tm instanceof LayerStack)) numTopics=tm.getNumTopics();
setDefaultLogger();
if(numTopics!=-1) setProgressMax(numTopics);
TopicClusteringCoefficient.TopicNeighborhood n = new TopicClusteringCoefficient.DefaultNeighborhood();
log("Calculating diameter of '"+tmTitle+"'");
log("Preparing topics 1/3");
Iterator<Topic> iter=tm.getTopics();
TopicHashMap<Integer> ids=new TopicHashMap<Integer>();
int counter=0;
while(iter.hasNext() && !forceStop()){
if((counter%100)==0) setProgress(counter);
Topic t = iter.next();
ids.put(t,counter);
counter++;
}
log("Preparing distance matrix 2/3");
if(ids.size() > 10000) {
setState(INVISIBLE);
int a = WandoraOptionPane.showConfirmDialog(admin, "The topic map has more than 10 000 topics. "+
"It is very likely that diameter calculation generates an Out of Memory Exception with a such topic map! "+
"Do you want to use the altenative topic map diamater tool to lessen the burden on memory at an expense of processing time?"
, "Topic map size warning", WandoraOptionPane.YES_NO_CANCEL_OPTION);
if(a == WandoraOptionPane.YES_OPTION) {
setState(VISIBLE);
useHash = true;
} else if(a == WandoraOptionPane.CANCEL_OPTION){
return;
} else {
setState(VISIBLE);
}
}
double average;
int max;
boolean connected;
if(useHash){
TopicMapDiamaterArray path = new TopicMapDiamaterArray(ids.size());
iter=tm.getTopics();
counter=0;
while(iter.hasNext() && !forceStop()){
if((counter%100)==0) setProgress(counter);
Topic topic = iter.next();
Integer tint=ids.get(topic);
counter++;
if(tint==null) continue; // happens if topic has no basename, subject identifiers or subject locator
int ti=tint.intValue();
for(Topic p : n.getNeighborhood(topic)){
Integer pint=ids.get(p);
if(pint==null) continue;
path.put(ti, pint.intValue(), 1);
}
}
log("Calculating diameter 3/3");
int size = ids.size();
counter=0;
setProgress(0);
setProgressMax(size);
for(int k=0;k<size && !forceStop();k++){
setProgress(k);
for(int i=0;i<size;i++){
int ik = path.get(i,k);
if(ik==-1) continue;
for(int j=0;j<size;j++){
int kj = path.get(k,j);
if(kj==-1) continue;
int ij = path.get(i,j);
if(ij > ik+kj || ij == -1) path.put(i,j,ik+kj);
}
}
}
max=1;
average=0;
connected=true;
counter=0;
for(int i=0;i<ids.size() && !forceStop();i++){
for(int j=0;j<ids.size() && !forceStop();j++){
if(i==j) continue;
if(path.get(i,j)!=-1){
if(path.get(i,j)>max) max=path.get(i,j);
average+=path.get(i,j);
counter++;
}
else connected=false;
}
}
} else {
int[][] path=new int[ids.size()][ids.size()];
for(int i=0;i<path.length;i++){
for(int j=0;j<path.length;j++){
path[i][j]=Integer.MAX_VALUE;
}
}
iter=tm.getTopics();
counter=0;
while(iter.hasNext() && !forceStop()){
if((counter%100)==0) setProgress(counter);
Topic topic = iter.next();
Integer tint=ids.get(topic);
counter++;
if(tint==null) continue; // happens if topic has no basename, subject identifiers or subject locator
int ti=tint.intValue();
for(Topic p : n.getNeighborhood(topic)){
Integer pint=ids.get(p);
if(pint==null) continue;
path[ti][pint.intValue()]=1;
}
}
log("Calculating diameter 3/3");
counter=0;
setProgress(0);
setProgressMax(path.length);
for(int k=0;k<path.length && !forceStop();k++){
setProgress(k);
for(int i=0;i<path.length && !forceStop();i++){
if(path[i][k]==Integer.MAX_VALUE) continue;
for(int j=0;j<path.length;j++){
if(path[k][j]==Integer.MAX_VALUE) continue;
if(path[i][j] > path[i][k]+path[k][j]) path[i][j]=path[i][k]+path[k][j];
}
}
}
max=1;
average=0;
connected=true;
counter=0;
for(int i=0;i<path.length && !forceStop();i++){
for(int j=0;j<path.length && !forceStop();j++){
if(i==j) continue;
if(path[i][j]!=Integer.MAX_VALUE){
if(path[i][j]>max) max=path[i][j];
average+=path[i][j];
counter++;
}
else connected=false;
}
}
}
average/=(double)counter;
if(forceStop()) {
log("Operation cancelled!");
log("Unfinished topic map diameter is "+max);
log("Unfinished average shortest path is "+average);
}
else {
if(connected){
log("Topic map is connected!");
log("Topic map diameter is "+max);
log("Average shortest path is "+average);
}
else{
log("Topic map is not connected!");
log("Diameter of largest connected component in topic map is "+max);
log("Average shortest path in connected components is "+average);
}
}
setState(WAIT);
}
}
| 9,044 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TopicMapDiamaterArray.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/statistics/TopicMapDiamaterArray.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* TopicClusteringCoefficient.java
*
* Created on 30. toukokuuta 2007, 13:34
*
*/
package org.wandora.application.tools.statistics;
/**
*
* @author
* Eero
*/
import java.util.HashMap;
import java.util.Map;
public class TopicMapDiamaterArray {
//private SparseDoubleMatrix2D map;
private Map<String,Integer> map;
public TopicMapDiamaterArray(int size){
map = new HashMap<String, Integer>();
}
public void put(int x, int y, int val){
String place = Integer.toString(x) + "-" + Integer.toString(y);
map.put(place,val);
}
public int get(int x,int y){
String place = Integer.toString(x) + "-" + Integer.toString(y);
if(this.map.containsKey(place)){
return this.map.get(place);
}
return -1;
}
}
| 1,616 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AssociationCounterTool.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/statistics/AssociationCounterTool.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* AssociationCounterTool.java
*
* Created on 29. toukokuuta 2007, 10:13
*
*/
package org.wandora.application.tools.statistics;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import javax.swing.Icon;
import org.wandora.application.Wandora;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.UIBox;
import org.wandora.application.tools.AbstractWandoraTool;
import org.wandora.application.tools.GenericOptionsDialog;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.topicmap.layered.Layer;
import org.wandora.topicmap.layered.LayerStack;
import org.wandora.topicmap.layered.LayeredTopic;
/**
*
* @author olli, akivela
*/
public class AssociationCounterTool extends AbstractWandoraTool {
private static final long serialVersionUID = 1L;
public AssociationCounterTool() {
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/layer_acount.png");
}
@Override
public String getName() {
return "Association statistics";
}
@Override
public String getDescription() {
return "Gather and show statistics about associations in the topic map.";
}
public void execute(Wandora admin, Context context) throws TopicMapException {
TopicMap tm = solveContextTopicMap(admin, context);
String tmTitle = solveNameForTopicMap(admin, tm);
GenericOptionsDialog god=new GenericOptionsDialog(admin,"Connection statistics options","Connection statistics options",true,new String[][]{
new String[]{"Type topic","topic","","Which topics are examined, leave blank to include all topics."},
new String[]{"Association type topic","topic","","Which associations are examined, leave blank to include all associations."},
new String[]{"Include instances","boolean","true"},
new String[]{"Include types","boolean","true"},
},admin);
god.setVisible(true);
if(god.wasCancelled()) return;
setDefaultLogger();
Map<String,String> values=god.getValues();
Topic typeTopic=null;
if(values.get("Type topic")!=null && values.get("Type topic").length()>0) {
LayeredTopic lt=(LayeredTopic)admin.getTopicMap().getTopic(values.get("Type topic"));
if(tm!=admin.getTopicMap()){
Layer l=admin.getTopicMap().getLayer(tm);
typeTopic=lt.getTopicForLayer(l);
if(typeTopic==null){
log("Selected type topic not found in layer");
setState(WAIT);
return;
}
}
else typeTopic=lt;
}
Topic associationTypeTopic=null;
if(values.get("Association type topic")!=null && values.get("Association type topic").length()>0) {
LayeredTopic lt=(LayeredTopic)admin.getTopicMap().getTopic(values.get("Association type topic"));
if(tm!=admin.getTopicMap()){
Layer l=admin.getTopicMap().getLayer(tm);
associationTypeTopic=lt.getTopicForLayer(l);
if(associationTypeTopic==null){
log("Selected association type topic not found in layer");
setState(WAIT);
return;
}
}
else associationTypeTopic=lt;
}
boolean includeInstances=Boolean.parseBoolean(values.get("Include instances"));
boolean includeTypes=Boolean.parseBoolean(values.get("Include types"));
int[] counters=new int[2000];
int numTopics=-1;
Iterator<Topic> iter;
if(typeTopic==null) {
log("Getting all topics");
if(!(tm instanceof LayerStack)) numTopics=tm.getNumTopics();
iter = tm.getTopics();
}
else {
log("Getting topics of selected type");
Collection<Topic> topics=tm.getTopicsOfType(typeTopic);
numTopics=topics.size();
iter=topics.iterator();
}
log("Examining topics");
if(numTopics!=-1) setProgressMax(numTopics);
int topicCounter=0;
Topic t;
while( iter.hasNext() && !forceStop()) {
topicCounter++;
if(topicCounter>100) setProgress(topicCounter);
t=iter.next();
int count=0;
if(associationTypeTopic != null)
count += t.getAssociations(associationTypeTopic).size();
else
count += t.getAssociations().size();
if(includeInstances) count+=tm.getTopicsOfType(t).size();
if(includeTypes) count+=t.getTypes().size();
if(count>=counters.length) count=counters.length-1;
counters[count]++;
}
setState(INVISIBLE);
if(!forceStop()) {
String histogramTitle = "Association counts"+(tmTitle==null?"":(" for layer '"+tmTitle)+"'");
HistogramPanel.showHistogramPanel(counters,admin,histogramTitle,true,
"topics: %1$d ; connections: %2$d ; average connections per topic: %3$.2f ; median connections per topic: %4$d","%2$d topics with %1$d connections");
}
}
}
| 6,207 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
MergeMatrixToolPanel.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/statistics/MergeMatrixToolPanel.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* MergeMatrixToolPanel.java
*
*/
package org.wandora.application.tools.statistics;
import java.util.List;
import javax.swing.JDialog;
import javax.swing.table.TableModel;
import org.wandora.application.Wandora;
import org.wandora.application.gui.UIBox;
import org.wandora.application.gui.simple.SimpleButton;
import org.wandora.application.gui.simple.SimpleLabel;
import org.wandora.application.gui.simple.SimpleRadioButton;
import org.wandora.utils.ClipboardBox;
/**
*
* @author
* Eero
*/
public class MergeMatrixToolPanel extends javax.swing.JPanel {
private static final long serialVersionUID = 1L;
private List<List<String>> data = null;
private String html = null;
private String delim = null;
private JDialog dialog = null;
private TableModel tableModel = null;
private MergeMatrixCellRenderer renderer = null;
/**
* Creates
* new
* form
* MergeMatrixToolPanel
*/
public MergeMatrixToolPanel(Wandora w,List<List<String>> data) {
/*
* The data is structured in the following manner:
* [
* [layer #0, layer #0 value #1, layer #0 value #2,...],
* [layer #1, layer #1 value #1, layer #1 value #2,...],
* .
* .
* .
* ]
*/
this.data = data;
this.html = this.dataToHtml();
String[] colNames = new String[this.data.size()+1];
colNames[0] = "";
Object[][] tableData = new Object[this.data.size()+1][];
tableData[0] = new Object[this.data.size()+1];
for(int i = 0;i<this.data.size();i++){
colNames[i+1] = (String)this.data.get(i).get(0);
tableData[0][i+1] = (String)this.data.get(i).get(0);
tableData[i+1] = new Object[this.data.get(i).size()];
for(int j = 0; j < this.data.get(i).size(); j++){
tableData[i+1][j] = this.data.get(i).get(j);
}
}
this.tableModel = new javax.swing.table.DefaultTableModel(tableData,colNames);
this.renderer = new MergeMatrixCellRenderer();
initComponents();
MMTPDelimGroup.add(MMTPDelimTab);
MMTPDelimGroup.add(MMTPDelimDot);
dialog = new JDialog(w,true);
dialog.add(this);
dialog.setSize(800,350);
dialog.setTitle("Merge matrix tool");
UIBox.centerWindow(dialog, w);
dialog.setVisible(true);
}
private String dataToHtml(){
StringBuilder sb = new StringBuilder();
String cellWidth = Double.toString(100.0 / this.data.get(0).size()) + "%";
sb.append("<html>\n")
.append("\t<body>\n")
.append("\t\t<table>\n")
.append("\t\t\t<th>\n");
for(List<String> row : this.data){
sb.append("\t\t\t\t<td>\n")
.append("\t\t\t\t\t").append(row.get(0)).append("\n")
.append("\t\t\t\t</td>\n");
}
for(List<String> row : this.data){
sb.append("\t\t\t<tr>\n");
for(Object cell : row){
String s = (String)cell;
sb.append("\t\t\t\t<td>\n")
.append("\t\t\t\t\t").append(s).append("\n")
.append("\t\t\t\t</td>\n");
}
sb.append("\t\t\t<tr>\n");
}
sb.append("\t\t</table>\n")
.append("\t</body>\n")
.append("</html>\n");
String out = sb.toString();
return out;
}
public void close() {
if(dialog != null) {
dialog.setVisible(false);
}
}
private void delimToClipboard(){
this.delim = "";
String delimeter = (MMTPDelimDot.isSelected()) ? ";" : "\t";
String eol = System.getProperty("line.separator");
delim += delimeter;
for (List<String> row : data) {
delim += (String)row.get(0) + delimeter;
}
delim += eol;
for (List<String> row : data){
for (Object cell : row){
String s = (String)cell;
delim += s + delimeter;
}
delim += eol;
}
ClipboardBox.setClipboard(delim);
}
private void htmlToClipboard(){
ClipboardBox.setClipboard(this.html);
}
/**
* 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;
MMTPDelimGroup = new javax.swing.ButtonGroup();
MMTPCloseButton = new SimpleButton();
MMTPCopyAsHTML = new SimpleButton();
MMTPCopyAsDelimited = new SimpleButton();
MMTPDelimTab = new SimpleRadioButton();
MMTPDelimDot = new SimpleRadioButton();
jScrollPane2 = new javax.swing.JScrollPane();
MMTPTable = new javax.swing.JTable();
MMTPDescription = new SimpleLabel();
setLayout(new java.awt.GridBagLayout());
MMTPCloseButton.setText("Close");
MMTPCloseButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
MMTPCloseButtonMouseReleased(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 4;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
add(MMTPCloseButton, gridBagConstraints);
MMTPCopyAsHTML.setText("Copy as HTML");
MMTPCopyAsHTML.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
MMTPCopyAsHTMLMouseReleased(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2);
add(MMTPCopyAsHTML, gridBagConstraints);
MMTPCopyAsDelimited.setText("Copy as delimited");
MMTPCopyAsDelimited.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
MMTPCopyAsDelimitedMouseReleased(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2);
add(MMTPCopyAsDelimited, gridBagConstraints);
MMTPDelimTab.setSelected(true);
MMTPDelimTab.setText("tab");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 2;
add(MMTPDelimTab, gridBagConstraints);
MMTPDelimDot.setText(";");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 2;
add(MMTPDelimDot, gridBagConstraints);
MMTPTable.setModel(this.tableModel);
MMTPTable.setDefaultRenderer(Object.class, this.renderer);
MMTPTable.setTableHeader(null);
jScrollPane2.setViewportView(MMTPTable);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jScrollPane2, gridBagConstraints);
MMTPDescription.setText("<html>The merge matrix tool has computed the amount of merges between topics and it's displayed below. The data is formatted in the following fashion: each cell has a value computed as the ratio of merging topics between the row layer and the column layer to the total amount of topics in the row layer. Cells in the diagonal have the maximum value as all topics merge with themselves. Maximum value in other cells usually corresponds to the row layer being a child to the column layer.");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
add(MMTPDescription, gridBagConstraints);
}// </editor-fold>//GEN-END:initComponents
private void MMTPCopyAsDelimitedMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_MMTPCopyAsDelimitedMouseReleased
delimToClipboard();
}//GEN-LAST:event_MMTPCopyAsDelimitedMouseReleased
private void MMTPCopyAsHTMLMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_MMTPCopyAsHTMLMouseReleased
htmlToClipboard();
}//GEN-LAST:event_MMTPCopyAsHTMLMouseReleased
private void MMTPCloseButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_MMTPCloseButtonMouseReleased
close();
}//GEN-LAST:event_MMTPCloseButtonMouseReleased
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton MMTPCloseButton;
private javax.swing.JButton MMTPCopyAsDelimited;
private javax.swing.JButton MMTPCopyAsHTML;
private javax.swing.JRadioButton MMTPDelimDot;
private javax.swing.ButtonGroup MMTPDelimGroup;
private javax.swing.JRadioButton MMTPDelimTab;
private javax.swing.JLabel MMTPDescription;
private javax.swing.JTable MMTPTable;
private javax.swing.JScrollPane jScrollPane2;
// End of variables declaration//GEN-END:variables
}
| 11,126 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AssetWeights.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/statistics/AssetWeights.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.statistics;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.Icon;
import org.wandora.application.Wandora;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.UIBox;
import org.wandora.application.gui.WandoraOptionPane;
import org.wandora.application.tools.AbstractWandoraTool;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
/**
* This Wandora tool calculates asset weights for a topic selection. Asset
* weight is a topic specific value describing how many associations and
* occurrences is linked to the topic and it's nearest neighbor topics. Asset
* weight measurement has been developed by Petra Haluzova and is described in
* detail in her research paper at
*
* http://www.topicmapslab.de/publications/evaluation-of-instances-asset-in-a-topic-maps-based-ontology
*
* This tool was implemented by Wandora Team / Aki
*
* @author akivela
*/
public class AssetWeights extends AbstractWandoraTool {
private static final long serialVersionUID = 1L;
public static int CONTEXT_IS_GIVEN = 0;
public static int CONTEXT_IS_TOPICMAP = 1;
private int forcedContext = CONTEXT_IS_GIVEN;
private AssetWeightPanel assetWeightPanel = null;
public AssetWeights() {
}
public AssetWeights(int context) {
forcedContext = context;
}
public AssetWeights(Context preferredContext) {
setContext(preferredContext);
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/asset_weight.png");
}
@Override
public String getName() {
return "Calculate topics' asset weights";
}
@Override
public String getDescription() {
return "Calculate asset weights for selected topics. Asset weight of a topic is a "+
"numeric value proportional to the number of associations and occurrences topic and it's neighbours have. "+
"Asset weight is a topic measure developed by Petra Haluzova. For more info see http://www.topicmapslab.de/publications/evaluation-of-instances-asset-in-a-topic-maps-based-ontology.";
}
@Override
public boolean requiresRefresh() {
return false;
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
ArrayList<Topic> topics = new ArrayList<Topic>();
String topicMapName = null;
TopicMap tm = null;
if(forcedContext == CONTEXT_IS_TOPICMAP) {
tm = solveContextTopicMap(wandora, context);
Iterator<Topic> tmTopics = tm.getTopics();
while(tmTopics.hasNext()) topics.add(tmTopics.next());
topicMapName = solveNameForTopicMap(wandora, tm);
if(topicMapName == null) topicMapName = "Layer stack";
}
else if(forcedContext == CONTEXT_IS_GIVEN) {
tm = wandora.getTopicMap();
int c = 0;
Iterator<Topic> i = context.getContextObjects();
while(i.hasNext()) { topics.add(i.next()); c++; }
topicMapName = "Selection of "+c+" topics";
}
if(!topics.isEmpty()) {
if(assetWeightPanel == null) {
assetWeightPanel = new AssetWeightPanel(wandora, topics);
}
else {
assetWeightPanel.setTopics(topics);
}
assetWeightPanel.open(topicMapName, tm); // BLOCKS TILL CLOSED
}
else {
WandoraOptionPane.showMessageDialog(wandora, "You have not selected any topics for asset weight calculations. Select topics and try again, please.", "Select topics");
}
}
}
| 4,573 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TopicMapStatistics.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/statistics/TopicMapStatistics.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
* TopicMapStatistics.java
*
* Created on 25. toukokuuta 2006, 19:50
*
*/
package org.wandora.application.tools.statistics;
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.TopicMapStatisticsDialog;
import org.wandora.application.gui.UIBox;
import org.wandora.application.tools.AbstractWandoraTool;
import org.wandora.topicmap.TopicMap;
/**
*
* @author akivela
*/
public class TopicMapStatistics extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
public TopicMapStatistics() {
}
public TopicMapStatistics(Context preferredContext) {
setContext(preferredContext);
}
@Override
public void execute(Wandora wandora, Context context) {
try {
TopicMap map = solveContextTopicMap(wandora, context);
String name = solveNameForTopicMap(wandora, map);
TopicMapStatisticsDialog d = new TopicMapStatisticsDialog(wandora, map, name);
d.setVisible(true);
}
catch(Exception e) {
log(e);
}
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/layer_info.png");
}
@Override
public String getName() {
return "Topic map statistics";
}
@Override
public String getDescription() {
return "View topic map statistics.";
}
@Override
public boolean requiresRefresh() {
return false;
}
}
| 2,436 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
HistogramPanel.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/statistics/HistogramPanel.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* HistogramPanel.java
*
* Created on 29. toukokuuta 2007, 10:54
*/
package org.wandora.application.tools.statistics;
import java.awt.Color;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.io.PrintWriter;
import java.io.StringWriter;
import javax.swing.JDialog;
import javax.swing.JPanel;
import org.wandora.application.gui.simple.SimpleButton;
import org.wandora.utils.ClipboardBox;
import org.wandora.utils.swing.GuiTools;
/**
*
* @author olli
*/
public class HistogramPanel extends javax.swing.JPanel {
private static final long serialVersionUID = 1L;
private int[] data;
private int maxValue;
private int dataSize;
private int zoomFactor;
private int mouseOverIndex;
private double average;
private int median;
private String infoString;
private Dialog parentDialog;
private String infoPattern;
private String mousePattern;
public static final String defaultInfoPattern="Sum = %1$d ; Sum values = %2$d ; Ave = %3$.2f ; Median = %4$d";
public static final String defaultMousePattern="%1$d, %2$d";
/** Creates new form HistogramPanel */
public HistogramPanel(int[] data) {
this(data,null,defaultInfoPattern,defaultMousePattern);
}
public HistogramPanel(int[] data,Dialog parentDialog,String infoPattern,String mousePattern) {
this.data=data;
this.parentDialog=parentDialog;
this.infoPattern=infoPattern;
this.mousePattern=mousePattern;
this.maxValue=1;
this.dataSize=0;
long sumNodes=0;
long sumLinks=0;
for(int i=0;i<data.length;i++){
sumLinks+=i*data[i];
sumNodes+=data[i];
if(data[i]>0) dataSize=i;
if(data[i]>maxValue) maxValue=data[i];
}
dataSize++;
if(sumNodes>0) average=(double)sumLinks/(double)sumNodes;
long sum2=0;
for(int i=0;i<data.length;i++){
sum2+=data[i];
if(sum2>sumNodes/2){
median=i;
break;
}
}
StringWriter sw=new StringWriter();
PrintWriter pw=new PrintWriter(sw);
pw.printf(infoPattern,sumNodes, sumLinks, average, median);
infoString=sw.toString();
zoomFactor=1;
mouseOverIndex=-1;
initComponents();
if(parentDialog==null) closeButton.setVisible(false);
infoLabel.setText(infoString);
updateContentSize();
}
public static void showHistogramPanel(int[] data,Frame parent,String title,boolean modal){
showHistogramPanel(data,parent,title,modal,defaultInfoPattern,defaultMousePattern);
}
public static void showHistogramPanel(int[] data,Frame parent,String title,boolean modal,String infoPattern,String mousePattern){
JDialog jd=new JDialog(parent,title,modal);
jd.getContentPane().setLayout(new GridBagLayout());
HistogramPanel p=new HistogramPanel(data,jd,infoPattern,mousePattern);
GridBagConstraints gbc=new GridBagConstraints();
gbc.fill=gbc.BOTH;
gbc.gridx=0;
gbc.gridy=0;
gbc.weightx=1.0;
gbc.weighty=1.0;
jd.getContentPane().add(p,gbc);
jd.setSize(700,400);
GuiTools.centerWindow(jd,parent);
jd.setVisible(true);
}
private void updateContentSize(){
int h=scrollPane.getViewport().getHeight();
contentPanel.setMinimumSize(new Dimension(zoomFactor*dataSize,h));
contentPanel.setMaximumSize(new Dimension(zoomFactor*dataSize,h));
contentPanel.setPreferredSize(new Dimension(zoomFactor*dataSize,h));
contentPanel.revalidate();
contentPanel.repaint();
}
/** 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();
infoLabel = new org.wandora.application.gui.simple.SimpleLabel();
mouseLabel = new org.wandora.application.gui.simple.SimpleLabel();
scrollPane = new javax.swing.JScrollPane();
contentPanel = new ContentPanel();
jPanel3 = new javax.swing.JPanel();
jPanel4 = new javax.swing.JPanel();
zoomOutButton = new SimpleButton();
zoomInButton = new SimpleButton();
copyButton = new SimpleButton();
closeButton = new SimpleButton();
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(java.awt.event.ComponentEvent evt) {
formComponentResized(evt);
}
});
setLayout(new java.awt.GridBagLayout());
jPanel2.setLayout(new java.awt.GridBagLayout());
infoLabel.setText(" ");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
jPanel2.add(infoLabel, gridBagConstraints);
mouseLabel.setText(" ");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
jPanel2.add(mouseLabel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 0, 4);
add(jPanel2, gridBagConstraints);
scrollPane.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
contentPanel.setPreferredSize(new java.awt.Dimension(400, 240));
contentPanel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
contentPanelMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
contentPanelMouseExited(evt);
}
});
contentPanel.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
contentPanelMouseMoved(evt);
}
});
contentPanel.setLayout(new java.awt.BorderLayout());
scrollPane.setViewportView(contentPanel);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
add(scrollPane, gridBagConstraints);
jPanel3.setLayout(new java.awt.GridBagLayout());
jPanel4.setLayout(new java.awt.GridBagLayout());
zoomOutButton.setText("-");
zoomOutButton.setToolTipText("Zoom out...");
zoomOutButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
zoomOutButtonActionPerformed(evt);
}
});
jPanel4.add(zoomOutButton, new java.awt.GridBagConstraints());
zoomInButton.setText("+");
zoomInButton.setToolTipText("Zoom in...");
zoomInButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
zoomInButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 0);
jPanel4.add(zoomInButton, gridBagConstraints);
copyButton.setText("Copy to clipboard");
copyButton.setToolTipText("Copy histogram data to system clipboard...");
copyButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
copyButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 0);
jPanel4.add(copyButton, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
jPanel3.add(jPanel4, gridBagConstraints);
closeButton.setText("Close");
closeButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
closeButtonActionPerformed(evt);
}
});
jPanel3.add(closeButton, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 4);
add(jPanel3, gridBagConstraints);
}// </editor-fold>//GEN-END:initComponents
private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeButtonActionPerformed
parentDialog.setVisible(false);
}//GEN-LAST:event_closeButtonActionPerformed
private void copyButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_copyButtonActionPerformed
StringBuffer sb=new StringBuffer();
for(int i=0;i<dataSize;i++){
sb.append(i+"\t"+data[i]+"\n");
}
ClipboardBox.setClipboard(sb.toString());
}//GEN-LAST:event_copyButtonActionPerformed
private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
updateContentSize();
}//GEN-LAST:event_formComponentResized
private void zoomInButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_zoomInButtonActionPerformed
zoomFactor++;
updateContentSize();
}//GEN-LAST:event_zoomInButtonActionPerformed
private void zoomOutButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_zoomOutButtonActionPerformed
if(zoomFactor>1){
zoomFactor--;
updateContentSize();
}
}//GEN-LAST:event_zoomOutButtonActionPerformed
private void contentPanelMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_contentPanelMouseMoved
int x=evt.getX();
mouseOverIndex=x/zoomFactor;
if(mouseOverIndex<data.length && mouseOverIndex>=0){
StringWriter sw=new StringWriter();
PrintWriter pw=new PrintWriter(sw);
pw.printf(mousePattern,mouseOverIndex,data[mouseOverIndex]);
mouseLabel.setText(sw.toString());
}
else{
mouseOverIndex=-1;
mouseLabel.setText(" ");
}
contentPanel.repaint();
}//GEN-LAST:event_contentPanelMouseMoved
private void contentPanelMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_contentPanelMouseExited
mouseOverIndex=-1;
mouseLabel.setText(" ");
}//GEN-LAST:event_contentPanelMouseExited
private void contentPanelMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_contentPanelMouseEntered
}//GEN-LAST:event_contentPanelMouseEntered
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton closeButton;
private javax.swing.JPanel contentPanel;
private javax.swing.JButton copyButton;
private javax.swing.JLabel infoLabel;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JLabel mouseLabel;
private javax.swing.JScrollPane scrollPane;
private javax.swing.JButton zoomInButton;
private javax.swing.JButton zoomOutButton;
// End of variables declaration//GEN-END:variables
private class ContentPanel extends JPanel {
private static final long serialVersionUID = 1L;
private Color barColor=new Color(0,0,0);
private Color bgColor=new Color(255,255,255);
private Color mouseBgColor=new Color(255,128,128);
private Color mouseColor=new Color(128,0,0);
private Color averageBgColor=new Color(128,255,128);
private Color averageColor=new Color(0,128,0);
private Color medianBgColor=new Color(128,255,255);
private Color medianColor=new Color(0,128,128);
public ContentPanel(){
}
public void paint(Graphics g){
Graphics2D g2=(Graphics2D)g;
int h=this.getHeight();
double offs=Math.log(10);
double f=(h-1)/(Math.log(maxValue+10)-offs);
g2.setColor(bgColor);
g2.fillRect(0,0,this.getWidth(),this.getHeight());
Color bg=null;
Color fg=null;
int ave=(int)(average+0.5);
for(int i=0;i<dataSize;i++){
int v=(int)Math.ceil(f*(Math.log(data[i]+10)-offs));
if(i==mouseOverIndex){
bg=mouseBgColor;
fg=mouseColor;
}
else if(i==ave){
bg=averageBgColor;
fg=averageColor;
}
else if(i==median){
bg=medianBgColor;
fg=medianColor;
}
else {
bg=bgColor;
fg=barColor;
}
if(bg!=bgColor) {
g2.setColor(bg);
g2.fillRect(i*zoomFactor,0,zoomFactor,h-v);
}
g2.setColor(fg);
g2.fillRect(i*zoomFactor,h-v,zoomFactor,v);
}
}
}
}
| 15,911 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AssetWeightPanel.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/statistics/AssetWeightPanel.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* AssetWeightPanel.java
*
* Created on 10.11.2010, 10:51:45
*/
package org.wandora.application.tools.statistics;
import java.awt.BorderLayout;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import javax.swing.JDialog;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;
import org.wandora.application.Wandora;
import org.wandora.application.gui.simple.SimpleButton;
import org.wandora.application.gui.simple.SimpleCheckBox;
import org.wandora.application.gui.simple.SimpleField;
import org.wandora.application.gui.simple.SimpleLabel;
import org.wandora.application.gui.simple.SimpleScrollPane;
import org.wandora.application.gui.simple.SimpleTabbedPane;
import org.wandora.application.gui.simple.SimpleToggleButton;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.utils.ClipboardBox;
/**
*
* @author akivela
*/
public class AssetWeightPanel extends javax.swing.JPanel {
private static final long serialVersionUID = 1L;
private JDialog assetWeightDialog = null;
private Wandora app = null;
private Collection<Topic> topics = null;
private TopicMap tm = null;
private TopicWeightTable followWeightTypesTable = null;
private TopicWeightTable partialWeightTypesTable = null;
private TopicWeightTable resultsTable = null;
private HashMap<Topic,Double> followWeightTypes = new LinkedHashMap<Topic,Double>();
private HashMap<Topic,Double> partialWeightTypes = new LinkedHashMap<Topic,Double>();
private HashMap<Topic, Double> partialWeights = new LinkedHashMap<Topic, Double>();
private HashMap<Topic, Double> neighborhoodWeights = new LinkedHashMap<Topic, Double>();
private HashMap<Topic, Double> totalTopicWeights = new LinkedHashMap<Topic, Double>();
private HashMap<Topic, Double> normalizedTotalTopicWeights = new LinkedHashMap<Topic, Double>();
/** Creates new form AssetWeightPanel */
public AssetWeightPanel(Wandora application, Collection<Topic> topics) {
this.app = application;
this.topics = topics;
this.tm = app.getTopicMap();
initComponents();
followWeightTypesTable = new TopicWeightTable(followWeightTypes);
followWeightTypesTableScrollPane.setViewportView(followWeightTypesTable);
followWeightTypesTablePanel.add(followWeightTypesTable.getTableHeader(), BorderLayout.NORTH);
partialWeightTypesTable = new TopicWeightTable(partialWeightTypes);
partialWeightTypesTableScrollPane.setViewportView(partialWeightTypesTable);
partialWeightTypesTablePanel.add(partialWeightTypesTable.getTableHeader(), BorderLayout.NORTH);
resultsTable = new TopicWeightTable(totalTopicWeights);
resultsTableScrollPane.setViewportView(resultsTable);
resultsTablePanel.add(resultsTable.getTableHeader(), BorderLayout.NORTH);
resultsTable.setColumnNames("Topic", "Asset weight");
}
public void open(String title, TopicMap topicMap) {
tm = topicMap;
assetWeightDialog = new JDialog(app, true);
if(title == null) title = "";
else title = " - "+title;
assetWeightDialog.setTitle("Topic asset weights" + title);
assetWeightDialog.add(this);
assetWeightDialog.setSize(800,350);
app.centerWindow(assetWeightDialog);
assetWeightDialog.setVisible(true);
resultsInfoLabel.setText("");
calculateAndUpdate();
}
public void close() {
if(assetWeightDialog != null) {
assetWeightDialog.setVisible(false);
}
}
public void setTopics(Collection<Topic> topics) {
this.topics = topics;
}
private void updateResultsInfo(double average) {
resultsInfoLabel.setText("Average weight: "+average);
}
/** 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;
assetWeightTabbedPane = new SimpleTabbedPane();
introductionPanel = new javax.swing.JPanel();
introductionPanelInner = new javax.swing.JPanel();
introductionLabel = new SimpleLabel();
partialWeightOptionsPanel = new javax.swing.JPanel();
partialWeightOptionsPanelInner = new javax.swing.JPanel();
partialWeightOptionsLabel = new SimpleLabel();
jPanel1 = new javax.swing.JPanel();
initialPartialWeightPanel = new javax.swing.JPanel();
initialPartialWeightLabel = new SimpleLabel();
initialPartialWeightTextField = new SimpleField();
includeOccurrencesPanel = new javax.swing.JPanel();
includeOccurrencesCheckBox = new SimpleCheckBox();
defaultPartialWeightOfOccurrenceTextField = new SimpleField();
includeAssociationsPanel = new javax.swing.JPanel();
includeAssociationsCheckBox = new SimpleCheckBox();
defaultPartialWeightOfAssociationTextField = new SimpleField();
includeClassesPanel = new javax.swing.JPanel();
includeClassesCheckBox = new SimpleCheckBox();
partialWeightOfClassTextField = new SimpleField();
includeInstancesPanel = new javax.swing.JPanel();
includeInstancesCheckBox = new SimpleCheckBox();
partialWeightOfinstanceTextField = new SimpleField();
partialWeightsPanel = new javax.swing.JPanel();
partialWeightTypesPanelInner = new javax.swing.JPanel();
partialWeightTypesTablePanel = new javax.swing.JPanel();
partialWeightTypesTableScrollPane = new javax.swing.JScrollPane();
partialWeightTypesButtonPanel = new javax.swing.JPanel();
addPartialWeightTypeButton = new SimpleButton();
removePartialWeightTypeButton = new SimpleButton();
followOptionsPanel = new javax.swing.JPanel();
followOptionsPanelPanelInner = new javax.swing.JPanel();
followOptionsLabel = new SimpleLabel();
jPanel2 = new javax.swing.JPanel();
followAssociationsPanel = new javax.swing.JPanel();
followAllAssociationsCheckBox = new SimpleCheckBox();
defaultFollowWeightOfAssociationTextField = new SimpleField();
followNaryAssociationsCheckBox = new SimpleCheckBox();
followClassesPanel = new javax.swing.JPanel();
followClassesCheckBox = new SimpleCheckBox();
followWeightOfClassTextField = new SimpleField();
followInstancesPanel = new javax.swing.JPanel();
followInstancesCheckBox = new SimpleCheckBox();
followWeightOfInstanceTextField = new SimpleField();
coefficientPanel = new javax.swing.JPanel();
coefficientLabel = new SimpleLabel();
coefficientTextField = new SimpleField();
followWeightsPanel = new javax.swing.JPanel();
followWeightsPanelInner = new javax.swing.JPanel();
followWeightTypesTablePanel = new javax.swing.JPanel();
followWeightTypesTableScrollPane = new SimpleScrollPane();
followWeightsButtonPanel = new javax.swing.JPanel();
addFollowWeightTypeButton = new SimpleButton();
removeFollowWeightTypeButton = new SimpleButton();
resultsPanel = new javax.swing.JPanel();
resultsPanelInner = new javax.swing.JPanel();
resultsTablePanel = new javax.swing.JPanel();
resultsTableScrollPane = new javax.swing.JScrollPane();
resultsButtonPanel = new javax.swing.JPanel();
jPanel4 = new javax.swing.JPanel();
resultsInfoLabel = new javax.swing.JLabel();
copyResultsButton = new SimpleButton();
normalizeButton = new SimpleToggleButton();
jPanel3 = new javax.swing.JPanel();
buttonPanel = new javax.swing.JPanel();
buttonFillerPanel = new javax.swing.JPanel();
calculateButton = new SimpleButton();
closeButton = new SimpleButton();
setLayout(new java.awt.GridBagLayout());
introductionPanel.setLayout(new java.awt.GridBagLayout());
introductionPanelInner.setLayout(new java.awt.GridBagLayout());
introductionLabel.setText("<html>Asset weight is a measure of a topic. The asset weight is a numeric value proportional to the number of occurrences and associations of a topic and it's neighbors. \nThe asset weight measure has been developed by Petra Haluzova and is described in detail in her TMRA'10 conference paper 'Evaluation of Instances Asset in a Topic Maps-Based Ontology'. This dialog is used to calculate asset weight values for selected topics.<br><br>To continue, select which assets you want to include asset weight calculations. The asset selection is created in 'Partial weight options' tab. You can specify type specific asset weights in 'Partial weights' tab. \nThen select which associations specify a neighborhood for a topic, and give follow weights. Finally, press Calculate button to create a result table.</html>");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
introductionPanelInner.add(introductionLabel, 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(20, 20, 20, 20);
introductionPanel.add(introductionPanelInner, gridBagConstraints);
assetWeightTabbedPane.addTab("Introduction", introductionPanel);
partialWeightOptionsPanel.setLayout(new java.awt.GridBagLayout());
partialWeightOptionsPanelInner.setLayout(new java.awt.GridBagLayout());
partialWeightOptionsLabel.setText("<html>In this tab you can specify which topic elements are used to calculate partial weights. Partial weight is a topic specific value proportional to the number of topic's occurrences and associations.</html>");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 10, 0);
partialWeightOptionsPanelInner.add(partialWeightOptionsLabel, gridBagConstraints);
jPanel1.setLayout(new java.awt.GridBagLayout());
initialPartialWeightPanel.setLayout(new java.awt.GridBagLayout());
initialPartialWeightLabel.setFont(org.wandora.application.gui.UIConstants.buttonLabelFont);
initialPartialWeightLabel.setText("Initial partial weight of a topic");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(3, 5, 3, 5);
initialPartialWeightPanel.add(initialPartialWeightLabel, gridBagConstraints);
initialPartialWeightTextField.setHorizontalAlignment(javax.swing.JTextField.CENTER);
initialPartialWeightTextField.setText("1");
initialPartialWeightTextField.setMinimumSize(new java.awt.Dimension(40, 20));
initialPartialWeightTextField.setPreferredSize(new java.awt.Dimension(40, 20));
initialPartialWeightPanel.add(initialPartialWeightTextField, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
jPanel1.add(initialPartialWeightPanel, gridBagConstraints);
includeOccurrencesPanel.setLayout(new java.awt.GridBagLayout());
includeOccurrencesCheckBox.setSelected(true);
includeOccurrencesCheckBox.setText("Include ALL occurrences. If unselected, includes only occurrences specified in Partial weights tab. Default occurrence weight is");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
includeOccurrencesPanel.add(includeOccurrencesCheckBox, gridBagConstraints);
defaultPartialWeightOfOccurrenceTextField.setHorizontalAlignment(javax.swing.JTextField.CENTER);
defaultPartialWeightOfOccurrenceTextField.setText("1");
defaultPartialWeightOfOccurrenceTextField.setMinimumSize(new java.awt.Dimension(40, 20));
defaultPartialWeightOfOccurrenceTextField.setPreferredSize(new java.awt.Dimension(40, 20));
includeOccurrencesPanel.add(defaultPartialWeightOfOccurrenceTextField, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
jPanel1.add(includeOccurrencesPanel, gridBagConstraints);
includeAssociationsPanel.setLayout(new java.awt.GridBagLayout());
includeAssociationsCheckBox.setText("Include ALL associations. If unselected, includes only associations specified in Partial weights tab. Default association weight is");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
includeAssociationsPanel.add(includeAssociationsCheckBox, gridBagConstraints);
defaultPartialWeightOfAssociationTextField.setHorizontalAlignment(javax.swing.JTextField.CENTER);
defaultPartialWeightOfAssociationTextField.setText("1");
defaultPartialWeightOfAssociationTextField.setMinimumSize(new java.awt.Dimension(40, 20));
defaultPartialWeightOfAssociationTextField.setPreferredSize(new java.awt.Dimension(40, 20));
includeAssociationsPanel.add(defaultPartialWeightOfAssociationTextField, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
jPanel1.add(includeAssociationsPanel, gridBagConstraints);
includeClassesPanel.setLayout(new java.awt.GridBagLayout());
includeClassesCheckBox.setText("Include classes. Class asset weight is");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
includeClassesPanel.add(includeClassesCheckBox, gridBagConstraints);
partialWeightOfClassTextField.setHorizontalAlignment(javax.swing.JTextField.CENTER);
partialWeightOfClassTextField.setText("1");
partialWeightOfClassTextField.setMinimumSize(new java.awt.Dimension(40, 20));
partialWeightOfClassTextField.setPreferredSize(new java.awt.Dimension(40, 20));
includeClassesPanel.add(partialWeightOfClassTextField, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
jPanel1.add(includeClassesPanel, gridBagConstraints);
includeInstancesPanel.setLayout(new java.awt.GridBagLayout());
includeInstancesCheckBox.setText("Include instances. Instance asset weight is");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
includeInstancesPanel.add(includeInstancesCheckBox, gridBagConstraints);
partialWeightOfinstanceTextField.setHorizontalAlignment(javax.swing.JTextField.CENTER);
partialWeightOfinstanceTextField.setText("1");
partialWeightOfinstanceTextField.setMinimumSize(new java.awt.Dimension(40, 20));
partialWeightOfinstanceTextField.setPreferredSize(new java.awt.Dimension(40, 20));
includeInstancesPanel.add(partialWeightOfinstanceTextField, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
jPanel1.add(includeInstancesPanel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
partialWeightOptionsPanelInner.add(jPanel1, 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);
partialWeightOptionsPanel.add(partialWeightOptionsPanelInner, gridBagConstraints);
assetWeightTabbedPane.addTab("Partial weight options", partialWeightOptionsPanel);
partialWeightsPanel.setLayout(new java.awt.GridBagLayout());
partialWeightTypesPanelInner.setLayout(new java.awt.GridBagLayout());
partialWeightTypesTablePanel.setLayout(new java.awt.BorderLayout());
partialWeightTypesTablePanel.add(partialWeightTypesTableScrollPane, java.awt.BorderLayout.CENTER);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
partialWeightTypesPanelInner.add(partialWeightTypesTablePanel, gridBagConstraints);
partialWeightTypesButtonPanel.setLayout(new java.awt.GridBagLayout());
addPartialWeightTypeButton.setText("Add type");
addPartialWeightTypeButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
addPartialWeightTypeButtonMouseReleased(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4);
partialWeightTypesButtonPanel.add(addPartialWeightTypeButton, gridBagConstraints);
removePartialWeightTypeButton.setText("Remove type");
removePartialWeightTypeButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
removePartialWeightTypeButtonMouseReleased(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 10);
partialWeightTypesButtonPanel.add(removePartialWeightTypeButton, 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);
partialWeightTypesPanelInner.add(partialWeightTypesButtonPanel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
partialWeightsPanel.add(partialWeightTypesPanelInner, gridBagConstraints);
assetWeightTabbedPane.addTab("Partial weights", partialWeightsPanel);
followOptionsPanel.setLayout(new java.awt.GridBagLayout());
followOptionsPanelPanelInner.setLayout(new java.awt.GridBagLayout());
followOptionsLabel.setText("<html>Here you can specify what is topic's neighborhood. You can follow all associations or just some.</html>");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 10, 0);
followOptionsPanelPanelInner.add(followOptionsLabel, gridBagConstraints);
jPanel2.setLayout(new java.awt.GridBagLayout());
followAssociationsPanel.setLayout(new java.awt.GridBagLayout());
followAllAssociationsCheckBox.setSelected(true);
followAllAssociationsCheckBox.setText("Follow ALL associations. If unselected, follows only associations specified in Follow weights tab. Default follow weight is");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
followAssociationsPanel.add(followAllAssociationsCheckBox, gridBagConstraints);
defaultFollowWeightOfAssociationTextField.setHorizontalAlignment(javax.swing.JTextField.CENTER);
defaultFollowWeightOfAssociationTextField.setText("1");
defaultFollowWeightOfAssociationTextField.setMinimumSize(new java.awt.Dimension(40, 20));
defaultFollowWeightOfAssociationTextField.setPreferredSize(new java.awt.Dimension(40, 20));
followAssociationsPanel.add(defaultFollowWeightOfAssociationTextField, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
jPanel2.add(followAssociationsPanel, gridBagConstraints);
followNaryAssociationsCheckBox.setSelected(true);
followNaryAssociationsCheckBox.setText("Follow N-ary associations.");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
jPanel2.add(followNaryAssociationsCheckBox, gridBagConstraints);
followClassesPanel.setLayout(new java.awt.GridBagLayout());
followClassesCheckBox.setSelected(true);
followClassesCheckBox.setText("Follow classes. Class asset follow weight is");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
followClassesPanel.add(followClassesCheckBox, gridBagConstraints);
followWeightOfClassTextField.setHorizontalAlignment(javax.swing.JTextField.CENTER);
followWeightOfClassTextField.setText("1");
followWeightOfClassTextField.setMinimumSize(new java.awt.Dimension(40, 20));
followWeightOfClassTextField.setPreferredSize(new java.awt.Dimension(40, 20));
followClassesPanel.add(followWeightOfClassTextField, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
jPanel2.add(followClassesPanel, gridBagConstraints);
followInstancesPanel.setLayout(new java.awt.GridBagLayout());
followInstancesCheckBox.setSelected(true);
followInstancesCheckBox.setText("Follow instances. Instance asset follow weight is");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
followInstancesPanel.add(followInstancesCheckBox, gridBagConstraints);
followWeightOfInstanceTextField.setHorizontalAlignment(javax.swing.JTextField.CENTER);
followWeightOfInstanceTextField.setText("1");
followWeightOfInstanceTextField.setMinimumSize(new java.awt.Dimension(40, 20));
followWeightOfInstanceTextField.setPreferredSize(new java.awt.Dimension(40, 20));
followInstancesPanel.add(followWeightOfInstanceTextField, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
jPanel2.add(followInstancesPanel, gridBagConstraints);
coefficientPanel.setLayout(new java.awt.GridBagLayout());
coefficientLabel.setFont(org.wandora.application.gui.UIConstants.buttonLabelFont);
coefficientLabel.setText("Follow coefficient is");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(2, 5, 2, 5);
coefficientPanel.add(coefficientLabel, gridBagConstraints);
coefficientTextField.setHorizontalAlignment(javax.swing.JTextField.CENTER);
coefficientTextField.setText("0.5");
coefficientTextField.setMinimumSize(new java.awt.Dimension(40, 20));
coefficientTextField.setPreferredSize(new java.awt.Dimension(40, 20));
coefficientPanel.add(coefficientTextField, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
jPanel2.add(coefficientPanel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
followOptionsPanelPanelInner.add(jPanel2, 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);
followOptionsPanel.add(followOptionsPanelPanelInner, gridBagConstraints);
assetWeightTabbedPane.addTab("Follow options", followOptionsPanel);
followWeightsPanel.setLayout(new java.awt.GridBagLayout());
followWeightsPanelInner.setLayout(new java.awt.GridBagLayout());
followWeightTypesTablePanel.setLayout(new java.awt.BorderLayout());
followWeightTypesTablePanel.add(followWeightTypesTableScrollPane, java.awt.BorderLayout.CENTER);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
followWeightsPanelInner.add(followWeightTypesTablePanel, gridBagConstraints);
followWeightsButtonPanel.setLayout(new java.awt.GridBagLayout());
addFollowWeightTypeButton.setText("Add type");
addFollowWeightTypeButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
addFollowWeightTypeButtonMouseReleased(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4);
followWeightsButtonPanel.add(addFollowWeightTypeButton, gridBagConstraints);
removeFollowWeightTypeButton.setText("Remove type");
removeFollowWeightTypeButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
removeFollowWeightTypeButtonMouseReleased(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 10);
followWeightsButtonPanel.add(removeFollowWeightTypeButton, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
followWeightsPanelInner.add(followWeightsButtonPanel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
followWeightsPanel.add(followWeightsPanelInner, gridBagConstraints);
assetWeightTabbedPane.addTab("Follow weights", followWeightsPanel);
resultsPanel.setLayout(new java.awt.GridBagLayout());
resultsPanelInner.setLayout(new java.awt.GridBagLayout());
resultsTablePanel.setLayout(new java.awt.BorderLayout());
resultsTablePanel.add(resultsTableScrollPane, java.awt.BorderLayout.CENTER);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
resultsPanelInner.add(resultsTablePanel, gridBagConstraints);
resultsButtonPanel.setLayout(new java.awt.GridBagLayout());
jPanel4.setPreferredSize(new java.awt.Dimension(100, 20));
jPanel4.setLayout(new java.awt.GridBagLayout());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
jPanel4.add(resultsInfoLabel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
resultsButtonPanel.add(jPanel4, gridBagConstraints);
copyResultsButton.setText("Copy");
copyResultsButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
copyResultsButtonMouseReleased(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5);
resultsButtonPanel.add(copyResultsButton, gridBagConstraints);
normalizeButton.setFont(org.wandora.application.gui.UIConstants.buttonLabelFont);
normalizeButton.setText("Normalize");
normalizeButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
normalizeButtonMouseReleased(evt);
}
});
resultsButtonPanel.add(normalizeButton, new java.awt.GridBagConstraints());
jPanel3.setPreferredSize(new java.awt.Dimension(100, 5));
jPanel3.setLayout(new java.awt.GridBagLayout());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
resultsButtonPanel.add(jPanel3, 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);
resultsPanelInner.add(resultsButtonPanel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
resultsPanel.add(resultsPanelInner, gridBagConstraints);
assetWeightTabbedPane.addTab("Results", resultsPanel);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(assetWeightTabbedPane, gridBagConstraints);
buttonPanel.setLayout(new java.awt.GridBagLayout());
buttonFillerPanel.setPreferredSize(new java.awt.Dimension(100, 10));
javax.swing.GroupLayout buttonFillerPanelLayout = new javax.swing.GroupLayout(buttonFillerPanel);
buttonFillerPanel.setLayout(buttonFillerPanelLayout);
buttonFillerPanelLayout.setHorizontalGroup(
buttonFillerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 597, Short.MAX_VALUE)
);
buttonFillerPanelLayout.setVerticalGroup(
buttonFillerPanelLayout.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(buttonFillerPanel, gridBagConstraints);
calculateButton.setText("Calculate");
calculateButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
calculateButtonMouseReleased(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3);
buttonPanel.add(calculateButton, gridBagConstraints);
closeButton.setText("Close");
closeButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
closeButtonMouseReleased(evt);
}
});
buttonPanel.add(closeButton, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
add(buttonPanel, gridBagConstraints);
}// </editor-fold>//GEN-END:initComponents
private void addFollowWeightTypeButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_addFollowWeightTypeButtonMouseReleased
try {
Topic t = app.showTopicFinder(app, "Select follow type topic");
if(t != null) {
followWeightTypesTable.addTopicWeight(t, 1);
}
}
catch(Exception e) {
app.handleError(e);
e.printStackTrace();
}
}//GEN-LAST:event_addFollowWeightTypeButtonMouseReleased
private void addPartialWeightTypeButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_addPartialWeightTypeButtonMouseReleased
try {
Topic t = app.showTopicFinder(app, "Select partial type topic");
if(t != null) {
partialWeightTypesTable.addTopicWeight(t, 1);
}
}
catch(Exception e) {
app.handleError(e);
e.printStackTrace();
}
}//GEN-LAST:event_addPartialWeightTypeButtonMouseReleased
private void closeButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_closeButtonMouseReleased
this.close();
}//GEN-LAST:event_closeButtonMouseReleased
private void calculateButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_calculateButtonMouseReleased
try {
calculateAndUpdate();
this.assetWeightTabbedPane.setSelectedComponent(resultsPanel);
}
catch(Exception e) {
e.printStackTrace();
}
}//GEN-LAST:event_calculateButtonMouseReleased
private void normalizeButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_normalizeButtonMouseReleased
try {
if(normalizeButton.isSelected()) {
resultsTable.refreshModel(normalizedTotalTopicWeights);
updateResultsInfo(averageNormalizedWeight);
}
else {
resultsTable.refreshModel(totalTopicWeights);
updateResultsInfo(averageWeight);
}
}
catch(Exception e) {
e.printStackTrace();
}
}//GEN-LAST:event_normalizeButtonMouseReleased
private void copyResultsButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_copyResultsButtonMouseReleased
String tableContent = resultsTable.copySelectedOrAllRows();
ClipboardBox.setClipboard(tableContent);
/*
HashMap<Topic, Double> hash = null;
if(normalizeButton.isSelected()) {
hash = normalizedTotalTopicWeights;
}
else {
hash = totalTopicWeights;
}
StringBuilder sb = new StringBuilder("");
if(hash != null && !hash.isEmpty()) {
for(Topic t : hash.keySet()) {
try {
String n = t.getBaseName();
if(n == null) n = t.getOneSubjectIdentifier().toExternalForm();
String w = hash.get(t).toString();
sb.append(n);
sb.append("\t");
sb.append(w);
sb.append("\n");
}
catch(Exception e) {
e.printStackTrace();
}
}
}
else {
sb.append("Asset weight result set is empty!");
}
ClipboardBox.setClipboard(sb.toString());
*/
}//GEN-LAST:event_copyResultsButtonMouseReleased
private void removePartialWeightTypeButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_removePartialWeightTypeButtonMouseReleased
partialWeightTypesTable.deleteSelectedRows();
}//GEN-LAST:event_removePartialWeightTypeButtonMouseReleased
private void removeFollowWeightTypeButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_removeFollowWeightTypeButtonMouseReleased
followWeightTypesTable.deleteSelectedRows();
}//GEN-LAST:event_removeFollowWeightTypeButtonMouseReleased
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton addFollowWeightTypeButton;
private javax.swing.JButton addPartialWeightTypeButton;
private javax.swing.JTabbedPane assetWeightTabbedPane;
private javax.swing.JPanel buttonFillerPanel;
private javax.swing.JPanel buttonPanel;
private javax.swing.JButton calculateButton;
private javax.swing.JButton closeButton;
private javax.swing.JLabel coefficientLabel;
private javax.swing.JPanel coefficientPanel;
private javax.swing.JTextField coefficientTextField;
private javax.swing.JButton copyResultsButton;
private javax.swing.JTextField defaultFollowWeightOfAssociationTextField;
private javax.swing.JTextField defaultPartialWeightOfAssociationTextField;
private javax.swing.JTextField defaultPartialWeightOfOccurrenceTextField;
private javax.swing.JCheckBox followAllAssociationsCheckBox;
private javax.swing.JPanel followAssociationsPanel;
private javax.swing.JCheckBox followClassesCheckBox;
private javax.swing.JPanel followClassesPanel;
private javax.swing.JCheckBox followInstancesCheckBox;
private javax.swing.JPanel followInstancesPanel;
private javax.swing.JCheckBox followNaryAssociationsCheckBox;
private javax.swing.JLabel followOptionsLabel;
private javax.swing.JPanel followOptionsPanel;
private javax.swing.JPanel followOptionsPanelPanelInner;
private javax.swing.JTextField followWeightOfClassTextField;
private javax.swing.JTextField followWeightOfInstanceTextField;
private javax.swing.JPanel followWeightTypesTablePanel;
private javax.swing.JScrollPane followWeightTypesTableScrollPane;
private javax.swing.JPanel followWeightsButtonPanel;
private javax.swing.JPanel followWeightsPanel;
private javax.swing.JPanel followWeightsPanelInner;
private javax.swing.JCheckBox includeAssociationsCheckBox;
private javax.swing.JPanel includeAssociationsPanel;
private javax.swing.JCheckBox includeClassesCheckBox;
private javax.swing.JPanel includeClassesPanel;
private javax.swing.JCheckBox includeInstancesCheckBox;
private javax.swing.JPanel includeInstancesPanel;
private javax.swing.JCheckBox includeOccurrencesCheckBox;
private javax.swing.JPanel includeOccurrencesPanel;
private javax.swing.JLabel initialPartialWeightLabel;
private javax.swing.JPanel initialPartialWeightPanel;
private javax.swing.JTextField initialPartialWeightTextField;
private javax.swing.JLabel introductionLabel;
private javax.swing.JPanel introductionPanel;
private javax.swing.JPanel introductionPanelInner;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JToggleButton normalizeButton;
private javax.swing.JTextField partialWeightOfClassTextField;
private javax.swing.JTextField partialWeightOfinstanceTextField;
private javax.swing.JLabel partialWeightOptionsLabel;
private javax.swing.JPanel partialWeightOptionsPanel;
private javax.swing.JPanel partialWeightOptionsPanelInner;
private javax.swing.JPanel partialWeightTypesButtonPanel;
private javax.swing.JPanel partialWeightTypesPanelInner;
private javax.swing.JPanel partialWeightTypesTablePanel;
private javax.swing.JScrollPane partialWeightTypesTableScrollPane;
private javax.swing.JPanel partialWeightsPanel;
private javax.swing.JButton removeFollowWeightTypeButton;
private javax.swing.JButton removePartialWeightTypeButton;
private javax.swing.JPanel resultsButtonPanel;
private javax.swing.JLabel resultsInfoLabel;
private javax.swing.JPanel resultsPanel;
private javax.swing.JPanel resultsPanelInner;
private javax.swing.JPanel resultsTablePanel;
private javax.swing.JScrollPane resultsTableScrollPane;
// End of variables declaration//GEN-END:variables
public void calculateAndUpdate() {
try {
this.calculate();
if(normalizeButton.isSelected()) {
resultsTable.refreshModel(normalizedTotalTopicWeights);
updateResultsInfo(averageNormalizedWeight);
}
else {
resultsTable.refreshModel(totalTopicWeights);
updateResultsInfo(averageWeight);
}
}
catch(Exception e) {
e.printStackTrace();
}
}
// -------------------------------------------------------------------------
private double initialPartialWeightOfATopic = 0;
private double defaultPartialWeightOfAssociation = 1;
private double defaultPartialWeightOfOccurrence = 1;
private double partialWeightOfClass = 1;
private double partialWeightOfInstance = 1;
private boolean includeAllOccurrences = true;
private boolean includeAllAssociations = true;
private boolean includeClasses = true;
private boolean includeInstances = true;
private double defaultFollowWeightOfAssociation = 1;
private double followWeightOfClass = 1;
private double followWeightOfInstance = 1;
private double coefficient = 0.5;
private boolean followAllAssociations = true;
private boolean followClasses = true;
private boolean followInstances = true;
private boolean followNaryAssociations = true;
private double averageWeight = 0;
private double averageNormalizedWeight = 0;
public void calculate() throws TopicMapException {
initialPartialWeightOfATopic = getInitialPartialWeight();
includeAllOccurrences = includeOccurrencesCheckBox.isSelected();
includeAllAssociations = includeAssociationsCheckBox.isSelected();
includeInstances = includeInstancesCheckBox.isSelected();
includeClasses = includeClassesCheckBox.isSelected();
partialWeightOfClass = getPartialWeightOfClass();
partialWeightOfInstance = getPartialWeightOfInstance();
defaultPartialWeightOfOccurrence = getDefaultPartialWeightOfOccurrence();
defaultPartialWeightOfAssociation = getDefaultPartialWeightOfAssociation();
followAllAssociations = followAllAssociationsCheckBox.isSelected();
followInstances = followInstancesCheckBox.isSelected();
followClasses = followClassesCheckBox.isSelected();
followNaryAssociations = followNaryAssociationsCheckBox.isSelected();
defaultFollowWeightOfAssociation = getDefaultFollowWeightOfAssociation();
followWeightOfClass = getFollowWeightOfClass();
followWeightOfInstance = getFollowWeightOfInstance();
coefficient = getCoefficient();
partialWeights = new LinkedHashMap<Topic, Double>();
neighborhoodWeights = new LinkedHashMap<Topic, Double>();
totalTopicWeights = new LinkedHashMap<Topic, Double>();
normalizedTotalTopicWeights = new LinkedHashMap<Topic, Double>();
double biggestWeight = -1;
double weight = 0;
double partialWeight = 0;
double normalizedWeight = 0;
double neighborhoodWeight = 0;
double totalWeight = 0;
double sumWeight = 0;
int numberOfWeights = 0;
// ****** CALCULATE WEIGHTS ******
for( Topic topic : topics ) {
partialWeight = getPartialWeight(topic);
neighborhoodWeight = getNeighborhoodWeight(topic, tm);
totalWeight = partialWeight + coefficient * neighborhoodWeight;
if(biggestWeight < totalWeight) biggestWeight = totalWeight;
totalTopicWeights.put(topic, totalWeight);
sumWeight = sumWeight + totalWeight;
numberOfWeights++;
}
averageWeight = sumWeight / numberOfWeights;
// ****** NORMALIZE ******
weight = 0;
sumWeight = 0;
normalizedWeight = 0;
for(Topic t : totalTopicWeights.keySet()) {
weight = totalTopicWeights.get(t);
normalizedWeight = weight / biggestWeight;
normalizedTotalTopicWeights.put(t, normalizedWeight);
sumWeight = sumWeight + normalizedWeight;
}
averageNormalizedWeight = sumWeight / numberOfWeights;
}
// ------------------------------------------------ NEIGHBORHOOD WEIGHT ----
private double getNeighborhoodWeight(Topic topic, TopicMap tm) throws TopicMapException {
if(neighborhoodWeights.containsKey(topic)) {
return neighborhoodWeights.get(topic);
}
else {
double weight = calculateNeighborhoodWeight(topic, tm);
neighborhoodWeights.put(topic, weight);
return weight;
}
}
private double calculateNeighborhoodWeight(Topic topic, TopicMap tm) throws TopicMapException {
double neighbourhoodWeight = 0;
double weight = 0;
Collection<Association> associations = topic.getAssociations();
for(Association a : associations) {
Topic associationType = a.getType();
Collection<Topic> roles = a.getRoles();
if(followNaryAssociations || roles.size() == 2) {
boolean topicFound = false;
for(Topic role : roles) {
Topic player = a.getPlayer(role);
if(player.mergesWithTopic(topic) && !topicFound) {
topicFound = true;
continue;
}
weight = getFollowWeightForType(associationType) * getPartialWeight(player);
neighbourhoodWeight = neighbourhoodWeight + weight;
}
}
}
if(followClasses) {
for(Topic type : topic.getTypes()) {
weight = followWeightOfClass * getPartialWeight(type);
neighbourhoodWeight = neighbourhoodWeight + weight;
}
}
if(followInstances) {
for(Topic instance : tm.getTopicsOfType(topic)) {
weight = followWeightOfInstance * getPartialWeight(instance);
neighbourhoodWeight = neighbourhoodWeight + weight;
}
}
return neighbourhoodWeight;
}
private double getFollowWeightForType(Topic type) {
if(followWeightTypes != null) {
if(followWeightTypes.containsKey(type)) {
return followWeightTypes.get(type);
}
}
if(followAllAssociations) {
return defaultFollowWeightOfAssociation;
}
else {
return 0;
}
}
// ----------------------------------------------------- PARTIAL WEIGHT ----
private double getPartialWeight(Topic topic) throws TopicMapException {
double partialWeight = 0;
if(partialWeights.containsKey(topic)) {
partialWeight = partialWeights.get(topic);
}
else {
partialWeight = calculatePartialWeight(topic);
partialWeights.put(topic, partialWeight);
}
return partialWeight;
}
private double calculatePartialWeight(Topic topic) throws TopicMapException {
double weight = initialPartialWeightOfATopic;
double associationWeight = 0;
double occurrenceWeight = 0;
Topic associationType;
Collection<Association> associations = topic.getAssociations();
for(Association association : associations) {
associationType = association.getType();
associationWeight = getPartialWeightForAssociationType(associationType);
weight = weight + associationWeight;
}
Collection<Topic> occurrenceTypes = topic.getDataTypes();
for(Topic occurrenceType : occurrenceTypes) {
occurrenceWeight = getPartialWeightForOccurrenceType(occurrenceType);
weight = weight + occurrenceWeight;
}
if(includeClasses) {
Collection<Topic> classes = topic.getTypes();
if(classes != null && !classes.isEmpty()) {
weight = weight + (partialWeightOfClass * classes.size());
}
}
if(includeInstances) {
Collection<Topic> instances = tm.getTopicsOfType(topic);
if(instances != null && !instances.isEmpty()) {
weight = weight + (partialWeightOfInstance * instances.size());
}
}
return weight;
}
private double getPartialWeightForAssociationType(Topic type) {
if(partialWeightTypes != null) {
if(partialWeightTypes.containsKey(type)) {
return partialWeightTypes.get(type);
}
}
if(includeAllAssociations) {
return defaultPartialWeightOfAssociation;
}
else {
return 0;
}
}
private double getPartialWeightForOccurrenceType(Topic type) {
if(partialWeightTypes != null) {
if(partialWeightTypes.containsKey(type)) {
return partialWeightTypes.get(type);
}
}
if(includeAllOccurrences) {
return defaultPartialWeightOfOccurrence;
}
else {
return 0;
}
}
// ---- GET DATA OUT OF TEXT FIELDS ----
public double getInitialPartialWeight() {
try {
return Double.parseDouble(initialPartialWeightTextField.getText());
}
catch(Exception e) {
e.printStackTrace();
}
return initialPartialWeightOfATopic;
}
public double getPartialWeightOfClass() {
try {
return Double.parseDouble(partialWeightOfClassTextField.getText());
}
catch(Exception e) {
e.printStackTrace();
}
return partialWeightOfClass;
}
public double getPartialWeightOfInstance() {
try {
return Double.parseDouble(partialWeightOfinstanceTextField.getText());
}
catch(Exception e) {
e.printStackTrace();
}
return partialWeightOfInstance;
}
public double getDefaultPartialWeightOfAssociation() {
try {
return Double.parseDouble(defaultPartialWeightOfAssociationTextField.getText());
}
catch(Exception e) {
e.printStackTrace();
}
return defaultPartialWeightOfAssociation;
}
public double getDefaultPartialWeightOfOccurrence() {
try {
return Double.parseDouble(defaultPartialWeightOfOccurrenceTextField.getText());
}
catch(Exception e) {
e.printStackTrace();
}
return defaultPartialWeightOfOccurrence;
}
// ----
public double getDefaultFollowWeightOfAssociation() {
try {
return Double.parseDouble(defaultFollowWeightOfAssociationTextField.getText());
}
catch(Exception e) {
e.printStackTrace();
}
return defaultFollowWeightOfAssociation;
}
public double getFollowWeightOfClass() {
try {
return Double.parseDouble(followWeightOfClassTextField.getText());
}
catch(Exception e) {
e.printStackTrace();
}
return followWeightOfClass;
}
public double getFollowWeightOfInstance() {
try {
return Double.parseDouble(followWeightOfInstanceTextField.getText());
}
catch(Exception e) {
e.printStackTrace();
}
return followWeightOfInstance;
}
public double getCoefficient() {
try {
return Double.parseDouble(coefficientTextField.getText());
}
catch(Exception e) {
e.printStackTrace();
}
return coefficient;
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
class TopicWeightTable extends JTable {
private static final long serialVersionUID = 1L;
private HashMap<Topic,Double> modelData = null;
private TopicWeightTableModel dm = null;
private String name1 = "Type";
private String name2 = "Weight";
public TopicWeightTable(HashMap<Topic,Double> typeWeights) {
modelData = typeWeights;
dm = new TopicWeightTableModel(modelData);
this.setModel(dm);
this.setRowSorter(new TopicWeightTableRowSorter(dm));
}
public void addTopicWeight(Topic t, double weight) {
modelData.put(t, weight);
refreshModel();
}
public void removeTopicWeight(Topic t) {
modelData.remove(t);
refreshModel();
}
public void refreshModel(HashMap<Topic,Double> weights) {
modelData = weights;
dm = new TopicWeightTableModel(modelData);
dm.setColumnNames(name1, name2);
this.setModel(dm);
this.setRowSorter(new TopicWeightTableRowSorter(dm));
}
public void refreshModel() {
dm = new TopicWeightTableModel(modelData);
dm.setColumnNames(name1, name2);
this.setModel(dm);
this.setRowSorter(new TopicWeightTableRowSorter(dm));
}
public void setColumnNames(String n1, String n2) {
name1 = n1;
name2 = n2;
dm.setColumnNames(n1, n2);
}
public void deleteSelectedRows() {
int[] selectedRows = getSelectedRows();
Topic t = null;
for(int i=0; i<selectedRows.length; i++) {
int row = convertRowIndexToModel(selectedRows[i]);
t = dm.getTopicAt(row);
if(t != null) {
modelData.remove(t);
}
}
refreshModel();
}
public String copySelectedOrAllRows() {
StringBuilder sb = new StringBuilder("");
int[] selectedRows = getSelectedRows();
if(selectedRows == null || selectedRows.length == 0) {
selectedRows = new int[this.getRowCount()];
for(int i=0; i<this.getRowCount(); i++)
selectedRows[i] = i;
}
Topic t = null;
for(int i=0; i<selectedRows.length; i++) {
int row = convertRowIndexToModel(selectedRows[i]);
t = dm.getTopicAt(row);
if(t != null) {
try {
String n = t.getBaseName();
if(n == null) n = t.getOneSubjectIdentifier().toExternalForm();
sb.append(n);
sb.append("\t");
sb.append(dm.getWeightAt(row));
sb.append("\n");
}
catch(Exception e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
}
class TopicWeightTableModel extends DefaultTableModel {
private ArrayList<Topic> topics = null;
private ArrayList<Double> weights = null;
private HashMap<Topic,Double> topicWeights = null;
private String columnName0 = "Type";
private String columnName1 = "Weight";
public TopicWeightTableModel(HashMap<Topic,Double> typeWeights) {
topics = new ArrayList<Topic>();
weights = new ArrayList<Double>();
topicWeights = typeWeights;
for(Topic topic : typeWeights.keySet()) {
topics.add(topic);
weights.add(typeWeights.get(topic));
}
}
public Topic getTopicAt(int row) {
if(row >= 0 && row < topics.size())
return topics.get(row);
else
return null;
}
public double getWeightAt(int row) {
if(row >= 0 && row < weights.size())
return weights.get(row);
else
return -1;
}
@Override
public void setValueAt(Object obj, int rowIndex, int columnIndex) {
try {
if(obj == null) return;
String data = obj.toString();
data = data.trim();
if(rowIndex >= 0 && rowIndex < topics.size()) {
switch(columnIndex) {
case 0: {
// CANT EDIT
break;
}
case 1: {
double weight = Double.parseDouble(data);
weights.set(rowIndex, weight);
topicWeights.put(topics.get(rowIndex), weight);
break;
}
}
}
}
catch (Exception ex) {
ex.printStackTrace();
}
}
@Override
public int getColumnCount() {
return 2;
}
@Override
public int getRowCount() {
if(topics == null) return 0;
return topics.size();
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
try {
if(rowIndex >= 0 && rowIndex < topics.size()) {
switch(columnIndex) {
case 0: {
Topic t = topics.get(rowIndex);
String n = t.getBaseName();
if(n == null) n = t.getOneSubjectIdentifier().toExternalForm();
return n;
}
case 1: {
Double weight = weights.get(rowIndex);
return (weight == null ? "[not a number]" : weight);
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void setColumnNames(String n1, String n2) {
columnName0 = n1;
columnName1 = n2;
}
@Override
public String getColumnName(int columnIndex){
try {
switch(columnIndex) {
case 0: {
return columnName0;
}
case 1: {
return columnName1;
}
}
return "";
}
catch (Exception e) {
e.printStackTrace();
}
return "ERROR";
}
@Override
public boolean isCellEditable(int row, int col) {
if(col == 0) return false;
return true;
}
}
class TopicWeightTableRowSorter extends TableRowSorter {
public TopicWeightTableRowSorter(TopicWeightTableModel dm) {
super(dm);
}
@Override
public Comparator<?> getComparator(int column) {
if(column == 1) {
return new Comparator() {
public int compare(Object o1, Object o2) {
if(o1 == null || o2 == null) return 0;
if(o1 instanceof Double && o2 instanceof Double) {
return ((Double) o1).compareTo(((Double) o2));
}
else if(o1 instanceof String && o2 instanceof String) {
try {
double d1 = Double.parseDouble((String)o1);
double d2 = Double.parseDouble((String)o2);
if(d1 > d2) return 1;
if(d1 < d2) return -1;
}
catch(Exception e) {}
return 0;
}
else {
return 0;
}
}
};
}
else {
return super.getComparator(column);
}
}
}
}
| 64,492 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TopicMapDiameterAlternative.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/statistics/TopicMapDiameterAlternative.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* TopicMapDiameter.java
*
* Created on 1.6.2007, 12:41
*
*/
package org.wandora.application.tools.statistics;
import java.util.Iterator;
import javax.swing.Icon;
import org.wandora.application.Wandora;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.UIBox;
import org.wandora.application.gui.WandoraOptionPane;
import org.wandora.application.tools.AbstractWandoraTool;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicHashMap;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.topicmap.layered.LayerStack;
/**
*
* @author olli
*/
// Apparently uses Floyd-Warshall algorithm
public class TopicMapDiameterAlternative extends AbstractWandoraTool {
private static final long serialVersionUID = 1L;
/** Creates a new instance of TopicMapDiameter */
public TopicMapDiameterAlternative() {
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/topicmap_diameter.png");
}
@Override
public String getName() {
return "Topic map diameter (using a hash structure)";
}
@Override
public String getDescription() {
return "Calculates diameter of a topic map, that is maximum shortest path between two topics. Also calculates average shortest path between all topic pairs. Not usable for topic maps of approximately more than 10000 topics.";
}
public void execute(Wandora admin, Context context) throws TopicMapException {
TopicMap tm = solveContextTopicMap(admin, context);
String tmTitle = solveNameForTopicMap(admin, tm);
int numTopics=-1;
if(!(tm instanceof LayerStack)) numTopics=tm.getNumTopics();
setDefaultLogger();
if(numTopics!=-1) setProgressMax(numTopics);
TopicClusteringCoefficient.TopicNeighborhood n = new TopicClusteringCoefficient.DefaultNeighborhood();
log("Calculating diameter of '"+tmTitle+"'");
log("Preparing topics 1/3");
Iterator<Topic> iter=tm.getTopics();
TopicHashMap<Integer> ids=new TopicHashMap<Integer>();
int counter=0;
while(iter.hasNext() && !forceStop()){
if((counter%100)==0) setProgress(counter);
Topic t = iter.next();
ids.put(t,counter);
counter++;
}
log("Preparing distance matrix 2/3");
if(ids.size() > 2000) {
setState(INVISIBLE);
int a = WandoraOptionPane.showConfirmDialog(admin, "The topic map has more than 2 000 topics. "+
"It is very likely that diameter calculation takes a while."+
"Are you sure you want to continue?", "Topic map size warning", WandoraOptionPane.YES_NO_OPTION);
if(a == WandoraOptionPane.NO_OPTION) {
return;
}
else {
setState(VISIBLE);
}
}
TopicMapDiamaterArray path = new TopicMapDiamaterArray(ids.size());
iter=tm.getTopics();
counter=0;
while(iter.hasNext() && !forceStop()){
if((counter%100)==0) setProgress(counter);
Topic topic = iter.next();
Integer tint=ids.get(topic);
counter++;
if(tint==null) continue; // happens if topic has no basename, subject identifiers or subject locator
int ti=tint.intValue();
for(Topic p : n.getNeighborhood(topic)){
Integer pint=ids.get(p);
if(pint==null) continue;
path.put(ti, pint.intValue(), 1);
}
}
log("Calculating diameter 3/3");
int size = ids.size();
counter=0;
setProgress(0);
setProgressMax(size);
for(int k=0;k<size && !forceStop();k++){
setProgress(k);
for(int i=0;i<size;i++){
int ik = path.get(i,k);
if(ik==-1) continue;
for(int j=0;j<size;j++){
int kj = path.get(k,j);
if(kj==-1) continue;
int ij = path.get(i,j);
if(ij > ik+kj || ij == -1) path.put(i,j,ik+kj);
}
}
}
int max=1;
double average=0;
boolean connected=true;
counter=0;
for(int i=0;i<ids.size() && !forceStop();i++){
for(int j=0;j<ids.size() && !forceStop();j++){
if(i==j) continue;
if(path.get(i,j)!=-1){
if(path.get(i,j)>max) max=path.get(i,j);
average+=path.get(i,j);
counter++;
}
else connected=false;
}
}
average/=(double)counter;
if(forceStop()) {
log("Operation cancelled!");
log("Unfinished topic map diameter is "+max);
log("Unfinished average shortest path is "+average);
}
else {
if(connected){
log("Topic map is connected!");
log("Topic map diameter is "+max);
log("Average shortest path is "+average);
}
else{
log("Topic map is not connected!");
log("Diameter of largest connected component in topic map is "+max);
log("Average shortest path in connected components is "+average);
}
}
setState(WAIT);
}
}
| 6,442 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AverageClusteringCoefficient.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/statistics/AverageClusteringCoefficient.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* AverageClusteringCoefficient.java
*
* Created on 30. toukokuuta 2007, 14:43
*
*/
package org.wandora.application.tools.statistics;
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.contexts.Context;
import org.wandora.application.gui.UIBox;
import org.wandora.application.tools.AbstractWandoraTool;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicHashMap;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.topicmap.layered.LayerStack;
/**
*
* @author olli
*/
public class AverageClusteringCoefficient extends AbstractWandoraTool {
private static final long serialVersionUID = 1L;
public AverageClusteringCoefficient() {
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/clustering_coefficient.png");
}
@Override
public String getName() {
return "Topic map clustering coefficient";
}
@Override
public String getDescription() {
return "Tool is used calculate average clustering coefficient in layer.";
}
@Override
public boolean requiresRefresh() {
return false;
}
@Override
public void execute(Wandora admin, Context context) throws TopicMapException {
TopicMap tm = solveContextTopicMap(admin, context);
String tmTitle = solveNameForTopicMap(admin, tm);
if(tm==null) return;
int numTopics=-1;
if(!(tm instanceof LayerStack)) numTopics=tm.getNumTopics();
setDefaultLogger();
if(numTopics!=-1) setProgressMax(numTopics);
TopicClusteringCoefficient.TopicNeighborhood n = new TopicClusteringCoefficient.DefaultNeighborhood();
log("Calculating clustering coefficient of '"+tmTitle+"'");
log("Preparing topics 1/3");
Iterator<Topic> iter=tm.getTopics();
TopicHashMap<Integer> ids=new TopicHashMap<Integer>();
int counter=0;
while(iter.hasNext() && !forceStop()){
if((counter%100)==0) setProgress(counter);
Topic t = iter.next();
ids.put(t,counter);
counter++;
}
log("Preparing connections 2/3");
HashMap<Integer,HashSet<Integer>> connections=new HashMap<Integer,HashSet<Integer>>();
iter=tm.getTopics();
counter=0;
while(iter.hasNext() && !forceStop()){
if((counter%100)==0) setProgress(counter);
Topic topic = iter.next();
Integer t=ids.get(topic);
counter++;
if(t==null) continue; // happens if topic has no basename, subject identifiers or subject locator
HashSet<Integer> cs=new HashSet<Integer>();
connections.put(t,cs);
for(Topic p : n.getNeighborhood(topic)){
Integer pint=ids.get(p);
if(pint==null) continue;
cs.add(pint);
}
}
log("Calculating clustering coefficient 3/3");
double sum=0.0;
counter=0;
iter=tm.getTopics();
while(iter.hasNext() && !forceStop()){
if((counter%100)==0) setProgress(counter);
Topic topic = iter.next();
int associationCounter=0;
Integer t=ids.get(topic);
counter++;
if(t==null) continue; // happens if topic has no basename, subject identifiers or subject locator
HashSet<Integer> tn=connections.get(t);
if(tn.size()<=1) continue;
for(Integer p : tn){
HashSet<Integer> pn=connections.get(p);
for(Integer r : pn){
if(p.equals(r)) continue;
if(tn.contains(r)) associationCounter++;
}
}
sum+=(double)associationCounter/(double)(tn.size()*(tn.size()-1));
}
/*
double sum=0.0;
int counter=0;
Iterator<Topic> iter=tm.getTopics();
while(iter.hasNext()){
if((counter%100)==0) setProgress(counter);
Topic t = iter.next();
sum+=TopicClusteringCoefficient.getClusteringCoefficientFor(t,n);
counter++;
} */
double c=sum/(double)counter;
if(forceStop()) {
log("Operation cancelled!");
}
else {
log("Average coefficient for layer "+(tmTitle==null?"":(tmTitle+" "))+"is "+c);
}
setState(WAIT);
}
}
| 5,494 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TopicClusteringCoefficient.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/statistics/TopicClusteringCoefficient.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* TopicClusteringCoefficient.java
*
* Created on 30. toukokuuta 2007, 13:34
*
*/
package org.wandora.application.tools.statistics;
import java.util.Collection;
import java.util.Iterator;
import javax.swing.Icon;
import org.wandora.application.Wandora;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.UIBox;
import org.wandora.application.tools.AbstractWandoraTool;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicHashSet;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author olli
*/
public class TopicClusteringCoefficient extends AbstractWandoraTool {
private static final long serialVersionUID = 1L;
/** Creates a new instance of TopicClusteringCoefficient */
public TopicClusteringCoefficient() {
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/clustering_coefficient.png");
}
@Override
public String getName() {
return "Topic clustering coefficient";
}
@Override
public String getDescription() {
return "Calculates clustering coefficient for a single topic.";
}
@Override
public boolean requiresRefresh() {
return false;
}
public static double getClusteringCoefficientFor(Topic t,TopicNeighborhood n) throws TopicMapException {
Collection<Topic> nc=n.getNeighborhood(t);
if(nc.size()<=1) return 0.0;
int associationCounter=0;
TopicHashSet l;
if(nc instanceof TopicHashSet) l=(TopicHashSet)nc;
else l=new TopicHashSet(nc);
for(Topic it : l){
for(Topic jt : n.getNeighborhood(it)){
if(l.contains(jt)) associationCounter++;
}
}
return (double)associationCounter/(double)(l.size()*(l.size()-1));
/*
ArrayList<Topic> l=new ArrayList<Topic>(nc);
l.add(t);
for(int i=0;i<l.size();i++){
Topic it=l.get(i);
for(int j=i+1;j<l.size();j++){
Topic jt=l.get(j);
if(n.areLinked(it,jt)) associationCounter++;
}
}
return 2.0*(double)associationCounter/(double)(l.size()*(l.size()-1));
*/
}
public static double getAverageClusteringCoefficient(TopicMap tm, TopicNeighborhood n) throws TopicMapException {
double sum=0.0;
int counter=0;
Iterator<Topic> iter=tm.getTopics();
while(iter.hasNext()){
sum+=getClusteringCoefficientFor(iter.next(),n);
counter++;
}
return sum/(double)counter;
}
@Override
public void execute(Wandora admin, Context context) throws TopicMapException {
Iterator iter=context.getContextObjects();
TopicNeighborhood n=new DefaultNeighborhood();
double average=0.0;
int counter=0;
setDefaultLogger();
while(iter.hasNext() && !forceStop()){
Object co=iter.next();
Topic t;
if(co instanceof Topic){
t=(Topic)co;
}
else{
log("Context object is not a Topic");
continue;
}
double c=getClusteringCoefficientFor(t,n);
log("Clustering coefficient for topic "+getTopicName(t)+" is "+c);
average+=c;
counter++;
}
if(forceStop()) {
log("Operation cancelled!");
log("Unfinished average clustering coefficient is "+(average/(double)counter));
}
else {
log("Average clustering coefficient is "+(average/(double)counter));
}
setState(WAIT);
}
public static interface TopicNeighborhood {
public Collection<Topic> getNeighborhood(Topic t) throws TopicMapException ;
public boolean areLinked(Topic t1,Topic t2) throws TopicMapException ;
}
public static class DefaultNeighborhood implements TopicNeighborhood {
public Collection<Topic> getNeighborhood(Topic t) throws TopicMapException {
TopicHashSet ret=new TopicHashSet();
for(Association a : t.getAssociations()){
for(Topic role : a.getRoles()){
Topic u=a.getPlayer(role);
if(!u.mergesWithTopic(t)) ret.add(u);
}
}
return ret;
}
public boolean areLinked(Topic t1,Topic t2) throws TopicMapException {
for(Association a : t1.getAssociations()){
for(Topic role : a.getRoles()){
Topic u=a.getPlayer(role);
if(u.mergesWithTopic(t2)) return true;
}
}
return false;
}
}
}
| 5,697 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
MergeMatrixTool.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/statistics/MergeMatrixTool.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* MergeMatrixTool.java
*
* Created on 29. toukokuuta 2007, 10:13
*
*/
package org.wandora.application.tools.statistics;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.ArrayList;
import java.util.HashMap;
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.contexts.Context;
import org.wandora.application.gui.UIBox;
import org.wandora.application.tools.AbstractWandoraTool;
import org.wandora.application.tools.GenericOptionsDialog;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.topicmap.layered.ContainerTopicMap;
import org.wandora.topicmap.layered.Layer;
/**
*
* @author
* Eero
*/
public class MergeMatrixTool extends AbstractWandoraTool{
private static final long serialVersionUID = 1L;
protected HashMap<String, Integer> processedPairs;
public MergeMatrixTool() {
processedPairs = new HashMap<String, Integer>();
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/layer_acount.png");
}
@Override
public String getName() {
return "Layer merge statistics";
}
@Override
public String getDescription() {
return "Gather and show statistics about topic merges between topic map layers.";
}
@Override
public boolean requiresRefresh() {
return false;
}
@Override
public void execute(Wandora admin, Context context) throws TopicMapException {
TopicMap tm = solveContextTopicMap(admin, context);
String tmTitle = solveNameForTopicMap(admin,tm);
GenericOptionsDialog god = new GenericOptionsDialog(
admin,
"Topic merge options",
"Connection statistics options",
true,
new String[][]{
new String[]{"Count percentage","boolean","true"},
},admin
);
god.setVisible(true);
if(god.wasCancelled()) return;
setDefaultLogger();
Map<String, String> values = god.getValues();
boolean countPer = Boolean.parseBoolean(values.get("Count percentage"));
List<Layer> rootLayers = admin.getTopicMap().getLayers();
List<Layer> allLayers = getChildLayers(rootLayers);
List<List<String>> sl = new ArrayList<>();
List<String> currentRow;
setProgressMax(allLayers.size()*allLayers.size());
int prog = 0;
for(Layer l : allLayers){
if (forceStop()) break;
currentRow = new ArrayList<String>();
currentRow.add(l.getName());
for (Layer ll : allLayers) {
log("now processing " + l.getName() + " - " + ll.getName());
prog++;
setProgress(prog);
if (forceStop()) break;
try{
int merges;
int total;
String possiblyProcessed = ll.getName() + "-" + l.getName();
if(l.equals(ll)){
merges = 1;
total = 1;
} else if(processedPairs.containsKey(possiblyProcessed)){
merges = processedPairs.get(possiblyProcessed);
total = l.getTopicMap().getNumTopics();
} else {
merges = getMatrixMerges(l,ll);
processedPairs.put(l.getName() + "-" + ll.getName(), merges);
total = l.getTopicMap().getNumTopics();
}
if(countPer){
float per = 100 * (float)merges / (float)total;
DecimalFormat df = new DecimalFormat("0.0");
DecimalFormatSymbols dfs = df.getDecimalFormatSymbols();
dfs.setDecimalSeparator('.');
df.setDecimalFormatSymbols(dfs);
String perf = df.format(per);
currentRow.add(perf);
} else {
String ms = Integer.toString(merges);
String ts = Integer.toString(total);
String r = ms + "/" + ts;
currentRow.add(r);
}
} catch(TopicMapException e){
currentRow.add("error");
}
}
sl.add(currentRow);
}
if (!forceStop()) new MergeMatrixToolPanel(admin,sl);
setState(CLOSE);
}
private List<Layer> getChildLayers(List<Layer> ll){
List<Layer> returnedLayers = new ArrayList<Layer>();
returnedLayers.addAll(ll);
for (Layer layer : ll) {
TopicMap ltm = layer.getTopicMap();
if(ltm instanceof ContainerTopicMap) {
ContainerTopicMap ctm = (ContainerTopicMap)ltm;
returnedLayers.addAll(getChildLayers(ctm.getLayers()));
}
}
return returnedLayers;
}
private int getMatrixMerges(Layer l, Layer ll) throws TopicMapException{
int n = 0;
Iterator<Topic> ti = l.getTopicMap().getTopics();
while(ti.hasNext()){
Topic t = (Topic)ti.next();
Iterator<Topic> tti = ll.getTopicMap().getTopics();
while(tti.hasNext()){
Topic tt = (Topic)tti.next();
if(t.mergesWithTopic(tt)){
n++;
}
}
}
return n;
}
}
| 6,561 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
RHelper.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/r/RHelper.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.r;
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.contexts.AssociationContext;
import org.wandora.application.contexts.LayeredTopicContext;
import org.wandora.application.tools.extractors.ExtractHelper;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author akivela
*/
public class RHelper {
private static final String IGRAPH_SI = "http://wandora.org/si/R/igraph";
private static final String LANG_SI = "http://www.topicmaps.org/xtm/1.0/language.xtm#en";
public static class Graph {
public int numNodes;
public String labels[];
public String colors[];
public int[] edges;
public Graph(int numNodes, String[] labels, String[] colors, int[] edges) {
this.numNodes = numNodes;
this.labels = labels;
this.colors = colors;
this.edges = edges;
}
}
public static Graph makeGraph(Topic[] topics){
try{
HashMap<String,Integer> indices=new HashMap<String,Integer>();
ArrayList<String> labels=new ArrayList<String>();
ArrayList<String> colors=new ArrayList<String>();
ArrayList<Integer> edges=new ArrayList<Integer>();
for(Topic t : topics){
indices.put(t.getOneSubjectIdentifier().toString(),labels.size()+1);
labels.add(t.getBaseName());
colors.add("lightblue");
}
for(Topic t : topics){
for(Association a : t.getAssociations()) {
Collection<Topic> rs=a.getRoles();
Topic player1=a.getPlayer(rs.iterator().next());
if(t.mergesWithTopic(player1)){
ArrayList<Topic> ps=new ArrayList<Topic>();
for(Topic r : rs){
Topic p=a.getPlayer(r);
if(indices.containsKey(p.getOneSubjectIdentifier().toString()))
ps.add(p);
}
if(ps.size()<=1) continue;
else if(ps.size()==2){
Iterator<Topic> iter=ps.iterator();
edges.add(indices.get(iter.next().getOneSubjectIdentifier().toString()));
edges.add(indices.get(iter.next().getOneSubjectIdentifier().toString()));
}
else {
int aind=labels.size();
labels.add("");
colors.add("gray");
Iterator<Topic> iter=ps.iterator();
while(iter.hasNext()) {
edges.add(indices.get(iter.next().getOneSubjectIdentifier().toString()));
edges.add(aind);
}
}
}
}
}
int[] iedges=new int[edges.size()];
for(int i=0;i<edges.size();i++){ iedges[i]=edges.get(i); }
return new Graph(labels.size(),labels.toArray(new String[labels.size()]),colors.toArray(new String[colors.size()]),iedges);
}
catch(TopicMapException tme){
tme.printStackTrace();
return null;
}
}
public static Association[] getContextAssociations(){
AssociationContext context=new AssociationContext();
context.initialize(Wandora.getWandora(), null, null);
ArrayList<Association> ret=new ArrayList<Association>();
Iterator iter=context.getContextObjects();
if(iter!=null){
while(iter.hasNext()){
Object o=iter.next();
if(o instanceof Association) ret.add((Association)o);
}
}
return ret.toArray(new Association[ret.size()]);
}
public static Topic[] getContextTopics(){
LayeredTopicContext context=new LayeredTopicContext(Wandora.getWandora(),null,null);
ArrayList<Topic> ret=new ArrayList<Topic>();
Iterator iter=context.getContextObjects();
if(iter!=null){
while(iter.hasNext()){
Object o=iter.next();
if(o instanceof Topic) ret.add((Topic)o);
}
}
return ret.toArray(new Topic[ret.size()]);
}
// "next" is a reserved word in R which makes this tricky
public static Object[] unwrapIterator(Iterator iter){
ArrayList<Object> ret=new ArrayList<Object>();
while(iter.hasNext()){
ret.add(iter.next());
}
return ret.toArray();
}
/*
* Create a set of topics from vertices connected by associations derived
* from edges. 'edges' should be a list of tuples.
*/
public static void createTopics(double[][] edges, int[] vertices, String[] bns, HashMap<String,String[]> occ ) throws TopicMapException{
/*
* Initialization: create type topics for the graph vertices and edges.
* Also make the type topics subclasses of the Wandora class.
*/
TopicMap tm = Wandora.getWandora().getTopicMap();
Topic iGraphTypeTopic = getiGraphTypeTopic(tm);
Topic vertexTypeTopic = getVertexTypeTopic(tm, iGraphTypeTopic);
Topic edgeTypeTopic = getEdgeTypeTopic(tm, iGraphTypeTopic);
Topic role1 = getRole1Topic(tm);
Topic role2 = getRole2Topic(tm);
HashMap<Integer,Topic> edgeMap = new HashMap<Integer, Topic>();
HashMap<String,Topic> occTypeMap = new HashMap<String,Topic>();
Topic[][] toAssoc = new Topic[edges.length][edges[0].length];
/*
* - Create a topic for each vertex.
*
* - Map the ids to topics so we can easily associate the topics after they've
* been created.
*/
if(occ != null){
for(String key : occ.keySet()){
System.out.println("adding occurrence type " + key);
occTypeMap.put(key, getOccTypeTopic(tm,key));
}
}
for (int i = 0; i <vertices.length; i++) {
Topic t = getVertexTopic(Integer.toString(vertices[i]), tm, vertexTypeTopic);
if(bns != null){
t.setBaseName(bns[i]);
}
if(occ != null){
for(String key : occ.keySet()){
addOccurrence(t,occTypeMap.get(key),occ.get(key)[i],tm);
}
}
edgeMap.put(vertices[i], t);
}
for (int j = 0; j < edges.length; j++) {
for (int k = 0; k < edges[0].length; k++) {
toAssoc[j][k] = edgeMap.get((int)edges[j][k]);
}
}
/*
* Finally associate the vertex topics by their edges.
*/
for (int p = 0; p < toAssoc.length; p++) {
addAssoc(tm, toAssoc[p], edgeTypeTopic, role1, role2);
}
}
private static Topic getLangTopic(TopicMap tm) throws TopicMapException {
Topic lang = ExtractHelper.getOrCreateTopic(LANG_SI,tm);
return lang;
}
private static void addOccurrence(Topic t, Topic type, String value, TopicMap tm) throws TopicMapException{
t.setData(type, getLangTopic(tm), value);
}
private static Topic getOccTypeTopic(TopicMap tm, String key) throws TopicMapException{
Topic type=ExtractHelper.getOrCreateTopic( IGRAPH_SI + "/occurrence/" + key, key,tm);
return type;
}
private static void addAssoc(TopicMap tm, Topic[] ts, Topic type, Topic role1, Topic role2) throws TopicMapException{
Association a = tm.createAssociation(type);
a.addPlayer(ts[0], role1);
a.addPlayer(ts[1], role2);
}
private static Topic getVertexTopic(String id, TopicMap tm, Topic typeTopic) throws TopicMapException {
Topic vertexTopic=ExtractHelper.getOrCreateTopic(IGRAPH_SI+"/vertex/"+id, tm);
vertexTopic.addType(typeTopic);
return vertexTopic;
}
private static Topic getiGraphTypeTopic(TopicMap tm) throws TopicMapException {
Topic type=ExtractHelper.getOrCreateTopic( IGRAPH_SI, "iGraph",tm);
Topic wandoraClass = ExtractHelper.getWandoraClass(tm);
ExtractHelper.makeSubclassOf(type, wandoraClass,tm);
return type;
}
private static Topic getVertexTypeTopic(TopicMap tm, Topic iGraphTypeTopic) throws TopicMapException {
Topic type=ExtractHelper.getOrCreateTopic( IGRAPH_SI + "/vertex", "Vertex",tm);
ExtractHelper.makeSubclassOf(type, iGraphTypeTopic,tm);
return type;
}
private static Topic getEdgeTypeTopic(TopicMap tm, Topic iGraphTypeTopic) throws TopicMapException {
Topic type=ExtractHelper.getOrCreateTopic( IGRAPH_SI + "/edge", "Edge",tm);
ExtractHelper.makeSubclassOf(type, iGraphTypeTopic,tm);
return type;
}
private static Topic getRole1Topic(TopicMap tm) throws TopicMapException{
Topic role=ExtractHelper.getOrCreateTopic( IGRAPH_SI + "/edgeEnd1", "Edge end 1",tm);
return role;
}
private static Topic getRole2Topic(TopicMap tm) throws TopicMapException{
Topic role=ExtractHelper.getOrCreateTopic( IGRAPH_SI + "/edgeEnd2", "Edge end 2",tm);
return role;
}
}
| 10,658 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
.#RConsole.java.1.6 | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/r/.#RConsole.java.1.6 | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://www.wandora.org/
*
* Copyright (C) 2004-2011 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.r;
import java.awt.FileDialog;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.security.Permission;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import javax.swing.JDialog;
import javax.swing.WindowConstants;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import org.rosuda.JRI.RMainLoopCallbacks;
import org.rosuda.JRI.Rengine;
import org.wandora.application.Wandora;
import org.wandora.application.contexts.AssociationContext;
import org.wandora.application.contexts.LayeredTopicContext;
import org.wandora.application.gui.GUIConstants;
import org.wandora.application.gui.GuiBox;
import org.wandora.application.gui.simple.SimpleButton;
import org.wandora.application.gui.simple.SimpleMenu;
import org.wandora.application.gui.simple.SimpleMenuItem;
import org.wandora.application.gui.simple.SimpleScrollPane;
import org.wandora.application.gui.simple.SimpleTextPane;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
import org.wandora.topicmap.layered.LayeredAssociation;
import org.wandora.utils.swing.GuiTools;
/**
*
* @author olli
*/
public class RConsole extends javax.swing.JPanel implements ActionListener {
private ArrayList<String> history=new ArrayList<String>(); { history.add(""); }
private int historyPtr=0;
private boolean prompt=false;
private Rengine engine;
private LoopCallbacks callbacks;
private static final String rErrorMessage=
"Unable to initialize R.\n"+
"\n"+
"This is likely because R has not been installer or the environment\n"+
"variables aren't setup correctly,or the rJava library has not been\n"+
"installed.\n"+
"\n"+
"To setup R do the following steps. These instructions are also\n"+
"explained in more detail in the Wandona wiki at\n"+
"http://www.wandora.org/wandora/wiki/index.php?title=R_in_Wandora\n"+
"\n"+
"1. Download R from http://www.r-project.org and install it.\n"+
"\n"+
"2. Install the required libraries in R. You need to run R as an\n"+
" administrator to do this. In Windows right click the R icon\n"+
" select Run as Adminsitrator. In Linux run R on console using\n"+
" \"sudo R\".\n"+
"\n"+
" Then in the R console install the rJava package with\n"+
" install.packages(\"rJava\")\n"+
" You will likely also want to install the igraph package with\n"+
" install.packages(\"igraph\")\n"+
" and in Windows also the JavaGD packages\n"+
" install.packages(\"JavaGD\")\n"+
" You will be asked to select a mirror to download the packages\n"+
" from, just select the country you're in or one close to it.\n"+
"\n"+
"3. Next make sure that the environment variables are setup correctly.\n"+
" Open the SetR.bat (on Windows) or SetR.sh (on Linux) in the bin\n"+
" directory. Make sure the R_HOME directory is right. If you are\n"+
" using Windows also make sure that the version number matches your\n"+
" installation and that the R_ARCH matches your Java installation.\n"+
" Use i386 for 32-bit Java and x64 for 64-bit Java. If you did a\n"+
" standard installation of R then the other variables should be\n"+
" correct, otherwise adjust them as needed.\n"+
"\n"+
"You should now be able to use R in Wandora.\n"+
"\n"+
"The error encountered while trying to initiale R is shown below:\n\n"
;
/** Creates new form RConsole */
public RConsole() {
initComponents();
callbacks=new LoopCallbacks();
try{
// this makes JRI behave gracefully when the native library isn't found
System.setProperty("jri.ignore.ule", "yes");
if(!Rengine.versionCheck()){
throw new Exception("R version mismatch, Java files don't match library version.");
}
engine=new Rengine(new String[]{},false,callbacks);
if(engine.waitForR()){
initEngine();
}
else {
throw new Exception("Couldn't load R");
}
}catch(UnsatisfiedLinkError e){
engine=null;
// Wandora.getWandora().handleError(new Exception(e));
// output.append("Unable to initialize R");
appendOutput(rErrorMessage);
StringWriter sw=new StringWriter();
PrintWriter pw=new PrintWriter(sw);
e.printStackTrace(pw);
pw.flush();
appendOutput("\n\n"+sw.toString());
}
catch(Exception e){
engine=null;
//Wandora.getWandora().handleError(e);
//output.append("Unable to initialize R");
appendOutput(rErrorMessage);
StringWriter sw=new StringWriter();
PrintWriter pw=new PrintWriter(sw);
e.printStackTrace(pw);
pw.flush();
appendOutput("\n\n"+sw.toString());
}
}
private void appendOutput(String text){
Document d=output.getDocument();
try{
d.insertString(d.getLength(), text, null);
}catch(BadLocationException ble){}
}
private final Object promptLock=new Object();
private String promptIn=null;
private String promptInput(String promptText){
synchronized(promptLock){
//output.append(promptText);
appendOutput(promptText);
prompt=true;
promptIn=null;
while(promptIn==null){
try{
promptLock.wait(100);
}catch(InterruptedException ie){return null;}
engine.rniIdle();
}
prompt=false;
return promptIn;
}
}
public void actionPerformed(ActionEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}
public static class Graph {
public int numNodes;
public String labels[];
public String colors[];
public int[] edges;
public Graph(int numNodes, String[] labels, String[] colors, int[] edges) {
this.numNodes = numNodes;
this.labels = labels;
this.colors = colors;
this.edges = edges;
}
}
public Graph makeGraph(Topic[] topics){
try{
HashMap<String,Integer> indices=new HashMap<String,Integer>();
ArrayList<String> labels=new ArrayList<String>();
ArrayList<String> colors=new ArrayList<String>();
ArrayList<Integer> edges=new ArrayList<Integer>();
for(Topic t : topics){
indices.put(t.getOneSubjectIdentifier().toString(),labels.size());
labels.add(t.getBaseName());
colors.add("lightblue");
}
for(Topic t : topics){
for(Association a : t.getAssociations()) {
Collection<Topic> rs=a.getRoles();
Topic player1=a.getPlayer(rs.iterator().next());
if(t.mergesWithTopic(player1)){
ArrayList<Topic> ps=new ArrayList<Topic>();
for(Topic r : rs){
Topic p=a.getPlayer(r);
if(indices.containsKey(p.getOneSubjectIdentifier().toString()))
ps.add(p);
}
if(ps.size()<=1) continue;
else if(ps.size()==2){
Iterator<Topic> iter=ps.iterator();
edges.add(indices.get(iter.next().getOneSubjectIdentifier().toString()));
edges.add(indices.get(iter.next().getOneSubjectIdentifier().toString()));
}
else {
int aind=labels.size();
labels.add("");
colors.add("gray");
Iterator<Topic> iter=ps.iterator();
while(iter.hasNext()) {
edges.add(indices.get(iter.next().getOneSubjectIdentifier().toString()));
edges.add(aind);
}
}
}
}
}
int[] iedges=new int[edges.size()];
for(int i=0;i<edges.size();i++){ iedges[i]=edges.get(i); }
return new Graph(labels.size(),labels.toArray(new String[labels.size()]),colors.toArray(new String[colors.size()]),iedges);
}catch(TopicMapException tme){
tme.printStackTrace();
return null;
}
}
public Association[] getContextAssociations(){
AssociationContext context=new AssociationContext();
context.initialize(Wandora.getWandora(), null, null);
ArrayList<Association> ret=new ArrayList<Association>();
Iterator iter=context.getContextObjects();
if(iter!=null){
while(iter.hasNext()){
Object o=iter.next();
if(o instanceof Association) ret.add((Association)o);
}
}
return ret.toArray(new Association[ret.size()]);
}
public Topic[] getContextTopics(){
LayeredTopicContext context=new LayeredTopicContext(Wandora.getWandora(),null,null);
ArrayList<Topic> ret=new ArrayList<Topic>();
Iterator iter=context.getContextObjects();
if(iter!=null){
while(iter.hasNext()){
Object o=iter.next();
if(o instanceof Topic) ret.add((Topic)o);
}
}
return ret.toArray(new Topic[ret.size()]);
}
// "next" is a reserved word in R which makes this tricky
public static Object[] unwrapIterator(Iterator iter){
ArrayList<Object> ret=new ArrayList<Object>();
while(iter.hasNext()){
ret.add(iter.next());
}
return ret.toArray();
}
public Rengine getEngine(){
return engine;
}
private void initEngine(){
engine.eval("source(\"conf/rinit.r\",TRUE)");
engine.startMainLoop();
}
private static RConsole console;
public static synchronized RConsole getConsole(){
if(console!=null) return console;
console=new RConsole();
return console;
}
private static JDialog consoleDialog;
public static synchronized JDialog getConsoleDialog(){
if(consoleDialog!=null) return consoleDialog;
RConsole console=getConsole();
consoleDialog=new JDialog(Wandora.getWandora(),"R Console",false);
consoleDialog.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
consoleDialog.getContentPane().add(console);
consoleDialog.setSize(800, 700);
consoleDialog.setJMenuBar(console.consoleMenuBar);
GuiTools.centerWindow(consoleDialog, Wandora.getWandora());
return consoleDialog;
}
class LoopCallbacks implements RMainLoopCallbacks {
public String rChooseFile(Rengine re, int newFile) {
FileDialog fd = new FileDialog(Wandora.getWandora(), (newFile==0)?"Select a file":"Select a new file", (newFile==0)?FileDialog.LOAD:FileDialog.SAVE);
fd.setVisible(true);
String res=null;
if (fd.getDirectory()!=null) res=fd.getDirectory();
if (fd.getFile()!=null) res=(res==null)?fd.getFile():(res+fd.getFile());
return res;
}
public void rFlushConsole(Rengine re) {
//output.setText("");
}
public void rLoadHistory(Rengine re, String filename) {
}
public void rSaveHistory(Rengine re, String filename) {
}
public String rReadConsole(Rengine re, String prompt, int addToHistory) {
String ret=promptInput(prompt);
return ret;
}
public void rBusy(Rengine re, int which) {
}
public void rShowMessage(Rengine re, String message) {
//output2.append("message: "+message);
appendOutput("message: "+message);
output.setCaretPosition(output.getDocument().getLength());
}
public void rWriteConsole(Rengine re, String text, int oType) {
//output2.append(text);
appendOutput(text);
output.setCaretPosition(output.getDocument().getLength());
}
}
/** 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;
consoleMenuBar = new javax.swing.JMenuBar();
fileMenu = new SimpleMenu();
closeMenuItem = new SimpleMenuItem();
outputScrollPane = new SimpleScrollPane();
output = new SimpleTextPane();
jScrollPane2 = new SimpleScrollPane();
input = new SimpleTextPane();
evalButton = new SimpleButton();
fileMenu.setText("File");
fileMenu.setFont(GUIConstants.menuFont);
closeMenuItem.setFont(GUIConstants.menuFont);
closeMenuItem.setIcon(GuiBox.getIcon("gui/icons/exit.png"));
closeMenuItem.setText("Close");
closeMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
closeMenuItemActionPerformed(evt);
}
});
fileMenu.add(closeMenuItem);
consoleMenuBar.add(fileMenu);
setLayout(new java.awt.GridBagLayout());
output.setEditable(false);
output.setFont(new java.awt.Font("Monospaced", 0, 12)); // NOI18N
outputScrollPane.setViewportView(output);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.ipadx = 240;
gridBagConstraints.ipady = 65;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
add(outputScrollPane, gridBagConstraints);
jScrollPane2.setMinimumSize(new java.awt.Dimension(23, 75));
jScrollPane2.setPreferredSize(new java.awt.Dimension(8, 75));
input.setFont(new java.awt.Font("Monospaced", 0, 12)); // NOI18N
input.setMaximumSize(new java.awt.Dimension(2147483647, 75));
input.setMinimumSize(new java.awt.Dimension(6, 75));
input.setPreferredSize(new java.awt.Dimension(6, 75));
input.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
inputKeyPressed(evt);
}
});
jScrollPane2.setViewportView(input);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridheight = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 5, 5, 5);
add(jScrollPane2, gridBagConstraints);
evalButton.setText("Evaluate");
evalButton.setMaximumSize(new java.awt.Dimension(75, 75));
evalButton.setMinimumSize(new java.awt.Dimension(75, 75));
evalButton.setPreferredSize(new java.awt.Dimension(75, 75));
evalButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
evalButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 5, 5);
add(evalButton, gridBagConstraints);
}// </editor-fold>//GEN-END:initComponents
private void evalButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_evalButtonActionPerformed
synchronized(promptLock){
String in=input.getText();
history.set(history.size()-1,in);
history.add("");
historyPtr=history.size()-1;
input.setText("");
//output2.append(in+"\n");
appendOutput(in+"\n");
if(prompt){
promptIn=in+"\n";
promptLock.notifyAll();
}
return;
}
}//GEN-LAST:event_evalButtonActionPerformed
private void inputKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_inputKeyPressed
if(evt.getKeyCode()==KeyEvent.VK_ENTER){
evalButtonActionPerformed(null);
evt.consume();
}
else if(evt.getKeyCode()==KeyEvent.VK_UP){
if(historyPtr>0){
if(historyPtr==history.size()-1)
history.set(history.size()-1,input.getText());
historyPtr--;
input.setText(history.get(historyPtr));
}
}
else if(evt.getKeyCode()==KeyEvent.VK_DOWN){
if(historyPtr<history.size()-1) {
historyPtr++;
input.setText(history.get(historyPtr));
}
}
}//GEN-LAST:event_inputKeyPressed
private void closeMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeMenuItemActionPerformed
consoleDialog.setVisible(false);
}//GEN-LAST:event_closeMenuItemActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JMenuItem closeMenuItem;
private javax.swing.JMenuBar consoleMenuBar;
private javax.swing.JButton evalButton;
private javax.swing.JMenu fileMenu;
private javax.swing.JTextPane input;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTextPane output;
private javax.swing.JScrollPane outputScrollPane;
// End of variables declaration//GEN-END:variables
}
| 20,142 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
RBridge.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/r/RBridge.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
* RBridge.java
*
* Created on 21.9.2011, 14:44:26
*/
package org.wandora.application.tools.r;
import java.awt.FileDialog;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Vector;
import org.rosuda.JRI.RMainLoopCallbacks;
import org.rosuda.JRI.Rengine;
import org.wandora.application.Wandora;
/**
*
* @author akivela
*/
public class RBridge {
private static RBridge rBridge = null;
private boolean prompt=false;
private boolean isBusy=false;
private Rengine engine=null;
private final LoopCallbacks callbacks=new LoopCallbacks();
private ArrayList<RBridgeListener> rBridgeListeners = new ArrayList<RBridgeListener>();
private StringBuilder welcomeMessage = new StringBuilder("");
//private Thread executeThread = null;
private Vector<String> inputArray = new Vector<String>();
private static final String rWelcomeMessage=
"To read more about Wandora's R console, it's limitations and \n"+
"possibilities read documentation at \n"+
"http://wandora.org/wiki/R_in_Wandora\n"+
"\n";
private static final String rErrorMessage=
"Unable to initialize R.\n"+
"\n"+
"This is likely because R has not been installed or the environment\n"+
"variables aren't setup correctly or the rJava library has not been\n"+
"installed.\n"+
"\n"+
"To setup R do the following steps. These instructions are also\n"+
"explained in more detail in the Wandora wiki at\n"+
"http://wandora.org/wiki/R_in_Wandora\n"+
"\n"+
"1. Download R from http://www.r-project.org and install it.\n"+
"\n"+
"2. Install the required libraries in R. You need to run R as an\n"+
" administrator to do this. In Windows right click the R icon\n"+
" select Run as Administrator. In Linux run R on console using\n"+
" \"sudo R\".\n"+
"\n"+
" Then in the R console install the rJava package with\n"+
" install.packages(\"rJava\")\n"+
" You will likely also want to install the igraph package with\n"+
" install.packages(\"igraph\")\n"+
" and in Windows also the JavaGD packages\n"+
" install.packages(\"JavaGD\")\n"+
" You will be asked to select a mirror to download the packages\n"+
" from, just select the country you're in or one close to it.\n"+
"\n"+
"3. Next make sure that the environment variables are setup correctly.\n"+
" Open the SetR.bat (on Windows) or SetR.sh (on Linux) in the bin\n"+
" directory. Make sure the R_HOME directory is right. If you are\n"+
" using Windows also make sure that the version number matches your\n"+
" installation and that the R_ARCH matches your Java installation.\n"+
" Use i386 for 32-bit Java and x64 for 64-bit Java. If you did a\n"+
" standard installation of R then the other variables should be\n"+
" correct, otherwise adjust them as needed.\n"+
"\n"+
"You should now be able to use R in Wandora.\n"+
"\n"+
"The error encountered while trying to initiale R is shown below:\n\n"
;
private RBridge() {
try {
if(engine == null) {
// this makes JRI behave gracefully when the native library isn't found
System.setProperty("jri.ignore.ule", "yes");
if(!Rengine.versionCheck()) {
throw new Exception("R version mismatch, Java files don't match library version.");
}
engine=new Rengine(new String[]{},false,callbacks);
if(engine.waitForR()) {
initEngine();
appendOutput(rWelcomeMessage);
}
else {
throw new Exception("Couldn't load R");
}
/*
executeThread = new Thread() {
@Override
public void run() {
handleInputLoop();
}
};
*/
}
}
catch(UnsatisfiedLinkError e){
engine=null;
// Wandora.getWandora().handleError(new Exception(e));
// output.append("Unable to initialize R");
appendOutput(rErrorMessage);
StringWriter sw=new StringWriter();
PrintWriter pw=new PrintWriter(sw);
e.printStackTrace(pw);
pw.flush();
appendOutput("\n\n"+sw.toString());
}
catch(Exception e){
engine=null;
// Wandora.getWandora().handleError(e);
// output.append("Unable to initialize R");
appendOutput(rErrorMessage);
StringWriter sw=new StringWriter();
PrintWriter pw=new PrintWriter(sw);
e.printStackTrace(pw);
pw.flush();
appendOutput("\n\n"+sw.toString());
}
}
public static RBridge getRBridge() {
if(rBridge == null) {
rBridge = new RBridge();
}
return rBridge;
}
public void addRBridgeListener(RBridgeListener rbl) {
rBridgeListeners.add(rbl);
rbl.output(welcomeMessage.toString());
}
public void removeRBridgeListener(RBridgeListener rbl) {
rBridgeListeners.remove(rbl);
}
private Rengine getEngine(){
return engine;
}
private void initEngine(){
engine.eval("source(\"conf/rinit.r\",TRUE)");
engine.startMainLoop();
}
private final Object promptLock=new Object();
private String promptIn=null;
private String promptInput(String promptText){
synchronized(promptLock) {
appendOutput(promptText);
prompt=true;
promptIn=null;
while(promptIn==null) {
try {
promptLock.wait(200);
}
catch(InterruptedException ie) {
return null;
}
engine.rniIdle();
}
prompt=false;
return promptIn;
}
}
public String handleInput(String input) {
inputArray.add(input);
handleInputLoop();
return "";
}
private void handleInputLoop() {
while(!inputArray.isEmpty()) {
String input = inputArray.get(0);
inputArray.remove(0);
if(input != null) {
synchronized(callbacks) {
if(isBusy) {
continue;
}
}
synchronized(promptLock) {
if(prompt) {
promptIn=input+"\n";
appendOutput(promptIn);
promptLock.notifyAll();
}
}
}
try {
Thread.sleep(200);
}
catch(Exception e) {
// WAKE UP
}
}
}
private void appendOutput(String text) {
if(rBridgeListeners == null || rBridgeListeners.isEmpty()) {
welcomeMessage.append(text);
}
else {
try {
for(RBridgeListener rbl : rBridgeListeners) {
rbl.output(text);
}
}
catch(Exception e) {
e.printStackTrace();
}
}
}
// -------------------------------------------------------------------------
private class LoopCallbacks implements RMainLoopCallbacks {
@Override
public String rChooseFile(Rengine re, int newFile) {
FileDialog fd = new FileDialog(Wandora.getWandora(), (newFile==0)?"Select a file":"Select a new file", (newFile==0)?FileDialog.LOAD:FileDialog.SAVE);
fd.setVisible(true);
String res=null;
if (fd.getDirectory()!=null) res=fd.getDirectory();
if (fd.getFile()!=null) res=(res==null)?fd.getFile():(res+fd.getFile());
return res;
}
@Override
public void rFlushConsole(Rengine re) {
//output.setText("");
}
@Override
public void rLoadHistory(Rengine re, String filename) {
}
@Override
public void rSaveHistory(Rengine re, String filename) {
}
@Override
public String rReadConsole(Rengine re, String prompt, int addToHistory) {
String ret=promptInput(prompt);
return ret;
}
@Override
public void rBusy(Rengine re, int which) {
synchronized(this){ isBusy=(which!=0); }
}
@Override
public void rShowMessage(Rengine re, String message) {
appendOutput("message: "+message);
}
@Override
public void rWriteConsole(Rengine re, String text, int oType) {
appendOutput(text);
}
}
}
| 10,355 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
RBridgeListener.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/r/RBridgeListener.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
* RBridgeListener.java
*
* Created on 21.9.2011, 14:44:26
*/
package org.wandora.application.tools.r;
/**
*
* @author akivela
*/
public interface RBridgeListener {
public void output(String output);
}
| 1,034 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
OpenRConsole.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/r/OpenRConsole.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.r;
import javax.swing.Icon;
import javax.swing.JDialog;
import org.wandora.application.Wandora;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.UIBox;
import org.wandora.application.tools.AbstractWandoraTool;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author olli
*/
public class OpenRConsole extends AbstractWandoraTool {
private static final long serialVersionUID = 1L;
public void execute(Wandora wandora, Context context) throws TopicMapException {
JDialog dialog=RConsole2.getConsoleDialog();
if(!dialog.isVisible()) dialog.setVisible(true);
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/r.png");
}
@Override
public String getName() {
return "Open R console";
}
@Override
public String getDescription() {
return "Open R console.";
}
}
| 1,754 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
RConsole2.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/r/RConsole2.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
* RConsole2.java
*
* Created on Aug 26, 2011, 9:19:18 PM
*/
package org.wandora.application.tools.r;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JDialog;
import javax.swing.JMenuBar;
import javax.swing.WindowConstants;
import org.wandora.application.Wandora;
import org.wandora.application.gui.UIBox;
import org.wandora.application.gui.simple.SimpleMenu;
import org.wandora.application.gui.simple.SimpleScrollPane;
import org.wandora.application.gui.simple.SimpleTextConsole;
import org.wandora.application.gui.simple.SimpleTextConsoleListener;
import org.wandora.application.tools.ExecBrowser;
import org.wandora.utils.swing.GuiTools;
/**
*
* @author akivela
*/
public class RConsole2 extends javax.swing.JPanel implements ActionListener, SimpleTextConsoleListener, RBridgeListener {
private static final long serialVersionUID = 1L;
private SimpleTextConsole simpleTextConsole = null;
protected static Object[] fileMenuStruct = new Object[] {
"Import...", UIBox.getIcon("gui/icons/file_open.png"),
"Export...", UIBox.getIcon("gui/icons/file_save.png"),
//"Export input...",
"---",
"Close", UIBox.getIcon("gui/icons/exit.png"),
};
protected static Object[] editMenuStruct = new Object[] {
"Cut", UIBox.getIcon("gui/icons/cut.png"),
"Copy", UIBox.getIcon("gui/icons/copy.png"),
"Paste", UIBox.getIcon("gui/icons/paste.png"),
"Clear", UIBox.getIcon("gui/icons/clear.png"),
};
protected static Object[] viewMenuStruct = new Object[] {
"Font size 9", UIBox.getIcon("gui/icons/font.png"),
"Font size 10", UIBox.getIcon("gui/icons/font.png"),
"Font size 12", UIBox.getIcon("gui/icons/font.png"),
"Font size 14", UIBox.getIcon("gui/icons/font.png"),
"Font size 16", UIBox.getIcon("gui/icons/font.png"),
"Font size 18", UIBox.getIcon("gui/icons/font.png"),
"---",
"Inverse colors"
};
protected static Object[] helpMenuStruct = new Object[] {
"R manuals", UIBox.getIcon("gui/icons/open_browser.png"), new ExecBrowser("http://cran.r-project.org/manuals.html"),
};
private static JDialog consoleDialog;
private RBridge rBridge = null;
/** Creates new form RConsole2 */
public RConsole2() {
initComponents();
simpleTextConsole = (SimpleTextConsole) consolePane;
rBridge = RBridge.getRBridge();
rBridge.addRBridgeListener(this);
}
@Override
public void output(String text) {
try {
if(simpleTextConsole.isVisible()) {
simpleTextConsole.output(text);
simpleTextConsole.refresh();
}
}
catch(Exception e) {
e.printStackTrace();
}
}
@Override
public void actionPerformed(ActionEvent e) {
if(e == null) return;
String c = e.getActionCommand();
if(simpleTextConsole != null) {
if("Import...".equalsIgnoreCase(c)) {
simpleTextConsole.load();
}
if("Export...".equalsIgnoreCase(c)) {
simpleTextConsole.save();
}
if("Export input...".equalsIgnoreCase(c)) {
simpleTextConsole.saveInput();
}
else if("Close".equalsIgnoreCase(c)) {
close();
}
else if("Cut".equalsIgnoreCase(c)) {
simpleTextConsole.cut();
}
else if("Copy".equalsIgnoreCase(c)) {
simpleTextConsole.copy();
}
else if("Paste".equalsIgnoreCase(c)) {
simpleTextConsole.paste();
}
else if("Clear".equalsIgnoreCase(c)) {
simpleTextConsole.clear();
}
else if("Refresh".equalsIgnoreCase(c)) {
simpleTextConsole.refresh();
}
else if(c.startsWith("Font size ")) {
String n = c.substring("Font size ".length());
int s = Integer.parseInt(n);
simpleTextConsole.setFontSize(s);
}
else if("Inverse colors".equalsIgnoreCase(c)) {
Color color = simpleTextConsole.getBackground();
simpleTextConsole.setBackground(simpleTextConsole.getForeground());
simpleTextConsole.setForeground(color);
simpleTextConsole.setCaretColor(color);
}
}
}
@Override
public String handleInput(String input) {
if(rBridge != null) {
return rBridge.handleInput(input);
}
return "";
}
public static synchronized JDialog getConsoleDialog(){
if(consoleDialog!=null) return consoleDialog;
RConsole2 console=new RConsole2();
consoleDialog=new JDialog(Wandora.getWandora(),"R console",false);
consoleDialog.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
consoleDialog.getContentPane().add(console);
consoleDialog.setSize(800, 700);
JMenuBar menubar = new JMenuBar();
SimpleMenu fileMenu = new SimpleMenu("File");
SimpleMenu editMenu = new SimpleMenu("Edit");
SimpleMenu viewMenu = new SimpleMenu("View");
SimpleMenu helpMenu = new SimpleMenu("Help");
fileMenu.setIcon(null);
editMenu.setIcon(null);
viewMenu.setIcon(null);
helpMenu.setIcon(null);
UIBox.attachMenu(fileMenu, fileMenuStruct, console);
UIBox.attachMenu(editMenu, editMenuStruct, console);
UIBox.attachMenu(viewMenu, viewMenuStruct, console);
UIBox.attachMenu(helpMenu, helpMenuStruct, console);
menubar.add(fileMenu);
menubar.add(editMenu);
menubar.add(viewMenu);
menubar.add(helpMenu);
consoleDialog.setJMenuBar(menubar);
//consoleDialog.setJMenuBar(console.consoleMenuBar);
GuiTools.centerWindow(consoleDialog, Wandora.getWandora());
return consoleDialog;
}
public static void close() {
if(consoleDialog != null) {
consoleDialog.setVisible(false);
}
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
scrollPane = new SimpleScrollPane();
consolePane = new SimpleTextConsole(this);
setLayout(new java.awt.GridBagLayout());
scrollPane.setViewportView(consolePane);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(scrollPane, gridBagConstraints);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextPane consolePane;
private javax.swing.JScrollPane scrollPane;
// End of variables declaration//GEN-END:variables
}
| 8,371 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
RConsole.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/r/RConsole.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.r;
import java.awt.FileDialog;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import javax.swing.JDialog;
import javax.swing.WindowConstants;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import org.rosuda.JRI.RMainLoopCallbacks;
import org.rosuda.JRI.Rengine;
import org.wandora.application.Wandora;
import org.wandora.application.gui.UIBox;
import org.wandora.application.gui.UIConstants;
import org.wandora.application.gui.simple.SimpleButton;
import org.wandora.application.gui.simple.SimpleMenu;
import org.wandora.application.gui.simple.SimpleMenuItem;
import org.wandora.application.gui.simple.SimpleScrollPane;
import org.wandora.application.gui.simple.SimpleTextPane;
import org.wandora.utils.swing.GuiTools;
/**
*
* @author olli
*/
public class RConsole extends javax.swing.JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
private ArrayList<String> history=new ArrayList<String>(); { history.add(""); }
private int historyPtr=0;
private boolean prompt=false;
private boolean isBusy=false;
private Rengine engine;
private final LoopCallbacks callbacks=new LoopCallbacks();
private static final String rErrorMessage=
"Unable to initialize R.\n"+
"\n"+
"This is likely because R has not been installed or the environment\n"+
"variables aren't setup correctly or the rJava library has not been\n"+
"installed.\n"+
"\n"+
"To setup R do the following steps. These instructions are also\n"+
"explained in more detail in the Wandora wiki at\n"+
"http://wandora.org/wiki/R_in_Wandora\n"+
"\n"+
"1. Download R from http://www.r-project.org and install it.\n"+
"\n"+
"2. Install the required libraries in R. You need to run R as an\n"+
" administrator to do this. In Windows right click the R icon\n"+
" select Run as Adminsitrator. In Linux run R on console using\n"+
" \"sudo R\".\n"+
"\n"+
" Then in the R console install the rJava package with\n"+
" install.packages(\"rJava\")\n"+
" You will likely also want to install the igraph package with\n"+
" install.packages(\"igraph\")\n"+
" and in Windows also the JavaGD packages\n"+
" install.packages(\"JavaGD\")\n"+
" You will be asked to select a mirror to download the packages\n"+
" from, just select the country you're in or one close to it.\n"+
"\n"+
"3. Next make sure that the environment variables are setup correctly.\n"+
" Open the SetR.bat (on Windows) or SetR.sh (on Linux) in the bin\n"+
" directory. Make sure the R_HOME directory is right. If you are\n"+
" using Windows also make sure that the version number matches your\n"+
" installation and that the R_ARCH matches your Java installation.\n"+
" Use i386 for 32-bit Java and x64 for 64-bit Java. If you did a\n"+
" standard installation of R then the other variables should be\n"+
" correct, otherwise adjust them as needed.\n"+
"\n"+
"You should now be able to use R in Wandora.\n"+
"\n"+
"The error encountered while trying to initiale R is shown below:\n\n"
;
/** Creates new form RConsole */
public RConsole() {
initComponents();
try{
// this makes JRI behave gracefully when the native library isn't found
System.setProperty("jri.ignore.ule", "yes");
if(!Rengine.versionCheck()){
throw new Exception("R version mismatch, Java files don't match library version.");
}
engine=new Rengine(new String[]{},false,callbacks);
if(engine.waitForR()){
initEngine();
}
else {
throw new Exception("Couldn't load R");
}
}catch(UnsatisfiedLinkError e){
engine=null;
// Wandora.getWandora().handleError(new Exception(e));
// output.append("Unable to initialize R");
appendOutput(rErrorMessage);
StringWriter sw=new StringWriter();
PrintWriter pw=new PrintWriter(sw);
e.printStackTrace(pw);
pw.flush();
appendOutput("\n\n"+sw.toString());
}
catch(Exception e){
engine=null;
//Wandora.getWandora().handleError(e);
//output.append("Unable to initialize R");
appendOutput(rErrorMessage);
StringWriter sw=new StringWriter();
PrintWriter pw=new PrintWriter(sw);
e.printStackTrace(pw);
pw.flush();
appendOutput("\n\n"+sw.toString());
}
}
private void appendOutput(String text){
Document d=output.getDocument();
try{
d.insertString(d.getLength(), text, null);
output.setCaretPosition(output.getDocument().getLength());
}catch(BadLocationException ble){}
}
private final Object promptLock=new Object();
private String promptIn=null;
private String promptInput(String promptText){
synchronized(promptLock){
//output.append(promptText);
appendOutput(promptText);
prompt=true;
promptIn=null;
while(promptIn==null){
try{
promptLock.wait(100);
}catch(InterruptedException ie){return null;}
engine.rniIdle();
}
prompt=false;
return promptIn;
}
}
public void actionPerformed(ActionEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}
public Rengine getEngine(){
return engine;
}
private void initEngine(){
engine.eval("source(\"conf/rinit.r\",TRUE)");
engine.startMainLoop();
}
private static RConsole console;
public static synchronized RConsole getConsole(){
if(console!=null) return console;
console=new RConsole();
return console;
}
private static JDialog consoleDialog;
public static synchronized JDialog getConsoleDialog(){
if(consoleDialog!=null) return consoleDialog;
RConsole console=getConsole();
consoleDialog=new JDialog(Wandora.getWandora(),"R Console",false);
consoleDialog.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
consoleDialog.getContentPane().add(console);
consoleDialog.setSize(800, 700);
consoleDialog.setJMenuBar(console.consoleMenuBar);
GuiTools.centerWindow(consoleDialog, Wandora.getWandora());
return consoleDialog;
}
class LoopCallbacks implements RMainLoopCallbacks {
public String rChooseFile(Rengine re, int newFile) {
FileDialog fd = new FileDialog(Wandora.getWandora(), (newFile==0)?"Select a file":"Select a new file", (newFile==0)?FileDialog.LOAD:FileDialog.SAVE);
fd.setVisible(true);
String res=null;
if (fd.getDirectory()!=null) res=fd.getDirectory();
if (fd.getFile()!=null) res=(res==null)?fd.getFile():(res+fd.getFile());
return res;
}
public void rFlushConsole(Rengine re) {
//output.setText("");
}
public void rLoadHistory(Rengine re, String filename) {
}
public void rSaveHistory(Rengine re, String filename) {
}
public String rReadConsole(Rengine re, String prompt, int addToHistory) {
String ret=promptInput(prompt);
return ret;
}
public void rBusy(Rengine re, int which) {
synchronized(this){ isBusy=(which!=0); }
}
public void rShowMessage(Rengine re, String message) {
//output2.append("message: "+message);
appendOutput("message: "+message);
}
public void rWriteConsole(Rengine re, String text, int oType) {
//output2.append(text);
appendOutput(text);
}
}
/** 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;
consoleMenuBar = new javax.swing.JMenuBar();
fileMenu = new SimpleMenu();
closeMenuItem = new SimpleMenuItem();
outputScrollPane = new SimpleScrollPane();
output = new SimpleTextPane();
jScrollPane2 = new SimpleScrollPane();
input = new SimpleTextPane();
evalButton = new SimpleButton();
fileMenu.setText("File");
fileMenu.setFont(UIConstants.menuFont);
closeMenuItem.setFont(UIConstants.menuFont);
closeMenuItem.setIcon(UIBox.getIcon("gui/icons/exit.png"));
closeMenuItem.setText("Close");
closeMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
closeMenuItemActionPerformed(evt);
}
});
fileMenu.add(closeMenuItem);
consoleMenuBar.add(fileMenu);
setLayout(new java.awt.GridBagLayout());
output.setEditable(false);
output.setFont(new java.awt.Font("Monospaced", 0, 12)); // NOI18N
outputScrollPane.setViewportView(output);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.ipadx = 240;
gridBagConstraints.ipady = 65;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
add(outputScrollPane, gridBagConstraints);
jScrollPane2.setMinimumSize(new java.awt.Dimension(23, 75));
jScrollPane2.setPreferredSize(new java.awt.Dimension(8, 75));
input.setFont(new java.awt.Font("Monospaced", 0, 12)); // NOI18N
input.setMaximumSize(new java.awt.Dimension(2147483647, 75));
input.setMinimumSize(new java.awt.Dimension(6, 75));
input.setPreferredSize(new java.awt.Dimension(6, 75));
input.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
inputKeyPressed(evt);
}
});
jScrollPane2.setViewportView(input);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridheight = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 5, 5, 5);
add(jScrollPane2, gridBagConstraints);
evalButton.setText("Evaluate");
evalButton.setMaximumSize(new java.awt.Dimension(75, 75));
evalButton.setMinimumSize(new java.awt.Dimension(75, 75));
evalButton.setPreferredSize(new java.awt.Dimension(75, 75));
evalButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
evalButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 5, 5);
add(evalButton, gridBagConstraints);
}// </editor-fold>//GEN-END:initComponents
private void evalButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_evalButtonActionPerformed
synchronized( callbacks ){ if(isBusy) return; }
synchronized(promptLock){
String in=input.getText();
history.set(history.size()-1,in);
history.add("");
historyPtr=history.size()-1;
input.setText("");
//output2.append(in+"\n");
appendOutput(in+"\n");
if(prompt){
promptIn=in+"\n";
promptLock.notifyAll();
}
return;
}
}//GEN-LAST:event_evalButtonActionPerformed
private void inputKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_inputKeyPressed
if(evt.getKeyCode()==KeyEvent.VK_ENTER){
evalButtonActionPerformed(null);
evt.consume();
}
else if(evt.getKeyCode()==KeyEvent.VK_UP){
if(historyPtr>0){
if(historyPtr==history.size()-1)
history.set(history.size()-1,input.getText());
historyPtr--;
input.setText(history.get(historyPtr));
}
}
else if(evt.getKeyCode()==KeyEvent.VK_DOWN){
if(historyPtr<history.size()-1) {
historyPtr++;
input.setText(history.get(historyPtr));
}
}
}//GEN-LAST:event_inputKeyPressed
private void closeMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeMenuItemActionPerformed
consoleDialog.setVisible(false);
}//GEN-LAST:event_closeMenuItemActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JMenuItem closeMenuItem;
private javax.swing.JMenuBar consoleMenuBar;
private javax.swing.JButton evalButton;
private javax.swing.JMenu fileMenu;
private javax.swing.JTextPane input;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTextPane output;
private javax.swing.JScrollPane outputScrollPane;
// End of variables declaration//GEN-END:variables
}
| 15,653 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TilingGenerator.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/generators/TilingGenerator.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* TilingGenerator.java
*
* Created on 2008-09-19, 16:28
*
*/
package org.wandora.application.tools.generators;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Map;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.WandoraOptionPane;
import org.wandora.application.tools.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.Tuples.T2;
import org.wandora.utils.swing.GuiTools;
/**
*
* http://en.wikipedia.org/wiki/Tiling_by_regular_polygons
*
* @author akivela
*/
public class TilingGenerator extends AbstractGenerator implements WandoraTool {
private static final long serialVersionUID = 1L;
public static String globalSiPattern = "";
public static String globalBasenamePattern = "";
public static boolean connectWithWandoraClass = true;
/** Creates a new instance of TilingGenerator */
public TilingGenerator() {
}
@Override
public String getName() {
return "Tiling graph generator";
}
@Override
public String getDescription() {
return "Tiling graph generator creates simple graphs that resemble plane tilings by regular polygons.";
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
TopicMap topicmap = solveContextTopicMap(wandora, context);
GenericOptionsDialog god=new GenericOptionsDialog(wandora,
"Tiling graph generator",
"Tiling graph generator creates simple graphs that resemble plane tilings by regular polygons. "+
"Created tilings consist of topics and associations. Topics can be thought as tiling vertices and "+
"associations as tiling edges. Select the type and size of created tiling below. Optionally you "+
"can set the name and subject identifier patterns for vertex topics as well as the assocation type and "+
"roles of tiling graph edges. Connecting topics with Wandora class creates some additional topics and "+
"associations that link the tiling graph with Wandora class topic.",
true,new String[][]{
new String[]{"Create square tiling","boolean"},
new String[]{"Width of square tiling","string"},
new String[]{"Height of square tiling","string"},
new String[]{"---1","separator"},
new String[]{"Create triangular tiling","boolean"},
new String[]{"Depth of triangular tiling","string"},
new String[]{"---2","separator"},
new String[]{"Create hexagonal tiling","boolean"},
new String[]{"Depth of hexagonal tiling","string"},
new String[]{"---3","separator"},
new String[]{"Subject identifier pattern","string",globalSiPattern,"Subject identifier patterns for the created node topics. Part __n__ in patterns is replaced with vertex identifier."},
new String[]{"Basename pattern","string",globalBasenamePattern,"Basename patterns for the created node topics. Part __n__ in patterns is replaced with vertex identifier."},
new String[]{"Connect topics with Wandora class","boolean", connectWithWandoraClass ? "true" : "false","Create additional topics and associations that connect created topics with the Wandora class." },
new String[]{"Association type topic","topic",null,"Optional association type for graph edges."},
new String[]{"First role topic","topic",null,"Optional role topic for graph edges."},
new String[]{"Second role topic","topic",null,"Optional role topic for graph edges."},
},wandora);
god.setSize(700, 620);
GuiTools.centerWindow(god,wandora);
god.setVisible(true);
if(god.wasCancelled()) return;
Map<String,String> optionsValues = god.getValues();
try {
globalSiPattern = optionsValues.get("Subject identifier pattern");
if(globalSiPattern != null && globalSiPattern.trim().length() > 0) {
if(!globalSiPattern.contains("__n__")) {
int a = WandoraOptionPane.showConfirmDialog(Wandora.getWandora(), "Subject identifier pattern doesn't contain part for topic counter '__n__'. This causes all generated topics to merge. Do you want to use it?", "Missing topic counter part", WandoraOptionPane.WARNING_MESSAGE);
if(a != WandoraOptionPane.YES_OPTION) globalSiPattern = null;
}
}
globalBasenamePattern = optionsValues.get("Basename pattern");
if(globalBasenamePattern != null && globalBasenamePattern.trim().length() > 0) {
if(!globalBasenamePattern.contains("__n__")) {
int a = WandoraOptionPane.showConfirmDialog(Wandora.getWandora(), "Basename pattern doesn't contain part for topic counter '__n__'. This causes all generated topics to merge. Do you want to use it?", "Missing topic counter part", WandoraOptionPane.WARNING_MESSAGE);
if(a != WandoraOptionPane.YES_OPTION) globalBasenamePattern = null;
}
}
connectWithWandoraClass = "true".equalsIgnoreCase(optionsValues.get("Connect topics with Wandora class"));
}
catch(Exception e) {
log(e);
}
Tiling tiling = null;
int width = 0;
int height = 0;
int depth = 0;
boolean tilingSelected = false;
setDefaultLogger();
setLogTitle("Tiling graph generator");
try {
if("true".equals(optionsValues.get("Create square tiling"))) {
try {
tilingSelected = true;
width = Integer.parseInt(optionsValues.get("Width of square tiling"));
height = Integer.parseInt(optionsValues.get("Height of square tiling"));
tiling = new SquareTiling(width, height);
makeTiling(tiling, topicmap, optionsValues);
}
catch(NumberFormatException nfe) {
log("Square tiling width and height should be positive integer numbers.");
}
}
if("true".equals(optionsValues.get("Create triangular tiling"))) {
try {
tilingSelected = true;
depth = Integer.parseInt(optionsValues.get("Depth of triangular tiling"));
tiling = new TriangularTiling(depth);
makeTiling(tiling, topicmap, optionsValues);
}
catch(NumberFormatException nfe) {
log("Triangular tiling depth should be positive integer number.");
}
}
if("true".equals(optionsValues.get("Create hexagonal tiling"))) {
try {
tilingSelected = true;
depth = Integer.parseInt(optionsValues.get("Depth of hexagonal tiling"));
tiling = new HexagonalTiling(depth);
makeTiling(tiling, topicmap, optionsValues);
}
catch(NumberFormatException nfe) {
log("Hexagonal tiling depth should be positive integer number.");
}
}
if(!tilingSelected) {
log("No tiling selected.");
}
}
catch(Exception e) {
log(e);
}
log("Ready.");
setState(WAIT);
}
public void makeTiling(Tiling tiling, TopicMap topicmap, Map<String,String> optionsValues) {
if(tiling != null) {
int progress = 0;
Collection<T2<String,String>> edges = tiling.getEdges();
log("Creating "+tiling.getName()+" tiling graph.");
Topic atype = tiling.getAssociationTypeTopic(topicmap,optionsValues);
Topic role1 = tiling.getRole1Topic(topicmap,optionsValues);
Topic role2 = tiling.getRole2Topic(topicmap,optionsValues);
Association a = null;
Topic node1 = null;
Topic node2 = null;
if(edges.size() > 0) {
setProgressMax(edges.size());
for(T2<String,String> edge : edges) {
if(edge != null) {
node1 = tiling.getVertexTopic(edge.e1, topicmap, optionsValues);
node2 = tiling.getVertexTopic(edge.e2, topicmap, optionsValues);
if(node1 != null && node2 != null) {
try {
a = topicmap.createAssociation(atype);
a.addPlayer(node1, role1);
a.addPlayer(node2, role2);
}
catch(Exception e) {
e.printStackTrace();
}
}
setProgress(progress++);
}
}
if(connectWithWandoraClass) {
log("You'll find created topics under the '"+tiling.getName()+" graph' topic.");
}
else {
String searchWord = tiling.getName();
if(globalBasenamePattern != null && globalBasenamePattern.trim().length() > 0) {
searchWord = globalBasenamePattern.replaceAll("__n__", "");
searchWord = searchWord.trim();
}
log("You'll find created topics by searching with a '"+searchWord+"'.");
}
}
else {
log("Number of tiling edges is zero. Tiling has no nodes either.");
}
}
}
// -------------------------------------------------------------------------
// ------------------------------------------------------------- TILINGS ---
// -------------------------------------------------------------------------
public interface Tiling {
public String getSIPrefix();
public String getName();
public int getSize();
public Collection<T2<String,String>> getEdges();
public Collection<String> getVertices();
public Topic getVertexTopic(String vertex, TopicMap topicmap, Map<String,String> optionsValues);
public Topic getAssociationTypeTopic(TopicMap topicmap, Map<String,String> optionsValues);
public Topic getRole1Topic(TopicMap topicmap, Map<String,String> optionsValues);
public Topic getRole2Topic(TopicMap topicmap, Map<String,String> optionsValues);
}
public abstract class AbstractTiling implements Tiling {
@Override
public Topic getVertexTopic(String vertex, TopicMap topicmap, Map<String,String> optionsValues) {
String newBasename = getName()+" vertex "+vertex;
if(globalBasenamePattern != null && globalBasenamePattern.trim().length() > 0) {
newBasename = globalBasenamePattern.replaceAll("__n__", vertex);
}
String newSubjectIdentifier = getSIPrefix()+"vertex-"+vertex;
if(globalSiPattern != null && globalSiPattern.trim().length() > 0) {
newSubjectIdentifier = globalSiPattern.replaceAll("__n__", vertex);
}
Topic t = getOrCreateTopic(topicmap, newSubjectIdentifier, newBasename);
if(connectWithWandoraClass) {
try {
Topic graphTopic = getOrCreateTopic(topicmap, getSIPrefix(), getName()+" graph");
Topic wandoraClass = getOrCreateTopic(topicmap, TMBox.WANDORACLASS_SI);
makeSuperclassSubclass(topicmap, wandoraClass, graphTopic);
t.addType(graphTopic);
}
catch(Exception e) {
e.printStackTrace();
}
}
return t;
}
@Override
public Topic getAssociationTypeTopic(TopicMap topicmap, Map<String,String> optionsValues) {
String atypeStr = null;
Topic atype = null;
if(optionsValues != null) {
atypeStr = optionsValues.get("Association type topic");
}
if(atypeStr != null) {
try {
atype = topicmap.getTopic(atypeStr);
}
catch(Exception e) {
e.printStackTrace();
}
}
if(atype == null) {
atype = getOrCreateTopic(topicmap, getSIPrefix()+"edge", getName()+" edge");
}
return atype;
}
@Override
public Topic getRole1Topic(TopicMap topicmap, Map<String,String> optionsValues) {
String roleStr = null;
Topic role = null;
if(optionsValues != null) {
roleStr = optionsValues.get("First role topic");
}
if(roleStr != null) {
try {
role = topicmap.getTopic(roleStr);
}
catch(Exception e) {
e.printStackTrace();
}
}
if(role == null) {
role = getOrCreateTopic(topicmap, getSIPrefix()+"role-1", "role 1");
}
return role;
}
@Override
public Topic getRole2Topic(TopicMap topicmap, Map<String,String> optionsValues) {
String roleStr = null;
Topic role = null;
if(optionsValues != null) {
roleStr = optionsValues.get("Second role topic");
}
if(roleStr != null) {
try {
role = topicmap.getTopic(roleStr);
}
catch(Exception e) {
e.printStackTrace();
}
}
if(role == null) {
role = getOrCreateTopic(topicmap, getSIPrefix()+"role-2", "role 2");
}
return role;
}
}
// -------------------------------------------------------------------------
private class SquareTiling extends AbstractTiling implements Tiling {
private int size = 0;
private int width = 0;
private int height = 0;
public SquareTiling(int w, int h) {
this.width = w;
this.height = h;
this.size = w*h;
}
@Override
public String getSIPrefix() {
return "http://wandora.org/si/tiling/square/";
}
@Override
public String getName() {
return "Square tiling";
}
@Override
public int getSize() {
return size;
}
@Override
public Collection<T2<String,String>> getEdges() {
ArrayList<T2<String,String>> edges = new ArrayList<>();
int w = width-1;
int h = height-1;
for(int x=0; x<w; x++) {
for(int y=0; y<h; y++) {
edges.add(new T2<>(x+"-"+y, x+"-"+(y+1)));
edges.add(new T2<>(x+"-"+y, (x+1)+"-"+y));
}
}
for(int x=0; x<w; x++) {
edges.add(new T2<>(x+"-"+h, (x+1)+"-"+h));
}
for(int y=0; y<h; y++) {
edges.add(new T2<>(w+"-"+y, w+"-"+(y+1)));
}
return edges;
}
@Override
public Collection<String> getVertices() {
ArrayList<String> vertices = new ArrayList<>();
for(int x=0; x<width; x++) {
for(int y=0; y<height; y++) {
vertices.add(x+"-"+y);
}
}
return vertices;
}
}
// -------------------------------------------------------------------------
private class TriangularTiling extends AbstractTiling implements Tiling {
private int depth = 0;
public TriangularTiling(int d) {
this.depth = d;
}
@Override
public String getSIPrefix() {
return "http://wandora.org/si/tiling/triangular/";
}
@Override
public String getName() {
return "Triangular tiling";
}
@Override
public int getSize() {
int size = 0;
for(int d=0; d<depth; d++) {
for(int f=0; f<d; f++) {
size++;
}
}
return size;
}
@Override
public Collection<T2<String,String>> getEdges() {
ArrayList<T2<String,String>> edges = new ArrayList<>();
for(int d=0; d<depth; d++) {
for(int f=0; f<d; f++) {
edges.add(new T2<>(d+"-"+f, (d-1)+"-"+f));
edges.add(new T2<>(d+"-"+f, d+"-"+(f+1)));
edges.add(new T2<>((d-1)+"-"+f, d+"-"+(f+1)));
}
}
return edges;
}
@Override
public Collection<String> getVertices() {
ArrayList<String> vertices = new ArrayList<>();
for(int d=0; d<depth; d++) {
for(int f=0; f<d; f++) {
vertices.add(d+"-"+f);
}
}
return vertices;
}
}
// -------------------------------------------------------------------------
private class HexagonalTiling extends AbstractTiling implements Tiling {
private int depth = 0;
public HexagonalTiling(int d) {
this.depth = d;
}
@Override
public String getSIPrefix() {
return "http://wandora.org/si/tiling/hexagonal/";
}
@Override
public String getName() {
return "Hexagonal tiling";
}
@Override
public int getSize() {
int size = 0;
for(int d=0; d<depth; d++) {
for(int f=0; f<d; f++) {
size++;
}
}
return size;
}
@Override
public Collection<T2<String,String>> getEdges() {
ArrayList<T2<String,String>> edges = new ArrayList<>();
String nc = null;
String n1 = null;
String n2 = null;
String n3 = null;
for(int d=0; d<depth; d++) {
for(int f=0; f<d+1; f++) {
nc = d+"-"+f+"-c";
n2 = d+"-"+f;
n3 = d+"-"+(f+1);
edges.add(new T2<>(nc, n2));
edges.add(new T2<>(nc, n3));
if(d == 0) {
n1 = d+"-"+f+"-t";
edges.add(new T2<>(nc, n1));
}
else {
n1 = (d-1)+"-"+f;
edges.add(new T2<>(nc, n1));
}
}
}
return edges;
}
@Override
public Collection<String> getVertices() {
HashSet<String> vertices = new LinkedHashSet<>();
for(int d=0; d<depth; d++) {
for(int f=0; f<d+1; f++) {
vertices.add( d+"-"+f+"-c" );
vertices.add( d+"-"+f );
vertices.add( d+"-"+(f+1) );
if(d == 0) {
vertices.add( d+"-"+f+"-t" );
}
else {
vertices.add( (d-1)+"-"+f );
}
}
}
return vertices;
}
}
}
| 21,347 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
CylinderGenerator.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/generators/CylinderGenerator.java | /*
* WANDORA Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* CylinderGenerator.java
*
* Created on 2012-05-11
*
*/
package org.wandora.application.tools.generators;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Map;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.WandoraOptionPane;
import org.wandora.application.tools.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.Tuples.T2;
import org.wandora.utils.swing.GuiTools;
/**
*
* http://en.wikipedia.org/wiki/Tiling_by_regular_polygons
*
* @author elehtonen
*/
public class CylinderGenerator extends AbstractGenerator implements WandoraTool {
private static final long serialVersionUID = 1L;
public static String globalSiPattern = "";
public static String globalBasenamePattern = "";
public static boolean connectWithWandoraClass = true;
/**
* Creates a new instance of Cylinder Generator
*/
public CylinderGenerator() {
}
@Override
public String getName() {
return "Cylinder graph generator";
}
@Override
public String getDescription() {
return "Generates cylinder graph topic maps";
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
TopicMap topicmap = solveContextTopicMap(wandora, context);
GenericOptionsDialog god = new GenericOptionsDialog(wandora,
"Cylinder graph generator",
"Cylinder graph generator creates simple graphs that resemble cylinders created with regular polygons. "+
"Created cylinders consist of topics and associations. Topics can be thought as cylinder vertices and "+
"associations as cylinder edges. Select the type and size of created tiling below. Optionally you "+
"can set the name and subject identifier patterns for vertex topics as well as the assocation type and "+
"roles of cylinder graph edges. Connecting topics with Wandora class creates some additional topics and "+
"associations that link the cylinder graph with Wandora class topic.",
true, new String[][]{
new String[]{"Create a cylinder with square tiling", "boolean"},
new String[]{"Create a cylinder with triangular tiling", "boolean"},
new String[]{"Create a cylinder with hexagonal tiling", "boolean"},
new String[]{"Width of cylinder", "string"},
new String[]{"Height of cylinder", "string"},
new String[]{"Toroid", "boolean"},
new String[]{"---3","separator"},
new String[]{"Subject identifier pattern","string",globalSiPattern,"Subject identifier patterns for the created node topics. Part __n__ in patterns is replaced with vertex identifier."},
new String[]{"Basename pattern","string",globalBasenamePattern,"Basename patterns for the created node topics. Part __n__ in patterns is replaced with vertex identifier."},
new String[]{"Connect topics with Wandora class","boolean", connectWithWandoraClass ? "true" : "false","Create additional topics and associations that connect created topics with the Wandora class." },
new String[]{"Association type topic","topic",null,"Optional association type for graph edges."},
new String[]{"First role topic","topic",null,"Optional role topic for graph edges."},
new String[]{"Second role topic","topic",null,"Optional role topic for graph edges."},
},
wandora);
god.setSize(700, 620);
GuiTools.centerWindow(god,wandora);
god.setVisible(true);
if (god.wasCancelled()) {
return;
}
Map<String, String> values = god.getValues();
try {
globalSiPattern = values.get("Subject identifier pattern");
if(globalSiPattern != null && globalSiPattern.trim().length() > 0) {
if(!globalSiPattern.contains("__n__")) {
int a = WandoraOptionPane.showConfirmDialog(Wandora.getWandora(), "Subject identifier pattern doesn't contain part for topic counter '__n__'. This causes all generated topics to merge. Do you want to use it?", "Missing topic counter part", WandoraOptionPane.WARNING_MESSAGE);
if(a != WandoraOptionPane.YES_OPTION) globalSiPattern = null;
}
}
globalBasenamePattern = values.get("Basename pattern");
if(globalBasenamePattern != null && globalBasenamePattern.trim().length() > 0) {
if(!globalBasenamePattern.contains("__n__")) {
int a = WandoraOptionPane.showConfirmDialog(Wandora.getWandora(), "Basename pattern doesn't contain part for topic counter '__n__'. This causes all generated topics to merge. Do you want to use it?", "Missing topic counter part", WandoraOptionPane.WARNING_MESSAGE);
if(a != WandoraOptionPane.YES_OPTION) globalBasenamePattern = null;
}
}
connectWithWandoraClass = "true".equalsIgnoreCase(values.get("Connect topics with Wandora class"));
}
catch(Exception e) {
log(e);
}
ArrayList<Cylinder> cylinders = new ArrayList<>();
int progress = 0;
int width = 0;
int height = 0;
boolean toggleToroid = false;
try {
toggleToroid = "true".equals(values.get("Toroid"));
width = Integer.parseInt(values.get("Width of cylinder"));
height = Integer.parseInt(values.get("Height of cylinder"));
if ("true".equals(values.get("Create a cylinder with square tiling"))) {
cylinders.add(new SquareCylinder(width, height, toggleToroid));
}
if ("true".equals(values.get("Create a cylinder with triangular tiling"))) {
cylinders.add(new TriangularCylinder(width, height, toggleToroid));
}
if ("true".equals(values.get("Create a cylinder with hexagonal tiling"))) {
cylinders.add(new HexagonalCylinder(width, height, toggleToroid));
}
}
catch (Exception e) {
singleLog(e);
return;
}
setDefaultLogger();
setLogTitle("Cylinder graph generator");
for (Cylinder cylinder : cylinders) {
Collection<T2<String,String>> edges = cylinder.getEdges();
log("Creating " + cylinder.getName() + " graph");
Topic atype = cylinder.getAssociationTypeTopic(topicmap,values);
Topic role1 = cylinder.getRole1Topic(topicmap,values);
Topic role2 = cylinder.getRole2Topic(topicmap,values);
Association a = null;
Topic node1 = null;
Topic node2 = null;
if (edges.size() > 0) {
setProgressMax(edges.size());
for (T2<String,String> edge : edges) {
if (edge != null) {
node1 = cylinder.getVertexTopic(edge.e1, topicmap, values);
node2 = cylinder.getVertexTopic(edge.e2, topicmap, values);
if (node1 != null && node2 != null) {
a = topicmap.createAssociation(atype);
a.addPlayer(node1, role1);
a.addPlayer(node2, role2);
}
setProgress(progress++);
}
}
if(connectWithWandoraClass) {
log("You'll find created topics under the '"+cylinder.getName()+" graph' topic.");
}
else {
String searchWord = cylinder.getName();
if(globalBasenamePattern != null && globalBasenamePattern.trim().length() > 0) {
searchWord = globalBasenamePattern.replaceAll("__n__", "");
searchWord = searchWord.trim();
}
log("You'll find created topics by searching with a '"+searchWord+"'.");
}
}
else {
log("Number of cylinder edges is zero. Cylinder has no vertices neithers.");
}
}
if(cylinders.isEmpty()) {
log("No cylinder selected.");
}
log("Ready.");
setState(WAIT);
}
// -------------------------------------------------------------------------
// ----------------------------------------------------------- CYLINDERS ---
// -------------------------------------------------------------------------
public interface Cylinder {
public String getSIPrefix();
public String getName();
public int getSize();
public Collection<T2<String,String>> getEdges();
public Collection<String> getVertices();
public Topic getVertexTopic(String vertex, TopicMap topicmap, Map<String,String> optionsValues);
public Topic getAssociationTypeTopic(TopicMap topicmap, Map<String,String> optionsValues);
public Topic getRole1Topic(TopicMap topicmap, Map<String,String> optionsValues);
public Topic getRole2Topic(TopicMap topicmap, Map<String,String> optionsValues);
}
public abstract class AbstractCylinder implements Cylinder {
@Override
public Topic getVertexTopic(String vertex, TopicMap topicmap, Map<String,String> optionsValues) {
String newBasename = getName()+" vertex "+vertex;
if(globalBasenamePattern != null && globalBasenamePattern.trim().length() > 0) {
newBasename = globalBasenamePattern.replaceAll("__n__", vertex);
}
String newSubjectIdentifier = getSIPrefix()+"vertex-"+vertex;
if(globalSiPattern != null && globalSiPattern.trim().length() > 0) {
newSubjectIdentifier = globalSiPattern.replaceAll("__n__", vertex);
}
Topic t = getOrCreateTopic(topicmap, newSubjectIdentifier, newBasename);
if(connectWithWandoraClass) {
try {
Topic graphTopic = getOrCreateTopic(topicmap, getSIPrefix(), getName()+" graph");
Topic wandoraClass = getOrCreateTopic(topicmap, TMBox.WANDORACLASS_SI);
makeSuperclassSubclass(topicmap, wandoraClass, graphTopic);
t.addType(graphTopic);
}
catch(Exception e) {
e.printStackTrace();
}
}
return t;
}
@Override
public Topic getAssociationTypeTopic(TopicMap topicmap, Map<String,String> optionsValues) {
String atypeStr = null;
Topic atype = null;
if(optionsValues != null) {
atypeStr = optionsValues.get("Association type topic");
}
if(atypeStr != null) {
try {
atype = topicmap.getTopic(atypeStr);
}
catch(Exception e) {
e.printStackTrace();
}
}
if(atype == null) {
atype = getOrCreateTopic(topicmap, getSIPrefix()+"edge", getName()+" edge");
}
return atype;
}
@Override
public Topic getRole1Topic(TopicMap topicmap, Map<String,String> optionsValues) {
String roleStr = null;
Topic role = null;
if(optionsValues != null) {
roleStr = optionsValues.get("First role topic");
}
if(roleStr != null) {
try {
role = topicmap.getTopic(roleStr);
}
catch(Exception e) {
e.printStackTrace();
}
}
if(role == null) {
role = getOrCreateTopic(topicmap, getSIPrefix()+"role-1", "role 1");
}
return role;
}
@Override
public Topic getRole2Topic(TopicMap topicmap, Map<String,String> optionsValues) {
String roleStr = null;
Topic role = null;
if(optionsValues != null) {
roleStr = optionsValues.get("Second role topic");
}
if(roleStr != null) {
try {
role = topicmap.getTopic(roleStr);
}
catch(Exception e) {
e.printStackTrace();
}
}
if(role == null) {
role = getOrCreateTopic(topicmap, getSIPrefix()+"role-2", "role 2");
}
return role;
}
}
// -------------------------------------------------------------------------
public class SquareCylinder extends AbstractCylinder implements Cylinder {
private int size = 0;
private int width = 0;
private int height = 0;
private boolean isToroid = false;
public SquareCylinder(int w, int h, boolean toroid) {
this.width = w;
this.height = h;
this.size = w * h;
this.isToroid = toroid;
}
@Override
public String getSIPrefix() {
return "http://wandora.org/si/cylinder/square/";
}
@Override
public String getName() {
return "Square-cylinder";
}
@Override
public int getSize() {
return size;
}
@Override
public Collection<T2<String,String>> getEdges() {
ArrayList<T2<String,String>> edges = new ArrayList<>();
for (int h = 0; h < height; h++) {
for (int w = 0; w < width; w++) {
int ww = (w == width - 1) ? 0 : (w + 1);
int hh = (h == height - 1 && isToroid) ? 0 : (h + 1);
edges.add(new T2<String,String>(h + "-" + w, h + "-" + ww));
edges.add(new T2<String,String>((h + "-" + ww), hh + "-" + ww));
}
}
if (!this.isToroid) {
for (int w = 0; w < width; w++) {
int ww = (w != width - 1) ? (w + 1) : 0;
edges.add(new T2<String,String>(height + "-" + w, height + "-" + ww));
}
}
return edges;
}
@Override
public Collection<String> getVertices() {
ArrayList<String> vertices = new ArrayList<>();
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
vertices.add(x + "-" + y);
}
}
return vertices;
}
}
// -------------------------------------------------------------------------
public class TriangularCylinder extends AbstractCylinder implements Cylinder {
private int depth = 0;
private int width = 0;
private boolean isToroid = false;
public TriangularCylinder(int w, int d, boolean toroid) {
this.width = w;
this.depth = d;
this.isToroid = toroid;
}
@Override
public String getSIPrefix() {
return "http://wandora.org/si/cylinder/triangular/";
}
@Override
public String getName() {
return "Triangular-cylinder";
}
@Override
public int getSize() {
int size = 0;
for (int d = 0; d < depth; d++) {
for (int f = 0; f < d; f++) {
size++;
}
}
return size;
}
@Override
public Collection<T2<String,String>> getEdges() {
ArrayList<T2<String,String>> edges = new ArrayList<>();
for (int d = 0; d < depth; d++) {
for (int w = 0; w < width; w++) {
int ww = (w == width - 1) ? 0 : (w + 1);
int dd = (d == depth - 1 && this.isToroid) ? 0 : (d + 1);
edges.add(new T2<String,String>(d + "-" + w, d + "-" + ww));
edges.add(new T2<String,String>(d + "-" + w, dd + "-" + ww));
edges.add(new T2<String,String>(d + "-" + ww, dd + "-" + ww));
}
}
if (!this.isToroid) {
for (int w = 0; w < width; w++) {
int ww = (w != width - 1) ? (w + 1) : 0;
edges.add(new T2<String,String>(depth + "-" + w, depth + "-" + ww));
}
}
return edges;
}
@Override
public Collection<String> getVertices() {
ArrayList<String> vertices = new ArrayList<>();
for (int d = 0; d < depth; d++) {
for (int f = 0; f < d; f++) {
vertices.add(d + "-" + f);
}
}
return vertices;
}
}
// -------------------------------------------------------------------------
public class HexagonalCylinder extends AbstractCylinder implements Cylinder {
private int depth = 0;
private int width = 0;
private boolean isToroid = false;
public HexagonalCylinder(int w, int d, boolean toroid) {
this.width = w;
this.depth = d;
this.isToroid = toroid;
}
@Override
public String getSIPrefix() {
return "http://wandora.org/si/cylinder/hexagonal/";
}
@Override
public String getName() {
return "Hexagonal-cylinder";
}
@Override
public int getSize() {
int size = 0;
for (int d = 0; d < depth; d++) {
for (int f = 0; f < d; f++) {
size++;
}
}
return size;
}
@Override
public Collection<T2<String,String>> getEdges() {
ArrayList<T2<String,String>> edges = new ArrayList<>();
String nc = null;
String n1 = null;
String n2 = null;
String n3 = null;
for (int d = 0; d < depth; d++) {
for (int w = 0; w < width; w++) {
nc = d + "-" + w + "-c";
n1 = (d == depth -1 && this.isToroid) ? 0 + "-" + w : (d+1) + "-" + w ;
n2 = d + "-" + w;
edges.add(new T2<String,String>(nc, n1));
edges.add(new T2<String,String>(nc, n2));
n3 = (w == width - 1) ? d + "-" + 0 : d + "-" + (w + 1);
edges.add(new T2<String,String>(nc, n3));
}
}
if (!this.isToroid) {
for (int w = 0; w < width; w++) {
nc = depth + "-" + w + "-c";
n1 = depth + "-" + w;
n2 = (w == width -1 ) ? depth + "-" + 0 : depth + "-" + (w + 1);
edges.add(new T2<String,String>(nc, n1));
edges.add(new T2<String,String>(nc, n2));
}
}
return edges;
}
@Override
public Collection<String> getVertices() {
HashSet<String> verticesSet = new LinkedHashSet<>();
for (int d = 0; d < depth; d++) {
for (int f = 0; f < d + 1; f++) {
verticesSet.add(d + "-" + f + "-c");
verticesSet.add(d + "-" + f);
verticesSet.add(d + "-" + (f + 1));
if (d == 0) {
verticesSet.add(d + "-" + f + "-t");
} else {
verticesSet.add((d - 1) + "-" + f);
}
}
}
return verticesSet;
}
}
}
| 21,316 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
HyperCubeGenerator.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/generators/HyperCubeGenerator.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* HyperCubeGenerator.java
*
* Created on 2008-09-19, 16:28
*
*/
package org.wandora.application.tools.generators;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.WandoraOptionPane;
import org.wandora.application.tools.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.Tuples.T2;
import org.wandora.utils.swing.GuiTools;
/**
*
* @author akivela
*/
public class HyperCubeGenerator extends AbstractGenerator implements WandoraTool {
private static final long serialVersionUID = 1L;
public static String HYPERCUBE_GRAPH_SI = "http://wandora.org/si/hypercube/";
public static String siPattern = "http://wandora.org/si/hypercube/vertex/__n__";
public static String basenamePattern = "Hypercube vertex __n__";
public static boolean connectWithWandoraClass = true;
public static int n = 4;
/** Creates a new instance of HyperCubeGenerator */
public HyperCubeGenerator() {
}
@Override
public String getName() {
return "Hypercube graph generator";
}
@Override
public String getDescription() {
return "Hypercube graph generator creates hypercube graphs with topic map structures.";
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
TopicMap topicmap = solveContextTopicMap(wandora, context);
GenericOptionsDialog god=new GenericOptionsDialog(wandora,
"Hypercube graph generator",
"Hypercube graph generator creates hypercube graphs with topic map structures. "+
"Topics represent hypercube vertices. Associations represent hypercube edges. In a "+
"hypercube each vertex is connected with other vertices. Number of connections per vertex "+
"is equal to the dimension of the hypercube. For example, in a three dimensional hypercube "+
"each vertex is connected with three other vertices.",
true,new String[][]{
new String[]{"Dimension of hypercube","string",""+n},
new String[]{"---1","separator"},
new String[]{"Subject identifier pattern","string",siPattern,"Subject identifier patterns for the created node topics. Part __n__ in patterns is replaced with node identifier."},
new String[]{"Basename pattern","string",basenamePattern,"Basename patterns for the created node topics. Part __n__ in patterns is replaced with node identifier."},
new String[]{"Connect topics with Wandora class","boolean", connectWithWandoraClass ? "true" : "false","Create additional topics and associations that connect created topics with the Wandora class." },
new String[]{"Association type topic","topic",null,"Optional association type for graph edges."},
new String[]{"First role topic","topic",null,"Optional role topic for graph edges."},
new String[]{"Second role topic","topic",null,"Optional role topic for graph edges."},
},wandora);
god.setSize(700, 420);
GuiTools.centerWindow(god,wandora);
god.setVisible(true);
if(god.wasCancelled()) return;
Map<String,String> values=god.getValues();
int progress = 0;
try {
n = Integer.parseInt(values.get("Dimension of hypercube"));
}
catch(Exception e) {
singleLog("Parse error. Hypercube dimension should be an integer number. Cancelling.", e);
return;
}
try {
siPattern = values.get("Subject identifier pattern");
if(!siPattern.contains("__n__")) {
int a = WandoraOptionPane.showConfirmDialog(wandora, "Subject identifier pattern doesn't contain part for topic counter '__n__'. This causes all generated topics to merge. Do you want to continue?", "Missing topic counter part", WandoraOptionPane.WARNING_MESSAGE);
if(a != WandoraOptionPane.YES_OPTION) return;
}
basenamePattern = values.get("Basename pattern");
if(!basenamePattern.contains("__n__")) {
int a = WandoraOptionPane.showConfirmDialog(wandora, "Basename pattern doesn't contain part for topic counter '__n__'. This causes all generated topics to merge. Do you want to continue?", "Missing topic counter part", WandoraOptionPane.WARNING_MESSAGE);
if(a != WandoraOptionPane.YES_OPTION) return;
}
connectWithWandoraClass = "true".equalsIgnoreCase(values.get("Connect topics with Wandora class"));
}
catch(Exception e) {
singleLog(e);
return;
}
Topic atype = topicmap.getTopic(values.get("Association type topic"));
if(atype == null || atype.isRemoved()) {
atype = getOrCreateTopic(topicmap, HYPERCUBE_GRAPH_SI+"/"+"association-type", "Hypercube edge");
}
Topic role1 = topicmap.getTopic(values.get("First role topic"));
if(role1 == null || role1.isRemoved()) {
role1 = getOrCreateTopic(topicmap, HYPERCUBE_GRAPH_SI+"/"+"role-1", "Hypercube edge role 1");
}
Topic role2 = topicmap.getTopic(values.get("Second role topic"));
if(role2 == null || role2.isRemoved()) {
role2 = getOrCreateTopic(topicmap, HYPERCUBE_GRAPH_SI+"/"+"role-2", "Hypercube edge role 2");
}
if(role1.mergesWithTopic(role2)) {
int a = WandoraOptionPane.showConfirmDialog(wandora, "Role topics are same. This causes associations to be unary instead of binary. Do you want to continue?", "Role topics are same", WandoraOptionPane.WARNING_MESSAGE);
if(a != WandoraOptionPane.YES_OPTION) {
return;
}
}
setDefaultLogger();
setLogTitle("Hypercube graph generator");
log("Creating hypercube graph.");
HyperCube hypercube = new HyperCube(n);
Collection<T2<String,String>> edges = hypercube.getEdges();
Association a = null;
Topic node1 = null;
Topic node2 = null;
long graphIdentifier = System.currentTimeMillis();
if(!edges.isEmpty()) {
setProgressMax(edges.size());
for(T2<String,String> edge : edges) {
if(edge != null) {
node1 = getOrCreateTopic(topicmap, edge.e1, graphIdentifier);
node2 = getOrCreateTopic(topicmap, edge.e2, graphIdentifier);
if(node1 != null && node2 != null) {
a = topicmap.createAssociation(atype);
a.addPlayer(node1, role1);
a.addPlayer(node2, role2);
}
setProgress(progress++);
}
}
}
if(connectWithWandoraClass) {
log("You'll find created topics and associations under the 'Hypercube graph' topic.");
}
else {
String searchWord = basenamePattern.replaceAll("__n__", "");
searchWord = searchWord.trim();
log("You'll find created topics and associations by searching with a '"+searchWord+"'.");
}
log("Ready.");
setState(WAIT);
}
private Topic getOrCreateTopic(TopicMap tm, String vertexIdentifier, long graphIdentifier) {
String newBasename = basenamePattern.replaceAll("__n__", vertexIdentifier);
String newSubjectIdentifier = siPattern.replaceAll("__n__", vertexIdentifier);
Topic t = getOrCreateTopic(tm, newSubjectIdentifier, newBasename);
if(connectWithWandoraClass) {
try {
Topic graphTopic = getOrCreateTopic(tm, HYPERCUBE_GRAPH_SI, "Hypercube graph");
Topic wandoraClass = getOrCreateTopic(tm, TMBox.WANDORACLASS_SI);
makeSuperclassSubclass(tm, wandoraClass, graphTopic);
Topic graphInstanceTopic = getOrCreateTopic(tm, HYPERCUBE_GRAPH_SI+"/"+graphIdentifier, "Hypercube graph "+graphIdentifier, graphTopic);
graphInstanceTopic.addType(graphTopic);
t.addType(graphInstanceTopic);
}
catch(Exception e) {
e.printStackTrace();
}
}
return t;
}
// -------------------------------------------------------------------------
private class HyperCube {
private int dimension = 0;
private HyperCube parent = null;
public HyperCube(int d) {
this.dimension = d;
if(d > 0) {
this.parent = new HyperCube(d-1);
}
}
public int getDimension() {
return dimension;
}
public Collection<T2<String,String>> getEdges() {
ArrayList<T2<String,String>> edges = new ArrayList<T2<String,String>>();
if(this.dimension == 0) {}
else if(this.dimension == 1) {
edges.add(new T2<String,String>("0", "0-1"));
}
else {
if(parent != null) {
Collection<T2<String,String>> parentEdges = parent.getEdges();
edges.addAll(parentEdges);
for(T2<String,String> edge : parentEdges) {
if(edge != null) {
edges.add( new T2<String,String>( edge.e1+"-"+this.dimension, edge.e2+"-"+this.dimension ));
}
}
Collection<String> parentVertices = parent.getVertices();
for(String vertex : parentVertices) {
if(vertex != null) {
edges.add( new T2<String,String>(vertex+"-"+this.dimension, vertex) );
}
}
//System.out.println("edges: dim="+this.dimension+", edges="+edges.size());
}
}
return edges;
}
public Collection<String> getVertices() {
ArrayList<String> vertices = new ArrayList<String>();
if(this.dimension == 0) {
vertices.add( "0" );
}
else {
if(parent != null) {
Collection<String> parentVertices = parent.getVertices();
vertices.addAll(parentVertices);
for(String vertex : parentVertices) {
vertices.add(vertex+"-"+this.dimension);
}
//System.out.println("dim="+this.dimension+", vertices="+vertices.size());
}
}
return vertices;
}
}
}
| 12,165 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
LatticeGenerator.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/generators/LatticeGenerator.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* TreeGraphGenerator.java
*
* Created on 10.5.2012
*
*/
package org.wandora.application.tools.generators;
import java.util.Map;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.WandoraOptionPane;
import org.wandora.application.tools.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.swing.GuiTools;
/**
*
* @author Eero, akivela
*/
public class LatticeGenerator extends AbstractGenerator implements WandoraTool {
private static final long serialVersionUID = 1L;
public static String LATTICE_GRAPH_SI = "http://wandora.org/si/lattice/";
public static String siPattern = "http://wandora.org/si/lattice/vertex/__n__";
public static String basenamePattern = "Lattice vertex __n__";
public static boolean connectWithWandoraClass = true;
public int[] dimensions = new int[] { 4,4,4 };
public int[] offsets = new int[] { 0,0,0 };
@Override
public String getName() {
return "Lattice graph generator";
}
@Override
public String getDescription() {
return "Generates a lattice graph topic map where topics represents lattice vertices and associations "+
"lattice edges.";
}
@Override
public void execute (Wandora wandora, Context context) throws TopicMapException {
TopicMap topicmap = solveContextTopicMap(wandora, context);
GenericOptionsDialog god = new GenericOptionsDialog(
wandora,
"Lattice graph generator",
"A lattice graph is a square grid graph where topics represent graph vertices and associations "+
"graph edges. Generator creates lattices in three dimensional and finite size. "+
"Each vertex has a 3D coordinate in the lattice. "+
"Offsets are numbers that move the initial 3D coordinate of vertices.",
true,
new String[][]{
new String[]{"Dimension 1 size", "string", ""+dimensions[0]},
new String[]{"Dimension 2 size", "string", ""+dimensions[1]},
new String[]{"Dimension 3 size", "string", ""+dimensions[2]},
new String[]{"Offset for dimension 1", "string", ""+offsets[0]},
new String[]{"Offset for dimension 2", "string", ""+offsets[0]},
new String[]{"Offset for dimension 3", "string", ""+offsets[0]},
new String[]{"---1", "separator"},
new String[]{"Subject identifier pattern", "string",siPattern, "Subject identifier patterns for the created node topics. Part __n__ in patterns is replaced with node identifier."},
new String[]{"Basename pattern", "string",basenamePattern, "Basename patterns for the created node topics. Part __n__ in patterns is replaced with node identifier."},
new String[]{"Connect topics with Wandora class", "boolean", connectWithWandoraClass ? "true" : "false", "Create additional topics and associations that connect created topics with the Wandora class." },
new String[]{"Association type topic", "topic", null, "Optional association type for graph edges."},
new String[]{"First role topic", "topic", null, "Optional role topic for graph edges."},
new String[]{"Second role topic", "topic", null, "Optional role topic for graph edges."},
},
wandora
);
god.setSize(700, 500);
GuiTools.centerWindow(god,wandora);
god.setVisible(true);
if(god.wasCancelled()) return;
Map<String,String> values = god.getValues();
try {
dimensions[0] = Integer.parseInt(values.get("Dimension 1 size"));
dimensions[1] = Integer.parseInt(values.get("Dimension 2 size"));
dimensions[2] = Integer.parseInt(values.get("Dimension 3 size"));
offsets[0] = Integer.parseInt(values.get("Offset for dimension 1"));
offsets[1] = Integer.parseInt(values.get("Offset for dimension 2"));
offsets[2] = Integer.parseInt(values.get("Offset for dimension 3"));
}
catch(NumberFormatException nfe) {
singleLog("Parse error. Hypercube dimensions and offsets should be integer numbers. Cancelling.", nfe);
return;
}
catch(Exception e) {
singleLog(e);
return;
}
try {
siPattern = values.get("Subject identifier pattern");
if(!siPattern.contains("__n__")) {
int a = WandoraOptionPane.showConfirmDialog(wandora, "Subject identifier pattern doesn't contain part for topic counter '__n__'. This causes all generated topics to merge. Do you want to continue?", "Missing topic counter part", WandoraOptionPane.WARNING_MESSAGE);
if(a != WandoraOptionPane.YES_OPTION) return;
}
basenamePattern = values.get("Basename pattern");
if(!basenamePattern.contains("__n__")) {
int a = WandoraOptionPane.showConfirmDialog(wandora, "Basename pattern doesn't contain part for topic counter '__n__'. This causes all generated topics to merge. Do you want to continue?", "Missing topic counter part", WandoraOptionPane.WARNING_MESSAGE);
if(a != WandoraOptionPane.YES_OPTION) return;
}
connectWithWandoraClass = "true".equalsIgnoreCase(values.get("Connect topics with Wandora class"));
}
catch(Exception e) {
singleLog(e);
return;
}
Topic aType = topicmap.getTopic(values.get("Association type topic"));
if(aType == null || aType.isRemoved()) {
aType = getOrCreateTopic(topicmap, LATTICE_GRAPH_SI+"/"+"association-type", "Lattice association");
}
Topic rType1 = topicmap.getTopic(values.get("First role topic"));
if(rType1 == null || rType1.isRemoved()) {
rType1 = getOrCreateTopic(topicmap, LATTICE_GRAPH_SI+"/"+"role-1", "Lattice role 1");
}
Topic rType2 = topicmap.getTopic(values.get("Second role topic"));
if(rType2 == null || rType2.isRemoved()) {
rType2 = getOrCreateTopic(topicmap, LATTICE_GRAPH_SI+"/"+"role-2", "Lattice role 2");
}
if(rType1.mergesWithTopic(rType2)) {
int a = WandoraOptionPane.showConfirmDialog(wandora, "Role topics are same. This causes associations to be unary instead of binary. Do you want to continue?", "Role topics are same", WandoraOptionPane.WARNING_MESSAGE);
if(a != WandoraOptionPane.YES_OPTION) {
return;
}
}
setDefaultLogger();
setLogTitle("Lattice graph generator");
for(int dimension : dimensions) {
if( dimension < 1) {
log("Dimension " + dimension + " is out of bounds. Using default value (1).");
dimension = 1;
}
}
for(int offset : offsets) {
if( offset < 0) {
log("Offset " + offset + " is out of bounds. Using default value (0).");
offset = 0;
}
}
long graphIdentifier = System.currentTimeMillis();
log("Creating lattice graph.");
//HashMap<String,Topic> topics = new HashMap();
Topic[][][] topics;
topics = new Topic[dimensions[0]+offsets[0]][dimensions[1]+offsets[1]][dimensions[2]+offsets[2]];
Association a;
for(int i = offsets[0]; i < dimensions[0]+offsets[0] && !forceStop(); i++){
for(int j = offsets[1]; j < dimensions[1]+offsets[1] && !forceStop(); j++){
for(int k = offsets[2]; k < dimensions[2]+offsets[2] && !forceStop(); k++){
String id = i + "-" + j + "-" + k;
String newBasename = basenamePattern.replaceAll("__n__", id);
String newSubjectIdentifier = siPattern.replaceAll("__n__", id);
Topic curTopic = getOrCreateTopic(topicmap, newSubjectIdentifier, newBasename);
connectWithWandoraClass(curTopic, topicmap, graphIdentifier);
topics[i][j][k] = curTopic;
if( i > 0 && topics[i-1][j][k] != null ){
Topic prevTopic = topics[i-1][j][k];
a = topicmap.createAssociation(aType);
a.addPlayer(prevTopic,rType1);
a.addPlayer(curTopic,rType2);
}
if( i < dimensions[0]+offsets[0]-1 && topics[i+1][j][k] != null ){
Topic nextTopic = topics[i+1][j][k];
a = topicmap.createAssociation(aType);
a.addPlayer(nextTopic,rType1);
a.addPlayer(curTopic,rType2);
}
if( j > 0 && topics[i][j-1][k] != null ){
Topic prevTopic = topics[i][j-1][k];
a = topicmap.createAssociation(aType);
a.addPlayer(prevTopic,rType1);
a.addPlayer(curTopic,rType2);
}
if( j < dimensions[1]+offsets[1]-1 && topics[i][j+1][k] != null ){
Topic nextTopic = topics[i][j+1][k];
a = topicmap.createAssociation(aType);
a.addPlayer(nextTopic,rType1);
a.addPlayer(curTopic,rType2);
}
if( k > 0 && topics[i][j][k-1] != null ){
Topic prevTopic = topics[i][j][k-1];
a = topicmap.createAssociation(aType);
a.addPlayer(prevTopic,rType1);
a.addPlayer(curTopic,rType2);
}
if( k < dimensions[2]+offsets[2]-1 && topics[i][j][k+1] != null ){
Topic nextTopic = topics[i][j][k+1];
a = topicmap.createAssociation(aType);
a.addPlayer(nextTopic,rType1);
a.addPlayer(curTopic,rType2);
}
}
}
}
if(connectWithWandoraClass) {
log("You'll find created topics and associations under the 'Lattice graph' topic.");
}
else {
String searchWord = basenamePattern.replaceAll("__n__", "");
searchWord = searchWord.trim();
log("You'll find created topics and associations by searching '"+searchWord+"'.");
}
log("Ready.");
setState(WAIT);
}
private void connectWithWandoraClass(Topic t, TopicMap tm, long graphIdentifier) {
if(connectWithWandoraClass) {
try {
Topic treeGraphTopic = getOrCreateTopic(tm, LATTICE_GRAPH_SI, "Lattice graph");
Topic wandoraClass = getOrCreateTopic(tm, TMBox.WANDORACLASS_SI);
makeSuperclassSubclass(tm, wandoraClass, treeGraphTopic);
Topic treeGraphInstanceTopic = getOrCreateTopic(tm, LATTICE_GRAPH_SI+"/"+graphIdentifier, "Lattice graph "+graphIdentifier, treeGraphTopic);
treeGraphInstanceTopic.addType(treeGraphTopic);
t.addType(treeGraphInstanceTopic);
}
catch(Exception e) {
e.printStackTrace();
}
}
}
}
| 12,691 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
FullyConnectedGraphGenerator.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/generators/FullyConnectedGraphGenerator.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* FullyConnectedGraphGenerator.java
*
* Created on 31. toukokuuta 2007, 11:33
*
*/
package org.wandora.application.tools.generators;
import java.util.Map;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.WandoraOptionPane;
import org.wandora.application.tools.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.swing.GuiTools;
/**
*
* @author akivela
*/
public class FullyConnectedGraphGenerator extends AbstractGenerator implements WandoraTool {
private static final long serialVersionUID = 1L;
public static String CONNECTED_GRAPH_SI = "http://wandora.org/si/connected-graph";
public static String siPattern = "http://wandora.org/si/connected-graph/node/__n__";
public static String basenamePattern = "Connected graph node __n__";
public static boolean connectWithWandoraClass = true;
public static int topicCounterOffset = 0;
/** Creates a new instance of FullyConnectedGraphGenerator */
public FullyConnectedGraphGenerator() {
}
@Override
public String getName() {
return "Fully connected graph generator";
}
@Override
public String getDescription() {
return "Generates a fully connected graph topic map.";
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
TopicMap topicmap = solveContextTopicMap(wandora, context);
GenericOptionsDialog god=new GenericOptionsDialog(wandora,
"Fully connected graph generator",
"Fully connected graph generator creates a subgraph of topics where every created topic is connected with every other created topic.",
true,new String[][]{
new String[]{"Number of connected topics","string"},
new String[]{"Directional associations","boolean","false","Create 2 associations per topic pair? Created association differ in role order."},
new String[]{"---1","separator"},
new String[]{"Subject identifier pattern","string",siPattern,"Subject identifier patterns for the created node topics. Part __n__ in patterns is replaced with node counter."},
new String[]{"Basename pattern","string",basenamePattern,"Basename patterns for the created node topics. Part __n__ in patterns is replaced with node counter."},
new String[]{"Node counter offset","string",""+topicCounterOffset,"What is the number of first generated topic node."},
new String[]{"Connect topics with Wandora class","boolean", connectWithWandoraClass ? "true" : "false","Create additional topics and associations that connect created topics with the Wandora class." },
new String[]{"Association type topic","topic",null,"Optional association type for random graph edges."},
new String[]{"First role topic","topic",null,"Optional role topic for graph edges."},
new String[]{"Second role topic","topic",null,"Optional role topic for graph edges."},
},wandora);
god.setSize(700, 420);
GuiTools.centerWindow(god,wandora);
god.setVisible(true);
if(god.wasCancelled()) return;
Map<String,String> values=god.getValues();
int n = 0;
boolean directional = false;
try {
n = Integer.parseInt(values.get("Number of connected topics"));
directional = Boolean.parseBoolean(values.get("Directional associations"));
}
catch(NumberFormatException nfe) {
singleLog("Parse error. Number of connected topics should be integer number.");
return;
}
catch(Exception e) {
singleLog(e);
return;
}
try {
siPattern = values.get("Subject identifier pattern");
if(!siPattern.contains("__n__")) {
int a = WandoraOptionPane.showConfirmDialog(wandora, "Subject identifier pattern doesn't contain part for topic counter '__n__'. This causes all generated topics to merge. Do you want to continue?", "Missing topic counter part", WandoraOptionPane.WARNING_MESSAGE);
if(a != WandoraOptionPane.YES_OPTION) return;
}
basenamePattern = values.get("Basename pattern");
if(!basenamePattern.contains("__n__")) {
int a = WandoraOptionPane.showConfirmDialog(wandora, "Basename pattern doesn't contain part for topic counter '__n__'. This causes all generated topics to merge. Do you want to continue?", "Missing topic counter part", WandoraOptionPane.WARNING_MESSAGE);
if(a != WandoraOptionPane.YES_OPTION) return;
}
connectWithWandoraClass = "true".equalsIgnoreCase(values.get("Connect topics with Wandora class"));
try {
topicCounterOffset = Integer.parseInt(values.get("Node counter offset"));
}
catch(NumberFormatException nfe) {
singleLog("Parse error. Initial node counter should be an integer number. Cancelling.");
return;
}
}
catch(Exception e) {
singleLog(e);
return;
}
Topic aType = topicmap.getTopic(values.get("Association type topic"));
if(aType == null || aType.isRemoved()) {
aType = getOrCreateTopic(topicmap, CONNECTED_GRAPH_SI+"/"+"association-type", "Connected graph association");
}
Topic role1 = topicmap.getTopic(values.get("First role topic"));
if(role1 == null || role1.isRemoved()) {
role1 = getOrCreateTopic(topicmap, CONNECTED_GRAPH_SI+"/"+"role-1", "Connected graph role 1");
}
Topic role2 = topicmap.getTopic(values.get("Second role topic"));
if(role2 == null || role2.isRemoved()) {
role2 = getOrCreateTopic(topicmap, CONNECTED_GRAPH_SI+"/"+"role-2", "Connected graph role 2");
}
if(role1.mergesWithTopic(role2)) {
int a = WandoraOptionPane.showConfirmDialog(wandora, "Role topics are same. This causes associations to be unary instead of binary. Do you want to continue?", "Role topics are same", WandoraOptionPane.WARNING_MESSAGE);
if(a != WandoraOptionPane.YES_OPTION) {
return;
}
}
setDefaultLogger();
setLogTitle("Fully connected graph generator");
log("Creating connected topics.");
Topic[] topics = new Topic[n];
long graphIdentifier = System.currentTimeMillis();
setProgressMax(n);
for(int i=0; i<n && !forceStop(); i++) {
setProgress(n);
int nodeCounter = topicCounterOffset+i;
topics[i] = getOrCreateTopic(topicmap, nodeCounter, graphIdentifier);
}
Topic t1 = null;
Topic t2 = null;
Association a = null;
log("Creating associations.");
setProgress(0);
setProgressMax(n*n);
int nk = 0;
for(int j=0; j<n && !forceStop(); j++) {
if(directional) nk = 0;
else nk = j;
t1 = topics[j];
for(int k=nk; k<n && !forceStop(); k++) {
t2 = topics[k];
a = topicmap.createAssociation(aType);
a.addPlayer(t1, role1);
a.addPlayer(t2, role2);
setProgress(j*n+k);
}
}
if(connectWithWandoraClass) {
log("You'll find created topics and associations under the 'Connected graph' topic.");
}
else {
String searchWord = basenamePattern.replaceAll("__n__", "");
searchWord = searchWord.trim();
log("You'll find created topics and associations by searching with a '"+searchWord+"'.");
}
log("Ready.");
setState(WAIT);
}
private Topic getOrCreateTopic(TopicMap topicmap, int topicIdentifier, long graphIdentifier) {
String newBasename = basenamePattern.replaceAll("__n__", ""+topicIdentifier);
String newSubjectIdentifier = siPattern.replaceAll("__n__", ""+topicIdentifier);
Topic t = getOrCreateTopic(topicmap, newSubjectIdentifier, newBasename);
if(connectWithWandoraClass) {
try {
Topic graphTopic = getOrCreateTopic(topicmap, CONNECTED_GRAPH_SI, "Connected graph");
Topic wandoraClass = getOrCreateTopic(topicmap, TMBox.WANDORACLASS_SI);
makeSuperclassSubclass(topicmap, wandoraClass, graphTopic);
Topic graphInstanceTopic = getOrCreateTopic(topicmap, CONNECTED_GRAPH_SI+"/"+graphIdentifier, "Connected graph "+graphIdentifier, graphTopic);
graphInstanceTopic.addType(graphTopic);
t.addType(graphInstanceTopic);
}
catch(Exception e) {
e.printStackTrace();
}
}
return t;
}
}
| 10,176 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TreeGraphGenerator.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/generators/TreeGraphGenerator.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* TreeGraphGenerator.java
*
* Created on 31. toukokuuta 2007, 13:21
*
*/
package org.wandora.application.tools.generators;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.WandoraOptionPane;
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.swing.GuiTools;
/**
*
* @author akivela
*/
public class TreeGraphGenerator extends AbstractGenerator implements WandoraTool {
private static final long serialVersionUID = 1L;
public static String TREE_GRAPH_SI = "http://wandora.org/si/tree-graph/";
public static String siPattern = "http://wandora.org/si/tree-graph/node/__n__";
public static String basenamePattern = "Tree graph node __n__";
public static boolean connectWithWandoraClass = true;
public static int d = 5; // Tree depth
public static int n = 2; // Number of child nodes
/** Creates a new instance of TreeGraphGenerator */
public TreeGraphGenerator() {
}
@Override
public String getName() {
return "Tree graph generator";
}
@Override
public String getDescription() {
return "Tree graph generator creates a set of topics and associations that resembles a graph tree where "+
"topics are graph nodes and associations graph edges between child and parent nodes. A tree has "+
"one root node. A tree node is connected with equal number of child nodes and one parent node.";
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
TopicMap topicmap = solveContextTopicMap(wandora, context);
GenericOptionsDialog god=new GenericOptionsDialog(wandora,
"Tree graph generator",
"Tree graph generator creates a set of topics and associations that resembles a graph tree where "+
"topics are graph nodes and associations graph edges between child and parent nodes. A tree has "+
"one root node. A tree node is connected with equal number of child nodes and one parent node."+
"Tree depth and number of child nodes should be positive integer numbers.",
true,new String[][]{
new String[]{"Tree depth","string",""+d},
new String[]{"Number of child nodes","string",""+n},
/* new String[]{"Add root additional branch","boolean","false","Should the root contain +1 edges?"}, */
new String[]{"---1","separator"},
new String[]{"Subject identifier pattern","string",siPattern,"Subject identifier patterns for the created node topics. Part __n__ in patterns is replaced with node identifier."},
new String[]{"Basename pattern","string",basenamePattern,"Basename patterns for the created node topics. Part __n__ in patterns is replaced with node identifier."},
new String[]{"Connect topics with Wandora class","boolean", connectWithWandoraClass ? "true" : "false","Create additional topics and associations that connect created topics with the Wandora class." },
new String[]{"Association type of tree edges","topic",null,"Optional association type for graph edges."},
new String[]{"Parent role in tree edges","topic",null,"Optional role topic for parent topics in tree graph."},
new String[]{"Child role in tree edges","topic",null,"Optional role topic for child topics in tree graph."},
},wandora);
god.setSize(700, 460);
GuiTools.centerWindow(god,wandora);
god.setVisible(true);
if(god.wasCancelled()) return;
Map<String,String> values=god.getValues();
boolean additionalRootBranch = false;
try {
d = Integer.parseInt(values.get("Tree depth"));
n = Integer.parseInt(values.get("Number of child nodes"));
// additionalRootBranch=Boolean.parseBoolean(values.get("Add root additional branch"));
}
catch(Exception e) {
singleLog("Parse error. Tree depth and number of child nodes should be integer numbers. Cancelling.", e);
return;
}
try {
siPattern = values.get("Subject identifier pattern");
if(!siPattern.contains("__n__")) {
int a = WandoraOptionPane.showConfirmDialog(wandora, "Subject identifier pattern doesn't contain part for topic counter '__n__'. This causes all generated topics to merge. Do you want to continue?", "Missing topic counter part", WandoraOptionPane.WARNING_MESSAGE);
if(a != WandoraOptionPane.YES_OPTION) return;
}
basenamePattern = values.get("Basename pattern");
if(!basenamePattern.contains("__n__")) {
int a = WandoraOptionPane.showConfirmDialog(wandora, "Basename pattern doesn't contain part for topic counter '__n__'. This causes all generated topics to merge. Do you want to continue?", "Missing topic counter part", WandoraOptionPane.WARNING_MESSAGE);
if(a != WandoraOptionPane.YES_OPTION) return;
}
connectWithWandoraClass = "true".equalsIgnoreCase(values.get("Connect topics with Wandora class"));
}
catch(Exception e) {
singleLog(e);
return;
}
Topic aType = topicmap.getTopic(values.get("Association type of tree edges"));
if(aType == null || aType.isRemoved()) {
aType = getOrCreateTopic(topicmap, TREE_GRAPH_SI+"/"+"association-type", "Tree graph association");
}
Topic parentT = topicmap.getTopic(values.get("Parent role in tree edges"));
if(parentT == null || parentT.isRemoved()) {
parentT = getOrCreateTopic(topicmap, TREE_GRAPH_SI+"/"+"parent", "Tree graph parent");
}
Topic childT = topicmap.getTopic(values.get("Child role in tree edges"));
if(childT == null || childT.isRemoved()) {
childT = getOrCreateTopic(topicmap, TREE_GRAPH_SI+"/"+"child", "Tree graph child");
}
if(parentT.mergesWithTopic(childT)) {
int a = WandoraOptionPane.showConfirmDialog(wandora, "Parent and child role topics are same. This causes associations to be unary instead of binary. Do you want to continue?", "Role topics are same", WandoraOptionPane.WARNING_MESSAGE);
if(a != WandoraOptionPane.YES_OPTION) {
return;
}
}
setDefaultLogger();
setLogTitle("Tree graph generator");
log("Creating tree graph");
ArrayList<Topic> topics = new ArrayList<Topic>();
ArrayList<Topic> nextTopics = null;
Topic parent = null;
Topic child = null;
int j = 0;
String id = "";
Association a = null;
long graphIdentifier = System.currentTimeMillis();
String newBasename = basenamePattern.replaceAll("__n__", "0");
String newSubjectIdentifier = siPattern.replaceAll("__n__", "0");
Topic rootTopic = getOrCreateTopic(topicmap, newSubjectIdentifier, newBasename);
connectWithWandoraClass(rootTopic, topicmap, graphIdentifier);
topics.add(rootTopic);
setProgressMax((int) (Math.pow(n, (d+1))-1)/(n-1));
int progress=0;
int nn = n;
for(int dep=1; dep<=d && !forceStop(); dep++) {
j = 0;
nextTopics = new ArrayList<Topic>();
if(additionalRootBranch && dep == 0) nn = n+1;
else nn = n;
Iterator<Topic> topicIterator = topics.iterator();
while( topicIterator.hasNext() && !forceStop() ) {
parent = topicIterator.next();
for(int k=0; k<nn && !forceStop(); k++) {
id = dep+"-"+j;
newBasename = basenamePattern.replaceAll("__n__", id);
newSubjectIdentifier = siPattern.replaceAll("__n__", id);
child = getOrCreateTopic(topicmap, newSubjectIdentifier, newBasename);
connectWithWandoraClass(child, topicmap, graphIdentifier);
nextTopics.add(child);
a = topicmap.createAssociation(aType);
a.addPlayer(parent, parentT);
a.addPlayer(child, childT);
setProgress(progress++);
j++;
}
}
topics = nextTopics;
}
if(connectWithWandoraClass) {
log("You'll find created topics and associations under the 'Tree graph' topic.");
}
else {
String searchWord = basenamePattern.replaceAll("__n__", "");
searchWord = searchWord.trim();
log("You'll find created topics and associations by searching '"+searchWord+"'.");
}
String rootTopicName = basenamePattern.replaceAll("__n__", "0");
log("Root of the tree is topic '"+rootTopicName+"'.");
log("Ready.");
setState(WAIT);
}
private void connectWithWandoraClass(Topic t, TopicMap tm, long graphIdentifier) {
if(connectWithWandoraClass) {
try {
Topic treeGraphTopic = getOrCreateTopic(tm, TREE_GRAPH_SI, "Tree graph");
Topic wandoraClass = getOrCreateTopic(tm, TMBox.WANDORACLASS_SI);
makeSuperclassSubclass(tm, wandoraClass, treeGraphTopic);
Topic treeGraphInstanceTopic = getOrCreateTopic(tm, TREE_GRAPH_SI+"/"+graphIdentifier, "Tree graph "+graphIdentifier, treeGraphTopic);
treeGraphInstanceTopic.addType(treeGraphTopic);
t.addType(treeGraphInstanceTopic);
}
catch(Exception e) {
e.printStackTrace();
}
}
}
}
| 11,158 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AbstractGenerator.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/generators/AbstractGenerator.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* AbstractGenerator.java
*
* Created on 1.6.2007, 10:39
*
*/
package org.wandora.application.tools.generators;
import javax.swing.Icon;
import org.wandora.application.WandoraTool;
import org.wandora.application.WandoraToolType;
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.XTMPSI;
/**
*
* @author akivela
*/
public abstract class AbstractGenerator extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
/** Creates a new instance of AbstractGenerator */
public AbstractGenerator() {
}
public Topic getOrCreateTopic(TopicMap map, String si) {
return getOrCreateTopic(map, si, null);
}
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;
}
public Topic getOrCreateTopic(TopicMap map, String si, String basename, Topic type) {
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);
if(type != null && type.isRemoved()) topic.addType(type);
}
}
catch(Exception e) {
log(e);
e.printStackTrace();
}
return topic;
}
public void makeSuperclassSubclass(TopicMap map, Topic superclass, Topic subclass) {
try {
if(map == null || superclass == null || subclass == null) return;
Topic associationType = getOrCreateTopic(map, XTMPSI.SUPERCLASS_SUBCLASS);
Topic superRole = getOrCreateTopic(map, XTMPSI.SUPERCLASS);
Topic subRole = getOrCreateTopic(map, XTMPSI.SUBCLASS);
if(associationType != null && superRole != null && subRole != null) {
Association a = map.createAssociation(associationType);
a.addPlayer(subclass, subRole);
a.addPlayer(superclass, superRole);
}
}
catch(Exception e) {
e.printStackTrace();
}
}
@Override
public WandoraToolType getType() {
return WandoraToolType.createGeneratorType();
}
@Override
public String getName() {
return "Abstract Generator Tool";
}
@Override
public Icon getIcon() {
return UIBox.getIcon("gui/icons/generate.png");
}
}
| 3,981 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
LSystemGraphGenerator.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/generators/LSystemGraphGenerator.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* LSystemGraphGenerator.java
*
* Created on 2008-09-20, 16:42
*
*/
package org.wandora.application.tools.generators;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.WandoraOptionPane;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.utils.Tuples.T2;
/**
*
* @author akivela
*/
public class LSystemGraphGenerator extends AbstractGenerator implements WandoraTool {
private static final long serialVersionUID = 1L;
public static String DEFAULT_SI_PREFIX = "http://wandora.org/si/l-system/";
public static String DEFAULT_ASSOCIATION_TYPE_SI = DEFAULT_SI_PREFIX+"association-type";
public static String DEFAULT_ROLE1_SI = DEFAULT_SI_PREFIX+"role-1";
public static String DEFAULT_ROLE2_SI = DEFAULT_SI_PREFIX+"role-2";
public String userSiPrefix = DEFAULT_SI_PREFIX;
public String currentColor = null;
private int topicCounter = 0;
private int associationCounter = 0;
private LSystemGraphGeneratorDialog sourceDialog = null;
/** Creates a new instance of LSystemGraphGenerator */
public LSystemGraphGenerator() {
}
@Override
public String getName() {
return "L-system graph generator";
}
@Override
public String getDescription() {
return "Generates topic maps with L-systems.";
}
@Override
public void execute(Wandora admin, Context context) throws TopicMapException {
TopicMap tm = solveContextTopicMap(admin, context);
topicCounter = 0;
associationCounter = 0;
if(sourceDialog == null) sourceDialog = new LSystemGraphGeneratorDialog(admin, this, true);
sourceDialog.setAccepted(false);
sourceDialog.setVisible(true);
if(!sourceDialog.wasAccepted()) return;
setDefaultLogger();
setLogTitle("L-system generator");
int sourceType = sourceDialog.getContentType();
if(sourceType == LSystemGraphGeneratorDialog.L_SYSTEM) {
String systemStr = sourceDialog.getContent();
int depth = sourceDialog.getDepth();
log("Starting L-system generation.");
userSiPrefix = DEFAULT_SI_PREFIX;
boolean initiatorFound = false;
String[] systemArray = systemStr.split("\n");
if(systemArray.length > 1) {
ArrayList<Rule> rules = new ArrayList<Rule>();
String str = null;
Word initiator = null;
for(int i=0; i<systemArray.length; i++) {
str = systemArray[i];
if(str != null) {
str = str.trim();
if(str.length() > 0) {
if(!str.startsWith("#")) {
if(!initiatorFound) {
initiator = new Word( str );
initiatorFound = true;
}
else {
String[] ruleStr = str.split("-->");
if(ruleStr.length == 2) {
ruleStr[0] = ruleStr[0].trim();
ruleStr[1] = ruleStr[1].trim();
if(ruleStr[0].length() > 0 && ruleStr[1].length() > 0) {
Word rule_pred = new Word( ruleStr[0] );
Word rule_succ = new Word( ruleStr[1] );
Rule rule = new Rule( rule_pred, rule_succ );
rules.add(rule);
}
}
}
}
else {
if(str.startsWith("#si-prefix:")) {
str = str.substring(11);
str = str.trim();
if(str.matches("[a-zA-Z0-9]+\\:\\/\\/.+?")) {
userSiPrefix = str;
}
}
}
}
}
}
if(initiator == null) {
log("Invalid L-system initiator given. First text line of L-system should contain initiator.");
}
else if(rules.isEmpty()) {
log("No L-system rules given. L-system rule format is 'predecessor' --> 'successor' ");
}
else {
boolean doit = true;
if(depth > 10) {
int a = WandoraOptionPane.showConfirmDialog(admin, "You have specified L-system iteration depth higher than 10. "+
"It is very likely L-system generates very high number of topics and associations. "+
"Would you like to continue anyway with given iteration depth?", "Iteration depth accepted?");
if(a == WandoraOptionPane.NO_OPTION) doit = false;
}
if(doit) {
log("Generating L-system string:");
LSystem lsystem = new LSystem(initiator, rules, depth );
log(lsystem.getState().toString());
LSystemParser lparser = new LSystemParser(this, lsystem.getState(), tm);
log("Parsing L-system results.");
lparser.parse();
}
}
}
else {
log("No L-system given.");
}
}
else if(sourceType == LSystemGraphGeneratorDialog.RAW_RESULT) {
LSystemParser lparser = new LSystemParser(this, new Word( sourceDialog.getContent() ), tm);
log("Parsing L-system string.");
lparser.parse();
}
if(forceStop()) log("User has stopped the L-system generator.");
log("Total "+topicCounter+" topics created.");
log("Total "+associationCounter+" associations created.");
log("Ready.");
setState(WAIT);
}
public Topic createNamedTopic(TopicMap tm, String name) throws Exception {
Topic t = tm.getTopicWithBaseName("topic "+name);
if(t == null) {
t = tm.createTopic();
t.addSubjectIdentifier(new Locator(userSiPrefix + "topic-" + name));
t.setBaseName("topic "+name);
}
if(currentColor != null) {
String typeSi = userSiPrefix+currentColor+"/topic-type";
Topic type = tm.getTopic(typeSi);
if(type == null) {
type = tm.createTopic();
type.addSubjectIdentifier(new Locator(typeSi));
type.setBaseName("type-"+currentColor);
}
t.addType(type);
}
return t;
}
public Topic createTopic(TopicMap tm) throws Exception {
Topic t = tm.getTopicWithBaseName("L-system topic "+topicCounter);
if(t == null) {
t = tm.createTopic();
t.addSubjectIdentifier(new Locator(userSiPrefix + "topic-" + topicCounter));
t.setBaseName("topic "+topicCounter);
}
if(currentColor != null) {
String typeSi = userSiPrefix+currentColor+"/topic-type";
Topic type = tm.getTopic(typeSi);
if(type == null) {
type = tm.createTopic();
type.addSubjectIdentifier(new Locator(typeSi));
type.setBaseName("L-system type-"+currentColor);
}
t.addType(type);
}
topicCounter++;
return t;
}
public Association createAssociation(TopicMap tm, Topic t1, Topic t2) throws Exception {
if(t1 == null || t2 == null) return null;
String actualAssociationTypeSi = userSiPrefix+"association-type";
String actualRole1Si = userSiPrefix+"role-1";
String actualRole2Si = userSiPrefix+"role-2";
String actualAssociationTypeName = "association-type";
String actualRole1Name = "role-1";
String actualRole2Name = "role-2";
if(currentColor != null) {
actualAssociationTypeSi = userSiPrefix+currentColor+"/association-type";
actualRole1Si = userSiPrefix+currentColor+"/role-1";
actualRole2Si = userSiPrefix+currentColor+"/role-2";
actualAssociationTypeName = "association-type ("+currentColor+")";
actualRole1Name = "role-1 ("+currentColor+")";
actualRole2Name = "role-2 ("+currentColor+")";
}
Topic atype = tm.getTopic(actualAssociationTypeSi);
if(atype == null) {
atype = tm.createTopic();
atype.addSubjectIdentifier(new Locator(actualAssociationTypeSi));
atype.setBaseName(actualAssociationTypeName);
}
Topic role1 = tm.getTopic(actualRole1Si);
if(role1 == null) {
role1 = tm.createTopic();
role1.addSubjectIdentifier(new Locator(actualRole1Si));
role1.setBaseName(actualRole1Name);
}
Topic role2 = tm.getTopic(actualRole2Si);
if(role2 == null) {
role2 = tm.createTopic();
role2.addSubjectIdentifier(new Locator(actualRole2Si));
role2.setBaseName(actualRole2Name);
}
//System.out.println("create association: "+atype);
//System.out.println(" with player: "+t1+" and role "+role1);
//System.out.println(" with player: "+t2+" and role "+role2);
Association a = tm.createAssociation(atype);
a.addPlayer(t1, role1);
a.addPlayer(t2, role2);
associationCounter++;
return a;
}
// -------------------------------------------------------------------------
// ------ LSystemParser -------------------------------------------------
// -------------------------------------------------------------------------
/**
* LSystemParser takes an <code>Alphabet</code> <code>Word</code> and parses
* it. Parser's vocabulary is
*
* <pre>
* a Create a topic and associate it with previous topic if such exists in current block.
* A-V Create named topic and associate it with previous topic if such exists in current block.
* eyuio Create colored (=typed) topic and associate it with previous one using colored association.
*
* [ Start parallel block
* ] Close parallel block
* ( Start sequential block
* ) Close sequential block
* { Start cycle block
* } Close cycle block
*
* - Substract topic counter by one
* + Add topic counter by one
* 0 Reset topic counter
*
* :c Set topic/association color c (global setting)
* :0 Reset topic/association color (global setting)
* </pre>
*
**/
private class LSystemParser {
private WandoraTool parent = null;
private Word input = null;
private int parsePoint = 0;
private Stack<T2<Alphabet,Stack<Topic>>> stackStack = new Stack<T2<Alphabet,Stack<Topic>>>();
private Stack<Topic> stack = new Stack<>();
private Alphabet defaultGuide = new Alphabet("("); // Sequential by default
private Alphabet guide = defaultGuide;
private TopicMap tm = null;
public LSystemParser(WandoraTool p, Word i, TopicMap topicMap) {
this.parsePoint = 0;
this.parent = p;
this.input = i;
this.tm = topicMap;
if(parent != null) {
parent.setProgressMax(input.size());
}
}
public void parse() {
if(input == null || tm == null) {
if(parent != null) parent.log("No input and/or topic map specified for the L-System parser!");
}
while(parsePoint < input.size() && !forceStop()) {
Alphabet a = input.get(parsePoint);
// ***** CREATE TOPIC *****
if(isCreateTopic(a)) {
try { parseTopic(); }
catch(Exception e) { log(e); }
}
// ***** COLORED TOPIC *****
else if(isColoredTopic(a)) {
try {
String tempColor = currentColor;
currentColor = a.getName();
parseTopic();
currentColor = tempColor;
}
catch(Exception e) {
log(e);
}
}
// ***** NAMED TOPIC *****
else if(isNamedTopic(a)) {
try { parseNamedTopic(a); }
catch(Exception e) { log(e); }
}
// ***** OPEN BLOCKS *****
else if(isCreateParallelBlock(a) || isCreateSequentialBlock(a) || isCreateCycleBlock(a)) {
//hlog("Creating Block");
stackStack.push(new T2<>(guide, stack));
stack = new Stack<>();
guide = a;
}
// ***** CLOSE BLOCKS *****
else if(isCloseParallelBlock(a) || isCloseSequentialBlock(a) || isCloseCycleBlock(a)) {
//hlog("Closing Block");
if(isCloseCycleBlock(a)) {
if(stack.size() > 2) {
try {
Topic first = (Topic) stack.get(0);
Topic last = (Topic) stack.get(stack.size()-1);
createAssociation(tm, last, first);
}
catch(Exception e) {
log(e);
}
}
}
if(!stackStack.empty()) {
T2<Alphabet,Stack<Topic>> guidedStack = stackStack.pop();
guide = guidedStack.e1;
stack = guidedStack.e2;
}
else {
stack = new Stack<>();
guide = defaultGuide;
}
}
// ***** SET ASSOCIATION COLOR *****
else if(isSetAssociationColor(a)) {
Alphabet associationColor = input.get(parsePoint+1);
if(isAssociationColor(associationColor)) {
String color = associationColor.getName();
if("0".equals(color)) {
currentColor = null;
}
else {
currentColor = color;
}
parsePoint++;
}
}
// ***** RESET TOPIC COUNTER *****
else if(isResetTopicCount(a)) {
topicCounter = 0;
}
// ***** SUBSTRACT TOPIC COUNTER *****
else if(isSubstractTopicCounter(a)) {
try {
topicCounter = topicCounter - 1;
}
catch(Exception e) {
log(e);
}
}
// ***** ADD TOPIC COUNTER *****
else if(isAddTopicCounter(a)) {
try {
topicCounter = topicCounter + 1;
}
catch(Exception e) {
log(e);
}
}
parsePoint++;
setProgress(parsePoint);
}
}
public void parseNamedTopic(Alphabet a) throws TopicMapException, Exception {
//hlog("Parser found named topic");
Topic t = createNamedTopic(tm, a.getName());
linkTopic(t);
}
public void parseTopic() throws TopicMapException, Exception {
//hlog("Parser found topic");
Topic t = createTopic(tm);
linkTopic(t);
}
public void linkTopic(Topic t) throws TopicMapException, Exception {
Topic oldTopic = null;
// **** HANDLE PARALLEL BLOCK ****
if(isCreateParallelBlock(guide)) {
if(!stackStack.empty()) {
int peekIndex = stackStack.size();
T2<Alphabet,Stack<Topic>> guidedStack = null;
do {
guidedStack = stackStack.get(--peekIndex);
} while(peekIndex > 0 && guidedStack.e2.empty());
if(!guidedStack.e2.empty()) {
oldTopic = (Topic) guidedStack.e2.peek();
}
}
}
// **** HANDLE SEQUENTIAL AND CYCLE BLOCK ****
else if(isCreateSequentialBlock(guide) || isCreateCycleBlock(guide)) {
if(!stack.empty()) {
oldTopic = (Topic) stack.peek();
}
else if(!stackStack.empty()) {
int peekIndex = stackStack.size();
T2<Alphabet,Stack<Topic>> guidedStack = null;
do {
guidedStack = stackStack.get(--peekIndex);
} while(peekIndex > 0 && guidedStack.e2.empty());
if(!guidedStack.e2.empty()) {
oldTopic = (Topic) guidedStack.e2.peek();
}
}
}
if(oldTopic != null) {
//hlog("Creating association between "+oldTopic+" and "+t);
createAssociation(tm, oldTopic, t);
}
stack.push(t);
}
// **** TEST PARSE FEED TOKENS *****
public boolean isAddTopicCounter(Alphabet a) {
if("+".indexOf(a.getName()) > -1) return true;
else return false;
}
public boolean isSubstractTopicCounter(Alphabet a) {
if("-".indexOf(a.getName()) > -1) return true;
else return false;
}
public boolean isResetTopicCount(Alphabet a) {
if("0".indexOf(a.getName()) > -1) return true;
else return false;
}
public boolean isAssociationColor(Alphabet a) {
if("qwertyuiopasdfghjklmnbvcxzQWERTYUIOPLKJHGFDSAZXCVBNM".indexOf(a.getName()) > -1) return true;
else return false;
}
public boolean isSetAssociationColor(Alphabet a) {
if(":".indexOf(a.getName()) > -1) return true;
else return false;
}
public boolean isNamedTopic(Alphabet a) {
if("ABCDEFGHIJKLMNOPQRSTUWV".indexOf(a.getName()) > -1) return true;
else return false;
}
public boolean isColoredTopic(Alphabet a) {
if("euioy".indexOf(a.getName()) > -1) return true;
else return false;
}
public boolean isCreateTopic(Alphabet a) {
if("a".equals(a.getName())) return true;
else return false;
}
public boolean isCreateParallelBlock(Alphabet a) {
if("[".equals(a.getName())) return true;
else return false;
}
public boolean isCloseParallelBlock(Alphabet a) {
if("]".equals(a.getName())) return true;
else return false;
}
public boolean isCreateSequentialBlock(Alphabet a) {
if("(".equals(a.getName())) return true;
else return false;
}
public boolean isCloseSequentialBlock(Alphabet a) {
if(")".equals(a.getName())) return true;
else return false;
}
public boolean isCreateCycleBlock(Alphabet a) {
if("{".equals(a.getName())) return true;
else return false;
}
public boolean isCloseCycleBlock(Alphabet a) {
if("}".equals(a.getName())) return true;
else return false;
}
}
// -------------------------------------------------------------------------
// ------ LSystem ----------------------------------------------------------
// -------------------------------------------------------------------------
private class LSystem {
private ArrayList<Rule> rules = new ArrayList<Rule>();
private Word state = new Word();
public LSystem(Word initial, ArrayList<Rule> ruleArray, int n) {
initialize(initial, ruleArray.toArray( new Rule[] {} ), n);
}
public LSystem(Word initial, Rule[] ruleArray, int n) {
initialize(initial, ruleArray, n);
}
public LSystem() {
}
public void initialize(Word initiator, Rule[] ruleArray, int n) {
clearRules();
if(ruleArray != null) {
for(int i=0; i<ruleArray.length; i++) {
addRule(ruleArray[i]);
}
}
setInitialState(initiator);
iterate(n);
}
public void setInitialState(Word s) {
if(s == null) s = new Word();
state = s;
}
public void addRule(Rule r) {
rules.add(r);
}
public void clearRules() {
rules = new ArrayList<Rule>();
}
public Word getState() {
return state;
}
public void iterate() {
iterate(1);
}
public void iterate(int n) {
Rule r = null;
for(int i=0; i<n && !forceStop(); i++) {
for(Iterator<Rule> it = rules.iterator(); it.hasNext() && !forceStop(); ) {
r = it.next();
state = r.apply(state);
}
state.setFresh(false);
}
}
@Override
public String toString() {
String s = "LSystem state: "+state.toString()+", rules: ";
for(int i=0; i<rules.size(); i++) {
s=s+rules.get(i).toString();
if(i<rules.size()-1) s=s+", ";
}
return s;
}
}
private class Word {
List<Alphabet> alphabets = new ArrayList<Alphabet>();
public Word() {
}
public Word(List<Alphabet> w) {
this.alphabets = w;
}
public Word(String[] str) {
this.alphabets = new ArrayList<Alphabet>();
for(int i=0; i<str.length; i++) {
alphabets.add(new Alphabet(str[i]));
}
}
public Word(String str) {
this(str, true);
}
public Word(String str, boolean split) {
if(split) {
for(int i=0; i<str.length(); i++) {
alphabets.add(new Alphabet(str.charAt(i)));
}
}
else {
alphabets.add(new Alphabet( str ));
}
}
public boolean startsWith(Word otherWord, int index) {
boolean found = false;
//System.out.println("startsWith-1");
if(alphabets != null && otherWord != null && alphabets.size() >= index+otherWord.size() ) {
Alphabet as = null;
Alphabet aw = null;
int kmax = otherWord.size();
found = true;
//System.out.println("startsWith-2");
for(int j=0; j<kmax; j++) {
as = alphabets.get(index+j);
if(as.isFresh()) {
found = false;
break;
}
aw = otherWord.get(j);
//System.out.println("startsWith-3");
if(!as.equals(aw)) {
//System.out.println("startsWith-4");
found = false;
break;
}
}
}
return found;
}
public void add(Word word, boolean fresh) {
List<Alphabet> alphas = word.getAlphabets();
for(int i=0; i<alphas.size(); i++) {
this.alphabets.add(alphas.get(i).duplicate(fresh));
}
}
public void add(Alphabet alphabet, boolean fresh) {
this.alphabets.add(alphabet.duplicate(fresh));
}
public void setFresh(boolean f) {
for(int i=0; i<alphabets.size(); i++) {
alphabets.get(i).setFresh(f);
}
}
public List<Alphabet> getAlphabets() {
return alphabets;
}
public int size() {
if(alphabets == null) return 0;
return alphabets.size();
}
public Alphabet get(int i) {
return alphabets.get(i);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for(int i=0; i<alphabets.size(); i++) {
sb.append(alphabets.get(i).toString());
}
return sb.toString();
}
}
private class Alphabet {
private String name = null;
private boolean fresh = false;
public Alphabet(char ch) {
this.name = "" + ch;
}
public Alphabet(String n) {
this.name = n;
}
public String getName() {
return name;
}
public void setFresh(boolean f) {
this.fresh = f;
}
public boolean isFresh() {
return fresh;
}
public boolean equals(Alphabet a) {
if(a == null) return false;
if(a.getName() == null && getName() == null) return true;
if(getName() != null) return getName().equals(a.getName());
return false;
}
@Override
public String toString() {
return name;
}
public Alphabet duplicate(boolean fresh) {
Alphabet a = new Alphabet(this.getName());
a.setFresh(fresh);
return a;
}
}
private class Rule {
private Word predecessor = null;
private Word successor = null;
public Rule(Word p, Word s) {
predecessor = p;
successor = s;
}
public Word apply(Word state) {
Word newState = new Word();
for(int i=0; i<state.size() && !forceStop(); i++) {
if(state.startsWith(predecessor, i)) {
newState.add(successor, true);
i = i + predecessor.size() - 1;
}
else {
newState.add(state.get(i), false);
}
}
return newState;
}
@Override
public String toString() {
return (predecessor == null ? "null" : predecessor.toString()) +"-->"+(successor == null ? "null" : successor.toString());
}
}
}
| 29,700 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
LSystemGraphGeneratorDialog.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/generators/LSystemGraphGeneratorDialog.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
* EdgeGeneratorDialog.java
*
* Created on 2008-09-22, 13:14
*/
package org.wandora.application.tools.generators;
import java.awt.Component;
import java.awt.Desktop;
import java.io.File;
import java.net.URI;
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.WandoraOptionPane;
import org.wandora.application.gui.simple.SimpleButton;
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;
import org.wandora.utils.Options;
import org.wandora.utils.Tuples.T2;
/**
*
* @author akivela
*/
public class LSystemGraphGeneratorDialog extends javax.swing.JDialog {
private static final long serialVersionUID = 1L;
public static final int L_SYSTEM = 11;
public static final int RAW_RESULT = 12;
private Wandora parent = null;
private WandoraTool parentTool = null;
private boolean wasAccepted = false;
public static final String optionsPrefix = "lsystems";
private ArrayList<T2<String,String>> lsystems = new ArrayList<T2<String,String>>();
/** Creates new form AbstractExtractorDialog */
public LSystemGraphGeneratorDialog(Wandora admin, WandoraTool parentTool, boolean modal) {
super(admin, modal);
this.parent = admin;
initComponents();
initialize(parentTool);
lSystemComboBox.setEditable(false);
restoreStoredLSystems();
}
public void initialize(WandoraTool parentTool) {
this.parentTool = parentTool;
wasAccepted = false;
((SimpleTextPane) fileTextPane).dropFileNames(true);
((SimpleTextPane) fileTextPane).setLineWrap(false);
((SimpleTextPane) urlTextPane).setLineWrap(false);
setTitle("L-system generator");
setSize(700,500);
if(parent != null) parent.centerWindow(this);
}
// -------------------------------------------------------------------------
public void restoreStoredLSystems() {
if(parent == null) return;
Options options = parent.getOptions();
if(options == null) return;
int i=0;
String lsystemName = null;
String lsystemSystem = null;
do {
lsystemName = options.get(optionsPrefix + ".lsystem[" + i +"].name");
lsystemSystem = options.get(optionsPrefix + ".lsystem[" + i +"].system");
if(lsystemName != null && lsystemSystem != null) {
lsystems.add(new T2<String,String>(lsystemName, lsystemSystem));
lSystemComboBox.addItem(lsystemName);
}
i++;
}
while(lsystemName != null && lsystemSystem != null && i<1000);
}
public void restoreLSystem() {
try {
int lsystemIndex = lSystemComboBox.getSelectedIndex();
if(lsystems.size() > lsystemIndex) {
T2<String,String> namedLSystem = lsystems.get(lsystemIndex);
if(namedLSystem != null) {
String lsystemSystem = (String) namedLSystem.e2;
if(lsystemSystem != null) {
lSystemTextPane.setText(lsystemSystem);
}
}
}
}
catch(Exception e) {
parent.handleError(e);
}
}
public void storeLSystem() {
try {
String newLSystemSystem = lSystemTextPane.getText();
String newLSystemName = WandoraOptionPane.showInputDialog(parent, "Name of created L-system?", "", "Name of created L-system?");
if(newLSystemSystem != null && newLSystemName.length()>0) {
lSystemComboBox.addItem(newLSystemName);
lsystems.add(new T2<>(newLSystemName, newLSystemSystem));
lSystemComboBox.setSelectedIndex(lSystemComboBox.getItemCount()-1);
if(parent != null && parent.getOptions() != null) {
Options options = parent.getOptions();
String lsystemSystem = null;
String lsystemName = null;
int i=0;
do {
lsystemName = options.get(optionsPrefix + ".lsystem[" + i +"].name");
lsystemSystem = options.get(optionsPrefix + ".lsystem[" + i +"].system");
i++;
}
while(lsystemName != null && lsystemSystem != null && i<1000);
options.put(optionsPrefix + ".lsystem[" + i +"].name", newLSystemName);
options.put(optionsPrefix + ".lsystem[" + i +"].system", newLSystemSystem);
}
else {
WandoraOptionPane.showMessageDialog(parent, "Unable to store L-system to application options!", WandoraOptionPane.WARNING_MESSAGE);
}
}
else {
WandoraOptionPane.showMessageDialog(parent, "No name given. L-system was not stored!", WandoraOptionPane.WARNING_MESSAGE);
}
}
catch(Exception e) {
parent.handleError(e);
}
}
// -------------------------------------------------------------------------
public void setAccepted(boolean accepted) {
this.wasAccepted = accepted;
}
public boolean wasAccepted() {
return wasAccepted;
}
public int getDepth() {
try {
return Integer.parseInt(this.depthTextField.getText());
}
catch(Exception e) {
return 0;
}
}
public int getContentType() {
Component selectedComponent = tabbedSourcePane.getSelectedComponent();
if(lSystemPanel.equals(selectedComponent)) {
return L_SYSTEM;
}
else if(rawPanel.equals(selectedComponent)) {
return RAW_RESULT;
}
return 0;
}
// --- CONTENT ---
public String getContent() {
Component selectedComponent = tabbedSourcePane.getSelectedComponent();
if(lSystemPanel.equals(selectedComponent)) {
return lSystemTextPane.getText();
}
else 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(int i=0; i<urls.length; i++) {
try {
sb.append(IObox.doUrl(new URL(urls[i])));
}
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(int i=0; i<filenames.length; i++) {
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(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).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();
tabbedSourcePane = new org.wandora.application.gui.simple.SimpleTabbedPane();
lSystemPanel = new javax.swing.JPanel();
lSystemLabel = new org.wandora.application.gui.simple.SimpleLabel();
selectLSystemPanel = new javax.swing.JPanel();
lSystemComboBox = new org.wandora.application.gui.simple.SimpleComboBox();
saveLSystemButton = new org.wandora.application.gui.simple.SimpleButton();
lSystemScrollPane = new javax.swing.JScrollPane();
lSystemTextPane = new org.wandora.application.gui.simple.SimpleTextPane();
depthPanel = new javax.swing.JPanel();
depthTextField = new org.wandora.application.gui.simple.SimpleField();
depthLabel = new org.wandora.application.gui.simple.SimpleLabel();
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();
buttonPanel = new javax.swing.JPanel();
infoButton = new SimpleButton();
fillerPanel = new javax.swing.JPanel();
generateButton = new org.wandora.application.gui.simple.SimpleButton();
cancelButton = new org.wandora.application.gui.simple.SimpleButton();
urlPanel.setLayout(new java.awt.GridBagLayout());
urlLabel.setText("<html>This tab is used to address URL resources with edge data. Please write URL addresses below 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);
filePanel.setLayout(new java.awt.GridBagLayout());
fileLabel.setText("<html>This tab is used to address files with edge data. Please browse files with edge data 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);
getContentPane().setLayout(new java.awt.GridBagLayout());
lSystemPanel.setLayout(new java.awt.GridBagLayout());
lSystemLabel.setText("<html>An L-system or Lindenmayer system is a parallel rewriting system and a type of formal grammar. \nAn L-system consists of an alphabet of symbols that can be used to make strings, a collection of production rules that expand each \nsymbol into some larger string of symbols, an initial \"axiom\" string from which to begin construction, and a mechanism for translating the \ngenerated strings into graph structures. Write your L-system to the textarea below or choose an L-system with the selector.</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);
lSystemPanel.add(lSystemLabel, gridBagConstraints);
selectLSystemPanel.setLayout(new java.awt.GridBagLayout());
lSystemComboBox.setMinimumSize(new java.awt.Dimension(28, 21));
lSystemComboBox.setPreferredSize(new java.awt.Dimension(28, 21));
lSystemComboBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
lSystemComboBoxActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 2);
selectLSystemPanel.add(lSystemComboBox, gridBagConstraints);
saveLSystemButton.setText("new");
saveLSystemButton.setMargin(new java.awt.Insets(0, 3, 0, 3));
saveLSystemButton.setMaximumSize(new java.awt.Dimension(50, 21));
saveLSystemButton.setMinimumSize(new java.awt.Dimension(50, 21));
saveLSystemButton.setPreferredSize(new java.awt.Dimension(50, 21));
saveLSystemButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
saveLSystemButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 0);
selectLSystemPanel.add(saveLSystemButton, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 5, 5, 5);
lSystemPanel.add(selectLSystemPanel, gridBagConstraints);
lSystemScrollPane.setPreferredSize(new java.awt.Dimension(10, 100));
lSystemTextPane.setFont(new java.awt.Font("Monospaced", 0, 12)); // NOI18N
lSystemScrollPane.setViewportView(lSystemTextPane);
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);
lSystemPanel.add(lSystemScrollPane, gridBagConstraints);
depthPanel.setLayout(new java.awt.GridBagLayout());
depthTextField.setHorizontalAlignment(javax.swing.JTextField.CENTER);
depthTextField.setText("5");
depthTextField.setMinimumSize(new java.awt.Dimension(35, 20));
depthTextField.setPreferredSize(new java.awt.Dimension(35, 20));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3);
depthPanel.add(depthTextField, gridBagConstraints);
depthLabel.setText("iterations");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3);
depthPanel.add(depthLabel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 5, 5, 5);
lSystemPanel.add(depthPanel, gridBagConstraints);
tabbedSourcePane.addTab("L-system", lSystemPanel);
rawPanel.setLayout(new java.awt.GridBagLayout());
rawLabel.setText("<html>Transform any generated L-system string into a topic map graph. Paste or write you L-system string below. Press Generate button to start transformation.</html>");
rawLabel.setToolTipText("<html>\nParser vocabulary is<br><pre>\na create topic and association it with previous one\n[A-V] create named topic and association it with previous\n[eiuoy] create topic and association it with previous one using named schema\n:[a-zA-Z] change global association type and roles\n:0 reset association type and roles\n\n( start sequential block\n) close sequential block\n[ start parallel block\n] close parallel block\n{ start cycle block\n} close cycle block\n\n0 reset topic counter</pre>\n- substract topic counter by one\n+ add topic counter bt one</pre>\n</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));
rawTextPane.setFont(new java.awt.Font("Monospaced", 0, 12)); // NOI18N
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("Parser", rawPanel);
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());
infoButton.setText("Info");
infoButton.setToolTipText("Get more information about L-system generator. Opens web browser at http://wandora.org/wiki/L-system_generator");
infoButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
infoButtonActionPerformed(evt);
}
});
buttonPanel.add(infoButton, 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, 364, 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);
generateButton.setText("Generate");
generateButton.setPreferredSize(new java.awt.Dimension(80, 23));
generateButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
generateButtonMouseReleased(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3);
buttonPanel.add(generateButton, gridBagConstraints);
cancelButton.setText("Cancel");
cancelButton.setPreferredSize(new java.awt.Dimension(80, 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 cancelButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cancelButtonMouseReleased
wasAccepted = false;
setVisible(false);
}//GEN-LAST:event_cancelButtonMouseReleased
private void generateButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_generateButtonMouseReleased
wasAccepted = true;
setVisible(false);
}//GEN-LAST:event_generateButtonMouseReleased
private void urlClearButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_urlClearButtonMouseReleased
this.urlTextPane.setText("");
}//GEN-LAST:event_urlClearButtonMouseReleased
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
private void fileClearButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_fileClearButtonMouseReleased
this.fileTextPane.setText("");
}//GEN-LAST:event_fileClearButtonMouseReleased
private void fileGetSLButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_fileGetSLButtonMouseReleased
selectContextSLFiles();
}//GEN-LAST:event_fileGetSLButtonMouseReleased
private void fileBrowseButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_fileBrowseButtonMouseReleased
selectFiles();
}//GEN-LAST:event_fileBrowseButtonMouseReleased
private void saveLSystemButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveLSystemButtonActionPerformed
storeLSystem();
}//GEN-LAST:event_saveLSystemButtonActionPerformed
private void lSystemComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_lSystemComboBoxActionPerformed
if((evt.getModifiers() | java.awt.event.ActionEvent.ACTION_PERFORMED) != 0) {
restoreLSystem();
}
}//GEN-LAST:event_lSystemComboBoxActionPerformed
private void infoButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_infoButtonActionPerformed
Desktop desktop = Desktop.getDesktop();
if(desktop != null) {
try {
desktop.browse(new URI("http://wandora.org/wiki/L-system_generator"));
}
catch(Exception e){
e.printStackTrace();
}
}
}//GEN-LAST:event_infoButtonActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel buttonPanel;
private javax.swing.JButton cancelButton;
private javax.swing.JLabel depthLabel;
private javax.swing.JPanel depthPanel;
private javax.swing.JTextField depthTextField;
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 generateButton;
private javax.swing.JButton infoButton;
private javax.swing.JComboBox lSystemComboBox;
private javax.swing.JLabel lSystemLabel;
private javax.swing.JPanel lSystemPanel;
private javax.swing.JScrollPane lSystemScrollPane;
private javax.swing.JTextPane lSystemTextPane;
private javax.swing.JLabel rawLabel;
private javax.swing.JPanel rawPanel;
private javax.swing.JScrollPane rawScrollPane;
private javax.swing.JTextPane rawTextPane;
private javax.swing.JButton saveLSystemButton;
private javax.swing.JPanel selectLSystemPanel;
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
}
| 38,098 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
RandomGraphGenerator.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/generators/RandomGraphGenerator.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* RandomGraphGenerator.java
*
* Created on 30. toukokuuta 2007, 14:11
*
*/
package org.wandora.application.tools.generators;
import java.util.HashSet;
import java.util.Map;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.WandoraOptionPane;
import org.wandora.application.tools.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.swing.GuiTools;
/**
*
* @author akivela
*/
public class RandomGraphGenerator extends AbstractGenerator implements WandoraTool {
private static final long serialVersionUID = 1L;
public static String RANDOM_GRAPH_SI = "http://wandora.org/si/random-graph";
public static String siPattern = "http://wandora.org/si/random-graph/node/__n__";
public static String basenamePattern = "Random graph node __n__";
public static boolean connectWithWandoraClass = true;
public static boolean ensureNumberOfAssociations = true;
public static int nodeCounterOffset = 0;
/** Creates a new instance of RandomGraphGenerator */
public RandomGraphGenerator() {
}
@Override
public String getName() {
return "Random graph generator";
}
@Override
public String getDescription() {
return "Random graph generator creates a graph of given number of nodes "+
"and edges between randomly selected graph nodes.";
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
TopicMap topicmap = solveContextTopicMap(wandora, context);
GenericOptionsDialog god=new GenericOptionsDialog(wandora,
"Random graph generator",
"Random graph generator creates a graph of given number of nodes "+
"and edges between randomly selected graph nodes. A node is a topic and "+
"an edge is an association. "+
"If 'number of associations' is a valid number "+
"it overrides 'association probality'. Number is a positive integer. "+
"Probability is a floating point number between 0.0 and 1.0.",
true,new String[][]{
new String[]{"Number of topics","string"},
new String[]{"Number of random associations","string"},
new String[]{"Random associations probability","string"},
new String[]{"---1","separator"},
new String[]{"Subject identifier pattern","string",siPattern,"Subject identifier patterns for the created node topics. Part __n__ in patterns is replaced with node identifier."},
new String[]{"Basename pattern","string",basenamePattern,"Basename patterns for the created node topics. Part __n__ in patterns is replaced with node identifier."},
new String[]{"Node counter offset","string",""+nodeCounterOffset,"What is the number of first generated topic node."},
new String[]{"Connect topics with Wandora class","boolean", connectWithWandoraClass ? "true" : "false","Create additional topics and associations that connect created topics with the Wandora class." },
new String[]{"Association type of random associations","topic",null,"Optional association type for random graph edges."},
new String[]{"First role of random associations","topic",null,"Optional role topic for random graph edges."},
new String[]{"Second role of random associations","topic",null,"Optional role topic for random graph edges."},
},wandora);
god.setSize(700, 460);
GuiTools.centerWindow(god,wandora);
god.setVisible(true);
if(god.wasCancelled()) return;
Map<String,String> values=god.getValues();
int n = 0;
int an = 0;
double ap = 0.0;
boolean useAssociationNumber = false;
try {
n = Integer.parseInt(values.get("Number of topics"));
String ans = values.get("Number of random associations");
if(ans != null && ans.length() > 0) {
an = Integer.parseInt(values.get("Number of random associations"));
useAssociationNumber = true;
}
else {
ap = Double.parseDouble(values.get("Random associations probability"));
useAssociationNumber = false;
}
}
catch(NumberFormatException nfe) {
singleLog("Parse error.\n"+
"Number of topics and number of associations should be integers.\n"+
"Association probability should be floating point number between 0.0 and 1.0.");
return;
}
catch(Exception e) {
singleLog(e);
return;
}
try {
siPattern = values.get("Subject identifier pattern");
if(!siPattern.contains("__n__")) {
int a = WandoraOptionPane.showConfirmDialog(wandora, "Subject identifier pattern doesn't contain part for topic counter '__n__'. This causes all generated topics to merge. Do you want to continue?", "Missing topic counter part", WandoraOptionPane.WARNING_MESSAGE);
if(a != WandoraOptionPane.YES_OPTION) return;
}
basenamePattern = values.get("Basename pattern");
if(!basenamePattern.contains("__n__")) {
int a = WandoraOptionPane.showConfirmDialog(wandora, "Basename pattern doesn't contain part for topic counter '__n__'. This causes all generated topics to merge. Do you want to continue?", "Missing topic counter part", WandoraOptionPane.WARNING_MESSAGE);
if(a != WandoraOptionPane.YES_OPTION) return;
}
connectWithWandoraClass = "true".equalsIgnoreCase(values.get("Connect topics with Wandora class"));
try {
nodeCounterOffset = Integer.parseInt(values.get("Node counter offset"));
}
catch(NumberFormatException nfe) {
singleLog("Parse error. Node counter offset should be an integer number. Using default value (0).");
nodeCounterOffset = 0;
}
}
catch(Exception e) {
singleLog(e);
return;
}
Topic aType = topicmap.getTopic(values.get("Association type of random associations"));
if(aType == null || aType.isRemoved()) {
aType = getOrCreateTopic(topicmap, RANDOM_GRAPH_SI+"/"+"association-type", "Random graph association");
}
Topic role1 = topicmap.getTopic(values.get("First role of random associations"));
if(role1 == null || role1.isRemoved()) {
role1 = getOrCreateTopic(topicmap, RANDOM_GRAPH_SI+"/"+"role-1", "Random graph role 1");
}
Topic role2 = topicmap.getTopic(values.get("Second role of random associations"));
if(role2 == null || role2.isRemoved()) {
role2 = getOrCreateTopic(topicmap, RANDOM_GRAPH_SI+"/"+"role-2", "Random graph role 2");
}
if(role1.mergesWithTopic(role2)) {
int a = WandoraOptionPane.showConfirmDialog(wandora, "Role topics are same. This causes associations to be unary instead of binary. Do you want to continue?", "Role topics are same", WandoraOptionPane.WARNING_MESSAGE);
if(a != WandoraOptionPane.YES_OPTION) {
return;
}
}
setDefaultLogger();
setLogTitle("Random graph generator");
log("Creating topics.");
Topic[] topics = new Topic[n];
long graphIdentifier = System.currentTimeMillis();
setProgressMax(n);
for(int i=0; i<n && !forceStop(); i++) {
setProgress(i);
int nodeCounter = nodeCounterOffset+i;
topics[i] = getOrCreateTopic(topicmap, nodeCounter, graphIdentifier);
}
Association a = null;
Topic t1 = null;
Topic t2 = null;
log("Creating random associations.");
setProgress(0);
// Creating exact number of random associations!
if(useAssociationNumber) {
setProgressMax(an);
HashSet createdAssociations = new HashSet(an);
for(int j=0; j<an && !forceStop(); j++) {
int n1 = (int) Math.floor( Math.random() * n );
int n2 = (int) Math.floor( Math.random() * n );
if(ensureNumberOfAssociations) {
String hash = n1+"-"+n2;
int retries = 100;
while(createdAssociations.contains(hash) && --retries>0) {
n1 = (int) Math.floor( Math.random() * n );
n2 = (int) Math.floor( Math.random() * n );
hash = n1+"-"+n2;
}
createdAssociations.add(hash);
}
t1 = topics[n1];
t2 = topics[n2];
a = topicmap.createAssociation(aType);
a.addPlayer(t1, role1);
a.addPlayer(t2, role2);
setProgress(j);
}
}
// Creating associations with given probability!
else {
setProgressMax(n*n);
double rd = 0.0;
for(int j=0; j<n && !forceStop(); j++) {
t1 = topics[j];
for(int k=0; k<n && !forceStop(); k++) {
rd = Math.random();
if(rd < ap) {
t2 = topics[k];
a = topicmap.createAssociation(aType);
a.addPlayer(t1, role1);
a.addPlayer(t2, role2);
}
setProgress(j*n+k);
}
}
}
if(connectWithWandoraClass) {
log("You'll find created topics and associations under the 'Random graph' topic.");
}
else {
String searchWord = basenamePattern.replaceAll("__n__", "");
searchWord = searchWord.trim();
log("You'll find created topics and associations by searching with a '"+searchWord+"'.");
}
log("Ready.");
setState(WAIT);
}
private Topic getOrCreateTopic(TopicMap topicmap, int topicIdentifier, long graphIdentifier) {
String newBasename = basenamePattern.replaceAll("__n__", ""+topicIdentifier);
String newSubjectIdentifier = siPattern.replaceAll("__n__", ""+topicIdentifier);
Topic t = getOrCreateTopic(topicmap, newSubjectIdentifier, newBasename);
if(connectWithWandoraClass) {
try {
Topic graphTopic = getOrCreateTopic(topicmap, RANDOM_GRAPH_SI, "Random graph");
Topic wandoraClass = getOrCreateTopic(topicmap, TMBox.WANDORACLASS_SI);
makeSuperclassSubclass(topicmap, wandoraClass, graphTopic);
Topic graphInstanceTopic = getOrCreateTopic(topicmap, RANDOM_GRAPH_SI+"/"+graphIdentifier, "Random graph "+graphIdentifier, graphTopic);
graphInstanceTopic.addType(graphTopic);
t.addType(graphInstanceTopic);
}
catch(Exception e) {
e.printStackTrace();
}
}
return t;
}
}
| 12,436 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
LinearListGenerator.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/generators/LinearListGenerator.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* LinearListGenerator.java
*
* Created on 31. toukokuuta 2007, 16:28
*
*/
package org.wandora.application.tools.generators;
import java.util.Map;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.WandoraOptionPane;
import org.wandora.application.tools.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.swing.GuiTools;
/**
*
* @author akivela
*/
public class LinearListGenerator extends AbstractGenerator implements WandoraTool {
private static final long serialVersionUID = 1L;
public static String LIST_GRAPH_SI = "http://wandora.org/si/linear-list/";
public static String siPattern = "http://wandora.org/si/linear-list/node/__n__";
public static String basenamePattern = "Linear list vertex __n__";
public static boolean connectWithWandoraClass = true;
public static int n = 10;
public static int topicCounterOffset = 0;
public static boolean makeCycle = false;
/** Creates a new instance of LinearListGenerator */
public LinearListGenerator() {
}
@Override
public String getName() {
return "Linear list graph generator";
}
@Override
public String getDescription() {
return "Generates a linear list graph topic map.";
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
TopicMap topicmap = solveContextTopicMap(wandora, context);
GenericOptionsDialog god=new GenericOptionsDialog(wandora,
"Linear list graph generator",
"Linear list graph generator creates a topic map of given number of " +
"topics associated like a linked list.",
true,new String[][]{
new String[]{"Number of list nodes","string",""+n},
new String[]{"Make cycle","boolean", makeCycle?"true":"false","Link last and first node?"},
new String[]{"---1","separator"},
new String[]{"Subject identifier pattern","string",siPattern,"Subject identifier patterns for the created node topics. Part __n__ in patterns is replaced with node identifier."},
new String[]{"Basename pattern","string",basenamePattern,"Basename patterns for the created node topics. Part __n__ in patterns is replaced with node identifier."},
new String[]{"Topic counter offset","string",""+topicCounterOffset,"What is the number of first generated topic node."},
new String[]{"Connect topics with Wandora class","boolean", connectWithWandoraClass ? "true" : "false","Create additional topics and associations that connect created topics with the Wandora class." },
new String[]{"Association type for edges of the linear list","topic",null,"Optional association type for graph edges."},
new String[]{"Role topic for the previous node","topic",null,"Optional role topic for parent topics in tree graph."},
new String[]{"Role topic for the next node","topic",null,"Optional role topic for child topics in tree graph."},
},wandora);
god.setSize(700, 460);
GuiTools.centerWindow(god,wandora);
god.setVisible(true);
if(god.wasCancelled()) return;
Map<String,String> values=god.getValues();
try {
n = Integer.parseInt(values.get("Number of list nodes"));
makeCycle=Boolean.parseBoolean(values.get("Make cycle"));
}
catch(Exception e) {
singleLog("Number of list nodes is not a number. Cancelling.", e);
return;
}
try {
siPattern = values.get("Subject identifier pattern");
if(!siPattern.contains("__n__")) {
int a = WandoraOptionPane.showConfirmDialog(wandora, "Subject identifier pattern doesn't contain part for topic counter '__n__'. This causes all generated topics to merge. Do you want to continue?", "Missing topic counter part", WandoraOptionPane.WARNING_MESSAGE);
if(a != WandoraOptionPane.YES_OPTION) return;
}
basenamePattern = values.get("Basename pattern");
if(!basenamePattern.contains("__n__")) {
int a = WandoraOptionPane.showConfirmDialog(wandora, "Basename pattern doesn't contain part for topic counter '__n__'. This causes all generated topics to merge. Do you want to continue?", "Missing topic counter part", WandoraOptionPane.WARNING_MESSAGE);
if(a != WandoraOptionPane.YES_OPTION) return;
}
connectWithWandoraClass = "true".equalsIgnoreCase(values.get("Connect topics with Wandora class"));
try {
topicCounterOffset = Integer.parseInt(values.get("Topic counter offset"));
}
catch(NumberFormatException nfe) {
singleLog("Parse error. Topic counter offset should be an integer number. Cancelling.");
return;
}
}
catch(Exception e) {
singleLog(e);
return;
}
Topic aType = topicmap.getTopic(values.get("Association type for edges of the linear list"));
if(aType == null || aType.isRemoved()) {
aType = getOrCreateTopic(topicmap, LIST_GRAPH_SI+"/"+"association-type", "Linear list association");
}
Topic previousT = topicmap.getTopic(values.get("Role topic for the previous node"));
if(previousT == null || previousT.isRemoved()) {
previousT = getOrCreateTopic(topicmap, LIST_GRAPH_SI+"/"+"previous", "Previous in list");
}
Topic nextT = topicmap.getTopic(values.get("Role topic for the next node"));
if(nextT == null || nextT.isRemoved()) {
nextT = getOrCreateTopic(topicmap, LIST_GRAPH_SI+"/"+"next", "Next in list");
}
if(previousT.mergesWithTopic(nextT)) {
int a = WandoraOptionPane.showConfirmDialog(wandora, "Previous and next role topics are same. This causes associations to be unary instead of binary. Do you want to continue?", "Role topics are same", WandoraOptionPane.WARNING_MESSAGE);
if(a != WandoraOptionPane.YES_OPTION) {
return;
}
}
setDefaultLogger();
setLogTitle("Linear list graph generator");
log("Creating linear list graph");
Association a = null;
long graphIdentifier = System.currentTimeMillis();
Topic first = null;
Topic previous = null;
Topic next = null;
setProgressMax(n);
int progress=0;
for(int i=topicCounterOffset; i<topicCounterOffset+n && !forceStop(); i++) {
next = getOrCreateTopic(topicmap, i, graphIdentifier);
if(previous != null) {
a = topicmap.createAssociation(aType);
a.addPlayer(previous, previousT);
a.addPlayer(next, nextT);
}
else {
first = next;
}
setProgress(progress++);
previous = next;
}
if(makeCycle) {
a = topicmap.createAssociation(aType);
a.addPlayer(previous, previousT);
a.addPlayer(first, nextT);
}
if(connectWithWandoraClass) {
log("You'll find created topics and associations under the 'Linear list' topic.");
}
else {
String searchWord = basenamePattern.replaceAll("__n__", "");
searchWord = searchWord.trim();
log("You'll find created topics and associations by searching '"+searchWord+"'.");
}
log("Ready.");
setState(WAIT);
}
private Topic getOrCreateTopic(TopicMap tm, int topicIdentifier, long graphIdentifier) {
String newBasename = basenamePattern.replaceAll("__n__", ""+topicIdentifier);
String newSubjectIdentifier = siPattern.replaceAll("__n__", ""+topicIdentifier);
Topic t = getOrCreateTopic(tm, newSubjectIdentifier, newBasename);
if(connectWithWandoraClass) {
try {
Topic listGraphTopic = getOrCreateTopic(tm, LIST_GRAPH_SI, "Linear list");
Topic wandoraClass = getOrCreateTopic(tm, TMBox.WANDORACLASS_SI);
makeSuperclassSubclass(tm, wandoraClass, listGraphTopic);
Topic listGraphInstanceTopic = getOrCreateTopic(tm, LIST_GRAPH_SI+"/"+graphIdentifier, "Linear list "+graphIdentifier, listGraphTopic);
listGraphInstanceTopic.addType(listGraphTopic);
t.addType(listGraphInstanceTopic);
}
catch(Exception e) {
e.printStackTrace();
}
}
return t;
}
}
| 9,892 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
FiniteGroupGenerator.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/generators/FiniteGroupGenerator.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* FiniteGroupGenerator.java
*
* Created on 31. toukokuuta 2007, 17:01
*
*/
package org.wandora.application.tools.generators;
import java.util.Map;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.WandoraOptionPane;
import org.wandora.application.tools.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.swing.GuiTools;
/**
*
* @author akivela
*/
public class FiniteGroupGenerator extends AbstractGenerator implements WandoraTool {
private static final long serialVersionUID = 1L;
public static String FINITE_GROUP_SI = "http://wandora.org/si/finite-group";
public static String siPattern = "http://wandora.org/si/finite-group/node/__n__";
public static String basenamePattern = "Topic __n__";
public static boolean connectWithWandoraClass = true;
public static int topicCounterOffset = 0;
/** Creates a new instance of FiniteGroupGenerator */
public FiniteGroupGenerator() {
}
@Override
public String getName() {
return "Finite group graph generator";
}
@Override
public String getDescription() {
return "Generates a finite group (algebra) topic map.";
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
TopicMap topicmap = solveContextTopicMap(wandora, context);
GenericOptionsDialog god=new GenericOptionsDialog(wandora,
"Finite group graph generator",
"Finite group graph generator options",
true,new String[][]{
new String[]{"Number of group elements","string"},
new String[]{"---1","separator"},
new String[]{"Subject identifier pattern","string",siPattern,"Subject identifier patterns for the created node topics. Part __n__ in patterns is replaced with node counter."},
new String[]{"Basename pattern","string",basenamePattern,"Basename patterns for the created node topics. Part __n__ in patterns is replaced with node counter."},
new String[]{"Topic counter offset","string",""+topicCounterOffset,"What is the number of first generated topic node."},
new String[]{"Connect topics with Wandora class","boolean", connectWithWandoraClass ? "true" : "false","Create additional topics and associations that connect created topics with the Wandora class." },
},wandora);
god.setSize(700, 420);
GuiTools.centerWindow(god,wandora);
god.setVisible(true);
if(god.wasCancelled()) return;
Map<String,String> values=god.getValues();
int n = 0;
try {
n = Integer.parseInt(values.get("Number of group elements"));
}
catch(Exception e) {
singleLog(e);
return;
}
try {
siPattern = values.get("Subject identifier pattern");
if(!siPattern.contains("__n__")) {
int a = WandoraOptionPane.showConfirmDialog(wandora, "Subject identifier pattern doesn't contain part for topic counter '__n__'. This causes all generated topics to merge. Do you want to continue?", "Missing topic counter part", WandoraOptionPane.WARNING_MESSAGE);
if(a != WandoraOptionPane.YES_OPTION) return;
}
basenamePattern = values.get("Basename pattern");
if(!basenamePattern.contains("__n__")) {
int a = WandoraOptionPane.showConfirmDialog(wandora, "Basename pattern doesn't contain part for topic counter '__n__'. This causes all generated topics to merge. Do you want to continue?", "Missing topic counter part", WandoraOptionPane.WARNING_MESSAGE);
if(a != WandoraOptionPane.YES_OPTION) return;
}
connectWithWandoraClass = "true".equalsIgnoreCase(values.get("Connect topics with Wandora class"));
try {
topicCounterOffset = Integer.parseInt(values.get("Topic counter offset"));
}
catch(NumberFormatException nfe) {
singleLog("Parse error. Counter offset should be an integer number. Using default value (0).");
topicCounterOffset = 0;
}
}
catch(Exception e) {
singleLog(e);
return;
}
setDefaultLogger();
setLogTitle("Finite group graph generator");
log("Creating a topic map for finite group (algebra).");
Topic[] topics = new Topic[n];
Topic operationType = getOrCreateTopic(topicmap, FINITE_GROUP_SI+"operation", "Operation");
Topic operand1T = getOrCreateTopic(topicmap, FINITE_GROUP_SI+"operand-1", "Operand 1");
Topic operand2T = getOrCreateTopic(topicmap, FINITE_GROUP_SI+"operand-2", "Operand 2");
Topic resultT = getOrCreateTopic(topicmap, FINITE_GROUP_SI+"result", "Result");
Association a = null;
Topic o1;
Topic o2;
Topic r;
long graphIdentifier = System.currentTimeMillis();
setProgressMax(n);
for(int i=0; i<n && !forceStop(); i++) {
setProgress(n);
topics[i] = getOrCreateTopic(topicmap, topicCounterOffset+i, graphIdentifier);
}
setProgressMax(n*n);
int progress=0;
for(int i=0; i<n && !forceStop(); i++) {
for(int j=0; j<n && !forceStop(); j++) {
o1 = topics[i];
o2 = topics[j];
r = topics[((i+j)%n)];
a = topicmap.createAssociation(operationType);
a.addPlayer(o1, operand1T);
a.addPlayer(o2, operand2T);
a.addPlayer(r, resultT);
setProgress(progress++);
}
}
if(connectWithWandoraClass) {
log("You'll find created topics and associations under the 'Finite group graph' topic.");
}
else {
String searchWord = basenamePattern.replaceAll("__n__", "");
searchWord = searchWord.trim();
log("You'll find created topics and associations by searching with a '"+searchWord+"'.");
}
log("Ready.");
setState(WAIT);
}
private Topic getOrCreateTopic(TopicMap topicmap, int topicIdentifier, long graphIdentifier) {
String newBasename = basenamePattern.replaceAll("__n__", ""+topicIdentifier);
String newSubjectIdentifier = siPattern.replaceAll("__n__", ""+topicIdentifier);
Topic t = getOrCreateTopic(topicmap, newSubjectIdentifier, newBasename);
if(connectWithWandoraClass) {
try {
Topic graphTopic = getOrCreateTopic(topicmap, FINITE_GROUP_SI, "Finite group graph");
Topic wandoraClass = getOrCreateTopic(topicmap, TMBox.WANDORACLASS_SI);
makeSuperclassSubclass(topicmap, wandoraClass, graphTopic);
Topic graphInstanceTopic = getOrCreateTopic(topicmap, FINITE_GROUP_SI+"/"+graphIdentifier, "Finite group graph "+graphIdentifier, graphTopic);
graphInstanceTopic.addType(graphTopic);
t.addType(graphInstanceTopic);
}
catch(Exception e) {
e.printStackTrace();
}
}
return t;
}
}
| 8,460 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
CalendarGenerator.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/generators/CalendarGenerator.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* CalendarGenerator.java
*
* Created on 22. tammikuuta 2007, 14:16
*/
package org.wandora.application.tools.generators;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Map;
import java.util.StringTokenizer;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.Context;
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.topicmap.XTMPSI;
/**
*
* @author akivela
*/
public class CalendarGenerator extends AbstractGenerator implements WandoraTool {
private static final long serialVersionUID = 1L;
public static String CALENDAR_SI_BODY = "http://wandora.org/si/calendar/";
/** Creates a new instance of CalendarGenerator */
public CalendarGenerator() {
}
@Override
public String getName() {
return "Calendar topic map generator";
}
@Override
public String getDescription() {
return "Generates a calendar topic map.";
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
TopicMap topicmap = solveContextTopicMap(wandora, context);
GenericOptionsDialog god=new GenericOptionsDialog(wandora,
"Calendar topic map generator",
"Creates a topic map that represents one year calendar.",
true,new String[][]{
new String[]{"Years","string", "", "Use comma (,) to separate years. Use minus (-) to define durations."},
},wandora);
god.setVisible(true);
if(god.wasCancelled()) return;
Map<String,String> values=god.getValues();
int[] yearNumbers = null;
ArrayList<String> yearNumberArray = new ArrayList<String>();
try {
String years = values.get("Years");
StringTokenizer st = new StringTokenizer(years, ",");
String yearToken = null;
while(st.hasMoreTokens()) {
yearToken = st.nextToken();
if(yearToken.indexOf("-") != -1) {
StringTokenizer dst = new StringTokenizer(yearToken, "-");
if(dst.countTokens() == 2) {
try {
String startYearS = dst.nextToken();
String endYearS = dst.nextToken();
int startYear = Integer.parseInt(startYearS);
int endYear = Integer.parseInt(endYearS);
for(int y=startYear; y<endYear; y++) {
yearNumberArray.add(""+y);
}
}
catch(Exception e) {
singleLog(e);
}
}
else {
singleLog("Invalid duration given!");
}
}
else {
yearNumberArray.add(yearToken);
}
}
// ***** Convert the string year array to integers! *****
yearNumbers = new int[yearNumberArray.size()];
for(int i=0; i<yearNumberArray.size(); i++) {
yearNumbers[i] = Integer.parseInt( yearNumberArray.get(i) );
}
}
catch(Exception e) {
singleLog("Invalid year '"+values.get("The year")+"' given!");
return;
}
if(yearNumbers == null) {
singleLog("Invalid years given!");
return;
}
setDefaultLogger();
setProgressMax(365 * yearNumbers.length);
setLogTitle("Calendar generator");
log("Creating topics for calendar");
int progress = 0;
for(int i=0; i<yearNumbers.length && !forceStop(); i++) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, yearNumbers[i]);
calendar.set(Calendar.MONTH, 0);
calendar.set(Calendar.DAY_OF_MONTH, 1);
while(calendar.get(Calendar.YEAR) == yearNumbers[i] && !forceStop()) {
setProgress(progress++);
log("Creating topics for " + DateFormat.getDateInstance().format(calendar.getTime()));
generateTopics(topicmap, calendar);
calendar.add(Calendar.DAY_OF_YEAR, 1);
}
}
if(forceStop()) log("User interruption!");
log("Ok!");
setState(WAIT);
}
public void generateTopics(TopicMap tm, Calendar calendar) {
try {
int year = calendar.get(Calendar.YEAR);
int month = 1+calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
int weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR);
Topic yearT = getOrCreateTopic(tm, CALENDAR_SI_BODY+"year/"+year, year+" (year)");
Topic yearType = getOrCreateTopic(tm, CALENDAR_SI_BODY+"year", "year");
yearT.addType(yearType);
Topic monthT = getOrCreateTopic(tm, CALENDAR_SI_BODY+"month/"+month, month+" (month)");
Topic monthType = getOrCreateTopic(tm, CALENDAR_SI_BODY+"month", "month");
monthT.addType(monthType);
Topic weekT = getOrCreateTopic(tm, CALENDAR_SI_BODY+"weekOfYear/"+weekOfYear, weekOfYear+" (week of year)");
Topic weekType = getOrCreateTopic(tm, CALENDAR_SI_BODY+"week", "week");
weekT.addType(weekType);
Topic dayOfWeekT = getOrCreateTopic(tm, CALENDAR_SI_BODY+"dayOfWeek/"+dayOfWeek, dayOfWeek+" (day of week)");
Topic dayOfWeekType = getOrCreateTopic(tm, CALENDAR_SI_BODY+"weekday", "weekday");
dayOfWeekT.addType(dayOfWeekType);
Topic dayT = getOrCreateTopic(tm, CALENDAR_SI_BODY+"dayOfMonth/"+day, day+" (day of month)");
Topic dayType = getOrCreateTopic(tm, CALENDAR_SI_BODY+"monthday", "monthday");
dayT.addType(dayType);
Topic dateT = getOrCreateTopic(tm, CALENDAR_SI_BODY+"date/"+year+"-"+month+"-"+day, year+"-"+month+"-"+day);
Topic dateType = getOrCreateTopic(tm, CALENDAR_SI_BODY+"date", "date");
dateT.addType(dateType);
Topic formattedDate = getOrCreateTopic(tm, CALENDAR_SI_BODY+"formattedDate", "formatted date");
dateT.setData(formattedDate, getOrCreateTopic(tm, XTMPSI.getLang(null), ""), DateFormat.getDateInstance().format(calendar.getTime()));
Topic monthOfYearT = getOrCreateTopic(tm, CALENDAR_SI_BODY+"monthOfYear", "month of year");
Association montha = tm.createAssociation(monthOfYearT);
montha.addPlayer(yearT, yearType);
montha.addPlayer(monthT, monthType);
Topic weekOfYearT = getOrCreateTopic(tm, CALENDAR_SI_BODY+"weekOfYear", "week of year");
Association weeka = tm.createAssociation(weekOfYearT);
weeka.addPlayer(yearT, yearType);
weeka.addPlayer(weekT, weekType);
Topic dayOfMonthT = getOrCreateTopic(tm, CALENDAR_SI_BODY+"dayOfMonth", "day of month");
Association daya = tm.createAssociation(dayOfMonthT);
daya.addPlayer(monthT, monthType);
daya.addPlayer(dayT, dayType);
Topic isDuring = getOrCreateTopic(tm, CALENDAR_SI_BODY+"isDuring", "is during");
Association isDuringA=null;
isDuringA = tm.createAssociation(isDuring);
isDuringA.addPlayer(dateT, dateType);
isDuringA.addPlayer(yearT, yearType);
isDuringA.addPlayer(monthT, monthType);
isDuringA.addPlayer(weekT, weekType);
isDuringA.addPlayer(dayOfWeekT, dayOfWeekType);
isDuringA.addPlayer(dayT, dayOfMonthT);
}
catch(Exception e) {
log(e);
}
}
}
| 9,121 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
PlatonicSolidGenerator.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/generators/PlatonicSolidGenerator.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* PlatonicSolidGenerator.java
*
* Created on 12. joulukuuta 2007, 12:16
*
*/
package org.wandora.application.tools.generators;
import java.util.Map;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.Context;
import org.wandora.application.tools.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.swing.GuiTools;
/**
*
* @author akivela
*/
public class PlatonicSolidGenerator extends AbstractGenerator implements WandoraTool {
private static final long serialVersionUID = 1L;
public static boolean connectWithWandoraClass = true;
public static String PLATONIC_SOLID_GRAPH_SI = "http://wandora.org/si/platonic-solid";
/** Creates a new instance of PlatonicSolidGenerator */
public PlatonicSolidGenerator() {
}
@Override
public String getName() {
return "Platonic solid generator";
}
@Override
public String getDescription() {
return "Generates topic map graphs for platonic solids such as tetrahedron and cube.";
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
TopicMap topicmap = solveContextTopicMap(wandora, context);
GenericOptionsDialog god=new GenericOptionsDialog(wandora,
"Platonic solid generator",
"Platonic solid generator creates topic map graphs for platonic solids. "+
"Topic map graph consists of topics and associations. Topics are graph nodes and "+
"associations graph edges. "+
"Select one or more graphs to create.",
true,new String[][]{
new String[]{"Tetrahedron graph","boolean"},
new String[]{"Cube graph","boolean"},
new String[]{"Octahedron graph","boolean"},
new String[]{"Dodecahedron graph","boolean"},
new String[]{"Icosahedron graph","boolean"},
new String[]{"---1","separator"},
new String[]{"Connect topics with Wandora class","boolean", connectWithWandoraClass ? "true" : "false","Create additional topics and associations that connect created topics with the Wandora class." },
},wandora);
god.setSize(600, 400);
GuiTools.centerWindow(god,wandora);
god.setVisible(true);
if(god.wasCancelled()) return;
Map<String,String> values=god.getValues();
try {
connectWithWandoraClass = "true".equalsIgnoreCase(values.get("Connect topics with Wandora class"));
}
catch(Exception e) {
log(e);
return;
}
setDefaultLogger();
setLogTitle("Platonic solid generator");
try {
if("true".equals(values.get("Tetrahedron graph"))) {
generateTetrahedron(topicmap);
}
if("true".equals(values.get("Cube graph"))) {
generateCube(topicmap);
}
if("true".equals(values.get("Octahedron graph"))) {
generateOctahedron(topicmap);
}
if("true".equals(values.get("Dodecahedron graph"))) {
generateDodecahedron(topicmap);
}
if("true".equals(values.get("Icosahedron graph"))) {
generateIcosahedron(topicmap);
}
}
catch(Exception e) {
log(e);
}
setState(WAIT);
}
public void generateTetrahedron(TopicMap topicmap) throws TopicMapException {
String TETRAHEDRON_SI = "http://wandora.org/si/platonic-solid/tetrahedron/";
log("Creating tetrahedron.");
setProgressMax(4+6);
int progress = 0;
long graphIdentifier = System.currentTimeMillis();
Topic[] nodes = new Topic[4];
for(int i=0; i<4 && !forceStop(); i++) {
nodes[i] = getOrCreateTopic(topicmap, TETRAHEDRON_SI+graphIdentifier+"/vertex/"+i, "Tetrahedron vertex "+i+" ("+graphIdentifier+")");
setProgress(++progress);
if(connectWithWandoraClass) {
Topic graphTopic = getOrCreateTopic(topicmap, TETRAHEDRON_SI+graphIdentifier, "Tetrahedron graph "+graphIdentifier);
connect(topicmap, nodes[i], graphTopic);
}
}
Topic t1 = null;
Topic t2 = null;
Topic aType = getOrCreateTopic(topicmap, TETRAHEDRON_SI+"edge", "Tetrahedron edge");
Topic role1 = getOrCreateTopic(topicmap, TETRAHEDRON_SI+"role-1", "Tetrahedron role 1");
Topic role2 = getOrCreateTopic(topicmap, TETRAHEDRON_SI+"role-2", "Tetrahedron role 2");
Association a = null;
for(int i=0; i<3 && !forceStop(); i++) {
try {
t1 = nodes[i];
t2 = nodes[(i+1) % 3];
a = topicmap.createAssociation(aType);
a.addPlayer(t1, role1);
a.addPlayer(t2, role2);
setProgress(++progress);
t1 = nodes[i];
t2 = nodes[3];
a = topicmap.createAssociation(aType);
a.addPlayer(t1, role1);
a.addPlayer(t2, role2);
setProgress(++progress);
}
catch(Exception e) {
log(e);
}
}
log("Ready.");
}
public void generateCube(TopicMap topicmap) throws TopicMapException {
String CUBE_SI = "http://wandora.org/si/platonic-solid/cube/";
log("Creating cube.");
setProgressMax(8+12);
int progress = 0;
long graphIdentifier = System.currentTimeMillis();
Topic[] nodes = new Topic[8];
for(int i=0; i<8 && !forceStop(); i++) {
nodes[i] = getOrCreateTopic(topicmap, CUBE_SI+graphIdentifier+"/vertex/"+i, "Cube vertex "+i+" ("+graphIdentifier+")");
setProgress(++progress);
if(connectWithWandoraClass) {
Topic graphTopic = getOrCreateTopic(topicmap, CUBE_SI+graphIdentifier, "Cube graph "+graphIdentifier);
connect(topicmap, nodes[i], graphTopic);
}
}
Topic t1 = null;
Topic t2 = null;
Topic aType = getOrCreateTopic(topicmap, CUBE_SI+"edge", "Cube edge");
Topic role1 = getOrCreateTopic(topicmap, CUBE_SI+"role-1", "Cube role 1");
Topic role2 = getOrCreateTopic(topicmap, CUBE_SI+"role-2", "Cube role 2");
Association a = null;
for(int i=0; i<4 && !forceStop(); i++) {
try {
// ***** first rectangle
t1 = nodes[i];
t2 = nodes[(i+1) % 4];
a = topicmap.createAssociation(aType);
a.addPlayer(t1, role1);
a.addPlayer(t2, role2);
setProgress(++progress);
// ***** second rectangle
t1 = nodes[4 + i];
t2 = nodes[4 + ((i+1) % 4)];
a = topicmap.createAssociation(aType);
a.addPlayer(t1, role1);
a.addPlayer(t2, role2);
setProgress(++progress);
// ***** edge between first and second rectangle
t1 = nodes[i];
t2 = nodes[4 + ((i+1) % 4)];
a = topicmap.createAssociation(aType);
a.addPlayer(t1, role1);
a.addPlayer(t2, role2);
setProgress(++progress);
}
catch(Exception e) {
log(e);
}
}
log("Ready.");
}
public void generateOctahedron(TopicMap topicmap) throws TopicMapException {
String OCTAHEDRON_SI = "http://wandora.org/si/platonic-solid/octahedron/";
log("Creating octahedron.");
setProgressMax(6+12);
int progress = 0;
long graphIdentifier = System.currentTimeMillis();
Topic[] nodes = new Topic[6];
for(int i=0; i<6 && !forceStop(); i++) {
setProgress(++progress);
nodes[i] = getOrCreateTopic(topicmap, OCTAHEDRON_SI+graphIdentifier+"/vertex/"+i, "Octahedron vertex "+i+" ("+graphIdentifier+")");
if(connectWithWandoraClass) {
Topic graphTopic = getOrCreateTopic(topicmap, OCTAHEDRON_SI+graphIdentifier, "Octahedron graph "+graphIdentifier);
connect(topicmap, nodes[i], graphTopic);
}
}
Topic t1 = null;
Topic t2 = null;
Topic aType = getOrCreateTopic(topicmap, OCTAHEDRON_SI+"edge", "Octahedron edge");
Topic role1 = getOrCreateTopic(topicmap, OCTAHEDRON_SI+"role-1", "Octahedron role 1");
Topic role2 = getOrCreateTopic(topicmap, OCTAHEDRON_SI+"role-2", "Octahedron role 2");
Association a = null;
for(int i=0; i<4 && !forceStop(); i++) {
try {
t1 = nodes[i];
t2 = nodes[i+1==4 ? 0 : i+1];
a = topicmap.createAssociation(aType);
a.addPlayer(t1, role1);
a.addPlayer(t2, role2);
setProgress(++progress);
t1 = nodes[i];
t2 = nodes[4];
a = topicmap.createAssociation(aType);
a.addPlayer(t1, role1);
a.addPlayer(t2, role2);
setProgress(++progress);
t1 = nodes[i];
t2 = nodes[5];
a = topicmap.createAssociation(aType);
a.addPlayer(t1, role1);
a.addPlayer(t2, role2);
setProgress(++progress);
}
catch(Exception e) {
log(e);
}
}
log("Ready.");
}
int[][] dodecahedronEdges = new int[][] {
{ 1,2 },
{ 2,3 },
{ 3,4 },
{ 4,5 },
{ 5,1 },
{ 1,14 },
{ 2,12 },
{ 3,10 },
{ 4,8 },
{ 5,6 },
{ 6,7 },
{ 7,8 },
{ 8,9 },
{ 9,10 },
{ 10,11 },
{ 11,12 },
{ 12,13 },
{ 13,14 },
{ 14,15 },
{ 15,6 },
{ 7,17 },
{ 9,18 },
{ 11,19 },
{ 13,20 },
{ 15,16 },
{ 16,17 },
{ 17,18 },
{ 18,19 },
{ 19,20 },
{ 20,16 },
};
public void generateDodecahedron(TopicMap topicmap) throws TopicMapException {
String DODECAHEDRON_SI = "http://wandora.org/si/platonic-solid/dodecahedron/";
log("Creating dodecahedron.");
setProgressMax(20+30);
int progress = 0;
long graphIdentifier = System.currentTimeMillis();
Topic[] nodes = new Topic[20];
for(int i=0; i<20 && !forceStop(); i++) {
setProgress(++progress);
nodes[i] = getOrCreateTopic(topicmap, DODECAHEDRON_SI+graphIdentifier+"/vertex/"+i, "Dodecahedron vertex "+i+" ("+graphIdentifier+")");
if(connectWithWandoraClass) {
Topic graphTopic = getOrCreateTopic(topicmap, DODECAHEDRON_SI+graphIdentifier, "Dodecahedron graph "+graphIdentifier);
connect(topicmap, nodes[i], graphTopic);
}
}
Topic t1 = null;
Topic t2 = null;
Topic aType = getOrCreateTopic(topicmap, DODECAHEDRON_SI+"edge", "Dodecahedron edge");
Topic role1 = getOrCreateTopic(topicmap, DODECAHEDRON_SI+"role-1", "Dodecahedron role 1");
Topic role2 = getOrCreateTopic(topicmap, DODECAHEDRON_SI+"role-2", "Dodecahedron role 2");
Association a = null;
for(int i=0; i<dodecahedronEdges.length && !forceStop(); i++) {
try {
t1 = nodes[dodecahedronEdges[i][0] - 1];
t2 = nodes[dodecahedronEdges[i][1] - 1];
a = topicmap.createAssociation(aType);
a.addPlayer(t1, role1);
a.addPlayer(t2, role2);
setProgress(++progress);
}
catch(Exception e) {
log(e);
}
}
log("Ready.");
}
int[][] icosahedronEdges = new int[][] {
{ 1,2 },
{ 1,6 },
{ 1,7 },
{ 1,8 },
{ 3,8 },
{ 3,9 },
{ 3,4 },
{ 2,4 },
{ 2,5 },
{ 2,6 },
{ 2,3 },
{ 3,1 },
{ 4,5 },
{ 5,6 },
{ 6,7 },
{ 7,8 },
{ 8,9 },
{ 9,4 },
{ 4,10 },
{ 5,10 },
{ 5,11 },
{ 6,11 },
{ 7,11 },
{ 7,12 },
{ 8,12 },
{ 9,12 },
{ 9,10 },
{ 10,11 },
{ 11,12 },
{ 12,10 }
};
public void generateIcosahedron(TopicMap topicmap) throws TopicMapException {
String ICOSAHEDRON_SI = "http://wandora.org/si/platonic-solid/icosahedron/";
log("Creating icosahedron.");
setProgressMax(12+30);
int progress = 0;
long graphIdentifier = System.currentTimeMillis();
Topic[] nodes = new Topic[12];
for(int i=0; i<12 && !forceStop(); i++) {
setProgress(++progress);
nodes[i] = getOrCreateTopic(topicmap, ICOSAHEDRON_SI+graphIdentifier+"/vertex/"+i, "Icosahedron vertex "+i+" ("+graphIdentifier+")");
if(connectWithWandoraClass) {
Topic graphTopic = getOrCreateTopic(topicmap, ICOSAHEDRON_SI+graphIdentifier, "Icosahedron graph "+graphIdentifier);
connect(topicmap, nodes[i], graphTopic);
}
}
Topic t1 = null;
Topic t2 = null;
Topic aType = getOrCreateTopic(topicmap, ICOSAHEDRON_SI+"edge", "Icosahedron edge");
Topic role1 = getOrCreateTopic(topicmap, ICOSAHEDRON_SI+"role-1", "Icosahedron role 1");
Topic role2 = getOrCreateTopic(topicmap, ICOSAHEDRON_SI+"role-2", "Icosahedron role 2");
Association a = null;
for(int i=0; i<icosahedronEdges.length && !forceStop(); i++) {
try {
t1 = nodes[icosahedronEdges[i][0] - 1];
t2 = nodes[icosahedronEdges[i][1] - 1];
a = topicmap.createAssociation(aType);
a.addPlayer(t1, role1);
a.addPlayer(t2, role2);
setProgress(++progress);
}
catch(Exception e) {
log(e);
}
}
log("Ready.");
}
private void connect(TopicMap topicmap, Topic vertexTopic, Topic platonicSolidInstance) {
try {
Topic platonicSolidType = getOrCreateTopic(topicmap, PLATONIC_SOLID_GRAPH_SI, "Platonic solid");
Topic wandoraClass = getOrCreateTopic(topicmap, TMBox.WANDORACLASS_SI);
makeSuperclassSubclass(topicmap, wandoraClass, platonicSolidType);
platonicSolidInstance.addType(platonicSolidType);
vertexTopic.addType(platonicSolidInstance);
}
catch(Exception e) {
e.printStackTrace();
}
}
}
| 16,299 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
HTTPServerStop.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/server/HTTPServerStop.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.server;
/**
*
* @author akivela
*/
public class HTTPServerStop extends HTTPServerTool {
private static final long serialVersionUID = 1L;
public HTTPServerStop(){
super(HTTPServerTool.STOP);
}
}
| 1,052 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
HTTPServerOpenPage.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/server/HTTPServerOpenPage.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.server;
/**
*
* @author akivela
*/
public class HTTPServerOpenPage extends HTTPServerTool {
private static final long serialVersionUID = 1L;
public HTTPServerOpenPage(){
super(HTTPServerTool.OPEN_PAGE);
}
}
| 1,064 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
HTTPServerStart.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/server/HTTPServerStart.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.server;
/**
*
* @author akivela
*/
public class HTTPServerStart extends HTTPServerTool {
private static final long serialVersionUID = 1L;
public HTTPServerStart(){
super(HTTPServerTool.START);
}
}
| 1,056 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
HTTPServerTool.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/server/HTTPServerTool.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.server;
import java.awt.Desktop;
import java.net.URI;
import java.util.Map;
import javax.swing.Icon;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.wandora.application.Wandora;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.UIBox;
import org.wandora.application.gui.WandoraOptionPane;
import org.wandora.application.gui.topicpanels.webview.WebViewPanel;
import org.wandora.application.modulesserver.ModulesWebApp;
import org.wandora.application.modulesserver.WandoraModulesServer;
import org.wandora.application.tools.AbstractWandoraTool;
import org.wandora.application.tools.GenericOptionsDialog;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author olli
*/
public class HTTPServerTool extends AbstractWandoraTool {
private static final long serialVersionUID = 1L;
public static final int CONFIGURE=1;
public static final int START=2;
public static final int STOP=4;
public static final int CONFIGURE_AND_START=CONFIGURE+START;
public static final int UPDATE_MENU=8;
public static final int START_AND_MENU=START+UPDATE_MENU;
public static final int STOP_AND_MENU=STOP+UPDATE_MENU;
public static final int OPEN_PAGE=16;
public static final int OPEN_PAGE_IN_BROWSER_TOPIC_PANEL=32;
private int mode;
private String forceUrl = null;
private Object param2 = null;
private ModulesWebApp webApp = null;
public HTTPServerTool(int mode, String fu, Object param2) {
super();
this.mode=mode;
this.forceUrl = fu;
this.param2 = param2;
}
public HTTPServerTool(int mode, String fu){
super();
this.mode=mode;
this.forceUrl = fu;
}
public HTTPServerTool(int mode, ModulesWebApp webApp, Object param2) {
super();
this.mode=mode;
this.webApp = webApp;
this.param2 = param2;
}
public HTTPServerTool(int mode, ModulesWebApp webApp){
super();
this.mode=mode;
this.webApp=webApp;
}
public HTTPServerTool(int mode){
super();
this.mode=mode;
}
@Override
public Icon getIcon() {
if((mode&CONFIGURE)!=0) return UIBox.getIcon("gui/icons/server_configure.png");
if((mode&START)!=0) return UIBox.getIcon("gui/icons/server_start.png");
if((mode&STOP)!=0) return UIBox.getIcon("gui/icons/server_stop.png");
if((mode&OPEN_PAGE)!=0) return UIBox.getIcon("gui/icons/server_open.png");
if((mode&OPEN_PAGE_IN_BROWSER_TOPIC_PANEL)!=0) return UIBox.getIcon("gui/icons/server_open.png");
return super.getIcon();
}
@Override
public String getName() {
if((mode&CONFIGURE)!=0) return "HTTP server configuration";
if((mode&START)!=0) return "Start HTTP server";
if((mode&STOP)!=0) return "Stop HTTP server";
if((mode&OPEN_PAGE)!=0) return "Open topic with Wandora HTTP server...";
if((mode&OPEN_PAGE_IN_BROWSER_TOPIC_PANEL)!=0) return "Open topic in Browser topic panel";
return "Wandora HTTP server tool";
}
@Override
public String getDescription() {
if((mode&CONFIGURE)!=0) return "Open Wandora HTTP server configuration dialog...";
if((mode&START)!=0) return "Start Wandora HTTP server";
if((mode&STOP)!=0) return "Stop Wandora HTTP server";
if((mode&OPEN_PAGE)!=0) return "Open current topic with external browser and Wandora's HTTP server...";
if((mode&OPEN_PAGE_IN_BROWSER_TOPIC_PANEL)!=0) return "Open current topic with Browser topic panel and Wandora's HTTP server...";
return "Wandora HTTP server tool";
}
@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {
if((mode&CONFIGURE) != 0) {
WandoraModulesServer server = wandora.getHTTPServer();
String u=null; //s.getLoginUser();
String p=null; //s.getLoginPassword();
if(u==null) u="";
if(p==null) p="";
String[] logLevels={"trace","debug","info","warn","error","fatal","none"};
GenericOptionsDialog god=new GenericOptionsDialog(wandora,"Wandora HTTP server settings","Wandora HTTP server settings",true,new String[][]{
new String[]{"Auto start","boolean",""+server.isAutoStart(),"Start server automatically when you start Wandora"},
new String[]{"Port","string",""+server.getPort(),"Port the server is listening to"},
new String[]{"Local only","boolean",""+server.isLocalOnly(),"Allow only local connections"},
new String[]{"Use SSL","boolean",""+server.isUseSSL(),"Should server use SSL"},
new String[]{"Keystore location","string",""+server.getKeystoreFile(),"Where SSL keystore file locates? Keystore is used only if you have selected to use SLL."},
new String[]{"Keystore password","string",""+server.getKeystorePassword(),"Keystore's password. Keystore is used only if you have selected to use SLL."},
// new String[]{"User name","string",u,"User name. Leave empty for anonymous login"},
// new String[]{"Password","password",p,"Password for the user if user name field is used"},
new String[]{"Server path","string",server.getServerPath(),"Path where Wandora web apps are deployed"},
// new String[]{"Static content path","string",s.getStaticPath(),"Path where static files are located"},
// new String[]{"Template path","string",s.getTemplatePath(),"Path where Velocity templates are located"},
// new String[]{"Template","string",s.getTemplateFile(),"Template file used to create a topic page"},
new String[]{"Log level","combo:"+StringUtils.join(logLevels,";"),logLevels[server.getLogLevel()],"Lowest level of log messages that are printed"},
},wandora);
god.setSize(800, 400);
if(wandora != null) wandora.centerWindow(god);
god.setVisible(true);
if(god.wasCancelled()) return;
boolean running = server.isRunning();
if(running) server.stopServer();
Map<String,String> values = god.getValues();
server.setAutoStart(Boolean.parseBoolean(values.get("Auto start")));
server.setPort(Integer.parseInt(values.get("Port")));
server.setLocalOnly(Boolean.parseBoolean(values.get("Local only")));
server.setUseSSL(Boolean.parseBoolean(values.get("Use SSL")));
server.setKeystoreFile(values.get("Keystore location"));
server.setKeystorePassword(values.get("Keystore password"));
// server.setLogin(values.get("User name"),values.get("Password"));
// server.setStaticPath(values.get("Static content path"));
// server.setTemplatePath(values.get("Template path"));
// server.setTemplateFile(values.get("Template"));
server.setServerPath(values.get("Server path"));
server.setLogLevel(ArrayUtils.indexOf(logLevels, values.get("Log level")));
server.writeOptions(wandora.getOptions());
server.initModuleManager();
server.readBundleDirectories();
if(running) server.start();
wandora.menuManager.refreshServerMenu();
}
if((mode&START) != 0) {
wandora.startHTTPServer();
}
else if((mode&STOP) != 0) {
wandora.stopHTTPServer();
}
if((mode&UPDATE_MENU) != 0) {
wandora.menuManager.refreshServerMenu();
}
if((mode&OPEN_PAGE) !=0) {
try {
if(!wandora.getHTTPServer().isRunning()) {
int a = WandoraOptionPane.showConfirmDialog(wandora, "HTTP server is not running at the moment. Would you like to start the server first?", "Start HTTP server?", WandoraOptionPane.OK_CANCEL_OPTION);
if( a == WandoraOptionPane.OK_OPTION) {
wandora.startHTTPServer();
wandora.menuManager.refreshServerMenu();
}
else if( a == WandoraOptionPane.CANCEL_OPTION) {
return;
}
}
WandoraModulesServer s = wandora.getHTTPServer();
String uri = (s.isUseSSL() ? "https" : "http")+"://127.0.0.1:"+s.getPort()+"/topic";
if(forceUrl != null) uri = forceUrl;
else if(webApp!=null) {
uri=webApp.getAppStartPage();
if(uri==null) {
WandoraOptionPane.showMessageDialog(wandora, "Can't launch selected webapp. Webapp says it's URI is null.");
return;
}
}
try {
Desktop desktop = Desktop.getDesktop();
desktop.browse(new URI(uri));
}
catch(Exception e) {
log(e);
}
}
catch(Exception e) {
wandora.handleError(e);
}
}
if((mode&OPEN_PAGE_IN_BROWSER_TOPIC_PANEL)!=0){
try {
if(!wandora.getHTTPServer().isRunning()) {
int a = WandoraOptionPane.showConfirmDialog(wandora, "HTTP server is not running at the moment. Would you like to start the server first?", "Start HTTP server?", WandoraOptionPane.OK_CANCEL_OPTION);
if( a == WandoraOptionPane.OK_OPTION) {
wandora.startHTTPServer();
wandora.menuManager.refreshServerMenu();
}
}
WandoraModulesServer s=wandora.getHTTPServer();
String uri = (s.isUseSSL() ? "https" : "http")+"://127.0.0.1:"+s.getPort()+"/topic";
if(forceUrl != null) uri = forceUrl;
else if(webApp!=null) {
uri=webApp.getAppStartPage();
if(uri==null) {
WandoraOptionPane.showMessageDialog(wandora, "Can't launch selected webapp. Webapp says it's URI is null.");
return;
}
}
try {
if(param2 != null) {
if(param2 instanceof WebViewPanel) {
WebViewPanel browserTopicPanel = (WebViewPanel) param2;
browserTopicPanel.browse(uri);
}
}
}
catch(Exception e) {
log(e);
}
}
catch(Exception e) {
wandora.handleError(e);
}
}
}
}
| 11,991 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SOMVector.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/som/SOMVector.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* SOMVector.java
*
* Created on 29. heinakuuta 2008, 17:42
*
*/
package org.wandora.application.tools.som;
/**
*
* @author akivela
*/
public class SOMVector {
private double[] vector = null;
public SOMVector(int dimension) {
dimension = Math.abs(dimension);
this.vector = new double[dimension];
}
public SOMVector(double[] v) {
this.vector = v;
}
public double get(int i) {
return vector[i];
}
public void set(int i, double value) {
vector[i] = value;
}
public int dimension() {
if(vector == null) return 0;
else return vector.length;
}
public double length() {
double l = 0.0;
if(vector == null) return l;
for(int i=0; i<vector.length; i++) {
l += vector[i]*vector[i];
}
return Math.sqrt(l);
}
public double distance(SOMVector other) throws IllegalDimensionException {
if(other == null) throw new NullPointerException();
if(other.dimension() != this.dimension()) throw new IllegalDimensionException();
SOMVector diff = this.duplicate();
diff.sub(other);
return diff.length();
}
public void sub(SOMVector s) throws IllegalDimensionException {
if(vector == null) return;
if(s == null) throw new NullPointerException();
if(s.dimension() != this.dimension()) throw new IllegalDimensionException();
for(int i=0; i<vector.length; i++) {
vector[i] -= s.get(i);
}
}
public void add(SOMVector s) throws IllegalDimensionException {
if(vector == null) return;
if(s == null) throw new NullPointerException();
if(s.dimension() != this.dimension()) throw new IllegalDimensionException();
for(int i=0; i<vector.length; i++) {
vector[i] += s.get(i);
}
}
public void sub(double d) {
if(vector == null) return;
for(int i=0; i<vector.length; i++) {
vector[i] -= d;
}
}
public void add(double d) {
if(vector == null) return;
for(int i=0; i<vector.length; i++) {
vector[i] += d;
}
}
public void multiply(double d) {
if(vector == null) return;
for(int i=0; i<vector.length; i++) {
vector[i] *= d;
}
}
public void div(double d) {
if(vector == null) return;
for(int i=0; i<vector.length; i++) {
vector[i] /= d;
}
}
public void normalize() {
if(vector == null) return;
double d = length();
for(int i=0; i<vector.length; i++) {
vector[i] /= d;
}
}
public SOMVector duplicate() {
int d = this.dimension();
SOMVector n = new SOMVector(d);
for(int i=0; i<vector.length; i++) {
n.set(i, vector[i]);
}
return n;
}
public void print() {
System.out.print("[ ");
for(int i=0; i<vector.length; i++) {
System.out.print( vector[i]+";" );
}
System.out.println(" ]");
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("[ ");
int m = vector.length-1;
for(int i=0; i<m; i++) {
sb.append(vector[i]).append( " ; ");
}
sb.append(vector[vector.length-1]).append( " ]");
return sb.toString();
}
public String toNLString() {
StringBuilder sb = new StringBuilder("");
int m = vector.length-1;
for(int i=0; i<m; i++) {
sb.append(vector[i]).append( "\n");
}
sb.append( vector[vector.length-1] );
return sb.toString();
}
}
| 4,581 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SOMNeuron.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/som/SOMNeuron.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* SOMNeuron.java
*
* Created on 29. heinakuuta 2008, 17:42
*
*/
package org.wandora.application.tools.som;
/**
*
* @author akivela
*/
public class SOMNeuron {
private SOMVector vector = null;
public SOMNeuron(int dim) {
this.vector = new SOMVector(dim);
}
public SOMNeuron(SOMVector v) {
this.vector = v;
}
public SOMVector getSOMVector() {
return vector;
}
public void setSOMVector(SOMVector v) {
vector = v;
}
public void randomize() {
if(vector == null) throw new NullPointerException();
int d = vector.dimension();
for(int i=0; i<d; i++) {
vector.set(i, Math.random() > 0.5 ? 1 : 0);
}
}
public void print() {
if(vector == null) System.out.println("-null-");
else vector.print();
}
@Override
public String toString() {
if(vector == null) return "null";
else return vector.toString();
}
public String toNLString() {
if(vector == null) return "null";
else return vector.toNLString();
}
}
| 1,934 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SOMClassifier.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/som/SOMClassifier.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* SOMClassifier.java
*
* Created on 29. heinakuuta 2008, 17:42
*
*/
package org.wandora.application.tools.som;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
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.contexts.LayeredTopicContext;
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>
* Creates a Self Organized Map (SOM) using given associations.
* SOM is a 2D matrix visualization of given association player topics where
* similar topics i.e. topics with similar associations locate near each other.
* Tool is able to group similar topics.
* </p>
* <p>
* This class is strictly speaking the a train vector builder while the
* actual SOM implementation locates in class SOMMap.
* </p>
* <p>
* About train vector building: Lets say user has selected eight binary associations
* a-q, a-e, a-t, b-e, b-l, c-q, c-o, and d-e. User selects first player as the
* grouping role. Training vectors for this setting are:
* </p>
* <p>
* a: [ q=1, e=1, t=1, l=0, o=0 ] <br>
* b: [ q=0, e=1, t=0, l=1, o=0 ] <br>
* c: [ q=1, e=0, t=1, l=0, o=1 ] <br>
* d: [ q=0, e=1, t=0, l=0, o=0 ] <br>
* </p>
* <p>
* in other words: <br>
* a: [ 1, 1, 1, 0, 0 ] <br>
* b: [ 0, 1, 0, 1, 0 ] <br>
* c: [ 1, 0, 1, 0, 1 ] <br>
* d: [ 0, 1, 0, 0, 0 ] <br>
* </p>
* <p>
* One should note SOM gives best results if vectors are NOT orthogonal.
* </p>
* <p>
* Read more about Self Organizing Maps here:
* http://en.wikipedia.org/wiki/Self-organizing_map
* </p>
*
* @author akivela
*/
public class SOMClassifier extends AbstractWandoraTool implements WandoraTool {
private static final long serialVersionUID = 1L;
public SOMClassifier(Context preferredContext) {
this.setContext(preferredContext);
}
@Override
public String getName() {
return "SOM of associations";
}
@Override
public String getDescription() {
return "Creates a Self Organized Map (SOM) using given associations. "+
"SOM is a 2D matrix visualization of given association player topics where "+
"similar topics i.e. topics with similar associations locate near each other. "+
"Tool is able to group similar topics.";
}
public void execute(Wandora wandora, Context context) {
if(context instanceof AssociationContext) {
try {
Iterator<Association> associations = context.getContextObjects();
Set<Topic> roles = getRolesFrom(associations);
if(roles.size() > 0) {
Topic groupingRole = (Topic) WandoraOptionPane.showOptionDialog(wandora, "Select grouping role topic", "Select grouping role topic", WandoraOptionPane.OK_CANCEL_OPTION, roles.toArray( new Topic[]{} ), roles.iterator().next());
// Topic groupingRole = admin.showTopicFinder(admin, "Select grouping role topic");
setDefaultLogger();
setLogTitle("SOM of associations");
if(groupingRole != null) {
log("Building input vectors");
Map<Topic,Set<Topic>> inputSets = buildInputSets(wandora, groupingRole, context.getContextObjects());
Map<Topic,SOMVector> inputVectors = buildInputVectors(inputSets);
log("Training SOM");
SOMMap map = new SOMMap(inputVectors, this);
SOMTopicVisualization visualization = new SOMTopicVisualization(wandora);
setState(INVISIBLE);
visualization.visualize(map);
setState(VISIBLE);
log("Ready.");
}
else {
log("Grouping role was not selected. Cancelling.");
}
}
else {
log("No roles found. Cancelling.");
}
}
catch(Exception e) {
log(e);
}
}
else if( context instanceof LayeredTopicContext ) {
System.out.println("LayeredTopicContext not processed!");
}
else {
System.out.println("Unknown context not processed!");
}
setState(WAIT);
}
private Set<Topic> getRolesFrom(Iterator<Association> associations) throws TopicMapException {
Set<Topic> roles = new HashSet<Topic>();
if(associations != null && associations.hasNext()) {
Association a = null;
Collection<Topic> aroles = null;
while(associations.hasNext() && !forceStop()) {
a = associations.next();
if(a != null && !a.isRemoved()) {
aroles = a.getRoles();
roles.addAll(aroles);
}
}
}
return roles;
}
private Map<Topic,Set<Topic>> buildInputSets(Wandora admin, Topic groupingRole, Iterator<Association> associations) {
HashMap<Topic,Set<Topic>> resultSets = new LinkedHashMap<Topic,Set<Topic>>();
Association a = null;
Topic groupingTopic = null;
Topic role = null;
Topic player = null;
Set<Topic> resultSet;
while(associations.hasNext()) {
try {
a = associations.next();
groupingTopic = a.getPlayer(groupingRole);
resultSet = resultSets.get(groupingTopic);
if(resultSet == null) {
resultSet = new HashSet<Topic>();
resultSets.put(groupingTopic, resultSet);
}
Collection<Topic> roles = a.getRoles();
Iterator<Topic> roleIterator = roles.iterator();
while(roleIterator.hasNext()) {
role = roleIterator.next();
if(!role.mergesWithTopic(groupingRole)) {
player = a.getPlayer(role);
if(player != null && !player.isRemoved()) {
resultSet.add(player);
}
}
}
}
catch(Exception e) {
log(e);
}
}
return resultSets;
}
private Map<Topic,SOMVector> buildInputVectors(Map<Topic,Set<Topic>> inputSets) {
ArrayList<Topic> fullVector = new ArrayList<Topic>();
Collection<Set<Topic>> sets = inputSets.values();
Set<Topic> set = null;
Topic t = null;
for(Iterator<Set<Topic>> setIterator = sets.iterator(); setIterator.hasNext(); ) {
try {
set = setIterator.next();
for(Iterator<Topic> topicIterator = set.iterator(); topicIterator.hasNext(); ) {
t = topicIterator.next();
if(t != null && !t.isRemoved()) {
if(!fullVector.contains(t)) fullVector.add(t);
}
}
}
catch(Exception e) {
log(e);
}
}
Map<Topic,SOMVector> inputVectors = new LinkedHashMap<Topic,SOMVector>();
int s = fullVector.size();
Set<Topic> keys = inputSets.keySet();
Iterator<Topic> keyIterator = keys.iterator();
Topic key = null;
set = null;
Topic[] vector = null;
while(keyIterator.hasNext()) {
try {
key = keyIterator.next();
if(key != null && !key.isRemoved()) {
set = inputSets.get(key);
vector = new Topic[s];
for(Iterator<Topic> topicIterator = set.iterator(); topicIterator.hasNext(); ) {
t = topicIterator.next();
if(t != null && !t.isRemoved()) {
int i = fullVector.indexOf(t);
vector[i] = t;
}
}
inputVectors.put(key, topicVector2SOMVector(vector));
}
}
catch(Exception e) {
log(e);
}
}
return inputVectors;
}
public SOMVector topicVector2SOMVector(Topic[] topicVector) {
int dim = topicVector.length;
SOMVector somVector = new SOMVector(dim);
for(int i=0; i<dim; i++) {
if(topicVector[i] == null) somVector.set(i, 0);
else somVector.set(i, 1);
}
return somVector;
}
// -------------------------------------------------------------------------
}
| 10,138 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SOMTopicVisualizationPanel.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/som/SOMTopicVisualizationPanel.java |
package org.wandora.application.tools.som;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.swing.JDialog;
import javax.swing.JPanel;
import org.wandora.application.gui.UIBox;
import org.wandora.application.gui.WandoraOptionPane;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.utils.ClipboardBox;
import org.wandora.utils.Tuples.T3;
/**
*
* @author akivela
*/
public class SOMTopicVisualizationPanel extends JPanel implements Runnable, ActionListener, MouseListener, MouseMotionListener, KeyListener {
private static final long serialVersionUID = 1L;
public static final String SI_PREFIX = "http://wandora.org/si/som/";
public static final String ASSOCIATE_TOPICS_IN_EVERY_CELL_TO_A_CELL_SPECIFIC_GROUP = "Group topics in every cell";
public static final String ASSOCIATE_TOPICS_IN_SELECTED_CELLS_TO_A_GROUP = "Group topics in selected cells";
public static final String PERMUTATE_TOPICS_WITHIN_EVERY_CELL = "Permutate topics within every cell";
public static final String PERMUTATE_TOPICS_WITHIN_SELECTED_CELLS = "Permutate topics within selected cells";
public static final String PERMUTATE_ALL_TOPICS_IN_SELECTED_CELLS = "Permutate all topics in selected cells";
public static final String COPY_AS_IMAGE = "Copy as image";
public static final String COPY_CELL_TOPICS_VECTORS = "Copy cell topic vectors";
public static final String COPY_CELL_TOPICS = "Copy cell topics";
public static final String COPY_CELL_NEURONS = "Copy cell neurons";
public static final String SELECT_CELL = "Select cell";
public static final String DESELECT_CELL = "Deselect cell";
public static final String SELECT_ALL_CELLS = "Select all cells";
public static final String CLEAR_SELECTION = "Clear selection";
private JDialog parent = null;
private int shouldStop = -1;
private SOMMap map = null;
private ArrayList<T3<Topic, Integer, Integer>> topicLocations = new ArrayList<T3<Topic, Integer, Integer>>();
private ArrayList<String>[][] cellLabels = null;
private boolean[][] selectedCells = null;
private int cellSize = 50;
private int fontSize = 6;
private Font cellFont = null;
private Font defaultFont = null;
private int mapSize = 1;
private int progress = 0;
private int progressMax = 100;
private MouseEvent mouseEvent;
private Object[] menuStruct = new Object[] {
SELECT_CELL,
DESELECT_CELL,
SELECT_ALL_CELLS,
CLEAR_SELECTION,
"---",
COPY_CELL_NEURONS,
COPY_CELL_TOPICS,
COPY_CELL_TOPICS_VECTORS,
"---",
COPY_AS_IMAGE,
"---",
ASSOCIATE_TOPICS_IN_SELECTED_CELLS_TO_A_GROUP,
ASSOCIATE_TOPICS_IN_EVERY_CELL_TO_A_CELL_SPECIFIC_GROUP,
"---",
PERMUTATE_TOPICS_WITHIN_SELECTED_CELLS,
PERMUTATE_ALL_TOPICS_IN_SELECTED_CELLS,
PERMUTATE_TOPICS_WITHIN_EVERY_CELL,
};
private RenderingHints qualityHints = new RenderingHints(
RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
private RenderingHints antialiasHints = new RenderingHints(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
private RenderingHints metricsHints = new RenderingHints(
RenderingHints.KEY_FRACTIONALMETRICS,
RenderingHints.VALUE_FRACTIONALMETRICS_ON);
public SOMTopicVisualizationPanel() {
defaultFont = new Font("SansSerif", Font.PLAIN, 12);
this.setComponentPopupMenu(UIBox.makePopupMenu(menuStruct, this));
this.addMouseListener(this);
this.addMouseMotionListener(this);
this.addKeyListener(this);
this.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
}
public void initialize(JDialog parent, SOMMap map) {
cellFont = new Font("SansSerif", Font.PLAIN, fontSize);
this.parent = parent;
this.map = map;
mapSize = map.getSize();
selectedCells = new boolean[mapSize][mapSize];
clearCellSelection();
cellLabels = new ArrayList[mapSize][mapSize];
if(shouldStop == -1) shouldStop = 0;
new Thread(this).start();
}
public void setCellSize(int size) {
if(cellSize != size) {
cellSize = size;
fontSize = Math.max(3, size / 12);
cellFont = new Font("SansSerif", Font.PLAIN, fontSize);
this.invalidate();
this.repaint();
}
}
public int getCellSize() {
return cellSize;
}
public void shouldStop() {
shouldStop = 1;
}
@Override
public Dimension getPreferredSize() {
return new Dimension(cellSize*mapSize, cellSize*mapSize);
}
@Override
public Dimension getMinimumSize() {
return new Dimension(cellSize*mapSize, cellSize*mapSize);
}
@Override
public Dimension getMaximumSize() {
return new Dimension(cellSize*mapSize, cellSize*mapSize);
}
@Override
public void paint(Graphics g) {
if(g instanceof Graphics2D) ((Graphics2D) g).addRenderingHints(antialiasHints);
super.paint(g);
if(topicLocations!=null && map != null) {
g.setColor(new Color(0xc8ddf2));
for(int i=0; i<mapSize; i++) {
for(int j=0; j<mapSize; j++) {
if(selectedCells[i][j]) {
g.fillRect(i*cellSize, j*cellSize, cellSize, cellSize);
}
}
}
g.setColor(Color.WHITE);
for(int i=0; i<=mapSize; i++) {
g.drawLine(i*cellSize, 0, i*cellSize, mapSize*cellSize);
g.drawLine(0, i*cellSize, mapSize*cellSize, i*cellSize);
}
g.setColor(Color.BLACK);
g.setFont(defaultFont);
if(progress < progressMax)
g.drawString("distributing topics "+100*progress/progressMax+"%", 10, 20);
else
g.drawString("ready.", 10, 20);
g.setFont(cellFont);
FontMetrics fm = g.getFontMetrics();
Rectangle2D labelBounds = null;
String label = null;
Rectangle bounds = g.getClipBounds();
if(bounds == null) bounds = new Rectangle(0,0,(1+cellSize)*mapSize,(1+cellSize)*mapSize);
int numberOfLines = 0;
int lineNumber = 0;
int labelHeight = 0;
int labelWidth = 0;
int x = 0;
int y = 0;
int cellTop = 0;
int cellLeft = 0;
Rectangle2D cellBounds = null;
synchronized(cellLabels) {
ArrayList<String> labels = null;
for(int i=0; i<mapSize; i++) {
for(int j=0; j<mapSize; j++) {
labels = cellLabels[i][j];
if(labels != null) {
cellLeft = i*cellSize;
cellTop = j*cellSize;
cellBounds = bounds.createIntersection(new Rectangle(cellLeft,cellTop, cellSize, cellSize ));
if(!cellBounds.isEmpty()) {
g.setClip(cellBounds);
numberOfLines = labels.size();
lineNumber = 0;
labelHeight = 0;
labelWidth = 0;
x = 0;
y = 0;
for(Iterator<String> labelIter = labels.iterator(); labelIter.hasNext(); ) {
label = labelIter.next();
if(label != null) {
labelBounds = fm.getStringBounds(label, g);
labelHeight = (int) labelBounds.getHeight();
labelWidth = (int) labelBounds.getWidth();
x = cellLeft+cellSize/2-(labelWidth/2);
y = cellTop+cellSize/2+lineNumber*labelHeight-numberOfLines*labelHeight/2;
g.drawString(label, x, y);
lineNumber++;
}
}
g.drawLine(cellLeft+2, (j+1)*cellSize-2, cellLeft+2+numberOfLines, (j+1)*cellSize-2);
}
}
}
}
}
g.setClip(bounds); // Restore clip bounds to original
}
}
public String getTopicLabel(Topic t) {
try {
return t.getBaseName();
}
catch(Exception e) {
return "n.a.";
}
}
public void run() {
if(map != null) {
Map<Topic,SOMVector> samples = map.getSamples();
Set<Topic> set = samples.keySet();
Topic t = null;
SOMVector v = null;
progressMax = set.size();
for(Iterator<Topic> iter = set.iterator(); iter.hasNext() && shouldStop != 1; ) {
try {
t = iter.next();
v = samples.get(t);
T3<Integer, Integer, SOMNeuron> bmu = map.getBMU(v);
int x = bmu.e1.intValue();
int y = bmu.e2.intValue();
synchronized(topicLocations) {
topicLocations.add(new T3<Topic,Integer,Integer>( t, Integer.valueOf(x), Integer.valueOf(y) ));
}
synchronized(cellLabels) {
if(cellLabels[x][y] == null) cellLabels[x][y] = new ArrayList<String>();
cellLabels[x][y].add(getTopicLabel(t));
}
progress++;
this.invalidate();
this.repaint();
if(parent != null) {
parent.invalidate();
parent.repaint();
}
try {
Thread.sleep(100);
}
catch(Exception e) { /* WAKEUP */ }
}
catch(Exception e) {
e.printStackTrace();
}
}
}
}
// -------------------------------------------------------------------------
public void actionPerformed(java.awt.event.ActionEvent actionEvent) {
String c = actionEvent.getActionCommand();
boolean requiresRefresh = false;
int x = mouseEvent.getX() / cellSize;
int y = mouseEvent.getY() / cellSize;
if(SELECT_CELL.equalsIgnoreCase(c)) {
selectCell(x,y);
requiresRefresh = true;
}
else if(DESELECT_CELL.equalsIgnoreCase(c)) {
deselectCell(x,y);
requiresRefresh = true;
}
else if(SELECT_ALL_CELLS.equalsIgnoreCase(c)) {
selectAllCells();
requiresRefresh = true;
}
else if(CLEAR_SELECTION.equalsIgnoreCase(c)) {
clearCellSelection();
requiresRefresh = true;
}
else if(COPY_CELL_NEURONS.equalsIgnoreCase(c)) {
boolean noSelection = true;
StringBuilder sb = new StringBuilder("");
for(int i=0; i<mapSize; i++) {
for(int j=0; j<mapSize; j++) {
if(selectedCells[i][j]) {
noSelection = false;
SOMNeuron n = map.getAt(i, j);
sb.append(i).append("\t").append(j).append("\t").append(n.toString()).append( "\n");
}
}
}
if(noSelection) {
if(x >= 0 && x < mapSize && y >= 0 && y < mapSize) {
SOMNeuron n = map.getAt(x, y);
sb.append(x).append("\t").append(y).append("\t").append( n.toString());
}
}
ClipboardBox.setClipboard( sb.toString() );
}
else if(COPY_CELL_TOPICS_VECTORS.equalsIgnoreCase(c)) {
StringBuffer sb = new StringBuffer("");
boolean noSelection = true;
for(int i=0; i<mapSize; i++) {
for(int j=0; j<mapSize; j++) {
if(selectedCells[i][j]) {
noSelection = false;
getTopicVectorAsString(sb, i, j);
}
}
}
if(noSelection) {
if(x >= 0 && x < mapSize && y >= 0 && y < mapSize) {
getTopicVectorAsString(sb, x, y);
}
}
String str = sb.toString();
if(str.length() == 0) str = "no topics in cell(s)";
ClipboardBox.setClipboard(str);
}
else if(COPY_CELL_TOPICS.equalsIgnoreCase(c)) {
StringBuilder sb = new StringBuilder("");
boolean noSelection = true;
for(int i=0; i<mapSize; i++) {
for(int j=0; j<mapSize; j++) {
if(selectedCells[i][j]) {
getCellTopicsAsString(sb, i, j);
noSelection = false;
}
}
}
if(noSelection) {
if(x >= 0 && x < mapSize && y >= 0 && y < mapSize) {
getCellTopicsAsString(sb, x ,y);
}
}
String str = sb.toString();
if(str.length() == 0) str = "no topics in cell(s)";
ClipboardBox.setClipboard(str);
}
else if(COPY_AS_IMAGE.equalsIgnoreCase(c)) {
BufferedImage image = new BufferedImage(cellSize*mapSize, cellSize*mapSize, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
paint(g);
ClipboardBox.setClipboard(image);
}
else if(ASSOCIATE_TOPICS_IN_EVERY_CELL_TO_A_CELL_SPECIFIC_GROUP.equalsIgnoreCase(c)) {
for(int i=0; i<mapSize; i++) {
for(int j=0; j<mapSize; j++) {
ArrayList<Topic> topicsInCell = topicsInCell(i, j);
if(topicsInCell != null && topicsInCell.size() > 1) {
String groupTopic = "SOM-Group-"+i+"-"+j;
Topic topic = null;
Topic[] topics = topicsInCell.toArray(new Topic[] {} );
int s = topics.length;
for(int k=0; k<s; k++) {
topic = topics[k];
groupAssociation(topic, groupTopic);
}
}
}
}
}
else if(ASSOCIATE_TOPICS_IN_SELECTED_CELLS_TO_A_GROUP.equalsIgnoreCase(c)) {
boolean noSelection = true;
String groupName = "SOM-Group-"+System.currentTimeMillis();
for(int i=0; i<mapSize; i++) {
for(int j=0; j<mapSize; j++) {
if(selectedCells[i][j]) {
noSelection = true;
groupTopicsInCell(groupName, i, j);
}
}
}
if(noSelection) {
groupTopicsInCell(groupName, x, y);
}
}
else if(PERMUTATE_TOPICS_WITHIN_SELECTED_CELLS.equalsIgnoreCase(c)) {
boolean noSelection = true;
for(int i=0; i<mapSize; i++) {
for(int j=0; j<mapSize; j++) {
if(selectedCells[i][j]) {
noSelection = false;
associateTopicsTogetherInCell(i, j);
}
}
}
if(noSelection) {
associateTopicsTogetherInCell(x, y);
}
}
else if(PERMUTATE_ALL_TOPICS_IN_SELECTED_CELLS.equalsIgnoreCase(c)) {
ArrayList<Topic> selectedTopics = topicsInCellSelection();
if(selectedTopics != null && selectedTopics.size() > 1) {
Topic player1 = null;
Topic player2 = null;
Topic[] topics = selectedTopics.toArray(new Topic[] {} );
int s = topics.length;
for(int i=0; i<s; i++) {
for(int j=0; j<s; j++) {
if(i==j) continue;
player1 = topics[i];
player2 = topics[j];
similarityAssociation(player1, player2);
}
}
}
}
else if(PERMUTATE_TOPICS_WITHIN_EVERY_CELL.equalsIgnoreCase(c)) {
for(int x2=0; x2<mapSize; x2++) {
for(int y2=0; y2<mapSize; y2++) {
ArrayList<Topic> topicsInCell = topicsInCell(x2, y2);
if(topicsInCell != null && topicsInCell.size() > 1) {
Topic player1 = null;
Topic player2 = null;
Topic[] topics = topicsInCell.toArray(new Topic[] {} );
int s = topics.length;
for(int i=0; i<s; i++) {
for(int j=0; j<s; j++) {
if(i==j) continue;
player1 = topics[i];
player2 = topics[j];
strongSimilarityAssociation(player1, player2);
}
}
}
}
}
}
else {
// Should not be here!
}
if(requiresRefresh) {
if(parent != null) {
parent.invalidate();
parent.repaint();
}
}
}
public void associateTopicsTogetherInCell(int x, int y) {
ArrayList<Topic> topicsInCell = topicsInCell(x, y);
if(topicsInCell != null && topicsInCell.size() > 1) {
Topic player1 = null;
Topic player2 = null;
Topic[] topics = topicsInCell.toArray(new Topic[] {} );
int s = topics.length;
for(int i=0; i<s; i++) {
for(int j=0; j<s; j++) {
if(i==j) continue;
player1 = topics[i];
player2 = topics[j];
strongSimilarityAssociation(player1, player2);
}
}
}
}
public void groupTopicsInCell(String groupName, int x, int y) {
ArrayList<Topic> topicsInCell = topicsInCell(x, y);
if(topicsInCell != null && topicsInCell.size() > 1) {
Topic topic = null;
Topic[] topics = topicsInCell.toArray(new Topic[] {} );
int s = topics.length;
for(int k=0; k<s; k++) {
topic = topics[k];
groupAssociation(topic, groupName);
}
}
}
public void getCellTopicsAsString(StringBuilder sb, int x, int y) {
synchronized(cellLabels) {
ArrayList<String> labels = cellLabels[x][y];
sb.append(x+"\t");
sb.append(y+"\t");
if(labels != null && labels.size() > 0) {
String label;
for(Iterator<String> labelIter = labels.iterator(); labelIter.hasNext(); ) {
label = labelIter.next();
if(label != null) {
sb.append(label+"\t");
}
}
}
}
sb.append("\n");
}
public void getTopicVectorAsString(StringBuffer sb, int x, int y) {
SOMVector v = null;
T3<Topic, Integer, Integer> location = null;
synchronized(topicLocations) {
for(Iterator<T3<Topic, Integer, Integer>> locations = topicLocations.iterator(); locations.hasNext(); ) {
location = locations.next();
if(x == location.e2.intValue() && y == location.e3.intValue()) {
v = map.getSampleFor(location.e1);
if(v != null) {
sb.append(x).append("\t");
sb.append(y).append("\t");
sb.append(v.toString()).append("\n");
}
}
}
}
}
public ArrayList<Topic> getTopicsInNearCells(int x, int y) {
ArrayList<Topic> nearTopicsArray = new ArrayList<Topic>();
nearTopicsArray.addAll(topicsInCell(x-1, y-1));
nearTopicsArray.addAll(topicsInCell(x-1, y));
nearTopicsArray.addAll(topicsInCell(x-1, y+1));
nearTopicsArray.addAll(topicsInCell(x, y-1));
nearTopicsArray.addAll(topicsInCell(x, y+1));
nearTopicsArray.addAll(topicsInCell(x+1, y-1));
nearTopicsArray.addAll(topicsInCell(x+1, y));
nearTopicsArray.addAll(topicsInCell(x+1, y+1));
return nearTopicsArray;
}
public ArrayList<Topic> topicsInCellSelection() {
ArrayList<Topic> topicsInSelection = new ArrayList<Topic>();
for(int i=0; i<mapSize; i++) {
for(int j=0; j<mapSize; j++) {
if(selectedCells[i][j]) {
topicsInSelection.addAll(topicsInCell(i, j));
}
}
}
return topicsInSelection;
}
public ArrayList<Topic> topicsInCell(int x, int y) {
ArrayList<Topic> topicsInCell = new ArrayList<Topic>();
if(x >= 0 && x < mapSize && y >= 0 && y < mapSize) {
T3<Topic, Integer, Integer> location = null;
synchronized(topicLocations) {
for(Iterator<T3<Topic, Integer, Integer>> locations = topicLocations.iterator(); locations.hasNext(); ) {
location = locations.next();
if(x == location.e2.intValue() && y == location.e3.intValue()) {
topicsInCell.add(location.e1);
}
}
}
}
return topicsInCell;
}
public Topic getOrCreateTopic(TopicMap tm, String basename) throws TopicMapException {
Topic t = tm.getTopicWithBaseName(basename);
if(t == null) {
t = tm.createTopic();
t.addSubjectIdentifier(new Locator(SI_PREFIX+basename));
t.setBaseName(basename);
}
return t;
}
public void strongSimilarityAssociation(Topic player1, Topic player2) {
try {
TopicMap tm = player1.getTopicMap();
Topic atype = getOrCreateTopic(tm, "Strong-SOM-Similarity");
Topic role1 = getOrCreateTopic(tm, "Strong-SOM-Similarity-Role1");
Topic role2 = getOrCreateTopic(tm, "Strong-SOM-Similarity-Role2");
Association a = tm.createAssociation(atype);
a.addPlayer(player1, role1);
a.addPlayer(player2, role2);
}
catch(Exception e) {
WandoraOptionPane.showMessageDialog(this, e.toString(), e.toString(), WandoraOptionPane.ERROR_MESSAGE);
}
}
public void similarityAssociation(Topic player1, Topic player2) {
try {
TopicMap tm = player1.getTopicMap();
Topic atype = getOrCreateTopic(tm, "SOM-Similarity");
Topic role1 = getOrCreateTopic(tm, "SOM-Similarity-Role1");
Topic role2 = getOrCreateTopic(tm, "SOM-Similarity-Role2");
Association a = tm.createAssociation(atype);
a.addPlayer(player1, role1);
a.addPlayer(player2, role2);
}
catch(Exception e) {
WandoraOptionPane.showMessageDialog(this, e.toString(), e.toString(), WandoraOptionPane.ERROR_MESSAGE);
}
}
public void nearSimilarityAssociation(Topic player1, Topic player2) {
try {
TopicMap tm = player1.getTopicMap();
Topic atype = getOrCreateTopic(tm, "SOM-near");
Topic role1 = getOrCreateTopic(tm, "SOM-cell-topic");
Topic role2 = getOrCreateTopic(tm, "SOM-near-cell-topic");
Association a = tm.createAssociation(atype);
a.addPlayer(player1, role1);
a.addPlayer(player2, role2);
}
catch(Exception e) {
WandoraOptionPane.showMessageDialog(this, e.toString(), e.toString(), WandoraOptionPane.ERROR_MESSAGE);
}
}
public void groupAssociation(Topic topic, String groupTopicName) {
try {
TopicMap tm = topic.getTopicMap();
Topic atype = getOrCreateTopic(tm, "SOM-Group");
Topic role1 = getOrCreateTopic(tm, "SOM-Topic");
Topic role2 = getOrCreateTopic(tm, "SOM-Group");
Topic groupTopic = getOrCreateTopic(tm, groupTopicName);
groupTopic.addType(atype);
Association a = tm.createAssociation(atype);
a.addPlayer(topic, role1);
a.addPlayer(groupTopic, role2);
}
catch(Exception e) {
WandoraOptionPane.showMessageDialog(this, e.toString(), e.toString(), WandoraOptionPane.ERROR_MESSAGE);
}
}
// -------------------------------------------------------------------------
public void selectCell(int x, int y) {
if(x >= 0 && x < mapSize && y >= 0 && y < mapSize) {
selectedCells[x][y] = true;
}
}
public void deselectCell(int x, int y) {
if(x >= 0 && x < mapSize && y >= 0 && y < mapSize) {
selectedCells[x][y] = false;
}
}
public void toggleCellSelection(int x, int y) {
if(x >= 0 && x < mapSize && y >= 0 && y < mapSize) {
selectedCells[x][y] = !selectedCells[x][y];
}
}
public void clearCellSelection() {
for(int i=0; i<mapSize; i++) {
for(int j=0; j<mapSize; j++) {
selectedCells[i][j] = false;
}
}
}
public void selectAllCells() {
for(int i=0; i<mapSize; i++) {
for(int j=0; j<mapSize; j++) {
selectedCells[i][j] = true;
}
}
}
public boolean getCellState(int x, int y) {
if(x >= 0 && x < mapSize && y >= 0 && y < mapSize) {
return selectedCells[x][y];
}
return false;
}
// -------------------------------------------------------------------------
public void mouseClicked(java.awt.event.MouseEvent mouseEvent) {
this.mouseEvent = mouseEvent;
}
public void mouseEntered(java.awt.event.MouseEvent mouseEvent) {
}
public void mouseExited(java.awt.event.MouseEvent mouseEvent) {
}
public void mousePressed(java.awt.event.MouseEvent mouseEvent) {
this.requestFocus();
this.mouseEvent = mouseEvent;
if(mouseEvent.getButton() == MouseEvent.BUTTON1) {
int x = mouseEvent.getX() / cellSize;
int y = mouseEvent.getY() / cellSize;
if(mouseEvent.isShiftDown()) {
toggleCellSelection(x, y);
}
else if(mouseEvent.isAltDown()) {
deselectCell(x, y);
}
else {
clearCellSelection();
selectCell(x, y);
}
if(parent != null) {
parent.invalidate();
parent.repaint();
}
}
}
public void mouseReleased(java.awt.event.MouseEvent mouseEvent) {
this.mouseEvent = mouseEvent;
}
public void mouseDragged(MouseEvent mouseEvent) {
boolean requiresRefresh = false;
int x = mouseEvent.getX() / cellSize;
int y = mouseEvent.getY() / cellSize;
if(mouseEvent.isShiftDown()) {
if(!getCellState(x, y)) {
selectCell(x, y);
requiresRefresh = true;
}
}
else if(mouseEvent.isAltDown()) {
if(getCellState(x, y)) {
deselectCell(x, y);
requiresRefresh = true;
}
}
else {
if(!getCellState(x, y)) {
clearCellSelection();
selectCell(x, y);
requiresRefresh=true;
}
}
if(requiresRefresh) {
if(parent != null) {
parent.invalidate();
parent.repaint();
}
}
}
public void mouseMoved(MouseEvent mouseEvent) {
}
// -------------------------------------------------------- KEY LISTENER ---
public void keyPressed(KeyEvent e) {
boolean requiresRefresh = false;
if(e.isControlDown()) {
// --- SELECT ALL
if(e.getKeyCode() == KeyEvent.VK_A) {
this.selectAllCells();
requiresRefresh = true;
}
// --- COPY TOPICS
else if(e.getKeyCode() == KeyEvent.VK_C) {
StringBuilder sb = new StringBuilder("");
for(int i=0; i<mapSize; i++) {
for(int j=0; j<mapSize; j++) {
if(selectedCells[i][j]) {
getCellTopicsAsString(sb, i, j);
}
}
}
String str = sb.toString();
if(str.length() == 0) str = "no topics in cell(s)";
ClipboardBox.setClipboard(str);
}
// --- CREATE GROUP ASSOCIATIONS
else if(e.getKeyCode() == KeyEvent.VK_G) {
String groupName = "SOM-Group-"+System.currentTimeMillis();
for(int i=0; i<mapSize; i++) {
for(int j=0; j<mapSize; j++) {
if(selectedCells[i][j]) {
groupTopicsInCell(groupName, i, j);
}
}
}
}
}
else if(e.isShiftDown()) {
// --- EXTEND SELECTION UP
if(e.getKeyCode() == KeyEvent.VK_UP) {
for(int i=0; i<mapSize; i++) {
for(int j=1; j<mapSize; j++) {
if(selectedCells[i][j]) {
selectedCells[i][j-1] = true;
requiresRefresh = true;
}
}
}
}
// --- EXTEND SELECTION DOWN
else if(e.getKeyCode() == KeyEvent.VK_DOWN) {
for(int i=0; i<mapSize; i++) {
for(int j=mapSize-2; j>=0; j--) {
if(selectedCells[i][j]) {
selectedCells[i][j+1] = true;
requiresRefresh = true;
}
}
}
}
// --- EXTEND SELECTION LEFT
else if(e.getKeyCode() == KeyEvent.VK_LEFT) {
for(int i=1; i<mapSize; i++) {
for(int j=0; j<mapSize; j++) {
if(selectedCells[i][j]) {
selectedCells[i-1][j] = true;
requiresRefresh = true;
}
}
}
}
// --- EXTEND SELECTION RIGHT
else if(e.getKeyCode() == KeyEvent.VK_RIGHT) {
for(int i=mapSize-2; i>=0; i--) {
for(int j=0; j<mapSize; j++) {
if(selectedCells[i][j]) {
selectedCells[i+1][j] = true;
requiresRefresh = true;
}
}
}
}
}
else {
// --- MOVE SELECTION UP
if(e.getKeyCode() == KeyEvent.VK_UP) {
for(int i=0; i<mapSize; i++) {
selectedCells[i][0] = false;
}
for(int i=0; i<mapSize; i++) {
for(int j=1; j<mapSize; j++) {
if(selectedCells[i][j]) {
selectedCells[i][j] = false;
selectedCells[i][j-1] = true;
requiresRefresh = true;
}
}
}
}
// --- MOVE SELECTION DOWN
else if(e.getKeyCode() == KeyEvent.VK_DOWN) {
for(int i=0; i<mapSize; i++) {
selectedCells[i][mapSize-1] = false;
}
for(int i=0; i<mapSize; i++) {
for(int j=mapSize-2; j>=0; j--) {
if(selectedCells[i][j]) {
selectedCells[i][j] = false;
selectedCells[i][j+1] = true;
requiresRefresh = true;
}
}
}
}
// --- MOVE SELECTION LEFT
else if(e.getKeyCode() == KeyEvent.VK_LEFT) {
for(int j=0; j<mapSize; j++) {
selectedCells[0][j] = false;
}
for(int i=1; i<mapSize; i++) {
for(int j=0; j<mapSize; j++) {
if(selectedCells[i][j]) {
selectedCells[i][j] = false;
selectedCells[i-1][j] = true;
requiresRefresh = true;
}
}
}
}
// --- MOVE SELECTION RIGHT
else if(e.getKeyCode() == KeyEvent.VK_RIGHT) {
for(int j=0; j<mapSize; j++) {
selectedCells[mapSize-1][j] = false;
}
for(int i=mapSize-2; i>=0; i--) {
for(int j=0; j<mapSize; j++) {
if(selectedCells[i][j]) {
selectedCells[i][j] = false;
selectedCells[i+1][j] = true;
requiresRefresh = true;
}
}
}
}
}
if(requiresRefresh) {
if(parent != null) {
parent.invalidate();
parent.repaint();
}
}
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
}
| 36,325 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SOMTopicVisualization.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/som/SOMTopicVisualization.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* SOMTopicVisualization.java
*
* Created on 30.7.2008, 13:43
*/
package org.wandora.application.tools.som;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.wandora.application.Wandora;
import org.wandora.application.gui.simple.SimpleButton;
import org.wandora.application.gui.simple.SimpleScrollPane;
import org.wandora.topicmap.Topic;
import org.wandora.utils.ClipboardBox;
/**
*
* @author akivela
*/
public class SOMTopicVisualization extends javax.swing.JDialog {
private static final long serialVersionUID = 1L;
SOMMap map = null;
/** Creates new form SOMTopicVisualization */
public SOMTopicVisualization(Wandora admin) {
super(admin, true);
initComponents();
this.setSize(600,600);
this.setTitle("Topic SOM Visualization");
admin.centerWindow(this);
addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent evt) {
((SOMTopicVisualizationPanel) mapPanel).shouldStop();
}
});
}
public void visualize(SOMMap map) {
this.map = map;
((SOMTopicVisualizationPanel) mapPanel).initialize(this, map);
setVisible(true);
}
public void copyMapVectors() {
StringBuilder sb = new StringBuilder("");
if(map != null) {
int mapSize = map.getSize();
SOMNeuron n = null;
for(int i=0; i<mapSize; i++) {
for(int j=0; j<mapSize; j++) {
sb.append(i).append("\t").append(j).append("\t");
n = map.getAt(i,j);
if(n != null) {
sb.append(n.toString());
}
else {
sb.append("null");
}
sb.append("\n");
}
}
}
ClipboardBox.setClipboard(sb.toString());
}
public void copySamples() {
StringBuilder sb = new StringBuilder("");
if(map != null) {
Map<Topic,SOMVector> samples = map.getSamples();
Set<Topic> set = samples.keySet();
Topic t = null;
SOMVector v = null;
for(Iterator<Topic> iter = set.iterator(); iter.hasNext(); ) {
try {
t = iter.next();
v = samples.get(t);
sb.append(t.getBaseName()).append("\t");
sb.append(v.toString());
sb.append("\n");
}
catch(Exception e) {
e.printStackTrace();
}
}
}
ClipboardBox.setClipboard(sb.toString());
}
public void updateCellSize() {
((SOMTopicVisualizationPanel) mapPanel).setCellSize(cellSizeSlider.getValue());
this.setVisible(true);
}
/** 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;
mapScrollPane = new SimpleScrollPane();
mapPanel = new SOMTopicVisualizationPanel();
buttonPanel = new javax.swing.JPanel();
sizeSliderPanel = new javax.swing.JPanel();
cellSizeSlider = new javax.swing.JSlider();
fillerPanel = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
closeButton = new SimpleButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
formKeyPressed(evt);
}
});
getContentPane().setLayout(new java.awt.GridBagLayout());
mapPanel.setFocusTraversalPolicyProvider(true);
javax.swing.GroupLayout mapPanelLayout = new javax.swing.GroupLayout(mapPanel);
mapPanel.setLayout(mapPanelLayout);
mapPanelLayout.setHorizontalGroup(
mapPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 539, Short.MAX_VALUE)
);
mapPanelLayout.setVerticalGroup(
mapPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 419, Short.MAX_VALUE)
);
mapScrollPane.setViewportView(mapPanel);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
getContentPane().add(mapScrollPane, gridBagConstraints);
buttonPanel.setLayout(new java.awt.GridBagLayout());
sizeSliderPanel.setLayout(new java.awt.GridBagLayout());
cellSizeSlider.setMaximum(200);
cellSizeSlider.setMinimum(5);
cellSizeSlider.setToolTipText("SOM cell size slider");
cellSizeSlider.setPreferredSize(new java.awt.Dimension(200, 21));
cellSizeSlider.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
cellSizeSliderMousePressed(evt);
}
public void mouseReleased(java.awt.event.MouseEvent evt) {
cellSizeSliderMouseReleased(evt);
}
});
cellSizeSlider.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseDragged(java.awt.event.MouseEvent evt) {
cellSizeSliderMouseDragged(evt);
}
public void mouseMoved(java.awt.event.MouseEvent evt) {
cellSizeSliderMouseMoved(evt);
}
});
sizeSliderPanel.add(cellSizeSlider, new java.awt.GridBagConstraints());
buttonPanel.add(sizeSliderPanel, new java.awt.GridBagConstraints());
javax.swing.GroupLayout fillerPanelLayout = new javax.swing.GroupLayout(fillerPanel);
fillerPanel.setLayout(fillerPanelLayout);
fillerPanelLayout.setHorizontalGroup(
fillerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
fillerPanelLayout.setVerticalGroup(
fillerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
buttonPanel.add(fillerPanel, gridBagConstraints);
jPanel2.setLayout(new java.awt.GridBagLayout());
closeButton.setText("Close");
closeButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
closeButtonMouseReleased(evt);
}
});
jPanel2.add(closeButton, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(5, 0, 5, 5);
buttonPanel.add(jPanel2, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
getContentPane().add(buttonPanel, gridBagConstraints);
pack();
}// </editor-fold>//GEN-END:initComponents
private void closeButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_closeButtonMouseReleased
((SOMTopicVisualizationPanel) mapPanel).shouldStop();
this.setVisible(false);
}//GEN-LAST:event_closeButtonMouseReleased
private void cellSizeSliderMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cellSizeSliderMousePressed
updateCellSize();
}//GEN-LAST:event_cellSizeSliderMousePressed
private void cellSizeSliderMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cellSizeSliderMouseMoved
updateCellSize();
}//GEN-LAST:event_cellSizeSliderMouseMoved
private void cellSizeSliderMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cellSizeSliderMouseReleased
updateCellSize();
}//GEN-LAST:event_cellSizeSliderMouseReleased
private void cellSizeSliderMouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cellSizeSliderMouseDragged
updateCellSize();
}//GEN-LAST:event_cellSizeSliderMouseDragged
private void formKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyPressed
System.out.println("key pressed at FORM");
if(mapPanel instanceof SOMTopicVisualizationPanel) {
((SOMTopicVisualizationPanel) mapPanel).keyPressed(evt);
}
}//GEN-LAST:event_formKeyPressed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel buttonPanel;
private javax.swing.JSlider cellSizeSlider;
private javax.swing.JButton closeButton;
private javax.swing.JPanel fillerPanel;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel mapPanel;
private javax.swing.JScrollPane mapScrollPane;
private javax.swing.JPanel sizeSliderPanel;
// End of variables declaration//GEN-END:variables
}
| 10,584 | 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.