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
AbstractGeoNamesWikipediaParser.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/geonames/AbstractGeoNamesWikipediaParser.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.geonames; import org.wandora.topicmap.TopicMap; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; /** * * @author akivela */ public abstract class AbstractGeoNamesWikipediaParser implements org.xml.sax.ContentHandler, org.xml.sax.ErrorHandler { protected String lang = "en"; protected int progress = 0; protected TopicMap tm; protected AbstractGeoNamesExtractor parent; protected String requestGeoObject = null; public AbstractGeoNamesWikipediaParser(TopicMap tm, AbstractGeoNamesExtractor parent, String lang){ this.lang=lang; this.tm=tm; this.parent=parent; } private static final String TAG_GEONAMES="geonames"; private static final String TAG_STATUS="status"; private static final String TAG_ENTRY="entry"; private static final String TAG_LANG="lang"; private static final String TAG_TITLE="title"; private static final String TAG_SUMMARY="summary"; private static final String TAG_FEATURE="feature"; private static final String TAG_COUNTRYCODE="countryCode"; private static final String TAG_LAT="lat"; private static final String TAG_LNG="lng"; private static final String TAG_POPULATION="population"; private static final String TAG_ELEVATION="elevation"; private static final String TAG_WIKIPEDIAURL="wikipediaUrl"; private static final String TAG_CLOUDS="clouds"; private static final String TAG_THUMBNAILIMG="thumbnailImg"; private static final int STATE_START=0; private static final int STATE_GEONAMES=2; private static final int STATE_GEONAMES_STATUS=200; private static final int STATE_ENTRY=3; private static final int STATE_ENTRY_LANG=4; private static final int STATE_ENTRY_LAT=5; private static final int STATE_ENTRY_LNG=6; private static final int STATE_ENTRY_TITLE=7; private static final int STATE_ENTRY_SUMMARY=8; private static final int STATE_ENTRY_FEATURE=9; private static final int STATE_ENTRY_COUNTRYCODE=10; private static final int STATE_ENTRY_POPULATION=11; private static final int STATE_ENTRY_ELEVATION=12; private static final int STATE_ENTRY_WIKIPEDIAURL=13; private static final int STATE_ENTRY_THUMBNAILIMG=14; private int state=STATE_START; protected String data_lang; protected String data_lat; protected String data_lng; protected String data_title; protected String data_summary; protected String data_feature; protected String data_countrycode; protected String data_population; protected String data_elevation; protected String data_wikipediaurl; protected String data_thumbnailimg; public void setRequestGeoObject(String p) { requestGeoObject = p; } // ********** OVERRIDE THIS METHOD IN EXTENDING CLASSSES! ********** public abstract void handleEntryElement(); public void startDocument() throws SAXException { progress = 0; } public void endDocument() throws SAXException { } public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { if(parent != null && parent.forceStop()){ throw new SAXException("User interrupt"); } switch(state){ case STATE_START: if(qName.equals(TAG_GEONAMES)) { state = STATE_GEONAMES; break; } case STATE_GEONAMES: if(qName.equals(TAG_STATUS)) { state = STATE_GEONAMES_STATUS; String msg = atts.getValue("message"); String val = atts.getValue("value"); if(parent != null) { parent.log("GeoNames web service says: "+msg+" ("+val+")"); } else { System.out.println("GeoNames web service says: "+msg+" ("+val+")"); } } else if(qName.equals(TAG_ENTRY)) { data_lang = ""; data_lat = ""; data_lng = ""; data_title = ""; data_summary = ""; data_feature = ""; data_countrycode = ""; data_population = ""; data_elevation = ""; data_wikipediaurl = ""; data_thumbnailimg = ""; state = STATE_ENTRY; } break; case STATE_ENTRY: if(qName.equals(TAG_LANG)) { state = STATE_ENTRY_LANG; data_lang = ""; } else if(qName.equals(TAG_LAT)) { state = STATE_ENTRY_LAT; data_lat = ""; } else if(qName.equals(TAG_LNG)) { state = STATE_ENTRY_LNG; data_lng = ""; } else if(qName.equals(TAG_TITLE)) { state = STATE_ENTRY_TITLE; data_title = ""; } else if(qName.equals(TAG_SUMMARY)) { state = STATE_ENTRY_SUMMARY; data_summary = ""; } else if(qName.equals(TAG_FEATURE)) { state = STATE_ENTRY_FEATURE; data_feature = ""; } else if(qName.equals(TAG_COUNTRYCODE)) { state = STATE_ENTRY_COUNTRYCODE; data_countrycode = ""; } else if(qName.equals(TAG_POPULATION)) { state = STATE_ENTRY_POPULATION; data_population = ""; } else if(qName.equals(TAG_ELEVATION)) { state = STATE_ENTRY_ELEVATION; data_elevation= ""; } else if(qName.equals(TAG_WIKIPEDIAURL)) { state = STATE_ENTRY_WIKIPEDIAURL; data_wikipediaurl = ""; } else if(qName.equals(TAG_THUMBNAILIMG)) { state = STATE_ENTRY_THUMBNAILIMG; data_thumbnailimg = ""; } break; } } public void endElement(String uri, String localName, String qName) throws SAXException { switch(state) { case STATE_ENTRY: { if(TAG_ENTRY.equals(qName)) { handleEntryElement(); state=STATE_GEONAMES; } break; } case STATE_GEONAMES_STATUS: { if(qName.equals(TAG_STATUS)) { state = STATE_GEONAMES; } break; } case STATE_GEONAMES: state=STATE_START; break; case STATE_ENTRY_LANG: { if(TAG_LANG.equals(qName)) state=STATE_ENTRY; break; } case STATE_ENTRY_LAT: { if(TAG_LAT.equals(qName)) state=STATE_ENTRY; break; } case STATE_ENTRY_LNG: { if(TAG_LNG.equals(qName)) state=STATE_ENTRY; break; } case STATE_ENTRY_TITLE: { if(TAG_TITLE.equals(qName)) state=STATE_ENTRY; break; } case STATE_ENTRY_SUMMARY: { if(TAG_SUMMARY.equals(qName)) state=STATE_ENTRY; break; } case STATE_ENTRY_FEATURE: { if(TAG_FEATURE.equals(qName)) state=STATE_ENTRY; break; } case STATE_ENTRY_COUNTRYCODE: { if(TAG_COUNTRYCODE.equals(qName)) state=STATE_ENTRY; break; } case STATE_ENTRY_POPULATION: { if(TAG_POPULATION.equals(qName)) state=STATE_ENTRY; break; } case STATE_ENTRY_ELEVATION: { if(TAG_ELEVATION.equals(qName)) state=STATE_ENTRY; break; } case STATE_ENTRY_WIKIPEDIAURL: { if(TAG_WIKIPEDIAURL.equals(qName)) state=STATE_ENTRY; break; } case STATE_ENTRY_THUMBNAILIMG: { if(TAG_THUMBNAILIMG.equals(qName)) state=STATE_ENTRY; break; } } } public void characters(char[] ch, int start, int length) throws SAXException { switch(state){ case STATE_ENTRY_LANG: data_lang+=new String(ch,start,length); break; case STATE_ENTRY_LAT: data_lat+=new String(ch,start,length); break; case STATE_ENTRY_LNG: data_lng+=new String(ch,start,length); break; case STATE_ENTRY_TITLE: data_title+=new String(ch,start,length); break; case STATE_ENTRY_SUMMARY: data_summary+=new String(ch,start,length); break; case STATE_ENTRY_FEATURE: data_feature+=new String(ch,start,length); break; case STATE_ENTRY_COUNTRYCODE: data_countrycode+=new String(ch,start,length); break; case STATE_ENTRY_POPULATION: data_population+=new String(ch,start,length); break; case STATE_ENTRY_ELEVATION: data_elevation+=new String(ch,start,length); break; case STATE_ENTRY_WIKIPEDIAURL: data_wikipediaurl+=new String(ch,start,length); break; case STATE_ENTRY_THUMBNAILIMG: data_thumbnailimg+=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 {} public boolean isValid(String str) { if(str != null && str.length() > 0) return true; else return false; } }
12,314
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
GeoNamesSiblings.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/geonames/GeoNamesSiblings.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * GeoNamesSiblings.java */ package org.wandora.application.tools.extractors.geonames; import java.io.InputStream; import java.net.URL; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; /** * See http://ws.geonames.org/siblings?geonameId=3017382&style=full * * @author akivela */ public class GeoNamesSiblings extends AbstractGeoNamesExtractor { private static final long serialVersionUID = 1L; public String dataLang = "en"; public String requestGeoObject = null; @Override public String getName() { return "GeoNames siblings extractor"; } @Override public String getDescription(){ return "Get siblings of given geo location and convert siblings to a topic map. "; } public void setRequestGeoObject(String p) { this.requestGeoObject = p; } @Override public synchronized void extractTopicsFrom(URL url, TopicMap topicMap) throws Exception { try { String str = url.toExternalForm(); Pattern p = Pattern.compile("geonameId=(\\w+)"); Matcher m = p.matcher(str); if(m.find()) { String geoid = m.group(1); if(geoid != null && geoid.length() > 0) { setRequestGeoObject(geoid); } } } catch(Exception e) {} super.extractTopicsFrom(url, topicMap); } 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(); SiblingsParser parserHandler = new SiblingsParser(topicMap,this,dataLang); parserHandler.setRequestGeoObject(requestGeoObject); 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); } if(parserHandler.progress == 0) log("No siblings found!"); else if(parserHandler.progress == 1) log("One sibling found!"); else log("Total " + parserHandler.progress + " siblings found!"); requestGeoObject = null; // FORCE NULL AS THIS OBJECT IS REUSED. return true; } // ------------------------------------------------------------------------- // --- GEONAMES XML FEED PARSER -------------------------------------------- // ------------------------------------------------------------------------- private static class SiblingsParser extends AbstractGeoNamesParser { public SiblingsParser(TopicMap tm, AbstractGeoNamesExtractor parent, String lang){ super(tm, parent, lang); } public void handleGeoNameElement() { if(data_name.length() > 0 || data_geonameid.length() > 0) { try { theGeoObject=getGeoTopic(tm, data_geonameid, data_name, lang); theGeoObjectSI=theGeoObject.getOneSubjectIdentifier().toExternalForm(); parent.setProgress(progress++); try { if(isValid(data_fcode)) { Topic fcodeTopic = getFCodeTopic(tm, data_fcode, data_fcodename); theGeoObject.addType(fcodeTopic); } if(isValid(data_fcl)) { Topic fclTopic = getFCLTopic(tm, data_fcl, data_fclname); theGeoObject.addType(fclTopic); } if(isValid(data_countrycode) && isValid(data_countryname)) { Topic countryTopic=getCountryTopic(tm, data_countrycode, data_countryname, lang); if(theGeoObject.isRemoved()) theGeoObject=tm.getTopic(theGeoObjectSI); makeGeoCountry(theGeoObject, countryTopic, tm); } if(isValid(data_continentcode)) { Topic continentTopic=getContinentTopic(tm, data_continentcode); if(theGeoObject.isRemoved()) theGeoObject=tm.getTopic(theGeoObjectSI); makeGeoContinent(theGeoObject, continentTopic, tm); } if(isValid(requestGeoObject)) { Topic requestTopic=getGeoTopic(tm, requestGeoObject); if(theGeoObject.isRemoved()) theGeoObject=tm.getTopic(theGeoObjectSI); makeSiblings(requestTopic, theGeoObject, tm); } if(isValid(data_lat) && isValid(data_lng)) { makeLatLong(data_lat, data_lng, theGeoObject, tm); } if(data_alternatename_all != null && data_alternatename_all.size() > 0) { if(theGeoObject.isRemoved()) theGeoObject=tm.getTopic(theGeoObjectSI); nameGeoObjectTopic(theGeoObject, data_alternatename_all); } if(isValid(data_population)) { if(theGeoObject.isRemoved()) theGeoObject=tm.getTopic(theGeoObjectSI); Topic populationTypeTopic = getPopulationTypeTopic(tm); theGeoObject.setData(populationTypeTopic, TMBox.getLangTopic(theGeoObject, lang), data_population); } } catch(Exception e) { parent.log(e); } } catch(TopicMapException tme){ parent.log(tme); } } } } }
7,337
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
GeoNamesExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/geonames/GeoNamesExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.geonames; 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 GeoNamesExtractor extends AbstractWandoraTool { private static final long serialVersionUID = 1L; private static GeoNamesExtractorSelector selector = null; @Override public String getName() { return "GeoNames extractor..."; } @Override public String getDescription(){ return "Convert various GeoNames web api feeds to topic maps"; } @Override public WandoraToolType getType() { return WandoraToolType.createExtractType(); } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_geonames.png"); } public void execute(Wandora admin, Context context) { try { if(selector == null) { selector = new GeoNamesExtractorSelector(admin); } selector.setAccepted(false); selector.setWandora(admin); selector.setContext(context); selector.setVisible(true); if(selector.wasAccepted()) { setDefaultLogger(); WandoraTool extractor = selector.getWandoraTool(this); if(extractor != null) { extractor.setToolLogger(getDefaultLogger()); extractor.execute(admin, context); } } else { // log("User cancelled the extraction!"); } } catch(Exception e) { singleLog(e); } if(selector != null && selector.wasAccepted()) setState(WAIT); else setState(CLOSE); } }
2,818
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
GeoNamesSearch.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/geonames/GeoNamesSearch.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * GeoNamesSearch.java * */ package org.wandora.application.tools.extractors.geonames; import java.io.InputStream; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; /** * * @author akivela */ public class GeoNamesSearch extends AbstractGeoNamesExtractor { private static final long serialVersionUID = 1L; public String dataLang = "en"; public String requestGeoObject = null; @Override public String getName() { return "GeoNames search extractor"; } @Override public String getDescription(){ return "Search geo locations from GeoNames web api and converts search results to a topic map."; } public void setRequestGeoObject(String p) { this.requestGeoObject = p; } /* @Override public synchronized void extractTopicsFrom(URL url, TopicMap topicMap) throws Exception { try { String str = url.toExternalForm(); Pattern p = Pattern.compile("geonameId=(\\w+)"); Matcher m = p.matcher(str); if(m.find()) { String geoid = m.group(1); if(geoid != null && geoid.length() > 0) { setRequestGeoObject(geoid); } } } catch(Exception e) {} super.extractTopicsFrom(url, topicMap); } */ 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(); GeoNamesSearchParser parserHandler = new GeoNamesSearchParser(topicMap,this,dataLang); parserHandler.setRequestGeoObject(requestGeoObject); 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); } if(parserHandler.progress == 0) log("No search results found!"); else if(parserHandler.progress == 1) log("One search result found!"); else log("Total " + parserHandler.progress + " search result found!"); requestGeoObject = null; // FORCE NULL AS THIS OBJECT IS REUSED. return true; } // ------------------------------------------------------------------------- // --- GEONAMES XML FEED PARSER -------------------------------------------- // ------------------------------------------------------------------------- private class GeoNamesSearchParser extends AbstractGeoNamesParser { public GeoNamesSearchParser(TopicMap tm, AbstractGeoNamesExtractor parent, String lang){ super(tm, parent, lang); } public void handleGeoNameElement() { if(data_name.length() > 0 || data_geonameid.length() > 0) { try { theGeoObject=getGeoTopic(tm, data_geonameid, data_name, lang); theGeoObjectSI=theGeoObject.getOneSubjectIdentifier().toExternalForm(); parent.setProgress(progress++); try { if(isValid(data_fcode)) { Topic fcodeTopic = getFCodeTopic(tm, data_fcode, data_fcodename); theGeoObject.addType(fcodeTopic); } if(isValid(data_fcl)) { Topic fclTopic = getFCLTopic(tm, data_fcl, data_fclname); theGeoObject.addType(fclTopic); } if(isValid(data_countrycode) && isValid(data_countryname)) { Topic countryTopic=getCountryTopic(tm, data_countrycode, data_countryname, lang); if(theGeoObject.isRemoved()) theGeoObject=tm.getTopic(theGeoObjectSI); makeGeoCountry(theGeoObject, countryTopic, tm); } if(isValid(data_continentcode)) { Topic continentTopic=getContinentTopic(tm, data_continentcode); if(theGeoObject.isRemoved()) theGeoObject=tm.getTopic(theGeoObjectSI); makeGeoContinent(theGeoObject, continentTopic, tm); } if(isValid(data_lat) && isValid(data_lng)) { makeLatLong(data_lat, data_lng, theGeoObject, tm); } if(data_alternatename_all != null && data_alternatename_all.size() > 0) { if(theGeoObject.isRemoved()) theGeoObject=tm.getTopic(theGeoObjectSI); nameGeoObjectTopic(theGeoObject, data_alternatename_all); } if(isValid(data_population)) { if(theGeoObject.isRemoved()) theGeoObject=tm.getTopic(theGeoObjectSI); Topic populationTypeTopic = getPopulationTypeTopic(tm); theGeoObject.setData(populationTypeTopic, TMBox.getLangTopic(theGeoObject, lang), data_population); } } catch(Exception e) { parent.log(e); } } catch(TopicMapException tme){ parent.log(tme); } } } } }
6,916
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DuckDuckGoExtractorUI.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/duckduckgo/DuckDuckGoExtractorUI.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.duckduckgo; import java.util.ArrayList; 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.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.topicmap.TopicMapException; /** * * @author Eero */ public class DuckDuckGoExtractorUI extends javax.swing.JPanel { private static final long serialVersionUID = 1L; private boolean accepted = false; private JDialog dialog = null; private Context context = null; private Wandora wandora = null; private static final String ddgEndpoint = "http://api.duckduckgo.com/"; /** * Creates new form DuckDuckGoExtractorUI */ public DuckDuckGoExtractorUI() { 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(550, 150); dialog.add(this); dialog.setTitle("DuckDuckGo API extractor"); UIBox.centerWindow(dialog, w); dialog.setVisible(true); } public WandoraTool[] getExtractors(DuckDuckGoExtractor tool) throws TopicMapException { WandoraTool wt; ArrayList<WandoraTool> wts = new ArrayList<>(); String query = ddgInput.getText(); String extractUrl = ddgEndpoint + "?q=" + query + "&format=json"; DuckDuckGoZeroClickExtractor ex = new DuckDuckGoZeroClickExtractor(); ex.setForceUrls(new String[]{ extractUrl }); wt = ex; wts.add(wt); return wts.toArray(new WandoraTool[]{}); } /** * 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; duckDuckGoPanel = new javax.swing.JPanel(); ddgLabel = new SimpleLabel(); ddgInput = new SimpleField(); filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 32767)); buttonPanel = new javax.swing.JPanel(); buttonFillerPanel = new javax.swing.JPanel(); okButton = new SimpleButton(); cancelButton = new SimpleButton(); setLayout(new java.awt.GridBagLayout()); duckDuckGoPanel.setLayout(new java.awt.GridBagLayout()); ddgLabel.setText("Search query"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; gridBagConstraints.weighty = 0.1; gridBagConstraints.insets = new java.awt.Insets(8, 4, 0, 4); duckDuckGoPanel.add(ddgLabel, gridBagConstraints); 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, 5, 5, 5); duckDuckGoPanel.add(ddgInput, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL; gridBagConstraints.weighty = 0.1; duckDuckGoPanel.add(filler1, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.PAGE_START; gridBagConstraints.weighty = 0.1; add(duckDuckGoPanel, 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 = 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 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 // 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.JTextField ddgInput; private javax.swing.JLabel ddgLabel; private javax.swing.JPanel duckDuckGoPanel; private javax.swing.Box.Filler filler1; private javax.swing.JButton okButton; // End of variables declaration//GEN-END:variables }
8,060
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DuckDuckGoZeroClickExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/duckduckgo/DuckDuckGoZeroClickExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.duckduckgo; import java.io.File; import java.io.FileInputStream; import java.net.URL; import java.util.HashMap; import org.apache.commons.io.IOUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.wandora.topicmap.Association; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.JsonNode; import com.mashape.unirest.http.Unirest; /** * * @author Eero */ public class DuckDuckGoZeroClickExtractor extends AbstractDuckDuckGoExtractor { private static final long serialVersionUID = 1L; private static final String API_SI = "http://api.duckduckgo.com"; private static final String API_NAME = "DuckDuckGo API"; private static final String SI_ROOT = "http://wandora.org/si/duckduckgo"; private static final String DUCK_T_SI = SI_ROOT + "/topic"; private static final String DEFINITON_SI = SI_ROOT + "/defintion"; private static final String HEADING_SI = SI_ROOT + "/heading"; private static final String IMAGE_SI = SI_ROOT + "/image"; private static final String ABSTRACT_SI = SI_ROOT + "/abstract"; private static final String ABST_SOURCE_SI = SI_ROOT + "/abstract_source"; private static final String ANSWER_SI = SI_ROOT + "/answer"; private static final String ANS_TYPE_SI = SI_ROOT + "/answer_type"; private static final String RELATED_SI = SI_ROOT + "/related"; private static final String RELATED_TO_SI = SI_ROOT + "/related_to"; private static final String RELATED_FROM_SI = SI_ROOT + "/related_from"; // {field in JSON, Type Topic SI, Base name} private static final String[][] typeStrings = { {"Topic", DUCK_T_SI, "Topic"}, {"Definition", DEFINITON_SI, "Definition"}, {"Heading", HEADING_SI, "Heading"}, {"Image", IMAGE_SI, "Image"}, {"Abstract", ABSTRACT_SI, "Abstract"}, {"AbstractSource", ABST_SOURCE_SI, "Abstract Source"}, {"Answer", ANSWER_SI, "Answer"}, {"AnswerType", ANS_TYPE_SI, "Answered Type"}, {"Related", RELATED_SI, "Related"}, {"RelatedTo", RELATED_TO_SI, "Related To"}, {"RelatedFrom", RELATED_FROM_SI, "Related From"} }; // A list of types that should be used as occurrence types // Should be a subset of the keys in typeStrings. private static final String[] occStrings = { "Definition", "Heading", "Image", "Abstract", "AbstractSource", "Answer", "AnswerType" }; // ------------------------------------------------------------------------- @Override public boolean _extractTopicsFrom(File f, TopicMap tm) throws Exception { FileInputStream is = new FileInputStream(f); String query = IOUtils.toString(is); _extractTopicsFrom(query, tm); return true; } @Override public boolean _extractTopicsFrom(URL u, TopicMap tm) throws Exception { String currentURL = u.toExternalForm(); extractTopicsFromText(currentURL, tm); return true; } @Override public boolean _extractTopicsFrom(String str, TopicMap tm) throws Exception { HttpResponse<JsonNode> resp = Unirest.get(str) .asJson(); parse(resp, tm); return true; } // ------------------------------------------------------------------------- private void parse(HttpResponse<JsonNode> json, TopicMap tm){ try { JsonNode jsonBody = json.getBody(); JSONObject body = jsonBody.getObject(); if(body.has("message")){ log(body.getString("message")); throw new Exception("Query failed: no result"); } Topic lang = getLangTopic(tm); Topic api = getAPIClass(tm, API_SI, API_NAME); HashMap<String, Topic> types = getTypes(tm,typeStrings, api); String bn = body.getString("Heading"); String absUrl = body.getString("AbstractURL"); Topic res = getTopic(tm, types.get("Topic"), absUrl ,bn); for (int i = 0; i < occStrings.length; i++) { String key = occStrings[i]; String val = body.getString(key); Topic type = types.get(key); if(val.length() > 0){ res.setData(type, lang , val); } } JSONArray relTopics = body.getJSONArray("RelatedTopics"); for (int i = 0; i < relTopics.length(); i++) { JSONObject relJson = relTopics.getJSONObject(i); String relUrl = relJson.getString("FirstURL"); String relDesc = relJson.getString("Text"); Topic rel = getTopic(tm, types.get("Topic"), relUrl, relDesc); Association a = tm.createAssociation(types.get("Related")); a.addPlayer(res, types.get("RelatedFrom")); a.addPlayer(rel, types.get("RelatedTo")); } } catch(JSONException jse){ log(jse.getMessage()); } catch (Exception e){ log(e.getMessage()); } } }
6,487
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AbstractDuckDuckGoExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/duckduckgo/AbstractDuckDuckGoExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.duckduckgo; 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 */ public abstract class AbstractDuckDuckGoExtractor extends AbstractExtractor{ private static final long serialVersionUID = 1L; private static final String LANG_SI = "http://www.topicmaps.org/xtm/1.0/language.xtm#en"; private static final String LAMBDA_SI = "https://lambda-face-detection-and-recognition.p.mashape.com"; private static final String TAG_SI = "http://wandora.org/si/mashape/lambda/tag"; private static final String FACE_SI = "http://wandora.org/si/mashape/lambda/face"; private static final String PHOTO_SI = "http://wandora.org/si/mashape/lambda/photo"; private static final String SMILE_SI = "http://wandora.org/si/mashape/lambda/smiling"; private static final String WIDTH_SI = "http://wandora.org/si/mashape/lambda/width"; private static final String HEIGHT_SI = "http://wandora.org/si/mashape/lambda/height"; @Override public String getName() { return "Abstract DuckDuckGo extractor"; } @Override public String getDescription(){ return "Abstract extractor for DuckDuckGo."; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_duckduckgo.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; } // ------------------------------------------------------ HELPERS --- 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 Topic getAPIClass(TopicMap tm, String si, String baseName) throws TopicMapException{ Topic t = getOrCreateTopic(tm, si, baseName); makeSubclassOf(tm, t, getWandoraClassTopic(tm)); return t; } protected static Topic getTypeClass(TopicMap tm, String si, String baseName) throws TopicMapException{ return getTypeClass(tm, null, si, baseName); } protected static Topic getTypeClass(TopicMap tm, Topic superClass, String si, String baseName) throws TopicMapException{ Topic type=getOrCreateTopic(tm, si, baseName); type.setBaseName(baseName); if(superClass != null){ makeSubclassOf(tm, type, superClass); } return type; } protected static Topic getTopic(TopicMap tm, Topic type, String si, String baseName ) throws TopicMapException{ Topic t = getOrCreateTopic(tm, si); t.addType(type); t.setBaseName(baseName); return t; } protected static HashMap<String, Topic> getTypes(TopicMap tm, String[][] typeStrings, Topic api) throws TopicMapException{ HashMap<String, Topic> ts = new HashMap<String,Topic>(); for (int i = 0; i < typeStrings.length; i++) { Topic t = getTypeClass(tm, api, typeStrings[i][1], typeStrings[i][2]); ts.put(typeStrings[i][0], t); } return ts; } }
5,266
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DuckDuckGoExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/duckduckgo/DuckDuckGoExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.duckduckgo; 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; /** * * @author Eero */ public class DuckDuckGoExtractor extends AbstractWandoraTool { private static final long serialVersionUID = 1L; private DuckDuckGoExtractorUI ui = null; @Override public String getName() { return "DuckDuckGo API Extractor"; } @Override public String getDescription(){ return "Extracts topics and associations from DuckDuckGo API"; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_duckduckgo.png"); } @Override public void execute(Wandora wandora, Context context) { try { if(ui == null) { ui = new DuckDuckGoExtractorUI(); } 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 API query..."); for(int i=0; i<extrs.length && !forceStop(); i++) { try { 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); } // ------------------------------------------------------------------------- }
3,344
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
BookmarkExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/bookmark/BookmarkExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.bookmark; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URL; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import javax.swing.Icon; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; 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.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.XTMPSI; /** * * @author Eero */ public class BookmarkExtractor extends AbstractExtractor { private static final long serialVersionUID = 1L; private String ROOT_SI = "http://wandora.org/si/bookmark"; private String HREF_SI = "http://wandora.org/si/bookmark/href"; private String ADD_SI = "http://wandora.org/si/bookmark/added"; private String MOD_SI = "http://wandora.org/si/bookmark/modified"; private String ICON_SI = "http://wandora.org/si/bookmark/icon"; private String LANG = XTMPSI.getLang("en"); private Topic langTopic; private SimpleDateFormat df; private String[][] itemProps = { {HREF_SI, "href", "href"}, {ICON_SI, "icon_uri", "icon uri"} }; private String[][] itemTimeProps = { {ADD_SI, "add_date", "date added"}, {MOD_SI, "last_modified", "date modified"} }; @Override public String getName() { return "Firefox bookmark extractor"; } @Override public String getDescription(){ return "Extracts topics and associations out of Firefox bookmark HTML file."; } @Override public int getExtractorType() { return FILE_EXTRACTOR | URL_EXTRACTOR; } public static final String[] contentTypes=new String[] { "text/html" }; @Override public String[] getContentTypes() { return contentTypes; } @Override public Icon getIcon() { return UIBox.getIcon(0xf097); } @Override public boolean _extractTopicsFrom(File f, TopicMap t) throws Exception { if(!f.isFile()) return false; try { Document d = Jsoup.parse(f, null); parse(d,t); } catch (Exception e) { log(e); return false; } return true; } @Override public boolean _extractTopicsFrom(URL u, TopicMap t) throws Exception { try { Document d = Jsoup.connect(u.toString()).get(); parse(d,t); } catch (Exception e) { log(e); return false; } return true; } @Override public boolean _extractTopicsFrom(String str, TopicMap t) throws Exception { try { Document d = Jsoup.parse(str); parse(d,t); } catch (Exception e) { log(e); return false; } return true; } private void parse(Document d, TopicMap t) throws FileNotFoundException, IOException, TopicMapException, ParseException{ langTopic = getOrCreateTopic(t, LANG); df = new SimpleDateFormat(); Elements menu = d.select("body > dl"); for(Element e : menu){ parseCategory(e,t); } } private void parseCategory(Element c, TopicMap t) throws TopicMapException, ParseException{ Topic wc = getWandoraClass(t); Topic root = getOrCreateTopic(t, ROOT_SI, "Bookmark"); root.setSubjectLocator(new Locator(ROOT_SI)); root.setDisplayName(LANG, "Bookmark"); makeSubclassOf(t, root, wc); for(Element child: c.children()){ if(child.tagName().equals("dt")){ for(Element grandChild: child.children()){ if(grandChild.tagName().equals("a")) parseItem(grandChild,root,t); else if(grandChild.tagName().equals("dl")) parseCategory(child, root, t); } } } parseCategory(c, root, t); } private void parseCategory(Element c, Topic parent, TopicMap t) throws TopicMapException, ParseException{ Topic cTopic = parent; Elements children = c.children(); for(Element child : children){ if(child.tagName().equals("h3")) { String cLocator = parent.getSubjectLocator().toString(); cLocator += "/" + urlEncode(child.html()); String cName = child.ownText(); cTopic = getOrCreateTopic(t, cLocator); cTopic.setSubjectLocator(new Locator(cLocator)); cTopic.setBaseName(cName + " (Bookmark)"); cTopic.setDisplayName(LANG, cName); makeSubclassOf(t, cTopic, parent); } } for(Element child : children){ if(!child.tagName().equals("dl")) continue; for(Element grandChild : child.children()){ if(!grandChild.tagName().equals("dt")) continue; for(Element ggChild : grandChild.children()){ if(ggChild.tagName().equals("a")) parseItem(ggChild,cTopic,t); else if(ggChild.tagName().equals("dl")) parseCategory(grandChild, cTopic, t); } } } } private void parseItem(Element i, Topic parent, TopicMap t) throws TopicMapException, ParseException{ String cLocator = i.attr("href"); Topic iTopic = getOrCreateTopic(t, cLocator); iTopic.setSubjectLocator(new Locator(cLocator)); iTopic.setBaseName(i.ownText() + " (Bookmark)"); iTopic.setDisplayName(LANG, i.ownText()); iTopic.addType(parent); String attr; Topic type; for (int j = 0; j < itemProps.length; j++) { type = getOrCreateTopic(t, itemProps[j][0],itemProps[j][2]); attr = i.attr(itemProps[j][1]); if(attr.length() > 0) iTopic.setData(type, langTopic, attr); } long timeStamp; for (int j = 0; j < itemTimeProps.length; j++) { type = getOrCreateTopic(t, itemTimeProps[j][0],itemTimeProps[j][2]); attr = i.attr(itemTimeProps[j][1]); if(attr.length() > 0) { timeStamp = Integer.parseInt(attr); timeStamp *= 1000; iTopic.setData(type, langTopic, df.format(new Date(timeStamp))); } } } private Topic getWandoraClass(TopicMap tm) throws TopicMapException { return createTopic(tm, TMBox.WANDORACLASS_SI, "Wandora class"); } private Topic getOrCreateTopic(TopicMap tm, String si) throws TopicMapException { return getOrCreateTopic(tm, si, null); } private Topic getOrCreateTopic(TopicMap tm, String si, String bn) throws TopicMapException { return ExtractHelper.getOrCreateTopic(si, bn, tm); } private void makeSubclassOf(TopicMap tm, Topic t, Topic superclass) throws TopicMapException { ExtractHelper.makeSubclassOf(t, superclass, tm); } }
8,412
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
RSSRDFExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/rdf/RSSRDFExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * RSSRDFExtractor.java * * Created on 26.2.2009,14:25 */ package org.wandora.application.tools.extractors.rdf; import javax.swing.Icon; import org.wandora.application.gui.UIBox; import org.wandora.application.tools.extractors.rdf.rdfmappings.DublinCoreMapping; import org.wandora.application.tools.extractors.rdf.rdfmappings.RDF2TopicMapsMapping; import org.wandora.application.tools.extractors.rdf.rdfmappings.RDFMapping; import org.wandora.application.tools.extractors.rdf.rdfmappings.RDFSMapping; import org.wandora.application.tools.extractors.rdf.rdfmappings.RSSMapping; /** * * @author akivela */ public class RSSRDFExtractor extends AbstractRDFExtractor { private static final long serialVersionUID = 1L; private RDF2TopicMapsMapping[] mappings = new RDF2TopicMapsMapping[] { new RSSMapping(), new RDFSMapping(), new RDFMapping(), new DublinCoreMapping(), }; public RSSRDFExtractor() { } @Override public String getName() { return "RSS RDF extractor..."; } @Override public String getDescription(){ return "Read RSS 1.0 RDF feed and convert it to a topic map."; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_rss.png"); } public RDF2TopicMapsMapping[] getMappings() { return mappings; } }
2,218
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TwineExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/rdf/TwineExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * TwineExtractor.java * * Created on 7.2.2009,12:32 */ package org.wandora.application.tools.extractors.rdf; import java.net.URL; import javax.swing.Icon; import org.wandora.application.gui.UIBox; import org.wandora.application.tools.extractors.rdf.rdfmappings.RDF2TopicMapsMapping; import org.wandora.application.tools.extractors.rdf.rdfmappings.RDFMapping; import org.wandora.application.tools.extractors.rdf.rdfmappings.RDFSMapping; import org.wandora.application.tools.extractors.rdf.rdfmappings.TwineMapping; import org.wandora.topicmap.TopicMap; /** * * @author akivela */ public class TwineExtractor extends AbstractRDFExtractor { private static final long serialVersionUID = 1L; private RDF2TopicMapsMapping[] mappings = new RDF2TopicMapsMapping[] { new TwineMapping(), new RDFSMapping(), new RDFMapping(), }; public TwineExtractor() { } @Override public String getName() { return "Twine RDF extractor..."; } @Override public String getDescription(){ return "Read Twine RDF feed and convert it to a topic map."; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_twine.png"); } public RDF2TopicMapsMapping[] getMappings() { return mappings; } @Override public boolean _extractTopicsFrom(URL url, TopicMap topicMap) throws Exception { url = fixTwineURL("http://www.twine.com/item/", url); url = fixTwineURL("http://www.twine.com/twine/", url); return super._extractTopicsFrom(url, topicMap); } public URL fixTwineURL(String twineUrlBody, URL url) { String urlStr = url.toExternalForm(); if(urlStr != null && urlStr.length() > 0) { if(!urlStr.endsWith("?rdf") && urlStr.startsWith(twineUrlBody)) { int startIndex = twineUrlBody.length(); int endIndex = startIndex; while(endIndex<urlStr.length() && urlStr.charAt(endIndex)!='/' && urlStr.charAt(endIndex)!='?' && urlStr.charAt(endIndex)!=' ') endIndex++; String twineId = urlStr.substring(startIndex, endIndex); if(twineId != null && twineId.length() > 0) { try { String fixedUrlStr = twineUrlBody+twineId+"?rdf"; log("Fixed Twine url: "+fixedUrlStr); url = new URL(fixedUrlStr); } catch(Exception e) { log(e); } } } } return url; } }
3,592
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
CreativeCommonsRDFExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/rdf/CreativeCommonsRDFExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * CreativeCommonsRDFExtractor.java * * Created on 7.10.2009,12:17 */ package org.wandora.application.tools.extractors.rdf; import javax.swing.Icon; import org.wandora.application.gui.UIBox; import org.wandora.application.tools.extractors.rdf.rdfmappings.CreativeCommonsMapping; import org.wandora.application.tools.extractors.rdf.rdfmappings.RDF2TopicMapsMapping; import org.wandora.application.tools.extractors.rdf.rdfmappings.RDFMapping; import org.wandora.application.tools.extractors.rdf.rdfmappings.RDFSMapping; /** * * @author akivela */ public class CreativeCommonsRDFExtractor extends AbstractRDFExtractor { private static final long serialVersionUID = 1L; private RDF2TopicMapsMapping[] mappings = new RDF2TopicMapsMapping[] { new CreativeCommonsMapping(), new RDFSMapping(), new RDFMapping(), }; public CreativeCommonsRDFExtractor() { } @Override public String getName() { return "Creative Commons RDF extractor..."; } @Override public String getDescription(){ return "Read Creative Commons (CC) RDF feed and convert it to a topic map."; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_cc.png"); } public RDF2TopicMapsMapping[] getMappings() { return mappings; } }
2,145
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AllMappingsExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/rdf/AllMappingsExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.rdf; import javax.swing.Icon; import org.wandora.application.gui.UIBox; import org.wandora.application.tools.extractors.rdf.rdfmappings.RDF2TopicMapsMapping; import org.wandora.application.tools.extractors.rdf.rdfmappings.RDFMapping; import org.wandora.application.tools.extractors.rdf.rdfmappings.RDFSMapping; /** * * @author akivela */ public class AllMappingsExtractor extends AbstractRDFExtractor { private static final long serialVersionUID = 1L; private RDF2TopicMapsMapping[] mappings = new RDF2TopicMapsMapping[] { new RDFSMapping(), new RDFMapping(), }; public AllMappingsExtractor() { } @Override public String getName() { return "All RDF mappings extractor..."; } @Override public String getDescription(){ return "Read RDF feed and convert it to a topic map."; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_rdfs.png"); } public RDF2TopicMapsMapping[] getMappings() { return mappings; } }
1,904
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
IIIFRDFExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/rdf/IIIFRDFExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.rdf; import org.apache.jena.rdf.model.Literal; 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.wandora.application.tools.extractors.rdf.rdfmappings.DublinCoreMapping; import org.wandora.application.tools.extractors.rdf.rdfmappings.EXIFMapping; import org.wandora.application.tools.extractors.rdf.rdfmappings.IIIFMapping; import org.wandora.application.tools.extractors.rdf.rdfmappings.OAMapping; import org.wandora.application.tools.extractors.rdf.rdfmappings.RDF2TopicMapsMapping; import org.wandora.application.tools.extractors.rdf.rdfmappings.RDFMapping; import org.wandora.application.tools.extractors.rdf.rdfmappings.RDFSMapping; import org.wandora.application.tools.extractors.rdf.rdfmappings.SCMapping; import org.wandora.application.tools.extractors.rdf.rdfmappings.SKOSMapping; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public class IIIFRDFExtractor extends AbstractRDFExtractor { private static final long serialVersionUID = 1L; protected RDF2TopicMapsMapping[] mappings=new RDF2TopicMapsMapping[]{ new IIIFMapping(), new SCMapping(), new OAMapping(), new DublinCoreMapping(), new EXIFMapping(), new RDFMapping(), new RDFSMapping(), new SKOSMapping(), }; @Override public String getName() { return "IIIF JSON-LD Extractor"; } @Override public String getDescription(){ return "Reads IIIF JSON-LD and converts it to a topic map"; } @Override public String getRDFContainerFormat() { return "JSON-LD"; } protected static final String label_uri=RDFSMapping.RDFS_NS+"label"; protected static final String type_uri=RDFMapping.RDF_NS+"type"; @Override 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 String predicateId=predicate.toString(); if(label_uri.equals(predicateId) && object.isLiteral()) { Topic subjectTopic = getOrCreateTopic(map, subject.toString()); subjectTopic.setDisplayName(null, ((Literal) object).getString()); } else if(type_uri.equals(predicateId) && object.isResource()){ Topic subjectTopic = getOrCreateTopic(map, subject.toString()); Topic objectTopic = getOrCreateTopic(map, object.toString()); subjectTopic.addType(objectTopic); if(object.toString().equals(DublinCoreMapping.DC_TYPES_NS+"Image")){ subjectTopic.setSubjectLocator(map.createLocator(subject.toString())); } } else { super.handleStatement(stmt, map); } } @Override public RDF2TopicMapsMapping[] getMappings() { return mappings; } }
4,075
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
FoafRDFExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/rdf/FoafRDFExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * FoafRDFExtractor.java * * Created on 12.2.2009,12:32 */ package org.wandora.application.tools.extractors.rdf; import javax.swing.Icon; import org.wandora.application.gui.UIBox; import org.wandora.application.tools.extractors.rdf.rdfmappings.DublinCoreMapping; import org.wandora.application.tools.extractors.rdf.rdfmappings.FOAFMapping; import org.wandora.application.tools.extractors.rdf.rdfmappings.RDF2TopicMapsMapping; import org.wandora.application.tools.extractors.rdf.rdfmappings.RDFMapping; import org.wandora.application.tools.extractors.rdf.rdfmappings.RDFSMapping; /** * Read more at http://xmlns.com/foaf/spec/ * * @author akivela */ public class FoafRDFExtractor extends AbstractRDFExtractor { private static final long serialVersionUID = 1L; private RDF2TopicMapsMapping[] mappings = new RDF2TopicMapsMapping[] { new FOAFMapping(), new RDFSMapping(), new RDFMapping(), new DublinCoreMapping(), }; public FoafRDFExtractor() { } @Override public String getName() { return "Foaf RDF extractor..."; } @Override public String getDescription(){ return "Read Foaf RDF feed and convert it to a topic map."; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_foaf.png"); } public RDF2TopicMapsMapping[] getMappings() { return mappings; } }
2,275
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DublinCoreRDFExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/rdf/DublinCoreRDFExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * DublinCoreRDFExtractor.java * * Created on 12.2.2009,12:32 */ package org.wandora.application.tools.extractors.rdf; import javax.swing.Icon; import org.wandora.application.gui.UIBox; import org.wandora.application.tools.extractors.rdf.rdfmappings.DublinCoreMapping; import org.wandora.application.tools.extractors.rdf.rdfmappings.RDF2TopicMapsMapping; import org.wandora.application.tools.extractors.rdf.rdfmappings.RDFMapping; import org.wandora.application.tools.extractors.rdf.rdfmappings.RDFSMapping; /** * * @author akivela */ public class DublinCoreRDFExtractor extends AbstractRDFExtractor { private static final long serialVersionUID = 1L; private RDF2TopicMapsMapping[] mappings = new RDF2TopicMapsMapping[] { new DublinCoreMapping(), new RDFSMapping(), new RDFMapping(), }; public DublinCoreRDFExtractor() { } @Override public String getName() { return "Dublin core RDF extractor..."; } @Override public String getDescription(){ return "Read Dublin core RDF feed and convert it to a topic map."; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_dc.png"); } public RDF2TopicMapsMapping[] getMappings() { return mappings; } }
2,156
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
OpenCYCOWLExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/rdf/OpenCYCOWLExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * OpenCYCOWLExtractor.java */ package org.wandora.application.tools.extractors.rdf; import javax.swing.Icon; import org.wandora.application.gui.UIBox; import org.wandora.application.tools.extractors.rdf.rdfmappings.OWLMapping; import org.wandora.application.tools.extractors.rdf.rdfmappings.OpenCYCMapping; import org.wandora.application.tools.extractors.rdf.rdfmappings.RDF2TopicMapsMapping; import org.wandora.application.tools.extractors.rdf.rdfmappings.RDFMapping; import org.wandora.application.tools.extractors.rdf.rdfmappings.RDFSMapping; /** * * @author akivela */ public class OpenCYCOWLExtractor extends AbstractRDFExtractor { private static final long serialVersionUID = 1L; private RDF2TopicMapsMapping[] mappings = new RDF2TopicMapsMapping[] { new OpenCYCMapping(), new OWLMapping(), new RDFSMapping(), new RDFMapping(), }; public OpenCYCOWLExtractor() { } @Override public String getName() { return "OpenCYC OWL extractor..."; } @Override public String getDescription(){ return "Read OpenCYC OWL feed and convert it to a topic map."; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_open_cyc.png"); } public RDF2TopicMapsMapping[] getMappings() { return mappings; } }
2,207
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
OWLExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/rdf/OWLExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * OWLExtractor.java * * Created on 5.3.2009,14:32 */ package org.wandora.application.tools.extractors.rdf; import javax.swing.Icon; import org.wandora.application.gui.UIBox; import org.wandora.application.tools.extractors.rdf.rdfmappings.OWLMapping; import org.wandora.application.tools.extractors.rdf.rdfmappings.RDF2TopicMapsMapping; import org.wandora.application.tools.extractors.rdf.rdfmappings.RDFMapping; import org.wandora.application.tools.extractors.rdf.rdfmappings.RDFSMapping; /** * * @author akivela */ public class OWLExtractor extends AbstractRDFExtractor { private static final long serialVersionUID = 1L; private RDF2TopicMapsMapping[] mappings = new RDF2TopicMapsMapping[] { new OWLMapping(), new RDFSMapping(), new RDFMapping(), }; public OWLExtractor() { } @Override public String getName() { return "OWL extractor..."; } @Override public String getDescription(){ return "Read OWL RDF feed and convert it to a topic map."; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_owl.png"); } public RDF2TopicMapsMapping[] getMappings() { return mappings; } }
2,085
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
RDFSExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/rdf/RDFSExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * RDFSExtractor.java * * Created on 12.2.2009,12:32 */ package org.wandora.application.tools.extractors.rdf; import javax.swing.Icon; import org.wandora.application.gui.UIBox; import org.wandora.application.tools.extractors.rdf.rdfmappings.RDF2TopicMapsMapping; import org.wandora.application.tools.extractors.rdf.rdfmappings.RDFMapping; import org.wandora.application.tools.extractors.rdf.rdfmappings.RDFSMapping; /** * * @author akivela */ public class RDFSExtractor extends AbstractRDFExtractor { private static final long serialVersionUID = 1L; private RDF2TopicMapsMapping[] mappings = new RDF2TopicMapsMapping[] { new RDFSMapping(), new RDFMapping(), }; public RDFSExtractor() { } @Override public String getName() { return "RDF(S) extractor..."; } @Override public String getDescription(){ return "Read RDF(S) feed and convert it to a topic map."; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_rdfs.png"); } public RDF2TopicMapsMapping[] getMappings() { return mappings; } }
1,997
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SKOSRDFExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/rdf/SKOSRDFExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * SKOSRDFExtractor.java * * Created on 26.2.2009,14:25 */ package org.wandora.application.tools.extractors.rdf; import javax.swing.Icon; import org.wandora.application.gui.UIBox; import org.wandora.application.tools.extractors.rdf.rdfmappings.RDF2TopicMapsMapping; import org.wandora.application.tools.extractors.rdf.rdfmappings.RDFMapping; import org.wandora.application.tools.extractors.rdf.rdfmappings.RDFSMapping; import org.wandora.application.tools.extractors.rdf.rdfmappings.SKOSMapping; /** * * @author akivela */ public class SKOSRDFExtractor extends AbstractRDFExtractor { private static final long serialVersionUID = 1L; private RDF2TopicMapsMapping[] mappings = new RDF2TopicMapsMapping[] { new SKOSMapping(), new RDFSMapping(), new RDFMapping(), }; public SKOSRDFExtractor() { } @Override public String getName() { return "SKOS RDF extractor..."; } @Override public String getDescription(){ return "Read Simple Knowledge Organization System (SKOS) RDF feed and convert it to a topic map."; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_skos.png"); } public RDF2TopicMapsMapping[] getMappings() { return mappings; } }
2,145
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AbstractRDFExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/rdf/AbstractRDFExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * AbstractRDFExtractor.java * * Created on 14.2.2009,12:32 */ package org.wandora.application.tools.extractors.rdf; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.StringBufferInputStream; import java.net.URL; import java.net.URLConnection; import java.util.List; import javax.swing.Icon; import org.apache.jena.rdf.model.Literal; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.ModelFactory; import org.apache.jena.rdf.model.Property; import org.apache.jena.rdf.model.RDFList; import org.apache.jena.rdf.model.RDFNode; import org.apache.jena.rdf.model.Resource; import org.apache.jena.rdf.model.Statement; import org.apache.jena.rdf.model.StmtIterator; import org.wandora.application.Wandora; import org.wandora.application.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.application.tools.extractors.rdf.rdfmappings.RDFMapping; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicTools; import org.wandora.topicmap.XTMPSI; import org.wandora.utils.Tuples.T2; /** * * @author akivela */ public abstract class AbstractRDFExtractor extends AbstractExtractor { private static final long serialVersionUID = 1L; private String defaultEncoding = "UTF-8"; public static String defaultLanguage = "en"; public static final String defaultOccurrenceScopeSI = TMBox.LANGINDEPENDENT_SI; public AbstractRDFExtractor() { } @Override public String getName() { return "Abstract RDF extractor..."; } @Override public String getDescription(){ return "Read RDF feed and convert it to a topic map."; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_rdf.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) { baseUrl = null; super.execute(wandora, context); } 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 boolean _extractTopicsFrom(URL url, TopicMap topicMap) throws Exception { setBaseUrl(url.toExternalForm()); URLConnection uc = url.openConnection(); uc.setUseCaches(false); boolean r = _extractTopicsFrom(uc.getInputStream(), topicMap); return r; } public boolean _extractTopicsFrom(File file, TopicMap topicMap) throws Exception { setBaseUrl(file.getAbsolutePath()); return _extractTopicsFrom(new FileInputStream(file),topicMap); } public boolean _extractTopicsFrom(InputStream in, TopicMap topicMap) throws Exception { try { importRDF(in, topicMap); return true; } catch(Exception e) { log(e); } return false; } public boolean _extractTopicsFrom(String in, TopicMap tm) throws Exception { try { importRDF(new StringBufferInputStream(in), tm); } catch(Exception e){ log("Exception when handling request",e); } return true; } /** * Override this if the RDF is in some other container format than XML/RDF. * See Jena documentation for Model.read. * @return */ public String getRDFContainerFormat(){ return null; } public void importRDF(InputStream in, TopicMap map) { if(in != null) { // create an empty model Model model = ModelFactory.createDefaultModel(); // read the RDF/XML file model.read(in, "", getRDFContainerFormat()); RDF2TopicMap(model, map); } } 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 static final String RDF_LIST_ORDER="http://wandora.org/si/rdf/list_order"; 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 String predicateS=predicate.toString(); if(predicateS!=null && ( predicateS.equals(RDFMapping.RDF_NS+"first") || predicateS.equals(RDFMapping.RDF_NS+"rest") ) ) { // skip broken down list statements, the list // should be handled properly when they are the object // of some other statement return; } //System.out.println("statement:\n "+subject+"\n "+predicate+"\n "+object); Topic subjectTopic = getOrCreateTopic(map, subject.toString()); if(object.isResource()) { Topic predicateTopic = getOrCreateTopic(map, predicate.toString()); if(object.canAs(RDFList.class)){ List<RDFNode> list=((RDFList)object.as(RDFList.class)).asJavaList(); int counter=1; Topic orderRole = getOrCreateTopic(map, RDF_LIST_ORDER, "List order"); for(RDFNode listObject : list){ if(!listObject.isResource()){ log("List element is not a resource, skipping."); continue; } Topic objectTopic = getOrCreateTopic(map, listObject.toString()); Topic orderTopic = getOrCreateTopic(map, RDF_LIST_ORDER+"/"+counter, ""+counter); Association association = map.createAssociation(predicateTopic); association.addPlayer(subjectTopic, solveSubjectRoleFor(predicate, subject, map)); association.addPlayer(objectTopic, solveObjectRoleFor(predicate, object, map)); association.addPlayer(orderTopic, orderRole); counter++; } } else { Topic objectTopic = getOrCreateTopic(map, object.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 abstract RDF2TopicMapsMapping[] getMappings(); public Topic solveSubjectRoleFor(Property predicate, Resource subject, TopicMap map) { if(map == null) return null; RDF2TopicMapsMapping[] mappings = 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; for(int i=0; i<mappings.length; i++) { mapped = mappings[i].solveSubjectRoleFor(predicateString, subjectString); if(mapped.e1 != null) { si = mapped.e1; bn = mapped.e2; if(bn==null) bn=solveBasenameFor(si); break; } } return getOrCreateTopic(map, si, bn); } public Topic solveObjectRoleFor(Property predicate, RDFNode object, TopicMap map) { if(map == null) return null; RDF2TopicMapsMapping[] mappings = 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; for(int i=0; i<mappings.length; i++) { mapped = mappings[i].solveObjectRoleFor(predicateString, objectString); if(mapped.e1 != null) { si = mapped.e1; bn = mapped.e2; if(bn==null) bn=solveBasenameFor(si); break; } } return getOrCreateTopic(map, si, bn); } public String solveBasenameFor(String si) { if(si == null) return null; RDF2TopicMapsMapping[] mappings = getMappings(); String bn = null; for(int i=0; i<mappings.length; i++) { bn = mappings[i].solveBasenameFor(si); if(bn != null) break; } return bn; } // ------------------------------------------------------------------------- public Topic getOrCreateTopic(TopicMap map, String si) { return getOrCreateTopic(map, si, solveBasenameFor(si)); } 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; } }
13,295
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
EXIFMapping.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/rdf/rdfmappings/EXIFMapping.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.rdf.rdfmappings; public class EXIFMapping extends RDF2TopicMapsMapping { public static final String EXIF_NS = "http://www.w3.org/2003/12/exif/ns#"; public static final String[] SI_BASENAME_MAPPING = new String[] { EXIF_NS+"exifdata", "exif:Exif data", EXIF_NS+"tag_number", "exif:Tag number", EXIF_NS+"tagid", "exif:Tag ID", EXIF_NS+"datatype", "exif:Data Type", EXIF_NS+"length", "exif:Length", EXIF_NS+"width", "exif:Width", EXIF_NS+"height", "exif:Height", EXIF_NS+"resolution", "exif:Resolution", EXIF_NS+"meter", "exif:Meter", EXIF_NS+"mm", "exif:Milimeter", EXIF_NS+"seconds", "exif:Seconds", EXIF_NS+"date", "exif:Date", EXIF_NS+"subseconds", "exif:Subseconds", EXIF_NS+"geo", "exif:Geometric data", EXIF_NS+"_unknown", "exif:Unknown tag", EXIF_NS+"exifAttribute", "exif:Exif Attribute", EXIF_NS+"dateAndOrTime", "exif:Date and/or Time", EXIF_NS+"gpsInfo", "exif:GPS Info", EXIF_NS+"ifdPointer", "exif:IFD Pointer", EXIF_NS+"imageConfig", "exif:Image Config", EXIF_NS+"imageDataCharacter", "exif:Image Data Character", EXIF_NS+"imageDataStruct", "exif:Image Data Structure", EXIF_NS+"interopInfo", "exif:Interoperability Info", EXIF_NS+"pictTaking", "exif:PictTaking", EXIF_NS+"pimInfo", "exif:PIM Info", EXIF_NS+"recOffset", "exif:Recording Offset", EXIF_NS+"relatedFile", "exif:Related File", EXIF_NS+"userInfo", "exif:User Info", EXIF_NS+"versionInfo", "exif:Version Info", EXIF_NS+"imageWidth", "exif:ImageWidth", EXIF_NS+"imageLength", "exif:ImageLength", EXIF_NS+"bitsPerSample", "exif:BitsPerSample", EXIF_NS+"compression", "exif:Compression", EXIF_NS+"photometricInterpretation", "exif:PhotometricInterpretation", EXIF_NS+"imageDescription", "exif:ImageDescription", EXIF_NS+"make", "exif:Make", EXIF_NS+"model", "exif:Model", EXIF_NS+"stripOffsets", "exif:StripOffsets", EXIF_NS+"orientation", "exif:Orientation", EXIF_NS+"samplesPerPixel", "exif:SamplesPerPixel", EXIF_NS+"rowsPerStrip", "exif:RowsPerStrip", EXIF_NS+"stripByteCounts", "exif:StripByteCounts", EXIF_NS+"xResolution", "exif:XResolution", EXIF_NS+"yResolution", "exif:YResolution", EXIF_NS+"planarConfiguration", "exif:PlanarConfiguration", EXIF_NS+"resolutionUnit", "exif:ResolutionUnit", EXIF_NS+"transferFunction", "exif:TransferFunction", EXIF_NS+"software", "exif:Software", EXIF_NS+"dateTime", "exif:DateTime", EXIF_NS+"artist", "exif:Artist", EXIF_NS+"whitePoint", "exif:WhitePoint", EXIF_NS+"primaryChromaticities", "exif:PrimaryChromaticities", EXIF_NS+"jpegInterchangeFormat", "exif:JPEGInterchangeFormat", EXIF_NS+"jpegInterchangeFormatLength", "exif:JPEGInterchangeFormatLength", EXIF_NS+"yCbCrCoefficients", "exif:YCbCrCoefficients", EXIF_NS+"yCbCrSubSampling", "exif:YCbCrSubSampling", EXIF_NS+"yCbCrPositioning", "exif:YCbCrPositioning", EXIF_NS+"referenceBlackWhite", "exif:ReferenceBlackWhite", EXIF_NS+"copyright", "exif:Copyright", EXIF_NS+"exif_IFD_Pointer", "exif:Exif IFD Pointer", EXIF_NS+"gpsInfo_IFD_Pointer", "exif:GPSInfo IFD Pointer", EXIF_NS+"exposureTime", "exif:ExposureTime", EXIF_NS+"fNumber", "exif:FNumber", EXIF_NS+"exposureProgram", "exif:ExposureProgram", EXIF_NS+"spectralSensitivity", "exif:SpectralSensitivity", EXIF_NS+"isoSpeedRatings", "exif:ISOSpeedRatings", EXIF_NS+"oecf", "exif:OECF", EXIF_NS+"exifVersion", "exif:ExifVersion", EXIF_NS+"dateTimeOriginal", "exif:DateTimeOriginal", EXIF_NS+"dateTimeDigitized", "exif:DateTimeDigitized", EXIF_NS+"componentsConfiguration", "exif:ComponentsConfiguration", EXIF_NS+"compressedBitsPerPixel", "exif:CompressedBitsPerPixel", EXIF_NS+"shutterSpeedValue", "exif:ShutterSpeedValue", EXIF_NS+"apertureValue", "exif:ApertureValue", EXIF_NS+"brightnessValue", "exif:BrightnessValue", EXIF_NS+"exposureBiasValue", "exif:ExposureBiasValue", EXIF_NS+"maxApertureValue", "exif:MaxApertureValue", EXIF_NS+"subjectDistance", "exif:SubjectDistance", EXIF_NS+"meteringMode", "exif:MeteringMode", EXIF_NS+"lightSource", "exif:LightSource", EXIF_NS+"flash", "exif:Flash", EXIF_NS+"focalLength", "exif:FocalLength", EXIF_NS+"subjectArea", "exif:SubjectArea", EXIF_NS+"makerNote", "exif:MakerNote", EXIF_NS+"userComment", "exif:UserComment", EXIF_NS+"subSecTime", "exif:SubSecTime", EXIF_NS+"subSecTimeOriginal", "exif:SubSecTimeOriginal", EXIF_NS+"subSecTimeDigitized", "exif:SubSecTimeDigitized", EXIF_NS+"flashpixVersion", "exif:FlashpixVersion", EXIF_NS+"colorSpace", "exif:ColorSpace", EXIF_NS+"pixelXDimension", "exif:PixelXDimension", EXIF_NS+"pixelYDimension", "exif:PixelYDimension", EXIF_NS+"relatedSoundFile", "exif:RelatedSoundFile", EXIF_NS+"interoperability_IFD_Pointer", "exif:Interoperability IFD Pointer", EXIF_NS+"flashEnergy", "exif:FlashEnergy", EXIF_NS+"spatialFrequencyResponse", "exif:SpatialFrequencyResponse", EXIF_NS+"focalPlaneXResolution", "exif:FocalPlaneXResolution", EXIF_NS+"focalPlaneYResolution", "exif:FocalPlaneYResolution", EXIF_NS+"focalPlaneResolutionUnit", "exif:FocalPlaneResolutionUnit", EXIF_NS+"subjectLocation", "exif:SubjectLocation", EXIF_NS+"exposureIndex", "exif:ExposureIndex", EXIF_NS+"sensingMethod", "exif:SensingMethod", EXIF_NS+"fileSource", "exif:FileSource", EXIF_NS+"sceneType", "exif:SceneType", EXIF_NS+"cfaPattern", "exif:CFAPattern", EXIF_NS+"customRendered", "exif:CustomRendered", EXIF_NS+"exposureMode", "exif:ExposureMode", EXIF_NS+"whiteBalance", "exif:WhiteBalance", EXIF_NS+"digitalZoomRatio", "exif:DigitalZoomRatio", EXIF_NS+"focalLengthIn35mmFilm", "exif:FocalLengthIn35mmFilm", EXIF_NS+"sceneCaptureType", "exif:SceneCaptureType", EXIF_NS+"gainControl", "exif:GainControl", EXIF_NS+"contrast", "exif:Contrast", EXIF_NS+"saturation", "exif:Saturation", EXIF_NS+"sharpness", "exif:Sharpness", EXIF_NS+"deviceSettingDescription", "exif:DeviceSettingDescription", EXIF_NS+"subjectDistanceRange", "exif:SubjectDistanceRange", EXIF_NS+"imageUniqueID", "exif:ImageUniqueID", EXIF_NS+"gpsVersionID", "exif:GPSVersionID", EXIF_NS+"gpsLatitudeRef", "exif:GPSLatitudeRef", EXIF_NS+"gpsLatitude", "exif:GPSLatitude", EXIF_NS+"gpsLongitudeRef", "exif:GPSLongitudeRef", EXIF_NS+"gpsLongitude", "exif:GPSLongitude", EXIF_NS+"gpsAltitudeRef", "exif:GPSAltitudeRef", EXIF_NS+"gpsAltitude", "exif:GPSAltitude", EXIF_NS+"gpsTimeStamp", "exif:GPSTimeStamp", EXIF_NS+"gpsSatellites", "exif:GPSSatellites", EXIF_NS+"gpsStatus", "exif:GPSStatus", EXIF_NS+"gpsMeasureMode", "exif:GPSMeasureMode", EXIF_NS+"gpsDOP", "exif:GPSDOP", EXIF_NS+"gpsSpeedRef", "exif:GPSSpeedRef", EXIF_NS+"gpsSpeed", "exif:GPSSpeed", EXIF_NS+"gpsTrackRef", "exif:GPSTrackRef", EXIF_NS+"gpsTrack", "exif:GPSTrack", EXIF_NS+"gpsImgDirectionRef", "exif:GPSImgDirectionRef", EXIF_NS+"gpsImgDirection", "exif:GPSImgDirection", EXIF_NS+"gpsMapDatum", "exif:GPSMapDatum", EXIF_NS+"gpsDestLatitudeRef", "exif:GPSDestLatitudeRef", EXIF_NS+"gpsDestLatitude", "exif:GPSDestLatitude", EXIF_NS+"gpsDestLongitudeRef", "exif:GPSDestLongitudeRef", EXIF_NS+"gpsDestLongitude", "exif:GPSDestLongitude", EXIF_NS+"gpsDestBearingRef", "exif:GPSDestBearingRef", EXIF_NS+"gpsDestBearing", "exif:GPSDestBearing", EXIF_NS+"gpsDestDistanceRef", "exif:GPSDestDistanceRef", EXIF_NS+"gpsDestDistance", "exif:GPSDestDistance", EXIF_NS+"gpsProcessingMethod", "exif:GPSProcessingMethod", EXIF_NS+"gpsAreaInformation", "exif:GPSAreaInformation", EXIF_NS+"gpsDateStamp", "exif:GPSDateStamp", EXIF_NS+"gpsDifferential", "exif:GPSDifferential", EXIF_NS+"interoperabilityIndex", "exif:InteroperabilityIndex", EXIF_NS+"interoperabilityVersion", "exif:InteroperabilityVersion", EXIF_NS+"relatedImageFileFormat", "exif:RelatedImageFileFormat", EXIF_NS+"relatedImageWidth", "exif:RelatedImageWidth", EXIF_NS+"relatedImageLength", "exif:RelatedImageLength", EXIF_NS+"printImageMatching_IFD_Pointer", "exif:PrintImageMatching IFD Pointer", EXIF_NS+"pimContrast", "exif:PrintIM Contrast", EXIF_NS+"pimBrightness", "exif:PrintIM Brightness", EXIF_NS+"pimColorBalance", "exif:PrintIM ColorBalance", EXIF_NS+"pimSaturation", "exif:PrintIM Saturation", EXIF_NS+"pimSharpness", "exif:PrintIM Sharpness", }; public static final String[] ASSOCIATION_TYPE_TO_ROLES_MAPPING = new String[] { }; public String[] getRoleMappings() { return ASSOCIATION_TYPE_TO_ROLES_MAPPING; } public String[] getBasenameMappings() { return SI_BASENAME_MAPPING; } }
11,854
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
IIIFMapping.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/rdf/rdfmappings/IIIFMapping.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.rdf.rdfmappings; /** * * @author olli */ public class IIIFMapping extends RDF2TopicMapsMapping { public static final String IIIF_NS = "http://library.stanford.edu/iiif/image-api/ns/"; public static final String[] SI_BASENAME_MAPPING = new String[] { }; public static final String[] ASSOCIATION_TYPE_TO_ROLES_MAPPING = new String[] { }; public String[] getRoleMappings() { return ASSOCIATION_TYPE_TO_ROLES_MAPPING; } public String[] getBasenameMappings() { return SI_BASENAME_MAPPING; } }
1,444
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SKOSMapping.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/rdf/rdfmappings/SKOSMapping.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * SKOSMapping.java * * Created on 13.2.2009,15:25 */ package org.wandora.application.tools.extractors.rdf.rdfmappings; /** * * @author akivela */ public class SKOSMapping extends RDF2TopicMapsMapping { public static final String SKOS_NS = "http://www.w3.org/2004/02/skos/core#"; public static final String SKOSXL_NS = "http://www.w3.org/2008/05/skos-xl#"; public static final String SKOS_ROLE_NS = "http://wandora.org/si/skos/role/"; public static final String[] SI_BASENAME_MAPPING = new String[] { SKOS_NS+"Concept", "skos:Concept", SKOS_NS+"ConceptScheme", "skos:ConceptScheme", SKOS_NS+"inScheme", "skos:inScheme", SKOS_NS+"hasTopConcept", "skos:hasTopConcept", SKOS_NS+"topConceptOf", "skos:topConceptOf", SKOS_NS+"prefLabel", "skos:prefLabel", SKOS_NS+"altLabel", "skos:altLabel", SKOS_NS+"hiddenLabel", "skos:hiddenLabel", SKOS_NS+"notation", "skos:notation", SKOS_NS+"note", "skos:note", SKOS_NS+"changeNote", "skos:changeNote", SKOS_NS+"definition", "skos:definition", SKOS_NS+"editorialNote", "skos:editorialNote", SKOS_NS+"example", "skos:example", SKOS_NS+"historyNote", "skos:historyNote", SKOS_NS+"scopeNote", "skos:scopeNote", SKOS_NS+"semanticRelation", "skos:semanticRelation", SKOS_NS+"broader", "skos:broader", SKOS_NS+"narrower", "skos:narrower", SKOS_NS+"related", "skos:related", SKOS_NS+"broaderTransitive", "skos:broaderTransitive", SKOS_NS+"narrowerTransitive", "skos:narrowerTransitive", SKOS_NS+"Collection", "skos:Collection", SKOS_NS+"OrderedCollection", "skos:OrderedCollection", SKOS_NS+"member", "skos:member", SKOS_NS+"memberList", "skos:memberList", SKOS_NS+"mappingRelation", "skos:mappingRelation", SKOS_NS+"closeMatch", "skos:closeMatch", SKOS_NS+"exactMatch", "skos:exactMatch", SKOS_NS+"broadMatch", "skos:broadMatch", SKOS_NS+"narrowMatch", "skos:narrowMatch", SKOS_NS+"relatedMatch", "skos:relatedMatch", // ****** SKOS XL ***** SKOSXL_NS+"Label", "skosxl:Label", SKOSXL_NS+"literalForm", "skosxl:literalForm", SKOSXL_NS+"prefLabel", "skosxl:prefLabel", SKOSXL_NS+"altLabel", "skosxl:altLabel", SKOSXL_NS+"hiddenLabel", "skosxl:hiddenLabel", SKOSXL_NS+"labelRelation", "skosxl:labelRelation", }; public static final String[] ASSOCIATION_TYPE_TO_ROLES_MAPPING = new String[] { SKOS_NS+"inScheme", SKOS_ROLE_NS+"concept", "concept (skos)", SKOS_ROLE_NS+"scheme", "scheme (skos)", SKOS_NS+"hasTopConcept", SKOS_ROLE_NS+"scheme", "scheme (skos)", SKOS_ROLE_NS+"concept", "concept (skos)", SKOS_NS+"topConceptOf", SKOS_ROLE_NS+"concept", "concept (skos)", SKOS_ROLE_NS+"scheme", "scheme (skos)", SKOS_NS+"semanticRelation", SKOS_ROLE_NS+"concept", "concept (skos)", SKOS_ROLE_NS+"semantically-related-concept", "semantically-related-concept (skos)", SKOS_NS+"broader", SKOS_ROLE_NS+"concept", "concept (skos)", SKOS_ROLE_NS+"broader-concept", "broader-concept (skos)", SKOS_NS+"narrower", SKOS_ROLE_NS+"concept", "concep (skos)", SKOS_ROLE_NS+"narrower-concept", "narrower-concept (skos)", SKOS_NS+"related", SKOS_ROLE_NS+"concept", "concept (skos)", SKOS_ROLE_NS+"related-concept", "related-concept (skos)", SKOS_NS+"broaderTransitive", SKOS_ROLE_NS+"concept", "concept (skos)", SKOS_ROLE_NS+"broader-concept", "broader-concept (skos)", SKOS_NS+"narrowerTransitive", SKOS_ROLE_NS+"concept", "concept (skos)", SKOS_ROLE_NS+"narrower-concept", "narrower-concept (skos)", SKOS_NS+"member", SKOS_ROLE_NS+"member", "member (skos)", SKOS_ROLE_NS+"collection", "collection (skos)", SKOS_NS+"memberList", SKOS_ROLE_NS+"member", "member (skos)", SKOS_ROLE_NS+"collection", "collection (skos)", SKOS_NS+"mappingRelation", SKOS_ROLE_NS+"concept", "concept (skos)", SKOS_ROLE_NS+"mapped-concept", "mapped-concept (skos)", SKOS_NS+"closeMatch", SKOS_ROLE_NS+"concept", "concept (skos)", SKOS_ROLE_NS+"mapped-concept", "mapped-concept (skos)", SKOS_NS+"exactMatch", SKOS_ROLE_NS+"concept", "concept (skos)", SKOS_ROLE_NS+"mapped-concept", "mapped-concept (skos)", SKOS_NS+"relatedMatch", SKOS_ROLE_NS+"concept", "concept (skos)", SKOS_ROLE_NS+"mapped-concept", "mapped-concept (skos)", SKOS_NS+"broadMatch", SKOS_ROLE_NS+"concept", "concept (skos)", SKOS_ROLE_NS+"mapped-concept", "mapped-concept (skos)", SKOS_NS+"narrowMatch", SKOS_ROLE_NS+"concept", "concept (skos)", SKOS_ROLE_NS+"mapped-concept", "mapped-concept (skos)", // ****** SKOS XL ***** SKOSXL_NS+"labelRelation", SKOS_ROLE_NS+"label", "label (skos)", SKOS_ROLE_NS+"related-label", "related-label (skos)", }; public String[] getRoleMappings() { return ASSOCIATION_TYPE_TO_ROLES_MAPPING; } public String[] getBasenameMappings() { return SI_BASENAME_MAPPING; } }
6,974
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
FOAFMapping.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/rdf/rdfmappings/FOAFMapping.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * FOAFMapping.java * * Created on 13.2.2009,15:25 */ package org.wandora.application.tools.extractors.rdf.rdfmappings; /** * * @author akivela */ public class FOAFMapping extends RDF2TopicMapsMapping { public static final String FOAF_NS = "http://xmlns.com/foaf/0.1/"; public static final String FOAF_ROLE_NS = "http://wandora.org/si/foaf/role/"; public static final String[] SI_BASENAME_MAPPING = new String[] { FOAF_NS+"Person", "foaf:Person", FOAF_NS+"Organization", "foaf:Organization", FOAF_NS+"Group", "foaf:Group", FOAF_NS+"knows", "foaf:knows", FOAF_NS+"membershipClass", "foaf:membershipClass", FOAF_NS+"member", "foaf:member", FOAF_NS+"homepage", "foaf:homepage", FOAF_NS+"weblog", "foaf:weblog", FOAF_NS+"nick", "foaf:nick", FOAF_NS+"givenname", "foaf:givenname", FOAF_NS+"name", "foaf:name", FOAF_NS+"firstName", "foaf:firstName", FOAF_NS+"surname", "foaf:surname", FOAF_NS+"family_name", "foaf:family_name", FOAF_NS+"gender", "foaf:gender", FOAF_NS+"title", "foaf:title", FOAF_NS+"geekcode", "foaf:geekcode", FOAF_NS+"msnChatID", "foaf:msnChatID", FOAF_NS+"myersBriggs", "foaf:myersBriggs", FOAF_NS+"schoolHomepage", "foaf:schoolHomepage", FOAF_NS+"publications", "foaf:publications", FOAF_NS+"plan", "foaf:plan", FOAF_NS+"phone", "foaf:phone", FOAF_NS+"homepage", "foaf:homepage", FOAF_NS+"holdsAccount", "foaf:holdsAccount", FOAF_NS+"pastProject", "foaf:pastProject", FOAF_NS+"currentProject", "foaf:currentProject", FOAF_NS+"Project", "foaf:Project", FOAF_NS+"page", "foaf:page", FOAF_NS+"birthday", "foaf:birthday", FOAF_NS+"openid", "foaf:openid", FOAF_NS+"jabberID", "foaf:jabberID", FOAF_NS+"aimChatID", "foaf:aimChatID", FOAF_NS+"icqChatID", "foaf:icqChatID", FOAF_NS+"dnaChecksum", "foaf:dnaChecksum", FOAF_NS+"mbox_sha1sum", "foaf:mbox_sha1sum", FOAF_NS+"address_sha1sum", "foaf:address_sha1sum", FOAF_NS+"mbox", "foaf:mbox", FOAF_NS+"PersonalProfileDocument", "foaf:PersonalProfileDocument", FOAF_NS+"maker", "foaf:maker", FOAF_NS+"made", "foaf:made", FOAF_NS+"logo", "foaf:logo", FOAF_NS+"interest", "foaf:interest", FOAF_NS+"img", "foaf:img", FOAF_NS+"Image", "foaf:Image", FOAF_NS+"fundedBy", "foaf:fundedBy", FOAF_NS+"depicts", "foaf:depicts", FOAF_NS+"depiction", "foaf:depiction", FOAF_NS+"based_near", "foaf:based_near", FOAF_NS+"workplaceHomepage", "foaf:workplaceHomepage", FOAF_NS+"accountServiceHomepage", "foaf:accountServiceHomepage", FOAF_NS+"accountName", "foaf:accountName", FOAF_NS+"OnlineGamingAccount", "foaf:OnlineGamingAccount", FOAF_NS+"OnlineEcommerceAccount", "foaf:OnlineEcommerceAccount", FOAF_NS+"OnlineChatAccount", "foaf:OnlineChatAccount", FOAF_NS+"OnlineAccount", "foaf:OnlineAccount", FOAF_NS+"Document", "foaf:Document", FOAF_NS+"Agent", "foaf:Agent", }; public static final String[] ASSOCIATION_TYPE_TO_ROLES_MAPPING = new String[] { FOAF_NS+"knows", FOAF_ROLE_NS+"knows", "knows (foaf)", FOAF_ROLE_NS+"is-known", "is-known (foaf)", FOAF_NS+"member", FOAF_ROLE_NS+"member", "member (foaf)", FOAF_ROLE_NS+"group", "group (foaf)", FOAF_NS+"homepage", FOAF_ROLE_NS+"person", "person (foaf)", FOAF_ROLE_NS+"homepage", "homepage (foaf)", FOAF_NS+"weblog", FOAF_ROLE_NS+"person", "person (foaf)", FOAF_ROLE_NS+"weblog", "weblog (foaf)", FOAF_NS+"nick", FOAF_ROLE_NS+"person", "person (foaf)", FOAF_ROLE_NS+"nick", "nick (foaf)", FOAF_NS+"givenname", FOAF_ROLE_NS+"person", "person (foaf)", FOAF_ROLE_NS+"givenname", "given-name (foaf)", FOAF_NS+"name", FOAF_ROLE_NS+"agent", "agent (foaf)", FOAF_ROLE_NS+"name", "name (foaf)", FOAF_NS+"firstName", FOAF_ROLE_NS+"person", "person (foaf)", FOAF_ROLE_NS+"first_name", "first_name (foaf)", FOAF_NS+"surname", FOAF_ROLE_NS+"person", "person (foaf)", FOAF_ROLE_NS+"surname", "surname (foaf)", FOAF_NS+"family_name", FOAF_ROLE_NS+"person", "person (foaf)", FOAF_ROLE_NS+"family_name", "family_name (foaf)", FOAF_NS+"gender", FOAF_ROLE_NS+"person", "person (foaf)", FOAF_ROLE_NS+"gender", "gender (foaf)", FOAF_NS+"geekcode", FOAF_ROLE_NS+"geekcode-owner", "geekcode-owner (foaf)", FOAF_ROLE_NS+"geekcode", "geekcode (foaf)", FOAF_NS+"msnChatID", FOAF_ROLE_NS+"msnchatid-owner", "msnchatid-owner (foaf)", FOAF_ROLE_NS+"msnchatid", "msnchatid (foaf)", FOAF_NS+"myersBriggs", FOAF_ROLE_NS+"myersbriggs-owner", "myersbriggs-owner (foaf)", FOAF_ROLE_NS+"myersbriggs", "myersbriggs (foaf)", FOAF_NS+"schoolHomepage", FOAF_ROLE_NS+"person", "person (foaf)", FOAF_ROLE_NS+"school homepage", "school homepage (foaf)", FOAF_NS+"workplaceHomepage", FOAF_ROLE_NS+"person", "person (foaf)", FOAF_ROLE_NS+"workplace homepage", "workplace homepage (foaf)", FOAF_NS+"publications", FOAF_ROLE_NS+"person", "person (foaf)", FOAF_ROLE_NS+"publications", "publications (foaf)", FOAF_NS+"plan", FOAF_ROLE_NS+"person", "person (foaf)", FOAF_ROLE_NS+"plan", "plan (foaf)", FOAF_NS+"phone", FOAF_ROLE_NS+"person", "person (foaf)", FOAF_ROLE_NS+"phone", "phone (foaf)", FOAF_NS+"homepage", FOAF_ROLE_NS+"person", "person (foaf)", FOAF_ROLE_NS+"homepage", "homepage (foaf)", FOAF_NS+"holdsAccount", FOAF_ROLE_NS+"person", "person (foaf)", FOAF_ROLE_NS+"holds-account", "holds-account (foaf)", FOAF_NS+"pastProject", FOAF_ROLE_NS+"person", "person (foaf)", FOAF_ROLE_NS+"past-project", "past-project (foaf)", FOAF_NS+"currentProject", FOAF_ROLE_NS+"person", "person (foaf)", FOAF_ROLE_NS+"current-project", "current-project (foaf)", FOAF_NS+"Project", FOAF_ROLE_NS+"person", "person (foaf)", FOAF_ROLE_NS+"project", "project (foaf)", FOAF_NS+"page", FOAF_ROLE_NS+"person", "person (foaf)", FOAF_ROLE_NS+"page", "page (foaf)", FOAF_NS+"birthday", FOAF_ROLE_NS+"person", "person (foaf)", FOAF_ROLE_NS+"birthday", "birthday (foaf)", FOAF_NS+"openid", FOAF_ROLE_NS+"person", "person (foaf)", FOAF_ROLE_NS+"openid", "openid (foaf)", FOAF_NS+"jabberID", FOAF_ROLE_NS+"person", "person (foaf)", FOAF_ROLE_NS+"jabberid", "jabberid (foaf)", FOAF_NS+"aimChatID", FOAF_ROLE_NS+"person", "person (foaf)", FOAF_ROLE_NS+"aimchatid", "aimchatid (foaf)", FOAF_NS+"icqChatID", FOAF_ROLE_NS+"person", "person (foaf)", FOAF_ROLE_NS+"icqchatid", "icqchatid (foaf)", FOAF_NS+"dnaChecksum", FOAF_ROLE_NS+"person", "person (foaf)", FOAF_ROLE_NS+"dna-checksum", "dna-checksum (foaf)", FOAF_NS+"mbox_sha1sum", FOAF_ROLE_NS+"person", "person (foaf)", FOAF_ROLE_NS+"mailbox-uri", "mailbox-uri (foaf)", FOAF_NS+"mbox", FOAF_ROLE_NS+"person", "person (foaf)", FOAF_ROLE_NS+"mbox", "mbox (foaf)", FOAF_NS+"maker", FOAF_ROLE_NS+"person", "person (foaf)", FOAF_ROLE_NS+"maker", "maker (foaf)", FOAF_NS+"made", FOAF_ROLE_NS+"person", "person (foaf)", FOAF_ROLE_NS+"made", "made (foaf)", FOAF_NS+"logo", FOAF_ROLE_NS+"person", "person (foaf)", FOAF_ROLE_NS+"logo", "logo (foaf)", FOAF_NS+"interest", FOAF_ROLE_NS+"person", "person (foaf)", FOAF_ROLE_NS+"interest", "interest (foaf)", FOAF_NS+"img", FOAF_ROLE_NS+"person", "person (foaf)", FOAF_ROLE_NS+"img", "img (foaf)", FOAF_NS+"fundedBy", FOAF_ROLE_NS+"person", "person (foaf)", FOAF_ROLE_NS+"funded-by", "funded-by (foaf)", FOAF_NS+"depicts", FOAF_ROLE_NS+"person", "person (foaf)", FOAF_ROLE_NS+"depicts", "depicts (foaf)", FOAF_NS+"depiction", FOAF_ROLE_NS+"person", "person (foaf)", FOAF_ROLE_NS+"depiction", "depiction (foaf)", FOAF_NS+"based_near", FOAF_ROLE_NS+"person", "person (foaf)", FOAF_ROLE_NS+"based_near", "based_near (foaf)", FOAF_NS+"accountServiceHomepage", FOAF_ROLE_NS+"person", "person (foaf)", FOAF_ROLE_NS+"account-service-homepage", "account-service-homepage (foaf)", FOAF_NS+"accountName", FOAF_ROLE_NS+"person", "person (foaf)", FOAF_ROLE_NS+"account-name", "account-name (foaf)", }; public String[] getRoleMappings() { return ASSOCIATION_TYPE_TO_ROLES_MAPPING; } public String[] getBasenameMappings() { return SI_BASENAME_MAPPING; } }
11,672
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
OpenCYCMapping.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/rdf/rdfmappings/OpenCYCMapping.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * OpenCYCMapping.java */ package org.wandora.application.tools.extractors.rdf.rdfmappings; /** * See http://sw.opencyc.org/ * * @author akivela */ public class OpenCYCMapping extends RDF2TopicMapsMapping { public static final String OPEN_CYC_NS = "http://sw.opencyc.org/2012/05/10/concept/en/"; public static final String[] SI_BASENAME_MAPPING = new String[] { OPEN_CYC_NS+"wikipediaArticleURL", "opencyc:wikipediaArticleURL", OPEN_CYC_NS+"seeAlsoURI", "opencyc:seeAlsoURI", OPEN_CYC_NS+"wikipediaArticleName_Canonical", "opencyc:wikipediaArticleName_Canonical", OPEN_CYC_NS+"facets_Generic", "opencyc:facets_Generic", OPEN_CYC_NS+"quotedIsa", "opencyc:quotedIsa", OPEN_CYC_NS+"superTaxons", "opencyc:superTaxons", OPEN_CYC_NS+"prettyString", "opencyc:prettyString", "http://sw.cyc.com/CycAnnotations_v1#label", "CycAnnotations_v1#label", "http://sw.cyc.com/CycAnnotations_v1#externalID", "CycAnnotations_v1#externalID", }; public static final String[] ASSOCIATION_TYPE_TO_ROLES_MAPPING = new String[] { /* ****** THINK NEXT AS AN EXAMPLE: ASSOCIATION TYPE AND THEN ROLES. RDF_NS+"type", RDF_ROLE_NS+"resource", "resource (rdf)", RDF_ROLE_NS+"class", "class (rdf)", */ }; public String[] getRoleMappings() { return ASSOCIATION_TYPE_TO_ROLES_MAPPING; } public String[] getBasenameMappings() { return SI_BASENAME_MAPPING; } }
2,442
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DublinCoreMapping.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/rdf/rdfmappings/DublinCoreMapping.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * DublinCoreMapping.java * * Created on 13.2.2009,15:25 */ package org.wandora.application.tools.extractors.rdf.rdfmappings; /** * * @author akivela */ public class DublinCoreMapping extends RDF2TopicMapsMapping { public final static String DC_ELEMENTS_NS = "http://purl.org/dc/elements/1.1/"; public final static String DC_TERMS_NS = "http://purl.org/dc/terms/"; public final static String DC_TYPES_NS = "http://purl.org/dc/dcmitype/"; public static final String DC_ROLE_NS = "http://wandora.org/si/dc/role/"; public static final String[] SI_BASENAME_MAPPING = new String[] { DC_ELEMENTS_NS+"title", "dc:title", DC_ELEMENTS_NS+"creator", "dc:creator", DC_ELEMENTS_NS+"subject", "dc:subject", DC_ELEMENTS_NS+"description", "dc:description", DC_ELEMENTS_NS+"publisher", "dc:publisher", DC_ELEMENTS_NS+"contributor", "dc:contributor", DC_ELEMENTS_NS+"date", "dc:date", DC_ELEMENTS_NS+"type", "dc:type", DC_ELEMENTS_NS+"format", "dc:format", DC_ELEMENTS_NS+"identifier", "dc:identifier", DC_ELEMENTS_NS+"source", "dc:source", DC_ELEMENTS_NS+"language", "dc:language", DC_ELEMENTS_NS+"relation", "dc:relation", DC_ELEMENTS_NS+"coverage", "dc:coverage", DC_ELEMENTS_NS+"rights", "dc:rights", // ****** DUBLIN CORE TERM ***** DC_TERMS_NS+"title", "dc-term:title", DC_TERMS_NS+"creator", "dc-term:creator", DC_TERMS_NS+"subject", "dc-term:subject", DC_TERMS_NS+"description", "dc-term:description", DC_TERMS_NS+"publisher", "dc-term:publisher", DC_TERMS_NS+"contributor", "dc-term:contributor", DC_TERMS_NS+"date", "dc-term:date", DC_TERMS_NS+"type", "dc-term:type", DC_TERMS_NS+"format", "dc-term:format", DC_TERMS_NS+"identifier", "dc-term:identifier", DC_TERMS_NS+"source", "dc-term:source", DC_TERMS_NS+"language", "dc-term:language", DC_TERMS_NS+"relation", "dc-term:relation", DC_TERMS_NS+"coverage", "dc-term:coverage", DC_TERMS_NS+"audience", "dc-term:audience", DC_TERMS_NS+"alternative", "dc-term:alternative", DC_TERMS_NS+"tableOfContents", "dc-term:table of contents", DC_TERMS_NS+"abstract", "dc-term:abstract", DC_TERMS_NS+"created", "dc-term:date created", DC_TERMS_NS+"valid", "dc-term:date valid", DC_TERMS_NS+"available", "dc-term:date available", DC_TERMS_NS+"issued", "dc-term:date issued", DC_TERMS_NS+"modified", "dc-term:date modified", DC_TERMS_NS+"extent", "dc-term:extent", DC_TERMS_NS+"medium", "dc-term:medium", DC_TERMS_NS+"isVersionOf", "dc-term:is version of", DC_TERMS_NS+"hasVersion", "dc-term:has version", DC_TERMS_NS+"isReplacedBy", "dc-term:is replaced by", DC_TERMS_NS+"replaces", "dc-term:replaces", DC_TERMS_NS+"isRequiredBy", "dc-term:is required by", DC_TERMS_NS+"requires", "dc-term:requires", DC_TERMS_NS+"isPartOf", "dc-term:is part of", DC_TERMS_NS+"hasPart", "dc-term:has part", DC_TERMS_NS+"isReferencedBy", "dc-term:is referenced by", DC_TERMS_NS+"references", "dc-term:references", DC_TERMS_NS+"isFormatOf", "dc-term:isFormatOf", DC_TERMS_NS+"hasFormat", "dc-term:hasFormat", DC_TERMS_NS+"conformsTo", "dc-term:conformsTo", DC_TERMS_NS+"spatial", "dc-term:spatial", DC_TERMS_NS+"temporal", "dc-term:temporal", DC_TERMS_NS+"mediator", "dc-term:mediator", DC_TERMS_NS+"dateAccepted", "dc-term:dateAccepted", DC_TERMS_NS+"dateCopyrighted", "dc-term:dateCopyrighted", DC_TERMS_NS+"dateSubmitted", "dc-term:dateSubmitted", DC_TERMS_NS+"educationLevel", "dc-term:educationLevel", DC_TERMS_NS+"accessRights", "dc-term:accessRights", DC_TERMS_NS+"bibliographicCitation", "dc-term:bibliographicCitation", DC_TERMS_NS+"license", "dc-term:license", DC_TERMS_NS+"rightsHolder", "dc-term:rightsHolder", DC_TERMS_NS+"provenance", "dc-term:provenance", DC_TERMS_NS+"instructionalMethod", "dc-term:instructionalMethod", DC_TERMS_NS+"accrualMethod", "dc-term:accrualMethod", DC_TERMS_NS+"accrualPeriodicity", "dc-term:accrualPeriodicity", DC_TERMS_NS+"accrualPolicy", "dc-term:accrualPolicy", DC_TERMS_NS+"Agent", "dc-term:Agent", DC_TERMS_NS+"AgentClass", "dc-term:AgentClass", DC_TERMS_NS+"BibliographicResource", "dc-term:BibliographicResource", DC_TERMS_NS+"FileFormat", "dc-term:FileFormat", DC_TERMS_NS+"Frequency", "dc-term:Frequency", DC_TERMS_NS+"Jurisdiction", "dc-term:Jurisdiction", DC_TERMS_NS+"LicenseDocument", "dc-term:LicenseDocument", DC_TERMS_NS+"LinguisticSystem", "dc-term:LinguisticSystem", DC_TERMS_NS+"Location", "dc-term:Location", DC_TERMS_NS+"LocationPeriodOrJurisdiction", "dc-term:LocationPeriodOrJurisdiction", DC_TERMS_NS+"MediaType", "dc-term:MediaType", DC_TERMS_NS+"MediaTypeOrExtent", "dc-term:MediaTypeOrExtent", DC_TERMS_NS+"MethodOfInstruction", "dc-term:MethodOfInstruction", DC_TERMS_NS+"MethodOfAccrual", "dc-term:MethodOfAccrual", DC_TERMS_NS+"PeriodOfTime", "dc-term:PeriodOfTime", DC_TERMS_NS+"PhysicalMedium", "dc-term:PhysicalMedium", DC_TERMS_NS+"PhysicalResource", "dc-term:PhysicalResource", DC_TERMS_NS+"Policy", "dc-term:Policy", DC_TERMS_NS+"ProvenanceStatement", "dc-term:ProvenanceStatement", DC_TERMS_NS+"RightsStatement", "dc-term:RightsStatement", DC_TERMS_NS+"SizeOrDuration", "dc-term:SizeOrDuration", DC_TERMS_NS+"Standard", "dc-term:Standard", DC_TERMS_NS+"ISO639-2", "dc-term:ISO639-2", DC_TERMS_NS+"RFC1766", "dc-term:RFC1766", DC_TERMS_NS+"URI", "dc-term:URI", DC_TERMS_NS+"Point", "dc-term:Point", DC_TERMS_NS+"ISO3166", "dc-term:ISO3166", DC_TERMS_NS+"Box", "dc-term:Box", DC_TERMS_NS+"Period", "dc-term:Period", DC_TERMS_NS+"W3CDTF", "dc-term:W3CDTF", DC_TERMS_NS+"RFC3066", "dc-term:RFC3066", DC_TERMS_NS+"RFC4646", "dc-term:RFC4646", DC_TERMS_NS+"ISO639-3", "dc-term:ISO639-3", DC_TERMS_NS+"LCSH", "dc-term:LCSH", DC_TERMS_NS+"MESH", "dc-term:MESH", DC_TERMS_NS+"DDC", "dc-term:DDC", DC_TERMS_NS+"LCC", "dc-term:LCC", DC_TERMS_NS+"UDC", "dc-term:UDC", DC_TERMS_NS+"DCMIType", "dc-term:DCMIType", DC_TERMS_NS+"IMT", "dc-term:IMT", DC_TERMS_NS+"TGN", "dc-term:Getty Thesaurus of Geographic Names", DC_TERMS_NS+"NLM", "dc-term:National Library of Medicine Classification", /* DC Types */ DC_TYPES_NS+"Collection", "dctypes:Collection", DC_TYPES_NS+"Dataset", "dctypes:Dataset", DC_TYPES_NS+"Event", "dctypes:Event", DC_TYPES_NS+"Image", "dctypes:Image", DC_TYPES_NS+"InteractiveResource", "dctypes:InteractiveResource", DC_TYPES_NS+"MovingImage", "dctypes:MovingImage", DC_TYPES_NS+"PhysicalObject", "dctypes:PhysicalObject", DC_TYPES_NS+"Service", "dctypes:Service", DC_TYPES_NS+"Software", "dctypes:Software", DC_TYPES_NS+"Sound", "dctypes:Sound", DC_TYPES_NS+"StillImage", "dctypes:StillImage", DC_TYPES_NS+"Text", "dctypes:Text", }; public static final String[] ASSOCIATION_TYPE_TO_ROLES_MAPPING = new String[] { }; public String[] getRoleMappings() { return ASSOCIATION_TYPE_TO_ROLES_MAPPING; } public String[] getBasenameMappings() { return SI_BASENAME_MAPPING; } }
10,075
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
OAMapping.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/rdf/rdfmappings/OAMapping.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.rdf.rdfmappings; /** * * @author olli */ public class OAMapping extends RDF2TopicMapsMapping{ public static final String OA_NS = "http://www.w3.org/ns/oa#"; public static final String RDF_NS = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; public static final String[] SI_BASENAME_MAPPING = new String[] { // CLASSES OA_NS+"Annotation", "oa:Annotation", OA_NS+"Choice", "oa:Choice", OA_NS+"Composite", "oa:Composite", OA_NS+"CssStyle", "oa:CssStyle", OA_NS+"DataPositionSelector", "oa:DataPositionSelector", OA_NS+"FragmentSelector", "oa:FragmentSelector", OA_NS+"HttpRequestState", "oa:HttpRequestState", OA_NS+"List", "oa:List", OA_NS+"Motivation", "oa:Motivation", OA_NS+"Selector", "oa:Selector", OA_NS+"SemanticTag", "oa:SemanticTag", OA_NS+"SpecificResource", "oa:SpecificResource", OA_NS+"State", "oa:State", OA_NS+"Style", "oa:Style", OA_NS+"SvgSelector", "oa:SvgSelector", OA_NS+"Tag", "oa:Tag", OA_NS+"TextPositionSelector", "oa:TextPositionSelector", OA_NS+"TextQuoteSelector", "oa:TextQuoteSelector", OA_NS+"TimeState", "oa:TimeState", // ObjectProperties OA_NS+"annotatedBy", "oa:annotatedBy", OA_NS+"cachedSource", "oa:cachedSource", OA_NS+"default", "oa:default", OA_NS+"equivalentTo", "oa:equivalentTo", OA_NS+"hasBody", "oa:hasBody", OA_NS+"hasScope", "oa:hasScope", OA_NS+"hasSelector", "oa:hasSelector", OA_NS+"hasSource", "oa:hasSource", OA_NS+"hasState", "oa:hasState", OA_NS+"hasTarget", "oa:hasTarget", OA_NS+"item", "oa:item", OA_NS+"motivatedBy", "oa:motivatedBy", OA_NS+"serializedBy", "oa:serializedBy", OA_NS+"styledBy", "oa:styledBy", // DatatypeProperties OA_NS+"annotatedAt", "oa:annotatedAt", OA_NS+"end", "oa:end", OA_NS+"exact", "oa:exact", OA_NS+"prefix", "oa:prefix", OA_NS+"serializedAt", "oa:serializedAt", OA_NS+"start", "oa:start", OA_NS+"styleClass", "oa:styleClass", OA_NS+"suffix", "oa:suffix", OA_NS+"when", "oa:when", }; public static final String[] ASSOCIATION_TYPE_TO_ROLES_MAPPING = new String[] { OA_NS+"annotatedBy", OA_NS+"Annotation",null, RDF_NS+"object", "Object", OA_NS+"cachedSource", OA_NS+"TimeState",null, RDF_NS+"object", "Object", OA_NS+"default", OA_NS+"Choice",null, RDF_NS+"object", "Object", OA_NS+"equivalentTo", RDF_NS+"subject", "Subject", RDF_NS+"object", "Object", OA_NS+"hasBody", OA_NS+"Annotation",null, RDF_NS+"object", "Object", OA_NS+"hasScope", OA_NS+"SpecificResource",null, RDF_NS+"object", "Object", OA_NS+"hasSelector", OA_NS+"SpecificResource",null, OA_NS+"Selector",null, OA_NS+"hasSource", OA_NS+"SpecificResource",null, RDF_NS+"object", "Object", OA_NS+"hasState", OA_NS+"SpecificResource",null, OA_NS+"State",null, OA_NS+"hasTarget", OA_NS+"Annotation",null, RDF_NS+"object", "Object", OA_NS+"item", RDF_NS+"object", "Subject", RDF_NS+"object", "Object", OA_NS+"motivatedBy", OA_NS+"Annotation",null, OA_NS+"Motivation",null, OA_NS+"serializedBy", OA_NS+"Annotation",null, RDF_NS+"object", "Object", OA_NS+"styledBy", OA_NS+"Annotation",null, OA_NS+"Style",null, }; public String[] getRoleMappings() { return ASSOCIATION_TYPE_TO_ROLES_MAPPING; } public String[] getBasenameMappings() { return SI_BASENAME_MAPPING; } }
5,468
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SCMapping.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/rdf/rdfmappings/SCMapping.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.rdf.rdfmappings; /** * * @author olli */ public class SCMapping extends RDF2TopicMapsMapping{ public static final String SC_NS = "http://www.shared-canvas.org/ns/"; public static final String RDF_NS = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; public static final String[] SI_BASENAME_MAPPING = new String[] { SC_NS+"hasRelatedService", "sc:hasRelatedService", SC_NS+"hasRelatedDescription", "sc:hasRelatedDescription", SC_NS+"hasSequences", "sc:hasSequences", SC_NS+"hasCanvases", "sc:hasCanvases", SC_NS+"hasAnnotations", "sc:hasAnnotations", SC_NS+"hasImageAnnotations", "sc:hasImageAnnotations", SC_NS+"hasLists", "sc:hasLists", SC_NS+"hasRanges", "sc:hasRanges", SC_NS+"metadataLabels", "sc:metadataLabels", SC_NS+"attributionLabel", "sc:attributionLabel", SC_NS+"viewingDirection", "sc:viewingDirection", SC_NS+"viewingHint", "sc:viewingHint", SC_NS+"Manifest", "sc:Manifest", SC_NS+"Sequence", "sc:Sequence", SC_NS+"Canvas", "sc:Canvas", SC_NS+"painting", // This not capitalised "sc:painting", }; public static final String[] ASSOCIATION_TYPE_TO_ROLES_MAPPING = new String[] { SC_NS+"hasSequences", SC_NS+"Manifest", null, SC_NS+"Sequence", null, SC_NS+"hasCanvases", SC_NS+"Sequence", null, SC_NS+"Canvas", null, SC_NS+"hasImageAnnotations", SC_NS+"Canvas", null, OAMapping.OA_NS+"Annotation", null, SC_NS+"hasRelatedService", RDF_NS+"subject", "Subject", RDF_NS+"object", "Object", }; public String[] getRoleMappings() { return ASSOCIATION_TYPE_TO_ROLES_MAPPING; } public String[] getBasenameMappings() { return SI_BASENAME_MAPPING; } }
3,017
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TwineMapping.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/rdf/rdfmappings/TwineMapping.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * RSSMapping.java * * Created on 13.2.2009,15:25 */ package org.wandora.application.tools.extractors.rdf.rdfmappings; /** * * @author akivela */ public class TwineMapping extends RDF2TopicMapsMapping { public static final String TWINE_BASIC_NS = "http://www.radarnetworks.com/2007/09/12/basic#"; public static final String TWINE_RADAR_NS = "http://www.radarnetworks.com/core#"; public static final String TWINE_APP_NS = "http://www.radarnetworks.com/shazam#"; public static final String TWINE_WEB_NS = "http://www.radarnetworks.com/web#"; public static final String TWINE_DI_NS = "http://www.radarnetworks.com/data-intelligence#"; public static final String TWINE_ENRICHMENT_NS = "http://www.radarnetworks.com/enrichment#"; public static final String TWINE_ROLE_NS = "http://wandora.org/si/twine/role/"; public static final String[] SI_BASENAME_MAPPING = new String[] { TWINE_BASIC_NS+"url", "twine:url", TWINE_BASIC_NS+"description", "twine:description", TWINE_BASIC_NS+"tag", "twine:tag", TWINE_BASIC_NS+"Bookmark", "twine:Bookmark", TWINE_BASIC_NS+"isTopicOf", "twine:isTopicOf", TWINE_BASIC_NS+"isAbout", "twine:isAbout", TWINE_BASIC_NS+"author", "twine:author", TWINE_BASIC_NS+"manufacturer", "twine:manufacturer", TWINE_RADAR_NS+"createdDate", "twine:createdDate", TWINE_RADAR_NS+"lastModifiedDate", "twine:lastModifiedDate", TWINE_RADAR_NS+"wasCreatedBy", "twine:wasCreatedBy", TWINE_RADAR_NS+"isContainedIn", "twine:isContainedIn", TWINE_RADAR_NS+"key"+ "twine:key", TWINE_RADAR_NS+"contains"+ "twine:contains", TWINE_APP_NS+"commentCount", "twine:commentCount", TWINE_APP_NS+"wasCreatedInSpot", "twine:wasCreatedInSpot", TWINE_APP_NS+"Post", "twine:Post", TWINE_APP_NS+"Spot", "twine:Spot", TWINE_APP_NS+"spotType", "twine:spotType", TWINE_APP_NS+"openMembership", "twine:openMembership", TWINE_APP_NS+"membersInvitingMembers", "twine:membersInvitingMembers", TWINE_APP_NS+"indirectlyContains", "twine:indirectlyContains", TWINE_APP_NS+"itemCount", "twine:itemCount", TWINE_APP_NS+"allowsComments", "twine:allowsComments", TWINE_WEB_NS+"views", "twine:views", TWINE_ENRICHMENT_NS+"language", "twine:language", TWINE_ENRICHMENT_NS+"enrichmentVersion", "twine:enrichmentVersion", TWINE_ENRICHMENT_NS+"convertedBinaryContent", "twine:convertedBinaryContent", TWINE_DI_NS+"annotationPositionalData", "twine:annotationPositionalData", TWINE_DI_NS+"isAboutTopic", "twine:isAboutTopic", TWINE_DI_NS+"hasAnnotation", "twine:hasAnnotation", }; public static final String[] ASSOCIATION_TYPE_TO_ROLES_MAPPING = new String[] { TWINE_BASIC_NS+"tag", TWINE_ROLE_NS+"object", "object (twine)", TWINE_ROLE_NS+"tag", "tag (twine)", TWINE_BASIC_NS+"isTopicOf", TWINE_ROLE_NS+"topic", "topic (twine)", TWINE_ROLE_NS+"object", "object (twine)", TWINE_BASIC_NS+"isAbout", TWINE_ROLE_NS+"object", "object (twine)", TWINE_ROLE_NS+"target", "target (twine)", TWINE_BASIC_NS+"author", TWINE_ROLE_NS+"author", "author (twine)", TWINE_ROLE_NS+"object", "object (twine)", TWINE_BASIC_NS+"manufacturer", TWINE_ROLE_NS+"manufacturer", "manufacturer (twine)", TWINE_ROLE_NS+"object", "object (twine)", TWINE_RADAR_NS+"wasCreatedBy", TWINE_ROLE_NS+"object", "object (twine)", TWINE_ROLE_NS+"creator", "creator (twine)", TWINE_RADAR_NS+"isContainedIn", TWINE_ROLE_NS+"member", "member (twine)", TWINE_ROLE_NS+"group", "group (twine)", TWINE_RADAR_NS+"contains"+ TWINE_ROLE_NS+"group", "group (twine)", TWINE_ROLE_NS+"member", "member (twine)", TWINE_APP_NS+"wasCreatedInSpot", TWINE_ROLE_NS+"object", "object (twine)", TWINE_ROLE_NS+"spot", "spot (twine)", TWINE_APP_NS+"spotType", TWINE_ROLE_NS+"spot", "spot (twine)", TWINE_ROLE_NS+"spot-type", "spot-type (twine)", TWINE_APP_NS+"indirectlyContains", TWINE_ROLE_NS+"group", "group (twine)", TWINE_ROLE_NS+"member", "member (twine)", TWINE_DI_NS+"isAboutTopic", TWINE_ROLE_NS+"object", "object (twine)", TWINE_ROLE_NS+"topic", "topic (twine)", TWINE_DI_NS+"hasAnnotation", TWINE_ROLE_NS+"object", "object (twine)", TWINE_ROLE_NS+"annotation", "annotation (twine)", }; public String[] getRoleMappings() { return ASSOCIATION_TYPE_TO_ROLES_MAPPING; } public String[] getBasenameMappings() { return SI_BASENAME_MAPPING; } }
6,316
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
RSSMapping.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/rdf/rdfmappings/RSSMapping.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * RSSMapping.java * * Created on 13.2.2009,15:25 */ package org.wandora.application.tools.extractors.rdf.rdfmappings; /** * * @author akivela */ public class RSSMapping extends RDF2TopicMapsMapping { public static final String RSS_NS = "http://purl.org/rss/1.0/"; public static final String RSS_SYNDICATION_NS = "http://purl.org/rss/1.0/modules/syndication/"; public static final String RSS_COMPANY_NS = "http://purl.org/rss/1.0/modules/company/"; public static final String RSS_TEXTINPUT_NS = "http://purl.org/rss/1.0/modules/textinput/"; public static final String RSS_CONTENT_NS = "http://purl.org/rss/1.0/modules/content/"; public static final String RSS_ROLE_NS = "http://wandora.org/si/rss/role/"; public static final String[] SI_BASENAME_MAPPING = new String[] { RSS_NS+"channel", "rss:channel", RSS_NS+"title", "rss:title", RSS_NS+"link", "rss:link", RSS_NS+"description", "rss:description", RSS_NS+"image", "rss:image", RSS_NS+"items", "rss:items", RSS_NS+"textinput", "rss:textinput", RSS_NS+"url", "rss:url", RSS_NS+"item", "rss:item", RSS_NS+"name", "rss:name", RSS_SYNDICATION_NS+"updatePeriod", "rss_syndication:updatePeriod", RSS_SYNDICATION_NS+"updateFrequency", "rss_syndication:updateFrequency", RSS_SYNDICATION_NS+"updateBase", "rss_syndication:updateBase", RSS_COMPANY_NS+"name", "rss_company:name", RSS_COMPANY_NS+"market", "rss_company:market", RSS_COMPANY_NS+"symbol", "rss_company:symbol", RSS_TEXTINPUT_NS+"function", "rss_textinput:function", RSS_TEXTINPUT_NS+"inputType", "rss_textinput:inputType", RSS_CONTENT_NS+"encoded", "rss_content:encoded", RSS_CONTENT_NS+"items", "rss_content:items", RSS_CONTENT_NS+"item", "rss_content:item", RSS_CONTENT_NS+"format", "rss_content:format", }; public static final String[] ASSOCIATION_TYPE_TO_ROLES_MAPPING = new String[] { RSS_NS+"title", RSS_ROLE_NS+"titled", "titled (rss)", RSS_ROLE_NS+"title", "title (rss)", RSS_NS+"link", RSS_ROLE_NS+"linked", "linked (rss)", RSS_ROLE_NS+"link", "link (rss)", RSS_NS+"image", RSS_ROLE_NS+"imaged", "imaged (rss)", RSS_ROLE_NS+"image", "image (rss)", RSS_NS+"items", RSS_ROLE_NS+"channel", "channel (rss)", RSS_ROLE_NS+"item-list", "item-list (rss)", RSS_NS+"textinput", RSS_ROLE_NS+"channel", "channel (rss)", RSS_ROLE_NS+"textinput", "textinput (rss)", RSS_NS+"item", RSS_ROLE_NS+"item-container", "item-container (rss)", RSS_ROLE_NS+"item", "item (rss)", }; public String[] getRoleMappings() { return ASSOCIATION_TYPE_TO_ROLES_MAPPING; } public String[] getBasenameMappings() { return SI_BASENAME_MAPPING; } }
4,214
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
RDFMapping.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/rdf/rdfmappings/RDFMapping.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * RDFMapping.java * * Created on 13.2.2009,15:25 */ package org.wandora.application.tools.extractors.rdf.rdfmappings; /** * * @author akivela */ public class RDFMapping extends RDF2TopicMapsMapping { public static final String RDF_NS = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; public static final String RDF_ROLE_NS = "http://wandora.org/si/rdf/role/"; public static final String[] SI_BASENAME_MAPPING = new String[] { RDF_NS+"type", "rdf:type", RDF_NS+"Property", "rdf:Property", RDF_NS+"Statement", "rdf:Statement", RDF_NS+"subject", "rdf:subject", RDF_NS+"predicate", "rdf:predicate", RDF_NS+"object", "rdf:object", RDF_NS+"Bag", "rdf:Bag", RDF_NS+"Seq", "rdf:Seq", RDF_NS+"Alt", "rdf:Alt", RDF_NS+"value", "rdf:value", RDF_NS+"List", "rdf:List", RDF_NS+"nil", "rdf:nil", RDF_NS+"first", "rdf:first", RDF_NS+"rest", "rdf:rest", RDF_NS+"XMLLiteral", "rdf:XMLLiteral", }; public static final String[] ASSOCIATION_TYPE_TO_ROLES_MAPPING = new String[] { RDF_NS+"type", RDF_ROLE_NS+"resource", "resource (rdf)", RDF_ROLE_NS+"class", "class (rdf)", RDF_NS+"subject", RDF_ROLE_NS+"statement", "statement (rdf)", RDF_ROLE_NS+"resource", "resource (rdf)", RDF_NS+"predicate", RDF_ROLE_NS+"statement", "statement (rdf)", RDF_ROLE_NS+"resource", "resource (rdf)", RDF_NS+"object", RDF_ROLE_NS+"statement", "statement (rdf)", RDF_ROLE_NS+"resource", "resource (rdf)", RDF_NS+"value", RDF_ROLE_NS+"resource", "resource (rdf)", RDF_ROLE_NS+"other-resource", "other-resource (rdf)", RDF_NS+"first", RDF_ROLE_NS+"list", "list (rdf)", RDF_ROLE_NS+"resource", "resource (rdf)", RDF_NS+"rest", RDF_ROLE_NS+"list", "list (rdf)", RDF_ROLE_NS+"rest-of-list", "rest-of-list (rdf)", }; public String[] getRoleMappings() { return ASSOCIATION_TYPE_TO_ROLES_MAPPING; } public String[] getBasenameMappings() { return SI_BASENAME_MAPPING; } }
3,300
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
RDFSMapping.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/rdf/rdfmappings/RDFSMapping.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * RDFSMapping.java * * Created on 13.2.2009,15:25 */ package org.wandora.application.tools.extractors.rdf.rdfmappings; /** * * @author akivela */ public class RDFSMapping extends RDF2TopicMapsMapping { public static final String RDFS_NS = "http://www.w3.org/2000/01/rdf-schema#"; public static final String RDFS_ROLE_NS = "http://wandora.org/si/rdfs/role/"; public static final String[] SI_BASENAME_MAPPING = new String[] { RDFS_NS+"Resource", "rdfs:Resource", RDFS_NS+"Class", "rdfs:Class", RDFS_NS+"subClassOf", "rdfs:subClassOf", RDFS_NS+"subPropertyOf", "rdfs:subPropertyOf", RDFS_NS+"comment", "rdfs:comment", RDFS_NS+"Property", "rdfs:Property", RDFS_NS+"label", "rdfs:label", RDFS_NS+"domain", "rdfs:domain", RDFS_NS+"range", "rdfs:range", RDFS_NS+"seeAlso", "rdfs:seeAlso", RDFS_NS+"isDefinedBy", "rdfs:isDefinedBy", RDFS_NS+"Literal", "rdfs:Literal", RDFS_NS+"Container", "rdfs:Container", RDFS_NS+"ContainerMembershipProperty", "rdfs:ContainerMembershipProperty", RDFS_NS+"member", "rdfs:member", RDFS_NS+"Datatype", "rdfs:Datatype", RDFS_NS+"Datatype", "rdfs:Datatype", }; public static final String[] ASSOCIATION_TYPE_TO_ROLES_MAPPING = new String[] { RDFS_NS+"subClassOf", RDFS_ROLE_NS+"subclass", "subclass (rdfs)", RDFS_ROLE_NS+"class", "class (rdfs)", RDFS_NS+"subPropertyOf", RDFS_ROLE_NS+"subproperty", "subproperty (rdfs)", RDFS_ROLE_NS+"property", "property (rdfs)", RDFS_NS+"domain", RDFS_ROLE_NS+"property", "property (rdfs)", RDFS_ROLE_NS+"domain", "domain (rdfs)", RDFS_NS+"range", RDFS_ROLE_NS+"property", "property (rdfs)", RDFS_ROLE_NS+"range", "range (rdfs)", RDFS_NS+"seeAlso", RDFS_ROLE_NS+"resource", "resource (rdfs)", RDFS_ROLE_NS+"other-resource", "other-resource (rdfs)", RDFS_NS+"isDefinedBy", RDFS_ROLE_NS+"defined-resource", "defined-resource (rdfs)", RDFS_ROLE_NS+"definer-resource", "definer-resource (rdfs)", RDFS_NS+"member", RDFS_ROLE_NS+"member-resource", "member-resource (rdfs)", RDFS_ROLE_NS+"group-resource", "group-resource (rdfs)", }; public String[] getRoleMappings() { return ASSOCIATION_TYPE_TO_ROLES_MAPPING; } public String[] getBasenameMappings() { return SI_BASENAME_MAPPING; } }
3,672
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
OWLMapping.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/rdf/rdfmappings/OWLMapping.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * OWLMapping.java * * Created on 13.2.2009,15:25 */ package org.wandora.application.tools.extractors.rdf.rdfmappings; /** * * @author akivela */ public class OWLMapping extends RDF2TopicMapsMapping { public static final String OWL_NS = "http://www.w3.org/2002/07/owl#"; public static final String OWL_ROLE_NS = "http://wandora.org/si/owl/role/"; public static final String[] SI_BASENAME_MAPPING = new String[] { OWL_NS+"AllDifferent", "owl:AllDifferent", OWL_NS+"allValuesFrom", "owl:allValuesFrom", OWL_NS+"AnnotationProperty", "owl:AnnotationProperty", OWL_NS+"backwardCompatibleWith", "owl:backwardCompatibleWith", OWL_NS+"cardinality", "owl:cardinality", OWL_NS+"Class", "owl:Class", OWL_NS+"complementOf", "owl:complementOf", OWL_NS+"DataRange", "owl:DataRange", OWL_NS+"DatatypeProperty", "owl:DatatypeProperty", OWL_NS+"DeprecatedClass", "owl:DeprecatedClass", OWL_NS+"DeprecatedProperty", "owl:DeprecatedProperty", OWL_NS+"differentFrom", "owl:differentFrom", OWL_NS+"disjointWith", "owl:disjointWith", OWL_NS+"distinctMembers", "owl:distinctMembers", OWL_NS+"equivalentClass", "owl:equivalentClass", OWL_NS+"equivalentProperty", "owl:equivalentProperty", OWL_NS+"FunctionalProperty", "owl:FunctionalProperty", OWL_NS+"hasValue", "owl:hasValue", OWL_NS+"imports", "owl:imports", OWL_NS+"incompatibleWith", "owl:incompatibleWith", OWL_NS+"intersectionOf", "owl:intersectionOf", OWL_NS+"InverseFunctionalProperty", "owl:InverseFunctionalProperty", OWL_NS+"inverseOf", "owl:inverseOf", OWL_NS+"maxCardinality", "owl:maxCardinality", OWL_NS+"minCardinality", "owl:minCardinality", OWL_NS+"Nothing", "owl:Nothing", OWL_NS+"ObjectProperty", "owl:ObjectProperty", OWL_NS+"oneOf", "owl:oneOf", OWL_NS+"onProperty", "owl:onProperty", OWL_NS+"Ontology", "owl:Ontology", OWL_NS+"OntologyProperty", "owl:OntologyProperty", OWL_NS+"priorVersion", "owl:priorVersion", OWL_NS+"Restriction", "owl:Restriction", OWL_NS+"sameAs", "owl:sameAs", OWL_NS+"someValuesFrom", "owl:someValuesFrom", OWL_NS+"SymmetricProperty", "owl:SymmetricProperty", OWL_NS+"Thing", "owl:Thing", OWL_NS+"TransitiveProperty", "owl:TransitiveProperty", OWL_NS+"unionOf", "owl:unionOf", OWL_NS+"versionInfo", "owl:versionInfo", }; public static final String[] ASSOCIATION_TYPE_TO_ROLES_MAPPING = new String[] { OWL_NS+"allValuesFrom", OWL_ROLE_NS+"restriction", "restriction (owl)", OWL_ROLE_NS+"class", "class (owl)", OWL_NS+"backwardCompatibleWith", OWL_ROLE_NS+"ontology", "ontology (owl)", OWL_ROLE_NS+"compatible-ontology", "compatible-ontology (owl)", OWL_NS+"complementOf", OWL_ROLE_NS+"class", "class (owl)", OWL_ROLE_NS+"complement-class", "complement-class (owl)", OWL_NS+"differentFrom", OWL_ROLE_NS+"thing", "thing (owl)", OWL_ROLE_NS+"different-thing", "different-thing (owl)", OWL_NS+"disjointWith", OWL_ROLE_NS+"class", "class (owl)", OWL_ROLE_NS+"disjoint-class", "disjoint-class (owl)", OWL_NS+"distinctMembers", OWL_ROLE_NS+"group", "group (owl)", OWL_ROLE_NS+"distinct-group", "distinct-group (owl)", OWL_NS+"equivalentClass", OWL_ROLE_NS+"class", "class (owl)", OWL_ROLE_NS+"equivalent-class", "equivalent-class (owl)", OWL_NS+"equivalentProperty", OWL_ROLE_NS+"property", "property (owl)", OWL_ROLE_NS+"equivalent-property", "equivalent-property (owl)", OWL_NS+"imports", OWL_ROLE_NS+"ontology", "ontology (owl)", OWL_ROLE_NS+"imported-ontology", "imported-ontology (owl)", OWL_NS+"incompatibleWith", OWL_ROLE_NS+"ontology", "ontology (owl)", OWL_ROLE_NS+"incompatible-ontology", "incompatible-ontology (owl)", OWL_NS+"intersectionOf", OWL_ROLE_NS+"class", "class (owl)", OWL_ROLE_NS+"list", "list (owl)", OWL_NS+"inverseOf", OWL_ROLE_NS+"property", "property (owl)", OWL_ROLE_NS+"inverse-property", "inverse-property (owl)", OWL_NS+"oneOf", OWL_ROLE_NS+"class", "class (owl)", OWL_ROLE_NS+"list", "list (owl)", OWL_NS+"onProperty", OWL_ROLE_NS+"restriction", "restriction (owl)", OWL_ROLE_NS+"property", "property (owl)", OWL_NS+"priorVersion", OWL_ROLE_NS+"ontology", "ontology (owl)", OWL_ROLE_NS+"prior-version-ontology", "prior-version-ontology (owl)", OWL_NS+"sameAs", OWL_ROLE_NS+"thing", "thing (owl)", OWL_ROLE_NS+"same-as-thing", "same-as-thing (owl)", OWL_NS+"someValuesFrom", OWL_ROLE_NS+"restriction", "restriction (owl)", OWL_ROLE_NS+"class", "class (owl)", OWL_NS+"unionOf", OWL_ROLE_NS+"class", "class (owl)", OWL_ROLE_NS+"list", "list (owl)", }; public String[] getRoleMappings() { return ASSOCIATION_TYPE_TO_ROLES_MAPPING; } public String[] getBasenameMappings() { return SI_BASENAME_MAPPING; } }
6,774
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
CreativeCommonsMapping.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/rdf/rdfmappings/CreativeCommonsMapping.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * CreativeCommonsMapping.java * * Created on 7.10.2009,12:02 */ package org.wandora.application.tools.extractors.rdf.rdfmappings; /** * * @author akivela */ public class CreativeCommonsMapping extends RDF2TopicMapsMapping { public static final String CC_NS = "http://creativecommons.org/ns#"; public static final String CC_ROLE_NS = "http://wandora.org/si/cc/role/"; public static final String[] SI_BASENAME_MAPPING = new String[] { CC_NS+"Work", "cc:Work", CC_NS+"License", "cc:License", CC_NS+"Jurisdiction", "cc:Jurisdiction", CC_NS+"Permission", "cc:Permission", CC_NS+"Requirement", "cc:Requirement", CC_NS+"Prohibition", "cc:Prohibition", CC_NS+"Reproduction", "cc:Reproduction", CC_NS+"Distribution", "cc:Distribution", CC_NS+"DerivativeWorks", "cc:DerivativeWorks", CC_NS+"HighIncomeNationUse", "cc:HighIncomeNationUse", CC_NS+"Sharing", "cc:Sharing", CC_NS+"Notice", "cc:Notice", CC_NS+"Attribution", "cc:Attribution", CC_NS+"ShareAlike", "cc:ShareAlike", CC_NS+"SourceCode", "cc:SourceCode", CC_NS+"Copyleft", "cc:Copyleft", CC_NS+"LesserCopyleft", "cc:LesserCopyleft", CC_NS+"CommercialUse", "cc:CommercialUse", CC_NS+"permits", "cc:permits", CC_NS+"requires", "cc:requires", CC_NS+"prohibits", "cc:prohibits", CC_NS+"jurisdiction", "cc:jurisdiction", CC_NS+"legalcode", "cc:legalcode", CC_NS+"deprecatedOn", "cc:deprecatedOn", CC_NS+"license", "cc:license", CC_NS+"morePermissions", "cc:morePermissions", CC_NS+"attributionName", "cc:attributionName", CC_NS+"attributionURL", "cc:attributionURL", }; public static final String[] ASSOCIATION_TYPE_TO_ROLES_MAPPING = new String[] { CC_NS+"prohibits", CC_ROLE_NS+"license", "license (cc)", CC_ROLE_NS+"prohibition", "prohibition (cc)", CC_NS+"requires", CC_ROLE_NS+"license", "license (cc)", CC_ROLE_NS+"requirement", "requirement (cc)", CC_NS+"jurisdiction", CC_ROLE_NS+"license", "license (cc)", CC_ROLE_NS+"jurisdiction", "jurisdiction (cc)", CC_NS+"permits", CC_ROLE_NS+"license", "license (cc)", CC_ROLE_NS+"permission", "permission (cc)", CC_NS+"attributionName", CC_ROLE_NS+"work", "work (cc)", CC_ROLE_NS+"name", "name (cc)", CC_NS+"deprecatedOn", CC_ROLE_NS+"license", "license (cc)", CC_ROLE_NS+"date", "date (cc)", CC_NS+"morePermissions", CC_ROLE_NS+"work", "work (cc)", CC_ROLE_NS+"resource", "resource (cc)", CC_NS+"license", CC_ROLE_NS+"work", "work (cc)", CC_ROLE_NS+"license", "license (cc)", CC_NS+"legalcode", CC_ROLE_NS+"license", "license (cc)", CC_ROLE_NS+"resource", "resource (cc)", CC_NS+"attributionURL", CC_ROLE_NS+"work", "work (cc)", CC_ROLE_NS+"resource", "resource (cc)", }; public String[] getRoleMappings() { return ASSOCIATION_TYPE_TO_ROLES_MAPPING; } public String[] getBasenameMappings() { return SI_BASENAME_MAPPING; } }
4,485
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
RDF2TopicMapsMapping.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/rdf/rdfmappings/RDF2TopicMapsMapping.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * RDF2TopicMapsMapping.java * * Created on 13.2.2009,15:25 */ package org.wandora.application.tools.extractors.rdf.rdfmappings; import org.wandora.utils.Tuples.T2; /** * * @author akivela */ public abstract class RDF2TopicMapsMapping { public abstract String[] getRoleMappings(); public abstract String[] getBasenameMappings(); public static final String DEFAULT_SUBJECT_ROLE_SI = "http://wandora.org/si/core/rdf-subject"; public static final String DEFAULT_SUBJECT_ROLE_BASENAME = "subject-role"; public static final String DEFAULT_OBJECT_ROLE_SI = "http://wandora.org/si/core/rdf-object"; public static final String DEFAULT_OBJECT_ROLE_BASENAME = "object-role"; public T2<String,String> solveSubjectRoleFor(String predicate, String subject) { String si = null; String bn = null; String[] roles = getRoleMappings(); if(predicate != null) { for(int i=0; i<roles.length; i=i+5) { if(predicate.equals(roles[i])) { si = roles[i+1]; bn = roles[i+2]; break; } } } return new T2(si, bn); } public T2<String,String> solveObjectRoleFor(String predicate, String object) { String si = null; String bn = null; String[] roles = getRoleMappings(); if(predicate != null) { for(int i=0; i<roles.length; i=i+5) { if(predicate.equals(roles[i])) { si = roles[i+3]; bn = roles[i+4]; break; } } } return new T2(si, bn); } public String solveBasenameFor(String si) { if(si == null) return null; String bn = null; String[] basenameMappings = getBasenameMappings(); for(int i=0; i<basenameMappings.length; i=i+2) { if(si.equals(basenameMappings[i])) { bn = basenameMappings[i+1]; break; } } return bn; } }
2,949
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AnnieExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/gate/AnnieExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.gate; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.util.HashSet; import java.util.Iterator; import java.util.Set; 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.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 gate.Annotation; import gate.AnnotationSet; import gate.Corpus; import gate.CorpusController; import gate.Document; import gate.DocumentContent; import gate.Factory; import gate.FeatureMap; import gate.Gate; import gate.corpora.DocumentContentImpl; import gate.corpora.DocumentImpl; import gate.util.GateException; import gate.util.persistence.PersistenceManager; /** * See: http://gate.ac.uk/wiki/code-repository/src/sheffield/examples/StandAloneAnnie.java * * @author akivela */ public class AnnieExtractor extends AbstractGate { 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/gate/entity"; public static final String ENTITY_TYPE_SI = "http://wandora.org/si/gate/entity-type"; public static final String GATE_ANNIE_SI = "http://gate.ac.uk"; // ----- Configuration ----- private AnnieConfiguration configuration = null; private static CorpusController annieController = null; @Override public String getName() { return "Gate Annie extractor"; } @Override public String getDescription(){ return "Look for entities out of given text with Gate Annie. See http://gate.ac.uk"; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_gate.png"); } private static 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 wandora, Options options, String prefix) throws TopicMapException { if(configuration == null && wandora != null) { configuration = new AnnieConfiguration(wandora, this); } configuration.setVisible(true); } @Override public void writeOptions(Wandora wandora, Options options, String prefix) { } // ------------------------------------------------------------------------- @Override public void execute(Wandora wandora, Context context) { if(configuration == null && wandora != null) { configuration = new AnnieConfiguration(wandora, this); } super.execute(wandora, context); } @Override public boolean _extractTopicsFrom(URL url, TopicMap topicMap) throws Exception { URLConnection uc = url.openConnection(); uc.setUseCaches(false); boolean r = _extractTopicsFrom(uc.getInputStream(), topicMap); return r; } @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 { try { String inStr = IObox.loadFile(in, "utf-8"); doAnnie(inStr, topicMap); return true; } catch(Exception e) { log(e); } return false; } @Override public boolean _extractTopicsFrom(String in, TopicMap tm) throws Exception { try { doAnnie(in, tm); } catch(Exception e){ log("Exception when handling request",e); } return true; } public void initializeAnnie() throws GateException, MalformedURLException, IOException { Gate.setGateHome(new File(GATE_HOME)); Gate.setPluginsHome(new File(GATE_PLUGIN_HOME)); Gate.setSiteConfigFile(new File(CONFIG_FILE)); Gate.init(); log("GATE initialised"); // Load ANNIE plugin File pluginsHome = Gate.getPluginsHome(); File anniePlugin = new File(pluginsHome, "ANNIE"); File annieGapp = new File(anniePlugin, "ANNIE_with_defaults.gapp"); annieController = (CorpusController) PersistenceManager.loadObjectFromFile(annieGapp); log("ANNIE loaded successfully"); } public void doAnnie(String in, TopicMap topicMap) throws GateException, MalformedURLException, IOException, TopicMapException { in = XMLbox.naiveGetAsText(in); // Strip HTML String originalContent = in; 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 && in != null && in.length() > 0) { try { masterTopic = topicMap.createTopic(); masterTopic.addSubjectIdentifier(topicMap.makeSubjectIndicatorAsLocator()); fillDocumentTopic(masterTopic, topicMap, in); } catch(Exception e) { log(e); } } if(annieController == null) { initializeAnnie(); } else { log("GATE and Annie already initialized. Reusing old installations."); } // ------------------------------------------------- // create a GATE corpus and add a document Corpus corpus = (Corpus) Factory.createResource("gate.corpora.CorpusImpl"); FeatureMap params = Factory.newFeatureMap(); params.put("preserveOriginalContent", true); params.put("collectRepositioningInfo", true); DocumentImpl doc = (DocumentImpl) Factory.createResource("gate.corpora.DocumentImpl", params); DocumentContent content = new DocumentContentImpl(in); doc.setContent(content); corpus.add(doc); // ------------------------------------------------- // tell the pipeline about the corpus and run it annieController.setCorpus(corpus); log("Running ANNIE..."); annieController.execute(); log("ANNIE completed. Processing results next..."); // ------------------------------------------------- // for each document, get the annotations Iterator<Document> iter = corpus.iterator(); int count = 0; while(iter.hasNext() && !forceStop()) { Document docu = (Document) iter.next(); AnnotationSet defaultAnnotSet = docu.getAnnotations(); Set<String> annotTypes = defaultAnnotSet.getAllTypes(); for(String annotType : annotTypes) { if(forceStop()) break; if(acceptAnnotationType(annotType)) { Set<Annotation> annotations = new HashSet<Annotation>(defaultAnnotSet.get(annotType)); ++count; setProgressMax(annotations.size()); int c = 0; log("Extracting "+annotations.size()+" entities of type '"+annotType+"'..."); Iterator<Annotation> it = annotations.iterator(); Annotation annotation; long positionEnd; long positionStart; while(it.hasNext() && !forceStop()) { setProgress(c++); annotation = (Annotation) it.next(); positionStart = annotation.getStartNode().getOffset(); positionEnd = annotation.getEndNode().getOffset(); if(positionEnd != -1 && positionStart != -1) { String token = originalContent.substring((int) positionStart, (int) positionEnd); // log("Found token '"+token+"' of type "+annotation.getType()); doAnnieAnnotation(token, annotType, masterTopic, topicMap); } } } } } } public void doAnnieAnnotation(String word, String annotationType, Topic masterTopic, TopicMap tm) throws TopicMapException { Topic entityTopic = getEntityTopic(word, annotationType, tm); Topic entityType = getEntityTypeTopic(annotationType, tm); if(entityTopic != null && masterTopic != null) { Topic entityMetaType = getEntityMetaType(tm); Association a = tm.createAssociation(entityMetaType); a.addPlayer(masterTopic, getTopicType(tm)); a.addPlayer(entityTopic, getEntityType(tm)); if(entityType != null) { a.addPlayer(entityType, entityMetaType); } } } public boolean acceptAnnotationType(String annotationType) { try { if(configuration == null) { configuration = new AnnieConfiguration(getWandora(), this); } } catch(Exception e) { /* DONT HANDLE */ } if(configuration != null) { if(configuration.acceptAllAnnotationTypes()) { return true; } if(configuration.acceptAnnotationType(annotationType)) return true; else return false; } return true; } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- public Topic getEntityMetaType(TopicMap tm) throws TopicMapException { Topic t = getOrCreateTopic(tm, ENTITY_TYPE_SI, "GATE Annie entity type"); t.addType(getGATEAnnieClass(tm)); return t; } public Topic getEntityTypeTopic(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(getEntityMetaType(tm)); return t; } public Topic getEntityType(TopicMap tm) throws TopicMapException { Topic t = getOrCreateTopic(tm, ENTITY_SI, "GATE Annie entity"); t.addType(getGATEAnnieClass(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 = getEntityTypeTopic(type, tm); entityTopic.addType(entityTypeTopic); entityTopic.addType(getEntityType(tm)); } return entityTopic; } } return null; } public Topic getGATEAnnieClass(TopicMap tm) throws TopicMapException { Topic t = getOrCreateTopic(tm, GATE_ANNIE_SI, "GATE Annie"); 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); } }
16,512
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AbstractGate.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/gate/AbstractGate.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.gate; import org.wandora.application.tools.extractors.AbstractExtractor; /** * * @author akivela */ public abstract class AbstractGate extends AbstractExtractor { private static final long serialVersionUID = 1L; public static final String GATE_HOME = "lib/gate"; public static final String GATE_PLUGIN_HOME = GATE_HOME+"/plugins"; public static final String CONFIG_FILE = GATE_HOME+"/gate.xml"; }
1,266
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AnnieConfiguration.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/gate/AnnieConfiguration.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.gate; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import javax.swing.JDialog; import org.wandora.application.Wandora; import org.wandora.application.gui.simple.SimpleButton; import org.wandora.application.gui.simple.SimpleCheckBox; import org.wandora.application.gui.simple.SimpleField; import org.wandora.application.gui.simple.SimpleLabel; import org.wandora.application.gui.simple.SimpleTabbedPane; /** * * @author akivela */ public class AnnieConfiguration extends JDialog { private static final long serialVersionUID = 1L; private boolean accepted = false; private Wandora wandora = null; private AnnieExtractor parent = null; private Map<Object,Object> oldData = new HashMap<>(); /** Creates new form AnnieConfiguration */ public AnnieConfiguration(Wandora w, AnnieExtractor p) { super(w, true); wandora = w; parent = p; initComponents(); setSize(350,460); if(wandora != null) { wandora.centerWindow(this); } } @Override public void setVisible(boolean visible) { if(visible) { oldData.put(firstPersonCheckBox, firstPersonCheckBox.isSelected()); oldData.put(lookupCheckBox, lookupCheckBox.isSelected()); oldData.put(personCheckBox, personCheckBox.isSelected()); oldData.put(sentenceCheckBox, sentenceCheckBox.isSelected()); oldData.put(spaceTokenCheckBox, spaceTokenCheckBox.isSelected()); oldData.put(splitCheckBox, splitCheckBox.isSelected()); oldData.put(tokenCheckBox, tokenCheckBox.isSelected()); oldData.put(unknownCheckBox, unknownCheckBox.isSelected()); oldData.put(dateCheckBox, dateCheckBox.isSelected()); oldData.put(jobTitleCheckBox, jobTitleCheckBox.isSelected()); oldData.put(locationCheckBox, locationCheckBox.isSelected()); oldData.put(organizationCheckBox, organizationCheckBox.isSelected()); oldData.put(tempCheckBox, tempCheckBox.isSelected()); oldData.put(identifierCheckBox, identifierCheckBox.isSelected()); oldData.put(moneyCheckBox, moneyCheckBox.isSelected()); oldData.put(percentCheckBox, percentCheckBox.isSelected()); oldData.put(titleCheckBox, titleCheckBox.isSelected()); oldData.put(otherTextField, otherTextField.getText()); } super.setVisible(visible); } public boolean wasAccepted() { return accepted; } public boolean acceptAllAnnotationTypes() { return allCheckBox.isSelected(); } private boolean annotationTypeUpdateRequired = true; private Set<String> annotationTypes = null; public boolean acceptAnnotationType(String t) { if(annotationTypes == null || annotationTypeUpdateRequired) { annotationTypes = getAnnotationTypes(); annotationTypeUpdateRequired = false; } if(annotationTypes.contains(t)) return true; return false; } // ADD Date, JobTitle, Location, Organization, Temp public Set<String> getAnnotationTypes() { LinkedHashSet<String> types = new LinkedHashSet<String>(); if(firstPersonCheckBox.isSelected()) types.add("FirstPerson"); if(lookupCheckBox.isSelected()) types.add("Lookup"); if(personCheckBox.isSelected()) types.add("Person"); if(sentenceCheckBox.isSelected()) types.add("Sentence"); if(spaceTokenCheckBox.isSelected()) types.add("SpaceToken"); if(splitCheckBox.isSelected()) types.add("Split"); if(tokenCheckBox.isSelected()) types.add("Token"); if(unknownCheckBox.isSelected()) types.add("Unknown"); if(dateCheckBox.isSelected()) types.add("Date"); if(jobTitleCheckBox.isSelected()) types.add("JobTitle"); if(locationCheckBox.isSelected()) types.add("Location"); if(organizationCheckBox.isSelected()) types.add("Organization"); if(tempCheckBox.isSelected()) types.add("Temp"); if(identifierCheckBox.isSelected()) types.add("Identifier"); if(moneyCheckBox.isSelected()) types.add("Money"); if(percentCheckBox.isSelected()) types.add("Percent"); if(titleCheckBox.isSelected()) types.add("Title"); String other = otherTextField.getText(); String[] others = other.split(","); if(others.length > 0) { for(int i=0; i<others.length; i++) { String o = others[i]; if(o != null && o.trim().length() > 0) { types.add(o); } } } return types; } private void restoreOldData() { try { firstPersonCheckBox.setSelected(((Boolean)oldData.get(firstPersonCheckBox)).booleanValue()); lookupCheckBox.setSelected(((Boolean)oldData.get(lookupCheckBox)).booleanValue()); personCheckBox.setSelected(((Boolean)oldData.get(personCheckBox)).booleanValue()); sentenceCheckBox.setSelected(((Boolean)oldData.get(sentenceCheckBox)).booleanValue()); spaceTokenCheckBox.setSelected(((Boolean)oldData.get(spaceTokenCheckBox)).booleanValue()); splitCheckBox.setSelected(((Boolean)oldData.get(splitCheckBox)).booleanValue()); tokenCheckBox.setSelected(((Boolean)oldData.get(tokenCheckBox)).booleanValue()); unknownCheckBox.setSelected(((Boolean)oldData.get(unknownCheckBox)).booleanValue()); dateCheckBox.setSelected(((Boolean)oldData.get(unknownCheckBox)).booleanValue()); jobTitleCheckBox.setSelected(((Boolean)oldData.get(jobTitleCheckBox)).booleanValue()); locationCheckBox.setSelected(((Boolean)oldData.get(locationCheckBox)).booleanValue()); organizationCheckBox.setSelected(((Boolean)oldData.get(organizationCheckBox)).booleanValue()); tempCheckBox.setSelected(((Boolean)oldData.get(tempCheckBox)).booleanValue()); identifierCheckBox.setSelected(((Boolean)oldData.get(identifierCheckBox)).booleanValue()); moneyCheckBox.setSelected(((Boolean)oldData.get(moneyCheckBox)).booleanValue()); percentCheckBox.setSelected(((Boolean)oldData.get(percentCheckBox)).booleanValue()); titleCheckBox.setSelected(((Boolean)oldData.get(titleCheckBox)).booleanValue()); otherTextField.setText( (String) oldData.get(otherTextField) ); } catch(Exception 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; annieTabbedPane = new SimpleTabbedPane(); acceptedAnnotationsPanel = new javax.swing.JPanel(); annotationTypeLabel = new SimpleLabel(); typesPanel = new javax.swing.JPanel(); allCheckBox = new SimpleCheckBox(); jSeparator = new javax.swing.JSeparator(); checkboxesPanel = new javax.swing.JPanel(); checkboxesPanel1 = new javax.swing.JPanel(); firstPersonCheckBox = new SimpleCheckBox(); lookupCheckBox = new SimpleCheckBox(); personCheckBox = new SimpleCheckBox(); sentenceCheckBox = new SimpleCheckBox(); spaceTokenCheckBox = new SimpleCheckBox(); splitCheckBox = new SimpleCheckBox(); tokenCheckBox = new SimpleCheckBox(); unknownCheckBox = new SimpleCheckBox(); dateCheckBox = new SimpleCheckBox(); checkboxesPanel2 = new javax.swing.JPanel(); jobTitleCheckBox = new SimpleCheckBox(); locationCheckBox = new SimpleCheckBox(); organizationCheckBox = new SimpleCheckBox(); tempCheckBox = new SimpleCheckBox(); identifierCheckBox = new SimpleCheckBox(); moneyCheckBox = new SimpleCheckBox(); percentCheckBox = new SimpleCheckBox(); titleCheckBox = new SimpleCheckBox(); otherPanel = new javax.swing.JPanel(); otherLabel = new SimpleLabel(); otherTextField = new SimpleField(); buttonPanel = new javax.swing.JPanel(); buttonFillerPanel = new javax.swing.JPanel(); okButton = new SimpleButton(); cancelButton = new SimpleButton(); setTitle("Configure GATE Annie extractor"); getContentPane().setLayout(new java.awt.GridBagLayout()); acceptedAnnotationsPanel.setLayout(new java.awt.GridBagLayout()); annotationTypeLabel.setText("<html>Select annotation types which Wandora should convert to topics and associations. Write additional types to 'Other' field as a comma separated list. Selecting 'Accept ALL' includes also nonlisted annotation types.</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(6, 6, 12, 6); acceptedAnnotationsPanel.add(annotationTypeLabel, gridBagConstraints); typesPanel.setLayout(new java.awt.GridBagLayout()); allCheckBox.setText("Accept ALL annotation types"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; typesPanel.add(allCheckBox, 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); typesPanel.add(jSeparator, gridBagConstraints); checkboxesPanel.setLayout(new java.awt.GridBagLayout()); checkboxesPanel1.setLayout(new java.awt.GridBagLayout()); firstPersonCheckBox.setSelected(true); firstPersonCheckBox.setText("FirstPerson"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; checkboxesPanel1.add(firstPersonCheckBox, gridBagConstraints); lookupCheckBox.setSelected(true); lookupCheckBox.setText("Lookup"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; checkboxesPanel1.add(lookupCheckBox, gridBagConstraints); personCheckBox.setSelected(true); personCheckBox.setText("Person"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; checkboxesPanel1.add(personCheckBox, gridBagConstraints); sentenceCheckBox.setText("Sentence"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; checkboxesPanel1.add(sentenceCheckBox, gridBagConstraints); spaceTokenCheckBox.setText("SpaceToken"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; checkboxesPanel1.add(spaceTokenCheckBox, gridBagConstraints); splitCheckBox.setText("Split"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; checkboxesPanel1.add(splitCheckBox, gridBagConstraints); tokenCheckBox.setText("Token"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; checkboxesPanel1.add(tokenCheckBox, gridBagConstraints); unknownCheckBox.setSelected(true); unknownCheckBox.setText("Unknown"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; checkboxesPanel1.add(unknownCheckBox, gridBagConstraints); dateCheckBox.setSelected(true); dateCheckBox.setText("Date"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; checkboxesPanel1.add(dateCheckBox, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; checkboxesPanel.add(checkboxesPanel1, gridBagConstraints); checkboxesPanel2.setLayout(new java.awt.GridBagLayout()); jobTitleCheckBox.setText("JobTitle"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; checkboxesPanel2.add(jobTitleCheckBox, gridBagConstraints); locationCheckBox.setSelected(true); locationCheckBox.setText("Location"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; checkboxesPanel2.add(locationCheckBox, gridBagConstraints); organizationCheckBox.setSelected(true); organizationCheckBox.setText("Organization"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; checkboxesPanel2.add(organizationCheckBox, gridBagConstraints); tempCheckBox.setText("Temp"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; checkboxesPanel2.add(tempCheckBox, gridBagConstraints); identifierCheckBox.setSelected(true); identifierCheckBox.setText("Identifier"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; checkboxesPanel2.add(identifierCheckBox, gridBagConstraints); moneyCheckBox.setText("Money"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; checkboxesPanel2.add(moneyCheckBox, gridBagConstraints); percentCheckBox.setText("Percent"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; checkboxesPanel2.add(percentCheckBox, gridBagConstraints); titleCheckBox.setSelected(true); titleCheckBox.setText("Title"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; checkboxesPanel2.add(titleCheckBox, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; checkboxesPanel.add(checkboxesPanel2, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 6, 0); typesPanel.add(checkboxesPanel, gridBagConstraints); otherPanel.setLayout(new java.awt.GridBagLayout()); otherLabel.setText("Other"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4); otherPanel.add(otherLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; otherPanel.add(otherTextField, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; typesPanel.add(otherPanel, 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, 12, 6, 12); acceptedAnnotationsPanel.add(typesPanel, gridBagConstraints); annieTabbedPane.addTab("Annotation types", acceptedAnnotationsPanel); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; getContentPane().add(annieTabbedPane, 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); 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, 3); buttonPanel.add(okButton, gridBagConstraints); cancelButton.setText("Cancel"); 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.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 annotationTypeUpdateRequired = true; accepted = true; setVisible(false); }//GEN-LAST:event_okButtonMouseReleased private void cancelButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cancelButtonMouseReleased accepted = false; setVisible(false); restoreOldData(); }//GEN-LAST:event_cancelButtonMouseReleased // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel acceptedAnnotationsPanel; private javax.swing.JCheckBox allCheckBox; private javax.swing.JTabbedPane annieTabbedPane; private javax.swing.JLabel annotationTypeLabel; private javax.swing.JPanel buttonFillerPanel; private javax.swing.JPanel buttonPanel; private javax.swing.JButton cancelButton; private javax.swing.JPanel checkboxesPanel; private javax.swing.JPanel checkboxesPanel1; private javax.swing.JPanel checkboxesPanel2; private javax.swing.JCheckBox dateCheckBox; private javax.swing.JCheckBox firstPersonCheckBox; private javax.swing.JCheckBox identifierCheckBox; private javax.swing.JSeparator jSeparator; private javax.swing.JCheckBox jobTitleCheckBox; private javax.swing.JCheckBox locationCheckBox; private javax.swing.JCheckBox lookupCheckBox; private javax.swing.JCheckBox moneyCheckBox; private javax.swing.JButton okButton; private javax.swing.JCheckBox organizationCheckBox; private javax.swing.JLabel otherLabel; private javax.swing.JPanel otherPanel; private javax.swing.JTextField otherTextField; private javax.swing.JCheckBox percentCheckBox; private javax.swing.JCheckBox personCheckBox; private javax.swing.JCheckBox sentenceCheckBox; private javax.swing.JCheckBox spaceTokenCheckBox; private javax.swing.JCheckBox splitCheckBox; private javax.swing.JCheckBox tempCheckBox; private javax.swing.JCheckBox titleCheckBox; private javax.swing.JCheckBox tokenCheckBox; private javax.swing.JPanel typesPanel; private javax.swing.JCheckBox unknownCheckBox; // End of variables declaration//GEN-END:variables }
23,716
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
JsoupHCardExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/microformats/JsoupHCardExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.microformats; import java.util.HashMap; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.wandora.topicmap.Association; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author Eero */ public class JsoupHCardExtractor extends AbstractJsoupMicroformatExtractor { private static final long serialVersionUID = 1L; private static final String SI_PREFIX = "http://wandora.org/si/hcard/"; private static final String[] CARD_PROPS = { "fn", "agent", "bday", "category", "class", "email", "key", "label", "logo", "mailer", "nickname", "note", "org", "photo", "rev", "role", "sort-string", "sound", "url", "tel", "title", "tz", "url", "uid" }; private HashMap<String,Topic> typeTopics; private TopicMap tm; @Override public String getName() { return "HCard microformat extractor"; } @Override public String getDescription() { return "Converts HCard microformat HTML snippets to Topic Maps."; } @Override public boolean extractTopicsFrom(Document d, String u, TopicMap t){ tm = t; try { //typeTopics = generateTypes(); typeTopics = new HashMap<String, Topic>(); Topic document = getOrCreateTopic(tm, d.baseUri(), d.title()); Topic docType = getType("document"); document.addType(docType); Elements cards = d.select(".vcard"); for(Element card : cards){ try { parseCard(document,card); } catch (TopicMapException tme) { log(tme); } } } catch (TopicMapException tme) { log(tme); return false; } return true; } private void parseCard(Topic document, Element element) throws TopicMapException { Topic topic = getOrCreateTopic(tm, null); Topic cardType = getType("vcard"); Topic docType = getType("document"); topic.addType(cardType); Association a = tm.createAssociation(cardType); a.addPlayer(topic,cardType); a.addPlayer(document,docType); for (int i = 0; i < CARD_PROPS.length; i++) { String propName = CARD_PROPS[i]; Elements props = element.select("." + propName); for(Element prop: props){ try { addProp(topic,propName,prop); } catch (TopicMapException tme) { log(tme); } } } Element name = element.select(".n").first(); if(name != null) try { parseName(topic, name); } catch (TopicMapException tme) { log(tme); } Element adr = element.select(".adr").first(); if(adr != null) try { parseAdr(topic, adr, "vcard"); } catch (TopicMapException tme) { log(tme); } Element geo = element.select(".geo").first(); if(geo != null) try { parseGeo(topic, geo, "vcard"); } catch (TopicMapException tme) { log(tme); } } @Override protected String[][] getTypeStrings() { return TYPE_STRINGS; } @Override protected HashMap<String, Topic> getTypeTopics() { return typeTopics; } @Override protected TopicMap getTopicMap() { return tm; } @Override protected String getSIPrefix() { return SI_PREFIX; } }
4,819
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AbstractJsoupMicroformatExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/microformats/AbstractJsoupMicroformatExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.microformats; import java.util.HashMap; import javax.swing.Icon; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.wandora.application.gui.UIBox; import org.wandora.application.tools.extractors.AbstractJsoupExtractor; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author Eero */ abstract class AbstractJsoupMicroformatExtractor extends AbstractJsoupExtractor{ private static final long serialVersionUID = 1L; @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_microformat.png"); } private static final String MICROFORMAT_SI = "http://microformats.org/"; protected static final String[][] TYPE_STRINGS = { {"microformat", "microformat"}, {"document", "document"}, {"vcard", "hCard"}, {"vcalendar", "hCalendar"}, {"vevent", "hCalendar event"}, {"fn", "full name"}, {"agent", "agent"}, {"bday", "birthday"}, {"category", "category"}, {"class", "class"}, {"email", "email address"}, {"key", "key"}, {"label", "label"}, {"logo", "logo"}, {"mailer", "mailer"}, {"nickname", "nickname"}, {"note", "note"}, {"org", "organization"}, {"photo", "photo"}, {"rev", "revision"}, {"role", "role"}, {"sort-string", "sort string"}, {"sound", "sound"}, {"url", "home page"}, {"tel", "telephone number"}, {"title", "title"}, {"tz", "timezone"}, {"url", "url"}, {"uid", "uid"}, {"n", "structured name"}, {"honorific-prefix","honorific prefix"}, {"given-name", "given name"}, {"additional-name", "additional name"}, {"family-name", "family name"}, {"honorific-suffix","honorific suffix"}, {"adr", "structured address"}, {"street-address", "street address"}, {"locality", "locality"}, {"region", "region"}, {"postal-code", "postal code"}, {"country-name", "country name"}, {"dstart", "start time"}, {"dtend", "end time"}, {"duration", "duration"}, {"rdate", "date"}, {"rrule", "rule"}, {"location", "location"}, {"category", "category"}, {"description", "description"}, {"geo", "geo location"}, {"latitude", "latitude"}, {"longitude", "longitude"} }; protected static final String[] ADR_PROPS = { "street-address", "locality", "region", "postal-code", "country-name" }; protected static final String[] NAME_PROPS = { "honorific-prefix", "given-name", "additional-name", "family-name", "honorific-suffix" }; protected static final String[] GEO_PROPS = { "latitude", "longitude" }; private Topic getMicroformatTopic(TopicMap tm) throws TopicMapException{ //Is the microformat topic already present? Topic microformatTopic = tm.getTopic(MICROFORMAT_SI); if(microformatTopic != null) return microformatTopic; //Nope. Create it. microformatTopic = getOrCreateTopic(tm, MICROFORMAT_SI, "microformat"); makeSubclassOf(tm, microformatTopic, getWandoraClassTopic(tm)); return microformatTopic; } //Avoid polluting the TopicMap with unused type topics. protected Topic getType(String typeKey) throws TopicMapException{ TopicMap tm = getTopicMap(); HashMap<String, Topic> typeTopics = getTypeTopics(); if(typeTopics.containsKey(typeKey)) return typeTopics.get(typeKey); Topic wandoraClass = getMicroformatTopic(tm); String typeName = null; for (int i = 0; i < TYPE_STRINGS.length; i++) { if(TYPE_STRINGS[i][0].equals(typeKey)) typeName = TYPE_STRINGS[i][1]; } if(typeName == null) throw new TopicMapException("Failed to get type topic"); Topic type = getOrCreateTopic(tm, getSIPrefix() + typeKey, typeName); makeSubclassOf(tm, type, wandoraClass); typeTopics.put(typeKey, type); return type; } protected void addProp(Topic topic, String propName, Element prop) throws TopicMapException { Topic topicType = getType("vcard"); addProp(topic, topicType,propName,prop); } protected void addProp(Topic topic,Topic topicType, String propName, Element prop) throws TopicMapException { Topic propType = getType(propName); String propValue; if(propName.equals("url")){ propValue = prop.attr("href"); topic.setSubjectLocator(new Locator(propValue)); } else if(propName.equals("email")){ propValue = prop.attr("href"); if(propValue.length() == 0) propValue = prop.text(); if(propValue.startsWith("mailto:")) propValue = propValue.substring(6,propValue.length()); } else if(propName.equals("title")){ propValue = prop.text(); topic.setBaseName(propValue); } else if(propName.equals("photo")){ propValue = prop.attr("src"); } else { propValue = prop.text(); } if(propValue.length() == 0){ log("Failed to add property: " + propName); return; } String si = getSIPrefix() + propName + "/" + propValue; Topic propTopic = getOrCreateTopic(getTopicMap(), si, propValue); propTopic.addType(propType); Association a = getTopicMap().createAssociation(propType); a.addPlayer(topic, topicType); a.addPlayer(propTopic, propType); } protected void parseName(Topic card, Element element) throws TopicMapException { TopicMap tm = getTopicMap(); Topic topic = getOrCreateTopic(tm, null); Topic nameType = getType("n"); Topic cardType = getType("vcard"); topic.addType(nameType); Association a = tm.createAssociation(nameType); a.addPlayer(topic,nameType); a.addPlayer(card,cardType); for (int i = 0; i < NAME_PROPS.length; i++) { String propName = NAME_PROPS[i]; Elements props = element.select("." + propName); for(Element prop: props){ try { addProp(topic,nameType,propName,prop); } catch (TopicMapException tme) { log(tme); } } } } protected void parseAdr(Topic parent, Element element, String parentTypeName) throws TopicMapException { TopicMap tm = getTopicMap(); Topic topic = getOrCreateTopic(tm, null); Topic adrType = getType("adr"); Topic parentType = getType(parentTypeName); topic.addType(adrType); Association a = tm.createAssociation(adrType); a.addPlayer(topic,adrType); a.addPlayer(parent,parentType); for (int i = 0; i < ADR_PROPS.length; i++) { String propName = ADR_PROPS[i]; Elements props = element.select("." + propName); for(Element prop: props){ try { addProp(topic,adrType,propName,prop); } catch (TopicMapException tme) { log(tme); } } } } protected void parseGeo(Topic card, Element element, String parentTypeName) throws TopicMapException { TopicMap tm = getTopicMap(); Topic topic = getOrCreateTopic(tm, null); Topic geoType = getType("geo"); Topic parentType = getType(parentTypeName); topic.addType(geoType); Association a = tm.createAssociation(geoType); a.addPlayer(topic,geoType); a.addPlayer(card,parentType); for (int i = 0; i < GEO_PROPS.length; i++) { String propName = GEO_PROPS[i]; Elements props = element.select("." + propName); for(Element prop: props){ try { addProp(topic,geoType,propName,prop); } catch (TopicMapException tme) { log(tme); } } } } abstract protected String[][] getTypeStrings(); abstract protected HashMap<String, Topic> getTypeTopics(); abstract protected TopicMap getTopicMap(); abstract protected String getSIPrefix(); }
10,205
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AdrExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/microformats/AdrExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * AdrExtractor.java * * Created on 13. joulukuuta 2007, 11:59 * */ package org.wandora.application.tools.extractors.microformats; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.Properties; import java.util.Stack; import javax.swing.Icon; import org.w3c.tidy.Tidy; import org.wandora.application.WandoraTool; import org.wandora.application.gui.UIBox; import org.wandora.application.tools.extractors.AbstractExtractor; import org.wandora.topicmap.Association; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicTools; 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 AdrExtractor extends AbstractExtractor implements WandoraTool { private static final long serialVersionUID = 1L; /** Creates a new instance of AdrExtractor */ public AdrExtractor() { } @Override public String getName() { return "Adr microformat extractor"; } @Override public String getDescription() { return "Converts ADR Microformat HTML snippets to topic maps."; } @Override public boolean useTempTopicMap(){ return false; } public static final String[] contentTypes=new String[] { "text/html" }; @Override public String[] getContentTypes() { return contentTypes; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_microformat.png"); } 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 boolean _extractTopicsFrom(InputStream in, TopicMap topicMap) throws Exception { Tidy tidy = null; String tidyXML = null; try { Properties tidyProps = new Properties(); tidyProps.put("trim-empty-elements", "no"); tidy = new Tidy(); tidy.setConfigurationFromProps(tidyProps); tidy.setXmlOut(true); tidy.setXmlPi(true); tidy.setTidyMark(false); ByteArrayOutputStream tidyOutput = null; tidyOutput = new ByteArrayOutputStream(); tidy.parse(in, tidyOutput); tidyXML = tidyOutput.toString(); } catch(Error er) { log("Unable to preprocess HTML with JTidy!"); log(er); } catch(Exception e) { log("Unable to preprocess HTML with JTidy!"); log(e); } if(tidyXML == null) { log("Trying to read HTML without preprocessing!"); tidyXML = IObox.loadFile(new InputStreamReader(in)); } //tidyXML = tidyXML.replace("&", "&amp;"); tidyXML = tidyXML.replace("&amp;deg;", "&#0176;"); //tidyXML = HTMLEntitiesCoder.decode(tidyXML); /* System.out.println("------"); System.out.println(tidyXML); System.out.println("------"); */ 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(); AdrParser parserHandler = new AdrParser(topicMap,this); reader.setContentHandler(parserHandler); reader.setErrorHandler(parserHandler); try{ reader.parse(new InputSource(new ByteArrayInputStream(tidyXML.getBytes()))); } catch(Exception e){ if(!(e instanceof SAXException) || !e.getMessage().equals("User interrupt")) log(e); } log("Total " + parserHandler.progress + " adr addresses found!"); return true; } public static class AdrParser implements org.xml.sax.ContentHandler, org.xml.sax.ErrorHandler { private static final boolean debug = true; private TopicMap tm = null; private AdrExtractor parent = null; public static final String SI_PREFIX = "http://wandora.org/si/adr/"; public int progress = 0; public int adrcount = 0; private static final int STATE_START=1111; private static final int STATE_ADR = 99; private static final int STATE_POST_OFFICE_BOX=1; private static final int STATE_EXTENDED_ADDRESS=2; private static final int STATE_STREET_ADDRESS=3; private static final int STATE_LOCALITY=4; private static final int STATE_REGION=5; private static final int STATE_POSTAL_CODE=6; private static final int STATE_COUNTRY_NAME=7; private static final int STATE_ABBR=10; private static final int STATE_OTHER=9999; private int state=STATE_START; private String postOfficeBox; private String extendedAddress; private String streetAddress; private String locality; private String region; private String postalCode; private String countryName; private String location; private Association association; private Stack<Integer> stateStack; // ------------------------------------------------------------------------- public AdrParser(TopicMap tm, AdrExtractor parent ) { this.tm=tm; this.parent=parent; postOfficeBox = null; extendedAddress = null; streetAddress = null; locality = null; region = null; postalCode = null; countryName = null; location = null; association = null; stateStack = new Stack<>(); } // ------------------------------------------------------------------------- public void startDocument() throws SAXException { } public void endDocument() throws SAXException { } public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { stateStack.push(Integer.valueOf(state)); String clas = atts.getValue("class"); if(debug) System.out.print("qname=="+ qName); if(debug) System.out.print(", class=="+ clas); if(debug) System.out.print(", sstate="+state); if(parent.forceStop()){ throw new SAXException("User interrupt"); } switch(state) { case STATE_START: { if("adr".equalsIgnoreCase(clas)) { state = STATE_ADR; } break; } case STATE_ADR: { if("abbr".equalsIgnoreCase(qName)) { String title = atts.getValue("title"); if(clas != null) { if("street-address".equalsIgnoreCase(clas)) { state = STATE_ABBR; streetAddress = title; } else if("post-office-box".equalsIgnoreCase(clas)) { state = STATE_ABBR; postOfficeBox = title; } else if("extended-address".equalsIgnoreCase(clas)) { state = STATE_ABBR; extendedAddress = title; } else if("locality".equalsIgnoreCase(clas)) { state = STATE_ABBR; locality = title; } else if("region".equalsIgnoreCase(clas)) { state = STATE_ABBR; region = title; } else if("postal-code".equalsIgnoreCase(clas)) { state = STATE_ABBR; postalCode = title; } else if("country-name".equalsIgnoreCase(clas)) { state = STATE_ABBR; countryName = title; } } } else { if("street-address".equalsIgnoreCase(clas)) { state = STATE_STREET_ADDRESS; streetAddress = null; } else if("post-office-box".equalsIgnoreCase(clas)) { state = STATE_POST_OFFICE_BOX; postOfficeBox = null; } else if("extended-address".equalsIgnoreCase(clas)) { state = STATE_EXTENDED_ADDRESS; extendedAddress = null; } else if("locality".equalsIgnoreCase(clas)) { state = STATE_LOCALITY; locality = null; } else if("region".equalsIgnoreCase(clas)) { state = STATE_REGION; region = null; } else if("postal-code".equalsIgnoreCase(clas)) { state = STATE_POSTAL_CODE; postalCode = null; } else if("country-name".equalsIgnoreCase(clas)) { state = STATE_COUNTRY_NAME; countryName = null; } } break; } } if(debug) System.out.println(", nstate="+state); } public void endElement(String uri, String localName, String qName) throws SAXException { switch(state) { case STATE_ADR: { if(!stateStack.contains(Integer.valueOf(STATE_ADR))) { processAdr(); } break; } } popState(); } public void characters(char[] data, int start, int length) throws SAXException { switch(state) { case STATE_START: { location = catenate(location, data, start, length); break; } case STATE_STREET_ADDRESS: { streetAddress = catenate(streetAddress, data, start, length); break; } case STATE_POST_OFFICE_BOX: { postOfficeBox = catenate(postOfficeBox, data, start, length); break; } case STATE_EXTENDED_ADDRESS: { extendedAddress = catenate(extendedAddress, data, start, length); break; } case STATE_LOCALITY: { locality = catenate(locality, data, start, length); break; } case STATE_REGION: { region = catenate(region, data, start, length); break; } case STATE_POSTAL_CODE: { postalCode = catenate(postalCode, data, start, length); break; } case STATE_COUNTRY_NAME: { countryName = catenate(countryName, data, start, length); break; } } } private String catenate(String base, char[] data, int start, int length) { if(base == null) base = ""; base = base + new String(data,start,length); return base; } 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 {} public void processAdr() { if(streetAddress != null || postOfficeBox != null || extendedAddress != null || locality != null || region != null || postalCode != null || countryName != null ) { adrcount++; try { Topic locationTypeTopic = createTopic(tm, SI_PREFIX+"location", "location"); boolean isDefaultLocation = false; if(location != null) location = location.trim(); if(location == null || location.length() < 1) { isDefaultLocation = true; location = "unknown-location-"+System.currentTimeMillis()+""+adrcount; } if(isDefaultLocation) { parent.log("Creating address for unknown location '"+location+"'"); } else { location = location.trim(); if(location.endsWith(":")) location = location.substring(0, location.length()-1); location = location.trim(); parent.log("Creating address for '"+location+"'"); } Topic locationTopic = createTopic(tm, SI_PREFIX+"location/"+location, location, new Topic[] { locationTypeTopic } ); createAssociationFor(streetAddress, "street-address", locationTopic, locationTypeTopic, tm); createAssociationFor(postOfficeBox, "post-office-box", locationTopic, locationTypeTopic, tm); createAssociationFor(extendedAddress, "extended-address", locationTopic, locationTypeTopic, tm); createAssociationFor(locality, "locality", locationTopic, locationTypeTopic, tm); createAssociationFor(region, "region", locationTopic, locationTypeTopic, tm); createAssociationFor(postalCode, "postal-code", locationTopic, locationTypeTopic, tm); createAssociationFor(countryName, "country-name", locationTopic, locationTypeTopic, tm); } catch(Exception e) { parent.log(e); } postOfficeBox = null; extendedAddress = null; streetAddress = null; locality = null; region = null; postalCode = null; countryName = null; location = null; progress++; } else { parent.log("Found adr without data. Rejecting!"); } } private void createAssociationFor(String basename, String associationTypeName, Topic player, Topic role, TopicMap tm) { if(basename != null) { basename = basename.trim(); if(basename.length() > 0) { try { Topic associationTypeTopic = createTopic(tm, SI_PREFIX+associationTypeName, associationTypeName); Topic playerTopic = createTopic(tm, SI_PREFIX+associationTypeName+"/"+basename, basename); Association association = tm.createAssociation(associationTypeTopic); association.addPlayer(player, role); association.addPlayer(playerTopic, associationTypeTopic); } catch(Exception e) { parent.log(e); } } } } private void popState() { if(!stateStack.empty()) { state = ((Integer) stateStack.pop()).intValue(); } else { state = STATE_OTHER; } } // -------------------- public Topic createTopic(TopicMap topicMap, String si, String baseName) throws TopicMapException { return createTopic(topicMap, si, baseName, null); } public Topic createTopic(TopicMap topicMap, String si, String baseName, Topic[] types) throws TopicMapException { Topic t = null; if(baseName != null && baseName.length() > 0 && si != null && si.length() > 0) { si = TopicTools.cleanDirtyLocator(si); t = topicMap.getTopic(si); if(t == null) { t = topicMap.getTopicWithBaseName(baseName); if(t == null) { t = topicMap.createTopic(); t.setBaseName(baseName); } t.addSubjectIdentifier(new org.wandora.topicmap.Locator(si)); } if(types != null) { for(int i=0; i<types.length; i++) { Topic typeTopic = types[i]; if(typeTopic != null) { t.addType(typeTopic); } } } } if(t == null) { System.out.println("Failed to create topic for basename '"+baseName+"' and si '"+si+"'."); } return t; } } }
20,374
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
JsoupAdrExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/microformats/JsoupAdrExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.microformats; import java.util.HashMap; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author Eero */ public class JsoupAdrExtractor extends AbstractJsoupMicroformatExtractor{ private static final long serialVersionUID = 1L; private static final String SI_PREFIX = "http://wandora.org/si/adr/"; private HashMap<String,Topic> typeTopics; private TopicMap tm; @Override public String getName() { return "Adr microformat extractor"; } @Override public String getDescription() { return "Converts Adr microformat HTML snippets to Topic Maps."; } @Override protected String[][] getTypeStrings() { return TYPE_STRINGS; } @Override protected HashMap<String, Topic> getTypeTopics() { return typeTopics; } @Override protected TopicMap getTopicMap() { return tm; } @Override protected String getSIPrefix() { return SI_PREFIX; } @Override public boolean extractTopicsFrom(Document d, String u, TopicMap t) throws Exception { tm = t; try { //typeTopics = generateTypes(); typeTopics = new HashMap<String, Topic>(); Topic document = getOrCreateTopic(tm, d.baseUri(), d.title()); Topic docType = getType("document"); document.addType(docType); Elements adrs = d.select(".adr"); for(Element adr : adrs){ try { parseAdr(document,adr, "document"); } catch (TopicMapException tme) { log(tme); } } } catch (TopicMapException tme) { log(tme); return false; } return true; } }
2,856
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
HCalendarExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/microformats/HCalendarExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * HCalendarExtractor.java * * Created on 13. joulukuuta 2007, 11:59 * */ package org.wandora.application.tools.extractors.microformats; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.Properties; import java.util.Stack; import javax.swing.Icon; import org.w3c.tidy.Tidy; import org.wandora.application.WandoraTool; import org.wandora.application.gui.UIBox; import org.wandora.application.tools.extractors.AbstractExtractor; import org.wandora.topicmap.Association; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicTools; 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 HCalendarExtractor extends AbstractExtractor implements WandoraTool { private static final long serialVersionUID = 1L; /** Creates a new instance of AdrExtractor */ public HCalendarExtractor() { } public String getName() { return "HCalendar microformat extractor"; } public String getDescription() { return "Converts HCalendar Microformat HTML snippets to topic maps."; } @Override public boolean useTempTopicMap(){ return false; } public static final String[] contentTypes=new String[] { "text/html" }; @Override public String[] getContentTypes() { return contentTypes; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_microformat.png"); } 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 boolean _extractTopicsFrom(InputStream in, TopicMap topicMap) throws Exception { Tidy tidy = null; String tidyXML = null; try { Properties tidyProps = new Properties(); tidyProps.put("trim-empty-elements", "no"); tidy = new Tidy(); tidy.setConfigurationFromProps(tidyProps); tidy.setXmlOut(true); tidy.setXmlPi(true); tidy.setTidyMark(false); ByteArrayOutputStream tidyOutput = null; tidyOutput = new ByteArrayOutputStream(); tidy.parse(in, tidyOutput); tidyXML = tidyOutput.toString(); } catch(Error er) { log("Unable to preprocess HTML with JTidy!"); log(er); } catch(Exception e) { log("Unable to preprocess HTML with JTidy!"); log(e); } if(tidyXML == null) { log("Trying to read HTML without preprocessing!"); tidyXML = IObox.loadFile(new InputStreamReader(in)); } //tidyXML = tidyXML.replace("&", "&amp;"); tidyXML = tidyXML.replace("&amp;deg;", "&#0176;"); System.out.println("------"); System.out.println(tidyXML); System.out.println("------"); 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(); HCalendarParser parserHandler = new HCalendarParser(topicMap,this); reader.setContentHandler(parserHandler); reader.setErrorHandler(parserHandler); try{ reader.parse(new InputSource(new ByteArrayInputStream(tidyXML.getBytes()))); } catch(Exception e){ if(!(e instanceof SAXException) || !e.getMessage().equals("User interrupt")) log(e); } log("Total " + parserHandler.eventcount + " HCalendar events found!"); return true; } public static class HCalendarParser implements org.xml.sax.ContentHandler, org.xml.sax.ErrorHandler { private static final boolean debug = true; private TopicMap tm = null; private HCalendarExtractor parent = null; public static final String SI_PREFIX = "http://wandora.org/si/hcalendar/"; public int progress = 0; public int eventcount = 0; private static final int STATE_START=1111; private static final int STATE_VCALENDAR = 999; private static final int STATE_VEVENT = 998; private static final int STATE_SUMMARY=1; private static final int STATE_LOCATION=2; private static final int STATE_URL=3; private static final int STATE_URL_A=35; private static final int STATE_DTEND=4; private static final int STATE_DURATION=5; private static final int STATE_RDATE=6; private static final int STATE_RRULE=7; private static final int STATE_CATEGORY=10; private static final int STATE_DESCRIPTION=11; private static final int STATE_UID=12; private static final int STATE_LATITUDE=13; private static final int STATE_LONGITUDE=14; private static final int STATE_DTSTART=15; private static final int STATE_ABBR=9998; private static final int STATE_OTHER=9999; private int state=STATE_START; private String dtstart; private String summary; private String location; private String url; private String url_href; private String dtend; private String duration; private String rdate; private String rrule; private String category; private String description; private String uid; private String latitude; private String longitude; private Association association; private Stack<Integer> stateStack; // ------------------------------------------------------------------------- public HCalendarParser(TopicMap tm, HCalendarExtractor parent ) { this.tm=tm; this.parent=parent; dtstart = null; summary = null; location = null; url = null; url_href = null; dtend = null; duration = null; rdate = null; rrule = null; category = null; description = null; uid = null; latitude = null; longitude = null; association = null; stateStack = new Stack<>(); } // ------------------------------------------------------------------------- public void startDocument() throws SAXException { } public void endDocument() throws SAXException { } public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { stateStack.push(Integer.valueOf(state)); String clas = atts.getValue("class"); if(parent.forceStop()){ throw new SAXException("User interrupt"); } if(debug) System.out.print("qname=="+ qName); if(debug) System.out.print(", class=="+ clas); if(debug) System.out.print(", sstate="+state); switch(state) { case STATE_START: { if("vcalendar".equalsIgnoreCase(clas)) { state = STATE_VCALENDAR; } else if("vevent".equalsIgnoreCase(clas)) { state = STATE_VEVENT; } break; } case STATE_VCALENDAR: { if("vevent".equalsIgnoreCase(clas)) { state = STATE_VEVENT; } break; } case STATE_VEVENT: { if("abbr".equalsIgnoreCase(qName)) { String title = atts.getValue("title"); if(clas != null) { if("dtstart".equalsIgnoreCase(clas)) { state = STATE_ABBR; dtstart = title; } else if("summary".equalsIgnoreCase(clas)) { state = STATE_ABBR; summary = title; } else if("location".equalsIgnoreCase(clas)) { state = STATE_ABBR; location = title; } else if("url".equalsIgnoreCase(clas)) { state = STATE_ABBR; url = title; url_href = atts.getValue("href"); } else if("dtend".equalsIgnoreCase(clas)) { state = STATE_ABBR; dtend = title; } else if("duration".equalsIgnoreCase(clas)) { state = STATE_ABBR; duration = title; } else if("rdate".equalsIgnoreCase(clas)) { state = STATE_ABBR; rdate = title; } else if("rrule".equalsIgnoreCase(clas)) { state = STATE_ABBR; rrule = title; } else if("category".equalsIgnoreCase(clas)) { state = STATE_ABBR; category = title; } else if("description".equalsIgnoreCase(clas)) { state = STATE_ABBR; description = title; } else if("uid".equalsIgnoreCase(clas)) { state = STATE_ABBR; uid = title; } else if("latitude".equalsIgnoreCase(clas)) { state = STATE_ABBR; latitude = title; } else if("longitude".equalsIgnoreCase(clas)) { state = STATE_ABBR; longitude = title; } } } else { if(clas != null) { if("dtstart".equalsIgnoreCase(clas)) { state = STATE_DTSTART; } else if("summary".equalsIgnoreCase(clas)) { state = STATE_SUMMARY; } else if("location".equalsIgnoreCase(clas)) { state = STATE_LOCATION; } else if("url".equalsIgnoreCase(clas)) { url_href = atts.getValue("href"); state = STATE_URL; } else if("dtend".equalsIgnoreCase(clas)) { state = STATE_DTEND; } else if("duration".equalsIgnoreCase(clas)) { state = STATE_DURATION; } else if("rdate".equalsIgnoreCase(clas)) { state = STATE_RDATE; } else if("rrule".equalsIgnoreCase(clas)) { state = STATE_RRULE; } else if("category".equalsIgnoreCase(clas)) { state = STATE_CATEGORY; } else if("description".equalsIgnoreCase(clas)) { state = STATE_DESCRIPTION; } else if("uid".equalsIgnoreCase(clas)) { state = STATE_UID; } else if("latitude".equalsIgnoreCase(clas)) { state = STATE_LATITUDE; } else if("longitude".equalsIgnoreCase(clas)) { state = STATE_LONGITUDE; } } } break; } case STATE_URL: { if("a".equalsIgnoreCase(qName)) { url_href = atts.getValue("href"); state = STATE_URL_A; break; } } } if(debug) System.out.println(", nstate="+state); } public void endElement(String uri, String localName, String qName) throws SAXException { switch(state) { case STATE_VCALENDAR: { if(!stateStack.contains(Integer.valueOf(STATE_VCALENDAR))) { processEvent(); } break; } case STATE_VEVENT: { if(!stateStack.contains(Integer.valueOf(STATE_VEVENT))) { processEvent(); } break; } } popState(); } public void characters(char[] data, int start, int length) throws SAXException { switch(state) { case STATE_DTSTART: { dtstart = catenate(dtstart, data, start, length); break; } case STATE_SUMMARY: { summary = catenate(summary, data, start, length); break; } case STATE_LOCATION: { location = catenate(location, data, start, length); break; } case STATE_URL: { url = catenate(url, data, start, length); break; } case STATE_DTEND: { dtend = catenate(dtend, data, start, length); break; } case STATE_DURATION: { duration = catenate(duration, data, start, length); break; } case STATE_RDATE: { rdate = catenate(rdate, data, start, length); break; } case STATE_RRULE: { rrule = catenate(rrule, data, start, length); break; } case STATE_CATEGORY: { category = catenate(category, data, start, length); break; } case STATE_DESCRIPTION: { description = catenate(description, data, start, length); break; } case STATE_UID: { uid = catenate(uid, data, start, length); break; } case STATE_LATITUDE: { latitude = catenate(latitude, data, start, length); break; } case STATE_LONGITUDE: { longitude = catenate(longitude, data, start, length); break; } } } private String catenate(String base, char[] data, int start, int length) { if(base == null) base = ""; base = base + new String(data,start,length); if(debug) System.out.println(" string=="+base); return base; } 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 {} public void processEvent() { if(dtstart != null && summary != null) { eventcount++; try { Topic eventTypeTopic = createTopic(tm, SI_PREFIX+"event", "event"); Topic eventTopic = createTopic(tm, SI_PREFIX+"event/"+dtstart, dtstart+" - "+summary, new Topic[] { eventTypeTopic } ); parent.log("Creating HCalendar event '"+getTopicName(eventTopic)+"'."); if(summary != null) { // **** ALWAYS TRUE **** Topic summaryType = createTopic(tm, SI_PREFIX+"summary", "summary"); parent.setData(eventTopic, summaryType, "en", summary); } if(dtstart != null) { // **** ALWAYS TRUE **** try { Topic associationTypeTopic = createTopic(tm, SI_PREFIX+"dtstart", "event-start-time"); Topic playerTopic = createTopic(tm, SI_PREFIX+"dtstart/"+dtstart, dtstart); association = tm.createAssociation(associationTypeTopic); association.addPlayer(eventTopic, eventTypeTopic); association.addPlayer(playerTopic, associationTypeTopic); } catch(Exception e) { parent.log(e); } } if(location != null) { try { Topic associationTypeTopic = createTopic(tm, SI_PREFIX+"location", "location"); Topic playerTopic = createTopic(tm, SI_PREFIX+"location/"+location, location); association = tm.createAssociation(associationTypeTopic); association.addPlayer(eventTopic, eventTypeTopic); association.addPlayer(playerTopic, associationTypeTopic); } catch(Exception e) { parent.log(e); } } if(url != null || url_href != null) { try { if(url_href != null) url = url_href; eventTopic.setSubjectLocator(new org.wandora.topicmap.Locator(url)); } catch(Exception e) { parent.log(e); } } if(dtend != null) { try { Topic associationTypeTopic = createTopic(tm, SI_PREFIX+"dtend", "event-end-time"); Topic playerTopic = createTopic(tm, SI_PREFIX+"dtend/"+dtend, dtend); association = tm.createAssociation(associationTypeTopic); association.addPlayer(eventTopic, eventTypeTopic); association.addPlayer(playerTopic, associationTypeTopic); } catch(Exception e) { parent.log(e); } } if(duration != null) { try { Topic associationTypeTopic = createTopic(tm, SI_PREFIX+"duration", "event-duration"); Topic playerTopic = createTopic(tm, SI_PREFIX+"duration/"+duration, duration); association = tm.createAssociation(associationTypeTopic); association.addPlayer(eventTopic, eventTypeTopic); association.addPlayer(playerTopic, associationTypeTopic); } catch(Exception e) { parent.log(e); } } if(rdate != null) { try { Topic associationTypeTopic = createTopic(tm, SI_PREFIX+"rdate", "repeat-date"); Topic playerTopic = createTopic(tm, SI_PREFIX+"rdate/"+rdate, rdate); association = tm.createAssociation(associationTypeTopic); association.addPlayer(eventTopic, eventTypeTopic); association.addPlayer(playerTopic, associationTypeTopic); } catch(Exception e) { parent.log(e); } } if(rrule != null) { try { Topic associationTypeTopic = createTopic(tm, SI_PREFIX+"rrule", "repeat-rule"); Topic playerTopic = createTopic(tm, SI_PREFIX+"rrule/"+rrule, rrule); association = tm.createAssociation(associationTypeTopic); association.addPlayer(eventTopic, eventTypeTopic); association.addPlayer(playerTopic, associationTypeTopic); } catch(Exception e) { parent.log(e); } } if(category != null) { try { Topic associationTypeTopic = createTopic(tm, SI_PREFIX+"category", "category"); Topic playerTopic = createTopic(tm, SI_PREFIX+"category/"+category, category); association = tm.createAssociation(associationTypeTopic); association.addPlayer(eventTopic, eventTypeTopic); association.addPlayer(playerTopic, associationTypeTopic); } catch(Exception e) { parent.log(e); } } if(description != null) { try { Topic descriptionType = createTopic(tm, SI_PREFIX+"description", "description"); parent.setData(eventTopic, descriptionType, "en", description); } catch(Exception e) { parent.log(e); } } if(uid != null) { try { eventTopic.addSubjectIdentifier(new org.wandora.topicmap.Locator(SI_PREFIX+"uid/"+uid)); } catch(Exception e) { parent.log(e); } } if(latitude != null && longitude != null) { Topic associationTypeTopic = createTopic(tm, SI_PREFIX+"geo-location", "geo-location"); Topic latitudeTypeTopic = createTopic(tm, SI_PREFIX+"latitude", "latitude"); Topic longitudeTypeTopic = createTopic(tm, SI_PREFIX+"longitude", "longitude"); Topic latitudeTopic = createTopic(tm, SI_PREFIX+"latitude/"+latitude, latitude, new Topic[] { latitudeTypeTopic }); Topic longitudeTopic = createTopic(tm, SI_PREFIX+"longitude/"+longitude, longitude, new Topic[] { longitudeTypeTopic }); association = tm.createAssociation(associationTypeTopic); association.addPlayer(latitudeTopic, latitudeTypeTopic); association.addPlayer(longitudeTopic, longitudeTypeTopic); association.addPlayer(eventTopic, eventTypeTopic); } } catch(Exception e) { parent.log(e); } dtstart = null; summary = null; location = null; url = null; url_href = null; dtend = null; duration = null; rdate = null; rrule = null; category = null; description = null; uid = null; latitude = null; longitude = null; progress++; } else { parent.log("Rejecting HCalendar event without obligatory dtstart or/and summary data!"); } } private void popState() { if(!stateStack.empty()) { state = ((Integer) stateStack.pop()).intValue(); if(debug) System.out.println(" popping state:"+state); } else { state = STATE_START; } } // -------------------- public Topic createTopic(TopicMap topicMap, String si, String baseName) throws TopicMapException { return createTopic(topicMap, si, baseName, null); } public Topic createTopic(TopicMap topicMap, String si, String baseName, Topic[] types) throws TopicMapException { Topic t = null; if(baseName != null && baseName.length() > 0 && si != null && si.length() > 0) { si = TopicTools.cleanDirtyLocator(si); t = topicMap.getTopic(si); if(t == null) { t = topicMap.getTopicWithBaseName(baseName); if(t == null) { t = topicMap.createTopic(); t.setBaseName(baseName); } t.addSubjectIdentifier(new org.wandora.topicmap.Locator(si)); } if(types != null) { for(int i=0; i<types.length; i++) { Topic typeTopic = types[i]; if(typeTopic != null) { t.addType(typeTopic); } } } } if(t == null) { System.out.println("Failed to create topic for basename '"+baseName+"' and si '"+si+"'."); } return t; } } }
30,246
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
JsoupGeoExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/microformats/JsoupGeoExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.microformats; import java.util.HashMap; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author Eero */ public class JsoupGeoExtractor extends AbstractJsoupMicroformatExtractor{ private static final long serialVersionUID = 1L; private static final String SI_PREFIX = "http://wandora.org/si/adr/"; private HashMap<String,Topic> typeTopics; private TopicMap tm; @Override public String getName() { return "Geo microformat extractor"; } @Override public String getDescription() { return "Converts Geo microformat HTML snippets to Topic Maps."; } @Override protected String[][] getTypeStrings() { return TYPE_STRINGS; } @Override protected HashMap<String, Topic> getTypeTopics() { return typeTopics; } @Override protected TopicMap getTopicMap() { return tm; } @Override protected String getSIPrefix() { return SI_PREFIX; } @Override public boolean extractTopicsFrom(Document d, String u, TopicMap t) throws Exception { tm = t; try { //typeTopics = generateTypes(); typeTopics = new HashMap<String, Topic>(); Topic document = getOrCreateTopic(tm, d.baseUri(), d.title()); Topic docType = getType("document"); document.addType(docType); Elements geos = d.select(".geo"); for(Element geo : geos){ try { parseGeo(document,geo, "document"); } catch (TopicMapException tme) { log(tme); } } } catch (TopicMapException tme) { log(tme); return false; } return true; } }
2,861
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
JsoupHCalendarExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/microformats/JsoupHCalendarExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.microformats; import java.util.HashMap; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.wandora.topicmap.Association; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author Eero */ public class JsoupHCalendarExtractor extends AbstractJsoupMicroformatExtractor { private static final long serialVersionUID = 1L; @Override public String getName() { return "HCalendar microformat extractor"; } @Override public String getDescription() { return "Converts HCalendar Microformat HTML snippets to Topic Maps."; } private static final String SI_PREFIX = "http://wandora.org/si/hcalendar/"; private static final String[] EVENT_PROPS = { "dstart", "dtend", "duration", "rdate", "rrule", "location", "category", "description", "url", "uid" }; private HashMap<String,Topic> typeTopics; private TopicMap tm; @Override public boolean extractTopicsFrom(Document d, String u, TopicMap t){ tm = t; typeTopics = new HashMap<String, Topic>(); Elements calendars = d.select(".vcalendar"); if(calendars.isEmpty()) { try { parseCalendar(d); } catch (TopicMapException tme) { log(tme.getMessage()); } } else { for(Element calendar: calendars) { try { parseCalendar(calendar); } catch (TopicMapException tme) { log(tme.getMessage()); } } } return true; } private void parseCalendar(Document document) throws TopicMapException { String title = document.title(); Topic type = getType("vcalendar"); Topic topic = getOrCreateTopic(tm,null, title); topic.addType(type); parseCalendar(topic, document.body()); } private void parseCalendar(Element element) throws TopicMapException { Topic type = getType("vcalendar"); Topic topic = getOrCreateTopic(tm,null); topic.addType(type); parseCalendar(topic, element); } private void parseCalendar(Topic topic, Element element) throws TopicMapException{ Elements events = element.select(".vevent"); for(Element event: events){ try { parseEvent(topic, event); } catch (TopicMapException tme) { log(tme); } } } private void parseEvent(Topic calendar, Element element) throws TopicMapException{ Topic eventType = getType("vevent"); Topic calendarType = getType("vcalendar"); Topic topic = getOrCreateTopic(tm, null); topic.addType(eventType); Association a = tm.createAssociation(eventType); a.addPlayer(topic, eventType); a.addPlayer(calendar, calendarType); for (int i = 0; i < EVENT_PROPS.length; i++) { String propName = EVENT_PROPS[i]; Elements props = element.select("." + propName); for(Element prop: props) { try { addProp(topic, propName, prop); } catch (TopicMapException tme) { log(tme); } } } } @Override protected String[][] getTypeStrings() { return TYPE_STRINGS; } @Override protected HashMap<String, Topic> getTypeTopics() { return typeTopics; } @Override protected TopicMap getTopicMap() { return tm; } @Override protected String getSIPrefix() { return SI_PREFIX; } }
4,845
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
GeoExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/microformats/GeoExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * GeoExtractor.java * * Created on 13. joulukuuta 2007, 12:00 * */ package org.wandora.application.tools.extractors.microformats; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.Properties; import javax.swing.Icon; import org.w3c.tidy.Tidy; import org.wandora.application.WandoraTool; import org.wandora.application.gui.UIBox; import org.wandora.application.tools.extractors.AbstractExtractor; import org.wandora.topicmap.Association; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicTools; 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; /** * This class implements a Wandora extractor for geo-location microformat * described in http://microformats.org/wiki/geo * * @author akivela */ public class GeoExtractor extends AbstractExtractor implements WandoraTool { private static final long serialVersionUID = 1L; /** Creates a new instance of GeoExtractor */ public GeoExtractor() { } public String getName() { return "Geo microformat extractor"; } public String getDescription() { return "Converts Geo Microformat HTML snippets to Topic Map associations."; } @Override public boolean useTempTopicMap(){ return false; } public static final String[] contentTypes=new String[] { "text/html" }; @Override public String[] getContentTypes() { return contentTypes; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_microformat.png"); } 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 boolean _extractTopicsFrom(InputStream in, TopicMap topicMap) throws Exception { Tidy tidy = null; String tidyXML = null; try { Properties tidyProps = new Properties(); tidyProps.put("trim-empty-elements", "no"); tidy = new Tidy(); tidy.setConfigurationFromProps(tidyProps); tidy.setXmlOut(true); tidy.setXmlPi(true); tidy.setTidyMark(false); ByteArrayOutputStream tidyOutput = null; tidyOutput = new ByteArrayOutputStream(); tidy.parse(in, tidyOutput); tidyXML = tidyOutput.toString(); } catch(Error er) { log("Unable to preprocess HTML with JTidy!"); log(er); } catch(Exception e) { log("Unable to preprocess HTML with JTidy!"); log(e); } if(tidyXML == null) { log("Trying to read HTML without preprocessing!"); tidyXML = IObox.loadFile(new InputStreamReader(in)); } //tidyXML = tidyXML.replace("&", "&amp;"); tidyXML = tidyXML.replace("&amp;deg;", "&#0176;"); /* System.out.println("------"); System.out.println(tidyXML); System.out.println("------"); */ 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(); GeoParser parserHandler = new GeoParser(topicMap,this); reader.setContentHandler(parserHandler); reader.setErrorHandler(parserHandler); try{ reader.parse(new InputSource(new ByteArrayInputStream(tidyXML.getBytes()))); } catch(Exception e){ if(!(e instanceof SAXException) || !e.getMessage().equals("User interrupt")) log(e); } log("Total " + parserHandler.progress + " geo coordinates found!"); return true; } public static class GeoParser implements org.xml.sax.ContentHandler, org.xml.sax.ErrorHandler { private TopicMap tm = null; private GeoExtractor parent = null; public static final String SI_PREFIX = "http://wandora.org/si/geo/"; public int progress = 0; private static final int STATE_START=1111; private static final int STATE_LATITUDE=1; private static final int STATE_LONGITUDE=2; private static final int STATE_OTHER=9999; private int state=STATE_START; private String latitude; private String longitude; private String location; private Association association; // ------------------------------------------------------------------------- public GeoParser(TopicMap tm, GeoExtractor parent ) { this.tm=tm; this.parent=parent; latitude = null; longitude = null; location = null; association = null; } // ------------------------------------------------------------------------- public void startDocument() throws SAXException { } public void endDocument() throws SAXException { } public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { //System.out.println("qname=="+ qName); //System.out.println("atts=="+ atts); if(parent.forceStop()){ throw new SAXException("User interrupt"); } if("span".equalsIgnoreCase(qName)) { String attribute = atts.getValue("class"); if(attribute != null) { if("latitude".equalsIgnoreCase(attribute.toString())) { state = STATE_LATITUDE; latitude = null; } else if("longitude".equalsIgnoreCase(attribute.toString())) { state = STATE_LONGITUDE; longitude = null; } } } else if("abbr".equalsIgnoreCase(qName)) { String clas = atts.getValue("class"); String title = atts.getValue("title"); if(clas != null) { if("latitude".equalsIgnoreCase(clas)) { latitude = title; } else if("longitude".equalsIgnoreCase(clas)) { longitude = title; } else if("geo".equalsIgnoreCase(clas)) { if(title != null) { String[] coords = title.split(";"); if(coords.length > 0) { latitude = coords[0]; } if(coords.length > 1) { longitude = coords[1]; } } } } } } public void endElement(String uri, String localName, String qName) throws SAXException { //System.out.println("handleEndTag: " + qName); if("span".equalsIgnoreCase(qName)) { processCoordinates(); state = STATE_OTHER; } if("abbr".equalsIgnoreCase(qName)) { processCoordinates(); } } public void characters(char[] data, int start, int length) throws SAXException { switch(state) { case STATE_LONGITUDE: { if(longitude == null) longitude = ""; longitude = longitude + new String(data,start,length); break; } case STATE_LATITUDE: { if(latitude == null) latitude = ""; latitude = latitude + new String(data,start,length); break; } case STATE_START: { if(location == null) location = ""; location = location + new String(data,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 {} public void processCoordinates() { if(latitude != null && longitude != null) { if(latitude.length() > 0 && longitude.length() > 0) { try { latitude = latitude.trim(); longitude = longitude.trim(); Topic associationTypeTopic = createTopic(tm, SI_PREFIX+"geo-location", "geo-location"); Topic latitudeTypeTopic = createTopic(tm, SI_PREFIX+"latitude", "latitude"); Topic longitudeTypeTopic = createTopic(tm, SI_PREFIX+"longitude", "longitude"); Topic locationTypeTopic = createTopic(tm, SI_PREFIX+"location", "location"); if(location != null) location = location.trim(); if(location == null || location.length() < 1) { location = "location at "+latitude+","+longitude; } location = location.trim(); if(location.endsWith(":")) location = location.substring(0, location.length()-1); location = location.trim(); parent.log("Creating geo-location for '"+location+"' at "+latitude+";"+longitude); Topic locationTopic = createTopic(tm, SI_PREFIX+"location/"+location, location, new Topic[] { locationTypeTopic } ); Topic latitudeTopic = createTopic(tm, SI_PREFIX+"latitude/"+latitude, latitude, new Topic[] { latitudeTypeTopic }); Topic longitudeTopic = createTopic(tm, SI_PREFIX+"longitude/"+longitude, longitude, new Topic[] { longitudeTypeTopic }); association = tm.createAssociation(associationTypeTopic); association.addPlayer(latitudeTopic, latitudeTypeTopic); association.addPlayer(longitudeTopic, longitudeTypeTopic); association.addPlayer(locationTopic, locationTypeTopic); latitude = null; longitude = null; location = null; progress++; } catch(Exception e) { parent.log(e); } } } } // -------------------- public Topic createTopic(TopicMap topicMap, String si, String baseName) throws TopicMapException { return createTopic(topicMap, si, baseName, null); } public Topic createTopic(TopicMap topicMap, String si, String baseName, Topic[] types) throws TopicMapException { Topic t = null; if(baseName != null && baseName.length() > 0 && si != null && si.length() > 0) { si = TopicTools.cleanDirtyLocator(si); t = topicMap.getTopic(si); if(t == null) { t = topicMap.getTopicWithBaseName(baseName); if(t == null) { t = topicMap.createTopic(); t.setBaseName(baseName); } t.addSubjectIdentifier(new org.wandora.topicmap.Locator(si)); } if(types != null) { for(int i=0; i<types.length; i++) { Topic typeTopic = types[i]; if(typeTopic != null) { t.addType(typeTopic); } } } } if(t == null) { System.out.println("Failed to create topic for basename '"+baseName+"' and si '"+si+"'."); } return t; } } }
14,731
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
HCardExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/microformats/HCardExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * HCardExtractor.java * */ package org.wandora.application.tools.extractors.microformats; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.Properties; import java.util.Stack; import javax.swing.Icon; import org.w3c.tidy.Tidy; import org.wandora.application.WandoraTool; import org.wandora.application.gui.UIBox; import org.wandora.application.tools.extractors.AbstractExtractor; import org.wandora.topicmap.Association; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicTools; 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 HCardExtractor extends AbstractExtractor implements WandoraTool { private static final long serialVersionUID = 1L; /** Creates a new instance of HCardExtractor */ public HCardExtractor() { } public String getName() { return "Hcard microformat extractor"; } public String getDescription() { return "Converts HCard Microformat HTML snippets to Topic Maps."; } @Override public boolean useTempTopicMap(){ return false; } public static final String[] contentTypes=new String[] { "text/html" }; @Override public String[] getContentTypes() { return contentTypes; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_microformat.png"); } 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 boolean _extractTopicsFrom(InputStream in, TopicMap topicMap) throws Exception { Tidy tidy = null; String tidyXML = null; try { Properties tidyProps = new Properties(); tidyProps.put("trim-empty-elements", "no"); tidy = new Tidy(); tidy.setConfigurationFromProps(tidyProps); tidy.setXmlOut(true); tidy.setXmlPi(true); tidy.setTidyMark(false); ByteArrayOutputStream tidyOutput = null; tidyOutput = new ByteArrayOutputStream(); tidy.parse(in, tidyOutput); tidyXML = tidyOutput.toString(); } catch(Error er) { log("Unable to preprocess HTML with JTidy!"); log(er); } catch(Exception e) { log("Unable to preprocess HTML with JTidy!"); log(e); } if(tidyXML == null) { log("Trying to read HTML without preprocessing!"); tidyXML = IObox.loadFile(new InputStreamReader(in)); } //tidyXML = tidyXML.replace("&", "&amp;"); //tidyXML = HTMLEntitiesCoder.decode(tidyXML); //tidyXML = tidyXML.replace("&amp;deg;", "&#0176;"); System.out.println("------"); System.out.println(tidyXML); System.out.println("------"); 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(); HCardParser parserHandler = new HCardParser(topicMap,this); reader.setContentHandler(parserHandler); reader.setErrorHandler(parserHandler); try{ reader.parse(new InputSource(new ByteArrayInputStream(tidyXML.getBytes()))); } catch(Exception e){ if(!(e instanceof SAXException) || !e.getMessage().equals("User interrupt")) log(e); } log("Total " + parserHandler.progress + " HCard entries found!"); return true; } public class HCardParser implements org.xml.sax.ContentHandler, org.xml.sax.ErrorHandler { private static final boolean debug = true; private TopicMap tm = null; private HCardExtractor parent = null; public static final String SI_PREFIX = "http://wandora.org/si/hcard/"; public static final String ABBR = "abbr"; public int progress = 0; private static final int STATE_START=11111; private static final int STATE_VCARD=10; private static final int STATE_FN=1000; private static final int STATE_N=1010; private static final int STATE_N_FAMILY=1011; private static final int STATE_N_GIVEN=1012; private static final int STATE_N_ADDITIONAL=1013; private static final int STATE_N_HONORIFIC_PREFIX=1014; private static final int STATE_N_HONORIFIC_SUFFIX=1015; private static final int STATE_NICKNAME=1020; private static final int STATE_SORTSTRING=1030; private static final int STATE_ADR=20; private static final int STATE_ADR_TYPE=21; private static final int STATE_ADR_VALUE=22; private static final int STATE_ADR_POST_OFFICE_BOX=23; private static final int STATE_ADR_EXTENDED_ADDRESS=24; private static final int STATE_ADR_STREET_ADDRESS=25; private static final int STATE_ADR_LOCALITY=26; private static final int STATE_ADR_REGION=27; private static final int STATE_ADR_POSTAL_CODE=28; private static final int STATE_ADR_COUNTRY_NAME=29; private static final int STATE_TEL=30; private static final int STATE_TEL_TYPE=31; private static final int STATE_TEL_VALUE=32; private static final int STATE_EMAIL=40; private static final int STATE_EMAIL_TYPE=41; private static final int STATE_EMAIL_VALUE=72; private static final int STATE_ORG=50; private static final int STATE_ORG_UNIT=51; private static final int STATE_ORG_NAME=52; private static final int STATE_URL=60; private static final int STATE_LABEL=80; private static final int STATE_GEO=80; private static final int STATE_GEO_LATITUDE=81; private static final int STATE_GEO_LONGITUDE=82; private static final int STATE_TZ=85; private static final int STATE_PHOTO=90; private static final int STATE_LOGO=91; private static final int STATE_SOUND=92; private static final int STATE_BDAY=93; private static final int STATE_TITLE=100; private static final int STATE_ROLE=110; private static final int STATE_CATEGORY=120; private static final int STATE_NOTE=130; private static final int STATE_CLASS=140; private static final int STATE_KEY=150; private static final int STATE_MAILER=160; private static final int STATE_UID=170; private static final int STATE_REV=180; private static final int STATE_OTHER=99999; private Name n; private String nickname; private ArrayList<String> nicknames; private String url; private ArrayList<String> urls; private Email email; private ArrayList<Email> emails; private Tel tel; private ArrayList<Tel> tels; private Adr adr; private ArrayList<Adr> adrs; private String label; private ArrayList<String> labels; private String latitude; private String longitude; private String tz; private String photo; private ArrayList<String> photos; private String logo; private ArrayList<String> logos; private String sound; private ArrayList<String> sounds; private String bday; private String title; private ArrayList<String> titles; private String role; private ArrayList<String> roles; private Org org; private ArrayList<Org> orgs; private String category; private ArrayList<String> categories; private String note; private ArrayList<String> notes; private String uid; private String classs; private String key; private ArrayList<String> keys; private String mailer; private ArrayList<String> mailers; private String rev; private ArrayList<String> revs; private Collection<Integer> state = null; private Stack<Collection<Integer>> stateStack = null; private int isAbbr = 0; // ------------------------------------------------------------------------- public HCardParser(TopicMap tm, HCardExtractor parent ) { this.tm=tm; this.parent=parent; initCard(); stateStack = new Stack<>(); state = new ArrayList<Integer>(); state.add(Integer.valueOf(STATE_START)); } // ------------------------------------------------------------------------- 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"); } stateStack.push(state); if(ABBR.equalsIgnoreCase(qName)) { isAbbr++; } String clas = atts.getValue("class"); String abbrTitle = atts.getValue("title"); if(debug) System.out.print("qname=="+ qName); if(debug) System.out.print(", class=="+ clas); if(debug) System.out.print(", sstate="+state); if(clas == null) { if(debug) System.out.println(", no class here - rejecting"); return; } String[] clases = clas.split(" "); Collection<Integer> newState = new ArrayList<>(); for(int i=0; i<clases.length; i++) { Iterator<Integer> stateIter = state.iterator(); while(stateIter.hasNext()) { Integer singleState = stateIter.next(); int singleStateInt = singleState.intValue(); switch(singleStateInt) { case STATE_START: { if("vcard".equalsIgnoreCase(clases[i])) { initCard(); newState.add(Integer.valueOf(STATE_VCARD)); } else { newState.add(Integer.valueOf(STATE_START)); } break; } case STATE_VCARD: { if("fn".equalsIgnoreCase(clases[i])) { if(n == null) n = new Name(); if(isAbbr > 0) { n.fn = abbrTitle; } newState.add(Integer.valueOf(STATE_FN)); } else if("n".equalsIgnoreCase(clases[i])) { if(n == null) n = new Name(); if(isAbbr > 0) { n.name = abbrTitle; } newState.add(Integer.valueOf(STATE_N)); } else if("nickname".equalsIgnoreCase(clases[i])) { if(nickname != null) { nicknames.add(nickname); nickname = null; } if(isAbbr > 0) { nickname = abbrTitle; } newState.add(Integer.valueOf(STATE_NICKNAME)); } else if("sort-string".equalsIgnoreCase(clases[i])) { if(n == null) n = new Name(); if(isAbbr > 0) { n.sortString = abbrTitle; } newState.add(Integer.valueOf(STATE_SORTSTRING)); } else if("url".equalsIgnoreCase(clases[i])) { if(url != null) { urls.add(url); url = null; } if(isAbbr > 0) { url = abbrTitle; } if("a".equalsIgnoreCase(qName)) { url = atts.getValue("href"); } newState.add(Integer.valueOf(STATE_URL)); } else if("email".equalsIgnoreCase(clases[i])) { if(email != null) { emails.add(email); } email = new Email(); if(isAbbr > 0) { email.value = abbrTitle; } if("a".equalsIgnoreCase(qName)) { email.value = atts.getValue("href"); if(email.value != null) { if(email.value.startsWith("mailto:")) { email.value = email.value.substring(7); } } } newState.add(Integer.valueOf(STATE_EMAIL)); } else if("tel".equalsIgnoreCase(clases[i])) { if(tel != null) { tels.add(tel); } tel = new Tel(); if(isAbbr > 0) { tel.value = abbrTitle; } newState.add(Integer.valueOf(STATE_TEL)); } else if("adr".equalsIgnoreCase(clases[i])) { if(adr != null) { adrs.add(adr); } adr = new Adr(); newState.add(Integer.valueOf(STATE_ADR)); } else if("label".equalsIgnoreCase(clases[i])) { if(label != null) { labels.add(label); label = null; } if(isAbbr > 0) { label = abbrTitle; } newState.add(Integer.valueOf(STATE_LABEL)); } else if("geo".equalsIgnoreCase(clases[i])) { latitude = null; longitude = null; if(isAbbr > 0 && abbrTitle != null) { String[] geo = abbrTitle.split(","); if(geo.length > 1) { latitude = geo[0]; longitude = geo[1]; } } newState.add(Integer.valueOf(STATE_GEO)); } else if("tz".equalsIgnoreCase(clases[i])) { tz = null; if(isAbbr > 0) { tz = abbrTitle; } newState.add(Integer.valueOf(STATE_TZ)); } else if("photo".equalsIgnoreCase(clases[i])) { if(photo != null) { photos.add(photo); photo = null; if(isAbbr > 0) { photo = abbrTitle; } if("img".equalsIgnoreCase(qName)) { photo = atts.getValue("src"); } else if("object".equalsIgnoreCase(qName)) { photo = atts.getValue("data"); } else if("a".equalsIgnoreCase(qName)) { photo = atts.getValue("href"); } } newState.add(Integer.valueOf(STATE_PHOTO)); } else if("logo".equalsIgnoreCase(clases[i])) { if(logo != null) { logos.add(logo); logo = null; if(isAbbr > 0) { logo = abbrTitle; } if("img".equalsIgnoreCase(qName)) { logo = atts.getValue("src"); } else if("object".equalsIgnoreCase(qName)) { logo = atts.getValue("data"); } else if("a".equalsIgnoreCase(qName)) { logo = atts.getValue("href"); } } newState.add(Integer.valueOf(STATE_LOGO)); } else if("sound".equalsIgnoreCase(clases[i])) { if(sound != null) { sounds.add(sound); sound = null; if(isAbbr > 0) { sound = abbrTitle; } if("img".equalsIgnoreCase(qName)) { sound = atts.getValue("src"); } else if("object".equalsIgnoreCase(qName)) { sound = atts.getValue("data"); } else if("a".equalsIgnoreCase(qName)) { sound = atts.getValue("href"); } } newState.add(Integer.valueOf(STATE_SOUND)); } else if("bday".equalsIgnoreCase(clases[i])) { bday = null; if("abbr".equalsIgnoreCase(qName)) { bday = abbrTitle; } newState.add(Integer.valueOf(STATE_BDAY)); } else if("title".equalsIgnoreCase(clases[i])) { if(title != null) { titles.add(title); title = null; } if(isAbbr > 0) { title = abbrTitle; } newState.add(Integer.valueOf(STATE_TITLE)); } else if("role".equalsIgnoreCase(clases[i])) { if(role != null) { roles.add(role); role = null; } if(isAbbr > 0) { role = abbrTitle; } newState.add(Integer.valueOf(STATE_ROLE)); } else if("org".equalsIgnoreCase(clases[i])) { if(org != null) { orgs.add(org); } org = new Org(); if(isAbbr > 0) { org.name = abbrTitle; } newState.add(Integer.valueOf(STATE_ORG)); } else if("category".equalsIgnoreCase(clases[i])) { if(category != null) { categories.add(category); category = null; } if(isAbbr > 0) { category = abbrTitle; } newState.add(Integer.valueOf(STATE_CATEGORY)); } else if("note".equalsIgnoreCase(clases[i])) { if(note != null) { notes.add(note); note = null; } if(isAbbr > 0) { note = abbrTitle; } newState.add(Integer.valueOf(STATE_NOTE)); } else if("class".equalsIgnoreCase(clases[i])) { classs = null; if(isAbbr > 0) { classs = abbrTitle; } newState.add(Integer.valueOf(STATE_CLASS)); } else if("key".equalsIgnoreCase(clases[i])) { if(key != null) { keys.add(key); key = null; } if(isAbbr > 0) { key = abbrTitle; } newState.add(Integer.valueOf(STATE_KEY)); } else if("mailer".equalsIgnoreCase(clases[i])) { if(mailer != null) { mailers.add(mailer); mailer = null; } if(isAbbr > 0) { mailer = abbrTitle; } newState.add(Integer.valueOf(STATE_MAILER)); } else if("uid".equalsIgnoreCase(clases[i])) { uid = null; if(isAbbr > 0) { uid = abbrTitle; } newState.add(Integer.valueOf(STATE_UID)); } else if("rev".equalsIgnoreCase(clases[i])) { if(rev != null) { revs.add(rev); rev = null; } if(isAbbr > 0) { rev = abbrTitle; } newState.add(Integer.valueOf(STATE_REV)); } else if("organization-name".equalsIgnoreCase(clases[i])) { if(org == null) org = new Org(); org.name = null; if(isAbbr > 0) { org.name = abbrTitle; } newState.add(Integer.valueOf(STATE_ORG_NAME)); } else if("organization-unit".equalsIgnoreCase(clases[i])) { if(org == null) org = new Org(); org.unit = null; if(isAbbr > 0) { org.unit = abbrTitle; } newState.add(Integer.valueOf(STATE_ORG_UNIT)); } break; } case STATE_N: { if("family-name".equalsIgnoreCase(clases[i])) { n.familyName = null; if(isAbbr > 0) { n.familyName = abbrTitle; } newState.add(Integer.valueOf(STATE_N_FAMILY)); } else if("given-name".equalsIgnoreCase(clases[i])) { n.givenName = null; if(isAbbr > 0) { n.givenName = abbrTitle; } newState.add(Integer.valueOf(STATE_N_GIVEN)); } else if("additional-name".equalsIgnoreCase(clases[i])) { n.additionalName = null; if(isAbbr > 0) { n.additionalName = abbrTitle; } newState.add(Integer.valueOf(STATE_N_ADDITIONAL)); } else if("honorific-prefix".equalsIgnoreCase(clases[i])) { n.honorifixPrefix = null; if(isAbbr > 0) { n.honorifixPrefix = abbrTitle; } newState.add(Integer.valueOf(STATE_N_HONORIFIC_PREFIX)); } else if("honorific-suffix".equalsIgnoreCase(clases[i])) { n.honorifixSuffix = null; if(isAbbr > 0) { n.honorifixSuffix = abbrTitle; } newState.add(Integer.valueOf(STATE_N_HONORIFIC_SUFFIX)); } break; } case STATE_EMAIL: { if("type".equalsIgnoreCase(clases[i])) { email.type = null; if(isAbbr > 0) { email.type = abbrTitle; } newState.add(Integer.valueOf(STATE_EMAIL_TYPE)); } else if("value".equalsIgnoreCase(clases[i])) { email.value = null; if(isAbbr > 0) { email.value = abbrTitle; } if("a".equalsIgnoreCase(qName)) { email.value = atts.getValue("href"); if(email.value != null) { if(email.value.startsWith("mailto:")) { email.value = email.value.substring(7); } } } newState.add(Integer.valueOf(STATE_EMAIL_VALUE)); } else { email.type = clases[i]; } break; } case STATE_TEL: { if("type".equalsIgnoreCase(clases[i])) { tel.type = null; if(isAbbr > 0) { tel.type = abbrTitle; } newState.add(Integer.valueOf(STATE_TEL_TYPE)); } else if("value".equalsIgnoreCase(clases[i])) { tel.value = null; if(isAbbr > 0) { tel.value = abbrTitle; } newState.add(Integer.valueOf(STATE_TEL_VALUE)); } break; } case STATE_ADR_VALUE: case STATE_ADR: { if("post-office-box".equalsIgnoreCase(clases[i])) { adr.postOfficeBox = null; if(isAbbr > 0) { adr.postOfficeBox = abbrTitle; } newState.add(Integer.valueOf(STATE_ADR_POST_OFFICE_BOX)); } else if("extended-address".equalsIgnoreCase(clases[i])) { adr.extendedAddress = null; if(isAbbr > 0) { adr.extendedAddress = abbrTitle; } newState.add(Integer.valueOf(STATE_ADR_EXTENDED_ADDRESS)); } else if("street-address".equalsIgnoreCase(clases[i])) { adr.streetAddress = null; if(isAbbr > 0) { adr.streetAddress = abbrTitle; } newState.add(Integer.valueOf(STATE_ADR_STREET_ADDRESS)); } else if("locality".equalsIgnoreCase(clases[i])) { adr.locality = null; if(isAbbr > 0) { adr.locality = abbrTitle; } newState.add(Integer.valueOf(STATE_ADR_LOCALITY)); } else if("region".equalsIgnoreCase(clases[i])) { adr.region = null; if(isAbbr > 0) { adr.region = abbrTitle; } newState.add(Integer.valueOf(STATE_ADR_REGION)); } else if("postal-code".equalsIgnoreCase(clases[i])) { adr.postalCode = null; if(isAbbr > 0) { adr.postalCode = abbrTitle; } newState.add(Integer.valueOf(STATE_ADR_POSTAL_CODE)); } else if("country-name".equalsIgnoreCase(clases[i])) { adr.countryName = null; if(isAbbr > 0) { adr.countryName = abbrTitle; } newState.add(Integer.valueOf(STATE_ADR_COUNTRY_NAME)); } else if("type".equalsIgnoreCase(clases[i])) { adr.type = null; if(isAbbr > 0) { adr.type = abbrTitle; } newState.add(Integer.valueOf(STATE_ADR_TYPE)); } else if("value".equalsIgnoreCase(clases[i])) { if(isAbbr > 0) { adr.adr = abbrTitle; } newState.add(Integer.valueOf(STATE_ADR_VALUE)); } break; } case STATE_GEO: { if("latitude".equalsIgnoreCase(clases[i])) { latitude = null; if(isAbbr > 0) { latitude = abbrTitle; } newState.add(Integer.valueOf(STATE_GEO_LATITUDE)); } else if("longitude".equalsIgnoreCase(clases[i])) { latitude = null; if(isAbbr > 0) { longitude = abbrTitle; } newState.add(Integer.valueOf(STATE_GEO_LONGITUDE)); } break; } case STATE_ORG: { if("organization-name".equalsIgnoreCase(clases[i])) { org.name = null; if(isAbbr > 0) { org.name = abbrTitle; } newState.add(Integer.valueOf(STATE_ORG_NAME)); } else if("organization-unit".equalsIgnoreCase(clases[i])) { org.unit = null; if(isAbbr > 0) { org.unit = abbrTitle; } newState.add(Integer.valueOf(STATE_ORG_UNIT)); } break; } } } } if(newState.size() == 0) { newState.addAll(state); } state = new ArrayList<>(); Iterator<Integer> newStateIterator = newState.iterator(); Integer i = null; while(newStateIterator.hasNext()) { i = newStateIterator.next(); if(!state.contains(i)) { state.add(i); } } if(debug) System.out.println(", nstate="+state); } public void endElement(String uri, String localName, String qName) throws SAXException { if(ABBR.equalsIgnoreCase(qName)) { isAbbr--; } Iterator<Integer> stateIter = state.iterator(); while(stateIter.hasNext()) { Integer singleState = stateIter.next(); int singleStateInt = singleState.intValue(); switch(singleStateInt) { case STATE_VCARD: { Iterator<Collection<Integer>> statesLeft = stateStack.iterator(); boolean doProcessCard = true; while(statesLeft.hasNext()) { Collection<Integer> stateLeft = statesLeft.next(); if(stateLeft.contains(Integer.valueOf(STATE_VCARD))) { doProcessCard = false; break; } } if(doProcessCard) processCard(); break; } } } // **** POP STATE **** if(!stateStack.empty()) { state = (ArrayList<Integer>) stateStack.pop(); if(debug) System.out.println(" popping state:"+state); } else { state = new ArrayList<Integer>(); state.add(Integer.valueOf(STATE_START)); } } public void characters(char[] data, int start, int length) throws SAXException { if(isAbbr > 0) return; Iterator<Integer> stateIter = state.iterator(); while(stateIter.hasNext()) { Integer singleState = stateIter.next(); int singleStateInt = singleState.intValue(); // TODO .......................................................... switch(singleStateInt) { // **** NAMES **** case STATE_FN: { n.fn = catenate(n.fn, data, start, length); break; } case STATE_N: { n.name = catenate(n.name, data, start, length); break; } case STATE_N_FAMILY: { n.familyName = catenate(n.familyName, data, start, length); break; } case STATE_N_GIVEN: { n.givenName = catenate(n.givenName, data, start, length); break; } case STATE_N_ADDITIONAL: { n.additionalName = catenate(n.additionalName, data, start, length); break; } case STATE_N_HONORIFIC_PREFIX: { n.honorifixPrefix = catenate(n.honorifixPrefix, data, start, length); break; } case STATE_N_HONORIFIC_SUFFIX: { n.honorifixSuffix = catenate(n.honorifixSuffix, data, start, length); break; } case STATE_NICKNAME: { nickname = catenate(nickname, data, start, length); break; } case STATE_SORTSTRING: { n.sortString = catenate(n.sortString, data, start, length); break; } // **** URL **** case STATE_URL: { url = catenate(url, data, start, length); break; } // **** EMAIL **** case STATE_EMAIL_VALUE: case STATE_EMAIL: { email.value = catenate(email.value, data, start, length); break; } case STATE_EMAIL_TYPE: { email.type = catenate(email.type, data, start, length); break; } // **** TEL **** case STATE_TEL_VALUE: case STATE_TEL: { tel.value = catenate(tel.value, data, start, length); break; } case STATE_TEL_TYPE: { tel.type = catenate(tel.type, data, start, length); break; } // **** ADDRESS **** case STATE_ADR_POST_OFFICE_BOX: { adr.postOfficeBox = catenate(adr.postOfficeBox, data, start, length); break; } case STATE_ADR_EXTENDED_ADDRESS: { adr.extendedAddress = catenate(adr.extendedAddress, data, start, length); break; } case STATE_ADR_STREET_ADDRESS: { adr.streetAddress = catenate(adr.streetAddress, data, start, length); break; } case STATE_ADR_LOCALITY: { adr.locality = catenate(adr.locality, data, start, length); break; } case STATE_ADR_REGION: { adr.region = catenate(adr.region, data, start, length); break; } case STATE_ADR_POSTAL_CODE: { adr.postalCode = catenate(adr.postalCode, data, start, length); break; } case STATE_ADR_COUNTRY_NAME: { adr.countryName = catenate(adr.countryName, data, start, length); break; } case STATE_ADR_TYPE: { adr.type = catenate(adr.type, data, start, length); break; } // **** LABEL **** case STATE_LABEL: { label = catenate(label, data, start, length); break; } // **** GEO **** case STATE_GEO_LATITUDE: { latitude = catenate(latitude, data, start, length); break; } case STATE_GEO_LONGITUDE: { longitude = catenate(longitude, data, start, length); break; } // **** TZ **** case STATE_TZ: { tz = catenate(tz, data, start, length); break; } // **** PHOTO **** case STATE_PHOTO: { photo = catenate(photo, data, start, length); break; } // **** LOGO **** case STATE_LOGO: { logo = catenate(logo, data, start, length); break; } // **** SOUND **** case STATE_SOUND: { sound = catenate(sound, data, start, length); break; } // **** BDAY **** case STATE_BDAY: { bday = catenate(bday, data, start, length); break; } // **** TITLE **** case STATE_TITLE: { title = catenate(title, data, start, length); break; } // **** ROLE **** case STATE_ROLE: { role = catenate(role, data, start, length); break; } // **** ORG **** case STATE_ORG: case STATE_ORG_NAME: { org.name = catenate(org.name, data, start, length); break; } case STATE_ORG_UNIT: { org.unit = catenate(org.unit, data, start, length); break; } // **** CATEGORY **** case STATE_CATEGORY: { category = catenate(category, data, start, length); break; } // **** NOTE **** case STATE_NOTE: { note = catenate(note, data, start, length); break; } // **** CLASS **** case STATE_CLASS: { classs = catenate(classs, data, start, length); break; } // **** KEY **** case STATE_KEY: { key = catenate(key, data, start, length); break; } case STATE_MAILER: { mailer = catenate(mailer, data, start, length); break; } case STATE_UID: { uid = catenate(uid, data, start, length); break; } case STATE_REV: { rev = catenate(rev, data, start, length); break; } } } } private String catenate(String base, char[] data, int start, int length) { if(base == null) base = ""; base = base + new String(data,start,length); if(debug) System.out.println(" string=="+base); return base; } 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 {} private void initCard() { n = new Name(); nickname = null; nicknames = new ArrayList<String>(); url = null; urls = new ArrayList<String>(); email = null; emails = new ArrayList<Email>(); tel = null; tels = new ArrayList<Tel>(); adr = null; adrs = new ArrayList<Adr>(); label = null; labels = new ArrayList<String>(); tz = null; photo = null; photos = new ArrayList<String>(); logo = null; logos = new ArrayList<String>(); sound = null; sounds = new ArrayList<String>(); bday = null; title = null; titles = new ArrayList<String>(); role = null; roles = new ArrayList<String>(); org = null; orgs = new ArrayList<Org>(); category = null; categories = new ArrayList<String>(); note = null; notes = new ArrayList<String>(); uid = null; classs = null; key = null; keys = new ArrayList<String>(); mailer = null; mailers = new ArrayList<String>(); rev = null; revs = new ArrayList<String>(); latitude = null; longitude = null; } public void processCard() { if(nickname != null) { nicknames.add(nickname); nickname = null; } if(url != null) { urls.add(url); url = null; } if(email != null) { emails.add(email); email = null; } if(tel != null) { tels.add(tel); tel = null; } if(adr != null) { adrs.add(adr); adr = null; } if(label != null) { labels.add(label); label = null; } if(photo != null) { photos.add(photo); photo = null; } if(logo != null) { logos.add(logo); logo = null; } if(sound != null) { sounds.add(sound); sound = null; } if(title != null) { titles.add(title); title = null; } if(role != null) { roles.add(role); role = null; } if(org != null) { orgs.add(org); org = null;} if(category != null) { categories.add(category); category = null; } if(note != null) { notes.add(note); note = null; } if(key != null) { keys.add(key); key = null; } if(mailer != null) { mailers.add(mailer); mailer = null; } if(rev != null) { revs.add(rev); rev = null; } if(n != null || org != null) { try { String cardName = ""; if(n != null) { if(n.givenName != null) { cardName += n.givenName.trim(); } if(n.additionalName != null) { if(cardName.length() > 0) { cardName += " " + n.additionalName.trim(); } } if(n.familyName != null) { if(cardName.length() > 0) cardName += " "; cardName += n.familyName.trim(); } if(n.honorifixPrefix != null) { if(cardName.length() > 0) { cardName = n.honorifixPrefix.trim() + " " + cardName; } } if(n.honorifixSuffix != null) { if(cardName.length() > 0) { cardName = cardName + " " + n.honorifixPrefix.trim(); } } if(cardName.length() == 0) { if(n.fn != null) { System.out.print("n.fn == " + n.fn); n.fn = n.fn.trim(); cardName = n.fn; System.out.print("cardName == " + cardName); if(n.fn.indexOf(", ") != -1) { String[] ns = n.fn.split(", "); n.familyName = ns[0]; if(ns[1].indexOf(" ") != -1) { String[] ns2 = ns[1].split(" "); n.givenName = ns2[0]; n.additionalName = ns2[1]; } else { n.givenName = ns[1]; } } else if(n.fn.indexOf(" ") != -1) { String[] ns = n.fn.split(" "); n.givenName = ns[0]; if(ns.length > 2) { n.additionalName = ns[1]; n.familyName = ns[2]; } else { n.familyName = ns[1]; } } } } } if(cardName.length() == 0) { if(org != null) { if(org.name != null) { cardName = org.name; } if(org.unit != null) { if(cardName.length() > 0) { cardName = ", "; } cardName += org.unit; } } } if(cardName.length() == 0) { parent.log("Couldn't generate name for hcard topic."); cardName = "default-hcard-" + System.currentTimeMillis() + this.progress; } parent.log("Creating hcard for '"+cardName+"'."); Topic cardTypeTopic = createTopic(tm, SI_PREFIX+"hcard", "HCard"); Topic cardTopic = createTopic(tm, SI_PREFIX+cardName, cardName, new Topic[] { cardTypeTopic } ); // **** NAME **** if(n != null) { if(n.familyName != null) { createAssociationFor(n.familyName, "family-name", cardTopic, cardTypeTopic, tm); } if(n.additionalName != null) { createAssociationFor(n.additionalName, "additional-name", cardTopic, cardTypeTopic, tm); } if(n.givenName != null) { createAssociationFor(n.givenName, "given-name", cardTopic, cardTypeTopic, tm); } if(n.honorifixPrefix != null) { createAssociationFor(n.honorifixPrefix, "honorific-prefix", cardTopic, cardTypeTopic, tm); } if(n.honorifixSuffix != null) { createAssociationFor(n.honorifixSuffix, "honorific-suffix", cardTopic, cardTypeTopic, tm); } } // **** NICKNAMES **** if(nicknames.size() > 0) { Iterator<String> nickIterator = nicknames.iterator(); while(nickIterator.hasNext()) { createAssociationFor(nickIterator.next(), "nickname", cardTopic, cardTypeTopic, tm); } } // **** PHOTO **** if(photos.size() > 0) { Iterator<String> photoIterator = photos.iterator(); while(photoIterator.hasNext()) { createSLAssociationFor(photoIterator.next(), "photo", cardTopic, cardTypeTopic, tm); } } // **** LOGO **** if(logos.size() > 0) { Iterator<String> logoIterator = logos.iterator(); while(logoIterator.hasNext()) { createSLAssociationFor(logoIterator.next(), "logo", cardTopic, cardTypeTopic, tm); } } // **** SOUND **** if(sounds.size() > 0) { Iterator<String> soundIterator = sounds.iterator(); while(soundIterator.hasNext()) { createSLAssociationFor(soundIterator.next(), "sound", cardTopic, cardTypeTopic, tm); } } // **** URLS **** if(urls.size() > 0) { Iterator<String> urlIterator = urls.iterator(); while(urlIterator.hasNext()) { createSLAssociationFor(urlIterator.next(), "url", cardTopic, cardTypeTopic, tm); } } // **** TITLE **** if(titles.size() > 0) { Iterator<String> titleIterator = titles.iterator(); while(titleIterator.hasNext()) { createAssociationFor(titleIterator.next(), "title", cardTopic, cardTypeTopic, tm); } } // **** ROLE **** if(roles.size() > 0) { Iterator<String> roleIterator = roles.iterator(); while(roleIterator.hasNext()) { createAssociationFor(roleIterator.next(), "role", cardTopic, cardTypeTopic, tm); } } // **** CATEGORY **** if(categories.size() > 0) { Iterator<String> categoryIterator = categories.iterator(); while(categoryIterator.hasNext()) { createAssociationFor(categoryIterator.next(), "category", cardTopic, cardTypeTopic, tm); } } if(keys.size() > 0) { Iterator<String> keyIterator = keys.iterator(); while(keyIterator.hasNext()) { createAssociationFor(keyIterator.next(), "key", cardTopic, cardTypeTopic, tm); } } if(mailers.size() > 0) { Iterator<String> mailerIterator = mailers.iterator(); while(mailerIterator.hasNext()) { createAssociationFor(mailerIterator.next(), "mailer", cardTopic, cardTypeTopic, tm); } } if(emails.size() > 0) { Iterator<Email> emailIterator = emails.iterator(); while(emailIterator.hasNext()) { Email email = emailIterator.next(); if(email.type == null) { createAssociationFor(email.value, "email-address", cardTopic, cardTypeTopic, tm); } else { createAssociationFor(email.value, "email-address", email.type, "email-address-type", "email-address", cardTopic, cardTypeTopic, tm); } } } if(tels.size() > 0) { Iterator<Tel> telIterator = tels.iterator(); while(telIterator.hasNext()) { Tel tel = telIterator.next(); if(tel.type == null) { createAssociationFor(tel.value, "telephone-number", cardTopic, cardTypeTopic, tm); } else { createAssociationFor(tel.value, "telephone-number", tel.type, "telephone-number-type", "telephone-number", cardTopic, cardTypeTopic, tm); } } } if(orgs.size() > 0) { Iterator<Org> orgIterator = orgs.iterator(); while(orgIterator.hasNext()) { Org org = orgIterator.next(); if(org.unit == null) { createAssociationFor(org.name, "organization-name", cardTopic, cardTypeTopic, tm); } else { createAssociationFor(org.name, "organization-name", org.unit, "organization-unit", "organization", cardTopic, cardTypeTopic, tm); } } } if(latitude != null && longitude != null) { createAssociationFor(latitude, "latitude", longitude, "longitude", "geo-location", cardTopic, cardTypeTopic, tm); } createAssociationFor(classs, "class", cardTopic, cardTypeTopic, tm); createAssociationFor(bday, "bday", cardTopic, cardTypeTopic, tm); createAssociationFor(tz, "tz", cardTopic, cardTypeTopic, tm); if(adrs.size() > 0) { int adrcount = 1; Iterator<Adr> adrIterator = adrs.iterator(); while(adrIterator.hasNext()) { Adr adr = adrIterator.next(); adrcount++; try { Topic addressTypeTopic = createTopic(tm, SI_PREFIX+"adr", "address"); String address = ""; if(adr.streetAddress != null) address += adr.streetAddress.trim()+", "; if(adr.extendedAddress != null) address += adr.extendedAddress.trim()+", "; if(adr.locality != null) address += adr.locality.trim()+", "; if(adr.region != null) address += adr.region.trim()+", "; if(adr.postalCode != null) address += adr.postalCode.trim()+", "; if(adr.countryName != null) address += adr.countryName.trim()+", "; if(address.length() < 2) address = "Address "+ (adrcount>1?adrcount+" ":"") +"of "+cardName; else address = address.substring(0, address.length()-2); Topic addressTopic = createTopic(tm, SI_PREFIX+"adr/"+address, address, new Topic[] { addressTypeTopic } ); createAssociationFor(adr.streetAddress, "street-address", addressTopic, addressTypeTopic, tm); createAssociationFor(adr.postOfficeBox, "post-office-box", addressTopic, addressTypeTopic, tm); createAssociationFor(adr.extendedAddress, "extended-address", addressTopic, addressTypeTopic, tm); createAssociationFor(adr.locality, "locality", addressTopic, addressTypeTopic, tm); createAssociationFor(adr.region, "region", addressTopic, addressTypeTopic, tm); createAssociationFor(adr.postalCode, "postal-code", addressTopic, addressTypeTopic, tm); createAssociationFor(adr.countryName, "country-name", addressTopic, addressTypeTopic, tm); Association cardAddress = tm.createAssociation(addressTypeTopic); cardAddress.addPlayer(cardTopic, cardTypeTopic); cardAddress.addPlayer(addressTopic, addressTypeTopic); if(adr.type != null) { Topic adrTypeTypeTopic = createTopic(tm, SI_PREFIX+"adr-type/", "address-type"); Topic adrTypeTopic = createTopic(tm, SI_PREFIX+"adr-type/"+adr.type, adr.type, new Topic[] { adrTypeTypeTopic }); cardAddress.addPlayer(adrTypeTopic, adrTypeTypeTopic); } } catch(Exception e) { parent.log(e); } } } // OK, DON'T GENERATE ANY MORE TOPICS... initCard(); progress++; } catch(Exception e) { parent.log(e); } } } private void createSLAssociationFor(String sl, String associationTypeName, Topic player, Topic role, TopicMap tm) { if(sl != null) { sl = sl.trim(); if(sl.length() > 0) { try { Topic associationTypeTopic = createTopic(tm, SI_PREFIX+associationTypeName, associationTypeName); Topic playerTopic = null; if(sl.startsWith("http://")) { playerTopic = createTopic(tm, sl, sl); playerTopic.setSubjectLocator(new org.wandora.topicmap.Locator(sl)); } else { // SL IS NOT REAL URL! playerTopic = createTopic(tm, SI_PREFIX+associationTypeName+"/"+sl, sl); } Association association = tm.createAssociation(associationTypeTopic); association.addPlayer(player, role); association.addPlayer(playerTopic, associationTypeTopic); } catch(Exception e) { parent.log(e); } } } } private void createAssociationFor(String basename, String associationTypeName, Topic player, Topic role, TopicMap tm) { if(basename != null) { basename = basename.trim(); if(basename.length() > 0) { try { Topic associationTypeTopic = createTopic(tm, SI_PREFIX+associationTypeName, associationTypeName); Topic playerTopic = createTopic(tm, SI_PREFIX+associationTypeName+"/"+basename, basename); Association association = tm.createAssociation(associationTypeTopic); association.addPlayer(player, role); association.addPlayer(playerTopic, associationTypeTopic); } catch(Exception e) { parent.log(e); } } } } private void createAssociationFor(String basename1, String role1, String basename2, String role2, String associationTypeName, Topic player, Topic role, TopicMap tm) { if(basename1 != null && basename2 != null && role1 != null && role2 != null) { basename1 = basename1.trim(); basename2 = basename2.trim(); role1 = role1.trim(); role2 = role2.trim(); if(basename1.length() > 0 && basename2.length() > 0 && role1.length() > 0 && role2.length() > 0) { try { Topic associationTypeTopic = createTopic(tm, SI_PREFIX+associationTypeName, associationTypeName); Topic player1Topic = createTopic(tm, SI_PREFIX+role1+"/"+basename1, basename1); Topic player2Topic = createTopic(tm, SI_PREFIX+role2+"/"+basename2, basename2); Topic role1Topic = createTopic(tm, SI_PREFIX+role1, role1); Topic role2Topic = createTopic(tm, SI_PREFIX+role2, role2); Association association = tm.createAssociation(associationTypeTopic); association.addPlayer(player, role); association.addPlayer(player1Topic, role1Topic); association.addPlayer(player2Topic, role2Topic); } catch(Exception e) { parent.log(e); } } } } // -------------------- public Topic createTopic(TopicMap topicMap, String si, String baseName) throws TopicMapException { return createTopic(topicMap, si, baseName, null); } public Topic createTopic(TopicMap topicMap, String si, String baseName, Topic[] types) throws TopicMapException { Topic t = null; if(baseName != null && baseName.length() > 0 && si != null && si.length() > 0) { si = TopicTools.cleanDirtyLocator(si); t = topicMap.getTopic(si); if(t == null) { t = topicMap.getTopicWithBaseName(baseName); if(t == null) { t = topicMap.createTopic(); t.setBaseName(baseName); } t.addSubjectIdentifier(new org.wandora.topicmap.Locator(si)); } if(types != null) { for(int i=0; i<types.length; i++) { Topic typeTopic = types[i]; if(typeTopic != null) { t.addType(typeTopic); } } } } if(t == null) { System.out.println("Failed to create topic for basename '"+baseName+"' and si '"+si+"'."); } return t; } } private class Name { public String fn = null; public String name = null; public String familyName = null; public String givenName = null; public String additionalName = null; public String honorifixPrefix = null; public String honorifixSuffix = null; public String sortString = null; } private class Adr { public String type = null; public String postOfficeBox = null; public String extendedAddress = null; public String streetAddress = null; public String locality = null; public String region = null; public String postalCode = null; public String countryName = null; public String adr = null; public Adr() { } } private class Tel { public String type = null; public String value = null; public Tel() { } } private class Email { public String type = null; public String value = null; public Email() { } } private class Org { public String name = null; public String unit = null; public Org() { } } }
74,521
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
HelmetUI.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/helmet/HelmetUI.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * HelmetUI.java * * Created on 25.5.2011, 21:58:53 */ package org.wandora.application.tools.extractors.helmet; import java.awt.Component; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Iterator; import javax.swing.JDialog; import javax.swing.JTextPane; 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.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.topicmap.Topic; /** * * @author akivela */ public class HelmetUI extends javax.swing.JPanel { private static final long serialVersionUID = 1L; public static final String baseURL = "http://data.kirjastot.fi/search"; public static final String authorURL = baseURL+"/author.json?query=__1__"; public static final String titleURL = baseURL+"/title.json?query=__1__"; public static final String isbnURL = baseURL+"/isbn.json?query=__1__"; private Wandora wandora = null; private boolean accepted = false; private JDialog dialog = null; private Context context = null; /** Creates new form HelmetUI */ public HelmetUI(Wandora w) { this.wandora = w; 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(400,300); dialog.add(this); dialog.setTitle("HelMet data API extractor"); UIBox.centerWindow(dialog, w); dialog.setVisible(true); } public String[] getQueryURLs(WandoraTool parentTool) { Component component = tabbedPane.getSelectedComponent(); String[] q = null; // ***** AUTHOR ***** if(authorPanel.equals(component)) { String query = authorTextPane.getText(); if(query == null) query = ""; String[] queries = newlineSplitter(query); String[] searchUrls = completeString(authorURL, urlEncode(queries)); q = searchUrls; } // ***** TITLE ***** else if(titlePanel.equals(component)) { String query = titleTextPane.getText(); if(query == null) query = ""; String[] queries = newlineSplitter(query); String[] searchUrls = completeString(titleURL, urlEncode(queries)); q = searchUrls; } // ***** ISBN ***** else if(titlePanel.equals(component)) { String query = isbnTextPane.getText(); if(query == null) query = ""; String[] queries = newlineSplitter(query); String[] searchUrls = completeString(isbnURL, urlEncode(queries)); q = searchUrls; } return q; } 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[] 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[] strs) { if(strs == null) return null; String[] cleanStrs = new String[strs.length]; for(int i=0; i<strs.length; i++) { cleanStrs[i] = urlEncode(strs[i]); } return cleanStrs; } public String urlEncode(String str) { try { // return URLEncoder.encode(str, "UTF-8"); return URLEncoder.encode(new String(str.getBytes("UTF-8"), "ISO-8859-1"), "ISO-8859-1"); } catch(Exception e) { return str; } } public void getContext() { JTextPane pane = null; Component component = tabbedPane.getSelectedComponent(); if(authorPanel.equals(component)) { pane = authorTextPane; } if(titlePanel.equals(component)) { pane = titleTextPane; } if(isbnPanel.equals(component)) { pane = isbnTextPane; } StringBuilder sb = new StringBuilder(""); if(context != null) { Iterator iterator = context.getContextObjects(); while(iterator.hasNext()) { try { Object o = iterator.next(); if(o == null) continue; if(o instanceof Topic) { String bn = ((Topic) o).getBaseName(); if(bn.indexOf('(') != -1) { bn = bn.substring(0,bn.indexOf('(')); bn = bn.trim(); } sb.append(bn); sb.append('\n'); } else if(o instanceof String) { sb.append(((String) o)); sb.append('\n'); } } catch(Exception e) { e.printStackTrace(); } } } if(pane != null) { if(sb.length() > 0) { pane.setText(sb.toString()); } else { WandoraOptionPane.showMessageDialog(Wandora.getWandora(), "No valid context available. Couldn't get text out of context.", "No valid context available"); } } } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; tabbedPane = new SimpleTabbedPane(); authorPanel = new javax.swing.JPanel(); authorPanelInner = new javax.swing.JPanel(); authorLabel = new SimpleLabel(); authorScrollPane = new SimpleScrollPane(); authorTextPane = new SimpleTextPane(); titlePanel = new javax.swing.JPanel(); titlePanelInner = new javax.swing.JPanel(); titleLabel = new SimpleLabel(); titleScrollPane = new SimpleScrollPane(); titleTextPane = new SimpleTextPane(); isbnPanel = new javax.swing.JPanel(); isbnPanelInner = new javax.swing.JPanel(); isbnLabel = new SimpleLabel(); isbnScrollPane = new SimpleScrollPane(); isbnTextPane = new SimpleTextPane(); buttonPanel = new javax.swing.JPanel(); getContextButton = new SimpleButton(); buttonFillerPanel = new javax.swing.JPanel(); okButton = new SimpleButton(); cancelButton = new SimpleButton(); setLayout(new java.awt.GridBagLayout()); authorPanel.setLayout(new java.awt.GridBagLayout()); authorPanelInner.setLayout(new java.awt.GridBagLayout()); authorLabel.setText("<html>Search HelMet library data using author 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, 4, 0); authorPanelInner.add(authorLabel, gridBagConstraints); authorScrollPane.setViewportView(authorTextPane); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; authorPanelInner.add(authorScrollPane, 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); authorPanel.add(authorPanelInner, gridBagConstraints); tabbedPane.addTab("Author", authorPanel); titlePanel.setLayout(new java.awt.GridBagLayout()); titlePanelInner.setLayout(new java.awt.GridBagLayout()); titleLabel.setText("<html>Search HelMet library data using title 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, 4, 0); titlePanelInner.add(titleLabel, gridBagConstraints); titleScrollPane.setViewportView(titleTextPane); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; titlePanelInner.add(titleScrollPane, 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); titlePanel.add(titlePanelInner, gridBagConstraints); tabbedPane.addTab("Title", titlePanel); isbnPanel.setLayout(new java.awt.GridBagLayout()); isbnPanelInner.setLayout(new java.awt.GridBagLayout()); isbnLabel.setText("<html>Search HelMet library data using ISBN codes.</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, 4, 0); isbnPanelInner.add(isbnLabel, gridBagConstraints); isbnScrollPane.setViewportView(isbnTextPane); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; isbnPanelInner.add(isbnScrollPane, 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); isbnPanel.add(isbnPanelInner, gridBagConstraints); tabbedPane.addTab("ISBN", isbnPanel); 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()); getContextButton.setText("Get context"); getContextButton.setMargin(new java.awt.Insets(2, 2, 2, 2)); getContextButton.setMaximumSize(new java.awt.Dimension(90, 23)); getContextButton.setMinimumSize(new java.awt.Dimension(90, 23)); getContextButton.setPreferredSize(new java.awt.Dimension(90, 23)); getContextButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { getContextButtonMouseReleased(evt); } }); buttonPanel.add(getContextButton, new java.awt.GridBagConstraints()); javax.swing.GroupLayout buttonFillerPanelLayout = new javax.swing.GroupLayout(buttonFillerPanel); buttonFillerPanel.setLayout(buttonFillerPanelLayout); buttonFillerPanelLayout.setHorizontalGroup( buttonFillerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); buttonFillerPanelLayout.setVerticalGroup( buttonFillerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; buttonPanel.add(buttonFillerPanel, gridBagConstraints); okButton.setText("OK"); okButton.setMargin(new java.awt.Insets(2, 5, 2, 5)); 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, 3); buttonPanel.add(okButton, gridBagConstraints); cancelButton.setText("Cancel"); 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.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { cancelButtonMouseReleased(evt); } }); buttonPanel.add(cancelButton, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); add(buttonPanel, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents private void cancelButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cancelButtonMouseReleased this.accepted = false; if(dialog != null) dialog.setVisible(false); }//GEN-LAST:event_cancelButtonMouseReleased private void okButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_okButtonMouseReleased this.accepted = true; if(dialog != null) dialog.setVisible(false); }//GEN-LAST:event_okButtonMouseReleased private void getContextButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_getContextButtonMouseReleased getContext(); }//GEN-LAST:event_getContextButtonMouseReleased // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel authorLabel; private javax.swing.JPanel authorPanel; private javax.swing.JPanel authorPanelInner; private javax.swing.JScrollPane authorScrollPane; private javax.swing.JTextPane authorTextPane; private javax.swing.JPanel buttonFillerPanel; private javax.swing.JPanel buttonPanel; private javax.swing.JButton cancelButton; private javax.swing.JButton getContextButton; private javax.swing.JLabel isbnLabel; private javax.swing.JPanel isbnPanel; private javax.swing.JPanel isbnPanelInner; private javax.swing.JScrollPane isbnScrollPane; private javax.swing.JTextPane isbnTextPane; private javax.swing.JButton okButton; private javax.swing.JTabbedPane tabbedPane; private javax.swing.JLabel titleLabel; private javax.swing.JPanel titlePanel; private javax.swing.JPanel titlePanelInner; private javax.swing.JScrollPane titleScrollPane; private javax.swing.JTextPane titleTextPane; // End of variables declaration//GEN-END:variables }
18,408
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
HelmetJSONParser.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/helmet/HelmetJSONParser.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.helmet; import java.net.URL; import java.net.URLEncoder; import java.util.LinkedHashSet; import org.json.JSONArray; import org.json.JSONObject; import org.wandora.application.Wandora; import org.wandora.application.gui.WandoraOptionPane; 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; import org.wandora.topicmap.TopicMapLogger; import org.wandora.utils.IObox; /** * * * * <pre> {"records": [ {"type":"book", "isbn":"0385410700", "title":"Deadline", "library_id":"(FI-HELMET)b1141424", "library_url":"http://www.helmet.fi/record=b1141424~S9*eng", "author":"Armstrong, Campbell", "author_details":[], "extent":["314, [1] s. ;"], "description":[], "contents":[] },... * </pre> * * @author akivela */ public class HelmetJSONParser { private static boolean SPLIT_CONTENTS_TO_TOPICS = true; private static boolean TRIM_AUTHORS_ENDING_DOT = true; private static boolean REMOVE_ROLE_PARENTHESIS = true; private static boolean SPLIT_LANGUAGES_IN_TITLE = true; private static boolean REMOVE_ID_PREFIX = true; private static LinkedHashSet<URL> history = null; public static final String GENERAL_SI = "http://data.kirjastot.fi/"; private TopicMap tm = null; private TopicMapLogger logger = null; private static int progress = 1; private static long waitBetweenURLRequests = 200; private static String DEFAULT_LANG = "fi"; private static String DEFAULT_ENCODING = "UTF-8"; private boolean extractAllPages = false; private String extractUrl = null; public HelmetJSONParser(TopicMap tm, TopicMapLogger logger, JSONObject inputJSON) { this(tm, logger); try { parse(inputJSON); } catch(Exception e) { log(e); } } public HelmetJSONParser(TopicMap tm, TopicMapLogger logger) { this.tm = tm; this.logger = logger; if(history == null) { clearHistory(); } } // ------------------------------------------------------------- HISTORY --- public void clearHistory() { history = new LinkedHashSet<URL>(); } public boolean inHistory(URL u) { if(history != null) { if(history.contains(u)) return true; } return false; } public void addToHistory(URL u) { if(history == null) clearHistory(); history.add(u); } // ------------------------------------------------------------------------- public boolean errorDetected(JSONObject inputJSON) { try { if(inputJSON.has("error")) { JSONObject error = inputJSON.getJSONObject("error"); if(error != null) { log(error.getString("message")+" ("+error.getString("type")+")"); return true; } } } catch(Exception e) { // NOTHING HERE } return false; } public void takeNap(long napTime) { try { Thread.sleep(napTime); } catch(Exception e) {} } // ------------------------------------------------------------------------- public void parse(JSONObject inputJSON) throws Exception { if(logger.forceStop()) return; if(logger != null) { logger.setProgress(progress++); } if(tm == null) { log("Warning: Parser has no Topic Map object for topics and associations. Aborting."); return; } if(errorDetected(inputJSON)) return; if(inputJSON.has("records")) { JSONArray records = inputJSON.getJSONArray("records"); int s = records.length(); for( int i=0; i<s; i++ ) { JSONObject record = records.getJSONObject(i); parseRecord(record); } } if(extractUrl != null) { if(inputJSON.has("current_page") && inputJSON.has("per_page") && inputJSON.has("total_entries")) { int cp = inputJSON.getInt("current_page"); int pp = inputJSON.getInt("per_page"); int te = inputJSON.getInt("total_entries"); int tp = te / pp + 1; if(cp < tp) { boolean extractNextPage = false; if(!extractAllPages) { int a = WandoraOptionPane.showConfirmDialog(Wandora.getWandora(), "Total "+te+" records found. Extracted records "+(cp*pp-pp+1)+"-"+Math.min(cp*pp, te)+". Would you like to continue?", "Continue?", WandoraOptionPane.YES_TO_ALL_NO_CANCEL_OPTION); if(a == WandoraOptionPane.YES_OPTION) extractNextPage = true; else if(a == WandoraOptionPane.YES_TO_ALL_OPTION) extractAllPages = true; } if(extractAllPages || extractNextPage) { String newExtractUrl = extractUrl + "&page="+(cp+1); parse(new URL(newExtractUrl)); } } } } } public void parseRecord(JSONObject inputJSON) throws Exception { if(logger != null) { logger.setProgress(progress++); } if(tm == null) { log("Warning: Parser has no Topic Map object for topics and associations. Aborting."); return; } if(errorDetected(inputJSON)) return; String libraryId = robustJSONGet(inputJSON, "library_id"); Topic recordT = getRecordTopic( robustJSONGet(inputJSON, "library_url"), libraryId, robustJSONGet(inputJSON, "isbn"), tm ); if(recordT != null) { if(inputJSON.has("type")) { String type = inputJSON.getString("type"); if(isNotNull(type)) { Topic t = getTypeTopic(type, tm); if(t != null) { Association a = tm.createAssociation(getTypeType(tm)); a.addPlayer(t, getTypeType(tm)); a.addPlayer(recordT, getRecordType(tm)); } } } if(inputJSON.has("title")) { String title = inputJSON.getString("title"); if(isNotNull(title)) { if(SPLIT_LANGUAGES_IN_TITLE) { String[] titles = title.split(" = "); if(titles.length == 3) { recordT.setDisplayName("fi", titles[0]); recordT.setDisplayName("sv", titles[1]); recordT.setDisplayName("en", titles[2]); } else if(titles.length == 2) { recordT.setDisplayName("fi", titles[0]); recordT.setDisplayName("sv", titles[1]); } else { recordT.setDisplayName(DEFAULT_LANG, title); } } else { recordT.setDisplayName(DEFAULT_LANG, title); } String basename = title; if(libraryId != null) { if(REMOVE_ID_PREFIX) { if(libraryId.startsWith("(FI-HELMET)")) libraryId = libraryId.substring(11); } basename = basename + " ("+libraryId+")"; } else { basename = basename + " (TEMP"+System.currentTimeMillis()+")"; } recordT.setBaseName(basename); } } if(inputJSON.has("author")) { String author = inputJSON.getString("author"); if(isNotNull(author)) { if(TRIM_AUTHORS_ENDING_DOT) { if(author.endsWith(".")) author = author.substring(0, author.length()-1); } Topic authorT = getAuthorTopic(author, tm); if(authorT != null) { Association a = tm.createAssociation(getAuthorType(tm)); a.addPlayer(recordT, getRecordType(tm)); a.addPlayer(authorT, getAuthorType(tm)); } } } if(inputJSON.has("author_details")) { JSONArray authorDetails = inputJSON.getJSONArray("author_details"); if(authorDetails != null) { int s = authorDetails.length(); for(int i=0; i<s; i++) { JSONObject authorDetail = authorDetails.getJSONObject(i); String role = null; String name = null; if(authorDetail.has("name")) { name = authorDetail.getString("name"); if(TRIM_AUTHORS_ENDING_DOT) { if(name.endsWith(".")) name = name.substring(0, name.length()-1); } } if(authorDetail.has("role")) { role = authorDetail.getString("role"); if(!isNotNull(role)) { role = "(default-role)"; } if(REMOVE_ROLE_PARENTHESIS) { if(role.startsWith("(")) role = role.substring(1); if(role.endsWith(")")) role = role.substring(0, role.length()-1); } } if(role != null && name != null) { Topic roleT = getRoleTopic(role, tm); Topic author2T = getAuthorTopic(name, tm); if(roleT != null && author2T != null) { Association a2 = tm.createAssociation(getAuthorType(tm)); a2.addPlayer(recordT, getRecordType(tm)); a2.addPlayer(roleT, getAuthorRoleType(tm)); a2.addPlayer(author2T, getAuthorType(tm)); } } } } } if(inputJSON.has("extent")) { JSONArray extentArray = inputJSON.getJSONArray("extent"); if(extentArray != null) { int s = extentArray.length(); for(int i=0; i<s; i++) { String extent = extentArray.getString(i); if(extent != null && extent.length() > 0) { recordT.setData(getExtentType(tm), TMBox.getLangTopic(recordT, DEFAULT_LANG), extent); } } } } if(inputJSON.has("description")) { JSONArray descriptionArray = inputJSON.getJSONArray("description"); if(descriptionArray != null) { int s = descriptionArray.length(); for(int i=0; i<s; i++) { String description = descriptionArray.getString(i); if(description != null && description.length() > 0) { recordT.setData(getDescriptionType(tm), TMBox.getLangTopic(recordT, DEFAULT_LANG), description); } } } } if(inputJSON.has("contents")) { JSONArray contentsArray = inputJSON.getJSONArray("contents"); if(contentsArray != null) { int s = contentsArray.length(); for(int i=0; i<s; i++) { String contents = contentsArray.getString(i); if(contents != null && contents.length() > 0) { if(SPLIT_CONTENTS_TO_TOPICS) { String[] splittedContents = contents.split(" ; "); for(int j=0; j<splittedContents.length; j++) { String split = splittedContents[j]; split = split.trim(); if(split.length() > 0) { Topic ct = getContentTopic(split, tm); if(ct != null) { Association a = tm.createAssociation(getContentsType(tm)); a.addPlayer(ct, getContentsType(tm)); a.addPlayer(recordT, getRecordType(tm)); } } } } else { recordT.setData(getContentsType(tm), TMBox.getLangTopic(recordT, DEFAULT_LANG), contents); } } } } } } } public void parse(URL url) throws Exception { if(extractUrl == null) { extractUrl = url.toExternalForm(); } if(waitBetweenURLRequests > 0) { takeNap(waitBetweenURLRequests); } if(url != null && !logger.forceStop()) { if(!inHistory(url)) { addToHistory(url); System.out.println("Parsing URL "+url); String in = IObox.doUrl(url); JSONObject inputJSON = new JSONObject(in); parse(inputJSON); } else { System.out.println("Rejecting already parsed URL "+url); } } } public boolean isNotNull(String str) { if(str == null || str.length() == 0 || "null".equals(str)) return false; return true; } // ------------------------------------------------------------------------- public String robustJSONGet(JSONObject json, String key) { try { if(json.has(key)) { return (String) json.get(key); } } catch(Exception e) { // NOTHING HERE } return null; } public boolean areEqual(String key, Object o) { if(key == null || o == null) return false; return key.equalsIgnoreCase(o.toString()); } // ------------------------------------------------------------------------- // -------------------------------------------------------------- TOPICS --- // ------------------------------------------------------------------------- public static final String HELMET_SI = GENERAL_SI + "kirjastot"; public static final String TYPE_SI = GENERAL_SI + "type"; public static final String AUTHOR_SI = GENERAL_SI + "author"; public static final String AUTHORROLE_SI = GENERAL_SI + "author-role"; public static final String AUTHORDETAILS_SI = GENERAL_SI + "author-details"; public static final String RECORD_SI = GENERAL_SI + "record"; public static final String EXTENT_SI = GENERAL_SI + "extent"; public static final String DESCRIPTION_SI = GENERAL_SI + "description"; public static final String CONTENTS_SI = GENERAL_SI + "contents"; public static final String ID_SI = GENERAL_SI + "id"; public static final String ISBN_SI = GENERAL_SI + "isbn"; public static final String ROLE_SI = GENERAL_SI + "role"; public Topic getWandoraType( TopicMap tm ) throws Exception { return ExtractHelper.getOrCreateTopic(TMBox.WANDORACLASS_SI, tm); } public Topic getDataKirjastotType(TopicMap tm) throws Exception { return ExtractHelper.getOrCreateTopic(HELMET_SI, "HelMet", getWandoraType(tm), tm); } private Topic getTypeType(TopicMap tm) throws Exception { return ExtractHelper.getOrCreateTopic(TYPE_SI, "Type", getDataKirjastotType(tm), tm); } private Topic getAuthorType(TopicMap tm) throws Exception { return ExtractHelper.getOrCreateTopic(AUTHOR_SI, "Author", getDataKirjastotType(tm), tm); } private Topic getAuthorRoleType(TopicMap tm) throws Exception { return ExtractHelper.getOrCreateTopic(AUTHORROLE_SI, "Author Role", getDataKirjastotType(tm), tm); } private Topic getRecordType(TopicMap tm) throws Exception { return ExtractHelper.getOrCreateTopic(RECORD_SI, "Record", getDataKirjastotType(tm), tm); } private Topic getExtentType(TopicMap tm) throws Exception { return ExtractHelper.getOrCreateTopic(EXTENT_SI, "Extent", getDataKirjastotType(tm), tm); } private Topic getDescriptionType(TopicMap tm) throws Exception { return ExtractHelper.getOrCreateTopic(DESCRIPTION_SI, "Description", getDataKirjastotType(tm), tm); } private Topic getContentsType(TopicMap tm) throws Exception { return ExtractHelper.getOrCreateTopic(CONTENTS_SI, "Contents", getDataKirjastotType(tm), tm); } private Topic getIDType(TopicMap tm) throws Exception { return ExtractHelper.getOrCreateTopic(ID_SI, "HelMet ID", getDataKirjastotType(tm), tm); } private Topic getISBNType(TopicMap tm) throws Exception { return ExtractHelper.getOrCreateTopic(ISBN_SI, "ISBN", getDataKirjastotType(tm), tm); } private Topic getRoleType(TopicMap tm) throws Exception { return ExtractHelper.getOrCreateTopic(ROLE_SI, "Author Role", getDataKirjastotType(tm), tm); } private Topic getContentTopic(String c, TopicMap tm) throws Exception { return getATopic(c, CONTENTS_SI, getContentsType(tm), tm); } private Topic getRoleTopic(String r, TopicMap tm) throws Exception { return getATopic(r, ROLE_SI, getRoleType(tm), tm); } public Topic getTypeTopic(String token, TopicMap tm) throws Exception { return getATopic(token, TYPE_SI, getTypeType(tm), tm); } private Topic getAuthorTopic(String name, TopicMap tm) throws Exception { return getATopic(name, AUTHOR_SI, getAuthorType(tm), tm); } private Topic getAuthorTopic(String name, Topic type, TopicMap tm) throws Exception { return getATopic(name, AUTHOR_SI, type, tm); } private Topic getRecordTopic(String url, String id, String isbn, TopicMap tm) throws Exception { Topic t = null; if(url != null && url.length() > 0) { t = tm.getTopic(url); if(t == null) t = tm.getTopicBySubjectLocator(url); if(t == null) { t = tm.createTopic(); t.addSubjectIdentifier(new Locator(url)); if(id != null && id.length() > 0) { if(REMOVE_ID_PREFIX) { if(id.startsWith("(FI-HELMET)")) id = id.substring(11); } t.setData(getIDType(tm), TMBox.getLangTopic(t, DEFAULT_LANG), id); } if(isbn != null && isbn.length() > 0) { t.setData(getISBNType(tm), TMBox.getLangTopic(t, DEFAULT_LANG), isbn); } Topic recordType = getRecordType(tm); t.addType(recordType); } } return t; } // -------- private Topic getATopic(String str, String si, TopicMap tm) throws TopicMapException { return getATopic(str, si, null, tm); } private Topic getATopic(String str, String si, Topic type, TopicMap tm) throws TopicMapException { if(str != null && si != null) { str = str.trim(); if(str.length() > 0) { Topic topic=ExtractHelper.getOrCreateTopic(si+"/"+urlEncode(str), str, tm); if(type != null) topic.addType(type); return topic; } } return null; } private String urlEncode(String str) { try { return URLEncoder.encode(str, DEFAULT_ENCODING); } catch(Exception e) {} return str; } // ------ 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 int maxLogs = 1000; private int logCount = 0; private void log(String str) { if(logCount<maxLogs) { logCount++; logger.log(str); if(logCount>=maxLogs) { logger.log("Silently passing rest logs..."); } } } private void log(Exception ex) { logger.log(ex); } }
22,548
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
HelmetJSONExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/helmet/HelmetJSONExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.helmet; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.net.URL; import javax.swing.Icon; import org.json.JSONObject; 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.topicmap.TopicMap; import org.wandora.utils.IObox; /* * See http://data.kirjastot.fi/ * * @author akivela */ public class HelmetJSONExtractor extends AbstractExtractor { private static final long serialVersionUID = 1L; private static String defaultEncoding = "UTF-8"; //"ISO-8859-1"; private HelmetUI ui = null; @Override public String getName() { return "HelMet Data API Extractor"; } @Override public String getDescription(){ return "Extracts library data from HelMet data API at http://data.kirjastot.fi/. "+ "HelMet is a bibliographical database of Helsinki (Finland) region libraries and contains "+ "information about 670000 bibliographical entries."; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_helmet.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 HelmetUI(wandora); } ui.open(wandora, context); if(ui.wasAccepted()) { setDefaultLogger(); TopicMap tm = wandora.getTopicMap(); String[] urls = ui.getQueryURLs(this); 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 feed '"+u.toExternalForm()+"'"); _extractTopicsFrom(u, tm); } catch(Exception e) { log(e); } } log("Ready."); } } else { // log("User cancelled the extraction!"); } } catch(Exception e) { singleLog(e); } if(ui != null && ui.wasAccepted()) setState(WAIT); else setState(CLOSE); } public boolean _extractTopicsFrom(URL url, TopicMap topicMap) throws Exception { if(url != null) { try { HelmetJSONParser parser = new HelmetJSONParser(topicMap, this); parser.clearHistory(); parser.parse(url); return true; } catch (Exception ex) { log(ex); } } return false; } 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 { HelmetJSONParser parser = new HelmetJSONParser(topicMap, this); parser.clearHistory(); parser.parse(new JSONObject(in)); } catch (Exception ex) { log(ex); } return true; } }
4,783
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AuthConfigDialog.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/flickr/AuthConfigDialog.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * AuthConfigDialog.java * * Created on 28. huhtikuuta 2008, 12:45 */ package org.wandora.application.tools.extractors.flickr; import java.awt.Color; import javax.swing.JLabel; import org.wandora.application.Wandora; import org.wandora.application.gui.WandoraOptionPane; /** * * @author anttirt */ public class AuthConfigDialog extends javax.swing.JDialog { private static final long serialVersionUID = 1L; private Wandora admin; private FlickrState flickrState; private JLabel[] curLabels; /** Creates new form AuthConfigDialog */ public AuthConfigDialog(java.awt.Frame parent, boolean modal, FlickrState state) { super(parent, modal); flickrState = state; initComponents(); curLabels = new JLabel[] { gotNone, gotRead, gotWrite, gotDelete }; int currentAuthLevel = FlickrState.getAuthLevel(state.PermissionLevel); Color validGreen = new Color(30, 220, 30); for(int i = 0; i <= currentAuthLevel; ++i) { curLabels[i].setForeground(validGreen); } fldUsername.setText(state.LastUserName); fldFrob.setText(state.Frob); fldToken.setText(state.Token); this.setSize(650, 280); if(parent instanceof Wandora) { admin = (Wandora)parent; admin.centerWindow(this); } } private boolean cancelled; public boolean wasCancelled() { return cancelled; } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; wandoraLabel2 = new org.wandora.application.gui.simple.SimpleLabel(); authPanel = new javax.swing.JPanel(); wandoraLabel3 = new org.wandora.application.gui.simple.SimpleLabel(); jPanel3 = new javax.swing.JPanel(); fldUsername = new javax.swing.JTextField(); fldToken = new javax.swing.JTextField(); fldFrob = new javax.swing.JTextField(); wandoraLabel6 = new org.wandora.application.gui.simple.SimpleLabel(); wandoraLabel5 = new org.wandora.application.gui.simple.SimpleLabel(); wandoraLabel4 = new org.wandora.application.gui.simple.SimpleLabel(); wandoraLabel7 = new org.wandora.application.gui.simple.SimpleLabel(); jPanel1 = new javax.swing.JPanel(); gotNone = new org.wandora.application.gui.simple.SimpleLabel(); gotRead = new org.wandora.application.gui.simple.SimpleLabel(); gotDelete = new org.wandora.application.gui.simple.SimpleLabel(); gotWrite = new org.wandora.application.gui.simple.SimpleLabel(); jPanel4 = new javax.swing.JPanel(); btnClearInfo = new org.wandora.application.gui.simple.SimpleButton(); btnValidate = new org.wandora.application.gui.simple.SimpleButton(); buttonPanel = new javax.swing.JPanel(); jPanel5 = new javax.swing.JPanel(); btnClose = new org.wandora.application.gui.simple.SimpleButton(); wandoraLabel2.setText("wandoraLabel2"); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Flickr authentication status"); getContentPane().setLayout(new java.awt.GridBagLayout()); authPanel.setLayout(new java.awt.GridBagLayout()); wandoraLabel3.setText("<html><body><p>This dialog lets you inspect and modify the Flickr authentication status of the current running Wandora instance. If you have saved the frob and token from a previous session, you can enter them here to avoid having to re-authenticate at the Flickr website.</p></body></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(10, 10, 0, 10); authPanel.add(wandoraLabel3, gridBagConstraints); jPanel3.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(153, 153, 153))); jPanel3.setLayout(new java.awt.GridBagLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 0, 0, 5); jPanel3.add(fldUsername, 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, 0, 5); jPanel3.add(fldToken, 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, 0, 5); jPanel3.add(fldFrob, gridBagConstraints); wandoraLabel6.setText("Current username"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5); jPanel3.add(wandoraLabel6, gridBagConstraints); wandoraLabel5.setText("Token"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 5); jPanel3.add(wandoraLabel5, gridBagConstraints); wandoraLabel4.setText("Frob"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 5); jPanel3.add(wandoraLabel4, gridBagConstraints); wandoraLabel7.setText("Current rights"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.insets = new java.awt.Insets(2, 5, 2, 5); jPanel3.add(wandoraLabel7, gridBagConstraints); jPanel1.setLayout(new java.awt.GridBagLayout()); gotNone.setForeground(new java.awt.Color(102, 102, 102)); gotNone.setText("none"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); jPanel1.add(gotNone, gridBagConstraints); gotRead.setForeground(new java.awt.Color(102, 102, 102)); gotRead.setText("read"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); jPanel1.add(gotRead, gridBagConstraints); gotDelete.setForeground(new java.awt.Color(102, 102, 102)); gotDelete.setText("delete"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); jPanel1.add(gotDelete, gridBagConstraints); gotWrite.setForeground(new java.awt.Color(102, 102, 102)); gotWrite.setText("write"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); jPanel1.add(gotWrite, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 2, 5, 5); jPanel3.add(jPanel1, gridBagConstraints); jPanel4.setLayout(new java.awt.GridBagLayout()); btnClearInfo.setText("Clear information"); btnClearInfo.setPreferredSize(new java.awt.Dimension(115, 21)); btnClearInfo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnClearInfoActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); jPanel4.add(btnClearInfo, gridBagConstraints); btnValidate.setText("Validate new frob and token"); btnValidate.setPreferredSize(new java.awt.Dimension(171, 21)); btnValidate.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnValidateActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; jPanel4.add(btnValidate, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); jPanel3.add(jPanel4, 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(10, 10, 0, 10); authPanel.add(jPanel3, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; getContentPane().add(authPanel, gridBagConstraints); buttonPanel.setLayout(new java.awt.GridBagLayout()); javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); jPanel5Layout.setVerticalGroup( jPanel5Layout.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(jPanel5, gridBagConstraints); btnClose.setText("Close"); btnClose.setPreferredSize(new java.awt.Dimension(70, 23)); btnClose.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnCloseActionPerformed(evt); } }); buttonPanel.add(btnClose, 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, 10, 10, 10); getContentPane().add(buttonPanel, gridBagConstraints); pack(); }// </editor-fold>//GEN-END:initComponents private void btnValidateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnValidateActionPerformed flickrState.Frob = fldFrob.getText(); flickrState.Token = fldToken.getText(); try { //WandoraOptionPane.showMessageDialog(admin, "Validating...", "Validating...", WandoraOptionPane.INFORMATION_MESSAGE); if(flickrState.validToken(FlickrState.PermRead)) { WandoraOptionPane.showMessageDialog(admin, "Validating done", "Successfully validated", WandoraOptionPane.INFORMATION_MESSAGE); fldUsername.setText(flickrState.LastUserName); fldFrob.setText(flickrState.Frob); fldToken.setText(flickrState.Token); int currentAuthLevel = FlickrState.getAuthLevel(flickrState.PermissionLevel); Color validGreen = new Color(30, 220, 30); for(int i = 0; i <= currentAuthLevel; ++i) { curLabels[i].setForeground(validGreen); } } else { WandoraOptionPane.showMessageDialog(this, "Validating failed", "Validating failed!", WandoraOptionPane.INFORMATION_MESSAGE); flickrState.Frob = null; flickrState.Token = null; } } catch(FlickrExtractor.RequestFailure e) { WandoraOptionPane.showMessageDialog(this, e.getMessage(), "Validating failed!", WandoraOptionPane.INFORMATION_MESSAGE); } }//GEN-LAST:event_btnValidateActionPerformed private void btnClearInfoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnClearInfoActionPerformed fldUsername.setText(""); fldFrob.setText(""); fldToken.setText(""); flickrState.Frob = null; flickrState.Token = null; flickrState.LastUserName = null; // 212 208 200 curLabels[0].setForeground(new Color(30, 220, 30)); for(int i = 1; i < 4; ++i) curLabels[i].setForeground(new Color(102, 102, 102)); }//GEN-LAST:event_btnClearInfoActionPerformed private void btnCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCloseActionPerformed cancelled = true; setVisible(false); }//GEN-LAST:event_btnCloseActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* java.awt.EventQueue.invokeLater(new Runnable() { public void run() { AuthConfigDialog dialog = new AuthConfigDialog(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); */ } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel authPanel; private org.wandora.application.gui.simple.SimpleButton btnClearInfo; private org.wandora.application.gui.simple.SimpleButton btnClose; private org.wandora.application.gui.simple.SimpleButton btnValidate; private javax.swing.JPanel buttonPanel; private javax.swing.JTextField fldFrob; private javax.swing.JTextField fldToken; private javax.swing.JTextField fldUsername; private javax.swing.JLabel gotDelete; private javax.swing.JLabel gotNone; private javax.swing.JLabel gotRead; private javax.swing.JLabel gotWrite; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private org.wandora.application.gui.simple.SimpleLabel wandoraLabel2; private org.wandora.application.gui.simple.SimpleLabel wandoraLabel3; private org.wandora.application.gui.simple.SimpleLabel wandoraLabel4; private org.wandora.application.gui.simple.SimpleLabel wandoraLabel5; private org.wandora.application.gui.simple.SimpleLabel wandoraLabel6; private org.wandora.application.gui.simple.SimpleLabel wandoraLabel7; // End of variables declaration//GEN-END:variables }
17,197
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
FlickrOccur.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/flickr/FlickrOccur.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.flickr; /** * * @author anttirt */ public enum FlickrOccur { Description, MemberCount, NSID, Location, PhotoID }
1,012
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
FlickrGroup.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/flickr/FlickrGroup.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.flickr; import java.util.TreeMap; import org.json.JSONException; import org.json.JSONObject; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; /** * * @author anttirt */ public class FlickrGroup { public String Name; public String ID; public FlickrGroup(JSONObject obj) throws JSONException { Name = obj.getString("name"); ID = obj.getString("nsid"); } public FlickrGroup() {} public Topic makeTopic(FlickrExtractor extractor) throws TopicMapException { Topic ret = FlickrUtils.createRaw(extractor.getCurrentMap(), "http://www.flickr.com/groups/" + ID + "/", " (flickr group)", Name, extractor.getTopic(FlickrTopic.Group)); ret.setData(extractor.getOccurrence(FlickrOccur.NSID), extractor.getLanguage(null), ID); TreeMap<String, String> args = new TreeMap<>(); args.put("group_id", ID); try { JSONObject obj = extractor.getFlickrState().unauthorizedCall("flickr.urls.getGroup", args); ret.addSubjectIdentifier(new Locator(FlickrUtils.searchString(obj, "group.url"))); } catch(JSONException e) { e.printStackTrace(); } catch(FlickrExtractor.RequestFailure e) { e.printStackTrace(); } return ret; } }
2,225
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
FlickrTopic.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/flickr/FlickrTopic.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.flickr; /** * * @author anttirt */ public enum FlickrTopic { Group, Profile, Photo, Tag }
982
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
FlickrUtils.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/flickr/FlickrUtils.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.flickr; import java.util.Collection; import java.util.Enumeration; import java.util.HashSet; import java.util.Iterator; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.XTMPSI; /** * * @author anttirt */ public class FlickrUtils { public static Locator buildSI(String siend) { if(siend == null) siend = "" + System.currentTimeMillis() + Math.random(); return new Locator("http://wandora.org/si/flickr/" + siend); } public static Topic createTopic(TopicMap topicMap, String baseString) throws TopicMapException { return createTopic(topicMap, baseString, "", baseString, new Topic[] { }); } public static <T> Iterable<T> each(final Iterator<T> iter) { return new Iterable<T>() { public Iterator<T> iterator() { return iter; } }; } public static class EnumToIter<T> implements Iterator<T> { private Enumeration<T> data; public boolean hasNext() { return data.hasMoreElements(); } public T next() { return data.nextElement(); } public void remove() { throw new UnsupportedOperationException("Remove not supported."); } public EnumToIter(Enumeration<T> e) { if(e == null) throw new NullPointerException(); data = e; } } public static <T> Iterable<T> each(final Enumeration<T> e) { return new Iterable<T>() { public Iterator<T> iterator() { return new EnumToIter<T>(e); } }; } public static Topic createTopic(TopicMap topicMap, String siString, String baseString) throws TopicMapException { return createTopic(topicMap, siString, "", baseString, new Topic[] { }); } public static Topic createTopic(TopicMap topicMap, String siString, String baseString, Topic type) throws TopicMapException { return createTopic(topicMap, siString, "", baseString, new Topic[] { type }); } public static Topic createTopic(TopicMap topicMap, String baseString, Topic type) throws TopicMapException { return createTopic(topicMap, baseString, "", baseString, new Topic[] { type }); } public static Topic createTopic(TopicMap topicMap, String siString, String baseNameString, String baseString) throws TopicMapException { return createTopic(topicMap, siString, baseNameString, baseString, new Topic[] { }); } public static Topic createTopic(TopicMap topicMap, String siString, String baseNameString, String baseString, Topic type) throws TopicMapException { return createTopic(topicMap, siString, baseNameString, baseString, new Topic[] { type }); } public static Topic createRaw(TopicMap topicMap, String siString, String baseNameString, String baseString, Topic type) throws TopicMapException { return createRaw(topicMap, siString, baseNameString, baseString, new Topic[] { type }); } public static Topic createTopic(TopicMap topicMap, String siString, String baseNameString, String baseString, Topic[] types) throws TopicMapException { if(baseString == null) throw new java.lang.IllegalArgumentException("Null baseString passed to createTopic (siString=\"" + siString + "\", baseNameString=\"" + baseNameString + "\""); if(baseString.length() == 0) throw new java.lang.IllegalArgumentException("Empty baseString passed to createTopic (siString=\"" + siString + "\", baseNameString=\"" + baseNameString + "\""); 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, "en", baseString); for(int i=0; i<types.length; i++) { Topic typeTopic = types[i]; if(typeTopic != null) { t.addType(typeTopic); } } return t; } public static Topic createRaw(TopicMap topicMap, String siString, String baseNameString, String baseString, Topic[] types) throws TopicMapException { if(baseString == null) throw new java.lang.IllegalArgumentException("Null baseString passed to createRaw (siString=\"" + siString + "\", baseNameString=\"" + baseNameString + "\""); if(baseString.length() == 0) throw new java.lang.IllegalArgumentException("Empty baseString passed to createRaw (siString=\"" + siString + "\", baseNameString=\"" + baseNameString + "\""); Locator si = new Locator(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, "en", baseString); for(int i=0; i<types.length; i++) { Topic typeTopic = types[i]; if(typeTopic != null) { t.addType(typeTopic); } } return t; } public static void setDisplayName(Topic t, String lang, String name) throws TopicMapException { if(t != null & lang != null && name != null) { String langsi=XTMPSI.getLang(lang); Topic langT=t.getTopicMap().getTopic(langsi); if(langT == null) { langT = t.getTopicMap().createTopic(); langT.addSubjectIdentifier(new Locator(langsi)); try { langT.setBaseName("Language " + lang.toUpperCase()); } catch (Exception e) { langT.setBaseName("Language " + langsi); } } String dispsi=XTMPSI.DISPLAY; Topic dispT=t.getTopicMap().getTopic(dispsi); if(dispT == null) { dispT = t.getTopicMap().createTopic(); dispT.addSubjectIdentifier(new Locator(dispsi)); dispT.setBaseName("Scope Display"); } HashSet scope=new HashSet(); if(langT!=null) scope.add(langT); if(dispT!=null) scope.add(dispT); t.setVariant(scope, name); } } public static void setData(Topic t, Topic type, String lang, String text) throws TopicMapException { if(t != null & type != null && lang != null && text != null) { String langsi=XTMPSI.getLang(lang); Topic langT=t.getTopicMap().getTopic(langsi); if(langT == null) { langT = t.getTopicMap().createTopic(); langT.addSubjectIdentifier(new Locator(langsi)); try { langT.setBaseName("Language " + lang.toUpperCase()); } catch (Exception e) { langT.setBaseName("Language " + langsi); } } t.setData(type, langT, text); } } public static Association createAssociation(TopicMap topicMap, Topic aType, Topic[] players) throws TopicMapException { Association a = topicMap.createAssociation(aType); Topic player; Topic role; Collection playerTypes; for(int i=0; i<players.length; i++) { player = players[i]; playerTypes = player.getTypes(); if(playerTypes.size() > 0) { role = (Topic) playerTypes.iterator().next(); a.addPlayer(player, role); } } return a; } public static Association createAssociation(TopicMap topicMap, Topic aType, Topic[] players, Topic[] roles) throws TopicMapException { Association a = topicMap.createAssociation(aType); Topic player; Topic role; for(int i=0; i<players.length; i++) { player = players[i]; role = roles[i]; a.addPlayer(player, role); } return a; } private static Pattern objOrArray = Pattern.compile("[^\\.\\[]+"); private static Pattern arrayIndex = Pattern.compile("[0-9]+"); private static enum curEnum { obj, arr } private static class SearchResult { public curEnum type; public JSONObject obj; public JSONArray arr; public String subName; public int subIdx; } private static SearchResult jsonSearch(JSONObject obj, String path) throws JSONException { Matcher m = objOrArray.matcher(path); SearchResult ret = new SearchResult(); //ret.type = curEnum.obj; //ret.obj = obj; while(m.find()) { if(ret.obj == null) { ret.obj = obj; } else { if(ret.type == curEnum.obj) ret.obj = ret.obj.getJSONObject(ret.subName); else ret.obj = ret.arr.getJSONObject(ret.subIdx); } ret.subName = m.group(); ret.type = curEnum.obj; if(m.hitEnd()) { break; } if(path.charAt(m.end()) == '.') { continue; } else { Matcher n = arrayIndex.matcher(path.subSequence(m.end() + 1, path.length())); if(!n.find()) throw new JSONException(path); if(ret.type == curEnum.obj) ret.arr = ret.obj.getJSONArray(ret.subName); else ret.arr = ret.arr.getJSONArray(ret.subIdx); ret.subIdx = Integer.parseInt(n.group()); ret.type = curEnum.arr; m.region(m.end() + 1 + n.end() + 1, path.length()); } } return ret; } public static int searchInt(JSONObject obj, String path) throws JSONException { SearchResult res = jsonSearch(obj, path); if(res.type == curEnum.arr) return res.arr.getInt(res.subIdx); else return res.obj.getInt(res.subName); } public static long searchLong(JSONObject obj, String path) throws JSONException { SearchResult res = jsonSearch(obj, path); if(res.type == curEnum.arr) return res.arr.getLong(res.subIdx); else return res.obj.getLong(res.subName); } public static double searchDouble(JSONObject obj, String path) throws JSONException { SearchResult res = jsonSearch(obj, path); if(res.type == curEnum.arr) return res.arr.getDouble(res.subIdx); else return res.obj.getDouble(res.subName); } public static String searchString(JSONObject obj, String path) throws JSONException { SearchResult res = jsonSearch(obj, path); if(res.type == curEnum.arr) return res.arr.getString(res.subIdx); else return res.obj.getString(res.subName); } public static JSONObject searchJSONObject(JSONObject obj, String path) throws JSONException { SearchResult res = jsonSearch(obj, path); if(res.type == curEnum.arr) return res.arr.getJSONObject(res.subIdx); else return res.obj.getJSONObject(res.subName); } public static JSONArray searchJSONArray(JSONObject obj, String path) throws JSONException { SearchResult res = jsonSearch(obj, path); if(res.type == curEnum.arr) return res.arr.getJSONArray(res.subIdx); else return res.obj.getJSONArray(res.subName); } }
13,119
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
PhotoInfoExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/flickr/PhotoInfoExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.flickr; import java.util.Collection; import java.util.HashMap; import java.util.TreeMap; 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.tools.extractors.geonames.AbstractGeoNamesExtractor; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; /** * * @author anttirt */ public class PhotoInfoExtractor extends FlickrExtractor { private static final long serialVersionUID = 1L; public boolean MAKE_GPS_OCCURRENCES = true; private FlickrPhoto photo; private Topic photoTopic; private Wandora currentAdmin; @Override public String getDescription() { return "Reads Flickr photo info and converts it to a topic map."; } @Override public String getName() { return "Flickr photo info extractor"; } @Override protected boolean extract(Wandora wandora, Context context) throws ExtractionFailure { currentAdmin = wandora; Collection<Topic> photoTopics = null; Topic photoT = null; try { photoT = getTopic(FlickrTopic.Photo); } catch(TopicMapException e) { throw new ExtractionFailure(e); } photoTopics = getWithType(context, photoT); if(photoTopics.isEmpty()) { log("Found no photo topics to look up!"); log("To extract information about photos you need to select Flickr photo topics first!"); log("Flickr photo topic has an occurrence with Flickr photo id."); } else { log("Found a total of " + photoTopics.size() + " photo topics to look up!"); } for(Topic t : photoTopics) { try { photoTopic = t; String photoID = photoTopic.getData(getOccurrence(FlickrOccur.PhotoID), getLanguage(null)); log("Extracting information for photo " + photoTopic.getDisplayName()); TreeMap<String, String> args = new TreeMap<>(); args.put("photo_id", photoID); JSONObject response = getFlickrState().unauthorizedCall("flickr.photos.getInfo", args); throwOnAPIError(response); photo = FlickrPhoto.makeFromPhotoInfo(response.getJSONObject("photo")); try { photos_getExif(); } catch(RequestFailure e) { log(e); } catch(JSONException e) { log(e); } catch(TopicMapException e) { log(e); } try { photos_geo_getLocation(); } catch(RequestFailure e) { log(e); } catch(JSONException e) { log(e); } catch(TopicMapException e) { log(e); } photo.makeTopic(this); } catch(RequestFailure e) { log(e); } catch(JSONException e) { log(e); } catch(TopicMapException e) { log(e); } catch(UserCancellation e) { log("User cancelled"); } } log("Ready."); return photoTopics.size() > 0; } private void photos_geo_getLocation() throws RequestFailure, JSONException, TopicMapException { TreeMap<String, String> args = new TreeMap<>(); args.put("photo_id", photo.ID); JSONObject response = getFlickrState().unauthorizedCall("flickr.photos.geo.getLocation", args); if(response.getString("stat").equals("ok")) { photo.Latitude = FlickrUtils.searchDouble(response, "photo.location.latitude"); photo.Longitude = FlickrUtils.searchDouble(response, "photo.location.longitude"); if(MAKE_GPS_OCCURRENCES) { Topic flickrTopic = getFlickrClass(); Topic latT = FlickrUtils.createTopic(currentMap, "latitude", flickrTopic); Topic lonT = FlickrUtils.createTopic(currentMap, "longitude", flickrTopic); photoTopic.setData(latT, getLanguage(null), String.valueOf(photo.Latitude)); photoTopic.setData(lonT, getLanguage(null), String.valueOf(photo.Longitude)); } else { AbstractGeoNamesExtractor.makeLatLong(String.valueOf(photo.Latitude), String.valueOf(photo.Longitude), photoTopic, photoTopic.getTopicMap()); } } } private void photos_getExif() throws RequestFailure, JSONException, TopicMapException, UserCancellation { TreeMap<String, String> args = new TreeMap<>(); args.put("photo_id", photo.ID); JSONObject exifResponse = getFlickrState().authorizedCall("flickr.photos.getExif", args, FlickrState.PermRead, currentAdmin); throwOnAPIError(exifResponse); JSONArray exifArray = FlickrUtils.searchJSONArray(exifResponse, "photo.exif"); Topic flickrTopic = getFlickrClass(); Topic xResT = FlickrUtils.createTopic(currentMap, "x-resolution", flickrTopic); Topic yResT = FlickrUtils.createTopic(currentMap, "y-resolution", flickrTopic); Topic xDimT = FlickrUtils.createTopic(currentMap, "x-dimension", flickrTopic); Topic yDimT = FlickrUtils.createTopic(currentMap, "y-dimension", flickrTopic); Topic resUnitT = FlickrUtils.createTopic(currentMap, "resolutionUnit", flickrTopic); Topic dateTimeT = FlickrUtils.createTopic(currentMap, "dateTime", flickrTopic); Topic exposureT = FlickrUtils.createTopic(currentMap, "exposure", flickrTopic); Topic apertureT = FlickrUtils.createTopic(currentMap, "aperture", flickrTopic); Topic focalLenT = FlickrUtils.createTopic(currentMap, "focalLength", flickrTopic); Topic colorSpaceT = FlickrUtils.createTopic(currentMap, "colorSpace", flickrTopic); Topic spaceAssocT = FlickrUtils.createTopic(currentMap, "isInSpace", flickrTopic); HashMap<String, JSONObject> exifTable = new HashMap<String, JSONObject>(); for(int i = 0; i < exifArray.length(); ++i) { try { JSONObject exifObj = exifArray.getJSONObject(i); exifTable.put(exifObj.getString("label"), exifObj); } catch(JSONException e) { log(e); continue; } } try { if(exifTable.get("Make") != null && exifTable.get("Model") != null) { Topic makeT = FlickrUtils.createTopic(currentMap, "cameraMaker", flickrTopic); Topic cameraT = FlickrUtils.createTopic(currentMap, "camera", flickrTopic); Topic makerAssoc = FlickrUtils.createTopic(currentMap, "madeBy", flickrTopic); Topic takenWithAssoc = FlickrUtils.createTopic(currentMap, "takenWith", flickrTopic); String cameraMakerName = FlickrUtils.searchString(exifTable.get("Make"), "raw._content"); String cameraModelName = FlickrUtils.searchString(exifTable.get("Model"), "raw._content"); Topic curCameraTopic = FlickrUtils.createTopic(currentMap, url(cameraModelName), " (camera)", cameraModelName, cameraT); Topic curCameraMaker = FlickrUtils.createTopic(currentMap, url(cameraMakerName), " (camera maker)", cameraMakerName, makeT); FlickrUtils.createAssociation(currentMap, makerAssoc, new Topic[] { curCameraMaker, curCameraTopic }); FlickrUtils.createAssociation(currentMap, takenWithAssoc, new Topic[] { curCameraTopic, photoTopic }); } } catch(JSONException e) { log(e); } //setDataIfNotNull(exifTable.get("Make"), "raw._content", makeT); //setDataIfNotNull(exifTable.get("Model"), "raw._content", modelT); setDataIfNotNull(exifTable.get("X-Resolution"), "raw._content", xResT); setDataIfNotNull(exifTable.get("Y-Resolution"), "raw._content", yResT); setDataIfNotNull(exifTable.get("Pixel X-Dimension"), "raw._content", xDimT); setDataIfNotNull(exifTable.get("Pixel Y-Dimension"), "raw._content", yDimT); setDataIfNotNull(exifTable.get("Resolution Unit"), "raw._content", resUnitT); setDataIfNotNull(exifTable.get("Exposure"), "raw._content", exposureT); setDataIfNotNull(exifTable.get("Aperture"), "raw._content", apertureT); setDataIfNotNull(exifTable.get("Focal Length"), "raw._content", focalLenT); JSONObject colorSpaceObj = exifTable.get("Color Space"); if(colorSpaceObj != null) { try { String colorSpaceName = FlickrUtils.searchString(colorSpaceObj, "clean._content"); Topic spaceT = FlickrUtils.createTopic(currentMap, url(colorSpaceName), " (color space)", colorSpaceName, colorSpaceT); FlickrUtils.createAssociation(currentMap, spaceAssocT, new Topic[] { spaceT, photoTopic }); } catch(JSONException e) { } } } private void setDataIfNotNull(JSONObject exifObj, String path, Topic type) { if(exifObj == null) return; try { photoTopic.setData(type, getLanguage(null), FlickrUtils.searchString(exifObj, path)); } catch(TopicMapException e) { log(e); } catch(JSONException e) { log(e); } } }
10,401
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ChooseUserDialog.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/flickr/ChooseUserDialog.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * ChooseUserDialog.java * * Created on 24. huhtikuuta 2008, 12:40 */ package org.wandora.application.tools.extractors.flickr; import java.util.ArrayList; import java.util.List; import org.wandora.application.Wandora; /** * * @author anttirt */ public class ChooseUserDialog extends javax.swing.JDialog { private static final long serialVersionUID = 1L; /** Creates new form ChooseUserDialog */ public ChooseUserDialog(java.awt.Frame parent, boolean modal, String text) { super(parent, modal); initComponents(); cancelled = false; this.pack(); this.setSize(450,200); if(parent instanceof Wandora) { Wandora w = (Wandora)parent; w.centerWindow(this); } if(text != null) wandoraLabel1.setText(text); } private boolean cancelled; public boolean wasCancelled() { return cancelled; } public String[] getUserList() { String users = this.userNameTextField.getText(); List<String> processedUserList = new ArrayList<>(); if(users != null) { if(users.indexOf(',') != -1) { String[] userList = users.split(","); for(int i=0; i<userList.length; i++) { userList[i] = userList[i].trim(); if(userList[i].length() > 0) { processedUserList.add(userList[i]); } } } else { processedUserList.add(users); } } return (String[]) processedUserList.toArray(new String[] {}); } /** 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; jPanel1 = new javax.swing.JPanel(); wandoraLabel1 = new org.wandora.application.gui.simple.SimpleLabel(); userNameTextField = new javax.swing.JTextField(); buttonPanel = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); btnCancel = new org.wandora.application.gui.simple.SimpleButton(); btnOK = new org.wandora.application.gui.simple.SimpleButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Choose user dialog"); getContentPane().setLayout(new java.awt.GridBagLayout()); jPanel1.setLayout(new java.awt.GridBagLayout()); wandoraLabel1.setText("<html><body><p>To convert Flickr user profile to a Topic Map you need to identify user profile with a username. Please write Flickr username below. To convert multiple profiles at once use comma (,) character between user names.</p></body></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(10, 10, 0, 10); jPanel1.add(wandoraLabel1, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(15, 10, 0, 10); jPanel1.add(userNameTextField, gridBagConstraints); buttonPanel.setLayout(new java.awt.GridBagLayout()); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.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(jPanel2, gridBagConstraints); btnCancel.setText("Cancel"); btnCancel.setMargin(new java.awt.Insets(1, 5, 1, 5)); btnCancel.setMaximumSize(new java.awt.Dimension(70, 23)); btnCancel.setMinimumSize(new java.awt.Dimension(70, 23)); btnCancel.setPreferredSize(new java.awt.Dimension(70, 23)); btnCancel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnCancelActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; buttonPanel.add(btnCancel, gridBagConstraints); btnOK.setText("OK"); btnOK.setMargin(new java.awt.Insets(1, 5, 1, 5)); btnOK.setMaximumSize(new java.awt.Dimension(70, 23)); btnOK.setMinimumSize(new java.awt.Dimension(70, 23)); btnOK.setPreferredSize(new java.awt.Dimension(70, 23)); btnOK.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnOKActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); buttonPanel.add(btnOK, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(15, 10, 5, 10); jPanel1.add(buttonPanel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; getContentPane().add(jPanel1, gridBagConstraints); pack(); }// </editor-fold>//GEN-END:initComponents private void btnOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOKActionPerformed cancelled = false; setVisible(false); }//GEN-LAST:event_btnOKActionPerformed private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed cancelled = true; setVisible(false); }//GEN-LAST:event_btnCancelActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* java.awt.EventQueue.invokeLater(new Runnable() { public void run() { ChooseUserDialog dialog = new ChooseUserDialog(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); */ } // Variables declaration - do not modify//GEN-BEGIN:variables private org.wandora.application.gui.simple.SimpleButton btnCancel; private org.wandora.application.gui.simple.SimpleButton btnOK; private javax.swing.JPanel buttonPanel; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JTextField userNameTextField; private org.wandora.application.gui.simple.SimpleLabel wandoraLabel1; // End of variables declaration//GEN-END:variables }
9,103
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
GroupSearchDialog.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/flickr/GroupSearchDialog.java
/* * GroupSearchDialog.java * * Created on 27. toukokuuta 2008, 11:55 */ package org.wandora.application.tools.extractors.flickr; import java.awt.Frame; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.SortedMap; import java.util.TreeMap; import javax.swing.DefaultListModel; 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.gui.UIConstants; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; /** * * @author anttirt */ public class GroupSearchDialog extends javax.swing.JDialog { private static final long serialVersionUID = 1L; private FlickrState flickrState; private DefaultListModel listModel; private Frame parentFrame; private HashMap<String, Topic> allGroups; private ArrayList<Topic> selectedGroups; private FlickrExtractor flickrExtractor; private boolean cancelled; private volatile boolean stopSearch; public Collection<Topic> selection() { return selectedGroups; } /** Creates new form GroupSearchDialog */ public GroupSearchDialog(java.awt.Frame parent, boolean modal, FlickrState state, FlickrExtractor extractor) { super(parent, modal); initComponents(); flickrState = state; flickrExtractor = extractor; parentFrame = parent; listModel = new DefaultListModel(); groupList.setModel(listModel); allGroups = new HashMap<String, Topic>(); if(parent instanceof Wandora) { Wandora admin = (Wandora)parent; admin.centerWindow(this); } groupList.setFont(UIConstants.plainFont); cancelled = true; stopSearch = 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. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { wandoraLabel1 = new org.wandora.application.gui.simple.SimpleLabel(); searchText = new org.wandora.application.gui.simple.SimpleField(); jScrollPane1 = new javax.swing.JScrollPane(); groupList = new javax.swing.JList(); btnOk = new org.wandora.application.gui.simple.SimpleButton(); btnCancel = new org.wandora.application.gui.simple.SimpleButton(); wandoraLabel2 = new org.wandora.application.gui.simple.SimpleLabel(); btnSearch = new org.wandora.application.gui.simple.SimpleButton(); warningLabel = new org.wandora.application.gui.simple.SimpleLabel(); warningLabel.setFont(UIConstants.smallButtonLabelFont); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Flickr group search"); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { onWindowClosing(evt); } }); wandoraLabel1.setText("<html><body><p>Please enter some text to search for in Flickr groups.</p></body></html>"); jScrollPane1.setViewportView(groupList); btnOk.setText("OK"); btnOk.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnOkActionPerformed(evt); } }); btnCancel.setText("Cancel"); btnCancel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnCancelActionPerformed(evt); } }); wandoraLabel2.setText("<html><body><p>Select one or more groups from the list.</p></body></html>"); btnSearch.setText("Search"); btnSearch.setMargin(new java.awt.Insets(1, 4, 2, 4)); btnSearch.setPreferredSize(new java.awt.Dimension(70, 20)); btnSearch.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSearchActionPerformed(evt); } }); warningLabel.setText("<html><body><p>Warning: Getting all the information for even a single group may take a very long time; it's recommended to only get information for one group at a time.</p></body></html>"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(searchText, javax.swing.GroupLayout.DEFAULT_SIZE, 489, Short.MAX_VALUE) .addComponent(wandoraLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 489, Short.MAX_VALUE) .addComponent(btnSearch, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(wandoraLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 489, Short.MAX_VALUE)) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(btnOk, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(13, 13, 13)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 489, Short.MAX_VALUE) .addComponent(warningLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 489, Short.MAX_VALUE)) .addContainerGap()))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(wandoraLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(searchText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnSearch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(wandoraLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 237, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(warningLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnCancel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnOk, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private GroupRequestThread reqThread; private class GroupRequestThread implements Runnable { public void run() { try { SortedMap<String, String> args = new TreeMap(); args.put("text", URLEncoder.encode(searchText.getText(), "UTF-8")); JSONObject result; // if we have read permissions we might get additional stuff if the user is age 18+ if(flickrState.PermissionLevel.equals(FlickrState.PermNone)) result = flickrState.unauthorizedCall("flickr.groups.search", args); else result = flickrState.authorizedCall("flickr.groups.search", args, FlickrState.PermRead, parentFrame); JSONArray groupArray = FlickrUtils.searchJSONArray(result, "groups.group"); for(int i = 0; i < groupArray.length() && !stopSearch; ++i) { try { final JSONObject group = groupArray.getJSONObject(i); final String name = group.getString("name"); final FlickrGroup g = new FlickrGroup(group); final Topic groupTopic = g.makeTopic(flickrExtractor); SwingUtilities.invokeLater(new Runnable() { public void run() { listModel.addElement(name); allGroups.put(name, groupTopic); }}); } catch(JSONException e) {} } } catch(FlickrExtractor.RequestFailure e) { } catch(UnsupportedEncodingException e) { } catch(JSONException e) { } catch(TopicMapException e) { } catch(FlickrExtractor.UserCancellation e) { SwingUtilities.invokeLater(new Runnable() { public void run() { flickrExtractor.log("User cancelled"); } }); } finally { SwingUtilities.invokeLater(new Runnable() { public void run() { reqThread = null; btnSearch.setText("Search"); btnSearch.setEnabled(true); } }); } } } private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSearchActionPerformed if(reqThread != null) return; listModel.clear(); allGroups.clear(); btnSearch.setText("Searching..."); btnSearch.setEnabled(false); reqThread = new GroupRequestThread(); new Thread(reqThread).start(); }//GEN-LAST:event_btnSearchActionPerformed private void btnOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOkActionPerformed stopSearch = true; cancelled = false; selectedGroups = new ArrayList<Topic>(); for(Object elem : groupList.getSelectedValues()) { selectedGroups.add(allGroups.get(elem)); } setVisible(false); }//GEN-LAST:event_btnOkActionPerformed private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed cancelled = true; stopSearch = true; setVisible(false); }//GEN-LAST:event_btnCancelActionPerformed private void onWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_onWindowClosing cancelled = true; stopSearch = true; }//GEN-LAST:event_onWindowClosing public boolean wasCancelled() { return cancelled; } /** * @param args the command line arguments * public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { GroupSearchDialog dialog = new GroupSearchDialog(new javax.swing.JFrame(), true, null); dialog.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); } */ // Variables declaration - do not modify//GEN-BEGIN:variables private org.wandora.application.gui.simple.SimpleButton btnCancel; private org.wandora.application.gui.simple.SimpleButton btnOk; private org.wandora.application.gui.simple.SimpleButton btnSearch; private javax.swing.JList groupList; private javax.swing.JScrollPane jScrollPane1; private org.wandora.application.gui.simple.SimpleField searchText; private org.wandora.application.gui.simple.SimpleLabel wandoraLabel1; private org.wandora.application.gui.simple.SimpleLabel wandoraLabel2; private javax.swing.JLabel warningLabel; // End of variables declaration//GEN-END:variables }
14,124
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AuthDisplay.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/flickr/AuthDisplay.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * AuthDisplay.java * * Created on 24. huhtikuuta 2008, 19:03 */ package org.wandora.application.tools.extractors.flickr; import java.awt.Color; import javax.swing.JLabel; import org.wandora.application.gui.simple.SimpleLabel; /** * * @author anttirt */ public class AuthDisplay extends javax.swing.JPanel { private static final long serialVersionUID = 1L; private JLabel[] curLabels, reqLabels; public int requiredAuthLevel, currentAuthLevel; private FlickrState flickrState; public AuthDisplay() { initComponents(); } /** Creates new form AuthDisplay */ public AuthDisplay(FlickrState state, String reqAuth) { initComponents(); flickrState = state; setRequiredLevel(reqAuth); } public void setRequiredLevel(String requiredAuth) { curLabels = new JLabel[] { gotNone, gotRead, gotWrite, gotDelete }; reqLabels = new JLabel[] { reqNone, reqRead, reqWrite, reqDelete }; requiredAuthLevel = FlickrState.getAuthLevel(requiredAuth); currentAuthLevel = FlickrState.getAuthLevel(flickrState.PermissionLevel); Color validGreen = new Color(30, 220, 30); Color invalidRed = new Color(220, 30, 30); for(int i = 0; i <= currentAuthLevel; ++i) { curLabels[i].setForeground(validGreen); } for(int i = 0; i <= requiredAuthLevel; ++i) { if(i <= currentAuthLevel) reqLabels[i].setForeground(validGreen); else reqLabels[i].setForeground(invalidRed); } } /** 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; reqNone = new SimpleLabel(); gotNone = new SimpleLabel(); reqRead = new SimpleLabel(); gotRead = new SimpleLabel(); reqWrite = new SimpleLabel(); gotWrite = new SimpleLabel(); reqDelete = new SimpleLabel(); gotDelete = new SimpleLabel(); lblPermLevel = new SimpleLabel(); lblAuthLevel = new SimpleLabel(); setLayout(new java.awt.GridBagLayout()); reqNone.setForeground(new java.awt.Color(102, 102, 102)); reqNone.setText("none"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); add(reqNone, gridBagConstraints); gotNone.setForeground(new java.awt.Color(102, 102, 102)); gotNone.setText("none"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); add(gotNone, gridBagConstraints); reqRead.setForeground(new java.awt.Color(102, 102, 102)); reqRead.setText("read"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); add(reqRead, gridBagConstraints); gotRead.setForeground(new java.awt.Color(102, 102, 102)); gotRead.setText("read"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); add(gotRead, gridBagConstraints); reqWrite.setForeground(new java.awt.Color(102, 102, 102)); reqWrite.setText("write"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); add(reqWrite, gridBagConstraints); gotWrite.setForeground(new java.awt.Color(102, 102, 102)); gotWrite.setText("write"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); add(gotWrite, gridBagConstraints); reqDelete.setForeground(new java.awt.Color(102, 102, 102)); reqDelete.setText("delete"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 4; add(reqDelete, gridBagConstraints); gotDelete.setForeground(new java.awt.Color(102, 102, 102)); gotDelete.setText("delete"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 4; add(gotDelete, gridBagConstraints); lblPermLevel.setText("Required authorization:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 10); add(lblPermLevel, gridBagConstraints); lblAuthLevel.setText("Given authorization:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 10); add(lblAuthLevel, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel gotDelete; private javax.swing.JLabel gotNone; private javax.swing.JLabel gotRead; private javax.swing.JLabel gotWrite; private javax.swing.JLabel lblAuthLevel; private javax.swing.JLabel lblPermLevel; private javax.swing.JLabel reqDelete; private javax.swing.JLabel reqNone; private javax.swing.JLabel reqRead; private javax.swing.JLabel reqWrite; // End of variables declaration//GEN-END:variables }
6,891
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
GroupInfoExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/flickr/GroupInfoExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.flickr; import java.util.Collection; import java.util.TreeMap; 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.topicmap.Topic; import org.wandora.topicmap.TopicMapException; /** * * @author anttirt */ public class GroupInfoExtractor extends FlickrExtractor { private static final long serialVersionUID = 1L; private FlickrGroup curGroup; private Topic curGroupTopic; @Override public String getDescription() { return "Extracts information from a flickr group. Gets the list of photos in a group's pool."; } @Override public String getName() { return "Flickr group info extractor"; } @Override protected boolean extract(Wandora wandora, Context context) throws ExtractionFailure { Collection<Topic> groupTopics = null; Topic groupT = null; try { groupT = getTopic(FlickrTopic.Group); } catch(TopicMapException e) { throw new ExtractionFailure(e); } groupTopics = getWithType(context, groupT); if(groupTopics.isEmpty()) { log("Unable to find any groups in context."); GroupSearchDialog dlg = new GroupSearchDialog(wandora, true, getFlickrState(), this); setState(INVISIBLE); dlg.setVisible(true); setState(VISIBLE); if(dlg.wasCancelled()) { log("User cancelled."); return false; } groupTopics = dlg.selection(); } else { log("Looking up info for " + groupTopics.size() + " groups."); } for(Topic t : groupTopics) { try { curGroup = new FlickrGroup(); curGroup.ID = t.getData(getOccurrence(FlickrOccur.NSID), getLanguage(null)); curGroup.Name = t.getDisplayName(); curGroupTopic = t; log("Getting info for group " + curGroup.Name); getPhotoList(wandora, "flickr.groups.pools.getPhotos", FlickrAssoc.InGroupPool, "in the photo pool of "); } catch(JSONException e) { log(e); } catch(RequestFailure e) { log(e); } catch(TopicMapException e) { log(e); } catch(UserCancellation e) { log("User cancelled."); } } return !groupTopics.isEmpty(); } private static final int photosPerPage = 250; private void getPhotoList(Wandora currentAdmin, String jsonAPI, FlickrAssoc association, String relationship) throws JSONException, TopicMapException, RequestFailure, ExtractionFailure, UserCancellation { int totalPhotos = 0; int photosReceived = 0; TreeMap<String, String> args = new TreeMap(); args.put("group_id", curGroup.ID); args.put("extras", "date_taken,date_upload,o_dims,geo,last_update,license,media,owner_name,tags,views"); args.put("per_page", "" + photosPerPage); JSONObject result = getFlickrState().authorizedCall(jsonAPI, args, FlickrState.PermRead, currentAdmin); totalPhotos = FlickrUtils.searchInt(result, "photos.total"); final int pageCount = 1 + totalPhotos / photosPerPage; getCurrentLogger().setProgressMax(totalPhotos); log("-- Getting info for " + totalPhotos + " photos in " + curGroup.Name + "'s pool."); for(int nextPageIndex = 2; nextPageIndex <= (pageCount + 1); ++nextPageIndex) { getCurrentLogger().setProgress(photosReceived); JSONArray photosArray = FlickrUtils.searchJSONArray(result, "photos.photo"); int received = photosArray.length(); log("-- -- Getting info for photos " + (photosReceived + 1) + " - " + (photosReceived + received) + " out of " + totalPhotos); for(int i = 0; i < received; ++i) { FlickrPhoto p = FlickrPhoto.makeFromPublicPhotoList(photosArray.getJSONObject(i)); Topic photoTopic = p.makeTopic(this); FlickrUtils.createAssociation(currentMap, getAssociation(association), new Topic[] { photoTopic, curGroupTopic }); } photosReceived += received; /* if(photosReceived >= totalPhotos || received <= perPage) { break; } */ if(forceStop()) { log("-- -- Cancellation requested; finished getting info for " + photosReceived + " out of " + totalPhotos + " photos."); break; } args.clear(); args.put("group_id", curGroup.ID); args.put("extras", "date_taken,date_upload,o_dims,geo,last_update,license,media,owner_name,tags,views"); args.put("per_page", "" + photosPerPage); args.put("page", "" + nextPageIndex); result = getFlickrState().authorizedCall(jsonAPI, args, FlickrState.PermRead, currentAdmin); } if(photosReceived < totalPhotos) { log("" + (totalPhotos - photosReceived) + " photos not sent by flickr"); } } }
6,283
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
FlickrPerson.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/flickr/FlickrPerson.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.flickr; import org.json.JSONException; import org.json.JSONObject; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; /** * * @author anttirt */ public class FlickrPerson { String ID; String UserName; String RealName; String Location; String PhotosURL; String ProfileURL; int PhotoCount; public FlickrPerson() { } public FlickrPerson(JSONObject obj) throws JSONException { ID = FlickrUtils.searchString(obj, "nsid"); UserName = FlickrUtils.searchString(obj, "username._content"); RealName = FlickrUtils.searchString(obj, "realname._content"); Location = FlickrUtils.searchString(obj, "location._content"); PhotosURL = FlickrUtils.searchString(obj, "photosurl._content"); ProfileURL = FlickrUtils.searchString(obj, "profileurl._content"); PhotoCount = FlickrUtils.searchInt(obj, "photos.count._content"); } public Topic makeTopic(FlickrExtractor extractor) throws TopicMapException { if(ProfileURL == null || ProfileURL.equals("")) { ProfileURL = "http://www.flickr.com/people/" + ID + "/"; } Topic ret = FlickrUtils.createRaw( extractor.getCurrentMap(), ProfileURL, " (flickr profile)", UserName, extractor.getTopic(FlickrTopic.Profile)); ret.setData(extractor.getOccurrence(FlickrOccur.NSID), extractor.getLanguage(null), ID); return ret; } }
2,469
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
FlickrExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/flickr/FlickrExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * FlickrExtractor.java * * Created on March 19, 2008, 12:34 AM */ package org.wandora.application.tools.extractors.flickr; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.Charset; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.SortedMap; import java.util.TreeMap; import javax.swing.Icon; import org.json.JSONException; import org.json.JSONObject; import org.wandora.application.Wandora; import org.wandora.application.WandoraToolType; import org.wandora.application.contexts.Context; import org.wandora.application.gui.UIBox; import org.wandora.application.tools.AbstractWandoraTool; 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; /** * * @author anttirt */ public abstract class FlickrExtractor extends AbstractWandoraTool { private static final long serialVersionUID = 1L; @Override public WandoraToolType getType() { return WandoraToolType.createExtractType(); } @Override public String getName() { return "Flickr api extractor (" + getDescription() + ")"; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_flickr.png"); } protected TopicMap currentMap; @Override public boolean isConfigurable() { return true; } @Override public void configure(Wandora wandora, org.wandora.utils.Options options, String prefix) { if(staticState == null) staticState = new FlickrState(); AuthConfigDialog dlg = new AuthConfigDialog(wandora, true, getFlickrState()); dlg.setVisible(true); } @Override public void execute(Wandora wandora, Context context) { if(staticState == null) staticState = new FlickrState(); currentMap = wandora.getTopicMap(); try { setDefaultLogger(); extract(wandora, context); } catch(ExtractionFailure e) { log(e); } setState(WAIT); } protected static class ExtractionFailure extends Exception { private static final long serialVersionUID = 1L; public ExtractionFailure(String message) { super(message); } public ExtractionFailure(Throwable cause) { super(cause); } public ExtractionFailure(String message, Throwable cause) { super(message, cause); } } protected static class RequestFailure extends Exception { private static final long serialVersionUID = 1L; public RequestFailure(String message) { super(message); } public RequestFailure(Throwable cause) { super(cause); } public RequestFailure(String message, Throwable cause) { super(message, cause); } } public static class UserCancellation extends Exception { private static final long serialVersionUID = 1L; public UserCancellation(String message) { super(message); } public UserCancellation(Throwable cause) { super(cause); } public UserCancellation(String message, Throwable cause) { super(message, cause); } } public static void main(String[] args) { try { JSONObject obj = new JSONObject( "{\"foo\" : {" + " \"bar\" : [ 1, 2, 3, 4 ]," + "\"baz\" : \"hablabl\" }" + "}"); int foo = FlickrUtils.searchInt(obj, "foo.bar[2]"); String baz = FlickrUtils.searchString(obj, "foo.baz"); } catch(Exception e) { System.out.println(e.getMessage()); } } protected static String url(String str) { if(str == null) return str; try { return URLEncoder.encode(str, "UTF-8"); } catch(Exception e) { return str; } } public TopicMap getCurrentMap() { return currentMap; } protected static String createSignature(SortedMap<String, String> arguments) throws RequestFailure { StringBuilder builder = new StringBuilder(FlickrState.ApiSecret); for(SortedMap.Entry<String, String> e : arguments.entrySet()) { builder.append(e.getKey()); builder.append(e.getValue()); } //logger.log("Created signature: " + builder.toString()); MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch(NoSuchAlgorithmException e) { throw new RequestFailure("MD5 not available", e); } Charset ASCII = Charset.forName("ISO-8859-1"); md.update(builder.toString().getBytes(ASCII)); builder.setLength(0); byte[] hash = md.digest(); for(int i = 0; i < hash.length; ++i) { builder.append(String.format("%02x", hash[i])); } String ret = builder.toString(); return ret; } protected static String getFrob() throws RequestFailure { TreeMap<String, String> args = new TreeMap<String, String>(); args.put("api_key", FlickrState.ApiKey); args.put("method", "flickr.auth.getFrob"); args.put("format", "json"); args.put("nojsoncallback", "1"); args.put("api_sig", createSignature(args)); try { JSONObject obj = new JSONObject(IObox.doUrl(new URL(FlickrState.makeRESTURL(args)))); if(!obj.getString("stat").equals("ok")) throw new RequestFailure(String.valueOf(obj.getInt("code")) + ": " + obj.getString("message")); return FlickrUtils.searchString(obj, "frob._content"); } catch(JSONException e) { throw new RequestFailure("Invalid json in frob response", e); } catch(MalformedURLException e) { throw new RequestFailure("Attempted to construct malformed URL", e); } catch(IOException e) { throw new RequestFailure("IOException while requesting frob", e); } } public Topic getLanguage(String id) throws TopicMapException { Topic lanT = currentMap.getTopic(XTMPSI.getLang(id)); if(lanT == null) { lanT = currentMap.createTopic(); lanT.addSubjectIdentifier(new Locator(XTMPSI.getLang(id))); lanT.setBaseName(""); } return lanT; } public Topic getFlickrClass() throws TopicMapException { Locator loc = new Locator("http://www.flickr.com"); Topic flickrClass = currentMap.getTopic(loc); if(flickrClass == null) { flickrClass = currentMap.createTopic(); flickrClass.addSubjectIdentifier(new Locator("http://www.flickr.com")); flickrClass.setBaseName("Flickr"); flickrClass.addType(getWandoraClass()); } return flickrClass; } public Topic getWandoraClass() throws TopicMapException { Locator loc = new Locator(TMBox.WANDORACLASS_SI); Topic wandoraClass = currentMap.getTopic(loc); if(wandoraClass == null) { wandoraClass = currentMap.createTopic(); wandoraClass.addSubjectIdentifier( new Locator(TMBox.WANDORACLASS_SI)); wandoraClass.setBaseName("Wandora class"); } return wandoraClass; } public Topic getLicenseTopic(int licenseID) throws TopicMapException { Topic licenseT = FlickrUtils.createTopic(currentMap, "license", getFlickrClass()); Topic retT = null; switch(licenseID) { case 0: retT = FlickrUtils.createTopic(currentMap, "allRightsReserved", " (license)", "All rights reserved", licenseT); break; case 1: retT = FlickrUtils.createRaw(currentMap, "http://creativecommons.org/licenses/by-nc-sa/2.0/", " (license)", "Attribution-NonCommercial-ShareAlike License", licenseT); break; case 2: retT = FlickrUtils.createRaw(currentMap, "http://creativecommons.org/licenses/by-nc/2.0/", " (license)", "Attribution-NonCommercial License", licenseT); break; case 3: retT = FlickrUtils.createRaw(currentMap, "http://creativecommons.org/licenses/by-nc-nd/2.0/", " (license)", "Attribution-NonCommercial-NoDerivs License", licenseT); break; case 4: retT = FlickrUtils.createRaw(currentMap, "http://creativecommons.org/licenses/by/2.0/", " (license)", "Attribution License", licenseT); break; case 5: retT = FlickrUtils.createRaw(currentMap, "http://creativecommons.org/licenses/by-sa/2.0/", " (license)", "Attribution-ShareAlike License", licenseT); break; case 6: retT = FlickrUtils.createRaw(currentMap, "http://creativecommons.org/licenses/by-nd/2.0/", " (license)", "Attribution-NoDerivs License", licenseT); break; default: } return retT; } public Topic getTopic(FlickrTopic topicClass) throws TopicMapException { Topic flickrClass = getFlickrClass(); switch(topicClass) { case Group: return FlickrUtils.createTopic(currentMap, "flickrGroup", flickrClass); case Profile: return FlickrUtils.createTopic(currentMap, "flickrProfile", flickrClass); case Photo: return FlickrUtils.createTopic(currentMap, "flickrPhoto", flickrClass); case Tag: return FlickrUtils.createTopic(currentMap, "flickrTag", flickrClass); default: return null; } } public Topic getOccurrence(FlickrOccur occurrenceClass) throws TopicMapException { Topic flickrClass = getFlickrClass(); switch(occurrenceClass) { case Description: return FlickrUtils.createTopic(currentMap, "description", flickrClass); case MemberCount: return FlickrUtils.createTopic(currentMap, "memberCount", flickrClass); case NSID: return FlickrUtils.createTopic(currentMap, "NSID", flickrClass); case Location: return FlickrUtils.createTopic(currentMap, "location", flickrClass); case PhotoID: return FlickrUtils.createTopic(currentMap, "photoID", flickrClass); default: return null; } } public Topic getAssociation(FlickrAssoc assocClass) throws TopicMapException { Topic flickrClass = getFlickrClass(); switch(assocClass) { case Membership: return FlickrUtils.createTopic(currentMap, "isMember", flickrClass); case Ownership: return FlickrUtils.createTopic(currentMap, "isOwner", flickrClass); case Description: return FlickrUtils.createTopic(currentMap, "describes", flickrClass); case Favorite: return FlickrUtils.createTopic(currentMap, "isFavorite", flickrClass); case License: return FlickrUtils.createTopic(currentMap, "governs", flickrClass); case InGroupPool: return FlickrUtils.createTopic(currentMap, "inGroupPool", flickrClass); default: return null; } } protected static void throwOnAPIError(JSONObject obj) throws RequestFailure { try { if(!obj.getString("stat").equals("ok")) throw new RequestFailure(String.valueOf(obj.getInt("code")) + ": " + obj.getString("message")); } catch(JSONException e) { throw new RequestFailure("Invalid JSON response structure", e); } } private static FlickrState staticState; protected FlickrState getFlickrState() { return staticState; } protected abstract boolean extract(Wandora admin, Context context) throws ExtractionFailure; public final Collection<Topic> getWithType( Context context, Topic type) { Iterator objs = context.getContextObjects(); ArrayList<Topic> topicList = new ArrayList<>(); if(type == null) return topicList; try { while(objs.hasNext()) { Topic t = (Topic)objs.next(); if(t == null) continue; boolean isRightType = false; for(Topic typeT : t.getTypes()) { if(typeT.mergesWithTopic(type)) { isRightType = true; break; } } if(isRightType) topicList.add(t); } } catch(TopicMapException e) { log(e); } return topicList; } }
14,482
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
FlickrState.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/flickr/FlickrState.java
package org.wandora.application.tools.extractors.flickr; import java.awt.Frame; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import org.json.JSONException; import org.json.JSONObject; import org.wandora.application.tools.extractors.flickr.FlickrExtractor.RequestFailure; import org.wandora.application.tools.extractors.flickr.FlickrExtractor.UserCancellation; import org.wandora.utils.IObox; public class FlickrState { public String Frob; public String Token; public String PermissionLevel; public String AuthedUserName; public String LastUserName; public String LastUserID; public TreeMap<String, String> Users; public TreeMap<String, String> Groups; public static final String PermNone = "none", PermRead = "read", PermWrite = "write", PermDelete = "delete", ApiKey = "1eab422260e1c488c998231f290330eb", // "38e1943f013d3625295b7549d3d2898a", //"1eab422260e1c488c998231f290330eb", ApiSecret = "d2094033862921ac", // "e50f5106e5684bad", //"d2094033862921ac", RESTbase = "https://api.flickr.com/services/rest/"; public static int getAuthLevel(String authLevel) { if(authLevel.equals(FlickrState.PermNone)) return 0; if(authLevel.equals(FlickrState.PermRead)) return 1; if(authLevel.equals(FlickrState.PermWrite)) return 2; if(authLevel.equals(FlickrState.PermDelete)) return 3; return -1; } public static String getAuthLevel(int authLevel) { switch(authLevel) { case 0: return FlickrState.PermNone; case 1: return FlickrState.PermRead; case 2: return FlickrState.PermWrite; case 3: return FlickrState.PermDelete; default: return null; } } public FlickrState() { super(); Users = new TreeMap<String, String>(); Groups = new TreeMap<String, String>(); PermissionLevel = PermNone; } public static String makeRESTURL(Map<String, String> params) { return makeRESTURL(params, FlickrState.RESTbase); } public static String makeRESTURL(Map<String, String> params, String baseUrl) { char introducer = '?'; StringBuilder bldr = new StringBuilder(baseUrl); for(Map.Entry<String, String> e : params.entrySet()) { bldr.append(introducer + e.getKey() + '=' + e.getValue()); introducer = '&'; } return bldr.toString(); } public JSONObject unauthorizedCall(String method, SortedMap<String, String> args) throws RequestFailure { args.put("method", method); args.put("api_key", ApiKey); args.put("format", "json"); args.put("nojsoncallback", "1"); try { return new JSONObject(IObox.doUrl(new URL(makeRESTURL(args)))); } catch (MalformedURLException e) { throw new RequestFailure("", e); } catch (JSONException e) { throw new RequestFailure("", e); } catch (IOException e) { throw new RequestFailure("", e); } } public void authenticate(String perms, Frame dlgParent) throws RequestFailure, UserCancellation { if (Frob == null) { Frob = FlickrExtractor.getFrob(); } if (Token == null || !validToken(perms)) { String loginURL = getLoginURL(perms); TokenRequestDialog dlg = new TokenRequestDialog(dlgParent, true, loginURL, perms, this); dlg.setVisible(true); if (dlg.cancelled()) { throw new UserCancellation("User cancelled authorization"); } Token = requestToken(); } } public JSONObject authorizedCall(String method, SortedMap<String, String> args, String perms, Frame dlgParent) throws RequestFailure, UserCancellation { authenticate(perms, dlgParent); args.put("method", method); args.put("auth_token", Token); args.put("api_key", ApiKey); args.put("format", "json"); args.put("nojsoncallback", "1"); args.put("api_sig", FlickrExtractor.createSignature(args)); String url = makeRESTURL(args); try { return new JSONObject(IObox.doUrl(new URL(url))); } catch (MalformedURLException e) { throw new RequestFailure("Malformed url:\n" + url, e); } catch (JSONException e) { throw new RequestFailure("Invalid response JSON, url:\n" + url, e); } catch (IOException e) { throw new RequestFailure("Failure with call, url:\n" + url, e); } } public boolean validToken(String neededPerms) throws RequestFailure { if (Token == null) { return false; } if (neededPerms.equals(PermNone)) { return true; } TreeMap<String, String> args = new TreeMap<String, String>(); args.put("method", "flickr.auth.checkToken"); args.put("api_key", ApiKey); args.put("auth_token", Token); args.put("format", "json"); args.put("nojsoncallback", "1"); args.put("api_sig", FlickrExtractor.createSignature(args)); try { String response = IObox.doUrl(new URL(makeRESTURL(args))); JSONObject obj = new JSONObject(response); if (!obj.getString("stat").equals("ok")) { if (obj.getInt("code") == 98) { return false; } throw new RequestFailure(String.valueOf(obj.getInt("code")) + ": " + obj.getString("message")); } String tokenPerms = FlickrUtils.searchString(obj, "auth.perms._content"); PermissionLevel = tokenPerms; return getAuthLevel(tokenPerms) >= getAuthLevel(neededPerms); } catch (JSONException e) { throw new RequestFailure("Received malformed json", e); } catch (MalformedURLException e) { throw new RequestFailure("Attempted to construct malformed URL", e); } catch (IOException e) { throw new RequestFailure("IOException while requesting token check", e); } } public String requestToken() throws RequestFailure { TreeMap<String, String> args = new TreeMap<String, String>(); args.put("method", "flickr.auth.getToken"); args.put("api_key", ApiKey); args.put("frob", Frob); args.put("nojsoncallback", "1"); args.put("format", "json"); args.put("api_sig", FlickrExtractor.createSignature(args)); try { JSONObject obj = new JSONObject(IObox.doUrl(new URL(makeRESTURL(args)))); if (!obj.getString("stat").equals("ok")) { throw new RequestFailure("Error while trying to request authorization token.\nDid you follow the url and authorize Wandora?\n\n" + String.valueOf(obj.getInt("code")) + ": " + obj.getString("message")); } LastUserID = FlickrUtils.searchString(obj, "auth.user.nsid"); LastUserName = FlickrUtils.searchString(obj, "auth.user.username"); PermissionLevel = FlickrUtils.searchString(obj, "auth.perms._content"); return FlickrUtils.searchString(obj, "auth.token._content"); } catch (MalformedURLException e) { throw new RequestFailure("Attempted to create malformed URL", e); } catch (JSONException e) { throw new RequestFailure("Received invalid json data", e); } catch (IOException e) { throw new RequestFailure("Error while connecting", e); } } public String getLoginURL(String perms) throws RequestFailure { TreeMap<String, String> args = new TreeMap<String, String>(); args.put("api_key", ApiKey); args.put("perms", perms); args.put("frob", Frob); args.put("api_sig", FlickrExtractor.createSignature(args)); return makeRESTURL(args, "https://www.flickr.com/services/auth/"); } }
8,370
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AuthorizationBox.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/flickr/AuthorizationBox.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * AuthorizationBox.java * * Created on 15. huhtikuuta 2008, 17:22 */ package org.wandora.application.tools.extractors.flickr; /** * * @author anttirt */ public class AuthorizationBox extends javax.swing.JPanel { private static final long serialVersionUID = 1L; private java.awt.Frame dlgParent; private FlickrState flickrState; private String authRequirements; /** Creates new form AuthorizationBox */ public AuthorizationBox(java.awt.Frame parent, FlickrState state, String authReq) { dlgParent = parent; flickrState = state; authRequirements = authReq; initComponents(); } /** 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() { jTabbedPane1 = new javax.swing.JTabbedPane(); jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); authDisplay = new AuthDisplay(this.flickrState, this.authRequirements); jPanel2 = new javax.swing.JPanel(); authBtn = new javax.swing.JButton(); cmbAuthRequest = new javax.swing.JComboBox(); jLabel3 = new javax.swing.JLabel(); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); jLabel1.setText("If the current authorization level is not sufficient,"); jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11)); jLabel2.setText("this action will prompt for further authorization."); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(jLabel2) .addComponent(authDisplay, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(32, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1) .addGap(1, 1, 1) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(authDisplay, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(20, 20, 20)) ); jTabbedPane1.addTab("Authentication status", jPanel1); authBtn.setFont(new java.awt.Font("Tahoma", 1, 11)); authBtn.setText("Authenticate"); authBtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { authBtnActionPerformed(evt); } }); cmbAuthRequest.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "none", "read", "write", "delete" })); jLabel3.setText("Authorization level:"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap(116, Short.MAX_VALUE) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(cmbAuthRequest, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING)) .addGap(110, 110, 110)) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(95, 95, 95) .addComponent(authBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(95, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(cmbAuthRequest, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(authBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jTabbedPane1.addTab("Manage authentication", jPanel2); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); }// </editor-fold>//GEN-END:initComponents private void authBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_authBtnActionPerformed try { flickrState.authenticate((String)cmbAuthRequest.getSelectedItem(), dlgParent); authDisplay.setRequiredLevel(FlickrState.getAuthLevel(authDisplay.requiredAuthLevel)); } catch(FlickrExtractor.RequestFailure e) { } catch(FlickrExtractor.UserCancellation e) { } }//GEN-LAST:event_authBtnActionPerformed // <editor-fold defaulstate="collapsed" desc="Variable declarations"> // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton authBtn; private org.wandora.application.tools.extractors.flickr.AuthDisplay authDisplay; private javax.swing.JComboBox cmbAuthRequest; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JTabbedPane jTabbedPane1; // End of variables declaration//GEN-END:variables // </editor-fold> }
8,337
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
PersonInfoExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/flickr/PersonInfoExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.flickr; import java.util.ArrayList; import java.util.Collection; import java.util.SortedMap; import java.util.TreeMap; 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.topicmap.Topic; import org.wandora.topicmap.TopicMapException; import org.wandora.utils.Tuples.T2; /** * * @author anttirt */ public class PersonInfoExtractor extends FlickrExtractor { private static final long serialVersionUID = 1L; private static final int photosPerPage = 250; private FlickrPerson curPerson; private Topic curPersonTopic; private Collection<T2<FlickrPerson, Topic>> promptForUsers(Wandora admin) throws ExtractionFailure { ArrayList<T2<FlickrPerson, Topic>> people = new ArrayList<>(); ChooseUserDialog dlg = new ChooseUserDialog(admin, true, null); setState(INVISIBLE); dlg.setVisible(true); if(dlg.wasCancelled()) { return null; } setState(VISIBLE); for(String username : dlg.getUserList()) { try { SortedMap<String, String> userInfoArgs = new TreeMap<>(); userInfoArgs.put("username", username); JSONObject obj = getFlickrState().unauthorizedCall("flickr.people.findByUsername", userInfoArgs); if(!"ok".equals(obj.getString("stat"))) continue; FlickrPerson p = new FlickrPerson(); p.UserName = FlickrUtils.searchString(obj, "user.username._content"); p.ID = FlickrUtils.searchString(obj, "user.nsid"); people.add(new T2<FlickrPerson, Topic>(p, p.makeTopic(this))); } catch(JSONException e) { throw new ExtractionFailure(e); } catch(RequestFailure e) { throw new ExtractionFailure(e); } catch(TopicMapException e) { throw new ExtractionFailure(e); } } return people; } @Override protected boolean extract(Wandora wandora, Context context) throws ExtractionFailure { Collection<T2<FlickrPerson, Topic>> people = null; Topic profileT = null; Topic nsidT = null; Topic langT = null; try { profileT = getTopic(FlickrTopic.Profile); nsidT = getOccurrence(FlickrOccur.NSID); langT = getLanguage(null); } catch(TopicMapException e) { throw new ExtractionFailure(e); } Collection<Topic> contextUserTopics = getWithType(context, profileT); if(contextUserTopics.isEmpty()) { people = promptForUsers(wandora); if(people == null) return false; // user cancelled } else { people = new ArrayList<T2<FlickrPerson, Topic>>(); for(Topic t : contextUserTopics) { try { FlickrPerson p = new FlickrPerson(); p.UserName = t.getDisplayName(); p.ID = t.getData(nsidT, langT); people.add(new T2<FlickrPerson, Topic>(p, t)); } catch(TopicMapException e) { log(e); } } } if(people.isEmpty()) { log("Found no profiles to look up!"); } else { log("Found a total of " + people.size() + " profiles to look up"); } for(T2<FlickrPerson, Topic> p : people) { try { curPerson = p.e1; curPersonTopic = p.e2; log("Getting profile info for " + p.e1.UserName); people_getInfo(wandora); if(forceStop()) return true; log("Getting public photo list for " + p.e1.UserName); getPhotoList(wandora, "flickr.people.getPublicPhotos", FlickrAssoc.Ownership, "owned"); if(forceStop()) return true; log("Getting favorite photo list for " + p.e1.UserName); getPhotoList(wandora, "flickr.favorites.getList", FlickrAssoc.Favorite, "marked as favorite"); if(forceStop()) return true; log("Getting public group list for " + p.e1.UserName); people_getPublicGroups(wandora); if(forceStop()) return true; } catch(TopicMapException e) { log(e); } catch(RequestFailure e) { log(e); } catch(JSONException e) { log(e); } catch(UserCancellation e) { log("User cancelled"); } } log("Ready."); return people.size() > 0; } private void getPhotoList(Wandora currentAdmin, String jsonAPI, FlickrAssoc association, String relationship) throws JSONException, TopicMapException, RequestFailure, ExtractionFailure, UserCancellation { int totalPhotos = 0; int photosReceived = 0; TreeMap<String, String> args = new TreeMap<>(); args.put("user_id", curPerson.ID); args.put("extras", "date_taken,date_upload,o_dims,geo,last_update,license,media,owner_name,tags,views"); args.put("per_page", "" + photosPerPage); JSONObject result = getFlickrState().authorizedCall(jsonAPI, args, FlickrState.PermRead, currentAdmin); totalPhotos = FlickrUtils.searchInt(result, "photos.total"); final int pageCount = 1 + totalPhotos / photosPerPage; getCurrentLogger().setProgressMax(totalPhotos); log("-- Getting info for " + totalPhotos + " photos " + relationship + " by " + curPerson.UserName + "."); for(int nextPageIndex = 2; nextPageIndex <= (pageCount + 1); ++nextPageIndex) { getCurrentLogger().setProgress(photosReceived); JSONArray photosArray = FlickrUtils.searchJSONArray(result, "photos.photo"); int received = photosArray.length(); log("-- -- Getting info for photos " + (photosReceived + 1) + " - " + (photosReceived + received) + " out of " + totalPhotos); photosReceived += received; for(int i = 0; i < received; ++i) { FlickrPhoto p = FlickrPhoto.makeFromPublicPhotoList(photosArray.getJSONObject(i)); Topic photoTopic = p.makeTopic(this); FlickrUtils.createAssociation(currentMap, getAssociation(association), new Topic[] { photoTopic, curPersonTopic }); } if(forceStop()) { log("-- -- Cancellation requested; finished getting info for " + photosReceived + " out of " + totalPhotos + " photos."); break; } args.clear(); args.put("user_id", curPerson.ID); args.put("extras", "date_taken,date_upload,o_dims,geo,last_update,license,media,owner_name,tags,views"); args.put("per_page", "" + photosPerPage); args.put("page", "" + nextPageIndex); result = getFlickrState().authorizedCall(jsonAPI, args, FlickrState.PermRead, currentAdmin); } if(photosReceived < totalPhotos) { log("" + (totalPhotos - photosReceived) + " photos not sent by flickr"); } } private void people_getPublicGroups(Wandora wandora) throws JSONException, TopicMapException, RequestFailure, ExtractionFailure { TreeMap<String, String> args = new TreeMap<>(); args.put("user_id", curPerson.ID); JSONObject result = getFlickrState().unauthorizedCall("flickr.people.getPublicGroups", args); { JSONArray groupArray = FlickrUtils.searchJSONArray(result, "groups.group"); log("-- Getting info for " + groupArray.length() + " groups."); getCurrentLogger().setProgressMax(groupArray.length()); for(int i = 0; i < groupArray.length() && !forceStop(); ++i) { getCurrentLogger().setProgress(i); FlickrGroup g = new FlickrGroup(groupArray.getJSONObject(i)); Topic groupTopic = g.makeTopic(this); FlickrUtils.createAssociation(currentMap, getAssociation(FlickrAssoc.Membership), new Topic[] { groupTopic, curPersonTopic }); } getCurrentLogger().setProgress(groupArray.length()); } } private void people_getInfo(Wandora wandora) throws JSONException, TopicMapException, RequestFailure, ExtractionFailure { TreeMap<String, String> args = new TreeMap<>(); args.put("user_id", curPerson.ID); JSONObject response = getFlickrState().unauthorizedCall("flickr.people.getInfo", args); throwOnAPIError(response); try { curPersonTopic.setData( getOccurrence(FlickrOccur.Location), getLanguage(null), FlickrUtils.searchString(response, "person.location._content")); } catch(JSONException e) { } } @Override public String getDescription() { return "Flickr person info extractor reads Flickr user profile and converts it to a topic map."; } @Override public String getName() { return "Flickr person info extractor"; } }
10,436
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TokenRequestDialog.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/flickr/TokenRequestDialog.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * TokenRequestDialog.java * * Created on 2. huhtikuuta 2008, 12:04 */ package org.wandora.application.tools.extractors.flickr; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.ClipboardOwner; import java.awt.datatransfer.StringSelection; import java.awt.datatransfer.Transferable; import org.wandora.application.Wandora; /** * * @author anttirt */ public class TokenRequestDialog extends javax.swing.JDialog { private static final long serialVersionUID = 1L; private boolean mCancelled; private String requiredAuth; private FlickrState flickrState; /** Creates new form TokenRequestDialog */ public TokenRequestDialog(java.awt.Frame parent, boolean modal, String authURL, String reqAuth, FlickrState state) { super(parent, modal); requiredAuth = reqAuth; flickrState = state; initComponents(); urlField.setText(authURL); mCancelled = false; this.setSize(600,280); if(parent instanceof Wandora) { Wandora w = (Wandora)parent; w.centerWindow(this); } } public boolean cancelled() { return mCancelled; } /** 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; labelPanel = new javax.swing.JPanel(); titleLabel = new org.wandora.application.gui.simple.SimpleLabel(); authInfoPanel = new javax.swing.JPanel(); authDisplay1 = new AuthDisplay(this.flickrState, this.requiredAuth); wandoraLabel2 = new org.wandora.application.gui.simple.SimpleLabel(); urlPanel = new javax.swing.JPanel(); urlField = new javax.swing.JTextField(); clipboardBtn = new org.wandora.application.gui.simple.SimpleButton(); buttonPanel = new javax.swing.JPanel(); fillerPanel = new javax.swing.JPanel(); okButton = new org.wandora.application.gui.simple.SimpleButton(); cancelButton = new org.wandora.application.gui.simple.SimpleButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Flickr authorization required"); getContentPane().setLayout(new java.awt.GridBagLayout()); labelPanel.setLayout(new java.awt.GridBagLayout()); titleLabel.setText("<html><body><p>Wandora requires your authorization before it can read your photos and data from Flickr.</p></body></html>"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; labelPanel.add(titleLabel, gridBagConstraints); authInfoPanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(153, 153, 153))); authInfoPanel.setLayout(new java.awt.GridBagLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(5, 15, 5, 15); authInfoPanel.add(authDisplay1, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.insets = new java.awt.Insets(10, 5, 0, 5); labelPanel.add(authInfoPanel, gridBagConstraints); wandoraLabel2.setText("<html><body><p>Authorizing is a simple process which takes place in your web browser. Copy the URL below to your browser and log in. When you're finished, return to this window and complete authorization.</p></body></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(10, 0, 0, 0); labelPanel.add(wandoraLabel2, gridBagConstraints); 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(10, 10, 0, 10); getContentPane().add(labelPanel, gridBagConstraints); urlPanel.setLayout(new java.awt.GridBagLayout()); urlField.setPreferredSize(new java.awt.Dimension(6, 21)); 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, 5); urlPanel.add(urlField, gridBagConstraints); clipboardBtn.setText("Copy"); clipboardBtn.setMargin(new java.awt.Insets(2, 2, 2, 2)); clipboardBtn.setMinimumSize(new java.awt.Dimension(120, 21)); clipboardBtn.setPreferredSize(new java.awt.Dimension(50, 21)); clipboardBtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { clipboardBtnActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; urlPanel.add(clipboardBtn, 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, 10, 0, 10); getContentPane().add(urlPanel, gridBagConstraints); buttonPanel.setLayout(new java.awt.GridBagLayout()); 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.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; buttonPanel.add(fillerPanel, gridBagConstraints); okButton.setText("Complete"); okButton.setMargin(new java.awt.Insets(2, 2, 2, 2)); okButton.setPreferredSize(new java.awt.Dimension(80, 23)); okButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { okButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); buttonPanel.add(okButton, gridBagConstraints); cancelButton.setText("Cancel"); cancelButton.setMinimumSize(new java.awt.Dimension(70, 21)); cancelButton.setPreferredSize(new java.awt.Dimension(70, 23)); cancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; 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(15, 10, 10, 10); getContentPane().add(buttonPanel, gridBagConstraints); pack(); }// </editor-fold>//GEN-END:initComponents private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed setVisible(false); }//GEN-LAST:event_okButtonActionPerformed private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed mCancelled = true; setVisible(false); }//GEN-LAST:event_cancelButtonActionPerformed private void clipboardBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clipboardBtnActionPerformed StringSelection sel = new StringSelection(urlField.getText()); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(sel, new ClipboardOwner() { @Override public void lostOwnership(Clipboard clipboard, Transferable contents) { } }); }//GEN-LAST:event_clipboardBtnActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* java.awt.EventQueue.invokeLater(new Runnable() { public void run() { TokenRequestDialog dialog = new TokenRequestDialog(new javax.swing.JFrame(), true, "lksjgfhlksujehrltkjsdnlgkjhltghlskdjfghliseurhglskjdfhgiluserhglksjlksjgfhlksujehrltkjsdnlgkjhltghlskdjfghliseurhglskjdfhgiluserhglksjlksjgfhlksujehrltkjsdnlgkjhltghlskdjfghliseurhglskjdfhgiluserhglksj"); dialog.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); */ } // Variables declaration - do not modify//GEN-BEGIN:variables private org.wandora.application.tools.extractors.flickr.AuthDisplay authDisplay1; private javax.swing.JPanel authInfoPanel; private javax.swing.JPanel buttonPanel; private javax.swing.JButton cancelButton; private javax.swing.JButton clipboardBtn; private javax.swing.JPanel fillerPanel; private javax.swing.JPanel labelPanel; private javax.swing.JButton okButton; private org.wandora.application.gui.simple.SimpleLabel titleLabel; private javax.swing.JTextField urlField; private javax.swing.JPanel urlPanel; private org.wandora.application.gui.simple.SimpleLabel wandoraLabel2; // End of variables declaration//GEN-END:variables }
11,988
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
FlickrPhoto.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/flickr/FlickrPhoto.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.flickr; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; /** * * @author anttirt */ public class FlickrPhoto { public String Title; public String OwnerName; public String OwnerID; public String ID; public ArrayList<String> Tags; public String Description; public String LastUpdate; public String DateTaken; public String DateUpload; public String Secret; public String Media; public double Latitude, Longitude; public Integer FarmID, ServerID; public Integer License; private static SimpleDateFormat ISO8601Format; public FlickrPhoto() {} static FlickrPhoto makeFromPhotoInfo(JSONObject obj) throws JSONException { FlickrPhoto ret = new FlickrPhoto(); if(ISO8601Format == null) { ISO8601Format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); } ret.ID = obj.getString("id"); ret.Title = FlickrUtils.searchString(obj, "title._content"); ret.OwnerName = FlickrUtils.searchString(obj, "owner.username"); ret.OwnerID = FlickrUtils.searchString(obj, "owner.nsid"); ret.Tags = new ArrayList<>(); JSONArray tagsArray = FlickrUtils.searchJSONArray(obj, "tags.tag"); for(int i = 0; i < tagsArray.length(); ++i) { JSONObject tagObj = tagsArray.getJSONObject(i); ret.Tags.add(tagObj.getString("_content")); } ret.DateTaken = FlickrUtils.searchString(obj, "dates.taken"); ret.DateUpload = FlickrUtils.searchString(obj, "dates.posted"); ret.LastUpdate = FlickrUtils.searchString(obj, "dates.lastupdate"); ret.FarmID = obj.getInt("farm"); ret.ServerID = obj.getInt("server"); ret.Secret = obj.optString("secret"); ret.License = obj.getInt("license"); JSONObject descObj = obj.optJSONObject("description"); if(descObj != null) { ret.Description = descObj.getString("_content"); } return ret; } static FlickrPhoto makeFromPublicPhotoList(JSONObject obj) throws JSONException { FlickrPhoto ret = new FlickrPhoto(); if(ISO8601Format == null) { ISO8601Format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); } ret.Title = obj.getString("title"); ret.OwnerName = obj.getString("ownername"); ret.OwnerID = obj.getString("owner"); ret.ID = obj.getString("id"); ret.Tags = new ArrayList<String>(Arrays.asList(obj.getString("tags").split(" "))); ret.LastUpdate = ISO8601Format.format(new Date(obj.getLong("lastupdate"))); ret.DateTaken = obj.getString("datetaken"); ret.DateUpload = ISO8601Format.format(new Date(obj.getLong("dateupload"))); ret.Secret = obj.getString("secret"); ret.Media = obj.getString("media"); ret.Latitude = obj.getLong("latitude"); ret.Longitude = obj.getLong("longitude"); ret.FarmID = obj.getInt("farm"); ret.ServerID = obj.getInt("server"); ret.Secret = obj.optString("secret"); ret.License = obj.getInt("license"); return ret; } Topic makeTopic(FlickrExtractor extractor) throws TopicMapException { if("".equals(Title)) Title = "(unnamed)"; String baseStr = "http://www.flickr.com/photos/" + OwnerID + "/" + ID + "/"; Topic photoTopic = FlickrUtils.createRaw(extractor.getCurrentMap(), baseStr, " (flickr photo " + ID + ")", Title, extractor.getTopic(FlickrTopic.Photo)); photoTopic.setData(extractor.getOccurrence(FlickrOccur.PhotoID), extractor.getLanguage(null), ID); if(FarmID != null && ServerID != null && Secret != null) { StringBuilder bldr = new StringBuilder("http://farm"); bldr.append(FarmID); bldr.append(".static.flickr.com/"); bldr.append(ServerID); bldr.append('/'); bldr.append(ID); bldr.append('_'); bldr.append(Secret); bldr.append("_d.jpg"); photoTopic.setSubjectLocator(new Locator(bldr.toString())); } if(Description != null) { photoTopic.setData(extractor.getOccurrence(FlickrOccur.Description), extractor.getLanguage(null), Description); } if(License != null) { Topic licenseT = extractor.getLicenseTopic(License); if(licenseT != null) FlickrUtils.createAssociation(extractor.getCurrentMap(), extractor.getAssociation(FlickrAssoc.License), new Topic[] { licenseT, photoTopic }); } for(String tag : Tags) { if("".equals(tag)) continue; String tagBaseStr = "http://www.flickr.com/photos/tags/" + tag + "/"; Topic tagTopic = FlickrUtils.createRaw(extractor.getCurrentMap(), tagBaseStr, " (flickr tag)", tag, extractor.getTopic(FlickrTopic.Tag)); if(photoTopic == null) throw new TopicMapException("Null photoTopic"); if(tagTopic == null) throw new TopicMapException("Null tagTopic"); FlickrUtils.createAssociation(extractor.getCurrentMap(), extractor.getAssociation(FlickrAssoc.Description), new Topic[] { photoTopic, tagTopic }); } if(OwnerID != null) { FlickrPerson p = new FlickrPerson(); p.UserName = OwnerName; p.ID = OwnerID; Topic personTopic = p.makeTopic(extractor); if(photoTopic == null) throw new TopicMapException("Null photoTopic"); if(personTopic == null) throw new TopicMapException("Null personTopic"); FlickrUtils.createAssociation(extractor.getCurrentMap(), extractor.getAssociation(FlickrAssoc.Ownership), new Topic[] {photoTopic, personTopic}); } return photoTopic; } }
7,233
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
FlickrAssoc.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/flickr/FlickrAssoc.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.flickr; /** * * @author anttirt */ public enum FlickrAssoc { Membership, Ownership, Description, Favorite, License, InGroupPool }
1,038
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DiscogsReleaseExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/discogs/DiscogsReleaseExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2013 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.discogs; import java.io.File; import java.net.URL; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; 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 nlaitine */ public class DiscogsReleaseExtractor extends AbstractDiscogsExtractor { private static final long serialVersionUID = 1L; private static String defaultLang = "en"; private static String currentURL = null; public DiscogsReleaseExtractor () { } @Override public String getName() { return "Discogs API Release extractor"; } @Override public String getDescription(){ return "Extractor fetches release data from Discogs API."; } @Override public boolean _extractTopicsFrom(File f, TopicMap tm) throws Exception { currentURL = null; String in = IObox.loadFile(f); JSONObject json = new JSONObject(in); parseRelease(json, tm); return true; } @Override public boolean _extractTopicsFrom(URL u, TopicMap tm) throws Exception { try { currentURL = u.toExternalForm(); log("Release search extraction with " + currentURL); String in = DiscogsSearchExtractor.doUrl(u); System.out.println("---------------Discogs API returned------------\n"+in+ "\n-----------------------------------------------"); JSONObject json = new JSONObject(in); parseRelease(json, 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); parseRelease(json, tm); return true; } // ------------------------- PARSING --------------------------------------- public void parseRelease(JSONObject json, TopicMap tm) throws TopicMapException { if(json.has("results")) { try { JSONArray resultsArray = json.getJSONArray("results"); if (resultsArray.length() > 0) { int count = 0; for(int i=0; i<resultsArray.length(); i++) { JSONObject result = resultsArray.getJSONObject(i); parseResult(result, tm); count++; } log("Search returned " + count + " releases."); } else { log("API returned no results."); } } catch (JSONException ex) { log(ex); } } else { log("API returned no results."); } } public void parseResult(JSONObject result, TopicMap tm) throws JSONException, TopicMapException { if(result.has("uri") && result.has("id")) { String id = result.getString("id"); String subjectId = DISCOGS_SI + result.getString("uri"); Topic itemTopic = tm.createTopic(); itemTopic.addSubjectIdentifier(new Locator(subjectId)); itemTopic.addType(getReleaseTypeTopic(tm)); Topic releaseTypeTopic = getReleaseTypeTopic(tm); if(result.has("title")) { String value = result.getString("title"); if(value != null && value.length() > 0) { Topic titleTypeTopic = getTitleTypeTopic(tm); itemTopic.setDisplayName(defaultLang, value); itemTopic.setBaseName(value + " (" + id + ")"); Topic langTopic = getLangTopic(tm); itemTopic.setData(titleTypeTopic, langTopic, value); int index = value.lastIndexOf(" - "); value = value.substring(0, index); if (!value.isEmpty()) { Topic artistTopic = tm.getTopicWithBaseName(value); if (artistTopic == null) { artistTopic = tm.createTopic(); artistTopic.addSubjectIdentifier(new Locator(DISCOGS_SI + "/artist/" + urlEncode(value))); artistTopic.addType(getArtistTypeTopic(tm)); artistTopic.setDisplayName(defaultLang, value); artistTopic.setBaseName(value); artistTopic.setData(titleTypeTopic, langTopic, value); } Topic artistTypeTopic = getArtistTypeTopic(tm); Association a = tm.createAssociation(artistTypeTopic); a.addPlayer(artistTopic, artistTypeTopic); a.addPlayer(itemTopic, releaseTypeTopic); } } } if(result.has("country")) { String value = result.getString("country"); if(value != null && value.length() > 0) { String subjectValue = COUNTRY_SI + "/" + urlEncode(value); Topic countryTopic = getCountryTopic(subjectValue, tm); Topic countryTypeTopic = getCountryTypeTopic(tm); Association a = tm.createAssociation(countryTypeTopic); a.addPlayer(countryTopic, countryTypeTopic); a.addPlayer(itemTopic, releaseTypeTopic); countryTopic.setBaseName(value); } } if(result.has("year")) { String value = result.getString("year"); if(value != null && value.length() > 0) { String subjectValue = YEAR_SI + "/" + urlEncode(value); Topic yearTopic = getYearTopic(subjectValue, tm); Topic yearTypeTopic = getYearTypeTopic(tm); Association a = tm.createAssociation(yearTypeTopic); a.addPlayer(yearTopic, yearTypeTopic); a.addPlayer(itemTopic, releaseTypeTopic); yearTopic.setBaseName(value); } } if(result.has("style")) { JSONArray values = result.getJSONArray("style"); if(values.length() > 0) { for(int i=0; i<values.length(); i++) { String value = values.getString(i); if(value != null && value.length() > 0) { String subjectValue = STYLE_SI + "/" + urlEncode(value); Topic styleTopic = getStyleTopic(subjectValue, tm); Topic styleTypeTopic = getStyleTypeTopic(tm); Association a = tm.createAssociation(styleTypeTopic); a.addPlayer(styleTopic, styleTypeTopic); a.addPlayer(itemTopic, releaseTypeTopic); styleTopic.setBaseName(value); } } } } if(result.has("barcode")) { JSONArray values = result.getJSONArray("barcode"); if(values.length() > 0) { for(int i=0; i<values.length(); i++) { String value = values.getString(i); if(value != null && value.length() > 0) { Topic barcodeTypeTopic = getBarcodeTypeTopic(tm); Topic langTopic = getLangTopic(tm); itemTopic.setData(barcodeTypeTopic, langTopic, value); } } } } if(result.has("label")) { JSONArray values = result.getJSONArray("label"); if(values.length() > 0) { for(int i=0; i<values.length(); i++) { String value = values.getString(i); if(value != null && value.length() > 0) { String subjectValue = LABEL_SI + "/" + urlEncode(value); Topic labelTopic = getLabelTopic(subjectValue, tm); Topic labelTypeTopic = getLabelTypeTopic(tm); Association a = tm.createAssociation(labelTypeTopic); a.addPlayer(labelTopic, labelTypeTopic); a.addPlayer(itemTopic, releaseTypeTopic); labelTopic.setBaseName(value); } } } } if(result.has("catno")) { String value = result.getString("catno"); if(value != null && value.length() > 0) { Topic catnoTypeTopic = getCatnoTypeTopic(tm); Topic langTopic = getLangTopic(tm); itemTopic.setData(catnoTypeTopic, langTopic, value); } } if(result.has("genre")) { JSONArray values = result.getJSONArray("genre"); if(values.length() > 0) { for(int i=0; i<values.length(); i++) { String value = values.getString(i); if(value != null && value.length() > 0) { String subjectValue = GENRE_SI + "/" + urlEncode(value); Topic genreTopic = getGenreTopic(subjectValue, tm); Topic genreTypeTopic = getGenreTypeTopic(tm); Association a = tm.createAssociation(genreTypeTopic); a.addPlayer(genreTopic, genreTypeTopic); a.addPlayer(itemTopic, releaseTypeTopic); genreTopic.setBaseName(value); } } } } if(result.has("format")) { JSONArray values = result.getJSONArray("format"); if(values.length() > 0) { for(int i=0; i<values.length(); i++) { String value = values.getString(i); if(value != null && value.length() > 0) { String subjectValue = FORMAT_SI + "/" + urlEncode(value); Topic formatTopic = getFormatTopic(subjectValue, tm); Topic formatTypeTopic = getFormatTypeTopic(tm); Association a = tm.createAssociation(formatTypeTopic); a.addPlayer(formatTopic, formatTypeTopic); a.addPlayer(itemTopic, releaseTypeTopic); formatTopic.setBaseName(value); } } } } if(result.has("thumb")) { String value = result.getString("thumb"); if(value != null && value.length() > 0) { Topic imageTypeTopic = getImageTypeTopic(tm); Topic langTopic = getLangTopic(tm); itemTopic.setData(imageTypeTopic, langTopic, value); } } } } }
12,760
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AbstractDiscogsExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/discogs/AbstractDiscogsExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2013 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.discogs; import java.io.File; import java.net.URL; 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 nlaitine */ public class AbstractDiscogsExtractor extends AbstractExtractor { private static final long serialVersionUID = 1L; // Default language of occurrences and variant names. public static String LANG = "en"; public static String LANGUAGE_SI = "http://www.topicmaps.org/xtm/1.0/language.xtm#en"; public static final String DISCOGS_SI = "http://www.discogs.com"; public static final String DISCOG_API_SI = "http://api.discogs.com"; public static final String RELEASE_SI = "http://www.discogs.com/release"; public static final String MASTER_SI = "http://www.discogs.com/master"; public static final String ARTIST_SI = "http://www.discogs.com/artist"; public static final String LABEL_SI = "http://www.discogs.com/label"; public static final String TYPE_SI = DISCOG_API_SI + "/type"; public static final String TITLE_SI = DISCOG_API_SI + "/title"; public static final String COUNTRY_SI = DISCOG_API_SI + "/country"; public static final String YEAR_SI = DISCOG_API_SI + "/year"; public static final String STYLE_SI = DISCOG_API_SI + "/style"; public static final String GENRE_SI = DISCOG_API_SI + "/genre"; public static final String FORMAT_SI = DISCOG_API_SI + "/format"; public static final String IMAGE_SI = DISCOG_API_SI + "/image"; public static final String CATNO_SI = DISCOG_API_SI + "/catno"; public static final String BARCODE_SI = DISCOG_API_SI + "/barcode"; @Override public String getName() { return "Abstract Discogs API extractor"; } @Override public String getDescription(){ return "Extracts data from The Discogs data API at http://api.discogs.com"; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_discogs.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; } // ----------------------------------------------------------------------------- @Override public boolean _extractTopicsFrom(File f, TopicMap t) throws Exception { throw new UnsupportedOperationException("This extractor is a frontend for other Discogs extractors. 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 Discogs extractors. 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 Discogs extractors. It doesn't perform extration it self."); } // --------------------------- TOPIC MAPS ------------------------------------ protected static Topic getLangTopic(TopicMap tm) throws TopicMapException { Topic lang = getOrCreateTopic(tm, LANGUAGE_SI); return lang; } 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); } public static Topic getDiscogsTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, DISCOG_API_SI, "Discogs API"); Topic wandoraClass = getWandoraClassTopic(tm); makeSubclassOf(tm, type, wandoraClass); return type; } // ------------------------------- TOPICS ------------------------------------ public static Topic getReleaseTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, RELEASE_SI, "release (Discogs API)"); Topic nytTopic = getDiscogsTypeTopic(tm); makeSubclassOf(tm, type, nytTopic); return type; } public static Topic getMasterTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, MASTER_SI, "master (Discogs API)"); Topic nytTopic = getDiscogsTypeTopic(tm); makeSubclassOf(tm, type, nytTopic); return type; } public static Topic getArtistTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, ARTIST_SI, "artist (Discogs API)"); Topic nytTopic = getDiscogsTypeTopic(tm); makeSubclassOf(tm, type, nytTopic); return type; } public static Topic getTitleTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, TITLE_SI, "title (Discogs API)"); Topic discogsTopic = getDiscogsTypeTopic(tm); makeSubclassOf(tm, type, discogsTopic); return type; } public static Topic getCountryTopic(String provider, TopicMap tm) throws TopicMapException { Topic resTopic=getOrCreateTopic(tm, provider); resTopic.addType(getCountryTypeTopic(tm)); return resTopic; } public static Topic getCountryTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, COUNTRY_SI, "country (Discogs API)"); Topic discogsTopic = getDiscogsTypeTopic(tm); makeSubclassOf(tm, type, discogsTopic); return type; } public static Topic getYearTopic(String provider, TopicMap tm) throws TopicMapException { Topic resTopic=getOrCreateTopic(tm, provider); resTopic.addType(getYearTypeTopic(tm)); return resTopic; } public static Topic getYearTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, YEAR_SI, "year (Discogs API)"); Topic discogsTopic = getDiscogsTypeTopic(tm); makeSubclassOf(tm, type, discogsTopic); return type; } public static Topic getStyleTopic(String provider, TopicMap tm) throws TopicMapException { Topic resTopic=getOrCreateTopic(tm, provider); resTopic.addType(getStyleTypeTopic(tm)); return resTopic; } public static Topic getStyleTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, STYLE_SI, "style (Discogs API)"); Topic discogsTopic = getDiscogsTypeTopic(tm); makeSubclassOf(tm, type, discogsTopic); return type; } public static Topic getGenreTopic(String provider, TopicMap tm) throws TopicMapException { Topic resTopic=getOrCreateTopic(tm, provider); resTopic.addType(getGenreTypeTopic(tm)); return resTopic; } public static Topic getGenreTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, GENRE_SI, "genre (Discogs API)"); Topic discogsTopic = getDiscogsTypeTopic(tm); makeSubclassOf(tm, type, discogsTopic); return type; } public static Topic getLabelTopic(String provider, TopicMap tm) throws TopicMapException { Topic resTopic=getOrCreateTopic(tm, provider); resTopic.addType(getLabelTypeTopic(tm)); return resTopic; } public static Topic getLabelTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, LABEL_SI, "label (Discogs API)"); Topic discogsTopic = getDiscogsTypeTopic(tm); makeSubclassOf(tm, type, discogsTopic); return type; } public static Topic getFormatTopic(String provider, TopicMap tm) throws TopicMapException { Topic resTopic=getOrCreateTopic(tm, provider); resTopic.addType(getFormatTypeTopic(tm)); return resTopic; } public static Topic getFormatTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, FORMAT_SI, "format (Discogs API)"); Topic discogsTopic = getDiscogsTypeTopic(tm); makeSubclassOf(tm, type, discogsTopic); return type; } public static Topic getImageTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, IMAGE_SI, "image (Discogs API)"); Topic discogsTopic = getDiscogsTypeTopic(tm); makeSubclassOf(tm, type, discogsTopic); return type; } public static Topic getCatnoTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, CATNO_SI, "catno (Discogs API)"); Topic discogsTopic = getDiscogsTypeTopic(tm); makeSubclassOf(tm, type, discogsTopic); return type; } public static Topic getBarcodeTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, BARCODE_SI, "barcode (Discogs API)"); Topic discogsTopic = getDiscogsTypeTopic(tm); makeSubclassOf(tm, type, discogsTopic); return type; } public static Topic getTypeTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, TYPE_SI, "type (Discogs API)"); Topic discogsTopic = getDiscogsTypeTopic(tm); makeSubclassOf(tm, type, discogsTopic); return type; } }
11,063
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DiscogsArtistExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/discogs/DiscogsArtistExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2013 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.discogs; import java.io.File; import java.net.URL; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; 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 nlaitine */ public class DiscogsArtistExtractor extends AbstractDiscogsExtractor { private static final long serialVersionUID = 1L; private static String defaultLang = "en"; private static String currentURL = null; public DiscogsArtistExtractor () { } @Override public String getName() { return "Discogs API Artist extractor"; } @Override public String getDescription(){ return "Extractor fetches artist data from Discogs API."; } @Override public boolean _extractTopicsFrom(File f, TopicMap tm) throws Exception { currentURL = null; String in = IObox.loadFile(f); JSONObject json = new JSONObject(in); parseArtist(json, tm); return true; } @Override public boolean _extractTopicsFrom(URL u, TopicMap tm) throws Exception { try { currentURL = u.toExternalForm(); log("Release search extraction with " + currentURL); String in = DiscogsSearchExtractor.doUrl(u); System.out.println("---------------Discogs API returned------------\n"+in+ "\n-----------------------------------------------"); JSONObject json = new JSONObject(in); parseArtist(json, 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); parseArtist(json, tm); return true; } // ------------------------- PARSING --------------------------------------- public void parseArtist(JSONObject json, TopicMap tm) throws TopicMapException { if(json.has("results")) { try { JSONArray resultsArray = json.getJSONArray("results"); if (resultsArray.length() > 0) { int count = 0; for(int i=0; i<resultsArray.length(); i++) { JSONObject result = resultsArray.getJSONObject(i); parseResult(result, tm); count++; } log("Search returned " + count + " artists."); } else { log("API returned no results."); } } catch (JSONException ex) { log(ex); } } else { log("API returned no results."); } } public void parseResult(JSONObject result, TopicMap tm) throws JSONException, TopicMapException { if(result.has("uri") && result.has("id")) { String id = result.getString("id"); String subjectId = DISCOGS_SI + result.getString("uri"); Topic itemTopic = tm.createTopic(); itemTopic.addSubjectIdentifier(new Locator(subjectId)); itemTopic.addType(getArtistTypeTopic(tm)); if(result.has("title")) { String value = result.getString("title"); if(value != null && value.length() > 0) { Topic titleTypeTopic = getTitleTypeTopic(tm); itemTopic.setDisplayName(defaultLang, value); itemTopic.setBaseName(value); Topic langTopic = getLangTopic(tm); itemTopic.setData(titleTypeTopic, langTopic, value); } } if(result.has("thumb")) { String value = result.getString("thumb"); if(value != null && value.length() > 0) { Topic imageTypeTopic = getImageTypeTopic(tm); Topic langTopic = getLangTopic(tm); itemTopic.setData(imageTypeTopic, langTopic, value); } } } } }
5,225
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DiscogsLabelExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/discogs/DiscogsLabelExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2013 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.discogs; import java.io.File; import java.net.URL; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; 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 nlaitine */ public class DiscogsLabelExtractor extends AbstractDiscogsExtractor { private static final long serialVersionUID = 1L; private static String defaultLang = "en"; private static String currentURL = null; public DiscogsLabelExtractor () { } @Override public String getName() { return "Discogs API Label extractor"; } @Override public String getDescription(){ return "Extractor fetches label data from Discogs API."; } @Override public boolean _extractTopicsFrom(File f, TopicMap tm) throws Exception { currentURL = null; String in = IObox.loadFile(f); JSONObject json = new JSONObject(in); parseLabel(json, tm); return true; } @Override public boolean _extractTopicsFrom(URL u, TopicMap tm) throws Exception { try { currentURL = u.toExternalForm(); log("Release search extraction with " + currentURL); String in = DiscogsSearchExtractor.doUrl(u); System.out.println("---------------Discogs API returned------------\n"+in+ "\n-----------------------------------------------"); JSONObject json = new JSONObject(in); parseLabel(json, 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); parseLabel(json, tm); return true; } // ------------------------- PARSING --------------------------------------- public void parseLabel(JSONObject json, TopicMap tm) throws TopicMapException { if(json.has("results")) { try { JSONArray resultsArray = json.getJSONArray("results"); if (resultsArray.length() > 0) { int count = 0; for(int i=0; i<resultsArray.length(); i++) { JSONObject result = resultsArray.getJSONObject(i); parseResult(result, tm); count++; } log("Search returned " + count + " labels."); } else { log("API returned no results."); } } catch (JSONException ex) { log(ex); } } else { log("API returned no results."); } } public void parseResult(JSONObject result, TopicMap tm) throws JSONException, TopicMapException { if(result.has("uri") && result.has("id")) { String id = result.getString("id"); String subjectId = DISCOGS_SI + result.getString("uri"); Topic itemTopic = tm.createTopic(); itemTopic.addSubjectIdentifier(new Locator(subjectId)); itemTopic.addType(getLabelTypeTopic(tm)); if(result.has("title")) { String value = result.getString("title"); if(value != null && value.length() > 0) { Topic titleTypeTopic = getTitleTypeTopic(tm); itemTopic.setDisplayName(defaultLang, value); itemTopic.setBaseName(value + " (" + id + ")"); Topic langTopic = getLangTopic(tm); itemTopic.setData(titleTypeTopic, langTopic, value); } } if(result.has("thumb")) { String value = result.getString("thumb"); if(value != null && value.length() > 0) { Topic imageTypeTopic = getImageTypeTopic(tm); Topic langTopic = getLangTopic(tm); itemTopic.setData(imageTypeTopic, langTopic, value); } } } } }
5,208
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DiscogsMasterExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/discogs/DiscogsMasterExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2013 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.discogs; import java.io.File; import java.net.URL; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; 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 nlaitine */ public class DiscogsMasterExtractor extends AbstractDiscogsExtractor { private static final long serialVersionUID = 1L; private static String defaultLang = "en"; private static String currentURL = null; public DiscogsMasterExtractor () { } @Override public String getName() { return "Discogs API Master extractor"; } @Override public String getDescription(){ return "Extractor fetches master data from Discogs API."; } @Override public boolean _extractTopicsFrom(File f, TopicMap tm) throws Exception { currentURL = null; String in = IObox.loadFile(f); JSONObject json = new JSONObject(in); parseMaster(json, tm); return true; } @Override public boolean _extractTopicsFrom(URL u, TopicMap tm) throws Exception { try { currentURL = u.toExternalForm(); log("Release search extraction with " + currentURL); String in = DiscogsSearchExtractor.doUrl(u); System.out.println("---------------Discogs API returned------------\n"+in+ "\n-----------------------------------------------"); JSONObject json = new JSONObject(in); parseMaster(json, 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); parseMaster(json, tm); return true; } // ------------------------- PARSING --------------------------------------- public void parseMaster(JSONObject json, TopicMap tm) throws TopicMapException { if(json.has("results")) { try { JSONArray resultsArray = json.getJSONArray("results"); if (resultsArray.length() > 0) { int count = 0; for(int i=0; i<resultsArray.length(); i++) { JSONObject result = resultsArray.getJSONObject(i); parseResult(result, tm); count++; } log("Search returned " + count + " masters."); } else { log("API returned no results."); } } catch (JSONException ex) { log(ex); } } else { log("API returned no results."); } } public void parseResult(JSONObject result, TopicMap tm) throws JSONException, TopicMapException { if(result.has("uri") && result.has("id")) { String id = result.getString("id"); String subjectId = DISCOGS_SI + result.getString("uri"); Topic itemTopic = tm.createTopic(); itemTopic.addSubjectIdentifier(new Locator(subjectId)); itemTopic.addType(getMasterTypeTopic(tm)); Topic releaseTypeTopic = getReleaseTypeTopic(tm); if(result.has("title")) { String value = result.getString("title"); if(value != null && value.length() > 0) { Topic titleTypeTopic = getTitleTypeTopic(tm); itemTopic.setDisplayName(defaultLang, value); itemTopic.setBaseName(value + " (" + id + ")"); Topic langTopic = getLangTopic(tm); itemTopic.setData(titleTypeTopic, langTopic, value); int index = value.lastIndexOf(" - "); value = value.substring(0, index); if (!value.isEmpty()) { Topic artistTopic = tm.getTopicWithBaseName(value); if (artistTopic == null) { artistTopic = tm.createTopic(); artistTopic.addSubjectIdentifier(new Locator(DISCOGS_SI + "/artist/" + urlEncode(value))); artistTopic.addType(getArtistTypeTopic(tm)); artistTopic.setDisplayName(defaultLang, value); artistTopic.setBaseName(value); artistTopic.setData(titleTypeTopic, langTopic, value); } Topic artistTypeTopic = getArtistTypeTopic(tm); Association a = tm.createAssociation(artistTypeTopic); a.addPlayer(artistTopic, artistTypeTopic); a.addPlayer(itemTopic, releaseTypeTopic); } } } if(result.has("country")) { String value = result.getString("country"); if(value != null && value.length() > 0) { String subjectValue = COUNTRY_SI + "/" + urlEncode(value); Topic countryTopic = getCountryTopic(subjectValue, tm); Topic countryTypeTopic = getCountryTypeTopic(tm); Association a = tm.createAssociation(countryTypeTopic); a.addPlayer(countryTopic, countryTypeTopic); a.addPlayer(itemTopic, releaseTypeTopic); countryTopic.setBaseName(value); } } if(result.has("year")) { String value = result.getString("year"); if(value != null && value.length() > 0) { String subjectValue = YEAR_SI + "/" + urlEncode(value); Topic yearTopic = getYearTopic(subjectValue, tm); Topic yearTypeTopic = getYearTypeTopic(tm); Association a = tm.createAssociation(yearTypeTopic); a.addPlayer(yearTopic, yearTypeTopic); a.addPlayer(itemTopic, releaseTypeTopic); yearTopic.setBaseName(value); } } if(result.has("style")) { JSONArray values = result.getJSONArray("style"); if(values.length() > 0) { for(int i=0; i<values.length(); i++) { String value = values.getString(i); if(value != null && value.length() > 0) { String subjectValue = STYLE_SI + "/" + urlEncode(value); Topic styleTopic = getStyleTopic(subjectValue, tm); Topic styleTypeTopic = getStyleTypeTopic(tm); Association a = tm.createAssociation(styleTypeTopic); a.addPlayer(styleTopic, styleTypeTopic); a.addPlayer(itemTopic, releaseTypeTopic); styleTopic.setBaseName(value); } } } } if(result.has("barcode")) { JSONArray values = result.getJSONArray("barcode"); if(values.length() > 0) { for(int i=0; i<values.length(); i++) { String value = values.getString(i); if(value != null && value.length() > 0) { Topic barcodeTypeTopic = getBarcodeTypeTopic(tm); Topic langTopic = getLangTopic(tm); itemTopic.setData(barcodeTypeTopic, langTopic, value); } } } } if(result.has("label")) { JSONArray values = result.getJSONArray("label"); if(values.length() > 0) { for(int i=0; i<values.length(); i++) { String value = values.getString(i); if(value != null && value.length() > 0) { String subjectValue = LABEL_SI + "/" + urlEncode(value); Topic labelTopic = getLabelTopic(subjectValue, tm); Topic labelTypeTopic = getLabelTypeTopic(tm); Association a = tm.createAssociation(labelTypeTopic); a.addPlayer(labelTopic, labelTypeTopic); a.addPlayer(itemTopic, releaseTypeTopic); labelTopic.setBaseName(value); } } } } if(result.has("catno")) { String value = result.getString("catno"); if(value != null && value.length() > 0) { Topic catnoTypeTopic = getCatnoTypeTopic(tm); Topic langTopic = getLangTopic(tm); itemTopic.setData(catnoTypeTopic, langTopic, value); } } if(result.has("genre")) { JSONArray values = result.getJSONArray("genre"); if(values.length() > 0) { for(int i=0; i<values.length(); i++) { String value = values.getString(i); if(value != null && value.length() > 0) { String subjectValue = GENRE_SI + "/" + urlEncode(value); Topic genreTopic = getGenreTopic(subjectValue, tm); Topic genreTypeTopic = getGenreTypeTopic(tm); Association a = tm.createAssociation(genreTypeTopic); a.addPlayer(genreTopic, genreTypeTopic); a.addPlayer(itemTopic, releaseTypeTopic); genreTopic.setBaseName(value); } } } } if(result.has("format")) { JSONArray values = result.getJSONArray("format"); if(values.length() > 0) { for(int i=0; i<values.length(); i++) { String value = values.getString(i); if(value != null && value.length() > 0) { String subjectValue = FORMAT_SI + "/" + urlEncode(value); Topic formatTopic = getFormatTopic(subjectValue, tm); Topic formatTypeTopic = getFormatTypeTopic(tm); Association a = tm.createAssociation(formatTypeTopic); a.addPlayer(formatTopic, formatTypeTopic); a.addPlayer(itemTopic, releaseTypeTopic); formatTopic.setBaseName(value); } } } } if(result.has("thumb")) { String value = result.getString("thumb"); if(value != null && value.length() > 0) { Topic imageTypeTopic = getImageTypeTopic(tm); Topic langTopic = getLangTopic(tm); itemTopic.setData(imageTypeTopic, langTopic, value); } } } } }
12,745
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DiscogsExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/discogs/DiscogsExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2013 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.discogs; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; /** * * @author nlaitinen */ public class DiscogsExtractor extends AbstractDiscogsExtractor { private static final long serialVersionUID = 1L; private DiscogsExtractorUI ui = null; @Override public void execute(Wandora wandora, Context context) { try { if(ui == null) { ui = new DiscogsExtractorUI(); } 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 Discogs API query..."); for(int i=0; i<extrs.length && !forceStop(); i++) { try { WandoraTool e = extrs[i]; e.setToolLogger(getDefaultLogger()); e.execute(wandora); setState(EXECUTE); 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); } }
2,786
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DiscogsExtractorUI.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/discogs/DiscogsExtractorUI.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2013 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.discogs; import java.awt.Component; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Iterator; import java.util.List; 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.UIBox; 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.SimpleTabbedPane; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; /** * * @author nlaitine */ public class DiscogsExtractorUI extends javax.swing.JPanel { private static final long serialVersionUID = 1L; private boolean accepted = false; private JDialog dialog = null; private Context context = null; private static final String DISCOGS_API_BASE = "http://api.discogs.com/database/search"; /** * Creates new form DiscogsExtractorUI */ public DiscogsExtractorUI() { 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(500, 240); dialog.add(this); dialog.setTitle("Discogs API extractor"); UIBox.centerWindow(dialog, w); dialog.setVisible(true); } public WandoraTool[] getExtractors(DiscogsExtractor tool) throws TopicMapException { WandoraTool[] wtArray = null; WandoraTool wt = null; List<WandoraTool> wts = new ArrayList<>(); Component tab = TabsPane.getSelectedComponent(); String extractUrl; // ***** SEARCH ***** if (searchPanel.equals(tab)) { String type = searchTypeComboBox.getSelectedItem().toString(); String query = searchTextField.getText(); extractUrl = DISCOGS_API_BASE + "?type=" + type + "&q=" + urlEncode(query); System.out.println("Search URL: " + extractUrl); if (type.equals("release")) { DiscogsReleaseExtractor ex = new DiscogsReleaseExtractor(); ex.setForceUrls(new String[]{extractUrl}); wts.add(ex); wtArray = wts.toArray(new WandoraTool[]{}); } else if (type.equals("master")) { DiscogsMasterExtractor ex = new DiscogsMasterExtractor(); ex.setForceUrls(new String[]{extractUrl}); wts.add(ex); wtArray = wts.toArray(new WandoraTool[]{}); } else if (type.equals("artist")) { DiscogsArtistExtractor ex = new DiscogsArtistExtractor(); ex.setForceUrls(new String[]{extractUrl}); wts.add(ex); wtArray = wts.toArray(new WandoraTool[]{}); } else if (type.equals("label")) { DiscogsLabelExtractor ex = new DiscogsLabelExtractor(); ex.setForceUrls(new String[]{extractUrl}); wts.add(ex); wtArray = wts.toArray(new WandoraTool[]{}); } } if (releaseSearchPanel.equals(tab)) { String query = releaseTextField.getText(); extractUrl = DISCOGS_API_BASE + "?type=release&q=" + urlEncode(query); System.out.println("Search URL: " + extractUrl); DiscogsReleaseExtractor ex = new DiscogsReleaseExtractor(); ex.setForceUrls( new String[] {extractUrl} ); wts.add(ex); wtArray = wts.toArray(new WandoraTool[]{}); } else if (masterSearchPanel.equals(tab)) { String query = masterTextField.getText(); extractUrl = DISCOGS_API_BASE + "?type=master&q=" + urlEncode(query); System.out.println("Search URL: " + extractUrl); DiscogsMasterExtractor ex = new DiscogsMasterExtractor(); ex.setForceUrls( new String[] {extractUrl} ); wts.add(ex); wtArray = wts.toArray(new WandoraTool[]{}); } else if (artistSearchPanel.equals(tab)) { String query = artistTextField.getText(); extractUrl = DISCOGS_API_BASE + "?type=artist&q=" + urlEncode(query); System.out.println("Search URL: " + extractUrl); DiscogsArtistExtractor ex = new DiscogsArtistExtractor(); ex.setForceUrls( new String[] {extractUrl} ); wts.add(ex); wtArray = wts.toArray(new WandoraTool[]{}); } else if (labelSearchPanel.equals(tab)) { String query = labelTextField.getText(); extractUrl = DISCOGS_API_BASE + "?type=label&q=" + urlEncode(query); System.out.println("Search URL: " + extractUrl); DiscogsLabelExtractor ex = new DiscogsLabelExtractor(); ex.setForceUrls( new String[] {extractUrl} ); wts.add(ex); wtArray = wts.toArray(new WandoraTool[]{}); } return wtArray; } protected static String urlEncode(String str) { try { str = URLEncoder.encode(str, "utf-8"); } catch (Exception e) { } return str; } 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.getDisplayName(AbstractDiscogsExtractor.LANG); 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(); } /** * 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; MainPanel = new javax.swing.JPanel(); TabsPane = new SimpleTabbedPane(); searchPanel = new javax.swing.JPanel(); searchTypeComboBox = new SimpleComboBox(); headlineLabel = new SimpleLabel(); searchTextField = new SimpleField(); releaseSearchPanel = new javax.swing.JPanel(); releaseLabel = new SimpleLabel(); releaseTextField = new SimpleField(); releaseButton = new SimpleButton(); masterSearchPanel = new javax.swing.JPanel(); masterLabel = new SimpleLabel(); masterTextField = new SimpleField(); masterButton = new SimpleButton(); artistSearchPanel = new javax.swing.JPanel(); artistLabel = new SimpleLabel(); artistTextField = new SimpleField(); artistButton = new SimpleButton(); labelSearchPanel = new javax.swing.JPanel(); labelLabel = new SimpleLabel(); labelTextField = new SimpleField(); labelButton = new SimpleButton(); bottomPanel = new javax.swing.JPanel(); fillerPanel = new javax.swing.JPanel(); okButton = new SimpleButton(); cancelButton = new SimpleButton(); setMinimumSize(new java.awt.Dimension(360, 250)); setPreferredSize(new java.awt.Dimension(360, 250)); setLayout(new java.awt.GridBagLayout()); MainPanel.setMinimumSize(new java.awt.Dimension(250, 100)); MainPanel.setPreferredSize(new java.awt.Dimension(250, 100)); MainPanel.setLayout(new java.awt.GridBagLayout()); TabsPane.setMinimumSize(new java.awt.Dimension(80, 160)); TabsPane.setPreferredSize(new java.awt.Dimension(32767, 32767)); searchPanel.setMinimumSize(new java.awt.Dimension(70, 140)); searchPanel.setLayout(new java.awt.GridBagLayout()); searchTypeComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "release", "master", "artist", "label" })); searchTypeComboBox.setFocusable(false); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(0, 20, 0, 4); searchPanel.add(searchTypeComboBox, gridBagConstraints); headlineLabel.setText("Search Discogs database by entering a search term"); headlineLabel.setMaximumSize(new java.awt.Dimension(64, 14)); headlineLabel.setMinimumSize(new java.awt.Dimension(64, 14)); headlineLabel.setPreferredSize(new java.awt.Dimension(230, 14)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 4, 0); searchPanel.add(headlineLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 20); searchPanel.add(searchTextField, gridBagConstraints); TabsPane.addTab("Search", searchPanel); releaseSearchPanel.setLayout(new java.awt.GridBagLayout()); releaseLabel.setText("<html>Search releases by context. Press Get context and Extract to extract by context.</html>"); releaseLabel.setToolTipText(""); releaseLabel.setMaximumSize(new java.awt.Dimension(2147483647, 50)); releaseLabel.setMinimumSize(new java.awt.Dimension(250, 50)); releaseLabel.setPreferredSize(new java.awt.Dimension(250, 50)); 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(0, 20, 0, 20); releaseSearchPanel.add(releaseLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(8, 20, 0, 20); releaseSearchPanel.add(releaseTextField, gridBagConstraints); releaseButton.setText("Get context"); releaseButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { releaseButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.insets = new java.awt.Insets(8, 0, 0, 0); releaseSearchPanel.add(releaseButton, gridBagConstraints); TabsPane.addTab("Release search", releaseSearchPanel); masterSearchPanel.setLayout(new java.awt.GridBagLayout()); masterLabel.setText("<html>Search masters by context. Press Get context and Extract to extract by context.</html>"); masterLabel.setMaximumSize(new java.awt.Dimension(250, 50)); masterLabel.setMinimumSize(new java.awt.Dimension(250, 50)); masterLabel.setPreferredSize(new java.awt.Dimension(250, 50)); 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, 20, 0, 20); masterSearchPanel.add(masterLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(8, 20, 0, 20); masterSearchPanel.add(masterTextField, gridBagConstraints); masterButton.setText("Get context"); masterButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { masterButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.insets = new java.awt.Insets(8, 0, 0, 0); masterSearchPanel.add(masterButton, gridBagConstraints); TabsPane.addTab("Master search", masterSearchPanel); artistSearchPanel.setLayout(new java.awt.GridBagLayout()); artistLabel.setText("<html>Search artists by context. Press Get context and Extract to extract by context.</html>"); artistLabel.setMaximumSize(new java.awt.Dimension(2147483647, 50)); artistLabel.setMinimumSize(new java.awt.Dimension(250, 50)); artistLabel.setPreferredSize(new java.awt.Dimension(250, 50)); 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(0, 20, 0, 20); artistSearchPanel.add(artistLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(8, 20, 0, 20); artistSearchPanel.add(artistTextField, gridBagConstraints); artistButton.setText("Get context"); artistButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { artistButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.insets = new java.awt.Insets(8, 0, 0, 0); artistSearchPanel.add(artistButton, gridBagConstraints); TabsPane.addTab("Artist search", artistSearchPanel); labelSearchPanel.setLayout(new java.awt.GridBagLayout()); labelLabel.setText("<html>Search labels by context. Press Get context and Extract to extract by context.</html>"); labelLabel.setMaximumSize(new java.awt.Dimension(2147483647, 50)); labelLabel.setMinimumSize(new java.awt.Dimension(250, 50)); labelLabel.setPreferredSize(new java.awt.Dimension(250, 50)); 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(0, 20, 0, 20); labelSearchPanel.add(labelLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(8, 20, 0, 20); labelSearchPanel.add(labelTextField, gridBagConstraints); labelButton.setText("Get context"); labelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { labelButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.insets = new java.awt.Insets(8, 0, 0, 0); labelSearchPanel.add(labelButton, gridBagConstraints); TabsPane.addTab("Label search", labelSearchPanel); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = java.awt.GridBagConstraints.RELATIVE; gridBagConstraints.gridheight = java.awt.GridBagConstraints.RELATIVE; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; MainPanel.add(TabsPane, gridBagConstraints); TabsPane.getAccessibleContext().setAccessibleName("search"); bottomPanel.setMinimumSize(new java.awt.Dimension(250, 35)); bottomPanel.setPreferredSize(new java.awt.Dimension(250, 35)); bottomPanel.setLayout(new java.awt.GridBagLayout()); 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; bottomPanel.add(fillerPanel, 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, 4); bottomPanel.add(okButton, gridBagConstraints); cancelButton.setText("Cancel"); cancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelButtonActionPerformed(evt); } }); bottomPanel.add(cancelButton, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); MainPanel.add(bottomPanel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2); add(MainPanel, gridBagConstraints); MainPanel.getAccessibleContext().setAccessibleName("Discogs search"); }// </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 releaseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_releaseButtonActionPerformed releaseTextField.setText(getContextAsString()); }//GEN-LAST:event_releaseButtonActionPerformed private void masterButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_masterButtonActionPerformed masterTextField.setText(getContextAsString()); }//GEN-LAST:event_masterButtonActionPerformed private void artistButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_artistButtonActionPerformed artistTextField.setText(getContextAsString()); }//GEN-LAST:event_artistButtonActionPerformed private void labelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_labelButtonActionPerformed labelTextField.setText(getContextAsString()); }//GEN-LAST:event_labelButtonActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(DiscogsExtractorUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(DiscogsExtractorUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(DiscogsExtractorUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(DiscogsExtractorUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new DiscogsExtractorUI().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel MainPanel; private javax.swing.JTabbedPane TabsPane; private javax.swing.JButton artistButton; private javax.swing.JLabel artistLabel; private javax.swing.JPanel artistSearchPanel; private javax.swing.JTextField artistTextField; private javax.swing.JPanel bottomPanel; private javax.swing.JButton cancelButton; private javax.swing.JPanel fillerPanel; private javax.swing.JLabel headlineLabel; private javax.swing.JButton labelButton; private javax.swing.JLabel labelLabel; private javax.swing.JPanel labelSearchPanel; private javax.swing.JTextField labelTextField; private javax.swing.JButton masterButton; private javax.swing.JLabel masterLabel; private javax.swing.JPanel masterSearchPanel; private javax.swing.JTextField masterTextField; private javax.swing.JButton okButton; private javax.swing.JButton releaseButton; private javax.swing.JLabel releaseLabel; private javax.swing.JPanel releaseSearchPanel; private javax.swing.JTextField releaseTextField; private javax.swing.JPanel searchPanel; private javax.swing.JTextField searchTextField; private javax.swing.JComboBox searchTypeComboBox; // End of variables declaration//GEN-END:variables }
26,421
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DiscogsSearchExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/discogs/DiscogsSearchExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2013 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.discogs; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.nio.charset.Charset; import org.wandora.application.Wandora; /** * * @author nlaitinen */ public class DiscogsSearchExtractor extends AbstractDiscogsExtractor { private static final long serialVersionUID = 1L; private static String defaultEncoding = "UTF-8"; public static String doUrl (URL url) throws IOException { StringBuilder sb = new StringBuilder(5000); if (url != null) { URLConnection con = url.openConnection(); Wandora.initUrlConnection(con); con.setDoInput(true); con.setUseCaches(false); con.setRequestProperty("Content-type", "text/plain"); try { BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), Charset.forName(defaultEncoding))); String s; while ((s = in.readLine()) != null) { sb.append(s); if(!(s.endsWith("\n") || s.endsWith("\r"))) sb.append("\n"); } in.close(); } catch (Exception ex) { System.out.println("There was an error fetching data from Discogs."); } } return sb.toString(); } }
2,328
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
FreebaseMQLExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/freebase/FreebaseMQLExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.freebase; import java.io.File; import java.io.IOException; import java.net.URL; import java.net.URLDecoder; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.wandora.topicmap.Association; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.utils.IObox; /** * * @author * Eero Lehtonen */ public class FreebaseMQLExtractor extends AbstractFreebaseExtractor { private static final long serialVersionUID = 1L; private static String currentURL = null; @Override public String getName() { return "Freebase MQL API extractor"; } @Override public String getDescription(){ return "Extractor performs an content query using Freebase MQL API and "+ "transforms results to topics and associations."; } // ------------------------------------------------------------------------- private int extractCount = 0; private int maxExtractCount; private boolean toggleLimit = FreebaseExtractorUI.toggleLimit; private int progress = 0; public ArrayList<String> extractedIDs = new ArrayList<String>(); @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(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; } @Override public boolean _extractTopicsFrom(URL u, TopicMap tm) throws Exception { setProgressMax(10); setProgress(0); String id = getIdFromUrl(u); return _extractTopicsFrom(u, tm, id); } public boolean _extractTopicsFrom(URL u, TopicMap tm, String id) throws Exception { extractedIDs = new ArrayList<String>(); extractedIDs.add(id); maxExtractCount = FreebaseExtractorUI.maxExtractCount; setProgressMax(10); setProgress(0); return _extractTopicsFrom(u, tm, 0, id); } public boolean _extractTopicsFrom(URL u, TopicMap tm, int depth, String id) throws Exception { if (depth >= FreebaseExtractorUI.maxDepth){ return true; } progress = (progress == 10) ? 0 : progress + 1; setProgress(progress); currentURL = u.toExternalForm(); log("MQL query extraction with id: "+id); String in = ""; try{ in = IObox.doUrl(u); } catch (IOException e) { e.printStackTrace(); } String printIn = (in.length() > 2000) ? in.substring(0, 1999) + "..." : in; System.out.println("Freebase API returned-------------------------\n" +printIn +"\n----------------------------------------------------"); JSONObject json = new JSONObject(in); ArrayList<String> nextIDs = new ArrayList<String>(); try{ String s = " current depth: " + depth + ", extractCount: " + extractCount + ", maxExtractCount: " + maxExtractCount + ", toggleLimit: " + toggleLimit; nextIDs = parse(json, tm); System.out.println("NextIDs.size(): " + nextIDs.size() + s); } catch (Exception e){ e.printStackTrace(); } // Don't request already extracted topics nextIDs.removeAll(extractedIDs); for(String cid : nextIDs) { if(extractCount >= maxExtractCount || forceStop()) { break; } extractedIDs.add(cid); String query = getQuery(cid); URL newURL = new URL(FreebaseExtractorUI.FREEBASE_MQL_API_BASE + "?query=" + query); try{ _extractTopicsFrom(newURL, tm, depth + 1, cid); } catch (Exception e) { e.printStackTrace(); } } return true; } // ------------------------------------------------------------------------- public ArrayList<String> parse(JSONObject json, TopicMap tm) throws TopicMapException, JSONException { if(!json.has("result")){ throw new TopicMapException("Query returned no results!"); } if(json.get("result") instanceof JSONObject) { try { JSONObject result = json.getJSONObject("result"); return parseResult(result, tm); } catch (Exception ex) { ex.printStackTrace(); log(ex); } } return new ArrayList<String>(); } public ArrayList<String> parseResult(JSONObject result, TopicMap tm) throws JSONException, TopicMapException { Topic objectTopic = createFreebaseTopic(tm, result); extractCount++; if (result.get("type") instanceof JSONArray && (extractCount < maxExtractCount || toggleLimit) ) { // Freebase type -> Wandora class JSONArray types = result.getJSONArray("type"); return parseTypes(types, objectTopic, tm); } return new ArrayList<String>(); } public ArrayList<String> parseTypes(JSONArray types, Topic objectTopic, TopicMap tm) throws JSONException, TopicMapException { ArrayList<String> typeTargetIDs = new ArrayList<String>(); for ( int i = 0; i < types.length(); i++){ if(extractCount >= maxExtractCount && !toggleLimit) break; JSONObject type = types.getJSONObject(i); Topic typeTopic = createType(tm, type); extractCount++; objectTopic.addType(typeTopic); if(type.get("properties") instanceof JSONArray){ // Freebase property -> Wandora association JSONArray typeProperties = type.getJSONArray(("properties")); typeTargetIDs.addAll(parseProperty(typeProperties, objectTopic, typeTopic, tm)); } } return typeTargetIDs; } public ArrayList<String> parseProperty(JSONArray properties, Topic objectTopic, Topic typeTopic, TopicMap tm ) throws JSONException,TopicMapException { ArrayList<String> propertyTargetIDs = new ArrayList<String>(); for ( int i = 0; i < properties.length(); i++){ if(extractCount >= maxExtractCount && !toggleLimit) break; JSONObject property = properties.getJSONObject(i); if(property.getJSONArray("links").length() != 0) { JSONObject expectedType = property.getJSONObject("expected_type"); Topic propertyTypeTopic = createLinkType(tm, property); extractCount++; Topic targetTypeTopic = createType(tm, expectedType); JSONArray links = property.getJSONArray(("links")); for (int j = 0; j < links.length(); j++){ JSONObject link = links.getJSONObject(j); if(link.get("target_value") instanceof String) { String targetValue = link.getString("target_value"); objectTopic.setData(propertyTypeTopic, getLangTopic(tm), targetValue); } else if(link.get("target") instanceof JSONObject && extractCount < maxExtractCount && !toggleLimit) { JSONObject target = link.getJSONObject("target"); propertyTargetIDs.add(target.getString("id")); Topic targetTopic = createFreebaseTopic(tm, target); extractCount++; targetTopic.addType(targetTypeTopic); Association a = tm.createAssociation(propertyTypeTopic); a.addPlayer(objectTopic, getSourceType(tm)); a.addPlayer(targetTopic, getTargetType(tm)); } } } if (property.get("master_property") instanceof JSONObject){ JSONObject mProperty = property.getJSONObject("master_property"); if(mProperty.has("links")){ JSONArray mlinks = mProperty.getJSONArray("links"); for (int j = 0; j < mlinks.length(); j++) { if(extractCount >= maxExtractCount && !toggleLimit) break; JSONObject mExpectedType = property.getJSONObject("expected_type"); Topic mPropertyTypeTopic = createLinkType(tm, mProperty); Topic mSourceTypeTopic = createType(tm, mExpectedType); JSONObject link = mlinks.getJSONObject(j); if(link.get("source") instanceof JSONObject) { JSONObject source = link.getJSONObject("source"); propertyTargetIDs.add(source.getString("id")); Topic mSourceTopic = createFreebaseTopic(tm, source); extractCount++; mSourceTopic.addType(mSourceTypeTopic); Association a = tm.createAssociation(mPropertyTypeTopic); a.addPlayer(objectTopic, getTargetType(tm)); a.addPlayer(mSourceTopic, getSourceType(tm)); } } } } } return propertyTargetIDs; } private String getIdFromUrl(URL u){ try{ String us = u.toString(); int beginID = us.indexOf("%22id%22%3A+%22%2F") + 18; int endID = us.indexOf("%22", beginID); String id = URLDecoder.decode(us.substring(beginID, endID),"UTF-8"); return id; } catch (Exception e) { e.printStackTrace(); } return null; } }
11,223
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
FreebaseExtractorUI.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/freebase/FreebaseExtractorUI.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.freebase; import java.awt.Component; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Iterator; import javax.swing.DefaultListModel; import javax.swing.JDialog; 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.SimpleTabbedPane; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; import org.wandora.utils.IObox; /** * * @author * Eero Lehtonen */ public class FreebaseExtractorUI 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; public static final String FREEBASE_MQL_API_BASE = "https://www.googleapis.com/freebase/v1/mqlread"; public static int maxDepth = 1; public static int maxExtractCount = 1500; public static boolean toggleLimit = false; private ArrayList<String> searchListIds; /* * Creates new form FreebaseExtractorUI */ public FreebaseExtractorUI() { 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, 300); dialog.add(this); dialog.setTitle("Freebase API extractor"); UIBox.centerWindow(dialog, w); dialog.setVisible(true); } public WandoraTool[] getExtractors(FreebaseExtractor tool) throws TopicMapException { Component component = freebaseTabbedPane.getSelectedComponent(); WandoraTool wt = null; ArrayList<WandoraTool> wts = new ArrayList<>(); try{ maxDepth = Integer.parseInt(mqlDepthTextField.getText()); maxExtractCount = Integer.parseInt(mqlMaxCountTextField.getText()); } catch (NumberFormatException ex) { throw new TopicMapException("Invalid depth or topic count!"); } toggleLimit = mqlToggleCountCheckBox.isSelected(); String[] idarray = new String[0]; if(component.equals(mqlIDQueryPanel)){ String ids = mqlQueryTextField.getText(); idarray = ids.split((",")); } else if (component.equals(mqlSearchQueryPanel)) { int[] selectedIndices = searchQueryResultList.getSelectedIndices(); idarray = new String[selectedIndices.length]; for (int i = 0; i < selectedIndices.length; i++) { idarray[i] = searchListIds.get(i).trim(); } } else { try{ String urlText = urlQueryTextField.getText(); if ( urlText.indexOf("freebase.com") == -1) throw new MalformedURLException(); URL url = new URL(urlText); String id = url.getPath().replace("/view", "").trim(); idarray = new String[1]; idarray[0] = id; } catch (MalformedURLException ex) { throw new TopicMapException("Invalid URL!"); } } ArrayList<String> urls = new ArrayList<String>(); for ( String id : idarray) { id = id.trim(); String query = AbstractFreebaseExtractor.getQuery(id); String extractUrl = FREEBASE_MQL_API_BASE +"?query=" + urlEncode(query); System.out.println("URL: " + extractUrl); urls.add(extractUrl); } FreebaseMQLExtractor ex = new FreebaseMQLExtractor(); ex.setForceUrls(urls.toArray(new String[urls.size()-1])); 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; } private void executeFreebaseSearch(String queryText){ try { String urlQuery = "https://www.googleapis.com/freebase/v1/search?query=" + urlEncode(queryText); String in; URL u = new URL(urlQuery); in = IObox.doUrl(u); JSONObject json = new JSONObject(in); JSONArray results = json.getJSONArray("result"); DefaultListModel model = new DefaultListModel(); searchQueryResultList.setModel(model); searchListIds = new ArrayList<String>(); for( int i = 0; i < results.length(); i++ ){ JSONObject result = results.getJSONObject(i); searchListIds.add(result.getString("mid")); String listText = result.getString("name"); if(result.has(("notable"))){ String notable = result.getJSONObject("notable").getString("name"); listText += " [" + notable + "]"; } model.add(i, listText); } } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } 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.getOneSubjectIdentifier().toString(); URL url = new URL(str); str = url.getPath(); 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(); } /* * 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; freebaseMQLQueryPanel = new javax.swing.JPanel(); freebaseTabbedPane = new SimpleTabbedPane(); mqlSearchQueryPanel = new javax.swing.JPanel(); searchQueryLabel = new SimpleLabel(); searchQueryTextField = new SimpleField(); searchQueryScrollPane = new javax.swing.JScrollPane(); searchQueryResultList = new javax.swing.JList(); searchQuerySubmitButton = new SimpleButton(); mqlIDQueryPanel = new javax.swing.JPanel(); mqlQueryLabel = new SimpleLabel(); mqlQueryTextField = new SimpleField(); mqlQueryContextButton = new SimpleButton(); mqlURLQueryPanel = new javax.swing.JPanel(); urlQueryLabel = new SimpleLabel(); urlQueryTextField = new SimpleField(); mqlDepthLabel = new SimpleLabel(); mqlDepthTextField = new SimpleField(); mqlMaxCountLabel = new SimpleLabel(); mqlMaxCountTextField = new SimpleField(); mqlToggleCountCheckBox = new SimpleCheckBox(); jPanel1 = new javax.swing.JPanel(); okButton = new SimpleButton(); cancelButton = new SimpleButton(); setMinimumSize(new java.awt.Dimension(160, 30)); setPreferredSize(new java.awt.Dimension(160, 30)); setLayout(new java.awt.GridBagLayout()); freebaseMQLQueryPanel.setLayout(new java.awt.GridBagLayout()); mqlSearchQueryPanel.setLayout(new java.awt.GridBagLayout()); searchQueryLabel.setText("Free text search"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2); mqlSearchQueryPanel.add(searchQueryLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 0.1; gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2); mqlSearchQueryPanel.add(searchQueryTextField, gridBagConstraints); searchQueryScrollPane.setViewportView(searchQueryResultList); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.gridwidth = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 0.1; gridBagConstraints.weighty = 0.1; gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2); mqlSearchQueryPanel.add(searchQueryScrollPane, gridBagConstraints); searchQuerySubmitButton.setText("Search"); searchQuerySubmitButton.setMargin(new java.awt.Insets(2, 6, 2, 6)); searchQuerySubmitButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { searchQuerySubmitButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); mqlSearchQueryPanel.add(searchQuerySubmitButton, gridBagConstraints); freebaseTabbedPane.addTab("Text search", mqlSearchQueryPanel); mqlIDQueryPanel.setLayout(new java.awt.GridBagLayout()); mqlQueryLabel.setText("Freebase ID"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); mqlIDQueryPanel.add(mqlQueryLabel, gridBagConstraints); mqlQueryTextField.setText("/en/jane_austen"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); mqlIDQueryPanel.add(mqlQueryTextField, gridBagConstraints); mqlQueryContextButton.setText("Get context"); mqlQueryContextButton.setMargin(new java.awt.Insets(2, 6, 2, 6)); mqlQueryContextButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { mqlQueryContextButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.PAGE_END; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); mqlIDQueryPanel.add(mqlQueryContextButton, gridBagConstraints); freebaseTabbedPane.addTab("Freebase ID", mqlIDQueryPanel); mqlURLQueryPanel.setLayout(new java.awt.GridBagLayout()); urlQueryLabel.setText("Freebase URL"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START; gridBagConstraints.weightx = 0.1; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); mqlURLQueryPanel.add(urlQueryLabel, gridBagConstraints); urlQueryTextField.setText("http://www.freebase.com/view/en/jane_austen"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); mqlURLQueryPanel.add(urlQueryTextField, gridBagConstraints); freebaseTabbedPane.addTab("Freebase URL", mqlURLQueryPanel); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 8; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 0.1; gridBagConstraints.weighty = 1.5; freebaseMQLQueryPanel.add(freebaseTabbedPane, gridBagConstraints); mqlDepthLabel.setText("Max depth"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2); freebaseMQLQueryPanel.add(mqlDepthLabel, gridBagConstraints); mqlDepthTextField.setHorizontalAlignment(javax.swing.JTextField.CENTER); mqlDepthTextField.setText("1"); mqlDepthTextField.setMaximumSize(new java.awt.Dimension(20, 2147483647)); mqlDepthTextField.setMinimumSize(new java.awt.Dimension(20, 23)); mqlDepthTextField.setPreferredSize(new java.awt.Dimension(20, 23)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.weightx = 0.1; gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2); freebaseMQLQueryPanel.add(mqlDepthTextField, gridBagConstraints); mqlMaxCountLabel.setText("Max topic count"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2); freebaseMQLQueryPanel.add(mqlMaxCountLabel, gridBagConstraints); mqlMaxCountTextField.setHorizontalAlignment(javax.swing.JTextField.CENTER); mqlMaxCountTextField.setText("1500"); mqlMaxCountTextField.setMaximumSize(new java.awt.Dimension(40, 2147483647)); mqlMaxCountTextField.setMinimumSize(new java.awt.Dimension(40, 23)); mqlMaxCountTextField.setPreferredSize(new java.awt.Dimension(40, 23)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 1; gridBagConstraints.weightx = 0.1; gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2); freebaseMQLQueryPanel.add(mqlMaxCountTextField, gridBagConstraints); mqlToggleCountCheckBox.setText("No limit"); mqlToggleCountCheckBox.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { mqlToggleCountCheckBoxStateChanged(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 4; gridBagConstraints.gridy = 1; freebaseMQLQueryPanel.add(mqlToggleCountCheckBox, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; freebaseMQLQueryPanel.add(jPanel1, 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.gridx = 6; gridBagConstraints.gridy = 1; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 0); freebaseMQLQueryPanel.add(okButton, gridBagConstraints); cancelButton.setText("Cancel"); cancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 7; gridBagConstraints.gridy = 1; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); freebaseMQLQueryPanel.add(cancelButton, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(freebaseMQLQueryPanel, 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 mqlToggleCountCheckBoxStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_mqlToggleCountCheckBoxStateChanged if (mqlToggleCountCheckBox.isSelected()) mqlMaxCountTextField.setEnabled(false); else mqlMaxCountTextField.setEnabled(true); }//GEN-LAST:event_mqlToggleCountCheckBoxStateChanged private void searchQuerySubmitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchQuerySubmitButtonActionPerformed executeFreebaseSearch(searchQueryTextField.getText()); }//GEN-LAST:event_searchQuerySubmitButtonActionPerformed private void mqlQueryContextButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mqlQueryContextButtonActionPerformed mqlQueryTextField.setText(getContextAsString()); }//GEN-LAST:event_mqlQueryContextButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton cancelButton; private javax.swing.JPanel freebaseMQLQueryPanel; private javax.swing.JTabbedPane freebaseTabbedPane; private javax.swing.JPanel jPanel1; private javax.swing.JLabel mqlDepthLabel; private javax.swing.JTextField mqlDepthTextField; private javax.swing.JPanel mqlIDQueryPanel; private javax.swing.JLabel mqlMaxCountLabel; private javax.swing.JTextField mqlMaxCountTextField; private javax.swing.JButton mqlQueryContextButton; private javax.swing.JLabel mqlQueryLabel; private javax.swing.JTextField mqlQueryTextField; private javax.swing.JPanel mqlSearchQueryPanel; private javax.swing.JCheckBox mqlToggleCountCheckBox; private javax.swing.JPanel mqlURLQueryPanel; private javax.swing.JButton okButton; private javax.swing.JLabel searchQueryLabel; private javax.swing.JList searchQueryResultList; private javax.swing.JScrollPane searchQueryScrollPane; private javax.swing.JButton searchQuerySubmitButton; private javax.swing.JTextField searchQueryTextField; private javax.swing.JLabel urlQueryLabel; private javax.swing.JTextField urlQueryTextField; // End of variables declaration//GEN-END:variables }
22,039
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
FreebaseExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/freebase/FreebaseExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.freebase; 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.WandoraToolType; 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 FreebaseExtractor extends AbstractExtractor { private static final long serialVersionUID = 1L; private FreebaseExtractorUI ui = null; @Override public WandoraToolType getType(){ return WandoraToolType.createExtractType(); } @Override public String getName(){ return "Freebase Extractor"; } @Override public String getDescription(){ return "Extracts topics and associations from the Freebase API. "+ "A personal api-key is required for the API access."; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_freebase.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 FreebaseExtractorUI(); } 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 Freebase 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("Done."); } 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 Freebase. 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 Freebase. 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 Freebase. It doesn't perform extration it self."); } }
4,776
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AbstractFreebaseExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/freebase/AbstractFreebaseExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.freebase; /** * * @author * Eero Lehtonen */ 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.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; public abstract class AbstractFreebaseExtractor extends AbstractExtractor { private static final long serialVersionUID = 1L; @Override public String getName() { return "Abstract Freebase API extractor"; } @Override public String getDescription(){ return "Abstract extractor for the Freebase API."; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract.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 FREEBASE_WANDORA_SI = "http://wandora.org/si/freebase"; public static final String FREEBASE_BASE_SI = "http://www.freebase.com"; public static final String OBJECT_SI = FREEBASE_WANDORA_SI + "/OBJECT"; public static final String TYPE_SI = FREEBASE_WANDORA_SI + "/TYPE"; public static final String NAME_SI = FREEBASE_WANDORA_SI + "/name"; public static final String TARGET_SI = FREEBASE_WANDORA_SI + "/target"; public static final String SOURCE_SI = FREEBASE_WANDORA_SI + "/source"; public static final String LINK_SI = FREEBASE_WANDORA_SI + "/link"; public static final String LANG_SI = "http://www.topicmaps.org/xtm/1.0/language.xtm#en"; protected static Topic getWandoraClassTopic(TopicMap tm) throws TopicMapException { return getOrCreateTopic(tm, TMBox.WANDORACLASS_SI, "Wandora class"); } public static Topic getNameType(TopicMap tm) throws TopicMapException{ Topic type = getOrCreateTopic(tm, NAME_SI, "Object name (Freebase API)"); return type; } public static Topic getObjectType(TopicMap tm) throws TopicMapException{ Topic type = getOrCreateTopic(tm, OBJECT_SI, "Object (Freebase API)"); Topic freebaseTopic = getFreebaseType(tm); makeSubclassOf(tm, type, freebaseTopic); return type; } public static Topic getTypeType(TopicMap tm) throws TopicMapException{ Topic type = getOrCreateTopic(tm, TYPE_SI, "Type (Freebase API)"); Topic freebaseTopic = getFreebaseType(tm); makeSubclassOf(tm, type, freebaseTopic); return type; } public static Topic getTargetType(TopicMap tm) throws TopicMapException{ Topic type = getOrCreateTopic(tm, TARGET_SI, "Target (Freebase API)"); Topic freebaseTopic = getFreebaseType(tm); return type; } public static Topic getSourceType(TopicMap tm) throws TopicMapException{ Topic type = getOrCreateTopic(tm, SOURCE_SI, "Source (Freebase API)"); Topic freebaseTopic = getFreebaseType(tm); return type; } public static Topic getLinkType(TopicMap tm) throws TopicMapException{ Topic type = getOrCreateTopic(tm, LINK_SI, "Link (Freebase API)"); Topic freebaseTopic = getFreebaseType(tm); makeSubclassOf(tm, type, freebaseTopic); return type; } public Topic createFreebaseTopic(TopicMap tm, JSONObject mqlObject) throws TopicMapException, JSONException{ String topicID = mqlObject.getString(("id")); String topicGUID = mqlObject.getString("guid"); topicGUID = topicGUID.replace("#", "/guid/"); String topicName = (mqlObject.get("name") instanceof String) ? mqlObject.getString(("name")) : "<no name>"; Topic topic = getOrCreateTopic(tm, FREEBASE_BASE_SI + topicGUID); topic.addSubjectIdentifier(new Locator(FREEBASE_BASE_SI + topicID)); topic.setBaseName(topicName + " (" + topicID + ")"); topic.setDisplayName("en", topicName); topic.setData(getNameType(tm), getLangTopic(tm), topicName); return topic; } public Topic createType(TopicMap tm, JSONObject mqlObject) throws TopicMapException, JSONException{ Topic type = createFreebaseTopic(tm, mqlObject); type.addType(getTypeType(tm)); return type; } public Topic createLinkType(TopicMap tm, JSONObject mqlObject) throws TopicMapException, JSONException{ Topic type = createFreebaseTopic(tm, mqlObject); type.addType(getLinkType(tm)); return type; } public static Topic getFreebaseType(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, FREEBASE_BASE_SI, "Freebase API"); Topic wandoraClass = getWandoraClassTopic(tm); makeSubclassOf(tm, type, wandoraClass); return type; } 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); } protected static String getQuery(String id){ return "{" + "\"id\": \"" + id + "\"," + "\"name\": null," + "\"guid\": null," + "\"type\": [{" + "\"id\": null," + "\"name\": null," + "\"guid\": null," + "\"properties\": [{" + "\"expected_type\":{" + "\"id\":null," + "\"guid\": null," + "\"name\":null" + "}," + "\"id\": null," + "\"guid\": null," + "\"name\": null," + "\"links\": [{" + "\"source\": {" + "\"id\": \"" + id + "\"" + "}," + "\"target\": {" + "\"guid\": null," + "\"id\": null," + "\"name\": null," + "\"optional\": true" + "}," + "\"optional\": true," + "\"target_value\": null" + "}]," + "\"master_property\": {" + "\"optional\": true," + "\"expected_type\":{" + "\"guid\": null," + "\"id\":null," + "\"name\":null" + "}," + "\"id\": null," + "\"guid\": null," + "\"name\": null," + "\"links\": [{" + "\"source\": {" + "\"guid\": null," + "\"id\": null," + "\"name\": null" + "}," + "\"target\": {" + "\"id\": \"" + id + "\"" + "}" + "}]" + "}" + "}]" + "}]" +"}"; } }
9,364
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
FreebaseExtractorUI.java.orig
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/freebase/FreebaseExtractorUI.java.orig
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2016 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.freebase; import java.awt.Component; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Iterator; import javax.swing.DefaultListModel; import javax.swing.JDialog; 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.*; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; import org.wandora.utils.IObox; /** * * @author * Eero Lehtonen */ public class FreebaseExtractorUI extends javax.swing.JPanel { private Wandora wandora = null; private boolean accepted = false; private JDialog dialog = null; private Context context = null; public static final String FREEBASE_MQL_API_BASE = "http://api.freebase.com/api/service/mqlread"; public static int maxDepth = 1; public static int maxExtractCount = 1500; public static boolean toggleLimit = false; private ArrayList<String> searchListIds; /* * Creates new form FreebaseExtractorUI */ public FreebaseExtractorUI() { 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, 300); dialog.add(this); dialog.setTitle("Freebase API extractor"); UIBox.centerWindow(dialog, w); dialog.setVisible(true); } public WandoraTool[] getExtractors(FreebaseExtractor tool) throws TopicMapException { Component component = freebaseTabbedPane.getSelectedComponent(); WandoraTool wt = null; ArrayList<WandoraTool> wts = new ArrayList(); try{ maxDepth = Integer.parseInt(mqlDepthTextField.getText()); maxExtractCount = Integer.parseInt(mqlMaxCountTextField.getText()); } catch (NumberFormatException ex) { throw new TopicMapException("Invalid depth or topic count!"); } toggleLimit = mqlToggleCountCheckBox.isSelected(); String[] idarray = new String[0]; if(component.equals(mqlIDQueryPanel)){ String ids = mqlQueryTextField.getText(); idarray = ids.split((",")); } else if (component.equals(mqlSearchQueryPanel)) { int[] selectedIndices = searchQueryResultList.getSelectedIndices(); idarray = new String[selectedIndices.length]; for (int i = 0; i < selectedIndices.length; i++) { idarray[i] = searchListIds.get(i).trim(); } } else { try{ String urlText = urlQueryTextField.getText(); if ( urlText.indexOf("freebase.com") == -1) throw new MalformedURLException(); URL url = new URL(urlText); String id = url.getPath().replace("/view", "").trim(); idarray = new String[1]; idarray[0] = id; } catch (MalformedURLException ex) { throw new TopicMapException("Invalid URL!"); } } ArrayList<String> urls = new ArrayList<String>(); for ( String id : idarray){ id = id.trim(); String query = AbstractFreebaseExtractor.getQuery(id); String extractUrl = FREEBASE_MQL_API_BASE +"?query=" + urlEncode(query); System.out.println("URL: " + extractUrl); urls.add(extractUrl); } FreebaseMQLExtractor ex = new FreebaseMQLExtractor(); ex.setForceUrls(urls.toArray(new String[urls.size()-1])); 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; } private void executeFreebaseSearch(String queryText){ try{ String urlQuery = "https://www.googleapis.com/freebase/v1/search?query=" + urlEncode(queryText); String in; URL u = new URL(urlQuery); in = IObox.doUrl(u); JSONObject json = new JSONObject(in); JSONArray results = json.getJSONArray("result"); DefaultListModel model = new DefaultListModel(); searchQueryResultList.setModel(model); searchListIds = new ArrayList<String>(); for( int i = 0; i < results.length(); i++ ){ JSONObject result = results.getJSONObject(i); searchListIds.add(result.getString("mid")); String listText = result.getString("name"); if(result.has(("notable"))){ String notable = result.getJSONObject("notable").getString("name"); listText += " [" + notable + "]"; } model.add(i, listText); } } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } 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.getOneSubjectIdentifier().toString(); URL url = new URL(str); str = url.getPath(); 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(); } /* * 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; freebaseMQLQueryPanel = new javax.swing.JPanel(); freebaseTabbedPane = new SimpleTabbedPane(); mqlSearchQueryPanel = new javax.swing.JPanel(); searchQueryLabel = new SimpleLabel(); searchQueryTextField = new SimpleField(); searchQueryScrollPane = new javax.swing.JScrollPane(); searchQueryResultList = new javax.swing.JList(); searchQuerySubmitButton = new SimpleButton(); mqlIDQueryPanel = new javax.swing.JPanel(); mqlQueryLabel = new SimpleLabel(); mqlQueryTextField = new SimpleField(); mqlQueryContextButton = new SimpleButton(); mqlURLQueryPanel = new javax.swing.JPanel(); urlQueryLabel = new javax.swing.JLabel(); urlQueryTextField = new javax.swing.JTextField(); mqlDepthLabel = new SimpleLabel(); mqlDepthTextField = new SimpleField(); mqlMaxCountLabel = new SimpleLabel(); mqlMaxCountTextField = new SimpleField(); mqlToggleCountCheckBox = new SimpleCheckBox(); jPanel1 = new javax.swing.JPanel(); okButton = new SimpleButton(); cancelButton = new SimpleButton(); setMinimumSize(new java.awt.Dimension(160, 30)); setPreferredSize(new java.awt.Dimension(160, 30)); setLayout(new java.awt.GridBagLayout()); freebaseMQLQueryPanel.setLayout(new java.awt.GridBagLayout()); mqlSearchQueryPanel.setLayout(new java.awt.GridBagLayout()); searchQueryLabel.setText("Free text search"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2); mqlSearchQueryPanel.add(searchQueryLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 0.1; gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2); mqlSearchQueryPanel.add(searchQueryTextField, gridBagConstraints); searchQueryScrollPane.setViewportView(searchQueryResultList); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.gridwidth = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 0.1; gridBagConstraints.weighty = 0.1; gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2); mqlSearchQueryPanel.add(searchQueryScrollPane, gridBagConstraints); searchQuerySubmitButton.setText("Search"); searchQuerySubmitButton.setMargin(new java.awt.Insets(1, 6, 1, 6)); searchQuerySubmitButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { searchQuerySubmitButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); mqlSearchQueryPanel.add(searchQuerySubmitButton, gridBagConstraints); freebaseTabbedPane.addTab("Text search", mqlSearchQueryPanel); mqlIDQueryPanel.setLayout(new java.awt.GridBagLayout()); mqlQueryLabel.setText("Freebase ID"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); mqlIDQueryPanel.add(mqlQueryLabel, gridBagConstraints); mqlQueryTextField.setText("/en/jane_austen"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); mqlIDQueryPanel.add(mqlQueryTextField, gridBagConstraints); mqlQueryContextButton.setText("Get context"); mqlQueryContextButton.setMargin(new java.awt.Insets(1, 6, 1, 6)); mqlQueryContextButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { mqlQueryContextButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.PAGE_END; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); mqlIDQueryPanel.add(mqlQueryContextButton, gridBagConstraints); freebaseTabbedPane.addTab("Freebase ID", mqlIDQueryPanel); mqlURLQueryPanel.setLayout(new java.awt.GridBagLayout()); urlQueryLabel.setText("Freebase URL"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START; gridBagConstraints.weightx = 0.1; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); mqlURLQueryPanel.add(urlQueryLabel, gridBagConstraints); urlQueryTextField.setText("http://www.freebase.com/view/en/jane_austen"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); mqlURLQueryPanel.add(urlQueryTextField, gridBagConstraints); freebaseTabbedPane.addTab("Freebase URL", mqlURLQueryPanel); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 8; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 0.1; gridBagConstraints.weighty = 1.5; freebaseMQLQueryPanel.add(freebaseTabbedPane, gridBagConstraints); mqlDepthLabel.setText("Max depth"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2); freebaseMQLQueryPanel.add(mqlDepthLabel, gridBagConstraints); mqlDepthTextField.setHorizontalAlignment(javax.swing.JTextField.CENTER); mqlDepthTextField.setText("1"); mqlDepthTextField.setMaximumSize(new java.awt.Dimension(20, 2147483647)); mqlDepthTextField.setMinimumSize(new java.awt.Dimension(20, 20)); mqlDepthTextField.setPreferredSize(new java.awt.Dimension(20, 20)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.weightx = 0.1; gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2); freebaseMQLQueryPanel.add(mqlDepthTextField, gridBagConstraints); mqlMaxCountLabel.setText("Max topic count"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2); freebaseMQLQueryPanel.add(mqlMaxCountLabel, gridBagConstraints); mqlMaxCountTextField.setHorizontalAlignment(javax.swing.JTextField.CENTER); mqlMaxCountTextField.setText("1500"); mqlMaxCountTextField.setMaximumSize(new java.awt.Dimension(40, 2147483647)); mqlMaxCountTextField.setMinimumSize(new java.awt.Dimension(40, 20)); mqlMaxCountTextField.setPreferredSize(new java.awt.Dimension(40, 20)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 1; gridBagConstraints.weightx = 0.1; gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2); freebaseMQLQueryPanel.add(mqlMaxCountTextField, gridBagConstraints); mqlToggleCountCheckBox.setText("No limit"); mqlToggleCountCheckBox.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { mqlToggleCountCheckBoxStateChanged(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 4; gridBagConstraints.gridy = 1; freebaseMQLQueryPanel.add(mqlToggleCountCheckBox, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; freebaseMQLQueryPanel.add(jPanel1, 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.gridx = 6; gridBagConstraints.gridy = 1; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 0); freebaseMQLQueryPanel.add(okButton, gridBagConstraints); cancelButton.setText("Cancel"); cancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 7; gridBagConstraints.gridy = 1; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); freebaseMQLQueryPanel.add(cancelButton, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(freebaseMQLQueryPanel, 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 mqlToggleCountCheckBoxStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_mqlToggleCountCheckBoxStateChanged if (mqlToggleCountCheckBox.isSelected()) mqlMaxCountTextField.setEnabled(false); else mqlMaxCountTextField.setEnabled(true); }//GEN-LAST:event_mqlToggleCountCheckBoxStateChanged private void searchQuerySubmitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchQuerySubmitButtonActionPerformed executeFreebaseSearch(searchQueryTextField.getText()); }//GEN-LAST:event_searchQuerySubmitButtonActionPerformed private void mqlQueryContextButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mqlQueryContextButtonActionPerformed mqlQueryTextField.setText(getContextAsString()); }//GEN-LAST:event_mqlQueryContextButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton cancelButton; private javax.swing.JPanel freebaseMQLQueryPanel; private javax.swing.JTabbedPane freebaseTabbedPane; private javax.swing.JPanel jPanel1; private javax.swing.JLabel mqlDepthLabel; private javax.swing.JTextField mqlDepthTextField; private javax.swing.JPanel mqlIDQueryPanel; private javax.swing.JLabel mqlMaxCountLabel; private javax.swing.JTextField mqlMaxCountTextField; private javax.swing.JButton mqlQueryContextButton; private javax.swing.JLabel mqlQueryLabel; private javax.swing.JTextField mqlQueryTextField; private javax.swing.JPanel mqlSearchQueryPanel; private javax.swing.JCheckBox mqlToggleCountCheckBox; private javax.swing.JPanel mqlURLQueryPanel; private javax.swing.JButton okButton; private javax.swing.JLabel searchQueryLabel; private javax.swing.JList searchQueryResultList; private javax.swing.JScrollPane searchQueryScrollPane; private javax.swing.JButton searchQuerySubmitButton; private javax.swing.JTextField searchQueryTextField; private javax.swing.JLabel urlQueryLabel; private javax.swing.JTextField urlQueryTextField; // End of variables declaration//GEN-END:variables }
21,760
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
EmailExtractorPanel.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/email/EmailExtractorPanel.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * EmailExtractorPanel.java * * Created on 5.7.2005, 14:43 */ package org.wandora.application.tools.extractors.email; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.Properties; import javax.imageio.ImageIO; import javax.swing.AbstractCellEditor; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellEditor; import org.wandora.application.gui.UIConstants; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.application.gui.simple.SimpleFileChooser; import org.wandora.application.tools.PictureView; import org.wandora.utils.Delegate; import org.wandora.utils.XMLbox; import jakarta.mail.Address; import jakarta.mail.BodyPart; import jakarta.mail.FetchProfile; import jakarta.mail.Flags; import jakarta.mail.Folder; import jakarta.mail.Message; import jakarta.mail.MessagingException; import jakarta.mail.Session; import jakarta.mail.Store; import jakarta.mail.URLName; import jakarta.mail.internet.MimeMultipart; /** * * @author olli */ public class EmailExtractorPanel extends javax.swing.JPanel { private static final long serialVersionUID = 1L; private DefaultTableModel tableModel; private List<BufferedImage> fullImages; private List<String> uids; private List<String> senders; private Map<String,Integer> uidMap; private java.awt.Frame parent; private String protocol="pop3"; private String host="localhost"; private String user="wandora"; private String pass="wandora"; private String msgFolder="INBOX"; private String port="110"; private String[] columnNames; private Class[] columnClasses; private boolean[] columnEditable; private String[] columnXMLKeys; private boolean tryXMLExtract; private Delegate<Delegate.Void,EmailExtractorPanel> okHandler; private Delegate<Delegate.Void,EmailExtractorPanel> cancelHandler; private int popupRow=-1; /** Creates new form EmailExtractorPanel */ public EmailExtractorPanel(java.awt.Frame parent,Delegate<Delegate.Void,EmailExtractorPanel> okHandler,Delegate<Delegate.Void,EmailExtractorPanel> cancelHandler,String host,String port,String user,String pass) { this(parent,okHandler,cancelHandler,host,port,user,pass,new Object[]{"Message",String.class,true,null}); } /* * Additional columns are given with four elements per column: * Column name,column class,editable,xml key for column. * Column name is the name shown to user in the table and also key for data in extracted Hashmap. * Column class is the java class of the data, * usually <code>String.class</code>. Editable is boolean indicating whether the column is editable. * XML key is the key used to get data for column from message xml or null if data is not taken * from message xml but left blank instead. * Column name "Message" is a special case and is used to get the original message of the email. */ public EmailExtractorPanel(java.awt.Frame parent,Delegate<Delegate.Void,EmailExtractorPanel> okHandler,Delegate<Delegate.Void,EmailExtractorPanel> cancelHandler,String host,String port,String user,String pass,Object[] additionalColumns) { this.host=host; this.port=port; this.user=user; this.pass=pass; this.okHandler=okHandler; this.cancelHandler=cancelHandler; this.parent=parent; this.columnNames=new String[4+additionalColumns.length/4]; this.columnClasses=new Class[columnNames.length]; this.columnEditable=new boolean[columnNames.length]; this.columnXMLKeys=new String[columnNames.length]; this.columnNames[0]="Import"; this.columnNames[1]="Delete"; this.columnNames[2]="Sent"; this.columnNames[3]="Image"; this.columnClasses[0]=this.columnClasses[1]=Boolean.class; this.columnClasses[2]=Date.class; this.columnClasses[3]=ImageIcon.class; this.columnEditable[0]=this.columnEditable[1]=this.columnEditable[3]=true; this.columnEditable[2]=false; this.tryXMLExtract=false; for(int i=0;i+3<additionalColumns.length;i+=4){ this.columnNames[4+i/4]=(String)additionalColumns[i]; this.columnClasses[4+i/4]=(Class)additionalColumns[i+1]; this.columnEditable[4+i/4]=((Boolean)additionalColumns[i+2]).booleanValue(); this.columnXMLKeys[4+i/4]=(String)additionalColumns[i+3]; if(columnXMLKeys[4+i/4]!=null) tryXMLExtract=true; } Object[] objectNames=new Object[this.columnNames.length]; for(int i=0;i<this.columnNames.length;i++) objectNames[i]=this.columnNames[i]; this.tableModel=new DefaultTableModel( /*new Object[]{"Import","Delete","Sent","Image","Message"}*/objectNames,0){ public Class getColumnClass(int columnIndex){ /* switch(columnIndex){ case 0: return Boolean.class; case 1: return Boolean.class; case 2: return Date.class; case 3: return ImageIcon.class; case 4: return String.class; }*/ if(columnIndex<columnClasses.length) return columnClasses[columnIndex]; return null; } public boolean isCellEditable(int rowIndex,int columnIndex){ /* switch(columnIndex){ case 0: return true; case 1: return true; case 2: return false; case 3: return true; case 4: return true; } */ if(columnIndex<columnEditable.length) return columnEditable[columnIndex]; return false; } }; initComponents(); table.setRowHeight(50); table.getColumnModel().getColumn(0).setPreferredWidth(50); table.getColumnModel().getColumn(0).setMaxWidth(50); table.getColumnModel().getColumn(1).setPreferredWidth(50); table.getColumnModel().getColumn(1).setMaxWidth(50); table.getColumnModel().getColumn(2).setPreferredWidth(100); table.getColumnModel().getColumn(2).setMaxWidth(100); int picwidth=(int)(50.0*4.0/3.0+10.0); table.getColumnModel().getColumn(3).setPreferredWidth(picwidth); table.getColumnModel().getColumn(3).setMaxWidth(picwidth); table.getColumnModel().getColumn(3).setCellEditor(new ImageViewerCellEditor()); table.setComponentPopupMenu(popupMenu); } private class ImageViewerCellEditor extends AbstractCellEditor implements TableCellEditor { private static final long serialVersionUID = 1L; private JButton button; private ImageIcon currentImage; private BufferedImage fullImage; public ImageViewerCellEditor(){ button=new JButton(); button.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ PictureView pv=new PictureView(parent,true,fullImage); pv.setVisible(true); fireEditingStopped(); } }); button.setBorderPainted(false); } public Object getCellEditorValue(){ return currentImage; } public java.awt.Component getTableCellEditorComponent(JTable table,Object value,boolean isSelected,int row,int column){ currentImage=(ImageIcon)value; fullImage=fullImages.get(row); return button; } } public static class ImageTableRenderer extends JComponent { private static final long serialVersionUID = 1L; private java.awt.Image img; public ImageTableRenderer(){} public void setImage(java.awt.Image img){ this.img=img; } public void paint(java.awt.Graphics g){ g.drawImage(img,0,0,this); } } public static class EmailSession{ public Session session; public Folder folder; public Store store; public EmailSession(Session session,Store store,Folder folder){ this.session=session; this.store=store; this.folder=folder; } public void close(boolean expunge) throws MessagingException { folder.close(expunge); store.close(); } public Message[] getMessages() throws MessagingException { int numMessages=folder.getMessageCount(); Message[] msgs=folder.getMessages(1,numMessages); return msgs; } public int getNumMessages() throws MessagingException { return folder.getMessageCount(); } public int getNumNewMessages() throws MessagingException { return folder.getNewMessageCount(); } } public EmailSession openEmailSession() throws MessagingException { System.out.println("Connecting to mail server"); Properties mailSessionProps=new Properties(); mailSessionProps.setProperty("mail.store.protocol",protocol); mailSessionProps.setProperty("mail."+protocol+".host",host); mailSessionProps.setProperty("mail."+protocol+".port",port); mailSessionProps.setProperty("mail."+protocol+".user",user); Session session=Session.getDefaultInstance(mailSessionProps); session.setDebug(false); URLName url=new URLName(protocol,host,-1,null,user,pass); Store store=session.getStore(url); store.connect(); Folder folder=store.getDefaultFolder(); folder=folder.getFolder(msgFolder); folder.open(Folder.READ_WRITE); return new EmailSession(session,store,folder); } public void getMessages() throws Exception { tableModel.setRowCount(0); fullImages=new ArrayList<>(); uids=new ArrayList<>(); uidMap=new HashMap<>(); senders=new ArrayList<>(); java.awt.EventQueue.invokeLater(new Runnable(){ public void run(){ messageLabel.setText("Connecting to mail server"); } }); EmailSession session=openEmailSession(); final int numMessages=session.getNumMessages(); int newMessages=session.getNumNewMessages(); java.awt.EventQueue.invokeLater(new Runnable(){ public void run(){ progressBar.setMinimum(0); progressBar.setMaximum(numMessages); progressBar.setValue(0); messageLabel.setText("Fetching "+numMessages+" messages"); } }); System.out.println("Fetching "+numMessages+" messages"); Message[] msgs=session.getMessages(); FetchProfile prof=new FetchProfile(); prof.add(FetchProfile.Item.ENVELOPE); prof.add(FetchProfile.Item.CONTENT_INFO); session.folder.fetch(msgs,prof); for(int i=0;i<msgs.length;i++){ final int progress=i; java.awt.EventQueue.invokeLater(new Runnable(){ public void run(){ progressBar.setValue(progress); } }); Object c=msgs[i].getContent(); String uid=msgs[i].getHeader("message-ID")[0]; boolean finalText=false; if(c instanceof MimeMultipart){ try{ MimeMultipart mm=(MimeMultipart)c; Object[] row=new Object[columnNames.length]; row[0]=Boolean.FALSE; row[1]=Boolean.FALSE; BufferedImage img=null; row[2]=msgs[i].getSentDate(); String message=""; for(int j=0;j<mm.getCount();j++){ BodyPart bp=mm.getBodyPart(j); String contentType=bp.getContentType(); if(contentType.startsWith("image/")){ System.out.println("found image"); img=ImageIO.read(bp.getInputStream()); int height=50; int width=(int)(img.getWidth()*(double)height/(double)img.getHeight()); BufferedImage thumb=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); thumb.getGraphics().drawImage(img,0,0,width,height,null); row[3]=new ImageIcon(thumb); } else if(!finalText && contentType.startsWith("text/plain")){ String[] cl=msgs[i].getHeader("Content-Location"); if(cl!=null && cl.length>0 && cl[0]!=null && cl[0].toUpperCase().endsWith(".txt")) finalText=true; message=bp.getContent().toString(); } } if(row[3]!=null){ Map table=null; if(tryXMLExtract){ try{ org.w3c.dom.Document doc=XMLbox.getDocument(message); table=XMLbox.xml2Hash(doc); }catch(Exception e){} } for(int j=4;j<columnNames.length;j++){ if(columnNames[j].equalsIgnoreCase("message")) row[j]=message; else if(columnXMLKeys[j]!=null && table!=null) row[j]=table.get(columnXMLKeys[j]); if(row[j]==null) row[j]=""; } tableModel.addRow(row); fullImages.add(img); uids.add(uid); uidMap.put(uid,uids.size()-1); String from=""; for(Address a : msgs[i].getFrom()){ if(from.length()>0) from+=", "; from+=a.toString(); } senders.add(from); System.out.println("UID: "+uid); } else msgs[i].setFlag(Flags.Flag.DELETED,true); }catch(Exception e){ e.printStackTrace(); msgs[i].setFlag(Flags.Flag.DELETED,true); } } else msgs[i].setFlag(Flags.Flag.DELETED,true); } session.close(true); } public Collection<Map<String,Object>> getSelectedData() { Collection<Map<String,Object>> selectedData=new ArrayList<>(); for(int i=0;i<tableModel.getRowCount();i++){ if(((Boolean)tableModel.getValueAt(i, 0)).booleanValue()){ Object sent=tableModel.getValueAt(i,2); Object image=fullImages.get(i); Map<String,Object> map=new HashMap<>(); map.put("id",uids.get(i)); map.put("sent",sent); map.put("image",image); map.put("sender",senders.get(i)); for(int j=4;j<columnNames.length;j++){ map.put(columnNames[j],tableModel.getValueAt(i,j)); } selectedData.add(map); } } return selectedData; } public void deleteSelected() throws Exception { fullImages=new ArrayList<>(); uids=new ArrayList<>(); EmailSession session=openEmailSession(); Message[] msgs=session.getMessages(); FetchProfile prof=new FetchProfile(); prof.add(FetchProfile.Item.ENVELOPE); session.folder.fetch(msgs,prof); int count=0; for(int i=0;i<msgs.length;i++){ Object c=msgs[i].getContent(); String uid=msgs[i].getHeader("message-ID")[0]; Integer index=uidMap.get(uid); if(index==null) continue; if(((Boolean)tableModel.getValueAt(index.intValue(), 1)).booleanValue()){ msgs[i].setFlag(Flags.Flag.DELETED, true); count++; } } System.out.println("Deleting "+count+" messages"); session.close(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. */ private void initComponents() {//GEN-BEGIN:initComponents java.awt.GridBagConstraints gridBagConstraints; messageToolPanel = new javax.swing.JPanel(); importAllButton = new javax.swing.JButton(); importNoneButton = new javax.swing.JButton(); deleteAllButton = new javax.swing.JButton(); deleteNoneButton = new javax.swing.JButton(); okButton = new javax.swing.JButton(); cancelButton = new javax.swing.JButton(); saveButton = new javax.swing.JButton(); popupMenu = new javax.swing.JPopupMenu(); menuItemRotRight = new javax.swing.JMenuItem(); menuItemRotLeft = new javax.swing.JMenuItem(); jScrollPane1 = new javax.swing.JScrollPane(); table = new javax.swing.JTable(); toolPanel = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); progressBar = new javax.swing.JProgressBar(); jPanel3 = new javax.swing.JPanel(); cancelButton2 = new javax.swing.JButton(); getMessagesButton = new javax.swing.JButton(); messageLabel = new javax.swing.JLabel(); messageToolPanel.setLayout(new java.awt.GridBagLayout()); importAllButton.setText("Import All"); importAllButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { importAllButtonActionPerformed(evt); } }); messageToolPanel.add(importAllButton, new java.awt.GridBagConstraints()); importNoneButton.setText("Import None"); importNoneButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { importNoneButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.insets = new java.awt.Insets(5, 0, 0, 0); messageToolPanel.add(importNoneButton, gridBagConstraints); deleteAllButton.setText("Delete All"); deleteAllButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { deleteAllButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 0); messageToolPanel.add(deleteAllButton, gridBagConstraints); deleteNoneButton.setText("Delete None"); deleteNoneButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { deleteNoneButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.insets = new java.awt.Insets(5, 10, 0, 0); messageToolPanel.add(deleteNoneButton, gridBagConstraints); okButton.setText("OK"); okButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { okButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 5; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.insets = new java.awt.Insets(5, 0, 0, 0); messageToolPanel.add(okButton, gridBagConstraints); cancelButton.setText("Cancel"); cancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5); messageToolPanel.add(cancelButton, gridBagConstraints); saveButton.setText("Save Image"); saveButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { saveButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 1; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5); messageToolPanel.add(saveButton, gridBagConstraints); popupMenu.addPopupMenuListener(new javax.swing.event.PopupMenuListener() { public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) { } public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) { } public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) { popupMenuPopupMenuWillBecomeVisible(evt); } }); menuItemRotRight.setText("Rotate right"); menuItemRotRight.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuItemRotRightActionPerformed(evt); } }); popupMenu.add(menuItemRotRight); menuItemRotLeft.setText("Rotate left"); menuItemRotLeft.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuItemRotLeftActionPerformed(evt); } }); popupMenu.add(menuItemRotLeft); setLayout(new java.awt.GridBagLayout()); table.setModel(tableModel); jScrollPane1.setViewportView(table); 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); add(jScrollPane1, gridBagConstraints); toolPanel.setLayout(new java.awt.BorderLayout()); jPanel2.setLayout(new java.awt.GridBagLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 30, 5, 30); jPanel2.add(progressBar, gridBagConstraints); jPanel3.setLayout(new java.awt.GridBagLayout()); cancelButton2.setText("Cancel"); cancelButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelButton2ActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 0); jPanel3.add(cancelButton2, gridBagConstraints); getMessagesButton.setText("Get Messages"); getMessagesButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { getMessagesButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 1; gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 0); jPanel3.add(getMessagesButton, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; jPanel3.add(messageLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel2.add(jPanel3, gridBagConstraints); toolPanel.add(jPanel2, java.awt.BorderLayout.CENTER); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(0, 10, 10, 10); add(toolPanel, gridBagConstraints); }//GEN-END:initComponents private void popupMenuPopupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {//GEN-FIRST:event_popupMenuPopupMenuWillBecomeVisible int row=table.rowAtPoint(table.getMousePosition()); popupRow=row; }//GEN-LAST:event_popupMenuPopupMenuWillBecomeVisible private void menuItemRotLeftActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItemRotLeftActionPerformed if(popupRow!=-1){ BufferedImage oldImg=fullImages.get(popupRow); BufferedImage newImg=new BufferedImage(oldImg.getHeight(),oldImg.getWidth(),BufferedImage.TYPE_INT_RGB); java.awt.Graphics2D g2=(java.awt.Graphics2D)newImg.getGraphics(); java.awt.geom.AffineTransform t=new java.awt.geom.AffineTransform(0,-1,1,0,0,oldImg.getWidth()); g2.drawImage(oldImg,t,null); fullImages.add(popupRow,newImg); int height=50; int width=(int)(newImg.getWidth()*(double)height/(double)newImg.getHeight()); BufferedImage thumb=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); thumb.getGraphics().drawImage(newImg,0,0,width,height,null); table.getModel().setValueAt(new ImageIcon(thumb), popupRow, 3); } }//GEN-LAST:event_menuItemRotLeftActionPerformed private void menuItemRotRightActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItemRotRightActionPerformed if(popupRow!=-1){ BufferedImage oldImg=fullImages.get(popupRow); BufferedImage newImg=new BufferedImage(oldImg.getHeight(),oldImg.getWidth(),BufferedImage.TYPE_INT_RGB); java.awt.Graphics2D g2=(java.awt.Graphics2D)newImg.getGraphics(); java.awt.geom.AffineTransform t=new java.awt.geom.AffineTransform(0,1,-1,0,oldImg.getHeight(),0); g2.drawImage(oldImg,t,null); fullImages.add(popupRow,newImg); int height=50; int width=(int)(newImg.getWidth()*(double)height/(double)newImg.getHeight()); BufferedImage thumb=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); thumb.getGraphics().drawImage(newImg,0,0,width,height,null); table.getModel().setValueAt(new ImageIcon(thumb), popupRow, 3); } }//GEN-LAST:event_menuItemRotRightActionPerformed private void cancelButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButton2ActionPerformed cancelHandler.invoke(this); }//GEN-LAST:event_cancelButton2ActionPerformed private void getMessagesButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_getMessagesButtonActionPerformed getMessagesButton.setEnabled(false); Thread t=new Thread(){ public void run(){ try{ getMessages(); java.awt.EventQueue.invokeLater(new Runnable(){ public void run(){ if(fullImages.size()==0) messageLabel.setText("No messages"); else{ toolPanel.removeAll(); toolPanel.add(messageToolPanel); toolPanel.revalidate(); } } }); }catch(Exception e){ e.printStackTrace(); messageLabel.setText("Error: "+e.getMessage()); } } }; t.start(); }//GEN-LAST:event_getMessagesButtonActionPerformed private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed okHandler.invoke(this); /* try{ deleteSelected(); }catch(Exception e){ e.printStackTrace(); }*/ }//GEN-LAST:event_okButtonActionPerformed private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed cancelHandler.invoke(this); // this.setVisible(false); }//GEN-LAST:event_cancelButtonActionPerformed private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed int[] rs=table.getSelectedRows(); if(rs.length!=1) return; BufferedImage img=fullImages.get(rs[0]); SimpleFileChooser fc=UIConstants.getFileChooser(); fc.setMultiSelectionEnabled(false); int s=fc.open(this, SimpleFileChooser.SAVE_DIALOG); if(s==SimpleFileChooser.APPROVE_OPTION){ try{ String file=fc.getSelectedFile().getName(); int ind=file.lastIndexOf("."); if(ind==-1){ WandoraOptionPane.showMessageDialog(this,"File name must end in a valid image suffix (e.g jpg,png)"); return; } String suffix=file.substring(ind+1).toLowerCase(); boolean success=ImageIO.write(img,suffix,fc.getSelectedFile()); if(!success){ WandoraOptionPane.showMessageDialog(this,"File format "+suffix+" not supported.", WandoraOptionPane.ERROR_MESSAGE); return; } }catch(IOException ioe){ ioe.printStackTrace(); WandoraOptionPane.showMessageDialog(this,"Error saving image: "+ioe.getMessage(), WandoraOptionPane.ERROR_MESSAGE); } } }//GEN-LAST:event_saveButtonActionPerformed private void deleteNoneButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteNoneButtonActionPerformed for(int i=0;i<tableModel.getRowCount();i++){ tableModel.setValueAt(Boolean.valueOf(false), i, 1); } }//GEN-LAST:event_deleteNoneButtonActionPerformed private void deleteAllButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteAllButtonActionPerformed for(int i=0;i<tableModel.getRowCount();i++){ tableModel.setValueAt(Boolean.valueOf(true), i, 1); } }//GEN-LAST:event_deleteAllButtonActionPerformed private void importNoneButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_importNoneButtonActionPerformed for(int i=0;i<tableModel.getRowCount();i++){ tableModel.setValueAt(Boolean.valueOf(false), i, 0); } }//GEN-LAST:event_importNoneButtonActionPerformed private void importAllButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_importAllButtonActionPerformed for(int i=0;i<tableModel.getRowCount();i++){ tableModel.setValueAt(Boolean.valueOf(true), i, 0); } }//GEN-LAST:event_importAllButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton cancelButton; private javax.swing.JButton cancelButton2; private javax.swing.JButton deleteAllButton; private javax.swing.JButton deleteNoneButton; private javax.swing.JButton getMessagesButton; private javax.swing.JButton importAllButton; private javax.swing.JButton importNoneButton; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JMenuItem menuItemRotLeft; private javax.swing.JMenuItem menuItemRotRight; private javax.swing.JLabel messageLabel; private javax.swing.JPanel messageToolPanel; private javax.swing.JButton okButton; private javax.swing.JPopupMenu popupMenu; private javax.swing.JProgressBar progressBar; private javax.swing.JButton saveButton; private javax.swing.JTable table; private javax.swing.JPanel toolPanel; // End of variables declaration//GEN-END:variables }
35,228
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
EmailExtractorDialog.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/email/EmailExtractorDialog.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * EmailExtractorDialog.java * * Created on 5.7.2005, 14:43 */ package org.wandora.application.tools.extractors.email; /** * * @author olli */ public class EmailExtractorDialog extends javax.swing.JDialog { private static final long serialVersionUID = 1L; /** Creates new form EmailExtractorDialog */ public EmailExtractorDialog(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); /* try{ ((EmailExtractorPanel)jPanel1).getMessages(); }catch(Exception e){ e.printStackTrace(); }*/ } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ private void initComponents() {//GEN-BEGIN:initComponents jPanel1 = new javax.swing.JPanel();/*new EmailExtractorPanel(this);*/ setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { formWindowClosing(evt); } }); getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER); pack(); }//GEN-END:initComponents private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing System.exit(0); }//GEN-LAST:event_formWindowClosing /** * @param args the command line arguments */ public static void main(String args[]) { /* java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new EmailExtractorDialog(new javax.swing.JFrame(), true).setVisible(true); } });*/ } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel jPanel1; // End of variables declaration//GEN-END:variables }
2,826
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimpleEmailExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/email/SimpleEmailExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * SimpleEmailExtractor.java * * Created on 20.6.2006, 20:00 * */ package org.wandora.application.tools.extractors.email; 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.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Enumeration; import java.util.List; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.mail.Address; import javax.mail.BodyPart; import javax.mail.Flags; import javax.mail.Folder; import javax.mail.Header; import javax.mail.Message; import javax.mail.Multipart; import javax.mail.Part; import javax.mail.Session; import javax.mail.Store; import javax.mail.internet.MimeMessage; //import jmbox.oe5dbx.*; import javax.swing.Icon; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.text.PDFTextStripper; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; 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.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.utils.MSOfficeBox; import org.wandora.utils.Textbox; import net.fortuna.mstor.model.MStorStore; /** * * @author akivela */ public class SimpleEmailExtractor extends AbstractExtractor implements BrowserPluginExtractor { private static final long serialVersionUID = 1L; private List<String> visitedEmailFolders = null; private List<String> visitedDirectories = null; private String defaultLang = "en"; private boolean shouldExtractHeaders = false; private boolean shouldExtractUnknownContentTypeAttachments = false; private SimpleEmailExtractorPanel gui = null; /** Creates a new instance of SimpleEmailExtractor */ public SimpleEmailExtractor() { } // ---------------------------------------------------- PLUGIN EXTRACTOR --- @Override public String doBrowserExtract(BrowserExtractRequest request, Wandora wandora) throws TopicMapException { String url=request.getSource(); try { ByteArrayInputStream in=new ByteArrayInputStream(request.getContent().getBytes("ISO-8859-1")); TopicMap tm=wandora.getTopicMap(); _extractTopicsFromStream(request.getSource(), in, tm); } catch(Exception e){ e.printStackTrace(); return BrowserPluginExtractor.RETURN_ERROR+e.getMessage(); } wandora.doRefresh(); return null; } @Override public boolean acceptBrowserExtractRequest(BrowserExtractRequest request, Wandora wandora) throws TopicMapException { if(request.getContent()!=null && request.isApplication(BrowserExtractRequest.APP_THUNDERBIRD)) return true; else return false; } // ------------------------------------------------------------------------- @Override public String getName() { return "Simple Email extractor..."; } @Override public String getDescription(){ return "Extracts text and metadata from email files."; } @Override public Icon getIcon() { return UIBox.getIcon(0xf003); } @Override public void execute(Wandora wandora, Context context) { TopicMap tm = wandora.getTopicMap(); visitedDirectories = new ArrayList<>(); visitedEmailFolders = new ArrayList<>(); setTopicMap(tm); boolean handledForcedContent = handleForcedContent(); if(!handledForcedContent) { if(gui == null) { gui = new SimpleEmailExtractorPanel(wandora); } gui.showDialog(); // WAIT TILL CLOSED if(gui.wasAccepted()) { int resourceType = gui.getEmailResourceType(); String resourceAddress = gui.getResourceAddress(); if(resourceAddress != null && resourceAddress.length() > 0) { try { setDefaultLogger(); _extractTopicsFrom(new File(resourceAddress), tm, resourceType); setState(WAIT); } catch(Exception e) { log(e); setState(WAIT); } } else { log("No email resource given."); } } } } @Override public boolean _extractTopicsFrom(URL url, TopicMap topicMap) throws Exception { try { URLConnection uc = null; if(getWandora() != null) { uc = getWandora().wandoraHttpAuthorizer.getAuthorizedAccess(url); } else { uc = url.openConnection(); Wandora.initUrlConnection(uc); } _extractTopicsFromStream(url.toExternalForm(), uc.getInputStream(), topicMap); return true; } catch(Exception e) { log("Exception occurred while extracting from url " + url.toExternalForm(), e); takeNap(1000); } return false; } @Override public boolean _extractTopicsFrom(String str, TopicMap topicMap) throws Exception { _extractTopicsFromStream("http://wandora.org/si/simple-email-extractor/"+System.currentTimeMillis(), new ByteArrayInputStream(str.getBytes()), topicMap); return true; } @Override public boolean _extractTopicsFrom(File file, TopicMap topicMap) throws Exception { System.out.println("@ _extractTopicsFrom: "+file.getAbsolutePath()); return _extractTopicsFrom(file, topicMap, SimpleEmailExtractorPanel.EMAIL_RESOURCE); } public boolean _extractTopicsFrom(File file, TopicMap topicMap, int type) throws Exception { if(file == null) return false; if(file.isDirectory()) { if(!visitedDirectories.contains(file.getAbsolutePath())) { visitedDirectories.add(file.getAbsolutePath()); log("Extracting from folder '"+file+"'."); File[] fs = file.listFiles(); for(int i=0; i<fs.length; i++) { _extractTopicsFrom(fs[i], topicMap, type); } } } else { try { if(SimpleEmailExtractorPanel.DBX_EMAIL_REPOSITORY == type) { log("Extracting DBX email repository '"+file+"'."); return extractTopicsFromDBX(file, topicMap); } else if(SimpleEmailExtractorPanel.MBOX_EMAIL_REPOSITORY == type) { log("Extracting MBOX email repository '"+file+"'."); return extractTopicsFromMBOX(file, topicMap); } else { FileInputStream fis = new FileInputStream(file); try { log("Extracting single email file '"+file+"'."); _extractTopicsFromStream(file.getPath(), fis, topicMap); } finally { if(fis != null) fis.close(); } return true; } } catch(Exception e) { log("Exception occurred while extracting from file " + file.getName(), e); takeNap(1000); } } return false; } // ------------------------------------------------------------------------- /* * #mstor.mbox.bufferStrategy={default|mapped|direct} mstor.mbox.bufferStrategy=default #mstor.mbox.cacheBuffers={true|false} #mstor.mbox.metadataStrategy={yaml|xml|none} mstor.mbox.metadataStrategy=none #mstor.mbox.mozillaCompatibility={true|false} #mstor.mbox.parsing.relaxed={true|false} #mstor.mbox.encoding=UTF-8 */ private int extractedEmails = 0; public boolean extractTopicsFromMBOX(File file, TopicMap topicMap) throws Exception { extractedEmails = 0; try { visitedEmailFolders = new ArrayList<>(); Properties properties = new Properties(); properties.setProperty("mstor.mbox.metadataStrategy", "none"); log("Initializing MBOX store '"+file.getName()+"'."); javax.mail.Session session = javax.mail.Session.getDefaultInstance(properties); //Provider mstorProvider = new Provider(Provider.Type.STORE, "mstor", "net.fortuna.mstor.MStorStore", null, null); //session.setProvider(mstorProvider); MStorStore store = new MStorStore(session, new javax.mail.URLName("mstor:"+file.getAbsolutePath())); store.connect(); javax.mail.Folder folder = store.getDefaultFolder(); extractTopicsFromFolder(topicMap, folder); } catch(javax.mail.NoSuchProviderException nspe) { log("Unable to read MBOX mail store! No suitable library available!"); log("In order to read the MBOX store please download mstor's jars (http://mstor.sourceforge.net/)\ninto Wandora's lib directory and add jars to bin/Wandora.bat!"); log(nspe); return false; } catch(Exception e) { log(e); } catch(NoClassDefFoundError er) { log(er); log("Unable to read MBOX mail store! No suitable library available!"); log("In order to read the MBOX store please download mstor's jars (http://mstor.sourceforge.net/)\ninto Wandora's lib directory and add jars to bin/Wandora.bat!"); return false; } log("Total "+extractedEmails+" emails extracted."); return true; } public boolean extractTopicsFromDBX(File file, TopicMap topicMap) throws Exception { extractedEmails = 0; try { visitedEmailFolders = new ArrayList<>(); Properties properties = new Properties(); log("Initializing DBX store '"+file.getName()+"'."); properties.put("mail.store.protocol", "oe5dbx"); String path = file.getPath(); properties.put("mail.oe5dbx.path", path); Session session = Session.getInstance(properties); Store store = session.getStore(); store.connect(); Folder folder = store.getDefaultFolder(); extractTopicsFromFolder(topicMap, folder); } catch(NoClassDefFoundError er) { log("Unable to read DBX mail storage! No suitable library available!"); log("In order to read the DBX store please download jmbox's jars (https://jmbox.dev.java.net/)\ninto Wandora's lib directory and add jars to bin/Wandora.bat!"); return false; } catch(javax.mail.NoSuchProviderException nspe) { log("Unable to read DBX mail store! No suitable library available!"); log("In order to read the DBX store please download jmbox's jars (https://jmbox.dev.java.net/)\ninto Wandora's lib directory and add jars to bin/Wandora.bat!"); return false; } catch(Exception e) { log(e); } log("Total "+extractedEmails+" emails extracted."); return true; } // ------------------------------------------------------------------------- public void _extractTopicsFromStream(String locator, InputStream inputStream, TopicMap map) { try { Session session = null; Message message = new MimeMessage(session, inputStream); extractTopicsFromMessage(map, message); } catch(Exception e) { log(e); } } public void extractTopicsFromFolder(TopicMap map, Folder folder) { try { visitedEmailFolders.add(folder.getFullName()); Topic folderType = createFolderTypeTopic(map); Topic folderTopic = createTopic(map, folder.getName() + " (email folder)"); folderTopic.addType(folderType); if(!folder.isOpen()) { folder.open(Folder.READ_ONLY); } if((folder.getType() & Folder.HOLDS_MESSAGES) > 0) { int c = folder.getMessageCount(); Message message = null; Topic emailType = createEmailTypeTopic(map); Topic emailTopic = null; log("Found " + c + " messages in folder '"+ folder.getName() + "'."); setProgressMax(c); setProgress(0); for(int i=1; i<=c && !forceStop(); i++) { try { setProgress(i); message = folder.getMessage(i); if(message != null) { emailTopic = extractTopicsFromMessage(map, message); if(emailTopic != null) { createAssociation(map, folderType, new Topic[] { emailTopic, folderTopic }, new Topic[] { emailType, folderType }); } } } catch(Exception e) { log(e.toString()); } } } if((folder.getType() & Folder.HOLDS_FOLDERS) > 0) { Folder[] allFolders = folder.list("*"); Folder anotherFolder = null; for(int i=0; i<allFolders.length && !forceStop(); i++) { anotherFolder = allFolders[i]; if(!visitedEmailFolders.contains(anotherFolder.getFullName())) { extractTopicsFromFolder(map, anotherFolder); } } } } catch(Exception e) { log(e); } catch(Error e) { log(e); } try { if(folder.isOpen()) { folder.close(false); } } catch(Exception e) {} } public Topic extractTopicsFromMessage(TopicMap map, Message message) { Topic emailType = null; Topic emailTopic = null; try { if(message != null) { String subject = message.getSubject(); if(subject == null) { subject = "No subject"; } extractedEmails++; String bnsuffix = null; if(message.getSentDate() != null) { bnsuffix = DateFormat.getInstance().format(message.getSentDate()); } else { bnsuffix = System.currentTimeMillis() + "-" + Math.random()*99999; } String basename = subject + " (" + bnsuffix + ")"; emailType = createEmailTypeTopic(map); emailTopic = createTopic(map, basename, " (email)", basename, emailType); emailTopic.setBaseName(basename); emailTopic.setDisplayName(defaultLang, subject); extractRecipients(map, emailTopic, message); extractSender(map, emailTopic, message); //extractReplyTo(map, emailTopic, message); extractMessageFlags(map, emailTopic, message); extractDates(map, emailTopic, message); extractContent(map, emailTopic, message); if(shouldExtractHeaders) extractHeaders(map, emailTopic, message); } else { log("Rejecting illegal (null) message."); } } catch(Exception e) { log(e); } catch(Error e) { log(e); } return emailTopic; } public void extractRecipients(TopicMap map, Topic emailTopic, Message message) { try { Address[] recipients = message.getAllRecipients(); if(recipients != null) { Address recipient = null; Topic emailType = createEmailTypeTopic(map); for(int i=0; i<recipients.length && !forceStop(); i++) { recipient = recipients[i]; if(recipient != null) { Topic addressType = createAddressTypeTopic(map); Topic recipientType = createTopic(map, "email-recipient"); Topic recipientTopic = createEmailAddressTopic(recipient, map); createAssociation(map, recipientType, new Topic[] { emailTopic, recipientTopic }, new Topic[] { emailType, addressType } ); } } } } catch(Exception e) { log(e); } } public void extractSender(TopicMap map, Topic emailTopic, Message message) { try { Address[] senders = message.getFrom(); if(senders != null) { Topic emailType = createEmailTypeTopic(map); Address sender = null; for(int i=0; i<senders.length && !forceStop(); i++) { sender = senders[i]; if(sender != null) { Topic addressType = createAddressTypeTopic(map); Topic senderType = createTopic(map, "email-sender"); Topic senderTopic = createEmailAddressTopic(sender, map); createAssociation(map, senderType, new Topic[] { emailTopic, senderTopic }, new Topic[] { emailType, addressType } ); } } } } catch(Exception e) { log(e); } } public void extractReplyTo(TopicMap map, Topic emailTopic, Message message) { try { Address[] replyTo = message.getFrom(); if(replyTo != null) { Topic emailType = createEmailTypeTopic(map); Address address = null; for(int i=0; i<replyTo.length && !forceStop(); i++) { address = replyTo[i]; if(address != null) { Topic addressType = createAddressTypeTopic(map); Topic replyToType = createTopic(map, "email-reply-to"); Topic replyToTopic = createEmailAddressTopic(address, map); createAssociation(map, replyToType, new Topic[] { emailTopic, replyToTopic }, new Topic[] { emailType, addressType } ); } } } } catch(Exception e) { log(e); } } public void extractMessageFlags(TopicMap map, Topic emailTopic, Message message) { try { Flags flags = message.getFlags(); if(flags != null) { if(flags.contains(Flags.Flag.ANSWERED)) { Topic answeredType = createTopic(map, "answered-email"); emailTopic.addType(answeredType); } if(flags.contains(Flags.Flag.DRAFT)) { Topic draftType = createTopic(map, "draft-email"); emailTopic.addType(draftType); } if(flags.contains(Flags.Flag.FLAGGED)) { Topic flaggedType = createTopic(map, "flagged-email"); emailTopic.addType(flaggedType); } if(flags.contains(Flags.Flag.RECENT)) { Topic recentType = createTopic(map, "recent-email"); emailTopic.addType(recentType); } if(flags.contains(Flags.Flag.SEEN)) { Topic seenType = createTopic(map, "seen-email"); emailTopic.addType(seenType); } if(flags.contains(Flags.Flag.USER)) { Topic userType = createTopic(map, "user-email"); emailTopic.addType(userType); } } } catch(Exception e) { log(e); } } public void extractDates(TopicMap map, Topic emailTopic, Message message) { try { SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat timeFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Topic dateType = createTopic(map, "date"); Topic emailType = createEmailTypeTopic(map); try { Date rDate = message.getReceivedDate(); if(rDate != null) { Topic receivedDateType = createTopic(map, "received-date"); String rDateString = dateFormatter.format(rDate); Topic rDateTopic = createTopic(map, rDateString); rDateTopic.addType(dateType); createAssociation(map, receivedDateType, new Topic[] { emailTopic, rDateTopic } ); } } catch(Exception e) { log("Warning: Exception occurred while processing 'received-date' field of an email."); e.printStackTrace(); } try { Date sDate = message.getSentDate(); if(sDate != null) { Topic sendDateType = createTopic(map, "sent-date"); String sDateString = dateFormatter.format(sDate); Topic sDateTopic = createTopic(map, sDateString); sDateTopic.addType(dateType); setData(emailTopic, sendDateType, defaultLang, timeFormatter.format(sDate)); createAssociation(map, sendDateType, new Topic[] { emailTopic, sDateTopic }, new Topic[] { emailType, dateType } ); } } catch(Exception e) { log("Warning: Exception occurred while processing 'sent-date' field of an email."); e.printStackTrace(); } } catch(Exception e) { log(e); } } public void extractContent(TopicMap map, Topic emailTopic, Part part) { try { Object content = part.getContent(); String contentType = part.getContentType(); String lowerCaseType = contentType.toLowerCase(); if(lowerCaseType.startsWith("text/plain")) { Topic textContentType = createTopic(map, "text-content"); String stringContent = (content != null ? content.toString() : ""); setData(emailTopic, textContentType, defaultLang, Textbox.trimExtraSpaces(stringContent)); } else if(lowerCaseType.startsWith("text/html")) { Topic htmlTextContentType = createTopic(map, "html-text-content"); String stringContent = (content != null ? content.toString() : ""); setData(emailTopic, htmlTextContentType, defaultLang, Textbox.trimExtraSpaces(stringContent)); } else if(lowerCaseType.startsWith("text/xml") || lowerCaseType.startsWith("application/xml")) { Topic contentTypeTopic = createTopic(map, "xml-content"); String stringContent = (content != null ? content.toString() : ""); setData(emailTopic, contentTypeTopic, defaultLang, stringContent); } else if(lowerCaseType.startsWith("application/msword") || lowerCaseType.startsWith("application/x-msword") || lowerCaseType.startsWith("application/x-ms-word") || lowerCaseType.startsWith("application/x-word")) { Topic contentTypeTopic = createTopic(map, "ms-word-text-content"); String stringContent = MSOfficeBox.getText(part.getInputStream()); setData(emailTopic, contentTypeTopic, defaultLang, Textbox.trimExtraSpaces(stringContent)); } else if(lowerCaseType.startsWith("application/msexcel") || lowerCaseType.startsWith("application/x-msexcel") || lowerCaseType.startsWith("application/x-ms-excel") || lowerCaseType.startsWith("application/x-excel") || lowerCaseType.startsWith("application/vnd.ms-excel")) { Topic contentTypeTopic = createTopic(map, "ms-excel-text-content"); String stringContent = MSOfficeBox.getText(part.getInputStream()); setData(emailTopic, contentTypeTopic, defaultLang, Textbox.trimExtraSpaces(stringContent)); } else if(lowerCaseType.startsWith("application/powerpoint") || lowerCaseType.startsWith("application/x-mspowerpoint") || lowerCaseType.startsWith("application/x-ms-powerpoint") || lowerCaseType.startsWith("application/x-powerpoint") || lowerCaseType.startsWith("application/vnd.ms-powerpoint")) { Topic contentTypeTopic = createTopic(map, "ms-powerpoint-text-content"); String stringContent = MSOfficeBox.getText(part.getInputStream()); setData(emailTopic, contentTypeTopic, defaultLang, Textbox.trimExtraSpaces(stringContent)); } else if(lowerCaseType.startsWith("application/pdf")) { Topic contentTypeTopic = createTopic(map, "pdf-text-content"); String stringContent = ""; try { PDDocument doc = PDDocument.load(part.getInputStream()); PDFTextStripper stripper = new PDFTextStripper(); stringContent = stripper.getText(doc); doc.close(); } catch(Exception e) { System.out.println("No PDF support!"); } setData(emailTopic, contentTypeTopic, defaultLang, stringContent.trim()); } else if(lowerCaseType.startsWith("multipart")) { Multipart multipart = (Multipart) content; BodyPart bodypart = null; int c = multipart.getCount(); for(int i=0; i<c; i++) { bodypart = multipart.getBodyPart(i); extractContent(map, emailTopic, bodypart); } } else { if(contentType.indexOf(";") > -1) { contentType = contentType.substring(0, contentType.indexOf(";")); } log("Unsupported attachment type '" + contentType + "' found."); if(shouldExtractUnknownContentTypeAttachments) { log("Processing anyway..."); Topic contentTypeTopic = createTopic(map, "unknown-content"); String unknownContent = (String) content; setData(emailTopic, contentTypeTopic, defaultLang, unknownContent); } } } catch(Exception e) { log(e); } catch(Error e) { log(e); } } public void extractHeaders(TopicMap map, Topic emailTopic, Part part) { try { Enumeration e = part.getAllHeaders(); Header header = null; String name = null; String value = null; Topic emailTopicType = createEmailTypeTopic(map); Topic headerType = createTopic(map, "header"); Topic headerNameType = createTopic(map, "header-name"); Topic headerValueType = createTopic(map, "header-value"); Topic headerName = null; Topic headerValue = null; while(e.hasMoreElements()) { header = (Header) e.nextElement(); if(header != null) { name = header.getName(); value = header.getValue(); if(name != null && value != null && name.length() > 0 && value.length() > 0) { headerName = createTopic(map, name); headerName.addType(headerNameType); headerValue = createTopic(map, value); headerValue.addType(headerValueType); createAssociation(map, headerType, new Topic[] { emailTopic, headerName, headerValue }, new Topic[] { emailTopicType, headerNameType, headerValueType }); } } } } catch(Exception e) { log(e); } } // ------------------------------------------------------------------------- public Topic createAddressTypeTopic(TopicMap map) throws TopicMapException { Topic e = createEmailsTypeTopic(map); Topic t = createTopic(map, "email-address"); t.addType(e); return t; } public Topic createEmailsTypeTopic(TopicMap map) throws TopicMapException { Topic t = createTopic(map, "Emails"); Topic w = createWandoraTypeTopic(map); t.addType(w); return t; } public Topic createFolderTypeTopic(TopicMap map) throws TopicMapException { Topic t = createTopic(map, "email folder"); Topic w = createEmailsTypeTopic(map); t.addType(w); return t; } public Topic createEmailTypeTopic(TopicMap map) throws TopicMapException { Topic t = createTopic(map, "email"); Topic e = createEmailsTypeTopic(map); t.addType(e); return t; } public Topic createWandoraTypeTopic(TopicMap map) throws TopicMapException { return createTopic(map, TMBox.WANDORACLASS_SI, "Wandora class"); } // ------------------------------------------------------------------------- private String emailPatternString = "([\\w\\.=-]+@[\\w\\.-]+\\.[\\w]{2,3})"; private Pattern emailPattern = Pattern.compile(emailPatternString); private String namePatternString = "(\\w+.+) \\<(.+)\\>"; private Pattern namePattern = Pattern.compile(namePatternString); public Topic createEmailAddressTopic(Address emailAddress, TopicMap map) throws Exception { return createEmailAddressTopic(emailAddress.toString(), null, map); } public Topic createEmailAddressTopic(String emailAddress, TopicMap map) throws Exception { return createEmailAddressTopic(emailAddress, null, map); } public Topic createEmailAddressTopic(Address emailAddress, Topic additionalType, TopicMap map) throws Exception { return createEmailAddressTopic(emailAddress.toString(), additionalType, map); } public Topic createEmailAddressTopic(String emailAddress, Topic additionalType, TopicMap map) throws Exception { //String originalAddress = emailAddress; String emailName = null; Matcher nameMatcher = namePattern.matcher(emailAddress); if(nameMatcher.matches()) { emailName = nameMatcher.group(1); emailAddress = nameMatcher.group(2); //System.out.println("found name '"+emailName+"' and address '"+emailAddress+"' in '"+originalAddress+"'"); } Matcher addressMatcher = emailPattern.matcher(emailAddress); if(addressMatcher.matches()) { //System.out.println("good! email address '"+emailAddress+"' matches the email pattern!"); } else { if(addressMatcher.find()) { emailAddress = addressMatcher.group(1); //System.out.println("found email address '"+emailAddress+"'!"); } } Topic addressType = createAddressTypeTopic(map); Topic emailAddressTopic = createTopic(map, emailAddress); emailAddressTopic.addType(addressType); if(additionalType != null) emailAddressTopic.addType(additionalType); if(emailName != null && emailName.length() > 0) { Topic nameType = createTopic(map, "name"); setData(emailAddressTopic, nameType, defaultLang, emailName.trim()); } return emailAddressTopic; } // ------------------------------------------------------------------------- @Override public Locator buildSI(String siend) { try { return new Locator("http://wandora.org/si/email/" + URLEncoder.encode(siend, "utf-8")); } catch(Exception e) { return new Locator("http://wandora.org/si/email/" + siend); } } }
34,338
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimpleEmailExtractorPanel.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/email/SimpleEmailExtractorPanel.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * SimpleEmailExtractorPanel.java * * Created on 9.12.2010, 12:42:50 */ package org.wandora.application.tools.extractors.email; import java.io.File; 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.SimpleComboBox; import org.wandora.application.gui.simple.SimpleField; import org.wandora.application.gui.simple.SimpleFileChooser; import org.wandora.application.gui.simple.SimpleLabel; /** * * @author akivela */ public class SimpleEmailExtractorPanel extends javax.swing.JPanel { private static final long serialVersionUID = 1L; public static int EMAIL_RESOURCE = 1; public static int MBOX_EMAIL_REPOSITORY = 2; public static int DBX_EMAIL_REPOSITORY = 3; private int emailResourceType = EMAIL_RESOURCE; private Wandora wandora = null; private JDialog dialog = null; private boolean isAccepted = false; private static String currentFile = null; /** Creates new form SimpleEmailExtractorPanel */ public SimpleEmailExtractorPanel(Wandora wandora) { this.wandora = wandora; initComponents(); typeComboBox.setEditable(false); } public void showDialog() { if(dialog == null) { dialog = new JDialog(wandora, true); dialog.setTitle("Simple email extractor"); dialog.add(this); dialog.setSize(650,200); UIBox.centerWindow(dialog, wandora); } isAccepted = false; dialog.setVisible(true); } public int getEmailResourceType() { Object ro = typeComboBox.getSelectedItem(); if(ro != null) { String rs = ro.toString(); if("Single email file".equals(rs)) { return EMAIL_RESOURCE; } else if("MBOX email repository".equals(rs)) { return MBOX_EMAIL_REPOSITORY; } else if("DBX email repository".equals(rs)) { return DBX_EMAIL_REPOSITORY; } } return emailResourceType; } public String getResourceAddress() { return resourceTextField.getText(); } public boolean wasAccepted() { return isAccepted; } /** 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; emailPanelInner = new javax.swing.JPanel(); descriptionLabel = new SimpleLabel(); optionsPanel = new javax.swing.JPanel(); typeLabel = new SimpleLabel(); typeComboBox = new SimpleComboBox(); resourceLabel = new SimpleLabel(); resourceTextField = new SimpleField(); fileButton = new SimpleButton(); buttonPanel = new javax.swing.JPanel(); buttonFillerPanel = new javax.swing.JPanel(); extractButton = new SimpleButton(); cancelButton2 = new SimpleButton(); setLayout(new java.awt.GridBagLayout()); emailPanelInner.setLayout(new java.awt.GridBagLayout()); descriptionLabel.setText("<html>Simple email extractor can extract single email files and MBOX email repositories. First select resource type. Then locate the email resource file and press Extract button.</html>"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 12, 0); emailPanelInner.add(descriptionLabel, gridBagConstraints); optionsPanel.setLayout(new java.awt.GridBagLayout()); typeLabel.setText("Resource type"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 4, 5); optionsPanel.add(typeLabel, gridBagConstraints); typeComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Single email file", "MBOX email repository" })); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 4, 0); optionsPanel.add(typeComboBox, gridBagConstraints); resourceLabel.setText("Email resource"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); optionsPanel.add(resourceLabel, 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, 0, 2); optionsPanel.add(resourceTextField, gridBagConstraints); fileButton.setText("Browse"); fileButton.setMargin(new java.awt.Insets(0, 2, 0, 2)); fileButton.setMaximumSize(new java.awt.Dimension(70, 23)); fileButton.setMinimumSize(new java.awt.Dimension(70, 23)); fileButton.setPreferredSize(new java.awt.Dimension(70, 23)); fileButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { fileButtonMouseReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; optionsPanel.add(fileButton, 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, 20, 12, 0); emailPanelInner.add(optionsPanel, 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); extractButton.setText("Extract"); extractButton.setMaximumSize(new java.awt.Dimension(70, 23)); extractButton.setMinimumSize(new java.awt.Dimension(70, 23)); extractButton.setPreferredSize(new java.awt.Dimension(70, 23)); extractButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { extractButtonMouseReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4); buttonPanel.add(extractButton, gridBagConstraints); cancelButton2.setText("Cancel"); cancelButton2.setMaximumSize(new java.awt.Dimension(70, 23)); cancelButton2.setMinimumSize(new java.awt.Dimension(70, 23)); cancelButton2.setPreferredSize(new java.awt.Dimension(70, 23)); cancelButton2.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { cancelButton2MouseReleased(evt); } }); buttonPanel.add(cancelButton2, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; emailPanelInner.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(10, 10, 10, 10); add(emailPanelInner, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents private void extractButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_extractButtonMouseReleased isAccepted = true; if(dialog != null) dialog.setVisible(false); }//GEN-LAST:event_extractButtonMouseReleased private void cancelButton2MouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cancelButton2MouseReleased isAccepted = false; if(dialog != null) dialog.setVisible(false); }//GEN-LAST:event_cancelButton2MouseReleased private void fileButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_fileButtonMouseReleased SimpleFileChooser fc = UIConstants.getFileChooser(); fc.setDialogTitle("Select email resource"); if(currentFile != null) { fc.setSelectedFile(new File(currentFile)); } int answer = fc.open(dialog, SimpleFileChooser.OPEN_DIALOG, "Select"); if(answer == SimpleFileChooser.APPROVE_OPTION) { File f = fc.getSelectedFile(); if(f != null) { resourceTextField.setText(f.getAbsolutePath()); currentFile = f.getAbsolutePath(); } } }//GEN-LAST:event_fileButtonMouseReleased // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel buttonFillerPanel; private javax.swing.JPanel buttonPanel; private javax.swing.JButton cancelButton2; private javax.swing.JLabel descriptionLabel; private javax.swing.JPanel emailPanelInner; private javax.swing.JButton extractButton; private javax.swing.JButton fileButton; private javax.swing.JPanel optionsPanel; private javax.swing.JLabel resourceLabel; private javax.swing.JTextField resourceTextField; private javax.swing.JComboBox typeComboBox; private javax.swing.JLabel typeLabel; // End of variables declaration//GEN-END:variables }
12,252
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SQLExtractorUI.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/sql/SQLExtractorUI.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * SQLExtractorUI.java * */ package org.wandora.application.tools.extractors.sql; import java.awt.Component; import javax.swing.JDialog; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; 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.gui.simple.SimpleScrollPane; import org.wandora.application.gui.simple.SimpleTabbedPane; import org.wandora.application.gui.simple.SimpleTextPane; /** * * @author akivela */ public class SQLExtractorUI extends javax.swing.JPanel { private static final long serialVersionUID = 1L; private boolean accepted = false; private JDialog dialog = null; private Wandora wandora = null; /** Creates new form SQLExtractorUI */ public SQLExtractorUI(Wandora w) { wandora = w; initComponents(); } 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(750,400); dialog.add(this); dialog.setTitle("SQL Extractor"); UIBox.centerWindow(dialog, w); dialog.setVisible(true); } public String getQuery(WandoraTool parentTool) { Component component = tabbedPane.getSelectedComponent(); // ***** GENERIC ***** if(genericPanel.equals(component)) { return genericQueryTextPane.getText(); } return null; } public String getURL() { Component component = tabbedPane.getSelectedComponent(); // ***** GENERIC ***** if(genericPanel.equals(component)) { String queryURL = genericURLTextField.getText(); return queryURL; } return null; } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; 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(); buttonPanel = new javax.swing.JPanel(); buttonFillerPanel = new javax.swing.JPanel(); okButton = new SimpleButton(); cancelButton = new SimpleButton(); setLayout(new java.awt.GridBagLayout()); genericPanel.setLayout(new java.awt.GridBagLayout()); genericPanelInner.setLayout(new java.awt.GridBagLayout()); genericTitle.setText("<html>This extractor sends SQL queries to a given end point and transform the result set to a topic map. Fill in the end point URL and the query.</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("Connection URL"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHEAST; gridBagConstraints.insets = new java.awt.Insets(2, 8, 2, 0); genericPanelInner.add(genericURLLabel, gridBagConstraints); urlPanel.setLayout(new java.awt.BorderLayout(4, 0)); genericURLTextField.setText("jdbc:mysql://localhost:3306/database;user=user;password=pass"); 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("SQL query"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHEAST; gridBagConstraints.insets = new java.awt.Insets(2, 8, 2, 0); genericPanelInner.add(genericQueryLabel, gridBagConstraints); genericQueryTextPane.setText("select * from ..."); 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()); 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); 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, 594, 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.setMaximumSize(new java.awt.Dimension(70, 23)); okButton.setMinimumSize(new java.awt.Dimension(70, 23)); okButton.setPreferredSize(new java.awt.Dimension(70, 23)); okButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { okButtonMouseReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3); buttonPanel.add(okButton, gridBagConstraints); cancelButton.setText("Close"); cancelButton.setMaximumSize(new java.awt.Dimension(70, 23)); cancelButton.setMinimumSize(new java.awt.Dimension(70, 23)); cancelButton.setPreferredSize(new java.awt.Dimension(70, 23)); cancelButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { cancelButtonMouseReleased(evt); } }); buttonPanel.add(cancelButton, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); add(buttonPanel, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents private void cancelButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cancelButtonMouseReleased accepted = false; if(dialog != null) dialog.setVisible(false); }//GEN-LAST:event_cancelButtonMouseReleased private void okButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_okButtonMouseReleased accepted = true; if(dialog != null) dialog.setVisible(false); }//GEN-LAST:event_okButtonMouseReleased // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel buttonFillerPanel; private javax.swing.JPanel buttonPanel; private javax.swing.JButton cancelButton; private javax.swing.JPanel genericButtonPanel; 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.JButton okButton; private javax.swing.JTabbedPane tabbedPane; private javax.swing.JPanel urlPanel; // End of variables declaration//GEN-END:variables }
11,592
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SQLExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/sql/SQLExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * SQLExtractor.java * */ package org.wandora.application.tools.extractors.sql; import java.io.File; import java.net.URL; import java.net.URLEncoder; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.Statement; import java.util.ArrayList; import java.util.LinkedHashMap; 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.extractors.AbstractExtractor; import org.wandora.topicmap.Association; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; /** * * @author akivela */ public class SQLExtractor extends AbstractExtractor { private static final long serialVersionUID = 1L; public static String DEFAULT_SI_ENCODING = "UTF-8"; public static String DEFAULT_LANG = "en"; public static String RESULTSET_SI = "http://wandora.org/si/sql/resultset"; public static String COLUMN_SI = "http://wandora.org/si/sql/resultset/column"; public static String VALUE_SI = "http://wandora.org/si/sql/resultset/value"; private SQLExtractorUI ui = null; public static final String defaultOccurrenceScopeSI = TMBox.LANGINDEPENDENT_SI; @Override public String getName() { return "SQL extractor"; } @Override public String getDescription(){ return "Transforms SQL result set to a topic map. Extractor requires SQL database."; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_sql.png"); } @Override public void execute(Wandora wandora, Context context) { try { if(ui == null) { ui = new SQLExtractorUI(wandora); } ui.open(wandora); if(ui.wasAccepted()) { setDefaultLogger(); //log("Extracting SQL result set..."); TopicMap tm = wandora.getTopicMap(); String query = ui.getQuery(this); String url = ui.getURL(); int c = 0; if(query != null && query.length() > 0) { Connection connection = null; try { //log("Opening SQL connection..."); connection = DriverManager.getConnection(url); Statement stmt = connection.createStatement(); log("Executing SQL query..."); ResultSet rs = stmt.executeQuery(query); //connection.commit(); log("Transforming SQL result set to a topic map..."); handleResultSet(rs, tm); c++; } catch(java.sql.SQLException esql) { log(esql.getMessage()); } catch(Exception e) { log(e); } finally { if(connection != null) { //log("Closing SQL connection..."); connection.close(); } } if(c == 0) log("No valid query given. Aborting."); log("Ready."); } } else { // log("User cancelled the extraction!"); } } catch(Exception e) { singleLog(e); } if(ui != null && ui.wasAccepted()) setState(WAIT); else setState(CLOSE); } // ------------------------------------------------------------------------- public void handleResultSet(ResultSet rs, TopicMap tm) throws Exception { if(rs == null) { log("Warning: no result set available!"); return; } ResultSetMetaData rsmd = rs.getMetaData(); int numColumns = rs.getMetaData().getColumnCount(); List<String> columns = new ArrayList<String>(); List<String> tableColumns = new ArrayList<String>(); for(int i=1; i<numColumns+1; i++) { String columnName = rsmd.getColumnName(i); columns.add(columnName); String tableName = rsmd.getTableName(i); if(columnName != null && tableName != null) { tableColumns.add(columnName+"."+tableName); } else if(columnName != null) { tableColumns.add(columnName); } else { tableColumns.add("column-"+i); } } int counter = 0; while(rs.next() && !forceStop()) { Map<Topic,Topic> roledPlayers = new LinkedHashMap<>(); for(int i=1; i<numColumns+1; i++) { try { if(forceStop()) break; String x = rs.getString(i); if(x == null || x.length() == 0) continue; String col = columns.get(i-1); String colName = tableColumns.get(i-1); Topic role = getRoleTopic(colName, tm); Topic player = null; String sif = x; if(x.length() > 128) sif = sif.substring(0, 127)+"_"+sif.hashCode(); String uri = VALUE_SI + "/" + encode(sif); String name = x; String lang = DEFAULT_LANG; player = createTopic(tm, uri, name); //System.out.println("lang=="+lang+" name=="+name); player.setDisplayName(lang, name); if(role != null && player != null) { roledPlayers.put(role, player); } } catch(Exception e) { log(e); } } 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); } log("Total result set rows processed: " + counter); } public Topic getAssociationType(ResultSet rs, TopicMap tm) throws Exception { Topic atype = createTopic(tm, RESULTSET_SI+"/"+rs.hashCode(), "SQL Result Set "+rs.hashCode()); Topic settype = createTopic(tm, RESULTSET_SI, "SQL 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; } } // ------------------------------------------------------------------------- @Override public boolean _extractTopicsFrom(File f, TopicMap t) throws Exception { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean _extractTopicsFrom(URL u, TopicMap t) throws Exception { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean _extractTopicsFrom(String str, TopicMap t) throws Exception { throw new UnsupportedOperationException("Not supported yet."); } // ------------------------------------------------------------------------- }
8,992
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Gedcom.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/gedcom/Gedcom.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * Gedcom.java * * Created on 2009-10-1, 20:52 */ package org.wandora.application.tools.extractors.gedcom; import java.io.BufferedReader; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Stack; import org.wandora.application.WandoraTool; /** * Class is based on Mike Dean's work on GEDCOM to DAML converter. DAML * converter is described at http://www.daml.org/2001/01/gedcom/ * * @author akivela */ public class Gedcom { public static boolean DEBUG = false; // map from String key to Node. public Map<String,Node> keys = new LinkedHashMap<>(); // stack used while parsing. private Stack<Node> stack = new Stack<>(); public int numberOfTopLevelNodes = 0; /** * return the Node with the specified key (e.g. "@I1@"). */ private Node lookup(String key) { return (Node) keys.get(key); } private void parseLine(String line) { int space1 = line.indexOf(' '); int level = Integer.parseInt(line.substring(0, space1)); if (level == 0) { numberOfTopLevelNodes++; } String key = null; int tagStart = space1 + 1; if (line.charAt(tagStart) == '@') { int keyEnd = line.indexOf(' ', tagStart); key = line.substring(tagStart, keyEnd); tagStart = keyEnd + 1; } String tag = null; String value = null; int tagEnd = line.indexOf(' ', tagStart); if (tagEnd == (-1)) { tag = line.substring(tagStart); } else { tag = line.substring(tagStart, tagEnd); value = line.substring(tagEnd + 1); } if (DEBUG) { System.out.println("level = " + level); System.out.println("key = " + key); System.out.println("tag = " + tag); System.out.println("value = " + value); System.out.println(); } Node node = new Node(key, tag, value); while (level < stack.size()) { stack.pop(); } stack.push(node); if (level > 0) { Node parent = (Node) stack.elementAt(level - 1); parent.children.add(node); } } /** * parse the specified file and return a tree representation. */ public static Gedcom parse(BufferedReader breader, WandoraTool tool) throws Exception { Gedcom gedcom = new Gedcom(); String line; int i = 0; try { while ((line = breader.readLine()) != null && !tool.forceStop()) { gedcom.parseLine(line); i++; tool.setProgress(i / 1000); } } catch (Exception e) { tool.log("Aborting model parsing..."); tool.log("Exception occurred while reading GEDCOM stream at line " + (i)); tool.log(e); } tool.log("Total " + gedcom.numberOfTopLevelNodes + " top level nodes parsed..."); return gedcom; } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- public class Node { String key = null; String tag = null; String value = null; List<Node> children = new ArrayList<>(); Node(String key, String tag, String value) { this.key = key; this.tag = tag; this.value = value; if (key != null) { keys.put(key, this); } } } }
3,958
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
GedcomExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/gedcom/GedcomExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * GedcomExtractor.java * * Created on 2009-10-1, 20:52 */ package org.wandora.application.tools.extractors.gedcom; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.InputStreamReader; import java.io.StringReader; import java.net.URL; import java.util.Collection; import java.util.Iterator; import javax.swing.Icon; import org.wandora.application.WandoraTool; 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.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; /** * Converts GEDCOM (GEnealogical Data COMmunication) formatted files to topic * maps. * * Extractor is based on Mike Dean's work on GEDCOM to DAML converter. DAML * converter is described at http://www.daml.org/2001/01/gedcom/ * * @author akivela */ public class GedcomExtractor extends AbstractExtractor implements WandoraTool { private static final long serialVersionUID = 1L; public static final boolean DEBUG = true; public static boolean ADD_SPACE_BEFORE_CONCATENATION = false; public static final String DEFAULT_LANG = "en"; public String SI_PREFIX = "http://wandora.org/si/gedcom/"; public String SCHEMA_PREFIX = "schema/"; /** Creates a new instance of GedcomExtractor */ public GedcomExtractor() { } @Override public Icon getIcon() { return UIBox.getIcon(0xf1ae); } @Override public String getName() { return "GEDCOM extractor"; } @Override public String getDescription() { return "Convert GEDCOM (GEnealogical Data COMmunication) formatted files to topic maps."; } @Override public String getGUIText(int textType) { switch (textType) { case SELECT_DIALOG_TITLE: return "Select GEDCOM data file(s) or directories containing GEDCOM data files!"; case POINT_START_URL_TEXT: return "Where would you like to start the crawl?"; case INFO_WAIT_WHILE_WORKING: return "Wait while seeking GEDCOM data files!"; case FILE_PATTERN: return ".*\\.ged"; case DONE_FAILED: return "Ready. No extractions! %1 GEDCOM data file(s) crawled!"; case DONE_ONE: return "Ready. Successful extraction! %1 GEDCOM data file(s) crawled!"; case DONE_MANY: return "Ready. Total %0 successful extractions! %1 GEDCOM data file(s) crawled!"; case LOG_TITLE: return "GEDCOM extraction Log"; } return ""; } public boolean _extractTopicsFrom(String str, TopicMap topicMap) throws Exception { return _extractTopicsFrom(new BufferedReader(new StringReader(str)), topicMap); } public boolean _extractTopicsFrom(URL url, TopicMap topicMap) throws Exception { if (url == null) return false; BufferedReader urlReader = new BufferedReader(new InputStreamReader(url.openStream())); return _extractTopicsFrom(urlReader, topicMap); } public boolean _extractTopicsFrom(File GEDCOMFile, TopicMap topicMap) throws Exception { boolean result = false; BufferedReader breader = null; try { if (GEDCOMFile == null) { log("No GEDCOM data file addressed!"); } else { FileReader fr = new FileReader(GEDCOMFile); breader = new BufferedReader(fr); result = _extractTopicsFrom(breader, topicMap); } } finally { if (breader != null) breader.close(); } return result; } public boolean _extractTopicsFrom(BufferedReader breader, TopicMap topicMap) throws Exception { int nindividuals = 0; int nfamilies = 0; int nsources = 0; int nobje = 0; int nnote = 0; int nrepo = 0; int nsubm = 0; int nhead = 0; int progress = 0; try { log("Parsing GEDCOM file to a tree representation."); Gedcom gedcom = Gedcom.parse(breader, this); log("Converting parsed tree representation to a topic map."); setProgress(0); setProgressMax(gedcom.numberOfTopLevelNodes); Iterator<Gedcom.Node> iterator = gedcom.keys.values().iterator(); while (iterator.hasNext() && !forceStop()) { Gedcom.Node node = (Gedcom.Node) iterator.next(); // if(DEBUG) node.print(0); progress++; setProgress(progress); if ("INDI".equals(node.tag)) { nindividuals++; processIndividual(node, topicMap); } else if ("FAM".equals(node.tag)) { nfamilies++; processFamily(node, topicMap); } else if ("OBJE".equals(node.tag)) { nobje++; } else if ("NOTE".equals(node.tag)) { nnote++; } else if ("REPO".equals(node.tag)) { nrepo++; } else if ("SOUR".equals(node.tag)) { nsources++; processSource(node, topicMap); } else if ("SUBM".equals(node.tag)) { nsubm++; } else if ("HEAD".equals(node.tag)) { nhead++; } else { // DO NOTHING } } } catch (Exception e) { log(e); } if (forceStop()) { log("User has stopped extraction. Aborting..."); } log("Found " + nindividuals + " individuals"); log("Found " + nfamilies + " families"); log("Found " + nsources + " sources"); if (nobje > 0) log("Skipped " + nobje + " object records"); if (nnote > 0) log("Skipped " + nnote + " note records"); if (nrepo > 0) log("Skipped " + nrepo + " repository records"); if (nsubm > 0) log("Skipped " + nsubm + " submitter records"); return true; } private void processIndividual(Gedcom.Node node, TopicMap tm) throws TopicMapException { if (node.key == null) { log("Individual has no key. Skipping."); return; } boolean firstName = true; Topic individualTopic = getOrCreateTopic(tm, fixNodeKey(node.key)); Topic individualTypeTopic = getOrCreateIndividualType(tm); individualTopic.addType(individualTypeTopic); Iterator<Gedcom.Node> childIterator = node.children.iterator(); while (childIterator.hasNext()) { Gedcom.Node child = (Gedcom.Node) childIterator.next(); if ("SEX".equals(child.tag)) { addAssociation(tm, "sex", individualTopic, individualTypeTopic, child.value, "sex"); } else if ("NAME".equals(child.tag)) { if (firstName) { if (child.value != null) { String name = child.value.trim(); individualTopic.setBaseName(name + " (" + fixNodeKey(node.key) + ")"); individualTopic.setDisplayName(DEFAULT_LANG, name); firstName = false; } } processName(child, tm, individualTopic, individualTypeTopic); } else if ("TITL".equals(child.tag)) { processEvent(child, tm, "title", individualTopic, individualTypeTopic); } else if ("ASSO".equals(child.tag)) { Topic assoTopic = getOrCreateTopic(tm, fixNodeKey(child.value)); Association assoAssociation = addAssociation(tm, "associated-individual", individualTopic, individualTypeTopic, assoTopic, "associated-individual"); Iterator<Gedcom.Node> childchildIterator = child.children.iterator(); while (childchildIterator.hasNext()) { Gedcom.Node childchild = (Gedcom.Node) childchildIterator.next(); if ("RELA".equals(childchild.tag)) { Topic relationTopic = getOrCreateTopic(tm, node.value); fillAssociation(tm, assoAssociation, relationTopic, "relation"); } } } else if ("NOTE".equals(child.tag)) { String note = getText(child); addOccurrence(tm, individualTopic, "note", note); } // --- INDIVIDUAL EVENTS --- else if ("BIRT".equals(child.tag)) { Association eventAssociation = processEvent(child, tm, "birth", individualTopic, individualTypeTopic); Iterator<Gedcom.Node> childchildIterator = child.children.iterator(); while (childchildIterator.hasNext()) { Gedcom.Node childchild = (Gedcom.Node) childchildIterator.next(); if ("FAMC".equals(childchild.tag)) { Topic familyTopic = getOrCreateTopic(tm, fixNodeKey(node.key)); Topic familyTypeTopic = getOrCreateFamilyType(tm); familyTopic.addType(familyTypeTopic); fillAssociation(tm, eventAssociation, familyTopic, "birth-family"); } } } else if ("ADOP".equals(child.tag)) { Association eventAssociation = processEvent(child, tm, "adoptation", individualTopic, individualTypeTopic); Iterator<Gedcom.Node> childchildIterator = child.children.iterator(); while (childchildIterator.hasNext()) { Gedcom.Node childchild = (Gedcom.Node) childchildIterator.next(); if ("FAMC".equals(childchild.tag)) { Topic familyTopic = getOrCreateTopic(tm, fixNodeKey(node.key)); Topic familyTypeTopic = getOrCreateFamilyType(tm); familyTopic.addType(familyTypeTopic); fillAssociation(tm, eventAssociation, familyTopic, "adoptation-family"); } } } else if ("DEAT".equals(child.tag)) { processEvent(child, tm, "death", individualTopic, individualTypeTopic); } else if ("BURI".equals(child.tag)) { processEvent(child, tm, "burial", individualTopic, individualTypeTopic); } else if ("CREM".equals(child.tag)) { processEvent(child, tm, "crematorion", individualTopic, individualTypeTopic); } else if ("IMMI".equals(child.tag)) { processEvent(child, tm, "immigration", individualTopic, individualTypeTopic); } else if ("NATU".equals(child.tag)) { processEvent(child, tm, "naturalization", individualTopic, individualTypeTopic); } else if ("EMIG".equals(child.tag)) { processEvent(child, tm, "emigration", individualTopic, individualTypeTopic); } else if ("GRAD".equals(child.tag)) { processEvent(child, tm, "graduation", individualTopic, individualTypeTopic); } else if ("RETI".equals(child.tag)) { processEvent(child, tm, "retirement", individualTopic, individualTypeTopic); } else if ("CENS".equals(child.tag)) { processEvent(child, tm, "cencus", individualTopic, individualTypeTopic); } else if ("PROB".equals(child.tag)) { processEvent(child, tm, "probate", individualTopic, individualTypeTopic); } else if ("WILL".equals(child.tag)) { processEvent(child, tm, "will", individualTopic, individualTypeTopic); } else if ("CHR".equals(child.tag)) { processEvent(child, tm, "christening", individualTopic, individualTypeTopic); } else if ("CHRA".equals(child.tag)) { processEvent(child, tm, "adult-christening", individualTopic, individualTypeTopic); } else if ("CONF".equals(child.tag)) { processEvent(child, tm, "confirmation", individualTopic, individualTypeTopic); } else if ("FCOM".equals(child.tag)) { processEvent(child, tm, "first-communion", individualTopic, individualTypeTopic); } else if ("ORDN".equals(child.tag)) { processEvent(child, tm, "ordination", individualTopic, individualTypeTopic); } // ------ else if ("OCCU".equals(child.tag)) { processEvent(child, tm, "occupation", individualTopic, individualTypeTopic); } else if ("CAST".equals(child.tag)) { processEvent(child, tm, "caste", individualTopic, individualTypeTopic); } else if ("DSCR".equals(child.tag)) { processEvent(child, tm, "physical-description", individualTopic, individualTypeTopic); } else if ("EDUC".equals(child.tag)) { processEvent(child, tm, "education", individualTopic, individualTypeTopic); } else if ("IDNO".equals(child.tag)) { processEvent(child, tm, "national-id-number", individualTopic, individualTypeTopic); } else if ("NATI".equals(child.tag)) { processEvent(child, tm, "national-or_tribal-origin", individualTopic, individualTypeTopic); } else if ("NCHI".equals(child.tag)) { processEvent(child, tm, "count-of-children", individualTopic, individualTypeTopic); } else if ("NMR".equals(child.tag)) { processEvent(child, tm, "count-of-marriages", individualTopic, individualTypeTopic); } else if ("PROP".equals(child.tag)) { processEvent(child, tm, "possessions", individualTopic, individualTypeTopic); } else if ("RELI".equals(child.tag)) { processEvent(child, tm, "religious-affiliation", individualTopic, individualTypeTopic); } else if ("SSN".equals(child.tag)) { processEvent(child, tm, "social-security-number", individualTopic, individualTypeTopic); } else if ("RESI".equals(child.tag)) { processEvent(child, tm, "residence", individualTopic, individualTypeTopic); } else if ("EVEN".equals(child.tag)) { processEvent(child, tm, "event", individualTopic, individualTypeTopic); } else if ("FAMC".equals(child.tag)) { Topic familyTopic = getOrCreateTopic(tm, fixNodeKey(child.value)); Topic familyTypeTopic = getOrCreateFamilyType(tm); addAssociation(tm, "child", familyTopic, familyTypeTopic, individualTopic, "child"); } /* * else if("FAMS".equals(child.tag)) { Topic familyTopic = getOrCreateTopic(tm, * fixNodeKey(child.value)); Topic familyTypeTopic = getOrCreateFamilyType(tm); * addAssociation(tm, "spouse", familyTopic, familyTypeTopic, individualTopic, * "spouse"); } */ else if ("SOUR".equals(child.tag)) { addAssociation(tm, "source", individualTopic, individualTypeTopic, fixNodeKey(child.value), "source"); } } } private void processFamily(Gedcom.Node node, TopicMap tm) throws TopicMapException { Topic familyTopic = getOrCreateTopic(tm, fixNodeKey(node.key)); Topic familyTypeTopic = getOrCreateFamilyType(tm); familyTopic.addType(familyTypeTopic); Iterator<Gedcom.Node> childIterator = node.children.iterator(); while (childIterator.hasNext()) { Gedcom.Node child = (Gedcom.Node) childIterator.next(); if ("HUSB".equals(child.tag)) { Topic husbandTopic = getOrCreateTopic(tm, fixNodeKey(child.value)); addAssociation(tm, "husband", familyTopic, familyTypeTopic, husbandTopic, "husband"); } else if ("WIFE".equals(child.tag)) { Topic wifeTopic = getOrCreateTopic(tm, fixNodeKey(child.value)); addAssociation(tm, "wife", familyTopic, familyTypeTopic, wifeTopic, "wife"); } else if ("CHIL".equals(child.tag)) { Topic childTopic = getOrCreateTopic(tm, fixNodeKey(child.value)); addAssociation(tm, "child", familyTopic, familyTypeTopic, childTopic, "child"); } else if ("ENGA".equals(child.tag)) { processEvent(child, tm, "engaged", familyTopic, familyTypeTopic); } else if ("MARR".equals(child.tag)) { processEvent(child, tm, "married", familyTopic, familyTypeTopic); } else if ("MARB".equals(child.tag)) { processEvent(child, tm, "marriage-bann", familyTopic, familyTypeTopic); } else if ("MARC".equals(child.tag)) { processEvent(child, tm, "marriage-contract", familyTopic, familyTypeTopic); } else if ("MARL".equals(child.tag)) { processEvent(child, tm, "marriage-license", familyTopic, familyTypeTopic); } else if ("MARS".equals(child.tag)) { processEvent(child, tm, "marriage-settlement", familyTopic, familyTypeTopic); } else if ("ANUL".equals(child.tag)) { processEvent(child, tm, "anulment", familyTopic, familyTypeTopic); } else if ("CENS".equals(child.tag)) { processEvent(child, tm, "census", familyTopic, familyTypeTopic); } else if ("DIVF".equals(child.tag)) { processEvent(child, tm, "divorce-filed", familyTopic, familyTypeTopic); } else if ("DIV".equals(child.tag)) { processEvent(child, tm, "divorced", familyTopic, familyTypeTopic); } else if ("EVEN".equals(child.tag)) { processEvent(child, tm, "event", familyTopic, familyTypeTopic); } else if ("NOTE".equals(child.tag)) { String note = getText(child); addOccurrence(tm, familyTopic, "note", note.toString()); } else if ("SOUR".equals(child.tag)) { addAssociation(tm, "source", familyTopic, familyTypeTopic, fixNodeKey(child.value), "source"); } } familyTopic.setBaseName(fixNodeKey(node.key)); } private Association processEvent( Gedcom.Node node, TopicMap tm, String eventType, Topic baseTopic, Topic baseTypeTopic) throws TopicMapException { Association eventAssociation = null; if (node.value != null && node.value.length() > 0 && !"Y".equals(node.value)) { eventAssociation = addAssociation(tm, eventType, baseTopic, baseTypeTopic, node.value, eventType); } else { eventAssociation = addAssociation(tm, eventType, baseTopic, baseTypeTopic); } Iterator<Gedcom.Node> childIterator = node.children.iterator(); while (childIterator.hasNext()) { Gedcom.Node child = (Gedcom.Node) childIterator.next(); if ("PLAC".equals(child.tag)) { fillAssociation(tm, eventAssociation, child.value, "place"); } else if ("DATE".equals(child.tag)) { fillAssociation(tm, eventAssociation, child.value, "date"); } else if ("TYPE".equals(child.tag)) { fillAssociation(tm, eventAssociation, child.value, "type"); } else if ("AGE".equals(child.tag)) { fillAssociation(tm, eventAssociation, child.value, "age"); } else if ("AGNC".equals(child.tag)) { fillAssociation(tm, eventAssociation, child.value, "agency"); } else if ("CAUS".equals(child.tag)) { fillAssociation(tm, eventAssociation, child.value, "cause"); } else if ("SOUR".equals(child.tag)) { fillAssociation(tm, eventAssociation, fixNodeKey(child.value), "source"); } else if ("NOTE".equals(child.tag)) { String note = getText(child); String noteBaseName = (note.length() > 255 ? note.substring(0, 255) + "..." : note.toString()); Topic noteTopic = getOrCreateTopic(tm, "note/" + System.currentTimeMillis() + ((int) Math.random() * 10000), noteBaseName); addOccurrence(tm, noteTopic, "note", note.toString()); fillAssociation(tm, eventAssociation, noteTopic, "note"); } } return eventAssociation; } private void processSource(Gedcom.Node node, TopicMap tm) throws TopicMapException { Topic sourceTopic = getOrCreateTopic(tm, fixNodeKey(node.key)); Topic sourceTypeTopic = getOrCreateSourceType(tm); sourceTopic.addType(sourceTypeTopic); Iterator<Gedcom.Node> childIterator = node.children.iterator(); while (childIterator.hasNext()) { Gedcom.Node child = (Gedcom.Node) childIterator.next(); if ("AUTH".equals(child.tag)) { processEvent(child, tm, "author", sourceTopic, sourceTypeTopic); } else if ("TITL".equals(child.tag)) { processEvent(child, tm, "title", sourceTopic, sourceTypeTopic); } else if ("ABBR".equals(child.tag)) { processEvent(child, tm, "abbreviation", sourceTopic, sourceTypeTopic); } else if ("PUBL".equals(child.tag)) { processEvent(child, tm, "publication", sourceTopic, sourceTypeTopic); } else if ("TEXT".equals(child.tag)) { String text = getText(child); addOccurrence(tm, sourceTopic, "text", text.toString()); } else if ("REFN".equals(child.tag)) { processEvent(child, tm, "reference", sourceTopic, sourceTypeTopic); } else if ("RIN".equals(child.tag)) { processEvent(child, tm, "record-id-number", sourceTopic, sourceTypeTopic); } else if ("NOTE".equals(child.tag)) { String note = getText(child); addOccurrence(tm, sourceTopic, "note", note.toString()); } } sourceTopic.setBaseName(fixNodeKey(node.key)); } private String getText(Gedcom.Node node) { StringBuffer note = new StringBuffer(node.value == null ? "" : node.value); Iterator<Gedcom.Node> childIterator = node.children.iterator(); while (childIterator.hasNext()) { Gedcom.Node child = (Gedcom.Node) childIterator.next(); if ("CONC".equals(child.tag)) { if (child.value != null) { if (ADD_SPACE_BEFORE_CONCATENATION) { if (note.length() > 0 && note.charAt(note.length() - 1) != ' ') { note.append(" "); } } note.append(child.value); } } else if ("CONT".equals(child.tag)) { note.append("\n"); if (child.value != null) { note.append(child.value); } } } // System.out.println("---note:"+note.toString()); return note.toString(); } private void processName( Gedcom.Node node, TopicMap tm, Topic nameCarrier, Topic nameCarrierType) throws TopicMapException { Iterator<Gedcom.Node> nameIterator = node.children.iterator(); if (nameIterator.hasNext()) { Association nameAssociation = addAssociation(tm, "name", nameCarrier, nameCarrierType); while (nameIterator.hasNext()) { Gedcom.Node name = (Gedcom.Node) nameIterator.next(); if (name.tag.equals("GIVN")) { fillAssociation(tm, nameAssociation, name.value, "given-name"); } else if ("SURN".equals(name.tag)) { fillAssociation(tm, nameAssociation, name.value, "surname"); } else if ("NICK".equals(name.tag)) { fillAssociation(tm, nameAssociation, name.value, "nickname"); } else if ("NPFX".equals(name.tag)) { fillAssociation(tm, nameAssociation, name.value, "prefix"); } else if ("SPFX".equals(name.tag)) { fillAssociation(tm, nameAssociation, name.value, "surname-prefix"); } else if ("NSFX".equals(name.tag)) { fillAssociation(tm, nameAssociation, name.value, "suffix"); } else if ("SOUR".equals(name.tag)) { fillAssociation(tm, nameAssociation, fixNodeKey(name.value), "source"); } else if ("NOTE".equals(name.tag)) { String note = getText(name); String noteBaseName = (note.length() > 255 ? note.substring(0, 255) + "..." : note.toString()); Topic noteTopic = getOrCreateTopic(tm, "note/" + System.currentTimeMillis() + ((int) Math.random() * 10000), noteBaseName); addOccurrence(tm, noteTopic, "note", note.toString()); fillAssociation(tm, nameAssociation, noteTopic, "name-note"); } } } } private String fixNodeKey(String key) { if (key != null) { if (key.startsWith("@")) { key = key.substring(1); } if (key.endsWith("@")) { key = key.substring(0, key.length() - 1); } } return key; } // ------------------------------------------------------------------------- public Topic getOrCreateGedcomType(TopicMap tm) throws TopicMapException { Topic wandoraClass = getOrCreateTopic(tm, TMBox.WANDORACLASS_SI, "Wandora class"); Topic t = getOrCreateTopic(tm, new Locator(SI_PREFIX), "GEDCOM"); makeSubclassOf(tm, t, wandoraClass); return t; } public Topic getOrCreateIndividualType(TopicMap tm) throws TopicMapException { Topic t = createTopicForSchemaTerm(tm, "individual"); return t; } public Topic getOrCreateFamilyType(TopicMap tm) throws TopicMapException { Topic t = createTopicForSchemaTerm(tm, "family"); return t; } public Topic getOrCreateNameType(TopicMap tm) throws TopicMapException { Topic t = createTopicForSchemaTerm(tm, "name"); return t; } public Topic getOrCreateSourceType(TopicMap tm) throws TopicMapException { Topic t = createTopicForSchemaTerm(tm, "source"); return t; } public void addOccurrence(TopicMap tm, Topic carrier, String occurrenceType, String occurrenceText) throws TopicMapException { if (tm == null) return; if (carrier == null) return; if (occurrenceType == null || occurrenceText == null) return; Topic occurrenceTypeTopic = createTopicForSchemaTerm(tm, occurrenceType); Topic langTopic = getOrCreateTopic(tm, XTMPSI.getLang(DEFAULT_LANG), DEFAULT_LANG); carrier.setData(occurrenceTypeTopic, langTopic, occurrenceText); } public Association fillAssociation(TopicMap tm, Association association, Topic playerTopic, String role) throws TopicMapException { if (tm == null) return null; if (playerTopic == null || role == null) return null; Topic roleTopic = createTopicForSchemaTerm(tm, role); association.addPlayer(playerTopic, roleTopic); return association; } public Association fillAssociation(TopicMap tm, Association association, String player, String role) throws TopicMapException { if (tm == null) return null; if (player == null || role == null) return null; Topic roleTopic = createTopicForSchemaTerm(tm, role); Topic playerTopic = getOrCreateTopic(tm, player); association.addPlayer(playerTopic, roleTopic); return association; } public Association addAssociation(TopicMap tm, String associationType, Topic player1Topic, Topic role1Topic) throws TopicMapException { if (tm == null) return null; if (associationType == null) return null; if (player1Topic == null || role1Topic == null) return null; Topic associationTypeTopic = createTopicForSchemaTerm(tm, associationType); Association association = tm.createAssociation(associationTypeTopic); association.addPlayer(player1Topic, role1Topic); return association; } public Association addAssociation(TopicMap tm, String associationType, Topic player1Topic, Topic role1Topic, String player2, String role2) throws TopicMapException { if (tm == null) return null; if (associationType == null) return null; if (player1Topic == null || role1Topic == null) return null; if (player2 == null || role2 == null) return null; Topic associationTypeTopic = createTopicForSchemaTerm(tm, associationType); Association association = tm.createAssociation(associationTypeTopic); Topic role2Topic = createTopicForSchemaTerm(tm, role2); Topic player2Topic = getOrCreateTopic(tm, player2); association.addPlayer(player1Topic, role1Topic); association.addPlayer(player2Topic, role2Topic); return association; } public Association addAssociation(TopicMap tm, String associationType, Topic player1Topic, Topic role1Topic, Topic player2Topic, String role2) throws TopicMapException { if (tm == null) return null; if (associationType == null) return null; if (player1Topic == null || role1Topic == null) return null; if (player2Topic == null || role2 == null) return null; Topic associationTypeTopic = createTopicForSchemaTerm(tm, associationType); Association association = tm.createAssociation(associationTypeTopic); Topic role2Topic = createTopicForSchemaTerm(tm, role2); association.addPlayer(player1Topic, role1Topic); association.addPlayer(player2Topic, role2Topic); return association; } public Topic createTopicForSchemaTerm(TopicMap tm, String schemaTerm) throws TopicMapException { if (tm == null) return null; if (schemaTerm == null) return null; String si = SCHEMA_PREFIX + schemaTerm; Topic schemaTopic = getOrCreateTopic(tm, TopicTools.cleanDirtyLocator(si)); schemaTopic.setBaseName(schemaTerm); makeSubclassOf(tm, schemaTopic, getOrCreateGedcomType(tm)); return schemaTopic; } public void makeSubclassOf(TopicMap tm, Topic t, Topic superclass) throws TopicMapException { ExtractHelper.makeSubclassOf(t, superclass, tm); } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- public boolean associationExists(Topic t1, Topic t2, Topic at) { if (t1 == null || t2 == null || at == null) return false; try { Collection<Association> c = t1.getAssociations(at); Association a = null; Collection<Topic> roles = null; Topic player = null; for (Iterator<Association> i = c.iterator(); i.hasNext();) { a = i.next(); roles = a.getRoles(); for (Iterator<Topic> it = roles.iterator(); it.hasNext();) { player = a.getPlayer(it.next()); if (player != null && t2.mergesWithTopic(player)) return true; } } } catch (Exception e) { e.printStackTrace(); } return false; } public Topic getOrCreateTopic(TopicMap tm, String si, String basename) throws TopicMapException { return getOrCreateTopic(tm, new Locator(si.trim()), basename); } public Topic getOrCreateTopic(TopicMap tm, String base) throws TopicMapException { return getOrCreateTopic(tm, this.makeSI(base), base); } public Topic getOrCreateTopic(TopicMap tm, Locator si, String basename) throws TopicMapException { if (tm == null) return null; Topic topic = tm.getTopic(si); if (topic == null) { topic = tm.createTopic(); topic.addSubjectIdentifier(si); } if (basename != null && topic.getBaseName() == null) { topic.setBaseName(basename.trim()); } return topic; } public Topic getTopic(TopicMap tm, String si) throws TopicMapException { if (tm == null) return null; Topic topic = tm.getTopic(si); return topic; } public Topic getOrCreateTopic(TopicMap topicmap, String si, String baseName, String displayName) { return getOrCreateTopic(topicmap, new Locator(si), baseName, displayName, null); } public Topic getOrCreateTopic(TopicMap topicmap, Locator si, String baseName, String displayName) { return getOrCreateTopic(topicmap, si, baseName, displayName, null); } public Topic getOrCreateTopic(TopicMap topicmap, Locator si, String baseName, String displayName, Topic typeTopic) { try { return ExtractHelper.getOrCreateTopic(si, baseName, displayName, typeTopic, topicmap); } catch (Exception e) { log(e); } return null; } public Locator makeSI(String str) { if (str == null) str = ""; return new Locator(TopicTools.cleanDirtyLocator(SI_PREFIX + str.trim())); } @Override public boolean useTempTopicMap() { return false; } }
30,162
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
BibtexParseException.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/bibtex/BibtexParseException.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * BibtexParseException.java * * Created on 17. lokakuuta 2007, 12:30 */ package org.wandora.application.tools.extractors.bibtex; /** * * @author olli */ public class BibtexParseException extends Exception { private static final long serialVersionUID = 1L; /** Creates a new instance of BibtexParseException */ public BibtexParseException() { } public BibtexParseException(String message) { super(message); } }
1,256
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
BibtexEntry.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/bibtex/BibtexEntry.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * BibtexEntry.java * * Created on 17. lokakuuta 2007, 11:11 * */ package org.wandora.application.tools.extractors.bibtex; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; /** * * @author olli */ public class BibtexEntry { private String type; private String id; private HashMap<String,Object> values; /** Creates a new instance of BibtexEntry */ public BibtexEntry() { values=new HashMap<String,Object>(); } public BibtexEntry(String type,String id) { this(); setType(type); setID(id); } public String getType(){return type;} public void setType(String type){this.type=type;} public String getID(){return id;} public void setID(String id){this.id=id;} public Map<String,Object> getValues(){return values;} public Object getValue(String key){return values.get(key);} public void setValue(String key,Object value){values.put(key,value);} public void addPerson(String key,BibtexPerson person){ ArrayList<BibtexPerson> list; Object o=values.get(key); if(o==null || !(o instanceof ArrayList)){ list=new ArrayList<BibtexPerson>(); values.put(key,list); } else list=(ArrayList<BibtexPerson>)o; list.add(person); } public String getString(String key){ Object o=values.get(key); if(o==null) return null; else return o.toString(); } }
2,293
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
BibtexPerson.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/bibtex/BibtexPerson.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * BibtexPerson.java * * Created on 17. lokakuuta 2007, 11:11 * */ package org.wandora.application.tools.extractors.bibtex; /** * * @author olli */ public class BibtexPerson { private String firstName; private String lastName; private String initials; /** Creates a new instance of BibtexPerson */ public BibtexPerson() { } public BibtexPerson(String firstName,String initials,String lastName) { setFirstName(firstName); setInitials(initials); setLastName(lastName); } public String getFirstName(){return firstName;} public void setFirstName(String firstName){this.firstName=firstName;} public String getLastName(){return lastName;} public void setLastName(String lastName){this.lastName=lastName;} public String getInitials(){return initials;} public void setInitials(String initials){this.initials=initials;} }
1,724
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
BibtexParser.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/bibtex/BibtexParser.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * BibtexParser.java * * Created on 17. lokakuuta 2007, 11:01 * */ package org.wandora.application.tools.extractors.bibtex; import static org.wandora.utils.Tuples.t2; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PushbackReader; import java.io.Reader; import java.util.ArrayList; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.wandora.utils.Tuples.T2; /** * * @author olli */ public class BibtexParser { private ArrayList<BibtexEntry> entries; /** Creates a new instance of BibtexParser */ public BibtexParser() { } public ArrayList<BibtexEntry> getEntries(){ return entries; } public void parse(Reader reader) throws IOException { parse(new PushbackReader(reader)); } public void parse(PushbackReader reader) throws IOException { entries=new ArrayList<BibtexEntry>(); int c; while( (c=reader.read())!=-1 ){ if(c=='@'){ try{ String type=readUntil(reader,"{"); type=type.substring(0,type.length()-1).trim(); // special processing for comment and string entries here BibtexEntry e=readEntryBlock(reader,type); if(e!=null) entries.add(e); }catch(BibtexParseException bpe){ bpe.printStackTrace(); } } } reader.close(); } private BibtexEntry readEntryBlock(PushbackReader reader,String type) throws IOException,BibtexParseException { BibtexEntry entry=new BibtexEntry(); entry.setType(type); StringBuffer key=null; StringBuffer value=null; boolean first=true; while( true ){ T2<String,Object> element=readEntryElement(reader); if(element==null) break; if(element.e2==null && first && element.e1!=null) entry.setID(element.e1); else if(element.e2==null || element.e1==null) throw new BibtexParseException(); else entry.setValue(element.e1,element.e2); first=false; } return entry; } private T2<String,Object> readEntryElement(PushbackReader reader) throws IOException,BibtexParseException { String key=readUntil(reader,",=}"); char last=key.charAt(key.length()-1); key=key.substring(0,key.length()-1).trim().toLowerCase(); if(last=='}' && key.length()==0) return null; if(last==',' && key.length()==0) throw new BibtexParseException(); if(last==',' || last=='}') { if(last=='}') reader.unread(last); return t2(key,null); } if(key.equals("author") || key.equals("editor")) { ArrayList<Object> values=readElementValue(reader,true); if(values!=null && values.size()>0) return t2(key,(Object)values); else return null; } else { ArrayList<Object> values=readElementValue(reader,false); if(values!=null && values.size()>0) return t2(key,values.get(0)); else return null; } } private Object makeValueObject(String r1,String r2,boolean people){ if(!people) return r1.toString(); else{ String first=null; String initials=null; String last=null; int ind=r1.indexOf(","); if(ind!=-1){ last=r1.substring(0,ind).trim(); first=""; if(ind<r1.length()-1) first=r1.substring(ind+1); if(r2!=null) first+=r2; first=first.trim(); } else if(r2!=null){ first=r1.trim(); last=r2.trim(); } else { ind=r1.lastIndexOf(" "); if(ind!=-1){ first=r1.substring(0,ind).trim(); if(ind<r1.length()-1) last=r1.substring(ind+1).trim(); if(last == null || last.length() == 0) { last=first; first=null; } } else last=r1.trim(); } if(first!=null && first.length()==0) first=null; if(first!=null){ Pattern p=Pattern.compile("([^\\s]+)((\\s+[^\\s]\\.)+)"); Matcher m=p.matcher(first); if(m.matches()){ initials=m.group(2); first=m.group(1).trim(); initials.replaceAll("\\s+",""); } } return new BibtexPerson(first,initials,last); } } private ArrayList<Object> readElementValue(PushbackReader reader,boolean people) throws IOException,BibtexParseException{ int c; int openBraces=0; int openQuotes=0; ArrayList<Object> parsed=new ArrayList<Object>(); StringBuffer read1=new StringBuffer(); StringBuffer read2=null; StringBuffer read=read1; while( (c=reader.read())!=-1 ){ if(c=='{') { if(people && read==read1 && openBraces+openQuotes==1 && read1.toString().trim().length()>0 && Character.isWhitespace(read1.charAt(read1.length()-1))){ read2=new StringBuffer(); read=read2; } openBraces++; continue; } else if(c=='}') { openBraces--; if(openBraces<0) { reader.unread(c); break; } else continue; } if(c=='\"' && openBraces==0){ if(openQuotes==0) openQuotes=1; else openQuotes=0; continue; } if(openQuotes>0 || openBraces>0){ if(c=='\\'){ String cmd=readEscapeCommand(reader); String block=""; int c2=reader.read(); if(c2=='{') block=readUntil(reader,"}"); else block=Character.toString((char)c2); boolean consumed=false; if(cmd.length()==1){ if(cmd.equals("\\")) read.append("\n"); else if("#$%&_{}".indexOf(cmd)!=-1) read.append(cmd); } // rest of special symbols at http://www.bibtex.org/SpecialSymbols/ if(cmd.equals("aa")) read.append("å"); else if(cmd.equals("AA")) read.append("Å"); else if(cmd.equals("\"") && block.equals("a")) {read.append("ä"); consumed=true;} else if(cmd.equals("\"") && block.equals("A")) {read.append("Ä"); consumed=true;} else if(cmd.equals("\"") && block.equals("o")) {read.append("ö"); consumed=true;} else if(cmd.equals("\"") && block.equals("O")) {read.append("Ö"); consumed=true;} else if(cmd.equals("\'") && block.equals("e")) {read.append("é"); consumed=true;} else if(cmd.equals("\'") && block.equals("E")) {read.append("É"); consumed=true;} else read.append("\\"+cmd); if(!consumed) reader.unread(c2); continue; } read.append((char)c); if(people && read.length()>=5){ if(read.substring(read.length()-4,read.length()-1).toLowerCase().equals("and") && Character.isWhitespace(read.charAt(read.length()-5)) && Character.isWhitespace(read.charAt(read.length()-1))){ String r1,r2; if(read==read2){ r1=read1.toString(); r2=read.substring(0,read.length()-5).trim(); } else{ r1=read.substring(0,read.length()-5).trim(); r2=null; } Object o=makeValueObject(r1,r2,true); if(o!=null) parsed.add(o); read1=new StringBuffer(); read2=null; read=read1; } } } else if(c=='#'){} // append operator else if(c==',') break; // end of entry else if(Character.isLetterOrDigit((char)c)) read.append((char)c); // numbers and some other values may be outside quotes } Object o=makeValueObject(read1.toString(),(read2==null?null:read2.toString()),people); if(o!=null) parsed.add(o); return parsed; } private String readEscapeCommand(PushbackReader reader) throws IOException { int c; StringBuffer read=new StringBuffer(); while( (c=reader.read())!=-1 ){ if(Character.isLetterOrDigit((char)c)){ read.append((char)c); } else{ if(read.length()==0) read.append((char)c); else reader.unread(c); break; } } return read.toString(); } private String readUntil(PushbackReader reader,String chars) throws IOException,BibtexParseException { int c; StringBuffer read=new StringBuffer(); while( (c=reader.read())!=-1 ){ read.append((char)c); if(chars.indexOf((char)c)!=-1) break; } return read.toString(); } private int readWhitespace(PushbackReader reader) throws IOException{ int c; while( (c=reader.read())!=-1 ){ if(!Character.isWhitespace((char)c)) return c; } return -1; } public static String removeBraces(String text){ return text.replace("{","").replace("}",""); } public static void main(String[] args) throws Exception { BibtexParser parser=new BibtexParser(); // parser.parse(new InputStreamReader(System.in)); parser.parse(new InputStreamReader(new FileInputStream("C:\\wandora\\build\\classes\\test.bib"))); for(BibtexEntry e : parser.getEntries()){ System.out.print("@"+e.getType()+"{"); if(e.getID()!=null) System.out.print(e.getID()+","); System.out.println(); Map<String,Object> values=e.getValues(); for(String key : values.keySet()){ Object value=values.get(key); if(value instanceof String) System.out.println("\t"+key+" = \""+value+"\","); else{ ArrayList<BibtexPerson> list=(ArrayList<BibtexPerson>)value; System.out.print("\t"+key+" = \""); boolean first=true; for(BibtexPerson p : list){ if(!first) System.out.print(" and "); else first=false; System.out.print(p.getLastName()); if(p.getFirstName()!=null){ System.out.print(", "+p.getFirstName()); if(p.getInitials()!=null) System.out.print(" "+p.getInitials()); } } System.out.println("\","); } } System.out.println("}"); } } }
12,642
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
BibtexExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/bibtex/BibtexExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * BibtexExtractor.java * * Created on 17. lokakuuta 2007, 10:21 * */ package org.wandora.application.tools.extractors.bibtex; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.HashSet; import java.util.Map; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.tools.extractors.AbstractExtractor; 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.GripCollections; /** * * @author olli */ public class BibtexExtractor extends AbstractExtractor implements WandoraTool { private static final long serialVersionUID = 1L; private String baseLocator = "http://wandora.org/si/bibtex/"; private String defaultEncoding = "ISO-8859-1"; /** Creates a new instance of BibtexExtractor */ public BibtexExtractor() { } public String getName() { return "BibTeX extractor (old version)"; } public String getDescription(){ return "Extracts information from BibTeX files!"; } public String getGUIText(int textType) { return super.getGUIText(textType); } private Topic getOrCreateTopic(TopicMap tm,String topic) throws TopicMapException { return getOrCreateTopic(tm,topic,false); } private Topic getOrCreateTopic(TopicMap tm,String topic,boolean addToBibTexClass) throws TopicMapException { Locator l=buildSI(topic.toLowerCase()); Topic t=tm.getTopic(l); if(t!=null) return t; t=tm.createTopic(); t.addSubjectIdentifier(l); t.setBaseName(topic); if(addToBibTexClass){ Topic bc = TMBox.getOrCreateTopic(tm,baseLocator); bc.setBaseName("Bibtex"); Topic c = TMBox.getOrCreateTopic(tm,TMBox.WANDORACLASS_SI); t.addType(bc); bc.addType(c); } return t; } private void addOccurrence(TopicMap tm,Topic entryTopic,BibtexEntry entry,String key) throws TopicMapException { Object o=entry.getValue(key); if(o==null) return; Topic type=getOrCreateTopic(tm,key); Topic lang=TMBox.getOrCreateTopic(tm,XTMPSI.LANG_INDEPENDENT); entryTopic.setData(type,lang,o.toString()); } private void addAssociation(TopicMap tm,Topic entryTopic,BibtexEntry entry,String key) throws TopicMapException { Object o=entry.getValue(key); if(o==null) return; Topic type=getOrCreateTopic(tm,key); Topic citation=getOrCreateTopic(tm,"citation"); Topic lang=TMBox.getOrCreateTopic(tm,XTMPSI.LANG_INDEPENDENT); ArrayList a; if(o instanceof ArrayList) a=(ArrayList)o; else { a=new ArrayList(); a.add(o); } for(Object v : a){ Association as=tm.createAssociation(type); as.addPlayer(entryTopic,citation); Topic p; if(v instanceof BibtexPerson){ p=createPersonTopic(tm,(BibtexPerson)v); } else{ p=tm.createTopic(); p.addType(type); p.setBaseName(v.toString()); } as.addPlayer(p,type); } } private Topic createPersonTopic(TopicMap tm,BibtexPerson p) throws TopicMapException { String name=p.getLastName(); if(p.getFirstName()!=null) name+=", "+p.getFirstName(); if(p.getInitials()!=null) name+=" "+p.getInitials(); Topic t=tm.createTopic(); t.setBaseName(name); Topic type=getOrCreateTopic(tm,"Person"); t.addType(type); return t; } public static final HashSet<String> associationFields=GripCollections.newHashSet("author","editor","institution","organization","booktitle","journal", "publisher","school","series","year","volume","number","month","type","chapter","edition","howpublished"); public static final HashSet<String> occurrenceFields=GripCollections.newHashSet("address","annote","crossref", "key","note","pages"); public boolean _extractTopicsFrom(Reader reader, TopicMap tm) throws Exception { BibtexParser parser=new BibtexParser(); try{ parser.parse(reader); ArrayList<BibtexEntry> entries=parser.getEntries(); for(BibtexEntry e : entries){ String typeS=e.getType(); Topic type=getOrCreateTopic(tm,typeS,true); Object titleS=e.getValue("title"); Topic entry=null; if(titleS!=null) entry=tm.getTopicWithBaseName(titleS.toString()); if(entry==null) entry=tm.createTopic(); entry.addType(type); if(titleS!=null) entry.setBaseName(titleS.toString()); Map<String,Object> values=e.getValues(); for(String key : values.keySet()){ if(associationFields.contains(key)){ addAssociation(tm,entry,e,key); } else { addOccurrence(tm,entry,e,key); } } } if(entries.size()>0) return true; }catch(IOException ioe){ log(ioe); } return false; } public boolean _extractTopicsFrom(URL file, TopicMap topicMap) throws Exception { URLConnection con=file.openConnection(); Wandora.initUrlConnection(con); String enc=con.getContentEncoding(); Reader reader=null; if(enc==null) enc=defaultEncoding; reader=new InputStreamReader(con.getInputStream(),enc); return _extractTopicsFrom(reader,topicMap); } public boolean _extractTopicsFrom(File file, TopicMap topicMap) throws Exception { Reader reader=new InputStreamReader(new FileInputStream(file),defaultEncoding); return _extractTopicsFrom(reader,topicMap); } public boolean _extractTopicsFrom(String str, TopicMap topicMap) throws Exception { Reader reader=new BufferedReader(new StringReader(str)); return _extractTopicsFrom(reader, topicMap); } @Override public Locator buildSI(String siend) { if(!baseLocator.endsWith("/")) baseLocator = baseLocator + "/"; return new Locator(TopicTools.cleanDirtyLocator(baseLocator + siend)); } private final String[] contentTypes=new String[] { "text/plain", "application/x-bibtex", "text/x-bibtex" }; public String[] getContentTypes() { return contentTypes; } }
8,108
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
HSFeedExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/hsopen/HSFeedExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * RSSExtractor.java * * Created on 3. marraskuuta 2007, 13:18 * */ package org.wandora.application.tools.extractors.hsopen; 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 org.wandora.application.Wandora; 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.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 HSFeedExtractor extends AbstractExtractor { private static final long serialVersionUID = 1L; /** Creates a new instance of HSFeedExtractor */ public HSFeedExtractor() { } @Override public boolean useURLCrawler() { return false; } @Override public String getName() { return "HS Feed Extractor"; } @Override public String getDescription(){ return "Extractor reads HS feed and converts the feed to a topic map."; } /* @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_hs.png"); } */ private final String[] contentTypes=new String[] { "text/xml", "application/xml", "application/rss+xml", "application/xhtml+xml" }; @Override public String[] getContentTypes() { return contentTypes; } public boolean _extractTopicsFrom(URL url, TopicMap topicMap) throws Exception { URLConnection uc=url.openConnection(); Wandora.initUrlConnection(uc); return _extractTopicsFrom(uc.getInputStream(),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 { boolean answer = _extractTopicsFrom(new ByteArrayInputStream(str.getBytes()), topicMap); return answer; } 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(); HSFeedParser parserHandler = new HSFeedParser(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.articleCount + " HS articles processed!"); return true; } private static class HSFeedParser implements org.xml.sax.ContentHandler, org.xml.sax.ErrorHandler { public static boolean MAKE_LINK_SUBJECT_LOCATOR = false; public static boolean MAKE_SUBCLASS_OF_WANDORA_CLASS = true; public HSFeedParser(TopicMap tm, HSFeedExtractor parent){ this.tm=tm; this.parent=parent; } public int progress=0; public int articleCount = 0; private TopicMap tm; private HSFeedExtractor parent; public static final String TAG_HS="articles"; public static final String TAG_ARTICLE="article"; public static final String TAG_TITLE="mainHeader"; public static final String TAG_LINK="link"; public static final String TAG_DESCRIPTION="description"; public static final String TAG_LANGUAGE="language"; public static final String TAG_CREATEDDATE="createdDate"; public static final String TAG_LASTBUILDDATE="lastBuildDate"; private static final int STATE_START=0; private static final int STATE_HS=2; private static final int STATE_ARTICLE=4; private static final int STATE_ARTICLE_TITLE=5; private static final int STATE_ARTICLE_LINK=6; private static final int STATE_ARTICLE_DESCRIPTION=7; private static final int STATE_ARTICLE_LANGUAGE=8; private static final int STATE_ARTICLE_CREATEDDATE=9; private static final int STATE_ARTICLE_LASTBUILDDATE=10; private int state=STATE_START; public static String HSFEED_SI = "http://purl.org/hsfeed/"; public static String SIPREFIX="http://purl.org/hsfeed/"; public static String ARTICLE_SI=SIPREFIX+"article"; public static String ARTICLE_LINK_SI=ARTICLE_SI+"/link"; public static String ARTICLE_DESCRIPTION_SI=ARTICLE_SI+"/description"; public static String ARTICLE_LANGUAGE_SI=ARTICLE_SI+"/language"; public static String ARTICLE_CREATEDDATE_SI=ARTICLE_SI+"/CREATEDDATE"; public static String ARTICLE_LASTBUILDDATE_SI=ARTICLE_SI+"/lastbuilddate"; public static String DATE_SI="http://wandora.org/si/date"; private String data_article_title; private String data_article_link; private String data_article_description; private String data_article_language; private String data_article_createddate; private String data_article_lastbuilddate; private Topic theArticle; private Topic getOrCreateTopic(String si) throws TopicMapException { return getOrCreateTopic(si, null); } private Topic getOrCreateTopic(String si,String bn) throws TopicMapException { return ExtractHelper.getOrCreateTopic(si, bn, tm); } public void startDocument() throws SAXException { articleCount = 0; } public void endDocument() throws SAXException { } public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { //parent.log("START" + state +" --- " + qName); if(parent.forceStop()){ throw new SAXException("User interrupt"); } switch(state){ case STATE_START: if(qName.equals(TAG_HS)) { state = STATE_HS; } break; case STATE_HS: if(qName.equals(TAG_ARTICLE)) { state = STATE_ARTICLE; try { Topic articleType=getOrCreateTopic(ARTICLE_SI,"HS feed article"); theArticle = tm.createTopic(); theArticle.addSubjectIdentifier(TopicTools.createDefaultLocator()); theArticle.addType(articleType); articleCount++; Topic HSFeedClass = getOrCreateTopic(HSFEED_SI, "HS feed"); Topic superClass = getOrCreateTopic(XTMPSI.SUPERCLASS, null); Topic subClass = getOrCreateTopic(XTMPSI.SUBCLASS, null); Topic supersubClass = getOrCreateTopic(XTMPSI.SUPERCLASS_SUBCLASS, null); Association supersubClassAssociation = tm.createAssociation(supersubClass); supersubClassAssociation.addPlayer(HSFeedClass, superClass); supersubClassAssociation.addPlayer(articleType, subClass); if(MAKE_SUBCLASS_OF_WANDORA_CLASS) { Topic wandoraClass = getOrCreateTopic(TMBox.WANDORACLASS_SI, "Wandora class"); supersubClassAssociation = tm.createAssociation(supersubClass); supersubClassAssociation.addPlayer(wandoraClass, superClass); supersubClassAssociation.addPlayer(HSFeedClass, subClass); } } catch(Exception e) { parent.log(e); } } break; case STATE_ARTICLE: if(qName.equals(TAG_TITLE)) { state = STATE_ARTICLE_TITLE; data_article_title = ""; } else if(qName.equals(TAG_LINK)) { state = STATE_ARTICLE_LINK; data_article_link = ""; } else if(qName.equals(TAG_DESCRIPTION)) { state = STATE_ARTICLE_DESCRIPTION; data_article_description = ""; } else if(qName.equals(TAG_LANGUAGE)) { state = STATE_ARTICLE_LANGUAGE; data_article_language = ""; } else if(qName.equals(TAG_CREATEDDATE)) { state = STATE_ARTICLE_CREATEDDATE; data_article_createddate = ""; } else if(qName.equals(TAG_LASTBUILDDATE)) { state = STATE_ARTICLE_LASTBUILDDATE; data_article_lastbuilddate = ""; } break; } } public void endElement(String uri, String localName, String qName) throws SAXException { //parent.log(" END" + state +" --- " + qName); switch(state) { case STATE_HS: { if(qName.equals(TAG_HS)) { state = STATE_START; } break; } case STATE_ARTICLE: { if(qName.equals(TAG_ARTICLE)) { state = STATE_HS; if(theArticle != null) { } } break; } case STATE_ARTICLE_TITLE: { if(qName.equals(TAG_TITLE)) { state = STATE_ARTICLE; if(theArticle != null && data_article_title.length() > 0) { try { theArticle.setBaseName(data_article_title + " (HS feed article)"); theArticle.setDisplayName("fi", data_article_title); } catch(Exception e) { parent.log(e); } } } break; } case STATE_ARTICLE_LINK: { if(qName.equals(TAG_LINK)) { state = STATE_ARTICLE; if(theArticle != null && data_article_link.length() > 0) { try { if(MAKE_LINK_SUBJECT_LOCATOR) { theArticle.setSubjectLocator(new org.wandora.topicmap.Locator(data_article_link)); } else { Topic linkType = getOrCreateTopic(ARTICLE_LINK_SI,"HS feed Link"); parent.setData(theArticle, linkType, "en", data_article_link); } } catch(Exception e) { parent.log(e); } } } break; } case STATE_ARTICLE_DESCRIPTION: { if(qName.equals(TAG_DESCRIPTION)) { state = STATE_ARTICLE; if(theArticle != null && data_article_description.length() > 0) { try { Topic descriptionType = getOrCreateTopic(ARTICLE_DESCRIPTION_SI,"HS feed description"); parent.setData(theArticle, descriptionType, "fi", data_article_description); } catch(Exception e) { parent.log(e); } } } break; } case STATE_ARTICLE_LANGUAGE: { if(qName.equals(TAG_LANGUAGE)) { state = STATE_ARTICLE; if(theArticle != null && data_article_language.length() > 0) { try { Topic articleType = getOrCreateTopic(ARTICLE_SI,"HS feed article"); Topic languageType = getOrCreateTopic(ARTICLE_LANGUAGE_SI,"RSS Channel Language"); Topic theLanguage = getOrCreateTopic(ARTICLE_LANGUAGE_SI + "/" + data_article_language, data_article_language); theLanguage.addType(languageType); Association articleLanguage = tm.createAssociation(languageType); articleLanguage.addPlayer(theArticle, articleType); articleLanguage.addPlayer(theLanguage, languageType); } catch(Exception e) { parent.log(e); } } } break; } case STATE_ARTICLE_CREATEDDATE: { if(qName.equals(TAG_CREATEDDATE)) { state = STATE_ARTICLE; if(theArticle != null && data_article_createddate.length() > 0) { try { Topic articleType = getOrCreateTopic(ARTICLE_SI,"HS feed article"); Topic dateType = getOrCreateTopic(DATE_SI,"Date"); Topic createddateType = getOrCreateTopic(ARTICLE_CREATEDDATE_SI,"HS feed article date"); Topic theDate = getOrCreateTopic(DATE_SI + "/" + data_article_createddate, data_article_createddate); theDate.addType(dateType); Association articleCreatedDate = tm.createAssociation(createddateType); articleCreatedDate.addPlayer(theArticle, articleType); articleCreatedDate.addPlayer(theDate, dateType); } catch(Exception e) { parent.log(e); } } } break; } case STATE_ARTICLE_LASTBUILDDATE: { if(qName.equals(TAG_LASTBUILDDATE)) { state = STATE_ARTICLE; if(theArticle != null && data_article_lastbuilddate.length() > 0) { try { Topic articleType = getOrCreateTopic(ARTICLE_SI,"HS feed article"); Topic dateType = getOrCreateTopic(DATE_SI,"Date"); Topic lastbuilddateType = getOrCreateTopic(ARTICLE_LASTBUILDDATE_SI,"HS feed article last build date"); Topic theDate = getOrCreateTopic(DATE_SI + "/" + data_article_lastbuilddate, data_article_lastbuilddate); theDate.addType(dateType); Association articlePubDate = tm.createAssociation(lastbuilddateType); articlePubDate.addPlayer(theArticle, articleType); articlePubDate.addPlayer(theDate, dateType); } catch(Exception e) { parent.log(e); } } } break; } } } public void characters(char[] ch, int start, int length) throws SAXException { switch(state){ case STATE_ARTICLE_TITLE: data_article_title+=new String(ch,start,length); break; case STATE_ARTICLE_LINK: data_article_link+=new String(ch,start,length); break; case STATE_ARTICLE_DESCRIPTION: data_article_description+=new String(ch,start,length); break; case STATE_ARTICLE_LANGUAGE: data_article_language+=new String(ch,start,length); break; case STATE_ARTICLE_CREATEDDATE: data_article_createddate+=new String(ch,start,length); break; case STATE_ARTICLE_LASTBUILDDATE: data_article_lastbuilddate+=new String(ch,start,length); break; } } public void warning(SAXParseException exception) throws SAXException { parent.log("Warning while parsing XML document at "+exception.getLineNumber()+","+exception.getColumnNumber(),exception); } 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 {} } }
20,073
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ApuRahatCSVExtract.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/hsopen/ApuRahatCSVExtract.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.hsopen; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.InputStreamReader; import java.io.StringReader; import java.net.URL; import org.wandora.application.WandoraTool; 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; import org.wandora.utils.Textbox; /** * * @author akivela */ public class ApuRahatCSVExtract extends AbstractExtractor implements WandoraTool { private static final long serialVersionUID = 1L; protected String defaultEncoding = "UTF-8"; public static String LANG = "fi"; public static final String APURAHAT_SI = "http://wandora.org/si/hsopen/apurahat"; public static final String KOONTI_SI = APURAHAT_SI+"/koonti"; public static final String HENKILO_SI = APURAHAT_SI+"/henkilo"; public static final String KIELI_SI = APURAHAT_SI+"/kieli"; public static final String SUKUPUOLI_SI = APURAHAT_SI+"/sukupuoli"; public static final String VUOSI_SI = APURAHAT_SI+"/vuosi"; public static final String HAKEMUSLUOKKA_SI = APURAHAT_SI+"/hakemusluokka"; public static final String PAATOS_SI = APURAHAT_SI+"/paatos"; public static final String JASEN_SI = APURAHAT_SI+"/jasen"; public static final String SUMMA_SI = APURAHAT_SI+"/summa"; public static final String MAAKUNTA_SI = APURAHAT_SI+"/maakunta"; public static final String LAANI_SI = APURAHAT_SI+"/laani"; public static final String KOTIPAIKKA_SI = APURAHAT_SI+"/kotipaikka"; public static final String SYNNYINKUUKAUSI_SI = APURAHAT_SI+"/synnyin-kuukausi"; public static final String SYNNYINPAIVA_SI = APURAHAT_SI+"/synnyin-paiva"; public static final String SYNNYINVUOSI_SI = APURAHAT_SI+"/synnyin-vuosi"; public static final String SYNNYINAIKA_SI = APURAHAT_SI+"/syntyma-aika"; public static final int KOONTI_COLUMN = 0; public static final int NIMI_COLUMN = 1; public static final int HETU_COLUMN = 2; public static final int KIELI_COLUMN = 3; public static final int SUKUPUOLI_COLUMN = 4; public static final int VUOSI_COLUMN = 5; public static final int HAKEMUSLUOKKA_COLUMN = 6; public static final int PAATOS_COLUMN = 7; public static final int JASENTEN_LKM_COLUMN = 8; public static final int SUMMA_COLUMN = 9; public static final int MAAKUNTA_COLUMN = 10; public static final int LAANI_COLUMN = 11; public static final int KOTIPAIKKA_COLUMN = 12; /** * Creates a new instance of ApuRahatCSVExtract */ public ApuRahatCSVExtract() { } @Override public String getName() { return "Apurahat CSV Extract (HSOpen)"; } @Override public String getDescription() { return "Apurahat CSV Extract (HSOpen)."; } @Override public String getGUIText(int textType) { switch(textType) { case SELECT_DIALOG_TITLE: return "Select ApurahaCSV file(s) or directories containing ApurahaCSV files!"; case POINT_START_URL_TEXT: return "Where would you like to start the crawl?"; case INFO_WAIT_WHILE_WORKING: return "Wait while seeking ApurahaCSV files!"; case FILE_PATTERN: return ".*\\.txt"; case DONE_FAILED: return "Ready. No extractions! %1 ApurahaCSV files(s) crawled!"; case DONE_ONE: return "Ready. Successful extraction! %1 ApurahaCSV files(s) crawled!"; case DONE_MANY: return "Ready. Total %0 successful extractions! %1 ApurahaCSV files(s) crawled!"; case LOG_TITLE: return "ApurahaCSV Extraction Log"; } return ""; } @Override public boolean useTempTopicMap() { return false; } public boolean _extractTopicsFrom(String str, TopicMap topicMap) throws Exception { boolean answer = _extractTopicsFrom(new BufferedReader(new StringReader(str)), topicMap); return answer; } public boolean _extractTopicsFrom(URL url, TopicMap topicMap) throws Exception { if(url == null) return false; BufferedReader urlReader = new BufferedReader( new InputStreamReader ( url.openStream() ) ); return _extractTopicsFrom(urlReader, topicMap); } public boolean _extractTopicsFrom(File keywordFile, TopicMap topicMap) throws Exception { boolean result = false; BufferedReader breader = null; try { if(keywordFile == null) { log("No CSV file addressed! Using default file name 'apurahat.txt'!"); keywordFile = new File("apurahat.txt"); } FileReader fr = new FileReader(keywordFile); breader = new BufferedReader(fr); result = _extractTopicsFrom(breader, topicMap); } finally { if(breader != null) breader.close(); } return result; } public boolean _extractTopicsFrom(BufferedReader breader, TopicMap tm) throws Exception { int rowCounter = 0; log("Extracting..."); try { String line = ""; String[] tokens = null; line = breader.readLine(); while(line != null && !forceStop()) { tokens = line.split("\t"); for(int i=0; i<tokens.length; i++) { // Trim results! if(tokens[i] != null && tokens[i].length() > 0) { //System.out.print("trimming " + tokens[i]); tokens[i] = Textbox.trimExtraSpaces(tokens[i]); //System.out.print(" --> " + tokens[i]); } } Topic koontiT = null; Topic henkiloT = null; Topic kieliT = null; Topic sukupuoliT = null; Topic vuosiT = null; Topic hakemusluokkaT = null; Topic paatosT = null; Topic jasenT = null; Topic summaT = null; Topic maakuntaT = null; Topic laaniT = null; Topic kotipaikkaT = null; if(tokens.length > 3) { String h = fix(tokens[HETU_COLUMN]); if(h == null || h.length() == 0) h = "SSN-"+System.currentTimeMillis(); koontiT = getKoontiTopic( fix(tokens[KOONTI_COLUMN]), tm ); henkiloT = getHenkiloTopic( h, fix(tokens[NIMI_COLUMN]), tm ); kieliT = getKieliTopic( fix(tokens[KIELI_COLUMN]), tm ); sukupuoliT = getSukupuoliTopic( fix(tokens[SUKUPUOLI_COLUMN]), tm ); vuosiT = getVuosiTopic( fix(tokens[VUOSI_COLUMN]), tm ); hakemusluokkaT = getHakemusluokkaTopic( fix(tokens[HAKEMUSLUOKKA_COLUMN]), tm ); paatosT = getPaatosTopic( fix(tokens[PAATOS_COLUMN]), tm ); jasenT = getJasenTopic( fix(tokens[JASENTEN_LKM_COLUMN]), tm ); summaT = getSummaTopic( fix(tokens[SUMMA_COLUMN]), tm ); if(tokens.length > MAAKUNTA_COLUMN) maakuntaT = getMaakuntaTopic( fix(tokens[MAAKUNTA_COLUMN]), tm ); if(tokens.length > LAANI_COLUMN) laaniT = getLaaniTopic( fix(tokens[LAANI_COLUMN]), tm ); if(tokens.length > KOTIPAIKKA_COLUMN) kotipaikkaT = getKotipaikkaTopic( fix(tokens[KOTIPAIKKA_COLUMN]), tm ); if(henkiloT != null && kieliT != null) { Association a = tm.createAssociation(getKieliType(tm)); a.addPlayer(kieliT, getKieliType(tm)); a.addPlayer(henkiloT, getHenkiloType(tm)); } if(henkiloT != null && sukupuoliT != null) { Association a = tm.createAssociation(getSukupuoliType(tm)); a.addPlayer(sukupuoliT, getSukupuoliType(tm)); a.addPlayer(henkiloT, getHenkiloType(tm)); } if(henkiloT!= null && kotipaikkaT != null) { Association a = tm.createAssociation(getKotipaikkaType(tm)); a.addPlayer(kotipaikkaT, getKotipaikkaType(tm)); a.addPlayer(henkiloT, getHenkiloType(tm)); if(maakuntaT != null) { a.addPlayer(maakuntaT, getMaakuntaType(tm)); } if(laaniT != null) { a.addPlayer(laaniT, getLaaniType(tm)); } } if(koontiT != null && henkiloT != null && vuosiT != null && hakemusluokkaT != null && paatosT != null && jasenT != null && summaT != null) { Association a = tm.createAssociation(getPaatosType(tm)); a.addPlayer(paatosT, getPaatosType(tm)); a.addPlayer(koontiT, getKoontiType(tm)); a.addPlayer(vuosiT, getVuosiType(tm)); a.addPlayer(jasenT, getJasenType(tm)); a.addPlayer(summaT, getSummaType(tm)); a.addPlayer(henkiloT, getHenkiloType(tm)); a.addPlayer(hakemusluokkaT, getHakemusluokkaType(tm)); } if(henkiloT != null && fix(tokens[HETU_COLUMN]) != null) { String hetu = fix(tokens[HETU_COLUMN]); if(hetu.length() == 5) hetu = "0"+hetu; if(hetu.length() == 6) { //String d = hetu.substring(0,2); //String m = hetu.substring(2,4); String y = hetu.substring(4,6); y = "19"+y; //Topic dT = getSynnyinPaivaTopic( d, tm ); //Topic mT = getSynnyinKuukausiTopic( m, tm ); Topic yT = getSynnyinVuosiTopic( y, tm ); if(yT != null) { Association a = tm.createAssociation(getSynnyinAikaType(tm)); //a.addPlayer(dT, getSynnyinPaivaType(tm)); //a.addPlayer(mT, getSynnyinKuukausiType(tm)); a.addPlayer(yT, getSynnyinVuosiType(tm)); a.addPlayer(henkiloT, getHenkiloType(tm)); } } } } else { log("Skipping row "+rowCounter); } setProgress(rowCounter++); line = breader.readLine(); } } catch(Exception e) { log(e); } log("Processed " + rowCounter + " rows."); return true; } public String fix(String str) { if(str != null) { str = str.trim(); if(str.startsWith("\"")) str = str.substring(1); if(str.endsWith("\"")) str = str.substring(0, str.length()-1); } return str; } // ------------------------------------------------------------------------- public Topic getWandoraType( TopicMap tm ) throws Exception { return ExtractHelper.getOrCreateTopic(TMBox.WANDORACLASS_SI, tm); } public Topic getApuRahatType( TopicMap tm ) throws Exception { return ExtractHelper.getOrCreateTopic(APURAHAT_SI, "Apurahat", getWandoraType(tm), tm); } public Topic getKoontiType( TopicMap tm ) throws Exception { return ExtractHelper.getOrCreateTopic(KOONTI_SI, "Koonti", getApuRahatType(tm), tm); } public Topic getHenkiloType( TopicMap tm ) throws Exception { return ExtractHelper.getOrCreateTopic(HENKILO_SI, "Henkil�", getApuRahatType(tm), tm); } public Topic getKieliType( TopicMap tm ) throws Exception { return ExtractHelper.getOrCreateTopic(KIELI_SI, "Kieli", getApuRahatType(tm), tm); } public Topic getSukupuoliType( TopicMap tm ) throws Exception { return ExtractHelper.getOrCreateTopic(SUKUPUOLI_SI, "Sukupuoli", getApuRahatType(tm), tm); } public Topic getVuosiType( TopicMap tm ) throws Exception { return ExtractHelper.getOrCreateTopic(VUOSI_SI, "Vuosi", getApuRahatType(tm), tm); } public Topic getHakemusluokkaType( TopicMap tm ) throws Exception { return ExtractHelper.getOrCreateTopic(HAKEMUSLUOKKA_SI, "Hakemusluokka", getApuRahatType(tm), tm); } public Topic getPaatosType( TopicMap tm ) throws Exception { return ExtractHelper.getOrCreateTopic(PAATOS_SI, "P��t�s", getApuRahatType(tm), tm); } public Topic getJasenType( TopicMap tm ) throws Exception { return ExtractHelper.getOrCreateTopic(JASEN_SI, "J�sen", getApuRahatType(tm), tm); } public Topic getSummaType( TopicMap tm ) throws Exception { return ExtractHelper.getOrCreateTopic(SUMMA_SI, "Summa", getApuRahatType(tm), tm); } public Topic getMaakuntaType( TopicMap tm ) throws Exception { return ExtractHelper.getOrCreateTopic(MAAKUNTA_SI, "Maakunta", getApuRahatType(tm), tm); } public Topic getLaaniType( TopicMap tm ) throws Exception { return ExtractHelper.getOrCreateTopic(LAANI_SI, "L��ni", getApuRahatType(tm), tm); } public Topic getKotipaikkaType( TopicMap tm ) throws Exception { return ExtractHelper.getOrCreateTopic(KOTIPAIKKA_SI, "Kotipaikka", getApuRahatType(tm), tm); } public Topic getSynnyinKuukausiType( TopicMap tm ) throws Exception { return ExtractHelper.getOrCreateTopic(SYNNYINKUUKAUSI_SI, "Synnyinkuukausi", getApuRahatType(tm), tm); } public Topic getSynnyinPaivaType( TopicMap tm ) throws Exception { return ExtractHelper.getOrCreateTopic(SYNNYINPAIVA_SI, "Synnyinp�iv�", getApuRahatType(tm), tm); } public Topic getSynnyinVuosiType( TopicMap tm ) throws Exception { return ExtractHelper.getOrCreateTopic(SYNNYINVUOSI_SI, "Synnyinvuosi", getApuRahatType(tm), tm); } public Topic getSynnyinAikaType( TopicMap tm ) throws Exception { return ExtractHelper.getOrCreateTopic(SYNNYINAIKA_SI, "Syntyma-aika", getApuRahatType(tm), tm); } // ------------------------------------------------------------------------- public Topic getKoontiTopic( String token, TopicMap tm ) throws Exception { return getATopic(token, KOONTI_SI, getKoontiType(tm), tm); } public Topic getHenkiloTopic( String hetu, String nimi, TopicMap tm ) throws Exception { Topic t = null; if(hetu != null) { if(hetu.length() == 5) hetu = "0"+hetu; t = getATopic(hetu, HENKILO_SI, getHenkiloType(tm), tm); if(t != null && nimi != null) { t.setBaseName(nimi); t.setDisplayName(LANG, nimi); } } return t; } public Topic getKieliTopic( String token, TopicMap tm ) throws Exception { return getATopic(token, KIELI_SI, getKieliType(tm), tm); } public Topic getSukupuoliTopic( String token, TopicMap tm ) throws Exception { return getATopic(token, SUKUPUOLI_SI, getSukupuoliType(tm), tm); } public Topic getVuosiTopic( String token, TopicMap tm ) throws Exception { return getATopic(token, VUOSI_SI, getVuosiType(tm), tm); } public Topic getHakemusluokkaTopic( String token, TopicMap tm ) throws Exception { return getATopic(token, HAKEMUSLUOKKA_SI, getHakemusluokkaType(tm), tm); } public Topic getPaatosTopic( String token, TopicMap tm ) throws Exception { return getATopic(token, PAATOS_SI, getPaatosType(tm), tm); } public Topic getJasenTopic( String token, TopicMap tm ) throws Exception { return getATopic(token, JASEN_SI, getJasenType(tm), tm); } public Topic getSummaTopic( String token, TopicMap tm ) throws Exception { return getATopic(token, SUMMA_SI, getSummaType(tm), tm); } public Topic getMaakuntaTopic( String token, TopicMap tm ) throws Exception { return getATopic(token, MAAKUNTA_SI, getMaakuntaType(tm), tm); } public Topic getLaaniTopic( String token, TopicMap tm ) throws Exception { return getATopic(token, LAANI_SI, getLaaniType(tm), tm); } public Topic getKotipaikkaTopic( String token, TopicMap tm ) throws Exception { return getATopic(token, KOTIPAIKKA_SI, getKotipaikkaType(tm), tm); } public Topic getSynnyinVuosiTopic( String token, TopicMap tm ) throws Exception { return getATopic(token, SYNNYINVUOSI_SI, getSynnyinVuosiType(tm), tm); } public Topic getSynnyinPaivaTopic( String token, TopicMap tm ) throws Exception { return getATopic(token, SYNNYINPAIVA_SI, getSynnyinPaivaType(tm), tm); } public Topic getSynnyinKuukausiTopic( String token, TopicMap tm ) throws Exception { return getATopic(token, SYNNYINKUUKAUSI_SI, getSynnyinKuukausiType(tm), tm); } private Topic getATopic(String str, String si, Topic type, TopicMap tm) throws TopicMapException { if(str != null && si != null) { str = str.trim(); if(str.length() > 0) { Topic topic=ExtractHelper.getOrCreateTopic(si+"/"+urlEncode(str), str, tm); if(type != null) topic.addType(type); return topic; } } return null; } public Topic getOrCreateTopic(TopicMap tm, String si) { return getOrCreateTopic(tm, new Locator(si)); } public Topic getOrCreateTopic(TopicMap tm, Locator si) { Topic topic = null; try { topic = tm.getTopic(si); if(topic == null) { topic = tm.createTopic(); topic.addSubjectIdentifier(si); } } catch(Exception e) { log(e); } return topic; } }
19,164
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AsuntojenHintaTiedotExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/hsopen/AsuntojenHintaTiedotExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.hsopen; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.wandora.utils.IObox; /** * * @author akivela */ public class AsuntojenHintaTiedotExtractor { public AsuntojenHintaTiedotExtractor() { } public static void scrapeData() { int p = 100; int pend = 1000; String ubody = "http://asuntojen.hintatiedot.fi/haku/?p=__p__&z=__z__"; String saveFolder = "G:/hsopen3/asuntojen_hintatiedot_111011"; for(int i=p; i<pend; i=i+10) { int z = 1; boolean nextPage = false; do { System.out.println("Scraping "+i+" and page "+z+"."); String u = ubody.replace("__p__", ""+i); u = u.replace("__z__", ""+z); try { URL url = new URL(u); String c = IObox.doUrl(url); IObox.saveFile(saveFolder+"/"+i+"_"+z+".html", c); if(c.indexOf("seuraava sivu") != -1) { nextPage = true; } else { nextPage = false; } z++; } catch(Exception e) { e.printStackTrace(); } try { Thread.sleep(200); } catch(Exception e) { // DO NOTHING, JUST WOKE UP } } while(nextPage); } } public static void scrapeData2() { String loadFolder = "G:/hsopen3/asuntojen_hintatiedot_111011"; String saveFile = "G:/asuntojen_hintatiedot_111011.txt"; StringBuilder sb = new StringBuilder(""); File[] files = IObox.getFiles(loadFolder); System.out.println("Found total "+files.length+" files."); for(int i=0; i<files.length; i++) { try { String c = IObox.loadFile(files[i]); int index = c.indexOf("<table id=\"mainTable\">"); if(index > 0) c = c.substring(index); index = c.indexOf("<div id=\"footer\">"); if(index > 0) c = c.substring(0, index); c = c.replace("&#228;", "�"); c = c.replace("&#246;", "�"); c = c.replace("&#160;", " "); c = c.replace("&#196;", "�"); String pn = files[i].getName(); int pni = pn.indexOf("_"); pn = pn.substring(0,pni); //System.out.println("-----------------------------"); //System.out.println(c); //System.out.println("-----------------------------"); Pattern p = Pattern.compile( "<tr(?:\\sclass\\=\\\"last\\\")?>\\s*?"+ "<td>"+ "(.*?)"+ // Kaupungin osa "<\\/td>\\s*?"+ "<td>"+ "(.*?)"+ // Huoneet "<\\/td>\\s*?"+ "<td>"+ "(.*?)"+ // Neli�t "<\\/td>\\s*?"+ "<td>"+ "(.*?)"+ // Hinta "<\\/td>\\s*?"+ "<td>"+ "(.*?)"+ // Neli�hinta "<\\/td>\\s*?"+ "<td>"+ "(.*?)"+ // Rak. vuosi "<\\/td>\\s*?"+ "<td>"+ "(.*?)"+ // Kerros "<\\/td>\\s*?"+ "<td>"+ "(.*?)"+ // Hissi "<\\/td>\\s*?"+ "<td>"+ "(.*?)"+ // Kunto "<\\/td>\\s*?"+ "<\\/tr>", Pattern.MULTILINE); Matcher m = p.matcher(c); int fp = 0; while(m.find(fp)) { String kpginOsa = m.group(1); String huoneet = m.group(2); String neliot = m.group(3); String hinta = m.group(4); String nelioHinta = m.group(5); String rakVuosi = m.group(6); String kerros = m.group(7); String hissi = m.group(8); String kunto = m.group(9); System.out.print( kpginOsa + " - " ); System.out.print( huoneet + " - " ); System.out.print( neliot + " - " ); System.out.print( hinta + " - " ); System.out.print( nelioHinta + " - " ); System.out.print( rakVuosi + " - " ); System.out.print( kerros + " - " ); System.out.print( hissi + " - " ); System.out.println( kunto + " - " ); sb.append(files[i].getName()).append( "\t"); sb.append(pn).append( "\t"); sb.append(kpginOsa).append( "\t"); sb.append(huoneet).append( "\t"); sb.append(neliot).append( "\t"); sb.append(hinta).append( "\t"); sb.append(nelioHinta).append( "\t"); sb.append(rakVuosi).append( "\t"); sb.append(kerros).append( "\t"); sb.append(hissi).append( "\t"); sb.append(kunto).append( "\n"); fp = m.end(); } } catch(Exception e) { e.printStackTrace(); } } try { IObox.saveFile(saveFile, sb.toString()); } catch(Exception e) { e.printStackTrace(); } } public static void calcData() { String ilmoituksetFilename = "C:/Users/akivela/Desktop/Projects/hsopen3/ilmoitukset.txt"; String myydytFilename = "C:/Users/akivela/Desktop/Projects/hsopen3/myydyt.txt"; String outputFile = "C:/Users/akivela/Desktop/Projects/hsopen3/results.txt"; StringBuilder sb = new StringBuilder(""); try { String ilmoituksetRaw = IObox.loadFile(new File(ilmoituksetFilename)); String myydytRaw = IObox.loadFile(new File(myydytFilename)); String[] ilmoituksetArray = ilmoituksetRaw.split("\n"); String[] myydytArray = myydytRaw.split("\n"); System.out.println(ilmoituksetArray.length + " ilmoitusta."); System.out.println(myydytArray.length + " myyntia."); HashMap<String,ArrayList<String[]>> ilmoituksetHash = new HashMap<>(); HashMap<String,ArrayList<String[]>> myydytHash = new HashMap<>(); for(String ilmo : ilmoituksetArray) { String[] ilmoParts = ilmo.split("\t"); String pno = ilmoParts[1]; ArrayList<String[]> pnoIlmos = ilmoituksetHash.get(pno); if(pnoIlmos == null) { pnoIlmos = new ArrayList<>(); } pnoIlmos.add(ilmoParts); ilmoituksetHash.put(pno, pnoIlmos); } for(String myydyt : myydytArray) { String[] myydytParts = myydyt.split("\t"); String pno = myydytParts[1]; ArrayList<String[]> pnoMyydyt = myydytHash.get(pno); if(pnoMyydyt == null) { pnoMyydyt = new ArrayList<>(); } pnoMyydyt.add(myydytParts); myydytHash.put(pno, pnoMyydyt); } // **** calculate **** for(String pno : ilmoituksetHash.keySet()) { if(!"100".equals(pno)) continue; System.out.println("--------------------"); ArrayList<String[]> iArray = ilmoituksetHash.get(pno); ArrayList<String[]> mArray = myydytHash.get(pno); int countI = 0; double hintaTotalI = 0; double nelioHintaTotalI = 0; if(iArray != null) { for(Object i : iArray) { String[] is = (String[]) i; double neliot = asNumber(is[3]); double hinta = asNumber(is[4]); double nelioHinta = neliot != 0 ? hinta / neliot : 0; hintaTotalI += hinta; nelioHintaTotalI += nelioHinta; countI++; } } System.out.println(pno+" kohteitaI="+countI); double keskiarvoHintaI = countI != 0 ? hintaTotalI / countI : 0; double keskiarvoNelioHintaI = countI != 0 ? nelioHintaTotalI / countI : 0; System.out.println(pno+" keskiarvoHintaI="+keskiarvoHintaI); System.out.println(pno+" keskiarvoNelioHintaI="+keskiarvoNelioHintaI); int countM = 0; double hintaTotalM = 0; double nelioHintaTotalM = 0; if(mArray != null) { for(Object m : mArray) { String[] ms = (String[]) m; double neliot = asNumber(ms[4]); double hinta = asNumber(ms[5]); double nelioHinta = neliot != 0 ? hinta / neliot : 0; hintaTotalM += hinta; nelioHintaTotalM += nelioHinta; countM++; } } System.out.println(pno+" kohteitaM="+countM); double keskiarvoHintaM = countM != 0 ? hintaTotalM / countM : 0; double keskiarvoNelioHintaM = countM != 0 ? nelioHintaTotalM / countM : 0; System.out.println(pno+" keskiarvoHintaM="+keskiarvoHintaM); System.out.println(pno+" keskiarvoNelioHintaM="+keskiarvoNelioHintaM); double hintaJousto = keskiarvoHintaI - keskiarvoHintaM; double nelioHintaJousto = keskiarvoNelioHintaI - keskiarvoNelioHintaM; System.out.println(pno+" hintaJousto="+hintaJousto); System.out.println(pno+" nelioHintaJousto="+nelioHintaJousto); sb.append(pno).append("\t"); sb.append(countI).append("\t"); sb.append(countM).append("\t"); sb.append(keskiarvoHintaI).append("\t"); sb.append(keskiarvoHintaM).append("\t"); sb.append(keskiarvoNelioHintaI).append("\t"); sb.append(keskiarvoNelioHintaM).append("\t"); sb.append(hintaJousto).append("\t"); sb.append(nelioHintaJousto).append("\t"); sb.append("\n"); } IObox.saveFile(outputFile, sb.toString()); } catch(Exception e) { e.printStackTrace(); } } public static float asNumber(String str) { float r = 0; try { str.replace(',', '.'); r = Float.parseFloat(str); } catch(Exception e) {} return r; } // ------------------------------------------------------------------------- public static void main(String[] args) { //AsuntojenHintaTiedotExtractor.scrapeData2(); //AsuntojenHintaTiedotExtractor.calcData(); //AsuntojenHintaTiedotExtractor.scrapeData(); } }
13,084
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AlbumInfoExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/audioscrobbler/AlbumInfoExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * AlbumInfoExtractor.java * * Created on 13. toukokuuta 2007, 19:20 * */ 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 Album Info feed. Example * of Album Info is found at * * http://ws.audioscrobbler.com/1.0/album/Metallica/Metallica/info.xml * * Audioscrobbler's web api documentation is found at * * http://www.audioscrobbler.net/data/webservices/ * * @author akivela */ public class AlbumInfoExtractor extends AbstractAudioScrobblerExtractor { private static final long serialVersionUID = 1L; /** Creates a new instance of AlbumInfoExtractor */ public AlbumInfoExtractor() { } @Override public String getName() { return "Audioscrobbler Album: Info extractor"; } @Override public String getDescription(){ return "Extractor reads the Album Info XML feed from Audioscrobbler's web api and converts the XML feed to a topic map. "+ "See http://ws.audioscrobbler.com/1.0/album/Metallica/Metallica/info.xml for an example of Album Info 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(); AlbumInfoParser parserHandler = new AlbumInfoParser(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 + " tracks found!"); return true; } private static class AlbumInfoParser implements org.xml.sax.ContentHandler, org.xml.sax.ErrorHandler { public AlbumInfoParser(TopicMap tm, AlbumInfoExtractor parent){ this.tm=tm; this.parent=parent; } public int progress=0; private TopicMap tm; private AlbumInfoExtractor parent; public static final String TAG_ALBUM="album"; public static final String TAG_REACH="reach"; public static final String TAG_URL="url"; 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"; public static final String TAG_MBID="mbid"; public static final String TAG_RELEASEDATE="releasedate"; public static final String TAG_TRACKS="tracks"; public static final String TAG_TRACK="track"; private static final int STATE_START=0; private static final int STATE_ALBUM=2; private static final int STATE_ALBUM_MBID=4; private static final int STATE_ALBUM_REACH=5; private static final int STATE_ALBUM_URL=6; private static final int STATE_ALBUM_RELEASEDATE=7; 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 static final int STATE_TRACKS=12; private static final int STATE_TRACK=13; private static final int STATE_TRACK_REACH=14; private static final int STATE_TRACK_URL=15; private int state=STATE_START; private String data_album_reach; private String data_album_mbid; private String data_album_url; private String data_album_releasedate; private String data_album_coverart_large; private String data_album_coverart_medium; private String data_album_coverart_small; private String data_track; private String data_track_url; private String data_track_reach; private Topic theArtist; private Topic theAlbum; private int trackIndex = 0; private String theArtistString = null; private String theAlbumString = 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_ALBUM)) { state = STATE_ALBUM; theArtistString = atts.getValue("artist"); theAlbumString = atts.getValue("title"); if(theArtistString != null && theAlbumString != null) { try { theArtist = getArtistTopic(tm, theArtistString); theAlbum = getAlbumTopic(tm, theAlbumString, theArtistString); Topic albumType = getAlbumTypeTopic(tm); Topic artistType = getArtistTypeTopic(tm); Association a = tm.createAssociation(albumType); a.addPlayer(theAlbum, albumType); a.addPlayer(theArtist, artistType); } catch(Exception e) { parent.log(e); } } } break; case STATE_ALBUM: if(qName.equals(TAG_REACH)) { state = STATE_ALBUM_REACH; data_album_reach = ""; } else if(qName.equals(TAG_URL)) { state = STATE_ALBUM_URL; data_album_url = ""; } else if(qName.equals(TAG_RELEASEDATE)) { state = STATE_ALBUM_RELEASEDATE; data_album_releasedate = ""; } else if(qName.equals(TAG_MBID)) { state = STATE_ALBUM_MBID; data_album_mbid = ""; } else if(qName.equals(TAG_TRACKS)) { state = STATE_TRACKS; data_album_mbid = ""; } else if(qName.equals(TAG_COVERART)) { data_album_coverart_small = ""; data_album_coverart_medium = ""; data_album_coverart_large = ""; state = STATE_ALBUM_COVERART; } 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; case STATE_TRACKS: if(qName.equals(TAG_TRACK)) { data_track = atts.getValue("title"); data_track_reach = ""; data_track_url = ""; state = STATE_TRACK; } break; case STATE_TRACK: if(qName.equals(TAG_REACH)) { state = STATE_TRACK_REACH; data_track_reach = ""; } else if(qName.equals(TAG_URL)) { state = STATE_TRACK_URL; data_track_url = ""; } break; } } public void endElement(String uri, String localName, String qName) throws SAXException { switch(state) { case STATE_TRACK: { if(data_track.length() > 0) { try { Topic trackType=getTrackTypeTopic(tm); Topic trackTopic=getTrackTopic(tm, data_track, data_track_url, theAlbumString, theArtistString); try { ++trackIndex; Association ta=tm.createAssociation(trackType); parent.setProgress(++progress); Topic albumType = getAlbumTypeTopic(tm); ta.addPlayer(theAlbum, albumType); ta.addPlayer(trackTopic, trackType); if(CONVERT_TRACK_INDEX) { Topic indexTopic = getIndexTopic(tm, trackIndex); Topic indexType = getIndexTypeTopic(tm); ta.addPlayer(indexTopic, indexType); } if(CONVERT_REACH && data_track_reach.length() > 0) { Topic reachTopic = getReachTopic(tm, data_track_reach); Topic reachType = getReachTypeTopic(tm); ta.addPlayer(reachTopic, reachType); } } catch(Exception e) { parent.log(e); } } catch(TopicMapException tme){ parent.log(tme); } } state=STATE_TRACKS; break; } case STATE_TRACK_REACH: { state=STATE_TRACK; break; } case STATE_TRACK_URL: { state=STATE_TRACK; break; } // --- Closing album's inner --- case STATE_ALBUM_COVERART: { if(theAlbum != null) { 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 image = getImageTopic(tm, data_album_coverart, "album "+theAlbumString); Topic albumType = getAlbumTypeTopic(tm); Topic imageType = getImageTypeTopic(tm); Association imagea = tm.createAssociation(imageType); imagea.addPlayer(image, imageType); imagea.addPlayer(theAlbum, albumType); } catch(Exception e) { parent.log(e); } } } state=STATE_ALBUM; break; } case STATE_ALBUM_URL: { if(theAlbum != null && data_album_url.length() > 0) { try { theAlbum.addSubjectIdentifier(tm.createLocator(data_album_url)); } catch(Exception e) { parent.log(e); } } state=STATE_ALBUM; break; } case STATE_ALBUM_REACH: { // DO NOTHING AT THE MOMENT state=STATE_ALBUM; break; } case STATE_ALBUM_RELEASEDATE: { if(theAlbum != null && data_album_releasedate != null) { data_album_releasedate = data_album_releasedate.trim(); if(data_album_releasedate.length() > 0) { try { Topic releasedateType = getOrCreateTopic(tm, RELEASEDATE_SI, "Release date"); parent.setData(theAlbum, releasedateType, LANG, data_album_releasedate); } catch(Exception e) { parent.log(e); } } } state=STATE_ALBUM; break; } case STATE_ALBUM_MBID: { if(theAlbum != null && data_album_mbid.length() > 0) { try { theAlbum.addSubjectIdentifier(tm.createLocator(MBID_SI + "/" + data_album_mbid)); } catch(Exception e) { parent.log(e); } } state=STATE_ALBUM; break; } case STATE_TRACKS: { state=STATE_ALBUM; 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_TRACK_REACH: data_track_reach+=new String(ch,start,length); break; case STATE_TRACK_URL: data_track_url+=new String(ch,start,length); break; case STATE_ALBUM_MBID: data_album_mbid+=new String(ch,start,length); break; case STATE_ALBUM_REACH: data_album_reach+=new String(ch,start,length); break; case STATE_ALBUM_URL: data_album_url+=new String(ch,start,length); break; case STATE_ALBUM_RELEASEDATE: data_album_releasedate+=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 {} } }
18,916
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ArtistTopTagsExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/audioscrobbler/ArtistTopTagsExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * TopTagsExtractor.java * * Created on 12. toukokuuta 2007, 12: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 Tags feed. Example * of Top Tags is found at * * http://ws.audioscrobbler.com/1.0/artist/Metallica/toptags.xml * * Audioscrobber's web api documentation is found at * * http://www.audioscrobbler.net/data/webservices/ * * @author akivela */ public class ArtistTopTagsExtractor extends AbstractAudioScrobblerExtractor { private static final long serialVersionUID = 1L; /** Creates a new instance of ArtistTopTagsExtractor */ public ArtistTopTagsExtractor() { } @Override public String getName() { return "Audioscrobbler Artists: 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/artist/Metallica/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(); ArtistTopTagsParser parserHandler = new ArtistTopTagsParser(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 with nonzero count found!"); return true; } private static class ArtistTopTagsParser implements org.xml.sax.ContentHandler, org.xml.sax.ErrorHandler { public ArtistTopTagsParser(TopicMap tm,ArtistTopTagsExtractor parent){ this.tm=tm; this.parent=parent; } public int progress=0; private TopicMap tm; private ArtistTopTagsExtractor parent; public static final String TAG_TOPTAGS="toptags"; public static final String TAG_TAG="tag"; public static final String TAG_NAME="name"; public static final String TAG_COUNT="count"; public static final String TAG_URL="url"; private static final int STATE_START=0; private static final int STATE_TOPTAGS=1; private static final int STATE_TAG=2; private static final int STATE_NAME=3; private static final int STATE_COUNT=4; private static final int STATE_URL=5; private int state=STATE_START; private String data_artist = ""; private String data_tag_name = ""; private String data_tag_count = ""; private String data_tag_url = ""; 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_TOPTAGS)) { state = STATE_TOPTAGS; String theArtistString = atts.getValue("artist"); if(theArtistString != null) { try { theArtist=getArtistTopic(tm, theArtistString); } catch(Exception e) { parent.log(e); } } } break; case STATE_TOPTAGS: if(qName.equals(TAG_TAG)) { state = STATE_TAG; data_tag_name = ""; data_tag_count = ""; data_tag_url = ""; } break; case STATE_TAG: if(qName.equals(TAG_NAME)) { state = STATE_NAME; data_tag_name = ""; } else if(qName.equals(TAG_COUNT)) { state = STATE_COUNT; data_tag_count = ""; } else if(qName.equals(TAG_URL)) { state = STATE_URL; data_tag_url = ""; } break; } } public void endElement(String uri, String localName, String qName) throws SAXException { switch(state) { case STATE_TAG: { if(data_tag_name.length() > 0) { try { Topic tagType=getTagTypeTopic(tm); Topic tagTopic=getTagTopic(tm, data_tag_name, data_tag_url); if(theArtist != null) { Topic artistType = getArtistTypeTopic(tm); Association ta=tm.createAssociation(tagType); ta.addPlayer(theArtist, artistType); ta.addPlayer(tagTopic, tagType); parent.setProgress(++progress); if(CONVERT_COUNTS && data_tag_count.length() > 0) { try { int count = Integer.parseInt(data_tag_count); if(count > 0) { try { Topic countTopic = getCountTopic(tm, data_tag_count); Topic countType = getCountTypeTopic(tm); ta.addPlayer(countTopic, countType); } catch(Exception e) { parent.log(e); } } } catch(Exception e) { // PASS THIS EXCEPTION. PARSEINT FAILED. OK! } } } } catch(TopicMapException tme){ parent.log(tme); } } state=STATE_TOPTAGS; break; } case STATE_NAME: { state=STATE_TAG; break; } case STATE_COUNT: { state=STATE_TAG; break; } case STATE_URL: { state=STATE_TAG; break; } } } public void characters(char[] ch, int start, int length) throws SAXException { switch(state){ case STATE_NAME: data_tag_name+=new String(ch,start,length); break; case STATE_COUNT: data_tag_count+=new String(ch,start,length); break; case STATE_URL: data_tag_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,576
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z