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
AtomExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/AtomExtractor.java
/* * WANDORA - Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * AtomExtractor.java * * Created on 28. marraskuuta 2008, 13:18 * */ package org.wandora.application.tools.extractors; 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.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.Icon; import org.wandora.application.Wandora; import org.wandora.application.gui.UIBox; import org.wandora.application.tools.browserextractors.BrowserExtractRequest; import org.wandora.application.tools.browserextractors.BrowserPluginExtractor; import org.wandora.topicmap.Association; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicTools; import org.wandora.topicmap.XTMPSI; import org.wandora.utils.HTMLEntitiesCoder; 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; /** * http://www.atomenabled.org/developers/syndication/ * * @author akivela */ public class AtomExtractor extends AbstractExtractor { private static final long serialVersionUID = 1L; public static final String DEFAULT_LANG = "en"; private String baseUrl = null; /** Creates a new instance of AtomExtractor */ public AtomExtractor() { } @Override public String getName() { return "Atom Extractor"; } @Override public String getDescription(){ return "Extractor reads Atom news feed and converts the feed to a topic map."; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_atom.png"); } private final String[] contentTypes=new String[] { "text/xml", "application/xml", "application/atom+xml", "application/xhtml+xml" }; @Override public String[] getContentTypes() { return contentTypes; } @Override public boolean useURLCrawler() { return false; } public boolean _extractTopicsFrom(URL url, TopicMap topicMap) throws Exception { baseUrl = solveBaseUrl(url.toExternalForm()); boolean answer = _extractTopicsFrom(url.openStream(), topicMap); baseUrl = null; return answer; } public boolean _extractTopicsFrom(File file, TopicMap topicMap) throws Exception { baseUrl = solveBaseUrl(file.toURI().toURL().toExternalForm()); boolean answer = _extractTopicsFrom(new FileInputStream(file), topicMap); baseUrl = null; return answer; } public boolean _extractTopicsFrom(String str, TopicMap topicMap) throws Exception { boolean answer = _extractTopicsFrom(new ByteArrayInputStream(str.getBytes()), topicMap); baseUrl = null; 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(); AtomParser parserHandler = new AtomParser(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.entryCount + " Atom entries processed!"); baseUrl = null; return true; } private String solveBaseUrl(String url) { if(url != null) { int index = url.lastIndexOf('/'); if(index > 0) { url = url.substring(0, index); } } return url; } @Override public String doBrowserExtract(BrowserExtractRequest request, Wandora wandora) throws TopicMapException { try { setWandora(wandora); String urlstr = request.getSource(); // System.out.println("FOUND URL: "+urlstr); URL url = new URL(urlstr); URLConnection uc = url.openConnection(); String type = uc.getContentType(); // System.out.println("FOUND TYPE: "+type); if(type != null && type.indexOf("text/html") > -1) { String htmlContent = IObox.doUrl(url); Pattern p1 = Pattern.compile("\\<link [^\\>]+\\>"); Pattern p2 = Pattern.compile("href\\=\"([^\"]+)\""); Matcher m1 = p1.matcher(htmlContent); int sp = 0; while(m1.find(sp)) { String linktag = m1.group(); if(linktag != null && linktag.length() > 0) { if(linktag.indexOf("application/atom+xml") > -1) { Matcher m2 = p2.matcher(linktag); if(m2.find()) { try { String atomfeed = m2.group(1); _extractTopicsFrom(new URL(atomfeed), wandora.getTopicMap()); } catch(Exception e) { e.printStackTrace(); } } } } sp = m1.end(); } wandora.doRefresh(); return null; } else if(type != null && type.indexOf("application/atom+xml") > -1) { _extractTopicsFrom(url, wandora.getTopicMap()); wandora.doRefresh(); return null; } else { return BrowserPluginExtractor.RETURN_ERROR + "Couldn't solve browser extractor content. Nothing extracted."; } } catch(Exception e){ e.printStackTrace(); return BrowserPluginExtractor.RETURN_ERROR+e.getMessage(); } } /* ---------------------------------------------------------------------- */ private class AtomParser implements org.xml.sax.ContentHandler, org.xml.sax.ErrorHandler { public boolean MAKE_LINK_SUBJECT_LOCATOR = false; public boolean MAKE_SUBCLASS_OF_WANDORA_CLASS = true; public AtomParser(TopicMap tm, AtomExtractor parent){ this.tm=tm; this.parent=parent; } public int progress=0; public int entryCount = 0; public int feedCount = 0; private TopicMap tm; private AtomExtractor parent; public static final String TAG_FEED="feed"; public static final String TAG_TITLE="title"; public static final String TAG_LINK="link"; public static final String TAG_UPDATED="updated"; public static final String TAG_AUTHOR="author"; public static final String TAG_NAME="name"; public static final String TAG_EMAIL="email"; public static final String TAG_URI="uri"; public static final String TAG_ID="id"; public static final String TAG_ENTRY="entry"; public static final String TAG_SUMMARY="summary"; public static final String TAG_CATEGORY="category"; public static final String TAG_CONTRIBUTOR="contributor"; public static final String TAG_GENERATOR="generator"; public static final String TAG_ICON="icon"; public static final String TAG_LOGO="logo"; public static final String TAG_RIGHTS="rights"; public static final String TAG_SUBTITLE="subtitle"; public static final String TAG_CONTENT="content"; public static final String TAG_PUBLISHED="published"; public static final String TAG_SOURCE="source"; private static final int STATE_START=0; private static final int STATE_FEED=2; private static final int STATE_FEED_TITLE=4; private static final int STATE_FEED_LINK=5; private static final int STATE_FEED_UPDATED=6; private static final int STATE_FEED_AUTHOR=7; private static final int STATE_FEED_AUTHOR_NAME=71; private static final int STATE_FEED_AUTHOR_URI=72; private static final int STATE_FEED_AUTHOR_EMAIL=73; private static final int STATE_FEED_ID=8; private static final int STATE_FEED_CATEGORY=9; private static final int STATE_FEED_GENERATOR=15; private static final int STATE_FEED_CONTRIBUTOR=10; private static final int STATE_FEED_CONTRIBUTOR_NAME=101; private static final int STATE_FEED_CONTRIBUTOR_EMAIL=102; private static final int STATE_FEED_CONTRIBUTOR_URI=103; private static final int STATE_FEED_ICON=11; private static final int STATE_FEED_LOGO=12; private static final int STATE_FEED_RIGHTS=13; private static final int STATE_FEED_SUBTITLE=14; private static final int STATE_FEED_ENTRY = 1000; private static final int STATE_FEED_ENTRY_ID = 1001; private static final int STATE_FEED_ENTRY_TITLE = 1002; private static final int STATE_FEED_ENTRY_UPDATED = 1003; private static final int STATE_FEED_ENTRY_AUTHOR = 1004; private static final int STATE_FEED_ENTRY_AUTHOR_NAME = 10041; private static final int STATE_FEED_ENTRY_AUTHOR_EMAIL = 10042; private static final int STATE_FEED_ENTRY_AUTHOR_URI = 10043; private static final int STATE_FEED_ENTRY_CONTENT = 1005; private static final int STATE_FEED_ENTRY_LINK = 1006; private static final int STATE_FEED_ENTRY_SUMMARY = 1007; private static final int STATE_FEED_ENTRY_CATEGORY=1008; private static final int STATE_FEED_ENTRY_CONTRIBUTOR=1009; private static final int STATE_FEED_ENTRY_CONTRIBUTOR_NAME=10091; private static final int STATE_FEED_ENTRY_CONTRIBUTOR_EMAIL=10092; private static final int STATE_FEED_ENTRY_CONTRIBUTOR_URI=10093; private static final int STATE_FEED_ENTRY_PUBLISHED = 1010; private static final int STATE_FEED_ENTRY_SOURCE = 1011; private static final int STATE_FEED_ENTRY_SOURCE_ID = 10111; private static final int STATE_FEED_ENTRY_SOURCE_TITLE = 10112; private static final int STATE_FEED_ENTRY_SOURCE_UPDATED = 10113; private static final int STATE_FEED_ENTRY_SOURCE_RIGHTS = 10114; private static final int STATE_FEED_ENTRY_RIGHTS = 1012; private int state=STATE_START; public String ATOMSI = "http://www.w3.org/2005/Atom/"; public String SIPREFIX="http://www.w3.org/2005/Atom/"; public String FEED_ID_SI=SIPREFIX+"id"; public String FEED_SI=SIPREFIX+"channel"; public String FEED_UPDATED_SI=SIPREFIX+"updated"; public String FEED_AUTHOR_SI=SIPREFIX+"author"; public String FEED_CONTRIBUTOR_SI=SIPREFIX+"contributor"; public String FEED_CATEGORY_SI=SIPREFIX+"category"; public String FEED_SUBTITLE_SI=SIPREFIX+"subtitle"; public String EMAIL_ADDRESS_SI=SIPREFIX+"email"; public String SCHEME_SI=SIPREFIX+"scheme"; public String FEED_LINK_SI=FEED_SI+"/link"; public String FEED_GENERATOR_SI=FEED_SI+"/generator"; public String FEED_GENERATOR_URI_SI=FEED_SI+"/generator-uri"; public String FEED_GENERATOR_VERSION_SI=FEED_SI+"/generator-version"; public String FEED_RIGHTS_SI=FEED_SI+"/rights"; public String FEED_ICON_SI=FEED_SI+"/icon"; public String FEED_LOGO_SI=FEED_SI+"/logo"; public String FEED_ENTRY_SI=FEED_SI+"/entry"; public String FEED_ENTRY_ID_SI=FEED_ENTRY_SI+"/id"; public String FEED_ENTRY_TITLE_SI=FEED_ENTRY_SI+"/title"; public String FEED_ENTRY_LINK_SI=FEED_ENTRY_SI+"/link"; public String FEED_ENTRY_CONTRIBUTOR_SI=FEED_ENTRY_SI+"/contributor"; public String FEED_ENTRY_SUMMARY_SI=FEED_ENTRY_SI+"/summary"; public String FEED_ENTRY_CONTENT_SI=FEED_ENTRY_SI+"/content"; public String FEED_ENTRY_PUBLISHED_SI=FEED_ENTRY_SI+"/published"; public String FEED_ENTRY_UPDATED_SI=FEED_ENTRY_SI+"/updated"; public String FEED_ENTRY_CATEGORY_SI=FEED_ENTRY_SI+"/category"; public String FEED_ENTRY_AUTHOR_SI=FEED_ENTRY_SI+"/author"; public String FEED_ENTRY_RIGHTS_SI=FEED_ENTRY_SI+"/rights"; public String FEED_ENTRY_SOURCE_SI=FEED_ENTRY_SI+"/source"; public String LINK_HREF_SI=SIPREFIX+"link/href"; public String LINK_REL_SI=SIPREFIX+"link/rel"; public String LINK_TYPE_SI=SIPREFIX+"link/type"; public String LINK_HREF_LANG_SI=SIPREFIX+"link/href-lang"; public String DATE_SI="http://wandora.org/si/date"; public String RIGHTS_SI="http://wandora.org/si/rights"; public String LINK_SI="http://wandora.org/si/link"; private String data_feed_id; private String data_feed_title; private String data_feed_title_type; private Link data_feed_link; private String data_feed_updated; private String data_feed_author_name; private String data_feed_author_uri; private String data_feed_author_email; private Category data_feed_category; private String data_feed_contributor_name; private String data_feed_contributor_uri; private String data_feed_contributor_email; private String data_feed_generator; private String data_feed_generator_uri; private String data_feed_generator_version; private String data_feed_icon; private String data_feed_logo; private String data_feed_rights; private String data_feed_rights_type; private String data_feed_subtitle; private String data_feed_subtitle_type; private String data_entry_id; private String data_entry_title; private String data_entry_title_type; private String data_entry_updated; private String data_entry_published; private String data_entry_author_name; private String data_entry_author_uri; private String data_entry_author_email; private String data_entry_content; private String data_entry_content_type; private String data_entry_content_src; private Link data_entry_link; private String data_entry_summary; private String data_entry_summary_src; private String data_entry_summary_type; private Category data_entry_category; private String data_entry_contributor_name; private String data_entry_contributor_uri; private String data_entry_contributor_email; private String data_entry_source_id; private String data_entry_source_title; private String data_entry_source_updated; private String data_entry_source_rights; private String data_entry_source_rights_type; private String data_entry_rights; private String data_entry_rights_type; private Topic theFeed; private Topic theEntry; private org.wandora.topicmap.Locator theFeedSI = null; private org.wandora.topicmap.Locator theEntrySI = null; private Topic getOrCreateTopic(String si) throws TopicMapException { return getOrCreateTopic(si,null); } private Topic getOrCreateTopic(String si,String bn) throws TopicMapException { if(si!=null){ si = TopicTools.cleanDirtyLocator(si); Topic t=tm.getTopic(si); if(t==null){ t=tm.createTopic(); t.addSubjectIdentifier(tm.createLocator(si)); if(bn!=null) t.setBaseName(bn); } return t; } else{ Topic t=tm.getTopicWithBaseName(bn); if(t==null){ t=tm.createTopic(); t.setBaseName(bn); if(si!=null) t.addSubjectIdentifier(tm.createLocator(si)); else t.addSubjectIdentifier(tm.makeSubjectIndicatorAsLocator()); } return t; } } private Topic getFeedType() { try { return getOrCreateTopic(FEED_SI, "Atom Feed"); } catch(Exception e) { parent.log(e); } return null; } private Topic getEntryType() { try { return getOrCreateTopic(FEED_ENTRY_SI, "Atom Entry"); } catch(Exception e) { parent.log(e); } return null; } private Topic getDateType() { try { return getOrCreateTopic(DATE_SI, "Date"); } catch(Exception e) { parent.log(e); } return null; } private Topic getDateTopic(String d) { Topic dateTopic = null; try { dateTopic = tm.getTopic(DATE_SI+d); if(dateTopic == null) { dateTopic = tm.createTopic(); dateTopic.addSubjectIdentifier(new org.wandora.topicmap.Locator(DATE_SI+d)); dateTopic.setBaseName(d); dateTopic.setDisplayName(DEFAULT_LANG, d); dateTopic.addType(getDateType()); } } catch(Exception e) { parent.log(e); } return dateTopic; } private Topic getRightsType() { try { return getOrCreateTopic(RIGHTS_SI, "Rights"); } catch(Exception e) { parent.log(e); } return null; } private Topic getRightsTopic(String r) { Topic rightsTopic = null; try { rightsTopic = tm.getTopic(RIGHTS_SI+r); if(rightsTopic == null) { rightsTopic = tm.createTopic(); rightsTopic.addSubjectIdentifier(new org.wandora.topicmap.Locator(RIGHTS_SI+r)); rightsTopic.setBaseName(r); rightsTopic.setDisplayName(DEFAULT_LANG, r); rightsTopic.addType(getRightsType()); } } catch(Exception e) { parent.log(e); } return rightsTopic; } private Topic getLinkType() { try { return getOrCreateTopic(LINK_SI, "Atom Link"); } catch(Exception e) { parent.log(e); } return null; } private String makeUrl(String url) { if(url != null) { if( !url.matches("[a-zA-Z0-9]+\\:\\/\\/.*?") ) { if(parent.baseUrl != null) { if(!url.startsWith("/")) url = "/" + url; url = parent.baseUrl + url; } } } return url; } private void createLinkStruct(Link link, Topic player, Topic role) throws TopicMapException { String href = link.getHref(); if(link != null && isValid(href)) { Topic linkType = getLinkType(); Topic hrefTopic = getOrCreateTopic(makeUrl(href)); Topic hrefType = getOrCreateTopic(LINK_HREF_SI, "Atom Link Href"); if(isValid(link.getTitle())) { hrefTopic.setBaseName(link.getTitle()); hrefTopic.setDisplayName(DEFAULT_LANG, link.getTitle()); } Association linka = tm.createAssociation(linkType); linka.addPlayer(player, role); linka.addPlayer(hrefTopic, hrefType); if(isValid(link.getRel())) { Topic relTopic = getOrCreateTopic(link.getRel()); Topic relType = getOrCreateTopic(LINK_REL_SI, "Atom Link Rel"); linka.addPlayer(relTopic, relType); } if(isValid(link.getType())) { Topic hrefTypeTopic = getOrCreateTopic(LINK_TYPE_SI+"/"+link.getType(), link.getType()); hrefTopic.addType(hrefTypeTopic); } if(isValid(link.getHrefLang())) { Topic hrefLangType = getOrCreateTopic(LINK_HREF_LANG_SI, "Atom Link Href Lang"); Topic hrefLangTopic = getOrCreateTopic(LINK_HREF_LANG_SI+"/"+link.getHrefLang(), link.getHrefLang()); Association la = tm.createAssociation(hrefLangType); la.addPlayer(hrefLangTopic, hrefLangType); la.addPlayer(hrefTopic, hrefType); } } } private String postProcessFeedText(String txt, String type) { if(txt != null && type!=null && type.length()>0) { if("text".equals(type)) {} else if("html".equals(type)) { txt = HTMLEntitiesCoder.decode(txt); } else if("xhtml".equals(type)) { txt = txt.replaceAll("\\&lt\\;", "<"); txt = txt.replaceAll("\\&gt\\;", ">"); txt = txt.replaceAll("\\&amp\\;", "&"); } } return txt; } private boolean isValid(String str) { if(str == null || str.trim().length() == 0) return false; return true; } // --------------------------------------------------------------------- public void startDocument() throws SAXException { feedCount = 0; entryCount = 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_FEED)) { try { Topic feedType=getFeedType(); theFeed = tm.createTopic(); theFeedSI = TopicTools.createDefaultLocator(); theFeed.addSubjectIdentifier(theFeedSI); theFeed.addType(feedType); feedCount++; Topic atomClass = getOrCreateTopic(ATOMSI, "Atom"); Topic superClass = getOrCreateTopic(XTMPSI.SUPERCLASS); Topic subClass = getOrCreateTopic(XTMPSI.SUBCLASS); Topic supersubClass = getOrCreateTopic(XTMPSI.SUPERCLASS_SUBCLASS); Association supersubClassAssociation = tm.createAssociation(supersubClass); supersubClassAssociation.addPlayer(atomClass, superClass); supersubClassAssociation.addPlayer(feedType, 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(atomClass, subClass); } } catch(Exception e) { parent.log(e); } data_feed_id = ""; data_feed_title = ""; data_feed_title_type = ""; data_feed_updated = ""; data_feed_category = null; data_feed_link = null; data_feed_generator = ""; data_feed_icon = ""; data_feed_logo = ""; data_feed_rights = ""; data_feed_subtitle = ""; data_feed_subtitle_type = ""; state = STATE_FEED; } break; case STATE_FEED: if(qName.equals(TAG_TITLE)) { data_feed_title_type = atts.getValue("type"); data_feed_title = ""; state = STATE_FEED_TITLE; } else if(qName.equals(TAG_LINK)) { String href = atts.getValue("href"); String rel = atts.getValue("rel"); String type = atts.getValue("type"); String hreflang = atts.getValue("hreflang"); String title = atts.getValue("title"); String length = atts.getValue("length"); data_feed_link = new Link(href, rel, type, hreflang, title, length); state = STATE_FEED_LINK; } else if(qName.equals(TAG_UPDATED)) { data_feed_updated = ""; state = STATE_FEED_UPDATED; } else if(qName.equals(TAG_AUTHOR)) { data_feed_author_name = ""; data_feed_author_uri = ""; data_feed_author_email = ""; state = STATE_FEED_AUTHOR; } else if(qName.equals(TAG_ID)) { data_feed_id = ""; state = STATE_FEED_ID; } else if(qName.equals(TAG_CATEGORY)) { String term = atts.getValue("term"); String scheme = atts.getValue("scheme"); String label = atts.getValue("label"); data_feed_category = new Category(term, scheme, label); state = STATE_FEED_CATEGORY; } else if(qName.equals(TAG_CONTRIBUTOR)) { data_feed_contributor_name = ""; data_feed_contributor_uri = ""; data_feed_contributor_email = ""; state = STATE_FEED_CONTRIBUTOR; } else if(qName.equals(TAG_GENERATOR)) { data_feed_generator = ""; data_feed_generator_uri = atts.getValue("uri"); data_feed_generator_version = atts.getValue("version"); state = STATE_FEED_GENERATOR; } else if(qName.equals(TAG_ICON)) { data_feed_icon = ""; state = STATE_FEED_ICON; } else if(qName.equals(TAG_LOGO)) { data_feed_logo = ""; state = STATE_FEED_LOGO; } else if(qName.equals(TAG_RIGHTS)) { data_feed_rights = ""; data_feed_rights_type = atts.getValue("type"); state = STATE_FEED_RIGHTS; } else if(qName.equals(TAG_SUBTITLE)) { data_feed_subtitle_type = atts.getValue("type"); data_feed_subtitle = ""; state = STATE_FEED_SUBTITLE; } else if(qName.equals(TAG_ENTRY)) { try { Topic entryType=getEntryType(); theEntry = tm.createTopic(); theEntrySI = TopicTools.createDefaultLocator(); theEntry.addSubjectIdentifier(theEntrySI); theEntry.addType(entryType); entryCount++; parent.setProgress(entryCount); Topic atomClass = getOrCreateTopic(ATOMSI, "Atom"); Topic superClass = getOrCreateTopic(XTMPSI.SUPERCLASS); Topic subClass = getOrCreateTopic(XTMPSI.SUBCLASS); Topic supersubClass = getOrCreateTopic(XTMPSI.SUPERCLASS_SUBCLASS); Association supersubClassAssociation = tm.createAssociation(supersubClass); supersubClassAssociation.addPlayer(atomClass, superClass); supersubClassAssociation.addPlayer(entryType, 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(atomClass, subClass); } } catch(Exception e) { parent.log(e); } data_entry_id = ""; data_entry_title = ""; data_entry_title_type = ""; data_entry_updated = ""; data_entry_published = ""; data_entry_author_name = ""; data_entry_author_uri = ""; data_entry_author_email = ""; data_entry_content = ""; data_entry_content_type = ""; data_entry_content_src = ""; data_entry_link = null; data_entry_summary = ""; data_entry_summary_src = ""; data_entry_summary_type = ""; data_entry_category = null; data_entry_contributor_name = ""; data_entry_contributor_uri = ""; data_entry_contributor_email = ""; data_entry_source_id = ""; data_entry_source_title = ""; data_entry_source_updated = ""; data_entry_source_rights = ""; data_entry_source_rights_type = ""; data_entry_rights = ""; data_entry_rights_type = ""; state = STATE_FEED_ENTRY; } break; case STATE_FEED_AUTHOR: if(qName.equals(TAG_NAME)) { state = STATE_FEED_AUTHOR_NAME; data_feed_author_name = ""; } else if(qName.equals(TAG_URI)) { state = STATE_FEED_AUTHOR_URI; data_feed_author_uri = ""; } else if(qName.equals(TAG_EMAIL)) { state = STATE_FEED_AUTHOR_EMAIL; data_feed_author_email = ""; } break; case STATE_FEED_CONTRIBUTOR: if(qName.equals(TAG_NAME)) { state = STATE_FEED_CONTRIBUTOR_NAME; data_feed_contributor_name = ""; } else if(qName.equals(TAG_URI)) { state = STATE_FEED_CONTRIBUTOR_URI; data_feed_contributor_uri = ""; } else if(qName.equals(TAG_EMAIL)) { state = STATE_FEED_CONTRIBUTOR_EMAIL; data_feed_contributor_email = ""; } break; case STATE_FEED_ENTRY: if(qName.equals(TAG_ID)) { state = STATE_FEED_ENTRY_ID; data_entry_id = ""; } else if(qName.equals(TAG_TITLE)) { state = STATE_FEED_ENTRY_TITLE; data_entry_title = ""; data_entry_title_type = atts.getValue("type"); } else if(qName.equals(TAG_UPDATED)) { state = STATE_FEED_ENTRY_UPDATED; data_entry_updated = ""; } else if(qName.equals(TAG_AUTHOR)) { data_entry_author_name = ""; data_entry_author_uri = ""; data_entry_author_email = ""; state = STATE_FEED_ENTRY_AUTHOR; } else if(qName.equals(TAG_CONTENT)) { state = STATE_FEED_ENTRY_CONTENT; data_entry_content = ""; data_entry_content_src = atts.getValue("src"); data_entry_content_type = atts.getValue("type"); } else if(qName.equals(TAG_LINK)) { state = STATE_FEED_ENTRY_LINK; String href = atts.getValue("href"); String rel = atts.getValue("rel"); String type = atts.getValue("type"); String hreflang = atts.getValue("hreflang"); String title = atts.getValue("title"); String length = atts.getValue("length"); data_entry_link = new Link(href, rel, type, hreflang, title, length); } else if(qName.equals(TAG_SUMMARY)) { state = STATE_FEED_ENTRY_SUMMARY; data_entry_summary = ""; data_entry_summary_src = atts.getValue("src"); data_entry_summary_type = atts.getValue("type"); } else if(qName.equals(TAG_CATEGORY)) { state = STATE_FEED_ENTRY_CATEGORY; String term = atts.getValue("term"); String scheme = atts.getValue("scheme"); String label = atts.getValue("label"); data_entry_category = new Category(term, scheme, label); } else if(qName.equals(TAG_CONTRIBUTOR)) { state = STATE_FEED_ENTRY_CONTRIBUTOR; data_entry_contributor_name = ""; data_entry_contributor_email = ""; data_entry_contributor_uri = ""; } else if(qName.equals(TAG_PUBLISHED)) { state = STATE_FEED_ENTRY_PUBLISHED; data_entry_published = ""; } else if(qName.equals(TAG_SOURCE)) { state = STATE_FEED_ENTRY_SOURCE; data_entry_source_id = ""; data_entry_source_title = ""; data_entry_source_updated = ""; data_entry_source_rights = ""; data_entry_source_rights_type = ""; } else if(qName.equals(TAG_RIGHTS)) { state = STATE_FEED_ENTRY_RIGHTS; data_entry_rights = ""; data_entry_rights_type = atts.getValue("type"); } break; case STATE_FEED_ENTRY_AUTHOR: if(qName.equals(TAG_NAME)) { data_entry_author_name = ""; state = STATE_FEED_ENTRY_AUTHOR_NAME; } else if(qName.equals(TAG_URI)) { data_entry_author_uri = ""; state = STATE_FEED_ENTRY_AUTHOR_URI; } else if(qName.equals(TAG_EMAIL)) { data_entry_author_email = ""; state = STATE_FEED_ENTRY_AUTHOR_EMAIL; } break; case STATE_FEED_ENTRY_CONTRIBUTOR: if(qName.equals(TAG_NAME)) { data_entry_contributor_name = ""; state = STATE_FEED_ENTRY_CONTRIBUTOR_NAME; } else if(qName.equals(TAG_URI)) { data_entry_contributor_uri = ""; state = STATE_FEED_ENTRY_CONTRIBUTOR_URI; } else if(qName.equals(TAG_EMAIL)) { data_entry_contributor_email = ""; state = STATE_FEED_ENTRY_CONTRIBUTOR_EMAIL; } break; case STATE_FEED_ENTRY_SOURCE: if(qName.equals(TAG_ID)) { data_entry_source_id = ""; state = STATE_FEED_ENTRY_SOURCE_ID; } else if(qName.equals(TAG_TITLE)) { data_entry_source_title = ""; state = STATE_FEED_ENTRY_SOURCE_TITLE; } else if(qName.equals(TAG_UPDATED)) { data_entry_source_updated = ""; state = STATE_FEED_ENTRY_SOURCE_UPDATED; } else if(qName.equals(TAG_RIGHTS)) { data_entry_source_rights_type = atts.getValue("type"); data_entry_source_rights = ""; state = STATE_FEED_ENTRY_SOURCE_RIGHTS; } break; } } public void endElement(String uri, String localName, String qName) throws SAXException { //parent.log(" END" + state +" --- " + qName); switch(state) { case STATE_FEED: { if(qName.equals(TAG_FEED)) { state = STATE_START; } break; } case STATE_FEED_TITLE: { if(qName.equals(TAG_TITLE)) { if(theFeed != null && isValid(data_feed_title)) { try { data_feed_title = postProcessFeedText(data_feed_title, data_feed_title_type); theFeed.setBaseName(data_feed_title + " (Atom feed)"); theFeed.setDisplayName(DEFAULT_LANG, data_feed_title); } catch(Exception e) { parent.log(e); } } state = STATE_FEED; } break; } case STATE_FEED_LINK: { if(qName.equals(TAG_LINK)) { if(theFeed != null && data_feed_link != null) { try { createLinkStruct(data_feed_link, theFeed, getFeedType()); } catch(Exception e) { parent.log(e); } } state = STATE_FEED; } break; } case STATE_FEED_UPDATED: { if(qName.equals(TAG_UPDATED)) { if(theFeed != null && isValid(data_feed_updated)) { try { Topic updatedType = getOrCreateTopic(FEED_UPDATED_SI,"Atom Feed Updated"); Topic dateTopic = getDateTopic(data_feed_updated); Association a = tm.createAssociation(updatedType); a.addPlayer(theFeed, getFeedType()); a.addPlayer(dateTopic, updatedType); } catch(Exception e) { parent.log(e); } } state = STATE_FEED; } break; } case STATE_FEED_AUTHOR: { if(qName.equals(TAG_AUTHOR)) { if(theFeed != null && isValid(data_feed_author_name)) { try { Topic feedType = getFeedType(); Topic authorType = getOrCreateTopic(FEED_AUTHOR_SI,"Atom Feed Author"); String authorSI = !isValid(data_feed_author_uri) ? FEED_AUTHOR_SI + "/" + data_feed_author_name : data_feed_author_uri; Topic theAuthor = getOrCreateTopic(authorSI, data_feed_author_name); theAuthor.addType(authorType); Association feedAuthor = tm.createAssociation(authorType); feedAuthor.addPlayer(theFeed, feedType); feedAuthor.addPlayer(theAuthor, authorType); if(isValid(data_feed_author_email)) { Topic emailType = getOrCreateTopic(EMAIL_ADDRESS_SI,"Email address"); parent.setData(theAuthor, emailType, DEFAULT_LANG, data_feed_author_email); } } catch(Exception e) { parent.log(e); } } state = STATE_FEED; } break; } case STATE_FEED_AUTHOR_NAME: { if(qName.equals(TAG_NAME)) { state = STATE_FEED_AUTHOR; } break; } case STATE_FEED_AUTHOR_URI: { if(qName.equals(TAG_URI)) { state = STATE_FEED_AUTHOR; } break; } case STATE_FEED_AUTHOR_EMAIL: { if(qName.equals(TAG_EMAIL)) { state = STATE_FEED_AUTHOR; } break; } case STATE_FEED_ID: { if(qName.equals(TAG_ID)) { if(theFeed != null && isValid(data_feed_id)) { try { if(data_feed_id.startsWith("http://")) { theFeed.addSubjectIdentifier(new org.wandora.topicmap.Locator(data_feed_id)); theFeed.removeSubjectIdentifier(theFeedSI); theFeed = tm.getTopic(data_feed_id); } else { Topic idType = getOrCreateTopic(FEED_ID_SI,"Atom Feed Id"); parent.setData(theFeed, idType, DEFAULT_LANG, data_feed_id); } } catch(Exception e) { parent.log(e); } } state = STATE_FEED; } break; } case STATE_FEED_CATEGORY: { if(qName.equals(TAG_CATEGORY)) { if(theFeed != null && data_feed_category != null) { try { Topic feedType = getFeedType(); Topic categoryType = getOrCreateTopic(FEED_CATEGORY_SI,"Atom Feed Category"); String term = data_feed_category.getTerm(); String label = data_feed_category.getLabel(); String scheme = data_feed_category.getScheme(); String categorySI = FEED_CATEGORY_SI + "/" + term; String categoryBasename = term; if(isValid(term) && isValid(scheme)) categorySI = scheme + term; if(isValid(label)) categoryBasename = label; Topic theCategory = getOrCreateTopic(categorySI, categoryBasename); theCategory.addType(categoryType); Association feedCategory = tm.createAssociation(categoryType); feedCategory.addPlayer(theFeed, feedType); feedCategory.addPlayer(theCategory, categoryType); if(isValid(scheme)) { Topic schemeType = getOrCreateTopic(SCHEME_SI,"Scheme"); parent.setData(theCategory, schemeType, DEFAULT_LANG, scheme); } if(isValid(label)) { theCategory.setDisplayName(DEFAULT_LANG, label); } } catch(Exception e) { parent.log(e); } } state = STATE_FEED; } break; } case STATE_FEED_CONTRIBUTOR: { if(qName.equals(TAG_CONTRIBUTOR)) { if(theFeed != null && isValid(data_feed_contributor_name)) { try { Topic feedType = getFeedType(); Topic contributorType = getOrCreateTopic(FEED_CONTRIBUTOR_SI,"Atom Feed Contributor"); String contributorSI = !isValid(data_feed_contributor_uri) ? FEED_CONTRIBUTOR_SI + "/" + data_feed_contributor_name : data_feed_contributor_uri; Topic theContributor = getOrCreateTopic(contributorSI, data_feed_contributor_name); theContributor.addType(contributorType); Association feedContributor = tm.createAssociation(contributorType); feedContributor.addPlayer(theFeed, feedType); feedContributor.addPlayer(theContributor, contributorType); if(isValid(data_feed_contributor_email)) { Topic emailType = getOrCreateTopic(EMAIL_ADDRESS_SI,"Email address"); parent.setData(theContributor, emailType, DEFAULT_LANG, data_feed_contributor_email); } } catch(Exception e) { parent.log(e); } } state = STATE_FEED; } break; } case STATE_FEED_CONTRIBUTOR_NAME: { if(qName.equals(TAG_NAME)) { state = STATE_FEED_CONTRIBUTOR; } break; } case STATE_FEED_CONTRIBUTOR_URI: { if(qName.equals(TAG_URI)) { state = STATE_FEED_CONTRIBUTOR; } break; } case STATE_FEED_CONTRIBUTOR_EMAIL: { if(qName.equals(TAG_EMAIL)) { state = STATE_FEED_CONTRIBUTOR; } break; } case STATE_FEED_GENERATOR: { if(qName.equals(TAG_GENERATOR)) { if(theFeed != null && isValid(data_feed_generator)) { try { Topic feedType = getFeedType(); Topic generatorType = getOrCreateTopic(FEED_GENERATOR_SI,"Atom Feed Generator"); String generatorSI = FEED_GENERATOR_SI + "/" + data_feed_generator; Topic theGenerator = getOrCreateTopic(generatorSI, data_feed_generator); theGenerator.addType(generatorType); Association feedGenerator = tm.createAssociation(generatorType); feedGenerator.addPlayer(theFeed, feedType); feedGenerator.addPlayer(theGenerator, generatorType); if(isValid(data_feed_generator_uri)) { Topic uriType = getOrCreateTopic(FEED_GENERATOR_URI_SI,"Atom Feed Generator URI"); parent.setData(theGenerator, uriType, DEFAULT_LANG, data_feed_generator_uri); } if(isValid(data_feed_generator_version)) { Topic versionType = getOrCreateTopic(FEED_GENERATOR_VERSION_SI,"Atom Feed Generator Version"); parent.setData(theGenerator, versionType, DEFAULT_LANG, data_feed_generator_version); } } catch(Exception e) { parent.log(e); } } state = STATE_FEED; } break; } case STATE_FEED_ICON: { if(qName.equals(TAG_ICON)) { if(theFeed != null && isValid(data_feed_icon)) { try { Topic feedType = getFeedType(); Topic iconType = getOrCreateTopic(FEED_ICON_SI,"Atom Feed Icon"); String iconSI = FEED_ICON_SI + "/" + data_feed_icon; if(data_feed_icon.startsWith("http://")) { iconSI = data_feed_icon; } else if(data_feed_icon.startsWith("/") && data_feed_id.startsWith("http://")) { String prefix = data_feed_id; if(prefix.endsWith("/")) prefix = prefix.substring(0, prefix.length()-1); iconSI = prefix + data_feed_icon; } Topic theIcon = getOrCreateTopic(iconSI, null); theIcon.setSubjectLocator(new org.wandora.topicmap.Locator(iconSI)); theIcon.addType(iconType); Association feedIcon = tm.createAssociation(iconType); feedIcon.addPlayer(theFeed, feedType); feedIcon.addPlayer(theIcon, iconType); } catch(Exception e) { parent.log(e); } } state = STATE_FEED; } break; } case STATE_FEED_LOGO: { if(qName.equals(TAG_LOGO)) { if(theFeed != null && isValid(data_feed_logo)) { try { Topic feedType = getFeedType(); Topic logoType = getOrCreateTopic(FEED_LOGO_SI,"Atom Feed Logo"); String logoSI = FEED_LOGO_SI + "/" + data_feed_logo; if(data_feed_icon.startsWith("http://")) { logoSI = data_feed_logo; } else if(data_feed_logo.startsWith("/") && data_feed_id.startsWith("http://")) { String prefix = data_feed_id; if(prefix.endsWith("/")) prefix = prefix.substring(0, prefix.length()-1); logoSI = prefix + data_feed_logo; } Topic theLogo = getOrCreateTopic(logoSI, null); theLogo.setSubjectLocator(new org.wandora.topicmap.Locator(logoSI)); theLogo.addType(logoType); Association feedLogo = tm.createAssociation(logoType); feedLogo.addPlayer(theFeed, feedType); feedLogo.addPlayer(theLogo, logoType); } catch(Exception e) { parent.log(e); } } state = STATE_FEED; } break; } case STATE_FEED_RIGHTS: { if(qName.equals(TAG_RIGHTS)) { if(theFeed != null && isValid(data_feed_rights)) { try { data_feed_rights = postProcessFeedText(data_feed_rights, data_feed_rights_type); Topic rightsType = getRightsType(); Topic rightsTopic = getRightsTopic(data_feed_rights); if(rightsType != null && rightsTopic != null) { Association a = tm.createAssociation(rightsType); a.addPlayer(theFeed, getFeedType()); a.addPlayer(rightsTopic, rightsType); } } catch(Exception e) { parent.log(e); } } state = STATE_FEED; } break; } case STATE_FEED_SUBTITLE: { if(qName.equals(TAG_SUBTITLE)) { if(theFeed != null && isValid(data_feed_subtitle)) { try { data_feed_subtitle = this.postProcessFeedText(data_feed_subtitle, data_feed_subtitle_type); Topic subtitleType = getOrCreateTopic(FEED_SUBTITLE_SI,"Atom Feed Subtitle"); parent.setData(theFeed, subtitleType, DEFAULT_LANG, data_feed_subtitle); } catch(Exception e) { parent.log(e); } } state = STATE_FEED; } break; } // ************************************************** // ********************* ENTRY ********************** // ************************************************** case STATE_FEED_ENTRY: { if(qName.equals(TAG_ENTRY)) { if(theEntry != null && theFeed != null) { try { Topic entryType = getEntryType(); Topic feedType = getFeedType(); Association a = tm.createAssociation(entryType); a.addPlayer(theEntry, entryType); a.addPlayer(theFeed, feedType); } catch(Exception e) { parent.log(e); } } state = STATE_FEED; } break; } case STATE_FEED_ENTRY_ID: { if(qName.equals(TAG_ID)) { if(theEntry != null && isValid(data_entry_id)) { try { if(data_entry_id.startsWith("http://")) { theEntry.addSubjectIdentifier(new org.wandora.topicmap.Locator(data_entry_id)); theEntry.removeSubjectIdentifier(theEntrySI); theEntry = tm.getTopic(data_entry_id); } else { Topic idType = getOrCreateTopic(FEED_ENTRY_ID_SI,"Atom Entry Id"); parent.setData(theEntry, idType, DEFAULT_LANG, data_entry_id); } } catch(Exception e) { parent.log(e); } } state = STATE_FEED_ENTRY; } break; } case STATE_FEED_ENTRY_TITLE: { if(qName.equals(TAG_TITLE)) { if(theEntry != null && isValid(data_entry_title)) { try { data_entry_title = postProcessFeedText(data_entry_title, data_entry_title_type); theEntry.setBaseName(data_entry_title + " (Atom entry)"); theEntry.setDisplayName(DEFAULT_LANG, data_entry_title); } catch(Exception e) { parent.log(e); } } state = STATE_FEED_ENTRY; } break; } case STATE_FEED_ENTRY_UPDATED: { if(qName.equals(TAG_UPDATED)) { if(theEntry != null && isValid(data_entry_updated)) { try { Topic updatedType = getOrCreateTopic(FEED_ENTRY_UPDATED_SI,"Atom Entry Updated"); Topic dateTopic = getDateTopic(data_entry_updated); if(dateTopic != null && updatedType != null) { Association a = tm.createAssociation(updatedType); a.addPlayer(theEntry, getEntryType()); a.addPlayer(dateTopic, updatedType); } } catch(Exception e) { parent.log(e); } } state = STATE_FEED_ENTRY; } break; } case STATE_FEED_ENTRY_AUTHOR: { if(qName.equals(TAG_AUTHOR)) { if(theEntry != null && isValid(data_entry_author_name)) { try { Topic entryType = getEntryType(); Topic authorType = getOrCreateTopic(FEED_ENTRY_AUTHOR_SI,"Atom Entry Author"); String authorSI = data_entry_author_uri == null || data_entry_author_uri.length() == 0 ? FEED_ENTRY_AUTHOR_SI + "/" + data_entry_author_name : data_entry_author_uri; Topic theAuthor = getOrCreateTopic(authorSI, data_entry_author_name); theAuthor.addType(authorType); Association entryAuthor = tm.createAssociation(authorType); entryAuthor.addPlayer(theEntry, entryType); entryAuthor.addPlayer(theAuthor, authorType); if(data_entry_author_email != null && data_entry_author_email.length() > 0) { Topic emailType = getOrCreateTopic(EMAIL_ADDRESS_SI,"Email address"); parent.setData(theAuthor, emailType, DEFAULT_LANG, data_entry_author_email); } } catch(Exception e) { parent.log(e); } } state = STATE_FEED_ENTRY; } break; } case STATE_FEED_ENTRY_AUTHOR_NAME: { if(qName.equals(TAG_NAME)) { state = STATE_FEED_ENTRY_AUTHOR; } break; } case STATE_FEED_ENTRY_AUTHOR_URI: { if(qName.equals(TAG_URI)) { state = STATE_FEED_ENTRY_AUTHOR; } break; } case STATE_FEED_ENTRY_AUTHOR_EMAIL: { if(qName.equals(TAG_EMAIL)) { state = STATE_FEED_ENTRY_AUTHOR; } break; } case STATE_FEED_ENTRY_CONTENT: { if(qName.equals(TAG_CONTENT)) { if(theEntry != null && (isValid(data_entry_content) || isValid(data_entry_content_src ))) { try { if(!isValid(data_entry_content)) { data_entry_content = IObox.doUrl(new URL(data_entry_content_src)); } data_entry_content = this.postProcessFeedText(data_entry_content, data_entry_content_type); Topic contentType = getOrCreateTopic(FEED_ENTRY_CONTENT_SI,"Atom Entry Content"); parent.setData(theEntry, contentType, DEFAULT_LANG, data_entry_content); } catch(Exception e) { parent.log(e); } } state = STATE_FEED_ENTRY; } break; } case STATE_FEED_ENTRY_LINK: { if(qName.equals(TAG_LINK)) { if(theEntry != null && data_entry_link != null) { try { createLinkStruct(data_entry_link, theEntry, getEntryType()); } catch(Exception e) { parent.log(e); } } state = STATE_FEED_ENTRY; } break; } case STATE_FEED_ENTRY_SUMMARY: { if(qName.equals(TAG_SUMMARY)) { if(theEntry != null && (isValid(data_entry_summary) || isValid(data_entry_summary_src))) { try { if(!isValid(data_entry_summary)) { data_entry_summary = IObox.doUrl(new URL(data_entry_summary_src)); } data_entry_summary = this.postProcessFeedText(data_entry_summary, data_entry_summary_type); Topic summaryType = getOrCreateTopic(FEED_ENTRY_SUMMARY_SI,"Atom Entry Summary"); parent.setData(theEntry, summaryType, DEFAULT_LANG, data_entry_summary); } catch(Exception e) { parent.log(e); } } state = STATE_FEED_ENTRY; } break; } case STATE_FEED_ENTRY_CATEGORY: { if(qName.equals(TAG_CATEGORY)) { if(theFeed != null && data_entry_category != null) { try { Topic entryType = getEntryType(); Topic categoryType = getOrCreateTopic(FEED_CATEGORY_SI,"Atom Entry Category"); String term = data_entry_category.getTerm(); String label = data_entry_category.getLabel(); String scheme = data_entry_category.getScheme(); String categorySI = FEED_ENTRY_CATEGORY_SI + "/" + term; String categoryBasename = term; if(isValid(scheme) && isValid(term)) categorySI = scheme+term; if(isValid(label)) categoryBasename = label; Topic theCategory = getOrCreateTopic(categorySI, categoryBasename); theCategory.addType(categoryType); Association entryCategory = tm.createAssociation(categoryType); entryCategory.addPlayer(theEntry, entryType); entryCategory.addPlayer(theCategory, categoryType); if(scheme != null && scheme.length() > 0) { Topic schemeType = getOrCreateTopic(SCHEME_SI,"Scheme"); parent.setData(theCategory, schemeType, DEFAULT_LANG, scheme); } if(label != null && label.length() > 0) { theCategory.setDisplayName(DEFAULT_LANG, label); } } catch(Exception e) { parent.log(e); } } state = STATE_FEED_ENTRY; } break; } case STATE_FEED_ENTRY_CONTRIBUTOR: { if(qName.equals(TAG_CONTRIBUTOR)) { if(theEntry != null && isValid(data_entry_contributor_name)) { try { Topic entryType = getEntryType(); Topic contributorType = getOrCreateTopic(FEED_ENTRY_CONTRIBUTOR_SI,"Atom Entry Contributor"); String contributorSI = data_entry_contributor_uri == null || data_entry_contributor_uri.length() == 0 ? FEED_CONTRIBUTOR_SI + "/" + data_entry_contributor_name : data_entry_contributor_uri; Topic theContributor = getOrCreateTopic(contributorSI, data_entry_contributor_name); theContributor.addType(contributorType); Association feedContributor = tm.createAssociation(contributorType); feedContributor.addPlayer(theEntry, entryType); feedContributor.addPlayer(theContributor, contributorType); if(data_entry_contributor_email != null && data_entry_contributor_email.length() > 0) { Topic emailType = getOrCreateTopic(EMAIL_ADDRESS_SI,"Email address"); parent.setData(theContributor, emailType, DEFAULT_LANG, data_entry_contributor_email); } } catch(Exception e) { parent.log(e); } } state = STATE_FEED_ENTRY; } break; } case STATE_FEED_ENTRY_CONTRIBUTOR_NAME: { if(qName.equals(TAG_NAME)) { state = STATE_FEED_ENTRY_CONTRIBUTOR; } break; } case STATE_FEED_ENTRY_CONTRIBUTOR_URI: { if(qName.equals(TAG_URI)) { state = STATE_FEED_ENTRY_CONTRIBUTOR; } break; } case STATE_FEED_ENTRY_CONTRIBUTOR_EMAIL: { if(qName.equals(TAG_EMAIL)) { state = STATE_FEED_ENTRY_CONTRIBUTOR; } break; } case STATE_FEED_ENTRY_PUBLISHED: { if(qName.equals(TAG_PUBLISHED)) { if(theEntry != null && isValid(data_entry_published)) { try { Topic publishedType = getOrCreateTopic(FEED_ENTRY_PUBLISHED_SI,"Atom Entry Published"); Topic dateTopic = getDateTopic(data_entry_published); if(dateTopic != null && publishedType != null) { Association a = tm.createAssociation(publishedType); a.addPlayer(theEntry, getEntryType()); a.addPlayer(dateTopic, publishedType); } } catch(Exception e) { parent.log(e); } } state = STATE_FEED_ENTRY; } break; } case STATE_FEED_ENTRY_SOURCE: { if(qName.equals(TAG_SOURCE)) { if(theEntry != null && isValid(data_entry_source_id)) { try { Topic sourceType = getOrCreateTopic(FEED_ENTRY_SOURCE_SI,"Atom Entry Source"); Topic theSource = tm.createTopic(); Topic theSourceRights = null; Topic theSourceUpdated = null; if(data_entry_source_id.startsWith("http://")) { theSource.addSubjectIdentifier(new org.wandora.topicmap.Locator(data_entry_source_id)); theSource.setSubjectLocator(new org.wandora.topicmap.Locator(data_entry_source_id)); } else { theSource.addSubjectIdentifier(new org.wandora.topicmap.Locator(FEED_ENTRY_SOURCE_SI+"/"+data_entry_source_id)); } if(isValid(data_entry_source_title)) { theSource.setBaseName(data_entry_source_title); } theSource.addType(sourceType); Association a = tm.createAssociation(sourceType); a.addPlayer(theEntry, getEntryType()); a.addPlayer(theSource, sourceType); if(isValid(data_entry_source_rights)) { Topic rightsType = getRightsType(); theSourceRights = getRightsTopic(postProcessFeedText(data_entry_source_rights, data_entry_source_rights_type)); a.addPlayer(theSourceRights, rightsType); } if(isValid(data_entry_source_updated)) { Topic dateType = getDateType(); theSourceUpdated = getDateTopic(data_entry_source_updated); a.addPlayer(theSourceUpdated, dateType); } } catch(Exception e) { parent.log(e); } } state = STATE_FEED_ENTRY; } break; } case STATE_FEED_ENTRY_SOURCE_ID: { if(qName.equals(TAG_ID)) { state = STATE_FEED_ENTRY_SOURCE; } break; } case STATE_FEED_ENTRY_SOURCE_TITLE: { if(qName.equals(TAG_TITLE)) { state = STATE_FEED_ENTRY_SOURCE; } break; } case STATE_FEED_ENTRY_SOURCE_UPDATED: { if(qName.equals(TAG_UPDATED)) { state = STATE_FEED_ENTRY_SOURCE; } break; } case STATE_FEED_ENTRY_SOURCE_RIGHTS: { if(qName.equals(TAG_RIGHTS)) { state = STATE_FEED_ENTRY_SOURCE; } break; } case STATE_FEED_ENTRY_RIGHTS: { if(qName.equals(TAG_RIGHTS)) { if(theEntry != null && isValid(data_entry_rights)) { try { data_entry_rights = postProcessFeedText(data_entry_rights, data_entry_rights_type); Topic rightsType = getRightsType(); Topic rightsTopic = getRightsTopic(data_entry_rights); if(rightsType != null && rightsTopic != null) { Association a = tm.createAssociation(rightsType); a.addPlayer(theEntry, getEntryType()); a.addPlayer(rightsTopic, rightsType); } } catch(Exception e) { parent.log(e); } } state = STATE_FEED_ENTRY; } break; } } } public void characters(char[] ch, int start, int length) throws SAXException { switch(state){ case STATE_FEED_ID: data_feed_id+=new String(ch,start,length); break; case STATE_FEED_TITLE: data_feed_title+=new String(ch,start,length); break; case STATE_FEED_UPDATED: data_feed_updated+=new String(ch,start,length); break; case STATE_FEED_AUTHOR_NAME: data_feed_author_name+=new String(ch,start,length); break; case STATE_FEED_AUTHOR_URI: data_feed_author_uri+=new String(ch,start,length); break; case STATE_FEED_AUTHOR_EMAIL: data_feed_author_email+=new String(ch,start,length); break; case STATE_FEED_CONTRIBUTOR_NAME: data_feed_contributor_name+=new String(ch,start,length); break; case STATE_FEED_CONTRIBUTOR_URI: data_feed_contributor_uri+=new String(ch,start,length); break; case STATE_FEED_CONTRIBUTOR_EMAIL: data_feed_contributor_email+=new String(ch,start,length); break; case STATE_FEED_GENERATOR: data_feed_generator+=new String(ch,start,length); break; case STATE_FEED_ICON: data_feed_icon+=new String(ch,start,length); break; case STATE_FEED_LOGO: data_feed_logo+=new String(ch,start,length); break; case STATE_FEED_RIGHTS: data_feed_rights+=new String(ch,start,length); break; case STATE_FEED_SUBTITLE: data_feed_subtitle+=new String(ch,start,length); break; // *********************** ENTRY ************************* case STATE_FEED_ENTRY_ID: data_entry_id+=new String(ch,start,length); break; case STATE_FEED_ENTRY_TITLE: data_entry_title+=new String(ch,start,length); break; case STATE_FEED_ENTRY_UPDATED: data_entry_updated+=new String(ch,start,length); break; case STATE_FEED_ENTRY_AUTHOR_NAME: data_entry_author_name+=new String(ch,start,length); break; case STATE_FEED_ENTRY_AUTHOR_URI: data_entry_author_uri+=new String(ch,start,length); break; case STATE_FEED_ENTRY_AUTHOR_EMAIL: data_entry_author_email+=new String(ch,start,length); break; case STATE_FEED_ENTRY_CONTENT: data_entry_content+=new String(ch,start,length); break; case STATE_FEED_ENTRY_SUMMARY: data_entry_summary+=new String(ch,start,length); break; case STATE_FEED_ENTRY_CONTRIBUTOR_NAME: data_entry_contributor_name+=new String(ch,start,length); break; case STATE_FEED_ENTRY_CONTRIBUTOR_URI: data_entry_contributor_uri+=new String(ch,start,length); break; case STATE_FEED_ENTRY_CONTRIBUTOR_EMAIL: data_entry_contributor_email+=new String(ch,start,length); break; case STATE_FEED_ENTRY_PUBLISHED: data_entry_published+=new String(ch,start,length); break; case STATE_FEED_ENTRY_SOURCE_ID: data_entry_source_id+=new String(ch,start,length); break; case STATE_FEED_ENTRY_SOURCE_TITLE: data_entry_source_title+=new String(ch,start,length); break; case STATE_FEED_ENTRY_SOURCE_UPDATED: data_entry_source_updated+=new String(ch,start,length); break; case STATE_FEED_ENTRY_SOURCE_RIGHTS: data_entry_source_rights+=new String(ch,start,length); break; case STATE_FEED_ENTRY_RIGHTS: data_entry_rights+=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 {} } // ------------------------------------------------------------------------- // ----------------------------------------------------- HELPER CLASSES ---- // ------------------------------------------------------------------------- private class Content { private String text; private String src; private String type; public Content(String t, String s, String type) { this.text = t; this.src = s; this.type = type; } public String getContent() { return text; } public String getType() { return type; } public String getSrc() { return src; } } private class Category { private String term; private String scheme; private String label; public Category(String t, String s, String l) { this.term = t; this.scheme = s; this.label = l; } public String getTerm() { return term; } public String getScheme() { return scheme; } public String getLabel() { return label; } } private class Text { private String text; private String type; public Text(String t, String type) { this.text = t; this.type = type; } public String getText() { return text; } public String getType() { return type; } } private class Person { private String name; private String uri; private String email; public Person(String n, String u, String e) { this.name = n; this.uri = u; this.email = e; } public String getName() { return name; } public String getUri() { return uri; } public String getEmail() { return email; } } private class Link { private String href; private String rel; private String type; private String hreflang; private String title; private String length; public Link(String h, String r, String ty, String hl, String ti, String len) { this.href = h; this.rel = r; this.type = ty; this.hreflang = hl; this.title = ti; this.length = len; } public String getHref() { return href; } public String getRel() { return rel; } public String getType() { return type; } public String getHrefLang() { return hreflang; } public String getTitle() { return title; } public String getLength() { return length; } } }
88,309
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
BigHugeThesaurusExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/bighugethesaurus/BigHugeThesaurusExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.bighugethesaurus; 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; /** * Converts Big Huge Thesaurus feeds to topics maps. Thesaurus service provided * by words.bighugelabs.com. * * @author akivela */ public class BigHugeThesaurusExtractor extends AbstractWandoraTool { private static final long serialVersionUID = 1L; private static BigHugeThesaurusSelector selector = null; @Override public String getName() { return "Big Huge Thesaurus extractor"; } @Override public String getDescription(){ return "Converts Big Huge Thesaurus feeds to topics maps. Thesaurus service provided by words.bighugelabs.com."; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_bighugethesaurus.png"); } @Override public WandoraToolType getType() { return WandoraToolType.createExtractType(); } public void execute(Wandora wandora, Context context) { int counter = 0; try { if(selector == null) { selector = new BigHugeThesaurusSelector(wandora); } selector.setAccepted(false); selector.setWandora(wandora); selector.setContext(context); selector.setVisible(true); if(selector.wasAccepted()) { setDefaultLogger(); WandoraTool extractor = selector.getWandoraTool(this); if(extractor != null) { extractor.setToolLogger(getDefaultLogger()); extractor.execute(wandora, context); } } else { //log("User cancelled the extraction!"); } } catch(Exception e) { singleLog(e); } if(selector != null && selector.wasAccepted()) setState(WAIT); } }
2,975
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
XMLBigHugeThesaurusExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/bighugethesaurus/XMLBigHugeThesaurusExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.bighugethesaurus; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.net.URL; import java.net.URLDecoder; import java.net.URLEncoder; import javax.swing.Icon; import org.wandora.application.gui.UIBox; import org.wandora.application.tools.extractors.AbstractExtractor; import org.wandora.application.tools.extractors.ExtractHelper; import org.wandora.topicmap.Association; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.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 XMLBigHugeThesaurusExtractor extends AbstractExtractor { private static final long serialVersionUID = 1L; public static final boolean INCLUDE_PART_OF_SPEECH = true; public static final boolean RELATIONSHIP_AS_ASSOCIATION_TYPE = true; private String queryTerm = null; protected String SI_BASE = "http://words.bighugelabs.com/"; protected String PARTOFSPEECH_SI = SI_BASE+"part-of-speech"; protected String TERM_SI = SI_BASE+"term"; protected String RELATEDTERM_SI = SI_BASE+"related-term"; protected String RELATIONSHIP_SI = SI_BASE+"relationship"; protected String SYNONYM_TYPE_SI = SI_BASE+"synonym"; protected String ANTONYM_TYPE_SI = SI_BASE+"antonym"; protected String RELATED_TYPE_SI = SI_BASE+"related"; protected String SIMILAR_TYPE_SI = SI_BASE+"similar"; protected String USERSUGGESTION_TYPE_SI = SI_BASE+"user-suggested"; protected String SOURCE_SI = "http://wandora.org/si/source"; private String defaultEncoding = "ISO-8859-1"; /** Creates a new instance of XMLBigHugeThesaurusExtractor */ public XMLBigHugeThesaurusExtractor() { } @Override public String getName() { return "Big Huge Thesaurus XML extractor."; } @Override public String getDescription(){ return "Converts Big Huge Thesaurus XML feeds to topics maps. Thesaurus service provided by words.bighugelabs.com."; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_bighugethesaurus.png"); } private final String[] contentTypes=new String[] { "text/xml", "application/xml" }; @Override public String[] getContentTypes() { return contentTypes; } @Override public boolean useURLCrawler() { return false; } public boolean _extractTopicsFrom(URL url, TopicMap topicMap) throws Exception { try { String urlStr = url.toExternalForm(); int i = urlStr.indexOf("/xml"); if(i != -1) { urlStr = urlStr.substring(0, i); i = urlStr.lastIndexOf("/"); if(i != -1) { queryTerm = urlStr.substring(i+1); try { queryTerm = URLDecoder.decode(queryTerm, defaultEncoding); } catch(Exception e) { // DO NOTHING... } } } } catch(Exception e) { log(e); } String in = IObox.doUrl(url); return _extractTopicsFrom(in, topicMap); } public boolean _extractTopicsFrom(File file, TopicMap topicMap) throws Exception { return _extractTopicsFrom(new FileInputStream(file),topicMap); } public boolean _extractTopicsFrom(InputStream in, TopicMap topicMap) throws Exception { String str = IObox.loadFile(in, defaultEncoding); return _extractTopicsFrom(str, topicMap); } public boolean _extractTopicsFrom(String in, TopicMap topicMap) throws Exception { try { String result = in; //System.out.println("Result = "+result); // ---- Parse results ---- javax.xml.parsers.SAXParserFactory factory=javax.xml.parsers.SAXParserFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(false); javax.xml.parsers.SAXParser parser=factory.newSAXParser(); XMLReader reader=parser.getXMLReader(); BigHugeThesaurusResultParser parserHandler = new BigHugeThesaurusResultParser(getMasterSubject(), queryTerm, topicMap, this); reader.setContentHandler(parserHandler); reader.setErrorHandler(parserHandler); try{ reader.parse(new InputSource(new ByteArrayInputStream(result.getBytes()))); } catch(Exception e){ if(!(e instanceof SAXException) || !e.getMessage().equals("User interrupt")) log(e); } String msg = null; if(parserHandler.progress == 0) { msg = "Found related words."; } else { msg = "Found "+parserHandler.progress+" related word(s)."; } if(msg != null) log(msg); } catch (Exception ex) { log(ex); } queryTerm = null; return true; } // ------------------------------------------------------------------------- public Topic getRelationshipType(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, RELATIONSHIP_SI, "Relationship"); Topic bhtClass = getBigHugeClass(tm); makeSubclassOf(tm, type, bhtClass); return type; } // ------- public Topic getPartOfSpeechTopic(String p, TopicMap tm) throws TopicMapException { if(p != null) { p = p.trim(); if(p.length() > 0) { Topic partOfSpeechTopic=getOrCreateTopic(tm, p); Topic partOfSpeechTypeTopic = getPartOfSpeechType(tm); partOfSpeechTopic.addType(partOfSpeechTypeTopic); return partOfSpeechTopic; } } return null; } public Topic getPartOfSpeechType(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, PARTOFSPEECH_SI, "Part of speech"); Topic bhtClass = getBigHugeClass(tm); makeSubclassOf(tm, type, bhtClass); return type; } // ------- public Topic getTermTopic(String term, TopicMap tm) throws TopicMapException { if(term != null) { term = term.trim(); if(term.length() > 0) { String si = null; try { si = SI_BASE+URLEncoder.encode(term, defaultEncoding); } catch(Exception e) { si = SI_BASE+term; } Topic termTopic=getOrCreateTopic(tm, si, term); Topic termTypeTopic = getTermType(tm); termTopic.addType(termTypeTopic); return termTopic; } } return null; } // ------- public Topic getTermType(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, TERM_SI, "Term"); Topic bhtClass = getBigHugeClass(tm); makeSubclassOf(tm, type, bhtClass); return type; } public Topic getRelatedTermType(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, RELATEDTERM_SI, "Related term"); return type; } // ---- RELATIONSHIPS ---- public Topic getSynonymType(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, SYNONYM_TYPE_SI, "Synonym"); Topic relationshipType = getRelationshipType(tm); makeSubclassOf(tm, type, relationshipType); return type; } public Topic getAntonymType(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, ANTONYM_TYPE_SI, "Antonym"); Topic relationshipType = getRelationshipType(tm); makeSubclassOf(tm, type, relationshipType); return type; } public Topic getRelatedType(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, RELATED_TYPE_SI, "Related"); Topic relationshipType = getRelationshipType(tm); makeSubclassOf(tm, type, relationshipType); return type; } public Topic getSimilarType(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, SIMILAR_TYPE_SI, "Similar"); Topic relationshipType = getRelationshipType(tm); makeSubclassOf(tm, type, relationshipType); return type; } public Topic getUserSuggestionsType(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, USERSUGGESTION_TYPE_SI, "User suggestion"); Topic relationshipType = getRelationshipType(tm); makeSubclassOf(tm, type, relationshipType); return type; } // ------------------------ public Topic getBigHugeClass(TopicMap tm) throws TopicMapException { Topic t = getOrCreateTopic(tm, SI_BASE,"Big Huge Thesaurus"); t.addType(getWandoraClass(tm)); return t; } public Topic getWandoraClass(TopicMap tm) throws TopicMapException { return getOrCreateTopic(tm, TMBox.WANDORACLASS_SI,"Wandora class"); } public Topic getSourceType(TopicMap tm) throws TopicMapException { return getOrCreateTopic(tm, SOURCE_SI, "Source"); } // -------- protected Topic getOrCreateTopic(TopicMap tm, String si) throws TopicMapException { return getOrCreateTopic(tm, si, null); } protected Topic getOrCreateTopic(TopicMap tm, String si,String bn) throws TopicMapException { return ExtractHelper.getOrCreateTopic(si, bn, tm); } protected void makeSubclassOf(TopicMap tm, Topic t, Topic superclass) throws TopicMapException { ExtractHelper.makeSubclassOf(t, superclass, tm); } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- private class BigHugeThesaurusResultParser implements org.xml.sax.ContentHandler, org.xml.sax.ErrorHandler { public int progress=0; private TopicMap tm; private XMLBigHugeThesaurusExtractor parent; private Topic termTopic = null; private Topic masterTopic = null; public BigHugeThesaurusResultParser(String master, String term, TopicMap tm, XMLBigHugeThesaurusExtractor parent) { this.tm=tm; this.parent=parent; try { if(term != null) { term = term.trim(); if(term.length() > 0) { termTopic = getTermTopic(term, tm); } } } catch(Exception e) { parent.log(e); } try { if(master != null) { masterTopic = tm.getTopicWithBaseName(master); if(masterTopic == null) masterTopic = tm.getTopic(master); } } catch(Exception e) { parent.log(e); } if(masterTopic != null && termTopic != null) { try { Association a = tm.createAssociation(getTermType(tm)); a.addPlayer(termTopic, getTermType(tm)); a.addPlayer(masterTopic, getSourceType(tm)); } catch(Exception e) { parent.log(e); } } } public static final String TAG_WORDS = "words"; public static final String TAG_W = "w"; public static final String TAG_MESSAGE = "Message"; private static final int STATE_START=0; private static final int STATE_WORDS=2; private static final int STATE_WORDS_W=4; private int state=STATE_START; private String data_w = null; private String data_p = null; private String data_r = 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_WORDS)) { state = STATE_WORDS; } break; case STATE_WORDS: if(qName.equals(TAG_W)) { data_w = ""; data_p = atts.getValue("p"); data_r = atts.getValue("r"); state = STATE_WORDS_W; } break; case STATE_WORDS_W: break; } } public void endElement(String uri, String localName, String qName) throws SAXException { switch(state) { case STATE_WORDS: { if(qName.equals(TAG_WORDS)) { state = STATE_START; } break; } case STATE_WORDS_W: { if(qName.equals(TAG_W)) { parent.setProgress(progress++); try { if(data_w != null && data_w.length() > 0) { data_w = data_w.trim(); Topic otherTermTopic = getTermTopic(data_w, tm); if(termTopic != null && otherTermTopic != null) { Topic relationshipType = null; if("syn".equalsIgnoreCase(data_r)) { relationshipType = getSynonymType(tm); } else if("ant".equalsIgnoreCase(data_r)) { relationshipType = getSynonymType(tm); } else if("rel".equalsIgnoreCase(data_r)) { relationshipType = getRelatedType(tm); } else if("sim".equalsIgnoreCase(data_r)) { relationshipType = getSimilarType(tm); } else if("usr".equalsIgnoreCase(data_r)) { relationshipType = getUserSuggestionsType(tm); } if(RELATIONSHIP_AS_ASSOCIATION_TYPE) { if(relationshipType != null) { Association relationship = tm.createAssociation(relationshipType); relationship.addPlayer(termTopic, getTermType(tm)); relationship.addPlayer(otherTermTopic, getRelatedTermType(tm)); if(INCLUDE_PART_OF_SPEECH) { Topic partOfSpeedTopic = getPartOfSpeechTopic(data_p, tm); Topic partOfSpeedType = getPartOfSpeechType(tm); if(partOfSpeedTopic != null && partOfSpeedType != null) { relationship.addPlayer(partOfSpeedTopic, partOfSpeedType); } } } } else { if(relationshipType != null) { Topic relationshipTypeType = getRelationshipType(tm); Association relationship = tm.createAssociation(relationshipTypeType); relationship.addPlayer(termTopic, getTermType(tm)); relationship.addPlayer(otherTermTopic, getRelatedTermType(tm)); relationship.addPlayer(relationshipType, relationshipTypeType); if(INCLUDE_PART_OF_SPEECH) { Topic partOfSpeedTopic = getPartOfSpeechTopic(data_p, tm); Topic partOfSpeedType = getPartOfSpeechType(tm); if(partOfSpeedTopic != null && partOfSpeedType != null) { relationship.addPlayer(partOfSpeedTopic, partOfSpeedType); } } } } } } } catch(Exception e) { parent.log(e); } state = STATE_WORDS; } break; } } } public void characters(char[] ch, int start, int length) throws SAXException { switch(state) { case STATE_WORDS_W: { data_w += new String(ch,start,length); break; } default: break; } } public void warning(SAXParseException exception) throws SAXException { } public void error(SAXParseException exception) throws SAXException { parent.log("Error parsing XML document at "+exception.getLineNumber()+","+exception.getColumnNumber(),exception); } public void fatalError(SAXParseException exception) throws SAXException { parent.log("Fatal error parsing XML document at "+exception.getLineNumber()+","+exception.getColumnNumber(),exception); } public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {} public void processingInstruction(String target, String data) throws SAXException {} public void startPrefixMapping(String prefix, String uri) throws SAXException {} public void endPrefixMapping(String prefix) throws SAXException {} public void setDocumentLocator(org.xml.sax.Locator locator) {} public void skippedEntity(String name) throws SAXException {} } }
20,165
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
BigHugeThesaurusSelector.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/bighugethesaurus/BigHugeThesaurusSelector.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * BigHugeThesaurusSelector.java * * Created on 26.12.2009, 12:45:42 */ package org.wandora.application.tools.extractors.bighugethesaurus; import java.awt.Component; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.application.gui.simple.SimpleButton; import org.wandora.application.gui.simple.SimpleField; import org.wandora.application.gui.simple.SimpleLabel; import org.wandora.application.gui.simple.SimpleTabbedPane; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; /** * * @author akivela */ public class BigHugeThesaurusSelector extends javax.swing.JDialog { private static final long serialVersionUID = 1L; public static String defaultLanguage = "en"; public static String apiURL = "http://words.bighugelabs.com/api/2/__2__/__1__/xml"; private Wandora wandora = null; private Context context = null; private boolean accepted = false; /** Creates new form BigHugeThesaurusSelector */ public BigHugeThesaurusSelector(Wandora wandora) { super(wandora, true); initComponents(); setTitle("Big Huge Thesaurus extractor"); setSize(500,200); wandora.centerWindow(this); this.wandora = wandora; accepted = false; } public void setWandora(Wandora wandora) { this.wandora = wandora; } public void setContext(Context context) { this.context = context; } public boolean wasAccepted() { return accepted; } public void setAccepted(boolean b) { accepted = b; } public WandoraTool getWandoraTool(WandoraTool parentTool) { Component component = tabbedPane.getSelectedComponent(); WandoraTool wt = null; // ***** WORDS ***** if(wordPanel.equals(component)) { String wordsAll = wordTextField.getText(); String[] words = urlEncode(commaSplitter(wordsAll)); String apikey = solveAPIKey(); if(apikey != null && apikey.length() > 0) { apikey = apikey.trim(); String[] wordUrls = completeString(apiURL, words, apikey); XMLBigHugeThesaurusExtractor ex = new XMLBigHugeThesaurusExtractor(); ex.setForceUrls( wordUrls ); wt = ex; } else { parentTool.log("Invalid apikey given. Aborting..."); } } return wt; } public String[] newlineSplitter(String str) { if(str.indexOf('\n') != -1) { String[] strs = str.split("\n"); ArrayList<String> strList = new ArrayList<String>(); String s = null; for(int i=0; i<strs.length; i++) { s = strs[i]; s = s.trim(); if(s.length() > 0) { strList.add(s); } } return strList.toArray( new String[] {} ); } else { return new String[] { str }; } } public String[] commaSplitter(String str) { if(str.indexOf(',') != -1) { String[] strs = str.split(","); ArrayList<String> strList = new ArrayList<String>(); String s = null; for(int i=0; i<strs.length; i++) { s = strs[i]; s = s.trim(); if(s.length() > 0) { strList.add(s); } } return strList.toArray( new String[] {} ); } else { return new String[] { str }; } } public String[] completeString(String template, String[] strs) { if(strs == null || template == null) return null; String[] completed = new String[strs.length]; for(int i=0; i<strs.length; i++) { completed[i] = template.replaceAll("__1__", strs[i]); } return completed; } public String[] completeString(String template, String[] strs1, String[] strs2) { if(strs1 == null || strs2 == null || template == null) return null; if(strs1.length != strs2.length) return null; String[] completed = new String[strs1.length]; for(int i=0; i<strs1.length; i++) { completed[i] = template.replaceAll("__1__", strs1[i]); completed[i] = completed[i].replaceAll("__2__", strs2[i]); } return completed; } public String[] completeString(String template, String[] strs1, String strs2) { if(strs1 == null || strs2 == null || template == null) return null; String[] completed = new String[strs1.length]; for(int i=0; i<strs1.length; i++) { completed[i] = template.replaceAll("__1__", strs1[i]); completed[i] = completed[i].replaceAll("__2__", strs2); } return completed; } public String[] completeString(String template, String[] strs1, String strs2, String strs3) { if(strs1 == null || strs2 == null || template == null) return null; String[] completed = new String[strs1.length]; for(int i=0; i<strs1.length; i++) { completed[i] = template.replaceAll("__1__", strs1[i]); completed[i] = completed[i].replaceAll("__2__", strs2); completed[i] = completed[i].replaceAll("__3__", strs3); } return completed; } public String[] urlEncode(String[] urls) { if(urls == null) return null; String[] cleanUrls = new String[urls.length]; for(int i=0; i<urls.length; i++) { cleanUrls[i] = urlEncode(urls[i]); } return cleanUrls; } public String urlEncode(String url) { try { return URLEncoder.encode(url, "UTF-8"); } catch(Exception e) { return url; } } public String getContextAsString() { 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.getBaseName(); str = t.getDisplayName("en"); if(str != null) { str = str.trim(); } } if(str != null && str.length() > 0) { sb.append(str); if(contextObjects.hasNext()) { sb.append(", "); } } } } catch(Exception e) { e.printStackTrace(); } } return sb.toString(); } public String getContextAsSIs(String delim) { StringBuffer sb = new StringBuffer(""); if(context != null) { try { Iterator contextObjects = context.getContextObjects(); String str = null; Object o = null; while(contextObjects.hasNext()) { str = null; o = contextObjects.next(); if(o instanceof Topic) { Topic t = (Topic) o; Collection<Locator> identifiers = t.getSubjectIdentifiers(); for( Iterator<Locator> iter = identifiers.iterator() ; iter.hasNext(); ) { Locator identifier = iter.next(); if(identifier != null) { str = identifier.toExternalForm().trim(); sb.append(str); if(iter.hasNext()) sb.append(delim); } } } } } catch(Exception e) { e.printStackTrace(); } } return sb.toString(); } public String getContextAsSI() { if(context != null) { try { Iterator contextObjects = context.getContextObjects(); String str = null; Object o = null; while(contextObjects.hasNext()) { str = null; o = contextObjects.next(); if(o instanceof Topic) { Topic t = (Topic) o; Collection<Locator> identifiers = t.getSubjectIdentifiers(); for( Iterator<Locator> iter = identifiers.iterator() ; iter.hasNext(); ) { Locator identifier = iter.next(); if(identifier != null) { str = identifier.toExternalForm().trim(); return str; } } } } } catch(Exception e) { e.printStackTrace(); } } return ""; } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- private static String apikey = null; private String solveAPIKey() { if(apikey == null) { apikey = ""; apikey = WandoraOptionPane.showInputDialog(wandora, "Please give valid apikey for Big Huge Thesaurus. You can register apikey at http://words.bighugelabs.com/api.php", apikey, "Big Huge Thesaurus apikey", WandoraOptionPane.QUESTION_MESSAGE); } return apikey; } public void forgetAuthorization() { apikey = 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; tabContainerPanel = new javax.swing.JPanel(); tabbedPane = new SimpleTabbedPane(); wordPanel = new javax.swing.JPanel(); wordLabel = new SimpleLabel(); wordTextField = new SimpleField(); getContextButton = new SimpleButton(); buttonPanel = new javax.swing.JPanel(); buttonFillerPanel = new javax.swing.JPanel(); extractButton = new SimpleButton(); cancelButton = new SimpleButton(); setTitle("Big Huge Thesaurus extractor"); getContentPane().setLayout(new java.awt.GridBagLayout()); tabContainerPanel.setLayout(new java.awt.GridBagLayout()); wordPanel.setLayout(new java.awt.GridBagLayout()); wordLabel.setText("<html>Big Huge Thesaurus extractor associates related words for given word(s). Please, write words to the field below.</html>"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5); wordPanel.add(wordLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); wordPanel.add(wordTextField, gridBagConstraints); getContextButton.setText("Get context"); getContextButton.setMargin(new java.awt.Insets(2, 4, 2, 4)); getContextButton.setMaximumSize(new java.awt.Dimension(100, 21)); getContextButton.setMinimumSize(new java.awt.Dimension(100, 21)); getContextButton.setPreferredSize(new java.awt.Dimension(100, 21)); getContextButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { getContextButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.insets = new java.awt.Insets(0, 5, 5, 5); wordPanel.add(getContextButton, gridBagConstraints); tabbedPane.addTab("Thesaurus", wordPanel); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; tabContainerPanel.add(tabbedPane, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 4, 0); getContentPane().add(tabContainerPanel, gridBagConstraints); buttonPanel.setLayout(new java.awt.GridBagLayout()); buttonFillerPanel.setPreferredSize(new java.awt.Dimension(100, 10)); javax.swing.GroupLayout buttonFillerPanelLayout = new javax.swing.GroupLayout(buttonFillerPanel); buttonFillerPanel.setLayout(buttonFillerPanelLayout); buttonFillerPanelLayout.setHorizontalGroup( buttonFillerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 255, Short.MAX_VALUE) ); buttonFillerPanelLayout.setVerticalGroup( buttonFillerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 10, Short.MAX_VALUE) ); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; buttonPanel.add(buttonFillerPanel, gridBagConstraints); extractButton.setText("Extract"); extractButton.setMaximumSize(new java.awt.Dimension(75, 21)); extractButton.setMinimumSize(new java.awt.Dimension(75, 21)); extractButton.setPreferredSize(new java.awt.Dimension(75, 21)); extractButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { extractButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3); buttonPanel.add(extractButton, gridBagConstraints); cancelButton.setText("Cancel"); cancelButton.setMaximumSize(new java.awt.Dimension(75, 21)); cancelButton.setMinimumSize(new java.awt.Dimension(75, 21)); cancelButton.setPreferredSize(new java.awt.Dimension(75, 21)); cancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelButtonActionPerformed(evt); } }); buttonPanel.add(cancelButton, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 4); getContentPane().add(buttonPanel, gridBagConstraints); pack(); }// </editor-fold>//GEN-END:initComponents private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed this.accepted = false; this.setVisible(false); }//GEN-LAST:event_cancelButtonActionPerformed private void extractButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_extractButtonActionPerformed this.accepted = true; this.setVisible(false); }//GEN-LAST:event_extractButtonActionPerformed private void getContextButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_getContextButtonActionPerformed String context = getContextAsString(); wordTextField.setText(context); }//GEN-LAST:event_getContextButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel buttonFillerPanel; private javax.swing.JPanel buttonPanel; private javax.swing.JButton cancelButton; private javax.swing.JButton extractButton; private javax.swing.JButton getContextButton; private javax.swing.JPanel tabContainerPanel; private javax.swing.JTabbedPane tabbedPane; private javax.swing.JLabel wordLabel; private javax.swing.JPanel wordPanel; private javax.swing.JTextField wordTextField; // End of variables declaration//GEN-END:variables }
18,690
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimpleFileExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/files/SimpleFileExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * SimpleDocumentExtractor.java * * Created on 31. lokakuuta 2007, 16:07 * */ package org.wandora.application.tools.extractors.files; import java.io.File; import java.net.URL; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; 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.browserextractors.BrowserExtractRequest; import org.wandora.application.tools.browserextractors.BrowserPluginExtractor; import org.wandora.application.tools.extractors.AbstractExtractor; import org.wandora.application.tools.extractors.ExtractHelper; import org.wandora.topicmap.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.DataURL; import org.wandora.utils.Textbox; import org.wandora.utils.XMLbox; /** * * @author akivela */ public class SimpleFileExtractor extends AbstractExtractor implements WandoraTool, BrowserPluginExtractor { private static final long serialVersionUID = 1L; protected static String TOPIC_SI = "http://wandora.org/si/topic"; protected static String SOURCE_SI = "http://wandora.org/si/source"; protected static String DOCUMENT_SI = "http://wandora.org/si/document"; protected static String DEFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; private String defaultLang = "en"; private Wandora wandora = null; private ArrayList<String> visitedDirectories = new ArrayList<String>(); /** Creates a new instance of SimpleFileExtractor */ public SimpleFileExtractor() { } @Override public String getName() { return "Simple File Extractor"; } @Override public String getDescription() { return "Creates topics for given files. The file URI is set as topic's subject locator."; } @Override public Icon getIcon() { return UIBox.getIcon(0xf016); } @Override public boolean useTempTopicMap(){ return false; } @Override public boolean useURLCrawler() { return false; } @Override public String getGUIText(int textType) { switch(textType) { case SELECT_DIALOG_TITLE: return "Select files(s) or directories containing files!"; case POINT_START_URL_TEXT: return "Where would you like to start the crawl?"; case INFO_WAIT_WHILE_WORKING: return "Wait while seeking files!"; case FILE_PATTERN: return ".*"; case DONE_FAILED: return "Ready. No extractions! %1 file(s) crawled!"; case DONE_ONE: return "Ready. Successful extraction! %1 file(s) crawled!"; case DONE_MANY: return "Ready. Total %0 successful extractions! %1 files crawled!"; case LOG_TITLE: return "Simple File Extraction Log"; } return ""; } // ---------------------------------------------------- PLUGIN EXTRACTOR --- @Override public String doBrowserExtract(BrowserExtractRequest request, Wandora wandora) throws TopicMapException { String url=request.getSource(); try { TopicMap tm=wandora.getTopicMap(); Topic theTopic=null; String content = request.getSelection(); // SOURCE IS A FRACTION OF URL if(content!=null) { String tidyContent = XMLbox.cleanUp( content ); if(tidyContent != null && tidyContent.length() > 0) { content = XMLbox.getAsText(tidyContent, "ISO-8859-1"); } Topic sourceTopic=tm.getTopicBySubjectLocator(url); if(sourceTopic==null) { sourceTopic=tm.createTopic(); Locator l = tm.createLocator(url); sourceTopic.addSubjectIdentifier(l); sourceTopic.setSubjectLocator(l); } theTopic = tm.createTopic(); theTopic.addSubjectIdentifier(tm.makeSubjectIndicatorAsLocator()); Association a = tm.createAssociation(getSourceType(tm)); a.addPlayer(theTopic, getDocumentType(tm)); a.addPlayer(sourceTopic, getSourceType(tm)); } // SOURCE IS A COMPLETE URL else { content = ExtractHelper.getContent(request); String tidyContent = XMLbox.cleanUp(content); if(tidyContent != null && tidyContent.length() > 0) { content = XMLbox.getAsText(tidyContent, "ISO-8859-1"); } theTopic=tm.getTopicBySubjectLocator(url); if(theTopic==null) { theTopic=tm.createTopic(); Locator l = tm.createLocator(url); theTopic.addSubjectIdentifier(l); theTopic.setSubjectLocator(l); } } } catch(Exception e){ e.printStackTrace(); return BrowserPluginExtractor.RETURN_ERROR+e.getMessage(); } wandora.doRefresh(); return null; } @Override public boolean browserExtractorConsumesPlainText() { return true; } // ------------------------------------------------------------------------- @Override public void execute(Wandora wandora, Context context) { visitedDirectories = new ArrayList<String>(); super.execute(wandora, context); } @Override public boolean _extractTopicsFrom(String str, TopicMap topicMap) throws Exception { if(str == null || str.length() == 0) return false; try { int hash = str.hashCode(); Topic documentType = this.getDocumentType(topicMap); String locator = "http://wandora.org/si/simple-file-extractor/"+hash; String name = null; if(str.length() > 80) { name = str.substring(0, 80) + " ("+hash+")"; } else { name = str; } Topic documentTopic = topicMap.getTopic(locator); if(documentTopic == null) documentTopic = topicMap.createTopic(); documentTopic.addSubjectIdentifier(new Locator( locator )); documentTopic.setBaseName(name); documentTopic.addType(documentType); if(DataURL.isDataURL(str)) { documentTopic.setSubjectLocator(new Locator(str)); } // --- ADD EXTRACTION TIME AS OCCURRENCE --- DateFormat dateFormatter = new SimpleDateFormat(DEFAULT_DATE_FORMAT); Topic extractionTimeType = createTopic(topicMap, "extraction-time"); String dateString = dateFormatter.format( new Date(System.currentTimeMillis()) ); setData(documentTopic, extractionTimeType, defaultLang, dateString); return true; } catch(Exception e) { log("Exception occurred while extracting from input string.", e); takeNap(1000); } return false; } @Override public boolean _extractTopicsFrom(URL url, TopicMap topicMap) throws Exception { if(url == null || url.toExternalForm().length() == 0) return false; try { Topic textType = this.getDocumentType(topicMap); String locator = url.toExternalForm(); int hash = locator.hashCode(); String name = url.getFile(); if(name != null && name.length() > 0) { if(name.lastIndexOf("/") > -1) { name = name.substring(name.lastIndexOf("/")+1); } } else { name = locator; } Topic documentTopic = topicMap.getTopic(locator); if(documentTopic == null) documentTopic = topicMap.createTopic(); documentTopic.addSubjectIdentifier(new Locator( locator )); documentTopic.setBaseName(name + " ("+hash+")"); documentTopic.setSubjectLocator(new Locator( locator )); documentTopic.addType(textType); // --- ADD EXTRACTION TIME AS OCCURRENCE --- DateFormat dateFormatter = new SimpleDateFormat(DEFAULT_DATE_FORMAT); Topic extractionTimeType = createTopic(topicMap, "extraction-time"); String dateString = dateFormatter.format( new Date(System.currentTimeMillis()) ); setData(documentTopic, extractionTimeType, defaultLang, dateString); return true; } catch(Exception e) { log("Exception occurred while extracting from url '" + url.toExternalForm()+"'.", e); takeNap(1000); } return false; } @Override public boolean _extractTopicsFrom(File file, TopicMap topicMap) throws Exception { if(file == null) return false; try { if(file.isDirectory()) { /* if(!visitedDirectories.contains(file.getAbsolutePath())) { visitedDirectories.add(file.getAbsolutePath()); File[] fs = file.listFiles(); for(int i=0; i<fs.length && !forceStop(); i++) { _extractTopicsFrom(fs[i], topicMap); } } */ return true; } } catch(Exception e) { log(e); } try { Topic textType = this.getDocumentType(topicMap); String locator = file.toURI().toURL().toExternalForm(); int hash = locator.hashCode(); Topic fileTopic = topicMap.getTopic(locator); if(fileTopic == null) fileTopic = topicMap.createTopic(); fileTopic.addSubjectIdentifier(new Locator( locator )); fileTopic.setBaseName(file.getName() + " ("+hash+")"); fileTopic.setSubjectLocator(new Locator( locator )); fileTopic.addType(textType); // --- ADD EXTRACTION TIME AS OCCURRENCE --- DateFormat dateFormatter = new SimpleDateFormat(DEFAULT_DATE_FORMAT); Topic extractionTimeType = createTopic(topicMap, "extraction-time"); String dateString = dateFormatter.format( new Date(System.currentTimeMillis()) ); setData(fileTopic, extractionTimeType, defaultLang, dateString); // --- ADD MODIFICATION TIME AS OCCURRENCE --- long lastModified = file.lastModified(); Topic modificationTimeType = createTopic(topicMap, "modification-time"); String modificationDateString = dateFormatter.format( new Date(lastModified) ); setData(fileTopic, modificationTimeType, defaultLang, modificationDateString); // --- ADD ABSOLUTE FILE NAME AS OCCURRENCE --- Topic fileType = createTopic(topicMap, "file-name"); String fileString = file.getAbsolutePath(); setData(fileTopic, fileType, defaultLang, fileString); return true; } catch(Exception e) { log("Exception occurred while extracting from file '" + file.getName()+"'.", e); takeNap(1000); } return false; } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- 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 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 static final String[] contentTypes=new String[] { "application/pdf", "text/plain", "text/html", "application/rtf", "application/xml", "application/msword" }; public String[] getContentTypes() { return contentTypes; } }
15,122
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimpleMP3Extractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/files/SimpleMP3Extractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * SimpleMP3Extractor.java * * Created on October 1, 2004, 3:46 PM */ package org.wandora.application.tools.extractors.files; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.util.Hashtable; import javax.swing.Icon; import org.apache.tika.metadata.Metadata; import org.apache.tika.parser.ParseContext; import org.apache.tika.parser.Parser; import org.apache.tika.parser.mp3.Mp3Parser; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.gui.UIBox; 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.TopicTools; import org.wandora.utils.IObox; import org.xml.sax.ContentHandler; import org.xml.sax.helpers.DefaultHandler; /** * * @author akivela */ public class SimpleMP3Extractor extends AbstractExtractor implements WandoraTool { private static final long serialVersionUID = 1L; private String tempFilename = "temp/wandora_temp.tmp"; private String baseLocator = "http://wandora.org/si/mp3"; private int extractionCounter = 0; private int foundCounter = 0; @Override public String getName() { return "Extract MP3 metadata..."; } @Override public String getDescription(){ return "Extracts metadata from MP3 files. Both ID3V1 and ID3V2 metadata tags are supported!"; } @Override public Icon getIcon() { return UIBox.getIcon(0xf1c7); } @Override public int getExtractorType() { return FILE_EXTRACTOR | URL_EXTRACTOR; } @Override public String getGUIText(int textType) { switch(textType) { case SELECT_DIALOG_TITLE: return "Select MP3 file(s) or directories!"; case POINT_START_URL_TEXT: return "Where would you like to start the crawl?"; case INFO_WAIT_WHILE_WORKING: return "Wait while seeking MP3 files with ID3V1 or ID3V2 metadata!"; case FILE_PATTERN: return ".*\\.(mp3|MP3|Mp3|MPEG3|mpeg3)"; case DONE_FAILED: return "Ready. No extractions! %1 mp3 file(s) crawled!"; case DONE_ONE: return "Ready. Successful extraction! %1 mp3 file(s) crawled!"; case DONE_MANY: return "Ready. Total %0 successful extractions! %1 mp3 files crawled!"; case LOG_TITLE: return "MP3 ID3V[12] Extraction Log"; } return ""; } @Override public synchronized void extractTopicsFrom(URL url, TopicMap topicMap) throws Exception { try { foundCounter++; setProgress(foundCounter); String urlString = url.toExternalForm(); log("Extracting from url '" + croppedUrlString(urlString)+"'"); TopicMap tempMap = new org.wandora.topicmap.memory.TopicMapImpl(); URLConnection uc = null; if(getWandora() != null) { uc = getWandora().wandoraHttpAuthorizer.getAuthorizedAccess(url); } else { uc = url.openConnection(); Wandora.initUrlConnection(uc); } Object content = uc.getContent(); IObox.saveBFile(tempFilename, (InputStream) content); File tempFile = new File(tempFilename); if(_extractTopicsFrom(tempFile, tempMap)) { Topic t = tempMap.getTopicBySubjectLocator(buildSL(tempFile)); t.setSubjectLocator(new Locator(urlString)); Locator l = t.getOneSubjectIdentifier(); t.addSubjectIdentifier(new Locator(urlString)); t.removeSubjectIdentifier(l); topicMap.mergeIn(tempMap); extractionCounter++; } else { log("Found no valid metadata in '"+croppedUrlString(urlString)+"'"); } } catch (Exception e) { log("Exception occurred '" + e.toString()+"'", e); } log("Wait while extracting metadata out of MP3 files!"); } public boolean _extractTopicsFrom(String str, TopicMap topicMap) throws Exception { throw(new Exception(STRING_EXTRACTOR_NOT_SUPPORTED_MESSAGE)); } public boolean _extractTopicsFrom(URL file, TopicMap topicMap) throws Exception { return false; } public boolean _extractTopicsFrom(File file, TopicMap topicMap) throws Exception { if(file == null || file.isDirectory()) return false; try { InputStream input = new FileInputStream(file); ContentHandler handler = new DefaultHandler(); Metadata metadata = new Metadata(); Parser parser = new Mp3Parser(); ParseContext parseCtx = new ParseContext(); parser.parse(input, handler, metadata, parseCtx); input.close(); if(metadata != null) { String length = metadata.get("xmpDM:duration"); String bpm = null; String lan = null; String media = null; String frequency = null; String bitrate = null; String album = metadata.get("xmpDM:album"); String artist = metadata.get("xmpDM:artist"); String genre = metadata.get("xmpDM:genre"); String title = metadata.get("title"); String identifier = null; String year = metadata.get("xmpDM:releaseDate"); if(title != null) { Topic wandoraClass = topicMap.createTopic(); wandoraClass.addSubjectIdentifier(new Locator(TMBox.WANDORACLASS_SI)); wandoraClass.setBaseName("Wandora class"); Topic lengthType = createTopic(topicMap, "length"); Topic frequencyType = createTopic(topicMap, "frequency"); Topic bitrateType = createTopic(topicMap, "bitrate"); Topic isVariableBitRateType = createTopic(topicMap, "isVariableBitRate"); Topic isCopyProtectedType = createTopic(topicMap, "isCopyProtected"); Topic containsType = createTopic(topicMap, "contains"); Topic hasAlbumType = createTopic(topicMap, "hasAlbum"); Topic hasTitleType = createTopic(topicMap, "hasTitle"); Topic isGenreType = createTopic(topicMap, "isGenre"); Topic timeType = createTopic(topicMap, "timeApellation"); Topic identifiesType = createTopic(topicMap, "identifies"); Topic mp3Type = createTopic(topicMap, "MP3", wandoraClass); Topic albumType = createTopic(topicMap, "album", mp3Type); Topic artistType = createTopic(topicMap, "artist", mp3Type); Topic genreType = createTopic(topicMap, "genre", mp3Type); Topic titleType = createTopic(topicMap, "title", mp3Type); Topic yearType = createTopic(topicMap, "year", mp3Type); Topic identifierType = createTopic(topicMap, "identifier", mp3Type); Topic albumT = null; Topic artistT = null; Topic genreT = null; Topic yearT = null; Topic identifierT = null; Topic titleT = null; if(title != null && title.length()>0) titleT = createTopic(topicMap, "title/" + title, " (title)", title, titleType); if(album != null && album.length()>0) albumT = createTopic(topicMap, "album/" + album, " (album)", album, albumType); if(artist != null && artist.length()>0) artistT = createTopic(topicMap, "artist/" + artist, " (artist)", artist, artistType); if(genre != null) genreT = createTopic(topicMap, "genre/" + genre, " (genre)", "" + genre, genreType); if(year != null && year.length()>0) yearT = createTopic(topicMap, "year/" + year, " (year)", year, yearType); if(identifier != null && identifier.length()>0) identifierT = createTopic(topicMap, "identifier/" + identifier, " (identifier)", identifier, identifierType); if(titleT != null && albumT != null) createAssociation(topicMap, containsType, new Topic[] { titleT, albumT } ); if(artistT != null && albumT != null) createAssociation(topicMap, hasAlbumType, new Topic[] { artistT, albumT } ); if(artistT != null && titleT != null) createAssociation(topicMap, hasTitleType, new Topic[] { artistT, titleT } ); if(titleT != null && genreT != null) createAssociation(topicMap, isGenreType, new Topic[] { titleT, genreT } ); if(titleT != null && identifierT != null) createAssociation(topicMap, identifiesType, new Topic[] { titleT, identifierT } ); if(titleT != null && yearT != null) createAssociation(topicMap, timeType, new Topic[] { titleT, yearT } ); if(titleT != null) { titleT.setSubjectLocator(buildSL(file)); Topic lanT = topicMap.getTopic(TMBox.LANGINDEPENDENT_SI); if(lanT == null) { lanT = topicMap.createTopic(); lanT.addSubjectIdentifier(new Locator(TMBox.LANGINDEPENDENT_SI)); lanT.setBaseName("Language independent"); } Hashtable hash = null; if(frequency != null) { hash = new Hashtable(); hash.put(lanT, frequency); titleT.setData(frequencyType,hash); } if(bitrate != null) { hash = new Hashtable(); hash.put(lanT, bitrate); titleT.setData(bitrateType,hash); } if(length != null) { hash = new Hashtable(); hash.put(lanT, length); titleT.setData(lengthType,hash); } } return true; } else { return false; } } } catch (Exception e) { log("Exception occurred while extracting from mp3 file.", e); } return false; } @Override public Locator buildSI(String siend) { if(!baseLocator.endsWith("/")) baseLocator = baseLocator + "/"; return new Locator(TopicTools.cleanDirtyLocator(baseLocator + siend)); } private final String[] contentTypes=new String[] { "audio/mp3", "audio/mpeg", "audio/x-mp3", "audio/x-mpeg", "audio/m3u", "audio/x-m3u" }; @Override public String[] getContentTypes() { return contentTypes; } // ------------------------------------------------------------------------- // --- GENRE SOLVER -------------------------------------------------------- // ------------------------------------------------------------------------- public static class GenreSolver { private static String[][] genreCodes = { { "0", "Blues" }, { "1", "Classic Rock" }, { "2", "Country" }, { "3", "Dance" }, { "4", "Disco" }, { "5", "Funk" }, { "6", "Grunge" }, { "7", "Hip-Hop" }, { "8", "Jazz" }, { "9", "Metal" }, { "10", "New Age" }, { "11", "Oldies" }, { "12", "Other" }, { "13", "Pop" }, { "14", "R&B" }, { "15", "Rap" }, { "16", "Reggae" }, { "17", "Rock" }, { "18", "Techno" }, { "19", "Industrial" }, { "20", "Alternative" }, { "21", "Ska" }, { "22", "Death Metal" }, { "23", "Pranks" }, { "24", "Soundtrack" }, { "25", "Euro-Techno" }, { "26", "Ambient" }, { "27", "Trip-Hop" }, { "28", "Vocal" }, { "29", "Jazz+Funk" }, { "30", "Fusion" }, { "31", "Trance" }, { "32", "Classical" }, { "33", "Instrumental" }, { "34", "Acid" }, { "35", "House" }, { "36", "Game" }, { "37", "Sound Clip" }, { "38", "Gospel" }, { "39", "Noise" }, { "40", "AlternRock" }, { "41", "Bass" }, { "42", "Soul" }, { "43", "Punk" }, { "44", "Space" }, { "45", "Meditative" }, { "46", "Instrumental Pop" }, { "47", "Instrumental Rock" }, { "48", "Ethnic" }, { "49", "Gothic" }, { "50", "Darkwave" }, { "51", "Techno-Industrial" }, { "52", "Electronic" }, { "53", "Pop-Folk" }, { "54", "Eurodance" }, { "55", "Dream" }, { "56", "Southern Rock" }, { "57", "Comedy" }, { "58", "Cult" }, { "59", "Gangsta" }, { "60", "Top 40" }, { "61", "Christian Rap" }, { "62", "Pop/Funk" }, { "63", "Jungle" }, { "64", "Native American" }, { "65", "Cabaret" }, { "66", "New Wave" }, { "67", "Psychadelic" }, { "68", "Rave" }, { "69", "Showtunes" }, { "70", "Trailer" }, { "71", "Lo-Fi" }, { "72", "Tribal" }, { "73", "Acid Punk" }, { "74", "Acid Jazz" }, { "75", "Polka" }, { "76", "Retro" }, { "77", "Musical" }, { "78", "Rock & Roll" }, { "79", "Hard Rock" }, { "80", "Folk" }, { "81", "Folk-Rock" }, { "82", "National Folk" }, { "83", "Swing" }, { "84", "Fast Fusion" }, { "85", "Bebob" }, { "86", "Latin" }, { "87", "Revival" }, { "88", "Celtic" }, { "89", "Bluegrass" }, { "90", "Avantgarde" }, { "91", "Gothic Rock" }, { "92", "Progressive Rock" }, { "93", "Psychedelic Rock" }, { "94", "Symphonic Rock" }, { "95", "Slow Rock" }, { "96", "Big Band" }, { "97", "Chorus" }, { "98", "Easy Listening" }, { "99", "Acoustic" }, { "100", "Humour" }, { "101", "Speech" }, { "102", "Chanson" }, { "103", "Opera" }, { "104", "Chamber Music" }, { "105", "Sonata" }, { "106", "Symphony" }, { "107", "Booty Bass" }, { "108", "Primus" }, { "109", "Porn Groove" }, { "110", "Satire" }, { "111", "Slow Jam" }, { "112", "Club" }, { "113", "Tango" }, { "114", "Samba" }, { "115", "Folklore" }, { "116", "Ballad" }, { "117", "Power Ballad" }, { "118", "Rhythmic Soul" }, { "119", "Freestyle" }, { "120", "Duet" }, { "121", "Punk Rock" }, { "122", "Drum Solo" }, { "123", "A capella" }, { "124", "Euro-House" }, { "125", "Dance Hall" }, }; public static String get(int genreCode) { if(genreCode > -1) { for(int i=0; i<genreCodes.length; i++) { if(genreCodes[i][0].equals("" + genreCode)) { return genreCodes[i][1]; } } } return "" + genreCode; } } }
17,278
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DirectoryStructureExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/files/DirectoryStructureExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * DirectoryStructureExtractor.java * * Created on 15. toukokuuta 2006, 15:39 * */ package org.wandora.application.tools.extractors.files; import java.io.File; import java.net.URL; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; 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.Locator; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author akivela */ public class DirectoryStructureExtractor extends AbstractExtractor implements WandoraTool { private static final long serialVersionUID = 1L; private String DEFAULT_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ssZ"; private String defaultLang = "en"; public static boolean USE_SUPERSUBCLASS_RELATION = true; /** Creates a new instance of DirectoryStructureExtractor */ public DirectoryStructureExtractor() { } private String baseLocator = "http://wandora.org/si/directory-structure-extractor/"; @Override public int getExtractorType() { return FILE_EXTRACTOR; } @Override public String getName() { return "Extract directory structure"; } @Override public String getDescription(){ return "Converts given directory stucture to a topic map where directories are associated with files and directories within."; } @Override public Icon getIcon() { return UIBox.getIcon(0xf114); } @Override public String getGUIText(int textType) { switch(textType) { case SELECT_DIALOG_TITLE: return "Select file(s) or directories!"; case POINT_START_URL_TEXT: return "Where would you like to start the crawl?"; case INFO_WAIT_WHILE_WORKING: return "Wait while seeking files!"; case FILE_PATTERN: return ".*"; case DONE_FAILED: return "Ready. No extractions! %2 file(s) crawled!"; case DONE_ONE: return "Ready. Successful extraction! %2 file(s) crawled!"; case DONE_MANY: return "Ready. Total %0 successful extractions! %2 files crawled!"; case LOG_TITLE: return "Directory Structure Extraction Log"; } return ""; } @Override public boolean _extractTopicsFrom(File file, TopicMap topicMap) throws Exception { if(file != null) { try { Topic dirType = createTopic(topicMap, baseLocator+"directory", "Directory"); Topic fileType = createTopic(topicMap, baseLocator+"file", "File"); Topic wandoraClass = getWandoraClass(topicMap); makeSubclassOf(topicMap, dirType, wandoraClass); makeSubclassOf(topicMap, fileType, wandoraClass); Topic fileTopic = null; String location = file.toURI().toURL().toExternalForm(); String name = buildBaseName(file); Topic typeTopic = null; if(file.isDirectory()) { typeTopic = dirType; } else { typeTopic = fileType; } fileTopic = createTopic(topicMap, location, name, typeTopic ); // --- SET FILE TOPIC'S VARIANT NAMES --- setDisplayName(fileTopic, defaultLang, file.getName()); fileTopic.setSubjectLocator(new Locator( location )); // --- ADD LAST MODIFICATION TIME AS OCCURRENCE --- try { DateFormat dateFormatter = new SimpleDateFormat(DEFAULT_DATE_FORMAT); Topic modType = createTopic(topicMap, baseLocator+"file-modified", "file-modified"); String dateString = dateFormatter.format( new Date(file.lastModified()) ); setData(fileTopic, modType, defaultLang, dateString); } catch(Exception e) { log("Exception occurred while setting file topic's modification time!", e); } // --- ADD FILE SIZE AS OCCURRENCE --- try { Topic sizeType = createTopic(topicMap, baseLocator+"file-size", "file-size"); setData(fileTopic, sizeType, defaultLang, ""+file.length()); } catch(Exception e) { log("Exception occurred while setting file topic's file size!", e); } // --- ADD TYPES IF FILE IS READABLE/WRITEABLE/HIDDEN --- try { if(file.canRead()) { Topic accessRightsType = createTopic(topicMap, baseLocator+"accessibility", "accessibility"); Topic readableFileType = createTopic(topicMap, baseLocator+"readable-file", "readable-file"); createAssociation(topicMap, accessRightsType, new Topic[] { fileTopic, readableFileType }, new Topic[] { fileType, accessRightsType } ); } if(file.canWrite()) { Topic accessRightsType = createTopic(topicMap, baseLocator+"accessibility", "accessibility"); Topic writeableFileType = createTopic(topicMap, baseLocator+"writeable-file", "writeable-file"); createAssociation(topicMap, accessRightsType, new Topic[] { fileTopic, writeableFileType }, new Topic[] { fileType, accessRightsType } ); } if(file.isHidden()) { Topic accessRightsType = createTopic(topicMap, baseLocator+"accessibility", "accessibility"); Topic hiddenFileType = createTopic(topicMap, baseLocator+"hidden-file", "hidden-file"); createAssociation(topicMap, accessRightsType, new Topic[] { fileTopic, hiddenFileType }, new Topic[] { fileType, accessRightsType } ); } } catch(Exception e) { log("Exception occurred while solving file's accessibility!", e); } // --- ADD ASSOCIATION TO PARENT FILE --- if(file.getParentFile() != null) { File parent = file.getParentFile(); if(parent != null && parent.exists()) { Topic parentDirectoryTopic = createTopic(topicMap, buildBaseName(parent), dirType ); setDisplayName(parentDirectoryTopic, defaultLang, parent.getName()); if(USE_SUPERSUBCLASS_RELATION) { makeSubclassOf(topicMap, fileTopic, parentDirectoryTopic); } else { Topic locatedType = createTopic(topicMap, baseLocator+"is-located", "is-located"); createAssociation(topicMap, locatedType, new Topic[] { fileTopic, parentDirectoryTopic }, new Topic[] { fileType, dirType } ); } } } // --- ADD EXTRACTION TIME AS OCCURRENCE --- DateFormat dateFormatter = new SimpleDateFormat(DEFAULT_DATE_FORMAT); Topic extractionTimeType = createTopic(topicMap, "extraction-time"); String dateString = dateFormatter.format( new Date(System.currentTimeMillis()) ); setData(fileTopic, extractionTimeType, defaultLang, dateString); return true; } catch (Exception e) { log(e); e.printStackTrace(); } } return false; } @Override public boolean _extractTopicsFrom(String str, TopicMap topicMap) throws Exception { throw(new Exception(STRING_EXTRACTOR_NOT_SUPPORTED_MESSAGE)); } // THIS TOOL SUPPORTS NO URL EXTRACTING! @Override public boolean _extractTopicsFrom(URL url, TopicMap topicMap) throws Exception { return false; } // ------------------------------------------------------------------------- public Topic getWandoraClass(TopicMap tm) throws TopicMapException { return getOrCreateTopic(tm, TMBox.WANDORACLASS_SI,"Wandora class"); } protected void makeSubclassOf(TopicMap tm, Topic t, Topic superclass) throws TopicMapException { ExtractHelper.makeSubclassOf(t, superclass, tm); } protected Topic getOrCreateTopic(TopicMap tm, String si, String bn) throws TopicMapException { return ExtractHelper.getOrCreateTopic(si, bn, tm); } // ----------- public String buildBaseName(File file) { if(file == null) return "[null]"; return file.getName() + " ("+file.getAbsolutePath().hashCode()+")"; } @Override public Locator buildSI(String siend) { if(siend.startsWith("http://")) { return new Locator(siend); } else if(siend.startsWith("file:/")) { return new Locator(siend); } else { try { return new Locator(new File(siend).toURI().toString()); } catch(Exception e) { return new Locator("file:/" + siend); } } } }
10,557
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimpleDocumentExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/files/SimpleDocumentExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * SimpleDocumentExtractor.java * * Created on 31. lokakuuta 2007, 16:07 * */ package org.wandora.application.tools.extractors.files; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.List; import javax.swing.Icon; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDDocumentInformation; import org.apache.pdfbox.text.PDFTextStripper; 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.browserextractors.BrowserExtractRequest; import org.wandora.application.tools.browserextractors.BrowserPluginExtractor; import org.wandora.application.tools.extractors.AbstractExtractor; import org.wandora.application.tools.extractors.ExtractHelper; import org.wandora.topicmap.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.DataURL; import org.wandora.utils.IObox; import org.wandora.utils.MSOfficeBox; import org.wandora.utils.MimeTypes; import org.wandora.utils.OpenOfficeBox; import org.wandora.utils.Textbox; import org.wandora.utils.XMLbox; import eu.medsea.mimeutil.MimeType; import eu.medsea.mimeutil.MimeUtil; /** * * @author akivela */ public class SimpleDocumentExtractor extends AbstractExtractor implements WandoraTool, BrowserPluginExtractor { private static final long serialVersionUID = 1L; protected static String TOPIC_SI = "http://wandora.org/si/topic"; protected static String SOURCE_SI = "http://wandora.org/si/source"; protected static String DOCUMENT_SI = "http://wandora.org/si/document"; protected static String DEFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; private String defaultLang = "en"; private Wandora wandora = null; private ArrayList<String> visitedDirectories = new ArrayList<>(); /** Creates a new instance of SimpleDocumentExtractor */ public SimpleDocumentExtractor() { } @Override public String getName() { return "Simple document extractor"; } @Override public String getDescription() { return "Creates a topic for given document and stores document content to an occurrence attached to the topic."; } @Override public Icon getIcon() { return UIBox.getIcon(0xf016); // or 0xf15b } @Override public boolean useTempTopicMap(){ return false; } @Override public boolean useURLCrawler() { return false; } @Override public String getGUIText(int textType) { switch(textType) { case SELECT_DIALOG_TITLE: return "Select document(s) or directories containing documents!"; case POINT_START_URL_TEXT: return "Where would you like to start the crawl?"; case INFO_WAIT_WHILE_WORKING: return "Wait while seeking documents!"; case FILE_PATTERN: return ".*"; case DONE_FAILED: return "Ready. No extractions! %1 file(s) crawled!"; case DONE_ONE: return "Ready. Successful extraction! %1 file(s) crawled!"; case DONE_MANY: return "Ready. Total %0 successful extractions! %1 files crawled!"; case LOG_TITLE: return "Simple Text Document Extraction Log"; } return ""; } // ---------------------------------------------------- PLUGIN EXTRACTOR --- @Override public String doBrowserExtract(BrowserExtractRequest request, Wandora wandora) throws TopicMapException { String url=request.getSource(); try { TopicMap tm=wandora.getTopicMap(); Topic theTopic=null; String content = request.getSelection(); // SOURCE IS A FRACTION OF URL if(content!=null) { String tidyContent = XMLbox.cleanUp( content ); if(tidyContent != null && tidyContent.length() > 0) { content = XMLbox.getAsText(tidyContent, "ISO-8859-1"); } Topic sourceTopic=tm.getTopicBySubjectLocator(url); if(sourceTopic==null) { sourceTopic=tm.createTopic(); Locator l = tm.createLocator(url); sourceTopic.addSubjectIdentifier(l); sourceTopic.setSubjectLocator(l); } theTopic = tm.createTopic(); theTopic.addSubjectIdentifier(tm.makeSubjectIndicatorAsLocator()); fillDocumentTopic(theTopic, tm, content); Association a = tm.createAssociation(getSourceType(tm)); a.addPlayer(theTopic, getDocumentType(tm)); a.addPlayer(sourceTopic, getSourceType(tm)); } // SOURCE IS A COMPLETE URL else { content = ExtractHelper.getContent(request); String tidyContent = XMLbox.cleanUp(content); if(tidyContent != null && tidyContent.length() > 0) { content = XMLbox.getAsText(tidyContent, "ISO-8859-1"); } theTopic=tm.getTopicBySubjectLocator(url); if(theTopic==null) { theTopic=tm.createTopic(); Locator l = tm.createLocator(url); theTopic.addSubjectIdentifier(l); theTopic.setSubjectLocator(l); } fillDocumentTopic(theTopic, tm, content); } } catch(Exception e){ e.printStackTrace(); return BrowserPluginExtractor.RETURN_ERROR+e.getMessage(); } wandora.doRefresh(); return null; } @Override public boolean browserExtractorConsumesPlainText() { return true; } // ------------------------------------------------------------------------- @Override public void execute(Wandora wandora, Context context) { visitedDirectories = new ArrayList<String>(); super.execute(wandora, context); } @Override public boolean _extractTopicsFrom(String str, TopicMap topicMap) throws Exception { if(str == null || str.length() == 0) return false; try { int hash = str.hashCode(); Topic documentType = this.getDocumentType(topicMap); String locator = "http://wandora.org/si/simple-document-extractor/"+hash; String name = null; if(str.length() > 80) { name = str.substring(0, 80) + " ("+hash+")"; } else { name = str; } Topic documentTopic = topicMap.getTopic(locator); if(documentTopic == null) documentTopic = topicMap.createTopic(); documentTopic.addSubjectIdentifier(new Locator( locator )); documentTopic.setBaseName(name); documentTopic.addType(documentType); // --- ADD EXTRACTION TIME AS OCCURRENCE --- DateFormat dateFormatter = new SimpleDateFormat(DEFAULT_DATE_FORMAT); Topic extractionTimeType = createTopic(topicMap, "extraction-time"); String dateString = dateFormatter.format( new Date(System.currentTimeMillis()) ); setData(documentTopic, extractionTimeType, defaultLang, dateString); _extractTopicsFromStream(locator, new ByteArrayInputStream(str.getBytes()), topicMap, documentTopic); return true; } catch(Exception e) { log("Exception occurred while extracting from input string.", e); takeNap(1000); } return false; } @Override public boolean _extractTopicsFrom(URL url, TopicMap topicMap) throws Exception { if(url == null || url.toExternalForm().length() == 0) return false; try { Topic documentType = this.getDocumentType(topicMap); String locator = url.toExternalForm(); int hash = locator.hashCode(); String name = url.getFile(); if(name != null && name.length() > 0) { if(name.lastIndexOf("/") > -1) { name = name.substring(name.lastIndexOf("/")+1); } } else { name = locator; } Topic documentTopic = topicMap.getTopic(locator); if(documentTopic == null) documentTopic = topicMap.createTopic(); documentTopic.addSubjectIdentifier(new Locator( locator )); documentTopic.setBaseName(name + " ("+hash+")"); documentTopic.setSubjectLocator(new Locator( locator )); documentTopic.addType(documentType); // --- ADD EXTRACTION TIME AS OCCURRENCE --- DateFormat dateFormatter = new SimpleDateFormat(DEFAULT_DATE_FORMAT); Topic extractionTimeType = createTopic(topicMap, "extraction-time"); String dateString = dateFormatter.format( new Date(System.currentTimeMillis()) ); setData(documentTopic, extractionTimeType, defaultLang, dateString); URLConnection uc = null; if(wandora != null) { uc = wandora.wandoraHttpAuthorizer.getAuthorizedAccess(url); } else { uc = url.openConnection(); Wandora.initUrlConnection(uc); } _extractTopicsFromStream(url.toExternalForm(), uc.getInputStream(), topicMap, documentTopic); return true; } catch(Exception e) { log("Exception occurred while extracting from url '" + url.toExternalForm()+"'.", e); takeNap(1000); } return false; } @Override public boolean _extractTopicsFrom(File file, TopicMap topicMap) throws Exception { if(file == null) return false; try { if(file.isDirectory()) { /* if(!visitedDirectories.contains(file.getAbsolutePath())) { visitedDirectories.add(file.getAbsolutePath()); File[] fs = file.listFiles(); for(int i=0; i<fs.length && !forceStop(); i++) { _extractTopicsFrom(fs[i], topicMap); } } */ return true; } } catch(Exception e) { log(e); } try { Topic documentType = this.getDocumentType(topicMap); String locator = file.toURI().toURL().toExternalForm(); int hash = locator.hashCode(); Topic documentTopic = topicMap.getTopic(locator); if(documentTopic == null) documentTopic = topicMap.createTopic(); documentTopic.addSubjectIdentifier(new Locator( locator )); documentTopic.setBaseName(file.getName() + " ("+hash+")"); documentTopic.setSubjectLocator(new Locator( locator )); documentTopic.addType(documentType); // --- ADD EXTRACTION TIME AS OCCURRENCE --- DateFormat dateFormatter = new SimpleDateFormat(DEFAULT_DATE_FORMAT); Topic extractionTimeType = createTopic(topicMap, "extraction-time"); String dateString = dateFormatter.format( new Date(System.currentTimeMillis()) ); setData(documentTopic, extractionTimeType, defaultLang, dateString); // --- ADD MODIFICATION TIME AS OCCURRENCE --- long lastModified = file.lastModified(); Topic modificationTimeType = createTopic(topicMap, "modification-time"); String modificationDateString = dateFormatter.format( new Date(lastModified) ); setData(documentTopic, modificationTimeType, defaultLang, modificationDateString); // --- ADD ABSOLUTE FILE NAME AS OCCURRENCE --- Topic fileType = createTopic(topicMap, "file-name"); String fileString = file.getAbsolutePath(); setData(documentTopic, fileType, defaultLang, fileString); _extractTopicsFromStream(file.getPath(), new FileInputStream(file), topicMap, documentTopic); return true; } catch(Exception e) { log("Exception occurred while extracting from file '" + file.getName()+"'.", e); takeNap(1000); } return false; } public void _extractTopicsFromStream(String locator, InputStream inputStream, TopicMap topicMap, Topic topic) { try { String name = locator; if(name.indexOf("/") != -1) { name = name.substring(name.lastIndexOf("/")+1); } else if(name.indexOf("\\") != -1) { name = name.substring(name.lastIndexOf("\\")+1); } String lowerCaseLocator = locator.toLowerCase(); // --- HANDLE PDF ENRICHMENT TEXT --- if(lowerCaseLocator.endsWith("pdf")) { PDDocument doc = PDDocument.load(inputStream); PDDocumentInformation info = doc.getDocumentInformation(); DateFormat dateFormatter = new SimpleDateFormat(DEFAULT_DATE_FORMAT); // --- PDF PRODUCER --- String producer = info.getProducer(); if(producer != null && producer.length() > 0) { Topic producerType = createTopic(topicMap, "pdf-producer"); setData(topic, producerType, defaultLang, producer.trim()); } // --- PDF MODIFICATION DATE --- Calendar mCal = info.getModificationDate(); if(mCal != null) { String mdate = dateFormatter.format(mCal.getTime()); if(mdate != null && mdate.length() > 0) { Topic modificationDateType = createTopic(topicMap, "pdf-modification-date"); setData(topic, modificationDateType, defaultLang, mdate.trim()); } } // --- PDF CREATOR --- String creator = info.getCreator(); if(creator != null && creator.length() > 0) { Topic creatorType = createTopic(topicMap, "pdf-creator"); setData(topic, creatorType, defaultLang, creator.trim()); } // --- PDF CREATION DATE --- Calendar cCal = info.getCreationDate(); if(cCal != null) { String cdate = dateFormatter.format(cCal.getTime()); if(cdate != null && cdate.length() > 0) { Topic creationDateType = createTopic(topicMap, "pdf-creation-date"); setData(topic, creationDateType, defaultLang, cdate.trim()); } } // --- PDF AUTHOR --- String author = info.getAuthor(); if(author != null && author.length() > 0) { Topic authorType = createTopic(topicMap, "pdf-author"); setData(topic, authorType, defaultLang, author.trim()); } // --- PDF SUBJECT --- String subject = info.getSubject(); if(subject != null && subject.length() > 0) { Topic subjectType = createTopic(topicMap, "pdf-subject"); setData(topic, subjectType, defaultLang, subject.trim()); } // --- PDF TITLE --- String title = info.getSubject(); if(title != null && title.length() > 0) { Topic titleType = createTopic(topicMap, "pdf-title"); setData(topic, titleType, defaultLang, title.trim()); } // --- PDF KEYWORDS (SEPARATED WITH SEMICOLON) --- String keywords = info.getKeywords(); if(keywords != null && keywords.length() > 0) { Topic keywordType = createTopic(topicMap, "pdf-keyword"); String[] keywordArray = keywords.split(";"); String keyword = null; for(int i=0; i<keywordArray.length; i++) { keyword = Textbox.trimExtraSpaces(keywordArray[i]); if(keyword != null && keyword.length() > 0) { Topic keywordTopic = createTopic(topicMap, keyword, keywordType); createAssociation(topicMap, keywordType, new Topic[] { topic, keywordTopic } ); } } } // --- PDF TEXT CONTENT --- PDFTextStripper stripper = new PDFTextStripper(); String content = stripper.getText(doc); doc.close(); setTextEnrichment(topic, topicMap, content, name); } // --- HANDLE RTF DOCUMENTS --- else if(lowerCaseLocator.endsWith("rtf")) { String content = Textbox.RTF2PlainText(inputStream); setTextEnrichment(topic, topicMap, content, name); } // --- HANDLE OFFICE DOCUMENTS --- else if(lowerCaseLocator.endsWith("doc") || lowerCaseLocator.endsWith("docx") || lowerCaseLocator.endsWith("ppt") || lowerCaseLocator.endsWith("xls") || lowerCaseLocator.endsWith("vsd") ) { String content = MSOfficeBox.getText(inputStream); if(content != null) { setTextEnrichment(topic, topicMap, content, name); } } else if(lowerCaseLocator.endsWith("odt") || lowerCaseLocator.endsWith("odp") || lowerCaseLocator.endsWith("odg") || lowerCaseLocator.endsWith("ods")) { org.odftoolkit.simple.Document oodocument = org.odftoolkit.simple.Document.loadDocument(inputStream); String content = OpenOfficeBox.getText(oodocument); setTextEnrichment(topic, topicMap, content, name); org.odftoolkit.simple.meta.Meta meta = oodocument.getOfficeMetadata(); // --- OO KEYWORDS --- List<String> keywords = meta.getKeywords(); if(keywords != null && !keywords.isEmpty()) { Topic keywordType = createTopic(topicMap, "oo-keyword"); for( String keyword : keywords) { keyword = keyword.trim(); if(keyword != null && keyword.length() > 0) { Topic keywordTopic = createTopic(topicMap, keyword, keywordType); createAssociation(topicMap, keywordType, new Topic[] { topic, keywordTopic } ); } } } // --- OO TITLE --- String title = meta.getTitle(); if(title != null && title.length() > 0) { Topic titleType = createTopic(topicMap, "oo-title"); setData(topic, titleType, defaultLang, title.trim()); } // --- OO SUBJECT --- String subject = meta.getSubject(); if(subject != null && subject.length() > 0) { Topic subjectType = createTopic(topicMap, "oo-subject"); setData(topic, subjectType, defaultLang, subject.trim()); } // --- OO CREATOR --- String author = meta.getCreator(); if(author != null && author.length() > 0) { Topic authorType = createTopic(topicMap, "oo-author"); setData(topic, authorType, defaultLang, author.trim()); } // --- OO CREATION DATE --- Calendar cCal = meta.getCreationDate(); if(cCal != null) { DateFormat dateFormatter = new SimpleDateFormat(DEFAULT_DATE_FORMAT); String cdate = dateFormatter.format(cCal.getTime()); if(cdate != null && cdate.length() > 0) { Topic creationDateType = createTopic(topicMap, "oo-creation-date"); setData(topic, creationDateType, defaultLang, cdate.trim()); } } // --- OO DESCRIPTION --- String description = meta.getDescription(); if(description != null && description.length() > 0) { Topic descriptionType = createTopic(topicMap, "oo-description"); setData(topic, descriptionType, defaultLang, description.trim()); } // --- OO GENERATOR --- String generator = meta.getGenerator(); if(generator != null && generator.length() > 0) { Topic generatorType = createTopic(topicMap, "oo-generator"); setData(topic, generatorType, defaultLang, generator.trim()); } } else if(lowerCaseLocator.endsWith("html") || lowerCaseLocator.endsWith("htm")) { String content = IObox.loadFile(new InputStreamReader(inputStream)); setTextEnrichment(topic, topicMap, content, name); } else if(lowerCaseLocator.endsWith("txt") || lowerCaseLocator.endsWith("text")) { String content = IObox.loadFile(new InputStreamReader(inputStream)); setTextEnrichment(topic, topicMap, content, name); } // --- HANDLE ANY OTHER DOCUMENTS --- else { byte[] content = IObox.loadBFile(inputStream); String mimeType = ""; MimeUtil.registerMimeDetector("eu.medsea.mimeutil.detector.MagicMimeMimeDetector"); Collection<MimeType> mimeTypes = new ArrayList(); if(locator != null) { if(MimeTypes.getMimeType(locator) != null) { mimeTypes.add(new MimeType(MimeTypes.getMimeType(locator))); } mimeTypes.addAll(MimeUtil.getMimeTypes(locator)); } mimeTypes.addAll(MimeUtil.getMimeTypes(content)); boolean isText = false; for(MimeType mime : mimeTypes) { if(MimeUtil.isTextMimeType(mime)) { isText = true; break; } } if(isText) { setTextEnrichment(topic, topicMap, new String(content), name); } else { if(!mimeTypes.isEmpty()) { MimeType mime = mimeTypes.iterator().next(); mimeType = mime.toString(); } setBinaryEnrichment(topic, topicMap, content, mimeType); } } } catch(Exception e) { log(e); } } public void setBinaryEnrichment(Topic textTopic, TopicMap topicMap, byte[] content, String mimeType) { try { if(content != null && content.length > 0) { Topic contentType = createTopic(topicMap, "document-content"); DataURL dataURL = new DataURL(mimeType, content); setData(textTopic, contentType, defaultLang, dataURL.toExternalForm()); } } catch(Exception e) { log(e); } } public void setTextEnrichment(Topic topic, TopicMap topicMap, String content, String title) { try { String trimmedText = Textbox.trimExtraSpaces(content); if(trimmedText != null && trimmedText.length() > 0) { Topic contentType = createTopic(topicMap, "document-content"); setData(topic, contentType, defaultLang, trimmedText); } if(title == null || title.length() == 0) { title = solveTitle(trimmedText); } if(title != null) { // textTopic.setBaseName(title + " ("+trimmedText.hashCode()+")"); // textTopic.setDisplayName(defaultLang, title); } } catch(Exception e) { log(e); } } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- 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-content"); setData(textTopic, contentType, defaultLang, trimmedText); } String title = solveTitle(trimmedText); if(title != null) { textTopic.setBaseName(title + " (" + content.hashCode() + ")"); textTopic.setDisplayName(defaultLang, title); } Topic documentType = getDocumentType(topicMap); textTopic.addType(documentType); } catch(Exception e) { log(e); } } 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 static final String[] contentTypes=new String[] { "application/pdf", "text/plain", "text/html", "application/rtf", "application/xml", "application/msword" }; public String[] getContentTypes() { return contentTypes; } }
30,253
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DirectoryStructureExtractor2.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/files/DirectoryStructureExtractor2.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * DirectoryStructureExtractor2.java * * */ package org.wandora.application.tools.extractors.files; import java.io.File; import java.net.URL; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; 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.Locator; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author akivela */ public class DirectoryStructureExtractor2 extends AbstractExtractor implements WandoraTool { private static final long serialVersionUID = 1L; private String DEFAULT_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ssZ"; private String defaultLang = "en"; private String baseLocator = "http://wandora.org/si/file/"; private int progress = 0; /** Creates a new instance of DirectoryStructureExtractor2 */ public DirectoryStructureExtractor2() { } @Override public int getExtractorType() { return FILE_EXTRACTOR; } @Override public String getName() { return "Extract directory structure"; } @Override public String getDescription(){ return "Converts given directory stucture to a topic map where directories are associated with files and directories within."; } @Override public boolean useURLCrawler() { return false; } @Override public Icon getIcon() { return UIBox.getIcon(0xf114); } @Override public String getGUIText(int textType) { switch(textType) { case SELECT_DIALOG_TITLE: return "Select file(s) or directories!"; case POINT_START_URL_TEXT: return "Where would you like to start the crawl?"; case INFO_WAIT_WHILE_WORKING: return "Wait while seeking files!"; case FILE_PATTERN: return ".*"; case DONE_FAILED: return "Ready. Extraction failed!"; case DONE_ONE: return "Ready."; case DONE_MANY: return "Ready."; case LOG_TITLE: return "Directory structure extraction log"; } return ""; } @Override public void handleFiles(File[] files, TopicMap tm) { if(files == null || files.length == 0) return; for(int i=0; i<files.length && !forceStop(); i++) { if(files[i] != null) { // FILES if(files[i].isFile()) { try { extractTopicsFrom(files[i], tm); } catch(Exception e) { log(e); log("Extraction from '" + croppedFilename(files[i].getName()) + "' failed."); takeNap(1000); } } // DIRECTORIES if(files[i].isDirectory()) { try { extractTopicsFrom(files[i], tm); } catch (Exception e) { log(e); takeNap(1000); } } } } } @Override public boolean _extractTopicsFrom(File file, TopicMap tm) throws Exception { progress = 0; Topic rootTopic = iterateFile(file, tm); Topic extractionType = createTopic(tm, baseLocator+"extraction-root", "File extraction root"); if(rootTopic != null && extractionType != null) { rootTopic.addType(extractionType); Topic wandoraClass = getWandoraClass(tm); if(wandoraClass != null) { makeSubclassOf(tm, extractionType, wandoraClass); } } return true; } public Topic iterateFile(File file, TopicMap tm) throws Exception { if(forceStop()) return null; Topic fileTopic = extractFile(file, tm); if(file.isDirectory()) { File[] filesWithin = file.listFiles(); for(int i=0; i<filesWithin.length; i++) { Topic fileTopicWithin = iterateFile(filesWithin[i], tm); if(fileTopicWithin != null) { fileTopicWithin.addType(fileTopic); } if(forceStop()) break; } } return fileTopic; } public Topic extractFile(File file, TopicMap tm) throws Exception { setProgress(++progress); if(file != null) { try { Topic fileType = createTopic(tm, baseLocator+"file", "File"); Topic fileTopic = null; String location = file.toURI().toURL().toExternalForm(); String name = buildBaseName(file); fileTopic = createTopic(tm, location, name, (Topic) null); // --- SET FILE TOPIC'S VARIANT NAMES --- setDisplayName(fileTopic, defaultLang, file.getName()); fileTopic.setSubjectLocator(new Locator( location )); // --- ADD LAST MODIFICATION TIME AS OCCURRENCE --- try { DateFormat dateFormatter = new SimpleDateFormat(DEFAULT_DATE_FORMAT); Topic modType = createTopic(tm, baseLocator+"file-modified", "file-modified"); String dateString = dateFormatter.format( new Date(file.lastModified()) ); setData(fileTopic, modType, defaultLang, dateString); } catch(Exception e) { log("Exception occurred while setting file topic's modification time!", e); } // --- ADD FILE SIZE AS OCCURRENCE --- try { Topic sizeType = createTopic(tm, baseLocator+"file-size", "file-size"); setData(fileTopic, sizeType, defaultLang, ""+file.length()); } catch(Exception e) { log("Exception occurred while setting file topic's file size!", e); } // --- ADD INFO ASSOCIATIONS IF FILE IS READABLE/WRITEABLE/HIDDEN... --- try { Topic fileInfoType = createTopic(tm, baseLocator+"file-info", "file-info"); if(fileInfoType != null) { if(file.canRead()) { Topic readableFileType = createTopic(tm, baseLocator+"is-readable-file", "is-readable-file"); createAssociation(tm, fileInfoType, new Topic[] { fileTopic, readableFileType }, new Topic[] { fileType, fileInfoType } ); } if(file.canWrite()) { Topic writeableFileType = createTopic(tm, baseLocator+"is-writeable-file", "is-writeable-file"); createAssociation(tm, fileInfoType, new Topic[] { fileTopic, writeableFileType }, new Topic[] { fileType, fileInfoType } ); } if(file.canExecute()) { Topic executableFileType = createTopic(tm, baseLocator+"is-executable-file", "is-executable-file"); createAssociation(tm, fileInfoType, new Topic[] { fileTopic, executableFileType }, new Topic[] { fileType, fileInfoType } ); } if(file.isHidden()) { Topic hiddenFileType = createTopic(tm, baseLocator+"is-hidden-file", "is-hidden-file"); createAssociation(tm, fileInfoType, new Topic[] { fileTopic, hiddenFileType }, new Topic[] { fileType, fileInfoType } ); } if(file.isDirectory()) { Topic dirType = createTopic(tm, baseLocator+"is-directory", "is-directory"); createAssociation(tm, fileInfoType, new Topic[] { fileTopic, dirType }, new Topic[] { fileType, fileInfoType } ); } int index = file.getName().lastIndexOf("."); if(index != -1) { try { String suffix = file.getName().substring(index+1); if(suffix != null && suffix.length() > 0) { suffix = suffix.toLowerCase(); Topic fileSuffix = createTopic(tm, baseLocator+"type/"+urlEncode(suffix), suffix); createAssociation(tm, fileInfoType, new Topic[] { fileTopic, fileSuffix }, new Topic[] { fileType, fileInfoType } ); } } catch(Exception e) { } } } } catch(Exception e) { log("Exception occurred while solving file's accessibility!", e); } // --- ADD EXTRACTION TIME AS OCCURRENCE --- DateFormat dateFormatter = new SimpleDateFormat(DEFAULT_DATE_FORMAT); Topic extractionTimeType = createTopic(tm, "extraction-time"); String dateString = dateFormatter.format( new Date(System.currentTimeMillis()) ); setData(fileTopic, extractionTimeType, defaultLang, dateString); return fileTopic; } catch (Exception e) { log(e); e.printStackTrace(); } } return null; } // THIS EXTRACTOR DOESN'T SUPPORT STRINGS! @Override public boolean _extractTopicsFrom(String str, TopicMap topicMap) throws Exception { throw(new Exception(STRING_EXTRACTOR_NOT_SUPPORTED_MESSAGE)); } // THIS EXTRACTOR DOESN'T SUPPORT URLS! @Override public boolean _extractTopicsFrom(URL url, TopicMap topicMap) throws Exception { return false; } // ------------------------------------------------------------------------- public Topic getWandoraClass(TopicMap tm) throws TopicMapException { return getOrCreateTopic(tm, TMBox.WANDORACLASS_SI,"Wandora class"); } protected void makeSubclassOf(TopicMap tm, Topic t, Topic superclass) throws TopicMapException { ExtractHelper.makeSubclassOf(t, superclass, tm); } protected Topic getOrCreateTopic(TopicMap tm, String si, String bn) throws TopicMapException { return ExtractHelper.getOrCreateTopic(si, bn, tm); } // ----------- public String buildBaseName(File file) { if(file == null) return "[null]"; try { return file.getName() + " ("+file.toURI().toURL().toExternalForm().hashCode()+")"; } catch(Exception e) { return file.getName(); } } @Override public Locator buildSI(String siend) { if(siend.startsWith("http://")) { return new Locator(siend); } else if(siend.startsWith("file:/")) { return new Locator(siend); } else { try { return new Locator(new File(siend).toURI().toURL().toExternalForm()); } catch(Exception e) { return new Locator("file:/" + siend); } } } }
12,632
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimplePDFExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/files/SimplePDFExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * SimplePDFExtractor.java * * Created on 9.6.2006, 15:08 * */ package org.wandora.application.tools.extractors.files; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.Icon; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDDocumentInformation; import org.apache.pdfbox.text.PDFTextStripper; import org.wandora.application.Wandora; import org.wandora.application.gui.UIBox; import org.wandora.application.tools.browserextractors.BrowserExtractRequest; import org.wandora.application.tools.browserextractors.BrowserPluginExtractor; import org.wandora.application.tools.extractors.AbstractExtractor; import org.wandora.application.tools.extractors.ExtractHelper; import org.wandora.topicmap.Locator; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.utils.IObox; import org.wandora.utils.Textbox; /** * * @author akivela */ public class SimplePDFExtractor extends AbstractExtractor { private static final long serialVersionUID = 1L; protected static String DEFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; public boolean makePageTopics = false; public boolean makeVariantFromTitle = true; private String defaultLang = "en"; public SimplePDFExtractor() { } @Override public String getName() { return "Simple PDF extractor..."; } @Override public String getDescription(){ return "Extracts text and metadata from PDF files."; } @Override public Icon getIcon() { return UIBox.getIcon(0xf1c1); } @Override public int getExtractorType() { return FILE_EXTRACTOR | URL_EXTRACTOR; } @Override public String getGUIText(int textType) { switch(textType) { case SELECT_DIALOG_TITLE: return "Select PDF file(s) or directories containing PDF files!"; case POINT_START_URL_TEXT: return "Where would you like to start the crawl?"; case INFO_WAIT_WHILE_WORKING: return "Wait while seeking PDF files!"; case FILE_PATTERN: return ".*\\.(pdf|PDF)"; case DONE_FAILED: return "Ready. No extractions! %1 pdf file(s) crawled!"; case DONE_ONE: return "Ready. Successful extraction. %1 pdf file(s) crawled!"; case DONE_MANY: return "Ready. Total %0 successful extractions. %1 pdf files crawled!"; case LOG_TITLE: return "Simple PDF Extraction Log"; } return ""; } @Override public String doBrowserExtract(BrowserExtractRequest request, Wandora wandora) throws TopicMapException { try { setWandora(wandora); String url = request.getSource(); TopicMap tm = wandora.getTopicMap(); if(url != null && url.endsWith(".pdf")) { _extractTopicsFrom(new URL(url), tm); wandora.doRefresh(); return null; } else { String content = request.getSelection(); if(content == null) { content = request.getContent(); } if(content == null && url != null) { try { System.out.println("Found no content. Reading the url content."); content = IObox.doUrl(new URL(url)); } catch(Exception e) { e.printStackTrace(); } } if(content != null) { System.out.println("--- browser plugin processing content ---"); System.out.println(content); Pattern p = Pattern.compile("\"[^\"]+?\\.pdf\""); Matcher m = p.matcher(content); ArrayList<String> pdfUrls = new ArrayList<String>(); int l = 0; while( l<content.length() && m.find(l) ) { String g = m.group(); if(g.startsWith("\"")) g = g.substring(1); if(g.endsWith("\"")) g = g.substring(0, g.length()-1); pdfUrls.add( g ); l = m.end(); } for( String u : pdfUrls ) { System.out.println("Extracting pdf url: " + u); _extractTopicsFrom(new URL(u), tm); } wandora.doRefresh(); return null; } else { return BrowserPluginExtractor.RETURN_ERROR+"Couldn't solve browser extractor content. Nothing extracted."; } } } catch(Exception e){ e.printStackTrace(); return BrowserPluginExtractor.RETURN_ERROR+e.getMessage(); } } // ------------------------------------------------------------------------- @Override public boolean _extractTopicsFrom(URL url, TopicMap topicMap) throws Exception { if(url == null) return false; try { Topic pdfType = createPDFTypeTopic(topicMap); String location = url.toExternalForm(); long hash = location.hashCode(); String urlfile = url.getFile(); String name = urlfile; if(urlfile.lastIndexOf("/") > -1) { name = urlfile.substring(urlfile.lastIndexOf("/")+1); } Topic pdfTopic = createTopic(topicMap, location, " ("+hash+")", name, pdfType); pdfTopic.setSubjectLocator(new Locator( location )); URLConnection uc = null; if(getWandora() != null) { uc = getWandora().wandoraHttpAuthorizer.getAuthorizedAccess(url); } else { uc = url.openConnection(); Wandora.initUrlConnection(uc); } _extractTopicsFromStream(url.toExternalForm(), uc.getInputStream(), topicMap, pdfTopic); // --- ADD EXTRACTION TIME AS OCCURRENCE --- DateFormat dateFormatter = new SimpleDateFormat(DEFAULT_DATE_FORMAT); Topic extractionTimeType = createTopic(topicMap, "extraction-time"); String dateString = dateFormatter.format( new Date(System.currentTimeMillis()) ); setData(pdfTopic, extractionTimeType, defaultLang, dateString); return true; } catch(Exception e) { log("Exception occurred while extracting from url\n" + url.toExternalForm(), e); takeNap(1000); } return false; } @Override public boolean _extractTopicsFrom(String str, TopicMap topicMap) throws Exception { throw(new Exception(STRING_EXTRACTOR_NOT_SUPPORTED_MESSAGE)); } @Override public boolean _extractTopicsFrom(File file, TopicMap topicMap) throws Exception { if(file == null || file.isDirectory()) return false; try { Topic pdfType = createPDFTypeTopic(topicMap); String location = file.toURI().toURL().toExternalForm(); long hash = location.hashCode(); Topic pdfTopic = createTopic(topicMap, location, " ("+hash+")", file.getName(), pdfType); pdfTopic.setSubjectLocator(new Locator( location )); // --- ADD LAST MODIFICATION TIME AS OCCURRENCE --- try { DateFormat dateFormatter = new SimpleDateFormat(DEFAULT_DATE_FORMAT); Topic modType = createTopic(topicMap, "file-modified"); String dateString = dateFormatter.format( new Date(file.lastModified()) ); setData(pdfTopic, modType, defaultLang, dateString); } catch(Exception e) { log("Exception occurred while setting file topic's modification time!", e); } // --- ADD FILE SIZE AS OCCURRENCE --- try { Topic sizeType = createTopic(topicMap, "file-size"); setData(pdfTopic, sizeType, defaultLang, ""+file.length()); } catch(Exception e) { log("Exception occurred while setting file topic's file size!", e); } FileInputStream fis = new FileInputStream(file); try { _extractTopicsFromStream(file.getPath(), fis, topicMap, pdfTopic); } finally { if(fis != null) fis.close(); } // --- ADD EXTRACTION TIME AS OCCURRENCE --- DateFormat dateFormatter = new SimpleDateFormat(DEFAULT_DATE_FORMAT); Topic extractionTimeType = createTopic(topicMap, "extraction-time"); String dateString = dateFormatter.format( new Date(System.currentTimeMillis()) ); setData(pdfTopic, extractionTimeType, defaultLang, dateString); return true; } catch(Exception e) { log("Exception occurred while extracting from file " + file.getName(), e); takeNap(1000); } return false; } public void _extractTopicsFromStream(String locator, InputStream inputStream, TopicMap topicMap, Topic pdfTopic) { PDDocument doc = null; try { if(locator.startsWith("http://")) { doc = PDDocument.load(new URL(locator).openStream()); } else { doc = PDDocument.load(new File(locator)); } PDDocumentInformation info = doc.getDocumentInformation(); DateFormat dateFormatter = new SimpleDateFormat(DEFAULT_DATE_FORMAT); // --- PDF PRODUCER --- String producer = info.getProducer(); if(producer != null && producer.length() > 0) { Topic producerType = createTopic(topicMap, "pdf-producer"); setData(pdfTopic, producerType, defaultLang, producer.trim()); } // --- PDF MODIFICATION DATE --- Calendar mCal = info.getModificationDate(); if(mCal != null) { String mdate = dateFormatter.format(mCal.getTime()); if(mdate != null && mdate.length() > 0) { Topic modificationDateType = createTopic(topicMap, "pdf-modification-date"); setData(pdfTopic, modificationDateType, defaultLang, mdate.trim()); } } // --- PDF CREATOR --- String creator = info.getCreator(); if(creator != null && creator.length() > 0) { Topic creatorType = createTopic(topicMap, "pdf-creator"); setData(pdfTopic, creatorType, defaultLang, creator.trim()); } // --- PDF CREATION DATE --- Calendar cCal = info.getCreationDate(); if(cCal != null) { String cdate = dateFormatter.format(cCal.getTime()); if(cdate != null && cdate.length() > 0) { Topic creationDateType = createTopic(topicMap, "pdf-creation-date"); setData(pdfTopic, creationDateType, defaultLang, cdate.trim()); } } // --- PDF AUTHOR --- String author = info.getAuthor(); if(author != null && author.length() > 0) { Topic authorType = createTopic(topicMap, "pdf-author"); setData(pdfTopic, authorType, defaultLang, author.trim()); } // --- PDF SUBJECT --- String subject = info.getSubject(); if(subject != null && subject.length() > 0) { Topic subjectType = createTopic(topicMap, "pdf-subject"); setData(pdfTopic, subjectType, defaultLang, subject.trim()); } // --- PDF TITLE --- String title = info.getSubject(); if(title != null && title.length() > 0) { if(makeVariantFromTitle) { pdfTopic.setDisplayName(defaultLang, title); } else { Topic titleType = createTopic(topicMap, "pdf-title"); setData(pdfTopic, titleType, defaultLang, title.trim()); } } // --- PDF KEYWORDS (SEPARATED WITH SEMICOLON) --- String keywords = info.getKeywords(); if(keywords != null && keywords.length() > 0) { Topic keywordType = createTopic(topicMap, "pdf-keyword"); String[] keywordArray = keywords.split(";"); String keyword = null; for(int i=0; i<keywordArray.length; i++) { keyword = Textbox.trimExtraSpaces(keywordArray[i]); if(keyword != null && keyword.length() > 0) { Topic keywordTopic = createTopic(topicMap, keyword, keywordType); createAssociation(topicMap, keywordType, new Topic[] { pdfTopic, keywordTopic } ); } } } // --- PDF TEXT CONTENT --- PDFTextStripper stripper = new PDFTextStripper(); String content = new String(); if(makePageTopics) { int pages=doc.getNumberOfPages(); String pageContent = null; for(int i=0;i<pages;i++) { stripper.setStartPage(i); stripper.setEndPage(i); pageContent = stripper.getText(doc); Topic pageType = createTopic(topicMap, "pdf-page"); Topic pageTopic = createTopic(topicMap, pdfTopic.getBaseName() + " (page "+i+")", pageType); Topic orderType = createTopic(topicMap, "order"); Topic orderTopic = createTopic(topicMap, i + ".", orderType); Topic contentType = createTopic(topicMap, "pdf-text"); setData(pageTopic, contentType, defaultLang, pageContent.trim()); createAssociation(topicMap, pageType, new Topic[] { pdfTopic, pageTopic, orderTopic } ); } } else { content = stripper.getText(doc); } if(!makePageTopics && content != null && content.length() > 0) { Topic contentType = createTopic(topicMap, "pdf-text"); setData(pdfTopic, contentType, defaultLang, content.trim()); } doc.close(); } catch(Exception e) { e.printStackTrace(); try { if(doc != null) doc.close(); } catch(Exception ix) { e.printStackTrace(); } } } // ------------------------------------------------------------------------- public static final String[] contentTypes=new String[] { "application/pdf" }; @Override public String[] getContentTypes() { return contentTypes; } @Override public Locator buildSI(String siend) { if(siend == null) siend = "" + System.currentTimeMillis() + Math.random()*999999; if(siend.startsWith("http://")) return new Locator(siend); if(siend.startsWith("file:/")) return new Locator(siend); if(siend.startsWith("/")) siend = siend.substring(1); return new Locator("http://wandora.org/si/pdf/" + urlEncode(siend)); } // ------------------------------------------------------------------------- public Topic createPDFTypeTopic(TopicMap tm) throws TopicMapException { Topic t = createTopic(tm, "PDF resource"); Topic w = getWandoraClass(tm); makeSubclassOf(tm, t, w); return t; } public Topic getWandoraClass(TopicMap tm) throws TopicMapException { return createTopic(tm, TMBox.WANDORACLASS_SI, "Wandora class"); } protected void makeSubclassOf(TopicMap tm, Topic t, Topic superclass) throws TopicMapException { ExtractHelper.makeSubclassOf(t, superclass, tm); } }
17,548
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
BatchExtractMarcXML.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/marcxml/BatchExtractMarcXML.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * MarcField.java * * Created on 2010-06-30 * */ package org.wandora.application.tools.extractors.marcxml; import java.io.File; import javax.swing.Icon; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.UIConstants; import org.wandora.application.gui.simple.SimpleFileChooser; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.topicmap.TopicMap; import org.wandora.utils.IObox; /** * * @author akivela */ public class BatchExtractMarcXML extends AbstractWandoraTool { private static final long serialVersionUID = 1L; @Override public String getName() { return "MarcXML batch extractor"; } @Override public String getDescription(){ return "Batch converts MarcXML documents to XTM topics maps."; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_marcxml.png"); } @Override public void execute(Wandora wandora, Context context) { try { SimpleFileChooser chooser=UIConstants.getFileChooser(); chooser.setMultiSelectionEnabled(true); chooser.setDialogTitle("Select MARCXML files to convert"); if(chooser.open(wandora)==SimpleFileChooser.APPROVE_OPTION) { setDefaultLogger(); importExport(chooser.getSelectedFiles()); } } catch(Exception e) { log(e); } setState(WAIT); } private void importExport(File[] importFiles) { if(importFiles != null && importFiles.length > 0) { long starttime = System.currentTimeMillis(); for(int i=0; i<importFiles.length && !forceStop(); i++) { try { TopicMap map = new org.wandora.topicmap.memory.TopicMapImpl(); File importFile = importFiles[i]; setLogTitle("Extracting '"+importFile.getName()+"'"); log("Extracting '"+importFile.getName()+"'"); MarcXMLExtractor importer = new MarcXMLExtractor(); importer.setToolLogger(this.getCurrentLogger()); importer._extractTopicsFrom(importFile, map); String exportPath = importFile.getParent()+File.separator+"wandora_export"; IObox.createPathFor(new File(exportPath)); String n = importFile.getName(); if(n.toLowerCase().endsWith(".xml")) { n = importFile.getName(); n = n.substring(0, n.length()-4); n = n + ".xtm"; } String exportFileName = exportPath+File.separator+n; log("Exporting '"+n+"'"); setLogTitle("Exporting '"+n+"'"); map.exportXTM(exportFileName, this.getCurrentLogger()); } catch(Exception e) { e.printStackTrace(); } } long endtime = System.currentTimeMillis(); long duration = (Math.round(((endtime-starttime)/1000))); if(duration > 1) { log("Batch conversion of MARCXML files took "+duration+" seconds."); } log("Ready."); } else { System.out.println("No MARCXML files to import!"); } } }
4,327
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MarcXMLExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/marcxml/MarcXMLExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://www.wandora.org/ * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * MarcXMLExtractor.java * * Created on 2010-06-30 * */ package org.wandora.application.tools.extractors.marcxml; import java.io.ByteArrayInputStream; import java.io.File; import java.io.InputStream; import java.net.URL; import java.net.URLEncoder; 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.gui.UIBox; import org.wandora.application.tools.GenericOptionsDialog; import org.wandora.application.tools.extractors.AbstractExtractor; import org.wandora.application.tools.extractors.ExtractHelper; import org.wandora.topicmap.Association; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicTools; import org.wandora.topicmap.XTMPSI; import org.wandora.utils.IObox; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; /** * * @author akivela */ public class MarcXMLExtractor extends AbstractExtractor { private static final long serialVersionUID = 1L; public static boolean TRIM_DATAS = false; public static boolean INCLUDE_INDX_IN_ASSOCIATIONS = true; public static boolean SOLVE_FIELD_NAMES = true; public static boolean SOLVE_SUBFIELD_NAMES = true; public static boolean CONVERT_LEADERS = true; public static String EXCLUDE_FIELDS = ""; public static String INCLUDE_FIELDS = ""; public static String EXCLUDE_SUBFIELDS = ""; public static String INCLUDE_SUBFIELDS = ""; public static String RECORD_SI_PATTERN = ""; public static String BASENAME_PATTERN = ""; protected static String MARC_SI = "http://www.loc.gov/marc/bibliographic/bdintro.html"; protected static String IND_SI = "http://www.loc.gov/marc/bibliographic/bdintro.html#indicator"; protected static String SUBFIELDCODE_SI = "http://www.loc.gov/marc/bibliographic/bdintro.html#subfield"; protected static String LEADER_SI = "http://www.loc.gov/marc/bibliographic/bdleader.html"; protected static String FIELD_SI = "http://www.loc.gov/marc/bibliographic/"; protected static String FIELD_SI_TEMPLATE = "http://www.loc.gov/marc/bibliographic/bd___x___.html"; protected static String DATA_SI = "http://www.wandora.org/marcxml/data"; protected static String RECORD_SI = "http://www.wandora.org/marcxml/record"; private static String defaultEncoding = "UTF-8"; //"ISO-8859-1"; private static String defaultLang = "en"; private Map<String,String> excludeFields = null; private Map<String,String> includeFields = null; private Map<String,String> excludeSubfields = null; private Map<String,String> includeSubfields = null; private List<String> recordSIPatterns = null; private List<String> basenamePatterns = null; /** Creates a new instance of MarcXMLExtractor */ public MarcXMLExtractor() { } @Override public String getName() { return "MarcXML extractor"; } @Override public String getDescription(){ return "Converts MarcXML documents to topics maps."; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_marcxml.png"); } private final String[] contentTypes=new String[] { "text/xml", "application/xml" }; @Override public String[] getContentTypes() { return contentTypes; } @Override public boolean useURLCrawler() { return false; } // ------------------------------------------------------------------------- @Override public boolean isConfigurable(){ return true; } @Override public void configure(Wandora wandora,org.wandora.utils.Options options,String prefix) throws TopicMapException { GenericOptionsDialog god=new GenericOptionsDialog(wandora,"MARCXML extract options","MARCXML extract options",true,new String[][]{ new String[] { "Record SI patterns", "string", RECORD_SI_PATTERN, "Comma separated list of subject identifier patterns for records. Refer MARCXML (sub)fields with tags like ___a@035___. Example: http://www.wandora.org/si/___a@035___", }, new String[] { "Record base name patterns", "string", BASENAME_PATTERN, "Comma separated list of base name patterns for records. Refer MARCXML (sub)fields with tags like ___a@245___. Example: ___a@245___ - ___b@245___", }, new String[] { "Trim datas", "boolean", (TRIM_DATAS ? "true" : "false"), "Should extractor remove trailing special characters in data fields." }, new String[] { "Solve field names", "boolean", (SOLVE_FIELD_NAMES ? "true" : "false"), "Should extractor solve field names? Fields are converted to association types" }, new String[] { "Solve subfield names", "boolean", (SOLVE_SUBFIELD_NAMES ? "true" : "false"), "Should extractor solve subfield names? Subfields are converted to association roles." }, new String[] { "Convert MARC indicators", "boolean", (INCLUDE_INDX_IN_ASSOCIATIONS ? "true" : "false"), "Should extractor add ind1 and ind2 attributes of MARCXML to associations as players?" }, new String[] { "Convert leaders", "boolean", (CONVERT_LEADERS ? "true" : "false"), "Should extractor convert record leaders also?" }, new String[] { "Include fields", "string", INCLUDE_FIELDS, "Comma separated list of included field codes" }, new String[] { "Exclude fields", "string", EXCLUDE_FIELDS, "Comma separated list of excluded field codes" }, new String[] { "Include subfields", "string", INCLUDE_SUBFIELDS, "Comma separated list of included subfield codes" }, new String[] { "Exclude subfields", "string", EXCLUDE_SUBFIELDS, "Comma separated list of excluded subfield codes" }, new String[] { "MARCXML encoding", "string", defaultEncoding, "Encoding of MARCXML file" }, new String[] { "Default language", "string", defaultLang, "Language used in occurrences for example. Use two letter acronyms." } },wandora); god.setVisible(true); if(god.wasCancelled()) return; Map<String, String> values = god.getValues(); parseSIPatterns( values.get("Record SI patterns") ); parseBasenamePatterns( values.get("Record base name patterns")); CONVERT_LEADERS = ("true".equals(values.get("Convert leaders")) ? true : false ); TRIM_DATAS = ("true".equals(values.get("Trim datas")) ? true : false ); SOLVE_FIELD_NAMES = ("true".equals(values.get("Solve field names")) ? true : false ); SOLVE_SUBFIELD_NAMES = ("true".equals(values.get("Solve subfield names")) ? true : false ); INCLUDE_INDX_IN_ASSOCIATIONS = ("true".equals(values.get("Convert MARC indicators")) ? true : false ); INCLUDE_FIELDS = values.get("Include fields"); EXCLUDE_FIELDS = values.get("Exclude fields"); INCLUDE_SUBFIELDS = values.get("Include subfields"); EXCLUDE_SUBFIELDS = values.get("Exclude subfields"); excludeFields = parseFieldCodes(EXCLUDE_FIELDS); includeFields = parseFieldCodes(INCLUDE_FIELDS); excludeSubfields = parseSubfieldCodes(EXCLUDE_SUBFIELDS); includeSubfields = parseSubfieldCodes(INCLUDE_SUBFIELDS); defaultEncoding = values.get("MARCXML encoding"); defaultLang = values.get("Default language"); } private Map<String,String> parseFieldCodes(String str) { String[] strs = str.split(","); Map<String,String> codes = new LinkedHashMap<>(); for(int i=0; i<strs.length; i++) { String s = strs[i]; s.trim(); if(s.length() > 0) { if(s.indexOf("-") > -1) { int si0 = 0; int si1 = 999; String sa[] = s.split("-"); String s0 = sa[0].trim(); String s1 = sa[1].trim(); try { si0 = Integer.parseInt( s0 ); } catch(Exception e) {} try { si1 = Integer.parseInt( s1 ); } catch(Exception e) {} for(int j=si0; j<=si1; j++) { String code = ""+j; if(code.length() == 1) code = "00"+code; else if(code.length() == 2) code = "0"+code; codes.put(code, code); System.out.println("field code: "+code); } } else { codes.put(s,s); } } } return codes; } public Map<String,String> parseSubfieldCodes(String str) { String[] strs = str.split(","); Map<String,String> codes = new LinkedHashMap<>(); for(int i=0; i<strs.length; i++) { String s = strs[i]; s.trim(); if(s.length() > 0) { codes.put(s,s); } } return codes; } public void parseSIPatterns(String patterns) { RECORD_SI_PATTERN = patterns; recordSIPatterns = new ArrayList<>(); if(RECORD_SI_PATTERN != null) { String[] siPatterns = RECORD_SI_PATTERN.split(","); String siPattern = null; for(int i=0; i<siPatterns.length; i++) { siPattern = siPatterns[i]; siPattern.trim(); if(siPattern.length() > 0) { recordSIPatterns.add(siPattern); } } } } public void parseBasenamePatterns(String patterns) { BASENAME_PATTERN = patterns; basenamePatterns = new ArrayList<>(); if(BASENAME_PATTERN != null) { String[] namePatterns = BASENAME_PATTERN.split(","); String namePattern = null; for(int i=0; i<namePatterns.length; i++) { namePattern = namePatterns[i]; namePattern.trim(); if(namePattern.length() > 0) { basenamePatterns.add(namePattern); } } } } // ------------------------------------------------------------------------- public boolean _extractTopicsFrom(URL url, TopicMap topicMap) throws Exception { String in = IObox.doUrl(url); InputSource inSource = new InputSource(new ByteArrayInputStream(in.getBytes(defaultEncoding))); inSource.setEncoding(defaultEncoding); return _extractTopicsFrom(inSource, topicMap); } public boolean _extractTopicsFrom(File file, TopicMap topicMap) throws Exception { String in = IObox.loadFile(file); InputSource inSource = new InputSource(new ByteArrayInputStream(in.getBytes(defaultEncoding))); inSource.setEncoding(defaultEncoding); return _extractTopicsFrom(inSource, 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 { InputSource inSource = new InputSource(in); inSource.setEncoding(defaultEncoding); return _extractTopicsFrom(inSource, topicMap); } public boolean _extractTopicsFrom(InputSource in, TopicMap topicMap) throws Exception { try { setDefaultLogger(); setProgressMax(100); parseSIPatterns( RECORD_SI_PATTERN ); parseBasenamePatterns( BASENAME_PATTERN ); excludeFields = parseFieldCodes(EXCLUDE_FIELDS); includeFields = parseFieldCodes(INCLUDE_FIELDS); excludeSubfields = parseSubfieldCodes(EXCLUDE_SUBFIELDS); includeSubfields = parseSubfieldCodes(INCLUDE_SUBFIELDS); if(!excludeFields.isEmpty()) { log("Exclude fields "+EXCLUDE_FIELDS); } else if(!includeFields.isEmpty()) { log("Include fields "+INCLUDE_FIELDS); } if(!excludeSubfields.isEmpty()) { log("Exclude subfields "+EXCLUDE_SUBFIELDS); } else if(!includeSubfields.isEmpty()) { log("Include subfields "+INCLUDE_SUBFIELDS); } // ---- Parse results ---- javax.xml.parsers.SAXParserFactory factory=javax.xml.parsers.SAXParserFactory.newInstance(); factory.setNamespaceAware(false); factory.setValidating(false); javax.xml.parsers.SAXParser parser=factory.newSAXParser(); XMLReader reader=parser.getXMLReader(); MarcXMLParser parserHandler = new MarcXMLParser(topicMap, this); reader.setContentHandler(parserHandler); reader.setErrorHandler(parserHandler); reader.setFeature("http://xml.org/sax/features/namespace-prefixes", false); try { reader.parse(in); } catch(Exception e){ if(!(e instanceof SAXException) || !e.getMessage().equals("User interrupt")) log(e); } String msg = null; if(parserHandler.progress == 0) { msg = "Found no records."; } else { msg = "Found "+parserHandler.progress+" record(s)."; } if(msg != null) log(msg); } catch (Exception ex) { log(ex); } return true; } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- private class MarcXMLParser implements org.xml.sax.ContentHandler, org.xml.sax.ErrorHandler { public MarcXMLParser(TopicMap tm, MarcXMLExtractor parent){ this.tm=tm; this.parent=parent; } public int progress=0; private TopicMap tm; private MarcXMLExtractor parent; public static final String TAG_COLLECTION = "collection"; public static final String TAG_RECORD = "record"; public static final String TAG_LEADER = "leader"; public static final String TAG_CONTROLFIELD = "controlfield"; public static final String TAG_DATAFIELD = "datafield"; public static final String TAG_SUBFIELD = "subfield"; private static final int STATE_START=0; private static final int STATE_COLLECTION=2; private static final int STATE_COLLECTION_RECORD=4; private static final int STATE_COLLECTION_RECORD_LEADER=41; private static final int STATE_COLLECTION_RECORD_CONTROLFIELD=42; private static final int STATE_COLLECTION_RECORD_DATAFIELD=43; private static final int STATE_COLLECTION_RECORD_DATAFIELD_SUBFIELD=431; private int state=STATE_START; private String data_leader = null; private String data_controlfield = null; private String data_controlfield_tag = null; private String data_datafield = null; // NOT USED! private MarcField datafield = null; private String data_subfield = null; private String data_datafield_tag = null; private String data_datafield_ind1 = null; private String data_datafield_ind2 = null; private String data_subfield_code = null; private List<MarcField> data_datafields = null; private Map<String,String> data_controlfields = null; private List<String> subjectIdentifiers = null; private List<String> basenames = 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(elementEquals(qName, TAG_COLLECTION)) { state = STATE_COLLECTION; } break; case STATE_COLLECTION: if(elementEquals(qName, TAG_RECORD)) { data_leader = ""; data_controlfield = ""; data_datafield = ""; data_subfield = ""; data_controlfields = new LinkedHashMap<>(); data_datafields = new ArrayList<>(); subjectIdentifiers = new ArrayList<>(); if(recordSIPatterns != null && !recordSIPatterns.isEmpty()) { for(String recordSIPattern : recordSIPatterns) { if(recordSIPattern != null && recordSIPattern.length() > 0) { subjectIdentifiers.add(recordSIPattern); } } } basenames = new ArrayList<String>(); if(basenamePatterns != null && !basenamePatterns.isEmpty()) { for(String namePattern : basenamePatterns) { if(namePattern != null && namePattern.length() > 0) { basenames.add(namePattern); } } } state = STATE_COLLECTION_RECORD; } break; case STATE_COLLECTION_RECORD: if(elementEquals(qName, TAG_LEADER)) { data_leader = ""; state = STATE_COLLECTION_RECORD_LEADER; } else if(elementEquals(qName, TAG_CONTROLFIELD)) { data_controlfield = ""; data_controlfield_tag = atts.getValue("tag"); state = STATE_COLLECTION_RECORD_CONTROLFIELD; } else if(elementEquals(qName, TAG_DATAFIELD)) { data_datafield = ""; data_datafield_tag = atts.getValue("tag"); data_datafield_ind1 = atts.getValue("ind1"); data_datafield_ind2 = atts.getValue("ind2"); datafield = new MarcField(data_datafield_tag, data_datafield_ind1, data_datafield_ind2); state = STATE_COLLECTION_RECORD_DATAFIELD; } break; case STATE_COLLECTION_RECORD_DATAFIELD: if(elementEquals(qName, TAG_SUBFIELD)) { data_subfield = ""; data_subfield_code = atts.getValue("code"); state = STATE_COLLECTION_RECORD_DATAFIELD_SUBFIELD; } break; } } public void endElement(String uri, String localName, String qName) throws SAXException { switch(state) { case STATE_COLLECTION_RECORD_DATAFIELD_SUBFIELD: { if(elementEquals(qName, TAG_SUBFIELD)) { String subfieldCode = data_subfield_code.trim(); if(datafield != null) { if(!excludeSubfields.containsKey(subfieldCode)) { if(!includeSubfields.isEmpty() && includeSubfields.containsKey(subfieldCode)) { datafield.addSubfield(subfieldCode, data_subfield); } else if(includeSubfields.isEmpty()) { datafield.addSubfield(subfieldCode, data_subfield); } } } // BUILD SIs String fieldCode = data_datafield_tag.trim(); if(subjectIdentifiers != null && subjectIdentifiers.size() > 0) { try { List<String> updatedSubjectIdentifiers = new ArrayList<String>(); for(String si : subjectIdentifiers) { if(si != null) { if( si.indexOf( "___"+subfieldCode+"@"+fieldCode+"___" ) > -1) { try { si = si.replaceAll("___"+subfieldCode+"@"+fieldCode+"___", URLEncoder.encode(data_subfield, defaultEncoding)); } catch(Exception e) { e.printStackTrace(); } } updatedSubjectIdentifiers.add(si); } } subjectIdentifiers = updatedSubjectIdentifiers; } catch(Exception e) { e.printStackTrace(); } } // BUILD BASENAMEs if(basenames != null && basenames.size() > 0) { try { List<String> updatedBasenames = new ArrayList<>(); for(String n : basenames) { if(n != null) { if( n.indexOf( "___"+subfieldCode+"@"+fieldCode+"___" ) > -1) { try { n = n.replaceAll("___"+subfieldCode+"@"+fieldCode+"___", data_subfield); } catch(Exception e) { e.printStackTrace(); } } updatedBasenames.add(n); } } basenames = updatedBasenames; } catch(Exception e) { e.printStackTrace(); } } state = STATE_COLLECTION_RECORD_DATAFIELD; } break; } case STATE_COLLECTION_RECORD_DATAFIELD: { if(elementEquals(qName, TAG_DATAFIELD)) { String fieldCode = data_datafield_tag.trim(); if(!excludeFields.containsKey(fieldCode)) { if(!includeFields.isEmpty() && includeFields.containsKey(fieldCode)) { //System.out.println("Adding a field: "+fieldCode); data_datafields.add(datafield); } else if(includeFields.isEmpty()) { //System.out.println("Adding a field: "+fieldCode); data_datafields.add(datafield); } } state = STATE_COLLECTION_RECORD; } break; } case STATE_COLLECTION_RECORD_CONTROLFIELD: { if(elementEquals(qName, TAG_CONTROLFIELD)) { String fieldCode = data_controlfield_tag.trim(); if(!excludeFields.containsKey(fieldCode)) { if(!includeFields.isEmpty() && includeFields.containsKey(fieldCode)) { //System.out.println("Adding a control field: "+fieldCode); data_controlfields.put(fieldCode, data_controlfield); } else if(includeFields.isEmpty()) { //System.out.println("Adding a control field: "+fieldCode); data_controlfields.put(fieldCode, data_controlfield); } } state = STATE_COLLECTION_RECORD; } break; } case STATE_COLLECTION_RECORD_LEADER: { if(elementEquals(qName, TAG_LEADER)) { state = STATE_COLLECTION_RECORD; } break; } case STATE_COLLECTION_RECORD: { if(elementEquals(qName, TAG_RECORD)) { progress++; setProgress(progress / 100); if(progress % 100 == 0) hlog("Found "+progress+" MARCXML records."); topicalize(data_leader, data_datafields, data_controlfields, subjectIdentifiers, basenames, tm); state = STATE_COLLECTION; } break; } case STATE_COLLECTION: { if(elementEquals(qName, TAG_COLLECTION)) { state = STATE_START; } break; } } } public void characters(char[] ch, int start, int length) throws SAXException { String str = new String(ch,start,length); try { str = new String(str.getBytes(), defaultEncoding); } catch(Exception e) {} switch(state) { case STATE_COLLECTION_RECORD_LEADER: { data_leader += str; break; } case STATE_COLLECTION_RECORD_CONTROLFIELD: { data_controlfield += str; break; } case STATE_COLLECTION_RECORD_DATAFIELD: { data_datafield += str; break; } case STATE_COLLECTION_RECORD_DATAFIELD_SUBFIELD: { data_subfield += str; break; } default: break; } } public void warning(SAXParseException exception) throws SAXException { } public void error(SAXParseException exception) throws SAXException { parent.log("Error parsing XML document at "+exception.getLineNumber()+","+exception.getColumnNumber(),exception); } public void fatalError(SAXParseException exception) throws SAXException { parent.log("Fatal error parsing XML document at "+exception.getLineNumber()+","+exception.getColumnNumber(),exception); } public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {} public void processingInstruction(String target, String data) throws SAXException {} public void startPrefixMapping(String prefix, String uri) throws SAXException {} public void endPrefixMapping(String prefix) throws SAXException {} public void setDocumentLocator(org.xml.sax.Locator locator) {} public void skippedEntity(String name) throws SAXException {} private boolean elementEquals(String e, String str) { if(e != null && str != null) { if(e.equals(str)) return true; if(e.indexOf(":") > -1) { String[] eParts = e.split(":"); if(str.equals(eParts[eParts.length-1])) return true; } } return false; } } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- private String[] titleCodes = new String[] { "220" }; private String[] authorCodes = new String[] { "100" }; protected void topicalize(String leader, List<MarcField> datafields, Map<String,String> controlfields, List<String> subjectIdentifiers, List<String> basenames, TopicMap tm) { if(!(leader == null && datafields.isEmpty() && controlfields.isEmpty() && tm == null && subjectIdentifiers.isEmpty() && basenames.isEmpty())) { try { String recordHook = null; Topic recordTopic = tm.createTopic(); Topic recordTypeTopic = getRecordType(tm); boolean requiresAdditionalSI = true; if(subjectIdentifiers != null && subjectIdentifiers.size() > 0) { for(String si : subjectIdentifiers ) { if(si != null) { if(si.indexOf("___") == -1) { recordTopic.addSubjectIdentifier(new org.wandora.topicmap.Locator(si)); requiresAdditionalSI = false; recordHook = si; } } } recordTopic = tm.getTopic(recordHook); } if(requiresAdditionalSI) { org.wandora.topicmap.Locator si = TopicTools.createDefaultLocator(); recordTopic.addSubjectIdentifier(si); recordHook = si.toExternalForm(); } if(basenames != null && basenames.size() > 0) { String bn = null; for(String n : basenames ) { if(n != null) { if(n.indexOf("___") == -1) { recordTopic.setBaseName( n ); bn = n; } } } recordTopic = tm.getTopicWithBaseName(bn); } recordTopic.addType( recordTypeTopic ); // **** LEADER if(CONVERT_LEADERS && leader != null && leader.length() > 0) { Topic leaderType = getLeaderType(tm); Topic langTopic = getOrCreateTopic(tm, XTMPSI.getLang(defaultLang)); recordTopic.setData(leaderType, langTopic, leader); } // **** PROCESS CONTROL FIELDS if(controlfields != null && !controlfields.isEmpty()) { for(String controlfield : controlfields.keySet()) { String controlvalue = controlfields.get(controlfield); if( controlfield != null && controlvalue != null) { processControlField( controlfield, controlvalue, recordTopic, recordTypeTopic, tm); } } } // **** PROCESS DATA FIELDS if(datafields != null && !datafields.isEmpty()) { for( MarcField datafield : datafields ) { if(datafield != null) { // *** DEFAULT CONVERSION BRANCH *** String tag = datafield.getTag(); if(tag != null && tag.length() > 0) { Topic tagTopic = getFieldTopic(tag, tm); Topic ind1Topic = null; Topic ind1Type = null; Topic ind2Topic = null; Topic ind2Type = null; if(INCLUDE_INDX_IN_ASSOCIATIONS) { String ind1 = datafield.getInd1(); if( ind1 != null ) { ind1 = ind1.trim(); if( ind1.length() > 0 ) { ind1Topic = getInd1Topic( ind1.trim(), tag, tm ); ind1Type = getInd1Type( tag, tm ); } } String ind2 = datafield.getInd2(); if( ind2 != null ) { ind2 = ind2.trim(); if( ind2.length() > 0 ) { ind2Topic = getInd2Topic( ind2.trim(), tag, tm ); ind2Type = getInd2Type( tag, tm ); } } } // ****** CREATE ASSOCIATION Association a = tm.createAssociation(tagTopic); recordTopic = tm.getTopic(recordHook); a.addPlayer(recordTopic, recordTypeTopic); Map<String,Integer> usedSubFields = new LinkedHashMap<>(); for( MarcSubfield subfield : datafield.getSubfields() ) { String subcode = subfield.getCode(); String subvalue = subfield.getValue(); if(usedSubFields.containsKey( subcode )) { //log("Warning: Subfield code '"+subcode+"' used more than once in same datafield '"+tag+"'."); Integer count = (Integer) usedSubFields.get(subcode); int counti = count.intValue(); counti++; usedSubFields.put(subcode, Integer.valueOf(counti)); Topic subfieldCodeTopic = getSubFieldCodeTopic( subcode, counti, tag, datafield.getInd1(), datafield.getInd2(), tm); Topic subfieldDataTopic = getSubFieldDataTopic( subvalue, tag, datafield.getInd1(), datafield.getInd2(), tm); if( subfieldCodeTopic != null && subfieldDataTopic != null) { a.addPlayer(subfieldDataTopic, subfieldCodeTopic); } } else { usedSubFields.put(subcode, Integer.valueOf(1)); Topic subfieldCodeTopic = getSubFieldCodeTopic( subcode, tag, datafield.getInd1(), datafield.getInd2(), tm); Topic subfieldDataTopic = getSubFieldDataTopic( subvalue, tag, datafield.getInd1(), datafield.getInd2(), tm); if( subfieldCodeTopic != null && subfieldDataTopic != null) { a.addPlayer(subfieldDataTopic, subfieldCodeTopic); } } } if(INCLUDE_INDX_IN_ASSOCIATIONS) { if(ind1Topic != null && ind1Type != null) { a.addPlayer(ind1Topic, ind1Type); } if(ind2Topic != null && ind2Type != null) { a.addPlayer(ind2Topic, ind2Type); } } } } } } } catch(Exception e) { log(e); } } } public void processControlField( String field, String data, Topic record, Topic type, TopicMap tm ) throws TopicMapException { Topic fieldTopic = getFieldTopic( field, tm ); Topic langTopic = getOrCreateTopic(tm, XTMPSI.getLang(defaultLang)); record.setData(fieldTopic, langTopic, data); } // ------------------------------------------------------------------------- public Topic getLeaderType(TopicMap tm) throws TopicMapException { return getOrCreateTopic(tm, LEADER_SI, "Leader (MARC)", getMARCClass(tm)); } // -------------- public Topic getFieldTopic(String field, TopicMap tm) throws TopicMapException { String bn = null; if(SOLVE_FIELD_NAMES) bn = MarcField.getFieldName(field); return getOrCreateTopic(tm, makeFieldSI(field), bn, getFieldType(tm)); } public Topic getFieldType(TopicMap tm) throws TopicMapException { return getOrCreateTopic(tm, FIELD_SI, "Field (MARC)", getMARCClass(tm)); } protected String makeFieldSI(String field) { if(field != null) { String fieldSI = FIELD_SI_TEMPLATE.replace("___x___", field); return fieldSI; } return null; } // --- public Topic getSubFieldCodeType( TopicMap tm ) throws TopicMapException { return getOrCreateTopic(tm, SUBFIELDCODE_SI, "Subfield code (MARC)", getMARCClass(tm)); } public Topic getSubFieldCodeTopic( String subfied, int counter, String field, String ind1Modifier, String ind2Modifier, TopicMap tm) throws TopicMapException { String si = makeFieldSI(field) + "#" + subfied+"+"+counter; String bn = null; if(SOLVE_SUBFIELD_NAMES) bn = MarcSubfield.getSubfieldName( field, subfied ) + " ("+counter+")"; return getOrCreateTopic(tm, si, bn, getSubFieldCodeType(tm)); } public Topic getSubFieldCodeTopic( String subfied, String field, String ind1Modifier, String ind2Modifier, TopicMap tm) throws TopicMapException { String si = makeFieldSI(field) + "#" + subfied; String bn = null; if(SOLVE_SUBFIELD_NAMES) bn = MarcSubfield.getSubfieldName( field, subfied ); return getOrCreateTopic(tm, si, bn, getSubFieldCodeType(tm)); } public Topic getSubFieldDataTopic( String data, String tagModifier, String ind1Modifier, String ind2Modifier, TopicMap tm) throws TopicMapException { if(data != null) { data = data.trim(); if(data.length() > 0) { String niceData = data.trim(); niceData = niceData.replace("\n", " "); niceData = niceData.replace("\r", " "); niceData = niceData.replace("\t", " "); niceData = niceData.trim(); if(TRIM_DATAS) { if(niceData.endsWith(",")) niceData = niceData.substring(0, niceData.length()-1); if(niceData.endsWith(";")) niceData = niceData.substring(0, niceData.length()-1); if(niceData.endsWith(":")) niceData = niceData.substring(0, niceData.length()-1); if(niceData.endsWith("/")) niceData = niceData.substring(0, niceData.length()-1); if(niceData.endsWith("+")) niceData = niceData.substring(0, niceData.length()-1); niceData = niceData.trim(); data = data.trim(); if(data.endsWith(",")) data = data.substring(0, data.length()-1); if(data.endsWith(";")) data = data.substring(0, data.length()-1); if(data.endsWith(":")) data = data.substring(0, data.length()-1); if(data.endsWith("/")) data = data.substring(0, data.length()-1); if(data.endsWith("+")) data = data.substring(0, data.length()-1); data = data.trim(); } if(niceData.length() > 128) { niceData = niceData.substring(0, 128); niceData = niceData + " ("+data.hashCode()+")"; } Topic dataTopic=getOrCreateTopic(tm, DATA_SI+"/"+data.hashCode(), niceData); Topic dataTypeTopic = getDataType(tm); Topic langTopic = getOrCreateTopic(tm, XTMPSI.getLang(defaultLang)); // **** Store original field data to an occurrence! dataTopic.setData(dataTypeTopic, langTopic, data); dataTopic.addType(dataTypeTopic); return dataTopic; } } return null; } public Topic getDataType(TopicMap tm) throws TopicMapException { return getOrCreateTopic(tm, DATA_SI, "Data (MARC)", getMARCClass(tm)); } // --- public Topic getInd1Topic(String ind1, String tag, TopicMap tm) throws TopicMapException { String si = FIELD_SI_TEMPLATE.replace("___x___", tag); si = si+"#indicator1."+ind1; return getOrCreateTopic(tm, si, getIndicatorValueName(tag, "1", ind1), getInd1Type(tag, tm)); } public Topic getInd1Type(String tag, TopicMap tm) throws TopicMapException { String si = FIELD_SI_TEMPLATE.replace("___x___", tag); si = si+"#indicator1"; return getOrCreateTopic(tm, si, MarcField.getFieldIndicatorName(tag, "1"), getIndType(tm)); } public Topic getIndType(TopicMap tm) throws TopicMapException { return getOrCreateTopic(tm, IND_SI, "Indicator (MARC)", getMARCClass(tm)); } // --- public Topic getInd2Topic(String ind2, String tag, TopicMap tm) throws TopicMapException { String si = FIELD_SI_TEMPLATE.replace("___x___", tag); si = si+"#indicator2."+ind2; return getOrCreateTopic(tm, si, getIndicatorValueName(tag, "2", ind2), getInd2Type(tag, tm)); } public Topic getInd2Type(String tag, TopicMap tm) throws TopicMapException { String si = FIELD_SI_TEMPLATE.replace("___x___", tag); si = si+"#indicator2"; return getOrCreateTopic(tm, si, MarcField.getFieldIndicatorName(tag, "2"), getIndType(tm)); } public String getIndicatorName(String field, String indicatorId, String value) { String indicatorName = MarcField.getFieldIndicatorName(field, indicatorId); if( indicatorName != null ) return indicatorName+" ("+value+"@"+field+"#ind"+indicatorId+")"; else return value+"@"+field+"#ind"+indicatorId; } public String getIndicatorValueName(String field, String indicatorId, String value) { String indicatorValueName = MarcField.getFieldIndicatorValue(field, indicatorId, value); if( indicatorValueName != null ) return indicatorValueName; else return value; } // --- public Topic getRecordType(TopicMap tm) throws TopicMapException { return getOrCreateTopic(tm, RECORD_SI, "Record (MARC)", getMARCClass(tm)); } // --- public Topic getMARCClass(TopicMap tm) throws TopicMapException { return getOrCreateTopic(tm, MARC_SI, "MARC", getWandoraClass(tm) ); } public Topic getWandoraClass(TopicMap tm) throws TopicMapException { return getOrCreateTopic(tm, TMBox.WANDORACLASS_SI,"Wandora class"); } // -------- public Topic getTopic(TopicMap tm, String str, String SIBase, Topic type) throws TopicMapException { if(str != null && SIBase != null) { str = str.trim(); if(str.length() > 0) { Topic strTopic=getOrCreateTopic(tm, makeSI(SIBase, str), str, type); return strTopic; } } return null; } protected Topic getOrCreateTopic(TopicMap tm, String si) throws TopicMapException { return getOrCreateTopic(tm, si, null); } protected Topic getOrCreateTopic(TopicMap tm, String si,String bn) throws TopicMapException { return getOrCreateTopic(tm, si, bn, null); } protected Topic getOrCreateTopic(TopicMap tm, String si, String bn, Topic type) throws TopicMapException { return ExtractHelper.getOrCreateTopic(si, bn, type, tm); } protected void makeSubclassOf(TopicMap tm, Topic t, Topic superclass) throws TopicMapException { ExtractHelper.makeSubclassOf(t, superclass, tm); } protected String makeSI(String base, String endPoint) { String end = endPoint; try { end = URLEncoder.encode(endPoint, defaultEncoding); } catch(Exception e) { log(e); } String si = base + "/" + end; return si; } // ---------------- }
47,178
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MarcSubfield.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/marcxml/MarcSubfield.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * MarcSubfield.java * * Created on 2010-06-30 * */ package org.wandora.application.tools.extractors.marcxml; import java.util.HashMap; /** * * @author akivela */ public class MarcSubfield { private String code = null; private String value = null; public MarcSubfield(String c, String v) { this.code = c; this.value = v; } public String getCode() { return this.code; } public String getValue() { return this.value; } // ------------------------------------------------------------------------- private static final Object [] subfieldNames = new Object[] { "010", new String[] { "a", "LC control number (NR)", "b", "NUCMC control number (R)", "c", "Canceled/invalid LC control number (R)", "8", "Field link and sequence number (R)" }, "013", new String[] { "a", "Number (NR)", "b", "Country (NR)", "c", "Type of number (NR)", "d", "Date (R)", "e", "Status (R)", "f", "Party to document (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "015", new String[] { "a", "National bibliography number (R)", "z", "Canceled/invalid national bibliography number (R)", "2", "Source (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "016", new String[] { "a", "Record control number (NR)", "z", "Canceled/invalid control number (R)", "2", "Source (NR)", "8", "Field link and sequence number (R)" }, "017", new String[] { "a", "Copyright or legal deposit number (R)", "b", "Assigning agency (NR)", "d", "Date (NR)", "i", "Display text (NR)", "z", "Canceled/invalid copyright or legal deposit number (R)", "2", "Source (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "018", new String[] { "a", "Copyright article-fee code (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "020", new String[] { "a", "International Standard Book Number (NR)", "c", "Terms of availability (NR)", "z", "Canceled/invalid ISBN (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "022", new String[] { "a", "International Standard Serial Number (NR)", "l", "ISSN-L (NR)", "m", "Canceled ISSN-L (R)", "y", "Incorrect ISSN (R)", "z", "Canceled ISSN (R)", "2", "Source (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "024", new String[] { "a", "Standard number or code (NR)", "c", "Terms of availability (NR)", "d", "Additional codes following the standard number or code (NR)", "z", "Canceled/invalid standard number or code (R)", "2", "Source of number or code (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "025", new String[] { "a", "Overseas acquisition number (R)", "8", "Field link and sequence number (R)" }, "027", new String[] { "a", "Standard technical report number (NR)", "z", "Canceled/invalid number (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "028", new String[] { "a", "Publisher number (NR)", "b", "Source (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "030", new String[] { "a", "CODEN (NR)", "z", "Canceled/invalid CODEN (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "031", new String[] { "a", "Number of work (NR)", "b", "Number of movement (NR)", "c", "Number of excerpt (NR)", "d", "Caption or heading (R)", "e", "Role (NR)", "g", "Clef (NR)", "m", "Voice/instrument (NR)", "n", "Key signature (NR)", "o", "Time signature (NR)", "p", "Musical notation (NR)", "q", "General note (R)", "r", "Key or mode (NR)", "s", "Coded validity note (R)", "t", "Text incipit (R)", "u", "Uniform Resource Identifier (R)", "y", "Link text (R)", "z", "Public note (R)", "2", "System code (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "032", new String[] { "a", "Postal registration number (NR)", "b", "Source agency assigning number (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "033", new String[] { "a", "Formatted date/time (R)", "b", "Geographic classification area code (R)", "c", "Geographic classification subarea code (R)", "p", "Place of event (R)", "0", "Record control number (R)", "2", "Source of term (R)", "3", "Materials specified (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "034", new String[] { "a", "Category of scale (NR)", "b", "Constant ratio linear horizontal scale (R)", "c", "Constant ratio linear vertical scale (R)", "d", "Coordinates - westernmost longitude (NR)", "e", "Coordinates - easternmost longitude (NR)", "f", "Coordinates - northernmost latitude (NR)", "g", "Coordinates - southernmost latitude (NR)", "h", "Angular scale (R)", "j", "Declination - northern limit (NR)", "k", "Declination - southern limit (NR)", "m", "Right ascension - eastern limit (NR)", "n", "Right ascension - western limit (NR)", "p", "Equinox (NR)", "r", "Distance from earth (NR)", "s", "G-ring latitude (R)", "t", "G-ring longitude (R)", "x", "Beginning date (NR)", "y", "Ending date (NR)", "x", "Name of extraterrestrial body (NR)", "2", "Source (NR)", "3", "Materials specified (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "035", new String[] { "a", "System control number (NR)", "z", "Canceled/invalid control number (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "036", new String[] { "a", "Original study number (NR)", "b", "Source agency assigning number (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "037", new String[] { "a", "Stock number (NR)", "b", "Source of stock number/acquisition (NR)", "c", "Terms of availability (R)", "f", "Form of issue (R)", "g", "Additional format characteristics (R)", "n", "Note (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "038", new String[] { "a", "Record content licensor (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, // -------- "040", new String[] { "a", "Original cataloging agency (NR)", "b", "Language of cataloging (NR)", "c", "Transcribing agency (NR)", "d", "Modifying agency (R)", "e", "Description conventions (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "041", new String[] { "a", "Language code of text/sound track or separate title (R)", "b", "Language code of summary or abstract (R)", "d", "Language code of sung or spoken text (R)", "e", "Language code of librettos (R)", "f", "Language code of table of contents (R)", "g", "Language code of accompanying material other than librettos (R)", "h", "Language code of original and/or intermediate translations of text (R)", "j", "Language code of subtitles or captions (R)", "2", "Source of code (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "042", new String[] { "a", "Authentication code (R)" }, "043", new String[] { "a", "Geographic area code (R)", "b", "Local GAC code (R)", "c", "ISO code (R)", "2", "Source of local code (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "044", new String[] { "a", "MARC country code (R)", "b", "Local subentity code (R)", "c", "ISO country code (R)", "2", "Source of local subentity code (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "045", new String[] { "a", "Time period code (R)", "b", "Formatted 9999 B.C. through C.E. time period (R)", "c", "Formatted pre-9999 B.C. time period (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "046", new String[] { "a", "Type of date code (NR)", "b", "Date 1, B.C. date (NR)", "c", "Date 1, C.E. date (NR)", "d", "Date 2, B.C. date (NR)", "e", "Date 2, C.E. date (NR)", "j", "Date resource modified (NR)", "k", "Beginning or single date created (NR)", "l", "Ending date created (NR)", "m", "Beginning of date valid (NR)", "n", "End of date valid (NR)", "2", "Source of date (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "047", new String[] { "a", "Form of musical composition code (R)", "2", "Source of code (NR)", "8", "Field link and sequence number (R)" }, "048", new String[] { "a", "Performer or ensemble (R)", "b", "Soloist (R)", "2", "Source of code (NR)", "8", "Field link and sequence number (R)" }, "050", new String[] { "a", "Classification number (R) ", "b", "Item number (NR)", "3", "Materials specified (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "051", new String[] { "a", "Classification number (NR)", "b", "Item number (NR)", "c", "Copy information (NR)", "8", "Field link and sequence number (R)" }, "052", new String[] { "a", "Geographic classification area code (NR)", "b", "Geographic classification subarea code (R)", "d", "Populated place name (R)", "2", "Code source (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "080", new String[] { "a", "Universal Decimal Classification number (NR)", "b", "Item number (NR)", "x", "Common auxiliary subdivision (R)", "2", "Edition identifier (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "055", new String[] { "a", "Classification number (NR)", "b", "Item number (NR)", "2", "Source of call/class number (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "060", new String[] { "a", "Classification number (R)", "b", "Item number (NR)", "8", "Field link and sequence number (R)" }, "061", new String[] { "a", "Classification number (R)", "b", "Item number (NR)", "c", "Copy information (NR)", "8", "Field link and sequence number (R)" }, "066", new String[] { "a", "Primary G0 character set (NR)", "b", "Primary G1 character set (NR)", "c", "Alternate G0 or G1 character set (R)", }, "070", new String[] { "a", "Classification number (R)", "b", "Item number (NR)", "8", "Field link and sequence number (R)" }, "071", new String[] { "a", "Classification number (R)", "b", "Item number (NR)", "c", "Copy information (R)", "8", "Field link and sequence number (R)" }, "072", new String[] { "a", "Subject category code (NR)", "x", "Subject category code subdivision (R)", "2", "Source (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "074", new String[] { "a", "GPO item number (NR)", "z", "Canceled/invalid GPO item number (R)", "8", "Field link and sequence number (R)" }, "080", new String[] { "a", "Universal Decimal Classification number (NR)", "b", "Item number (NR)", "x", "Common auxiliary subdivision (R)", "2", "Edition identifier (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "082", new String[] { "a", "Classification number (R)", "b", "Item number (NR)", "m", "Standard or optional designation (NR)", "q", "Assigning agency (NR)", "2", "Edition number (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "083", new String[] { "a", "Classification number (R)", "c", "Classification number--Ending number of span (R)", "m", "Standard or optional designation (NR)", "q", "Assigning agency (NR)", "y", "Table sequence number for internal subarrangement or add table (R)", "z", "Table identification (R)", "2", "Edition number (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "084", new String[] { "a", "Classification number (R)", "b", "Item number (NR)", "2", "Number source (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "085", new String[] { "a", "Number where instructions are found-single number or beginning number of span (R)", "b", "Base number (R)", "c", "Classification number-ending number of span (R)", "f", "Facet designator (R)", "r", "Root number (R)", "s", "Digits added from classification number in schedule or external table (R)", "t", "Digits added from internal subarrangement or add table (R)", "u", "Number being analyzed (R)", "v", "Number in internal subarrangement or add table where instructions are found (R)", "w", "Table identification-Internal subarrangement or add table (R)", "y", "Table sequence number for internal subarrangement or add table (R)", "z", "Table identification (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "086", new String[] { "a", "Classification number (NR)", "z", "Canceled/invalid classification number (R)", "2", "Number source (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "088", new String[] { "a", "Report number (NR)", "z", "Canceled/invalid report number (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "100", new String[] { "a", "Personal name (NR)", "b", "Numeration (NR)", "c", "Titles and words associated with a name (R)", "d", "Dates associated with a name (NR)", "e", "Relator term (R)", "f", "Date of a work (NR)", "g", "Miscellaneous information (NR)", "j", "Attribution qualifier (R)", "k", "Form subheading (R)", "l", "Language of a work (NR)", "n", "Number of part/section of a work (R)", "p", "Name of part/section of a work (R)", "q", "Fuller form of name (NR)", "t", "Title of a work (NR)", "u", "Affiliation (NR)", "0", "Authority record control number (R)", "4", "Relator code (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "110", new String[] { "a", "Corporate name or jurisdiction name as entry element (NR)", "b", "Subordinate unit (R)", "c", "Location of meeting (NR)", "d", "Date of meeting or treaty signing (R)", "e", "Relator term (R)", "f", "Date of a work (NR)", "g", "Miscellaneous information (NR)", "k", "Form subheading (R)", "l", "Language of a work (NR)", "n", "Number of part/section/meeting (R)", "p", "Name of part/section of a work (R)", "t", "Title of a work (NR)", "u", "Affiliation (NR)", "0", "Authority record control number (R)", "4", "Relator code (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "111", new String[] { "a", "Meeting name or jurisdiction name as entry element (NR)", "c", "Location of meeting (NR)", "d", "Date of meeting (NR)", "e", "Subordinate unit (R)", "f", "Date of a work (NR)", "g", "Miscellaneous information (NR)", "j", "Relator term (R)", "k", "Form subheading (R)", "l", "Language of a work (NR)", "n", "Number of part/section/meeting (R)", "p", "Name of part/section of a work (R)", "q", "Name of meeting following jurisdiction name entry element (NR)", "t", "Title of a work (NR)", "u", "Affiliation (NR)", "0", "Authority record control number (R)", "4", "Relator code (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "130", new String[] { "a", "Uniform title (NR)", "d", "Date of treaty signing (R)", "f", "Date of a work (NR)", "g", "Miscellaneous information (NR)", "h", "Medium (NR)", "k", "Form subheading (R)", "l", "Language of a work (NR)", "m", "Medium of performance for music (R)", "n", "Number of part/section of a work (R)", "o", "Arranged statement for music (NR)", "p", "Name of part/section of a work (R)", "r", "Key for music (NR)", "s", "Version (NR)", "t", "Title of a work (NR)", "0", "Authority record control number (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "210", new String[] { "a", "Abbreviated title (NR)", "b", "Qualifying information (NR)", "2", "Source (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "022", new String[] { "a", "Key title (NR)", "b", "Qualifying information (NR)", "6", "$Linkage (NR)", "8", "Field link and sequence number (R)" }, "240", new String[] { "a", "Uniform title (NR)", "d", "Date of treaty signing (R)", "f", "Date of a work (NR)", "g", "Miscellaneous information (NR)", "h", "Medium (NR)", "k", "Form subheading (R)", "l", "Language of a work (NR)", "m", "Medium of performance for music (R)", "n", "Number of part/section of a work (R)", "o", "Arranged statement for music (NR)", "p", "Name of part/section of a work (R)", "r", "Key for music (NR)", "s", "Version (NR)", "0", "Authority record control number (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "242", new String[] { "a", "Title (NR)", "b", "Remainder of title (NR)", "c", "Statement of responsibility, etc. (NR)", "h", "Medium (NR)", "n", "Number of part/section of a work (R)", "p", "Name of part/section of a work (R)", "y", "Language code of translated title (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "243", new String[] { "a", "Uniform title (NR)", "d", "Date of treaty signing (R)", "f", "Date of a work (NR)", "g", "Miscellaneous information (NR)", "h", "Medium (NR)", "k", "Form subheading (R)", "l", "Language of a work (NR)", "m", "Medium of performance for music (R)", "n", "Number of part/section of a work (R)", "o", "Arranged statement for music (NR)", "p", "Name of part/section of a work (R)", "r", "Key for music (NR)", "s", "Version (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "245", new String[] { "a", "Title (NR)", "b", "Remainder of title (NR)", "c", "Statement of responsibility, etc. (NR)", "f", "Inclusive dates (NR)", "g", "Bulk dates (NR)", "h", "Medium (NR)", "k", "Form (R)", "n", "Number of part/section of a work (R)", "p", "Name of part/section of a work (R)", "s", "Version (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "246", new String[] { "a", "Title proper/short title (NR)", "b", "Remainder of title (NR)", "f", "Date or sequential designation (NR)", "g", "Miscellaneous information (NR)", "h", "Medium (NR)", "i", "Display text (NR)", "n", "Number of part/section of a work (R)", "p", "Name of part/section of a work (R)", "5", "Institution to which field applies (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "247", new String[] { "a", "Title (NR)", "b", "Remainder of title (NR)", "f", "Date or sequential designation (NR)", "g", "Miscellaneous information (NR)", "h", "Medium (NR)", "n", "Number of part/section of a work (R)", "p", "Name of part/section of a work (R)", "x", "International Standard Serial Number (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "250", new String[] { "a", "Edition statement (NR)", "b", "Remainder of edition statement (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "254", new String[] { "a", "Musical presentation statement (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "255", new String[] { "a", "Statement of scale (NR)", "b", "Statement of projection (NR)", "c", "Statement of coordinates (NR)", "d", "Statement of zone (NR)", "e", "Statement of equinox (NR)", "f", "Outer G-ring coordinate pairs (NR)", "g", "Exclusion G-ring coordinate pairs (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "256", new String[] { "a", "Computer file characteristics (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "257", new String[] { "a", "Country of producing entity (R)", "2", "Source (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "258", new String[] { "a", "Issuing jurisdiction (NR)", "b", "Denomination (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "260", new String[] { "a", "Place of publication, distribution, etc. (R)", "b", "Name of publisher, distributor, etc. (R)", "c", "Date of publication, distribution, etc. (R)", "e", "Place of manufacture (R)", "f", "Manufacturer (R)", "g", "Date of manufacture (R)", "3", "Materials specified (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "263", new String[] { "a", "Projected publication date (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "270", new String[] { "a", "Address (R)", "b", "City (NR)", "c", "State or province (NR)", "d", "Country (NR)", "e", "Postal code (NR)", "f", "Terms preceding attention name (NR)", "g", "Attention name (NR)", "h", "Attention position (NR)", "i", "Type of address (NR)", "j", "Specialized telephone number (R)", "k", "Telephone number (R)", "l", "Fax number (R)", "m", "Electronic mail address (R)", "n", "TDD or TTY number (R)", "p", "Contact person (R)", "q", "Title of contact person (R)", "r", "Hours (R)", "z", "Public note (R)", "4", "Relator code (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "300", new String[] { "a", "Extent (R)", "b", "Other physical details (NR)", "c", "Dimensions (R)", "e", "Accompanying material (NR)", "f", "Type of unit (R)", "g", "Size of unit (R)", "3", "Materials specified (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "306", new String[] { "a", "Playing time (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)", }, "307", new String[] { "a", "Hours (NR)", "b", "Additional information (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "310", new String[] { "a", "Current publication frequency (NR)", "b", "Date of current publication frequency (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "321", new String[] { "a", "Former publication frequency (NR)", "b", "Dates of former publication frequency (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "336", new String[] { "a", "Content type term (R)", "b", "Content type code (R)", "2", "Source (NR)", "3", "Materials specified (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "337", new String[] { "a", "Media type term (R)", "b", "Media type code (R)", "2", "Source (NR)", "3", "Materials specified (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "338", new String[] { "a", "Carrier type term (R)", "b", "Media type code (R)", "2", "Source (NR)", "3", "Materials specified (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "340", new String[] { "a", "Material base and configuration (R)", "b", "Dimensions (R)", "c", "Materials applied to surface (R)", "d", "Information recording technique (R)", "e", "Support (R)", "f", "Production rate/ratio (R)", "h", "Location within medium (R)", "i", "Technical specifications of medium (R)", "3", "Materials specified (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "342", new String[] { "a", "Name (NR)", "b", "Coordinate units or distance units (NR)", "c", "Latitude resolution (NR)", "d", "Longitude resolution (NR)", "e", "Standard parallel or oblique line latitude (R)", "f", "Oblique line longitude (R)", "g", "Longitude of central meridian or projection center (NR)", "h", "Latitude of projection center or projection origin (NR)", "i", "False easting (NR)", "j", "False northing (NR)", "k", "Scale factor (NR)", "l", "Height of perspective point above surface (NR)", "m", "Azimuthal angle (NR)", "n", "Azimuth measure point longitude or straight vertical longitude from pole (NR)", "o", "Landsat number and path number (NR)", "p", "Zone identifier (NR)", "q", "Ellipsoid name (NR)", "r", "Semi-major axis (NR)", "s", "Denominator of flattening ratio (NR)", "t", "Vertical resolution (NR)", "u", "Vertical encoding method (NR)", "v", "Local planar, local, or other projection or grid description (NR)", "w", "Local planar or local georeference information (NR)", "2", "Reference method used (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "343", new String[] { "a", "Planar coordinate encoding method (NR)", "b", "Planar distance units (NR)", "c", "Abscissa resolution (NR)", "d", "Ordinate resolution (NR)", "e", "Distance resolution (NR)", "f", "Bearing resolution (NR)", "g", "Bearing units (NR)", "h", "Bearing reference direction (NR)", "i", "Bearing reference meridian (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "351", new String[] { "a", "Organization (R)", "b", "Arrangement (R)", "c", "Hierarchical level (NR)", "3", "Materials specified (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "352", new String[] { "a", "Direct reference method (NR)", "b", "Object type (R)", "c", "Object count (R)", "d", "Row count (NR)", "e", "Column count (NR)", "f", "Vertical count (NR)", "g", "VPF topology level (NR)", "i", "Indirect reference description (NR)", "q", "Format of the digital image (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "355", new String[] { "a", "Security classification (NR)", "b", "Handling instructions (R)", "c", "External dissemination information (R)", "d", "Downgrading or declassification event (NR)", "e", "Classification system (NR)", "f", "Country of origin code (NR)", "g", "Downgrading date (NR)", "h", "Declassification date (NR)", "j", "Authorization (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "357", new String[] { "a", "Originator control term (NR)", "b", "Originating agency (R)", "c", "Authorized recipients of material (R)", "g", "Other restrictions (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "362", new String[] { "a", "Dates of publication and/or sequential designation (NR)", "z", "Source of information (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "363", new String[] { "a", "First level of enumeration (NR)", "b", "Second level of enumeration (NR)", "c", "Third level of enumeration (NR)", "d", "Fourth level of enumeration (NR)", "e", "Fifth level of enumeration (NR)", "f", "Sixth level of enumeration (NR)", "g", "Alternative numbering scheme, first level of enumeration (NR)", "h", "Alternative numbering scheme, second level of enumeration (NR)", "i", "First level of chronology (NR)", "j", "Second level of chronology (NR)", "k", "Third level of chronology (NR)", "l", "Fourth level of chronology (NR)", "m", "Alternative numbering scheme, chronology (NR)", "u", "First level textual designation (NR)", "v", "First level of chronology, issuance (NR)", "x", "Nonpublic note (R)", "z", "Public note (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "365", new String[] { "a", "Price type code (NR)", "b", "Price amount (NR)", "c", "Currency code (NR)", "d", "Unit of pricing (NR)", "e", "Price note (NR)", "f", "Price effective from (NR)", "g", "Price effective until (NR)", "h", "Tax rate 1 (NR)", "i", "Tax rate 2 (NR)", "j", "ISO country code (NR)", "k", "MARC country code (NR)", "m", "Identification of pricing entity (NR)", "2", "Source of price type code (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "366", new String[] { "a", "Publishers' compressed title identification (NR)", "b", "Detailed date of publication (NR)", "c", "Availability status code (NR)", "d", "Expected next availability date (NR)", "e", "Note (NR)", "f", "Publisher's discount category (NR)", "g", "Date made out of print (NR)", "j", "ISO country code (NR)", "k", "MARC country code (NR)", "m", "Identification of agency (NR)", "2", "Source of availability status code (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "380", new String[] { "a", "Form of work (R)", "0", "Record control number (R)", "2", "Source of term (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "381", new String[] { "a", "Other distinguishing characteristic (R)", "u", "Uniform Resource Identifier (R)", "v", "Source of information (R)", "0", "Record control number (R)", "2", "Source of term (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "382", new String[] { "a", "Medium of performance (R)", "u", "Record control number (R)", "2", "Source of term (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "383", new String[] { "a", "Serial number (R)", "b", "Opus number (R)", "c", "Thematic index number (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "384", new String[] { "a", "Key (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "490", new String[] { "a", "Series statement (R)", "l", "Library of Congress call number (NR)", "v", "Volume/sequential designation (R)", "x", "International Standard Serial Number (R)", "3", "Materials specified (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "500", new String[] { "a", "General note (NR)", "3", "Materials specified (NR)", "5", "Institution to which field applies (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "501", new String[] { "a", "With note (NR)", "5", "Institution to which field applies (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "502", new String[] { "a", "Dissertation note (NR)", "b", "Degree type (NR)", "c", "Name of granting institution (NR)", "d", "Year degree granted (NR)", "g", "Miscellaneous information (R)", "o", "Dissertation identifier (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "504", new String[] { "a", "Bibliography, etc. note (NR)", "b", "Number of references (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "505", new String[] { "a", "Formatted contents note (NR)", "g", "Miscellaneous information (R)", "r", "Statement of responsibility (R)", "t", "Title (R)", "u", "Uniform Resource Identifier (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "506", new String[] { "a", "Terms governing access (NR)", "b", "Jurisdiction (R)", "c", "Physical access provisions (R)", "d", "Authorized users (R)", "e", "Authorization (R)", "f", "Standardized terminology for access restriction (R)", "u", "Uniform Resource Identifier (R)", "2", "Source of term (NR)", "3", "Materials specified (NR)", "5", "Institution to which field applies (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "507", new String[] { "a", "Representative fraction of scale note (NR)", "b", "Remainder of scale note (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "508", new String[] { "a", "Creation/production credits note (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "510", new String[] { "a", "Name of source (NR)", "b", "Coverage of source (NR)", "c", "Location within source (NR)", "u", "Uniform Resource Identifier (R)", "x", "International Standard Serial Number (NR)", "3", "Materials specified (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "511", new String[] { "a", "Participant or performer note (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "513", new String[] { "a", "Type of report (NR)", "b", "Period covered (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "514", new String[] { "a", "Attribute accuracy report (NR)", "b", "Attribute accuracy value (R)", "c", "Attribute accuracy explanation (R)", "d", "Logical consistency report (NR)", "e", "Completeness report (NR)", "f", "Horizontal position accuracy report (NR)", "g", "Horizontal position accuracy value (R)", "h", "Horizontal position accuracy explanation (R)", "i", "Vertical positional accuracy report (NR)", "j", "Vertical positional accuracy value (R)", "k", "Vertical positional accuracy explanation (R)", "m", "Cloud cover (NR)", "u", "Uniform Resource Identifier (R)", "z", "Display note (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "515", new String[] { "a", "Numbering peculiarities note (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "516", new String[] { "a", "Type of computer file or data note (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "518", new String[] { "a", "Date/time and place of an event note (NR)", "d", "Date of event (R)", "o", "Other event information (R)", "p", "Place of event (R)", "0", "Record control number (R)", "2", "Source of term (R)", "3", "Materials specified (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "520", new String[] { "a", "Summary, etc. (NR)", "b", "Expansion of summary note (NR)", "c", "Assigning source (NR)", "u", "Uniform Resource Identifier (R)", "2", "Source (NR)", "3", "Materials specified (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "521", new String[] { "a", "Target audience note (R)", "b", "Source (NR)", "3", "Materials specified (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "522", new String[] { "a", "Geographic coverage note (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "524", new String[] { "a", "Preferred citation of described materials note (NR)", "2", "Source of schema used (NR)", "3", "Materials specified (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "525", new String[] { "a", "Supplement note (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "526", new String[] { "a", "Program name (NR)", "b", "Interest level (NR)", "c", "Reading level (NR)", "d", "Title point value (NR)", "i", "Display text (NR)", "x", "Nonpublic note (R)", "z", "Public note (R)", "5", "Institution to which field applies (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "530", new String[] { "a", "Additional physical form available note (NR)", "b", "Availability source (NR)", "c", "Availability conditions (NR)", "d", "Order number (NR)", "u", "Uniform Resource Identifier (R)", "3", "Materials specified (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "533", new String[] { "a", "Type of reproduction (NR)", "b", "Place of reproduction (R)", "c", "Agency responsible for reproduction (R)", "d", "Date of reproduction (NR)", "e", "Physical description of reproduction (NR)", "f", "Series statement of reproduction (R)", "m", "Dates and/or sequential designation of issues reproduced (R)", "n", "Note about reproduction (R)", "3", "Materials specified (NR)", "5", "Institution to which field applies (NR)", "7", "Fixed-length data elements of reproduction (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "534", new String[] { "a", "Main entry of original (NR)", "b", "Edition statement of original (NR)", "c", "Publication, distribution, etc. of original (NR)", "e", "Physical description, etc. of original (NR)", "f", "Series statement of original (R)", "k", "Key title of original (R)", "l", "Location of original (NR)", "m", "Material specific details (NR)", "n", "Note about original (R)", "o", "Other resource identifier (R)", "p", "Introductory phrase (NR)", "t", "Title statement of original (NR)", "x", "International Standard Serial Number (R)", "z", "International Standard Book Number (R)", "3", "Materials specified (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "535", new String[] { "a", "Custodian (NR)", "b", "Postal address (R)", "c", "Country (R)", "d", "Telecommunications address (R)", "g", "Repository location code (NR)", "3", "Materials specified (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "536", new String[] { "a", "Text of note (NR)", "b", "Contract number (R)", "c", "Grant number (R)", "d", "Undifferentiated number (R)", "e", "Program element number (R)", "f", "Project number (R)", "g", "Task number (R)", "h", "Work unit number (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "538", new String[] { "a", "System details note (NR)", "i", "Display text (NR)", "u", "Uniform Resource Identifier (R)", "3", "Materials specified (NR)", "5", "Institution to which field applies (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "540", new String[] { "a", "Terms governing use and reproduction (NR)", "b", "Jurisdiction (NR)", "c", "Authorization (NR)", "d", "Authorized users (NR)", "u", "Uniform Resource Identifier (R)", "3", "Materials specified (NR)", "5", "Institution to which field applies (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "541", new String[] { "a", "Source of acquisition (NR)", "b", "Address (NR)", "c", "Method of acquisition (NR)", "d", "Date of acquisition (NR)", "e", "Accession number (NR)", "f", "Owner (NR)", "h", "Purchase price (NR)", "n", "Extent (R)", "o", "Type of unit (R)", "3", "Materials specified (NR)", "5", "Institution to which field applies (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "542", new String[] { "a", "Personal creator (NR)", "b", "Personal creator death date (NR)", "c", "Corporate creator (NR)", "d", "Copyright holder (R)", "e", "Copyright holder contact information (R)", "f", "Copyright statement (R)", "g", "Copyright date (NR)", "h", "Copyright renewal date (R)", "i", "Publication date (NR)", "j", "Creation date (NR)", "k", "Publisher (R)", "l", "Copyright status (NR)", "m", "Publication status (NR)", "n", "Note (R)", "o", "Research date (NR)", "p", "Country of publication or creation (R)", "q", "Supplying agency (NR)", "r", "Jurisdiction of copyright assessment (NR)", "s", "Source of information (NR)", "u", "Uniform Resource Identifier (R)", "3", "Materials specified (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "544", new String[] { "a", "Custodian (R)", "b", "Address (R)", "c", "Country (R)", "d", "Title (R)", "e", "Provenance (R)", "n", "Note (R)", "3", "Materials specified (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "545", new String[] { "a", "Biographical or historical data (NR)", "b", "Expansion (NR)", "u", "Uniform Resource Identifier (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "546", new String[] { "a", "Language note (NR)", "b", "Information code or alphabet (R)", "3", "Materials specified (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "547", new String[] { "a", "Former title complexity note (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "550", new String[] { "a", "Issuing body note (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "552", new String[] { "a", "Entity type label (NR)", "b", "Entity type definition and source (NR)", "c", "Attribute label (NR)", "d", "Attribute definition and source (NR)", "e", "Enumerated domain value (R)", "f", "Enumerated domain value definition and source (R)", "g", "Range domain minimum and maximum (NR)", "h", "Codeset name and source (NR)", "i", "Unrepresentable domain (NR)", "j", "Attribute units of measurement and resolution (NR)", "k", "Beginning and ending date of attribute values (NR)", "l", "Attribute value accuracy (NR)", "m", "Attribute value accuracy explanation (NR)", "n", "Attribute measurement frequency (NR)", "o", "Entity and attribute overview (R)", "p", "Entity and attribute detail citation (R)", "u", "Uniform Resource Identifier (R)", "z", "Display note (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "555", new String[] { "a", "Cumulative index/finding aids note (NR)", "b", "Availability source (R)", "c", "Degree of control (NR)", "d", "Bibliographic reference (NR)", "u", "Uniform Resource Identifier (R)", "3", "Materials specified (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "556", new String[] { "a", "Information about documentation note (NR)", "z", "International Standard Book Number (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "561", new String[] { "a", "History (NR)", "3", "Materials specified (NR)", "5", "Institution to which field applies (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "562", new String[] { "a", "Identifying markings (R)", "b", "Copy identification (R)", "c", "Version identification (R)", "d", "Presentation format (R)", "e", "Number of copies (R)", "3", "Materials specified (NR)", "5", "Institution to which field applies (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "563", new String[] { "a", "Binding note (NR)", "u", "Uniform Resource Identifier (R)", "3", "Materials specified (NR)", "5", "Institution to which field applies (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "565", new String[] { "a", "Number of cases/variables (NR)", "b", "Name of variable (R)", "c", "Unit of analysis (R)", "d", "Universe of data (R)", "e", "Filing scheme or code (R)", "3", "Materials specified (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "567", new String[] { "a", "Methodology note (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "580", new String[] { "a", "Linking entry complexity note (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "581", new String[] { "a", "Publications about described materials note (NR)", "z", "International Standard Book Number (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "583", new String[] { "a", "Action (NR)", "b", "Action identification (R)", "c", "Time/date of action (R)", "d", "Action interval (R)", "e", "Contingency for action (R)", "f", "Authorization (R)", "h", "Jurisdiction (R)", "i", "Method of action (R)", "j", "Site of action (R)", "k", "Action agent (R)", "l", "Status (R)", "n", "Extent (R)", "o", "Type of unit (R)", "u", "Uniform Resource Identifier (R)", "x", "Nonpublic note (R)", "z", "Public note (R)", "2", "Source of term (NR)", "3", "Materials specified (NR)", "5", "Institution to which field applies (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "584", new String[] { "a", "Accumulation (R)", "b", "Frequency of use (R)", "3", "Materials specified (NR)", "5", "Institution to which field applies (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "585", new String[] { "a", "Exhibitions note (NR)", "3", "Materials specified (NR)", "5", "Institution to which field applies (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "586", new String[] { "a", "Awards note (NR)", "3", "Materials specified (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "588", new String[] { "a", "Source of description note (NR)", "5", "Institution to which field applies (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "600", new String[] { "a", "Personal name (NR)", "b", "Numeration (NR)", "c", "Titles and other words associated with a name (R)", "d", "Dates associated with a name (NR)", "e", "Relator term (R)", "f", "Date of a work (NR)", "g", "Miscellaneous information (NR)", "h", "Medium (NR)", "j", "Attribution qualifier (R)", "k", "Form subheading (R)", "l", "Language of a work (NR)", "m", "Medium of performance for music (R)", "n", "Number of part/section of a work (R)", "o", "Arranged statement for music (NR)", "p", "Name of part/section of a work (R)", "q", "Fuller form of name (NR)", "r", "Key for music (NR)", "s", "Version (NR)", "t", "Title of a work (NR)", "u", "Affiliation (NR)", "v", "Form subdivision (R)", "x", "General subdivision (R)", "y", "Chronological subdivision (R)", "z", "Geographic subdivision (R)", "0", "Authority record control number (R)", "2", "Source of heading or term (NR)", "3", "Materials specified (NR)", "4", "Relator code (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "610", new String[] { "a", "Corporate name or jurisdiction name as entry element (NR)", "b", "Subordinate unit (R)", "c", "Location of meeting (NR)", "d", "Date of meeting or treaty signing (R)", "e", "Relator term (R)", "f", "Date of a work (NR)", "g", "Miscellaneous information (NR)", "h", "Medium (NR)", "k", "Form subheading (R)", "l", "Language of a work (NR)", "m", "Medium of performance for music (R)", "n", "Number of part/section/meeting (R)", "o", "Arranged statement for music (NR)", "p", "Name of part/section of a work (R)", "r", "Key for music (NR)", "s", "Version (NR)", "t", "Title of a work (NR)", "u", "Affiliation (NR)", "v", "Form subdivision (R)", "x", "General subdivision (R)", "y", "Chronological subdivision (R)", "z", "Geographic subdivision (R)", "0", "Authority record control number (R)", "2", "Source of heading or term (NR)", "3", "Materials specified (NR)", "4", "Relator code (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "611", new String[] { "a", "Meeting name or jurisdiction name as entry element (NR)", "c", "Location of meeting (NR)", "d", "Date of meeting (NR)", "e", "Subordinate unit (R)", "f", "Date of a work (NR)", "g", "Miscellaneous information (NR)", "h", "Medium (NR)", "j", "Relator term (R)", "k", "Form subheading (R)", "l", "Language of a work (NR)", "n", "Number of part/section/meeting (R)", "p", "Name of part/section of a work (R)", "q", "Name of meeting following jurisdiction name entry element (NR)", "s", "Version (NR)", "t", "Title of a work (NR)", "u", "Affiliation (NR)", "v", "Form subdivision (R)", "x", "General subdivision (R)", "y", "Chronological subdivision (R)", "z", "Geographic subdivision (R)", "0", "Authority record control number (R)", "2", "Source of heading or term (NR)", "3", "Materials specified (NR)", "4", "Relator code (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "630", new String[] { "a", "Uniform title (NR) ", "d", "Date of treaty signing (R)", "e", "Relator term (R)", "f", "Date of a work (NR)", "g", "Miscellaneous information (NR)", "h", "Medium (NR)", "k", "Form subheading (R)", "l", "Language of a work (NR)", "m", "Medium of performance for music (R)", "n", "Number of part/section of a work (R)", "o", "Arranged statement for music (NR)", "p", "Name of part/section of a work (R)", "r", "Key for music (NR)", "s", "Version (NR)", "t", "Title of a work (NR)", "v", "Form subdivision (R)", "x", "General subdivision (R)", "y", "Chronological subdivision (R)", "z", "Geographic subdivision (R)", "0", "Authority record control number (R)", "2", "Source of heading or term (NR)", "3", "Materials specified (NR)", "4", "Relator code (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "648", new String[] { "a", "Chronological term (NR)", "v", "Form subdivision (R)", "x", "General subdivision (R)", "y", "Chronological subdivision (R)", "z", "Geographic subdivision (R)", "0", "Authority record control number (R)", "2", "Source of heading or term (NR)", "3", "Materials specified (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)", }, "650", new String[] { "a", "Topical term or geographic name entry element (NR)", "b", "Topical term following geographic name entry element (NR)", "c", "Location of event (NR)", "d", "Active dates (NR)", "e", "Relator term (R)", "4", "Relator code (R)", "v", "Form subdivision (R)", "x", "General subdivision (R)", "y", "Chronological subdivision (R)", "z", "Geographic subdivision (R)", "0", "Authority record control number (R)", "2", "Source of heading or term (NR)", "3", "Materials specified (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)", }, "651", new String[] { "a", "Geographic name (NR)", "e", "Relator term (R)", "4", "Relator code (R)", "v", "Form subdivision (R)", "x", "General subdivision (R)", "y", "Chronological subdivision (R)", "z", "Geographic subdivision (R)", "0", "Authority record control number (R)", "2", "Source of heading or term (NR)", "3", "Materials specified (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)", }, "653", new String[] { "a", "Uncontrolled term (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "654", new String[] { "a", "Focus term (R)", "b", "Non-focus term (R)", "c", "Facet/hierarchy designation (R)", "e", "Relator term (R)", "v", "Form subdivision (R)", "y", "Chronological subdivision (R)", "z", "Geographic subdivision (R)", "0", "Authority record control number (R)", "2", "Source of heading or term (NR)", "3", "Materials specified (NR)", "4", "Relator code (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "655", new String[] { "a", "Genre/form data or focus term (NR)", "b", "Non-focus term (R)", "c", "Facet/hierarchy designation (R)", "v", "Form subdivision (R)", "x", "General subdivision (R)", "y", "Chronological subdivision (R)", "z", "Geographic subdivision (R)", "0", "Authority record control number (R)", "2", "Source of term (NR)", "3", "Materials specified (NR)", "5", "Institution to which field applies (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "656", new String[] { "a", "Occupation (NR)", "k", "Form (NR)", "v", "Form subdivision (R)", "x", "General subdivision (R)", "y", "Chronological subdivision (R)", "z", "Geographic subdivision (R)", "0", "Authority record control number (R)", "2", "Source of term (NR)", "3", "Materials specified (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "657", new String[] { "a", "Function (NR)", "v", "Form subdivision (R)", "x", "General subdivision (R)", "y", "Chronological subdivision (R)", "z", "Geographic subdivision (R)", "0", "Authority record control number (R)", "2", "Source of term (NR)", "3", "Materials specified (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "658", new String[] { "a", "Main curriculum objective (NR)", "b", "Subordinate curriculum objective (R)", "c", "Curriculum code (NR)", "d", "Correlation factor (NR)", "2", "Source of term or code (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "662", new String[] { "a", "Country or larger entity (R)", "b", "First-order political jurisdiction (NR)", "c", "Intermediate political jurisdiction (R)", "d", "City (NR)", "e", "Relator term (R)", "f", "City subsection (R)", "g", "Other nonjurisdictional geographic region and feature (R)", "h", "Extraterrestrial area (R)", "0", "Authority record control number (R)", "2", "Source of heading or term (NR)", "4", "Relator code (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "700", new String[] { "a", "Personal name (NR)", "b", "Numeration (NR)", "c", "Titles and other words associated with a name (R)", "d", "Dates associated with a name (NR)", "e", "Relator term (R)", "f", "Date of a work (NR)", "g", "Miscellaneous information (NR)", "h", "Medium (NR)", "i", "Relationship information (R)", "j", "Attribution qualifier (R)", "k", "Form subheading (R)", "l", "Language of a work (NR)", "m", "Medium of performance for music (R)", "n", "Number of part/section of a work (R)", "o", "Arranged statement for music (NR)", "p", "Name of part/section of a work (R)", "q", "Fuller form of name (NR)", "r", "Key for music (NR)", "s", "Version (NR)", "t", "Title of a work (NR)", "u", "Affiliation (NR)", "v", "Form subdivision (R)", "x", "General subdivision (R)", "y", "Chronological subdivision (R)", "z", "Geographic subdivision (R)", "0", "Authority record control number (R)", "2", "Source of heading or term (NR)", "3", "Materials specified (NR)", "4", "Relator code (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "710", new String[] { "a", "Corporate name or jurisdiction name as entry element (NR)", "b", "Subordinate unit (R)", "c", "Location of meeting (NR)", "d", "Date of meeting or treaty signing (R)", "e", "Relator term (R)", "f", "Date of a work (NR)", "g", "Miscellaneous information (NR)", "h", "Medium (NR)", "i", "Relationship information (R)", "k", "Form subheading (R)", "l", "Language of a work (NR)", "m", "Medium of performance for music (R)", "n", "Number of part/section/meeting (R)", "o", "Arranged statement for music (NR)", "p", "Name of part/section of a work (R)", "r", "Key for music (NR)", "s", "Version (NR)", "t", "Title of a work (NR)", "u", "Affiliation (NR)", "v", "Form subdivision (R)", "x", "General subdivision (R)", "y", "Chronological subdivision (R)", "z", "Geographic subdivision (R)", "0", "Authority record control number (R)", "2", "Source of heading or term (NR)", "3", "Materials specified (NR)", "4", "Relator code (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "711", new String[] { "a", "Meeting name or jurisdiction name as entry element (NR)", "c", "Location of meeting (NR)", "d", "Date of meeting (R)", "e", "Subordinate unit (R)", "f", "Date of a work (NR)", "g", "Miscellaneous information (NR)", "h", "Medium (NR)", "i", "Relationship information (R)", "j", "Relator term (R)", "k", "Form subheading (R)", "l", "Language of a work (NR)", "n", "Number of part/section/meeting (R)", "p", "Name of part/section of a work (R)", "q", "Name of meeting following jurisdiction name entry element (NR)", "s", "Version (NR)", "t", "Title of a work (NR)", "u", "Affiliation (NR)", "x", "International Standard Serial Number (NR)", "0", "Authority record control number (R)", "3", "Materials specified (NR)", "4", "Relator code (R)", "5", "Institution to which field applies (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "720", new String[] { "a", "Name (NR)", "e", "Relator term (R)", "4", "Relator code (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "730", new String[] { "a", "Uniform title (NR)", "d", "Date of treaty signing (R)", "f", "Date of a work (NR)", "g", "Miscellaneous information (NR)", "h", "Medium (NR)", "i", "Relationship information (R)", "k", "Form subheading (R)", "l", "Language of a work (NR)", "m", "Medium of performance for music (R)", "n", "Number of part/section/meeting (R)", "o", "Arranged statement for music (NR)", "p", "Name of part/section of a work (R)", "r", "Key for music (NR)", "s", "Version (NR)", "t", "Title of a work (NR)", "x", "International Standard Serial Number (NR)", "0", "Authority record control number (R)", "3", "Materials specified (NR)", "5", "Institution to which field applies (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "740", new String[] { "a", "Uncontrolled related/analytical title (NR)", "h", "Medium (NR)", "n", "Number of part/section/meeting (R)", "p", "Name of part/section of a work (R)", "5", "Institution to which field applies (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "751", new String[] { "a", "Geographic name (NR)", "e", "Relator term (R)", "0", "Authority record control number (R)", "2", "Source of heading or term (NR)", "3", "Materials specified (NR)", "4", "Relator code (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "752", new String[] { "a", "Country or larger entity (R) ", "b", "First-order political jurisdiction (NR)", "c", "Intermediate political jurisdiction (R)", "d", "City (NR)", "f", "City subsection (R)", "g", "Other nonjurisdictional geographic region and feature (R)", "h", "Extraterrestrial area (R)", "0", "Authority record control number (R)", "2", "Source of heading or term (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "753", new String[] { "a", "Make and model of machine (NR)", "b", "Programming language (NR)", "c", "Operating system (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "754", new String[] { "a", "Taxonomic name (R)", "c", "Taxonomic category (R)", "d", "Common or alternative name (R)", "x", "Non-public note (R)", "z", "Public note (R)", "0", "Authority record control number (R)", "2", "Source of taxonomic identification (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "760", new String[] { "a", "Main entry heading (NR)", "b", "Edition (NR)", "c", "Qualifying information (NR)", "d", "Place, publisher, and date of publication (NR)", "g", "Related parts (R)", "h", "Physical description (NR)", "i", "Relationship information (R)", "m", "Material-specific details (NR)", "n", "Note (R)", "o", "Other item identifier (R)", "s", "Uniform title (NR)", "t", "Title (NR)", "w", "Record control number (R)", "x", "International Standard Serial Number (NR)", "y", "CODEN designation (NR)", "4", "Relationship code (R)", "6", "Linkage (NR)", "7", "Control subfield (NR)", "8", "Field link and sequence number (R)" }, "762", new String[] { "a", "Main entry heading (NR)", "b", "Edition (NR)", "c", "Qualifying information (NR)", "d", "Place, publisher, and date of publication (NR)", "g", "Related parts (R)", "h", "Physical description (NR)", "i", "Relationship information (R)", "m", "Material-specific details (NR)", "n", "Note (R)", "o", "Other item identifier (R)", "s", "Uniform title (NR)", "t", "Title (NR)", "w", "Record control number (R)", "x", "International Standard Serial Number (NR)", "y", "CODEN designation (NR)", "4", "Relationship code (R)", "6", "Linkage (NR)", "7", "Control subfield (NR)", "8", "Field link and sequence number (R)" }, "765", new String[] { "a", "Main entry heading (NR)", "b", "Edition (NR)", "c", "Qualifying information (NR)", "d", "Place, publisher, and date of publication (NR)", "g", "Related parts (R)", "h", "Physical description (NR)", "i", "Relationship information (R)", "k", "Series data for related item (R)", "m", "Material-specific details (NR)", "n", "Note (R)", "o", "Other item identifier (R)", "r", "Report number (R)", "s", "Uniform title (NR)", "t", "Title (NR)", "u", "Standard Technical Report Number (NR)", "w", "Record control number (R)", "x", "International Standard Serial Number (NR)", "y", "CODEN designation (NR)", "z", "International Standard Book Number (R)", "4", "Relationship code (R)", "6", "Linkage (NR)", "7", "Control subfield (NR)", "8", "Field link and sequence number (R)" }, "767", new String[] { "a", "Main entry heading (NR)", "b", "Edition (NR)", "c", "Qualifying information (NR)", "d", "Place, publisher, and date of publication (NR)", "g", "Related parts (R)", "h", "Physical description (NR)", "i", "Relationship information (R)", "k", "Series data for related item (R)", "m", "Material-specific details (NR)", "n", "Note (R)", "o", "Other item identifier (R)", "r", "Report number (R)", "s", "Uniform title (NR)", "t", "Title (NR)", "u", "Standard Technical Report Number (NR)", "w", "Record control number (R)", "x", "International Standard Serial Number (NR)", "y", "CODEN designation (NR)", "z", "International Standard Book Number (R)", "4", "Relationship code (R)", "6", "Linkage (NR)", "7", "Control subfield (NR)", "8", "Field link and sequence number (R)" }, "770", new String[] { "a", "Main entry heading (NR)", "b", "Edition (NR)", "c", "Qualifying information (NR)", "d", "Place, publisher, and date of publication (NR)", "g", "Related parts (R)", "h", "Physical description (NR)", "i", "Relationship information (R)", "k", "Series data for related item (R)", "m", "Material-specific details (NR)", "n", "Note (R)", "o", "Other item identifier (R)", "r", "Report number (R)", "s", "Uniform title (NR)", "t", "Title (NR)", "u", "Standard Technical Report Number (NR)", "w", "Record control number (R)", "x", "International Standard Serial Number (NR)", "y", "CODEN designation (NR)", "z", "International Standard Book Number (R)", "4", "Relationship code (R)", "6", "Linkage (NR)", "7", "Control subfield (NR)", "8", "Field link and sequence number (R)" }, "772", new String[] { "a", "Main entry heading (NR)", "b", "Edition (NR)", "c", "Qualifying information (NR)", "d", "Place, publisher, and date of publication (NR)", "g", "Related parts (R)", "h", "Physical description (NR)", "i", "Relationship information (R)", "k", "Series data for related item (R)", "m", "Material-specific details (NR)", "n", "Note (R)", "o", "Other item identifier (R)", "r", "Report number (R)", "s", "Uniform title (NR)", "t", "Title (NR)", "u", "Standard Technical Report Number (NR)", "w", "Record control number (R)", "x", "International Standard Serial Number (NR)", "y", "CODEN designation (NR)", "z", "International Standard Book Number (R)", "4", "Relationship code (R)", "6", "Linkage (NR)", "7", "Control subfield (NR)", "8", "Field link and sequence number (R)" }, "773", new String[] { "a", "Main entry heading (NR)", "b", "Edition (NR)", "d", "Place, publisher, and date of publication (NR)", "g", "Related parts (R)", "h", "Physical description (NR)", "i", "Relationship information (R)", "k", "Series data for related item (R)", "m", "Material-specific details (NR)", "n", "Note (R)", "o", "Other item identifier (R)", "p", "Abbreviated title (NR)", "q", "Enumeration and first page (NR)", "r", "Report number (R)", "s", "Uniform title (NR)", "t", "Title (NR)", "u", "Standard Technical Report Number (NR)", "w", "Record control number (R)", "x", "International Standard Serial Number (NR)", "y", "CODEN designation (NR)", "z", "International Standard Book Number (R)", "3", "Materials specified (NR)", "4", "Relationship code (R)", "6", "Linkage (NR)", "7", "Control subfield (NR)", "8", "Field link and sequence number (R)" }, "774", new String[] { "a", "Main entry heading (NR)", "b", "Edition (NR)", "c", "Qualifying information (NR)", "d", "Place, publisher, and date of publication (NR)", "g", "Related parts (R)", "h", "Physical description (NR)", "i", "Relationship information (R)", "k", "Series data for related item (R)", "m", "Material-specific details (NR)", "n", "Note (R)", "o", "Other item identifier (R)", "r", "Report number (R)", "s", "Uniform title (NR)", "t", "Title (NR)", "u", "Standard Technical Report Number (NR)", "w", "Record control number (R)", "x", "International Standard Serial Number (NR)", "y", "CODEN designation (NR)", "z", "International Standard Book Number (R)", "4", "Relationship code (R)", "6", "Linkage (NR)", "7", "Control subfield (NR)", "8", "Field link and sequence number (R)" }, "775", new String[] { "a", "Main entry heading (NR)", "b", "Edition (NR)", "c", "Qualifying information (NR)", "d", "Place, publisher, and date of publication (NR)", "e", "Language code (NR)", "f", "Country code (NR)", "g", "Related parts (R)", "h", "Physical description (NR)", "i", "Relationship information (R)", "k", "Series data for related item (R)", "m", "Material-specific details (NR)", "n", "Note (R)", "o", "Other item identifier (R)", "r", "Report number (R)", "s", "Uniform title (NR)", "t", "Title (NR)", "u", "Standard Technical Report Number (NR)", "w", "Record control number (R)", "x", "International Standard Serial Number (NR)", "y", "CODEN designation (NR)", "z", "International Standard Book Number (R)", "4", "Relationship code (R)", "6", "Linkage (NR)", "7", "Control subfield (NR)", "8", "Field link and sequence number (R)" }, "776", new String[] { "a", "Main entry heading (NR)", "b", "Edition (NR)", "c", "Qualifying information (NR)", "d", "Place, publisher, and date of publication (NR)", "g", "Related parts (R)", "h", "Physical description (NR)", "i", "Relationship information (R)", "k", "Series data for related item (R)", "m", "Material-specific details (NR)", "n", "Note (R)", "o", "Other item identifier (R)", "r", "Report number (R)", "s", "Uniform title (NR)", "t", "Title (NR)", "u", "Standard Technical Report Number (NR)", "w", "Record control number (R)", "x", "International Standard Serial Number (NR)", "y", "CODEN designation (NR)", "z", "International Standard Book Number (R)", "4", "Relationship code (R)", "6", "Linkage (NR)", "7", "Control subfield (NR)", "8", "Field link and sequence number (R)" }, "777", new String[] { "a", "Main entry heading (NR)", "b", "Edition (NR)", "c", "Qualifying information (NR)", "d", "Place, publisher, and date of publication (NR)", "g", "Related parts (R)", "h", "Physical description (NR)", "i", "Relationship information (R)", "k", "Series data for related item (R)", "m", "Material-specific details (NR)", "n", "Note (R)", "o", "Other item identifier (R)", "s", "Uniform title (NR)", "t", "Title (NR)", "w", "Record control number (R)", "x", "International Standard Serial Number (NR)", "y", "CODEN designation (NR)", "4", "Relationship code (R)", "6", "Linkage (NR)", "7", "Control subfield (NR)", "8", "Field link and sequence number (R)" }, "780", new String[] { "a", "Main entry heading (NR)", "b", "Edition (NR)", "c", "Qualifying information (NR)", "d", "Place, publisher, and date of publication (NR)", "g", "Related parts (R)", "h", "Physical description (NR)", "i", "Relationship information (R)", "k", "Series data for related item (R)", "m", "Material-specific details (NR)", "n", "Note (R)", "o", "Other item identifier (R)", "r", "Report number (R)", "s", "Uniform title (NR)", "t", "Title (NR)", "u", "Standard Technical Report Number (NR)", "w", "Record control number (R)", "x", "International Standard Serial Number (NR)", "y", "CODEN designation (NR)", "z", "International Standard Book Number (R)", "4", "Relationship code (R)", "6", "Linkage (NR)", "7", "Control subfield (NR)", "8", "Field link and sequence number (R)" }, "785", new String[] { "a", "Main entry heading (NR)", "b", "Edition (NR)", "c", "Qualifying information (NR)", "d", "Place, publisher, and date of publication (NR)", "g", "Related parts (R)", "h", "Physical description (NR)", "i", "Relationship information (R)", "k", "Series data for related item (R)", "m", "Material-specific details (NR)", "n", "Note (R)", "o", "Other item identifier (R)", "r", "Report number (R)", "s", "Uniform title (NR)", "t", "Title (NR)", "u", "Standard Technical Report Number (NR)", "w", "Record control number (R)", "x", "International Standard Serial Number (NR)", "y", "CODEN designation (NR)", "z", "International Standard Book Number (R)", "4", "Relationship code (R)", "6", "Linkage (NR)", "7", "Control subfield (NR)", "8", "Field link and sequence number (R)" }, "786", new String[] { "a", "Main entry heading (NR)", "b", "Edition (NR)", "c", "Qualifying information (NR)", "d", "Place, publisher, and date of publication (NR)", "g", "Related parts (R)", "h", "Physical description (NR)", "i", "Relationship information (R)", "k", "Series data for related item (R)", "m", "Material-specific details (NR)", "n", "Note (R)", "o", "Other item identifier (R)", "p", "Abbreviated title (NR)", "r", "Report number (R)", "s", "Uniform title (NR)", "t", "Title (NR)", "u", "Standard Technical Report Number (NR)", "w", "Record control number (R)", "v", "Source Contribution (NR)", "x", "International Standard Serial Number (NR)", "y", "CODEN designation (NR)", "z", "International Standard Book Number (R)", "4", "Relationship code (R)", "6", "Linkage (NR)", "7", "Control subfield (NR)", "8", "Field link and sequence number (R)" }, "787", new String[] { "a", "Main entry heading (NR)", "b", "Edition (NR)", "c", "Qualifying information (NR)", "d", "Place, publisher, and date of publication (NR)", "g", "Related parts (R)", "h", "Physical description (NR)", "i", "Relationship information (R)", "k", "Series data for related item (R)", "m", "Material-specific details (NR)", "n", "Note (R)", "o", "Other item identifier (R)", "r", "Report number (R)", "s", "Uniform title (NR)", "t", "Title (NR)", "u", "Standard Technical Report Number (NR)", "w", "Record control number (R)", "x", "International Standard Serial Number (NR)", "y", "CODEN designation (NR)", "z", "International Standard Book Number (R)", "4", "Relationship code (R)", "6", "Linkage (NR)", "7", "Control subfield (NR)", "8", "Field link and sequence number (R)" }, "800", new String[] { "a", "Personal name (NR)", "b", "Numeration (NR)", "c", "Titles and other words associated with a name (R)", "d", "Dates associated with a name (NR)", "e", "Relator term (R)", "f", "Date of a work (NR)", "g", "Miscellaneous information (NR)", "h", "Medium (NR)", "j", "Attribution qualifier (R)", "k", "Form subheading (R)", "l", "Language of a work (NR)", "m", "Medium of performance for music (R)", "n", "Number of part/section of a work (R)", "o", "Arranged statement for music (NR)", "p", "Name of part/section of a work (R)", "q", "Fuller form of name (NR)", "r", "Key for music (NR)", "s", "Version (NR)", "t", "Title of a work (NR)", "u", "Affiliation (NR)", "v", "Volume/sequential designation (NR)", "w", "Bibliographic record control number (R)", "x", "International Standard Serial Number (NR)", "0", "Authority record control number (R)", "3", "Materials specified (NR)", "4", "Relator code (R)", "5", "Institution to which field applies (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "810", new String[] { "a", "Corporate name or jurisdiction name as entry element (NR)", "b", "Subordinate unit (R)", "c", "Location of meeting (NR)", "d", "Date of meeting or treaty signing (R)", "e", "Relator term (R)", "f", "Date of a work (NR)", "g", "Miscellaneous information (NR)", "h", "Medium (NR)", "k", "Form subheading (R)", "l", "Language of a work (NR)", "m", "Medium of performance for music (R)", "n", "Number of part/section/meeting (R)", "o", "Arranged statement for music (NR)", "p", "Name of part/section of a work (R)", "r", "Key for music (NR)", "s", "Version (NR)", "t", "Title of a work (NR)", "u", "Affiliation (NR)", "v", "Volume/sequential designation (NR)", "w", "Bibliographic record control number (R)", "x", "International Standard Serial Number (NR)", "0", "Authority record control number (R)", "3", "Materials specified (NR)", "4", "Relator code (R)", "5", "Institution to which field applies (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "811", new String[] { "a", "Meeting name or jurisdiction name as entry element (NR)", "c", "Location of meeting (NR)", "d", "Date of meeting (NR)", "e", "Subordinate unit (R)", "f", "Date of a work (NR)", "g", "Miscellaneous information (NR)", "h", "Medium (NR)", "j", "Relator term (R)", "k", "Form subheading (R)", "l", "Language of a work (NR)", "n", "Number of part/section/meeting (R)", "p", "Name of part/section of a work (R)", "q", "Name of meeting following jurisdiction name entry element (NR)", "s", "Version (NR)", "t", "Title of a work (NR)", "u", "Affiliation (NR)", "v", "Volume/sequential designation (NR)", "w", "Bibliographic record control number (R)", "x", "International Standard Serial Number (NR)", "0", "Authority record control number (R)", "3", "Materials specified (NR)", "4", "Relator code (R)", "5", "Institution to which field applies (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "830", new String[] { "a", "Uniform title (NR)", "d", "Date of treaty signing (R)", "f", "Date of a work (NR)", "g", "Miscellaneous information (NR)", "h", "Medium (NR)", "k", "Form subheading (R)", "l", "Language of a work (NR)", "m", "Medium of performance for music (R)", "n", "Number of part/section/meeting (R)", "o", "Arranged statement for music (NR)", "p", "Name of part/section of a work (R)", "q", "Name of meeting following jurisdiction name entry element (NR)", "r", "Key for music (NR)", "s", "Version (NR)", "t", "Title of a work (NR)", "v", "Volume/sequential designation (NR)", "w", "Bibliographic record control number (R)", "x", "International Standard Serial Number (NR)", "0", "Authority record control number (R)", "3", "Materials specified (NR)", "5", "Institution to which field applies (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "850", new String[] { "a", "Holding institution (R)", "8", "Field link and sequence number (R)" }, "852", new String[] { "a", "Location (NR)", "b", "Sublocation or collection (R)", "c", "Shelving location (R)", "d", "Former shelving location (R)", "e", "Address (R)", "f", "Coded location qualifier (R)", "g", "Non-coded location qualifier (R)", "h", "Classification part (NR)", "i", "Item part (R)", "j", "Shelving control number (NR)", "k", "Call number prefix (R)", "l", "Shelving form of title (NR)", "m", "Call number suffix (R)", "n", "Country code (NR)", "p", "Piece designation (NR)", "q", "Piece physical condition (NR)", "s", "Copyright article-fee code (R)", "t", "Copy number (NR)", "u", "Uniform Resource Identifier (R)", "x", "Nonpublic note (R)", "z", "Public note (R)", "2", "Source of classification or shelving scheme (NR)", "3", "Materials specified (NR)", "6", "Linkage (NR)", "8", "Sequence number (NR)" }, "856", new String[] { "a", "Host name (R)", "b", "Access number (R)", "c", "Compression information (R)", "d", "Path (R)", "f", "Electronic name (R)", "h", "Processor of request (NR)", "i", "Instruction (R)", "j", "Bits per second (NR)", "k", "Password (NR)", "l", "Logon (NR)", "m", "Contact for access assistance (R)", "n", "Name of location of host (NR)", "o", "Operating system (NR)", "p", "Port (NR)", "q", "Electronic format type (NR)", "r", "Settings (NR)", "s", "File size (R)", "t", "Terminal emulation (R)", "u", "Uniform Resource Identifier (R)", "v", "Hours access method available (R)", "w", "Record control number (R)", "x", "Nonpublic note (R)", "y", "Link text (R)", "z", "Public note (R)", "2", "Access method (NR)", "3", "Materials specified (NR)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, // 880 MISSING! "882", new String[] { "a", "Replacement title (R)", "i", "Explanatory text (R)", "w", "Replacement bibliographic record control number (R)", "6", "Linkage (NR)", "8", "Field link and sequence number (R)" }, "886", new String[] { "a", "Tag of the foreign MARC field (NR)", "b", "Content of the foreign MARC field (NR)", "2", "Source of data (NR)", }, "887", new String[] { "a", "Content of non-MARC field (NR)", "2", "Source of data (NR)", } }; private static HashMap<String,String> subfieldNameHash = null; public static String getSubfieldName(String field, String subfield) { if(subfieldNameHash == null) { subfieldNameHash = new HashMap<>(); for(int i=0; i<subfieldNames.length; i=i+2) { String[] subfields = (String[]) subfieldNames[i+1]; for(int j=0; j<subfields.length; j=j+2) { String hashKey = ((String) subfieldNames[i])+((String) subfields[j]); subfieldNameHash.put(hashKey, (String) subfields[j+1]); } } } if(subfieldNameHash.containsKey(field+subfield)) { return subfieldNameHash.get(field+subfield) + " ("+subfield+"@"+field+")"; } return subfield+"@"+field; } }
101,136
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MarcField.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/marcxml/MarcField.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * MarcField.java * * Created on 2010-06-30 * */ package org.wandora.application.tools.extractors.marcxml; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * * @author akivela */ public class MarcField { private String tag = null; private String ind1 = null; private String ind2 = null; private List<MarcSubfield> subfields = null; public MarcField(String tag, String ind1, String ind2) { this.tag = tag; this.ind1 = ind1; this.ind2 = ind2; subfields = new ArrayList<MarcSubfield>(); } public void addSubfield(String code, String value) { subfields.add(new MarcSubfield(code, value)); } public String getTag() { return tag; } public String getInd1() { return ind1; } public String getInd2() { return ind2; } public Collection<MarcSubfield> getSubfields() { return subfields; } // ------------------------------------------------------------------------- private static final String [] fieldNames = new String[] { "001", "001 - Control Number (NR)", "003", "003 - Control Number Identifier (NR)", "005", "005 - Date and Time of Latest Transaction (NR)", "006", "006 - Fixed-Length Data Elements-Additional Material Characteristics", "007", "007 - Physical Description Fixed Field-General Information (R)", "008", "008 - Fixed-Length Data Elements-General Information (NR)", "010", "010 - Library of Congress Control Number (NR)", "013", "013 - Patent Control Information (R)", "015", "015 - National Bibliography Number (R)", "016", "016 - National Bibliographic Agency Control Number (R)", "017", "017 - Copyright or Legal Deposit Number (R)", "018", "018 - Copyright Article-Fee Code (NR)", "020", "020 - International Standard Book Number (R)", "022", "022 - International Standard Serial Number (R)", "024", "024 - Other Standard Identifier (R)", "025", "025 - Overseas Acquisition Number (R)", "026", "026 - Fingerprint Identifier (R)", "027", "027 - Standard Technical Report Number (R)", "028", "028 - Publisher Number (R)", "030", "030 - CODEN Designation (R)", "031", "031 - Musical Incipits Information (R)", "032", "032 - Postal Registration Number (R)", "033", "033 - Date/Time and Place of an Event (R)", "034", "034 - Coded Cartographic Mathematical Data (R)", "035", "035 - System Control Number (R)", "036", "036 - Original Study Number for Computer Data Files (NR)", "037", "037 - Source of Acquisition (R)", "038", "038 - Record Content Licensor (NR)", "040", "040 - Cataloging Source (NR)", "041", "041 - Language Code (R)", "042", "042 - Authentication Code (NR)", "043", "043 - Geographic Area Code (NR)", "044", "044 - Country of Publishing/Producing Entity Code (NR)", "045", "045 - Time Period of Content (NR)", "046", "046 - Special Coded Dates (R)", "047", "047 - Form of Musical Composition Code (R)", "048", "048 - Number of Musical Instruments or Voices Code (R)", "050", "050 - Library of Congress Call Number (R)", "051", "051 - Library of Congress Copy, Issue, Offprint Statement (R)", "052", "052 - Geographic Classification (R)", "055", "055 - Classification Numbers Assigned in Canada (R)", "060", "060 - National Library of Medicine Call Number (R)", "061", "061 - National Library of Medicine Copy Statement (R)", "066", "066 - Character Sets Present (NR)", "070", "070 - National Agricultural Library Call Number (R)", "071", "071 - National Agricultural Library Copy Statement (R)", "072", "072 - Subject Category Code (R)", "074", "074 - GPO Item Number (R)", "080", "080 - Universal Decimal Classification Number (R)", "082", "082 - Dewey Decimal Classification Number (R)", "083", "083 - Additional Dewey Decimal Classification Number (R)", "084", "084 - Other Classification Number (R)", "085", "085 - Synthesized Classification Number Components (R)", "086", "086 - Government Document Classification Number (R)", "088", "088 - Report Number (R)", "100", "100 - Main Entry-Personal Name (NR)", "110", "110 - Main Entry-Corporate Name (NR)", "111", "111 - Main Entry-Meeting Name (NR)", "130", "130 - Main Entry-Uniform Title (NR)", "210", "210 - Abbreviated Title (R)", "222", "222 - Key Title (R)", "245", "245 - Title Statement (NR)", "246", "246 - Varying Form of Title (R)", "247", "247 - Former Title (R)", "250", "250 - Edition Statement (NR)", "254", "254 - Musical Presentation Statement (NR)", "255", "255 - Cartographic Mathematical Data (R)", "256", "256 - Computer File Characteristics (NR)", "257", "257 - Country of Producing Entity (R)", "258", "258 - Philatelic Issue Data (R)", "260", "260 - Publication, Distribution, etc. (Imprint) (R)", "261", "261 - Imprint Statement for Films (Pre-AACR 1 Revised) (NR)", "262", "262 - Imprint Statement for Sound Recordings (Pre-AACR 1) (NR)", "263", "263 - Projected Publication Date (NR)", "270", "270 - Address (R)", "300", "300 - Physical Description (R)", "306", "306 - Playing Time (NR)", "307", "307 - Hours, Etc. (R)", "310", "310 - Current Publication Frequency (NR)", "321", "321 - Former Publication Frequency (R)", "336", "336 - Content Type (R)", "337", "337 - Media Type (R)", "338", "338 - Carrier Type (R)", "340", "340 - Physical Medium (R)", "342", "342 - Geospatial Reference Data (R)", "343", "343 - Planar Coordinate Data (R)", "351", "351 - Organization and Arrangement of Materials (R)", "352", "352 - Digital Graphic Representation (R)", "355", "355 - Security Classification Control (R)", "357", "357 - Originator Dissemination Control (NR)", "362", "362 - Dates of Publication and/or Sequential Designation (R)", "363", "363 - Normalized Date and Sequential Designation (R)", "365", "365 - Trade Price (R)", "366", "366 - Trade Availability Information (R)", "380", "380 - Form of Work (R)", "381", "381 - Other Distinguishing Characteristics of Work or Expression (R)", "382", "382 - Medium of Performance (R)", "383", "383 - Numeric Designation of Musical Work (R)", "384", "384 - Key (NR)", "400", "400 - Series Statement/Added Entry-Personal Name (R)", "410", "410 - Series Statement/Added Entry-Corporate Name (R)", "440", "440 - Series Statement/Added Entry-Title (R)", "490", "490 - Series Statement (R)", "500", "500 - General Note (R)", "501", "501 - With Note (R)", "502", "502 - Dissertation Note (R)", "504", "504 - Bibliography, Etc. Note (R)", "505", "505 - Formatted Contents Note (R)", "506", "506 - Restrictions on Access Note (R)", "507", "507 - Scale Note for Graphic Material (NR)", "508", "508 - Creation/Production Credits Note (R)", "510", "510 - Citation/References Note (R)", "511", "511 - Participant or Performer Note (R)", "513", "513 - Type of Report and Period Covered Note (R)", "514", "514 - Data Quality Note (NR)", "515", "515 - Numbering Peculiarities Note (R)", "516", "516 - Type of Computer File or Data Note (R)", "518", "518 - Date/Time and Place of an Event Note (R)", "520", "520 - Summary, Etc. (R)", "521", "521 - Target Audience Note (R)", "522", "522 - Geographic Coverage Note (R)", "524", "524 - Preferred Citation of Described Materials Note (R)", "525", "525 - Supplement Note (R)", "526", "526 - Study Program Information Note (R)", "530", "530 - Additional Physical Form Available Note (R)", "533", "533 - Reproduction Note (R)", "534", "534 - Original Version Note (R)", "535", "535 - Location of Originals/Duplicates Note (R)", "536", "536 - Funding Information Note (R)", "538", "538 - System Details Note (R)", "540", "540 - Terms Governing Use and Reproduction Note (R)", "541", "541 - Immediate Source of Acquisition Note (R)", "542", "542 - Information Relating to Copyright Status (R)", "544", "544 - Location of Other Archival Materials Note (R)", "545", "545 - Biographical or Historical Data (R)", "546", "546 - Language Note (R)", "547", "547 - Former Title Complexity Note (R)", "550", "550 - Issuing Body Note (R)", "552", "552 - Entity and Attribute Information Note (R)", "555", "555 - Cumulative Index/Finding Aids Note (R)", "556", "556 - Information About Documentation Note (R)", "561", "561 - Ownership and Custodial History (R)", "562", "562 - Copy and Version Identification Note (R)", "563", "563 - Binding Information (R)", "565", "565 - Case File Characteristics Note (R)", "567", "567 - Methodology Note (R)", "580", "580 - Linking Entry Complexity Note (R)", "581", "581 - Publications About Described Materials Note (R)", "583", "583 - Action Note (R)", "584", "584 - Accumulation and Frequency of Use Note (R)", "600", "600 - Subject Added Entry-Personal Name (R)", "610", "610 - Subject Added Entry-Corporate Name (R)", "611", "611 - Subject Added Entry-Meeting Name (R)", "630", "630 - Subject Added Entry-Uniform Title (R)", "648", "648 - Subject Added Entry-Chronological Term (R)", "650", "650 - Subject Added Entry-Topical Term (R)", "651", "651 - Subject Added Entry-Geographic Name (R)", "653", "653 - Index Term-Uncontrolled (R)", "654", "654 - Subject Added Entry-Faceted Topical Terms (R)", "655", "655 - Index Term-Genre/Form (R)", "656", "656 - Index Term-Occupation (R)", "657", "657 - Index Term-Function (R)", "658", "658 - Index Term-Curriculum Objective (R)", "662", "662 - Subject Added Entry-Hierarchical Place Name (R)", "700", "700 - Added Entry-Personal Name (R)", "710", "710 - Added Entry-Corporate Name (R)", "711", "711 - Added Entry-Meeting Name (R)", "720", "720 - Added Entry-Uncontrolled Name (R)", "730", "730 - Added Entry-Uniform Title (R)", "740", "740 - Added Entry-Uncontrolled Related/Analytical Title (R)", "751", "751 - Added Entry-Geographic Name (R)", "752", "752 - Added Entry-Hierarchical Place Name (R)", "753", "753 - System Details Access to Computer Files (R)", "754", "754 - Added Entry-Taxonomic Identification (R)", "760", "760 - Main Series Entry (R)", "762", "762 - Subseries Entry (R)", "765", "765 - Original Language Entry (R)", "767", "767 - Translation Entry (R)", "770", "770 - Supplement/Special Issue Entry (R)", "772", "772 - Supplement Parent Entry (R)", "773", "773 - Host Item Entry (R)", "774", "774 - Constituent Unit Entry (R)", "775", "775 - Other Edition Entry (R)", "776", "776 - Additional Physical Form Entry (R)", "777", "777 - Issued With Entry (R)", "780", "780 - Preceding Entry (R)", "785", "785 - Succeeding Entry (R)", "786", "786 - Data Source Entry (R)", "787", "787 - Other Relationship Entry (R)", "800", "800 - Series Added Entry-Personal Name (R)", "810", "810 - Series Added Entry-Corporate Name (R)", "811", "811 - Series Added Entry-Meeting Name (R)", "830", "830 - Series Added Entry-Uniform Title (R)", "850", "850 - Holding Institution (R)", "852", "852 - Location (R)", "856", "856 - Electronic Location and Access (R)", "880", "880 - Alternate Graphic Representation (R)", "882", "882 - Replacement Record Information (NR)", "886", "886 - Foreign MARC Information Field (R)", "887", "887 - Non-MARC Information Field (R)", }; private static Map<String,String> fieldNameHash = null; public static String getFieldName(String field) { if(fieldNameHash == null) { fieldNameHash = new LinkedHashMap<String,String>(); for(int i=0; i<fieldNames.length; i=i+2) { fieldNameHash.put(fieldNames[i], fieldNames[i+1]); } } if(fieldNameHash.containsKey(field)) { return fieldNameHash.get(field); } return field; } private static Object[] fieldIndicatorNames = new Object[] { "016", "National bibliographic agency", new String[] { // First "7", "Source specified in subfield $2", }, "Undefined", new String[] { // Second }, "017", "Undefined", new String[] { // First }, "Display constant controller", new String[] { // Second "8", "No display constant generated", }, "022", "Level of international interest", new String[] { // First "0", "Continuing resource of international interest", "1", "Continuing resource not of international interest" }, "Undefined", new String[] { // Second }, "024", "Type of standard number or code", new String[] { // First "0", "International Standard Recording Code", "1", "Universal Product Code", "2", "International Standard Music Number", "3", "International Article Number", "4", "Serial Item and Contribution Identifier", "7", "Source specified in subfield $2", "8", "Unspecified type of standard number or code" }, "Difference indicator", new String[] { // Second "0", "No difference", "1", "Difference" }, "028", "Type of publisher number", new String[] { // First "0", "Issue number", "1", "Matrix number", "2", "Plate number", "3", "Other music number", "4", "Videorecording number", "5", "Other publisher number", }, "Note/added entry controller", new String[] { // Second "0", "No note, no added entry", "1", "Note, added entry", "2", "Note, no added entry", "3", "No note, added entry" }, "033", "Type of date in subfield $a", new String[] { // First "0", "Single date", "1", "Multiple single dates", "2", "Range of dates", }, "Type of event", new String[] { // Second "0", "Capture", "1", "Broadcast", "2", "Finding", }, "034", "Type of scale", new String[] { // First "0", "Scale indeterminable/No scale recorded", "1", "Single scale", "3", "Range of scales", }, "Type of ring", new String[] { // Second "0", "Outer ring", "1", "Exclusion ring", }, "041", "Translation indication", new String[] { // First "0", "Item not a translation/does not include a translation", "1", "Item is or includes a translation", }, "Source of code", new String[] { // Second "7", "Source specified in subfield $2", }, "045", "Type of time period in subfield $b or $c", new String[] { // First "0", "Single date/time", "1", "Multiple single dates/times", "2", "Range of dates/times" }, "Undefined", new String[] { // Second }, "047", "Undefined", new String[] { // First }, "Source of code", new String[] { // Second "7", "Source specified in subfield $2" }, "048", "Undefined", new String[] { // First }, "Source of code", new String[] { // Second "7", "Source specified in subfield $2" }, "050", "Existence in LC collection", new String[] { // First "0", "Item is in LC", "1", "Item is not in LC" }, "Source of call number", new String[] { // Second "0", "Assigned by LC", "4", "Assigned by agency other than LC" }, "052", "Code source", new String[] { // First "1", "U.S. Dept. of Defense Classification", "7", "Source specified in subfield $2" }, "Undefined", new String[] { // Second }, "055", "Existence in LAC collection", new String[] { // First "0", "Work held by LAC", "1", "Work not held by LAC" }, "Type, completeness, source of class/call number", new String[] { // Second "0", "LC-based call number assigned by LAC", "1", "Complete LC class number assigned by LAC", "2", "Incomplete LC class number assigned by LAC", "3", "LC-based call number assigned by the contributing library", "4", "Complete LC class number assigned by the contributing library", "5", "Incomplete LC class number assigned by the contributing library", "6", "Other call number assigned by LAC", "7", "Other class number assigned by LAC", "8", "Other call number assigned by the contributing library", "9", "Other class number assigned by the contributing library" }, "060", "Existence in NLM collection", new String[] { // First "0", "Item is in NLM", "1", "Item is not in NLM" }, "Source of call number", new String[] { // Second "0", "Assigned by NLM", "4", "Assigned by agency other than NLM" }, "070", "Existence in NAL collection", new String[] { // First "0", "Item is in NAL", "1", "Item is not in NAL" }, "Undefined", new String[] { // Second }, "072", "Undefined", new String[] { // First }, "Code source", new String[] { // Second "0", "NAL subject category code list", "7", "Source specified in subfield $2" }, "080", "Type of edition", new String[] { // First "0", "Full", "1", "Abridged" }, "Undefined", new String[] { // Second }, "082", "Type of edition", new String[] { // First "0", "Full edition", "1", "Abridged edition" }, "Source of classification number", new String[] { // Second "0", "Assigned by LC", "4", "Assigned by agency other than LC" }, "083", "Type of edition", new String[] { // First "0", "Full edition", "1", "Abridged edition" }, "Undefined", new String[] { // Second }, "086", "Number source", new String[] { // First "0", "Superintendent of Documents Classification System", "1", "Government of Canada Publications: Outline of Classification" }, "Undefined", new String[] { // Second }, "100", "Type of personal name entry element", new String[] { // First "0", "Forename", "1", "Surname", "3", "Family name" }, "Undefined", new String[] { // Second }, "110", "Type of corporate name entry element", new String[] { // First "0", "Inverted name", "1", "Jurisdiction name", "3", "Name in direct order" }, "Undefined", new String[] { // Second }, "111", "Type of meeting name entry element", new String[] { // First "0", "Inverted name", "1", "Jurisdiction name", "3", "Name in direct order" }, "Undefined", new String[] { // Second }, "210", "Title added entry", new String[] { // First "0", "No added entry", "1", "Added entry", }, "Type", new String[] { // Second "0", "Other abbreviated title" }, "222", "Undefined", new String[] { // First }, "Nonfiling characters", new String[] { // Second "0", "No nonfiling characters", }, "240", "Uniform title printed or displayed", new String[] { // First "0", "Not printed or displayed", "1", "Printed or displayed" }, "Nonfiling characters", new String[] { // Second }, "242", "Title added entry", new String[] { // First "0", "No added entry", "1", "Added entry" }, "Nonfiling characters", new String[] { // Second "0", "No nonfiling characters" }, "243", "Uniform title printed or displayed", new String[] { // First "0", "Not printed or displayed", "1", "Printed or displayed" }, "Nonfiling characters", new String[] { // Second }, "245", "Title added entry", new String[] { // First "0", "No added entry", "1", "Added entry" }, "Nonfiling characters", new String[] { // Second "0", "No nonfiling characters" }, "246", "Note/added entry controller", new String[] { // First "0", "Note, no added entry", "1", "Note, added entry", "2", "No note, no added entry", "3", "No note, added entry" }, "Type of title", new String[] { // Second "0", "Portion of title", "1", "Parallel title", "2", "Distinctive title", "3", "Other title", "4", "Cover title", "5", "Added title page title", "6", "Caption title", "7", "Running title", "8", "Spine title" }, "247", "Title added entry", new String[] { // First "0", "No added entry", "1", "Added entry", }, "Note controller", new String[] { // Second "0", "Display note", "1", "Do not display note", }, "260", "Sequence of publishing statements", new String[] { // First "2", "Intervening publisher", "3", "Current/latest publisher", }, "Undefined", new String[] { // Second }, "270", "Level", new String[] { // First "1", "Primary", "3", "Secondary", }, "Type of address", new String[] { // Second "0", "Mailing", "7", "Type specified in subfield $i" }, "307", "Display constant controller", new String[] { // First "8", "No display constant generated", }, "Undefined", new String[] { // Second }, "342", "Geospatial reference dimension", new String[] { // First "0", "Horizontal coordinate system", "1", "Vertical coordinate system", }, "Geospatial reference method", new String[] { // Second "0", "Geographic", "1", "Map projection", "2", "Grid coordinate system", "3", "Local planar", "4", "Local", "5", "Geodetic model", "6", "Altitude", "7", "Method specified in $2", "8", "Depth" }, "355", "Controlled element", new String[] { // First "0", "Document", "1", "Title", "2", "Abstract", "3", "Contents note", "4", "Author", "5", "Record", "8", "None of the above" }, "Undefined", new String[] { // Second }, "362", "Format of date", new String[] { // First "0", "Formatted style", "1", "Unformatted note", }, "Undefined", new String[] { // Second }, "363", "Start/End designator", new String[] { // First "0", "Starting information", "1", "Ending information", }, "State of issuance", new String[] { // Second "0", "Closed", "1", "Open", }, "384", "Key type", new String[] { // First "0", "Original key", "1", "Transposed key", }, "Undefined", new String[] { // Second }, "490", "Series tracing policy", new String[] { // First "0", "Series not traced", "1", "Series traced", }, "Undefined", new String[] { // Second }, "505", "Display constant controller", new String[] { // First "0", "Contents", "1", "Incomplete contents", "2", "Partial contents", "8", "No display constant generated" }, "Level of content designation", new String[] { // Second "0", "Enhanced" }, "506", "Restriction", new String[] { // First "0", "No restrictions", "1", "Restrictions apply", }, "Undefined", new String[] { // Second }, "510", "Coverage/location in source", new String[] { // First "0", "Coverage unknown", "1", "Coverage complete", "2", "Coverage is selective", "3", "Location in source not given", "4", "Location in source given" }, "Undefined", new String[] { // Second }, "511", "Display constant controller", new String[] { // First "0", "No display constant generated", "1", "Cast", }, "Undefined", new String[] { // Second }, "516", "Display constant controller", new String[] { // First "8", "No display constant generated", }, "Undefined", new String[] { // Second }, "520", "Display constant controller", new String[] { // First "0", "Subject", "1", "Review", "2", "Scope and content", "3", "Abstract", "4", "Content advice", "8", "No display constant generated" }, "Undefined", new String[] { // Second }, "521", "Display constant controller", new String[] { // First "0", "Reading grade level", "1", "Interest age level", "2", "Interest grade level", "3", "Special audience characteristics", "4", "Motivation/interest level", "8", "No display constant generated" }, "Undefined", new String[] { // Second }, "522", "Display constant controller", new String[] { // First "8", "No display constant generated" }, "Undefined", new String[] { // Second }, "524", "Display constant controller", new String[] { // First "8", "No display constant generated" }, "Undefined", new String[] { // Second }, "526", "Display constant controller", new String[] { // First "0", "Reading program", "8", "No display constant generated" }, "Undefined", new String[] { // Second }, "535", "Display constant controller", new String[] { // First "1", "Holder of originals", "2", "Holder of duplicates" }, "Undefined", new String[] { // Second }, "541", "Privacy", new String[] { // First "0", "Private", "1", "Not private" }, "Undefined", new String[] { // Second }, "542", "Privacy", new String[] { // First "0", "Private", "1", "Not private" }, "Undefined", new String[] { // Second }, "544", "Relationship", new String[] { // First "0", "Associated materials", "1", "Related materials" }, "Undefined", new String[] { // Second }, "545", "Type of data", new String[] { // First "0", "Biographical sketch", "1", "Administrative history" }, "Undefined", new String[] { // Second }, "555", "Display constant controller", new String[] { // First "0", "Finding aids", "8", "No display constant generated" }, "Undefined", new String[] { // Second }, "556", "Display constant controller", new String[] { // First "8", "No display constant generated" }, "Undefined", new String[] { // Second }, "561", "Privacy", new String[] { // First "0", "Private", "1", "Not private" }, "Undefined", new String[] { // Second }, "565", "Display constant controller", new String[] { // First "0", "Case file characteristics", "8", "No display constant generated" }, "Undefined", new String[] { // Second }, "567", "Display constant controller", new String[] { // First "8", "No display constant generated" }, "Undefined", new String[] { // Second }, "581", "Display constant controller", new String[] { // First "8", "No display constant generated" }, "Undefined", new String[] { // Second }, "583", "Privacy", new String[] { // First "0", "Private", "1", "Not private" }, "Undefined", new String[] { // Second }, "586", "Display constant controller", new String[] { // First "8", "No display constant generated" }, "Undefined", new String[] { // Second }, "600", "Type of personal name entry element", new String[] { // First "0", "Forename", "1", "Surname", "3", "Family name" }, "Thesaurus", new String[] { // Second "0", "Library of Congress Subject Headings", "1", "LC subject headings for children's literature", "2", "Medical Subject Headings", "3", "National Agricultural Library subject authority file", "4", "Source not specified", "5", "Canadian Subject Headings", "6", "Répertoire de vedettes-matière", "7", "Source specified in subfield $2" }, "610", "Type of corporate name entry element", new String[] { // First "0", "Inverted name", "1", "Jurisdiction name", "2", "Name in direct order" }, "Thesaurus", new String[] { // Second "0", "Library of Congress Subject Headings", "1", "LC subject headings for children's literature", "2", "Medical Subject Headings", "3", "National Agricultural Library subject authority file", "4", "Source not specified", "5", "Canadian Subject Headings", "6", "Répertoire de vedettes-matière", "7", "Source specified in subfield $2" }, "611", "Type of meeting name entry element", new String[] { // First "0", "Inverted name", "1", "Jurisdiction name", "2", "Name in direct order" }, "Thesaurus", new String[] { // Second "0", "Library of Congress Subject Headings", "1", "LC subject headings for children's literature", "2", "Medical Subject Headings", "3", "National Agricultural Library subject authority file", "4", "Source not specified", "5", "Canadian Subject Headings", "6", "Répertoire de vedettes-matière", "7", "Source specified in subfield $2" }, "630", "Nonfiling characters", new String[] { // First }, "Thesaurus", new String[] { // Second "0", "Library of Congress Subject Headings", "1", "LC subject headings for children's literature", "2", "Medical Subject Headings", "3", "National Agricultural Library subject authority file", "4", "Source not specified", "5", "Canadian Subject Headings", "6", "Répertoire de vedettes-matière", "7", "Source specified in subfield $2" }, "648", "Undefined", new String[] { // First }, "Thesaurus", new String[] { // Second "0", "Library of Congress Subject Headings", "1", "LC subject headings for children's literature", "2", "Medical Subject Headings", "3", "National Agricultural Library subject authority file", "4", "Source not specified", "5", "Canadian Subject Headings", "6", "Répertoire de vedettes-matière", "7", "Source specified in subfield $2" }, "650", "Level of subject", new String[] { // First "0", "No level specified", "1", "Primary", "2", "Secondary" }, "Thesaurus", new String[] { // Second "0", "Library of Congress Subject Headings", "1", "LC subject headings for children's literature", "2", "Medical Subject Headings", "3", "National Agricultural Library subject authority file", "4", "Source not specified", "5", "Canadian Subject Headings", "6", "Répertoire de vedettes-matière", "7", "Source specified in subfield $2" }, "651", "Undefined", new String[] { // First }, "Thesaurus", new String[] { // Second "0", "Library of Congress Subject Headings", "1", "LC subject headings for children's literature", "2", "Medical Subject Headings", "3", "National Agricultural Library subject authority file", "4", "Source not specified", "5", "Canadian Subject Headings", "6", "Répertoire de vedettes-matière", "7", "Source specified in subfield $2" }, "653", "Level of index term", new String[] { // First "0", "No level specified", "1", "Primary", "2", "Secondary" }, "Type of term or name", new String[] { // Second "0", "Topical term", "1", "Personal name", "2", "Corporate name", "3", "Meeting name", "4", "Chronological term", "5", "Geographic name", "6", "Genre/form term", }, "654", "Level of subject", new String[] { // First "0", "No level specified", "1", "Primary", "2", "Secondary" }, "Undefined", new String[] { // Second }, "655", "Type of heading", new String[] { // First "0", "Faceted" }, "Thesaurus", new String[] { // Second "0", "Library of Congress Subject Headings", "1", "LC subject headings for children's literature", "2", "Medical Subject Headings", "3", "National Agricultural Library subject authority file", "4", "Source not specified", "5", "Canadian Subject Headings", "6", "Répertoire de vedettes-matière", "7", "Source specified in subfield $2" }, "656", "Undefined", new String[] { // First }, "Source of term", new String[] { // Second "7", "Source specified in subfield $2" }, "657", "Undefined", new String[] { // First }, "Source of term", new String[] { // Second "7", "Source specified in subfield $2" }, "700", "Type of personal name entry element", new String[] { // First "0", "Forename", "1", "Surname", "3", "Family name" }, "Type of added entry", new String[] { // Second "2", "Analytical entry" }, "710", "Type of corporate name entry element", new String[] { // First "0", "Inverted name", "1", "Jurisdiction name", "2", "Name in direct order" }, "Type of added entry", new String[] { // Second "2", "Analytical entry" }, "711", "Type of meeting name entry element", new String[] { // First "0", "Inverted name", "1", "Jurisdiction name", "2", "Name in direct order" }, "Type of added entry", new String[] { // Second "2", "Analytical entry" }, "720", "Type of name", new String[] { // First "1", "Personal", "2", "Other" }, "Undefined", new String[] { // Second }, "730", "Nonfiling characters", new String[] { // First }, "Type of added entry", new String[] { // Second "2", "Analytical entry" }, "740", "Nonfiling characters", new String[] { // First "0", "No nonfiling characters" }, "Type of added entry", new String[] { // Second "2", "Analytical entry" }, "760", "Note controller", new String[] { // First "0", "Display note", "1", "Do not display note" }, "Display constant controller", new String[] { // Second "8", "No display constant generated" }, "762", "Note controller", new String[] { // First "0", "Display note", "1", "Do not display note" }, "Display constant controller", new String[] { // Second "8", "No display constant generated" }, "765", "Note controller", new String[] { // First "0", "Display note", "1", "Do not display note" }, "Display constant controller", new String[] { // Second "8", "No display constant generated" }, "767", "Note controller", new String[] { // First "0", "Display note", "1", "Do not display note" }, "Display constant controller", new String[] { // Second "8", "No display constant generated" }, "770", "Note controller", new String[] { // First "0", "Display note", "1", "Do not display note" }, "Display constant controller", new String[] { // Second "8", "No display constant generated" }, "772", "Note controller", new String[] { // First "0", "Display note", "1", "Do not display note" }, "Display constant controller", new String[] { // Second "0", "Parent", "8", "No display constant generated" }, "773", "Note controller", new String[] { // First "0", "Display note", "1", "Do not display note" }, "Display constant controller", new String[] { // Second "8", "No display constant generated" }, "774", "Note controller", new String[] { // First "0", "Display note", "1", "Do not display note" }, "Display constant controller", new String[] { // Second "8", "No display constant generated" }, "775", "Note controller", new String[] { // First "0", "Display note", "1", "Do not display note" }, "Display constant controller", new String[] { // Second "8", "No display constant generated" }, "776", "Note controller", new String[] { // First "0", "Display note", "1", "Do not display note" }, "Display constant controller", new String[] { // Second "8", "No display constant generated" }, "777", "Note controller", new String[] { // First "0", "Display note", "1", "Do not display note" }, "Display constant controller", new String[] { // Second "8", "No display constant generated" }, "780", "Note controller", new String[] { // First "0", "Display note", "1", "Do not display note" }, "Type of relationship", new String[] { // Second "0", "Continues", "1", "Continues in part", "2", "Supersedes", "3", "Supersedes in part", "4", "Formed by the union of ... and ...", "5", "Absorbed", "6", "Absorbed in part", "7", "Separated from" }, "785", "Note controller", new String[] { // First "0", "Display note", "1", "Do not display note" }, "Type of relationship", new String[] { // Second "0", "Continued by", "1", "Continued in part by", "2", "Superseded by", "3", "Superseded in part by", "4", "Absorbed by", "5", "Absorbed in part by", "6", "Split into ... and ...", "7", "Merged with ... to form ...", "8", "Changed back to" }, "786", "Note controller", new String[] { // First "0", "Display note", "1", "Do not display note" }, "Display constant controller", new String[] { // Second "8", "No display constant generated" }, "787", "Note controller", new String[] { // First "0", "Display note", "1", "Do not display note" }, "Display constant controller", new String[] { // Second "8", "No display constant generated" }, "800", "Type of personal name entry element", new String[] { // First "0", "Forename", "1", "Surname", "3", "Family name" }, "Undefined", new String[] { // Second }, "810", "Type of personal name entry element", new String[] { // First "0", "Inverted name", "1", "Jurisdiction name", "2", "Name in direct order" }, "Undefined", new String[] { // Second }, "811", "Type of personal name entry element", new String[] { // First "0", "Inverted name", "1", "Jurisdiction name", "2", "Name in direct order" }, "Undefined", new String[] { // Second }, "830", "Undefined", new String[] { // First }, "Nonfiling characters", new String[] { // Second "0", "No nonfiling characters", }, "852", "Shelving scheme", new String[] { // First "0", "Library of Congress classification", "1", "Dewey Decimal classification", "2", "National Library of Medicine classification", "3", "Superintendent of Documents classification", "4", "Shelving control number", "5", "Title", "6", "Shelved separately", "7", "Source specified in subfield $2", "8", "Other scheme" }, "Shelving order", new String[] { // Second "0", "Not enumeration", "1", "Primary enumeration", "2", "Alternative enumeration" }, "856", "Access method", new String[] { // First "0", "Email", "1", "FTP", "2", "Remote login (Telnet)", "3", "Dial-up", "4", "HTTP", "7", "Method specified in subfield $2", }, "Relationship", new String[] { // Second "0", "Resource", "1", "Version of resource", "2", "Related resource", "8", "No display constant generated" }, "886", "Type of field", new String[] { // First "0", "Leader", "1", "Variable control fields (002-009)", "2", "Variable data fields (010-999)", }, "Undefined", new String[] { // Second }, }; private static HashMap<String,String> indicatorNameHash = null; private static HashMap<String,String> indicatorValueHash = null; public static String getFieldIndicatorName(String field, String indicatorNumber) { if(indicatorNameHash == null) { fillIndicatorHashMaps(); } return indicatorNameHash.get(field+""+indicatorNumber); } public static String getFieldIndicatorValue(String field, String indicatorNumber, String indicator) { if(indicatorValueHash == null) { fillIndicatorHashMaps(); } return indicatorValueHash.get(field+""+indicatorNumber+""+indicator); } private static void fillIndicatorHashMaps() { indicatorNameHash = new HashMap<>(); indicatorValueHash = new HashMap<>(); String fn = null; String in = null; String iva[] = null; for(int i=0; i<fieldIndicatorNames.length; i=i+5) { fn = (String) fieldIndicatorNames[i]; in = (String) fieldIndicatorNames[i+1]; if(!"Undefined".equals(in)) { indicatorNameHash.put(fn+"1", in); } if(fieldIndicatorNames[i+2] instanceof String[]) { iva = (String[]) fieldIndicatorNames[i+2]; for(int j=0; j<iva.length; j=j+2) { if(iva[j] != null && iva[j+1] != null) { indicatorValueHash.put(fn+"1"+""+iva[j], iva[j+1]); } } } in = (String) fieldIndicatorNames[i+3]; if(!"Undefined".equals(in)) { indicatorNameHash.put(fn+"2", in); } if(fieldIndicatorNames[i+4] instanceof String[]) { iva = (String[]) fieldIndicatorNames[i+4]; for(int j=0; j<iva.length; j=j+2) { if(iva[j] != null && iva[j+1] != null) { indicatorValueHash.put(fn+"2"+""+iva[j], iva[j+1]); } } } } } }
57,566
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MadsExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/mads/MadsExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.mads; import java.io.ByteArrayInputStream; import java.io.File; import java.io.InputStream; import java.net.URL; import java.net.URLEncoder; import javax.swing.Icon; import org.wandora.application.gui.UIBox; import org.wandora.application.tools.extractors.AbstractExtractor; import org.wandora.application.tools.extractors.ExtractHelper; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; 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 MadsExtractor extends AbstractExtractor { private static final long serialVersionUID = 1L; protected static String MADS_SI = "http://www.loc.gov/marc/bibliographic/bdintro.html"; protected static String AUTHORITY_SI = "http://www.loc.gov/marc/bibliographic/bdintro.html#indicator"; private static String defaultEncoding = "UTF-8"; //"ISO-8859-1"; private static String defaultLang = "en"; /** Creates a new instance of MadsExtractor */ public MadsExtractor() { } @Override public String getName() { return "MADS extractor"; } @Override public String getDescription(){ return "Converts MADS XML documents to topics maps."; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_mads.png"); } private final String[] contentTypes=new String[] { "text/xml", "application/xml" }; @Override public String[] getContentTypes() { return contentTypes; } @Override public boolean useURLCrawler() { return false; } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- public boolean _extractTopicsFrom(URL url, TopicMap topicMap) throws Exception { String in = IObox.doUrl(url); InputSource inSource = new InputSource(new ByteArrayInputStream(in.getBytes(defaultEncoding))); inSource.setEncoding(defaultEncoding); return _extractTopicsFrom(inSource, topicMap); } public boolean _extractTopicsFrom(File file, TopicMap topicMap) throws Exception { String in = IObox.loadFile(file); InputSource inSource = new InputSource(new ByteArrayInputStream(in.getBytes(defaultEncoding))); inSource.setEncoding(defaultEncoding); return _extractTopicsFrom(inSource, 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 { InputSource inSource = new InputSource(in); inSource.setEncoding(defaultEncoding); return _extractTopicsFrom(inSource, topicMap); } public boolean _extractTopicsFrom(InputSource in, TopicMap topicMap) throws Exception { try { setDefaultLogger(); setProgressMax(100); // ---- Parse results ---- javax.xml.parsers.SAXParserFactory factory=javax.xml.parsers.SAXParserFactory.newInstance(); factory.setNamespaceAware(false); factory.setValidating(false); javax.xml.parsers.SAXParser parser=factory.newSAXParser(); XMLReader reader=parser.getXMLReader(); MadsXMLParser parserHandler = new MadsXMLParser(topicMap, this); reader.setContentHandler(parserHandler); reader.setErrorHandler(parserHandler); reader.setFeature("http://xml.org/sax/features/namespace-prefixes", false); try { reader.parse(in); } catch(Exception e){ if(!(e instanceof SAXException) || !e.getMessage().equals("User interrupt")) log(e); } String msg = null; if(parserHandler.progress == 0) { msg = "Found no records."; } else { msg = "Found "+parserHandler.progress+" record(s)."; } if(msg != null) log(msg); } catch (Exception ex) { log(ex); } return true; } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- private class MadsXMLParser implements org.xml.sax.ContentHandler, org.xml.sax.ErrorHandler { public MadsXMLParser(TopicMap tm, MadsExtractor parent){ this.tm=tm; this.parent=parent; } public int progress=0; private TopicMap tm; private MadsExtractor parent; public static final String TAG_MADS = "mads"; public static final String TAG_AUTHORITY = "authority"; public static final String TAG_RELATED = "related"; public static final String TAG_VARIANT = "variant"; public static final String TAG_NAME = "name"; public static final String TAG_TITLEINFO = "titleInfo"; public static final String TAG_TOPIC = "topic"; public static final String TAG_TEMPORAL = "temporal"; public static final String TAG_GENRE = "genre"; public static final String TAG_GEOGRAPHIC = "geographic"; public static final String TAG_HIERARCHICALGEOGRAPHIC = "hierarchicalGeographic"; public static final String TAG_OCCUPATION = "occupation"; public static final String TAG_NOTE = "note"; public static final String TAG_AFFILIATION = "affiliation"; public static final String TAG_URL = "url"; public static final String TAG_IDENTIFIER = "identifier"; public static final String TAG_FIELDOFACTIVITY = "fieldOfActivity"; public static final String TAG_EXTENSION = "extension"; public static final String TAG_RECORDINFO = "recordInfo"; // NAME public static final String TAG_NAMEPART = "namePart"; public static final String TAG_DESCRIPTION = "description"; // AFFILIATION public static final String TAG_ORGANIZATION = "organization"; public static final String TAG_POSITION = "position"; public static final String TAG_ADDRESS = "address"; public static final String TAG_EMAIL = "email"; public static final String TAG_PHONE = "phone"; public static final String TAG_FAX = "fax"; public static final String TAG_HOURS = "hours"; public static final String TAG_DATEVALID = "dateValid"; // ADDRESS public static final String TAG_STREET = "street"; public static final String TAG_CITY = "city"; public static final String TAG_STATE = "state"; public static final String TAG_COUNTRY = "country"; public static final String TAG_POSTCODE = "postcode"; public static final String ATTRIBUTE_VERSION = "version"; public static final String ATTRIBUTE_AUTHORITY = "authority"; public static final String ATTRIBUTE_TYPE = "type"; public static final String ATTRIBUTE_LANG = "lang"; public static final String ATTRIBUTE_ID = "ID"; // URL public static final String ATTRIBUTE_DATELASTACCESSED = "dateLastAccessed"; public static final String ATTRIBUTE_DISPLAYLABEL = "displayLabel"; public static final String ATTRIBUTE_NOTE = "note"; public static final String ATTRIBUTE_USAGE = "usage"; public static final String ATTRIBUTE_INVALID = "invalid"; public static final String ATTRIBUTE_ALTREPGROUP = "altRepGroup"; public static final String ATTRIBUTE_SCRIPT = "script"; public static final String ATTRIBUTE_TRANSLITERATION = "transliteration"; // STATES private static final int STATE_START=0; private static final int STATE_MADS=2; private static final int STATE_MADS_AUTHORITY=4; private static final int STATE_MADS_RELATED=5; private static final int STATE_MADS_VARIANT=6; private static final int STATE_MADS_AUTHORITY_NAME=42; private static final int STATE_MADS_AUTHORITY_NAME_NAMEPART=421; private static final int STATE_MADS_AUTHORITY_NAME_DESCRIPTION=422; private static final int STATE_MADS_AUTHORITY_TITLEINFO=43; private static final int STATE_MADS_AUTHORITY_TOPIC=44; private static final int STATE_MADS_AUTHORITY_TEMPORAL=45; private static final int STATE_MADS_AUTHORITY_GENRE=46; private static final int STATE_MADS_AUTHORITY_GEOGRAPHIC=47; private static final int STATE_MADS_AUTHORITY_HIERARCHICALGEOGRAPHIC=48; private static final int STATE_MADS_AUTHORITY_OCCUPATION=49; private static final int STATE_MADS_RELATED_NAME=52; private static final int STATE_MADS_RELATED_NAME_NAMEPART=521; private static final int STATE_MADS_RELATED_NAME_DESCRIPTION=522; private static final int STATE_MADS_RELATED_TITLEINFO=53; private static final int STATE_MADS_RELATED_TOPIC=54; private static final int STATE_MADS_RELATED_TEMPORAL=55; private static final int STATE_MADS_RELATED_GENRE=56; private static final int STATE_MADS_RELATED_GEOGRAPHIC=57; private static final int STATE_MADS_RELATED_HIERARCHICALGEOGRAPHIC=58; private static final int STATE_MADS_RELATED_OCCUPATION=59; private static final int STATE_MADS_VARIANT_NAME=62; private static final int STATE_MADS_VARIANT_NAME_NAMEPART=621; private static final int STATE_MADS_VARIANT_NAME_DESCRIPTION=622; private static final int STATE_MADS_VARIANT_TITLEINFO=63; private static final int STATE_MADS_VARIANT_TOPIC=64; private static final int STATE_MADS_VARIANT_TEMPORAL=65; private static final int STATE_MADS_VARIANT_GENRE=66; private static final int STATE_MADS_VARIANT_GEOGRAPHIC=67; private static final int STATE_MADS_VARIANT_HIERARCHICALGEOGRAPHIC=68; private static final int STATE_MADS_VARIANT_OCCUPATION=69; public static final int STATE_MADS_NOTE = 101; public static final int STATE_MADS_AFFILIATION = 102; public static final int STATE_MADS_URL = 103; public static final int STATE_MADS_IDENTIFIER = 104; public static final int STATE_MADS_FIELDOFACTIVITY = 105; public static final int STATE_MADS_EXTENSION = 106; public static final int STATE_MADS_RECORDINFO = 107; /* RECORDINFO * <xs:element ref="recordContentSource"/> <xs:element ref="recordCreationDate"/> <xs:element ref="recordChangeDate"/> <xs:element ref="recordIdentifier"/> <xs:element ref="languageOfCataloging"/> <xs:element ref="recordOrigin"/> <xs:element ref="descriptionStandard"/> */ public static final int STATE_MADS_AFFILIATION_ORGANIZATION = 1021; public static final int STATE_MADS_AFFILIATION_POSITION = 1022; public static final int STATE_MADS_AFFILIATION_ADDRESS = 1023; public static final int STATE_MADS_AFFILIATION_EMAIL = 1024; public static final int STATE_MADS_AFFILIATION_PHONE = 1025; public static final int STATE_MADS_AFFILIATION_FAX = 1026; public static final int STATE_MADS_AFFILIATION_HOURS = 1027; public static final int STATE_MADS_AFFILIATION_DATEVALID = 1028; public static final int STATE_MADS_AFFILIATION_ADDRESS_STREET = 10231; public static final int STATE_MADS_AFFILIATION_ADDRESS_CITY = 10232; public static final int STATE_MADS_AFFILIATION_ADDRESS_STATE = 10233; public static final int STATE_MADS_AFFILIATION_ADDRESS_COUNTRY = 10234; public static final int STATE_MADS_AFFILIATION_ADDRESS_POSTCODE = 10235; private int state=STATE_START; private MadsModel mads = null; private MadsModel.MadsAuthority authority = null; private MadsModel.MadsRelated related = null; private MadsModel.MadsVariant variant = null; private MadsModel.MadsGenre genre = null; private MadsModel.MadsGeographic geographic = null; private MadsModel.MadsName name = null; private MadsModel.MadsOccupation occupation = null; private MadsModel.MadsHierarchicalGeographic hierarchicalGeographic = null; private MadsModel.MadsTemporal temporal = null; private MadsModel.MadsTitleInfo titleInfo = null; private MadsModel.MadsTopic topic = null; private MadsModel.MadsAddress address = null; private MadsModel.MadsAffiliation affiliation = null; private MadsModel.MadsDateValid dateValid = null; private MadsModel.MadsDescription description = null; private MadsModel.MadsEmail email = null; private MadsModel.MadsExtension extension = null; private MadsModel.MadsFax fax = null; private MadsModel.MadsHours hours = null; private MadsModel.MadsIdentifier identifier = null; private MadsModel.MadsNamePart namePart = null; private MadsModel.MadsNote note = null; private MadsModel.MadsOrganization organization = null; private MadsModel.MadsPhone phone = null; private MadsModel.MadsPosition position = null; private MadsModel.MadsRecordInfo recordInfo = null; private MadsModel.MadsUrl url = null; private MadsModel.MadsFieldOfActivity fieldOfActivity = null; private String astreet = null; private String acity = null; private String astate = null; private String acountry = null; private String apostcode = 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(elementEquals(qName, TAG_MADS)) { mads = new MadsModel(); mads.id = atts.getValue(ATTRIBUTE_ID); mads.version = atts.getValue(ATTRIBUTE_VERSION); state = STATE_MADS; } break; case STATE_MADS: if(elementEquals(qName, TAG_AUTHORITY)) { authority = mads.new MadsAuthority(); state = STATE_MADS_AUTHORITY; } else if(elementEquals(qName, TAG_RELATED)) { related = mads.new MadsRelated(); state = STATE_MADS_RELATED; } else if(elementEquals(qName, TAG_VARIANT)) { variant = mads.new MadsVariant(); state = STATE_MADS_VARIANT; } // ***** Additional elements ***** else if(elementEquals(qName, TAG_NOTE)) { note = mads.new MadsNote(); state = STATE_MADS_NOTE; } else if(elementEquals(qName, TAG_AFFILIATION)) { affiliation = mads.new MadsAffiliation(); state = STATE_MADS_AFFILIATION; } else if(elementEquals(qName, TAG_URL)) { url = mads.new MadsUrl(); url.dateLastAccessed = atts.getValue(ATTRIBUTE_DATELASTACCESSED); url.displayLabel = atts.getValue(ATTRIBUTE_DISPLAYLABEL); url.note = atts.getValue(ATTRIBUTE_NOTE); url.usage = atts.getValue(ATTRIBUTE_USAGE); state = STATE_MADS_URL; } else if(elementEquals(qName, TAG_IDENTIFIER)) { identifier = mads.new MadsIdentifier(); identifier.type = atts.getValue(ATTRIBUTE_TYPE); identifier.displayLabel = atts.getValue(ATTRIBUTE_DISPLAYLABEL); identifier.invalid = atts.getValue(ATTRIBUTE_INVALID); identifier.altRepGroup = atts.getValue(ATTRIBUTE_ALTREPGROUP); state = STATE_MADS_IDENTIFIER; } else if(elementEquals(qName, TAG_FIELDOFACTIVITY)) { fieldOfActivity = mads.new MadsFieldOfActivity(); state = STATE_MADS_FIELDOFACTIVITY; } else if(elementEquals(qName, TAG_EXTENSION)) { extension = mads.new MadsExtension(); extension.displayLabel = atts.getValue(ATTRIBUTE_DISPLAYLABEL); state = STATE_MADS_EXTENSION; } else if(elementEquals(qName, TAG_RECORDINFO)) { recordInfo = mads.new MadsRecordInfo(); recordInfo.displayLabel = atts.getValue(ATTRIBUTE_DISPLAYLABEL); recordInfo.lang = atts.getValue(ATTRIBUTE_LANG); recordInfo.script = atts.getValue(ATTRIBUTE_SCRIPT); recordInfo.transliteration = atts.getValue(ATTRIBUTE_TRANSLITERATION); state = STATE_MADS_RECORDINFO; } break; case STATE_MADS_AUTHORITY: if(elementEquals(qName, TAG_NAME)) { name = mads.new MadsName(); name.type = atts.getValue(ATTRIBUTE_TYPE); name.authority = atts.getValue(ATTRIBUTE_AUTHORITY); state = STATE_MADS_AUTHORITY_NAME; } else if(elementEquals(qName, TAG_TITLEINFO)) { titleInfo = mads.new MadsTitleInfo(); titleInfo.type = atts.getValue(ATTRIBUTE_TYPE); titleInfo.authority = atts.getValue(ATTRIBUTE_AUTHORITY); state = STATE_MADS_AUTHORITY_TITLEINFO; } else if(elementEquals(qName, TAG_TOPIC)) { topic = mads.new MadsTopic(); topic.authority = atts.getValue(ATTRIBUTE_AUTHORITY); state = STATE_MADS_AUTHORITY_TOPIC; } else if(elementEquals(qName, TAG_TEMPORAL)) { temporal = mads.new MadsTemporal(); temporal.authority = atts.getValue(ATTRIBUTE_AUTHORITY); state = STATE_MADS_AUTHORITY_TEMPORAL; } else if(elementEquals(qName, TAG_GENRE)) { genre = mads.new MadsGenre(); genre.authority = atts.getValue(ATTRIBUTE_AUTHORITY); state = STATE_MADS_AUTHORITY_GENRE; } else if(elementEquals(qName, TAG_GEOGRAPHIC)) { geographic = mads.new MadsGeographic(); geographic.authority = atts.getValue(ATTRIBUTE_AUTHORITY); state = STATE_MADS_AUTHORITY_GEOGRAPHIC; } else if(elementEquals(qName, TAG_HIERARCHICALGEOGRAPHIC)) { hierarchicalGeographic = mads.new MadsHierarchicalGeographic(); hierarchicalGeographic.authority = atts.getValue(ATTRIBUTE_AUTHORITY); state = STATE_MADS_AUTHORITY_HIERARCHICALGEOGRAPHIC; } else if(elementEquals(qName, TAG_OCCUPATION)) { occupation = mads.new MadsOccupation(); occupation.authority = atts.getValue(ATTRIBUTE_AUTHORITY); state = STATE_MADS_AUTHORITY_OCCUPATION; } break; case STATE_MADS_RELATED: if(elementEquals(qName, TAG_NAME)) { name = mads.new MadsName(); state = STATE_MADS_RELATED_NAME; } else if(elementEquals(qName, TAG_TITLEINFO)) { titleInfo = mads.new MadsTitleInfo(); state = STATE_MADS_RELATED_TITLEINFO; } else if(elementEquals(qName, TAG_TOPIC)) { topic = mads.new MadsTopic(); state = STATE_MADS_RELATED_TOPIC; } else if(elementEquals(qName, TAG_TEMPORAL)) { temporal = mads.new MadsTemporal(); state = STATE_MADS_RELATED_TEMPORAL; } else if(elementEquals(qName, TAG_GENRE)) { genre = mads.new MadsGenre(); state = STATE_MADS_RELATED_GENRE; } else if(elementEquals(qName, TAG_GEOGRAPHIC)) { geographic = mads.new MadsGeographic(); state = STATE_MADS_RELATED_GEOGRAPHIC; } else if(elementEquals(qName, TAG_HIERARCHICALGEOGRAPHIC)) { hierarchicalGeographic = mads.new MadsHierarchicalGeographic(); state = STATE_MADS_RELATED_HIERARCHICALGEOGRAPHIC; } else if(elementEquals(qName, TAG_OCCUPATION)) { occupation = mads.new MadsOccupation(); state = STATE_MADS_RELATED_OCCUPATION; } break; case STATE_MADS_VARIANT: if(elementEquals(qName, TAG_NAME)) { name = mads.new MadsName(); state = STATE_MADS_VARIANT_NAME; } else if(elementEquals(qName, TAG_TITLEINFO)) { titleInfo = mads.new MadsTitleInfo(); state = STATE_MADS_VARIANT_TITLEINFO; } else if(elementEquals(qName, TAG_TOPIC)) { topic = mads.new MadsTopic(); state = STATE_MADS_VARIANT_TOPIC; } else if(elementEquals(qName, TAG_TEMPORAL)) { temporal = mads.new MadsTemporal(); state = STATE_MADS_VARIANT_TEMPORAL; } else if(elementEquals(qName, TAG_GENRE)) { genre = mads.new MadsGenre(); state = STATE_MADS_VARIANT_GENRE; } else if(elementEquals(qName, TAG_GEOGRAPHIC)) { geographic = mads.new MadsGeographic(); state = STATE_MADS_VARIANT_GEOGRAPHIC; } else if(elementEquals(qName, TAG_HIERARCHICALGEOGRAPHIC)) { hierarchicalGeographic = mads.new MadsHierarchicalGeographic(); state = STATE_MADS_VARIANT_HIERARCHICALGEOGRAPHIC; } else if(elementEquals(qName, TAG_OCCUPATION)) { occupation = mads.new MadsOccupation(); state = STATE_MADS_VARIANT_OCCUPATION; } break; // ***** NAMES ***** case STATE_MADS_AUTHORITY_NAME: if(elementEquals(qName, TAG_NAMEPART)) { namePart = mads.new MadsNamePart(); state = STATE_MADS_AUTHORITY_NAME_NAMEPART; } else if(elementEquals(qName, TAG_DESCRIPTION)) { description = mads.new MadsDescription(); state = STATE_MADS_AUTHORITY_NAME_DESCRIPTION; } break; case STATE_MADS_VARIANT_NAME: if(elementEquals(qName, TAG_NAMEPART)) { namePart = mads.new MadsNamePart(); state = STATE_MADS_VARIANT_NAME_NAMEPART; } else if(elementEquals(qName, TAG_DESCRIPTION)) { description = mads.new MadsDescription(); state = STATE_MADS_VARIANT_NAME_DESCRIPTION; } break; case STATE_MADS_RELATED_NAME: if(elementEquals(qName, TAG_NAMEPART)) { namePart = mads.new MadsNamePart(); state = STATE_MADS_RELATED_NAME_NAMEPART; } else if(elementEquals(qName, TAG_DESCRIPTION)) { description = mads.new MadsDescription(); state = STATE_MADS_RELATED_NAME_DESCRIPTION; } break; // ****** AFFILIATION ****** case STATE_MADS_AFFILIATION: if(elementEquals(qName, TAG_ORGANIZATION)) { organization = mads.new MadsOrganization(); state = STATE_MADS_AFFILIATION_ORGANIZATION; } else if(elementEquals(qName, TAG_POSITION)) { position = mads.new MadsPosition(); state = STATE_MADS_AFFILIATION_POSITION; } else if(elementEquals(qName, TAG_ADDRESS)) { address = mads.new MadsAddress(); state = STATE_MADS_AFFILIATION_ADDRESS; } else if(elementEquals(qName, TAG_EMAIL)) { email = mads.new MadsEmail(); state = STATE_MADS_AFFILIATION_EMAIL; } else if(elementEquals(qName, TAG_PHONE)) { phone = mads.new MadsPhone(); state = STATE_MADS_AFFILIATION_PHONE; } else if(elementEquals(qName, TAG_FAX)) { fax = mads.new MadsFax(); state = STATE_MADS_AFFILIATION_FAX; } else if(elementEquals(qName, TAG_HOURS)) { hours = mads.new MadsHours(); state = STATE_MADS_AFFILIATION_HOURS; } else if(elementEquals(qName, TAG_DATEVALID)) { dateValid = mads.new MadsDateValid(); state = STATE_MADS_AFFILIATION_DATEVALID; } break; case STATE_MADS_AFFILIATION_ADDRESS: if(elementEquals(qName, TAG_STREET)) { astreet = ""; state = STATE_MADS_AFFILIATION_ADDRESS_STREET; } else if(elementEquals(qName, TAG_CITY)) { acity = ""; state = STATE_MADS_AFFILIATION_ADDRESS_CITY; } else if(elementEquals(qName, TAG_STATE)) { astate = ""; state = STATE_MADS_AFFILIATION_ADDRESS_STATE; } else if(elementEquals(qName, TAG_COUNTRY)) { acountry = ""; state = STATE_MADS_AFFILIATION_ADDRESS_COUNTRY; } else if(elementEquals(qName, TAG_POSTCODE)) { apostcode = ""; state = STATE_MADS_AFFILIATION_ADDRESS_POSTCODE; } break; } } public void endElement(String uri, String localName, String qName) throws SAXException { switch(state) { // ****** VARIANT ****** case STATE_MADS_VARIANT_NAME: { if(elementEquals(qName, TAG_NAME)) { state = STATE_MADS_VARIANT; } break; } case STATE_MADS_VARIANT_TITLEINFO: { if(elementEquals(qName, TAG_TITLEINFO)) { state = STATE_MADS_VARIANT; } break; } case STATE_MADS_VARIANT_TOPIC: { if(elementEquals(qName, TAG_TOPIC)) { state = STATE_MADS_VARIANT; } break; } case STATE_MADS_VARIANT_TEMPORAL: { if(elementEquals(qName, TAG_TEMPORAL)) { state = STATE_MADS_VARIANT; } break; } case STATE_MADS_VARIANT_GENRE: { if(elementEquals(qName, TAG_GENRE)) { state = STATE_MADS_VARIANT; } break; } case STATE_MADS_VARIANT_GEOGRAPHIC: { if(elementEquals(qName, TAG_GEOGRAPHIC)) { state = STATE_MADS_VARIANT; } break; } case STATE_MADS_VARIANT_HIERARCHICALGEOGRAPHIC: { if(elementEquals(qName, TAG_HIERARCHICALGEOGRAPHIC)) { state = STATE_MADS_VARIANT; } break; } // ****** RELATED ****** case STATE_MADS_RELATED_NAME: { if(elementEquals(qName, TAG_NAME)) { state = STATE_MADS_RELATED; } break; } case STATE_MADS_RELATED_TITLEINFO: { if(elementEquals(qName, TAG_TITLEINFO)) { state = STATE_MADS_RELATED; } break; } case STATE_MADS_RELATED_TOPIC: { if(elementEquals(qName, TAG_TOPIC)) { state = STATE_MADS_RELATED; } break; } case STATE_MADS_RELATED_TEMPORAL: { if(elementEquals(qName, TAG_TEMPORAL)) { state = STATE_MADS_RELATED; } break; } case STATE_MADS_RELATED_GENRE: { if(elementEquals(qName, TAG_GENRE)) { state = STATE_MADS_RELATED; } break; } case STATE_MADS_RELATED_GEOGRAPHIC: { if(elementEquals(qName, TAG_GEOGRAPHIC)) { state = STATE_MADS_RELATED; } break; } case STATE_MADS_RELATED_HIERARCHICALGEOGRAPHIC: { if(elementEquals(qName, TAG_HIERARCHICALGEOGRAPHIC)) { state = STATE_MADS_RELATED; } break; } // ****** AUTHORITY ****** case STATE_MADS_AUTHORITY_NAME: { if(elementEquals(qName, TAG_NAME)) { state = STATE_MADS_AUTHORITY; } break; } case STATE_MADS_AUTHORITY_TITLEINFO: { if(elementEquals(qName, TAG_TITLEINFO)) { state = STATE_MADS_AUTHORITY; } break; } case STATE_MADS_AUTHORITY_TOPIC: { if(elementEquals(qName, TAG_TOPIC)) { state = STATE_MADS_AUTHORITY; } break; } case STATE_MADS_AUTHORITY_TEMPORAL: { if(elementEquals(qName, TAG_TEMPORAL)) { state = STATE_MADS_AUTHORITY; } break; } case STATE_MADS_AUTHORITY_GENRE: { if(elementEquals(qName, TAG_GENRE)) { state = STATE_MADS_AUTHORITY; } break; } case STATE_MADS_AUTHORITY_GEOGRAPHIC: { if(elementEquals(qName, TAG_GEOGRAPHIC)) { state = STATE_MADS_AUTHORITY; } break; } case STATE_MADS_AUTHORITY_HIERARCHICALGEOGRAPHIC: { if(elementEquals(qName, TAG_HIERARCHICALGEOGRAPHIC)) { state = STATE_MADS_AUTHORITY; } break; } // ******* NAMES ****** case STATE_MADS_AUTHORITY_NAME_NAMEPART: { if(elementEquals(qName, TAG_NAMEPART)) { state = STATE_MADS_AUTHORITY_NAME; } break; } case STATE_MADS_AUTHORITY_NAME_DESCRIPTION: { if(elementEquals(qName, TAG_DESCRIPTION)) { state = STATE_MADS_AUTHORITY_NAME; } break; } case STATE_MADS_RELATED_NAME_NAMEPART: { if(elementEquals(qName, TAG_NAMEPART)) { state = STATE_MADS_RELATED_NAME; } break; } case STATE_MADS_RELATED_NAME_DESCRIPTION: { if(elementEquals(qName, TAG_DESCRIPTION)) { state = STATE_MADS_RELATED_NAME; } break; } case STATE_MADS_VARIANT_NAME_NAMEPART: { if(elementEquals(qName, TAG_NAMEPART)) { state = STATE_MADS_VARIANT_NAME; } break; } case STATE_MADS_VARIANT_NAME_DESCRIPTION: { if(elementEquals(qName, TAG_DESCRIPTION)) { state = STATE_MADS_VARIANT_NAME; } break; } // ****** AFFILIATION ******* case STATE_MADS_AFFILIATION_ORGANIZATION: { if(elementEquals(qName, TAG_ORGANIZATION)) { state = STATE_MADS_AFFILIATION; } break; } case STATE_MADS_AFFILIATION_POSITION: { if(elementEquals(qName, TAG_POSITION)) { state = STATE_MADS_AFFILIATION; } break; } case STATE_MADS_AFFILIATION_ADDRESS: { if(elementEquals(qName, TAG_ADDRESS)) { state = STATE_MADS_AFFILIATION; } break; } case STATE_MADS_AFFILIATION_EMAIL: { if(elementEquals(qName, TAG_EMAIL)) { state = STATE_MADS_AFFILIATION; } break; } case STATE_MADS_AFFILIATION_PHONE: { if(elementEquals(qName, TAG_PHONE)) { state = STATE_MADS_AFFILIATION; } break; } case STATE_MADS_AFFILIATION_FAX: { if(elementEquals(qName, TAG_FAX)) { state = STATE_MADS_AFFILIATION; } break; } case STATE_MADS_AFFILIATION_HOURS: { if(elementEquals(qName, TAG_HOURS)) { state = STATE_MADS_AFFILIATION; } break; } case STATE_MADS_AFFILIATION_DATEVALID: { if(elementEquals(qName, TAG_DATEVALID)) { state = STATE_MADS_AFFILIATION; } break; } // ****** AFFILIATION - ADDRESS ****** case STATE_MADS_AFFILIATION_ADDRESS_STREET: { if(elementEquals(qName, TAG_STREET)) { state = STATE_MADS_AFFILIATION_ADDRESS; } break; } case STATE_MADS_AFFILIATION_ADDRESS_CITY: { if(elementEquals(qName, TAG_CITY)) { state = STATE_MADS_AFFILIATION_ADDRESS; } break; } case STATE_MADS_AFFILIATION_ADDRESS_STATE: { if(elementEquals(qName, TAG_STATE)) { state = STATE_MADS_AFFILIATION_ADDRESS; } break; } case STATE_MADS_AFFILIATION_ADDRESS_COUNTRY: { if(elementEquals(qName, TAG_COUNTRY)) { state = STATE_MADS_AFFILIATION_ADDRESS; } break; } case STATE_MADS_AFFILIATION_ADDRESS_POSTCODE: { if(elementEquals(qName, TAG_POSTCODE)) { state = STATE_MADS_AFFILIATION_ADDRESS; } break; } // ****** MADS > ****** case STATE_MADS_AUTHORITY: { if(elementEquals(qName, TAG_AUTHORITY)) { state = STATE_MADS; } break; } case STATE_MADS_RELATED: { if(elementEquals(qName, TAG_RELATED)) { state = STATE_MADS; } break; } case STATE_MADS_VARIANT: { if(elementEquals(qName, TAG_VARIANT)) { state = STATE_MADS; } break; } case STATE_MADS_NOTE: { if(elementEquals(qName, TAG_NOTE)) { state = STATE_MADS; } break; } case STATE_MADS_AFFILIATION: { if(elementEquals(qName, TAG_AFFILIATION)) { state = STATE_MADS; } break; } case STATE_MADS_URL: { if(elementEquals(qName, TAG_URL)) { state = STATE_MADS; } break; } case STATE_MADS_IDENTIFIER: { if(elementEquals(qName, TAG_IDENTIFIER)) { state = STATE_MADS; } break; } case STATE_MADS_FIELDOFACTIVITY: { if(elementEquals(qName, TAG_FIELDOFACTIVITY)) { state = STATE_MADS; } break; } case STATE_MADS_EXTENSION: { if(elementEquals(qName, TAG_EXTENSION)) { state = STATE_MADS; } break; } case STATE_MADS_RECORDINFO: { if(elementEquals(qName, TAG_RECORDINFO)) { state = STATE_MADS; } break; } } } public void characters(char[] ch, int start, int length) throws SAXException { String str = new String(ch,start,length); try { str = new String(str.getBytes(), defaultEncoding); } catch(Exception e) {} switch(state) { case STATE_MADS_IDENTIFIER: { //data_identifier += str; break; } default: break; } } public void warning(SAXParseException exception) throws SAXException { } public void error(SAXParseException exception) throws SAXException { parent.log("Error parsing XML document at "+exception.getLineNumber()+","+exception.getColumnNumber(),exception); } public void fatalError(SAXParseException exception) throws SAXException { parent.log("Fatal error parsing XML document at "+exception.getLineNumber()+","+exception.getColumnNumber(),exception); } public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {} public void processingInstruction(String target, String data) throws SAXException {} public void startPrefixMapping(String prefix, String uri) throws SAXException {} public void endPrefixMapping(String prefix) throws SAXException {} public void setDocumentLocator(org.xml.sax.Locator locator) {} public void skippedEntity(String name) throws SAXException {} private boolean elementEquals(String e, String str) { if(e != null && str != null) { if(e.equals(str)) return true; if(e.indexOf(":") > -1) { String[] eParts = e.split(":"); if(str.equals(eParts[eParts.length-1])) return true; } } return false; } } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // --- public Topic getAuthorityType(TopicMap tm) throws TopicMapException { return getOrCreateTopic(tm, AUTHORITY_SI, "Authority (MADS)", getMadsClass(tm)); } // --- public Topic getMadsClass(TopicMap tm) throws TopicMapException { return getOrCreateTopic(tm, MADS_SI, "MADS", getWandoraClass(tm) ); } public Topic getWandoraClass(TopicMap tm) throws TopicMapException { return getOrCreateTopic(tm, TMBox.WANDORACLASS_SI,"Wandora class"); } // -------- public Topic getTopic(TopicMap tm, String str, String SIBase, Topic type) throws TopicMapException { if(str != null && SIBase != null) { str = str.trim(); if(str.length() > 0) { Topic strTopic=getOrCreateTopic(tm, makeSI(SIBase, str), str, type); return strTopic; } } return null; } protected Topic getOrCreateTopic(TopicMap tm, String si) throws TopicMapException { return getOrCreateTopic(tm, si, null); } protected Topic getOrCreateTopic(TopicMap tm, String si,String bn) throws TopicMapException { return getOrCreateTopic(tm, si, bn, null); } protected Topic getOrCreateTopic(TopicMap tm, String si, String bn, Topic type) throws TopicMapException { if(si!=null){ Topic t=tm.getTopic(si); if(t==null){ t=tm.createTopic(); t.addSubjectIdentifier(tm.createLocator(si)); if(bn != null) t.setBaseName(bn); if(type != null) t.addType(type); } return t; } else { Topic t=tm.getTopicWithBaseName(bn); if(t==null){ t=tm.createTopic(); if(bn!=null) t.setBaseName(bn); if(si!=null) t.addSubjectIdentifier(tm.createLocator(si)); else t.addSubjectIdentifier(tm.makeSubjectIndicatorAsLocator()); if(type != null) t.addType(type); } return t; } } protected void makeSubclassOf(TopicMap tm, Topic t, Topic superclass) throws TopicMapException { ExtractHelper.makeSubclassOf(t, superclass, tm); } protected String makeSI(String base, String endPoint) { String end = endPoint; try { end = URLEncoder.encode(endPoint, defaultEncoding); } catch(Exception e) { log(e); } String si = base + "/" + end; return si; } // ---------------- }
46,493
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MadsModel.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/mads/MadsModel.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.mads; import java.util.ArrayList; import java.util.List; /** * * @author akivela */ public class MadsModel { String version = null; String id = null; List<MadsAuthority> authorities = new ArrayList<>(); List<MadsRelated> related = new ArrayList<>(); List<MadsVariant> variant = new ArrayList<>(); List<MadsNote> notes = new ArrayList<>(); List<MadsAffiliation> affiliations = new ArrayList<>(); List<MadsUrl> urls = new ArrayList<>(); List<MadsIdentifier> identifiers = new ArrayList<>(); List<MadsFieldOfActivity> fieldOfActivities = new ArrayList<>(); List<MadsExtension> extensions = new ArrayList<>(); List<MadsRecordInfo> recordInfos = new ArrayList<>(); class MadsAuthority { String link = null; String language = null; String id = null; List<MadsTopic> topics = new ArrayList<>(); List<MadsName> names = new ArrayList<>(); List<MadsTitleInfo> titleInfos = new ArrayList<>(); List<MadsTemporal> temporals = new ArrayList<>(); List<MadsGenre> genres = new ArrayList<>(); List<MadsGeographic> geographics = new ArrayList<>(); List<MadsHierarchicalGeographic> hgeographics = new ArrayList<>(); List<MadsOccupation> occupations = new ArrayList<>(); } class MadsRelated { String link = null; String language = null; String id = null; String type = null; List<MadsTopic> topics = new ArrayList<>(); List<MadsName> names = new ArrayList<>(); List<MadsTitleInfo> titleInfos = new ArrayList<>(); List<MadsTemporal> temporals = new ArrayList<>(); List<MadsGenre> genres = new ArrayList<>(); List<MadsGeographic> geographics = new ArrayList<>(); List<MadsHierarchicalGeographic> hgeographics = new ArrayList<>(); List<MadsOccupation> occupations = new ArrayList<>(); } class MadsVariant { String link = null; String language = null; String id = null; String type = null; List<MadsTopic> topics = new ArrayList<>(); List<MadsName> names = new ArrayList<>(); List<MadsTitleInfo> titleInfos = new ArrayList<>(); List<MadsTemporal> temporals = new ArrayList<>(); List<MadsGenre> genres = new ArrayList<>(); List<MadsGeographic> geographics = new ArrayList<>(); List<MadsHierarchicalGeographic> hgeographics = new ArrayList<>(); List<MadsOccupation> occupations = new ArrayList<>(); } // ------ class MadsName { String type = null; String authority = null; List<MadsNamePart> nameParts = new ArrayList<>(); List<MadsDescription> descriptions = new ArrayList<>(); } class MadsNamePart { String language = null; String type = null; String value = null; } class MadsDescription { String language = null; String type = null; String value = null; } class MadsTopic { String authority = null; String value = null; } class MadsGenre { String authority = null; String value = null; } class MadsGeographic { String authority = null; String value = null; } class MadsHierarchicalGeographic { String authority = null; String geographic = null; MadsHierarchicalGeographic next = null; } class MadsOccupation { String authority = null; String value = null; } class MadsTemporal { String authority = null; String value = null; } class MadsTitleInfo { String type = null; String authority = null; String value = null; } class MadsExtension { String displayLabel = null; String value = null; } class MadsRecordInfo { String lang = null; String script = null; String transliteration = null; String displayLabel = null; String value = null; } class MadsIdentifier { String type = null; String displayLabel = null; String invalid = null; String altRepGroup = null; String value = null; } class MadsUrl { String dateLastAccessed = null; String displayLabel = null; String note = null; String access = null; String usage = null; String value = null; } class MadsNote { String language = null; String value = null; } class MadsAffiliation { String language = null; String value = null; List<MadsOrganization> organizations = new ArrayList<>(); List<MadsPosition> positions = new ArrayList<>(); List<MadsAddress> addresses = new ArrayList<>(); List<MadsEmail> emails = new ArrayList<>(); List<MadsPhone> phones = new ArrayList<>(); List<MadsFax> faxs = new ArrayList<>(); List<MadsHours> hours = new ArrayList<>(); List<MadsDateValid> dateValids = new ArrayList<>(); } class MadsOrganization { String value = null; } class MadsPosition { String value = null; } class MadsAddress { List<String> streets = new ArrayList<>(); List<String> cities = new ArrayList<>(); List<String> states = new ArrayList<>(); List<String> countries = new ArrayList<>(); List<String> postcodes = new ArrayList<>(); String value = null; } class MadsEmail { String value = null; } class MadsPhone { String value = null; } class MadsFax { String value = null; } class MadsHours { String value = null; } class MadsDateValid { String authority = null; String value = null; } class MadsFieldOfActivity { String value = null; } }
6,844
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AbstractWordExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/word/AbstractWordExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.word; import java.io.File; import java.net.URL; import java.nio.charset.Charset; import java.nio.file.Files; import java.util.Arrays; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Set; import org.apache.commons.io.IOUtils; import org.wandora.application.contexts.Context; import org.wandora.application.tools.extractors.AbstractExtractor; import org.wandora.application.tools.extractors.ExtractHelper; import org.wandora.topicmap.Association; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author Eero Lehtonen */ abstract class AbstractWordExtractor extends AbstractExtractor{ private static final long serialVersionUID = 1L; private Topic baseTopic = null; private WordConfiguration config; //-------------------------------------------------------------------------- @Override public boolean _extractTopicsFrom(File f, TopicMap t) throws Exception { List<String> words = Files.readAllLines(f.toPath(), Charset.forName("UTF-8")); return handleWordList(words, t); } @Override public boolean _extractTopicsFrom(URL u, TopicMap t) throws Exception { String str = IOUtils.toString(u.openStream()); return _extractTopicsFrom(str, t); } @Override public boolean _extractTopicsFrom(String str, TopicMap t) throws Exception { String[] strArray = str.split("\\r?\\n"); return handleWordList(Arrays.asList(strArray), t); } abstract WordConfiguration getConfig(); /** * * Associates each topic in current context with a word if the word is found * in the topic instance data. * * First look up topics for each word, then create topics from words and * associate words with corresponding existing topics. * * @param words a list of words to look for in instance data * @param tm * @return whether the process succeeded */ protected boolean handleWordList(List<String> words, TopicMap tm) throws TopicMapException { log("Handling " + words.size() + " words"); if (config == null) { config = getConfig(); } baseTopic = ExtractHelper.getOrCreateTopic(getSIBase(), getName(), tm); makeSubclassOfWandoraClass(baseTopic, tm); HashMap<String, HashMap<Topic,Float>> mapping = new HashMap<>(); for (String word : words) { try { log("Finding topics for \"" + word + "\""); HashMap<Topic,Float> topics = solveTopics(word, tm); mapping.put(word, topics); } catch (Exception e) { log(e.getMessage()); } } for (String word : words) { HashMap<Topic,Float> matches = mapping.get(word); if (matches == null) { continue; //In case solveTopics failed for this word } try { Topic wt = createWordTopic(word, tm); log("Associating " + matches.keySet().size() + " topics with \"" + word + "\""); for (Topic t : matches.keySet()) { Topic st = createScoreTopic(matches.get(t), tm); associateWord(wt, t, st, tm); } } catch (TopicMapException tme) { log(tme.getMessage()); } } return true; } /** * Find topics with content matching 'word' according to given configuration * * @param word * @param tm * @return a set of topics matching word */ private HashMap<Topic, Float> solveTopics(String word, TopicMap tm) { Context c = getContext(); Iterator contextIterator = c.getContextObjects(); HashMap<Topic, Float> scores = new HashMap<>(); Object needle = this.formNeedle(word); while (contextIterator.hasNext()) { Object o = contextIterator.next(); if (!(o instanceof Topic)) { continue; } Topic t = (Topic) o; try { // Check base name if (config.getBaseName()) { float score = isMatch(needle, t.getBaseName()); if(score > 0){ if(!scores.containsKey(t) || scores.get(t) < score){ scores.put(t, score); } } } // Check variant names if (config.getVariantName()) { for (Set<Topic> scope : t.getVariantScopes()) { String variant = t.getVariant(scope); if (!config.getCaseSensitive()) { variant = variant.toLowerCase(); } float score = isMatch(needle, variant); if(score > 0){ if(!scores.containsKey(t) || scores.get(t) < score){ scores.put(t, score); } } } } // Check instance data if (config.getInstanceData()) { for (Topic type : t.getDataTypes()) { Enumeration<String> data = t.getData(type).elements(); while (data.hasMoreElements()) { String datum = data.nextElement(); if (!config.getCaseSensitive()) { datum = datum.toLowerCase(); } float score = isMatch(needle, datum); if(score > 0){ if(!scores.containsKey(t) || scores.get(t) < score){ scores.put(t, score); } } } } } } catch (TopicMapException tme) { log(tme.getMessage()); } } return scores; } /** * Create a Topic representing word * * @param word * @param tm * @return * @throws TopicMapException if topic creation fails */ private Topic createWordTopic(String word, TopicMap tm) throws TopicMapException { String bnSuffix = getBNSuffix(); String si = getSIBase() + "word/" + word; String bn = word + " " + bnSuffix; Topic w = ExtractHelper.getOrCreateTopic(si, bn, tm); ExtractHelper.makeSubclassOf(w, baseTopic, tm); return w; } private Topic createScoreTopic(Float get, TopicMap tm) throws TopicMapException { String bnSuffix = getBNSuffix(); String si = getSIBase() + "score/" + get.toString(); String bn = get.toString() + " " + bnSuffix; Topic w = ExtractHelper.getOrCreateTopic(si, bn, tm); return w; } /** * Associate the Topic word with a Topic t * * @param w * @param t * @param tm * @throws TopicMapException if creating the association fails */ private void associateWord(Topic w, Topic t, Topic s, TopicMap tm) throws TopicMapException { String bnSuffix = getBNSuffix(); Topic wordType = ExtractHelper.getOrCreateTopic(getSIBase() + "word", "word " + bnSuffix, tm); Topic targetType = ExtractHelper.getOrCreateTopic(getSIBase() + "target", "target " + bnSuffix, tm); Association a = tm.createAssociation(wordType); a.addPlayer(w, wordType); a.addPlayer(t, targetType); if(config.getAssociateScore()){ Topic scoreType = ExtractHelper.getOrCreateTopic(getSIBase() + "score", "score " + bnSuffix, tm); a.addPlayer(s, scoreType); } } abstract protected Object formNeedle(String s); abstract protected String getBNSuffix(); abstract protected String getSIBase(); abstract protected float isMatch(Object needle, String haystack); }
9,416
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimpleWordConfiguration.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/word/SimpleWordConfiguration.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.word; /** * * @author Eero Lehtonen */ class SimpleWordConfiguration extends WordConfiguration{ private boolean REGEX; private boolean MATCH_WORDS; public SimpleWordConfiguration() { super(); REGEX = false; MATCH_WORDS = false; } protected boolean getRegex(){ return REGEX; } protected boolean getMatchWords(){ return MATCH_WORDS; } protected void setRegex(boolean b){ REGEX = b; } protected void setMatchWords(boolean b){ MATCH_WORDS = b; } }
1,435
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimilarityMatchingExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/word/SimilarityMatchingExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.word; import static org.wandora.application.gui.search.SimilarityBox.getSimilarity; import org.wandora.application.Wandora; import org.wandora.topicmap.TopicMapException; import org.wandora.utils.Options; import uk.ac.shef.wit.simmetrics.similaritymetrics.InterfaceStringMetric; /** * * @author Eero Lehtonen */ public class SimilarityMatchingExtractor extends AbstractWordExtractor{ private static final long serialVersionUID = 1L; private final String SI_BASE = "http://wandora.org/si/word-similarity/"; private static final String BN_SUFFIX = "(word similarity matching extractor)"; protected SimilarityWordConfiguration config; @Override public String getName(){ return "Word Similarity Matching Extractor"; } @Override public String getDescription(){ return "Matches given words to topic data with given similarity measure" + " and creates associations between matched topics and given" + " words."; } @Override public boolean isConfigurable() { return true; } @Override public void configure(Wandora w, Options o, String p) throws TopicMapException { SimilarityWordConfigurationDialog d = new SimilarityWordConfigurationDialog(w); d.openDialog(config); if (d.wasAccepted()) { config = d.getConfiguration(); } } @Override WordConfiguration getConfig() { if(config == null) config = new SimilarityWordConfiguration(); return config; } @Override protected Object formNeedle(String s) { if (!config.getCaseSensitive()) { s = s.toLowerCase(); } return s; } @Override protected float isMatch(Object needle, String haystack) { InterfaceStringMetric metric = config.getStringMetric(); float sim = getSimilarity((String)needle, haystack, metric, true); return (sim > config.getThreshold()) ? sim : 0f; } @Override protected String getBNSuffix() { return BN_SUFFIX; } @Override protected String getSIBase() { return SI_BASE; } }
3,034
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimpleWordConfigurationDialog.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/word/SimpleWordConfigurationDialog.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.word; import javax.swing.JDialog; import org.wandora.application.Wandora; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.simple.SimpleButton; import org.wandora.application.gui.simple.SimpleCheckBox; /** * * @author Eero Lehtonen */ class SimpleWordConfigurationDialog extends javax.swing.JPanel { private static final long serialVersionUID = 1L; private Wandora wandora = null; private boolean wasAccepted = false; private JDialog myDialog = null; private SimpleWordConfiguration config; private SimpleWordConfiguration newConfig; protected boolean wasAccepted() { return wasAccepted; } public SimpleWordConfigurationDialog(Wandora w) { wandora = w; initComponents(); } public void openDialog(SimpleWordConfiguration c) { wasAccepted = false; if (myDialog == null) { myDialog = new JDialog(wandora, true); myDialog.add(this); myDialog.setSize(320, 320); myDialog.setTitle("Simple Word Extractor Configuration"); UIBox.centerWindow(myDialog, wandora); } newConfig = (c != null) ? c : new SimpleWordConfiguration(); toggleRegex.setSelected(newConfig.getRegex()); toggleCaseSensitive.setSelected(newConfig.getCaseSensitive()); toggleMatchWords.setSelected(newConfig.getMatchWords()); toggleBaseName.setSelected(newConfig.getBaseName()); toggleVariantName.setSelected(newConfig.getVariantName()); toggleInstanceData.setSelected(newConfig.getInstanceData()); myDialog.setVisible(true); } private void saveConfiguration() { if (newConfig == null) { newConfig = new SimpleWordConfiguration(); } newConfig.setRegex(toggleRegex.isSelected()); newConfig.setCaseSensitive(toggleCaseSensitive.isSelected()); newConfig.setMatchWords(toggleMatchWords.isSelected()); newConfig.setBaseName(toggleBaseName.isSelected()); newConfig.setVariantName(toggleVariantName.isSelected()); newConfig.setInstanceData(toggleInstanceData.isSelected()); config = newConfig; } protected SimpleWordConfiguration getConfiguration() { if(config == null) config = new SimpleWordConfiguration(); return config; } ; /** * 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; container = new javax.swing.JPanel(); toggleRegex = new SimpleCheckBox(); toggleCaseSensitive = new SimpleCheckBox(); toggleMatchWords = new SimpleCheckBox(); toggleBaseName = new SimpleCheckBox(); toggleVariantName = new SimpleCheckBox(); toggleInstanceData = new SimpleCheckBox(); submit = new SimpleButton(); cancel = new SimpleButton(); setLayout(new java.awt.GridBagLayout()); container.setLayout(new java.awt.GridBagLayout()); toggleRegex.setText("Regex"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; container.add(toggleRegex, gridBagConstraints); toggleCaseSensitive.setText("Case sensitive"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; container.add(toggleCaseSensitive, gridBagConstraints); toggleMatchWords.setText("Match word"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; container.add(toggleMatchWords, gridBagConstraints); toggleBaseName.setText("Base Name"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; container.add(toggleBaseName, gridBagConstraints); toggleVariantName.setText("Variant Name"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; container.add(toggleVariantName, gridBagConstraints); toggleInstanceData.setText("Instance Data"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; container.add(toggleInstanceData, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 0.1; gridBagConstraints.weighty = 0.1; add(container, gridBagConstraints); submit.setText("OK"); submit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { submitActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; gridBagConstraints.weightx = 0.1; gridBagConstraints.insets = new java.awt.Insets(0, 0, 4, 4); add(submit, gridBagConstraints); cancel.setText("Cancel"); cancel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; gridBagConstraints.insets = new java.awt.Insets(0, 0, 4, 4); add(cancel, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents private void cancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelActionPerformed wasAccepted = false; if (myDialog != null) { myDialog.setVisible(false); } }//GEN-LAST:event_cancelActionPerformed private void submitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_submitActionPerformed wasAccepted = true; saveConfiguration(); if (myDialog != null) { myDialog.setVisible(false); } }//GEN-LAST:event_submitActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton cancel; private javax.swing.JPanel container; private javax.swing.JButton submit; private javax.swing.JCheckBox toggleBaseName; private javax.swing.JCheckBox toggleCaseSensitive; private javax.swing.JCheckBox toggleInstanceData; private javax.swing.JCheckBox toggleMatchWords; private javax.swing.JCheckBox toggleRegex; private javax.swing.JCheckBox toggleVariantName; // End of variables declaration//GEN-END:variables }
8,868
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
WordConfiguration.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/word/WordConfiguration.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.word; /** * * @author Eero Lehtonen */ class WordConfiguration { private boolean BASE_NAME; private boolean INSTANCE_DATA; private boolean VARIANT_NAME; private boolean CASE_SENSITIVE; private boolean ASSOCIATE_SCORE; public WordConfiguration() { CASE_SENSITIVE = false; BASE_NAME = true; VARIANT_NAME = true; INSTANCE_DATA = true; ASSOCIATE_SCORE = false; } protected void setBaseName(boolean b){ BASE_NAME = b; } protected void setInstanceData(boolean b){ INSTANCE_DATA = b; } protected void setVariantName(boolean b){ VARIANT_NAME = b; } protected void setCaseSensitive(boolean b){ CASE_SENSITIVE = b; } protected void setAssociateScore(boolean b){ ASSOCIATE_SCORE = b; } protected boolean getBaseName(){ return BASE_NAME; } protected boolean getInstanceData(){ return INSTANCE_DATA; } protected boolean getVariantName(){ return VARIANT_NAME; } protected boolean getCaseSensitive(){ return CASE_SENSITIVE; } protected boolean getAssociateScore(){ return ASSOCIATE_SCORE; } }
2,129
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimpleWordMatchingExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/word/SimpleWordMatchingExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.word; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import org.wandora.application.Wandora; import org.wandora.topicmap.TopicMapException; import org.wandora.utils.Options; /** * * @author Eero Lehtonen */ public class SimpleWordMatchingExtractor extends AbstractWordExtractor { private static final long serialVersionUID = 1L; private final String SI_BASE = "http://wandora.org/si/simple-word/"; private final String BN_SUFFIX = "(simple word extractor)"; private SimpleWordConfiguration config; @Override public String getName(){ return "Simple Word Matching Extractor"; } @Override public String getDescription(){ return "Matches given words and regular expressions to topic data and" + " creates associations between matched topics and given words."; } @Override public boolean isConfigurable() { return true; } @Override public void configure(Wandora w, Options o, String p) throws TopicMapException { SimpleWordConfigurationDialog d = new SimpleWordConfigurationDialog(w); d.openDialog(config); if (d.wasAccepted()) { config = d.getConfiguration(); } } @Override WordConfiguration getConfig() { if(config == null) config = new SimpleWordConfiguration(); return config; } @Override protected float isMatch(Object needle, String haystack) { if (needle instanceof Pattern) { Pattern p = (Pattern) needle; return p.matcher(haystack).find() ? 1f : 0f; } else if (needle instanceof String) { String s = (String) needle; int index = haystack.indexOf(s); boolean isMatch = (index != -1); if (config.getMatchWords() && isMatch) { if (index > 0 && Character.isLetterOrDigit(haystack.charAt(index - 1))) { isMatch = false; } if (index + s.length() < haystack.length() && Character.isLetterOrDigit(haystack.charAt(index + s.length()))) { isMatch = false; } } return isMatch ? 1f : 0f; } else { throw new UnsupportedOperationException("Match operation failed."); } } @Override protected Object formNeedle(String word) { Object needle; if (config.getRegex()) { try { needle = Pattern.compile(word); } catch (PatternSyntaxException pse) { throw new IllegalArgumentException("Invalid regex syntax for " + "pattern \"" + word + "\": " + pse.getMessage()); } } else if (!config.getCaseSensitive()) { needle = word.toLowerCase(); } else { needle = word; } return needle; } @Override protected String getBNSuffix() { return BN_SUFFIX; } @Override protected String getSIBase() { return SI_BASE; } }
4,031
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimilarityWordConfiguration.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/word/SimilarityWordConfiguration.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.word; import java.util.ArrayList; import java.util.List; import org.apache.commons.collections.bidimap.DualHashBidiMap; import uk.ac.shef.wit.simmetrics.similaritymetrics.InterfaceStringMetric; import uk.ac.shef.wit.simmetrics.similaritymetrics.Jaro; import uk.ac.shef.wit.simmetrics.similaritymetrics.JaroWinkler; import uk.ac.shef.wit.simmetrics.similaritymetrics.Levenshtein; /** * * @author Eero Lehtonen */ class SimilarityWordConfiguration extends WordConfiguration{ private float THRESHOLD; private InterfaceStringMetric STRING_METRIC; private final DualHashBidiMap STRING_METRICS; SimilarityWordConfiguration() { super(); setAssociateScore(true); THRESHOLD = 0.5f; STRING_METRICS = new DualHashBidiMap(); STRING_METRICS.put("Levenshtein", new Levenshtein()); STRING_METRICS.put("Jaro", new Jaro()); STRING_METRICS.put("Jaro Winkler", new JaroWinkler()); STRING_METRIC = new Levenshtein(); } protected float getThreshold(){ return THRESHOLD; } protected void setThreshold(float f){ THRESHOLD = f; } protected void setStringMetric(String s){ STRING_METRIC = (InterfaceStringMetric) STRING_METRICS.get(s); } protected InterfaceStringMetric getStringMetric(){ return STRING_METRIC; } protected String getStringMetricName(){ return (String)STRING_METRICS.getKey(STRING_METRIC); } protected List<String> getSTringMetricNames(){ List<String> l = new ArrayList(); l.addAll(STRING_METRICS.keySet()); return l; } }
2,563
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimilarityWordConfigurationDialog.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/word/SimilarityWordConfigurationDialog.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.word; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.List; import javax.swing.DefaultComboBoxModel; import javax.swing.JDialog; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import javax.swing.text.DocumentFilter; import javax.swing.text.PlainDocument; import org.wandora.application.Wandora; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.simple.SimpleButton; import org.wandora.application.gui.simple.SimpleCheckBox; /** * * @author Eero Lehtonen */ class SimilarityWordConfigurationDialog extends javax.swing.JPanel { private static final long serialVersionUID = 1L; private Wandora wandora = null; private boolean wasAccepted = false; private JDialog myDialog = null; private SimilarityWordConfiguration config; private SimilarityWordConfiguration newConfig; private static final float THRESHOLD_RESOLUTION = 100f; protected boolean wasAccepted() { return wasAccepted; } public SimilarityWordConfigurationDialog(Wandora w) { wandora = w; initComponents(); } public void openDialog(SimilarityWordConfiguration c) { wasAccepted = false; if (myDialog == null) { myDialog = new JDialog(wandora, true); myDialog.add(this); myDialog.setSize(330, 310); myDialog.setTitle("Word Similarity Extractor Configuration"); UIBox.centerWindow(myDialog, wandora); } newConfig = (c != null) ? c : new SimilarityWordConfiguration(); toggleCaseSensitive.setSelected(newConfig.getCaseSensitive()); toggleBaseName.setSelected(newConfig.getBaseName()); toggleVariantName.setSelected(newConfig.getVariantName()); toggleInstanceData.setSelected(newConfig.getInstanceData()); PlainDocument thresholdDocument = (PlainDocument)thresholdDisplay.getDocument(); thresholdDocument.setDocumentFilter(new ThresholdFilter()); thresholdDisplay.setValue(newConfig.getThreshold()); thresholdDisplay.addPropertyChangeListener(new PropertyChangeListener(){ @Override public void propertyChange(PropertyChangeEvent evt) { float displayValue; try { displayValue = (float)thresholdDisplay.getValue(); } catch (ClassCastException cce) { displayValue = ((Double)thresholdDisplay.getValue()).floatValue(); } int newVal = Math.round(displayValue*THRESHOLD_RESOLUTION); if(newVal != thresholdSlider.getValue()) thresholdSlider.setValue(newVal); } }); thresholdSlider.setMinimum(0); thresholdSlider.setMaximum(Math.round(THRESHOLD_RESOLUTION)); thresholdSlider.addChangeListener(new ChangeListener(){ @Override public void stateChanged(ChangeEvent e) { float newVal = thresholdSlider.getValue()/THRESHOLD_RESOLUTION; float displayValue; try { displayValue = (float)thresholdDisplay.getValue(); } catch (ClassCastException cce) { displayValue = ((Double)thresholdDisplay.getValue()).floatValue(); } if(newVal != displayValue) thresholdDisplay.setValue(thresholdSlider.getValue()/THRESHOLD_RESOLUTION); } }); List<String> MetricNameList = newConfig.getSTringMetricNames(); String[] metricNameArray = new String[MetricNameList.size()]; metrics.setModel(new DefaultComboBoxModel(MetricNameList.toArray(metricNameArray))); myDialog.setVisible(true); } class ThresholdFilter extends DocumentFilter{ private boolean test(String s){ try { float f = Float.parseFloat(s); return (f >= 0 && f <= 1); } catch (NumberFormatException e) { System.out.println(s); return false; } } @Override public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException { Document doc = fb.getDocument(); StringBuilder sb = new StringBuilder(); sb.append(doc.getText(0, doc.getLength())); sb.insert(offset, string); if(test(sb.toString())){ super.insertString(fb, offset, string, attr); } } @Override public void replace(FilterBypass fb, int offset, int length, String string, AttributeSet attr) throws BadLocationException { Document doc = fb.getDocument(); StringBuilder sb = new StringBuilder(); sb.append(doc.getText(0, doc.getLength())); sb.replace(offset, offset+length, string); if(test(sb.toString())){ super.replace(fb, offset, length, string, attr); } } @Override public void remove(FilterBypass fb, int offset, int length) throws BadLocationException { Document doc = fb.getDocument(); StringBuilder sb = new StringBuilder(); sb.append(doc.getText(0, doc.getLength())); sb.delete(offset, offset+length); if(test(sb.toString())){ super.remove(fb, offset, length); } } } private void saveConfiguration() { if (newConfig == null) { newConfig = new SimilarityWordConfiguration(); } newConfig.setCaseSensitive(toggleCaseSensitive.isSelected()); newConfig.setBaseName(toggleBaseName.isSelected()); newConfig.setVariantName(toggleVariantName.isSelected()); newConfig.setInstanceData(toggleInstanceData.isSelected()); float displayValue; try { displayValue = (float)thresholdDisplay.getValue(); } catch (ClassCastException cce) { displayValue = ((Double)thresholdDisplay.getValue()).floatValue(); } newConfig.setThreshold(displayValue); config = newConfig; } protected SimilarityWordConfiguration getConfiguration() { return config; } ; /** * 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; container = new javax.swing.JPanel(); toggleCaseSensitive = new SimpleCheckBox(); toggleBaseName = new SimpleCheckBox(); toggleVariantName = new SimpleCheckBox(); toggleInstanceData = new SimpleCheckBox(); metrics = new javax.swing.JComboBox(); metricsLabel = new javax.swing.JLabel(); thresholdSlider = new javax.swing.JSlider(); thresholdLabel = new javax.swing.JLabel(); thresholdDisplay = new javax.swing.JFormattedTextField(); submit = new SimpleButton(); cancel = new SimpleButton(); setLayout(new java.awt.GridBagLayout()); container.setLayout(new java.awt.GridBagLayout()); toggleCaseSensitive.setText("Case sensitive"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; container.add(toggleCaseSensitive, gridBagConstraints); toggleBaseName.setText("Base Name"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.gridwidth = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; container.add(toggleBaseName, gridBagConstraints); toggleVariantName.setText("Variant Name"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.gridwidth = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; container.add(toggleVariantName, gridBagConstraints); toggleInstanceData.setText("Instance Data"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 5; gridBagConstraints.gridwidth = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; container.add(toggleInstanceData, gridBagConstraints); metrics.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 0.2; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); container.add(metrics, gridBagConstraints); metricsLabel.setText("Similarity metric"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; gridBagConstraints.insets = new java.awt.Insets(4, 4, 0, 4); container.add(metricsLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 0.3; gridBagConstraints.insets = new java.awt.Insets(1, 0, 1, 0); container.add(thresholdSlider, gridBagConstraints); thresholdLabel.setText("Threshold"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; gridBagConstraints.insets = new java.awt.Insets(4, 4, 0, 4); container.add(thresholdLabel, gridBagConstraints); thresholdDisplay.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter())); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 0.1; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); container.add(thresholdDisplay, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 0.1; gridBagConstraints.weighty = 0.1; add(container, gridBagConstraints); submit.setText("OK"); submit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { submitActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; gridBagConstraints.weightx = 0.1; gridBagConstraints.insets = new java.awt.Insets(0, 0, 4, 4); add(submit, gridBagConstraints); cancel.setText("Cancel"); cancel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; gridBagConstraints.insets = new java.awt.Insets(0, 0, 4, 4); add(cancel, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents private void cancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelActionPerformed wasAccepted = false; if (myDialog != null) { myDialog.setVisible(false); } }//GEN-LAST:event_cancelActionPerformed private void submitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_submitActionPerformed wasAccepted = true; saveConfiguration(); if (myDialog != null) { myDialog.setVisible(false); } }//GEN-LAST:event_submitActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton cancel; private javax.swing.JPanel container; private javax.swing.JComboBox metrics; private javax.swing.JLabel metricsLabel; private javax.swing.JButton submit; private javax.swing.JFormattedTextField thresholdDisplay; private javax.swing.JLabel thresholdLabel; private javax.swing.JSlider thresholdSlider; private javax.swing.JCheckBox toggleBaseName; private javax.swing.JCheckBox toggleCaseSensitive; private javax.swing.JCheckBox toggleInstanceData; private javax.swing.JCheckBox toggleVariantName; // End of variables declaration//GEN-END:variables }
15,360
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DefinitionListExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/list/DefinitionListExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.list; 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.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Stack; import javax.swing.Icon; import javax.swing.text.MutableAttributeSet; import javax.swing.text.html.HTML; import javax.swing.text.html.HTMLDocument; import javax.swing.text.html.HTMLEditorKit; import org.w3c.tidy.Tidy; import org.wandora.application.WandoraTool; import org.wandora.application.gui.UIBox; import org.wandora.application.tools.browserextractors.BrowserPluginExtractor; import org.wandora.application.tools.extractors.AbstractExtractor; import org.wandora.application.tools.extractors.ExtractHelper; import org.wandora.topicmap.Locator; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicTools; import org.wandora.topicmap.XTMPSI; import org.wandora.utils.IObox; /** * <p> * Tool reads a HTML fragment with definition lists defined with * DL, DT and DD elements and creates topics and occurrences with * extracted information. * </p> * <p> * Extractor creates a topic for each faced definition list title (DT) * and adds following definitions (DD) as an occurrence to the previous * title topic. If there is multiple sequential definitions (multiple DD elements) following * the title, Wandora adds multiple numbered occurrences to the title * topic. If there is multiple sequential definition titles (multiple DT * elements), Wandora adds following definition occurrences to all these * title topics. * </p> * @author akivela */ public class DefinitionListExtractor extends AbstractExtractor implements WandoraTool, BrowserPluginExtractor { private static final long serialVersionUID = 1L; @Override public String getName() { return "HTML definition list extractor"; } @Override public String getDescription() { return "Converts HTML lists to instance relations with definition occurrences."; } @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(0xf121); } // ------------------------------------------------------------------------- @Override public boolean _extractTopicsFrom(URL url, TopicMap topicMap) throws Exception { return _extractTopicsFrom(url.openStream(),topicMap); } @Override public boolean _extractTopicsFrom(File file, TopicMap topicMap) throws Exception { return _extractTopicsFrom(new FileInputStream(file),topicMap); } @Override public boolean _extractTopicsFrom(String str, TopicMap topicMap) throws Exception { return _extractTopicsFrom(new ByteArrayInputStream(str.getBytes()), topicMap); } public boolean _extractTopicsFrom(InputStream in, TopicMap topicMap) throws Exception { Tidy tidy = null; String tidyHTML = null; try { Properties tidyProps = new Properties(); tidyProps.put("trim-empty-elements", "no"); tidy = new Tidy(); tidy.setConfigurationFromProps(tidyProps); tidy.setXmlOut(false); tidy.setXmlPi(false); tidy.setTidyMark(false); ByteArrayOutputStream tidyOutput = null; tidyOutput = new ByteArrayOutputStream(); tidy.parse(in, tidyOutput); tidyHTML = 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(tidyHTML == null) { log("Trying to read HTML without preprocessing!"); tidyHTML = IObox.loadFile(new InputStreamReader(in)); } HTMLDocument htmlDoc = new HTMLDocument(); HTMLEditorKit.Parser parser = new HTMLParse().getParser(); htmlDoc.setParser(parser); DefinitionListParseListener parserListener = new DefinitionListParseListener(topicMap, this); parser.parse(new InputStreamReader(new ByteArrayInputStream(tidyHTML.getBytes())), parserListener, true); parserListener.processCapturedData(); log("Total " + parserListener.progress + " definitions created!"); setState(WAIT); return true; } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- private static class HTMLParse extends HTMLEditorKit { private static final long serialVersionUID = 1L; /** * Call to obtain a HTMLEditorKit.Parser object. * @return A new HTMLEditorKit.Parser object. */ @Override public HTMLEditorKit.Parser getParser() { HTMLEditorKit.Parser parser = super.getParser(); return parser; } } // ------------------------------------------------------------------------- private class DefinitionListParseListener extends HTMLEditorKit.ParserCallback { public int progress = 0; public static final String SI_PREFIX = "http://wandora.org/si/list/"; private TopicMap tm; private DefinitionListExtractor parent; private int previousStartState=STATE_OTHER; private int state=STATE_OTHER; private static final int STATE_OTHER=9999; private static final int STATE_DL=0; private static final int STATE_DT=1; private static final int STATE_DD=2; private String currentName; private String currentUrl; private String currentDefinition; private Map<String,String> currentUrls; private List<String> currentNames; private List<String> currentDefinitions; private Topic currentTopic; private Topic parentTopic; private Topic definitionTypeTopic; private Topic definitionScopeTopic; private Stack<Integer> stateStack; private Stack<Topic> parentTopics; // ------------------------------------------------------------------------- public DefinitionListParseListener(TopicMap tm, DefinitionListExtractor parent) { this.tm=tm; this.parent=parent; currentDefinition = null; currentName = null; currentUrl = null; currentNames = new ArrayList<String>(); currentUrls = new HashMap<String,String>(); currentDefinitions = new ArrayList<String>(); definitionTypeTopic = null; definitionScopeTopic = null; stateStack = new Stack<>(); parentTopics = new Stack<>(); parentTopic = null; try { Topic listRoot = createTopic(tm, SI_PREFIX, "List"); Topic wandoraClass = createTopic(tm, TMBox.WANDORACLASS_SI, "Wandora Class"); ExtractHelper.makeSubclassOf(listRoot, wandoraClass, tm); long stamp = System.currentTimeMillis(); parentTopic = createTopic(tm, SI_PREFIX + "list-"+stamp, "List-"+stamp); parentTopic.addType(listRoot); currentTopic = parentTopic; } catch(Exception e) { } } // ------------------------------------------------------------------------- @Override public void handleStartTag(HTML.Tag t,MutableAttributeSet a,int pos) { if(t == HTML.Tag.DL) { processCapturedData(); previousStartState = STATE_DL; stateStack.push(Integer.valueOf(state)); state = STATE_DL; } else if(t == HTML.Tag.DT) { if(currentName != null) { currentNames.add(currentName); if(currentUrl != null) { currentUrls.put(currentName, currentUrl); currentUrl = null; } currentName = null; } if(previousStartState == STATE_DD) { processCapturedData(); } previousStartState = STATE_DT; stateStack.push(Integer.valueOf(state)); state = STATE_DT; } else if(t == HTML.Tag.DD) { if(currentDefinition != null) { currentDefinitions.add(currentDefinition); currentDefinition = null; } previousStartState = STATE_DD; stateStack.push(Integer.valueOf(state)); state = STATE_DD; } else if(t == HTML.Tag.A) { if(state == STATE_DT) { try { currentUrl = (String) a.getAttribute(HTML.Attribute.HREF); } catch(Exception e) { // IGNORE } } } } @Override public void handleEndTag(HTML.Tag t,int pos) { if(t == HTML.Tag.DL) { processCapturedData(); popState(); } else if(t == HTML.Tag.DT) { popState(); } else if(t == HTML.Tag.DD) { popState(); } } @Override public void handleSimpleTag(HTML.Tag t,MutableAttributeSet a,int pos) { } @Override public void handleText(char[] data,int pos) { switch(state) { case STATE_DT: { if(currentName == null) currentName = ""; currentName = currentName + new String(data); break; } case STATE_DD: { if(currentDefinition == null) currentDefinition = ""; currentDefinition = currentDefinition + new String(data); break; } } } @Override public void handleError(String errorMsg,int pos) { System.out.println("DefinitionListExtractor: " + errorMsg); } // -------------------- public void processCapturedData() { if(currentName != null) { currentNames.add(currentName); if(currentUrl != null) { currentUrls.put(currentName, currentUrl); currentUrl = null; } currentName = null; } if(currentDefinition != null) { currentDefinitions.add(currentDefinition); currentDefinition = null; } if(currentNames.size() > 0) { for(Iterator<String> names = currentNames.iterator(); names.hasNext(); ) { currentName = names.next(); if(currentName == null) continue; currentName = currentName.trim(); if(currentName.length() > 0) { try { // MAKE TOPIC FOR CURRENT TOPIC NAME AND ASSOCIATE NEW TOPIC TO PARENT currentTopic = createTopic(tm, SI_PREFIX + currentName, currentName); currentUrl = currentUrls.get(currentName); if(currentUrl != null) { if(currentUrl.startsWith("http://") || currentUrl.startsWith("https://") || currentUrl.startsWith("ftp://") || currentUrl.startsWith("ftps://") || currentUrl.startsWith("mailto://")) { try { currentTopic.addSubjectIdentifier(new Locator(currentUrl)); } catch(Exception e) { log(e); } } currentUrl = null; } if(parentTopic != null) { currentTopic.addType(parentTopic); } if(currentDefinitions.size() > 0) { int defcount = 0; String definitionType = null; for(Iterator<String> definitions=currentDefinitions.iterator(); definitions.hasNext();) { currentDefinition = definitions.next(); if(currentDefinition != null) { currentDefinition = currentDefinition.trim(); if(currentDefinition.length() > 0) { definitionType = "Definition" + ( defcount>0 ? " "+(1+defcount) : "" ); definitionTypeTopic = createTopic(tm, SI_PREFIX + definitionType, definitionType); if(definitionScopeTopic == null) definitionScopeTopic = createTopic(tm, XTMPSI.getLang("en"), "Language EN"); currentTopic.setData(definitionTypeTopic, definitionScopeTopic, currentDefinition); log("Creating definition "+( defcount>0 ? "("+(1+defcount)+") " : "" )+"occurrence for '"+getTopicName(currentTopic)+"'."); progress++; defcount++; } } } } } catch(Exception e) { log(e); } } } } currentName = null; currentDefinition = null; currentUrl = null; currentNames = new ArrayList<String>(); currentDefinitions = new ArrayList<String>(); currentUrls = new LinkedHashMap<String,String>(); } private void popStateAndParent() { popState(); popParent(); } private void popState() { if(!stateStack.empty()) { state = ((Integer) stateStack.pop()).intValue(); } else { state = STATE_OTHER; } } private void popParent() { currentTopic = parentTopic; if(!parentTopics.empty()) { parentTopic = (Topic) parentTopics.pop(); } else { parentTopic = null; } } 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; } } }
18,442
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
JsoupDefinitionListExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/list/JsoupDefinitionListExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.list; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.wandora.application.WandoraTool; import org.wandora.application.tools.browserextractors.BrowserPluginExtractor; import org.wandora.application.tools.extractors.AbstractJsoupExtractor; import org.wandora.topicmap.Association; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author Eero */ public class JsoupDefinitionListExtractor extends AbstractJsoupExtractor implements WandoraTool, BrowserPluginExtractor { private static final long serialVersionUID = 1L; public static final String SI_PREFIX = "http://wandora.org/si/"; public static final String LIST_SI = SI_PREFIX + "list/"; public static final String DOCUMENT_SI = SI_PREFIX + "document/"; public static final String NAME_SI = SI_PREFIX + "name/"; public static final String DEF_SI = SI_PREFIX + "definition/"; public static final String CHILD_SI = SI_PREFIX + "child/"; public static final String PARENT_SI = SI_PREFIX + "parent/"; public static final String RELATION_SI = SI_PREFIX + "relation/"; private TopicMap tm; private Topic wandoraClass; private Topic documentTopic; private Topic langTopic; private Topic documentType; private Topic listType; private Topic definitionType; private Topic childType; private Topic parentType; private Topic relationType; //Catch all @Override public boolean extractTopicsFrom(Document d, String u, TopicMap t) throws Exception{ Elements lists = d.select("dl"); if(lists.isEmpty()) throw new Exception("No definition lists found!"); //Basic init this.tm = t; this.wandoraClass = getWandoraClassTopic(tm); this.langTopic = getLangTopic(tm); this.childType = getOrCreateTopic(tm, CHILD_SI, "child"); this.parentType = getOrCreateTopic(tm, PARENT_SI, "parent"); this.relationType = getOrCreateTopic(tm, RELATION_SI, "relationship"); this.documentType = getOrCreateTopic(tm, DOCUMENT_SI, "document"); makeSubclassOf(tm, documentType, wandoraClass); this.listType = getOrCreateTopic(tm, LIST_SI, "list"); makeSubclassOf(tm, listType, wandoraClass); this.definitionType = getOrCreateTopic(tm, DEF_SI, "definition"); makeSubclassOf(tm, definitionType, wandoraClass); this.documentTopic = getOrCreateTopic(tm, u , d.title()); documentTopic.addType(documentType); for(Element list: lists) parseList(list, documentTopic); return true; } private void parseList(Element list, Topic documentTopic) throws TopicMapException { Topic listTopic = getOrCreateTopic(tm, null); listTopic.addType(getOrCreateTopic(tm, LIST_SI)); declareChild(documentTopic, listTopic); Elements names = list.select("dt"); for(Element name: names) parseName(name,listTopic); } private void parseName(Element name, Topic listTopic) throws TopicMapException { Topic nameTopic = getOrCreateTopic(tm, null, name.text()); nameTopic.addType(definitionType); declareChild(listTopic, nameTopic); Element defCandidate = name.nextElementSibling(); while(defCandidate != null && defCandidate.tagName().equals("dd")){ nameTopic.setData(definitionType, langTopic, defCandidate.text()); defCandidate = defCandidate.nextElementSibling(); } } //-------------------------------------------------------------------------- void declareChild(Topic parent, Topic child) throws TopicMapException{ Association a = tm.createAssociation(relationType); a.addPlayer(parent, parentType); a.addPlayer(child, childType); } }
5,004
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SuperSubClassListExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/list/SuperSubClassListExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.list; 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.net.URLEncoder; import java.util.Properties; import java.util.Stack; import javax.swing.Icon; import javax.swing.text.MutableAttributeSet; import javax.swing.text.html.HTML; import javax.swing.text.html.HTMLDocument; import javax.swing.text.html.HTMLEditorKit; import org.w3c.tidy.Tidy; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.gui.UIBox; import org.wandora.application.tools.browserextractors.BrowserExtractRequest; import org.wandora.application.tools.browserextractors.BrowserPluginExtractor; 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; import org.wandora.utils.IObox; /** * <p> * Reads HTML document or HTML fragment and converts included HTML list structure * to a Topic Map. A topic is created for each list element (content of LI element). * Created topic is associated to outer list element with super-subclass * association. Outer element is considered as a superclass. As an example * consider simple list: * </p> * * <ul> * <li>Mammal</li> * <ul> * <li>Cat</li> * <li>Horse</li> * <li>Pig</li> * </ul> * <li>Bird</li> * <ul> * <li>Parrot</li> * <li>Duck<li> * </ul> * </ul> * * @author akivela */ public class SuperSubClassListExtractor extends AbstractExtractor implements WandoraTool, BrowserPluginExtractor { private static final long serialVersionUID = 1L; private URL basePath = null; private static int listCounter = 0; @Override public String getName() { return "HTML super-subclass list extractor"; } @Override public String getDescription() { return "Converts HTML lists to super-subclass 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(0xf121); } @Override public String doBrowserExtract(BrowserExtractRequest request, Wandora wandora) throws TopicMapException { try { basePath = new URL(request.getSource()); } catch(Exception e) { e.printStackTrace(); } String s = super.doBrowserExtract(request, wandora); basePath = null; return s; } @Override public boolean _extractTopicsFrom(URL url, TopicMap topicMap) throws Exception { basePath = url; boolean r = _extractTopicsFrom(url.openStream(),topicMap); basePath = null; return r; } @Override public boolean _extractTopicsFrom(File file, TopicMap topicMap) throws Exception { basePath = file.toURI().toURL(); boolean r = _extractTopicsFrom(new FileInputStream(file),topicMap); basePath = null; return r; } @Override public boolean _extractTopicsFrom(String str, TopicMap topicMap) throws Exception { return _extractTopicsFrom(new ByteArrayInputStream(str.getBytes()), topicMap); } public boolean _extractTopicsFrom(InputStream in, TopicMap topicMap) throws Exception { Tidy tidy = null; String tidyHTML = null; try { Properties tidyProps = new Properties(); tidyProps.put("trim-empty-elements", "no"); tidy = new Tidy(); tidy.setConfigurationFromProps(tidyProps); tidy.setXmlOut(false); tidy.setXmlPi(false); tidy.setTidyMark(false); ByteArrayOutputStream tidyOutput = null; tidyOutput = new ByteArrayOutputStream(); tidy.parse(in, tidyOutput); tidyHTML = 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(tidyHTML == null) { log("Trying to read HTML without preprocessing!"); tidyHTML = IObox.loadFile(new InputStreamReader(in)); } HTMLDocument htmlDoc = new HTMLDocument(); HTMLEditorKit.Parser parser = new HTMLParse().getParser(); htmlDoc.setParser(parser); ListParseListener parserListener = new ListParseListener(topicMap, this); parser.parse(new InputStreamReader(new ByteArrayInputStream(tidyHTML.getBytes())), parserListener, true); log("Total " + parserListener.progress + " super-subclass associations created!"); setState(WAIT); return true; } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- private static class HTMLParse extends HTMLEditorKit { private static final long serialVersionUID = 1L; /** * Call to obtain a HTMLEditorKit.Parser object. * @return A new HTMLEditorKit.Parser object. */ @Override public HTMLEditorKit.Parser getParser() { HTMLEditorKit.Parser parser = super.getParser(); return parser; } } // ------------------------------------------------------------------------- private class ListParseListener extends HTMLEditorKit.ParserCallback { public int progress = 0; public static final String SI_PREFIX = "http://wandora.org/si/list/"; private TopicMap tm; private SuperSubClassListExtractor parent; private int state=STATE_OTHER; private static final int STATE_OTHER=9999; private static final int STATE_UL=0; private static final int STATE_OL=1; private static final int STATE_LI=2; private String currentTopicUrl; private String currentTopicName; private Topic currentTopic; private Topic parentTopic; private String listId; private Stack<Integer> stateStack; private Stack<Topic> parentTopics; private Topic listRoot = null; // --------------------------------------------------------------------- public ListParseListener(TopicMap tm, SuperSubClassListExtractor parent) { this.tm=tm; this.parent=parent; currentTopicName = null; currentTopicUrl = null; stateStack = new Stack<>(); parentTopics = new Stack<>(); parentTopic = null; currentTopic = null; listId = null; try { listRoot = createTopic(tm, SI_PREFIX, "List"); Topic wandoraClass = createTopic(tm, TMBox.WANDORACLASS_SI, "Wandora Class"); ExtractHelper.makeSubclassOf(listRoot, wandoraClass, tm); } catch(Exception e) { e.printStackTrace(); } } // ------------------------------------------------------------------------- @Override public void handleStartTag(HTML.Tag t, MutableAttributeSet a, int pos) { if(t == HTML.Tag.UL) { if(parentTopic != null) { parentTopics.push(parentTopic); } try { if(state != STATE_OTHER && currentTopic != null) { processCapturedData(); parentTopic = currentTopic; parentTopic.addType(listRoot); } else { parentTopic = createListTopic(); } } catch(Exception e) {} stateStack.push(Integer.valueOf(state)); state = STATE_UL; } else if(t == HTML.Tag.OL) { if(parentTopic != null) { parentTopics.push(parentTopic); } try { if(state != STATE_OTHER && currentTopic != null) { processCapturedData(); parentTopic = currentTopic; parentTopic.addType(listRoot); } else { parentTopic = createListTopic(); } } catch(Exception e) {} stateStack.push(Integer.valueOf(state)); state = STATE_OL; } else if(t == HTML.Tag.LI) { if(parentTopic == null) { parentTopic = createListTopic(); } currentTopicUrl = null; stateStack.push(Integer.valueOf(state)); state = STATE_LI; } else if(t == HTML.Tag.A) { try { currentTopicUrl = (String) a.getAttribute(HTML.Attribute.HREF); } catch(Exception e) { // IGNORE } } } @Override public void handleEndTag(HTML.Tag t,int pos) { if(t == HTML.Tag.LI) { processCapturedData(); popState(); } else if(t == HTML.Tag.UL) { popState(); popParent(); } else if(t == HTML.Tag.OL) { popState(); popParent(); } } @Override public void handleSimpleTag(HTML.Tag t, MutableAttributeSet a, int pos) { } @Override public void handleText(char[] data, int pos) { switch(state) { case STATE_LI: { if(currentTopicName == null) currentTopicName = ""; currentTopicName = currentTopicName + new String(data); break; } } } @Override public void handleError(String errorMsg,int pos) { // System.out.println("InstanceListExtractor: " + errorMsg); } // --------------------------------------------------------------------- private Topic createListTopic() { Topic t = null; try { long stamp = System.currentTimeMillis(); listCounter++; t = createTopic(tm, SI_PREFIX+"list-"+stamp+"-"+listCounter, "List-"+stamp+"-"+listCounter); t.addType(listRoot); } catch(Exception e) { e.printStackTrace(); } return t; } private void processCapturedData() { if(currentTopicName != null) { currentTopicName = currentTopicName.trim(); if(currentTopicName.length() > 0) { try { // MAKE TOPIC FOR CURRENT TOPIC NAME AND ASSOCIATE NEW TOPIC TO PARENT currentTopic = createListItemTopic(tm, getSubjectForListItem(), currentTopicName); if(parentTopic != null) { Topic subTypeTopic = createTopic(tm, XTMPSI.SUBCLASS, "Subclass"); Topic superTypeTopic = createTopic(tm, XTMPSI.SUPERCLASS, "Superclass"); Topic supersubTypeTopic = createTopic(tm, XTMPSI.SUPERCLASS_SUBCLASS, "Superclass-Subclass"); Association supersubAssociation = tm.createAssociation(supersubTypeTopic); supersubAssociation.addPlayer(parentTopic, superTypeTopic); supersubAssociation.addPlayer(currentTopic, subTypeTopic); log("Creating super-subclass association '"+getTopicName(parentTopic)+"' > '"+getTopicName(currentTopic)+"'."); progress++; } } catch(Exception e) { log(e); } currentTopicName = null; currentTopicUrl = null; } } } private String getSubjectForListItem() { if(currentTopicUrl != null) { if(currentTopicUrl.startsWith("http:") || currentTopicUrl.startsWith("https:") || currentTopicUrl.startsWith("ftp:") || currentTopicUrl.startsWith("ftps:")) { return currentTopicUrl; } if(basePath != null) { if(currentTopicUrl.startsWith("/")) { return basePath.toExternalForm().substring(0, basePath.toExternalForm().indexOf(basePath.getPath()))+currentTopicUrl; } return basePath.toExternalForm() + currentTopicUrl; } if(SI_PREFIX.endsWith("/") && currentTopicUrl.startsWith("/")) { currentTopicUrl = currentTopicUrl.substring(1); } return SI_PREFIX + "item/" + currentTopicUrl; } String subjectPath = currentTopicName; if(subjectPath.length() > 50) { subjectPath = subjectPath.substring(0,50); subjectPath = subjectPath + "-" + currentTopicName.hashCode(); } try { return SI_PREFIX + "item/" + URLEncoder.encode(subjectPath, "UTF-8"); } catch(Exception e) { return SI_PREFIX + "item/" + subjectPath; } } private void popState() { if(!stateStack.empty()) { state = ((Integer) stateStack.pop()).intValue(); } else { state = STATE_OTHER; } } private void popParent() { currentTopic = parentTopic; if(!parentTopics.empty()) { parentTopic = (Topic) parentTopics.pop(); } else { parentTopic = null; } } public Topic createListItemTopic(TopicMap topicMap, String si, String listItem) throws TopicMapException { Topic t = createTopic(topicMap, si, listItem, null); try { Topic occurrenceType = topicMap.createTopic(); occurrenceType.addSubjectIdentifier(new Locator(SI_PREFIX + "item-text")); occurrenceType.setBaseName("List item text"); Topic lang = topicMap.getTopic(XTMPSI.LANG_INDEPENDENT); if(lang == null) lang = topicMap.getTopic(XTMPSI.getLang("en")); if(lang != null) { t.setData(occurrenceType, lang, listItem); } } catch(Exception e) {} return t; } 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) { if(baseName.length() > 512) baseName = baseName.substring(0, 509) + "..."; 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) { log("Failed to create topic for a basename '"+baseName+"' and a subject '"+si+"'."); } return t; } } }
18,740
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
InstanceListExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/list/InstanceListExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.list; 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.net.URLEncoder; import java.util.Properties; import java.util.Stack; import javax.swing.Icon; import javax.swing.text.MutableAttributeSet; import javax.swing.text.html.HTML; import javax.swing.text.html.HTMLDocument; import javax.swing.text.html.HTMLEditorKit; import org.w3c.tidy.Tidy; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.gui.UIBox; import org.wandora.application.tools.browserextractors.BrowserExtractRequest; import org.wandora.application.tools.browserextractors.BrowserPluginExtractor; import org.wandora.application.tools.extractors.AbstractExtractor; import org.wandora.application.tools.extractors.ExtractHelper; import org.wandora.topicmap.Locator; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicTools; import org.wandora.topicmap.XTMPSI; import org.wandora.utils.IObox; /** /** * <p> * Reads HTML document or HTML fragment and converts included HTML list structure * to a Topic Map. A topic is created for each list element (content of LI element). * Created topic is related to outer list element with instance-of relation. * Outer element is considered as a type. As an example consider simple list: * </p> * * <ul> * <li>Movies</li> * <ul> * <li>Blade Runner</li> * <li>2001: A Space Odyssey</li> * <li>Spaceballs</li> * </ul> * <li>Directors</li> * <ul> * <li>Ridley Scott</li> * <li>Stanley Kubrick<li> * <li>Mel Brooks<li> * </ul> * </ul> * * @author akivela */ public class InstanceListExtractor extends AbstractExtractor implements WandoraTool, BrowserPluginExtractor { private static final long serialVersionUID = 1L; private URL basePath = null; private static int listCounter = 0; @Override public String getName() { return "HTML instance list extractor"; } @Override public String getDescription() { return "Converts HTML lists to instance relations."; } @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(0xf121); } @Override public String doBrowserExtract(BrowserExtractRequest request, Wandora wandora) throws TopicMapException { try { basePath = new URL(request.getSource()); } catch(Exception e) { e.printStackTrace(); } String s = super.doBrowserExtract(request, wandora); basePath = null; return s; } @Override public boolean _extractTopicsFrom(URL url, TopicMap topicMap) throws Exception { basePath = url; boolean r = _extractTopicsFrom(url.openStream(),topicMap); basePath = null; return r; } @Override public boolean _extractTopicsFrom(File file, TopicMap topicMap) throws Exception { basePath = file.toURI().toURL(); boolean r = _extractTopicsFrom(new FileInputStream(file),topicMap); basePath = null; return r; } @Override public boolean _extractTopicsFrom(String str, TopicMap topicMap) throws Exception { return _extractTopicsFrom(new ByteArrayInputStream(str.getBytes()), topicMap); } public boolean _extractTopicsFrom(InputStream in, TopicMap topicMap) throws Exception { Tidy tidy = null; String tidyHTML = null; try { Properties tidyProps = new Properties(); tidyProps.put("trim-empty-elements", "no"); tidy = new Tidy(); tidy.setConfigurationFromProps(tidyProps); tidy.setXmlOut(false); tidy.setXmlPi(false); tidy.setTidyMark(false); ByteArrayOutputStream tidyOutput = null; tidyOutput = new ByteArrayOutputStream(); tidy.parse(in, tidyOutput); tidyHTML = 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(tidyHTML == null) { log("Trying to read HTML without preprocessing!"); tidyHTML = IObox.loadFile(new InputStreamReader(in)); } HTMLDocument htmlDoc = new HTMLDocument(); HTMLEditorKit.Parser parser = new HTMLParse().getParser(); htmlDoc.setParser(parser); ListParseListener parserListener = new ListParseListener(topicMap, this); parser.parse(new InputStreamReader(new ByteArrayInputStream(tidyHTML.getBytes())), parserListener, true); log("Total " + parserListener.progress + " instance relations created!"); setState(WAIT); basePath = null; return true; } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- private static class HTMLParse extends HTMLEditorKit { private static final long serialVersionUID = 1L; /** * Call to obtain a HTMLEditorKit.Parser object. * @return A new HTMLEditorKit.Parser object. */ @Override public HTMLEditorKit.Parser getParser() { HTMLEditorKit.Parser parser = super.getParser(); return parser; } } // ------------------------------------------------------------------------- private class ListParseListener extends HTMLEditorKit.ParserCallback { public int progress = 0; public static final String SI_PREFIX = "http://wandora.org/si/list/"; private TopicMap tm; private InstanceListExtractor parent; private int state=STATE_OTHER; private static final int STATE_OTHER=9999; private static final int STATE_UL=0; private static final int STATE_OL=1; private static final int STATE_LI=2; private String currentTopicUrl; private String currentTopicName; private Topic currentTopic; private Topic parentTopic; private String listId; private Stack<Integer> stateStack; private Stack<Topic> parentTopics; private Topic listRoot = null; // --------------------------------------------------------------------- public ListParseListener(TopicMap tm, InstanceListExtractor parent) { this.tm=tm; this.parent=parent; currentTopicName = null; currentTopicUrl = null; stateStack = new Stack<>(); parentTopics = new Stack<>(); parentTopic = null; currentTopic = null; listId = null; try { listRoot = createTopic(tm, SI_PREFIX, "List"); Topic wandoraClass = createTopic(tm, TMBox.WANDORACLASS_SI, "Wandora Class"); ExtractHelper.makeSubclassOf(listRoot, wandoraClass, tm); } catch(Exception e) { e.printStackTrace(); } } // ------------------------------------------------------------------------- @Override public void handleStartTag(HTML.Tag t, MutableAttributeSet a, int pos) { if(t == HTML.Tag.UL) { if(parentTopic != null) { parentTopics.push(parentTopic); } try { if(state != STATE_OTHER && currentTopic != null) { processCapturedData(); parentTopic = currentTopic; parentTopic.addType(listRoot); } else { parentTopic = createListTopic(); } } catch(Exception e) {} stateStack.push(Integer.valueOf(state)); state = STATE_UL; } else if(t == HTML.Tag.OL) { if(parentTopic != null) { parentTopics.push(parentTopic); } try { if(state != STATE_OTHER && currentTopic != null) { processCapturedData(); parentTopic = currentTopic; parentTopic.addType(listRoot); } else { parentTopic = createListTopic(); } } catch(Exception e) {} stateStack.push(Integer.valueOf(state)); state = STATE_OL; } else if(t == HTML.Tag.LI) { if(parentTopic == null) { parentTopic = createListTopic(); } currentTopicUrl = null; stateStack.push(Integer.valueOf(state)); state = STATE_LI; } else if(t == HTML.Tag.A) { try { currentTopicUrl = (String) a.getAttribute(HTML.Attribute.HREF); } catch(Exception e) { // IGNORE } } } @Override public void handleEndTag(HTML.Tag t,int pos) { if(t == HTML.Tag.LI) { processCapturedData(); popState(); } else if(t == HTML.Tag.UL) { popState(); popParent(); } else if(t == HTML.Tag.OL) { popState(); popParent(); } } @Override public void handleSimpleTag(HTML.Tag t, MutableAttributeSet a, int pos) { } @Override public void handleText(char[] data, int pos) { switch(state) { case STATE_LI: { if(currentTopicName == null) currentTopicName = ""; currentTopicName = currentTopicName + new String(data); break; } } } @Override public void handleError(String errorMsg,int pos) { // System.out.println("InstanceListExtractor: " + errorMsg); } // --------------------------------------------------------------------- private Topic createListTopic() { Topic t = null; try { long stamp = System.currentTimeMillis(); listCounter++; t = createTopic(tm, SI_PREFIX+"list-"+stamp+"-"+listCounter, "List-"+stamp+"-"+listCounter); t.addType(listRoot); } catch(Exception e) { e.printStackTrace(); } return t; } private void processCapturedData() { if(currentTopicName != null) { currentTopicName = currentTopicName.trim(); if(currentTopicName.length() > 0) { try { // MAKE TOPIC FOR CURRENT TOPIC NAME AND ASSOCIATE NEW TOPIC TO PARENT currentTopic = createListItemTopic(tm, getSubjectForListItem(), currentTopicName); if(parentTopic != null) { currentTopic.addType(parentTopic); log("Creating instance relation '"+getTopicName(parentTopic)+"' -- '"+getTopicName(currentTopic)+"'."); progress++; } } catch(Exception e) { log(e); } currentTopicName = null; currentTopicUrl = null; } } } private String getSubjectForListItem() { if(currentTopicUrl != null) { if(currentTopicUrl.startsWith("http:") || currentTopicUrl.startsWith("https:") || currentTopicUrl.startsWith("ftp:") || currentTopicUrl.startsWith("ftps:")) { return currentTopicUrl; } if(basePath != null) { if(currentTopicUrl.startsWith("/")) { return basePath.toExternalForm().substring(0, basePath.toExternalForm().indexOf(basePath.getPath()))+currentTopicUrl; } return basePath.toExternalForm() + currentTopicUrl; } if(SI_PREFIX.endsWith("/") && currentTopicUrl.startsWith("/")) { currentTopicUrl = currentTopicUrl.substring(1); } return SI_PREFIX + "item/" + currentTopicUrl; } String subjectPath = currentTopicName; if(subjectPath.length() > 50) { subjectPath = subjectPath.substring(0,50); subjectPath = subjectPath + "-" + currentTopicName.hashCode(); } try { return SI_PREFIX + "item/" + URLEncoder.encode(subjectPath, "UTF-8"); } catch(Exception e) { return SI_PREFIX + "item/" + subjectPath; } } private void popState() { if(!stateStack.empty()) { state = ((Integer) stateStack.pop()).intValue(); } else { state = STATE_OTHER; } } private void popParent() { currentTopic = parentTopic; if(!parentTopics.empty()) { parentTopic = (Topic) parentTopics.pop(); } else { parentTopic = null; } } public Topic createListItemTopic(TopicMap topicMap, String si, String listItem) throws TopicMapException { Topic t = createTopic(topicMap, si, listItem, null); try { Topic occurrenceType = topicMap.createTopic(); occurrenceType.addSubjectIdentifier(new Locator(SI_PREFIX + "item-text")); occurrenceType.setBaseName("List item text"); Topic lang = topicMap.getTopic(XTMPSI.LANG_INDEPENDENT); if(lang == null) lang = topicMap.getTopic(XTMPSI.getLang("en")); if(lang != null) { t.setData(occurrenceType, lang, listItem); } } catch(Exception e) {} return t; } 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) { if(baseName.length() > 512) baseName = baseName.substring(0, 509) + "..."; 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) { log("Failed to create topic for a basename '"+baseName+"' and a subject '"+si+"'."); } return t; } } }
18,131
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
JsoupInstanceListExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/list/JsoupInstanceListExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.list; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.wandora.application.WandoraTool; import org.wandora.application.tools.browserextractors.BrowserPluginExtractor; import org.wandora.application.tools.extractors.AbstractJsoupExtractor; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author Eero */ public class JsoupInstanceListExtractor extends AbstractJsoupExtractor implements WandoraTool, BrowserPluginExtractor { private static final long serialVersionUID = 1L; private TopicMap tm; private Topic wandoraClass; @Override public boolean extractTopicsFrom(Document d, String u, TopicMap t) throws Exception { this.tm = t; this.wandoraClass = getWandoraClassTopic(tm); Elements children = d.body().children(); for(Element listCandidate : children){ System.out.println(listCandidate.outerHtml()); if(listCandidate.tagName().equals("ul")) parseList(listCandidate, null); } return true; } private void parseList(Element list, Topic typeTopic) throws TopicMapException { Elements listElements = list.children(); for(Element outerElement: listElements){ if(outerElement.children().isEmpty()){ parseTopic(outerElement, typeTopic); } } } private void parseTopic(Element classElement, Topic typeTopic) throws TopicMapException { System.out.println(classElement.text()); Topic t = getOrCreateTopic(tm, null, classElement.text()); if(typeTopic == null) typeTopic = wandoraClass; t.addType(typeTopic); // See if the next element is a list (of instances) Element listWrapper = classElement.nextElementSibling(); if(listWrapper != null && !listWrapper.children().isEmpty()) { for(Element listCandidate: listWrapper.children()) { if(listCandidate.tagName().equals("ul")) { parseList(listCandidate, t); } } } } }
3,133
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
JsoupSuperSubClassListExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/list/JsoupSuperSubClassListExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.list; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.wandora.application.WandoraTool; import org.wandora.application.tools.browserextractors.BrowserPluginExtractor; import org.wandora.application.tools.extractors.AbstractJsoupExtractor; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author Eero */ public class JsoupSuperSubClassListExtractor extends AbstractJsoupExtractor implements WandoraTool, BrowserPluginExtractor { private static final long serialVersionUID = 1L; private TopicMap tm; private Topic wandoraClass; @Override public boolean extractTopicsFrom(Document d, String u, TopicMap t) throws Exception { this.tm = t; this.wandoraClass = getWandoraClassTopic(tm); Elements children = d.body().children(); for(Element listCandidate: children){ System.out.println(listCandidate.outerHtml()); if(listCandidate.tagName().equals("ul")) parseList(listCandidate, null); } return true; } private void parseList(Element list, Topic classTopic) throws TopicMapException { Elements listElements = list.children(); for(Element outerElement: listElements){ if(outerElement.children().isEmpty()){ parseTopic(outerElement, classTopic); } } } private void parseTopic(Element classElement, Topic classTopic) throws TopicMapException { String name = classElement.text().trim(); if(name.length() == 0) return; Topic t = getOrCreateTopic(tm, null , name); if(classTopic == null) classTopic = wandoraClass; makeSubclassOf(tm, t, classTopic); // See if the next element is a list (of instances) Element listWrapper = classElement.nextElementSibling(); if(listWrapper != null && !listWrapper.children().isEmpty()) { for(Element listCandidate: listWrapper.children()){ if(listCandidate.tagName().equals("ul")) parseList(listCandidate, t); } } } }
3,216
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ExtractIconclassKeywords.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/fng/ExtractIconclassKeywords.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * ExtractIconclassKeywords.java * * Created on 5. maaliskuuta 2007, 12:39 * */ package org.wandora.application.tools.extractors.fng; 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.HashMap; 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.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicTools; import org.wandora.topicmap.XTMPSI; /** * <p> * Tool is used to convert Iconclass keyword files to topic maps. * Iconclass is a subject-specific classification system used to * annotate images such as artworks. Classification system contains 28 000 hierarchically * ordered definitions divided into ten main divisions. * </p> * <p> * Iconclass keyword files are simple text files. Keyword file contains * term specifications such as * </p> * <p><pre> * NOT[34 F 1] * TXT[animals threatening man] * FIT[ihminen el�inten uhkaamana] * * NOT[34 F 11] * TXT[man struggling with animals] * FIT[ihmisen ja el�inten v�linen kamppailu] * * NOT[34 F 11 1] * TXT[man struggling with animals as ornamental variant with antithetically placed animals (mostly lions)] * FIT[] * * NOT[34 F 12] * TXT[man killing animal] * FIT[ihminen surmaa el�imen] * </pre></p> * * <p> * where NOT structure specifies the Iconclass notation (id) of the term. * TXT specifies the English description of the term and * FIT specifies Finnish description of the term. * </p> * <p> * Iconclass file extraction generates a topic map with * a topic for each found Iconclass term. Topic's variant names are * English and Finnish descriptions. Iconclass topics are arranged * into a super-subclass tree using the Iconclass notation identifier. * </p> * <p> * Wandora doesn't include any Iconclass keyword files. This extractor * was created for Finnish National Gallery's artwork site at * http://kokoelmat.fng.fi * </p> * <p> * To read more about the Iconclass system see * http://www.iconclass.nl. * </p> * * * @author akivela */ public class ExtractIconclassKeywords extends AbstractExtractor implements WandoraTool { private static final long serialVersionUID = 1L; public static boolean CREATE_ICONCLASS_TOPICS = false; /** Creates a new instance of ExtractIconclassKeywords */ public ExtractIconclassKeywords() { } @Override public String getName() { return "Extract Iconclass keywords"; } @Override public String getDescription() { return "Extracts Iconclass keyword files."; } @Override public String getGUIText(int textType) { switch(textType) { case SELECT_DIALOG_TITLE: return "Select Iconclass keyword file(s) or directories containing Iconclass keyword files!"; case POINT_START_URL_TEXT: return "Where would you like to start the crawl?"; case INFO_WAIT_WHILE_WORKING: return "Wait while seeking Iconclass keyword files!"; case FILE_PATTERN: return ".*\\.txt"; case DONE_FAILED: return "Ready. No extractions! %1 Iconclass keyword(s) and %2 other file(s) crawled!"; case DONE_ONE: return "Ready. Successful extraction! %1 Iconclass keyword(s) and %2 other file(s) crawled!"; case DONE_MANY: return "Ready. Total %0 successful extractions! %1 Iconclass keyword(s) and %2 other files crawled!"; case LOG_TITLE: return "Iconclass Keyword Extraction Log"; } return ""; } 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 Iconclass keyword file addressed! Using default file name 'iconclass_keywords.txt'!"); keywordFile = new File("iconclass_keywords.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 topicMap) throws Exception { log("Extracting Iconclass keywords!"); int iconclassCounter = 0; int nameCounter = 0; try { Topic iconclassType = topicMap.getTopic("http://www.iconclass.nl/"); if(iconclassType == null) { iconclassType = topicMap.createTopic(); iconclassType.addSubjectIdentifier(new Locator("http://www.iconclass.nl/")); iconclassType.setBaseName("Keyword (iconclass)"); } String line = ""; String iconclassString = null; String iconclassSI = null; String iconclassBasename = null; Locator iconclassSILocator = null; String iconclass = null; Topic iconclassTopic = null; String iconclassDisplayName = null; Association iconclassAssociation = null; HashMap players = null; line = breader.readLine(); while(line != null && !forceStop()) { if(line.startsWith("NOT[")) { iconclassTopic = null; try { iconclassString = removeSpaces(removeBlocks(line.substring(3))); iconclassSILocator = getLocatorForIconclass(iconclassString); iconclassTopic = topicMap.getTopic(iconclassSILocator); if(iconclassTopic == null) { iconclassTopic = topicMap.getTopic( new Locator(TopicTools.cleanDirtyLocator("http://www.iconclass.nl/" + iconclassString)) ); } if(CREATE_ICONCLASS_TOPICS && iconclassTopic == null) { iconclassCounter++; iconclassBasename = iconclassString; iconclassTopic = topicMap.createTopic(); iconclassTopic.addSubjectIdentifier(iconclassSILocator); iconclassTopic.setBaseName(iconclassBasename + " (iconclass)"); iconclassTopic.addType(iconclassType); iconclassTopic.addSubjectIdentifier(new Locator(TopicTools.cleanDirtyLocator("http://www.iconclass.nl/" + iconclassString))); // **** BUILD SUPER-CLASSES FOR THE ICONCLASS TOPIC! **** String iconclassSubCode = iconclassString; String iconclassSuperCode = null; for(int i=Math.min(3, iconclassString.length()); i>=0; i--) { iconclassSuperCode = iconclassString.substring(0,i); if(! iconclassSuperCode.matches("[0-9A-Z]+")) continue; createIconclassSubSuperRelation( iconclassSubCode, iconclassSuperCode, topicMap ); iconclassSubCode = iconclassSuperCode; } } } catch(Exception e) { log(e); } } else if(line.startsWith("TXT[")) { String newline = ""; while(line.indexOf("]") == -1 && newline != null && !forceStop() ) { newline = breader.readLine(); if(newline != null) line += " " + newline; } try { if(iconclassTopic != null) { iconclassDisplayName = removeBlocks(line.substring(3)); if(iconclassDisplayName != null && iconclassDisplayName.length() > 0) { iconclassTopic.setDisplayName("en", iconclassDisplayName); nameCounter++; } } } catch(Exception e) { log(e); } } else if(line.startsWith("FIT[")) { String newline = ""; while(line.indexOf("]") == -1 && newline != null && !forceStop() ) { newline = breader.readLine(); if(newline != null) line += " " + newline; } try { if(iconclassTopic != null) { iconclassDisplayName = removeBlocks(line.substring(3)); if(iconclassDisplayName != null && iconclassDisplayName.length() > 0) { iconclassTopic.setDisplayName("fi", iconclassDisplayName); nameCounter++; } } } catch(Exception e) { log(e); } } setProgress(iconclassCounter); line = breader.readLine(); } } catch(Exception e) { log(e); } log("Extracted " + iconclassCounter + " iconclass keyword topics."); log("Extracted " + nameCounter + " names for iconclass topics."); return true; } public String removeSpaces(String str) { if(str != null) { str = str.replaceAll(" ", ""); } return str; } public String removeBlocks(String str) { if(str != null) { if(str.indexOf('[') > -1 && str.indexOf(']') > -1) { str = str.substring(str.indexOf('[')+1, str.indexOf(']')); } } return str; } public void createIconclassSubSuperRelation(String sub, String sup, TopicMap topicMap) { try { Topic superClass = getOrCreateIconclassTopic(topicMap, getLocatorForIconclass(sup)); Topic subClass = getOrCreateIconclassTopic(topicMap, getLocatorForIconclass(sub)); Topic supersubclassType = getOrCreateTopic(topicMap, XTMPSI.SUPERCLASS_SUBCLASS); Topic superclassType = getOrCreateTopic(topicMap, XTMPSI.SUPERCLASS); Topic subclassType = getOrCreateTopic(topicMap, XTMPSI.SUBCLASS); if(superClass != null && subClass != null && supersubclassType != null && superclassType != null && subclassType != null ) { if(subClass.getBaseName() == null) { subClass.setBaseName(sub + " (iconclass)"); } if(superClass.getBaseName() == null) { superClass.setBaseName(sup + " (iconclass)"); } HashMap players = new HashMap(); players.put(superclassType, superClass); players.put(subclassType, subClass); Association supeclassAssociation = topicMap.createAssociation(supersubclassType); supeclassAssociation.addPlayers(players); } } catch(Exception e) { log(e); } } public Topic getOrCreateIconclassTopic(TopicMap topicmap, String si) { return getOrCreateIconclassTopic(topicmap, new Locator(si)); } public Topic getOrCreateIconclassTopic(TopicMap topicmap, Locator si) { Topic topic = getOrCreateTopic(topicmap, si); try { if(topic != null) topic.addType(topicmap.getTopic("http://www.iconclass.nl/")); } catch(Exception e) { log(e); } return topic; } 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; } public Locator getLocatorForIconclass(String iconclassCode) { try { return new Locator( TopicTools.cleanDirtyLocator("http://wandora.org/si/iconclass/" + iconclassCode) ); } catch(Exception e) { log(e); return null; } } public boolean isValidIconclass(String iconclass) { if(iconclass != null && iconclass.length() > 0) { if(!iconclass.startsWith("X") && !iconclass.startsWith("x") && !iconclass.startsWith("?")) return true; } return false; } @Override public boolean useTempTopicMap() { return false; } }
14,822
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ExtractSIFFKeywords.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/fng/ExtractSIFFKeywords.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * ExtractSIFFKeywords.java * * Created on 6.6.2006, 19:51 * */ package org.wandora.application.tools.extractors.fng; 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.Hashtable; 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.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicTools; import org.wandora.utils.Textbox; /** * <p> * Class implements special extractor for Sinebrychoff's artwork files. * Sinebrychoff's artwork file is basically a database dump file containing * artwork specific information. Class extracts only artworks and keywords * found in given file(s). * </p> * <p> * About the file format. In the given file artworks are supposed to be separated * with "\n\n" characters. Artwork specific data record begins with a line * containing artwork identifier (inventory code). Identifier line is recognized * with string "@@NO:". Artwork's keyword record line is recognized with "AH:". * Keyword record may contain multiple semicolon separated keywords. * Below is an example fragment of the Sinebrychoff's artwork file. * </p> * <p><pre> * NO:A IV 3299 * MU:SFF * OM:Valtion taidemuseo * NI:INTIALAINEN MINIATYYRI ; Kaksi naista soittaa kahdelle pyh�lle miehelle (sadhulle), Rajput-miniatyyri * VV:n 1800 * MA:vesiv�ri, kulta ja hopea * MI:20x12,7 * ME:merk. * MJ:takana * MS:Rajasthan School * SI:V;SFF * HA:osto * HT:taiteilija Per Stenius * OA:1.6.1959 * HH:30.000 * VY:MV * VN: 11085 * P�:maalaus * ER:miniatyyri * AH:KOHTAUS;musiikki;naiset;pyh�t miehet;intialaiset;koira * KI:B.Robinson * LI:RV/87 * </pre> * </p> * * * * @author akivela */ public class ExtractSIFFKeywords extends AbstractExtractor implements WandoraTool { private static final long serialVersionUID = 1L; public boolean createArtworkTopics = true; /** Creates a new instance of ExtractSIFFKeywords */ public ExtractSIFFKeywords() { } @Override public String getName() { return "Extract SIFF keywords"; } @Override public String getDescription() { return "Extract keyword and artwork topics from Sinebrychoff artmuseum's artwork text file."; } @Override public String getGUIText(int textType) { switch(textType) { case SELECT_DIALOG_TITLE: return "Select SIFF Keyword file(s) or directories containing SIFF Keyword files!"; case POINT_START_URL_TEXT: return "Where would you like to start the crawl?"; case INFO_WAIT_WHILE_WORKING: return "Wait while seeking SIFF Keyword files!"; case FILE_PATTERN: return ".*\\.txt"; case DONE_FAILED: return "Ready. No extractions! %1 SIFF keyword(s) and %2 other file(s) crawled!"; case DONE_ONE: return "Ready. Successful extraction! %1 SIFF keyword(s) and %2 other file(s) crawled!"; case DONE_MANY: return "Ready. Total %0 successful extractions! %1 SIFF keyword(s) and %2 other files crawled!"; case LOG_TITLE: return "SIFF Keyword Extraction Log"; } return ""; } 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 keyword file addressed! Using default file name!"); keywordFile = new File("siff_keywords.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 topicMap) throws Exception { log("Extracting SIFF keywords!"); int workCounter = 0; int keywordCounter = 0; try { Topic artWorkType=topicMap.getTopic("http://www.muusa.net/Teos"); if(artWorkType == null) { artWorkType = topicMap.createTopic(); artWorkType.addSubjectIdentifier(new Locator("http://www.muusa.net/Teos")); artWorkType.setBaseName("Teos"); } Topic asiasanaClassType=topicMap.getTopic("http://www.sinebrychoffintaidemuseo.fi/keywords"); if(asiasanaClassType == null) { asiasanaClassType = topicMap.createTopic(); asiasanaClassType.addSubjectIdentifier(new Locator("http://www.sinebrychoffintaidemuseo.fi/keywords")); asiasanaClassType.setBaseName("asiasana (siff)"); } String line = ""; String[] tokens = null; String currentWorkId = null; String currentWorkSI = null; Topic currentWork = null; String asiasanaString = null; String[] asiasanat = null; String asiasanaSI = null; String asiasana = null; Topic asiasanaTopic = null; String asiasanaDisplayName = null; Association asiasanaAssociation = null; Hashtable<Topic,Topic> players = null; line = breader.readLine(); while(line != null && !forceStop()) { if(line.startsWith("@@NO:")) { currentWorkId = Textbox.trimExtraSpaces(line.substring(5)); if(currentWorkId.length() > 0) { workCounter++; log("Found artwork '" + currentWorkId + "'"); currentWorkSI = TopicTools.cleanDirtyLocator("http://www.muusa.net/E42_Object_Identifier/" + currentWorkId); currentWork = topicMap.getTopic(currentWorkSI); if(currentWork == null && createArtworkTopics) { currentWork = topicMap.createTopic(); currentWork.addSubjectIdentifier(new Locator(currentWorkSI)); currentWork.addType(artWorkType); } if(currentWork == null) { line = breader.readLine(); while(line != null && !line.startsWith("@@NO:")) { line = breader.readLine(); } continue; } } } else if(line.startsWith("AH:")) { asiasanaString = line.substring(3); asiasanat = asiasanaString.split(";"); for(int i=0; i<asiasanat.length; i++) { asiasana = Textbox.trimExtraSpaces(asiasanat[i]); if(asiasana.length() > 0) { keywordCounter++; log("Found keyword '" + asiasana + "'"); asiasanaSI = TopicTools.cleanDirtyLocator("http://www.sinebrychoffintaidemuseo.fi/keywords/" + asiasana); asiasanaTopic = topicMap.getTopic(asiasanaSI); if(asiasanaTopic == null) { asiasanaTopic = topicMap.createTopic(); asiasanaTopic.addSubjectIdentifier(new Locator(asiasanaSI)); asiasanaTopic.setBaseName(asiasana + " (asiasana)"); asiasanaTopic.addType(asiasanaClassType); asiasanaTopic.setDisplayName("fi", asiasana); } if(currentWork != null) { log("Associating keyword '" + asiasana + "' and artwork '" + currentWorkId + "'!"); players = new Hashtable<>(); players.put(asiasanaClassType, asiasanaTopic ); players.put(artWorkType, currentWork); asiasanaAssociation = topicMap.createAssociation(asiasanaClassType); asiasanaAssociation.addPlayers(players); } } } } setProgress(keywordCounter); line = breader.readLine(); } } catch(Exception e) { log(e); } log("Extracted " + workCounter + " artworks."); log("Extracted " + keywordCounter + " keywords."); return true; } public boolean useTempTopicMap() { return false; } }
10,446
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ExtractMuusaIconclassBridge.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/fng/ExtractMuusaIconclassBridge.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * ExtractMuusaIconclassBridge.java * * Created on 5. maaliskuuta 2007, 10:07 * */ package org.wandora.application.tools.extractors.fng; 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.Hashtable; 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.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicTools; import org.wandora.topicmap.XTMPSI; import org.wandora.utils.Textbox; /** * <p> * Extractor is an example of solution used to bridge to separate keyword islands. * Extractor reads a simple text file with Muusa and Iconclass keywords, and * creates a bridge associations to link similar keywords. The extractor was * created for Finnish National Gallery's site at http://kokoelmant.fng.fi. * </p> * <p> * <pre> * [Muusa keyword] [usage] [Muusa keyword variant] [Iconclass keyword] * * lierihattu (asiasana) 19 41D221 * portaat (asiasana) 19 41A34 * taistelu (asiasana) 18 45 * tupakointi (asiasana) 18 41C7 * kaappi (asiasana) 17 41A254 * portti (asiasana) 17 41A5 * pullot (asiasana) 17 41A77 * ratsastaja (asiasana) 17 46C131 *</pre> * </p> * * @author akivela */ public class ExtractMuusaIconclassBridge extends AbstractExtractor implements WandoraTool { private static final long serialVersionUID = 1L; /** Creates a new instance of ExtractMuusaIconclassBridge */ public ExtractMuusaIconclassBridge() { } @Override public String getName() { return "Extract Muusa-Iconclass bridge"; } @Override public String getDescription() { return "Extracts Iconclass and Muusa keywords, and links extracted keywords"; } @Override public String getGUIText(int textType) { switch(textType) { case SELECT_DIALOG_TITLE: return "Select Muusa-Iconclass keyword file(s) or directories containing Kiasma keyword files!"; case POINT_START_URL_TEXT: return "Where would you like to start the crawl?"; case INFO_WAIT_WHILE_WORKING: return "Wait while seeking Muusa-Iconclass keyword files!"; case FILE_PATTERN: return ".*\\.txt"; case DONE_FAILED: return "Ready. No extractions! %1 Muusa-Iconclass keyword(s) and %2 other file(s) crawled!"; case DONE_ONE: return "Ready. Successful extraction! %1 Muusa-Iconclass keyword(s) and %2 other file(s) crawled!"; case DONE_MANY: return "Ready. Total %0 successful extractions! %1 Muusa-Iconclass keyword(s) and %2 other files crawled!"; case LOG_TITLE: return "Muusa-Iconclass Keyword Extraction Log"; } return ""; } 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 keyword file addressed! Using default file name 'muusaiconclass_keywords.txt'!"); keywordFile = new File("muusaiconclass_keywords.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 topicMap) throws Exception { int iconclassCounter = 0; int muusaKeywordCounter = 0; int bridgeCounter = 0; log("Extracting keyword bridge..."); try { Topic muusaType=topicMap.getTopic("http://www.muusa.net/keyword"); if(muusaType == null) { muusaType = topicMap.createTopic(); muusaType.addSubjectIdentifier(new Locator("http://www.muusa.net/keyword")); muusaType.setBaseName("Keyword (muusa)"); } Topic iconclassType=topicMap.getTopic("http://www.iconclass.nl/"); if(iconclassType == null) { iconclassType = topicMap.createTopic(); iconclassType.addSubjectIdentifier(new Locator("http://www.iconclass.nl/")); iconclassType.setBaseName("Keyword (iconclass)"); } Topic muusaIconclassBridgeType=topicMap.getTopic("http://wandora.org/si/muusa_iconclass_bridge"); if(muusaIconclassBridgeType == null) { muusaIconclassBridgeType = topicMap.createTopic(); muusaIconclassBridgeType.addSubjectIdentifier(new Locator("http://wandora.org/si/muusa_iconclass_bridge")); muusaIconclassBridgeType.setBaseName("Keyword bridge (muusa - iconclass)"); } String line = ""; String[] tokens = null; String muusaKeywordId = null; String muusaKeywordSI = null; Topic muusaKeyword = null; //String iconClassSI = null; Locator iconclassSILocator = null; String iconclassCode = null; String iconclassBasename = null; Topic iconclassTopic = null; String iconclassDisplayName = null; Association iconclassAssociation = null; Hashtable<Topic,Topic> players = null; Association muusaIconclassBridge = 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]); } } if(tokens.length > 1) { if(tokens[0].length() > 0) { // Inventory number of artwork! muusaKeywordId = tokens[0]; muusaKeyword = topicMap.getTopicWithBaseName(muusaKeywordId); if(muusaKeyword != null) { log("Found Muusa keyword for '" + muusaKeywordId + "'."); muusaKeywordCounter++; } else { log("Muusa keyword missing '" + muusaKeywordId + "'."); } } if(muusaKeyword != null) { //System.out.println("tokens length:" + tokens.length); if(tokens.length > 3 && isValidIconclass(tokens[3])) { // Iconclass code exists! iconclassCode = tokens[3]; log("Found iconclass keyword '" + iconclassCode + "'."); iconclassSILocator = getLocatorForIconclass(iconclassCode); iconclassTopic = topicMap.getTopic(iconclassSILocator); if(iconclassTopic == null) { iconclassCounter++; iconclassBasename = iconclassCode; iconclassTopic = topicMap.createTopic(); iconclassTopic.addSubjectIdentifier(iconclassSILocator); iconclassTopic.setBaseName(iconclassBasename + " (iconclass)"); iconclassTopic.addType(iconclassType); iconclassTopic.addSubjectIdentifier(new Locator(TopicTools.cleanDirtyLocator("http://www.iconclass.nl/" + iconclassCode))); // **** BUILD SUPER-CLASSES FOR THE ICONCLASS TOPIC! **** String iconclassSubCode = iconclassCode; String iconclassSuperCode = null; for(int i=Math.min(3, iconclassCode.length()); i>=0; i--) { iconclassSuperCode = iconclassCode.substring(0,i); if(! iconclassSuperCode.matches("[0-9A-Z]+")) continue; createIconclassSubSuperRelation( iconclassSubCode, iconclassSuperCode, topicMap ); iconclassSubCode = iconclassSuperCode; } } if(iconclassTopic != null && muusaKeyword != null) { players = new Hashtable<>(); players.put(iconclassType, iconclassTopic); players.put(muusaType, muusaKeyword); muusaIconclassBridge = topicMap.createAssociation(muusaIconclassBridgeType); muusaIconclassBridge.addPlayers(players); bridgeCounter++; } } } } setProgress(iconclassCounter); line = breader.readLine(); } } catch(Exception e) { log(e); } log("Extracted " + muusaKeywordCounter + " Muusa keywords."); log("Extracted " + iconclassCounter + " Iconclass keywords."); log("Created " + bridgeCounter + " bridges between Iconclass and Muusa keywords."); return true; } public void createIconclassSubSuperRelation(String sub, String sup, TopicMap topicMap) { try { Topic superClass = getOrCreateIconclassTopic(topicMap, getLocatorForIconclass(sup)); Topic subClass = getOrCreateIconclassTopic(topicMap, getLocatorForIconclass(sub)); Topic supersubclassType = getOrCreateTopic(topicMap, XTMPSI.SUPERCLASS_SUBCLASS); Topic superclassType = getOrCreateTopic(topicMap, XTMPSI.SUPERCLASS); Topic subclassType = getOrCreateTopic(topicMap, XTMPSI.SUBCLASS); if(superClass != null && subClass != null && supersubclassType != null && superclassType != null && subclassType != null ) { if(subClass.getBaseName() == null) { subClass.setBaseName(sub + " (iconclass)"); } if(superClass.getBaseName() == null) { superClass.setBaseName(sup + " (iconclass)"); } Hashtable<Topic,Topic> players = new Hashtable<>(); players.put(superclassType, superClass); players.put(subclassType, subClass); Association supeclassAssociation = topicMap.createAssociation(supersubclassType); supeclassAssociation.addPlayers(players); } } catch(Exception e) { log(e); } } public Topic getOrCreateIconclassTopic(TopicMap topicmap, String si) { return getOrCreateIconclassTopic(topicmap, new Locator(si)); } public Topic getOrCreateIconclassTopic(TopicMap topicmap, Locator si) { Topic topic = getOrCreateTopic(topicmap, si); try { if(topic != null) topic.addType(topicmap.getTopic("http://www.iconclass.nl/")); } catch(Exception e) { log(e); } return topic; } 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; } public Locator getLocatorForIconclass(String iconclassCode) { try { return new Locator( TopicTools.cleanDirtyLocator("http://wandora.org/si/iconclass/" + iconclassCode) ); } catch(Exception e) { log(e); return null; } } public boolean isValidIconclass(String iconclass) { if(iconclass != null && iconclass.length() > 0) { if(!iconclass.startsWith("X") && !iconclass.startsWith("x") && !iconclass.startsWith("?")) return true; } return false; } public boolean useTempTopicMap() { return false; } }
14,779
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ExtractFNGTextEnrichment.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/fng/ExtractFNGTextEnrichment.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * ExtractFNGTextEnrichment.java * * Created on 10.6.2006, 11:18 * */ package org.wandora.application.tools.extractors.fng; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.text.DateFormat; import java.util.Date; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDDocumentInformation; import org.apache.pdfbox.text.PDFTextStripper; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.tools.extractors.AbstractExtractor; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicTools; import org.wandora.utils.IObox; import org.wandora.utils.MSOfficeBox; import org.wandora.utils.Textbox; /** * * @author akivela */ public class ExtractFNGTextEnrichment extends AbstractExtractor implements WandoraTool { private static final long serialVersionUID = 1L; protected Wandora wandora = null; protected File keywordFile = null; private String defaultLang = "en"; /** Creates a new instance of ApplyKiasmaKeywords */ public ExtractFNGTextEnrichment() { } @Override public String getName() { return "FNG Enrichment Text Extractor"; } @Override public String getDescription() { return "Extract enrichment texts for FNG collection browser."; } @Override public String getGUIText(int textType) { switch(textType) { case SELECT_DIALOG_TITLE: return "Select enrichment text file(s) or directories containing enrichment text files!"; case POINT_START_URL_TEXT: return "Where would you like to start the crawl?"; case INFO_WAIT_WHILE_WORKING: return "Wait while seeking enrichment text files!"; case FILE_PATTERN: return ".*\\.(pdf|txt|rtf|doc)"; case DONE_FAILED: return "Ready. No extractions! %1 enrichment text(s) and %2 other file(s) crawled!"; case DONE_ONE: return "Ready. Successful extraction! %1 enrichment text(s) and %2 other file(s) crawled!"; case DONE_MANY: return "Ready. Total %0 successful extractions! %1 enrichment text(s) and %2 other files crawled!"; case LOG_TITLE: return "Enrichment Text Extraction Log"; } return ""; } public boolean _extractTopicsFrom(URL url, TopicMap topicMap) throws Exception { if(url == null) return false; try { Topic textType = createTopic(topicMap, "tekstidokumentti"); Topic textTopic = createTopic(topicMap, url.getFile(), " (tekstidokumentti)", url.getFile(), textType); textTopic.addSubjectIdentifier(new Locator(TopicTools.cleanDirtyLocator(url.toExternalForm()))); URLConnection uc = null; if(wandora != null) { uc = wandora.wandoraHttpAuthorizer.getAuthorizedAccess(url); } else { uc = url.openConnection(); Wandora.initUrlConnection(uc); } _extractTopicsFromStream(url.toExternalForm(), uc.getInputStream(), topicMap, textTopic); return true; } catch(Exception e) { log("Exception occurred while extracting from url\n" + url.toExternalForm(), e); takeNap(1000); } return false; } public boolean _extractTopicsFrom(String str, TopicMap topicMap) throws Exception { throw(new Exception(STRING_EXTRACTOR_NOT_SUPPORTED_MESSAGE)); } public boolean _extractTopicsFrom(File file, TopicMap topicMap) throws Exception { if(file == null || file.isDirectory()) return false; try { Topic textType = createTopic(topicMap, "tekstidokumentti"); Topic textTopic = createTopic(topicMap, file.getName(), " (tekstidokumentti)", file.getName(), textType); textTopic.addSubjectIdentifier(new Locator(TopicTools.cleanDirtyLocator(file.toURL().toExternalForm()))); // --- ADD LAST MODIFICATION TIME AS OCCURRENCE --- try { Topic modType = createTopic(topicMap, "file-modified"); String dateString = DateFormat.getDateInstance().format( new Date(file.lastModified()) ); setData(textTopic, modType, "en", dateString); setData(textTopic, modType, "fi", dateString); } catch(Exception e) { log("Exception occurred while setting enrichment topic's modification time!", e); } _extractTopicsFromStream(file.getPath(), new FileInputStream(file), topicMap, textTopic); return true; } catch(Exception e) { log("Exception occurred while extracting from file " + file.getName(), e); takeNap(1000); } return false; } public void _extractTopicsFromStream(String locator, InputStream inputStream, TopicMap topicMap, Topic textTopic) { try { String lowerCaseLocator = locator.toLowerCase(); // --- HANDLE PDF ENRICHMENT TEXT --- if(lowerCaseLocator.endsWith("pdf")) { PDDocument doc = PDDocument.load(new URL(locator).openStream()); PDDocumentInformation info = doc.getDocumentInformation(); // --- PDF SUBJECT --- String subject = info.getSubject(); if(subject != null && subject.length() > 0) { Topic subjectType = createTopic(topicMap, "subject"); setData(textTopic, subjectType, defaultLang, subject.trim()); } // --- PDF TITLE --- String title = info.getTitle(); if(title != null && title.length() > 0) { Topic titleType = createTopic(topicMap, "title"); setData(textTopic, titleType, defaultLang, title.trim()); } // --- PDF KEYWORDS --- String keywords = info.getKeywords(); if(keywords != null && keywords.length() > 0) { Topic keywordType = createTopic(topicMap, "keywords"); setData(textTopic, keywordType, defaultLang, keywords.trim()); } // --- PDF TEXT CONTENT --- PDFTextStripper stripper = new PDFTextStripper(); String content = stripper.getText(doc); setTextEnrichment(textTopic, topicMap, content); doc.close(); } // --- HANDLE RTF DOCUMENTS --- else if(lowerCaseLocator.endsWith("rtf")) { String content = Textbox.RTF2PlainText(inputStream); setTextEnrichment(textTopic, topicMap, content); } // --- HANDLE OFFICE DOCUMENTS --- else if(lowerCaseLocator.endsWith("doc") || lowerCaseLocator.endsWith("docx") || lowerCaseLocator.endsWith("ppt") || lowerCaseLocator.endsWith("xsl") || lowerCaseLocator.endsWith("vsd") ) { String content = MSOfficeBox.getText(inputStream); if(content != null) { setTextEnrichment(textTopic, topicMap, content); } } // --- HANDLE TXT DOCUMENTS --- else { String content = IObox.loadFile(new InputStreamReader(inputStream)); setTextEnrichment(textTopic, topicMap, content); } } catch(Exception e) { log(e); } } public String solveTitle(String content) { String title = null; title = content.substring(0, Math.max(80, content.indexOf("\n"))); if(title != null && title.length() > 80) { while(!title.endsWith(" ")) { title = title.substring(0, title.length()-1); } title = Textbox.trimExtraSpaces(title); if(title == null || title.length() == 0) return null; } return title; } public void setTextEnrichment(Topic textTopic, TopicMap topicMap, String content) { try { String trimmedText = Textbox.trimExtraSpaces(content); if(trimmedText != null && trimmedText.length() > 0) { Topic contentType = createTopic(topicMap, "teksti"); setData(textTopic, contentType, "en", trimmedText); setData(textTopic, contentType, "fi", trimmedText); setData(textTopic, contentType, "se", trimmedText); } String title = solveTitle(trimmedText); if(title != null) { textTopic.setDisplayName("en", title); textTopic.setDisplayName("fi", title); textTopic.setDisplayName("se", title); } } catch(Exception e) { log(e); } } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- public static final String[] contentTypes=new String[] { "application/pdf", "text/plain", "application/rtf", "application/msword" }; public String[] getContentTypes() { return contentTypes; } }
10,685
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ExtractKiasmaKeywords.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/fng/ExtractKiasmaKeywords.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * ExtractKiasmaKeywords.java * * Created on 3. huhtikuuta 2006, 21:27 * */ package org.wandora.application.tools.extractors.fng; 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.Hashtable; 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.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicTools; import org.wandora.topicmap.XTMPSI; import org.wandora.utils.Textbox; /** * <p> * Class implements an extraction tool for Kiasma artmuseum's iconclass keyword * file. File contains artworks and linked iconclass keywords. File is originally * created and updated with Microsoft Excel and later exported as tab limited * text file. Thus all records in file are separated with tabulator on new line * character. *</p> * <p> * First column of keyword file contains artwork's identifier (inventory code). * Second column of file contains artist's name. Third column contains artwork's name * Remaining one to four columns contains iconclass keywords linked to the artwork. * First remaining column contains iconclass code of the keyword and latter code's * English, Finnish and Swedish representation. Below is an example of single * artwork in file. In order to make example more readable all tab characters * have been changed to sets of spaces. * <p> * <p><pre> * N-1992-225 Trockel, Rosemarie Nimet�n 41B2 liesi, hella, uuni yms. * 49D452 hexahedron, cube * 22C4(WHITE) v�rit, pigmentit ja maalit: valkoinen * </pre></p> * * * @author akivela */ public class ExtractKiasmaKeywords extends AbstractExtractor implements WandoraTool { private static final long serialVersionUID = 1L; /** * Creates a new instance of ExtractKiasmaKeywords */ public ExtractKiasmaKeywords() { } @Override public String getName() { return "Extract Kiasma keywords"; } @Override public String getDescription() { return "Extract Iconclass keywords and artworks from Kiasma's iconclass file."; } @Override public String getGUIText(int textType) { switch(textType) { case SELECT_DIALOG_TITLE: return "Select Kiasma keyword file(s) or directories containing Kiasma keyword files!"; case POINT_START_URL_TEXT: return "Where would you like to start the crawl?"; case INFO_WAIT_WHILE_WORKING: return "Wait while seeking Kiasma keyword files!"; case FILE_PATTERN: return ".*\\.txt"; case DONE_FAILED: return "Ready. No extractions! %1 Kiasma keyword(s) and %2 other file(s) crawled!"; case DONE_ONE: return "Ready. Successful extraction! %1 Kiasma keyword(s) and %2 other file(s) crawled!"; case DONE_MANY: return "Ready. Total %0 successful extractions! %1 Kiasma keyword(s) and %2 other files crawled!"; case LOG_TITLE: return "Kiasma Keyword Extraction Log"; } return ""; } 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 keyword file addressed! Using default file name 'kiasma_keywords.txt'!"); keywordFile = new File("kiasma_keywords.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 topicMap) throws Exception { int workCounter = 0; int keywordCounter = 0; log("Extracting keywords..."); try { Topic artWorkType=topicMap.getTopic("http://www.muusa.net/Teos"); if(artWorkType == null) { artWorkType = topicMap.createTopic(); artWorkType.addSubjectIdentifier(new Locator("http://www.muusa.net/Teos")); artWorkType.setBaseName("Teos"); } Topic iconclassType=topicMap.getTopic("http://www.iconclass.nl/"); if(iconclassType == null) { iconclassType = topicMap.createTopic(); iconclassType.addSubjectIdentifier(new Locator("http://www.iconclass.nl/")); iconclassType.setBaseName("Iconclass"); } String line = ""; String[] tokens = null; String currentWorkId = null; String currentWorkSI = null; Topic currentWork = null; //String iconclassSI = null; Locator iconclassSILocator = null; String iconclassCode = null; String iconclassBasename = null; Topic iconclassTopic = null; String iconclassDisplayName = null; Association iconclassAssociation = null; Hashtable<Topic,Topic> players = 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]); } } if(tokens.length > 1) { if(tokens[0].length() > 0) { // Inventory number of artwork! currentWorkId = tokens[0]; currentWorkSI = TopicTools.cleanDirtyLocator("http://www.muusa.net/E42_Object_Identifier/" + currentWorkId); currentWork = topicMap.getTopic(currentWorkSI); if(currentWork == null) { currentWork = topicMap.getTopicWithBaseName(currentWorkId); } if(currentWork != null) { log("Found artwork for '" + currentWorkId + "'."); workCounter++; } else { log("Artwork missing '" + currentWorkSI + "'."); } } if(currentWork != null) { //System.out.println("tokens length:" + tokens.length); if(tokens.length > 3 && tokens[3].length() > 0) { // Iconclass code exists! iconclassCode = tokens[3]; log("Found iconclass keyword '" + iconclassCode + "'."); iconclassSILocator = getLocatorForIconclass(iconclassCode); iconclassTopic = topicMap.getTopic(iconclassSILocator); if(iconclassTopic == null) { keywordCounter++; iconclassBasename = iconclassCode; iconclassTopic = topicMap.createTopic(); iconclassTopic.addSubjectIdentifier(iconclassSILocator); if(tokens.length > 4 && tokens[4].length() > 0) { // Iconclass en name exists! iconclassBasename += " - " + tokens[4]; iconclassTopic.setDisplayName("en", tokens[4]); } iconclassTopic.setBaseName(iconclassBasename + " (iconclass)"); if(tokens.length > 5 && tokens[5].length() > 0) { // Iconclass fi name exists! iconclassTopic.setDisplayName("fi", tokens[5]); } iconclassTopic.addType(iconclassType); iconclassTopic.addSubjectIdentifier(new Locator(TopicTools.cleanDirtyLocator("http://www.iconclass.nl/" + iconclassCode))); // **** BUILD SUPER-CLASSES FOR THE ICONCLASS TOPIC! **** String iconclassSubCode = iconclassCode; String iconclassSuperCode = null; for(int i=Math.min(3, iconclassCode.length()); i>=0; i--) { iconclassSuperCode = iconclassCode.substring(0,i); if(! iconclassSuperCode.matches("[0-9A-Z]+")) continue; createIconclassSubSuperRelation( iconclassSubCode, iconclassSuperCode, topicMap ); iconclassSubCode = iconclassSuperCode; } } else { iconclassDisplayName = iconclassTopic.getDisplayName("en"); if(tokens.length > 4 && tokens[4].length() > 0 && (iconclassDisplayName == null || iconclassDisplayName.length() == 0)) { iconclassTopic.setDisplayName("en", tokens[4]); iconclassTopic.setBaseName(iconclassCode + " - " + tokens[4] + " (iconclass)"); if(tokens.length > 5 && tokens[5].length() > 0) { // Iconclass fi name exists! iconclassTopic.setDisplayName("fi", tokens[5]); } } } players = new Hashtable<>(); players.put(iconclassType, iconclassTopic); players.put(artWorkType, currentWork); iconclassAssociation = topicMap.createAssociation(iconclassType); iconclassAssociation.addPlayers(players); } } } setProgress(keywordCounter); line = breader.readLine(); } } catch(Exception e) { log(e); } log("Extracted " + workCounter + " artworks."); log("Extracted " + keywordCounter + " keywords."); return true; } public void createIconclassSubSuperRelation(String sub, String sup, TopicMap topicMap) { try { Topic superClass = getOrCreateIconclassTopic(topicMap, getLocatorForIconclass(sup)); Topic subClass = getOrCreateIconclassTopic(topicMap, getLocatorForIconclass(sub)); Topic supersubclassType = getOrCreateTopic(topicMap, XTMPSI.SUPERCLASS_SUBCLASS); Topic superclassType = getOrCreateTopic(topicMap, XTMPSI.SUPERCLASS); Topic subclassType = getOrCreateTopic(topicMap, XTMPSI.SUBCLASS); if(superClass != null && subClass != null && supersubclassType != null && superclassType != null && subclassType != null ) { if(subClass.getBaseName() == null) { subClass.setBaseName(sub + " (iconclass)"); } if(superClass.getBaseName() == null) { superClass.setBaseName(sup + " (iconclass)"); } Hashtable<Topic,Topic> players = new Hashtable<>(); players.put(superclassType, superClass); players.put(subclassType, subClass); Association supeclassAssociation = topicMap.createAssociation(supersubclassType); supeclassAssociation.addPlayers(players); } } catch(Exception e) { log(e); } } public Topic getOrCreateIconclassTopic(TopicMap topicmap, String si) { return getOrCreateIconclassTopic(topicmap, new Locator(si)); } public Topic getOrCreateIconclassTopic(TopicMap topicmap, Locator si) { Topic topic = getOrCreateTopic(topicmap, si); try { if(topic != null) topic.addType(topicmap.getTopic("http://www.iconclass.nl/")); } catch(Exception e) { log(e); } return topic; } 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; } public Locator getLocatorForIconclass(String iconclassCode) { try { return new Locator( TopicTools.cleanDirtyLocator("http://wandora.org/si/iconclass/" + iconclassCode) ); } catch(Exception e) { log(e); return null; } } @Override public boolean useTempTopicMap() { return false; } }
15,215
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
CSVExtractorConfiguration.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/csv/CSVExtractorConfiguration.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.csv; import javax.swing.JDialog; import org.wandora.application.Wandora; 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; /** * * @author akivela */ public class CSVExtractorConfiguration extends javax.swing.JPanel { private static final long serialVersionUID = 1L; public static final char defaultStringCharacter = '"'; public static final char defaultLineSeparator = '\n'; public static final char defaultValueSeparator = ','; private JDialog myDialog = null; private boolean wasAccepted = false; /** * Creates new form CSVExtractorConfiguration */ public CSVExtractorConfiguration() { initComponents(); encodingComboBox.setEditable(false); } public void open(Wandora wandora) { if(myDialog == null) { myDialog = new JDialog(wandora, true); myDialog.setTitle("CSV extractor options"); myDialog.add(this); } wasAccepted = false; myDialog.setSize(400,240); wandora.centerWindow(myDialog); myDialog.setVisible(true); // WAIT TILL CONFIGURATION DIALOG IS CLOSED! } public boolean wasAccepted() { return wasAccepted; } public void setStringCharacter(char c) { stringCharTextField.setText(getAsString(c)); } public void setLineSeparator(char c) { lineSeparatorTextField.setText(getAsString(c)); } public void setValueSeparator(char c) { valueSeparatorTextField.setText(getAsString(c)); } public void setEncoding(String encoding) { encodingComboBox.setSelectedItem(encoding); } public char getStringCharacter() { return getAsChar(stringCharTextField.getText()); } public char getLineSeparator() { return getAsChar(lineSeparatorTextField.getText()); } public char getValueSeparator() { return getAsChar(valueSeparatorTextField.getText()); } public String getEncoding() { return encodingComboBox.getSelectedItem().toString(); } // ------- private char getAsChar(String str) { if(str.length() == 0) return 0; if(str != null && str.length() == 1) return str.charAt(0); if(str.charAt(0)=='\\' && str.charAt(1)=='n') return '\n'; if(str.charAt(0)=='\\' && str.charAt(1)=='t') return '\t'; if(str.charAt(0)=='\\' && str.charAt(1)=='r') return '\r'; if(str.charAt(0)=='0' && str.charAt(1)=='x') { try { int n = Integer.parseInt(str.substring(2), 16); return (char) n; } catch(Exception e) { // PASS SILENTLY } } return str.charAt(0); } private String getAsString(char c) { if(c == '\n') return "\\n"; if(c == '\t') return "\\t"; if(c == '\r') return "\\r"; if(c == '\r') return "\\r"; return "" + c; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; optionsPanel = new javax.swing.JPanel(); confLabel = new SimpleLabel(); valueseparatorLabel = new SimpleLabel(); valueSeparatorTextField = new SimpleField(); lineSeparatorLabel = new SimpleLabel(); lineSeparatorTextField = new SimpleField(); stringCharLabel = new SimpleLabel(); stringCharTextField = new SimpleField(); encodingLabel = new SimpleLabel(); encodingComboBox = new SimpleComboBox(); buttonPanel = new javax.swing.JPanel(); fillerPanel = new javax.swing.JPanel(); okButton = new SimpleButton(); cancelButton = new SimpleButton(); setLayout(new java.awt.GridBagLayout()); optionsPanel.setLayout(new java.awt.GridBagLayout()); confLabel.setText("CSV extractor options are"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.insets = new java.awt.Insets(0, 0, 10, 0); optionsPanel.add(confLabel, gridBagConstraints); valueseparatorLabel.setText("Value separator"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.insets = new java.awt.Insets(0, 0, 4, 0); optionsPanel.add(valueseparatorLabel, 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, 4, 4, 0); optionsPanel.add(valueSeparatorTextField, gridBagConstraints); lineSeparatorLabel.setText("Line separator"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.insets = new java.awt.Insets(0, 0, 4, 0); optionsPanel.add(lineSeparatorLabel, 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, 4, 4, 0); optionsPanel.add(lineSeparatorTextField, gridBagConstraints); stringCharLabel.setText("String character"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.insets = new java.awt.Insets(0, 0, 4, 0); optionsPanel.add(stringCharLabel, 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, 4, 4, 0); optionsPanel.add(stringCharTextField, gridBagConstraints); encodingLabel.setText("Character encoding"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.insets = new java.awt.Insets(0, 0, 4, 0); optionsPanel.add(encodingLabel, gridBagConstraints); encodingComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "UTF-8", "UTF-16", "ISO-8859-1", "US-ASCII", " " })); 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, 4, 0); optionsPanel.add(encodingComboBox, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(8, 8, 8, 8); add(optionsPanel, gridBagConstraints); buttonPanel.setLayout(new java.awt.GridBagLayout()); fillerPanel.setLayout(new java.awt.GridBagLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; buttonPanel.add(fillerPanel, gridBagConstraints); okButton.setText("OK"); okButton.setPreferredSize(new java.awt.Dimension(75, 23)); okButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { okButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 2); buttonPanel.add(okButton, gridBagConstraints); cancelButton.setText("Cancel"); cancelButton.setPreferredSize(new java.awt.Dimension(75, 23)); cancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelButtonActionPerformed(evt); } }); 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(2, 2, 2, 2); add(buttonPanel, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed wasAccepted = false; if(myDialog != null) myDialog.setVisible(false); }//GEN-LAST:event_cancelButtonActionPerformed private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed wasAccepted = true; if(myDialog != null) myDialog.setVisible(false); }//GEN-LAST:event_okButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel buttonPanel; private javax.swing.JButton cancelButton; private javax.swing.JLabel confLabel; private javax.swing.JComboBox encodingComboBox; private javax.swing.JLabel encodingLabel; private javax.swing.JPanel fillerPanel; private javax.swing.JLabel lineSeparatorLabel; private javax.swing.JTextField lineSeparatorTextField; private javax.swing.JButton okButton; private javax.swing.JPanel optionsPanel; private javax.swing.JLabel stringCharLabel; private javax.swing.JTextField stringCharTextField; private javax.swing.JTextField valueSeparatorTextField; private javax.swing.JLabel valueseparatorLabel; // End of variables declaration//GEN-END:variables }
12,035
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AbstractCSVExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/csv/AbstractCSVExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.csv; import java.io.ByteArrayInputStream; import java.io.File; import java.net.URL; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.tools.extractors.AbstractExtractor; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.utils.CSVParser; import org.wandora.utils.CSVParser.Table; /** * * @author akivela */ public abstract class AbstractCSVExtractor extends AbstractExtractor implements WandoraTool { private static final long serialVersionUID = 1L; protected static char csvStringCharacter = '"'; protected static char csvLineSeparator = '\n'; protected static char csvValueSeparator = ','; protected static String csvEncoding = "UTF-8"; // ------------------------------------------------------------------------- @Override public boolean isConfigurable() { return true; } @Override public void configure(Wandora wandora, org.wandora.utils.Options options, String prefix) throws TopicMapException { CSVExtractorConfiguration conf = new CSVExtractorConfiguration(); conf.setStringCharacter(csvStringCharacter); conf.setLineSeparator(csvLineSeparator); conf.setValueSeparator(csvValueSeparator); conf.setEncoding(csvEncoding); conf.open(wandora); if(conf.wasAccepted()) { csvStringCharacter = conf.getStringCharacter(); csvLineSeparator = conf.getLineSeparator(); csvValueSeparator = conf.getValueSeparator(); csvEncoding = conf.getEncoding(); } } // ------------------------------------------------------------------------- @Override public boolean _extractTopicsFrom(File f, TopicMap tm) throws Exception { CSVParser parser = new CSVParser(); parser.setEncoding(csvEncoding); parser.setLineSeparator(csvLineSeparator); parser.setValueSeparator(csvValueSeparator); parser.setStringCharacter(csvStringCharacter); Table table = parser.parse(f); return _extractTopicsFrom(table, tm); } @Override public boolean _extractTopicsFrom(URL u, TopicMap tm) throws Exception { CSVParser parser = new CSVParser(); parser.setEncoding(csvEncoding); parser.setLineSeparator(csvLineSeparator); parser.setValueSeparator(csvValueSeparator); parser.setStringCharacter(csvStringCharacter); Table table = parser.parse(u.openStream()); return _extractTopicsFrom(table, tm); } @Override public boolean _extractTopicsFrom(String str, TopicMap tm) throws Exception { CSVParser parser = new CSVParser(); parser.setEncoding(csvEncoding); parser.setLineSeparator(csvLineSeparator); parser.setValueSeparator(csvValueSeparator); parser.setStringCharacter(csvStringCharacter); Table table = parser.parse(new ByteArrayInputStream(str.getBytes())); return _extractTopicsFrom(table, tm); } public abstract boolean _extractTopicsFrom(Table table, TopicMap tm) throws Exception; // ------------------------------------------------------------------------- }
4,168
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimpleCSVAssociationExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/csv/SimpleCSVAssociationExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.csv; import javax.swing.Icon; import org.wandora.application.gui.UIBox; import org.wandora.application.tools.extractors.ExtractHelper; import org.wandora.topicmap.Association; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.utils.CSVParser.Row; import org.wandora.utils.CSVParser.Table; /** * * @author akivela */ public class SimpleCSVAssociationExtractor extends AbstractCSVExtractor { private static final long serialVersionUID = 1L; @Override public String getName() { return "Simple CSV association extractor"; } @Override public String getDescription(){ return "Convert CSV file to topics and associations. Each row in CSV file is transformed "+ "into an association. Each column is transformed into a player topic in the association."; } @Override public boolean useURLCrawler() { return false; } @Override public Icon getIcon() { return UIBox.getIcon(0xf0f6); } @Override public String getGUIText(int textType) { switch(textType) { case SELECT_DIALOG_TITLE: return "Select CSV file(s) or directories containing CSV files!"; case POINT_START_URL_TEXT: return "Where would you like to start the crawl?"; case INFO_WAIT_WHILE_WORKING: return "Wait while reading CSV files!"; case FILE_PATTERN: return ".*\\.(csv|CSV|txt|TXT)"; case DONE_FAILED: return "Ready. No extractions! %1 CSV file(s) crawled!"; case DONE_ONE: return "Ready. Successful extraction! %1 CSV file(s) crawled!"; case DONE_MANY: return "Ready. Total %0 successful extractions! %1 CSV files crawled!"; case LOG_TITLE: return "Simple CSV Extraction Log"; } return ""; } @Override public boolean _extractTopicsFrom(Table table, TopicMap tm) throws Exception { if(table == null || tm == null) return false; Topic csvType = getCSVAssociationType(tm); for(Row row : table) { int i = 0; Association a = tm.createAssociation(csvType); for(Object item : row) { Topic role = getCSVRole(i, tm); Topic player = getCSVTopic(item, tm); a.addPlayer(player, role); i++; } if(i == 0) { a.remove(); } if(forceStop()) break; } return true; } // ------------------------------------------------------------------------- public Topic getCSVAssociationType(TopicMap tm) throws Exception { long stamp = System.currentTimeMillis(); return ExtractHelper.getOrCreateTopic("http://wandora.org/si/csv/association/"+stamp, "CSV association "+stamp, tm); } public Topic getCSVRole(int i, TopicMap tm) throws Exception { return ExtractHelper.getOrCreateTopic("http://wandora.org/si/csv/role/"+i, "CSV role "+i, tm); } public Topic getCSVTopic(Object o, TopicMap tm) throws Exception { String str = urlEncode(o.toString()); return ExtractHelper.getOrCreateTopic("http://wandora.org/si/csv/"+str, str, tm); } }
4,232
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
OpenCycSiblingsExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/opencyc/OpenCycSiblingsExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * OpenCycSiblingsExtractor.java * */ package org.wandora.application.tools.extractors.opencyc; import java.io.InputStream; import org.wandora.topicmap.Association; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; /** * * @author akivela */ public class OpenCycSiblingsExtractor extends AbstractOpenCycExtractor { private static final long serialVersionUID = 1L; /** Creates a new instance of OpenCycSiblingsExtractor */ public OpenCycSiblingsExtractor() { } @Override public String getName() { return "OpenCyc siblings extractor"; } @Override public String getDescription(){ return "Extractor reads the siblings XML feed from OpenCyc's web api and converts the XML feed to a topic map. "+ "See http://65.99.218.242:8080/RESTfulCyc/Constant/Retriever-Dog/siblings for an example of such XML feed."; } public String getMasterTerm(String u) { try { if(u.endsWith("/siblings")) { u = u.substring(0, u.length()-"/siblings".length()); int i = u.lastIndexOf('/'); if(i > 0) { u = u.substring(i+1); return u; } } } catch(Exception e) { log(e); } return null; } 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(); CycSiblingsParser parserHandler = new CycSiblingsParser(getMasterSubject(), 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 + " Cyc siblings found!"); return true; } private static class CycSiblingsParser implements org.xml.sax.ContentHandler, org.xml.sax.ErrorHandler { String masterTerm = null; public CycSiblingsParser(String term, TopicMap tm, AbstractOpenCycExtractor parent){ this.masterTerm = term; this.tm=tm; this.parent=parent; } public int progress=0; private TopicMap tm; private AbstractOpenCycExtractor parent; public static final String TAG_CYCLIFY="cyclify"; public static final String TAG_CONSTANT="constant"; public static final String TAG_LIST="list"; public static final String TAG_SIBLINGS="siblings"; public static final String TAG_GUID="guid"; public static final String TAG_NAME="name"; public static final String TAG_DISPLAYNAME="displayname"; public static final String TAG_NAT="nat"; public static final String TAG_FUNCTOR="functor"; public static final String TAG_ARG="arg"; private static final int STATE_START=0; private static final int STATE_CYCLIFY=2; private static final int STATE_CYCLIFY_CONSTANT=3; private static final int STATE_CYCLIFY_CONSTANT_SIBLINGS=4; private static final int STATE_CYCLIFY_CONSTANT_SIBLINGS_LIST=5; private static final int STATE_CYCLIFY_CONSTANT_SIBLINGS_LIST_CONSTANT=6; private static final int STATE_CYCLIFY_CONSTANT_SIBLINGS_LIST_CONSTANT_GUID=7; private static final int STATE_CYCLIFY_CONSTANT_SIBLINGS_LIST_CONSTANT_NAME=8; private static final int STATE_CYCLIFY_CONSTANT_SIBLINGS_LIST_CONSTANT_DISPLAYNAME=9; private static final int STATE_CYCLIFY_CONSTANT_SIBLINGS_LIST_NAT = 100; private int state=STATE_START; private String data_the_guid = ""; private String data_sibling_guid = ""; private String data_sibling_name = ""; private String data_sibling_displayname = ""; private Topic theTopic; private Topic siblingTopic; 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_CYCLIFY)) { state = STATE_CYCLIFY; } break; case STATE_CYCLIFY: if(qName.equals(TAG_CONSTANT)) { state = STATE_CYCLIFY_CONSTANT; data_the_guid = atts.getValue("guid"); } break; case STATE_CYCLIFY_CONSTANT: if(qName.equals(TAG_SIBLINGS)) { state = STATE_CYCLIFY_CONSTANT_SIBLINGS; } break; case STATE_CYCLIFY_CONSTANT_SIBLINGS: if(qName.equals(TAG_LIST)) { state = STATE_CYCLIFY_CONSTANT_SIBLINGS_LIST; } break; case STATE_CYCLIFY_CONSTANT_SIBLINGS_LIST: if(qName.equals(TAG_CONSTANT)) { state = STATE_CYCLIFY_CONSTANT_SIBLINGS_LIST_CONSTANT; } else if(qName.equals(TAG_NAT)) { state = STATE_CYCLIFY_CONSTANT_SIBLINGS_LIST_NAT; } break; case STATE_CYCLIFY_CONSTANT_SIBLINGS_LIST_CONSTANT: if(qName.equals(TAG_GUID)) { data_sibling_guid = ""; state = STATE_CYCLIFY_CONSTANT_SIBLINGS_LIST_CONSTANT_GUID; } else if(qName.equals(TAG_NAME)) { data_sibling_name = ""; state = STATE_CYCLIFY_CONSTANT_SIBLINGS_LIST_CONSTANT_NAME; } else if(qName.equals(TAG_DISPLAYNAME)) { data_sibling_displayname = ""; state = STATE_CYCLIFY_CONSTANT_SIBLINGS_LIST_CONSTANT_DISPLAYNAME; } break; } } public void endElement(String uri, String localName, String qName) throws SAXException { switch(state) { case STATE_CYCLIFY_CONSTANT_SIBLINGS_LIST_CONSTANT_DISPLAYNAME: { if(qName.equals(TAG_DISPLAYNAME)) { state=STATE_CYCLIFY_CONSTANT_SIBLINGS_LIST_CONSTANT; } break; } case STATE_CYCLIFY_CONSTANT_SIBLINGS_LIST_CONSTANT_NAME: { if(qName.equals(TAG_NAME)) { state=STATE_CYCLIFY_CONSTANT_SIBLINGS_LIST_CONSTANT; } break; } case STATE_CYCLIFY_CONSTANT_SIBLINGS_LIST_CONSTANT_GUID: { if(qName.equals(TAG_GUID)) { state=STATE_CYCLIFY_CONSTANT_SIBLINGS_LIST_CONSTANT; } break; } case STATE_CYCLIFY_CONSTANT_SIBLINGS_LIST_CONSTANT: { if(qName.equals(TAG_CONSTANT)) { try { if(data_the_guid != null && data_the_guid.length() > 0) { theTopic = getTermTopic(data_the_guid, masterTerm, tm); } if(data_sibling_guid != null && data_sibling_guid.length() > 0) { siblingTopic = getTermTopic(data_sibling_guid, data_sibling_name, tm); siblingTopic.setDisplayName(LANG, data_sibling_displayname); parent.setProgress(progress++); if(theTopic != null && siblingTopic != null) { Topic siblingType = getSiblingTypeTopic(tm); Association siblinga = tm.createAssociation(siblingType); siblinga.addPlayer(theTopic, getTermTypeTopic(tm)); siblinga.addPlayer(siblingTopic, siblingType); } } } catch(Exception e) { parent.log(e); } state=STATE_CYCLIFY_CONSTANT_SIBLINGS_LIST; } break; } case STATE_CYCLIFY_CONSTANT_SIBLINGS_LIST_NAT: if(qName.equals(TAG_NAT)) { state = STATE_CYCLIFY_CONSTANT_SIBLINGS_LIST; } break; case STATE_CYCLIFY_CONSTANT_SIBLINGS_LIST: { if(qName.equals(TAG_LIST)) { state=STATE_CYCLIFY_CONSTANT_SIBLINGS; } break; } case STATE_CYCLIFY_CONSTANT_SIBLINGS: { if(qName.equals(TAG_SIBLINGS)) { state=STATE_CYCLIFY_CONSTANT; } break; } case STATE_CYCLIFY_CONSTANT: { if(!qName.equals(TAG_CONSTANT)) { state=STATE_CYCLIFY; } break; } case STATE_CYCLIFY: { state=STATE_START; break; } } } public void characters(char[] ch, int start, int length) throws SAXException { switch(state){ case STATE_CYCLIFY_CONSTANT_SIBLINGS_LIST_CONSTANT_DISPLAYNAME: data_sibling_displayname+=new String(ch,start,length); break; case STATE_CYCLIFY_CONSTANT_SIBLINGS_LIST_CONSTANT_NAME: data_sibling_name+=new String(ch,start,length); break; case STATE_CYCLIFY_CONSTANT_SIBLINGS_LIST_CONSTANT_GUID: data_sibling_guid+=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 {} } }
13,116
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
OpenCycCommentExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/opencyc/OpenCycCommentExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * OpenCycCommentExtractor.java */ package org.wandora.application.tools.extractors.opencyc; import java.io.InputStream; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; /** * * @author akivela */ public class OpenCycCommentExtractor extends AbstractOpenCycExtractor { private static final long serialVersionUID = 1L; /** Creates a new instance of OpenCycCommentExtractor */ public OpenCycCommentExtractor() { } @Override public String getName() { return "OpenCyc comment extractor"; } @Override public String getDescription(){ return "Extractor reads the constant comment XML feed from OpenCyc's web api and converts the XML feed to a topic map. "+ "See http://65.99.218.242:8080/RESTfulCyc/Constant/Food/comment for an example of such XML feed."; } public String getMasterTerm(String u) { try { if(u.endsWith("/comment")) { u = u.substring(0, u.length()-8); int i = u.lastIndexOf('/'); if(i > 0) { u = u.substring(i+1); return u; } } } catch(Exception e) { log(e); } return null; } 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(); CycCommentParser parserHandler = new CycCommentParser(getMasterSubject(), 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 + " Cyc constant comments found!"); return true; } private static class CycCommentParser implements org.xml.sax.ContentHandler, org.xml.sax.ErrorHandler { String masterTerm = null; public CycCommentParser(String term, TopicMap tm, AbstractOpenCycExtractor parent){ this.masterTerm = term; this.tm=tm; this.parent=parent; } public int progress=0; private TopicMap tm; private AbstractOpenCycExtractor parent; public static final String TAG_CYCLIFY="cyclify"; public static final String TAG_CONSTANT="constant"; public static final String TAG_COMMENT="comment"; private static final int STATE_START=0; private static final int STATE_CYCLIFY=2; private static final int STATE_CYCLIFY_CONSTANT=4; private static final int STATE_CYCLIFY_CONSTANT_COMMENT=5; private int state=STATE_START; private String data_comment; private String data_guid; private Topic theTopic; 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_CYCLIFY)) { state = STATE_CYCLIFY; data_guid = null; } break; case STATE_CYCLIFY: if(qName.equals(TAG_CONSTANT)) { state = STATE_CYCLIFY_CONSTANT; data_guid = atts.getValue("guid"); } break; case STATE_CYCLIFY_CONSTANT: if(qName.equals(TAG_COMMENT)) { state = STATE_CYCLIFY_CONSTANT_COMMENT; data_comment = ""; } break; } } public void endElement(String uri, String localName, String qName) throws SAXException { switch(state) { case STATE_CYCLIFY_CONSTANT_COMMENT: { if(qName.equals(TAG_COMMENT)) { state=STATE_CYCLIFY_CONSTANT; } break; } case STATE_CYCLIFY_CONSTANT: { if(qName.equals(TAG_CONSTANT)) { if(data_comment != null && data_comment.length() > 0) { try { parent.setProgress(progress++); theTopic = getTermTopic(data_guid, masterTerm, tm); Topic occurrenceType = getCommentTypeTopic(tm); parent.setData(theTopic, occurrenceType, LANG, data_comment); } catch(Exception e) { parent.log(e); } } state=STATE_CYCLIFY; } break; } case STATE_CYCLIFY: { if(qName.equals(TAG_CYCLIFY)) { state=STATE_START; } break; } } } public void characters(char[] ch, int start, int length) throws SAXException { switch(state){ case STATE_CYCLIFY_CONSTANT_COMMENT: data_comment+=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 {} } }
8,179
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
OpenCycIsaExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/opencyc/OpenCycIsaExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * OpenCycIsaExtractor.java * */ package org.wandora.application.tools.extractors.opencyc; import java.io.InputStream; import org.wandora.topicmap.Association; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; /** * * @author akivela */ public class OpenCycIsaExtractor extends AbstractOpenCycExtractor { private static final long serialVersionUID = 1L; /** Creates a new instance of OpenCycIsaExtractor */ public OpenCycIsaExtractor() { } @Override public String getName() { return "OpenCyc isa extractor"; } @Override public String getDescription(){ return "Extractor reads the isa XML feed from OpenCyc's web api and converts the XML feed to a topic map. "+ "See http://65.99.218.242:8080/RESTfulCyc/Constant/EiffelTower/isa for an example of such XML feed."; } public String getMasterTerm(String u) { try { if(u.endsWith("/isa")) { u = u.substring(0, u.length()-"/isa".length()); int i = u.lastIndexOf('/'); if(i > 0) { u = u.substring(i+1); return u; } } } catch(Exception e) { log(e); } return null; } 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(); CycIsaParser parserHandler = new CycIsaParser(getMasterSubject(), 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 + " Cyc isa's found!"); return true; } private static class CycIsaParser implements org.xml.sax.ContentHandler, org.xml.sax.ErrorHandler { String masterTerm = null; public CycIsaParser(String term, TopicMap tm, AbstractOpenCycExtractor parent){ this.masterTerm = term; this.tm=tm; this.parent=parent; } public int progress=0; private TopicMap tm; private AbstractOpenCycExtractor parent; public static final String TAG_CYCLIFY="cyclify"; public static final String TAG_CONSTANT="constant"; public static final String TAG_LIST="list"; public static final String TAG_ISA="isa"; public static final String TAG_GUID="guid"; public static final String TAG_NAME="name"; public static final String TAG_DISPLAYNAME="displayname"; private static final int STATE_START=0; private static final int STATE_CYCLIFY=2; private static final int STATE_CYCLIFY_CONSTANT=3; private static final int STATE_CYCLIFY_CONSTANT_ISA=4; private static final int STATE_CYCLIFY_CONSTANT_ISA_LIST=5; private static final int STATE_CYCLIFY_CONSTANT_ISA_LIST_CONSTANT=6; private static final int STATE_CYCLIFY_CONSTANT_ISA_LIST_CONSTANT_GUID=7; private static final int STATE_CYCLIFY_CONSTANT_ISA_LIST_CONSTANT_NAME=8; private static final int STATE_CYCLIFY_CONSTANT_ISA_LIST_CONSTANT_DISPLAYNAME=9; private int state=STATE_START; private String data_the_guid = ""; private String data_isa_guid = ""; private String data_isa_name = ""; private String data_isa_displayname = ""; private Topic theTopic; private Topic isaTopic; 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_CYCLIFY)) { state = STATE_CYCLIFY; } break; case STATE_CYCLIFY: if(qName.equals(TAG_CONSTANT)) { state = STATE_CYCLIFY_CONSTANT; data_the_guid = atts.getValue("guid"); } break; case STATE_CYCLIFY_CONSTANT: if(qName.equals(TAG_ISA)) { state = STATE_CYCLIFY_CONSTANT_ISA; } break; case STATE_CYCLIFY_CONSTANT_ISA: if(qName.equals(TAG_LIST)) { state = STATE_CYCLIFY_CONSTANT_ISA_LIST; } break; case STATE_CYCLIFY_CONSTANT_ISA_LIST: if(qName.equals(TAG_CONSTANT)) { data_isa_guid = ""; data_isa_name = ""; data_isa_displayname = ""; state = STATE_CYCLIFY_CONSTANT_ISA_LIST_CONSTANT; } break; case STATE_CYCLIFY_CONSTANT_ISA_LIST_CONSTANT: if(qName.equals(TAG_GUID)) { state = STATE_CYCLIFY_CONSTANT_ISA_LIST_CONSTANT_GUID; } else if(qName.equals(TAG_NAME)) { state = STATE_CYCLIFY_CONSTANT_ISA_LIST_CONSTANT_NAME; } else if(qName.equals(TAG_DISPLAYNAME)) { state = STATE_CYCLIFY_CONSTANT_ISA_LIST_CONSTANT_DISPLAYNAME; } break; } } public void endElement(String uri, String localName, String qName) throws SAXException { switch(state) { case STATE_CYCLIFY_CONSTANT_ISA_LIST_CONSTANT_DISPLAYNAME: { if(qName.equals(TAG_DISPLAYNAME)) { state=STATE_CYCLIFY_CONSTANT_ISA_LIST_CONSTANT; } break; } case STATE_CYCLIFY_CONSTANT_ISA_LIST_CONSTANT_NAME: { if(qName.equals(TAG_NAME)) { state=STATE_CYCLIFY_CONSTANT_ISA_LIST_CONSTANT; } break; } case STATE_CYCLIFY_CONSTANT_ISA_LIST_CONSTANT_GUID: { if(qName.equals(TAG_GUID)) { state=STATE_CYCLIFY_CONSTANT_ISA_LIST_CONSTANT; } break; } case STATE_CYCLIFY_CONSTANT_ISA_LIST_CONSTANT: { if(qName.equals(TAG_CONSTANT)) { try { if(data_the_guid != null && data_the_guid.length() > 0) { theTopic = getTermTopic(data_the_guid, masterTerm, tm); } if(data_isa_guid != null && data_isa_guid.length() > 0) { isaTopic = getTermTopic(data_isa_guid, data_isa_name, tm); isaTopic.setDisplayName(LANG, data_isa_displayname); parent.setProgress(progress++); if(theTopic != null && isaTopic != null) { if(ISA_EQUALS_INSTANCE) { theTopic.addType(isaTopic); } else { Topic isaType = getIsaTypeTopic(tm); Association isaa = tm.createAssociation(isaType); isaa.addPlayer(isaTopic, getCollectionTypeTopic(tm)); isaa.addPlayer(theTopic, getInstanceTypeTopic(tm)); } } } } catch(Exception e) { parent.log(e); } state=STATE_CYCLIFY_CONSTANT_ISA_LIST; } break; } case STATE_CYCLIFY_CONSTANT_ISA_LIST: { if(qName.equals(TAG_LIST)) { state=STATE_CYCLIFY_CONSTANT_ISA; } break; } case STATE_CYCLIFY_CONSTANT_ISA: { if(qName.equals(TAG_ISA)) { state=STATE_CYCLIFY_CONSTANT; } break; } case STATE_CYCLIFY_CONSTANT: { if(!qName.equals(TAG_CONSTANT)) { state=STATE_CYCLIFY; } break; } case STATE_CYCLIFY: { state=STATE_START; break; } } } public void characters(char[] ch, int start, int length) throws SAXException { switch(state){ case STATE_CYCLIFY_CONSTANT_ISA_LIST_CONSTANT_DISPLAYNAME: data_isa_displayname+=new String(ch,start,length); break; case STATE_CYCLIFY_CONSTANT_ISA_LIST_CONSTANT_NAME: data_isa_name+=new String(ch,start,length); break; case STATE_CYCLIFY_CONSTANT_ISA_LIST_CONSTANT_GUID: data_isa_guid+=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 {} } }
12,470
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AbstractOpenCycExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/opencyc/AbstractOpenCycExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * AbstractOpenCycExtractor.java * */ package org.wandora.application.tools.extractors.opencyc; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.net.URL; import javax.swing.Icon; import org.wandora.application.gui.UIBox; import org.wandora.application.tools.extractors.AbstractExtractor; import org.wandora.application.tools.extractors.ExtractHelper; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author akivela */ public abstract class AbstractOpenCycExtractor extends AbstractExtractor { private static final long serialVersionUID = 1L; protected static boolean ISA_EQUALS_INSTANCE = false; public static String termSIBase = "http://www.opencyc.org/"; public static String SIPREFIX="http://wandora.org/si/opencyc/"; public static String COMMENT_SI = SIPREFIX+"comment"; public static String SIBLING_SI = SIPREFIX+"sibling"; public static String FUNCTOR_SI = SIPREFIX+"functor"; public static String ARG_SI = SIPREFIX+"arg"; public static String ISA_SI = SIPREFIX+"isa"; public static String GENLS_SI = SIPREFIX+"genls"; public static String TERM_SI = SIPREFIX+"term"; public static String COLLECTION_SI = SIPREFIX+"collection"; public static String INSTANCE_SI = SIPREFIX+"instance"; // Default language of occurrences and variant names. public static String LANG = "en"; /** * Try to retrieve topic before new to creation. Setting this true may speed * the extraction but extraction may loose some data as topic is created only once. */ public static boolean USE_EXISTING_TOPICS = false; @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_opencyc.png"); } private final String[] contentTypes=new String[] { "text/xml", "application/xml" }; @Override public String[] getContentTypes() { return contentTypes; } @Override public boolean useURLCrawler() { return false; } public boolean _extractTopicsFrom(URL url, TopicMap topicMap) throws Exception { setMasterSubject( getMasterTerm(url.toExternalForm()) ); return _extractTopicsFrom(url.openStream(),topicMap); } public boolean _extractTopicsFrom(File file, TopicMap topicMap) throws Exception { setMasterSubject( getMasterTerm(file.toURI().toURL().toExternalForm()) ); return _extractTopicsFrom(new FileInputStream(file),topicMap); } public boolean _extractTopicsFrom(String str, TopicMap topicMap) throws Exception { setMasterSubject( "http://wandora.org/si/opencyc/" ); return _extractTopicsFrom(new ByteArrayInputStream(str.getBytes()), topicMap); } public abstract boolean _extractTopicsFrom(InputStream inputStream, TopicMap topicMap) throws Exception; public abstract String getMasterTerm(String u); // ------------------------------------------------------------------------- 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 getWandoraClassTopic(TopicMap tm) throws TopicMapException { return getOrCreateTopic(tm, TMBox.WANDORACLASS_SI,"Wandora class"); } protected static Topic getTermTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, TERM_SI, "OpenCyc term"); Topic wandoraClass = getWandoraClassTopic(tm); makeSubclassOf(tm, type, wandoraClass); return type; } protected static Topic getCommentTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, COMMENT_SI, "OpenCyc comment"); return type; } protected static Topic getSiblingTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, SIBLING_SI, "OpenCyc sibling"); return type; } protected static Topic getIsaTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, ISA_SI, "OpenCyc isa"); return type; } protected static Topic getFunctorType(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, FUNCTOR_SI, "OpenCyc functor"); return type; } protected static Topic getArgType(TopicMap tm, int argNum) throws TopicMapException { Topic type=getOrCreateTopic(tm, ARG_SI+argNum, "OpenCyc arg"+argNum); return type; } protected static Topic getCollectionTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, COLLECTION_SI, "OpenCyc collection"); return type; } protected static Topic getInstanceTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, INSTANCE_SI, "OpenCyc instance"); return type; } protected static Topic getTermTopic(String guid, String basename, TopicMap tm) throws TopicMapException { String si = termSIBase+guid; Topic t = null; if(basename != null&& basename.length() > 0) { t = tm.getTopicWithBaseName(basename); } if(t == null && si != null && si.length() > 0) { t = tm.getTopic(si); } if(t == null) { t = tm.createTopic(); if(si != null && si.length() > 0) t.addSubjectIdentifier(new org.wandora.topicmap.Locator( si ) ); else t.addSubjectIdentifier(tm.makeSubjectIndicatorAsLocator()); if(basename != null && basename.length() > 0) t.setBaseName(basename); } Topic termType = getTermTypeTopic(tm); t.addType(termType); return t; } }
7,222
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
OpenCycGenlsExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/opencyc/OpenCycGenlsExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * OpenCycGenlsExtractor.java * */ package org.wandora.application.tools.extractors.opencyc; import java.io.InputStream; import java.util.ArrayList; import java.util.Iterator; import org.wandora.topicmap.Association; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; 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 OpenCycGenlsExtractor extends AbstractOpenCycExtractor { private static final long serialVersionUID = 1L; /** Creates a new instance of OpenCycIsaExtractor */ public OpenCycGenlsExtractor() { } @Override public String getName() { return "OpenCyc genls extractor"; } @Override public String getDescription(){ return "Extractor reads the genls XML feed from OpenCyc's web api and converts the XML feed to a topic map. "+ "See http://65.99.218.242:8080/RESTfulCyc/Constant/Tower/genls for an example of such XML feed."; } public String getMasterTerm(String u) { try { if(u.endsWith("/genls")) { u = u.substring(0, u.length()-"/genls".length()); int i = u.lastIndexOf('/'); if(i > 0) { u = u.substring(i+1); return u; } } } catch(Exception e) { log(e); } return null; } 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(); CycGenlsParser parserHandler = new CycGenlsParser(getMasterSubject(), 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 + " Cyc genls' found!"); return true; } private static class CycGenlsParser implements org.xml.sax.ContentHandler, org.xml.sax.ErrorHandler { String masterTerm = null; public CycGenlsParser(String term, TopicMap tm, AbstractOpenCycExtractor parent){ this.masterTerm = term; this.tm=tm; this.parent=parent; } public int progress=0; private TopicMap tm; private AbstractOpenCycExtractor parent; public static final String TAG_CYCLIFY="cyclify"; public static final String TAG_CONSTANT="constant"; public static final String TAG_LIST="list"; public static final String TAG_GENLS="genls"; public static final String TAG_GUID="guid"; public static final String TAG_NAME="name"; public static final String TAG_DISPLAYNAME="displayname"; public static final String TAG_NAT="nat"; public static final String TAG_FUNCTOR="functor"; public static final String TAG_ARG="arg"; private static final int STATE_START=0; private static final int STATE_CYCLIFY=2; private static final int STATE_CYCLIFY_CONSTANT=3; private static final int STATE_CYCLIFY_CONSTANT_GENLS=4; private static final int STATE_CYCLIFY_CONSTANT_GENLS_LIST=5; private static final int STATE_CYCLIFY_CONSTANT_GENLS_LIST_CONSTANT=6; private static final int STATE_CYCLIFY_CONSTANT_GENLS_LIST_CONSTANT_GUID=7; private static final int STATE_CYCLIFY_CONSTANT_GENLS_LIST_CONSTANT_NAME=8; private static final int STATE_CYCLIFY_CONSTANT_GENLS_LIST_CONSTANT_DISPLAYNAME=9; private static final int STATE_CYCLIFY_CONSTANT_GENLS_LIST_NAT = 200; private static final int STATE_CYCLIFY_CONSTANT_GENLS_LIST_NAT_FUNCTOR = 210; private static final int STATE_CYCLIFY_CONSTANT_GENLS_LIST_NAT_FUNCTOR_GUID = 212; private static final int STATE_CYCLIFY_CONSTANT_GENLS_LIST_NAT_FUNCTOR_NAME = 213; private static final int STATE_CYCLIFY_CONSTANT_GENLS_LIST_NAT_FUNCTOR_DISPLAYNAME = 214; private static final int STATE_CYCLIFY_CONSTANT_GENLS_LIST_NAT_ARG = 220; private static final int STATE_CYCLIFY_CONSTANT_GENLS_LIST_NAT_ARG_GUID = 222; private static final int STATE_CYCLIFY_CONSTANT_GENLS_LIST_NAT_ARG_NAME = 223; private static final int STATE_CYCLIFY_CONSTANT_GENLS_LIST_NAT_ARG_DISPLAYNAME = 224; private int state=STATE_START; private String data_the_guid = ""; private String data_genls_guid = ""; private String data_genls_name = ""; private String data_genls_displayname = ""; private String data_functor_guid = ""; private String data_functor_name = ""; private String data_functor_displayname = ""; private String data_arg_guid = ""; private String data_arg_name = ""; private String data_arg_displayname = ""; private ArrayList args = new ArrayList(); private Topic theTopic; private Topic genlsTopic; 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_CYCLIFY)) { state = STATE_CYCLIFY; } break; case STATE_CYCLIFY: if(qName.equals(TAG_CONSTANT)) { state = STATE_CYCLIFY_CONSTANT; data_the_guid = atts.getValue("guid"); } break; case STATE_CYCLIFY_CONSTANT: if(qName.equals(TAG_GENLS)) { state = STATE_CYCLIFY_CONSTANT_GENLS; } break; case STATE_CYCLIFY_CONSTANT_GENLS: if(qName.equals(TAG_LIST)) { state = STATE_CYCLIFY_CONSTANT_GENLS_LIST; } break; case STATE_CYCLIFY_CONSTANT_GENLS_LIST: if(qName.equals(TAG_CONSTANT)) { data_genls_guid = ""; data_genls_name = ""; data_genls_displayname = ""; state = STATE_CYCLIFY_CONSTANT_GENLS_LIST_CONSTANT; } else if(qName.equals(TAG_NAT)) { data_functor_guid = ""; data_functor_name = ""; data_functor_displayname = ""; data_arg_guid = ""; data_arg_name = ""; data_arg_displayname = ""; args = new ArrayList(); state = STATE_CYCLIFY_CONSTANT_GENLS_LIST_NAT; } break; case STATE_CYCLIFY_CONSTANT_GENLS_LIST_CONSTANT: if(qName.equals(TAG_GUID)) { state = STATE_CYCLIFY_CONSTANT_GENLS_LIST_CONSTANT_GUID; } else if(qName.equals(TAG_NAME)) { state = STATE_CYCLIFY_CONSTANT_GENLS_LIST_CONSTANT_NAME; } else if(qName.equals(TAG_DISPLAYNAME)) { state = STATE_CYCLIFY_CONSTANT_GENLS_LIST_CONSTANT_DISPLAYNAME; } break; case STATE_CYCLIFY_CONSTANT_GENLS_LIST_NAT: if(qName.equals(TAG_FUNCTOR)) { data_functor_guid = ""; data_functor_name = ""; data_functor_displayname = ""; state = STATE_CYCLIFY_CONSTANT_GENLS_LIST_NAT_FUNCTOR; } if(qName.equals(TAG_ARG)) { data_arg_guid = ""; data_arg_name = ""; data_arg_displayname = ""; state = STATE_CYCLIFY_CONSTANT_GENLS_LIST_NAT_ARG; } break; case STATE_CYCLIFY_CONSTANT_GENLS_LIST_NAT_FUNCTOR: if(qName.equals(TAG_GUID)) { state = STATE_CYCLIFY_CONSTANT_GENLS_LIST_NAT_FUNCTOR_GUID; } else if(qName.equals(TAG_NAME)) { state = STATE_CYCLIFY_CONSTANT_GENLS_LIST_NAT_FUNCTOR_NAME; } else if(qName.equals(TAG_DISPLAYNAME)) { state = STATE_CYCLIFY_CONSTANT_GENLS_LIST_NAT_FUNCTOR_DISPLAYNAME; } break; case STATE_CYCLIFY_CONSTANT_GENLS_LIST_NAT_ARG: if(qName.equals(TAG_GUID)) { state = STATE_CYCLIFY_CONSTANT_GENLS_LIST_NAT_ARG_GUID; } else if(qName.equals(TAG_NAME)) { state = STATE_CYCLIFY_CONSTANT_GENLS_LIST_NAT_ARG_NAME; } else if(qName.equals(TAG_DISPLAYNAME)) { state = STATE_CYCLIFY_CONSTANT_GENLS_LIST_NAT_ARG_DISPLAYNAME; } break; } } public void endElement(String uri, String localName, String qName) throws SAXException { switch(state) { case STATE_CYCLIFY_CONSTANT_GENLS_LIST_CONSTANT_DISPLAYNAME: { if(qName.equals(TAG_DISPLAYNAME)) { state=STATE_CYCLIFY_CONSTANT_GENLS_LIST_CONSTANT; } break; } case STATE_CYCLIFY_CONSTANT_GENLS_LIST_CONSTANT_NAME: { if(qName.equals(TAG_NAME)) { state=STATE_CYCLIFY_CONSTANT_GENLS_LIST_CONSTANT; } break; } case STATE_CYCLIFY_CONSTANT_GENLS_LIST_CONSTANT_GUID: { if(qName.equals(TAG_GUID)) { state=STATE_CYCLIFY_CONSTANT_GENLS_LIST_CONSTANT; } break; } case STATE_CYCLIFY_CONSTANT_GENLS_LIST_CONSTANT: { if(qName.equals(TAG_CONSTANT)) { try { if(data_the_guid != null && data_the_guid.length() > 0) { theTopic = getTermTopic(data_the_guid, masterTerm, tm); } if(data_genls_guid != null && data_genls_guid.length() > 0) { genlsTopic = getTermTopic(data_genls_guid, data_genls_name, tm); genlsTopic.setDisplayName(LANG, data_genls_displayname); parent.setProgress(progress++); if(theTopic != null && genlsTopic != null) { makeSubclassOf(tm, theTopic, genlsTopic); } } } catch(Exception e) { parent.log(e); } state=STATE_CYCLIFY_CONSTANT_GENLS_LIST; } break; } // ------------------------- case STATE_CYCLIFY_CONSTANT_GENLS_LIST_NAT_FUNCTOR_DISPLAYNAME: { if(qName.equals(TAG_DISPLAYNAME)) { state=STATE_CYCLIFY_CONSTANT_GENLS_LIST_NAT_FUNCTOR; } break; } case STATE_CYCLIFY_CONSTANT_GENLS_LIST_NAT_FUNCTOR_NAME: { if(qName.equals(TAG_NAME)) { state=STATE_CYCLIFY_CONSTANT_GENLS_LIST_NAT_FUNCTOR; } break; } case STATE_CYCLIFY_CONSTANT_GENLS_LIST_NAT_FUNCTOR_GUID: { if(qName.equals(TAG_GUID)) { state=STATE_CYCLIFY_CONSTANT_GENLS_LIST_NAT_FUNCTOR; } break; } case STATE_CYCLIFY_CONSTANT_GENLS_LIST_NAT_FUNCTOR: { if(qName.equals(TAG_FUNCTOR)) { state=STATE_CYCLIFY_CONSTANT_GENLS_LIST_NAT; } break; } // ---- case STATE_CYCLIFY_CONSTANT_GENLS_LIST_NAT_ARG_DISPLAYNAME: { if(qName.equals(TAG_DISPLAYNAME)) { state=STATE_CYCLIFY_CONSTANT_GENLS_LIST_NAT_ARG; } break; } case STATE_CYCLIFY_CONSTANT_GENLS_LIST_NAT_ARG_NAME: { if(qName.equals(TAG_NAME)) { state=STATE_CYCLIFY_CONSTANT_GENLS_LIST_NAT_ARG; } break; } case STATE_CYCLIFY_CONSTANT_GENLS_LIST_NAT_ARG_GUID: { if(qName.equals(TAG_GUID)) { state=STATE_CYCLIFY_CONSTANT_GENLS_LIST_NAT_ARG; } break; } case STATE_CYCLIFY_CONSTANT_GENLS_LIST_NAT_ARG: { if(qName.equals(TAG_FUNCTOR)) { args.add( data_arg_guid ); args.add( data_arg_name ); args.add( data_arg_displayname ); state=STATE_CYCLIFY_CONSTANT_GENLS_LIST_NAT; } break; } // --- case STATE_CYCLIFY_CONSTANT_GENLS_LIST_NAT: { if(qName.equals(TAG_NAT)) { try { if(data_the_guid != null && data_the_guid.length() > 0) { theTopic = getTermTopic(data_the_guid, masterTerm, tm); } if(data_functor_guid != null && data_functor_guid.length() > 0) { Topic functorTopic = getTermTopic(data_functor_guid, data_functor_name, tm); functorTopic.setDisplayName(LANG, data_functor_displayname); parent.setProgress(progress++); Association a = tm.createAssociation( tm.getTopic(XTMPSI.SUPERCLASS_SUBCLASS )); a.addPlayer(theTopic, tm.getTopic(XTMPSI.SUBCLASS)); a.addPlayer(functorTopic, getFunctorType(tm)); for(Iterator<String> i=args.iterator(); i.hasNext();) { try { String arg_guid = i.next(); String arg_name = i.next(); String arg_displayname = i.next(); int argNum = 1; if(arg_guid != null && arg_guid.length() > 0) { Topic argTopic = getTermTopic(arg_guid, arg_name, tm); if(arg_displayname != null && arg_displayname.length() > 0) argTopic.setDisplayName(LANG, arg_displayname); a.addPlayer(argTopic, getArgType(tm, argNum)); argNum++; } } catch(Exception e) { parent.log(e); } } } } catch(Exception e) { parent.log(e); } state=STATE_CYCLIFY_CONSTANT_GENLS_LIST; } break; } // ----- case STATE_CYCLIFY_CONSTANT_GENLS_LIST: { if(qName.equals(TAG_LIST)) { state=STATE_CYCLIFY_CONSTANT_GENLS; } break; } case STATE_CYCLIFY_CONSTANT_GENLS: { if(qName.equals(TAG_GENLS)) { state=STATE_CYCLIFY_CONSTANT; } break; } case STATE_CYCLIFY_CONSTANT: { if(!qName.equals(TAG_CONSTANT)) { state=STATE_CYCLIFY; } break; } case STATE_CYCLIFY: { state=STATE_START; break; } } } public void characters(char[] ch, int start, int length) throws SAXException { switch(state){ case STATE_CYCLIFY_CONSTANT_GENLS_LIST_CONSTANT_DISPLAYNAME: data_genls_displayname+=new String(ch,start,length); break; case STATE_CYCLIFY_CONSTANT_GENLS_LIST_CONSTANT_NAME: data_genls_name+=new String(ch,start,length); break; case STATE_CYCLIFY_CONSTANT_GENLS_LIST_CONSTANT_GUID: data_genls_guid+=new String(ch,start,length); break; case STATE_CYCLIFY_CONSTANT_GENLS_LIST_NAT_FUNCTOR_DISPLAYNAME: data_functor_displayname+=new String(ch,start,length); break; case STATE_CYCLIFY_CONSTANT_GENLS_LIST_NAT_FUNCTOR_NAME: data_functor_name+=new String(ch,start,length); break; case STATE_CYCLIFY_CONSTANT_GENLS_LIST_NAT_FUNCTOR_GUID: data_functor_guid+=new String(ch,start,length); break; case STATE_CYCLIFY_CONSTANT_GENLS_LIST_NAT_ARG_DISPLAYNAME: data_arg_displayname+=new String(ch,start,length); break; case STATE_CYCLIFY_CONSTANT_GENLS_LIST_NAT_ARG_NAME: data_arg_name+=new String(ch,start,length); break; case STATE_CYCLIFY_CONSTANT_GENLS_LIST_NAT_ARG_GUID: data_arg_guid+=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 {} } }
21,832
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
OpenCycDenotationsExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/opencyc/OpenCycDenotationsExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * OpenCycDenotationsExtractor.java */ package org.wandora.application.tools.extractors.opencyc; import java.io.InputStream; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; /** * * @author akivela */ public class OpenCycDenotationsExtractor extends AbstractOpenCycExtractor { private static final long serialVersionUID = 1L; /** Creates a new instance of OpenCycDenotationsExtractor */ public OpenCycDenotationsExtractor() { } @Override public String getName() { return "OpenCyc denotations extractor"; } @Override public String getDescription(){ return "Extractor reads the denotations XML feed from OpenCyc's web api and converts the XML feed to a topic map. "+ "See http://65.99.218.242:8080/RESTfulCyc/denotation/president for an example of such XML feed."; } public String getMasterTerm(String u) { return null; } 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(); CycDenotationsParser parserHandler = new CycDenotationsParser(getMasterSubject(), 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 + " Cyc denotations found!"); return true; } private static class CycDenotationsParser implements org.xml.sax.ContentHandler, org.xml.sax.ErrorHandler { String masterTerm = null; public CycDenotationsParser(String term, TopicMap tm, AbstractOpenCycExtractor parent){ this.masterTerm = term; this.tm=tm; this.parent=parent; } public int progress=0; private TopicMap tm; private AbstractOpenCycExtractor parent; public static final String TAG_CYCLIFY="cyclify"; public static final String TAG_DENOTATIONS="denotations"; public static final String TAG_LIST="list"; public static final String TAG_CONSTANT="constant"; public static final String TAG_GUID="guid"; public static final String TAG_NAME="name"; public static final String TAG_DISPLAYNAME="displayname"; private static final int STATE_START=0; private static final int STATE_CYCLIFY=2; private static final int STATE_CYCLIFY_DENOTATIONS=4; private static final int STATE_CYCLIFY_DENOTATIONS_CONSTANT=5; private static final int STATE_CYCLIFY_DENOTATIONS_CONSTANT_GUID=6; private static final int STATE_CYCLIFY_DENOTATIONS_CONSTANT_NAME=7; private static final int STATE_CYCLIFY_DENOTATIONS_CONSTANT_DISPLAYNAME=8; private int state=STATE_START; private String data_denotations_string = ""; private String data_guid = ""; private String data_name = ""; private String data_displayname = ""; private Topic theTopic; 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_CYCLIFY)) { state = STATE_CYCLIFY; data_guid = null; } break; case STATE_CYCLIFY: if(qName.equals(TAG_DENOTATIONS)) { state = STATE_CYCLIFY_DENOTATIONS; data_denotations_string = atts.getValue("string"); } break; case STATE_CYCLIFY_DENOTATIONS: if(qName.equals(TAG_LIST)) { } else if(qName.equals(TAG_CONSTANT)) { state = STATE_CYCLIFY_DENOTATIONS_CONSTANT; } break; case STATE_CYCLIFY_DENOTATIONS_CONSTANT: if(qName.equals(TAG_GUID)) { state = STATE_CYCLIFY_DENOTATIONS_CONSTANT_GUID; data_guid = ""; } else if(qName.equals(TAG_NAME)) { state = STATE_CYCLIFY_DENOTATIONS_CONSTANT_NAME; data_name = ""; } else if(qName.equals(TAG_DISPLAYNAME)) { state = STATE_CYCLIFY_DENOTATIONS_CONSTANT_DISPLAYNAME; data_displayname = ""; } break; } } public void endElement(String uri, String localName, String qName) throws SAXException { switch(state) { case STATE_CYCLIFY_DENOTATIONS_CONSTANT_DISPLAYNAME: { if(qName.equals(TAG_DISPLAYNAME)) { state=STATE_CYCLIFY_DENOTATIONS_CONSTANT; } break; } case STATE_CYCLIFY_DENOTATIONS_CONSTANT_NAME: { if(qName.equals(TAG_NAME)) { state=STATE_CYCLIFY_DENOTATIONS_CONSTANT; } break; } case STATE_CYCLIFY_DENOTATIONS_CONSTANT_GUID: { if(qName.equals(TAG_GUID)) { state=STATE_CYCLIFY_DENOTATIONS_CONSTANT; } break; } case STATE_CYCLIFY_DENOTATIONS_CONSTANT: { if(qName.equals(TAG_CONSTANT)) { if(data_displayname != null && data_displayname.length() > 0) { try { parent.setProgress(progress++); theTopic = getTermTopic(data_guid, data_name, tm); theTopic.setDisplayName(LANG, data_displayname); } catch(Exception e) { parent.log(e); } } state=STATE_CYCLIFY_DENOTATIONS; } break; } case STATE_CYCLIFY_DENOTATIONS: { if(qName.equals(TAG_DENOTATIONS)) { state=STATE_CYCLIFY; } break; } case STATE_CYCLIFY: { if(qName.equals(TAG_CYCLIFY)) { state=STATE_START; } break; } } } public void characters(char[] ch, int start, int length) throws SAXException { switch(state){ case STATE_CYCLIFY_DENOTATIONS_CONSTANT_DISPLAYNAME: data_displayname+=new String(ch,start,length); break; case STATE_CYCLIFY_DENOTATIONS_CONSTANT_NAME: data_name+=new String(ch,start,length); break; case STATE_CYCLIFY_DENOTATIONS_CONSTANT_GUID: data_guid+=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,193
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
OpenCycExtractorSelector.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/opencyc/OpenCycExtractorSelector.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * OpenCycExtractorSelector.java * * Created on 22.7.2008, 12:17 */ package org.wandora.application.tools.extractors.opencyc; import java.awt.Component; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Iterator; import javax.swing.JDialog; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.tools.extractors.rdf.OpenCYCOWLExtractor; import org.wandora.topicmap.Topic; /** * Originally this extractor was created for openCYC rest API at 65.99.218.242. * However, it seems the rest API is very unstable and rarely answers requests. * Therefore this extractor has been changes and performs now an extraction to * the semantic web endpoint of the CYC at http://sw.opencyc.org/2012/05/10/concept/en/ . * As a consequence the number of available subextractors has decreased to one. * * Old rest API extractors are still available but requires some changes in * UI. To activate old rest API extractors, move their UI tabs (panels) from * Other components to cycTabbedPane. * * @author akivela */ public class OpenCycExtractorSelector extends JDialog { private static final long serialVersionUID = 1L; public static String webServiceBase = "http://65.99.218.242:8080/RESTfulCyc/"; private Wandora wandora = null; private Context context = null; private boolean accepted = false; /** Creates new form OpenCycExtractorSelector */ public OpenCycExtractorSelector(Wandora wandora) { super(wandora, true); initComponents(); setTitle("OpenCyc extractors"); setSize(450,300); wandora.centerWindow(this); this.wandora = wandora; accepted = false; } public void setWandora(Wandora wandora) { this.wandora = wandora; } public void setContext(Context context) { this.context = context; } public boolean wasAccepted() { return accepted; } public void setAccepted(boolean b) { accepted = b; } public WandoraTool getWandoraTool(WandoraTool parentTool) { Component component = cycTabbedPane.getSelectedComponent(); WandoraTool wt = null; if(swConceptPanel.equals(component)) { String conceptsAll = swConceptField.getText(); String[] concepts = urlEncode(commaSplitter(conceptsAll)); // http://sw.opencyc.org/2012/05/10/concept/en/Game String[] termUrls = completeString("http://sw.opencyc.org/2012/05/10/concept/en/__1__", concepts); // Notice the semantic web ap of CYC actually returns RDF triplets. // Thus, we use OpenCYCOWLExtractor. OpenCYCOWLExtractor ex = new OpenCYCOWLExtractor(); ex.setForceUrls( termUrls ); wt = ex; } // ***** TERM COMMENTS ***** else if(commentsTab.equals(component)) { String termsAll = commentsField.getText(); String[] terms = urlEncode(commaSplitter(termsAll)); // http://65.99.218.242:8080/RESTfulCyc/Constant/Food/comment String[] termUrls = completeString(webServiceBase+"Constant/__1__/comment", terms); OpenCycCommentExtractor ex = new OpenCycCommentExtractor(); ex.setForceUrls( termUrls ); wt = ex; } // ***** DENOTATIONS ***** else if(denotationsTab.equals(component)) { String termsAll = denotationsField.getText(); String[] terms = urlEncode(commaSplitter(termsAll)); // http://65.99.218.242:8080/RESTfulCyc/denotation/president String[] termUrls = completeString(webServiceBase+"denotation/__1__", terms); OpenCycDenotationsExtractor ex = new OpenCycDenotationsExtractor(); ex.setForceUrls( termUrls ); wt = ex; } // ***** SIBLINGS ***** else if(siblingsTab.equals(component)) { String termsAll = siblingsField.getText(); String[] terms = urlEncode(commaSplitter(termsAll)); // http://65.99.218.242:8080/RESTfulCyc/Constant/Retriever-Dog/siblings String[] termUrls = completeString(webServiceBase+"Constant/__1__/siblings", terms); OpenCycSiblingsExtractor ex = new OpenCycSiblingsExtractor(); ex.setForceUrls( termUrls ); wt = ex; } // ***** ISA ***** else if(isaTab.equals(component)) { String termsAll = isaField.getText(); String[] terms = urlEncode(commaSplitter(termsAll)); // http://65.99.218.242:8080/RESTfulCyc/Constant/EiffelTower/isa String[] termUrls = completeString(webServiceBase+"Constant/__1__/isa", terms); OpenCycIsaExtractor ex = new OpenCycIsaExtractor(); ex.setForceUrls( termUrls ); wt = ex; } // ***** INSTANCE ***** else if(instancesTab.equals(component)) { String termsAll = instancesField.getText(); String[] terms = urlEncode(commaSplitter(termsAll)); // http://65.99.218.242:8080/RESTfulCyc/Constant/Dog/instances String[] termUrls = completeString(webServiceBase+"Constant/__1__/instances", terms); OpenCycInstanceExtractor ex = new OpenCycInstanceExtractor(); ex.setForceUrls( termUrls ); wt = ex; } // ***** GENERALIZATIONS ***** else if(genlsTab.equals(component)) { String termsAll = genlsField.getText(); String[] terms = urlEncode(commaSplitter(termsAll)); // http://65.99.218.242:8080/RESTfulCyc/Constant/EiffelTower/genls String[] termUrls = completeString(webServiceBase+"Constant/__1__/genls", terms); OpenCycGenlsExtractor ex = new OpenCycGenlsExtractor(); ex.setForceUrls( termUrls ); wt = ex; } // ***** SPECIALIZATIONS ***** else if(specsTab.equals(component)) { String termsAll = specsField.getText(); String[] terms = urlEncode(commaSplitter(termsAll)); // http://65.99.218.242:8080/RESTfulCyc/Constant/Shirt/specs String[] termUrls = completeString(webServiceBase+"Constant/__1__/specs", terms); OpenCycSpecsExtractor ex = new OpenCycSpecsExtractor(); ex.setForceUrls( termUrls ); wt = ex; } return wt; } public String[] commaSplitter(String str) { if(str.indexOf(',') != -1) { String[] strs = str.split(","); ArrayList<String> strList = new ArrayList<String>(); String s = null; for(int i=0; i<strs.length; i++) { s = strs[i]; s = s.trim(); if(s.length() > 0) { strList.add(s); } } return strList.toArray( new String[] {} ); } else { return new String[] { str }; } } public String[] completeString(String template, String[] strs) { if(strs == null || template == null) return null; String[] completed = new String[strs.length]; for(int i=0; i<strs.length; i++) { completed[i] = template.replaceAll("__1__", strs[i]); } return completed; } public String[] completeString(String template, String[] strs1, String[] strs2) { if(strs1 == null || strs2 == null || template == null) return null; if(strs1.length != strs2.length) return null; String[] completed = new String[strs1.length]; for(int i=0; i<strs1.length; i++) { completed[i] = template.replaceAll("__1__", strs1[i]); completed[i] = completed[i].replaceAll("__2__", strs2[i]); } return completed; } public String[] urlEncode(String[] urls) { if(urls == null) return null; String[] cleanUrls = new String[urls.length]; for(int i=0; i<urls.length; i++) { cleanUrls[i] = urlEncode(urls[i]); } return cleanUrls; } public String urlEncode(String url) { try { return URLEncoder.encode(url, "UTF-8"); } catch(Exception e) { return url; } } public String getContextAsString() { StringBuilder sb = new StringBuilder(""); if(context != null) { try { Iterator contextObjects = context.getContextObjects(); String str = null; Object o = null; while(contextObjects.hasNext()) { str = null; o = contextObjects.next(); if(o instanceof Topic) { Topic t = (Topic) o; str = t.getBaseName(); if(str != null) { str = str.trim(); } else { str = t.getOneSubjectIdentifier().toExternalForm(); if(str.indexOf('/') != -1) { str = str.substring(str.lastIndexOf('/')+1); 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; isaTab = new javax.swing.JPanel(); isaInnerPanel = new javax.swing.JPanel(); isaLabel = new org.wandora.application.gui.simple.SimpleLabel(); isaField = new org.wandora.application.gui.simple.SimpleField(); isaGetButton = new org.wandora.application.gui.simple.SimpleButton(); instancesTab = new javax.swing.JPanel(); instancesInnerPanel = new javax.swing.JPanel(); instancesLabel = new org.wandora.application.gui.simple.SimpleLabel(); instancesField = new org.wandora.application.gui.simple.SimpleField(); instancesGetButton = new org.wandora.application.gui.simple.SimpleButton(); genlsTab = new javax.swing.JPanel(); genlsInnerPanel = new javax.swing.JPanel(); genlsLabel = new org.wandora.application.gui.simple.SimpleLabel(); genlsField = new org.wandora.application.gui.simple.SimpleField(); genlsGetButton = new org.wandora.application.gui.simple.SimpleButton(); specsTab = new javax.swing.JPanel(); specsInnerPanel = new javax.swing.JPanel(); specsLabel = new org.wandora.application.gui.simple.SimpleLabel(); specsField = new org.wandora.application.gui.simple.SimpleField(); specsButton = new org.wandora.application.gui.simple.SimpleButton(); siblingsTab = new javax.swing.JPanel(); siblingsInnerPanel = new javax.swing.JPanel(); siblingsLabel = new org.wandora.application.gui.simple.SimpleLabel(); siblingsField = new org.wandora.application.gui.simple.SimpleField(); siblingsGetButton = new org.wandora.application.gui.simple.SimpleButton(); commentsTab = new javax.swing.JPanel(); commentsInnerPanel = new javax.swing.JPanel(); commentsLabel = new org.wandora.application.gui.simple.SimpleLabel(); commentsField = new org.wandora.application.gui.simple.SimpleField(); commentsGetButton = new org.wandora.application.gui.simple.SimpleButton(); denotationsTab = new javax.swing.JPanel(); denotationsInnerPanel = new javax.swing.JPanel(); denotationsLabel = new org.wandora.application.gui.simple.SimpleLabel(); denotationsField = new org.wandora.application.gui.simple.SimpleField(); denotationsGetButton = new org.wandora.application.gui.simple.SimpleButton(); cycTabbedPane = new org.wandora.application.gui.simple.SimpleTabbedPane(); swConceptPanel = new javax.swing.JPanel(); swConceptInnerPanel = new javax.swing.JPanel(); swConceptLabel = new org.wandora.application.gui.simple.SimpleLabel(); swConceptField = new org.wandora.application.gui.simple.SimpleField(); swConceptGetButton = new org.wandora.application.gui.simple.SimpleButton(); buttonPanel = new javax.swing.JPanel(); emptyPanel = new javax.swing.JPanel(); okButton = new org.wandora.application.gui.simple.SimpleButton(); cancelButton = new org.wandora.application.gui.simple.SimpleButton(); isaTab.setLayout(new java.awt.GridBagLayout()); isaInnerPanel.setLayout(new java.awt.GridBagLayout()); isaLabel.setText("<html>Fetch classes for given terms. Cyc classes are isa related terms. Please write term names below or get the context. Use comma (,) character to separate different terms.</html>"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 10, 0); isaInnerPanel.add(isaLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; isaInnerPanel.add(isaField, gridBagConstraints); isaGetButton.setLabel("Get context"); isaGetButton.setMargin(new java.awt.Insets(0, 2, 1, 2)); isaGetButton.setMaximumSize(new java.awt.Dimension(90, 20)); isaGetButton.setMinimumSize(new java.awt.Dimension(90, 20)); isaGetButton.setPreferredSize(new java.awt.Dimension(90, 20)); isaGetButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { isaGetButtonMouseReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.insets = new java.awt.Insets(10, 5, 0, 0); isaInnerPanel.add(isaGetButton, 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); isaTab.add(isaInnerPanel, gridBagConstraints); instancesTab.setLayout(new java.awt.GridBagLayout()); instancesInnerPanel.setLayout(new java.awt.GridBagLayout()); instancesLabel.setText("<html>Fetch instances for given terms. Please write term names below or get the context. Use comma (,) character to separate different terms.</html>"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 10, 0); instancesInnerPanel.add(instancesLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; instancesInnerPanel.add(instancesField, gridBagConstraints); instancesGetButton.setLabel("Get context"); instancesGetButton.setMargin(new java.awt.Insets(0, 2, 1, 2)); instancesGetButton.setMaximumSize(new java.awt.Dimension(90, 20)); instancesGetButton.setMinimumSize(new java.awt.Dimension(90, 20)); instancesGetButton.setPreferredSize(new java.awt.Dimension(90, 20)); instancesGetButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { instancesGetButtonMouseReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.insets = new java.awt.Insets(10, 5, 0, 0); instancesInnerPanel.add(instancesGetButton, 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); instancesTab.add(instancesInnerPanel, gridBagConstraints); genlsTab.setLayout(new java.awt.GridBagLayout()); genlsInnerPanel.setLayout(new java.awt.GridBagLayout()); genlsLabel.setText("<html>Fetch superclasses i.e. generalizations for given terms. Cyc generalizations are genls related terms. Please write term names below or get the context. Use comma (,) character to separate different terms.</html>"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 10, 0); genlsInnerPanel.add(genlsLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; genlsInnerPanel.add(genlsField, gridBagConstraints); genlsGetButton.setLabel("Get context"); genlsGetButton.setMargin(new java.awt.Insets(0, 2, 1, 2)); genlsGetButton.setMaximumSize(new java.awt.Dimension(90, 20)); genlsGetButton.setMinimumSize(new java.awt.Dimension(90, 20)); genlsGetButton.setPreferredSize(new java.awt.Dimension(90, 20)); genlsGetButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { genlsGetButtonMouseReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.insets = new java.awt.Insets(10, 5, 0, 0); genlsInnerPanel.add(genlsGetButton, 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); genlsTab.add(genlsInnerPanel, gridBagConstraints); specsTab.setLayout(new java.awt.GridBagLayout()); specsInnerPanel.setLayout(new java.awt.GridBagLayout()); specsLabel.setText("<html>Fetch subclasses i.e. specializations for given terms. Please write term names below or get the context. Use comma (,) character to separate different terms.</html>"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 10, 0); specsInnerPanel.add(specsLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; specsInnerPanel.add(specsField, gridBagConstraints); specsButton.setLabel("Get context"); specsButton.setMargin(new java.awt.Insets(0, 2, 1, 2)); specsButton.setMaximumSize(new java.awt.Dimension(90, 20)); specsButton.setMinimumSize(new java.awt.Dimension(90, 20)); specsButton.setPreferredSize(new java.awt.Dimension(90, 20)); specsButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { specsButtonMouseReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.insets = new java.awt.Insets(10, 5, 0, 0); specsInnerPanel.add(specsButton, 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); specsTab.add(specsInnerPanel, gridBagConstraints); siblingsTab.setLayout(new java.awt.GridBagLayout()); siblingsInnerPanel.setLayout(new java.awt.GridBagLayout()); siblingsLabel.setText("<html>Fetch siblings for given terms. Please write terms below or get the context. Use comma character (,) to separate different terms.</html>"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 10, 0); siblingsInnerPanel.add(siblingsLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; siblingsInnerPanel.add(siblingsField, gridBagConstraints); siblingsGetButton.setLabel("Get context"); siblingsGetButton.setMargin(new java.awt.Insets(0, 2, 1, 2)); siblingsGetButton.setMaximumSize(new java.awt.Dimension(90, 20)); siblingsGetButton.setMinimumSize(new java.awt.Dimension(90, 20)); siblingsGetButton.setPreferredSize(new java.awt.Dimension(90, 20)); siblingsGetButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { siblingsGetButtonMouseReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.insets = new java.awt.Insets(10, 5, 0, 0); siblingsInnerPanel.add(siblingsGetButton, 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); siblingsTab.add(siblingsInnerPanel, gridBagConstraints); commentsTab.setLayout(new java.awt.GridBagLayout()); commentsInnerPanel.setLayout(new java.awt.GridBagLayout()); commentsLabel.setText("<html>Fetch comments for given terms. Please write terms below or get the context. Use comma (,) character to separate different terms.</html>"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 10, 0); commentsInnerPanel.add(commentsLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; commentsInnerPanel.add(commentsField, gridBagConstraints); commentsGetButton.setLabel("Get context"); commentsGetButton.setMargin(new java.awt.Insets(0, 2, 1, 2)); commentsGetButton.setMaximumSize(new java.awt.Dimension(90, 20)); commentsGetButton.setMinimumSize(new java.awt.Dimension(90, 20)); commentsGetButton.setPreferredSize(new java.awt.Dimension(90, 20)); commentsGetButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { commentsGetButtonMouseReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.insets = new java.awt.Insets(10, 5, 0, 0); commentsInnerPanel.add(commentsGetButton, 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); commentsTab.add(commentsInnerPanel, gridBagConstraints); denotationsTab.setLayout(new java.awt.GridBagLayout()); denotationsInnerPanel.setLayout(new java.awt.GridBagLayout()); denotationsLabel.setText("<html>Fetch denotations for given terms. Please write terms below or get the context. Use comma (,) character to separate different terms.</html>"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 10, 0); denotationsInnerPanel.add(denotationsLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; denotationsInnerPanel.add(denotationsField, gridBagConstraints); denotationsGetButton.setLabel("Get context"); denotationsGetButton.setMargin(new java.awt.Insets(0, 2, 1, 2)); denotationsGetButton.setMaximumSize(new java.awt.Dimension(90, 20)); denotationsGetButton.setMinimumSize(new java.awt.Dimension(90, 20)); denotationsGetButton.setPreferredSize(new java.awt.Dimension(90, 20)); denotationsGetButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { denotationsGetButtonMouseReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.insets = new java.awt.Insets(10, 5, 0, 0); denotationsInnerPanel.add(denotationsGetButton, 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); denotationsTab.add(denotationsInnerPanel, gridBagConstraints); getContentPane().setLayout(new java.awt.GridBagLayout()); swConceptPanel.setLayout(new java.awt.GridBagLayout()); swConceptInnerPanel.setLayout(new java.awt.GridBagLayout()); swConceptLabel.setText("<html>Extract information about CYC concepts. Please write concept names below or get context names. Use comma (,) character to separate names. Notice, a name of CYC concept is in camel case, for example 'Cat', 'IsaacNewton'.</html>"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 10, 0); swConceptInnerPanel.add(swConceptLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; swConceptInnerPanel.add(swConceptField, gridBagConstraints); swConceptGetButton.setLabel("Get context"); swConceptGetButton.setMargin(new java.awt.Insets(0, 2, 1, 2)); swConceptGetButton.setMaximumSize(new java.awt.Dimension(90, 20)); swConceptGetButton.setMinimumSize(new java.awt.Dimension(90, 20)); swConceptGetButton.setPreferredSize(new java.awt.Dimension(90, 20)); swConceptGetButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { swConceptGetButtonMouseReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.insets = new java.awt.Insets(10, 5, 0, 0); swConceptInnerPanel.add(swConceptGetButton, 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); swConceptPanel.add(swConceptInnerPanel, gridBagConstraints); cycTabbedPane.addTab("Concept", swConceptPanel); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; getContentPane().add(cycTabbedPane, gridBagConstraints); buttonPanel.setLayout(new java.awt.GridBagLayout()); emptyPanel.setPreferredSize(new java.awt.Dimension(100, 10)); javax.swing.GroupLayout emptyPanelLayout = new javax.swing.GroupLayout(emptyPanel); emptyPanel.setLayout(emptyPanelLayout); emptyPanelLayout.setHorizontalGroup( emptyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 252, Short.MAX_VALUE) ); emptyPanelLayout.setVerticalGroup( emptyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 10, Short.MAX_VALUE) ); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; buttonPanel.add(emptyPanel, gridBagConstraints); okButton.setText("Extract"); okButton.setPreferredSize(new java.awt.Dimension(75, 23)); okButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { okButtonMouseReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3); buttonPanel.add(okButton, gridBagConstraints); cancelButton.setText("Cancel"); cancelButton.setPreferredSize(new java.awt.Dimension(75, 23)); cancelButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { cancelButtonMouseReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 0; buttonPanel.add(cancelButton, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); getContentPane().add(buttonPanel, gridBagConstraints); pack(); }// </editor-fold>//GEN-END:initComponents private void commentsGetButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_commentsGetButtonMouseReleased commentsField.setText(getContextAsString()); }//GEN-LAST:event_commentsGetButtonMouseReleased private void denotationsGetButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_denotationsGetButtonMouseReleased denotationsField.setText(getContextAsString()); }//GEN-LAST:event_denotationsGetButtonMouseReleased private void siblingsGetButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_siblingsGetButtonMouseReleased siblingsField.setText(getContextAsString()); }//GEN-LAST:event_siblingsGetButtonMouseReleased private void isaGetButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_isaGetButtonMouseReleased isaField.setText(getContextAsString()); }//GEN-LAST:event_isaGetButtonMouseReleased private void genlsGetButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_genlsGetButtonMouseReleased genlsField.setText(getContextAsString()); }//GEN-LAST:event_genlsGetButtonMouseReleased private void specsButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_specsButtonMouseReleased specsField.setText(getContextAsString()); }//GEN-LAST:event_specsButtonMouseReleased private void okButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_okButtonMouseReleased accepted = true; setVisible(false); }//GEN-LAST:event_okButtonMouseReleased private void cancelButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cancelButtonMouseReleased accepted = false; setVisible(false); }//GEN-LAST:event_cancelButtonMouseReleased private void instancesGetButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_instancesGetButtonMouseReleased instancesField.setText(getContextAsString()); }//GEN-LAST:event_instancesGetButtonMouseReleased private void swConceptGetButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_swConceptGetButtonMouseReleased swConceptField.setText(getContextAsString()); }//GEN-LAST:event_swConceptGetButtonMouseReleased // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel buttonPanel; private javax.swing.JButton cancelButton; private javax.swing.JTextField commentsField; private javax.swing.JButton commentsGetButton; private javax.swing.JPanel commentsInnerPanel; private javax.swing.JLabel commentsLabel; private javax.swing.JPanel commentsTab; private javax.swing.JTabbedPane cycTabbedPane; private javax.swing.JTextField denotationsField; private javax.swing.JButton denotationsGetButton; private javax.swing.JPanel denotationsInnerPanel; private javax.swing.JLabel denotationsLabel; private javax.swing.JPanel denotationsTab; private javax.swing.JPanel emptyPanel; private javax.swing.JTextField genlsField; private javax.swing.JButton genlsGetButton; private javax.swing.JPanel genlsInnerPanel; private javax.swing.JLabel genlsLabel; private javax.swing.JPanel genlsTab; private javax.swing.JTextField instancesField; private javax.swing.JButton instancesGetButton; private javax.swing.JPanel instancesInnerPanel; private javax.swing.JLabel instancesLabel; private javax.swing.JPanel instancesTab; private javax.swing.JTextField isaField; private javax.swing.JButton isaGetButton; private javax.swing.JPanel isaInnerPanel; private javax.swing.JLabel isaLabel; private javax.swing.JPanel isaTab; private javax.swing.JButton okButton; private javax.swing.JTextField siblingsField; private javax.swing.JButton siblingsGetButton; private javax.swing.JPanel siblingsInnerPanel; private javax.swing.JLabel siblingsLabel; private javax.swing.JPanel siblingsTab; private javax.swing.JButton specsButton; private javax.swing.JTextField specsField; private javax.swing.JPanel specsInnerPanel; private javax.swing.JLabel specsLabel; private javax.swing.JPanel specsTab; private javax.swing.JTextField swConceptField; private javax.swing.JButton swConceptGetButton; private javax.swing.JPanel swConceptInnerPanel; private javax.swing.JLabel swConceptLabel; private javax.swing.JPanel swConceptPanel; // End of variables declaration//GEN-END:variables }
39,020
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
OpenCycExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/opencyc/OpenCycExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * OpenCycExtractor.java * */ package org.wandora.application.tools.extractors.opencyc; 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; /** * OpenCyc API has been closed and this extractor (and all other OpenCyc * extractors are more or less deprecated. However, the code is still * kept in safe if the API opens up later on or somebody publishes * similar API. * * @author akivela */ public class OpenCycExtractor extends AbstractWandoraTool { private static final long serialVersionUID = 1L; private static OpenCycExtractorSelector selector = null; @Override public String getName() { return "OpenCyc extractor..."; } @Override public String getDescription(){ return "Convert various OpenCyc XML feeds to topic maps"; } @Override public WandoraToolType getType() { return WandoraToolType.createExtractType(); } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_opencyc.png"); } public void execute(Wandora admin, Context context) { int counter = 0; try { if(selector == null) { selector = new OpenCycExtractorSelector(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); } }
3,048
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
OpenCycSpecsExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/opencyc/OpenCycSpecsExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * OpenCycGenlsExtractor.java * */ package org.wandora.application.tools.extractors.opencyc; import java.io.InputStream; import java.util.ArrayList; import java.util.Iterator; import org.wandora.topicmap.Association; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; 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 OpenCycSpecsExtractor extends AbstractOpenCycExtractor { private static final long serialVersionUID = 1L; /** Creates a new instance of OpenCycIsaExtractor */ public OpenCycSpecsExtractor() { } @Override public String getName() { return "OpenCyc specs extractor"; } @Override public String getDescription(){ return "Extractor reads the specs XML feed from OpenCyc's web api and converts the XML feed to a topic map. "+ "See http://65.99.218.242:8080/RESTfulCyc/Constant/Shirt/specs for an example of such XML feed."; } public String getMasterTerm(String u) { try { if(u.endsWith("/specs")) { u = u.substring(0, u.length()-"/specs".length()); int i = u.lastIndexOf('/'); if(i > 0) { u = u.substring(i+1); return u; } } } catch(Exception e) { log(e); } return null; } 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(); CycSpecsParser parserHandler = new CycSpecsParser(getMasterSubject(), 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 + " Cyc specs' found!"); return true; } private static class CycSpecsParser implements org.xml.sax.ContentHandler, org.xml.sax.ErrorHandler { String masterTerm = null; public CycSpecsParser(String term, TopicMap tm, AbstractOpenCycExtractor parent){ this.masterTerm = term; this.tm=tm; this.parent=parent; } public int progress=0; private TopicMap tm; private AbstractOpenCycExtractor parent; public static final String TAG_CYCLIFY="cyclify"; public static final String TAG_CONSTANT="constant"; public static final String TAG_LIST="list"; public static final String TAG_SPECS="specs"; public static final String TAG_GUID="guid"; public static final String TAG_NAME="name"; public static final String TAG_DISPLAYNAME="displayname"; public static final String TAG_NAT="nat"; public static final String TAG_FUNCTOR="functor"; public static final String TAG_ARG="arg"; private static final int STATE_START=0; private static final int STATE_CYCLIFY=2; private static final int STATE_CYCLIFY_CONSTANT=3; private static final int STATE_CYCLIFY_CONSTANT_SPECS=4; private static final int STATE_CYCLIFY_CONSTANT_SPECS_LIST=5; private static final int STATE_CYCLIFY_CONSTANT_SPECS_LIST_CONSTANT=6; private static final int STATE_CYCLIFY_CONSTANT_SPECS_LIST_CONSTANT_GUID=7; private static final int STATE_CYCLIFY_CONSTANT_SPECS_LIST_CONSTANT_NAME=8; private static final int STATE_CYCLIFY_CONSTANT_SPECS_LIST_CONSTANT_DISPLAYNAME=9; private static final int STATE_CYCLIFY_CONSTANT_SPECS_LIST_NAT = 200; private static final int STATE_CYCLIFY_CONSTANT_SPECS_LIST_NAT_FUNCTOR = 210; private static final int STATE_CYCLIFY_CONSTANT_SPECS_LIST_NAT_FUNCTOR_GUID = 212; private static final int STATE_CYCLIFY_CONSTANT_SPECS_LIST_NAT_FUNCTOR_NAME = 213; private static final int STATE_CYCLIFY_CONSTANT_SPECS_LIST_NAT_FUNCTOR_DISPLAYNAME = 214; private static final int STATE_CYCLIFY_CONSTANT_SPECS_LIST_NAT_ARG = 220; private static final int STATE_CYCLIFY_CONSTANT_SPECS_LIST_NAT_ARG_GUID = 222; private static final int STATE_CYCLIFY_CONSTANT_SPECS_LIST_NAT_ARG_NAME = 223; private static final int STATE_CYCLIFY_CONSTANT_SPECS_LIST_NAT_ARG_DISPLAYNAME = 224; private int state=STATE_START; private String data_the_guid = ""; private String data_specs_guid = ""; private String data_specs_name = ""; private String data_specs_displayname = ""; private String data_functor_guid = ""; private String data_functor_name = ""; private String data_functor_displayname = ""; private String data_arg_guid = ""; private String data_arg_name = ""; private String data_arg_displayname = ""; private ArrayList args = new ArrayList(); private Topic theTopic; private Topic specsTopic; 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_CYCLIFY)) { state = STATE_CYCLIFY; } break; case STATE_CYCLIFY: if(qName.equals(TAG_CONSTANT)) { state = STATE_CYCLIFY_CONSTANT; data_the_guid = atts.getValue("guid"); } break; case STATE_CYCLIFY_CONSTANT: if(qName.equals(TAG_SPECS)) { state = STATE_CYCLIFY_CONSTANT_SPECS; } break; case STATE_CYCLIFY_CONSTANT_SPECS: if(qName.equals(TAG_LIST)) { state = STATE_CYCLIFY_CONSTANT_SPECS_LIST; } break; case STATE_CYCLIFY_CONSTANT_SPECS_LIST: if(qName.equals(TAG_CONSTANT)) { data_specs_guid = ""; data_specs_name = ""; data_specs_displayname = ""; state = STATE_CYCLIFY_CONSTANT_SPECS_LIST_CONSTANT; } else if(qName.equals(TAG_NAT)) { data_functor_guid = ""; data_functor_name = ""; data_functor_displayname = ""; data_arg_guid = ""; data_arg_name = ""; data_arg_displayname = ""; args = new ArrayList(); state = STATE_CYCLIFY_CONSTANT_SPECS_LIST_NAT; } break; case STATE_CYCLIFY_CONSTANT_SPECS_LIST_CONSTANT: if(qName.equals(TAG_GUID)) { state = STATE_CYCLIFY_CONSTANT_SPECS_LIST_CONSTANT_GUID; } else if(qName.equals(TAG_NAME)) { state = STATE_CYCLIFY_CONSTANT_SPECS_LIST_CONSTANT_NAME; } else if(qName.equals(TAG_DISPLAYNAME)) { state = STATE_CYCLIFY_CONSTANT_SPECS_LIST_CONSTANT_DISPLAYNAME; } break; case STATE_CYCLIFY_CONSTANT_SPECS_LIST_NAT: if(qName.equals(TAG_FUNCTOR)) { data_functor_guid = ""; data_functor_name = ""; data_functor_displayname = ""; state = STATE_CYCLIFY_CONSTANT_SPECS_LIST_NAT_FUNCTOR; } if(qName.equals(TAG_ARG)) { data_arg_guid = ""; data_arg_name = ""; data_arg_displayname = ""; state = STATE_CYCLIFY_CONSTANT_SPECS_LIST_NAT_ARG; } break; case STATE_CYCLIFY_CONSTANT_SPECS_LIST_NAT_FUNCTOR: if(qName.equals(TAG_GUID)) { state = STATE_CYCLIFY_CONSTANT_SPECS_LIST_NAT_FUNCTOR_GUID; } else if(qName.equals(TAG_NAME)) { state = STATE_CYCLIFY_CONSTANT_SPECS_LIST_NAT_FUNCTOR_NAME; } else if(qName.equals(TAG_DISPLAYNAME)) { state = STATE_CYCLIFY_CONSTANT_SPECS_LIST_NAT_FUNCTOR_DISPLAYNAME; } break; case STATE_CYCLIFY_CONSTANT_SPECS_LIST_NAT_ARG: if(qName.equals(TAG_GUID)) { state = STATE_CYCLIFY_CONSTANT_SPECS_LIST_NAT_ARG_GUID; } else if(qName.equals(TAG_NAME)) { state = STATE_CYCLIFY_CONSTANT_SPECS_LIST_NAT_ARG_NAME; } else if(qName.equals(TAG_DISPLAYNAME)) { state = STATE_CYCLIFY_CONSTANT_SPECS_LIST_NAT_ARG_DISPLAYNAME; } break; } } public void endElement(String uri, String localName, String qName) throws SAXException { switch(state) { case STATE_CYCLIFY_CONSTANT_SPECS_LIST_CONSTANT_DISPLAYNAME: { if(qName.equals(TAG_DISPLAYNAME)) { state=STATE_CYCLIFY_CONSTANT_SPECS_LIST_CONSTANT; } break; } case STATE_CYCLIFY_CONSTANT_SPECS_LIST_CONSTANT_NAME: { if(qName.equals(TAG_NAME)) { state=STATE_CYCLIFY_CONSTANT_SPECS_LIST_CONSTANT; } break; } case STATE_CYCLIFY_CONSTANT_SPECS_LIST_CONSTANT_GUID: { if(qName.equals(TAG_GUID)) { state=STATE_CYCLIFY_CONSTANT_SPECS_LIST_CONSTANT; } break; } case STATE_CYCLIFY_CONSTANT_SPECS_LIST_CONSTANT: { if(qName.equals(TAG_CONSTANT)) { try { if(data_the_guid != null && data_the_guid.length() > 0) { theTopic = getTermTopic(data_the_guid, masterTerm, tm); } if(data_specs_guid != null && data_specs_guid.length() > 0) { specsTopic = getTermTopic(data_specs_guid, data_specs_name, tm); specsTopic.setDisplayName(LANG, data_specs_displayname); parent.setProgress(progress++); if(theTopic != null && specsTopic != null) { makeSubclassOf(tm, specsTopic, theTopic); } } } catch(Exception e) { parent.log(e); } state=STATE_CYCLIFY_CONSTANT_SPECS_LIST; } break; } // ------------------------- case STATE_CYCLIFY_CONSTANT_SPECS_LIST_NAT_FUNCTOR_DISPLAYNAME: { if(qName.equals(TAG_DISPLAYNAME)) { state=STATE_CYCLIFY_CONSTANT_SPECS_LIST_NAT_FUNCTOR; } break; } case STATE_CYCLIFY_CONSTANT_SPECS_LIST_NAT_FUNCTOR_NAME: { if(qName.equals(TAG_NAME)) { state=STATE_CYCLIFY_CONSTANT_SPECS_LIST_NAT_FUNCTOR; } break; } case STATE_CYCLIFY_CONSTANT_SPECS_LIST_NAT_FUNCTOR_GUID: { if(qName.equals(TAG_GUID)) { state=STATE_CYCLIFY_CONSTANT_SPECS_LIST_NAT_FUNCTOR; } break; } case STATE_CYCLIFY_CONSTANT_SPECS_LIST_NAT_FUNCTOR: { if(qName.equals(TAG_FUNCTOR)) { state=STATE_CYCLIFY_CONSTANT_SPECS_LIST_NAT; } break; } // ---- case STATE_CYCLIFY_CONSTANT_SPECS_LIST_NAT_ARG_DISPLAYNAME: { if(qName.equals(TAG_DISPLAYNAME)) { state=STATE_CYCLIFY_CONSTANT_SPECS_LIST_NAT_ARG; } break; } case STATE_CYCLIFY_CONSTANT_SPECS_LIST_NAT_ARG_NAME: { if(qName.equals(TAG_NAME)) { state=STATE_CYCLIFY_CONSTANT_SPECS_LIST_NAT_ARG; } break; } case STATE_CYCLIFY_CONSTANT_SPECS_LIST_NAT_ARG_GUID: { if(qName.equals(TAG_GUID)) { state=STATE_CYCLIFY_CONSTANT_SPECS_LIST_NAT_ARG; } break; } case STATE_CYCLIFY_CONSTANT_SPECS_LIST_NAT_ARG: { if(qName.equals(TAG_FUNCTOR)) { args.add( data_arg_guid ); args.add( data_arg_name ); args.add( data_arg_displayname ); state=STATE_CYCLIFY_CONSTANT_SPECS_LIST_NAT; } break; } // --- case STATE_CYCLIFY_CONSTANT_SPECS_LIST_NAT: { if(qName.equals(TAG_NAT)) { try { if(data_the_guid != null && data_the_guid.length() > 0) { theTopic = getTermTopic(data_the_guid, masterTerm, tm); } if(data_functor_guid != null && data_functor_guid.length() > 0) { Topic functorTopic = getTermTopic(data_functor_guid, data_functor_name, tm); functorTopic.setDisplayName(LANG, data_functor_displayname); parent.setProgress(progress++); Association a = tm.createAssociation( tm.getTopic(XTMPSI.SUPERCLASS_SUBCLASS )); a.addPlayer(theTopic, tm.getTopic(XTMPSI.SUPERCLASS)); a.addPlayer(functorTopic, getFunctorType(tm)); for(Iterator<String> i=args.iterator(); i.hasNext();) { try { String arg_guid = i.next(); String arg_name = i.next(); String arg_displayname = i.next(); int argNum = 1; if(arg_guid != null && arg_guid.length() > 0) { Topic argTopic = getTermTopic(arg_guid, arg_name, tm); if(arg_displayname != null && arg_displayname.length() > 0) argTopic.setDisplayName(LANG, arg_displayname); a.addPlayer(argTopic, getArgType(tm, argNum)); argNum++; } } catch(Exception e) { parent.log(e); } } } } catch(Exception e) { parent.log(e); } state=STATE_CYCLIFY_CONSTANT_SPECS_LIST; } break; } // ----- case STATE_CYCLIFY_CONSTANT_SPECS_LIST: { if(qName.equals(TAG_LIST)) { state=STATE_CYCLIFY_CONSTANT_SPECS; } break; } case STATE_CYCLIFY_CONSTANT_SPECS: { if(qName.equals(TAG_SPECS)) { state=STATE_CYCLIFY_CONSTANT; } break; } case STATE_CYCLIFY_CONSTANT: { if(!qName.equals(TAG_CONSTANT)) { state=STATE_CYCLIFY; } break; } case STATE_CYCLIFY: { state=STATE_START; break; } } } public void characters(char[] ch, int start, int length) throws SAXException { switch(state){ case STATE_CYCLIFY_CONSTANT_SPECS_LIST_CONSTANT_DISPLAYNAME: data_specs_displayname+=new String(ch,start,length); break; case STATE_CYCLIFY_CONSTANT_SPECS_LIST_CONSTANT_NAME: data_specs_name+=new String(ch,start,length); break; case STATE_CYCLIFY_CONSTANT_SPECS_LIST_CONSTANT_GUID: data_specs_guid+=new String(ch,start,length); break; case STATE_CYCLIFY_CONSTANT_SPECS_LIST_NAT_FUNCTOR_DISPLAYNAME: data_functor_displayname+=new String(ch,start,length); break; case STATE_CYCLIFY_CONSTANT_SPECS_LIST_NAT_FUNCTOR_NAME: data_functor_name+=new String(ch,start,length); break; case STATE_CYCLIFY_CONSTANT_SPECS_LIST_NAT_FUNCTOR_GUID: data_functor_guid+=new String(ch,start,length); break; case STATE_CYCLIFY_CONSTANT_SPECS_LIST_NAT_ARG_DISPLAYNAME: data_arg_displayname+=new String(ch,start,length); break; case STATE_CYCLIFY_CONSTANT_SPECS_LIST_NAT_ARG_NAME: data_arg_name+=new String(ch,start,length); break; case STATE_CYCLIFY_CONSTANT_SPECS_LIST_NAT_ARG_GUID: data_arg_guid+=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 {} } }
21,871
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
OpenCycInstanceExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/opencyc/OpenCycInstanceExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * OpenCycInstanceExtractor.java * */ package org.wandora.application.tools.extractors.opencyc; import java.io.InputStream; import org.wandora.topicmap.Association; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; /** * * @author akivela */ public class OpenCycInstanceExtractor extends AbstractOpenCycExtractor { private static final long serialVersionUID = 1L; /** Creates a new instance of OpenCycInstanceExtractor */ public OpenCycInstanceExtractor() { } @Override public String getName() { return "OpenCyc instance extractor"; } @Override public String getDescription(){ return "Extractor reads the instance XML feed from OpenCyc's web api and converts the XML feed to a topic map. "+ "See http://65.99.218.242:8080/RESTfulCyc/Constant/Dog/instances for an example of such XML feed."; } public String getMasterTerm(String u) { try { if(u.endsWith("/instances")) { u = u.substring(0, u.length()-"/instances".length()); int i = u.lastIndexOf('/'); if(i > 0) { u = u.substring(i+1); return u; } } } catch(Exception e) { log(e); } return null; } 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(); CycInstanceParser parserHandler = new CycInstanceParser(getMasterSubject(), 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 + " Cyc instances found!"); return true; } private static class CycInstanceParser implements org.xml.sax.ContentHandler, org.xml.sax.ErrorHandler { String masterTerm = null; public CycInstanceParser(String term, TopicMap tm, AbstractOpenCycExtractor parent){ this.masterTerm = term; this.tm=tm; this.parent=parent; } public int progress=0; private TopicMap tm; private AbstractOpenCycExtractor parent; public static final String TAG_CYCLIFY="cyclify"; public static final String TAG_CONSTANT="constant"; public static final String TAG_LIST="list"; public static final String TAG_INSTANCES="instances"; public static final String TAG_GUID="guid"; public static final String TAG_NAME="name"; public static final String TAG_DISPLAYNAME="displayname"; public static final String TAG_NAT="nat"; private static final int STATE_START=0; private static final int STATE_CYCLIFY=2; private static final int STATE_CYCLIFY_CONSTANT=3; private static final int STATE_CYCLIFY_CONSTANT_INSTANCES=4; private static final int STATE_CYCLIFY_CONSTANT_INSTANCES_LIST=5; private static final int STATE_CYCLIFY_CONSTANT_INSTANCES_LIST_CONSTANT=6; private static final int STATE_CYCLIFY_CONSTANT_INSTANCES_LIST_CONSTANT_GUID=7; private static final int STATE_CYCLIFY_CONSTANT_INSTANCES_LIST_CONSTANT_NAME=8; private static final int STATE_CYCLIFY_CONSTANT_INSTANCES_LIST_CONSTANT_DISPLAYNAME=9; private static final int STATE_CYCLIFY_CONSTANT_INSTANCES_LIST_NAT = 100; private int state=STATE_START; private String data_the_guid = ""; private String data_instance_guid = ""; private String data_instance_name = ""; private String data_instance_displayname = ""; private Topic theTopic; private Topic instanceTopic; 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_CYCLIFY)) { state = STATE_CYCLIFY; } break; case STATE_CYCLIFY: if(qName.equals(TAG_CONSTANT)) { state = STATE_CYCLIFY_CONSTANT; data_the_guid = atts.getValue("guid"); } break; case STATE_CYCLIFY_CONSTANT: if(qName.equals(TAG_INSTANCES)) { state = STATE_CYCLIFY_CONSTANT_INSTANCES; } break; case STATE_CYCLIFY_CONSTANT_INSTANCES: if(qName.equals(TAG_LIST)) { state = STATE_CYCLIFY_CONSTANT_INSTANCES_LIST; } break; case STATE_CYCLIFY_CONSTANT_INSTANCES_LIST: if(qName.equals(TAG_CONSTANT)) { data_instance_guid = ""; data_instance_name = ""; data_instance_displayname = ""; state = STATE_CYCLIFY_CONSTANT_INSTANCES_LIST_CONSTANT; } if(qName.equals(TAG_NAT)) { state = STATE_CYCLIFY_CONSTANT_INSTANCES_LIST_NAT; } break; case STATE_CYCLIFY_CONSTANT_INSTANCES_LIST_CONSTANT: if(qName.equals(TAG_GUID)) { state = STATE_CYCLIFY_CONSTANT_INSTANCES_LIST_CONSTANT_GUID; } else if(qName.equals(TAG_NAME)) { state = STATE_CYCLIFY_CONSTANT_INSTANCES_LIST_CONSTANT_NAME; } else if(qName.equals(TAG_DISPLAYNAME)) { state = STATE_CYCLIFY_CONSTANT_INSTANCES_LIST_CONSTANT_DISPLAYNAME; } break; } } public void endElement(String uri, String localName, String qName) throws SAXException { switch(state) { case STATE_CYCLIFY_CONSTANT_INSTANCES_LIST_CONSTANT_DISPLAYNAME: { if(qName.equals(TAG_DISPLAYNAME)) { state=STATE_CYCLIFY_CONSTANT_INSTANCES_LIST_CONSTANT; } break; } case STATE_CYCLIFY_CONSTANT_INSTANCES_LIST_CONSTANT_NAME: { if(qName.equals(TAG_NAME)) { state=STATE_CYCLIFY_CONSTANT_INSTANCES_LIST_CONSTANT; } break; } case STATE_CYCLIFY_CONSTANT_INSTANCES_LIST_CONSTANT_GUID: { if(qName.equals(TAG_GUID)) { state=STATE_CYCLIFY_CONSTANT_INSTANCES_LIST_CONSTANT; } break; } case STATE_CYCLIFY_CONSTANT_INSTANCES_LIST_CONSTANT: { if(qName.equals(TAG_CONSTANT)) { try { if(data_the_guid != null && data_the_guid.length() > 0) { theTopic = getTermTopic(data_the_guid, masterTerm, tm); } if(data_instance_guid != null && data_instance_guid.length() > 0) { instanceTopic = getTermTopic(data_instance_guid, data_instance_name, tm); instanceTopic.setDisplayName(LANG, data_instance_displayname); parent.setProgress(progress++); if(theTopic != null && instanceTopic != null) { if(ISA_EQUALS_INSTANCE) { instanceTopic.addType(theTopic); } else { Topic isaType = getIsaTypeTopic(tm); Association isaa = tm.createAssociation(isaType); isaa.addPlayer(instanceTopic, getInstanceTypeTopic(tm)); isaa.addPlayer(theTopic, getCollectionTypeTopic(tm)); } } } } catch(Exception e) { parent.log(e); } state=STATE_CYCLIFY_CONSTANT_INSTANCES_LIST; } break; } case STATE_CYCLIFY_CONSTANT_INSTANCES_LIST_NAT: if(qName.equals(TAG_NAT)) { state = STATE_CYCLIFY_CONSTANT_INSTANCES_LIST; } break; case STATE_CYCLIFY_CONSTANT_INSTANCES_LIST: { if(qName.equals(TAG_LIST)) { state=STATE_CYCLIFY_CONSTANT_INSTANCES; } break; } case STATE_CYCLIFY_CONSTANT_INSTANCES: { if(qName.equals(TAG_INSTANCES)) { state=STATE_CYCLIFY_CONSTANT; } break; } case STATE_CYCLIFY_CONSTANT: { if(!qName.equals(TAG_CONSTANT)) { state=STATE_CYCLIFY; } break; } case STATE_CYCLIFY: { state=STATE_START; break; } } } public void characters(char[] ch, int start, int length) throws SAXException { switch(state){ case STATE_CYCLIFY_CONSTANT_INSTANCES_LIST_CONSTANT_DISPLAYNAME: data_instance_displayname+=new String(ch,start,length); break; case STATE_CYCLIFY_CONSTANT_INSTANCES_LIST_CONSTANT_NAME: data_instance_name+=new String(ch,start,length); break; case STATE_CYCLIFY_CONSTANT_INSTANCES_LIST_CONSTANT_GUID: data_instance_guid+=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 {} } }
13,299
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
UClassifierDialog.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/uclassify/UClassifierDialog.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * UCLassifierDialog.java * */ package org.wandora.application.tools.extractors.uclassify; import java.awt.Component; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.gui.UIConstants; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.application.gui.simple.SimpleButton; import org.wandora.application.gui.simple.SimpleComboBox; import org.wandora.application.gui.simple.SimpleField; import org.wandora.application.gui.simple.SimpleFileChooser; import org.wandora.application.gui.simple.SimpleLabel; import org.wandora.application.gui.simple.SimpleTextPane; import org.wandora.application.tools.extractors.AbstractExtractor; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.utils.IObox; /** * * @author akivela */ public class UClassifierDialog extends javax.swing.JDialog { private static final long serialVersionUID = 1L; private Wandora wandora = null; private WandoraTool parentTool = null; private boolean wasAccepted = false; private HashMap<Component,Integer> registeredSources = null; /** Creates new form UClassifierDialog */ public UClassifierDialog(Wandora admin, boolean modal) { super(admin, modal); this.wandora = admin; initComponents(); //initialize(null); } public void initialize(WandoraTool parentTool, String[] cs) { initialize(parentTool); for(int i=0; i<cs.length; i=i+2) { classifierComboBox.addItem(new UClassifierOption(cs[i], cs[i+1])); } classifierComboBox.setEditable(false); } public void initialize(WandoraTool parentTool) { this.parentTool = parentTool; wasAccepted = false; ((SimpleTextPane) fileTextPane).dropFileNames(true); ((SimpleTextPane) fileTextPane).setLineWrap(false); ((SimpleTextPane) urlTextPane).dropFileNames(true); ((SimpleTextPane) urlTextPane).setLineWrap(false); if(parentTool instanceof AbstractExtractor) { if(!((AbstractExtractor) parentTool).useURLCrawler()) { crawlerPanel.setVisible(false); } else { crawlerPanel.setVisible(true); } } if(parentTool != null) setTitle(parentTool.getName()); else setTitle("uClassifier"); setSize(800,400); if(wandora != null) wandora.centerWindow(this); registeredSources = new HashMap<Component,Integer>(); } public boolean wasAccepted() { return wasAccepted; } public int getSelectedSource() { Component selectedComponent = tabbedSourcePane.getSelectedComponent(); Integer source = registeredSources.get(selectedComponent); return source.intValue(); } public void registerSource(String name, Component component, int id) { if(component == null) return; if(registeredSources.get(component) == null) { registeredSources.put(component, Integer.valueOf(id)); tabbedSourcePane.addTab(name, component); } } public void registerUrlSource() { registerSource("Urls", urlPanel, AbstractExtractor.URL_EXTRACTOR); } public void registerFileSource() { registerSource("Files", filePanel, AbstractExtractor.FILE_EXTRACTOR); } public void registerRawSource() { registerSource("Raw", rawPanel, AbstractExtractor.RAW_EXTRACTOR); } // --- CONTENT --- public String getContent() { return rawTextPane.getText(); } public double getThresholdValue() { double d = 0.0; try { d = Double.parseDouble(thresholdTextField.getText()); } catch(Exception e) { e.printStackTrace(); } return d; } public String getClassifier() { UClassifierOption co = (UClassifierOption) classifierComboBox.getSelectedItem(); if(co != null) { return co.getName(); } return null; } public String getClassifierOwner() { UClassifierOption co = (UClassifierOption) classifierComboBox.getSelectedItem(); if(co != null) { return co.getOwner(); } return null; } // --- FILE SOURCE --- public File[] getFileSources() { String input = fileTextPane.getText(); String[] filenames = splitText(input); ArrayList<File> files = new ArrayList<File>(); File f = null; for(int i=0; i<filenames.length; i++) { if(filenames[i] != null && filenames[i].trim().length() > 0) { f = new File(filenames[i]); if(f.exists()) files.add(f); else { if(parentTool != null) parentTool.log("File '"+filenames[i]+"' not found!"); } } } return files.toArray( new File[] {} ); } // --- URL SOURCE --- public String[] getURLSources() { String input = urlTextPane.getText(); String[] urls = splitText(input); return urls; } public int getCrawlerMode(int defaultValue) { int mode = defaultValue; try { mode = crawlerComboBox.getSelectedIndex(); System.out.println("getCrawlerMode: "+ mode); } catch(Exception e) {} return mode; } private String[] splitText(String str) { if(str == null) return null; if(str.indexOf("\n") != -1) { String[] s = str.split("\n"); for(int i=0; i<s.length; i++) { s[i] = s[i].trim(); } return s; } else { return new String[] { str.trim() }; } } // ------------------------------------------------------------------------- private void selectFiles() { SimpleFileChooser chooser = UIConstants.getFileChooser(); chooser.setMultiSelectionEnabled(true); //chooser.setDialogTitle(getGUIText(SELECT_DIALOG_TITLE)); chooser.setApproveButtonText("Select"); chooser.setFileSelectionMode(SimpleFileChooser.FILES_AND_DIRECTORIES); //if(accessoryPanel != null) { chooser.setAccessory(accessoryPanel); } if(chooser.open(wandora)==SimpleFileChooser.APPROVE_OPTION) { File[] files = chooser.getSelectedFiles(); File f = null; String fs = ""; for(int i=0; i<files.length; i++) { f = files[i]; fs = fs + f.getAbsolutePath(); if(i<files.length-1) fs = fs + "\n"; } String s = fileTextPane.getText(); if(s == null || s.length() == 0) s = fs; else s = s + "\n" + fs; fileTextPane.setText(s); } } private void selectContextSLFiles() { if(parentTool == null) return; Context context = parentTool.getContext(); Iterator iter = context.getContextObjects(); Object o = null; Topic t = null; Locator locator = null; StringBuilder sb = new StringBuilder(""); while(iter.hasNext()) { try { o = iter.next(); if(o == null) continue; if(o instanceof Topic) { t = (Topic) o; if(!t.isRemoved()) { locator = t.getSubjectLocator(); if(locator != null) { String locatorStr = locator.toExternalForm(); if(locatorStr.startsWith("file:")) { locatorStr = IObox.getFileFromURL(locatorStr); sb.append(locatorStr).append("\n"); } } } } } catch(Exception e) { parentTool.log(e); } } String s = urlTextPane.getText(); if(s == null || s.length() == 0) s = sb.toString(); else s = s + "\n" + sb.toString(); fileTextPane.setText(s); } private void selectContextSLs() { if(parentTool == null) return; Context context = parentTool.getContext(); Iterator iter = context.getContextObjects(); Object o = null; Topic t = null; Locator locator = null; StringBuilder sb = new StringBuilder(""); while(iter.hasNext()) { try { o = iter.next(); if(o == null) continue; if(o instanceof Topic) { t = (Topic) o; if(!t.isRemoved()) { locator = t.getSubjectLocator(); if(locator != null) { String locatorStr = locator.toExternalForm(); sb.append(locatorStr).append("\n"); } } } } catch(Exception e) { parentTool.log(e); } } String s = urlTextPane.getText(); if(s == null || s.length() == 0) s = sb.toString(); else s = s + "\n" + sb.toString(); urlTextPane.setText(s); } private void selectContextSIs() { if(parentTool == null) return; Context context = parentTool.getContext(); Iterator iter = context.getContextObjects(); Object o = null; Topic t = null; Locator locator = null; StringBuilder sb = new StringBuilder(""); while(iter.hasNext()) { try { o = iter.next(); if(o == null) continue; if(o instanceof Topic) { t = (Topic) o; if(!t.isRemoved()) { Collection<Locator> ls = t.getSubjectIdentifiers(); Iterator<Locator> ils = ls.iterator(); while(ils.hasNext()) { locator = ils.next(); if(locator != null) { String locatorStr = locator.toExternalForm(); sb.append(locatorStr).append("\n"); } } } } } catch(Exception e) { parentTool.log(e); } } String s = urlTextPane.getText(); if(s == null || s.length() == 0) s = sb.toString(); else s = s + "\n" + sb.toString(); urlTextPane.setText(s); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; forgetApiKeyButton = new SimpleButton(); urlPanel = new javax.swing.JPanel(); urlLabel = new org.wandora.application.gui.simple.SimpleLabel(); crawlerPanel = new javax.swing.JPanel(); crawlerLabel = new org.wandora.application.gui.simple.SimpleLabel(); crawlerComboBox = new org.wandora.application.gui.simple.SimpleComboBox(); crawlerComboBox.setEditable(false); urlScrollPane = new javax.swing.JScrollPane(); urlTextPane = new org.wandora.application.gui.simple.SimpleTextPane(); urlButtonPanel = new javax.swing.JPanel(); urlGetSIButton = new org.wandora.application.gui.simple.SimpleButton(); urlGetSLButton = new org.wandora.application.gui.simple.SimpleButton(); urlClearButton = new org.wandora.application.gui.simple.SimpleButton(); filePanel = new javax.swing.JPanel(); fileLabel = new org.wandora.application.gui.simple.SimpleLabel(); fileScrollPane = new javax.swing.JScrollPane(); fileTextPane = new org.wandora.application.gui.simple.SimpleTextPane(); fileButtonPanel = new javax.swing.JPanel(); fileBrowseButton = new org.wandora.application.gui.simple.SimpleButton(); fileGetSLButton = new org.wandora.application.gui.simple.SimpleButton(); fileClearButton = new org.wandora.application.gui.simple.SimpleButton(); rawPanel = new javax.swing.JPanel(); rawLabel = new org.wandora.application.gui.simple.SimpleLabel(); rawScrollPane = new javax.swing.JScrollPane(); rawTextPane = new org.wandora.application.gui.simple.SimpleTextPane(); tabbedSourcePane = new org.wandora.application.gui.simple.SimpleTabbedPane(); buttonPanel = new javax.swing.JPanel(); classifierPanel = new javax.swing.JPanel(); classifierLabel = new SimpleLabel(); classifierComboBox = new SimpleComboBox(); thresholdLabel = new SimpleLabel(); thresholdTextField = new SimpleField(); fillerPanel = new javax.swing.JPanel(); extractButton = new org.wandora.application.gui.simple.SimpleButton(); cancelButton = new org.wandora.application.gui.simple.SimpleButton(); forgetApiKeyButton.setText("Forget Api Key"); forgetApiKeyButton.setMargin(new java.awt.Insets(2, 4, 2, 4)); forgetApiKeyButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { forgetApiKeyButtonMouseReleased(evt); } }); urlPanel.setLayout(new java.awt.GridBagLayout()); urlLabel.setText("<html>Select URL resources you want to classify. Write URL addresses below or get subjects of context topics.</html>"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); urlPanel.add(urlLabel, gridBagConstraints); crawlerPanel.setLayout(new java.awt.GridBagLayout()); crawlerLabel.setText("Extract"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); crawlerPanel.add(crawlerLabel, gridBagConstraints); crawlerComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "exactly given urls", "given urls and directly linked documents", "given urls and crawled documents in url domain", "given urls and all crawled documents" })); crawlerComboBox.setPreferredSize(new java.awt.Dimension(200, 21)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; crawlerPanel.add(crawlerComboBox, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(2, 5, 5, 5); urlPanel.add(crawlerPanel, gridBagConstraints); urlScrollPane.setPreferredSize(new java.awt.Dimension(10, 100)); urlScrollPane.setViewportView(urlTextPane); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 5); urlPanel.add(urlScrollPane, gridBagConstraints); urlButtonPanel.setLayout(new java.awt.GridBagLayout()); urlGetSIButton.setText("Get SIs"); urlGetSIButton.setMargin(new java.awt.Insets(1, 6, 1, 6)); urlGetSIButton.setPreferredSize(new java.awt.Dimension(70, 21)); urlGetSIButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { urlGetSIButtonMouseReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 1); urlButtonPanel.add(urlGetSIButton, gridBagConstraints); urlGetSLButton.setText("Get SLs"); urlGetSLButton.setMargin(new java.awt.Insets(1, 6, 1, 6)); urlGetSLButton.setPreferredSize(new java.awt.Dimension(70, 21)); urlGetSLButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { urlGetSLButtonMouseReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 1); urlButtonPanel.add(urlGetSLButton, gridBagConstraints); urlClearButton.setText("Clear"); urlClearButton.setMargin(new java.awt.Insets(1, 6, 1, 6)); urlClearButton.setPreferredSize(new java.awt.Dimension(70, 21)); urlClearButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { urlClearButtonMouseReleased(evt); } }); urlButtonPanel.add(urlClearButton, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); urlPanel.add(urlButtonPanel, gridBagConstraints); filePanel.setLayout(new java.awt.GridBagLayout()); fileLabel.setText("<html>Select files you want to classify. Write, browse or get subject locator files. Text field accepts also dropped files.</html>"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); filePanel.add(fileLabel, gridBagConstraints); fileScrollPane.setPreferredSize(new java.awt.Dimension(10, 100)); fileScrollPane.setViewportView(fileTextPane); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 5); filePanel.add(fileScrollPane, gridBagConstraints); fileButtonPanel.setLayout(new java.awt.GridBagLayout()); fileBrowseButton.setText("Browse"); fileBrowseButton.setMargin(new java.awt.Insets(1, 6, 1, 6)); fileBrowseButton.setPreferredSize(new java.awt.Dimension(70, 21)); fileBrowseButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { fileBrowseButtonMouseReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 1); fileButtonPanel.add(fileBrowseButton, gridBagConstraints); fileGetSLButton.setText("Get SLs"); fileGetSLButton.setMargin(new java.awt.Insets(1, 6, 1, 6)); fileGetSLButton.setPreferredSize(new java.awt.Dimension(70, 21)); fileGetSLButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { fileGetSLButtonMouseReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 1); fileButtonPanel.add(fileGetSLButton, gridBagConstraints); fileClearButton.setText("Clear"); fileClearButton.setMargin(new java.awt.Insets(1, 6, 1, 6)); fileClearButton.setPreferredSize(new java.awt.Dimension(70, 21)); fileClearButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { fileClearButtonMouseReleased(evt); } }); fileButtonPanel.add(fileClearButton, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); filePanel.add(fileButtonPanel, gridBagConstraints); rawPanel.setLayout(new java.awt.GridBagLayout()); rawLabel.setText("<html>Paste or write text content you want to classify. Field accepts text drops also.</html>"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); rawPanel.add(rawLabel, gridBagConstraints); rawScrollPane.setPreferredSize(new java.awt.Dimension(10, 100)); rawScrollPane.setViewportView(rawTextPane); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 5, 5, 5); rawPanel.add(rawScrollPane, gridBagConstraints); getContentPane().setLayout(new java.awt.GridBagLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 4, 0); getContentPane().add(tabbedSourcePane, gridBagConstraints); buttonPanel.setLayout(new java.awt.GridBagLayout()); classifierPanel.setLayout(new java.awt.GridBagLayout()); classifierLabel.setText("Select uClassifier"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4); classifierPanel.add(classifierLabel, gridBagConstraints); classifierComboBox.setPreferredSize(new java.awt.Dimension(150, 23)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 10); classifierPanel.add(classifierComboBox, gridBagConstraints); thresholdLabel.setText("Threshold value"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4); classifierPanel.add(thresholdLabel, gridBagConstraints); thresholdTextField.setHorizontalAlignment(javax.swing.JTextField.CENTER); thresholdTextField.setText("0.01"); thresholdTextField.setMinimumSize(new java.awt.Dimension(40, 23)); thresholdTextField.setPreferredSize(new java.awt.Dimension(40, 23)); classifierPanel.add(thresholdTextField, new java.awt.GridBagConstraints()); buttonPanel.add(classifierPanel, new java.awt.GridBagConstraints()); fillerPanel.setPreferredSize(new java.awt.Dimension(100, 10)); javax.swing.GroupLayout fillerPanelLayout = new javax.swing.GroupLayout(fillerPanel); fillerPanel.setLayout(fillerPanelLayout); fillerPanelLayout.setHorizontalGroup( fillerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 159, Short.MAX_VALUE) ); fillerPanelLayout.setVerticalGroup( fillerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 10, Short.MAX_VALUE) ); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; buttonPanel.add(fillerPanel, gridBagConstraints); extractButton.setText("Classify"); extractButton.setMargin(new java.awt.Insets(2, 2, 2, 2)); 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, 3); buttonPanel.add(extractButton, gridBagConstraints); cancelButton.setText("Cancel"); cancelButton.setMargin(new java.awt.Insets(2, 2, 2, 2)); cancelButton.setPreferredSize(new java.awt.Dimension(70, 23)); cancelButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { cancelButtonMouseReleased(evt); } }); buttonPanel.add(cancelButton, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 4); getContentPane().add(buttonPanel, gridBagConstraints); pack(); }// </editor-fold>//GEN-END:initComponents private void urlClearButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_urlClearButtonMouseReleased this.urlTextPane.setText(""); }//GEN-LAST:event_urlClearButtonMouseReleased private void fileClearButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_fileClearButtonMouseReleased this.fileTextPane.setText(""); }//GEN-LAST:event_fileClearButtonMouseReleased private void cancelButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cancelButtonMouseReleased wasAccepted = false; setVisible(false); }//GEN-LAST:event_cancelButtonMouseReleased private void extractButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_extractButtonMouseReleased wasAccepted = true; setVisible(false); }//GEN-LAST:event_extractButtonMouseReleased private void fileBrowseButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_fileBrowseButtonMouseReleased selectFiles(); }//GEN-LAST:event_fileBrowseButtonMouseReleased private void fileGetSLButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_fileGetSLButtonMouseReleased selectContextSLFiles(); }//GEN-LAST:event_fileGetSLButtonMouseReleased private void urlGetSLButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_urlGetSLButtonMouseReleased selectContextSLs(); }//GEN-LAST:event_urlGetSLButtonMouseReleased private void urlGetSIButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_urlGetSIButtonMouseReleased selectContextSIs(); }//GEN-LAST:event_urlGetSIButtonMouseReleased private void forgetApiKeyButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_forgetApiKeyButtonMouseReleased if(parentTool != null && parentTool instanceof AbstractUClassifier) { ((AbstractUClassifier) parentTool).forgetAuthorization(); WandoraOptionPane.showMessageDialog(this, "Wandora asks new api key next time you access the uClassify web service.", "uClassify Api Key Forgot"); } }//GEN-LAST:event_forgetApiKeyButtonMouseReleased // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel buttonPanel; private javax.swing.JButton cancelButton; private javax.swing.JComboBox classifierComboBox; private javax.swing.JLabel classifierLabel; private javax.swing.JPanel classifierPanel; private javax.swing.JComboBox crawlerComboBox; private javax.swing.JLabel crawlerLabel; private javax.swing.JPanel crawlerPanel; private javax.swing.JButton extractButton; private javax.swing.JButton fileBrowseButton; private javax.swing.JPanel fileButtonPanel; private javax.swing.JButton fileClearButton; private javax.swing.JButton fileGetSLButton; private javax.swing.JLabel fileLabel; private javax.swing.JPanel filePanel; private javax.swing.JScrollPane fileScrollPane; private javax.swing.JTextPane fileTextPane; private javax.swing.JPanel fillerPanel; private javax.swing.JButton forgetApiKeyButton; private javax.swing.JLabel rawLabel; private javax.swing.JPanel rawPanel; private javax.swing.JScrollPane rawScrollPane; private javax.swing.JTextPane rawTextPane; private javax.swing.JTabbedPane tabbedSourcePane; private javax.swing.JLabel thresholdLabel; private javax.swing.JTextField thresholdTextField; private javax.swing.JPanel urlButtonPanel; private javax.swing.JButton urlClearButton; private javax.swing.JButton urlGetSIButton; private javax.swing.JButton urlGetSLButton; private javax.swing.JLabel urlLabel; private javax.swing.JPanel urlPanel; private javax.swing.JScrollPane urlScrollPane; private javax.swing.JTextPane urlTextPane; // End of variables declaration//GEN-END:variables private class UClassifierOption { private String name = null; private String owner = null; public UClassifierOption(String n, String o) { name = n; owner = o; } public String getName() { return name; } public String getOwner() { return owner; } @Override public String toString() { return name; } } }
32,160
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
UClassifier.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/uclassify/UClassifier.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.uclassify; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.application.gui.texteditor.OccurrenceTextEditor; import org.wandora.application.tools.extractors.ExtractHelper; 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; /** * * @author akivela */ public class UClassifier extends AbstractUClassifier { private static final long serialVersionUID = 1L; protected static final String OPTIONS_KEY = "uclassify"; private static String[] defaultClassifiers = new String[] { "Text Language", "uClassify", "Sentiment", "uClassify", "Topics", "uClassify", }; private UClassifierDialog uClassifierDialog = null; private String forceClassifier = null; private String forceOwner = null; private double forceProbability = -1.0; public UClassifier() { } public UClassifier(String classifier, String owner, double probability) { forceClassifier = classifier; forceOwner = owner; forceProbability = probability; } @Override public String getName() { return "UClassifier"; } @Override public String getDescription(){ return "Extracts classes out of given text using uClassifier. Read more at http://www.uclassify.com."; } // ------------------------------------------------------------------------- @Override public boolean isConfigurable(){ return true; } @Override public void configure(Wandora wandora, org.wandora.utils.Options options, String prefix) throws TopicMapException { readOptions(options); UClassifierConfiguration conf = new UClassifierConfiguration(wandora, options, this); conf.setClassifiers(defaultClassifiers); conf.open(); if(conf.wasAccepted()) { defaultClassifiers = conf.getClassifiers(); options.removeAll(OPTIONS_KEY+".uclassifiers"); for(int i=0; i<defaultClassifiers.length; i=i+2) { options.put(OPTIONS_KEY+".uclassifiers.uclassifier["+i/2+"].name", defaultClassifiers[i]); options.put(OPTIONS_KEY+".uclassifiers.uclassifier["+i/2+"].author", defaultClassifiers[i+1]); } } } @Override public void writeOptions(Wandora wandora, org.wandora.utils.Options options, String prefix) { if(options != null) { options.removeAll(OPTIONS_KEY+".uclassifiers"); for(int i=0; i<defaultClassifiers.length; i=i+2) { options.put(OPTIONS_KEY+".uclassifiers.uclassifier["+i/2+"].name", defaultClassifiers[i]); options.put(OPTIONS_KEY+".uclassifiers.uclassifier["+i/2+"].author", defaultClassifiers[i+1]); } } } private void readOptions(Options options) { if(options != null) { int i = 0; ArrayList<String> classifiers = new ArrayList<String>(); try { while(true) { String classifierName = options.get(OPTIONS_KEY+".uclassifiers.uclassifier["+i+"].name"); String classifierAuthor = options.get(OPTIONS_KEY+".uclassifiers.uclassifier["+i+"].author"); if(classifierName != null && classifierAuthor != null) { classifiers.add(classifierName); classifiers.add(classifierAuthor); } else break; i++; } if(classifiers.isEmpty()) { System.out.print("Warning: UClassifier didn't find any classifiers in Wandora options."); } } catch(Exception e) { e.printStackTrace(); } defaultClassifiers = classifiers.toArray( new String[] {} ); } } // ------------------------------------------------------------------------- @Override public void execute(Wandora wandora, Context context) { setWandora(wandora); readOptions(wandora.getOptions()); Object contextSource = context.getContextSource(); if(contextSource instanceof OccurrenceTextEditor) { try { OccurrenceTextEditor occurrenceEditor = (OccurrenceTextEditor) contextSource; if(context.getContextObjects().hasNext()) { Topic masterTopic = (Topic) context.getContextObjects().next(); setMasterSubject(masterTopic); String str = occurrenceEditor.getSelectedText(); if(str == null || str.length() == 0) { str = occurrenceEditor.getText(); } _extractTopicsFrom(str, wandora.getTopicMap()); } } catch(Exception e) { log(e); } } else { try { TopicMap tm = wandora.getTopicMap(); setTopicMap(tm); int possibleTypes = getExtractorType(); uClassifierDialog = new UClassifierDialog(wandora, true); uClassifierDialog.initialize(this, defaultClassifiers); if((possibleTypes & RAW_EXTRACTOR) != 0) uClassifierDialog.registerRawSource(); if((possibleTypes & FILE_EXTRACTOR) != 0) uClassifierDialog.registerFileSource(); if((possibleTypes & URL_EXTRACTOR) != 0) uClassifierDialog.registerUrlSource(); if((possibleTypes & CUSTOM_EXTRACTOR) != 0) initializeCustomType(); uClassifierDialog.setVisible(true); if(!uClassifierDialog.wasAccepted()) return; int selectedType = uClassifierDialog.getSelectedSource(); setDefaultLogger(); log(getGUIText(INFO_WAIT_WHILE_WORKING)); // --- FILE TYPE --- if((selectedType & FILE_EXTRACTOR) != 0) { handleFiles( uClassifierDialog.getFileSources(), tm ); } // --- URL TYPE --- if((selectedType & URL_EXTRACTOR) != 0) { handleUrls( uClassifierDialog.getURLSources(), tm ); } // --- RAW TYPE --- if((selectedType & RAW_EXTRACTOR) != 0) { handleContent( uClassifierDialog.getContent(), tm ); } // --- CUSTOM TYPE --- if((selectedType & CUSTOM_EXTRACTOR) != 0) { handleCustomType(); } lockLog(false); setState(WAIT); } catch(Exception e) { log(e); setState(WAIT); } } clearMasterSubject(); } @Override public boolean _extractTopicsFrom(URL url, TopicMap topicMap) throws Exception { return _extractTopicsFrom(url.openStream(),topicMap); } @Override public boolean _extractTopicsFrom(File file, TopicMap topicMap) throws Exception { return _extractTopicsFrom(new FileInputStream(file),topicMap); } @Override public boolean _extractTopicsFrom(InputStream in, TopicMap topicMap) throws Exception { String data = IObox.loadFile(in, defaultEncoding); return _extractTopicsFrom(data, topicMap); } @Override public boolean _extractTopicsFrom(String data, TopicMap tm) throws Exception { if(data != null && data.length() > 0) { String content = ExtractHelper.getTextData(data); String classifier = "Text Language"; String classifierOwner = "uClassify"; double thresholdProbability = 0.0001; if(forceClassifier != null) classifier = forceClassifier; if(forceOwner != null) classifierOwner = forceOwner; if(forceProbability != -1.0) thresholdProbability = forceProbability; if(uClassifierDialog != null) { thresholdProbability = uClassifierDialog.getThresholdValue(); classifier = uClassifierDialog.getClassifier(); classifierOwner = uClassifierDialog.getClassifierOwner(); } String result = uClassify(content, classifier, classifierOwner, thresholdProbability, tm); } else { log("No valid data given! Aborting!"); } return true; } // ------------------------------------------------------------------------- }
9,893
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AbstractUClassifier.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/uclassify/AbstractUClassifier.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.uclassify; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringReader; import java.io.StringWriter; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import javax.swing.Icon; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; /** * * @author akivela */ import org.w3c.dom.Document; import org.wandora.application.Wandora; import org.wandora.application.WandoraToolType; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.application.tools.browserextractors.BrowserExtractRequest; import org.wandora.application.tools.extractors.AbstractExtractor; import org.wandora.application.tools.extractors.ExtractHelper; import org.wandora.topicmap.Association; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.utils.Base64; import org.wandora.utils.Textbox; 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; public abstract class AbstractUClassifier extends AbstractExtractor { private static final long serialVersionUID = 1L; private String REQUEST_TEMPLATE = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>"+ "<uclassify xmlns=\"http://api.uclassify.com/1/RequestSchema\" version=\"1.01\">"+ "<texts>"+ "<textBase64 id=\"UnknownText1\">__REQUEST_DATA__</textBase64>"+ "</texts>"+ "<readCalls readApiKey=\"__API_KEY__\">"+ "<classify id=\"Classify\" username=\"__PUBLISHED_USER__\" classifierName=\"__PUBLISHED_CLASSIFIER__\" textId=\"UnknownText1\"/>"+ "</readCalls>"+ "</uclassify>"; protected static final String API_URL = "http://api.uclassify.com"; protected String defaultEncoding = "UTF-8"; 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 UCLASSIFY_SI = "http://www.uclassify.com"; public static final String UCLASSIFY_CLASSIFIER_SI = "http://wandora.org/si/uclassify/classifier"; public static final String UCLASSIFY_CLASSIFIER_TYPE_SI = "http://wandora.org/si/uclassify/classifier-type"; public static final String UCLASSIFY_CLASS_SI = "http://wandora.org/si/uclassify/term"; public static final String UCLASSIFY_CLASS_TYPE_SI = "http://wandora.org/si/uclassify/term-type"; public static final String UCLASSIFY_PROBABILITY_SI = "http://wandora.org/si/uclassify/probability"; public static final String UCLASSIFY_PROBABILITY_TYPE_SI = "http://wandora.org/si/uclassify/probability-type"; @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_uclassify.png"); } @Override public WandoraToolType getType() { return WandoraToolType.createExtractType(); } private final String[] contentTypes=new String[] { "text/plain", "text/html" }; @Override public String[] getContentTypes() { return contentTypes; } @Override public boolean useURLCrawler() { return false; } // ------------------------------------------------------------------------- @Override public boolean isConfigurable(){ return false; } // ------------------------------------------------------------------------- @Override public String doBrowserExtract(BrowserExtractRequest request, Wandora wandora) throws TopicMapException { setWandora(wandora); return ExtractHelper.doBrowserExtractForClassifiers(this, request, wandora, defaultEncoding); } // ------------------------------------------------------------------------- public abstract boolean _extractTopicsFrom(InputStream in, TopicMap topicMap) throws Exception; public String solveTitle(String content) { if(content == null || content.length() == 0) return "empty-document"; boolean forceTrim = false; String title = null; int i = content.indexOf("\n"); if(i > 0) title = content.substring(0, i); else { title = content.substring(0, Math.min(80, content.length())); forceTrim = true; } if(title != null && (forceTrim || title.length() > 80)) { title = title.substring(0, Math.min(80, title.length())); while(!title.endsWith(" ") && title.length()>10) { title = title.substring(0, title.length()-1); } title = Textbox.trimExtraSpaces(title) + "..."; } return title; } public void fillDocumentTopic(Topic textTopic, TopicMap topicMap, String content) { try { String trimmedText = Textbox.trimExtraSpaces(content); if(trimmedText != null && trimmedText.length() > 0) { Topic contentType = createTopic(topicMap, "document-text"); setData(textTopic, contentType, "en", trimmedText); } String title = solveTitle(trimmedText); if(title != null) { textTopic.setBaseName(title + " (" + content.hashCode() + ")"); textTopic.setDisplayName("en", title); } Topic documentType = getDocumentType(topicMap); textTopic.addType(documentType); } catch(Exception e) { log(e); } } // ******** TOPIC MAPS ********* public Topic getUClassifierType(TopicMap tm) throws TopicMapException { Topic t = getOrCreateTopic(tm, UCLASSIFY_CLASSIFIER_TYPE_SI, "uClassify classifier"); makeSubclassOf(tm, t, getUClassifyClass(tm)); return t; } public Topic getUClassifierTopic(String uclassifier, TopicMap tm) throws TopicMapException { if(uclassifier != null) { uclassifier = uclassifier.trim(); if(uclassifier.length() > 0) { Topic uTopic=getOrCreateTopic(tm, UCLASSIFY_CLASSIFIER_TYPE_SI+"/"+encode(uclassifier), uclassifier); Topic classifierType = getUClassifierType(tm); uTopic.addType(classifierType); return uTopic; } } return null; } public Topic getUClassType(TopicMap tm) throws TopicMapException { Topic t = getOrCreateTopic(tm, UCLASSIFY_CLASS_TYPE_SI, "uClassify class"); makeSubclassOf(tm, t, getUClassifyClass(tm)); return t; } public Topic getUClassTopic(String uclass, TopicMap tm) throws TopicMapException { if(uclass != null) { uclass = uclass.trim(); if(uclass.length() > 0) { Topic classTopic=getOrCreateTopic(tm, UCLASSIFY_CLASS_SI+"/"+encode(uclass), uclass); Topic classType = getUClassType(tm); classTopic.addType(classType); return classTopic; } } return null; } public Topic getUProbabilityType(TopicMap tm) throws TopicMapException { Topic t = getOrCreateTopic(tm, UCLASSIFY_PROBABILITY_TYPE_SI, "uClassifier probability"); makeSubclassOf(tm, t, getUClassifyClass(tm)); return t; } public Topic getUProbabilityTopic(String uprobability, TopicMap tm) throws TopicMapException { if(uprobability != null) { uprobability = uprobability.trim(); if(uprobability.length() > 0) { Topic uTopic=getOrCreateTopic(tm, UCLASSIFY_PROBABILITY_SI+"/"+encode(uprobability), uprobability); Topic probabilityType = getUProbabilityType(tm); uTopic.addType(probabilityType); return uTopic; } } return null; } public Topic getUClassifyClass(TopicMap tm) throws TopicMapException { Topic t = getOrCreateTopic(tm, UCLASSIFY_SI, "uClassify"); makeSubclassOf(tm, t, getWandoraClass(tm)); //t.addType(getWandoraClass(tm)); return t; } public Topic getWandoraClass(TopicMap tm) throws TopicMapException { return getOrCreateTopic(tm, TMBox.WANDORACLASS_SI, "Wandora class"); } public Topic getTopicType(TopicMap tm) throws TopicMapException { return getOrCreateTopic(tm, TOPIC_SI, "Topic"); } public Topic getSourceType(TopicMap tm) throws TopicMapException { return getOrCreateTopic(tm, SOURCE_SI, "Source"); } public Topic getDocumentType(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, DOCUMENT_SI, "Document"); Topic wandoraClass = getWandoraClass(tm); makeSubclassOf(tm, type, wandoraClass); return type; } // -------- protected Topic getOrCreateTopic(TopicMap tm, String si) throws TopicMapException { return getOrCreateTopic(tm, si,null); } protected Topic getOrCreateTopic(TopicMap tm, String si,String bn) throws TopicMapException { return ExtractHelper.getOrCreateTopic(si, bn, tm); } protected void makeSubclassOf(TopicMap tm, Topic t, Topic superclass) throws TopicMapException { ExtractHelper.makeSubclassOf(t, superclass, tm); } // ------------------------------------------------------------------------- public String encode(String str) { try { str = URLEncoder.encode(str, defaultEncoding); } catch(Exception e) { e.printStackTrace(); } return str; } // ------------------------------------------------------------------------- protected String getStringFromDocument(Document doc) { try { DOMSource domSource = new DOMSource(doc); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.transform(domSource, result); return writer.toString(); } catch(TransformerException ex) { ex.printStackTrace(); return null; } } // utility function protected String getFileContents(File file) throws IOException, FileNotFoundException { StringBuilder contents = new StringBuilder(); BufferedReader input = new BufferedReader(new FileReader(file)); try { String line = null; while ((line = input.readLine()) != null) { contents.append(line); contents.append(System.getProperty("line.separator")); } } finally { input.close(); } return contents.toString(); } // ------------------------------------------------------------------------- public String uClassify(String data, String classifier, String classifierOwner, double thresholdProbability, TopicMap tm) { try { String requestData = REQUEST_TEMPLATE; String apikey = solveAPIKey(); if(apikey != null) { requestData = requestData.replace("__API_KEY__", apikey); requestData = requestData.replace("__REQUEST_DATA__", Base64.encodeBytes(data.getBytes())); requestData = requestData.replace("__PUBLISHED_USER__", classifierOwner); requestData = requestData.replace("__PUBLISHED_CLASSIFIER__", classifier); System.out.println("Sending: "+requestData); String result = sendRequest(new URL(API_URL), requestData, "text/xml; charset=utf-8", "POST"); System.out.println("uClassifier returned == "+result); javax.xml.parsers.SAXParserFactory factory=javax.xml.parsers.SAXParserFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(false); javax.xml.parsers.SAXParser parser=factory.newSAXParser(); XMLReader reader=parser.getXMLReader(); UClassifyParser parserHandler = new UClassifyParser(getMasterSubject(), data, classifier, thresholdProbability, tm, this); reader.setContentHandler(parserHandler); reader.setErrorHandler(parserHandler); try { reader.parse(new InputSource(new StringReader(result))); } catch(Exception e){ if(!(e instanceof SAXException) || !e.getMessage().equals("User interrupt")) log(e); } if(getCurrentLogger() != null) log("Total " + parserHandler.progress + " classes found by uClassify"); } else { log("No Apikey available. Aborting."); } } catch(Exception e) { log(e); } return null; } public static String sendRequest(URL url, String data, String ctype, String method) throws IOException { StringBuilder sb = new StringBuilder(5000); if (url != null) { URLConnection con = url.openConnection(); Wandora.initUrlConnection(con); con.setDoInput(true); con.setUseCaches(false); if(method != null && con instanceof HttpURLConnection) { ((HttpURLConnection) con).setRequestMethod(method); //System.out.println("****** Setting HTTP request method to "+method); } if(ctype != null) { con.setRequestProperty("Content-type", ctype); } if(data != null && data.length() > 0) { con.setRequestProperty("Content-length", data.length() + ""); con.setDoOutput(true); PrintWriter out = new PrintWriter(con.getOutputStream()); out.print(data); out.flush(); out.close(); } // DataInputStream in = new DataInputStream(con.getInputStream()); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String s; while ((s = in.readLine()) != null) { sb.append(s); if(!(s.endsWith("\n") || s.endsWith("\r"))) sb.append("\n"); } in.close(); } return sb.toString(); } // ------------------------------------------------------------------------- private static String apikey = null; // "t0ckynnsXWB0WLHQCuLx6m8IOs"; public String solveAPIKey(Wandora wandora) { setWandora(wandora); return solveAPIKey(); } public String solveAPIKey() { if(apikey == null) { apikey = ""; apikey = WandoraOptionPane.showInputDialog(getWandora(), "Please give valid apikey for uClassify. You can register your apikey at http://www.uclassify.com/", apikey, "uClassify apikey", WandoraOptionPane.QUESTION_MESSAGE); } return apikey; } public void forgetAuthorization() { apikey = null; } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- public class UClassifyParser implements org.xml.sax.ContentHandler, org.xml.sax.ErrorHandler { private int totalClassesFound = 0; private int acceptedClassesFound = 0; private double thresholdProbability = 0.0; private String classifier = null; private Topic masterTopic = null; public int progress=0; private TopicMap tm; private AbstractUClassifier parent; public UClassifyParser(String term, String data, String c, double tp, TopicMap tm, AbstractUClassifier parent){ this.tm=tm; this.parent=parent; this.classifier = c; this.thresholdProbability = tp; try { if(term != null) { masterTopic = tm.getTopicWithBaseName(term); if(masterTopic == null) masterTopic = tm.getTopic(term); } } catch(Exception e) { parent.log(e); } if(masterTopic == null && data != null && data.length() > 0) { try { masterTopic = tm.createTopic(); masterTopic.addSubjectIdentifier(tm.makeSubjectIndicatorAsLocator()); parent.fillDocumentTopic(masterTopic, tm, data); } catch(Exception e) { parent.log(e); } } this.tm=tm; this.parent=parent; } public static final String TAG_UCLASSIFY="uclassify"; public static final String TAG_STATUS="status"; public static final String TAG_READCALLS="readCalls"; public static final String TAG_CLASSIFY="classify"; public static final String TAG_CLASSIFICATION="classification"; public static final String TAG_CLASS="class"; private static final int STATE_START=0; private static final int STATE_UCLASSIFY=1; private static final int STATE_UCLASSIFY_READCALLS=11; private static final int STATE_UCLASSIFY_READCALLS_CLASSIFY=111; private static final int STATE_UCLASSIFY_READCALLS_CLASSIFY_CLASSIFICATION=1111; private static final int STATE_UCLASSIFY_READCALLS_CLASSIFY_CLASSIFICATION_CLASS=11111; private static final int STATE_UCLASSIFY_STATUS=12; private int state=STATE_START; private String classifyId = null; private String textCoverage = null; private String className = null; private String p = null; private String statusText = ""; 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_UCLASSIFY)) { state = STATE_UCLASSIFY; } break; case STATE_UCLASSIFY: if(qName.equals(TAG_STATUS)) { state = STATE_UCLASSIFY_STATUS; String statusCode = atts.getValue("statusCode"); String success = atts.getValue("success"); statusText = ""; if(!"true".equalsIgnoreCase(success)) { parent.log("Warning: uClassify returned error code "+statusCode); } } else if(qName.equals(TAG_READCALLS)) { state = STATE_UCLASSIFY_READCALLS; } break; case STATE_UCLASSIFY_READCALLS: if(qName.equals(TAG_CLASSIFY)) { classifyId = atts.getValue("id"); state = STATE_UCLASSIFY_READCALLS_CLASSIFY; } break; case STATE_UCLASSIFY_READCALLS_CLASSIFY: if(qName.equals(TAG_CLASSIFICATION)) { textCoverage = atts.getValue("textCoverage"); state = STATE_UCLASSIFY_READCALLS_CLASSIFY_CLASSIFICATION; } break; case STATE_UCLASSIFY_READCALLS_CLASSIFY_CLASSIFICATION: if(qName.equals(TAG_CLASS)) { className = atts.getValue("className"); p = atts.getValue("p"); if(className != null && className.length() > 0) { totalClassesFound++; try { if(parent.getCurrentLogger() != null) parent.log("uClassify found class '"+className+"'" + (p != null ? " with probability "+p+"." : ".")); double dp = 1.0; if(p != null && p.length() > 0) { try { dp = Double.parseDouble(p); } catch(Exception e) { // PASS SILENTLY } } if(dp > thresholdProbability) { Topic uClassTopic = parent.getUClassTopic(className, tm); if(masterTopic != null && uClassTopic != null) { Topic uClassType = parent.getUClassType(tm); Association a = tm.createAssociation(uClassType); a.addPlayer(masterTopic, parent.getTopicType(tm)); a.addPlayer(uClassTopic, uClassType); if(p != null && p.length() > 0) { Topic uProbabilityType = parent.getUProbabilityType(tm); Topic uProbabilityTopic = parent.getUProbabilityTopic(p, tm); a.addPlayer(uProbabilityTopic, uProbabilityType); } if(classifier != null && classifier.length() > 0) { Topic uClassifierType = parent.getUClassifierType(tm); Topic uClassifierTopic = parent.getUClassifierTopic(classifier, tm); a.addPlayer(uClassifierTopic, uClassifierType); } acceptedClassesFound++; } } } catch(Exception e) { parent.log(e); } } state = STATE_UCLASSIFY_READCALLS_CLASSIFY_CLASSIFICATION_CLASS; } break; } } public void endElement(String uri, String localName, String qName) throws SAXException { switch(state) { case STATE_UCLASSIFY_READCALLS_CLASSIFY_CLASSIFICATION_CLASS: if(qName.equals(TAG_CLASS)) { parent.setProgress( progress++ ); state = STATE_UCLASSIFY_READCALLS_CLASSIFY_CLASSIFICATION; } break; case STATE_UCLASSIFY_READCALLS_CLASSIFY_CLASSIFICATION: if(qName.equals(TAG_CLASSIFICATION)) { state = STATE_UCLASSIFY_READCALLS_CLASSIFY; } break; case STATE_UCLASSIFY_READCALLS_CLASSIFY: if(qName.equals(TAG_CLASSIFY)) { state = STATE_UCLASSIFY_READCALLS; } break; case STATE_UCLASSIFY_READCALLS: if(qName.equals(TAG_READCALLS)) { state = STATE_UCLASSIFY; } break; case STATE_UCLASSIFY_STATUS: if(qName.equals(TAG_STATUS)) { if(statusText != null && statusText.length() > 0) { parent.log(statusText); } state = STATE_UCLASSIFY; } break; case STATE_UCLASSIFY: if(qName.equals(TAG_UCLASSIFY)) { state = STATE_START; } break; } } public void characters(char[] ch, int start, int length) throws SAXException { switch(state) { case STATE_UCLASSIFY_STATUS: { statusText += new String(ch,start,length); } } } 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 {} } }
27,663
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TextLanguageUClassifier.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/uclassify/TextLanguageUClassifier.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.uclassify; /** * * @author akivela */ public class TextLanguageUClassifier extends UClassifier { private static final long serialVersionUID = 1L; public TextLanguageUClassifier() { super("Text Language", "uClassify", 0.001); } @Override public String getName() { return "Text Language uClassifier"; } @Override public String getDescription(){ return "Extracts language classes out of given text using uClassifier. Read more at http://www.uclassify.com."; } }
1,384
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicsUClassifier.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/uclassify/TopicsUClassifier.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.uclassify; /** * * @author akivela */ public class TopicsUClassifier extends UClassifier { private static final long serialVersionUID = 1L; public TopicsUClassifier() { super("Topics", "uClassify", 0.001); } @Override public String getName() { return "Topics uClassifier"; } @Override public String getDescription(){ return "Extracts topic classes out of given text using uClassifier. Read more at http://www.uclassify.com."; } }
1,359
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
UClassifierAddDialog.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/uclassify/UClassifierAddDialog.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * UClassifierAddDialog.java * * Created on 20.7.2011, 14:48:46 */ package org.wandora.application.tools.extractors.uclassify; import org.wandora.application.Wandora; import org.wandora.application.gui.simple.SimpleButton; import org.wandora.application.gui.simple.SimpleField; import org.wandora.application.gui.simple.SimpleLabel; /** * * @author akivela */ public class UClassifierAddDialog extends javax.swing.JDialog { private static final long serialVersionUID = 1L; private boolean isAccepted = false; /** Creates new form UClassifierAddDialog */ public UClassifierAddDialog(Wandora w) { super(w, true); setTitle("Add uClassifier"); initComponents(); } public boolean wasAccepted() { return isAccepted; } public String getName() { return uClassifierNameTextField.getText(); } public String getAuthor() { return uClassifierAuthorTextField.getText(); } // ------------------------------------------------------------------------- /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; formPanel = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); uClassifierNameLabel = new SimpleLabel(); uClassifierNameTextField = new SimpleField(); uClassifierAuthorLabel = new SimpleLabel(); uClassifierAuthorTextField = new SimpleField(); buttonPanel = new javax.swing.JPanel(); buttonFillerPanel = new javax.swing.JPanel(); createButton = new SimpleButton(); cancelButton = new SimpleButton(); getContentPane().setLayout(new java.awt.GridBagLayout()); formPanel.setLayout(new java.awt.GridBagLayout()); jLabel1.setText("<html>Add new classifier to Wandora's uClassify extractor. You can browse public classifiers at http://www.uclassify.com/browse .</html>"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 8, 0); formPanel.add(jLabel1, gridBagConstraints); uClassifierNameLabel.setText("uClassifier name"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 4, 4); formPanel.add(uClassifierNameLabel, 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, 4, 0); formPanel.add(uClassifierNameTextField, gridBagConstraints); uClassifierAuthorLabel.setText("uClassifier author"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4); formPanel.add(uClassifierAuthorLabel, gridBagConstraints); uClassifierAuthorTextField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { uClassifierAuthorTextFieldActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; formPanel.add(uClassifierAuthorTextField, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(4, 4, 0, 4); getContentPane().add(formPanel, gridBagConstraints); buttonPanel.setLayout(new java.awt.GridBagLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; buttonPanel.add(buttonFillerPanel, gridBagConstraints); createButton.setText("Add"); createButton.setMargin(new java.awt.Insets(2, 2, 2, 2)); createButton.setPreferredSize(new java.awt.Dimension(70, 23)); createButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { createButtonMouseReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4); buttonPanel.add(createButton, gridBagConstraints); cancelButton.setText("Cancel"); cancelButton.setMargin(new java.awt.Insets(2, 2, 2, 2)); cancelButton.setPreferredSize(new java.awt.Dimension(70, 23)); cancelButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { cancelButtonMouseReleased(evt); } }); buttonPanel.add(cancelButton, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); getContentPane().add(buttonPanel, gridBagConstraints); pack(); }// </editor-fold>//GEN-END:initComponents private void cancelButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cancelButtonMouseReleased isAccepted = false; setVisible(false); }//GEN-LAST:event_cancelButtonMouseReleased private void createButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_createButtonMouseReleased isAccepted = true; setVisible(false); }//GEN-LAST:event_createButtonMouseReleased private void uClassifierAuthorTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_uClassifierAuthorTextFieldActionPerformed // TODO add your handling code here: }//GEN-LAST:event_uClassifierAuthorTextFieldActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel buttonFillerPanel; private javax.swing.JPanel buttonPanel; private javax.swing.JButton cancelButton; private javax.swing.JButton createButton; private javax.swing.JPanel formPanel; private javax.swing.JLabel jLabel1; private javax.swing.JLabel uClassifierAuthorLabel; private javax.swing.JTextField uClassifierAuthorTextField; private javax.swing.JLabel uClassifierNameLabel; private javax.swing.JTextField uClassifierNameTextField; // End of variables declaration//GEN-END:variables }
8,529
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
UClassifierConfiguration.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/uclassify/UClassifierConfiguration.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * UClassifierConfiguration.java * * Created on 20.7.2011, 13:26:29 */ package org.wandora.application.tools.extractors.uclassify; import java.util.ArrayList; import java.util.Arrays; import javax.swing.JDialog; import javax.swing.RowSorter; import javax.swing.event.TableModelListener; import javax.swing.table.TableModel; import javax.swing.table.TableRowSorter; import org.wandora.application.Wandora; 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.SimpleScrollPane; import org.wandora.utils.Options; /** * * @author akivela */ public class UClassifierConfiguration extends javax.swing.JPanel { private static final long serialVersionUID = 1L; private JDialog confDialog = null; private boolean isAccepted = false; private Wandora wandora = null; private String[] classifiers = null; private AbstractUClassifier parent = null; /** Creates new form UClassifierConfiguration */ public UClassifierConfiguration(Wandora w, Options options, AbstractUClassifier p) { wandora = w; parent = p; initComponents(); } public void setClassifiers(String[] cs) { classifiers = cs; TableModel model = new ClassifierTableModel(cs); RowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model); classifierTable.setRowSorter(sorter); classifierTable.setModel(model); } public boolean wasAccepted() { return isAccepted; } public String[] getClassifiers() { return classifiers; } public void open() { confDialog = new JDialog(wandora, true); confDialog.setTitle("uClassifier configuration"); confDialog.add(this); confDialog.setSize(730,350); wandora.centerWindow(confDialog); confDialog.setVisible(true); } private void removeSelectedClassifiers() { int[] rows = classifierTable.getSelectedRows(); ArrayList<String> newClassifiers = new ArrayList<String>(); for(int r=0; r<classifiers.length/2; r++) { boolean isSelected = false; for(int j=0; j<rows.length; j++) { if(r == j) { isSelected = true; break; } } if(!isSelected) { newClassifiers.add(classifiers[r*2]); newClassifiers.add(classifiers[r*2+1]); } } setClassifiers( newClassifiers.toArray( new String[] {} )); } private void addClassifier() { UClassifierAddDialog d = new UClassifierAddDialog(wandora); d.setSize(400,180); UIBox.centerWindow(d, wandora); d.setVisible(true); // --- WAIT if(d.wasAccepted()) { String n = d.getName(); String a = d.getAuthor(); if(n == null || n.length() == 0) return; if(a == null || a.length() == 0) return; ArrayList<String> newClassifiers = new ArrayList<String>(); newClassifiers.addAll(Arrays.asList(classifiers)); newClassifiers.add(n); newClassifiers.add(a); setClassifiers( newClassifiers.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. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; tablePanel = new javax.swing.JPanel(); tableScrollPane = new SimpleScrollPane(); classifierTable = new javax.swing.JTable(); buttonPanel = new javax.swing.JPanel(); addClassifierButton = new SimpleButton(); removeClassifierButton = new SimpleButton(); buttonFillerPanel2 = new javax.swing.JPanel(); forgetApiKeyButton = new SimpleButton(); buttonFillerPanel = new javax.swing.JPanel(); okButton = new SimpleButton(); cancelButton = new SimpleButton(); setLayout(new java.awt.GridBagLayout()); tablePanel.setLayout(new java.awt.GridBagLayout()); classifierTable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } ) { boolean[] canEdit = new boolean [] { false, false, false, false }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); tableScrollPane.setViewportView(classifierTable); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; tablePanel.add(tableScrollPane, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 4, 0); add(tablePanel, gridBagConstraints); buttonPanel.setLayout(new java.awt.GridBagLayout()); addClassifierButton.setText("Add"); addClassifierButton.setMargin(new java.awt.Insets(2, 2, 2, 2)); addClassifierButton.setPreferredSize(new java.awt.Dimension(75, 23)); addClassifierButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { addClassifierButtonMouseReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4); buttonPanel.add(addClassifierButton, gridBagConstraints); removeClassifierButton.setText("Remove"); removeClassifierButton.setMargin(new java.awt.Insets(2, 2, 2, 2)); removeClassifierButton.setPreferredSize(new java.awt.Dimension(75, 23)); removeClassifierButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { removeClassifierButtonMouseReleased(evt); } }); buttonPanel.add(removeClassifierButton, new java.awt.GridBagConstraints()); buttonFillerPanel2.setLayout(new java.awt.GridBagLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 5); buttonPanel.add(buttonFillerPanel2, gridBagConstraints); forgetApiKeyButton.setText("Forget Api Key"); forgetApiKeyButton.setMargin(new java.awt.Insets(1, 6, 1, 6)); forgetApiKeyButton.setPreferredSize(new java.awt.Dimension(105, 23)); forgetApiKeyButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { forgetApiKeyButtonMouseReleased(evt); } }); buttonPanel.add(forgetApiKeyButton, new java.awt.GridBagConstraints()); buttonFillerPanel.setMinimumSize(new java.awt.Dimension(2, 2)); buttonFillerPanel.setLayout(new java.awt.GridBagLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; buttonPanel.add(buttonFillerPanel, gridBagConstraints); okButton.setText("OK"); okButton.setMargin(new java.awt.Insets(2, 2, 2, 2)); okButton.setPreferredSize(new java.awt.Dimension(75, 23)); okButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { okButtonMouseReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4); buttonPanel.add(okButton, gridBagConstraints); cancelButton.setText("Cancel"); cancelButton.setMargin(new java.awt.Insets(2, 2, 2, 2)); cancelButton.setPreferredSize(new java.awt.Dimension(75, 23)); cancelButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { cancelButtonMouseReleased(evt); } }); buttonPanel.add(cancelButton, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 4); add(buttonPanel, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents private void cancelButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cancelButtonMouseReleased isAccepted = false; if(confDialog != null) confDialog.setVisible(false); }//GEN-LAST:event_cancelButtonMouseReleased private void okButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_okButtonMouseReleased isAccepted = true; if(confDialog != null) confDialog.setVisible(false); }//GEN-LAST:event_okButtonMouseReleased private void removeClassifierButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_removeClassifierButtonMouseReleased removeSelectedClassifiers(); }//GEN-LAST:event_removeClassifierButtonMouseReleased private void addClassifierButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_addClassifierButtonMouseReleased addClassifier(); }//GEN-LAST:event_addClassifierButtonMouseReleased private void forgetApiKeyButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_forgetApiKeyButtonMouseReleased if(parent != null) { parent.forgetAuthorization(); WandoraOptionPane.showMessageDialog(confDialog, "uClassify api key is forgot. Wandora asks new api key next time you access the uClassify web service.", "uClassify api key forgot"); } }//GEN-LAST:event_forgetApiKeyButtonMouseReleased // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton addClassifierButton; private javax.swing.JPanel buttonFillerPanel; private javax.swing.JPanel buttonFillerPanel2; private javax.swing.JPanel buttonPanel; private javax.swing.JButton cancelButton; private javax.swing.JTable classifierTable; private javax.swing.JButton forgetApiKeyButton; private javax.swing.JButton okButton; private javax.swing.JButton removeClassifierButton; private javax.swing.JPanel tablePanel; private javax.swing.JScrollPane tableScrollPane; // End of variables declaration//GEN-END:variables // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- private class ClassifierTableModel implements TableModel { private String[] modelArray = null; public ClassifierTableModel(String[] m) { modelArray = m; } public int getRowCount() { return modelArray.length / 2; } public int getColumnCount() { return 2; } public String getColumnName(int columnIndex) { switch(columnIndex) { case 0: return "Classifier name"; case 1: return "Classifier author"; } return null; } public Class<?> getColumnClass(int columnIndex) { return String.class; } public boolean isCellEditable(int rowIndex, int columnIndex) { return false; } public Object getValueAt(int rowIndex, int columnIndex) { return modelArray[rowIndex*2+columnIndex]; } public void setValueAt(Object aValue, int rowIndex, int columnIndex) { modelArray[rowIndex*2+columnIndex] = aValue.toString(); } public void addTableModelListener(TableModelListener l) { } public void removeTableModelListener(TableModelListener l) { } } }
14,186
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SentimentUClassifier.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/uclassify/SentimentUClassifier.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.uclassify; /** * * @author akivela */ public class SentimentUClassifier extends UClassifier { private static final long serialVersionUID = 1L; public SentimentUClassifier() { super("Sentiment", "uClassify", 0.001); } @Override public String getName() { return "Sentiment uClassifier"; } @Override public String getDescription(){ return "Extracts sentiment classes out of given text using uClassifier. Read more at http://www.uclassify.com."; } }
1,370
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
NYTExtractorUI.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/nyt/NYTExtractorUI.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * NYTExtractorUI.java * * Created on Apr 14, 2012, 9:43:48 PM */ package org.wandora.application.tools.extractors.nyt; import java.awt.Component; import java.net.URLEncoder; import java.util.ArrayList; import javax.swing.JDialog; import javax.swing.ListModel; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.application.gui.simple.SimpleButton; import org.wandora.application.gui.simple.SimpleCheckBox; import org.wandora.application.gui.simple.SimpleField; import org.wandora.application.gui.simple.SimpleLabel; import org.wandora.application.gui.simple.SimpleList; import org.wandora.application.gui.simple.SimpleTabbedPane; import org.wandora.topicmap.TopicMapException; /** * * @author akivela * @author Eero Lehtonen */ public class NYTExtractorUI extends javax.swing.JPanel { private static final long serialVersionUID = 1L; private Wandora wandora = null; private boolean accepted = false; private JDialog dialog = null; private Context context = null; private static final String NYT_API_BASE = "http://api.nytimes.com/svc/search/v2/"; private static final String NYT_API_EVENT_BASE = "http://api.nytimes.com/svc/events/v2/listings.json"; /** * Creates * new * form * NYTExtractorUI */ public NYTExtractorUI() { initComponents(); } public boolean wasAccepted() { return accepted; } public void setAccepted(boolean b) { accepted = b; } public void open(Wandora w, Context c) { context = c; accepted = false; dialog = new JDialog(w, true); dialog.setSize(550, 500); dialog.add(this); dialog.setTitle("New York Times API extractor"); UIBox.centerWindow(dialog, w); if(eventapikey != null || articleapikey != null){ forgetButton.setEnabled(true); } else { forgetButton.setEnabled(false); } dialog.setVisible(true); } public WandoraTool[] getExtractors(NYTExtractor tool) throws TopicMapException { Component component = nytTabbedPane.getSelectedComponent(); WandoraTool wt; ArrayList<WandoraTool> wts = new ArrayList<>(); // ***** SEARCH ARTICLES ***** if (articleSearchPanel.equals(component)) { String query = searchQueryTextField.getText(); String key = solveAPIKey(); if(key == null){ return null; } String extractUrl = NYT_API_BASE + "articlesearch.json?q=" + urlEncode(query) + "&api-key=" + key; String facets = facetsTextField.getText().trim(); if (facets != null && facets.length() > 0) { extractUrl += "&facet_field=" + urlEncode(facets); } int[] fieldIndexes = fieldsList.getSelectedIndices(); ListModel listModel = fieldsList.getModel(); StringBuilder fieldValues = new StringBuilder(""); for (int i = 0; i < fieldIndexes.length; i++) { if (i > 0) { fieldValues.append(","); } fieldValues.append(listModel.getElementAt(fieldIndexes[i])); } if (fieldValues.length() > 0) { extractUrl += "&f1=" + urlEncode("url," + fieldValues.toString()); } String beginDate = beginDateTextField.getText().trim(); if (beginDate != null && beginDate.length() > 0) { extractUrl += "&begin_date=" + urlEncode(beginDate); } String endDate = endDateTextField.getText().trim(); if (endDate != null && endDate.length() > 0) { extractUrl += "&end_date=" + urlEncode(endDate); } String offset = pageTextField.getText().trim(); if (offset == null || offset.length() == 0) { offset = "0"; } extractUrl += "&page=" + urlEncode(offset); String rank = sortComboBox.getSelectedItem().toString(); if (rank != null && rank.length() > 0) { extractUrl += "&sort=" + urlEncode(rank); } System.out.println("URL: " + extractUrl); NYTArticleSearchExtractor ex = new NYTArticleSearchExtractor(); ex.setForceUrls(new String[]{extractUrl}); wt = ex; wts.add(wt); } // ***** SEARCH EVENTS ***** else if (eventSearchPanel.equals(component)) { String eventKey = solveAPIKey(); if(eventKey == null){ throw new TopicMapException("Invalid key."); } String extractUrl = NYT_API_EVENT_BASE + "?"; String query = urlEncode(eventQueryTextField.getText()); if (!query.isEmpty()) { extractUrl += "&query=" + query; } Component subComponent = eventLocationTabs.getSelectedComponent(); if (eventCircleTab.equals(subComponent)) { if(circlCtrLatTextField.getText().matches("^-?\\d*[.,]\\d*") && circlCtrLongTextField.getText().matches("^-?\\d*[.,]\\d*")){ extractUrl += "&ll=" + urlEncode(circlCtrLatTextField.getText() + "," + circlCtrLongTextField.getText()); } else throw new TopicMapException("Invalid circle coordinates."); if(circlRadTextField.getText().matches("\\d*")){ extractUrl += "&radius=" + urlEncode(circlRadTextField.getText()); } else throw new TopicMapException("Invalid radius."); } else if (eventBoxTab.equals(subComponent)) { if(boxNELatTextField.getText().matches("^-?\\d*[,.]\\d*") && boxNELongTextField.getText().matches("^-?\\d*[,.]\\d*")) { extractUrl += "&ne=" + urlEncode(boxNELatTextField.getText() + "," + boxNELongTextField.getText()); } else throw new TopicMapException("Invalid box coordinates!"); if(boxSWLatTextField.getText().matches("^-?\\d*[,.]\\d*") && boxSWLongTextField.getText().matches("^-?\\d*[,.]\\d*")) { extractUrl += "&ne=" + urlEncode(boxSWLatTextField.getText() + "," + boxSWLongTextField.getText()); } else throw new TopicMapException("Invalid box coordinates!"); } else if (eventFilterTab.equals(subComponent)) { String filCat = evtFilterCatTextField.getText(); String filSubCat = evtFilterSubCatTextField.getText(); String filBor = evtFilterBoroughTextField.getText(); String filNghbrhd = evtFilterNeighborhoodTextField.getText(); String filter = "&filters="; if (!filCat.isEmpty()) { filter += "category:(" + filCat + "),"; } if (!filSubCat.isEmpty()) { filter += "subcategory:(" + filSubCat + "),"; } if (!filBor.isEmpty()) { filter += "borough:(" + filBor + "),"; } if (!filNghbrhd.isEmpty()) { filter += "neighborhood:(" + filNghbrhd + "),"; } if (evtFilterTimesPick.isSelected()) { filter += "times_pick:true,"; } if (evtFilterFree.isSelected()) { filter += "free:true,"; } if (evtFilterKidFriendly.isSelected()) { filter += "kid_friendly:true,"; } if (evtFilterLastChance.isSelected()) { filter += "last_chance:true,"; } if (evtFilterFestival.isSelected()) { filter += "festival:true,"; } if (evtFilterLongRunningShow.isSelected()) { filter += "long_running_show:true,"; } if (evtFilterPreviewsAndOpenings.isSelected()) { filter += "previews_and_openings:true,"; } extractUrl += filter; } String dateRange = (!evtDateStartTextField.getText().isEmpty() && !evtDateEndTextField.getText().isEmpty()) ? urlEncode(evtDateStartTextField.getText() + ":" + evtDateEndTextField.getText()) : null; if (dateRange != null) { if(dateRange.matches("\\d\\d\\d\\d-\\d\\d-\\d\\d%3A\\d\\d\\d\\d-\\d\\d-\\d\\d")){ extractUrl += "&date_range=" + urlEncode(dateRange); } else throw new TopicMapException("Invalid date range!"); } String offset = evtOffsetTextField.getText(); if (!offset.isEmpty()) { if(offset.matches("\\d*")){ extractUrl += "&offset=" + urlEncode(offset); } else throw new TopicMapException("Invalid offset value!"); } String limit = evtLimitTextField.getText(); if(limit.matches("\\d*")){ extractUrl += "&limit=" + limit; } else throw new TopicMapException("Invalid limit value!"); extractUrl += "&api-key=" + eventKey; System.out.println(extractUrl); NYTEventSearchExtractor ex = new NYTEventSearchExtractor(); ex.setForceUrls(new String[]{extractUrl}); wt = ex; wts.add(wt); } return wts.toArray(new WandoraTool[]{}); } protected static String urlEncode(String str) { try { str = URLEncoder.encode(str, "utf-8"); } catch (Exception e) { } return str; } // ------------------------------------------------------------ API-KEY ---- private static String articleapikey = null; private static String eventapikey = null; public String solveAPIKey(Wandora wandora) { return solveAPIKey(); } public String solveAPIKey() { if (eventSearchPanel.equals(nytTabbedPane.getSelectedComponent())){ if(eventapikey == null){ eventapikey = ""; eventapikey = WandoraOptionPane.showInputDialog(Wandora.getWandora(), "Please give an api-key for NYT event search. You can register your api-key at http://developer.nytimes.com/docs/reference/keys", eventapikey, "NYT Event api-key", WandoraOptionPane.QUESTION_MESSAGE); if(eventapikey != null) eventapikey = eventapikey.trim(); } forgetButton.setEnabled(true); return eventapikey; } else if (articleSearchPanel.equals(nytTabbedPane.getSelectedComponent())){ if(articleapikey == null) { articleapikey = ""; articleapikey = WandoraOptionPane.showInputDialog(Wandora.getWandora(), "Please give an api-key for NYT article search. You can register your api-key at http://developer.nytimes.com/docs/reference/keys", articleapikey, "NYT Article api-key", WandoraOptionPane.QUESTION_MESSAGE); if(articleapikey != null) articleapikey = articleapikey.trim(); } forgetButton.setEnabled(true); return articleapikey; } return null; } public void forgetAuthorization() { if (articleSearchPanel.equals(nytTabbedPane.getSelectedComponent())){ articleapikey = null; forgetButton.setEnabled(false); } else if(eventSearchPanel.equals(nytTabbedPane.getSelectedComponent())) { eventapikey = null; forgetButton.setEnabled(false); } } // ------------------------------------------------------------------------- /** * This * method * is * called * from * within * the * constructor * to * initialize * the * form. * WARNING: * Do * NOT * modify * this * code. * The * content * of * this * method * is * always * regenerated * by * the * Form * Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; facetsLabel = new SimpleLabel(); facetsTextField = new SimpleField(); nytTabbedPane = new SimpleTabbedPane(); articleSearchPanel = new javax.swing.JPanel(); articleSearchInnerPanel = new javax.swing.JPanel(); searchLabel = new SimpleLabel(); searchQueryTextField = new SimpleField(); optionalArticleSearchFieldsPanel = new javax.swing.JPanel(); fieldsLabel = new SimpleLabel(); fieldsListScrollPane = new javax.swing.JScrollPane(); fieldsList = new SimpleList(); beginDateLabel = new SimpleLabel(); beginDateTextField = new SimpleField(); endDateLabel = new SimpleLabel(); endDateTextField = new SimpleField(); pageLabel = new SimpleLabel(); pageTextField = new SimpleField(); sortLabel = new SimpleLabel(); sortComboBox = new javax.swing.JComboBox(); eventSearchPanel = new javax.swing.JPanel(); eventSearchInnerPanel = new javax.swing.JPanel(); eventQueryLabel = new SimpleLabel(); eventQueryTextField = new SimpleField(); eventLocationTabs = new SimpleTabbedPane(); eventBoxTab = new javax.swing.JPanel(); boxLabel = new javax.swing.JLabel(); boxSWpanel = new javax.swing.JPanel(); boxSWLatLabel = new SimpleLabel(); boxSWLongLabel = new SimpleLabel(); boxSWLatTextField = new SimpleField(); boxSWLongTextField = new SimpleField(); boxNEpanel = new javax.swing.JPanel(); boxNELatLabel = new SimpleLabel(); boxNELongLabel = new SimpleLabel(); boxNELatTextField = new SimpleField(); boxNELongTextField = new SimpleField(); eventCircleTab = new javax.swing.JPanel(); circleLabel = new javax.swing.JLabel(); circlCenterPanel = new javax.swing.JPanel(); circlCtrLongTextField = new SimpleField(); circlCtrLatTextField = new SimpleField(); circlCtrLongLabel = new SimpleLabel(); circlCtrLatLabel = new SimpleLabel(); circlRadiusPanel = new javax.swing.JPanel(); circlRadTextField = new SimpleField(); eventFilterTab = new javax.swing.JPanel(); filterLabel = new javax.swing.JLabel(); evtFilterCatLabel = new SimpleLabel(); evtFilterCatTextField = new SimpleField(); evtFilterSubCatLabel = new SimpleLabel(); evtFilterSubCatTextField = new SimpleField(); evtFilterBoroughLabel = new SimpleLabel(); evtFilterBoroughTextField = new SimpleField(); evtFilterNeighborhoodLabel = new SimpleLabel(); evtFilterNeighborhoodTextField = new SimpleField(); evtFilterTimesPick = new SimpleCheckBox(); evtFilterFree = new SimpleCheckBox(); evtFilterKidFriendly = new SimpleCheckBox(); evtFilterLastChance = new SimpleCheckBox(); evtFilterFestival = new SimpleCheckBox(); evtFilterLongRunningShow = new SimpleCheckBox(); evtFilterPreviewsAndOpenings = new SimpleCheckBox(); eventLimitPanel = new javax.swing.JPanel(); eventDateRangePanel = new javax.swing.JPanel(); evtDateStartLabel = new SimpleLabel(); evtDateEndLabel = new SimpleLabel(); evtDateStartTextField = new SimpleField(); evtDateEndTextField = new SimpleField(); eventOffsetPanel = new javax.swing.JPanel(); evtOffset = new SimpleLabel(); evtOffsetTextField = new SimpleField(); evtLimitLabel = new SimpleLabel(); evtLimitTextField = new SimpleField(); jPanel1 = new javax.swing.JPanel(); buttonPanel = new javax.swing.JPanel(); forgetButton = new SimpleButton(); buttonFillerPanel = new javax.swing.JPanel(); okButton = new SimpleButton(); cancelButton = new SimpleButton(); facetsLabel.setText("Facets"); facetsLabel.setToolTipText("Comma-delimited list of up to 5 facets."); setLayout(new java.awt.GridBagLayout()); nytTabbedPane.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { nytTabbedPaneStateChanged(evt); } }); articleSearchPanel.setLayout(new java.awt.GridBagLayout()); articleSearchInnerPanel.setLayout(new java.awt.GridBagLayout()); searchLabel.setText("Search query"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; articleSearchInnerPanel.add(searchLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; articleSearchInnerPanel.add(searchQueryTextField, gridBagConstraints); optionalArticleSearchFieldsPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Optional params")); optionalArticleSearchFieldsPanel.setLayout(new java.awt.GridBagLayout()); fieldsLabel.setText("Fields"); fieldsLabel.setToolTipText("Comma-delimited list of fields (no limit)."); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_END; gridBagConstraints.insets = new java.awt.Insets(2, 0, 2, 4); optionalArticleSearchFieldsPanel.add(fieldsLabel, gridBagConstraints); fieldsListScrollPane.setMinimumSize(new java.awt.Dimension(23, 150)); fieldsListScrollPane.setPreferredSize(new java.awt.Dimension(125, 150)); fieldsList.setModel(new javax.swing.AbstractListModel() { String[] strings = { "abstract", "author", "body", "byline", "date", "dbpedia_resource_url", "lead_paragraph", "title" }; public int getSize() { return strings.length; } public Object getElementAt(int i) { return strings[i]; } }); fieldsListScrollPane.setViewportView(fieldsList); 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, 0, 2, 0); optionalArticleSearchFieldsPanel.add(fieldsListScrollPane, gridBagConstraints); beginDateLabel.setText("Begin date (YYYYMMDD)"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; gridBagConstraints.insets = new java.awt.Insets(0, 0, 2, 4); optionalArticleSearchFieldsPanel.add(beginDateLabel, 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, 2, 0); optionalArticleSearchFieldsPanel.add(beginDateTextField, gridBagConstraints); endDateLabel.setText("End date (YYYYMMDD)"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; gridBagConstraints.insets = new java.awt.Insets(0, 0, 2, 4); optionalArticleSearchFieldsPanel.add(endDateLabel, 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, 2, 0); optionalArticleSearchFieldsPanel.add(endDateTextField, gridBagConstraints); pageLabel.setText("Page"); pageLabel.setToolTipText("The value of offset corresponds to a set of 10 results."); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; gridBagConstraints.insets = new java.awt.Insets(0, 0, 2, 4); optionalArticleSearchFieldsPanel.add(pageLabel, 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, 2, 0); optionalArticleSearchFieldsPanel.add(pageTextField, gridBagConstraints); sortLabel.setText("Sort"); sortLabel.setToolTipText("Use the rank parameter to set the order of the results. The default rank is newest."); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4); optionalArticleSearchFieldsPanel.add(sortLabel, gridBagConstraints); sortComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "newest", "oldest" })); sortComboBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { sortComboBoxActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; optionalArticleSearchFieldsPanel.add(sortComboBox, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(8, 0, 0, 0); articleSearchInnerPanel.add(optionalArticleSearchFieldsPanel, 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); articleSearchPanel.add(articleSearchInnerPanel, gridBagConstraints); nytTabbedPane.addTab("Article Search", articleSearchPanel); eventSearchPanel.setLayout(new java.awt.GridBagLayout()); eventSearchInnerPanel.setLayout(new java.awt.GridBagLayout()); eventQueryLabel.setText("Search query"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; eventSearchInnerPanel.add(eventQueryLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; eventSearchInnerPanel.add(eventQueryTextField, gridBagConstraints); eventBoxTab.setLayout(new java.awt.GridBagLayout()); boxLabel.setText("<html>Filter events by their location by specifying the Southwestern and Northeastern corners of a box.The default positions are Liberty State Park as the Southwestern corner and Jeromes Park as the Northeastern corner.</html>"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; 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, 12, 4); eventBoxTab.add(boxLabel, gridBagConstraints); boxSWpanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Southwest corner")); boxSWpanel.setLayout(new java.awt.GridBagLayout()); boxSWLatLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); boxSWLatLabel.setText("Latitude"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 0); boxSWpanel.add(boxSWLatLabel, gridBagConstraints); boxSWLongLabel.setText("Longitude"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(4, 4, 0, 0); boxSWpanel.add(boxSWLongLabel, gridBagConstraints); boxSWLatTextField.setText("40.702635"); 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, 4, 0, 4); boxSWpanel.add(boxSWLatTextField, gridBagConstraints); boxSWLongTextField.setText("-74.054976"); 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(4, 4, 0, 4); boxSWpanel.add(boxSWLongTextField, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; eventBoxTab.add(boxSWpanel, gridBagConstraints); boxNEpanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Northeast corner")); boxNEpanel.setLayout(new java.awt.GridBagLayout()); boxNELatLabel.setText("Latitude"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 0); boxNEpanel.add(boxNELatLabel, gridBagConstraints); boxNELongLabel.setText("Longitude"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(4, 4, 0, 0); boxNEpanel.add(boxNELongLabel, gridBagConstraints); boxNELatTextField.setText("40.877829"); 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, 4, 0, 4); boxNEpanel.add(boxNELatTextField, gridBagConstraints); boxNELongTextField.setText("-73.895845"); 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(4, 4, 0, 4); boxNEpanel.add(boxNELongTextField, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; eventBoxTab.add(boxNEpanel, gridBagConstraints); eventLocationTabs.addTab("Box", eventBoxTab); eventCircleTab.setLayout(new java.awt.GridBagLayout()); circleLabel.setText("<html>Filter events by their location by specifying the center coordinates and radius of a circle. By default the center of the circle is the New York Times building on Times Square and the radius of the circle is 1000 meters.</html>"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(4, 4, 12, 4); eventCircleTab.add(circleLabel, gridBagConstraints); circlCenterPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Center coordinates")); circlCenterPanel.setLayout(new java.awt.GridBagLayout()); circlCtrLongTextField.setText("-73.99021"); circlCtrLongTextField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { circlCtrLongTextFieldActionPerformed(evt); } }); 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(4, 4, 0, 4); circlCenterPanel.add(circlCtrLongTextField, gridBagConstraints); circlCtrLatTextField.setText("40.756146"); circlCtrLatTextField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { circlCtrLatTextFieldActionPerformed(evt); } }); 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, 4, 0, 4); circlCenterPanel.add(circlCtrLatTextField, gridBagConstraints); circlCtrLongLabel.setText("Longitude"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(4, 4, 0, 0); circlCenterPanel.add(circlCtrLongLabel, gridBagConstraints); circlCtrLatLabel.setText("Latitude"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 0); circlCenterPanel.add(circlCtrLatLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.PAGE_START; gridBagConstraints.weightx = 1.0; eventCircleTab.add(circlCenterPanel, gridBagConstraints); circlRadiusPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Radius")); circlRadiusPanel.setLayout(new java.awt.GridBagLayout()); circlRadTextField.setText("1000"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(4, 4, 0, 4); circlRadiusPanel.add(circlRadTextField, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.PAGE_START; gridBagConstraints.weightx = 0.7; eventCircleTab.add(circlRadiusPanel, gridBagConstraints); eventLocationTabs.addTab("Circle", eventCircleTab); eventFilterTab.setLayout(new java.awt.GridBagLayout()); filterLabel.setText("<html>Filter events by facets. Each text field and checkbox can be used independently of each other. '+' functions as a 'OR' operator and '-' as a 'NOT' operator. For example \"Theater+Dance-Movies\" in the Category field shows theater and dance events but not movies.</html>"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.PAGE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(4, 4, 12, 4); eventFilterTab.add(filterLabel, gridBagConstraints); evtFilterCatLabel.setText("Category"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 0); eventFilterTab.add(evtFilterCatLabel, 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, 4, 0, 4); eventFilterTab.add(evtFilterCatTextField, gridBagConstraints); evtFilterSubCatLabel.setText("Subcategory"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 0); eventFilterTab.add(evtFilterSubCatLabel, 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, 4, 0, 4); eventFilterTab.add(evtFilterSubCatTextField, gridBagConstraints); evtFilterBoroughLabel.setText("Borough"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 0); eventFilterTab.add(evtFilterBoroughLabel, 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, 4, 0, 4); eventFilterTab.add(evtFilterBoroughTextField, gridBagConstraints); evtFilterNeighborhoodLabel.setText("Neighborhood"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 0); eventFilterTab.add(evtFilterNeighborhoodLabel, 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, 4, 4, 4); eventFilterTab.add(evtFilterNeighborhoodTextField, gridBagConstraints); evtFilterTimesPick.setText("Times pick"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; eventFilterTab.add(evtFilterTimesPick, gridBagConstraints); evtFilterFree.setText("Free"); evtFilterFree.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; eventFilterTab.add(evtFilterFree, gridBagConstraints); evtFilterKidFriendly.setText("Kid friendly"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; eventFilterTab.add(evtFilterKidFriendly, gridBagConstraints); evtFilterLastChance.setText("Last chance"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 4, 0); eventFilterTab.add(evtFilterLastChance, gridBagConstraints); evtFilterFestival.setText("Festival"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; eventFilterTab.add(evtFilterFestival, gridBagConstraints); evtFilterLongRunningShow.setText("Long running show"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; eventFilterTab.add(evtFilterLongRunningShow, gridBagConstraints); evtFilterPreviewsAndOpenings.setText("Previews and Openings"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 1); eventFilterTab.add(evtFilterPreviewsAndOpenings, gridBagConstraints); eventLocationTabs.addTab("Faceted", eventFilterTab); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(8, 0, 8, 0); eventSearchInnerPanel.add(eventLocationTabs, gridBagConstraints); eventLimitPanel.setLayout(new java.awt.GridBagLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.gridheight = 2; eventSearchInnerPanel.add(eventLimitPanel, gridBagConstraints); eventDateRangePanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Time range")); eventDateRangePanel.setLayout(new java.awt.GridBagLayout()); evtDateStartLabel.setText("Start (YYYY-MM-DD)"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; eventDateRangePanel.add(evtDateStartLabel, gridBagConstraints); evtDateEndLabel.setText("End (YYYY-MM-DD)"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(4, 0, 0, 0); eventDateRangePanel.add(evtDateEndLabel, gridBagConstraints); evtDateStartTextField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { evtDateStartTextFieldActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 4); eventDateRangePanel.add(evtDateStartTextField, 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(4, 4, 0, 4); eventDateRangePanel.add(evtDateEndTextField, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 0.6; eventSearchInnerPanel.add(eventDateRangePanel, gridBagConstraints); eventOffsetPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Offset")); eventOffsetPanel.setLayout(new java.awt.GridBagLayout()); evtOffset.setText("Offset"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; eventOffsetPanel.add(evtOffset, gridBagConstraints); evtOffsetTextField.setText("0"); 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, 4, 0, 4); eventOffsetPanel.add(evtOffsetTextField, gridBagConstraints); evtLimitLabel.setText("Limit"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.insets = new java.awt.Insets(0, 0, 4, 0); eventOffsetPanel.add(evtLimitLabel, gridBagConstraints); evtLimitTextField.setText("20"); 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, 4, 4, 4); eventOffsetPanel.add(evtLimitTextField, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 0.4; eventSearchInnerPanel.add(eventOffsetPanel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; eventSearchInnerPanel.add(jPanel1, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); eventSearchPanel.add(eventSearchInnerPanel, gridBagConstraints); nytTabbedPane.addTab("Event search", eventSearchPanel); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(nytTabbedPane, gridBagConstraints); buttonPanel.setLayout(new java.awt.GridBagLayout()); forgetButton.setText("Forget api-key"); forgetButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { forgetButtonActionPerformed(evt); } }); buttonPanel.add(forgetButton, new java.awt.GridBagConstraints()); buttonFillerPanel.setLayout(new java.awt.GridBagLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; buttonPanel.add(buttonFillerPanel, gridBagConstraints); okButton.setText("Extract"); okButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { okButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 2); buttonPanel.add(okButton, gridBagConstraints); cancelButton.setText("Cancel"); cancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelButtonActionPerformed(evt); } }); buttonPanel.add(cancelButton, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2); add(buttonPanel, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed accepted = false; if (this.dialog != null) { this.dialog.setVisible(false); } }//GEN-LAST:event_cancelButtonActionPerformed 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 forgetButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_forgetButtonActionPerformed if (articleSearchPanel.equals(nytTabbedPane.getSelectedComponent())){ articleapikey = null; forgetButton.setEnabled(false); } else if(eventSearchPanel.equals(nytTabbedPane.getSelectedComponent())){ eventapikey = null; forgetButton.setEnabled(false); } }//GEN-LAST:event_forgetButtonActionPerformed private void nytTabbedPaneStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_nytTabbedPaneStateChanged if(articleSearchPanel.equals(nytTabbedPane.getSelectedComponent())){ if(articleapikey != null) forgetButton.setEnabled(true); else forgetButton.setEnabled(false); } else if(eventSearchPanel.equals(nytTabbedPane.getSelectedComponent())){ if(eventapikey != null) forgetButton.setEnabled(true); else forgetButton.setEnabled(false); } }//GEN-LAST:event_nytTabbedPaneStateChanged private void sortComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sortComboBoxActionPerformed // TODO add your handling code here: }//GEN-LAST:event_sortComboBoxActionPerformed private void circlCtrLongTextFieldActionPerformed(java.awt.event.ActionEvent evt){ } private void circlCtrLatTextFieldActionPerformed(java.awt.event.ActionEvent evt){ } private void evtDateStartTextFieldActionPerformed(java.awt.event.ActionEvent evt){ } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel articleSearchInnerPanel; private javax.swing.JPanel articleSearchPanel; private javax.swing.JLabel beginDateLabel; private javax.swing.JTextField beginDateTextField; private javax.swing.JLabel boxLabel; private javax.swing.JLabel boxNELatLabel; private javax.swing.JTextField boxNELatTextField; private javax.swing.JLabel boxNELongLabel; private javax.swing.JTextField boxNELongTextField; private javax.swing.JPanel boxNEpanel; private javax.swing.JLabel boxSWLatLabel; private javax.swing.JTextField boxSWLatTextField; private javax.swing.JLabel boxSWLongLabel; private javax.swing.JTextField boxSWLongTextField; private javax.swing.JPanel boxSWpanel; private javax.swing.JPanel buttonFillerPanel; private javax.swing.JPanel buttonPanel; private javax.swing.JButton cancelButton; private javax.swing.JPanel circlCenterPanel; private javax.swing.JLabel circlCtrLatLabel; private javax.swing.JTextField circlCtrLatTextField; private javax.swing.JLabel circlCtrLongLabel; private javax.swing.JTextField circlCtrLongTextField; private javax.swing.JTextField circlRadTextField; private javax.swing.JPanel circlRadiusPanel; private javax.swing.JLabel circleLabel; private javax.swing.JLabel endDateLabel; private javax.swing.JTextField endDateTextField; private javax.swing.JPanel eventBoxTab; private javax.swing.JPanel eventCircleTab; private javax.swing.JPanel eventDateRangePanel; private javax.swing.JPanel eventFilterTab; private javax.swing.JPanel eventLimitPanel; private javax.swing.JTabbedPane eventLocationTabs; private javax.swing.JPanel eventOffsetPanel; private javax.swing.JLabel eventQueryLabel; private javax.swing.JTextField eventQueryTextField; private javax.swing.JPanel eventSearchInnerPanel; private javax.swing.JPanel eventSearchPanel; private javax.swing.JLabel evtDateEndLabel; private javax.swing.JTextField evtDateEndTextField; private javax.swing.JLabel evtDateStartLabel; private javax.swing.JTextField evtDateStartTextField; private javax.swing.JLabel evtFilterBoroughLabel; private javax.swing.JTextField evtFilterBoroughTextField; private javax.swing.JLabel evtFilterCatLabel; private javax.swing.JTextField evtFilterCatTextField; private javax.swing.JCheckBox evtFilterFestival; private javax.swing.JCheckBox evtFilterFree; private javax.swing.JCheckBox evtFilterKidFriendly; private javax.swing.JCheckBox evtFilterLastChance; private javax.swing.JCheckBox evtFilterLongRunningShow; private javax.swing.JLabel evtFilterNeighborhoodLabel; private javax.swing.JTextField evtFilterNeighborhoodTextField; private javax.swing.JCheckBox evtFilterPreviewsAndOpenings; private javax.swing.JLabel evtFilterSubCatLabel; private javax.swing.JTextField evtFilterSubCatTextField; private javax.swing.JCheckBox evtFilterTimesPick; private javax.swing.JLabel evtLimitLabel; private javax.swing.JTextField evtLimitTextField; private javax.swing.JLabel evtOffset; private javax.swing.JTextField evtOffsetTextField; private javax.swing.JLabel facetsLabel; private javax.swing.JTextField facetsTextField; private javax.swing.JLabel fieldsLabel; private javax.swing.JList fieldsList; private javax.swing.JScrollPane fieldsListScrollPane; private javax.swing.JLabel filterLabel; private javax.swing.JButton forgetButton; private javax.swing.JPanel jPanel1; private javax.swing.JTabbedPane nytTabbedPane; private javax.swing.JButton okButton; private javax.swing.JPanel optionalArticleSearchFieldsPanel; private javax.swing.JLabel pageLabel; private javax.swing.JTextField pageTextField; private javax.swing.JLabel searchLabel; private javax.swing.JTextField searchQueryTextField; private javax.swing.JComboBox sortComboBox; private javax.swing.JLabel sortLabel; // End of variables declaration//GEN-END:variables }
55,560
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
NYTExtractorUI.java.orig
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/nyt/NYTExtractorUI.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/>. * * * NYTExtractorUI.java * * Created on Apr 14, 2012, 9:43:48 PM */ package org.wandora.application.tools.extractors.nyt; import java.awt.Component; import java.net.URLEncoder; import java.util.ArrayList; import javax.swing.JDialog; import javax.swing.ListModel; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.application.gui.simple.SimpleButton; import org.wandora.application.gui.simple.SimpleField; import org.wandora.application.gui.simple.SimpleLabel; import org.wandora.application.gui.simple.SimpleList; import org.wandora.application.gui.simple.SimpleTabbedPane; import org.wandora.application.tools.extractors.AbstractExtractor; /** * * @author akivela */ public class NYTExtractorUI extends javax.swing.JPanel { private Wandora wandora = null; private boolean accepted = false; private JDialog dialog = null; private Context context = null; private static final String NYT_API_BASE = "http://api.nytimes.com/svc/search/v1/"; private static final String NYT_API_EVENT_BASE = "http://api.nytimes.com/svc/events/v2/listings.json"; /** Creates new form NYTExtractorUI */ public NYTExtractorUI() { initComponents(); } public boolean wasAccepted() { return accepted; } public void setAccepted(boolean b) { accepted = b; } public void open(Wandora w, Context c) { context = c; accepted = false; dialog = new JDialog(w, true); dialog.setSize(550,500); dialog.add(this); dialog.setTitle("New York Times API extractor"); UIBox.centerWindow(dialog, w); if(apikey == null) { forgetButton.setEnabled(false); } else { forgetButton.setEnabled(true); } dialog.setVisible(true); } public WandoraTool[] getExtractors(NYTExtractor tool) { Component component = eventSearchPanel.getSelectedComponent(); WandoraTool wt = null; ArrayList<WandoraTool> wts = new ArrayList(); // ***** SEARCH ARTICLES ***** if(articleSearchPanel.equals(component)) { String query = searchQueryTextField.getText(); String key = solveAPIKey(); String extractUrl = NYT_API_BASE+"article?query="+urlEncode(query)+"&api-key="+key; String facets = facetsTextField.getText().trim(); if(facets != null && facets.length() > 0) { extractUrl += "&facets="+urlEncode(facets); } int[] fieldIndexes = fieldsList.getSelectedIndices(); ListModel listModel = fieldsList.getModel(); StringBuilder fieldValues = new StringBuilder(""); for(int i=0; i<fieldIndexes.length; i++) { if(i>0) fieldValues.append(","); fieldValues.append(listModel.getElementAt(fieldIndexes[i])); } if(fieldValues.length() > 0) { extractUrl += "&fields="+urlEncode("url,"+fieldValues.toString()); } String beginDate = beginDateTextField.getText().trim(); if(beginDate != null && beginDate.length() > 0) { extractUrl += "&begin_date="+urlEncode(beginDate); } String endDate = endDateTextField.getText().trim(); if(endDate != null && endDate.length() > 0) { extractUrl += "&end_date="+urlEncode(endDate); } String offset = offsetTextField.getText().trim(); if(offset == null || offset.length() == 0) offset = "0"; extractUrl += "&offset="+urlEncode(offset); String rank = rankComboBox.getSelectedItem().toString(); if(rank != null && rank.length() > 0) { extractUrl += "&rank="+urlEncode(rank); } System.out.println("URL: "+extractUrl); NYTArticleSearchExtractor ex = new NYTArticleSearchExtractor(); ex.setForceUrls( new String[] { extractUrl } ); wt = ex; wts.add( wt ); } //***** SEARCH EVENTS ***** else if( eventSearchPanel.equals(component) ) { String key = solveAPIKey(); String extractUrl = NYT_API_EVENT_BASE+"?ll=40.756146,-73.99021&api-key="+key; System.out.println("URL: "+extractUrl); NYTEventSearchExtractor ex = new NYTEventSearchExtractor(); ex.setForceUrls(new String[] {extractUrl } ); wt = ex; wts.add(wt); } return wts.toArray( new WandoraTool[] {} ); } protected static String urlEncode(String str) { try { str = URLEncoder.encode(str, "utf-8"); } catch(Exception e) {} return str; } // ------------------------------------------------------------ API-KEY ---- private static String apikey = null; public String solveAPIKey(Wandora wandora) { return solveAPIKey(); } public String solveAPIKey() { if(apikey == null) { apikey = ""; apikey = WandoraOptionPane.showInputDialog(Wandora.getWandora(), "Please give an api-key for NYT. You can register your api-key at http://developer.nytimes.com/docs/reference/keys", apikey, "NYT api-key", WandoraOptionPane.QUESTION_MESSAGE); apikey = apikey.trim(); } return apikey; } public void forgetAuthorization() { apikey = 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; facetsLabel = new SimpleLabel(); facetsTextField = new SimpleField(); eventSearchPanel = new SimpleTabbedPane(); articleSearchPanel = new javax.swing.JPanel(); articleSearchInnerPanel = new javax.swing.JPanel(); searchLabel = new SimpleLabel(); searchQueryTextField = new SimpleField(); optionalArticleSearchFieldsPanel = new javax.swing.JPanel(); fieldsLabel = new SimpleLabel(); fieldsListScrollPane = new javax.swing.JScrollPane(); fieldsList = new SimpleList(); beginDateLabel = new SimpleLabel(); beginDateTextField = new SimpleField(); endDateLabel = new SimpleLabel(); endDateTextField = new SimpleField(); offsetLabel = new SimpleLabel(); offsetTextField = new SimpleField(); rankLabel = new SimpleLabel(); rankComboBox = new javax.swing.JComboBox(); jTabbedPane1 = new javax.swing.JTabbedPane(); buttonPanel = new javax.swing.JPanel(); forgetButton = new SimpleButton(); buttonFillerPanel = new javax.swing.JPanel(); okButton = new SimpleButton(); cancelButton = new SimpleButton(); facetsLabel.setText("Facets"); facetsLabel.setToolTipText("Comma-delimited list of up to 5 facets."); setLayout(new java.awt.GridBagLayout()); articleSearchPanel.setLayout(new java.awt.GridBagLayout()); articleSearchInnerPanel.setLayout(new java.awt.GridBagLayout()); searchLabel.setText("Search query"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; articleSearchInnerPanel.add(searchLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; articleSearchInnerPanel.add(searchQueryTextField, gridBagConstraints); optionalArticleSearchFieldsPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Optional params")); optionalArticleSearchFieldsPanel.setLayout(new java.awt.GridBagLayout()); fieldsLabel.setText("Fields"); fieldsLabel.setToolTipText("Comma-delimited list of fields (no limit)."); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_END; gridBagConstraints.insets = new java.awt.Insets(2, 0, 2, 4); optionalArticleSearchFieldsPanel.add(fieldsLabel, gridBagConstraints); fieldsListScrollPane.setMinimumSize(new java.awt.Dimension(23, 150)); fieldsListScrollPane.setPreferredSize(new java.awt.Dimension(125, 150)); fieldsList.setModel(new javax.swing.AbstractListModel() { String[] strings = { "abstract", "author", "body", "byline", "classifiers_facet", "column_facet", "date", "dbpedia_resource_url", "des_facet", "geo_facet", "lead_paragraph", "material_type_facet", "org_facet", "per_facet", "source_facet", "title" }; public int getSize() { return strings.length; } public Object getElementAt(int i) { return strings[i]; } }); fieldsListScrollPane.setViewportView(fieldsList); 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, 0, 2, 0); optionalArticleSearchFieldsPanel.add(fieldsListScrollPane, gridBagConstraints); beginDateLabel.setText("Begin date (YYYYMMDD)"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; gridBagConstraints.insets = new java.awt.Insets(0, 0, 2, 4); optionalArticleSearchFieldsPanel.add(beginDateLabel, 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, 2, 0); optionalArticleSearchFieldsPanel.add(beginDateTextField, gridBagConstraints); endDateLabel.setText("End date (YYYYMMDD)"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; gridBagConstraints.insets = new java.awt.Insets(0, 0, 2, 4); optionalArticleSearchFieldsPanel.add(endDateLabel, 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, 2, 0); optionalArticleSearchFieldsPanel.add(endDateTextField, gridBagConstraints); offsetLabel.setText("Offset"); offsetLabel.setToolTipText("The value of offset corresponds to a set of 10 results."); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; gridBagConstraints.insets = new java.awt.Insets(0, 0, 2, 4); optionalArticleSearchFieldsPanel.add(offsetLabel, 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, 2, 0); optionalArticleSearchFieldsPanel.add(offsetTextField, gridBagConstraints); rankLabel.setText("Rank"); rankLabel.setToolTipText("Use the rank parameter to set the order of the results. The default rank is newest."); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4); optionalArticleSearchFieldsPanel.add(rankLabel, gridBagConstraints); rankComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "newest", "oldest", "closest" })); rankComboBox.setMinimumSize(new java.awt.Dimension(120, 20)); rankComboBox.setPreferredSize(new java.awt.Dimension(120, 20)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; optionalArticleSearchFieldsPanel.add(rankComboBox, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(8, 0, 0, 0); articleSearchInnerPanel.add(optionalArticleSearchFieldsPanel, 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); articleSearchPanel.add(articleSearchInnerPanel, gridBagConstraints); eventSearchPanel.addTab("Article search", articleSearchPanel); eventSearchPanel.addTab("Event search", jTabbedPane1); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(eventSearchPanel, gridBagConstraints); buttonPanel.setLayout(new java.awt.GridBagLayout()); forgetButton.setText("Forget api-key"); forgetButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { forgetButtonActionPerformed(evt); } }); buttonPanel.add(forgetButton, new java.awt.GridBagConstraints()); buttonFillerPanel.setLayout(new java.awt.GridBagLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; buttonPanel.add(buttonFillerPanel, gridBagConstraints); okButton.setText("Extract"); okButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { okButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 2); buttonPanel.add(okButton, gridBagConstraints); cancelButton.setText("Cancel"); cancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelButtonActionPerformed(evt); } }); buttonPanel.add(cancelButton, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2); add(buttonPanel, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed accepted = false; if(this.dialog != null) this.dialog.setVisible(false); }//GEN-LAST:event_cancelButtonActionPerformed 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 forgetButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_forgetButtonActionPerformed apikey = null; }//GEN-LAST:event_forgetButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel articleSearchInnerPanel; private javax.swing.JPanel articleSearchPanel; private javax.swing.JLabel beginDateLabel; private javax.swing.JTextField beginDateTextField; private javax.swing.JPanel buttonFillerPanel; private javax.swing.JPanel buttonPanel; private javax.swing.JButton cancelButton; private javax.swing.JLabel endDateLabel; private javax.swing.JTextField endDateTextField; private javax.swing.JTabbedPane eventSearchPanel; private javax.swing.JLabel facetsLabel; private javax.swing.JTextField facetsTextField; private javax.swing.JLabel fieldsLabel; private javax.swing.JList fieldsList; private javax.swing.JScrollPane fieldsListScrollPane; private javax.swing.JButton forgetButton; private javax.swing.JTabbedPane jTabbedPane1; private javax.swing.JLabel offsetLabel; private javax.swing.JTextField offsetTextField; private javax.swing.JButton okButton; private javax.swing.JPanel optionalArticleSearchFieldsPanel; private javax.swing.JComboBox rankComboBox; private javax.swing.JLabel rankLabel; private javax.swing.JLabel searchLabel; private javax.swing.JTextField searchQueryTextField; // End of variables declaration//GEN-END:variables }
19,576
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AbstractNYTExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/nyt/AbstractNYTExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.nyt; import java.util.HashMap; import java.util.Map; 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 * akivela * @author Eero Lehtonen */ public abstract class AbstractNYTExtractor extends AbstractExtractor { private static final long serialVersionUID = 1L; @Override public String getName() { return "Abstract New York Times API extractor"; } @Override public String getDescription(){ return "Abstract extractor for The New York Times API."; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_nyt.png"); } private final String[] contentTypes=new String[] { "text/plain", "text/json", "application/json" }; @Override public String[] getContentTypes() { return contentTypes; } @Override public boolean useURLCrawler() { return false; } @Override public boolean runInOwnThread() { return false; } // ------------------------------------------------------------------------- // ------------------------------------------------------ ARTICLE SEARCH --- public static final String DBPEDIA_RESOURCE_SI = "http://wandora.org/si/nytimes/dbpedia"; public static final String BYLINE_SI = "http://wandora.org/si/nytimes/byline"; public static final String ARTICLE_SI = "http://api.nytimes.com/svc/search/v1/article"; public static final String BODY_SI = "http://wandora.org/si/nytimes/body"; public static final String TEXT_SI = "http://wandora.org/si/nytimes/text"; public static final String ABSTRACT_SI = "http://wandora.org/si/nytimes/abstract"; public static final String LEAD_PARAGRAPH_SI = "http://wandora.org/si/nytimes/lead-paragraph"; public static final String DATE_SI = "http://wandora.org/si/nytimes/date"; public static final String LANG_SI = "http://www.topicmaps.org/xtm/1.0/language.xtm#en"; public static final String FACET_SI = "http://wandora.org/si/nytimes/facet"; public static final String KEYWORD_SI = "http://wandora.org/si/nytimes/keyword"; public static final String DES_FACET_SI = "http://wandora.org/si/nytimes/facet/des"; public static final String GEO_FACET_SI = "http://wandora.org/si/nytimes/facet/geo"; public static final String ORG_FACET_SI = "http://wandora.org/si/nytimes/facet/org"; public static final String PER_FACET_SI = "http://wandora.org/si/nytimes/facet/per"; public static final String SOURCE_FACET_SI = "http://wandora.org/si/nytimes/facet/source"; public static final String CLASSIFIER_FACET_SI = "http://wandora.org/si/nytimes/facet/classifier"; public static final String COLUMN_FACET_SI = "http://wandora.org/si/nytimes/facet/column"; public static final String MATERIAL_TYPE_FACET_SI = "http://wandora.org/si/nytimes/facet/material-type"; public static final String NYT_SI = "http://www.nytimes.com"; protected static Topic getLangTopic(TopicMap tm) throws TopicMapException { Topic lang = getOrCreateTopic(tm, LANG_SI); return lang; } public static Topic getBylineTopic(String byline, TopicMap tm) throws TopicMapException { Topic facetTopic=getOrCreateTopic(tm, BYLINE_SI+urlEncode(byline), byline); facetTopic.addType(getBylineTypeTopic(tm)); return facetTopic; } public static Topic getBylineTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, BYLINE_SI, "byline (New York Times API)"); Topic nytTopic = getNYTTypeTopic(tm); makeSubclassOf(tm, type, nytTopic); return type; } public static Topic getKeywordTopic(String keyword, TopicMap tm) throws TopicMapException { Topic keywordTopic=getOrCreateTopic(tm, KEYWORD_SI+"/"+urlEncode(keyword), keyword); keywordTopic.addType(getKeywordTypeTopic(tm)); return keywordTopic; } public static Topic getKeywordNameTopic(String name, TopicMap tm) throws TopicMapException { Topic nameTopic=getOrCreateTopic(tm, KEYWORD_SI+"/"+urlEncode(name), "article-"+name+"-keyword (New York Times API)"); Topic typeTopic = getKeywordTypeTopic(tm); makeSubclassOf(tm, nameTopic, typeTopic); return nameTopic; } public static Topic getKeywordTypeTopic(TopicMap tm) throws TopicMapException { Topic typeTopic=getOrCreateTopic(tm, KEYWORD_SI, "article-keyword (New York Times API)"); Topic nytTopic = getNYTTypeTopic(tm); makeSubclassOf(tm, typeTopic, nytTopic); return typeTopic; } public static Topic getDBpediaResourceTopic(String res, TopicMap tm) throws TopicMapException { Topic resTopic=getOrCreateTopic(tm, res); resTopic.addType(getDBpediaResourceTypeTopic(tm)); return resTopic; } public static Topic getDBpediaResourceTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, DBPEDIA_RESOURCE_SI, "article-dbpedia-resource (New York Times API)"); Topic nytTopic = getNYTTypeTopic(tm); makeSubclassOf(tm, type, nytTopic); return type; } public static Topic getAbstractTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, ABSTRACT_SI, "article-abstract (New York Times API)"); Topic nytTopic = getNYTTypeTopic(tm); makeSubclassOf(tm, type, nytTopic); return type; } public static Topic getBodyTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, BODY_SI, "article-body (New York Times API)"); Topic nytTopic = getNYTTypeTopic(tm); makeSubclassOf(tm, type, nytTopic); return type; } public static Topic getTextTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, TEXT_SI, "article-text (New York Times API)"); Topic nytTopic = getNYTTypeTopic(tm); makeSubclassOf(tm, type, nytTopic); return type; } public static Topic getLeadParagraphTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, LEAD_PARAGRAPH_SI, "article-lead-paragraph (New York Times API)"); Topic nytTopic = getNYTTypeTopic(tm); makeSubclassOf(tm, type, nytTopic); return type; } public static Topic getArticleTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, ARTICLE_SI, "article (New York Times API)"); Topic nytTopic = getNYTTypeTopic(tm); makeSubclassOf(tm, type, nytTopic); return type; } public static Topic getDateTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, DATE_SI, "article-date (New York Times API)"); Topic nytTopic = getNYTTypeTopic(tm); makeSubclassOf(tm, type, nytTopic); return type; } public static Topic getNYTTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, NYT_SI, "New York Times API"); Topic wandoraClass = getWandoraClassTopic(tm); makeSubclassOf(tm, type, wandoraClass); return type; } 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); } // ------------------------------------------------------ EVENT SEARCH ----- // Also uses getNYTTypeTopic from above public static final String EVENT_SI = "http://api.nytimes.com/svc/events/v2"; public static final String EVENT_DETAIL_URL_SI = "http://wandora.org/si/nytimes/event/url"; public static final String EVENT_NAME_SI = "http://wandora.org/si/nytimes/event/name"; public static final String EVENT_DESCRIPTION_SI = "http://wandora.org/si/nytimes/event/description"; public static final String EVENT_VENUE_SI = "http://wandora.org/si/nytimes/event/venue"; public static final String EVENT_CATEGORY_SI = "http://wandora.org/si/nytimes/event/category"; public static final String EVENT_LATITUDE_SI = "http://wandora.org/si/nytimes/event/latitude"; public static final String EVENT_LONGITUDE_SI = "http://wandora.org/si/nytimes/event/longitude"; public static final String EVENT_DATE_SI = "http://wandora.org/si/nytimes/eventDate"; public static final String START_DATE_SI = "http://wandora.org/si/nytimes/startDate"; public static final String END_DATE_SI = "http://wandora.org/si/nytimes/endDate"; public static final String WEEKDAY_SI = "http://wandora.org/si/nytimes/dayOfWeek/"; public static final String RECURRING_DAY_SI = "http://wandora.org/si/nytimes/recurringDay/"; public static Topic getEventTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, EVENT_SI, "Event (New York Times API)"); Topic nytTopic = getNYTTypeTopic(tm); makeSubclassOf(tm, type, nytTopic); return type; } public static Topic getDescriptionTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, EVENT_DESCRIPTION_SI, "Event description (New York Times API)"); Topic nytTopic = getNYTTypeTopic(tm); makeSubclassOf(tm, type, nytTopic); return type; } public static Topic getLatitudeTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, EVENT_LATITUDE_SI, "Event latitude (New York Times API)"); Topic nytTopic = getNYTTypeTopic(tm); makeSubclassOf(tm, type, nytTopic); return type; } public static Topic getLongitudeTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, EVENT_LONGITUDE_SI, "Event longitude (New York Times API)"); Topic nytTopic = getNYTTypeTopic(tm); makeSubclassOf(tm, type, nytTopic); return type; } public static Topic getVenueTopic(String venue, TopicMap tm) throws TopicMapException { Topic resTopic=getOrCreateTopic(tm, venue); resTopic.addType(getVenueTypeTopic(tm)); return resTopic; } public static Topic getVenueTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, EVENT_VENUE_SI, "Event venue (New York Times API)"); Topic nytTopic = getNYTTypeTopic(tm); makeSubclassOf(tm, type, nytTopic); return type; } public static Topic getCategoryTopic(String category, TopicMap tm) throws TopicMapException { Topic resTopic=getOrCreateTopic(tm, category); resTopic.addType(getCategoryTypeTopic(tm)); return resTopic; } public static Topic getCategoryTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, EVENT_CATEGORY_SI, "Event category (New York Times API)"); Topic nytTopic = getNYTTypeTopic(tm); makeSubclassOf(tm, type, nytTopic); return type; } public static Topic getEventDateTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, EVENT_DATE_SI, "Event date (New York Times API)"); Topic nytTopic = getNYTTypeTopic(tm); makeSubclassOf(tm, type, nytTopic); return type; } public static Topic getStartDateTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, START_DATE_SI, "Event start date (New York Times API)"); Topic nytTopic = getNYTTypeTopic(tm); makeSubclassOf(tm, type, nytTopic); return type; } public static Topic getEndDateTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, END_DATE_SI, "Event end date (New York Times API)"); Topic nytTopic = getNYTTypeTopic(tm); makeSubclassOf(tm, type, nytTopic); return type; } public static Topic getDayOfWeekTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, WEEKDAY_SI, "Day of Week (New York Times API)"); Topic nytTopic = getNYTTypeTopic(tm); makeSubclassOf(tm, type, nytTopic); return type; } public static Topic getRecurringDayTypeTopic(TopicMap tm) throws TopicMapException{ return getOrCreateTopic(tm, RECURRING_DAY_SI, "Recurring Day (New York Times API)"); } private enum DayOfWeek{ MONDAY ("monday", "Monday"), TUESDAY ("tuesday", "Tuesday"), WEDNESDAY ("wednesday", "Wednesday"), THURSDAY ("thursday", "Thursday"), FRIDAY ("friday", "Friday"), SATURDAY ("saturday", "Saturday"), SUNDAY ("sunday", "Sunday"); public final String urlStub; public final String display; DayOfWeek(String urlStub, String display){ this.urlStub = urlStub; this.display = display; } } static final Map<String, DayOfWeek> abbrToDayOfWeek = new HashMap<String, DayOfWeek>(){{ put("mon", DayOfWeek.MONDAY); put("tue", DayOfWeek.TUESDAY); put("wed", DayOfWeek.WEDNESDAY); put("thu", DayOfWeek.THURSDAY); put("fri", DayOfWeek.FRIDAY); put("sat", DayOfWeek.SATURDAY); put("sun", DayOfWeek.SUNDAY); }}; public static Topic getRecurringDayTopic(TopicMap tm, String abbr) throws TopicMapException{ DayOfWeek wd = abbrToDayOfWeek.get(abbr); String si = WEEKDAY_SI + wd.urlStub; String baseName = wd.display + " (New York Times API)"; Topic dayTopic = getOrCreateTopic(tm, si, baseName); dayTopic.addType(getDayOfWeekTypeTopic(tm)); return dayTopic; } }
15,574
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
NYTExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/nyt/NYTExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.nyt; import java.io.File; import java.net.URL; import javax.swing.Icon; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.gui.UIBox; import org.wandora.application.tools.extractors.AbstractExtractor; import org.wandora.topicmap.TopicMap; /** * * @author akivela */ public class NYTExtractor extends AbstractExtractor { private static final long serialVersionUID = 1L; private NYTExtractorUI ui = null; @Override public String getName() { return "NYT API Extractor"; } @Override public String getDescription(){ return "Extracts topics and associations from The New York Times API. "+ "Extractor supports only Article Search API at the moment. A personal api-key is"+ "required for the API access."; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_nyt.png"); } private final String[] contentTypes=new String[] { "text/plain", "text/json", "application/json" }; @Override public String[] getContentTypes() { return contentTypes; } @Override public boolean useURLCrawler() { return false; } @Override public void execute(Wandora wandora, Context context) { try { if(ui == null) { ui = new NYTExtractorUI(); } 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 New York Times 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); } // ------------------------------------------------------------------------- @Override public boolean _extractTopicsFrom(File f, TopicMap t) throws Exception { throw new UnsupportedOperationException("This extractor is a frontend for other New Your Times 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 New Your Times 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 New Your Times extractors. It doesn't perform extration it self."); } }
4,563
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
NYTArticleSearchExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/nyt/NYTArticleSearchExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.nyt; import java.io.File; import java.net.URL; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.wandora.application.Wandora; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.utils.HTMLEntitiesCoder; import org.wandora.utils.IObox; /** * * @author akivela * @author Eero Lehtonen */ public class NYTArticleSearchExtractor extends AbstractNYTExtractor { private static final long serialVersionUID = 1L; private static String defaultLang = "en"; private static String currentURL = null; @Override public String getName() { return "New York Times Article Search API extractor"; } @Override public String getDescription() { return "Extractor performs an article search using The New York Times API and " + "transforms results to topics and associations."; } // ------------------------------------------------------------------------- @Override public boolean _extractTopicsFrom(File f, TopicMap tm) throws Exception { currentURL = null; String in = IObox.loadFile(f); JSONObject json = new JSONObject(in); parse(json, tm); return true; } @Override public boolean _extractTopicsFrom(URL u, TopicMap tm) throws Exception { currentURL = u.toExternalForm(); log("Article search extraction with " + currentURL); String in = IObox.doUrl(u); System.out.println("New York Times API returned-------------------------\n" + in + "\n----------------------------------------------------"); 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); parse(json, tm); return true; } // ------------------------------------------------------------------------- public void parse(JSONObject json, TopicMap tm) throws TopicMapException { if (json.has("response")) { try { json = json.getJSONObject("response"); if (json.has("docs")) { JSONArray resultsArray = json.getJSONArray("docs"); for (int i = 0; i < resultsArray.length(); i++) { JSONObject result = resultsArray.getJSONObject(i); try { parseResult(result, tm); } catch (JSONException | TopicMapException e) { e.printStackTrace(); log(e); } } } handlePagination(json, tm); } catch (JSONException e) { log(e); } } } private boolean shouldHandlePagination = true; private String defaultPagingOption = null; private void handlePagination(JSONObject json, TopicMap tm) { if (!shouldHandlePagination || forceStop()) { return; } try { JSONObject meta = json.getJSONObject("meta"); int page = 0; if (meta.has("offset")) { page = meta.getInt("offset"); } int total = meta.getInt("hits"); int totalPages = (total / 10) + (total % 10 == 0 ? 0 : 1); if (page >= totalPages || currentURL == null) return; String[] pagingOptions = new String[]{ "Do not extract any more pages", "Extract only next page", "Extract next page", "Extract 10 next pages", "Extract all next pages" }; String message = "You have just extracted page " + (page + 1) + ". There is total " + totalPages + " pages available. " + "What would you like to do? Remember New York Times " + "APIs limit daily requests. Extracting one page takes " + "one request."; if (defaultPagingOption == null) { defaultPagingOption = pagingOptions[0]; } String a = WandoraOptionPane.showOptionDialog( Wandora.getWandora(), message, "Found more pages", WandoraOptionPane.OK_CANCEL_OPTION, pagingOptions, defaultPagingOption); defaultPagingOption = a; if (a == null) return; String originalURL = currentURL; if (pagingOptions[1].equals(a)) { System.out.println("Selected to extract only next page"); String newURL = originalURL.replace("page=" + page, "page=" + (page + 1)); shouldHandlePagination = false; _extractTopicsFrom(new URL(newURL), tm); } else if (pagingOptions[2].equals(a)) { System.out.println("Selected to extract next page"); String newURL = originalURL.replace("page=" + page, "page=" + (page + 1)); _extractTopicsFrom(new URL(newURL), tm); } else if (pagingOptions[3].equals(a)) { System.out.println("Selected to extract 10 next pages"); shouldHandlePagination = false; setProgress(1); setProgressMax(10); int progress = 1; for (int p = page + 1; p <= Math.min(page + 10, totalPages) && !forceStop(); p++) { String newURL = originalURL.replace("page=" + page, "page=" + p); if (p == page + 10) { shouldHandlePagination = true; } _extractTopicsFrom(new URL(newURL), tm); setProgress(progress++); nap(); } } else if (pagingOptions[4].equals(a)) { System.out.println("Selected to extract all pages"); shouldHandlePagination = false; setProgress(1); setProgressMax((int) (total - page)); int progress = 1; for (int p = page + 1; p <= totalPages && !forceStop(); p++) { String newURL = originalURL.replace("page=" + page, "page=" + p); _extractTopicsFrom(new URL(newURL), tm); setProgress(progress++); nap(); } shouldHandlePagination = true; } } catch (Exception ex) { log(ex); } } private void nap() { try { Thread.sleep(200); } catch (Exception e) { // WAKE UP } } public void parseResult(JSONObject result, TopicMap tm) throws JSONException, TopicMapException { String url = result.getString("web_url"); // All results should contain an url at least. Topic articleTopic = tm.createTopic(); articleTopic.addSubjectIdentifier(new Locator(url)); articleTopic.addType(getArticleTypeTopic(tm)); if (result.has("body") && !result.isNull("body")) { String body = result.getString("body"); if (body != null && body.length() > 0) { body = HTMLEntitiesCoder.decode(body); Topic bodyTypeTopic = getBodyTypeTopic(tm); Topic langTopic = getLangTopic(tm); articleTopic.setData(bodyTypeTopic, langTopic, body); } } if (result.has("abstract") && !result.isNull("abstract")) { String abst = result.getString("abstract"); if (abst != null && abst.length() > 0) { abst = HTMLEntitiesCoder.decode(abst); Topic abstTypeTopic = getAbstractTypeTopic(tm); Topic langTopic = getLangTopic(tm); articleTopic.setData(abstTypeTopic, langTopic, abst); } } if (result.has("text") && !result.isNull("text")) { String text = result.getString("text"); if (text != null && text.length() > 0) { text = HTMLEntitiesCoder.decode(text); Topic textTypeTopic = getTextTypeTopic(tm); Topic langTopic = getLangTopic(tm); articleTopic.setData(textTypeTopic, langTopic, text); } } if (result.has("lead_paragraph") && !result.isNull("lead_paragraph")) { String lead_paragraph = result.getString("lead_paragraph"); if (lead_paragraph != null && lead_paragraph.length() > 0) { lead_paragraph = HTMLEntitiesCoder.decode(lead_paragraph); Topic leadParagraphTypeTopic = getLeadParagraphTypeTopic(tm); Topic langTopic = getLangTopic(tm); articleTopic.setData(leadParagraphTypeTopic, langTopic, lead_paragraph); } } if (result.has("pub_date") && !result.isNull("pub_date")) { String date = result.getString("pub_date"); if (date != null && date.length() > 0) { Topic dateTypeTopic = getDateTypeTopic(tm); Topic langTopic = getLangTopic(tm); articleTopic.setData(dateTypeTopic, langTopic, date); } } if (result.has("headline") && !result.isNull("headline")) { JSONObject headline = result.getJSONObject("headline"); if(headline.has("main")){ String title = headline.getString("main"); if (title != null && title.length() > 0) { title = HTMLEntitiesCoder.decode(title); articleTopic.setDisplayName(defaultLang, title); articleTopic.setBaseName(title + " (NYT article)"); } } } if (result.has("keywords") && !result.isNull("keywords")) { JSONArray keywords = result.getJSONArray("keywords"); for (int i = 0; i < keywords.length(); i++) { try { JSONObject keyword = keywords.getJSONObject(i); String name = keyword.getString("name"); name = HTMLEntitiesCoder.decode(name); String value = keyword.getString("value"); value = HTMLEntitiesCoder.decode(value); parseKeyword(name, value, articleTopic, tm); } catch (JSONException | TopicMapException e) { log(e); } } } if (result.has("dbpedia_resource_url") && !result.isNull("dbpedia_resource_url")) { JSONArray resources = result.getJSONArray("dbpedia_resource_url"); for (int i = 0; i < resources.length(); i++) { String res = resources.getString(i); if (res == null) continue; res = res.trim(); if( res.length() == 0) continue; Topic resourceTopic = getDBpediaResourceTopic(res, tm); Topic articleTypeTopic = getArticleTypeTopic(tm); Topic resourceTypeTopic = getDBpediaResourceTypeTopic(tm); if (resourceTopic != null && resourceTypeTopic != null && articleTypeTopic != null) { Association a = tm.createAssociation(resourceTypeTopic); a.addPlayer(resourceTopic, resourceTypeTopic); a.addPlayer(articleTopic, articleTypeTopic); } } } if (result.has("byline") && !result.isNull("byline")) { try { JSONObject byline = result.getJSONObject("byline"); if (byline.has("original")){ String bylineString = byline.getString("original"); if (bylineString != null && bylineString.length() > 0) { bylineString = HTMLEntitiesCoder.decode(bylineString); Topic bylineTopic = getBylineTopic(bylineString, tm); Topic bylineTypeTopic = getBylineTypeTopic(tm); Topic articleTypeTopic = getArticleTypeTopic(tm); Association a = tm.createAssociation(bylineTypeTopic); a.addPlayer(bylineTopic, bylineTypeTopic); a.addPlayer(articleTopic, articleTypeTopic); } } } catch (JSONException e) { // The API might represent an empty byline as an empty array..? } } } private void parseKeyword(String name, String value, Topic articleTopic, TopicMap tm) throws TopicMapException { Topic keywordTypeTopic = getKeywordNameTopic(name, tm); Topic keywordTopic = getKeywordTopic(value, tm); Topic articleTypeTopic = getArticleTypeTopic(tm); Association a = tm.createAssociation(keywordTypeTopic); a.addPlayer(keywordTopic, keywordTypeTopic); a.addPlayer(articleTopic, articleTypeTopic); } }
14,484
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
NYTEventSearchExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/nyt/NYTEventSearchExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.nyt; import java.io.File; import java.net.URL; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; 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.HTMLEntitiesCoder; import org.wandora.utils.IObox; import org.wandora.utils.XMLbox; /** * * @author Eero */ public class NYTEventSearchExtractor extends AbstractNYTExtractor { private static final long serialVersionUID = 1L; private static String defaultLang = "en"; private static String currentURL = null; @Override public String getName() { return "New York Times Event Search API extractor"; } @Override public String getDescription() { return "Extractor performs an event search using The New York Times API and " + "transforms results to topics and associations."; } // ------------------------------------------------------------------------- @Override public boolean _extractTopicsFrom(File f, TopicMap tm) throws Exception { currentURL = null; String in = IObox.loadFile(f); JSONObject json = new JSONObject(in); parse(json, tm); return true; } @Override public boolean _extractTopicsFrom(URL u, TopicMap tm) throws Exception { try { currentURL = u.toExternalForm(); log("Event search extraction with " + currentURL); String in = IObox.doUrl(u); System.out.println("New York Times API returned-------------------------\n" + in + "\n----------------------------------------------------"); JSONObject json = new JSONObject(in); if (json.get("num_results").toString().equals("0")){ log("No results returned."); } else { parse(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); parse(json, tm); return true; } public void parse(JSONObject json, TopicMap tm) throws TopicMapException { if (json.has("results")) { try { JSONArray resultsArray = json.getJSONArray("results"); for (int i = 0; i < resultsArray.length(); i++) { JSONObject result = resultsArray.getJSONObject(i); parseResult(result, tm); } } catch (JSONException ex) { log(ex); System.out.println(ex); } } } public void parseResult(JSONObject result, TopicMap tm) throws JSONException, TopicMapException { if (result.has("event_detail_url")) { String url = result.getString("event_detail_url"); Topic eventTopic = tm.createTopic(); eventTopic.addSubjectIdentifier(new Locator(url)); eventTopic.addType(getEventTypeTopic(tm)); if (result.has("event_name")) { String title = result.getString("event_name"); if (title != null && title.length() > 0) { eventTopic.setDisplayName(defaultLang, title); eventTopic.setBaseName(title + " (NYT event)"); } } if (result.has("web_description")) { String description = result.getString("web_description"); if (description != null && description.length() > 0) { description = HTMLEntitiesCoder.decode(XMLbox.naiveGetAsText(description).trim()); Topic descriptionTypeTopic = getDescriptionTypeTopic(tm); Topic langTopic = getLangTopic(tm); eventTopic.setData(descriptionTypeTopic, langTopic, description); } } if (result.has("geocode_latitude")) { String latitude = result.getString("geocode_latitude"); if (latitude != null && latitude.length() > 0) { Topic latitudeTypeTopic = getLatitudeTypeTopic(tm); Topic langTopic = getLangTopic(tm); eventTopic.setData(latitudeTypeTopic, langTopic, latitude); } } if (result.has("geocode_longitude")) { String longitude = result.getString("geocode_longitude"); if (longitude != null && longitude.length() > 0) { Topic longitudeTypeTopic = getLongitudeTypeTopic(tm); Topic langTopic = getLangTopic(tm); eventTopic.setData(longitudeTypeTopic, langTopic, longitude); } } if (result.has("venue_name")) { String venue = result.getString("venue_name"); if (venue != null) { venue = venue.trim(); if (venue.length() > 0) { Topic venueTopic = getVenueTopic(venue, tm); Topic eventTypeTopic = getEventTypeTopic(tm); Topic venueTypeTopic = getVenueTypeTopic(tm); if (venueTopic != null && eventTypeTopic != null && venueTypeTopic != null) { Association a = tm.createAssociation(venueTypeTopic); a.addPlayer(venueTopic, venueTypeTopic); a.addPlayer(eventTopic, eventTypeTopic); } } } } if (result.has("category")) { String category = result.getString("category"); if (category != null) { category = category.trim(); if (category.length() > 0) { Topic categoryTopic = getCategoryTopic(category, tm); Topic eventTypeTopic = getEventTypeTopic(tm); Topic categoryTypeTopic = getCategoryTypeTopic(tm); if (categoryTopic != null && eventTypeTopic != null && categoryTypeTopic != null) { Association a = tm.createAssociation(categoryTypeTopic); a.addPlayer(categoryTopic, categoryTypeTopic); a.addPlayer(eventTopic, eventTypeTopic); } } } } if (result.has("event_date_list")){ String dates = ""; JSONArray resultJSONArray = result.getJSONArray("event_date_list"); Locale locale = new Locale("ENGLISH"); SimpleDateFormat input = new SimpleDateFormat("yyyy-MM-dd",locale); SimpleDateFormat output = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss '-0500'",locale); for( int i = 0; i < resultJSONArray.length(); i++ ){ if(i != 0) { dates += ","; } String dateString = resultJSONArray.getString(i); try{ Date date = input.parse(dateString); dateString = output.format(date); } catch (Exception e){ } dates += dateString; } if (!dates.isEmpty()){ Topic dateTypeTopic = getEventDateTypeTopic(tm); Topic langTopic = getLangTopic(tm); eventTopic.setData(dateTypeTopic, langTopic, dates); } } else if (result.has("recurring_start_date")) { Locale locale = new Locale("ENGLISH"); SimpleDateFormat input = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",locale); SimpleDateFormat output = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss '-0500'",locale); String startDateString = result.getString("recurring_start_date"); try{ Date startDate = input.parse(startDateString); startDateString = output.format(startDate); } catch (Exception e){ System.out.println("dateparseerror"); } if(startDateString != null && startDateString.length() > 0) { Topic dateStartTypeTopic = getStartDateTypeTopic(tm); Topic langTopic = getLangTopic(tm); eventTopic.setData(dateStartTypeTopic, langTopic, startDateString); } if (result.has("recur_days")){ JSONArray recurDays = result.getJSONArray("recur_days"); for (int i = 0; i < recurDays.length(); i++) { String abbr = recurDays.getString(i); Topic recurDayTopic = getRecurringDayTopic(tm, abbr); Topic eventTypeTopic = getEventTypeTopic(tm); Topic recurDayTypeTopic = getRecurringDayTypeTopic(tm); Topic dayTypeTopic = getDayOfWeekTypeTopic(tm); if (recurDayTopic != null && eventTypeTopic != null && recurDayTypeTopic != null) { Association a = tm.createAssociation(recurDayTypeTopic); a.addPlayer(recurDayTopic, dayTypeTopic); a.addPlayer(eventTopic, eventTypeTopic); } } } if (result.has("recurring_end_date")) { String endDateString = result.getString("recurring_end_date"); try { Date endDate = input.parse(endDateString); endDateString = output.format(endDate); } catch (Exception e){ System.out.println("dateparseerror"); } if(endDateString != null && endDateString.length() > 0) { Topic dateEndTypeTopic = getEndDateTypeTopic(tm); Topic langTopic = getLangTopic(tm); eventTopic.setData(dateEndTypeTopic, langTopic, endDateString); } } } } } }
11,454
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MillionFirstStepsBookTSVExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/britishlibrary/MillionFirstStepsBookTSVExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.britishlibrary; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.Arrays; import java.util.HashMap; import org.wandora.topicmap.Association; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.memory.TopicMapImpl; /** * * @author akivela */ public class MillionFirstStepsBookTSVExtractor extends AbstractMillionFirstStepsExtractor { private static final long serialVersionUID = 1L; @Override public String getName() { return "BL's million first steps book TSV extractor"; } @Override public String getDescription(){ return "Extracts topic map from the British Library's a million first steps book TSV https://github.com/BL-Labs/imagedirectory"; } // ------------------------------------------------------------------------- @Override public boolean _extractTopicsFrom(File f, TopicMap tm) throws Exception { if(f != null) { if(f.isDirectory()) { _extractTopicsFrom(f.listFiles()); } else { log("Reading file "+f.getName()); try { BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(f), defaultEncoding)); StringBuilder stringBuilder = new StringBuilder(""); String str; while ((str = in.readLine()) != null) { stringBuilder.append(str); stringBuilder.append("\n"); } in.close(); parse(stringBuilder.toString(), tm); } catch(Exception e) { log(e); } } } return true; } public void _extractTopicsFrom(File[] f) throws Exception { Arrays.sort(f); int i=0; File file = null; String year = null; String filename = null; String nextYear = null; while(i<f.length && !forceStop()) { file = f[i]; filename = file.getName(); if(filename.endsWith(".tsv") && !file.isDirectory()) { year = filename.substring(0, 4); TopicMap tm = new TopicMapImpl(); do { _extractTopicsFrom(file, tm); i++; file = f[i]; nextYear = file.getName().substring(0, 3); } while(year.equalsIgnoreCase(nextYear) && !forceStop()); File parent = file.getParentFile(); File exportFolder = new File( parent.getAbsolutePath()+"/"+"xtm" ); if(!exportFolder.exists()) exportFolder.mkdir(); String tmFilename = exportFolder.getAbsolutePath()+"/"+year+".xtm"; log("Exporting topic map to "+tmFilename); tm.exportXTM(tmFilename); } else { i++; } } } @Override public void handleFiles(File[] files, TopicMap tm) { if(files == null || files.length == 0) return; for(int i=0; i<files.length && !forceStop(); i++) { if(files[i] != null) { try { extractTopicsFrom(files[i], tm); } catch(Exception e) { log(e); log("Extraction from '" + croppedFilename(files[i].getName()) + "' failed."); } } } } @Override public boolean _extractTopicsFrom(URL u, TopicMap tm) throws Exception { try { log("Reading URL "+u.toExternalForm()); String in = doUrl(u); parse(in, tm); } catch (Exception e){ log(e); } return true; } @Override public boolean _extractTopicsFrom(String str, TopicMap tm) throws Exception { log("Processing string."); parse(str, tm); return true; } // ------------------------------------------------------------------------- public void parse(String str, TopicMap tm) { if(str != null && str.length() > 0) { HashMap<String,Integer> columnIndexes = new HashMap(); String[] lines = str.split("\n"); if(lines.length > 1) { log("Parsing data."); setProgressMax(lines.length); parseColumnNames(lines[0], columnIndexes); for(int i=1; i<lines.length && !forceStop(); i++) { parseLine(lines[i], columnIndexes, tm); setProgress(i); } } else { log("Data should contain more than one line. First line contains column labels."); } } else { log("No data for parser."); } } public void parseColumnNames(String columns, HashMap<String,Integer> columnIndexes) { String[] columnNames = columns.split("\t"); for(int i=0; i<columnNames.length; i++) { columnIndexes.put(columnNames[i], i); } } public void parseLine(String str, HashMap<String,Integer> columnIndexes, TopicMap tm) { if(str != null && str.length()>0) { String[] tokens = str.split("\t"); if(tokens.length > 4) { String flickr_id = getIndex("flickr_id", tokens, columnIndexes); String flickr_url = getIndex("flickr_url", tokens, columnIndexes); String book_identifier = getIndex("book_identifier", tokens, columnIndexes); String title = getIndex("title", tokens, columnIndexes); String first_author = getIndex("first_author", tokens, columnIndexes); String pubplace = getIndex("pubplace", tokens, columnIndexes); String publisher = getIndex("publisher", tokens, columnIndexes); String date = getIndex("date", tokens, columnIndexes); String volume = getIndex("volume", tokens, columnIndexes); String page = getIndex("page", tokens, columnIndexes); String image_idx = getIndex("image_idx", tokens, columnIndexes); String ARK_id_of_book = getIndex("ARK_id_of_book", tokens, columnIndexes); String BL_DLS_ID = getIndex("BL_DLS_ID", tokens, columnIndexes); String flickr_original_source = getIndex("flickr_original_source", tokens, columnIndexes); String flickr_original_height = getIndex("flickr_original_height", tokens, columnIndexes); String flickr_original_width = getIndex("flickr_original_width", tokens, columnIndexes); String flickr_large_source = getIndex("flickr_large_source", tokens, columnIndexes); String flickr_large_height = getIndex("flickr_large_height", tokens, columnIndexes); String flickr_large_width = getIndex("flickr_large_width", tokens, columnIndexes); String flickr_medium_source = getIndex("flickr_medium_source", tokens, columnIndexes); String flickr_medium_height = getIndex("flickr_medium_height", tokens, columnIndexes); String flickr_medium_width = getIndex("flickr_medium_width", tokens, columnIndexes); String flickr_small_source = getIndex("flickr_small_source", tokens, columnIndexes); String flickr_small_height = getIndex("flickr_small_height", tokens, columnIndexes); String flickr_small_width = getIndex("flickr_small_width", tokens, columnIndexes); if(isValid(book_identifier)) { try { Topic bookTopic = getBookTopic(book_identifier, tm); if(isValid(title)) { bookTopic.setBaseName(title+" ("+book_identifier+")"); bookTopic.setDisplayName(defaultLang, title); } if(isValid(ARK_id_of_book)) { Topic typeTopic = getArkIdTypeTopic(tm); Topic langTopic = getLangTopic(tm); bookTopic.setData(typeTopic, langTopic, ARK_id_of_book); } if(isValid(BL_DLS_ID)) { Topic typeTopic = getBLDLSIdTypeTopic(tm); Topic langTopic = getLangTopic(tm); bookTopic.setData(typeTopic, langTopic, BL_DLS_ID); Topic pdfTypeTopic = getPDFTypeTopic(tm); bookTopic.setData(pdfTypeTopic, langTopic, "http://access.bl.uk/item/pdf/"+BL_DLS_ID); } if(isValid(first_author)) { Topic topic = getAuthorTopic(first_author, tm); Topic typeTopic = getAuthorTypeTopic(tm); Association a = tm.createAssociation(typeTopic); a.addPlayer(topic, typeTopic); a.addPlayer(bookTopic, getBookTypeTopic(tm)); } if(isValid(flickr_id) && isValid(flickr_original_source)) { Topic imageTopic = getImageTopic(flickr_id, flickr_original_source, tm); Topic typeTopic = getImageTypeTopic(tm); Association a = tm.createAssociation(typeTopic); a.addPlayer(imageTopic, typeTopic); a.addPlayer(bookTopic, getBookTypeTopic(tm)); if(imageTopic != null) { if(isValid(image_idx)) { Topic imageIdxTypeTopic = getImageIdxTypeTopic(tm); Topic langTopic = getLangTopic(tm); imageTopic.setData(imageIdxTypeTopic, langTopic, image_idx); } if(isValid(volume)) { Topic volumeTypeTopic = getVolumeTypeTopic(tm); Topic langTopic = getLangTopic(tm); imageTopic.setData(volumeTypeTopic, langTopic, volume); } if(isValid(page)) { Topic pageTypeTopic = getPageTypeTopic(tm); Topic langTopic = getLangTopic(tm); imageTopic.setData(pageTypeTopic, langTopic, page); } } } if(isValid(first_author)) { Topic authorTopic = getAuthorTopic(first_author, tm); Topic typeTopic = getAuthorTypeTopic(tm); Association a = tm.createAssociation(typeTopic); a.addPlayer(authorTopic, typeTopic); a.addPlayer(bookTopic, getBookTypeTopic(tm)); } if(isValid(publisher)) { Topic publisherTopic = getPublisherTopic(publisher, tm); Topic typeTopic = getPublisherTypeTopic(tm); Association a = tm.createAssociation(typeTopic); a.addPlayer(publisherTopic, typeTopic); a.addPlayer(bookTopic, getBookTypeTopic(tm)); } if(isValid(pubplace)) { Topic pubplaceTopic = getPlaceTopic(pubplace, tm); Topic typeTopic = getPlaceTypeTopic(tm); Association a = tm.createAssociation(typeTopic); a.addPlayer(pubplaceTopic, typeTopic); a.addPlayer(bookTopic, getBookTypeTopic(tm)); } if(isValid(date)) { Topic dateTopic = getDateTopic(date, tm); Topic typeTopic = getDateTypeTopic(tm); Association a = tm.createAssociation(typeTopic); a.addPlayer(dateTopic, typeTopic); a.addPlayer(bookTopic, getBookTypeTopic(tm)); } } catch(Exception e) { log(e); } } } } } private boolean isValid(String data) { if(data != null && data.length() > 0) { return true; } return false; } private String getIndex(String indexName, String[] array, HashMap<String,Integer> columnIndexes) { if(array != null && indexName != null && columnIndexes != null) { try { return array[columnIndexes.get(indexName)]; } catch(Exception e) {} } return null; } }
14,530
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AbstractMillionFirstStepsExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/britishlibrary/AbstractMillionFirstStepsExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.britishlibrary; 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 javax.swing.Icon; import org.wandora.application.Wandora; 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; /** * * @author akivela */ public abstract class AbstractMillionFirstStepsExtractor extends AbstractExtractor { private static final long serialVersionUID = 1L; protected static String defaultEncoding = "UTF-8"; protected static String defaultLang = "en"; public static final String LANG_SI = "http://www.topicmaps.org/xtm/1.0/language.xtm#"+defaultLang; public static final String BRITISH_LIBRARY_SI = "http://www.bl.uk/"; public static final String BASE_SI = "http://wandora.org/si/british-libary/"; public static final String BOOK_SI = BASE_SI + "book"; public static final String AUTHOR_SI = BASE_SI + "author"; public static final String CORPORATE_SI = BASE_SI + "corporate"; public static final String TITLE_SI = BASE_SI + "title"; public static final String PLACE_SI = BASE_SI + "publishing-place"; public static final String DATE_SI = BASE_SI + "date"; public static final String DATEFIELD_SI = BASE_SI + "date-field"; public static final String PUBLISHER_SI = BASE_SI + "publisher"; public static final String EDITION_SI = BASE_SI + "edition"; public static final String ISSUANCE_SI = BASE_SI + "issuance"; public static final String SHELFMARK_SI = BASE_SI + "shelfmark"; public static final String IMAGE_SI = BASE_SI + "image"; public static final String IMAGEIDX_SI = BASE_SI + "image-idx"; public static final String ROLE_SI = BASE_SI + "role"; public static final String ORDER_SI = BASE_SI + "order"; public static final String ARKID_SI = BASE_SI + "ARK_id_of_book"; public static final String BL_DLS_SI = BASE_SI + "BL_DLS_ID"; public static final String PAGE_SI = BASE_SI + "page"; public static final String VOLUME_SI = BASE_SI + "volume"; public static final String PDF_SI = BASE_SI + "pdf"; protected static Topic getLangTopic(TopicMap tm) throws TopicMapException { Topic lang = getOrCreateTopic(tm, LANG_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 getBritishLibraryTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, BRITISH_LIBRARY_SI, "British Library"); Topic wandoraClass = getWandoraClassTopic(tm); makeSubclassOf(tm, type, wandoraClass); return type; } // ------------------------------------------------------------------------- public static Topic getATopic(String str, String si, String type, TopicMap tm) throws TopicMapException { Topic resTopic=null; if(str.startsWith("http://")) { resTopic = getOrCreateTopic(tm, str, null); } else { resTopic = getOrCreateTopic(tm, si+"/"+urlEncode(str), str); } Topic typeTopic = getATypeTopic(si, type, tm); if(!resTopic.isOfType(typeTopic)) resTopic.addType(typeTopic); return resTopic; } public static Topic getATypeTopic(String si, String type, TopicMap tm) throws TopicMapException { Topic typeTopic=getOrCreateTopic(tm, si, type); Topic blTopic = getBritishLibraryTypeTopic(tm); makeSubclassOf(tm, typeTopic, blTopic); return typeTopic; } // ------------------------------------------------------------------------- public static Topic getBookTopic(String book, TopicMap tm) throws TopicMapException { Topic resTopic=getOrCreateTopic(tm, BOOK_SI+"/"+urlEncode(book), book); resTopic.addType(getBookTypeTopic(tm)); return resTopic; } public static Topic getBookTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, BOOK_SI, "Book (British Library)"); Topic blTopic = getBritishLibraryTypeTopic(tm); makeSubclassOf(tm, type, blTopic); return type; } // ------------------------------------------------------------------------- public static Topic getArkIdTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, ARKID_SI, "Ark id of book (British Library)"); Topic blTopic = getBritishLibraryTypeTopic(tm); makeSubclassOf(tm, type, blTopic); return type; } public static Topic getBLDLSIdTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, BL_DLS_SI, "Digital Library Service identifier (British Library)"); Topic blTopic = getBritishLibraryTypeTopic(tm); makeSubclassOf(tm, type, blTopic); return type; } public static Topic getPDFTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, PDF_SI, "PDF (British Library)"); Topic blTopic = getBritishLibraryTypeTopic(tm); makeSubclassOf(tm, type, blTopic); return type; } public static Topic getImageIdxTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, IMAGEIDX_SI, "Image idx (British Library)"); Topic blTopic = getBritishLibraryTypeTopic(tm); makeSubclassOf(tm, type, blTopic); return type; } // ------------------------------------------------------------------------- public static Topic getAuthorTopic(String author, TopicMap tm) throws TopicMapException { Topic resTopic=getOrCreateTopic(tm, AUTHOR_SI+"/"+urlEncode(author), author); resTopic.addType(getAuthorTypeTopic(tm)); return resTopic; } public static Topic getAuthorTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, AUTHOR_SI, "Author (British Library)"); Topic blTopic = getBritishLibraryTypeTopic(tm); makeSubclassOf(tm, type, blTopic); return type; } // ------------------------------------------------------------------------- public static Topic getCorporateTopic(String str, TopicMap tm) throws TopicMapException { Topic resTopic=getOrCreateTopic(tm, CORPORATE_SI+"/"+urlEncode(str), str); resTopic.addType(getCorporateTypeTopic(tm)); return resTopic; } public static Topic getCorporateTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, CORPORATE_SI, "Corporate (British Library)"); Topic blTopic = getBritishLibraryTypeTopic(tm); makeSubclassOf(tm, type, blTopic); return type; } // ------------------------------------------------------------------------- public static Topic getTitleTopic(String str, TopicMap tm) throws TopicMapException { Topic resTopic=getOrCreateTopic(tm, TITLE_SI+"/"+urlEncode(str), str); resTopic.addType(getTitleTypeTopic(tm)); return resTopic; } public static Topic getTitleTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, TITLE_SI, "Title (British Library)"); Topic blTopic = getBritishLibraryTypeTopic(tm); makeSubclassOf(tm, type, blTopic); return type; } // ------------------------------------------------------------------------- public static Topic getPageTopic(String str, TopicMap tm) throws TopicMapException { Topic resTopic=getOrCreateTopic(tm, PAGE_SI+"/"+urlEncode(str), str); resTopic.addType(getTitleTypeTopic(tm)); return resTopic; } public static Topic getPageTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, PAGE_SI, "Page (British Library)"); Topic blTopic = getBritishLibraryTypeTopic(tm); makeSubclassOf(tm, type, blTopic); return type; } // ------------------------------------------------------------------------- public static Topic getVolumeTopic(String str, TopicMap tm) throws TopicMapException { Topic resTopic=getOrCreateTopic(tm, VOLUME_SI+"/"+urlEncode(str), str); resTopic.addType(getTitleTypeTopic(tm)); return resTopic; } public static Topic getVolumeTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, VOLUME_SI, "Volume (British Library)"); Topic blTopic = getBritishLibraryTypeTopic(tm); makeSubclassOf(tm, type, blTopic); return type; } // ------------------------------------------------------------------------- public static Topic getPlaceTopic(String str, TopicMap tm) throws TopicMapException { Topic resTopic=getOrCreateTopic(tm, PLACE_SI+"/"+urlEncode(str), str); resTopic.addType(getPlaceTypeTopic(tm)); return resTopic; } public static Topic getPlaceTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, PLACE_SI, "Place of publishing (British Library)"); Topic blTopic = getBritishLibraryTypeTopic(tm); makeSubclassOf(tm, type, blTopic); return type; } // ------------------------------------------------------------------------- public static Topic getDatefieldTopic(String str, TopicMap tm) throws TopicMapException { Topic resTopic=getOrCreateTopic(tm, DATEFIELD_SI+"/"+urlEncode(str), str); resTopic.addType(getDatefieldTypeTopic(tm)); return resTopic; } public static Topic getDatefieldTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, DATEFIELD_SI, "Datefield (British Library)"); Topic blTopic = getBritishLibraryTypeTopic(tm); makeSubclassOf(tm, type, blTopic); return type; } // ------------------------------------------------------------------------- public static Topic getDateTopic(String str, TopicMap tm) throws TopicMapException { Topic resTopic=getOrCreateTopic(tm, DATE_SI+"/"+urlEncode(str), str); resTopic.addType(getDateTypeTopic(tm)); return resTopic; } public static Topic getDateTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, DATE_SI, "Date (British Library)"); Topic blTopic = getBritishLibraryTypeTopic(tm); makeSubclassOf(tm, type, blTopic); return type; } // ------------------------------------------------------------------------- public static Topic getPublisherTopic(String str, TopicMap tm) throws TopicMapException { Topic resTopic=getOrCreateTopic(tm, PUBLISHER_SI+"/"+urlEncode(str), str); resTopic.addType(getPublisherTypeTopic(tm)); return resTopic; } public static Topic getPublisherTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, PUBLISHER_SI, "Publisher (British Library)"); Topic blTopic = getBritishLibraryTypeTopic(tm); makeSubclassOf(tm, type, blTopic); return type; } // ------------------------------------------------------------------------- public static Topic getEditionTopic(String str, TopicMap tm) throws TopicMapException { Topic resTopic=getOrCreateTopic(tm, EDITION_SI+"/"+urlEncode(str), str); resTopic.addType(getEditionTypeTopic(tm)); return resTopic; } public static Topic getEditionTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, EDITION_SI, "Edition (British Library)"); Topic blTopic = getBritishLibraryTypeTopic(tm); makeSubclassOf(tm, type, blTopic); return type; } // ------------------------------------------------------------------------- public static Topic getIssuanceTopic(String str, TopicMap tm) throws TopicMapException { Topic resTopic=getOrCreateTopic(tm, ISSUANCE_SI+"/"+urlEncode(str), str); resTopic.addType(getIssuanceTypeTopic(tm)); return resTopic; } public static Topic getIssuanceTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, ISSUANCE_SI, "Issuance (British Library)"); Topic blTopic = getBritishLibraryTypeTopic(tm); makeSubclassOf(tm, type, blTopic); return type; } // ------------------------------------------------------------------------- public static Topic getShelfmarkTopic(String str, TopicMap tm) throws TopicMapException { Topic resTopic=getOrCreateTopic(tm, SHELFMARK_SI+"/"+urlEncode(str), str); resTopic.addType(getShelfmarkTypeTopic(tm)); return resTopic; } public static Topic getShelfmarkTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, SHELFMARK_SI, "Shelfmark (British Library)"); Topic blTopic = getBritishLibraryTypeTopic(tm); makeSubclassOf(tm, type, blTopic); return type; } // ------------------------------------------------------------------------- public static Topic getImageTopic(String str, String sl, TopicMap tm) throws TopicMapException { Topic resTopic=getOrCreateTopic(tm, sl, str); resTopic.setSubjectLocator(new Locator(sl)); resTopic.addType(getImageTypeTopic(tm)); return resTopic; } public static Topic getImageTopic(String str, TopicMap tm) throws TopicMapException { Topic resTopic=getOrCreateTopic(tm, str); resTopic.setSubjectLocator(new Locator(str)); resTopic.addType(getImageTypeTopic(tm)); return resTopic; } public static Topic getImageTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, IMAGE_SI, "Image (British Library)"); Topic blTopic = getBritishLibraryTypeTopic(tm); makeSubclassOf(tm, type, blTopic); return type; } // ------------------------------------------------------------------------- public static Topic getOrderTopic(String str, TopicMap tm) throws TopicMapException { Topic resTopic=getOrCreateTopic(tm, ORDER_SI+"/"+urlEncode(str), str); resTopic.addType(getOrderTypeTopic(tm)); return resTopic; } public static Topic getOrderTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, ORDER_SI, "Order (British Library)"); Topic blTopic = getBritishLibraryTypeTopic(tm); makeSubclassOf(tm, type, blTopic); return type; } // ------------------------------------------------------------------------- public static Topic getRoleTopic(String str, TopicMap tm) throws TopicMapException { Topic resTopic=getOrCreateTopic(tm, ROLE_SI+"/"+urlEncode(str), str); resTopic.addType(getRoleTypeTopic(tm)); return resTopic; } public static Topic getRoleTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, ROLE_SI, "Role (British Library)"); Topic blTopic = getBritishLibraryTypeTopic(tm); makeSubclassOf(tm, type, blTopic); return type; } // ------------------------------------------------------------------------- @Override public String getName() { return "Abstract Million First Steps extractor"; } @Override public String getDescription(){ return "Extracts topic map from the British Library's a million first steps metadata https://github.com/BL-Labs/imagedirectory"; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_britishlibrary.png"); } @Override public boolean runInOwnThread() { return true; } @Override public boolean useTempTopicMap() { return false; } @Override public boolean useURLCrawler() { return false; } // ------------------------------------------------------------------------- protected 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) { log(ex); } } return sb.toString(); } }
19,124
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MillionFirstStepsBookMetadataJSONExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/britishlibrary/MillionFirstStepsBookMetadataJSONExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.britishlibrary; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.nio.charset.Charset; import java.util.Iterator; import org.json.JSONArray; import org.json.JSONObject; import org.wandora.application.Wandora; import org.wandora.topicmap.Association; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.utils.IObox; /** * * @author akivela */ public class MillionFirstStepsBookMetadataJSONExtractor extends AbstractMillionFirstStepsExtractor { private static final long serialVersionUID = 1L; @Override public String getName() { return "BL's million first steps book JSON extractor"; } @Override public String getDescription(){ return "Extracts topic map from the British Library's a million first steps book metadata https://github.com/BL-Labs/imagedirectory"; } // ------------------------------------------------------------------------- @Override public boolean _extractTopicsFrom(File f, TopicMap tm) throws Exception { String in = IObox.loadFile(f); JSONObject json = new JSONObject(in); parse(json, tm); return true; } @Override public boolean _extractTopicsFrom(URL u, TopicMap tm) throws Exception { try { String in = doUrl(u); JSONObject json = new JSONObject(in); parse(json, tm); } catch (Exception e){ e.printStackTrace(); } return true; } @Override public boolean _extractTopicsFrom(String str, TopicMap tm) throws Exception { JSONObject json = new JSONObject(str); parse(json, tm); return true; } public 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) { log(ex); } } return sb.toString(); } // ------------------------------- PARSING --------------------------------- public void parse(JSONObject json, TopicMap tm) throws TopicMapException { Iterator keys = json.keys(); int i=0; while(keys.hasNext() && !forceStop()) { try { String key = (String) keys.next(); JSONObject bookData = json.getJSONObject(key); parseBookData(key, bookData, tm); hlog("Parsing "+key+" ("+i+")"); setProgress(++i); } catch(Exception ex) { log(ex); } } } public void parseBookData(String key, JSONObject bookData, TopicMap tm) { if(key != null && bookData != null && tm != null) { if(bookData.has("identifier")) { try { String identifier = bookData.getString("identifier"); Topic bookTopic = getBookTopic(identifier, tm); if(bookData.has("title")) { parseN(bookTopic, bookData.get("title"), identifier, tm); parseO(bookTopic, bookData.get("title"), TITLE_SI, "Title (British Library)", tm); } if(bookData.has("authors")) { parseA(bookTopic, bookData.get("authors"), AUTHOR_SI, "Author (British Library)", tm); } if(bookData.has("corporate")) { parseA(bookTopic, bookData.get("corporate"), CORPORATE_SI, "Corporate (British Library)", tm); } if(bookData.has("place")) { parseA(bookTopic, bookData.get("place"), PLACE_SI, "Place (British Library)", tm); } if(bookData.has("datefield")) { parseO(bookTopic, bookData.get("datefield"), DATEFIELD_SI, "Datefield (British Library)", tm); } if(bookData.has("date")) { String date = bookData.getString("date"); if(date != null && date.length() > 0) { Topic dateTopic = getDateTopic(date, tm); Topic dateTypeTopic = getDateTypeTopic(tm); Association a = tm.createAssociation(dateTypeTopic); a.addPlayer(dateTopic, dateTypeTopic); a.addPlayer(bookTopic, getBookTypeTopic(tm)); } } if(bookData.has("issuance")) { String issuance = bookData.getString("issuance"); if(issuance != null && issuance.length() > 0) { Topic issuanceTopic = getIssuanceTopic(issuance, tm); Topic issuanceTypeTopic = getIssuanceTypeTopic(tm); Association a = tm.createAssociation(issuanceTypeTopic); a.addPlayer(issuanceTopic, issuanceTypeTopic); a.addPlayer(bookTopic, getBookTypeTopic(tm)); } } if(bookData.has("publisher")) { parseA(bookTopic, bookData.get("publisher"), PUBLISHER_SI, "Publisher (British Library)", tm); } if(bookData.has("edition")) { String edition = bookData.getString("edition"); if(edition != null && edition.length() > 0) { Topic editionTopic = getEditionTopic(edition, tm); Topic editionTypeTopic = getEditionTypeTopic(tm); Association a = tm.createAssociation(editionTypeTopic); a.addPlayer(editionTopic, editionTypeTopic); a.addPlayer(bookTopic, getBookTypeTopic(tm)); } } if(bookData.has("shelfmarks")) { parseO(bookTopic, bookData.get("shelfmarks"), SHELFMARK_SI, "Shelfmark (British Library)", tm); } if(bookData.has("flickr_url_to_book_images")) { parseA(bookTopic, bookData.get("flickr_url_to_book_images"), IMAGE_SI, "Image (British Library)", tm); } } catch(Exception e) { log(e); } } } } public Association parseA(Topic bookTopic, Object data, String typesi, String type, TopicMap tm) { if(data != null) { if(data instanceof String) { String dataString = (String) data; if(dataString.length() > 0) { try { Topic topic = getATopic(dataString, typesi, type, tm); Topic typeTopic = getATypeTopic(typesi, type, tm); Association a = tm.createAssociation(typeTopic); a.addPlayer(topic, typeTopic); a.addPlayer(bookTopic, getBookTypeTopic(tm)); return a; } catch(Exception e) { log(e); } } } else if(data instanceof JSONArray) { JSONArray dataArray = (JSONArray) data; for(int i=0; i<dataArray.length(); i++) { try { Association a = parseA(bookTopic, dataArray.get(i), typesi, type, tm); if(a != null && dataArray.length() > 1) { Topic orderTopic = getOrderTopic(""+i, tm); Topic orderType = getOrderTypeTopic(tm); a.addPlayer(orderTopic, orderType); } return a; } catch(Exception e) { log(e); } } } else if(data instanceof JSONObject) { JSONObject dataObject = (JSONObject) data; Iterator keys = dataObject.keys(); while( keys.hasNext() ) { try { String key = (String) keys.next(); Object innerData = dataObject.get(key); if(innerData != null) { Association a = parseA(bookTopic, innerData, typesi, type, tm); if(a != null) { a.addPlayer(getRoleTopic(key, tm), getRoleTypeTopic(tm)); } return a; } } catch(Exception e) { log(e); } } } } return null; } public void parseO(Topic bookTopic, Object data, String typesi, String type, TopicMap tm) { if(data != null) { if(data instanceof String) { String dataString = (String) data; if(dataString.length() > 0) { try { Topic typeTopic = getATypeTopic(typesi, type, tm); String oldOccurrence = bookTopic.getData(typeTopic, getLangTopic(tm)); if(oldOccurrence != null) { dataString = oldOccurrence+"\n\n"+dataString; } bookTopic.setData(typeTopic, getLangTopic(tm), dataString); } catch(Exception e) { log(e); } } } else if(data instanceof JSONArray) { JSONArray dataArray = (JSONArray) data; for(int i=0; i<dataArray.length(); i++) { try { parseO(bookTopic, dataArray.get(i), typesi, type, tm); } catch(Exception e) { log(e); } } } else if(data instanceof JSONObject) { JSONObject dataObject = (JSONObject) data; Iterator keys = dataObject.keys(); while( keys.hasNext() ) { try { String key = (String) keys.next(); Object innerData = dataObject.get(key); if(innerData != null) { parseO(bookTopic, innerData, typesi, type, tm); } } catch(Exception e) { log(e); } } } } } public void parseN(Topic bookTopic, Object data, String id, TopicMap tm) { if(data != null) { if(data instanceof String) { String dataString = (String) data; if(dataString.length() > 0) { try { bookTopic.setBaseName(dataString+" ("+id+")"); bookTopic.setDisplayName(defaultLang, dataString); } catch(Exception e) { log(e); } } } else if(data instanceof JSONArray) { JSONArray dataArray = (JSONArray) data; for(int i=0; i<dataArray.length(); i++) { try { parseN(bookTopic, dataArray.get(i), id, tm); } catch(Exception e) { log(e); } } } else if(data instanceof JSONObject) { JSONObject dataObject = (JSONObject) data; Iterator keys = dataObject.keys(); while( keys.hasNext() ) { try { String key = (String) keys.next(); Object innerData = dataObject.get(key); if(innerData != null) { parseN(bookTopic, innerData, id, tm); } } catch(Exception e) { log(e); } } } } } }
14,588
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
EuropeanaExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/europeana/EuropeanaExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.europeana; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; /** * * @author nlaitinen */ public class EuropeanaExtractor extends AbstractEuropeanaExtractor { private static final long serialVersionUID = 1L; private EuropeanaExtractorUI ui = null; @Override public void execute(Wandora wandora, Context context) { try { if(ui == null) { ui = new EuropeanaExtractorUI(); } 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 Europeana 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,804
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AbstractEuropeanaExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/europeana/AbstractEuropeanaExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.europeana; 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 nlaitinen */ public abstract class AbstractEuropeanaExtractor extends AbstractExtractor { private static final long serialVersionUID = 1L; @Override public String getName() { return "Abstract Europeana API extractor"; } @Override public String getDescription(){ return "Extracts data from The Europeana data API at http://pro.europeana.eu"; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_europeana.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 Europeana 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 Europeana 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 Europeana extractors. It doesn't perform extration it self."); } // --------------------------- SEARCH ---------------------------------------- public static final String LANG_SI = "http://www.topicmaps.org/xtm/1.0/language.xtm#en"; public static final String EUROPEANA_SI = "http://pro.europeana.eu"; public static final String ITEM_SI = "http://wandora.org/si/europeana/item"; public static final String PROVIDER_SI = "http://wandora.org/si/europeana/item/provider"; public static final String LANGUAGE_SI = "http://wandora.org/si/europeana/item/language"; public static final String YEAR_SI = "http://wandora.org/si/europeana/item/year"; public static final String RIGHTS_LINK_SI = "http://wandora.org/si/europeana/item/rightsLink"; public static final String TITLE_SI = "http://wandora.org/si/europeana/item/title"; public static final String DC_CREATOR_SI = "http://wandora.org/si/europeana/item/dcCreator"; public static final String COUNTRY_SI = "http://wandora.org/si/europeana/item/country"; public static final String COLLECTION_NAME_SI = "http://wandora.org/si/europeana/item/collectionName"; public static final String CONCEPT_LABEL_SI = "http://wandora.org/si/europeana/item/conceptLabel"; public static final String TYPE_SI = "http://wandora.org/si/europeana/item/type"; public static final String DATA_PROVIDER_SI = "http://wandora.org/si/europeana/item/dataProvider"; public static final String PLACE_LABEL_SI = "http://wandora.org/si/europeana/item/placeLabel"; public static final String PREVIEW_LINK_SI = "http://wandora.org/si/europeana/item/previewLink"; public static final String GUID_LINK_SI = "http://wandora.org/si/europeana/item/guidLink"; protected static Topic getLangTopic(TopicMap tm) throws TopicMapException { Topic lang = getOrCreateTopic(tm, LANG_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 getEuropeanaTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, EUROPEANA_SI, "Europeana API"); Topic wandoraClass = getWandoraClassTopic(tm); makeSubclassOf(tm, type, wandoraClass); return type; } public static Topic getItemTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, ITEM_SI, "item (Europeana API)"); Topic nytTopic = getEuropeanaTypeTopic(tm); makeSubclassOf(tm, type, nytTopic); return type; } public static Topic getProviderTopic(String provider, TopicMap tm) throws TopicMapException { Topic resTopic=getOrCreateTopic(tm, provider); resTopic.addType(getProviderTypeTopic(tm)); return resTopic; } public static Topic getProviderTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, PROVIDER_SI, "provider (Europeana API)"); Topic europeanaTopic = getEuropeanaTypeTopic(tm); makeSubclassOf(tm, type, europeanaTopic); return type; } public static Topic getLanguageTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, LANGUAGE_SI, "language (Europeana API)"); Topic europeanaTopic = getEuropeanaTypeTopic(tm); makeSubclassOf(tm, type, europeanaTopic); return type; } public static Topic getYearTopic(String year, TopicMap tm) throws TopicMapException { Topic resTopic=getOrCreateTopic(tm, year); resTopic.addType(getYearTypeTopic(tm)); return resTopic; } public static Topic getYearTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, YEAR_SI, "year (Europeana API)"); Topic europeanaTopic = getEuropeanaTypeTopic(tm); makeSubclassOf(tm, type, europeanaTopic); return type; } public static Topic getRightsLinkTopic(String rights, TopicMap tm) throws TopicMapException { Topic resTopic=getOrCreateTopic(tm, rights); resTopic.addType(getRightsLinkTypeTopic(tm)); return resTopic; } public static Topic getRightsLinkTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, RIGHTS_LINK_SI, "rights-link (Europeana API)"); Topic europeanaTopic = getEuropeanaTypeTopic(tm); makeSubclassOf(tm, type, europeanaTopic); return type; } public static Topic getTitleTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, TITLE_SI, "title (Europeana API)"); Topic europeanaTopic = getEuropeanaTypeTopic(tm); makeSubclassOf(tm, type, europeanaTopic); return type; } public static Topic getDcCreatorTopic(String dcCreator, TopicMap tm) throws TopicMapException { Topic resTopic=getOrCreateTopic(tm, dcCreator); resTopic.addType(getDcCreatorTypeTopic(tm)); return resTopic; } public static Topic getDcCreatorTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, DC_CREATOR_SI, "dcCreator (Europeana API)"); Topic europeanaTopic = getEuropeanaTypeTopic(tm); makeSubclassOf(tm, type, europeanaTopic); return type; } public static Topic getCountryTopic(String country, TopicMap tm) throws TopicMapException { Topic resTopic=getOrCreateTopic(tm, country); resTopic.addType(getCountryTypeTopic(tm)); return resTopic; } public static Topic getCountryTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, COUNTRY_SI, "country (Europeana API)"); Topic europeanaTopic = getEuropeanaTypeTopic(tm); makeSubclassOf(tm, type, europeanaTopic); return type; } public static Topic getCollectionNameTopic(String collectionName, TopicMap tm) throws TopicMapException { Topic resTopic=getOrCreateTopic(tm, collectionName); resTopic.addType(getCollectionNameTypeTopic(tm)); return resTopic; } public static Topic getCollectionNameTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, COLLECTION_NAME_SI, "collection-name (Europeana API)"); Topic europeanaTopic = getEuropeanaTypeTopic(tm); makeSubclassOf(tm, type, europeanaTopic); return type; } public static Topic getConceptLabelTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, CONCEPT_LABEL_SI, "concept-label (Europeana API)"); Topic europeanaTopic = getEuropeanaTypeTopic(tm); makeSubclassOf(tm, type, europeanaTopic); return type; } public static Topic getTypeTopic(String type, TopicMap tm) throws TopicMapException { Topic resTopic=getOrCreateTopic(tm, type); resTopic.addType(getTypeTypeTopic(tm)); return resTopic; } public static Topic getTypeTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, TYPE_SI, "type (Europeana API)"); Topic europeanaTopic = getEuropeanaTypeTopic(tm); makeSubclassOf(tm, type, europeanaTopic); return type; } public static Topic getDataProviderTopic(String dataProvider, TopicMap tm) throws TopicMapException { Topic resTopic=getOrCreateTopic(tm, dataProvider); resTopic.addType(getDataProviderTypeTopic(tm)); return resTopic; } public static Topic getDataProviderTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, DATA_PROVIDER_SI, "data-provider (Europeana API)"); Topic europeanaTopic = getEuropeanaTypeTopic(tm); makeSubclassOf(tm, type, europeanaTopic); return type; } public static Topic getPlaceLabelTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, PLACE_LABEL_SI, "place-label (Europeana API)"); Topic europeanaTopic = getEuropeanaTypeTopic(tm); makeSubclassOf(tm, type, europeanaTopic); return type; } public static Topic getPreviewLinkTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, PREVIEW_LINK_SI, "preview-link (Europeana API)"); Topic europeanaTopic = getEuropeanaTypeTopic(tm); makeSubclassOf(tm, type, europeanaTopic); return type; } public static Topic getGuidLinkTypeTopic(TopicMap tm) throws TopicMapException { Topic type=getOrCreateTopic(tm, GUID_LINK_SI, "guid-link (Europeana API)"); Topic europeanaTopic = getEuropeanaTypeTopic(tm); makeSubclassOf(tm, type, europeanaTopic); return type; } }
12,380
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
EuropeanaSearchExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/europeana/EuropeanaSearchExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.europeana; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.nio.charset.Charset; import javax.swing.Icon; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.wandora.application.Wandora; import org.wandora.application.gui.UIBox; 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 nlaitinen */ public class EuropeanaSearchExtractor extends AbstractEuropeanaExtractor { private static final long serialVersionUID = 1L; private static String defaultEncoding = "UTF-8"; private static String defaultLang = "en"; private static String currentURL = null; @Override public String getName() { return "Europeana API search extractor"; } @Override public String getDescription(){ return "Extracts data from The Europeana data API at http://pro.europeana.eu"; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_europeana.png"); } // ------------------------------------------------------------------------- @Override public boolean _extractTopicsFrom(File f, TopicMap tm) throws Exception { currentURL = null; String in = IObox.loadFile(f); JSONObject json = new JSONObject(in); parse(json, tm); return true; } @Override public boolean _extractTopicsFrom(URL u, TopicMap tm) throws Exception { try { currentURL = u.toExternalForm(); log("Item search extraction with " + currentURL); String in = doUrl(u); System.out.println("---------------Europeana API returned------------\n"+in+ "\n-----------------------------------------------"); JSONObject json = new JSONObject(in); parse(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); parse(json, tm); return true; } public 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) { log("Authentication failed. Check API Key."); } } return sb.toString(); } // ------------------------- PARSING --------------------------------------- public void parse(JSONObject json, TopicMap tm) throws TopicMapException { if(json.has("items")) { try { JSONArray resultsArray = json.getJSONArray("items"); for(int i=0; i<resultsArray.length(); i++) { JSONObject result = resultsArray.getJSONObject(i); parseResult(result, tm); } } catch (JSONException ex) { log(ex); } } else if (!json.has("items")) { log("API returned no results."); } } public void parseResult(JSONObject result, TopicMap tm) throws JSONException, TopicMapException { if(result.has("id")) { // All results should contain an url at least. String id = result.getString("id"); String subjectId = ITEM_SI + urlEncode(id); Topic itemTopic = tm.createTopic(); itemTopic.addSubjectIdentifier(new Locator(subjectId)); itemTopic.addType(getItemTypeTopic(tm)); Topic itemTypeTopic = getItemTypeTopic(tm); if(result.has("provider")) { JSONArray provider = result.getJSONArray("provider"); if(provider.length() > 0) { for(int i=0; i<provider.length(); i++) { String value = provider.getString(i); if(value != null && value.length() > 0) { String subjectValue = PROVIDER_SI + "/" + urlEncode(value); Topic providerTopic = getProviderTopic(subjectValue, tm); Topic providerTypeTopic = getProviderTypeTopic(tm); Association a = tm.createAssociation(providerTypeTopic); a.addPlayer(providerTopic, providerTypeTopic); a.addPlayer(itemTopic, itemTypeTopic); providerTopic.setBaseName(value); } } } } if(result.has("language")) { JSONArray language = result.getJSONArray("language"); if(language.length() > 0) { for(int i=0; i<language.length(); i++) { String value = language.getString(i); if(value != null && value.length() > 0) { Topic languageTypeTopic = getLanguageTypeTopic(tm); Topic langTopic = getLangTopic(tm); itemTopic.setData(languageTypeTopic, langTopic, value); } } } } if(result.has("year")) { JSONArray year = result.getJSONArray("year"); if(year.length() > 0) { for(int i=0; i<year.length(); i++) { String value = year.getString(i); if(value != null && value.length() > 0) { String subjectValue = YEAR_SI + "/" + urlEncode(value); Topic yearTopic = getYearTopic(subjectValue, tm); Topic yearTypeTopic = getYearTypeTopic(tm); Topic langTopic = getLangTopic(tm); Association a = tm.createAssociation(yearTypeTopic); a.addPlayer(yearTopic, yearTypeTopic); a.addPlayer(itemTopic, itemTypeTopic); itemTopic.setData(yearTypeTopic, langTopic, value); } } } } if(result.has("rights")) { JSONArray rights = result.getJSONArray("rights"); if(rights.length() > 0) { for(int i=0; i<rights.length(); i++) { String value = rights.getString(i); if(value != null && value.length() > 0) { String subjectValue = RIGHTS_LINK_SI + "/" + urlEncode(value); Topic rightsLinkTopic = getRightsLinkTopic(subjectValue, tm); Topic rightsLinkTypeTopic = getRightsLinkTypeTopic(tm); Topic langTopic = getLangTopic(tm); Association a = tm.createAssociation(rightsLinkTypeTopic); a.addPlayer(rightsLinkTopic, rightsLinkTypeTopic); a.addPlayer(itemTopic, itemTypeTopic); itemTopic.setData(rightsLinkTypeTopic, langTopic, value); rightsLinkTopic.setBaseName(value); } } } } if(result.has("title")) { JSONArray title = result.getJSONArray("title"); if(title.length() > 0) { for(int i=0; i<title.length(); i++) { String value = title.getString(i); 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("dcCreator")) { JSONArray dcCreator = result.getJSONArray("dcCreator"); if(dcCreator.length() > 0) { for(int i=0; i<dcCreator.length(); i++) { String value = dcCreator.getString(i); if(value != null && value.length() > 0) { String subjectValue = DC_CREATOR_SI + "/" + urlEncode(value); Topic dcCreatorTopic = getDcCreatorTopic(subjectValue, tm); Topic dcCreatorTypeTopic = getDcCreatorTypeTopic(tm); Topic langTopic = getLangTopic(tm); Association a = tm.createAssociation(dcCreatorTypeTopic); a.addPlayer(dcCreatorTopic, dcCreatorTypeTopic); a.addPlayer(itemTopic, itemTypeTopic); itemTopic.setData(dcCreatorTypeTopic, langTopic, value); dcCreatorTopic.setBaseName(value); } } } } if(result.has("country")) { JSONArray country = result.getJSONArray("country"); if(country.length() > 0) { for(int i=0; i<country.length(); i++) { String value = country.getString(i); if(value != null && value.length() > 0) { String subjectValue = COUNTRY_SI + "/" + urlEncode(value); Topic countryTopic = getCountryTopic(subjectValue, tm); Topic countryTypeTopic = getCountryTypeTopic(tm); Topic langTopic = getLangTopic(tm); Association a = tm.createAssociation(countryTypeTopic); a.addPlayer(countryTopic, countryTypeTopic); a.addPlayer(itemTopic, itemTypeTopic); itemTopic.setData(countryTypeTopic, langTopic, value); } } } } if(result.has("europeanaCollectionName")) { JSONArray collectionName = result.getJSONArray("europeanaCollectionName"); if(collectionName.length() > 0) { for(int i=0; i<collectionName.length(); i++) { String value = collectionName.getString(i); if(value != null && value.length() > 0) { String subjectValue = COLLECTION_NAME_SI + "/" + urlEncode(value); Topic collectionNameTopic = getCollectionNameTopic(subjectValue, tm); Topic collectionNameTypeTopic = getCollectionNameTypeTopic(tm); Topic langTopic = getLangTopic(tm); Association a = tm.createAssociation(collectionNameTypeTopic); a.addPlayer(collectionNameTopic, collectionNameTypeTopic); a.addPlayer(itemTopic, itemTypeTopic); itemTopic.setData(collectionNameTypeTopic, langTopic, value); collectionNameTopic.setBaseName(value); } } } } if(result.has("edmConceptLabel")) { JSONArray conceptLabel = result.getJSONArray("edmConceptLabel"); if(conceptLabel.length() > 0) { for(int i=0; i<conceptLabel.length(); i++) { JSONObject obj = conceptLabel.getJSONObject(i); String def = obj.getString("def"); if(obj != null && def != null) { Topic conceptLabelTypeTopic = getConceptLabelTypeTopic(tm); Topic langTopic = getLangTopic(tm); itemTopic.setData(conceptLabelTypeTopic, langTopic, def); } } } } if(result.has("type")) { String type = result.getString("type"); if(type != null && type.length() > 0) { String subjectValue = TYPE_SI + "/" + urlEncode(type); Topic typeTopic = getTypeTopic(subjectValue, tm); Topic typeTypeTopic = getTypeTypeTopic(tm); Association a = tm.createAssociation(typeTypeTopic); a.addPlayer(typeTopic, typeTypeTopic); a.addPlayer(itemTopic, itemTypeTopic); typeTopic.setBaseName(type); } } if(result.has("dataProvider")) { JSONArray dataProvider = result.getJSONArray("dataProvider"); if(dataProvider.length() > 0) { for(int i=0; i<dataProvider.length(); i++) { String value = dataProvider.getString(i); if(value != null && value.length() > 0) { String subjectValue = DATA_PROVIDER_SI + "/" + urlEncode(value); Topic dataProviderTopic = getDataProviderTopic(subjectValue, tm); Topic dataProviderTypeTopic = getDataProviderTypeTopic(tm); Topic langTopic = getLangTopic(tm); Association a = tm.createAssociation(dataProviderTypeTopic); a.addPlayer(dataProviderTopic, dataProviderTypeTopic); a.addPlayer(itemTopic, itemTypeTopic); itemTopic.setData(dataProviderTypeTopic, langTopic, value); dataProviderTopic.setBaseName(value); } } } } if(result.has("edmPlaceLabel")) { JSONArray placeLabel = result.getJSONArray("edmPlaceLabel"); if(placeLabel.length() > 0) { for(int i=0; i<placeLabel.length(); i++) { JSONObject obj = placeLabel.getJSONObject(i); String def = obj.getString("def"); if(obj != null && def.length() > 0) { Topic placeLabelTypeTopic = getPlaceLabelTypeTopic(tm); Topic langTopic = getLangTopic(tm); itemTopic.setData(placeLabelTypeTopic, langTopic, def); } } } } if(result.has("edmPreview")) { JSONArray previewLink = result.getJSONArray("edmPreview"); if(previewLink.length() > 0) { for(int i=0; i<previewLink.length(); i++) { String value = previewLink.getString(i); if(value != null && value.length() > 0) { Topic previewLinkTypeTopic = getPreviewLinkTypeTopic(tm); Topic langTopic = getLangTopic(tm); itemTopic.setData(previewLinkTypeTopic, langTopic, value); } } } } if(result.has("guid")) { String guid = result.getString("guid"); if(guid != null && guid.length() > 0) { Topic guidTypeTopic = getGuidLinkTypeTopic(tm); Topic langTopic = getLangTopic(tm); itemTopic.setData(guidTypeTopic, langTopic, guid); itemTopic.addSubjectIdentifier(new Locator(guid)); } } } } }
18,327
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
EuropeanaExtractorUI.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/europeana/EuropeanaExtractorUI.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.europeana; import java.net.URLEncoder; import java.util.ArrayList; 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.WandoraOptionPane; import org.wandora.application.gui.simple.SimpleButton; import org.wandora.application.gui.simple.SimpleField; import org.wandora.application.gui.simple.SimpleLabel; import org.wandora.topicmap.TopicMapException; /** * * @author nlaitinen */ public class EuropeanaExtractorUI extends javax.swing.JPanel { private static final long serialVersionUID = 1L; private Wandora wandora = null; private boolean accepted = false; private JDialog dialog = null; private Context context = null; private static final String EUROPEANA_API_BASE = "http://www.europeana.eu/api/v2/search.json"; /** * Creates new form EuropeanaExtractorUI */ public EuropeanaExtractorUI() { 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(420, 200); dialog.add(this); dialog.setTitle("Europeana API extractor"); UIBox.centerWindow(dialog, w); if(apiKey != null){ forgetKeyButton.setEnabled(true); } else { forgetKeyButton.setEnabled(false); } dialog.setVisible(true); } public WandoraTool[] getExtractors(EuropeanaExtractor tool) throws TopicMapException { WandoraTool wt = null; List<WandoraTool> wts = new ArrayList<>(); // ***** SEARCH ***** String query = searchTextField.getText(); String key = solveAPIKey(); if(key == null) { accepted = false; return null; } String extractUrl = EUROPEANA_API_BASE + "?wskey=" + key + "&profile=standard&query=" + urlEncode(query); System.out.println("Search URL: " + extractUrl); EuropeanaSearchExtractor ex = new EuropeanaSearchExtractor(); ex.setForceUrls(new String[]{extractUrl}); wt = ex; wts.add(wt); return wts.toArray(new WandoraTool[]{}); } protected static String urlEncode(String str) { try { str = URLEncoder.encode(str, "utf-8"); } catch (Exception e) { } return str; } // ------------------- Forget API Key ------------------------------------- private static String apiKey = null; public String solveAPIKey(Wandora wandora) { return solveAPIKey(); } public String solveAPIKey() { if(apiKey == null){ apiKey = ""; apiKey = WandoraOptionPane.showInputDialog(Wandora.getWandora(), "Please give an API Key for Europeana API search. You can register your API Key at http://pro.europeana.eu/api", apiKey, "Europeana API Key", WandoraOptionPane.QUESTION_MESSAGE); if(apiKey != null) { apiKey = apiKey.trim(); } } forgetKeyButton.setEnabled(true); return apiKey; } public void forgetAuthorization() { apiKey = null; forgetKeyButton.setEnabled(false); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; mainPanel = new javax.swing.JPanel(); topPanel = new javax.swing.JPanel(); headlineLabel = new SimpleLabel(); searchTextField = new SimpleField(); bottomPanel = new javax.swing.JPanel(); forgetKeyButton = new SimpleButton(); fillerPanel = new javax.swing.JPanel(); okButton = new SimpleButton(); cancelButton = new SimpleButton(); setLayout(new java.awt.GridBagLayout()); mainPanel.setLayout(new java.awt.GridBagLayout()); topPanel.setLayout(new java.awt.GridBagLayout()); headlineLabel.setText("Search Europeana database by entering search term"); headlineLabel.setMaximumSize(new java.awt.Dimension(64, 14)); headlineLabel.setMinimumSize(new java.awt.Dimension(64, 14)); headlineLabel.setPreferredSize(new java.awt.Dimension(64, 14)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 4, 0); topPanel.add(headlineLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; topPanel.add(searchTextField, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); mainPanel.add(topPanel, gridBagConstraints); bottomPanel.setMinimumSize(new java.awt.Dimension(250, 25)); bottomPanel.setPreferredSize(new java.awt.Dimension(250, 25)); bottomPanel.setLayout(new java.awt.GridBagLayout()); forgetKeyButton.setText("Forget API Key"); forgetKeyButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { forgetKeyActionPerformed(evt); } }); bottomPanel.add(forgetKeyButton, new java.awt.GridBagConstraints()); javax.swing.GroupLayout fillerPanelLayout = new javax.swing.GroupLayout(fillerPanel); fillerPanel.setLayout(fillerPanelLayout); fillerPanelLayout.setHorizontalGroup( fillerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); fillerPanelLayout.setVerticalGroup( fillerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; bottomPanel.add(fillerPanel, gridBagConstraints); okButton.setLabel("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.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("Europeana search"); mainPanel.getAccessibleContext().setAccessibleDescription(""); }// </editor-fold>//GEN-END:initComponents private void forgetKeyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_forgetKeyActionPerformed apiKey = null; forgetKeyButton.setEnabled(false); }//GEN-LAST:event_forgetKeyActionPerformed 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 bottomPanel; private javax.swing.JButton cancelButton; private javax.swing.JPanel fillerPanel; private javax.swing.JButton forgetKeyButton; private javax.swing.JLabel headlineLabel; private javax.swing.JPanel mainPanel; private javax.swing.JButton okButton; private javax.swing.JTextField searchTextField; private javax.swing.JPanel topPanel; // End of variables declaration//GEN-END:variables }
11,128
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/foaf/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/>. * * * * TwineExtractor.java * * Created on 7.2.2009,12:32 */ package org.wandora.application.tools.extractors.foaf; 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 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.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.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.XTMPSI; /** * * @author akivela */ public class FoafRDFExtractor extends AbstractExtractor { private static final long serialVersionUID = 1L; private String defaultEncoding = "UTF-8"; public static String defaultLanguage = "en"; 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"); } 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) { super.execute(wandora, context); } public boolean _extractTopicsFrom(URL url, TopicMap topicMap) throws Exception { URLConnection uc = url.openConnection(); uc.setUseCaches(false); boolean r = _extractTopicsFrom(uc.getInputStream(), topicMap); return r; } 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 { importFoafRDF(in, topicMap); return true; } catch(Exception e) { log(e); } return false; } public boolean _extractTopicsFrom(String in, TopicMap tm) throws Exception { try { importFoafRDF(new StringBufferInputStream(in), tm); } catch(Exception e){ log("Exception when handling request",e); } return true; } public void importFoafRDF(InputStream in, TopicMap map) { if(in != null) { // create an empty model Model model = ModelFactory.createDefaultModel(); // read the RDF/XML file model.read(in, ""); RDF2TopicMap(model, map); } } public 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("Foaf RDF statements processed: " + counter); } log("Total Foaf RDF statements processed: " + counter); } public String occurrenceScopeSI = TMBox.LANGINDEPENDENT_SI; public void handleStatement(Statement stmt, TopicMap map) throws TopicMapException { Resource subject = stmt.getSubject(); // get the subject Property predicate = stmt.getPredicate(); // get the predicate RDFNode object = stmt.getObject(); // get the object System.out.println("statement:\n "+subject+"\n "+predicate+"\n "+object); Topic subjectTopic = getOrCreateTopic(map, subject.toString()); Topic predicateTopic = getOrCreateTopic(map, predicate.toString()); if(object.isResource()) { 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()) { String occurrenceLang = occurrenceScopeSI; 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!"); } } String[] roles = new String[] { "http://www.w3.org/1999/02/22-rdf-syntax-ns#type", "http://wandora.org/si/core/rdf-type-carrier", "rdf-type-carrier", "http://wandora.org/si/core/rdf-type", "rdf-type", "http://www.w3.org/2000/01/rdf-schema#seeAlso", "http://wandora.org/si/core/subject", "subject", "http://wandora.org/si/core/rdf-schema/see-also", "rdf-see-also", "http://xmlns.com/foaf/0.1/nick", "http://wandora.org/si/foaf/person", "person", "http://wandora.org/si/foaf/nick", "nick", "http://xmlns.com/foaf/0.1/weblog", "http://wandora.org/si/foaf/person", "person", "http://wandora.org/si/foaf/weblog", "weblog", "http://xmlns.com/foaf/0.1/homepage", "http://wandora.org/si/foaf/person", "person", "http://wandora.org/si/foaf/homepage", "homepage", "http://xmlns.com/foaf/0.1/member", "http://wandora.org/si/foaf/person", "person", "http://wandora.org/si/foaf/group", "group", "http://xmlns.com/foaf/0.1/knows", "http://wandora.org/si/foaf/person", "person", "http://wandora.org/si/foaf/known-person", "known-person", }; public Topic solveSubjectRoleFor(Property predicate, Resource subject, TopicMap map) { if(map == null) return null; String predicateString = predicate.toString(); String si = "http://wandora.org/si/core/rdf-subject"; String bn = "subject-role"; for(int i=0; i<roles.length; i=i+5) { if(predicateString.equals(roles[i])) { si = roles[i+1]; bn = roles[i+2]; break; } } return getOrCreateTopic(map, si, bn); } public Topic solveObjectRoleFor(Property predicate, RDFNode object, TopicMap map) { if(map == null) return null; String predicateString = predicate.toString(); String si = "http://wandora.org/si/core/rdf-object"; String bn = "object-role"; for(int i=0; i<roles.length; i=i+5) { if(predicateString.equals(roles[i])) { si = roles[i+3]; bn = roles[i+4]; break; } } return getOrCreateTopic(map, si, bn); } String[] basenames = new String[] { "http://www.w3.org/1999/02/22-rdf-syntax-ns#type", "rdf-type", "http://www.w3.org/2000/01/rdf-schema#label", "label", "http://www.radarnetworks.com/core#contains", "contains", "http://www.radarnetworks.com/shazam#indirectlyContains", "indirectly-contains", "http://xmlns.com/foaf/0.1/person", "person", "http://xmlns.com/foaf/0.1/Organization", "organization", "http://xmlns.com/foaf/0.1/Group", "group", "http://xmlns.com/foaf/0.1/knows", "knows", "http://xmlns.com/foaf/0.1/membershipClass", "membership", "http://xmlns.com/foaf/0.1/member", "member", "http://xmlns.com/foaf/0.1/homepage", "homepage", "http://xmlns.com/foaf/0.1/weblog", "weblog", "http://xmlns.com/foaf/0.1/nick", "nickname", "http://xmlns.com/foaf/0.1/givenname", "given name", "http://xmlns.com/foaf/0.1/name", "name", "http://xmlns.com/foaf/0.1/firstName", "first name", "http://xmlns.com/foaf/0.1/surname", "surname", "http://xmlns.com/foaf/0.1/family_name", "family name", "http://xmlns.com/foaf/0.1/gender", "gender", "http://xmlns.com/foaf/0.1/geekcode", "geekcode", "http://xmlns.com/foaf/0.1/msnChatID", "msnChatID", "http://xmlns.com/foaf/0.1/myersBriggs", "Myers Briggs (MBTI) personality classification", "http://xmlns.com/foaf/0.1/schoolHomepage", "schoolHomepage", "http://xmlns.com/foaf/0.1/publications", "publications", "http://xmlns.com/foaf/0.1/plan", "plan-comment", "http://xmlns.com/foaf/0.1/phone", "phone", "http://xmlns.com/foaf/0.1/homepage", "homepage", "http://xmlns.com/foaf/0.1/holdsAccount", "holds account", "http://xmlns.com/foaf/0.1/pastProject", "past project", "http://xmlns.com/foaf/0.1/currentProject", "current project", "http://xmlns.com/foaf/0.1/Project", "project", "http://xmlns.com/foaf/0.1/page", "page", "http://xmlns.com/foaf/0.1/birthday", "birthday", "http://xmlns.com/foaf/0.1/openid", "openid", "http://xmlns.com/foaf/0.1/jabberID", "Jabber ID", "http://xmlns.com/foaf/0.1/aimChatID", "AIM chat ID", "http://xmlns.com/foaf/0.1/icqChatID", "ICQ chat ID", "http://xmlns.com/foaf/0.1/dnaChecksum", "DNA checksum", "http://xmlns.com/foaf/0.1/mbox_sha1sum", "personal mailbox URI", "http://xmlns.com/foaf/0.1/mbox", "a personal mailbox", "http://xmlns.com/foaf/0.1/PersonalProfileDocument", "personal profile document", "http://xmlns.com/foaf/0.1/maker", "maker", "http://xmlns.com/foaf/0.1/made", "made", "http://xmlns.com/foaf/0.1/logo", "logo", "http://xmlns.com/foaf/0.1/interest", "interest", "http://xmlns.com/foaf/0.1/img", "image", "http://xmlns.com/foaf/0.1/Image", "image (2)", "http://xmlns.com/foaf/0.1/fundedBy", "funded by", "http://xmlns.com/foaf/0.1/depicts", "depicts", "http://xmlns.com/foaf/0.1/depiction", "depiction", "http://xmlns.com/foaf/0.1/based_near", "based near", "http://xmlns.com/foaf/0.1/accountServiceHomepage", "account service homepage", "http://xmlns.com/foaf/0.1/accountName", "account name", "http://xmlns.com/foaf/0.1/OnlineGamingAccount", "online gaming account", "http://xmlns.com/foaf/0.1/OnlineEcommerceAccount", "online e-commerce account", "http://xmlns.com/foaf/0.1/OnlineChatAccount", "online chat account", "http://xmlns.com/foaf/0.1/OnlineAccount", "online account", "http://xmlns.com/foaf/0.1/Document", "document", "http://xmlns.com/foaf/0.1/Agent", "agent", }; public String solveBasenameFor(String si) { if(si == null) return null; String bn = null; for(int i=0; i<basenames.length; i=i+2) { if(si.equals(basenames[i])) { bn = basenames[i+1]; 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 { topic = map.getTopic(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; } }
14,994
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Any23Extractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/any23/Any23Extractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.any23; import java.io.File; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import javax.swing.Icon; import org.apache.any23.Any23; import org.apache.any23.extractor.ExtractionContext; import org.apache.any23.http.HTTPClient; import org.apache.any23.source.DocumentSource; import org.apache.any23.source.FileDocumentSource; import org.apache.any23.source.HTTPDocumentSource; import org.apache.any23.source.StringDocumentSource; import org.apache.any23.writer.TripleHandler; import org.apache.any23.writer.TripleHandlerException; import org.wandora.application.Wandora; import org.wandora.application.gui.UIBox; import org.wandora.application.tools.browserextractors.BrowserExtractRequest; import org.wandora.application.tools.extractors.AbstractExtractor; import org.wandora.application.tools.extractors.ExtractHelper; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicTools; import org.wandora.topicmap.XTMPSI; /** * Extract information out of given resources using Any23 (See https://any23.apache.org/index.html). * Transform extracted information to topics and associations. Sign all extracted * information with the information source. Information source is added to associations * as an extra player topic. * * @author akivela */ public class Any23Extractor extends AbstractExtractor { private static final long serialVersionUID = 1L; public static final String SOURCE_TYPE = "http://wandora.org/si/any23/source"; // Used also as a role-topic. public static final String ANY23_PREDICATE_TYPE = "http://wandora.org/si/any23/predicate"; public static final String ANY23_SUBJECT_TYPE = "http://wandora.org/si/any23/subject"; public static final String ANY23_OBJECT_TYPE = "http://wandora.org/si/any23/object"; public static final String ANY23_BASE = "http://any23.org/"; public static boolean SIGN_ALL_TRIPLETS = true; public static boolean TYPE_ALL_PREDICATES = true; public static boolean TYPE_ALL_SUBJECTS = true; public static boolean TYPE_ALL_OBJECTS = true; private String namespace = null; private String tripletSource = null; /** Creates a new instance of Any23Extractor */ public Any23Extractor() { } @Override public boolean useURLCrawler() { return false; } @Override public String getName() { return "Any23 extractor"; } @Override public String getDescription(){ return "Any23 extractor reads triplets out of given sources and "+ "transforms triplets to associations and topics."; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_any23.png"); } @Override public int getExtractorType() { return FILE_EXTRACTOR | URL_EXTRACTOR; } private final String[] contentTypes=new String[] { "text/html", "text/xml", "application/xml", "application/rdf+xml", "application/xhtml+xml" }; @Override public String[] getContentTypes() { return contentTypes; } @Override public boolean _extractTopicsFrom(URL url, TopicMap topicMap) throws Exception { if(url != null) { tripletSource = url.toExternalForm(); Any23 runner = new Any23(); runner.setHTTPUserAgent("Wandora ANY23 Extractor"); HTTPClient httpClient = runner.getHTTPClient(); DocumentSource source = new HTTPDocumentSource( httpClient, url.toExternalForm() ); namespace = url.toExternalForm(); TripleHandler handler = new TopicMapsCreator(topicMap); runner.extract(source, handler); } tripletSource = null; return true; } @Override public boolean _extractTopicsFrom(File file, TopicMap topicMap) throws Exception { if(file != null) { Any23 runner = new Any23(); tripletSource = file.toURI().toURL().toExternalForm(); DocumentSource source = new FileDocumentSource(file); TripleHandler handler = new TopicMapsCreator(topicMap); runner.extract(source, handler); } tripletSource = null; return true; } @Override public boolean _extractTopicsFrom(String str, TopicMap topicMap) throws Exception { if(str != null && str.length() > 0) { Any23 runner = new Any23(); DocumentSource source = new StringDocumentSource(str, tripletSource); TripleHandler handler = new TopicMapsCreator(topicMap); runner.extract(source, handler); } return true; } public boolean _extractTopicsFrom(InputStream in, TopicMap topicMap) throws Exception { return true; } @Override public String doBrowserExtract(BrowserExtractRequest request, Wandora wandora) throws TopicMapException { tripletSource = request.getSource(); String reply = super.doBrowserExtract(request, wandora); tripletSource = null; return reply; } // ------------------------------------------------------------------------- public Topic getPredicateTopic(TopicMap tm, String predicate) throws TopicMapException { Topic predicateTopic = getOrCreateTopic(tm, predicate); if(TYPE_ALL_PREDICATES) { Topic predicateType = getPredicateType(tm); predicateTopic.addType(predicateType); } return predicateTopic; } public Topic getPredicateType(TopicMap tm) throws TopicMapException { Topic predicateType = ExtractHelper.getOrCreateTopic(ANY23_PREDICATE_TYPE, "Any23 predicate", tm); Topic any23Type = getAny23Type(tm); ExtractHelper.makeSubclassOf(predicateType, any23Type, tm); return predicateType; } public Topic getObjectTopic(TopicMap tm, String object) throws TopicMapException { Topic objectTopic = getOrCreateTopic(tm, object); if(TYPE_ALL_OBJECTS) { Topic objectType = getObjectType(tm); objectTopic.addType(objectType); } return objectTopic; } public Topic getObjectType(TopicMap tm) throws TopicMapException { Topic objectType = ExtractHelper.getOrCreateTopic(ANY23_OBJECT_TYPE, "Any23 object", tm); Topic any23Type = getAny23Type(tm); ExtractHelper.makeSubclassOf(objectType, any23Type, tm); return objectType; } public Topic getSubjectTopic(TopicMap tm, String subject) throws TopicMapException { Topic subjectTopic = getOrCreateTopic(tm, subject); if(TYPE_ALL_SUBJECTS) { Topic subjectType = getSubjectType(tm); subjectTopic.addType(subjectType); } return subjectTopic; } public Topic getSubjectType(TopicMap tm) throws TopicMapException { Topic subjectType = ExtractHelper.getOrCreateTopic(ANY23_SUBJECT_TYPE, "Any23 subject", tm); Topic any23Type = getAny23Type(tm); ExtractHelper.makeSubclassOf(subjectType, any23Type, tm); return subjectType; } public Topic getSourceRoleType(TopicMap tm) throws TopicMapException { return ExtractHelper.getOrCreateTopic(SOURCE_TYPE, "Any23 source", tm); } public Topic getSourcePlayer(TopicMap tm) throws TopicMapException { if(tripletSource != null) { Topic sourceTopic = ExtractHelper.getOrCreateTopic(tripletSource, tm); Topic sourceType = getSourceType(tm); sourceTopic.addType(sourceType); return sourceTopic; } return null; } public Topic getSourceType(TopicMap tm) throws TopicMapException { Topic sourceType = ExtractHelper.getOrCreateTopic(SOURCE_TYPE, "Any23 triplet source", tm); Topic any23Type = getAny23Type(tm); ExtractHelper.makeSubclassOf(sourceType, any23Type, tm); return sourceType; } public Topic getAny23Type(TopicMap tm) throws TopicMapException { Topic any23Type = ExtractHelper.getOrCreateTopic(ANY23_BASE, "Any23", tm); Topic wc = ExtractHelper.getOrCreateTopic(TMBox.WANDORACLASS_SI, tm); ExtractHelper.makeSubclassOf(any23Type, wc, tm); return any23Type; } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- public class TopicMapsCreator implements TripleHandler { private TopicMap tm = null; private ArrayList<ExtractionContext> extractionContexts = null; private long contentLength = -1; private int tripletCounter = 0; public String defaultLanguage = "en"; public final String defaultOccurrenceScopeSI = TMBox.LANGINDEPENDENT_SI; public TopicMapsCreator(TopicMap topicMap) { this.tm = topicMap; extractionContexts = new ArrayList<ExtractionContext>(); namespace = null; tripletCounter = 0; } @Override public void startDocument(org.eclipse.rdf4j.model.IRI uri) throws TripleHandlerException { namespace = uri.getNamespace(); } @Override public void openContext(ExtractionContext ec) throws TripleHandlerException { extractionContexts.add(ec); } @Override public void receiveTriple(org.eclipse.rdf4j.model.Resource subject, org.eclipse.rdf4j.model.IRI predicate, org.eclipse.rdf4j.model.Value object, org.eclipse.rdf4j.model.IRI graph, ExtractionContext ec) throws TripleHandlerException { try { tripletCounter++; hlog("Found triplet: "+subject+" --- "+predicate+" --- "+object); Topic subjectTopic = getSubjectTopic(tm, subject.toString()); if(object instanceof org.openrdf.model.Literal) { org.openrdf.model.Literal literal = (org.openrdf.model.Literal) object; Topic predicateTopic = getPredicateTopic(tm, predicate.toString()); String occurrenceLang = literal.getLanguage(); if(occurrenceLang == null) { occurrenceLang = XTMPSI.getLang(defaultLanguage); } String literalStr = literal.getLabel(); String oldOccurrence = ""; // subjectTopic.getData(predicateTopic, occurrenceLang); if(oldOccurrence != null && oldOccurrence.length() > 0) { literalStr = oldOccurrence + "\n\n" + literalStr; } subjectTopic.setData(predicateTopic, getOrCreateTopic(tm, occurrenceLang), literalStr); } else { Topic objectTopic = getObjectTopic(tm, object.toString()); Topic predicateTopic = getPredicateTopic(tm, predicate.toString()); Association association = tm.createAssociation(predicateTopic); association.addPlayer(subjectTopic, getSubjectType(tm)); association.addPlayer(objectTopic, getObjectType(tm)); if(SIGN_ALL_TRIPLETS && tripletSource != null) { try { Topic role = getSourceRoleType(tm); Topic player = getSourcePlayer(tm); if(role != null && player != null) { association.addPlayer(player, role); } } catch(Exception e) { e.printStackTrace(); } } } if(ec != null) { //System.out.println(" context: "+ec.getDocumentURI()); } } catch(Exception e) { log(e); e.printStackTrace(); } } @Override public void receiveNamespace(String prefix, String uri, ExtractionContext ec) throws TripleHandlerException { namespace = uri; } @Override public void closeContext(ExtractionContext ec) throws TripleHandlerException { for(int i=extractionContexts.size()-1; i>=0; i--) { if(ec.equals(extractionContexts.get(i))) { extractionContexts.remove(i); } } } @Override public void endDocument(org.eclipse.rdf4j.model.IRI uri) throws TripleHandlerException { } @Override public void setContentLength(long l) { contentLength = l; } @Override public void close() throws TripleHandlerException { log("Total "+tripletCounter+" triplets found!"); } } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- public String getBaseSubject() { if(namespace != null) return namespace; else return "http://wandora.org/si/default"; } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- public Topic getOrCreateTopic(TopicMap map, String si) { return getOrCreateTopic(map, si, null); } public Topic getOrCreateTopic(TopicMap map, String si, String basename) { Topic topic = null; try { if(si == null || si.length() == 0) { si = TopicTools.createDefaultLocator().toExternalForm(); } if(si.startsWith("_:") && getBaseSubject() != null) { String base = getBaseSubject(); if(base.endsWith("/")) si = base + si.substring(2); else si = base + "/" + si.substring(2); } if(si.indexOf("://") == -1 && getBaseSubject() != null) { String base = getBaseSubject(); if(base.endsWith("/")) si = base + si; else si = base + "/" + 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) { log(e); } return topic; } }
16,216
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DbpediaRDFExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/dbpedia/DbpediaRDFExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * DbpediaRDFExtractor.java * * Created on 21.10.2009, 11:17:11 */ package org.wandora.application.tools.extractors.dbpedia; import javax.swing.Icon; import org.wandora.application.gui.UIBox; import org.wandora.application.tools.extractors.rdf.AbstractRDFExtractor; 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.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; import org.wandora.application.tools.extractors.rdf.rdfmappings.RSSMapping; import org.wandora.application.tools.extractors.rdf.rdfmappings.SKOSMapping; /** * * @author akivela */ public class DbpediaRDFExtractor extends AbstractRDFExtractor { private static final long serialVersionUID = 1L; private RDF2TopicMapsMapping[] mappings = new RDF2TopicMapsMapping[] { new FOAFMapping(), new RDFSMapping(), new RDFMapping(), new OWLMapping(), new RSSMapping(), new SKOSMapping(), new DublinCoreMapping(), }; public DbpediaRDFExtractor() { } @Override public String getName() { return "DBpedia RDF/XML extractor..."; } @Override public String getDescription(){ return "Read DBpedia RDF/XML feed and convert it to a topic map."; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_dbpedia.png"); } @Override public RDF2TopicMapsMapping[] getMappings() { return mappings; } }
2,611
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DbpediaExtractorSelector.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/dbpedia/DbpediaExtractorSelector.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.dbpedia; import java.awt.Component; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import javax.swing.JDialog; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.gui.simple.SimpleButton; import org.wandora.application.gui.simple.SimpleLabel; import org.wandora.application.gui.simple.SimpleScrollPane; import org.wandora.application.gui.simple.SimpleTabbedPane; import org.wandora.application.gui.simple.SimpleTextArea; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; /** * * @author akivela */ public class DbpediaExtractorSelector extends JDialog { private static final long serialVersionUID = 1L; public static String webServiceBase = "http://www.dbpedia.org/"; public static String sparqlServiceBase = "http://dbpedia.org/sparql/"; private Wandora wandora = null; private Context context = null; private boolean accepted = false; /** Creates new form OpenCycExtractorSelector */ public DbpediaExtractorSelector(Wandora wandora) { super(wandora, true); initComponents(); setTitle("DBpedia extractors"); setSize(450,300); wandora.centerWindow(this); this.wandora = wandora; accepted = false; } public void setWandora(Wandora wandora) { this.wandora = wandora; } public void setContext(Context context) { this.context = context; } public boolean wasAccepted() { return accepted; } public void setAccepted(boolean b) { accepted = b; } public WandoraTool getWandoraTool(WandoraTool parentTool) { Component component = dbpediaTabbedPane.getSelectedComponent(); WandoraTool wt = null; // ***** TERMS ***** if(termPanel.equals(component)) { String termsAll = termsTextArea.getText(); String[] terms = urlEncode(space2Underline(newlineSplitter(termsAll))); // Example URL: http://dbpedia.org/data/Berlin.rdf String[] termUrls = completeString(webServiceBase+"data/__1__.rdf", terms); DbpediaRDFExtractor ex = new DbpediaRDFExtractor(); ex.setForceUrls( termUrls ); wt = ex; } if(sparqlPanel.equals(component)) { String query = sparqlTextArea.getText(); if(query != null && query.trim().length() > 0) { query = query.trim(); query = urlEncode(query); String url = sparqlServiceBase+"?query="+query+"&format=application%2Frdf%2Bxml"; //System.out.println("url == '"+url+"'"); //url = "http://dbpedia.org/sparql/?query=PREFIX+dbo%3A+%3Chttp%3A%2F%2Fdbpedia.org%2Fontology%2F%3E%0D%0A%0D%0ASELECT+%3Fname+%3Fbirth+%3Fdescription+%3Fperson+WHERE+{%0D%0A+++++%3Fperson+dbo%3Abirthplace+%3Chttp%3A%2F%2Fdbpedia.org%2Fresource%2FBerlin%3E+.%0D%0A+++++%3Fperson+skos%3Asubject+%3Chttp%3A%2F%2Fdbpedia.org%2Fresource%2FCategory%3AGerman_musicians%3E+.%0D%0A+++++%3Fperson+dbo%3Abirthdate+%3Fbirth+.%0D%0A+++++%3Fperson+foaf%3Aname+%3Fname+.%0D%0A+++++%3Fperson+rdfs%3Acomment+%3Fdescription+.%0D%0A+++++FILTER+%28LANG%28%3Fdescription%29+%3D+%27en%27%29+.%0D%0A}%0D%0AORDER+BY+%3Fname&format=application%2Frdf%2Bxml"; DbpediaRDFExtractor ex = new DbpediaRDFExtractor(); ex.setForceUrls( new String[] { url } ); wt = ex; } else { parentTool.log("Given SPARQL query is zero length."); } } return wt; } public String[] space2Underline(String[] strs) { ArrayList<String> strs2 = new ArrayList<String>(); if(strs != null && strs.length > 0) { for(int i=0; i<strs.length; i++) { if(strs[i] != null) { strs2.add(strs[i].replace(" ", "_")); } } } return strs2.toArray( new String[] {} ); } 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[] urls) { if(urls == null) return null; String[] cleanUrls = new String[urls.length]; for(int i=0; i<urls.length; i++) { cleanUrls[i] = urlEncode(urls[i]); } return cleanUrls; } public String urlEncode(String url) { try { return URLEncoder.encode(url, "UTF-8"); } catch(Exception e) { return url; } } public String getContextAsString() { StringBuilder sb = new StringBuilder(""); if(context != null) { try { Iterator contextObjects = context.getContextObjects(); String str = null; Object o = null; while(contextObjects.hasNext()) { str = null; o = contextObjects.next(); if(o instanceof Topic) { Topic t = (Topic) o; str = t.getBaseName(); if(str != null) { str = str.trim(); } else { Collection<Locator> sis = t.getSubjectIdentifiers(); for(Locator l : sis) { if(l != null) { String locatorPrefix = "http://dbpedia.org/resource/"; if(l.toExternalForm().startsWith(locatorPrefix)) { str = l.toExternalForm().substring(locatorPrefix.length()); str = URLDecoder.decode(str, "UTF-8"); str = str.replace("_", " "); break; } locatorPrefix = "http://www.dbpedia.org/resource/"; if(l.toExternalForm().startsWith(locatorPrefix)) { str = l.toExternalForm().substring(locatorPrefix.length()); str = URLDecoder.decode(str, "UTF-8"); str = str.replace("_", " "); break; } locatorPrefix = "http://www.dbpedia.org/data/"; if(l.toExternalForm().startsWith(locatorPrefix)) { str = l.toExternalForm().substring(locatorPrefix.length()); str = URLDecoder.decode(str, "UTF-8"); str = str.replace("_", " "); break; } } } } } if(str != null && str.length() > 0) { sb.append(str); if(contextObjects.hasNext()) { sb.append("\n"); } } } } 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; sparqlPanel = new javax.swing.JPanel(); jPanel1 = new javax.swing.JPanel(); sparqlLabel = new javax.swing.JLabel(); sparqlScrollPane = new javax.swing.JScrollPane(); sparqlTextArea = new javax.swing.JTextArea(); dbpediaTabbedPane = new SimpleTabbedPane(); termPanel = new javax.swing.JPanel(); termsInnerPanel = new javax.swing.JPanel(); termsLabel = new SimpleLabel(); termsScrollPane = new SimpleScrollPane(); termsTextArea = new SimpleTextArea(); termsGetContextPanel = new javax.swing.JPanel(); getContextButton = new SimpleButton(); buttonPanel = new javax.swing.JPanel(); buttonFillerPanel = new javax.swing.JPanel(); extractButton = new SimpleButton(); cancelButton = new SimpleButton(); sparqlPanel.setLayout(new java.awt.GridBagLayout()); jPanel1.setLayout(new java.awt.GridBagLayout()); sparqlLabel.setText("<html>Access DBpedia's SPARQL endpoint with given query. Note: Wandora doesn't evaluate or check given query.</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, 3, 0); jPanel1.add(sparqlLabel, gridBagConstraints); sparqlTextArea.setColumns(20); sparqlTextArea.setRows(5); sparqlScrollPane.setViewportView(sparqlTextArea); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; jPanel1.add(sparqlScrollPane, 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); sparqlPanel.add(jPanel1, gridBagConstraints); getContentPane().setLayout(new java.awt.GridBagLayout()); termPanel.setLayout(new java.awt.GridBagLayout()); termsInnerPanel.setLayout(new java.awt.GridBagLayout()); termsLabel.setText("<html>Extract terms from DBpedia. Use newline character to separate different terms. You can also get context terms to extractor.</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, 3, 0); termsInnerPanel.add(termsLabel, gridBagConstraints); termsTextArea.setColumns(20); termsTextArea.setRows(5); termsScrollPane.setViewportView(termsTextArea); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; termsInnerPanel.add(termsScrollPane, gridBagConstraints); termsGetContextPanel.setLayout(new java.awt.GridBagLayout()); getContextButton.setText("Get context"); getContextButton.setMargin(new java.awt.Insets(1, 4, 1, 4)); getContextButton.setMaximumSize(new java.awt.Dimension(85, 21)); getContextButton.setMinimumSize(new java.awt.Dimension(85, 21)); getContextButton.setPreferredSize(new java.awt.Dimension(85, 21)); getContextButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { getContextButtonMouseReleased(evt); } }); termsGetContextPanel.add(getContextButton, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.insets = new java.awt.Insets(3, 0, 0, 0); termsInnerPanel.add(termsGetContextPanel, 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); termPanel.add(termsInnerPanel, gridBagConstraints); dbpediaTabbedPane.addTab("Terms", termPanel); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; getContentPane().add(dbpediaTabbedPane, 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.setMargin(new java.awt.Insets(2, 4, 2, 4)); extractButton.setMaximumSize(new java.awt.Dimension(75, 23)); extractButton.setMinimumSize(new java.awt.Dimension(75, 23)); extractButton.setPreferredSize(new java.awt.Dimension(75, 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(4, 0, 4, 3); buttonPanel.add(extractButton, gridBagConstraints); cancelButton.setText("Cancel"); cancelButton.setMargin(new java.awt.Insets(2, 4, 2, 4)); cancelButton.setMaximumSize(new java.awt.Dimension(75, 23)); cancelButton.setMinimumSize(new java.awt.Dimension(75, 23)); cancelButton.setPreferredSize(new java.awt.Dimension(75, 23)); cancelButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { cancelButtonMouseReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(4, 0, 4, 4); buttonPanel.add(cancelButton, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; getContentPane().add(buttonPanel, gridBagConstraints); pack(); }// </editor-fold>//GEN-END:initComponents private void extractButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_extractButtonMouseReleased this.accepted = true; setVisible(false); }//GEN-LAST:event_extractButtonMouseReleased private void cancelButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cancelButtonMouseReleased this.accepted = false; setVisible(false); }//GEN-LAST:event_cancelButtonMouseReleased private void getContextButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_getContextButtonMouseReleased this.termsTextArea.setText(getContextAsString()); }//GEN-LAST:event_getContextButtonMouseReleased // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel buttonFillerPanel; private javax.swing.JPanel buttonPanel; private javax.swing.JButton cancelButton; private javax.swing.JTabbedPane dbpediaTabbedPane; private javax.swing.JButton extractButton; private javax.swing.JButton getContextButton; private javax.swing.JPanel jPanel1; private javax.swing.JLabel sparqlLabel; private javax.swing.JPanel sparqlPanel; private javax.swing.JScrollPane sparqlScrollPane; private javax.swing.JTextArea sparqlTextArea; private javax.swing.JPanel termPanel; private javax.swing.JPanel termsGetContextPanel; private javax.swing.JPanel termsInnerPanel; private javax.swing.JLabel termsLabel; private javax.swing.JScrollPane termsScrollPane; private javax.swing.JTextArea termsTextArea; // End of variables declaration//GEN-END:variables }
19,664
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DbpediaExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/dbpedia/DbpediaExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * DbpediaExtractor.java * * Created on 2009-10-21, 13:18 * */ package org.wandora.application.tools.extractors.dbpedia; 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 DbpediaExtractor extends AbstractWandoraTool { private static final long serialVersionUID = 1L; private static DbpediaExtractorSelector selector = null; @Override public String getName() { return "DBpedia extractor..."; } @Override public String getDescription(){ return "Convert DBpedia RDF/XML feeds to topic maps"; } @Override public WandoraToolType getType() { return WandoraToolType.createExtractType(); } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_dbpedia.png"); } @Override public void execute(Wandora wandora, Context context) { int counter = 0; try { if(selector == null) { selector = new DbpediaExtractorSelector(wandora); } selector.setAccepted(false); selector.setWandora(wandora); selector.setContext(context); selector.setVisible(true); if(selector.wasAccepted()) { setDefaultLogger(); WandoraTool extractor = selector.getWandoraTool(this); if(extractor != null) { extractor.setToolLogger(getDefaultLogger()); extractor.execute(wandora, context); } } else { //log("User cancelled the extraction!"); } } catch(Exception e) { singleLog(e); } if(selector != null && selector.wasAccepted()) { setState(WAIT); } } }
2,880
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AbstractExcelExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/excel/AbstractExcelExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.excel; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URL; import java.text.DateFormat; import java.text.SimpleDateFormat; import javax.swing.Icon; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.Comment; import org.apache.poi.ss.usermodel.DataFormatter; import org.apache.poi.ss.usermodel.DateUtil; import org.apache.poi.ss.usermodel.RichTextString; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.wandora.application.WandoraTool; import org.wandora.application.WandoraToolType; import org.wandora.application.gui.UIBox; 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.XTMPSI; /** * * @author akivela */ public abstract class AbstractExcelExtractor extends AbstractExtractor implements WandoraTool { private static final long serialVersionUID = 1L; public static String DEFAULT_LANG = "en"; @Override public String getName() { return "Abstract Excel extractor"; } @Override public String getDescription() { return "Abstract Excel extractor."; } @Override public WandoraToolType getType() { return WandoraToolType.createExtractType(); } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_excel.png"); } @Override public boolean runInOwnThread(){ return true; } @Override public boolean useTempTopicMap(){ return false; } @Override public boolean useURLCrawler() { return false; } @Override public int getExtractorType() { return FILE_EXTRACTOR | URL_EXTRACTOR; } // ------------------------------------------------------------------------- @Override public boolean _extractTopicsFrom(File f, TopicMap topicMap) throws Exception { try { if(f != null) { String fn = f.getAbsolutePath(); if(fn.toLowerCase().endsWith(".xls")) { HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(f)); processWorkbook(workbook, topicMap); } else { XSSFWorkbook workbook = new XSSFWorkbook(f.getAbsolutePath()); processWorkbook(workbook, topicMap); } log("Ok!"); } } catch (FileNotFoundException ex) { log(ex); } catch (IOException ex) { log(ex); } catch (Exception ex) { log(ex); } setState(WAIT); return true; } @Override public boolean _extractTopicsFrom(URL u, TopicMap topicMap) throws Exception { try { HSSFWorkbook workbook = new HSSFWorkbook(u.openStream()); processWorkbook(workbook, topicMap); log("Ok!"); } catch (FileNotFoundException ex) { log(ex); } catch (IOException ex) { log(ex); } catch (Exception ex) { log(ex); } setState(WAIT); return true; } @Override public boolean _extractTopicsFrom(String str, TopicMap t) throws Exception { return false; } public abstract void processWorkbook(HSSFWorkbook workbook, TopicMap topicMap); public abstract void processWorkbook(XSSFWorkbook workbook, TopicMap topicMap); public abstract void processSheet(HSSFSheet sheet, TopicMap topicMap); public abstract void processSheet(XSSFSheet sheet, TopicMap topicMap); // ------------------------------------------------------------------------- protected String getCellValueAsString(Cell cell) { if(cell != null) { if(cell.getCellType() == CellType.FORMULA) { return getCellValueAsString(cell, cell.getCachedFormulaResultType()); } else { return getCellValueAsString(cell, cell.getCellType()); } } return null; } private DataFormatter formatter = new DataFormatter(); private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); protected String getCellValueAsString(Cell cell, CellType type) { if(cell != null) { switch(type) { case ERROR: { return "ERROR"+cell.getErrorCellValue(); } case BOOLEAN: { return ""+cell.getBooleanCellValue(); } case NUMERIC: { if(DateUtil.isCellDateFormatted(cell)) { return dateFormat.format(cell.getDateCellValue()); } else { double value = cell.getNumericCellValue(); String formatString = cell.getCellStyle().getDataFormatString(); int formatIndex = cell.getCellStyle().getDataFormat(); return formatter.formatRawCellContents(value, formatIndex, formatString); } } case STRING: { return cell.getRichStringCellValue().getString(); } } } return null; } // ------------------------------------------------------------------------- public void associateToSheet(Cell cell, TopicMap tm) throws TopicMapException { if(cell.getSheet() != null) { Topic sheetTypeTopic = getSheetTypeTopic(tm); Topic sheetTopic = getSheetTopic(cell, tm); Topic cellTypeTopic = getCellTypeTopic(tm); Topic cellTopic = getCellTopic(cell, tm); if(sheetTypeTopic != null && sheetTopic != null && cellTypeTopic != null && cellTopic != null) { Association a = tm.createAssociation(sheetTypeTopic); a.addPlayer(cellTopic, cellTypeTopic); a.addPlayer(sheetTopic, sheetTypeTopic); } } } public void associateToLocation(Cell cell, TopicMap tm) throws TopicMapException { Topic locationTypeTopic = getCellLocationTypeTopic(tm); Topic rowTypeTopic = getRowTypeTopic(tm); Topic rowTopic = getRowTopic(cell, tm); Topic columnTypeTopic = getColumnTypeTopic(tm); Topic columnTopic = getColumnTopic(cell, tm); Topic cellTypeTopic = getCellTypeTopic(tm); Topic cellTopic = getCellTopic(cell, tm); if(locationTypeTopic != null && rowTypeTopic != null && rowTopic != null && columnTopic != null && columnTypeTopic != null && cellTypeTopic != null && cellTopic != null) { Association a = tm.createAssociation(locationTypeTopic); a.addPlayer(cellTopic, cellTypeTopic); a.addPlayer(rowTopic, rowTypeTopic); a.addPlayer(columnTopic, columnTypeTopic); } } public void associateToColors(Cell cell, TopicMap tm) throws TopicMapException { if(cell.getCellStyle() != null) { Topic colorTypeTopic = getBackgroundColorTypeTopic(tm); Topic colorTopic = getColorTopic(cell, tm); Topic cellTypeTopic = getCellTypeTopic(tm); Topic cellTopic = getCellTopic(cell, tm); if(colorTypeTopic != null && colorTopic != null && cellTypeTopic != null && cellTopic != null) { Association a = tm.createAssociation(colorTypeTopic); a.addPlayer(cellTopic, cellTypeTopic); a.addPlayer(colorTopic, colorTypeTopic); } colorTypeTopic = getForegroundColorTypeTopic(tm); colorTopic = getColorTopic(cell, tm); if(colorTypeTopic != null && colorTopic != null && cellTypeTopic != null && cellTopic != null) { Association a = tm.createAssociation(colorTypeTopic); a.addPlayer(cellTopic, cellTypeTopic); a.addPlayer(colorTopic, colorTypeTopic); } } } public void associateToType(Cell cell, TopicMap tm) throws TopicMapException { Topic typeTypeTopic = getCellTypeTypeTopic(tm); Topic typeTopic = getCellTypeTopic(cell, tm); Topic cellTypeTopic = getCellTypeTopic(tm); Topic cellTopic = getCellTopic(cell, tm); if(typeTypeTopic != null && typeTopic != null && cellTypeTopic != null && cellTopic != null) { Association a = tm.createAssociation(typeTypeTopic); a.addPlayer(cellTopic, cellTypeTopic); a.addPlayer(typeTopic, typeTypeTopic); } } public void associateToComment(Cell cell, TopicMap tm) throws TopicMapException { if(cell.getCellComment() != null) { Topic commentTypeTopic = getCommentTypeTopic(tm); Topic commentTopic = getCommentTopic(cell, tm); Topic cellTypeTopic = getCellTypeTopic(tm); Topic cellTopic = getCellTopic(cell, tm); if(commentTypeTopic != null && commentTopic != null && cellTypeTopic != null && cellTopic != null) { Association a = tm.createAssociation(commentTypeTopic); a.addPlayer(cellTopic, cellTypeTopic); a.addPlayer(commentTopic, commentTypeTopic); } } } public void associateToFormula(Cell cell, TopicMap tm) throws TopicMapException { if(cell.getCellType() == CellType.FORMULA) { if(cell.getCellFormula() != null) { Topic formulaTypeTopic = getFormulaTypeTopic(tm); Topic formulaTopic = getFormulaTopic(cell, tm); Topic cellTypeTopic = getCellTypeTopic(tm); Topic cellTopic = getCellTopic(cell, tm); if(formulaTypeTopic != null && formulaTopic != null && cellTypeTopic != null && cellTopic != null) { Association a = tm.createAssociation(formulaTypeTopic); a.addPlayer(cellTopic, cellTypeTopic); a.addPlayer(formulaTopic, formulaTypeTopic); } } } } // ------------------------------------------------------------------------- public static final int CELL_VALUE = 1; public static final int CELL_LOCATION = 2; public static final int CELL_SHEET_AND_LOCATION = 4; public static final int CELL_HASH = 8; public static int CELL_TOPIC_IS_BASED_ON = CELL_VALUE; public static String EXCEL_SI_PREFIX = "http://wandora.org/si/excel"; public static String EXCEL_COLUMN_SI_PREFIX = EXCEL_SI_PREFIX + "/column"; public static String EXCEL_ROW_SI_PREFIX = EXCEL_SI_PREFIX + "/row"; public static String EXCEL_SHEET_SI_PREFIX = EXCEL_SI_PREFIX + "/sheet"; public static String EXCEL_CELL_SI_PREFIX = EXCEL_SI_PREFIX + "/cell"; public static String EXCEL_COLOR_SI_PREFIX = EXCEL_SI_PREFIX + "/color"; public static String EXCEL_FORMULA_SI_PREFIX = EXCEL_SI_PREFIX + "/formula"; public static String EXCEL_COMMENT_SI_PREFIX = EXCEL_SI_PREFIX + "/comment"; public static String EXCEL_CELL_TYPE_SI_PREFIX = EXCEL_SI_PREFIX + "/cell-type"; public static String EXCEL_CELL_LOCATION_SI_PREFIX = EXCEL_SI_PREFIX + "/cell-location"; public static String DEFAULT_ASSOCIATION_TYPE_SI = EXCEL_SI_PREFIX+"/association-type"; public static String DEFAULT_ROLE_TYPE_SI = EXCEL_SI_PREFIX+"/role"; public static String DEFAULT_UPPER_ROLE_SI = DEFAULT_ROLE_TYPE_SI+"/upper"; public static String DEFAULT_LOWER_ROLE_SI = DEFAULT_ROLE_TYPE_SI+"/lower"; public static String DEFAULT_OCCURRENCE_TYPE_SI = EXCEL_SI_PREFIX+"/occurrence-type"; public static String EXCEL_CELL_VALUE_SI = EXCEL_SI_PREFIX + "/cell-value"; // ----- public Topic getExcelTypeTopic(TopicMap tm) { Topic typeTopic = getOrCreateTopic(tm, EXCEL_SI_PREFIX, "Excel"); try { typeTopic.addType(tm.getTopic(TMBox.WANDORACLASS_SI)); } catch(Exception e) {} return typeTopic; } // ----- public Topic getCellTopic(Cell cell, TopicMap tm) throws TopicMapException { String cellIdentifier = null; switch(CELL_TOPIC_IS_BASED_ON) { case CELL_VALUE: { cellIdentifier = getCellValueAsString(cell); break; } case CELL_SHEET_AND_LOCATION: { Sheet sheet = cell.getSheet(); String sheetName = sheet.getSheetName(); cellIdentifier = sheetName+"-"+cell.getColumnIndex()+"-"+cell.getRowIndex(); break; } case CELL_LOCATION: { cellIdentifier = cell.getColumnIndex()+"-"+cell.getRowIndex(); break; } case CELL_HASH: { cellIdentifier = Integer.toString(cell.hashCode()); break; } } if(cellIdentifier != null) { String si = EXCEL_CELL_SI_PREFIX +"/"+ urlEncode(cellIdentifier); Topic cellTopic = getOrCreateTopic(tm, si, cellIdentifier); cellTopic.addType(getCellTypeTopic(tm)); return cellTopic; } return null; } public Topic getCellTypeTopic(TopicMap tm) throws TopicMapException { Topic typeTopic = getOrCreateTopic(tm, EXCEL_CELL_SI_PREFIX, "Excel cell"); typeTopic.addType(getExcelTypeTopic(tm)); return typeTopic; } public Topic getCellValueTypeTopic(TopicMap tm) throws TopicMapException { Topic typeTopic = getOrCreateTopic(tm, EXCEL_CELL_VALUE_SI, "Excel cell value"); typeTopic.addType(getExcelTypeTopic(tm)); return typeTopic; } // ----- public Topic getCellTypeTopic(Cell cell, TopicMap tm) throws TopicMapException { CellType type = cell.getCellType(); String typeStr = "string"; switch(type) { case BLANK: { typeStr = "blank"; break; } case BOOLEAN: { typeStr = "boolean"; break; } case ERROR: { typeStr = "error"; break; } case FORMULA: { typeStr = "formula"; break; } case NUMERIC: { typeStr = "numeric"; break; } case STRING: { typeStr = "string"; break; } } Topic t = getOrCreateTopic(tm, EXCEL_CELL_TYPE_SI_PREFIX+"/"+typeStr, "Excel cell type "+typeStr); t.addType(getCellTypeTypeTopic(tm)); return t; } public Topic getCellTypeTypeTopic(TopicMap tm) throws TopicMapException { Topic typeTopic = getOrCreateTopic(tm, EXCEL_CELL_TYPE_SI_PREFIX, "Excel cell type"); typeTopic.addType(getExcelTypeTopic(tm)); return typeTopic; } // ----- public Topic getColorTopic(Cell cell, TopicMap tm) throws TopicMapException { CellStyle style = cell.getCellStyle(); int color = style.getFillBackgroundColor(); String si = EXCEL_COLOR_SI_PREFIX + "/" + urlEncode(Integer.toString(color)); Topic topic = getOrCreateTopic(tm, si, "Color "+color); topic.addType(getColorTypeTopic(tm)); return topic; } public Topic getColorTypeTopic(TopicMap tm) throws TopicMapException { Topic typeTopic = getOrCreateTopic(tm, EXCEL_COLOR_SI_PREFIX, "Excel color"); typeTopic.addType(getExcelTypeTopic(tm)); return typeTopic; } public Topic getBackgroundColorTypeTopic(TopicMap tm) throws TopicMapException { Topic typeTopic = getOrCreateTopic(tm, EXCEL_COLOR_SI_PREFIX+"/background", "Excel background color"); typeTopic.addType(getExcelTypeTopic(tm)); return typeTopic; } public Topic getForegroundColorTypeTopic(TopicMap tm) throws TopicMapException { Topic typeTopic = getOrCreateTopic(tm, EXCEL_COLOR_SI_PREFIX+"/foreground", "Excel foreground color"); typeTopic.addType(getExcelTypeTopic(tm)); return typeTopic; } // ----- public Topic getDefaultAssociationTypeTopic(TopicMap tm) throws TopicMapException { Topic typeTopic = getOrCreateTopic(tm, DEFAULT_ASSOCIATION_TYPE_SI, "Excel association type"); typeTopic.addType(getExcelTypeTopic(tm)); return typeTopic; } public Topic getDefaultUpperRoleTopic(TopicMap tm) throws TopicMapException { Topic typeTopic = getOrCreateTopic(tm, DEFAULT_UPPER_ROLE_SI, "Excel upper role"); typeTopic.addType(getExcelTypeTopic(tm)); return typeTopic; } public Topic getDefaultLowerRoleTopic(TopicMap tm) throws TopicMapException { Topic typeTopic = getOrCreateTopic(tm, DEFAULT_LOWER_ROLE_SI, "Excel lower role"); typeTopic.addType(getExcelTypeTopic(tm)); return typeTopic; } // ----- public Topic getRowTopic(Cell cell, TopicMap tm) throws TopicMapException { Topic topic=getOrCreateTopic(tm, EXCEL_ROW_SI_PREFIX+"/"+urlEncode(Integer.toString(cell.getRowIndex())), "Excel row "+cell.getRowIndex()); topic.addType(getRowTypeTopic(tm)); return topic; } public Topic getRowTypeTopic(TopicMap tm) throws TopicMapException { Topic typeTopic = getOrCreateTopic(tm, EXCEL_ROW_SI_PREFIX, "Excel row"); typeTopic.addType(getExcelTypeTopic(tm)); return typeTopic; } // ----- public Topic getColumnTopic(Cell cell, TopicMap tm) throws TopicMapException { Topic topic=getOrCreateTopic(tm, EXCEL_COLUMN_SI_PREFIX+"/"+urlEncode(Integer.toString(cell.getColumnIndex())), "Excel column "+cell.getColumnIndex()); topic.addType(getColumnTypeTopic(tm)); return topic; } public Topic getColumnTypeTopic(TopicMap tm) throws TopicMapException { Topic typeTopic = getOrCreateTopic(tm, EXCEL_COLUMN_SI_PREFIX, "Excel column"); typeTopic.addType(getExcelTypeTopic(tm)); return typeTopic; } // ----- public Topic getCommentTopic(Cell cell, TopicMap tm) throws TopicMapException { Comment comment = cell.getCellComment(); if(comment != null) { RichTextString rts = comment.getString(); String str = rts.getString(); String basename = str.replace('\n', ' '); basename = basename.replace('\r', ' '); basename = basename.replace('\t', ' '); Topic topic=getOrCreateTopic(tm, EXCEL_COMMENT_SI_PREFIX+"/"+urlEncode(basename), basename); topic.setData(getCommentTypeTopic(tm), tm.getTopic(XTMPSI.getLang(DEFAULT_LANG)), str); topic.addType(getCommentTypeTopic(tm)); return topic; } return null; } public Topic getCommentTypeTopic(TopicMap tm) throws TopicMapException { Topic typeTopic = getOrCreateTopic(tm, EXCEL_COMMENT_SI_PREFIX, "Excel comment"); typeTopic.addType(getExcelTypeTopic(tm)); return typeTopic; } // ------ public Topic getFormulaTopic(Cell cell, TopicMap tm) throws TopicMapException { String formula = cell.getCellFormula(); if(formula != null) { Topic topic=getOrCreateTopic(tm, EXCEL_FORMULA_SI_PREFIX+"/"+urlEncode(formula), formula); topic.setData(getFormulaTypeTopic(tm), tm.getTopic(XTMPSI.getLang(DEFAULT_LANG)), formula); topic.addType(getFormulaTypeTopic(tm)); return topic; } return null; } public Topic getFormulaTypeTopic(TopicMap tm) throws TopicMapException { Topic typeTopic = getOrCreateTopic(tm, EXCEL_FORMULA_SI_PREFIX, "Excel formula"); typeTopic.addType(getExcelTypeTopic(tm)); return typeTopic; } // ------ public Topic getCellLocationTypeTopic(TopicMap tm) throws TopicMapException { Topic typeTopic = getOrCreateTopic(tm, EXCEL_CELL_LOCATION_SI_PREFIX, "Excel cell location"); typeTopic.addType(getExcelTypeTopic(tm)); return typeTopic; } // ------ public Topic getSheetTopic(Cell cell, TopicMap tm) throws TopicMapException { Sheet sheet = cell.getSheet(); if(sheet != null) { String sheetName = sheet.getSheetName(); Topic topic=getOrCreateTopic(tm, EXCEL_SHEET_SI_PREFIX+"/"+urlEncode(sheetName), sheetName); topic.addType(getSheetTypeTopic(tm)); return topic; } return null; } public Topic getSheetTypeTopic(TopicMap tm) throws TopicMapException { Topic typeTopic = getOrCreateTopic(tm, EXCEL_SHEET_SI_PREFIX, "Excel sheet"); typeTopic.addType(getExcelTypeTopic(tm)); return typeTopic; } // ------------------------------------------------------------------------- public Topic getOrCreateTopic(TopicMap map, String si, String basename) { Topic topic = null; try { topic = map.getTopic(si); if(topic == null) { topic = map.createTopic(); topic.addSubjectIdentifier(new Locator(si)); if(basename != null && basename.length() > 0) topic.setBaseName(basename); } } catch(Exception e) { log(e); e.printStackTrace(); } return topic; } }
23,536
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ExcelTopicTreeExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/excel/ExcelTopicTreeExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.excel; import java.util.Iterator; import java.util.Map; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.wandora.application.Wandora; import org.wandora.application.tools.GenericOptionsDialog; import org.wandora.topicmap.Association; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.XTMPSI; /** * * @author akivela */ public class ExcelTopicTreeExtractor extends AbstractExcelExtractor { private static final long serialVersionUID = 1L; public static boolean MAKE_SUPER_SUB_CLASS_RELATION = false; public static boolean MAKE_CLASS_INSTANCE_RELATION = true; public static boolean MAKE_EXCEL_RELATION = false; public static boolean MAKE_CUSTOM_RELATION = false; private String customAssociationTypeSI = null; private String customUpperRoleSI = null; private String customLowerRoleSI = null; private Topic[] hierarchy = null; @Override public String getName(){ return "Excel topic tree extractor"; } @Override public String getDescription(){ return "Excel topics and associations in tree layout."; } @Override public void processWorkbook(HSSFWorkbook workbook, TopicMap topicMap) { int numberOfSheets = workbook.getNumberOfSheets(); for(int i=0; i<numberOfSheets && !forceStop(); i++) { HSSFSheet sheet = workbook.getSheetAt(i); processSheet(sheet, topicMap); } } @Override public void processWorkbook(XSSFWorkbook workbook, TopicMap topicMap) { int numberOfSheets = workbook.getNumberOfSheets(); for(int i=0; i<numberOfSheets && !forceStop(); i++) { XSSFSheet sheet = workbook.getSheetAt(i); processSheet(sheet, topicMap); } } public void processSheet(HSSFSheet sheet, TopicMap tm) { Iterator<Row> rowIterator = sheet.iterator(); hierarchy = new Topic[1000]; while(rowIterator.hasNext() && !forceStop()) { Row row = rowIterator.next(); processRow(row, tm); } } public void processSheet(XSSFSheet sheet, TopicMap tm) { Iterator<Row> rowIterator = sheet.iterator(); hierarchy = new Topic[1000]; while(rowIterator.hasNext() && !forceStop()) { Row row = rowIterator.next(); processRow(row, tm); } } public void processRow(Row row, TopicMap tm) { int firstColumn = row.getFirstCellNum(); int lastColumn = row.getLastCellNum(); for(int j=firstColumn; j<=lastColumn && !forceStop(); j++) { try { Cell cell = row.getCell(j); if(getCellValueAsString(cell) != null) { Topic t = getCellTopic(cell, tm); if(t != null) { for(int k=j-1; k>=0; k--) { Topic ct = hierarchy[k]; if(ct != null) { try { if(MAKE_SUPER_SUB_CLASS_RELATION) { Association a = tm.createAssociation(tm.getTopic(XTMPSI.SUPERCLASS_SUBCLASS)); if(a != null) { Topic superClassRole = tm.getTopic(XTMPSI.SUPERCLASS); Topic subClassRole = tm.getTopic(XTMPSI.SUBCLASS); if(superClassRole != null && subClassRole != null) { a.addPlayer(ct, superClassRole); a.addPlayer(t, subClassRole); } } } if(MAKE_CLASS_INSTANCE_RELATION) { t.addType(ct); } if(MAKE_EXCEL_RELATION) { Association a = tm.createAssociation(getDefaultAssociationTypeTopic(tm)); if(a != null) { Topic upperRole = getDefaultUpperRoleTopic(tm); Topic lowerRole = getDefaultLowerRoleTopic(tm); if(upperRole != null && lowerRole != null) { a.addPlayer(ct, upperRole); a.addPlayer(t, lowerRole); } } } if(MAKE_CUSTOM_RELATION) { if(customAssociationTypeSI == null || customUpperRoleSI == null || customLowerRoleSI == null) { requestCustomTypeAndRoles(tm); } if(customAssociationTypeSI != null && customUpperRoleSI != null && customLowerRoleSI != null) { Association a = tm.createAssociation(tm.getTopic(customAssociationTypeSI)); if(a != null) { Topic upperRole = tm.getTopic(customUpperRoleSI); Topic lowerRole = tm.getTopic(customLowerRoleSI); if(upperRole != null && lowerRole != null) { a.addPlayer(ct, upperRole); a.addPlayer(t, lowerRole); } } } } break; } catch(Exception e) {} } } hierarchy[j] = t; for(int k=j+1; k<1000; k++) { hierarchy[k] = null; } } } } catch (TopicMapException ex) { log(ex); } catch (Exception ex) { log(ex); } } } private void requestCustomTypeAndRoles(TopicMap tm) { Wandora wandora = Wandora.getWandora(); GenericOptionsDialog god=new GenericOptionsDialog(wandora,"Custom association type and roles","Custom association type and roles",true,new String[][]{ new String[]{"Custom association type topic","topic", null, "If custom relation is chosen, what is the association type?"}, new String[]{"Custom upper role topic","topic", null, "If custom relation is chosen, what is the upper role topic?"}, new String[]{"Custom lower role topic","topic", null, "If custom relation is chosen, what is the lower role topic?"}, },wandora); god.setVisible(true); if(god.wasCancelled()) return; Map<String, String> values = god.getValues(); customAssociationTypeSI = values.get("Custom association type topic"); customUpperRoleSI = values.get("Custom upper role topic"); customLowerRoleSI = values.get("Custom lower role topic"); } // ---------------------------------------------------------- CONFIGURE ---- @Override public boolean isConfigurable() { return true; } @Override public void configure(Wandora wandora,org.wandora.utils.Options options,String prefix) throws TopicMapException { GenericOptionsDialog god=new GenericOptionsDialog(wandora,"Excel topic tree extractor options","Excel topic tree extractor options",true,new String[][]{ new String[]{"Make superclass-subclass relation?","boolean",(MAKE_SUPER_SUB_CLASS_RELATION ? "true" : "false"),null }, new String[]{"Make class-instance relation?","boolean",(MAKE_CLASS_INSTANCE_RELATION ? "true" : "false"),null }, new String[]{"Make default Excel relation?","boolean",(MAKE_EXCEL_RELATION ? "true" : "false"),null }, new String[]{"Make custom relation?","boolean",(MAKE_CUSTOM_RELATION ? "true" : "false"),null }, new String[]{"Custom association type topic","topic", null, "If custom relation is chosen, what is the association type?"}, new String[]{"Custom upper role topic","topic", null, "If custom relation is chosen, what is the upper role topic?"}, new String[]{"Custom lower role topic","topic", null, "If custom relation is chosen, what is the lower role topic?"}, },wandora); god.setVisible(true); if(god.wasCancelled()) return; Map<String, String> values = god.getValues(); MAKE_SUPER_SUB_CLASS_RELATION = ("true".equals(values.get("Make superclass-subclass relation?")) ? true : false ); MAKE_CLASS_INSTANCE_RELATION = ("true".equals(values.get("Make class-instance relation?")) ? true : false ); MAKE_EXCEL_RELATION = ("true".equals(values.get("Make default Excel relation?")) ? true : false ); MAKE_CUSTOM_RELATION = ("true".equals(values.get("Make custom relation?")) ? true : false ); customAssociationTypeSI = values.get("Custom association type topic"); customUpperRoleSI = values.get("Custom upper role topic"); customLowerRoleSI = values.get("Custom lower role topic"); } }
11,169
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ExcelExtractorUI.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/excel/ExcelExtractorUI.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.excel; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import org.wandora.application.Wandora; import org.wandora.application.gui.simple.SimpleButton; import org.wandora.application.gui.simple.SimpleComboBox; import org.wandora.application.gui.simple.SimpleLabel; /** * * @author akivela */ public class ExcelExtractorUI extends javax.swing.JPanel { private static final long serialVersionUID = 1L; private JDialog myDialog = null; private boolean accepted = false; private List<JComboBox> comboboxes = null; /** * Creates new form ExcelExtractorUI */ public ExcelExtractorUI() { initComponents(); } public void open(Collection<String> sheets, Collection<String> extractors) { JPanel sheetSelectors = new JPanel(); sheetSelectors.setLayout(new GridBagLayout()); GridBagConstraints gridBagConstraints = new GridBagConstraints(); comboboxes = new ArrayList<>(); for(String sheet : sheets) { JLabel label = new SimpleLabel(sheet); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 0.0; gridBagConstraints.insets = new Insets(6,6,6,6); sheetSelectors.add(label, gridBagConstraints); JComboBox combobox = new SimpleComboBox(extractors); combobox.setEditable(false); gridBagConstraints.gridx = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new Insets(6,0,6,6); sheetSelectors.add(combobox, gridBagConstraints); comboboxes.add(combobox); } scrollPane.setViewportView(sheetSelectors); Wandora wandora = Wandora.getWandora(); myDialog = new JDialog(wandora, true); myDialog.setTitle("Select extractor for each Excel sheet"); myDialog.setSize(500, 300); myDialog.add(this); wandora.centerWindow(myDialog); myDialog.setVisible(true); } public String[] getExtractors() { List<String> extractors = new ArrayList<>(); for(JComboBox combobox : comboboxes) { if(combobox != null) { Object extractor = combobox.getSelectedItem(); extractors.add(extractor.toString()); } } return extractors.toArray( new String[] {} ); } public boolean wasAccepted() { return accepted; } public void setAccepted(boolean b) { accepted = b; } /** * 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; selectorPanel = new javax.swing.JPanel(); infoLabel = new SimpleLabel(); scrollPane = new javax.swing.JScrollPane(); buttonPanel = new javax.swing.JPanel(); fillerPanel = new javax.swing.JPanel(); okButton = new SimpleButton(); cancelButton = new SimpleButton(); setLayout(new java.awt.GridBagLayout()); selectorPanel.setLayout(new java.awt.GridBagLayout()); infoLabel.setText("Select extractor for each Excel sheet."); 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, 6, 6); selectorPanel.add(infoLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; selectorPanel.add(scrollPane, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(selectorPanel, gridBagConstraints); buttonPanel.setLayout(new java.awt.GridBagLayout()); fillerPanel.setLayout(new java.awt.GridBagLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; buttonPanel.add(fillerPanel, gridBagConstraints); okButton.setText("Extract"); okButton.setMargin(new java.awt.Insets(2, 6, 2, 6)); okButton.setMaximumSize(new java.awt.Dimension(70, 23)); okButton.setMinimumSize(new java.awt.Dimension(70, 23)); okButton.setPreferredSize(new java.awt.Dimension(70, 23)); okButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { okButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2); buttonPanel.add(okButton, gridBagConstraints); cancelButton.setText("Cancel"); cancelButton.setMargin(new java.awt.Insets(2, 6, 2, 6)); cancelButton.setMaximumSize(new java.awt.Dimension(70, 23)); cancelButton.setMinimumSize(new java.awt.Dimension(70, 23)); cancelButton.setPreferredSize(new java.awt.Dimension(70, 23)); cancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(2, 0, 2, 2); buttonPanel.add(cancelButton, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; add(buttonPanel, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed setAccepted(false); if(myDialog != null) myDialog.setVisible(false); }//GEN-LAST:event_cancelButtonActionPerformed private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed setAccepted(true); if(myDialog != null) myDialog.setVisible(false); }//GEN-LAST:event_okButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel buttonPanel; private javax.swing.JButton cancelButton; private javax.swing.JPanel fillerPanel; private javax.swing.JLabel infoLabel; private javax.swing.JButton okButton; private javax.swing.JScrollPane scrollPane; private javax.swing.JPanel selectorPanel; // End of variables declaration//GEN-END:variables }
8,807
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ExcelAdjacencyListExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/excel/ExcelAdjacencyListExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.excel; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.wandora.application.Wandora; import org.wandora.application.tools.GenericOptionsDialog; import org.wandora.topicmap.Association; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author akivela */ public class ExcelAdjacencyListExtractor extends AbstractExcelExtractor { private static final long serialVersionUID = 1L; public static boolean FIRST_ROW_CONTAINS_ROLES = true; private Map<String,String> rolesPerColumn = new LinkedHashMap<>(); @Override public String getName(){ return "Excel adjacency list extractor"; } @Override public String getDescription(){ return "Excel adjacency list extractor interprets Excel sheet as an adjacency list."; } @Override public void processWorkbook(HSSFWorkbook workbook, TopicMap topicMap) { int numberOfSheets = workbook.getNumberOfSheets(); for(int i=0; i<numberOfSheets && !forceStop(); i++) { HSSFSheet sheet = workbook.getSheetAt(i); processSheet(sheet, topicMap); } } @Override public void processWorkbook(XSSFWorkbook workbook, TopicMap topicMap) { int numberOfSheets = workbook.getNumberOfSheets(); for(int i=0; i<numberOfSheets && !forceStop(); i++) { XSSFSheet sheet = workbook.getSheetAt(i); processSheet(sheet, topicMap); } } public void processSheet(HSSFSheet sheet, TopicMap tm) { Iterator<Row> rowIterator = sheet.iterator(); boolean isFirst = true; rolesPerColumn = new LinkedHashMap<>(); while(rowIterator.hasNext() && !forceStop()) { Row row = rowIterator.next(); if(isFirst && FIRST_ROW_CONTAINS_ROLES) { processRowAsRoles(row, tm); isFirst = false; } else { processRow(row, tm); } } } public void processSheet(XSSFSheet sheet, TopicMap tm) { Iterator<Row> rowIterator = sheet.iterator(); boolean isFirst = true; rolesPerColumn = new LinkedHashMap<>(); while(rowIterator.hasNext() && !forceStop()) { Row row = rowIterator.next(); if(isFirst && FIRST_ROW_CONTAINS_ROLES) { processRowAsRoles(row, tm); isFirst = false; } else { processRow(row, tm); } } } public void processRow(Row row, TopicMap tm) { Iterator<Cell> cellIterator = row.cellIterator(); Association a = null; while(cellIterator.hasNext() && !forceStop()) { try { Cell cell = cellIterator.next(); if(getCellValueAsString(cell) != null) { Topic player = getCellTopic(cell, tm); if(player != null) { if(a == null) { a = tm.createAssociation(getDefaultAssociationTypeTopic(tm)); } if(a != null) { String roleSI = rolesPerColumn.get(Integer.toString(cell.getColumnIndex())); if(roleSI != null) { Topic role = tm.getTopic(roleSI); if(role == null) role = getDefaultRoleTopic(cell, tm); a.addPlayer(player, role); } } } } } catch (TopicMapException ex) { log(ex); } catch (Exception ex) { log(ex); } } } public void processRowAsRoles(Row row, TopicMap topicMap) { Iterator<Cell> cellIterator = row.cellIterator(); while(cellIterator.hasNext()) { try { Cell cell = cellIterator.next(); if(getCellValueAsString(cell) != null) { Topic cellTopic = getCellTopic(cell, topicMap); rolesPerColumn.put(Integer.toString(cell.getColumnIndex()), cellTopic.getOneSubjectIdentifier().toExternalForm()); } } catch (TopicMapException ex) { log(ex); } catch (Exception ex) { log(ex); } } } // ------------------------------------------------------------------------- public Topic getDefaultRoleTopic(Cell cell, TopicMap tm) { int i = cell.getColumnIndex(); Topic typeTopic = getOrCreateTopic(tm, DEFAULT_ROLE_TYPE_SI+"/"+i, "Excel role "+i); return typeTopic; } // ---------------------------------------------------------- CONFIGURE ---- @Override public boolean isConfigurable() { return true; } @Override public void configure(Wandora wandora,org.wandora.utils.Options options,String prefix) throws TopicMapException { GenericOptionsDialog god=new GenericOptionsDialog(wandora,"Excel adjacency list extractor options","Excel adjacency list extractor options",true,new String[][]{ new String[]{"First row contains association role topics?","boolean",(FIRST_ROW_CONTAINS_ROLES ? "true" : "false"),null }, },wandora); god.setVisible(true); if(god.wasCancelled()) return; Map<String, String> values = god.getValues(); FIRST_ROW_CONTAINS_ROLES = ("true".equals(values.get("First row contains association role topics?")) ? true : false ); } }
7,050
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ExcelTopicExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/excel/ExcelTopicExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.excel; import java.util.Iterator; import java.util.Map; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.wandora.application.Wandora; import org.wandora.application.tools.GenericOptionsDialog; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.XTMPSI; /** * * @author akivela */ public class ExcelTopicExtractor extends AbstractExcelExtractor { private static final long serialVersionUID = 1L; public static boolean EXTRACT_CELL_TYPE = true; public static boolean EXTRACT_CELL_COLORS = true; public static boolean EXTRACT_SHEET = true; public static boolean EXTRACT_CELL_FORMULA = true; public static boolean EXTRACT_CELL_COMMENT = true; public static boolean EXTRACT_CELL_LOCATION = true; @Override public String getName(){ return "Excel topic extractor"; } @Override public String getDescription(){ return "Excel topic extractor extracts cell values as topics and cell properties as associations of the topic."; } @Override public void processWorkbook(HSSFWorkbook workbook, TopicMap topicMap) { int numberOfSheets = workbook.getNumberOfSheets(); for(int i=0; i<numberOfSheets && !forceStop(); i++) { HSSFSheet sheet = workbook.getSheetAt(i); processSheet(sheet, topicMap); } } @Override public void processWorkbook(XSSFWorkbook workbook, TopicMap topicMap) { int numberOfSheets = workbook.getNumberOfSheets(); for(int i=0; i<numberOfSheets && !forceStop(); i++) { XSSFSheet sheet = workbook.getSheetAt(i); processSheet(sheet, topicMap); } } public void processSheet(HSSFSheet sheet, TopicMap tm) { Iterator<Row> rowIterator = sheet.iterator(); while(rowIterator.hasNext() && !forceStop()) { Row row = rowIterator.next(); processRow(row, tm); } } public void processSheet(XSSFSheet sheet, TopicMap tm) { Iterator<Row> rowIterator = sheet.iterator(); while(rowIterator.hasNext() && !forceStop()) { Row row = rowIterator.next(); processRow(row, tm); } } public void processRow(Row row, TopicMap tm) { Iterator<Cell> cellIterator = row.cellIterator(); try { while(cellIterator.hasNext() && !forceStop()) { Cell cell = cellIterator.next(); processCell(cell, tm); } } catch (Exception ex) { log(ex); } } public void processCell(Cell cell, TopicMap tm) { if(getCellValueAsString(cell) != null) { try { Topic t = getCellTopic(cell, tm); if(t != null) { if(EXTRACT_SHEET) associateToSheet(cell, tm); if(EXTRACT_CELL_LOCATION) associateToLocation(cell, tm); if(EXTRACT_CELL_COLORS) associateToColors(cell, tm); if(EXTRACT_CELL_TYPE) associateToType(cell, tm); if(EXTRACT_CELL_COMMENT) associateToComment(cell, tm); if(EXTRACT_CELL_FORMULA) associateToFormula(cell, tm); } } catch(Exception e) { log(e); } } } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- @Override public Topic getCellTopic(Cell cell, TopicMap tm) throws TopicMapException { Topic cellTopic = super.getCellTopic(cell,tm); if(cellTopic != null) { String str = getCellValueAsString(cell); if(str != null) { cellTopic.setData(getCellValueTypeTopic(tm), tm.getTopic(XTMPSI.getLang(DEFAULT_LANG)), str); } } return cellTopic; } // ---------------------------------------------------------- CONFIGURE ---- @Override public boolean isConfigurable() { return true; } @Override public void configure(Wandora wandora,org.wandora.utils.Options options,String prefix) throws TopicMapException { GenericOptionsDialog god=new GenericOptionsDialog(wandora,"Excel topic extractor options","Excel topic extractor options",true,new String[][]{ new String[]{"Extract cell colors?","boolean",(EXTRACT_CELL_COLORS ? "true" : "false"), "Associate cell to it's background and foreground color?" }, new String[]{"Extract sheet?","boolean",(EXTRACT_SHEET ? "true" : "false"), "Associate cell to it's sheet?" }, new String[]{"Extract cell location?","boolean",(EXTRACT_CELL_LOCATION ? "true" : "false"), "Associate cell to it's row and column?" }, new String[]{"Extract cell formula?","boolean",(EXTRACT_CELL_FORMULA ? "true" : "false"), "Associate cell to it's formula?" }, new String[]{"Extract cell comment?","boolean",(EXTRACT_CELL_COMMENT ? "true" : "false"), "Associate cell to it's comment?" }, new String[]{"Extract cell type?","boolean",(EXTRACT_CELL_TYPE ? "true" : "false"), "Associate cell to it's type?" }, },wandora); god.setVisible(true); if(god.wasCancelled()) return; Map<String, String> values = god.getValues(); EXTRACT_CELL_COLORS = ("true".equals(values.get("Extract cell colors?")) ? true : false ); EXTRACT_SHEET = ("true".equals(values.get("Extract sheet?")) ? true : false ); EXTRACT_CELL_LOCATION = ("true".equals(values.get("Extract cell location?")) ? true : false ); EXTRACT_CELL_FORMULA = ("true".equals(values.get("Extract cell formula?")) ? true : false ); EXTRACT_CELL_COMMENT = ("true".equals(values.get("Extract cell comment?")) ? true : false ); EXTRACT_CELL_TYPE = ("true".equals(values.get("Extract cell type?")) ? true : false ); } }
7,291
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ExcelTopicOccurrenceExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/excel/ExcelTopicOccurrenceExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.excel; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.wandora.application.Wandora; import org.wandora.application.tools.GenericOptionsDialog; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.XTMPSI; /** * * @author akivela */ public class ExcelTopicOccurrenceExtractor extends AbstractExcelExtractor { private static final long serialVersionUID = 1L; public static boolean FIRST_ROW_CONTAINS_OCCURRENCE_TYPES = true; private Map<String,String> occurrenceTypes = new LinkedHashMap<>(); @Override public String getName(){ return "Excel topic occurrence extractor"; } @Override public String getDescription(){ return "Excel topic occurrence extractor extracts occurrences for first column topics."; } @Override public void processWorkbook(HSSFWorkbook workbook, TopicMap topicMap) { int numberOfSheets = workbook.getNumberOfSheets(); for(int i=0; i<numberOfSheets && !forceStop(); i++) { HSSFSheet sheet = workbook.getSheetAt(i); processSheet(sheet, topicMap); } } @Override public void processWorkbook(XSSFWorkbook workbook, TopicMap topicMap) { int numberOfSheets = workbook.getNumberOfSheets(); for(int i=0; i<numberOfSheets && !forceStop(); i++) { XSSFSheet sheet = workbook.getSheetAt(i); processSheet(sheet, topicMap); } } public void processSheet(HSSFSheet sheet, TopicMap tm) { Iterator<Row> rowIterator = sheet.iterator(); boolean isFirst = true; occurrenceTypes = new HashMap<>(); while(rowIterator.hasNext() && !forceStop()) { Row row = rowIterator.next(); if(isFirst && FIRST_ROW_CONTAINS_OCCURRENCE_TYPES) { processRowAsOccurrenceTypes(row, tm); isFirst = false; } else { processRow(row, tm); } } } public void processSheet(XSSFSheet sheet, TopicMap tm) { Iterator<Row> rowIterator = sheet.iterator(); boolean isFirst = true; occurrenceTypes = new HashMap<>(); while(rowIterator.hasNext() && !forceStop()) { Row row = rowIterator.next(); if(isFirst && FIRST_ROW_CONTAINS_OCCURRENCE_TYPES) { processRowAsOccurrenceTypes(row, tm); isFirst = false; } else { processRow(row, tm); } } } public void processRow(Row row, TopicMap tm) { try { Iterator<Cell> cellIterator = row.cellIterator(); Topic topic = null; Cell firstCell = row.getCell(0); if(getCellValueAsString(firstCell) != null) { topic = getCellTopic(firstCell, tm); } if(topic != null) { while(cellIterator.hasNext() && !forceStop()) { Cell cell = cellIterator.next(); if(cell.getColumnIndex() > 0) { String occurrence = getCellValueAsString(cell); if(occurrence != null) { Topic type = null; String typeSI = occurrenceTypes.get(Integer.toString(cell.getColumnIndex())); if(typeSI != null) type = tm.getTopic(typeSI); if(type == null) type = getDefaultOccurrenceTypeTopic(cell, tm); topic.setData(type, tm.getTopic(XTMPSI.getLang(DEFAULT_LANG)), occurrence); } } } } } catch (TopicMapException ex) { log(ex); } catch (Exception ex) { log(ex); } } public void processRowAsOccurrenceTypes(Row row, TopicMap topicMap) { Iterator<Cell> cellIterator = row.cellIterator(); while(cellIterator.hasNext()) { try { Cell cell = cellIterator.next(); if(getCellValueAsString(cell) != null) { Topic cellTopic = getCellTopic(cell, topicMap); occurrenceTypes.put(Integer.toString(cell.getColumnIndex()), cellTopic.getOneSubjectIdentifier().toExternalForm()); } } catch (TopicMapException ex) { log(ex); } catch (Exception ex) { log(ex); } } } // ------------------------------------------------------------------------- public Topic getDefaultOccurrenceTypeTopic(Cell cell, TopicMap tm) { if(cell != null && tm != null) { int i = cell.getColumnIndex(); Topic typeTopic = getOrCreateTopic(tm, DEFAULT_OCCURRENCE_TYPE_SI+"/"+i, "Excel occurrence type "+i); return typeTopic; } return null; } // ------------------------------------------------------------------------- // ---------------------------------------------------------- CONFIGURE ---- // ------------------------------------------------------------------------- @Override public boolean isConfigurable() { return true; } @Override public void configure(Wandora wandora,org.wandora.utils.Options options,String prefix) throws TopicMapException { GenericOptionsDialog god=new GenericOptionsDialog(wandora,"Excel topic occurrence extractor options","Excel topic occurrence extractor options",true,new String[][]{ new String[]{"First row contains occurrence types?","boolean",(FIRST_ROW_CONTAINS_OCCURRENCE_TYPES ? "true" : "false"),null }, },wandora); god.setVisible(true); if(god.wasCancelled()) return; Map<String, String> values = god.getValues(); FIRST_ROW_CONTAINS_OCCURRENCE_TYPES = ("true".equals(values.get("First row contains occurrence types?")) ? true : false ); } }
7,448
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ExcelAdjacencyMatrixExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/excel/ExcelAdjacencyMatrixExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.excel; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.wandora.application.Wandora; import org.wandora.application.tools.GenericOptionsDialog; import org.wandora.topicmap.Association; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author akivela */ public class ExcelAdjacencyMatrixExtractor extends AbstractExcelExtractor { private static final long serialVersionUID = 1L; public static boolean ADD_CELL_VALUE_AS_PLAYER = false; public static boolean ADD_CELL_COLOR_AS_PLAYER = false; public static boolean INTERPRET_FALSE_AS_EMPTY_CELL = true; public static boolean INTERPRET_ZERO_AS_EMPTY_CELL = true; public static boolean INTERPRET_ZERO_LENGTH_STRING_AS_EMPTY_CELL = true; public static boolean INTERPRET_COLOR_AS_VALID_CELL_VALUE = false; public static boolean USE_SHEET_AS_ASSOCIATION_TYPE = true; private Map<String,String> columnLabels = new LinkedHashMap<>(); private Map<String,String> rowLabels = new LinkedHashMap<>(); @Override public String getName(){ return "Excel adjacency matrix extractor"; } @Override public String getDescription(){ return "Excel adjacency matrix extractor interprets Excel sheet as an adjacency matrix."; } @Override public void processWorkbook(HSSFWorkbook workbook, TopicMap topicMap) { int numberOfSheets = workbook.getNumberOfSheets(); for(int i=0; i<numberOfSheets && !forceStop(); i++) { HSSFSheet sheet = workbook.getSheetAt(i); processSheet(sheet, topicMap); } } @Override public void processWorkbook(XSSFWorkbook workbook, TopicMap topicMap) { int numberOfSheets = workbook.getNumberOfSheets(); for(int i=0; i<numberOfSheets && !forceStop(); i++) { XSSFSheet sheet = workbook.getSheetAt(i); processSheet(sheet, topicMap); } } public void processSheet(HSSFSheet sheet, TopicMap tm) { Iterator<Row> rowIterator = sheet.iterator(); boolean isFirst = true; columnLabels = new LinkedHashMap<>(); rowLabels = new LinkedHashMap<>(); while(rowIterator.hasNext() && !forceStop()) { Row row = rowIterator.next(); if(isFirst) { processAsLabels(row, tm); isFirst = false; } else { processRow(row, tm); } } } public void processSheet(XSSFSheet sheet, TopicMap tm) { Iterator<Row> rowIterator = sheet.iterator(); boolean isFirst = true; columnLabels = new LinkedHashMap<>(); rowLabels = new LinkedHashMap<>(); while(rowIterator.hasNext() && !forceStop()) { Row row = rowIterator.next(); if(isFirst) { processAsLabels(row, tm); isFirst = false; } else { processRow(row, tm); } } } public void processRow(Row row, TopicMap tm) { Association a = null; try { Cell firstColumnCell = row.getCell(0); if(firstColumnCell != null) { if(getCellValueAsString(firstColumnCell) != null) { Topic cellTopic = getCellTopic(firstColumnCell, tm); rowLabels.put(Integer.toString(firstColumnCell.getRowIndex()), cellTopic.getOneSubjectIdentifier().toExternalForm()); } else { return; } } Iterator<Cell> cellIterator = row.cellIterator(); while(cellIterator.hasNext() && !forceStop()) { Cell cell = cellIterator.next(); if(cell.getColumnIndex() > 0) { processCell(cell, tm); } } } catch (TopicMapException ex) { log(ex); } catch (Exception ex) { log(ex); } } public void processCell(Cell cell, TopicMap tm) { if(cell != null) { try { String rowLabel = rowLabels.get(Integer.toString(cell.getRowIndex())); String columnLabel = columnLabels.get(Integer.toString(cell.getColumnIndex())); if(rowLabel != null && columnLabel != null) { if(hasValue(cell)) { Topic rowTopic = tm.getTopic(rowLabel); Topic columnTopic = tm.getTopic(columnLabel); if(rowTopic != null && columnTopic != null) { Association a = tm.createAssociation(getAssociationTypeTopic(cell, tm)); a.addPlayer(rowTopic, getRowTypeTopic(tm)); a.addPlayer(columnTopic, getColumnTypeTopic(tm)); if(ADD_CELL_VALUE_AS_PLAYER) { Topic cellTopic = getCellTopic(cell, tm); Topic cellType = getCellTypeTopic(tm); if(cellTopic != null && cellType != null) { a.addPlayer(cellTopic, cellType); } } if(ADD_CELL_COLOR_AS_PLAYER) { Topic cellColorTopic = getColorTopic(cell, tm); Topic cellType = getColorTypeTopic(tm); if(cellColorTopic != null && cellType != null) { a.addPlayer(cellColorTopic, cellType); } } } } } } catch(Exception e) { log(e); } } } private Topic getAssociationTypeTopic(Cell cell, TopicMap tm) throws TopicMapException { if(USE_SHEET_AS_ASSOCIATION_TYPE) { return getDefaultAssociationTypeTopic(tm); } else { return getSheetTopic(cell, tm); } } public void processAsLabels(Row row, TopicMap topicMap) { Iterator<Cell> cellIterator = row.cellIterator(); while(cellIterator.hasNext()) { try { Cell cell = cellIterator.next(); if(getCellValueAsString(cell) != null) { Topic cellTopic = getCellTopic(cell, topicMap); columnLabels.put(Integer.toString(cell.getColumnIndex()), cellTopic.getOneSubjectIdentifier().toExternalForm()); } } catch (TopicMapException ex) { log(ex); } catch (Exception ex) { log(ex); } } } public boolean hasValue(Cell cell) { if(ADD_CELL_COLOR_AS_PLAYER || INTERPRET_COLOR_AS_VALID_CELL_VALUE) { CellStyle style = cell.getCellStyle(); short color = style.getFillBackgroundColor(); if(color != 0) { return true; } } String str = getCellValueAsString(cell); if(str == null) return false; if(INTERPRET_FALSE_AS_EMPTY_CELL && "false".equalsIgnoreCase(str)) return false; if(INTERPRET_ZERO_AS_EMPTY_CELL && "0".equalsIgnoreCase(str)) return false; if(INTERPRET_ZERO_LENGTH_STRING_AS_EMPTY_CELL && "".equalsIgnoreCase(str)) return false; return true; } // ------------------------------------------------------------------------- // ---------------------------------------------------------- CONFIGURE ---- // ------------------------------------------------------------------------- @Override public boolean isConfigurable() { return true; } @Override public void configure(Wandora wandora,org.wandora.utils.Options options,String prefix) throws TopicMapException { GenericOptionsDialog god=new GenericOptionsDialog(wandora,"Excel adjacency matrix extractor options","Excel adjacency matrix extractor options",true,new String[][]{ new String[]{"Interpret false as empty cell?","boolean",(INTERPRET_FALSE_AS_EMPTY_CELL ? "true" : "false"),null }, new String[]{"Interpret zero character (0) as empty cell?","boolean",(INTERPRET_ZERO_AS_EMPTY_CELL ? "true" : "false"),null }, new String[]{"Interpret zero length string as empty cell?","boolean",(INTERPRET_ZERO_LENGTH_STRING_AS_EMPTY_CELL ? "true" : "false"),null }, new String[]{"Interpret background color as nonempty cell?","boolean",(INTERPRET_COLOR_AS_VALID_CELL_VALUE ? "true" : "false"),null }, new String[]{"Add cell's background color to association as player?","boolean",(ADD_CELL_COLOR_AS_PLAYER ? "true" : "false"),null }, new String[]{"Add cell's value to association as player?","boolean",(ADD_CELL_VALUE_AS_PLAYER ? "true" : "false"),null }, new String[]{"Use sheet as an association type?","boolean",(USE_SHEET_AS_ASSOCIATION_TYPE ? "true" : "false"),null }, },wandora); god.setVisible(true); if(god.wasCancelled()) return; Map<String, String> values = god.getValues(); INTERPRET_FALSE_AS_EMPTY_CELL = ("true".equals(values.get("Interpret false as empty cell?")) ? true : false ); INTERPRET_ZERO_AS_EMPTY_CELL = ("true".equals(values.get("Interpret zero character (0) as empty cell?")) ? true : false ); INTERPRET_ZERO_LENGTH_STRING_AS_EMPTY_CELL = ("true".equals(values.get("Interpret zero length string as empty cell?")) ? true : false ); INTERPRET_COLOR_AS_VALID_CELL_VALUE = ("true".equals(values.get("Interpret background color as nonempty cell?")) ? true : false ); ADD_CELL_COLOR_AS_PLAYER = ("true".equals(values.get("Add cell's background color to association as player?")) ? true : false ); ADD_CELL_VALUE_AS_PLAYER = ("true".equals(values.get("Add cell's value to association as player?")) ? true : false ); USE_SHEET_AS_ASSOCIATION_TYPE = ("true".equals(values.get("Use sheet as an association type?")) ? true : false ); } }
11,775
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ExcelTopicNameExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/excel/ExcelTopicNameExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.excel; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.wandora.application.Wandora; import org.wandora.application.tools.GenericOptionsDialog; 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 akivela */ public class ExcelTopicNameExtractor extends AbstractExcelExtractor { private static final long serialVersionUID = 1L; public static boolean FIRST_ROW_CONTAINS_LANGUAGES = true; public static boolean CREATE_MISSING_LANGUAGE_TOPICS = true; public static boolean ADD_DISPLAY_TO_SCOPE = true; public static boolean ADD_SORT_TO_SCOPE = false; private Map<String,String> languagesPerColumn = new HashMap<>(); @Override public String getName(){ return "Excel topic name extractor"; } @Override public String getDescription(){ return "Excel topic name extractor extracts variant names for first column topics."; } @Override public void processWorkbook(HSSFWorkbook workbook, TopicMap topicMap) { int numberOfSheets = workbook.getNumberOfSheets(); for(int i=0; i<numberOfSheets && !forceStop(); i++) { HSSFSheet sheet = workbook.getSheetAt(i); processSheet(sheet, topicMap); } } @Override public void processWorkbook(XSSFWorkbook workbook, TopicMap topicMap) { int numberOfSheets = workbook.getNumberOfSheets(); for(int i=0; i<numberOfSheets && !forceStop(); i++) { XSSFSheet sheet = workbook.getSheetAt(i); processSheet(sheet, topicMap); } } public void processSheet(HSSFSheet sheet, TopicMap tm) { Iterator<Row> rowIterator = sheet.iterator(); boolean isFirst = true; languagesPerColumn = new HashMap<>(); while(rowIterator.hasNext() && !forceStop()) { Row row = rowIterator.next(); if(isFirst && FIRST_ROW_CONTAINS_LANGUAGES) { processRowAsLanguages(row, tm); isFirst = false; } else { processRow(row, tm); } } } public void processSheet(XSSFSheet sheet, TopicMap tm) { Iterator<Row> rowIterator = sheet.iterator(); boolean isFirst = true; languagesPerColumn = new HashMap<>(); while(rowIterator.hasNext() && !forceStop()) { Row row = rowIterator.next(); if(isFirst && FIRST_ROW_CONTAINS_LANGUAGES) { processRowAsLanguages(row, tm); isFirst = false; } else { processRow(row, tm); } } } public void processRow(Row row, TopicMap tm) { try { Iterator<Cell> cellIterator = row.cellIterator(); Topic topic = null; Cell firstCell = row.getCell(0); if(getCellValueAsString(firstCell) != null) { topic = getCellTopic(firstCell, tm); } if(topic != null) { while(cellIterator.hasNext() && !forceStop()) { Cell cell = cellIterator.next(); if(cell.getColumnIndex() != 0) { String name = getCellValueAsString(cell); if(name != null) { String langSI = languagesPerColumn.get(Integer.toString(cell.getColumnIndex())); Topic lang = tm.getTopic(langSI); if(lang == null) lang = getDefaultLanguageTopic(cell, tm); Set<Topic> scope = new LinkedHashSet<>(); scope.add(lang); if(ADD_DISPLAY_TO_SCOPE) scope.add(tm.getTopic(XTMPSI.DISPLAY)); if(ADD_SORT_TO_SCOPE) scope.add(tm.getTopic(XTMPSI.SORT)); topic.setVariant(scope, name); } } } } } catch (TopicMapException ex) { log(ex); } catch (Exception ex) { log(ex); } } public void processRowAsLanguages(Row row, TopicMap tm) { Iterator<Cell> cellIterator = row.cellIterator(); while(cellIterator.hasNext()) { try { String langSI = null; Cell cell = cellIterator.next(); String lang = getCellValueAsString(cell); if(lang != null) { Topic langTopic = tm.getTopicWithBaseName(lang); if(langTopic != null) langSI = langTopic.getOneSubjectIdentifier().toExternalForm(); else langSI = XTMPSI.getLang(lang); langTopic = tm.getTopic(new Locator(langSI)); languagesPerColumn.put(Integer.toString(cell.getColumnIndex()), langSI); if(langTopic == null && CREATE_MISSING_LANGUAGE_TOPICS) { langTopic = tm.createTopic(); langTopic.addSubjectIdentifier(new Locator(langSI)); Topic langTypeTopic = tm.getTopic(XTMPSI.LANGUAGE); if(langTypeTopic != null) { langTopic.addType(langTypeTopic); } } } } catch (Exception ex) { log(ex); } } } // ------------------------------------------------------------------------- public static String DEFAULT_LANGUAGE_SI = EXCEL_SI_PREFIX + "/language"; public Topic getDefaultLanguageTopic(Cell cell, TopicMap tm) { if(cell != null && tm != null) { int i = cell.getColumnIndex(); Topic typeTopic = getOrCreateTopic(tm, DEFAULT_LANGUAGE_SI+"/"+i, "Excel language "+i); return typeTopic; } return null; } // ------------------------------------------------------------------------- // ---------------------------------------------------------- CONFIGURE ---- // ------------------------------------------------------------------------- @Override public boolean isConfigurable() { return true; } @Override public void configure(Wandora wandora,org.wandora.utils.Options options,String prefix) throws TopicMapException { GenericOptionsDialog god=new GenericOptionsDialog(wandora,"Excel topic name extractor options","Excel topic name extractor options",true,new String[][]{ new String[]{"First row contains languages?","boolean",(FIRST_ROW_CONTAINS_LANGUAGES ? "true" : "false"),null }, new String[]{"Create display names?","boolean",(ADD_DISPLAY_TO_SCOPE ? "true" : "false"),null }, new String[]{"Create sort names?","boolean",(ADD_SORT_TO_SCOPE ? "true" : "false"),null }, },wandora); god.setVisible(true); if(god.wasCancelled()) return; Map<String, String> values = god.getValues(); FIRST_ROW_CONTAINS_LANGUAGES = ("true".equals(values.get("First row contains languages?")) ? true : false ); ADD_DISPLAY_TO_SCOPE = ("true".equals(values.get("Create display names?")) ? true : false ); ADD_SORT_TO_SCOPE = ("true".equals(values.get("Create sort names?")) ? true : false ); } }
8,913
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ExcelExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/excel/ExcelExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.excel; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.swing.Icon; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.wandora.application.WandoraToolType; import org.wandora.application.gui.UIBox; import org.wandora.application.tools.extractors.AbstractExtractor; import org.wandora.topicmap.TopicMap; /** * * @author akivela */ public class ExcelExtractor extends AbstractExtractor { private static final long serialVersionUID = 1L; @Override public String getName() { return "Excel extractor"; } @Override public String getDescription() { return "Excel extractor enables sheet specific Excel extractor."; } @Override public WandoraToolType getType() { return WandoraToolType.createExtractType(); } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_excel.png"); } @Override public boolean runInOwnThread(){ return true; } @Override public boolean useTempTopicMap(){ return false; } @Override public boolean useURLCrawler() { return false; } @Override public int getExtractorType() { return FILE_EXTRACTOR | URL_EXTRACTOR; } // ------------------------------------------------------------------------- @Override public boolean _extractTopicsFrom(URL u, TopicMap tm) throws Exception { try { HSSFWorkbook workbook = new HSSFWorkbook(u.openStream()); ExcelExtractorUI ui = new ExcelExtractorUI(); ui.open(getSheets(workbook), getExtractors()); if(ui.wasAccepted()) { String[] extractors = ui.getExtractors(); int numberOfSheets = workbook.getNumberOfSheets(); for(int i=0; i<numberOfSheets && !forceStop(); i++) { String sheetName = workbook.getSheetName(i); AbstractExcelExtractor extractor = getExcelExtractorFor(extractors[i]); if(extractor != null) { log("Applying '"+extractor.getName()+"' to sheet '"+sheetName+"'."); extractor.setToolLogger(getDefaultLogger()); extractor.processSheet(workbook.getSheetAt(i), tm); } else { log("Leaving sheet '"+sheetName+"' unprocessed."); } } } else { log("Extraction cancelled."); } log("Ok!"); } catch (FileNotFoundException ex) { log(ex); } catch (IOException ex) { log(ex); } catch (Exception ex) { log(ex); } setState(WAIT); return true; } @Override public boolean _extractTopicsFrom(String str, TopicMap t) throws Exception { return false; } @Override public boolean _extractTopicsFrom(File f, TopicMap tm) throws Exception { try { if(f != null) { String fn = f.getAbsolutePath(); if(fn.toLowerCase().endsWith(".xls")) { HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(f)); ExcelExtractorUI ui = new ExcelExtractorUI(); ui.open(getSheets(workbook), getExtractors()); if(ui.wasAccepted()) { String[] extractors = ui.getExtractors(); int numberOfSheets = workbook.getNumberOfSheets(); for(int i=0; i<numberOfSheets && !forceStop(); i++) { String sheetName = workbook.getSheetName(i); AbstractExcelExtractor extractor = getExcelExtractorFor(extractors[i]); if(extractor != null) { log("Applying '"+extractor.getName()+"' to sheet '"+sheetName+"'."); extractor.setToolLogger(getDefaultLogger()); extractor.processSheet(workbook.getSheetAt(i), tm); } else { log("Leaving sheet '"+sheetName+"' unprocessed."); } } } else { log("Extraction cancelled."); } } else { XSSFWorkbook workbook = new XSSFWorkbook(f.getAbsolutePath()); ExcelExtractorUI ui = new ExcelExtractorUI(); ui.open(getSheets(workbook), getExtractors()); if(ui.wasAccepted()) { String[] extractors = ui.getExtractors(); int numberOfSheets = workbook.getNumberOfSheets(); for(int i=0; i<numberOfSheets && !forceStop(); i++) { String sheetName = workbook.getSheetName(i); AbstractExcelExtractor extractor = getExcelExtractorFor(extractors[i]); if(extractor != null) { log("Applying '"+extractor.getName()+"' to sheet '"+sheetName+"'."); extractor.setToolLogger(getDefaultLogger()); extractor.processSheet(workbook.getSheetAt(i), tm); } else { log("Leaving sheet '"+sheetName+"' unprocessed."); } } } else { log("Extraction cancelled."); } } log("Ok!"); } } catch (FileNotFoundException ex) { log(ex); } catch (IOException ex) { log(ex); } catch (Exception ex) { log(ex); } setState(WAIT); return true; } public Collection<String> getSheets(HSSFWorkbook workbook) { List<String> sheets = new ArrayList<>(); int numberOfSheets = workbook.getNumberOfSheets(); for(int i=0; i<numberOfSheets && !forceStop(); i++) { sheets.add(workbook.getSheetName(i)); } return sheets; } public Collection<String> getSheets(XSSFWorkbook workbook) { List<String> sheets = new ArrayList<>(); int numberOfSheets = workbook.getNumberOfSheets(); for(int i=0; i<numberOfSheets && !forceStop(); i++) { sheets.add(workbook.getSheetName(i)); } return sheets; } public Collection<String> getExtractors() { List<String> extractors = new ArrayList<>(); extractors.add("-- Don't extract --"); extractors.add("Extract topics"); extractors.add("Extract adjacency list"); extractors.add("Extract adjacency matrix"); extractors.add("Extract association tree"); extractors.add("Extract variant names"); extractors.add("Extract occurrences"); return extractors; } public AbstractExcelExtractor getExcelExtractorFor(String extractorName) { if("Extract topics".equals(extractorName)) return new ExcelTopicExtractor(); if("Extract adjacency list".equals(extractorName)) return new ExcelAdjacencyListExtractor(); if("Extract adjacency matrix".equals(extractorName)) return new ExcelAdjacencyMatrixExtractor(); if("Extract association tree".equals(extractorName)) return new ExcelTopicTreeExtractor(); if("Extract variant names".equals(extractorName)) return new ExcelTopicNameExtractor(); if("Extract occurrences".equals(extractorName)) return new ExcelTopicOccurrenceExtractor(); else return null; } }
9,232
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AbstractMediaWikiAPIExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/mediawikiapi/AbstractMediaWikiAPIExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.mediawikiapi; import org.wandora.application.tools.extractors.AbstractExtractor; import org.wandora.application.tools.extractors.ExtractHelper; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.XTMPSI; import org.wandora.utils.language.LanguageBox; /** * * @author Eero */ abstract class AbstractMediaWikiAPIExtractor extends AbstractExtractor { private static final long serialVersionUID = 1L; protected static final String LANG_SI = "http://www.topicmaps.org/xtm/1.0/language.xtm#en"; protected static final String SI_ROOT = "http://wandora.org/si/mediawiki/api/"; protected static final String PAGE_SI = SI_ROOT + "page/"; protected static final String CONTENT_TYPE_SI = SI_ROOT + "content/"; // ------------------------------------------------------------------------- protected static Topic getMediaWikiClass(TopicMap tm) throws TopicMapException { Topic reddit = getOrCreateTopic(tm, SI_ROOT, "MediaWiki API"); makeSubclassOf(tm, reddit, getWandoraClassTopic(tm)); return reddit; } protected static Topic getWandoraClassTopic(TopicMap tm) throws TopicMapException { return getOrCreateTopic(tm, TMBox.WANDORACLASS_SI, "Wandora class"); } protected static Topic getOrCreateTopic(TopicMap tm, String si) throws TopicMapException { return getOrCreateTopic(tm, si, null); } protected static Topic getOrCreateTopic(TopicMap tm, String si, String bn) throws TopicMapException { return ExtractHelper.getOrCreateTopic(si, bn, tm); } protected static void makeSubclassOf(TopicMap tm, Topic t, Topic superclass) throws TopicMapException { ExtractHelper.makeSubclassOf(t, superclass, tm); } protected static Topic getLangTopic(TopicMap tm) throws TopicMapException { return getOrCreateTopic(tm, LANG_SI); } protected static Topic getLangTopic(TopicMap tm, String lang) throws TopicMapException{ Topic t = tm.getTopic(XTMPSI.getLang(lang)); if(t == null){ t = LanguageBox.createTopicForLanguageCode(lang, tm); } return t; } protected static Topic getContentTypeTopic(TopicMap tm) throws TopicMapException { return getOrCreateTopic(tm, CONTENT_TYPE_SI, "Content (MediaWiki API)"); } // ------------------------------------------------------------------------- }
3,449
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MediaWikiAPIPageExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/mediawikiapi/MediaWikiAPIPageExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.mediawikiapi; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.io.IOUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.wandora.application.WandoraToolLogger; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.JsonNode; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.http.exceptions.UnirestException; /** * * @author Eero */ public class MediaWikiAPIPageExtractor extends AbstractMediaWikiAPIExtractor{ private static final long serialVersionUID = 1L; private int nExtracted; private String baseURL; private String queryURL; private boolean crawlClasses; private String[] qType; private int progress; private WandoraToolLogger logger; MediaWikiAPIPageExtractor(String baseURL, String[] qType, boolean crawl){ super(); nExtracted = 0; this.baseURL = baseURL; this.qType = qType; this.crawlClasses = crawl; } @Override public boolean useURLCrawler() { return false; } @Override public boolean runInOwnThread(){ return false; } protected void setQueryUrl(String u){ this.queryURL = u; } protected String getBaseUrl(){ return this.baseURL; } protected String getQueryUrl(){ return this.queryURL; } protected void incrementExtractions(){ nExtracted++; } private final String[] contentTypes = new String[] { "text/plain", "text/json", "application/json" }; @Override public String[] getContentTypes() { return contentTypes; } @Override public boolean _extractTopicsFrom(File f, TopicMap t) throws Exception { throw new UnsupportedOperationException("Not supported."); } @Override public boolean _extractTopicsFrom(URL u, TopicMap t) throws Exception { return extractTopicsFromURL(u, t); } @Override public boolean _extractTopicsFrom(String str, TopicMap t) throws Exception { return extractTopicsFromString(str, t); } private boolean extractTopicsFromString(String str, TopicMap t){ String[] titles = str.split(","); List<String> titleList = Arrays.asList(titles); for(String title : titleList){ try { parsePage(title,t); } catch (Exception e) { log(e); } } return true; } private boolean extractTopicsFromURL(URL u, TopicMap t){ HttpResponse<JsonNode> resp; JsonNode body; JSONObject contObject; boolean shouldContinue; try { resp = Unirest.get(u.toExternalForm()) .header("accept", "application/json") .asJson(); body = resp.getBody(); contObject = parse(body.getObject(),t); String msg = "Extracted " + nExtracted + " pages in total.\n" + "Should we continue the extraction?"; try { if(contObject != null && !forceStop()) continueExtraction(contObject,t); } catch (Exception e) { log("Nothing more to extract"); } } catch (Exception e) { e.printStackTrace(); log(e.getMessage()); return false; } return true; } private void continueExtraction(JSONObject contObject, TopicMap t) throws Exception{ String typeName = qType[0], typePrefix = qType[1]; String cont; if(contObject.has(typeName)){ cont = "&" + typePrefix + "from=" + contObject.getJSONObject(typeName).getString(typePrefix + "from"); } else if(contObject.has(typePrefix + "continue")){ cont = "&" + typePrefix + "continue=" + contObject.getString(typePrefix + "continue"); } else { throw new Exception("Failed to get the continuation parameter"); } System.out.println(this.queryURL + cont); URL u = new URL(this.queryURL + cont); extractTopicsFromURL(u,t); } private JSONObject parse(JSONObject body, TopicMap tm) throws JSONException, TopicMapException, IOException{ logger = getDefaultLogger(); progress = 0; if(body.has("error")){ printError(body); return null; } if(body.has("warnings")) printWarnings(body); JSONObject query = body.getJSONObject("query"); JSONArray pages = null; String typeName = qType[0], typePrefix = qType[1]; if(query.has(typeName)) pages = query.getJSONArray(typeName); if(pages == null) throw new JSONException("No suitable data in JSON"); JSONObject page; logger.setProgressMax(pages.length()); logger.setProgress(0); for (int i = 0; i < pages.length(); i++) { if(forceStop()) break; page = pages.getJSONObject(i); parsePage(page,tm); } if(body.has("query-continue")) return body.getJSONObject("query-continue"); else if(body.has("continue")) return body.getJSONObject("continue"); return null; } private void parsePage(JSONObject page, TopicMap tm) throws JSONException, TopicMapException, IOException{ String title = page.getString("title"); parsePage(title,tm); } private void parsePage(String title, TopicMap tm) throws JSONException, TopicMapException, IOException{ log("Adding page #" + (nExtracted+1) + ": \"" + title + "\""); HashMap<String,String> info = getArticleInfo(title); String body = getArticleBody(title); List<String> classes = getArticleClasses(title); if(info == null || body == null){ log("Failed to get page: " + title); return; } String lang = (info.containsKey("pagelanguage")) ? info.get("pagelanguage") : "en"; Topic mediaWikiClass = getMediaWikiClass(tm); Topic langTopic = getLangTopic(tm,lang); Topic typeTopic = getContentTypeTopic(tm); Topic pageTopic = getOrCreateTopic(tm, info.get("fullurl") , title); pageTopic.setSubjectLocator(new Locator(info.get("fullurl"))); makeSubclassOf(tm, pageTopic, mediaWikiClass); if(this.crawlClasses && classes != null){ for(String articleClass: classes){ HashMap<String,String> classInfo = getArticleInfo(articleClass); String classURL = classInfo.get("fullurl"); Topic classTopic = getOrCreateTopic(tm, classURL, articleClass); makeSubclassOf(tm,classTopic,mediaWikiClass); makeSubclassOf(tm, pageTopic, classTopic); } } pageTopic.setData(typeTopic, langTopic, body); this.incrementExtractions(); getDefaultLogger().setProgress(progress++); } private String getArticleBody(String title) throws IOException{ StringBuilder queryBuilder = new StringBuilder(this.baseURL) .append("/index.php?action=raw&title=") .append(URLEncoder.encode(title)); HttpResponse<InputStream> resp; try { resp = Unirest.get(queryBuilder.toString()) .header("accept", "text/x-wiki") .asBinary(); } catch (UnirestException ex) { throw new IOException(ex); } InputStream body = resp.getBody(); String bodyString = IOUtils.toString(body,"UTF-8"); return bodyString; } private HashMap<String,String> getArticleInfo(String title) throws IOException{ Map<String,Object> fields = new HashMap<String,Object>(); fields.put("action", "query"); fields.put("prop","info"); fields.put("format","json"); fields.put("inprop","url"); fields.put("titles",title); HttpResponse<JsonNode> resp; try { HashMap<String,String> info = new HashMap<String, String>(); try { resp = Unirest.post(this.baseURL + "/api.php") .fields(fields) .asJson(); } catch (UnirestException ex) { throw new IOException(ex); } JsonNode body = resp.getBody(); JSONObject bodyObject = body.getObject(); if(!bodyObject.has("query")) return null; JSONObject q = bodyObject.getJSONObject("query"); JSONObject pages = q.getJSONObject("pages"); Iterator<String> pageKeys = pages.keys(); while(pageKeys.hasNext()){ JSONObject page = pages.getJSONObject(pageKeys.next()); if(!page.getString("title").equals(title)) continue; Iterator<String> valueKeys = page.keys(); while(valueKeys.hasNext()){ String key = valueKeys.next(); info.put(key, page.get(key).toString()); } return info; } } catch (JSONException jse) { jse.printStackTrace(); log(jse.getMessage()); } return null; } private List<String> getArticleClasses(String title) throws IOException{ Map<String,Object> fields = new HashMap<String,Object>(); fields.put("action", "query"); fields.put("prop","categories"); fields.put("format","json"); fields.put("cllimit","100"); fields.put("titles",title); HttpResponse<JsonNode> resp; try { try { resp = Unirest.post(this.baseURL + "/api.php") .fields(fields) .asJson(); } catch (UnirestException ex) { throw new IOException(ex); } JsonNode body = resp.getBody(); JSONObject bodyObject = body.getObject(); if(!bodyObject.has("query")) return null; JSONObject q = bodyObject.getJSONObject("query"); JSONObject pages = q.getJSONObject("pages"); Iterator<String> pageKeys = pages.keys(); while(pageKeys.hasNext()){ JSONObject page = pages.getJSONObject(pageKeys.next()); if(!page.getString("title").equals(title)) continue; /* * Got the correct key (There should only be a single key anyway) */ if(!page.has("categories")) break; JSONArray categories = page.getJSONArray("categories"); List<String> categoryList = new ArrayList<String>(); for (int i = 0; i < categories.length(); i++) { JSONObject category = categories.getJSONObject(i); categoryList.add(category.getString("title")); } return categoryList; } } catch (JSONException jse) { jse.printStackTrace(); log(jse.getMessage()); } return null; } private void printError(JSONObject body) throws JSONException{ JSONObject e = body.getJSONObject("error"); log(e.getString("info")); } private void printWarnings(JSONObject body) throws JSONException{ JSONObject warnings = body.getJSONObject("warnings"); Iterator warningCategoryKeys = warnings.keys(); String categoryKey; JSONObject category; while(warningCategoryKeys.hasNext()){ categoryKey = (String)warningCategoryKeys.next(); category = warnings.getJSONObject(categoryKey); Iterator warningKeys = category.keys(); String warningKey; String warning; while(warningKeys.hasNext()){ warningKey = (String)warningKeys.next(); warning = category.getString(warningKey); log("warning of type " + categoryKey + ": " + warning); } } } }
14,280
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MediaWikiAPIExtractorUI.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/mediawikiapi/MediaWikiAPIExtractorUI.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.mediawikiapi; import java.awt.Component; import java.awt.event.KeyEvent; import java.util.ArrayList; 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.SimpleCheckBox; 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.SimpleTextArea; /** * * @author Eero */ public class MediaWikiAPIExtractorUI extends javax.swing.JPanel { private static final long serialVersionUID = 1L; private int LIMIT = 100; private String FORMAT = "json"; private boolean accepted = false; private JDialog dialog = null; private Context context = null; private Wandora wandora = null; /** * Creates new form MediaWikiAPIExtractorUI */ public MediaWikiAPIExtractorUI() { 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, 300); dialog.add(this); dialog.setTitle("MediaWiki API extractor"); UIBox.centerWindow(dialog, w); dialog.setVisible(true); } public WandoraTool[] getExtractors(MediaWikiAPIExtractor tool) throws Exception { WandoraTool wt; List<WandoraTool> wts = new ArrayList<>(); StringBuilder urlBuilder = new StringBuilder(); String baseUrl, extractUrl; String[] qType = new String[2]; baseUrl = urlField.getText(); boolean crawlClasses = classCrawlToggle.isSelected(); MediaWikiAPIPageExtractor ex= new MediaWikiAPIPageExtractor(baseUrl, qType, crawlClasses); //General parameters urlBuilder.append(baseUrl) .append("/api.php?action=query") .append("&format=") .append(FORMAT) .append("&continue="); //For legacy query continue Component selected = modeTabs.getSelectedComponent(); if(selected.equals(catergoryPanel)){ String category = categoryField.getText(); if(category.length() > 0){ qType[0] = "categorymembers"; qType[1] = "cm"; urlBuilder.append("&list=categorymembers&cmtitle="); if(category.length() < 9 || !category.substring(0, 9).equals("Category:")){ urlBuilder.append("Category:"); } urlBuilder.append(category) .append("&cmlimit=") .append(LIMIT); } else { qType[0] = "allpages"; qType[1] = "ap"; urlBuilder.append("&list=allpages") .append("&aplimit=") .append(LIMIT); } extractUrl = urlBuilder.toString(); ex.setForceUrls(new String[]{extractUrl}); } else if(selected.equals(prefixPanel)){ qType[0] = "allpages"; qType[1] = "ap"; urlBuilder.append("&list=allpages") .append("&apfrom=") .append(prefixField.getText()) .append("&aplimit=") .append(LIMIT); extractUrl = urlBuilder.toString(); ex.setForceUrls(new String[]{extractUrl}); } else if(selected.equals(searchPanel)){ qType[0] = "search"; qType[1] = "sr"; urlBuilder.append("&list=search") .append("&srsearch=") .append(searchField.getText()) .append("&srlimit=") .append(LIMIT); extractUrl = urlBuilder.toString(); ex.setForceUrls(new String[]{extractUrl}); } else if(selected.equals(titlePanel)){ ex.setForceContent(titleTextArea.getText()); } else { throw new Exception("Invalid panel!"); } ex.setQueryUrl(urlBuilder.toString()); wt = ex; wts.add(ex); 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; configPanel = new javax.swing.JPanel(); urlLabel = new javax.swing.JLabel(); urlField = new javax.swing.JTextField(); modeTabs = new SimpleTabbedPane(); catergoryPanel = new javax.swing.JPanel(); categoryDescription = new SimpleLabel(); categoryLabel = new SimpleLabel(); categoryField = new javax.swing.JTextField(); prefixPanel = new javax.swing.JPanel(); prefixDescription = new SimpleLabel(); prefixLabel = new SimpleLabel(); prefixField = new javax.swing.JTextField(); searchPanel = new javax.swing.JPanel(); searchLabel = new SimpleLabel(); searchField = new javax.swing.JTextField(); searchDescription = new SimpleLabel(); titlePanel = new javax.swing.JPanel(); titleDescription = new SimpleLabel(); titleScrollPane = new SimpleScrollPane(); titleTextArea = new SimpleTextArea(); description = new SimpleLabel(); buttonPanel = new javax.swing.JPanel(); FillerjPanel = new javax.swing.JPanel(); okButton = new SimpleButton(); cancelButton = new SimpleButton(); classCrawlToggle = new SimpleCheckBox(); setMinimumSize(new java.awt.Dimension(700, 150)); setPreferredSize(new java.awt.Dimension(900, 150)); setLayout(new java.awt.GridBagLayout()); configPanel.setLayout(new java.awt.GridBagLayout()); urlLabel.setText("Instance URL: "); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.insets = new java.awt.Insets(4, 4, 0, 0); configPanel.add(urlLabel, gridBagConstraints); urlField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { urlFieldActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.ipadx = 311; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 0.1; gridBagConstraints.insets = new java.awt.Insets(4, 4, 0, 4); configPanel.add(urlField, gridBagConstraints); catergoryPanel.setLayout(new java.awt.GridBagLayout()); categoryDescription.setText("<html><head></head><body>Specify a category used to filter articles in the wiki. Leave blank to extract all articles in the wiki."); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START; gridBagConstraints.insets = new java.awt.Insets(8, 4, 0, 4); catergoryPanel.add(categoryDescription, gridBagConstraints); categoryLabel.setText("Category:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weighty = 0.1; gridBagConstraints.insets = new java.awt.Insets(6, 4, 0, 4); catergoryPanel.add(categoryLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 0.1; gridBagConstraints.weighty = 0.1; gridBagConstraints.insets = new java.awt.Insets(4, 0, 0, 4); catergoryPanel.add(categoryField, gridBagConstraints); modeTabs.addTab("Category", catergoryPanel); prefixPanel.setLayout(new java.awt.GridBagLayout()); prefixDescription.setText("<html><head></head><body>Specify a title prefix used to filter articles in the wiki. Leave blank to extract all articles in the wiki."); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START; gridBagConstraints.insets = new java.awt.Insets(8, 4, 0, 4); prefixPanel.add(prefixDescription, gridBagConstraints); prefixLabel.setText("Prefix:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weighty = 0.1; gridBagConstraints.insets = new java.awt.Insets(7, 4, 0, 4); prefixPanel.add(prefixLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 0.1; gridBagConstraints.weighty = 0.1; gridBagConstraints.insets = new java.awt.Insets(4, 0, 0, 4); prefixPanel.add(prefixField, gridBagConstraints); modeTabs.addTab("Prefix", prefixPanel); searchPanel.setLayout(new java.awt.GridBagLayout()); searchLabel.setText("Search:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(6, 4, 0, 4); searchPanel.add(searchLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 0.1; gridBagConstraints.weighty = 0.1; gridBagConstraints.insets = new java.awt.Insets(4, 0, 0, 4); searchPanel.add(searchField, gridBagConstraints); searchDescription.setText("<html><head></head><body>Specify a search term used to filter articles in the wiki. This is equivalent to the free text search available on the web page."); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START; gridBagConstraints.insets = new java.awt.Insets(8, 4, 0, 4); searchPanel.add(searchDescription, gridBagConstraints); modeTabs.addTab("Search", searchPanel); titlePanel.setLayout(new java.awt.GridBagLayout()); titleDescription.setText("<html><head></head><body>Use a comma separated list of article names to extract."); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START; gridBagConstraints.insets = new java.awt.Insets(8, 4, 0, 4); titlePanel.add(titleDescription, gridBagConstraints); titleTextArea.setColumns(20); titleTextArea.setRows(5); titleScrollPane.setViewportView(titleTextArea); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START; gridBagConstraints.weightx = 0.1; gridBagConstraints.weighty = 0.2; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); titlePanel.add(titleScrollPane, gridBagConstraints); modeTabs.addTab("Titles", titlePanel); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 0.1; gridBagConstraints.weighty = 0.1; configPanel.add(modeTabs, gridBagConstraints); description.setText("<html><head></head><body>Specify the URL where the wiki instance's api.php and index.php are reached. (http://en.wikipedia.org/w/ for the English Wikipedia) A few methods for filtering the articles to be extracted are presented below. Stub articles may be extracted for the article categories found for each article."); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); configPanel.add(description, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 0.1; gridBagConstraints.weighty = 0.1; add(configPanel, gridBagConstraints); buttonPanel.setMaximumSize(new java.awt.Dimension(116, 25)); buttonPanel.setMinimumSize(new java.awt.Dimension(116, 25)); buttonPanel.setPreferredSize(new java.awt.Dimension(116, 25)); buttonPanel.setLayout(new java.awt.GridBagLayout()); FillerjPanel.setMaximumSize(new java.awt.Dimension(0, 0)); javax.swing.GroupLayout FillerjPanelLayout = new javax.swing.GroupLayout(FillerjPanel); FillerjPanel.setLayout(FillerjPanelLayout); FillerjPanelLayout.setHorizontalGroup( FillerjPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); FillerjPanelLayout.setVerticalGroup( FillerjPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; buttonPanel.add(FillerjPanel, gridBagConstraints); okButton.setText("OK"); 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); } }); okButton.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { okButtonKeyReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 2); buttonPanel.add(okButton, gridBagConstraints); cancelButton.setText("Cancel"); 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); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 0; buttonPanel.add(cancelButton, gridBagConstraints); classCrawlToggle.setText("Crawl Article Categories"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; buttonPanel.add(classCrawlToggle, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); add(buttonPanel, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents private void urlFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_urlFieldActionPerformed // TODO add your handling code here: }//GEN-LAST:event_urlFieldActionPerformed private void okButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_okButtonMouseReleased accepted = true; if(dialog != null) dialog.setVisible(false); }//GEN-LAST:event_okButtonMouseReleased private void okButtonKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_okButtonKeyReleased accepted = true; if(evt.getKeyCode() == KeyEvent.VK_ENTER) { if(dialog != null) { dialog.setVisible(false); } } }//GEN-LAST:event_okButtonKeyReleased private void cancelButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cancelButtonMouseReleased accepted = false; if(dialog != null) dialog.setVisible(false); }//GEN-LAST:event_cancelButtonMouseReleased // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel FillerjPanel; private javax.swing.JPanel buttonPanel; private javax.swing.JButton cancelButton; private javax.swing.JLabel categoryDescription; private javax.swing.JTextField categoryField; private javax.swing.JLabel categoryLabel; private javax.swing.JPanel catergoryPanel; private javax.swing.JCheckBox classCrawlToggle; private javax.swing.JPanel configPanel; private javax.swing.JLabel description; private javax.swing.JTabbedPane modeTabs; private javax.swing.JButton okButton; private javax.swing.JLabel prefixDescription; private javax.swing.JTextField prefixField; private javax.swing.JLabel prefixLabel; private javax.swing.JPanel prefixPanel; private javax.swing.JLabel searchDescription; private javax.swing.JTextField searchField; private javax.swing.JLabel searchLabel; private javax.swing.JPanel searchPanel; private javax.swing.JLabel titleDescription; private javax.swing.JPanel titlePanel; private javax.swing.JScrollPane titleScrollPane; private javax.swing.JTextArea titleTextArea; private javax.swing.JTextField urlField; private javax.swing.JLabel urlLabel; // End of variables declaration//GEN-END:variables }
22,226
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MediaWikiAPIExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/mediawikiapi/MediaWikiAPIExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.mediawikiapi; 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 MediaWikiAPIExtractor extends AbstractWandoraTool{ private static final long serialVersionUID = 1L; private MediaWikiAPIExtractorUI ui = null; @Override public String getName() { return "MediaWiki API Extractor"; } @Override public String getDescription(){ return "Extracts topics and associations from MediaWiki API"; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_mediawiki.png"); } private final String[] contentTypes = new String[] { "text/plain", "text/json", "application/json" }; public String[] getContentTypes() { return contentTypes; } public boolean useURLCrawler() { return false; } @Override public void execute(Wandora wandora, Context context) { try { if(ui == null) { ui = new MediaWikiAPIExtractorUI(); } 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,context); c++; } catch(Exception e) { log(e); } } log("Ready."); } else { String msg = "Couldn't find a suitable subextractor to " + "perform or there was an error with an " + "extractor."; log(msg); } } } catch(Exception e) { singleLog(e); } finally { if(ui != null && ui.wasAccepted()) setState(WAIT); else setState(WAIT); } } }
3,657
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AbstractGeoNamesWeatherParser.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/geonames/AbstractGeoNamesWeatherParser.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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 AbstractGeoNamesWeatherParser 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 AbstractGeoNamesWeatherParser(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_OBSERVATION="observation"; private static final String TAG_OBSERVATIONTIME="observationTime"; private static final String TAG_STATIONNAME="stationName"; private static final String TAG_ICAO="ICAO"; private static final String TAG_COUNTRYCODE="countryCode"; private static final String TAG_ELEVATION="elevation"; private static final String TAG_LAT="lat"; private static final String TAG_LNG="lng"; private static final String TAG_TEMPERATURE="temperature"; private static final String TAG_DEWPOINT="dewPoint"; private static final String TAG_HUMIDITY="humidity"; private static final String TAG_CLOUDS="clouds"; private static final String TAG_WEATHERCONDITION="weatherCondition"; private static final String TAG_HECTOPASCALTIMETER="hectoPascAltimeter"; private static final String TAG_WINDDIRECTION="windDirection"; private static final String TAG_WINDSPEED="windSpeed"; 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_OBSERVATION=3; private static final int STATE_OBSERVATION_OBSERVATION=4; private static final int STATE_OBSERVATION_LAT=5; private static final int STATE_OBSERVATION_LNG=6; private static final int STATE_OBSERVATION_OBSERVATIONTIME=7; private static final int STATE_OBSERVATION_STATIONNAME=8; private static final int STATE_OBSERVATION_ICAO=9; private static final int STATE_OBSERVATION_COUNTRYCODE=10; private static final int STATE_OBSERVATION_ELEVATION=11; private static final int STATE_OBSERVATION_TEMPERATURE=12; private static final int STATE_OBSERVATION_DEWPOINT=13; private static final int STATE_OBSERVATION_HUMIDITY=14; private static final int STATE_OBSERVATION_CLOUDS=15; private static final int STATE_OBSERVATION_WEATHERCONDITION=16; private static final int STATE_OBSERVATION_HECTOPASCALTIMETER=17; private static final int STATE_OBSERVATION_WINDDIRECTION=18; private static final int STATE_OBSERVATION_WINDSPEED=19; private int state=STATE_START; protected String data_observation; protected String data_lat; protected String data_lng; protected String data_observationtime; protected String data_stationname; protected String data_icao; protected String data_countrycode; protected String data_elevation; protected String data_temperature; protected String data_dewpoint; protected String data_humidity; protected String data_clouds; protected String data_weathercondition; protected String data_hectopascaltimeter; protected String data_winddirection; protected String data_windspeed; public void setRequestGeoObject(String p) { requestGeoObject = p; } // ********** OVERRIDE THIS METHOD IN EXTENDING CLASSSES! ********** public abstract void handleObservationElement(); 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_OBSERVATION)) { data_observation = ""; data_lat = ""; data_lng = ""; data_observationtime = ""; data_stationname = ""; data_icao = ""; data_countrycode = ""; data_elevation = ""; data_temperature = ""; data_dewpoint = ""; data_humidity = ""; data_clouds = ""; data_weathercondition = ""; data_hectopascaltimeter = ""; data_winddirection = ""; data_windspeed = ""; state = STATE_OBSERVATION; } break; case STATE_OBSERVATION: if(qName.equals(TAG_OBSERVATION)) { state = STATE_OBSERVATION_OBSERVATION; data_observation = ""; } else if(qName.equals(TAG_LAT)) { state = STATE_OBSERVATION_LAT; data_lat = ""; } else if(qName.equals(TAG_LNG)) { state = STATE_OBSERVATION_LNG; data_lng = ""; } else if(qName.equals(TAG_OBSERVATIONTIME)) { state = STATE_OBSERVATION_OBSERVATIONTIME; data_observationtime = ""; } else if(qName.equals(TAG_COUNTRYCODE)) { state = STATE_OBSERVATION_COUNTRYCODE; data_countrycode = ""; } else if(qName.equals(TAG_STATIONNAME)) { state = STATE_OBSERVATION_STATIONNAME; data_stationname = ""; } else if(qName.equals(TAG_ICAO)) { state = STATE_OBSERVATION_ICAO; data_icao = ""; } else if(qName.equals(TAG_ELEVATION)) { state = STATE_OBSERVATION_ELEVATION; data_elevation = ""; } else if(qName.equals(TAG_TEMPERATURE)) { state = STATE_OBSERVATION_TEMPERATURE; data_temperature = ""; } else if(qName.equals(TAG_DEWPOINT)) { state = STATE_OBSERVATION_DEWPOINT; data_dewpoint = ""; } else if(qName.equals(TAG_HUMIDITY)) { state = STATE_OBSERVATION_HUMIDITY; data_humidity = ""; } else if(qName.equals(TAG_CLOUDS)) { state = STATE_OBSERVATION_CLOUDS; data_clouds = ""; } else if(qName.equals(TAG_WEATHERCONDITION)) { state = STATE_OBSERVATION_WEATHERCONDITION; data_weathercondition = ""; } else if(qName.equals(TAG_HECTOPASCALTIMETER)) { state = STATE_OBSERVATION_HECTOPASCALTIMETER; data_hectopascaltimeter = ""; } else if(qName.equals(TAG_WINDDIRECTION)) { state = STATE_OBSERVATION_WINDDIRECTION; data_winddirection = ""; } else if(qName.equals(TAG_WINDSPEED)) { state = STATE_OBSERVATION_WINDSPEED; data_windspeed = ""; } break; } } public void endElement(String uri, String localName, String qName) throws SAXException { switch(state) { case STATE_OBSERVATION: { if(TAG_OBSERVATION.equals(qName)) { handleObservationElement(); 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_OBSERVATION_OBSERVATION: { if(TAG_OBSERVATION.equals(qName)) state=STATE_OBSERVATION; break; } case STATE_OBSERVATION_LAT: { if(TAG_LAT.equals(qName)) state=STATE_OBSERVATION; break; } case STATE_OBSERVATION_LNG: { if(TAG_LNG.equals(qName)) state=STATE_OBSERVATION; break; } case STATE_OBSERVATION_OBSERVATIONTIME: { if(TAG_OBSERVATIONTIME.equals(qName)) state=STATE_OBSERVATION; break; } case STATE_OBSERVATION_COUNTRYCODE: { if(TAG_COUNTRYCODE.equals(qName)) state=STATE_OBSERVATION; break; } case STATE_OBSERVATION_STATIONNAME: { if(TAG_STATIONNAME.equals(qName)) state=STATE_OBSERVATION; break; } case STATE_OBSERVATION_ICAO: { if(TAG_ICAO.equals(qName)) state=STATE_OBSERVATION; break; } case STATE_OBSERVATION_ELEVATION: { if(TAG_ELEVATION.equals(qName)) state=STATE_OBSERVATION; break; } case STATE_OBSERVATION_TEMPERATURE: { if(TAG_TEMPERATURE.equals(qName)) state=STATE_OBSERVATION; break; } case STATE_OBSERVATION_DEWPOINT: { if(TAG_DEWPOINT.equals(qName)) state=STATE_OBSERVATION; break; } case STATE_OBSERVATION_HUMIDITY: { if(TAG_HUMIDITY.equals(qName)) state=STATE_OBSERVATION; break; } case STATE_OBSERVATION_CLOUDS: { if(TAG_CLOUDS.equals(qName)) state=STATE_OBSERVATION; break; } case STATE_OBSERVATION_WEATHERCONDITION: { if(TAG_WEATHERCONDITION.equals(qName)) state=STATE_OBSERVATION; break; } case STATE_OBSERVATION_HECTOPASCALTIMETER: { if(TAG_HECTOPASCALTIMETER.equals(qName)) state=STATE_OBSERVATION; break; } case STATE_OBSERVATION_WINDDIRECTION: { if(TAG_WINDDIRECTION.equals(qName)) state=STATE_OBSERVATION; break; } case STATE_OBSERVATION_WINDSPEED: { if(TAG_WINDSPEED.equals(qName)) state=STATE_OBSERVATION; break; } } } public void characters(char[] ch, int start, int length) throws SAXException { switch(state){ case STATE_OBSERVATION_OBSERVATION: data_observation+=new String(ch,start,length); break; case STATE_OBSERVATION_LAT: data_lat+=new String(ch,start,length); break; case STATE_OBSERVATION_LNG: data_lng+=new String(ch,start,length); break; case STATE_OBSERVATION_OBSERVATIONTIME: data_observationtime+=new String(ch,start,length); break; case STATE_OBSERVATION_COUNTRYCODE: data_countrycode+=new String(ch,start,length); break; case STATE_OBSERVATION_STATIONNAME: data_stationname+=new String(ch,start,length); break; case STATE_OBSERVATION_ICAO: data_icao+=new String(ch,start,length); break; case STATE_OBSERVATION_ELEVATION: data_elevation+=new String(ch,start,length); break; case STATE_OBSERVATION_TEMPERATURE: data_temperature+=new String(ch,start,length); break; case STATE_OBSERVATION_DEWPOINT: data_dewpoint+=new String(ch,start,length); break; case STATE_OBSERVATION_HUMIDITY: data_humidity+=new String(ch,start,length); break; case STATE_OBSERVATION_CLOUDS: data_clouds+=new String(ch,start,length); break; case STATE_OBSERVATION_WEATHERCONDITION: data_weathercondition+=new String(ch,start,length); break; case STATE_OBSERVATION_HECTOPASCALTIMETER: data_hectopascaltimeter+=new String(ch,start,length); break; case STATE_OBSERVATION_WINDDIRECTION: data_winddirection+=new String(ch,start,length); break; case STATE_OBSERVATION_WINDSPEED: data_windspeed+=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; } }
16,312
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
GeoNamesCountryInfo.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/geonames/GeoNamesCountryInfo.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * GeoNamesCountryInfo.java * * */ package org.wandora.application.tools.extractors.geonames; import java.io.InputStream; 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.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; /** * See http://ws.geonames.org/countryInfo?lang=en&country=FI&style=full * * @author akivela */ public class GeoNamesCountryInfo extends AbstractGeoNamesExtractor { private static final long serialVersionUID = 1L; public String dataLang = "en"; /** Creates a new instance of GeoNamesCountryInfo */ public GeoNamesCountryInfo() { } @Override public String getName() { return "GeoNames country info extractor"; } @Override public String getDescription(){ return "Get country data from geo names web api and convert the data to a topic map. "; } 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(); CountryInfoParser parserHandler = new CountryInfoParser(topicMap,this,dataLang); 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 countries found!"); else if(parserHandler.progress == 1) log("One country found!"); else log("Total " + parserHandler.progress + " countries found!"); return true; } // ------------------------------------------------------------------------- // --- GEONAMES XML FEED PARSER -------------------------------------------- // ------------------------------------------------------------------------- private static class CountryInfoParser implements org.xml.sax.ContentHandler, org.xml.sax.ErrorHandler { public CountryInfoParser(TopicMap tm, GeoNamesCountryInfo parent, String lang){ this.lang=lang; this.tm=tm; this.parent=parent; } private String lang = "en"; public int progress=0; private TopicMap tm; private GeoNamesCountryInfo parent; public static final String TAG_GEONAMES="geonames"; public static final String TAG_STATUS="status"; public static final String TAG_COUNTRY="country"; public static final String TAG_COUNTRYCODE="countryCode"; public static final String TAG_COUNTRYNAME="countryName"; public static final String TAG_ISONUMERIC="isoNumeric"; public static final String TAG_ISOALPHA3="isoAlpha3"; public static final String TAG_FIPSCODE="fipsCode"; public static final String TAG_CONTINENT="continent"; public static final String TAG_CAPITAL="capital"; public static final String TAG_AREAINSQKM="areaInSqKm"; public static final String TAG_POPULATION="population"; public static final String TAG_CURRENCYCODE="currencyCode"; public static final String TAG_LANGUAGES="languages"; public static final String TAG_GEONAMEID="geonameId"; public static final String TAG_BBOXWEST="bBoxWest"; public static final String TAG_BBOXNORTH="bBoxNorth"; public static final String TAG_BBOXEAST="bBoxEast"; public static final String TAG_BBOXSOUTH="bBoxSouth"; 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_COUNTRY=3; private static final int STATE_COUNTRY_COUNTRYCODE=4; private static final int STATE_COUNTRY_COUNTRYNAME=5; private static final int STATE_COUNTRY_ISONUMERIC=6; private static final int STATE_COUNTRY_ISOALPHA3=7; private static final int STATE_COUNTRY_FIPSCODE=8; private static final int STATE_COUNTRY_CONTINENT=9; private static final int STATE_COUNTRY_CAPITAL=10; private static final int STATE_COUNTRY_AREAINSQKM=11; private static final int STATE_COUNTRY_POPULATION=12; private static final int STATE_COUNTRY_CURRENCYCODE=13; private static final int STATE_COUNTRY_LANGUAGES=14; private static final int STATE_COUNTRY_GEONAMEID=15; private static final int STATE_COUNTRY_BBOXWEST=16; private static final int STATE_COUNTRY_BBOXNORTH=17; private static final int STATE_COUNTRY_BBOXEAST=18; private static final int STATE_COUNTRY_BBOXSOUTH=19; private int state=STATE_START; private String data_countrycode; private String data_countryname; private String data_isonumeric; private String data_isoalpha3; private String data_fipscode; private String data_continent; private String data_capital; private String data_areainsqkm; private String data_population; private String data_currencycode; private String data_languages; private String data_geonameid; private String data_bboxwest; private String data_bboxnorth; private String data_bboxeast; private String data_bboxsouth; private Topic theCountry; 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_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_COUNTRY)) { data_countrycode = ""; data_countryname = ""; data_isonumeric = ""; data_isoalpha3 = ""; data_fipscode = ""; data_continent = ""; data_capital = ""; data_areainsqkm = ""; data_population = ""; data_currencycode = ""; data_languages = ""; data_geonameid = ""; data_bboxwest = ""; data_bboxnorth = ""; data_bboxeast = ""; data_bboxsouth = ""; state = STATE_COUNTRY; } break; } case STATE_COUNTRY: if(qName.equals(TAG_COUNTRYCODE)) { state = STATE_COUNTRY_COUNTRYCODE; data_countrycode = ""; } else if(qName.equals(TAG_COUNTRYNAME)) { state = STATE_COUNTRY_COUNTRYNAME; data_countryname = ""; } else if(qName.equals(TAG_ISONUMERIC)) { state = STATE_COUNTRY_ISONUMERIC; data_isonumeric = ""; } else if(qName.equals(TAG_ISOALPHA3)) { state = STATE_COUNTRY_ISOALPHA3; data_isoalpha3= ""; } else if(qName.equals(TAG_FIPSCODE)) { state = STATE_COUNTRY_FIPSCODE; data_fipscode = ""; } else if(qName.equals(TAG_CONTINENT)) { state = STATE_COUNTRY_CONTINENT; data_continent = ""; } else if(qName.equals(TAG_CAPITAL)) { state = STATE_COUNTRY_CAPITAL; data_capital = ""; } else if(qName.equals(TAG_AREAINSQKM)) { state = STATE_COUNTRY_AREAINSQKM; data_areainsqkm = ""; } else if(qName.equals(TAG_POPULATION)) { state = STATE_COUNTRY_POPULATION; data_population = ""; } else if(qName.equals(TAG_CURRENCYCODE)) { state = STATE_COUNTRY_CURRENCYCODE; data_currencycode = ""; } else if(qName.equals(TAG_LANGUAGES)) { state = STATE_COUNTRY_LANGUAGES; data_languages = ""; } else if(qName.equals(TAG_GEONAMEID)) { state = STATE_COUNTRY_GEONAMEID; data_geonameid= ""; } else if(qName.equals(TAG_BBOXWEST)) { state = STATE_COUNTRY_BBOXWEST; data_bboxwest = ""; } else if(qName.equals(TAG_BBOXNORTH)) { state = STATE_COUNTRY_BBOXNORTH; data_bboxnorth = ""; } else if(qName.equals(TAG_BBOXEAST)) { state = STATE_COUNTRY_BBOXEAST; data_bboxeast = ""; } else if(qName.equals(TAG_BBOXSOUTH)) { state = STATE_COUNTRY_BBOXSOUTH; data_bboxsouth = ""; } break; } } public void endElement(String uri, String localName, String qName) throws SAXException { switch(state) { case STATE_COUNTRY: { if(TAG_COUNTRY.equals(qName)) { if(data_countrycode.length() > 0 || data_geonameid.length() > 0) { try { //Topic countryType=getCountryTypeTopic(tm); theCountry=getCountryTopic(tm, data_countrycode, data_geonameid, data_countryname, lang); String theCountrySI=theCountry.getOneSubjectIdentifier().toExternalForm(); parent.setProgress(progress++); try { if(isValid(data_continent)) { Topic continentTopic=getContinentTopic(tm, data_continent); if(theCountry.isRemoved()) theCountry=tm.getTopic(theCountrySI); makeGeoContinent(theCountry, continentTopic, tm); } if(isValid(data_capital)) { Topic capitalTopic=getCityTopic(tm, data_capital, lang); makeCountryCapital(theCountry, capitalTopic, tm); } if(isValid(data_bboxwest) && isValid(data_bboxnorth) && isValid(data_bboxeast) && isValid(data_bboxsouth)) { makeBoundingBox(theCountry, data_bboxnorth, data_bboxwest, data_bboxsouth, data_bboxeast, tm); } if(isValid(data_languages)) { String[] languages = data_languages.split(","); Topic lanType = getLanguageTypeTopic(tm); Topic geoObjectType = getGeoObjectTypeTopic(tm); if(theCountry.isRemoved()) theCountry=tm.getTopic(theCountrySI); if(languages.length > 0) { for(int i=0; i<languages.length; i++) { if(languages[i]!=null && languages[i].length()>0) { Topic languageTopic = getLanguageTopic(tm, languages[i]); if(languageTopic != null) { Association la = tm.createAssociation(lanType); la.addPlayer(languageTopic, lanType); la.addPlayer(theCountry, geoObjectType); } } } } } if(isValid(data_currencycode)) { Topic currencyType = getCurrencyTypeTopic(tm); Topic currencyTopic = getCurrencyTopic(tm, data_currencycode, lang); Topic geoObjectType = getGeoObjectTypeTopic(tm); if(currencyTopic != null && currencyType != null && !currencyTopic.isRemoved() && !currencyType.isRemoved()) { if(theCountry.isRemoved()) theCountry=tm.getTopic(theCountrySI); Association cura = tm.createAssociation(currencyType); cura.addPlayer(theCountry, geoObjectType); cura.addPlayer(currencyTopic, currencyType); } } if(isValid(data_population)) { Topic populationTypeTopic = getPopulationTypeTopic(tm); if(theCountry.isRemoved()) theCountry=tm.getTopic(theCountrySI); theCountry.setData(populationTypeTopic, TMBox.getLangTopic(theCountry, lang), data_population); } if(isValid(data_isoalpha3)) { if(theCountry.isRemoved()) theCountry=tm.getTopic(theCountrySI); theCountry.addSubjectIdentifier(new org.wandora.topicmap.Locator(createCountryAlpha3SI(data_isoalpha3))); } if(isValid(data_isonumeric)) { if(theCountry.isRemoved()) theCountry=tm.getTopic(theCountrySI); theCountry.addSubjectIdentifier(new org.wandora.topicmap.Locator(createCountryNumericSI(data_isonumeric))); } if(isValid(data_areainsqkm)) { Topic areaTypeTopic = getAreaTypeTopic(tm); if(theCountry.isRemoved()) theCountry=tm.getTopic(theCountrySI); theCountry.setData(areaTypeTopic, TMBox.getLangTopic(theCountry, lang), data_areainsqkm); } if(isValid(data_fipscode)) { if(theCountry.isRemoved()) theCountry=tm.getTopic(theCountrySI); theCountry.addSubjectIdentifier(new org.wandora.topicmap.Locator(createFIPSSI(data_fipscode))); } } catch(Exception e) { parent.log(e); } } catch(TopicMapException tme){ parent.log(tme); } } 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_COUNTRY_COUNTRYCODE: { if(TAG_COUNTRYCODE.equals(qName)) state=STATE_COUNTRY; break; } case STATE_COUNTRY_COUNTRYNAME: { if(TAG_COUNTRYNAME.equals(qName)) state=STATE_COUNTRY; break; } case STATE_COUNTRY_ISONUMERIC: { if(TAG_ISONUMERIC.equals(qName)) state=STATE_COUNTRY; break; } case STATE_COUNTRY_ISOALPHA3: { if(TAG_ISOALPHA3.equals(qName)) state=STATE_COUNTRY; break; } case STATE_COUNTRY_FIPSCODE: { if(TAG_FIPSCODE.equals(qName)) state=STATE_COUNTRY; break; } case STATE_COUNTRY_CONTINENT: { if(TAG_CONTINENT.equals(qName)) state=STATE_COUNTRY; break; } case STATE_COUNTRY_CAPITAL: { if(TAG_CAPITAL.equals(qName)) state=STATE_COUNTRY; break; } case STATE_COUNTRY_AREAINSQKM: { if(TAG_AREAINSQKM.equals(qName)) state=STATE_COUNTRY; break; } case STATE_COUNTRY_POPULATION: { if(TAG_POPULATION.equals(qName)) state=STATE_COUNTRY; break; } case STATE_COUNTRY_CURRENCYCODE: { if(TAG_CURRENCYCODE.equals(qName)) state=STATE_COUNTRY; break; } case STATE_COUNTRY_LANGUAGES: { if(TAG_LANGUAGES.equals(qName)) state=STATE_COUNTRY; break; } case STATE_COUNTRY_GEONAMEID: { if(TAG_GEONAMEID.equals(qName)) state=STATE_COUNTRY; break; } case STATE_COUNTRY_BBOXWEST: { if(TAG_BBOXWEST.equals(qName)) state=STATE_COUNTRY; break; } case STATE_COUNTRY_BBOXNORTH: { if(TAG_BBOXNORTH.equals(qName)) state=STATE_COUNTRY; break; } case STATE_COUNTRY_BBOXEAST: { if(TAG_BBOXEAST.equals(qName)) state=STATE_COUNTRY; break; } case STATE_COUNTRY_BBOXSOUTH: { if(TAG_BBOXSOUTH.equals(qName)) state=STATE_COUNTRY; break; } } } public void characters(char[] ch, int start, int length) throws SAXException { switch(state){ case STATE_COUNTRY_COUNTRYCODE: data_countrycode+=new String(ch,start,length); break; case STATE_COUNTRY_COUNTRYNAME: data_countryname+=new String(ch,start,length); break; case STATE_COUNTRY_ISONUMERIC: data_isonumeric+=new String(ch,start,length); break; case STATE_COUNTRY_ISOALPHA3: data_isoalpha3+=new String(ch,start,length); break; case STATE_COUNTRY_CONTINENT: data_continent+=new String(ch,start,length); break; case STATE_COUNTRY_CAPITAL: data_capital+=new String(ch,start,length); break; case STATE_COUNTRY_AREAINSQKM: data_areainsqkm+=new String(ch,start,length); break; case STATE_COUNTRY_POPULATION: data_population+=new String(ch,start,length); break; case STATE_COUNTRY_CURRENCYCODE: data_currencycode+=new String(ch,start,length); break; case STATE_COUNTRY_LANGUAGES: data_languages+=new String(ch,start,length); break; case STATE_COUNTRY_GEONAMEID: data_geonameid+=new String(ch,start,length); break; case STATE_COUNTRY_BBOXWEST: data_bboxwest+=new String(ch,start,length); break; case STATE_COUNTRY_BBOXNORTH: data_bboxnorth+=new String(ch,start,length); break; case STATE_COUNTRY_BBOXEAST: data_bboxeast+=new String(ch,start,length); break; case STATE_COUNTRY_BBOXSOUTH: data_bboxsouth+=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; } } }
25,389
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
GeoNamesNeighbours.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/geonames/GeoNamesNeighbours.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * GeoNamesNeighbours.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/neighbours?geonameId=2658434&style=full * * @author akivela */ public class GeoNamesNeighbours extends AbstractGeoNamesExtractor { private static final long serialVersionUID = 1L; public String dataLang = "en"; public String requestGeoObject = null; @Override public String getName() { return "GeoNames neighbours extractor"; } @Override public String getDescription(){ return "Get the neighbours for given geo location and convert the neighbours 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(); NeighboursParser parserHandler = new NeighboursParser(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 neighbors found!"); else if(parserHandler.progress == 1) log("One neighbor found!"); else log("Total " + parserHandler.progress + " neighbors found!"); requestGeoObject = null; // FORCE NULL AS THIS OBJECT IS REUSED. return true; } // ------------------------------------------------------------------------- // --- GEONAMES XML FEED PARSER -------------------------------------------- // ------------------------------------------------------------------------- private static class NeighboursParser extends AbstractGeoNamesParser { public NeighboursParser(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); makeNeighbours(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,378
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
GeoNamesWikipediaSearch.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/geonames/GeoNamesWikipediaSearch.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * GeoNamesWikipediaSearch.java * */ package org.wandora.application.tools.extractors.geonames; import java.io.InputStream; 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.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; /** * * @author akivela */ public class GeoNamesWikipediaSearch extends AbstractGeoNamesExtractor { private static final long serialVersionUID = 1L; public String dataLang = "en"; public String requestGeoObject = null; @Override public String getName() { return "GeoNames wikipedia search extractor"; } @Override public String getDescription(){ return "Search wikipedia geo locations from GeoNames web api and convert 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(); GeoNamesWikipediaSearchParser parserHandler = new GeoNamesWikipediaSearchParser(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 GeoNamesWikipediaSearchParser extends AbstractGeoNamesWikipediaParser { public GeoNamesWikipediaSearchParser(TopicMap tm, AbstractGeoNamesExtractor parent, String lang){ super(tm, parent, lang); } public void handleEntryElement() { if(data_title.length() > 0) { try { Topic wikiGeoObject = getWikipediaGeoTopic(tm, data_title, data_wikipediaurl, lang); parent.setProgress(progress++); try { if(isValid(data_summary)) { Topic typeTopic = getWikipediaSummaryTypeTopic(tm); wikiGeoObject.setData(typeTopic, TMBox.getLangTopic(wikiGeoObject, lang), data_summary); } if(isValid(data_thumbnailimg)) { Topic img = tm.createTopic(); img.addSubjectIdentifier(new org.wandora.topicmap.Locator(data_thumbnailimg)); img.setSubjectLocator(new org.wandora.topicmap.Locator(data_thumbnailimg)); Topic imgTypeTopic = getWikipediaThumbnailTypeTopic(tm); Topic geoType = getWikipediaGeoObjectTypeTopic(tm); Association a = tm.createAssociation(imgTypeTopic); a.addPlayer(img, imgTypeTopic); a.addPlayer(wikiGeoObject, geoType); } if(isValid(data_feature)) { Topic featureTopic = getWikipediaGeoFeatureTopic(tm, data_feature); wikiGeoObject.addType(featureTopic); } if(isValid(data_countrycode)) { Topic countryTopic=getCountryTopic(tm, data_countrycode, lang); makeGeoCountry(wikiGeoObject, countryTopic, tm); } if(isValid(data_lat) && isValid(data_lng)) { makeLatLong(data_lat, data_lng, wikiGeoObject, tm); } if(isValid(data_population) && !data_population.equals("0")) { Topic populationTypeTopic = getPopulationTypeTopic(tm); wikiGeoObject.setData(populationTypeTopic, TMBox.getLangTopic(wikiGeoObject, lang), data_population); } } catch(Exception e) { parent.log(e); } } catch(TopicMapException tme){ parent.log(tme); } } } } }
6,809
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AbstractGeoNamesParser.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/geonames/AbstractGeoNamesParser.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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 java.util.HashMap; import org.wandora.topicmap.Topic; 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 AbstractGeoNamesParser 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; protected String masterSubject = null; public AbstractGeoNamesParser(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_GEONAME="geoname"; private static final String TAG_NAME="name"; private static final String TAG_LAT="lat"; private static final String TAG_LNG="lng"; private static final String TAG_GEONAMEID="geonameId"; private static final String TAG_COUNTRYCODE="countryCode"; private static final String TAG_COUNTRYNAME="countryName"; private static final String TAG_FCL="fcl"; private static final String TAG_FCODE="fcode"; private static final String TAG_FCLNAME="fclName"; private static final String TAG_FCODENAME="fcodeName"; private static final String TAG_POPULATION="population"; private static final String TAG_ALTERNATENAMES="alternateNames"; private static final String TAG_ELEVATION="elevation"; private static final String TAG_CONTINENTCODE="continentCode"; private static final String TAG_ADMINCODE1="adminCode1"; private static final String TAG_ADMINNAME1="adminName1"; private static final String TAG_ADMINCODE2="adminCode2"; private static final String TAG_ADMINNAME2="adminName2"; private static final String TAG_ALTERNATENAME="alternateName"; private static final String TAG_TIMEZONE="timezone"; 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_GEONAME=3; private static final int STATE_GEONAME_NAME=4; private static final int STATE_GEONAME_LAT=5; private static final int STATE_GEONAME_LNG=6; private static final int STATE_GEONAME_GEONAMEID=7; private static final int STATE_GEONAME_COUNTRYCODE=8; private static final int STATE_GEONAME_COUNTRYNAME=9; private static final int STATE_GEONAME_FCL=10; private static final int STATE_GEONAME_FCODE=11; private static final int STATE_GEONAME_FCLNAME=12; private static final int STATE_GEONAME_FCODENAME=13; private static final int STATE_GEONAME_POPULATION=14; private static final int STATE_GEONAME_ALTERNATENAMES=15; private static final int STATE_GEONAME_ELEVATION=16; private static final int STATE_GEONAME_CONTINENTCODE=17; private static final int STATE_GEONAME_ADMINCODE1=18; private static final int STATE_GEONAME_ADMINNAME1=19; private static final int STATE_GEONAME_ADMINCODE2=20; private static final int STATE_GEONAME_ADMINNAME2=21; private static final int STATE_GEONAME_ALTERNATENAME=22; private static final int STATE_GEONAME_TIMEZONE=23; private int state=STATE_START; protected String data_name; protected String data_lat; protected String data_lng; protected String data_geonameid; protected String data_countrycode; protected String data_countryname; protected String data_fcl; protected String data_fcode; protected String data_fclname; protected String data_fcodename; protected String data_population; protected String data_alternatenames; protected String data_elevation; protected String data_continentcode; protected String data_admincode1; protected String data_adminname1; protected String data_admincode2; protected String data_adminname2; protected String data_alternatename; protected String data_alternatename_lang; protected HashMap<String,String> data_alternatename_all; protected String data_dstoffset; protected String data_gmtoffset; protected String data_timezone; protected Topic theGeoObject; protected String theGeoObjectSI; public void setMasterSubject(String subject) { masterSubject = subject; } public void setRequestGeoObject(String p) { requestGeoObject = p; } // ********** OVERRIDE THIS METHOD IN EXTENDING CLASSES! ********** public abstract void handleGeoNameElement(); 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_GEONAME)) { data_name = ""; data_lat = ""; data_lng = ""; data_geonameid = ""; data_countrycode = ""; data_countryname = ""; data_fcl = ""; data_fcode = ""; data_fclname = ""; data_fcodename = ""; data_population = ""; data_alternatenames = ""; data_elevation = ""; data_continentcode = ""; data_admincode1 = ""; data_adminname1 = ""; data_admincode2 = ""; data_adminname2 = ""; data_alternatename = ""; data_alternatename_lang = ""; data_alternatename_all = new HashMap<String, String>(); data_dstoffset = ""; data_gmtoffset = ""; data_timezone = ""; state = STATE_GEONAME; } break; case STATE_GEONAME: if(qName.equals(TAG_NAME)) { state = STATE_GEONAME_NAME; data_name = ""; } else if(qName.equals(TAG_LAT)) { state = STATE_GEONAME_LAT; data_lat = ""; } else if(qName.equals(TAG_LNG)) { state = STATE_GEONAME_LNG; data_lng = ""; } else if(qName.equals(TAG_GEONAMEID)) { state = STATE_GEONAME_GEONAMEID; data_geonameid = ""; } else if(qName.equals(TAG_COUNTRYCODE)) { state = STATE_GEONAME_COUNTRYCODE; data_countrycode = ""; } else if(qName.equals(TAG_COUNTRYNAME)) { state = STATE_GEONAME_COUNTRYNAME; data_countryname = ""; } else if(qName.equals(TAG_FCL)) { state = STATE_GEONAME_FCL; data_fcl = ""; } else if(qName.equals(TAG_FCODE)) { state = STATE_GEONAME_FCODE; data_fcode = ""; } else if(qName.equals(TAG_FCLNAME)) { state = STATE_GEONAME_FCLNAME; data_fclname = ""; } else if(qName.equals(TAG_FCODENAME)) { state = STATE_GEONAME_FCODENAME; data_fcodename = ""; } else if(qName.equals(TAG_POPULATION)) { state = STATE_GEONAME_POPULATION; data_population = ""; } else if(qName.equals(TAG_ALTERNATENAMES)) { state = STATE_GEONAME_ALTERNATENAMES; data_alternatenames = ""; } else if(qName.equals(TAG_ELEVATION)) { state = STATE_GEONAME_ELEVATION; data_elevation = ""; } else if(qName.equals(TAG_CONTINENTCODE)) { state = STATE_GEONAME_CONTINENTCODE; data_continentcode = ""; } else if(qName.equals(TAG_ADMINCODE1)) { state = STATE_GEONAME_ADMINCODE1; data_admincode1 = ""; } else if(qName.equals(TAG_ADMINNAME1)) { state = STATE_GEONAME_ADMINNAME1; data_adminname1 = ""; } else if(qName.equals(TAG_ADMINCODE2)) { state = STATE_GEONAME_ADMINCODE2; data_admincode2 = ""; } else if(qName.equals(TAG_ADMINNAME2)) { state = STATE_GEONAME_ADMINNAME2; data_adminname2 = ""; } else if(qName.equals(TAG_ALTERNATENAME)) { state = STATE_GEONAME_ALTERNATENAME; data_alternatename_lang = atts.getValue("lang"); data_alternatename = ""; } else if(qName.equals(TAG_TIMEZONE)) { state = STATE_GEONAME_TIMEZONE; data_timezone = ""; data_dstoffset = atts.getValue("dstOffset"); data_gmtoffset = atts.getValue("gmtOffset"); } break; } } public void endElement(String uri, String localName, String qName) throws SAXException { switch(state) { case STATE_GEONAME: { if(TAG_GEONAME.equals(qName)) { handleGeoNameElement(); state=STATE_GEONAMES; } break; } case STATE_GEONAMES_STATUS: if(TAG_STATUS.equals(qName)) { state=STATE_GEONAMES; } break; case STATE_GEONAMES: state=STATE_START; break; case STATE_GEONAME_NAME: { if(TAG_NAME.equals(qName)) state=STATE_GEONAME; break; } case STATE_GEONAME_LAT: { if(TAG_LAT.equals(qName)) state=STATE_GEONAME; break; } case STATE_GEONAME_LNG: { if(TAG_LNG.equals(qName)) state=STATE_GEONAME; break; } case STATE_GEONAME_GEONAMEID: { if(TAG_GEONAMEID.equals(qName)) state=STATE_GEONAME; break; } case STATE_GEONAME_COUNTRYCODE: { if(TAG_COUNTRYCODE.equals(qName)) state=STATE_GEONAME; break; } case STATE_GEONAME_COUNTRYNAME: { if(TAG_COUNTRYNAME.equals(qName)) state=STATE_GEONAME; break; } case STATE_GEONAME_FCL: { if(TAG_FCL.equals(qName)) state=STATE_GEONAME; break; } case STATE_GEONAME_FCODE: { if(TAG_FCODE.equals(qName)) state=STATE_GEONAME; break; } case STATE_GEONAME_FCLNAME: { if(TAG_FCLNAME.equals(qName)) state=STATE_GEONAME; break; } case STATE_GEONAME_FCODENAME: { if(TAG_FCODENAME.equals(qName)) state=STATE_GEONAME; break; } case STATE_GEONAME_POPULATION: { if(TAG_POPULATION.equals(qName)) state=STATE_GEONAME; break; } case STATE_GEONAME_ALTERNATENAMES: { if(TAG_ALTERNATENAMES.equals(qName)) state=STATE_GEONAME; break; } case STATE_GEONAME_ELEVATION: { if(TAG_ELEVATION.equals(qName)) state=STATE_GEONAME; break; } case STATE_GEONAME_CONTINENTCODE: { if(TAG_CONTINENTCODE.equals(qName)) state=STATE_GEONAME; break; } case STATE_GEONAME_ADMINCODE1: { if(TAG_ADMINCODE1.equals(qName)) state=STATE_GEONAME; break; } case STATE_GEONAME_ADMINNAME1: { if(TAG_ADMINNAME1.equals(qName)) state=STATE_GEONAME; break; } case STATE_GEONAME_ADMINCODE2: { if(TAG_ADMINCODE2.equals(qName)) state=STATE_GEONAME; break; } case STATE_GEONAME_ADMINNAME2: { if(TAG_ADMINNAME2.equals(qName)) state=STATE_GEONAME; break; } case STATE_GEONAME_ALTERNATENAME: { if(TAG_ALTERNATENAME.equals(qName)) { if(data_alternatename_lang != null && data_alternatename_lang.length() > 0 && data_alternatename != null && data_alternatename.length() > 0) { data_alternatename_all.put(data_alternatename_lang, data_alternatename); } state=STATE_GEONAME; } break; } case STATE_GEONAME_TIMEZONE: { if(TAG_TIMEZONE.equals(qName)) state=STATE_GEONAME; break; } } } public void characters(char[] ch, int start, int length) throws SAXException { switch(state){ case STATE_GEONAME_NAME: data_name+=new String(ch,start,length); break; case STATE_GEONAME_LAT: data_lat+=new String(ch,start,length); break; case STATE_GEONAME_LNG: data_lng+=new String(ch,start,length); break; case STATE_GEONAME_GEONAMEID: data_geonameid+=new String(ch,start,length); break; case STATE_GEONAME_COUNTRYCODE: data_countrycode+=new String(ch,start,length); break; case STATE_GEONAME_COUNTRYNAME: data_countryname+=new String(ch,start,length); break; case STATE_GEONAME_FCL: data_fcl+=new String(ch,start,length); break; case STATE_GEONAME_FCODE: data_fcode+=new String(ch,start,length); break; case STATE_GEONAME_FCLNAME: data_fclname+=new String(ch,start,length); break; case STATE_GEONAME_FCODENAME: data_fcodename+=new String(ch,start,length); break; case STATE_GEONAME_POPULATION: data_population+=new String(ch,start,length); break; case STATE_GEONAME_ALTERNATENAMES: data_alternatenames+=new String(ch,start,length); break; case STATE_GEONAME_ELEVATION: data_elevation+=new String(ch,start,length); break; case STATE_GEONAME_CONTINENTCODE: data_continentcode+=new String(ch,start,length); break; case STATE_GEONAME_ADMINCODE1: data_admincode1+=new String(ch,start,length); break; case STATE_GEONAME_ADMINNAME1: data_adminname1+=new String(ch,start,length); break; case STATE_GEONAME_ADMINCODE2: data_admincode2+=new String(ch,start,length); break; case STATE_GEONAME_ADMINNAME2: data_adminname2+=new String(ch,start,length); break; case STATE_GEONAME_ALTERNATENAME: data_alternatename+=new String(ch,start,length); break; case STATE_GEONAME_TIMEZONE: data_timezone+=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; } }
19,560
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AbstractGeoNamesExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/geonames/AbstractGeoNamesExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * AbstractGeoNamesExtractor.java * * */ package org.wandora.application.tools.extractors.geonames; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.net.URL; import java.net.URLEncoder; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.Icon; import org.wandora.application.gui.UIBox; import org.wandora.application.tools.extractors.AbstractExtractor; import org.wandora.application.tools.extractors.ExtractHelper; import org.wandora.topicmap.Association; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.XTMPSI; /** * * @author akivela */ public abstract class AbstractGeoNamesExtractor extends AbstractExtractor { private static final long serialVersionUID = 1L; public static boolean USE_EXISTING_TOPICS = false; // Default language for occurrences, variant names, and web API requests. public static final String LANG = "en"; public static final String GEONAMES_PREFIX="http://www.geonames.org/"; public static final String GEONAMEID_SI="http://www.geonames.org"; public static final String LANGUAGE_SI = GEONAMES_PREFIX+"language"; public static final String COUNTRY_SI = GEONAMES_PREFIX+"country"; public static final String COUNTRY_CODE_SI = GEONAMES_PREFIX+"country-code"; public static final String CONTINENT_SI = GEONAMES_PREFIX+"continent"; public static final String COUNTRY_CAPITAL_SI = GEONAMES_PREFIX+"country-capital"; public static final String CAPITAL_SI = GEONAMES_PREFIX+"capital-city"; public static final String CITY_SI = GEONAMES_PREFIX+"city"; public static final String BBOX_SI = GEONAMES_PREFIX+"bbox"; public static final String BBOXWEST_SI = GEONAMES_PREFIX+"bbox-west"; public static final String BBOXEAST_SI = GEONAMES_PREFIX+"bbox-east"; public static final String BBOXSOUTH_SI = GEONAMES_PREFIX+"bbox-south"; public static final String BBOXNORTH_SI = GEONAMES_PREFIX+"bbox-north"; public static final String GEOOBJECT_SI = GEONAMES_PREFIX+"geo-object"; public static final String GPS_SI = GEONAMES_PREFIX+"gps-number"; public static final String AREA_SI = GEONAMES_PREFIX+"area"; public static final String POPULATION_SI = GEONAMES_PREFIX+"population"; public static final String CURRENCY_SI = GEONAMES_PREFIX+"currency"; public static final String ISOALPHA3_SI = "http://www.iso.org/ISO3166-1alpha-3/"; public static final String ISONUMERIC_SI = "http://www.iso.org/ISO3166-1numeric/"; public static final String FIPS_SI = "http://www.itl.nist.gov/fipspubs/10-4/"; public static final String LOCATION_SI = GEONAMES_PREFIX+"location"; public static final String LOCATED_SI = GEONAMES_PREFIX+"located"; public static final String LNG_SI = GEONAMES_PREFIX+"lng"; public static final String LAT_SI = GEONAMES_PREFIX+"lat"; public static final String FCL_SI = GEONAMES_PREFIX+"fcl"; public static final String FCODE_SI = GEONAMES_PREFIX+"fcode"; public static final String PARENT_CHILD_SI = GEONAMES_PREFIX+"parent-child"; // Association type public static final String PARENT_SI = GEONAMES_PREFIX+"parent"; // role public static final String CHILD_SI = GEONAMES_PREFIX+"child"; // role public static final String PART_WHOLE_SI = GEONAMES_PREFIX+"part-whole"; // Association type public static final String WHOLE_SI = GEONAMES_PREFIX+"whole"; // role public static final String PART_SI = GEONAMES_PREFIX+"part"; // role public static final String NEIGHBOURS_SI = GEONAMES_PREFIX+"neighbours"; // Association type public static final String NEIGHBOUR_SI = GEONAMES_PREFIX+"neighbour"; // role public static final String NEIGHBOUR2_SI = GEONAMES_PREFIX+"neighbour2"; // role public static final String SIBLINGS_SI = GEONAMES_PREFIX+"siblings"; // Association type public static final String SIBLING_SI = GEONAMES_PREFIX+"sibling"; // role public static final String SIBLING2_SI = GEONAMES_PREFIX+"sibling2"; // role public static boolean USE_FCODES_AS_PRIMARY_CATEGORIZATION = true; public static boolean USE_ALL_VARIANT_NAMES = true; public static final String ELEVATION_SI = GEONAMES_PREFIX+"elevation"; // **** WEATHER **** public static final String WEATHER_SI = GEONAMES_PREFIX+"weather"; public static final String WEATHER_OBSERVATION_SI = WEATHER_SI + "/observation"; public static final String WEATHER_OBSERVATIONTIME_SI = WEATHER_SI + "/time"; public static final String WEATHER_STATION_SI = WEATHER_SI + "/station"; public static final String WEATHER_ICAO_SI = GEONAMES_PREFIX + "/icao"; public static final String WEATHER_ELEVATION_SI = WEATHER_SI + "/elevation"; public static final String WEATHER_TEMPERATURE_SI = WEATHER_SI + "/temperature"; public static final String WEATHER_DEWPOINT_SI = WEATHER_SI + "/dewpoint"; public static final String WEATHER_HUMIDITY_SI = WEATHER_SI + "/humidity"; public static final String WEATHER_CLOUDS_SI = WEATHER_SI + "/clouds"; public static final String WEATHER_WEATHERCONDITION_SI = WEATHER_SI + "/weathercondition"; public static final String WEATHER_HECTOPASCALTIMETER_SI = WEATHER_SI + "/hectopascaltimeter"; public static final String WEATHER_WINDDIRECTION_SI = WEATHER_SI + "/wind/direction"; public static final String WEATHER_WINDSPEED_SI = WEATHER_SI + "/wind/speed"; // **** WIKIPEDIA **** public static final String WIKIPEDIA_GEO_PREFIX="http://www.geonames.org/wikipedia"; public static final String WIKIPEDIA_GEO_ENTRY_SI=WIKIPEDIA_GEO_PREFIX+"/entry"; public static final String WIKIPEDIA_GEO_FEATURE_SI=WIKIPEDIA_GEO_PREFIX+"/feature"; public static final String WIKIPEDIA_GEOOBJECT_SI = WIKIPEDIA_GEO_PREFIX+"/geo-object"; public static final String WIKIPEDIA_GEO_SUMMARY_SI = WIKIPEDIA_GEO_PREFIX+"/summary"; public static final String WIKIPEDIA_GEO_THUMBNAIL_SI = WIKIPEDIA_GEO_PREFIX+"/thumbnail"; @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/extract_geonames.png"); } private final String[] contentTypes=new String[] { "text/xml", "application/xml" }; @Override public String[] getContentTypes() { return contentTypes; } @Override public boolean useURLCrawler() { return false; } public boolean _extractTopicsFrom(URL url, TopicMap topicMap) throws Exception { return _extractTopicsFrom(url.openStream(),topicMap); } public boolean _extractTopicsFrom(File file, TopicMap topicMap) throws Exception { return _extractTopicsFrom(new FileInputStream(file),topicMap); } public boolean _extractTopicsFrom(String str, TopicMap topicMap) throws Exception { return _extractTopicsFrom(new ByteArrayInputStream(str.getBytes()), topicMap); } public abstract boolean _extractTopicsFrom(InputStream inputStream, TopicMap topicMap) throws Exception; // ******** TOPIC MAPS ********* protected static Topic getOrCreateTopic(TopicMap tm, String si) throws TopicMapException { return getOrCreateTopic(tm, si,null); } protected static Topic getOrCreateTopic(TopicMap tm, String si, String bn) throws TopicMapException { return ExtractHelper.getOrCreateTopic(si, bn, tm); } protected static void makeSubclassOf(TopicMap tm, Topic t, Topic superclass) throws TopicMapException { ExtractHelper.makeSubclassOf(t, superclass, tm); } // ------------------------------------------------------------------------- // --- TYPE TOPICS --------------------------------------------------------- // ------------------------------------------------------------------------- public static Topic getCountryCapitalTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, COUNTRY_CAPITAL_SI, "country-capital (geonames)"); Topic gnClass = getGeoNamesClassTopic(tm); makeSubclassOf(tm, type, gnClass); return type; } public static Topic getCountryTypeTopic(TopicMap tm) throws TopicMapException { if(USE_FCODES_AS_PRIMARY_CATEGORIZATION) return getFCodeTopic(tm, "PCLI", "independent political entity"); else return getFCLTopic(tm, "A", "country, state, region,..."); /* Topic type = getOrCreateTopic(tm, COUNTRY_SI, "country (geonames)"); Topic gnClass = getGeoNamesClassTopic(tm); makeSubclassOf(tm, type, gnClass); return type; */ } public static Topic getContinentTypeTopic(TopicMap tm) throws TopicMapException { if(USE_FCODES_AS_PRIMARY_CATEGORIZATION) return getFCodeTopic(tm, "CONT", "continent"); else return getFCLTopic(tm, "L", "parks,area, ..."); /* Topic type = getOrCreateTopic(tm, CONTINENT_SI, "continent (geonames)"); Topic gnClass = getGeoNamesClassTopic(tm); makeSubclassOf(tm, type, gnClass); return type; */ } public static Topic getCapitalTypeTopic(TopicMap tm) throws TopicMapException { //return getCityTypeTopic(tm); Topic type = getOrCreateTopic(tm, CAPITAL_SI, "capital (geonames)"); //Topic gnClass = getGeoNamesClassTopic(tm); //makeSubclassOf(tm, type, gnClass); Topic cityType = getCityTypeTopic(tm); makeSubclassOf(tm, type, cityType); return type; } public static Topic getCityTypeTopic(TopicMap tm) throws TopicMapException { if(USE_FCODES_AS_PRIMARY_CATEGORIZATION) return getFCodeTopic(tm, "PPLA", "seat of a first-order administrative division"); else return getFCLTopic(tm, "P", "city, village,..."); /* Topic type = getOrCreateTopic(tm, CITY_SI, "city (geonames)"); Topic gnClass = getGeoNamesClassTopic(tm); makeSubclassOf(tm, type, gnClass); return type; */ } public static Topic getBBoxTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, BBOX_SI, "bounding box (geonames)"); Topic gnClass = getGeoNamesClassTopic(tm); makeSubclassOf(tm, type, gnClass); return type; } public static Topic getBBoxWestTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, BBOXWEST_SI, "west of bounding box (geonames)"); return type; } public static Topic getBBoxEastTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, BBOXEAST_SI, "east of bounding box (geonames)"); return type; } public static Topic getBBoxSouthTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, BBOXSOUTH_SI, "south of bounding box (geonames)"); return type; } public static Topic getBBoxNorthTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, BBOXNORTH_SI, "north of bounding box (geonames)"); return type; } public static Topic getGPSNumberTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, GPS_SI, "gps number (geonames)"); Topic gnClass = getGeoNamesClassTopic(tm); makeSubclassOf(tm, type, gnClass); return type; } public static Topic getGeoObjectTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, GEOOBJECT_SI, "geo-object (geonames)"); return type; } public static Topic getWikipediaGeoObjectTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, WIKIPEDIA_GEOOBJECT_SI, "wikipedia geo-object (geonames)"); return type; } public static Topic getWikipediaSummaryTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, WIKIPEDIA_GEO_SUMMARY_SI, "wikipedia geo-summary (geonames)"); return type; } public static Topic getWikipediaThumbnailTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, WIKIPEDIA_GEO_THUMBNAIL_SI, "wikipedia thumbnail (geonames)"); Topic gnClass = getGeoNamesClassTopic(tm); makeSubclassOf(tm, type, gnClass); return type; } public static Topic getWikipediaFeatureTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, WIKIPEDIA_GEO_FEATURE_SI, "wikipedia geo-feature (geonames)"); Topic gnClass = getGeoNamesClassTopic(tm); makeSubclassOf(tm, type, gnClass); return type; } public static Topic getLanguageTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, LANGUAGE_SI, "language (geonames)"); Topic gnClass = getGeoNamesClassTopic(tm); makeSubclassOf(tm, type, gnClass); return type; } public static Topic getCurrencyTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, CURRENCY_SI, "currency (geonames)"); Topic gnClass = getGeoNamesClassTopic(tm); makeSubclassOf(tm, type, gnClass); return type; } public static Topic getAreaTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, AREA_SI, "area (geonames)"); return type; } public static Topic getPopulationTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, POPULATION_SI, "population (geonames)"); return type; } public static Topic getElevationTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, ELEVATION_SI, "elevation (geonames)"); return type; } // GPS LOCATION! public static Topic getLocationTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, LOCATION_SI, "gps location (geonames)"); Topic gnClass = getGeoNamesClassTopic(tm); makeSubclassOf(tm, type, gnClass); return type; } public static Topic getLocatedTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, LOCATED_SI, "located (geonames)"); Topic gnClass = getGeoNamesClassTopic(tm); makeSubclassOf(tm, type, gnClass); return type; } public static Topic getLatTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, LAT_SI, "latitude (geonames)"); return type; } public static Topic getLngTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, LNG_SI, "longitude (geonames)"); return type; } public static Topic getPartWholeTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, PART_WHOLE_SI, "part-whole (geonames)"); return type; } public static Topic getWholeTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, WHOLE_SI, "whole (geonames)"); return type; } public static Topic getPartTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, PART_SI, "part (geonames)"); return type; } public static Topic getParentChildTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, PARENT_CHILD_SI, "parent-child (geonames)"); return type; } public static Topic getParentTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, PARENT_SI, "parent (geonames)"); return type; } public static Topic getChildTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, CHILD_SI, "child (geonames)"); return type; } public static Topic getNeighboursTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, NEIGHBOURS_SI, "neighbours (geonames)"); return type; } public static Topic getNeighbourTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, NEIGHBOUR_SI, "neighbour (geonames)"); return type; } public static Topic getNeighbour2TypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, NEIGHBOUR2_SI, "neighbour-2 (geonames)"); return type; } public static Topic getSiblingsTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, SIBLINGS_SI, "siblings (geonames)"); return type; } public static Topic getSiblingTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, SIBLING_SI, "sibling (geonames)"); return type; } public static Topic getSibling2TypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, SIBLING2_SI, "sibling-2 (geonames)"); return type; } public static Topic getFCLTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, FCL_SI, "FCL (geonames)"); Topic gnClass = getGeoNamesClassTopic(tm); makeSubclassOf(tm, type, gnClass); return type; } public static Topic getFCodeTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, FCODE_SI, "fcode (geonames)"); Topic gnClass = getGeoNamesClassTopic(tm); makeSubclassOf(tm, type, gnClass); return type; } // ----- ACTUAL INSTANCE TOPICS ------ public static Topic getGeoTopic(TopicMap tm, String geonameid) throws TopicMapException { String geoSI = createGeonameSI(geonameid); Topic geoTopic = null; if(USE_EXISTING_TOPICS) geoTopic = tm.getTopic(geoSI); if(geoTopic == null) { geoTopic=tm.createTopic(); geoTopic.addSubjectIdentifier(tm.createLocator(geoSI)); } return geoTopic; } public static Topic getGeoTopic(TopicMap tm, String geonameid, String name, String lang) throws TopicMapException { String geoSI = createGeonameSI(geonameid); Topic geoTopic = null; if(USE_EXISTING_TOPICS) geoTopic = tm.getTopic(geoSI); if(geoTopic == null) { geoTopic=tm.createTopic(); geoTopic.addSubjectIdentifier(tm.createLocator(geoSI)); geoTopic.setBaseName(name + " ("+geonameid+")"); if(lang != null) geoTopic.setDisplayName(lang, name); else geoTopic.setDisplayName(LANG, name); } return geoTopic; } public static Topic getWikipediaGeoTopic(TopicMap tm, String title, String wikipediaUrl, String lang) throws TopicMapException { String si = null; if(wikipediaUrl != null && wikipediaUrl.length() > 0) { si = wikipediaUrl; } else { si = WIKIPEDIA_GEO_ENTRY_SI + "/" + encode(title); } Topic geoTopic = null; if(USE_EXISTING_TOPICS) geoTopic = tm.getTopic(si); if(geoTopic == null) { geoTopic=tm.createTopic(); geoTopic.addSubjectIdentifier(tm.createLocator(si)); if(title != null && title.length() > 0) { geoTopic.setBaseName(title + " (wikipedia geo-object)"); if(lang != null) geoTopic.setDisplayName(lang, title); else geoTopic.setDisplayName(LANG, title); } } return geoTopic; } public static Topic getCountryTopic(TopicMap tm, String countrycode, String lang) throws TopicMapException { String countryname = solveCountryName(countrycode); return getCountryTopic(tm, countrycode, countryname, lang); } public static Topic getCountryTopic(TopicMap tm, String countrycode, String countryname, String lang) throws TopicMapException { String countrySI = COUNTRY_CODE_SI + "/" + encode(countrycode); Topic theCountry = null; if(USE_EXISTING_TOPICS) theCountry = tm.getTopic(countrySI); if(theCountry == null) { Topic countryType = getCountryTypeTopic(tm); theCountry=tm.createTopic(); theCountry.addSubjectIdentifier(tm.createLocator(countrySI)); //theCountry.setBaseName(countryname + " (geoname)"); if(lang != null) theCountry.setDisplayName(lang, countryname); else theCountry.setDisplayName(LANG, countryname); theCountry.addType(countryType); } return theCountry; } public static Topic getCountryTopic(TopicMap tm, String countrycode, String geonameid, String countryname, String lang) throws TopicMapException { String countrySI = createGeonameSI(geonameid); Topic theCountry = null; if(USE_EXISTING_TOPICS) theCountry = tm.getTopic(countrySI); if(theCountry == null) { Topic countryType = getCountryTypeTopic(tm); theCountry=tm.createTopic(); theCountry.addSubjectIdentifier(tm.createLocator(countrySI)); if(countrycode!=null && countrycode.length()>0) { theCountry.addSubjectIdentifier(tm.createLocator(COUNTRY_CODE_SI+"/"+encode(countrycode))); } theCountry.setBaseName(countryname + " ("+geonameid+")"); if(lang != null) theCountry.setDisplayName(lang, countryname); else theCountry.setDisplayName(LANG, countryname); theCountry.addType(countryType); } return theCountry; } public static Topic getContinentTopic(TopicMap tm, String continentcode) throws TopicMapException { String continentSI = CONTINENT_SI + "/" + encode(continentcode); Topic theContinent = null; if(USE_EXISTING_TOPICS) theContinent = tm.getTopic(continentSI); if(theContinent == null) { Topic continentType = getContinentTypeTopic(tm); theContinent=tm.createTopic(); theContinent.addSubjectIdentifier(tm.createLocator(continentSI)); //theContinent.setBaseName(continentcode + " (geoname)"); theContinent.addType(continentType); } return theContinent; } // ------- public static Topic getCityTopic(TopicMap tm, String city, String lang) throws TopicMapException { String citySI = CITY_SI + "/" + encode(city); Topic theCity = null; if(USE_EXISTING_TOPICS) theCity = tm.getTopic(citySI); if(theCity == null) { Topic cityType = getCityTypeTopic(tm); theCity=tm.createTopic(); theCity.addSubjectIdentifier(tm.createLocator(citySI)); //theCity.setBaseName(city + " (geoname)"); if(lang != null) theCity.setDisplayName(lang, city); else theCity.setDisplayName("en", city); theCity.addType(cityType); } return theCity; } public static Topic getCityTopic(TopicMap tm, String geonameid, String cityname, String lang) throws TopicMapException { String citySI = createGeonameSI(geonameid); Topic theCity = null; if(USE_EXISTING_TOPICS) theCity = tm.getTopic(citySI); if(theCity == null) { Topic cityType = getCityTypeTopic(tm); theCity=tm.createTopic(); theCity.addSubjectIdentifier(tm.createLocator(citySI)); theCity.setBaseName(cityname + " ("+geonameid+")"); if(lang != null) theCity.setDisplayName(lang, cityname); else theCity.setDisplayName(LANG, cityname); theCity.addType(cityType); } return theCity; } // ------- public static Topic getCurrencyTopic(TopicMap tm, String currency, String lang) throws TopicMapException { String currencySI = CURRENCY_SI + "/" + encode(currency); Topic theCurrency = null; if(USE_EXISTING_TOPICS) theCurrency = tm.getTopic(currencySI); if(theCurrency == null) { Topic currencyType = getCurrencyTypeTopic(tm); theCurrency=tm.createTopic(); theCurrency.addSubjectIdentifier(tm.createLocator(currencySI)); theCurrency.setBaseName(currency + " (currency)"); if(lang != null) theCurrency.setDisplayName(lang, currency); else theCurrency.setDisplayName("en", currency); theCurrency.addType(currencyType); } return theCurrency; } public static Topic getGPSNumberTopic(TopicMap tm, String gpsnumber) throws TopicMapException { String gpsSI = GPS_SI + "/" + encode(gpsnumber); Topic theGPSNumber = null; if(USE_EXISTING_TOPICS) theGPSNumber = tm.getTopic(gpsSI); if(theGPSNumber == null) { Topic gpsNumberType = getGPSNumberTypeTopic(tm); theGPSNumber=tm.createTopic(); theGPSNumber.addSubjectIdentifier(tm.createLocator(gpsSI)); theGPSNumber.setBaseName(gpsnumber + " (gps number)"); theGPSNumber.setDisplayName(null, gpsnumber); theGPSNumber.addType(gpsNumberType); } return theGPSNumber; } public static Topic getLanguageTopic(TopicMap tm, String l) throws TopicMapException { String languageSI = LANGUAGE_SI + "/" + encode(l); Topic theLanguage = null; if(USE_EXISTING_TOPICS) theLanguage = tm.getTopic(languageSI); if(theLanguage == null) { Topic languageType = getLanguageTypeTopic(tm); theLanguage=tm.createTopic(); theLanguage.addSubjectIdentifier(tm.createLocator(languageSI)); theLanguage.setBaseName(l + " (language)"); theLanguage.addType(languageType); } return theLanguage; } public static Topic getFCLTopic(TopicMap tm, String fclCode, String fclName) throws TopicMapException { String fclSI = FCL_SI + "/" + encode(fclCode); Topic theFCL = null; if(USE_EXISTING_TOPICS) theFCL = tm.getTopic(fclSI); if(theFCL == null) { Topic fclType = getFCLTypeTopic(tm); theFCL=tm.createTopic(); theFCL.addSubjectIdentifier(tm.createLocator(fclSI)); if(fclName != null && fclName.length() > 0) theFCL.setBaseName(fclName + " (fcl)"); theFCL.addType(fclType); } return theFCL; } public static Topic getFCodeTopic(TopicMap tm, String fCode, String fCodeName) throws TopicMapException { String fCodeSI = FCODE_SI + "/" + encode(fCode); Topic fCodeTopic = null; if(USE_EXISTING_TOPICS) fCodeTopic = tm.getTopic(fCodeSI); if(fCodeTopic == null) { Topic fCodeType = getFCodeTypeTopic(tm); fCodeTopic=tm.createTopic(); fCodeTopic.addSubjectIdentifier(tm.createLocator(fCodeSI)); if(fCodeName != null && fCodeName.length() > 0) fCodeTopic.setBaseName(fCodeName + " (fcode)"); fCodeTopic.addType(fCodeType); } return fCodeTopic; } public static Topic getWikipediaGeoFeatureTopic(TopicMap tm, String feature) throws TopicMapException { String si = WIKIPEDIA_GEO_FEATURE_SI + "/" + encode(feature); Topic featureTopic = null; if(USE_EXISTING_TOPICS) featureTopic = tm.getTopic(si); if(featureTopic == null) { Topic featureType = getWikipediaFeatureTypeTopic(tm); featureTopic=tm.createTopic(); featureTopic.addSubjectIdentifier(tm.createLocator(si)); if(feature != null && feature.length() > 0) featureTopic.setBaseName(feature + " (wikipedia geo-feature)"); featureTopic.addType(featureType); } return featureTopic; } public static Topic getElevationTopic(TopicMap tm, String elevation, String lang) throws TopicMapException { String elevationSI = ELEVATION_SI + "/" + encode(elevation); Topic elevationTopic = null; if(USE_EXISTING_TOPICS) elevationTopic = tm.getTopic(elevationSI); if(elevationTopic == null) { Topic elevationType = getElevationTypeTopic(tm); elevationTopic=tm.createTopic(); elevationTopic.addSubjectIdentifier(tm.createLocator(elevationSI)); if(elevation != null && elevation.length() > 0) { elevationTopic.setBaseName(elevation + " (elevation)"); elevationTopic.setDisplayName(null, elevation); } elevationTopic.addType(elevationType); } return elevationTopic; } public static Topic getGeoNamesClassTopic(TopicMap tm) throws TopicMapException { Topic gnTopic = getOrCreateTopic(tm, GEONAMES_PREFIX, "GeoNames"); gnTopic.addType(getWandoraClassTopic(tm)); return gnTopic; } public static Topic getWandoraClassTopic(TopicMap tm) throws TopicMapException { return getOrCreateTopic(tm, TMBox.WANDORACLASS_SI,"Wandora class"); } public static Topic getGenericTopic(TopicMap tm) throws TopicMapException { return getOrCreateTopic(tm, "http://wandora.org/si/topic", "Topic"); } public static String createCountryAlpha3SI(String alpha3) { return ISOALPHA3_SI+alpha3; } public static String createCountryNumericSI(String n) { return ISONUMERIC_SI+n; } public static String createFIPSSI(String fips) { return FIPS_SI+fips; } public static String createGeonameSI(String geonameid) { return GEONAMEID_SI+"/"+geonameid; } public static boolean isValidGPSCoordinate(String coordinate) { boolean isValid = false; Pattern GPSPattern = Pattern.compile("[\\+\\-]?\\d+(\\.\\d+)?"); Matcher GPSMatcher = GPSPattern.matcher(coordinate); if(GPSMatcher.matches()) isValid = true; return isValid; } public static void nameGeoObjectTopic(Topic geoTopic, HashMap<String, String> names) { if(geoTopic == null || names == null || names.isEmpty()) return; Set<String> keys = names.keySet(); String alang = null; String aname = null; for(Iterator<String> keyIter = keys.iterator(); keyIter.hasNext(); ) { try { alang = keyIter.next(); if(USE_ALL_VARIANT_NAMES || isValidSchemaLanguage(geoTopic, alang)) { aname = names.get(alang); geoTopic.setDisplayName(alang, aname); } } catch(Exception e) { // DO NOTHING! } } } public static boolean isValidSchemaLanguage(Topic referenceTopic, String lang) { boolean isValid = false; String langSI = XTMPSI.getLang(lang); TopicMap tm = referenceTopic.getTopicMap(); if(tm != null && langSI != null) { try { Topic langTopic = tm.getTopic(langSI); if(langTopic != null) { Collection<Topic> languageTopics = tm.getTopicsOfType(TMBox.LANGUAGE_SI); Topic schemaLangTopic = null; for(Iterator<Topic> i=languageTopics.iterator(); i.hasNext(); ) { schemaLangTopic = (Topic) i.next(); if(langTopic.mergesWithTopic(schemaLangTopic)) { isValid = true; break; } } } } catch(Exception e) { // DO NOTHING... } } return isValid; } public static String encode(String str) { try { str = URLEncoder.encode(str, "UTF-8"); } catch(Exception e) { // DO NOTHING } return str; } // ------------------------------------------------------------------------- // --- DEFAULT RELATIONS --------------------------------------------------- // ------------------------------------------------------------------------- public static void makeGeoContinent(Topic geoTopic, Topic continent, TopicMap tm) throws TopicMapException { if(geoTopic == null || continent == null || geoTopic.mergesWithTopic(continent)) return; Topic continentType=getContinentTypeTopic(tm); Topic geoObjectType=getGeoObjectTypeTopic(tm); Association a=tm.createAssociation(continentType); a.addPlayer(geoTopic, geoObjectType); a.addPlayer(continent, continentType); } public static void makeGeoCountry(Topic geoTopic, Topic country, TopicMap tm) throws TopicMapException { if(geoTopic == null || country == null || geoTopic.mergesWithTopic(country)) return; Topic countryType=getCountryTypeTopic(tm); Topic geoObjectType=getGeoObjectTypeTopic(tm); Association a=tm.createAssociation(countryType); a.addPlayer(geoTopic, geoObjectType); a.addPlayer(country, countryType); } public static void makeChildParent(Topic child, Topic parent, TopicMap tm) throws TopicMapException { if(child == null || parent == null || child.mergesWithTopic(parent)) return; Topic parentChildType=getParentChildTypeTopic(tm); Topic parentType=getParentTypeTopic(tm); Topic childType=getChildTypeTopic(tm); Association a=tm.createAssociation(parentChildType); a.addPlayer(child, childType); a.addPlayer(parent, parentType); } public static void makePartWhole(Topic part, Topic whole, TopicMap tm) throws TopicMapException { if(part == null || whole == null || part.mergesWithTopic(whole)) return; Topic partWholeType=getPartWholeTypeTopic(tm); Topic wholeType=getWholeTypeTopic(tm); Topic partType=getPartTypeTopic(tm); Association a=tm.createAssociation(partWholeType); a.addPlayer(part, partType); a.addPlayer(whole, wholeType); } public static void makeSiblings(Topic s1, Topic s2, TopicMap tm) throws TopicMapException { if(s1 == null || s2 == null || s1.mergesWithTopic(s2)) return; Topic siblingsType=getSiblingsTypeTopic(tm); Topic siblingType=getSiblingTypeTopic(tm); Topic sibling2Type=getSibling2TypeTopic(tm); Association a=tm.createAssociation(siblingsType); a.addPlayer(s1, siblingType); a.addPlayer(s2, sibling2Type); } public static void makeNeighbours(Topic n1, Topic n2, TopicMap tm) throws TopicMapException { if(n1 == null || n2 == null || n1.mergesWithTopic(n2)) return; Topic neighboursType=getNeighboursTypeTopic(tm); Topic neighbourType=getNeighbourTypeTopic(tm); Topic neighbour2Type=getNeighbour2TypeTopic(tm); Association a=tm.createAssociation(neighboursType); a.addPlayer(n1, neighbourType); a.addPlayer(n2, neighbour2Type); } public static void makeLatLong(String latStr, String lngStr, Topic geoTopic, TopicMap tm) throws TopicMapException { Topic locatedType=getLocatedTypeTopic(tm); Topic locationType=getLocationTypeTopic(tm); Topic latType=getLatTypeTopic(tm); Topic lngType=getLngTypeTopic(tm); Topic lat = getGPSNumberTopic(tm, latStr); Topic lng = getGPSNumberTopic(tm, lngStr); Association la = tm.createAssociation(locationType); la.addPlayer(lat, latType); la.addPlayer(lng, lngType); la.addPlayer(geoTopic, locatedType); } public static void makeBoundingBox(Topic geoTopic, String n, String w, String s, String e, TopicMap tm) throws TopicMapException { Topic geoObjectType=getGeoObjectTypeTopic(tm); Topic bBoxType=getBBoxTypeTopic(tm); Topic bBoxWestType=getBBoxWestTypeTopic(tm); Topic bBoxEastType=getBBoxEastTypeTopic(tm); Topic bBoxNorthType=getBBoxNorthTypeTopic(tm); Topic bBoxSouthType=getBBoxSouthTypeTopic(tm); Topic west = getGPSNumberTopic(tm, w); Topic east = getGPSNumberTopic(tm, e); Topic north = getGPSNumberTopic(tm, n); Topic south = getGPSNumberTopic(tm, s); Association bba = tm.createAssociation(bBoxType); bba.addPlayer(east, bBoxEastType); bba.addPlayer(west, bBoxWestType); bba.addPlayer(north, bBoxNorthType); bba.addPlayer(south, bBoxSouthType); bba.addPlayer(geoTopic, geoObjectType); } public static void makeCountryCapital(Topic country, Topic capital, TopicMap tm) throws TopicMapException { Topic countryCapitalType = getCountryCapitalTypeTopic(tm); Topic countryType = getCountryTypeTopic(tm); Topic capitalType = getCapitalTypeTopic(tm); capital.addType(capitalType); Association a=tm.createAssociation(countryCapitalType); a.addPlayer(country, countryType); a.addPlayer(capital, capitalType); } public static void makeGeoElevation(Topic geoObject, Topic elevation, TopicMap tm) throws TopicMapException { Topic elevationType = getElevationTypeTopic(tm); Topic geoObjectType = getGeoObjectTypeTopic(tm); Association a=tm.createAssociation(elevationType); a.addPlayer(geoObject, geoObjectType); a.addPlayer(elevation, elevationType); } // ------------------------------------------------------------------------- public static String[][] getFeatureClassData() { String[][] continentData = new String[][] { { "A", "country, state, region,..." }, { "H", "stream, lake, ..." }, { "L", "parks,area, ..." }, { "P", "city, village,..." }, { "R", "road, railroad " }, { "S", "spot, building, farm" }, { "T", "mountain,hill,rock,... " }, { "U", "undersea" }, { "V", "forest,heath,..." }, }; return continentData; } public static String solveFeatureClassCode(String featureClassName) { if(featureClassName == null) return null; String featureClassCode = null; String[][] featureClassData = getFeatureClassData(); for(int j=0; j<featureClassData.length; j++) { if(featureClassName.equalsIgnoreCase(featureClassData[j][1])) { featureClassCode = featureClassData[j][0]; break; } } return featureClassCode; } public static String[][] getContinentData() { String[][] continentData = new String[][] { { "AF", "Africa" }, { "AS", "Asia" }, { "EU", "Europe" }, { "NA", "North America" }, { "OC", "Oceanic" }, { "SA", "South America" }, { "AN", "Antarctica" }, }; return continentData; } public static String solveContinentCode(String continentName) { if(continentName == null) return null; String continentCode = null; String[][] continentData = getContinentData(); for(int j=0; j<continentData.length; j++) { if(continentName.equalsIgnoreCase(continentData[j][1])) { continentCode = continentData[j][0]; break; } } return continentCode; } public static String[][] getCountryData() { String[][] countryData = new String[][] { { "AD", "Andorra" }, { "AE", "United Arab Emirate" }, { "AF", "Afghanistan" }, { "AG", "Antigua and Barbuda" }, { "AI", "Anguilla" }, { "AL", "Albania" }, { "AM", "Armenia" }, { "AN", "Netherlands Antilles" }, { "AO", "Angola" }, { "AQ", "Antarctica" }, { "AR", "Argentina" }, { "AS", "American Samoa" }, { "AT", "Austria" }, { "AU", "Australia" }, { "AW", "Aruba" }, { "AZ", "Azerbaijan" }, { "BA", "Bosnia and Herzegovina" }, { "BB", "Barbados" }, { "BD", "Bangladesh" }, { "BE", "Belgium" }, { "BF", "Burkina Faso" }, { "BG", "Bulgaria" }, { "BH", "Bahrain" }, { "BI", "Burundi" }, { "BJ", "Benin" }, { "BL", "Saint Barth�lemy" }, { "BM", "Bermuda" }, { "BN", "Brunei" }, { "BO", "Bolivia" }, { "BR", "Brazil" }, { "BS", "Bahamas" }, { "BT", "Bhutan" }, { "BV", "Bouvet Island" }, { "BW", "Botswana" }, { "BY", "Belarus" }, { "BZ", "Belize" }, { "CA", "Canada" }, { "CC", "Cocos Islands" }, { "CD", "Congo - Kinshasa" }, { "CF", "Central African Republic" }, { "CG", "Congo - Brazzaville" }, { "CH", "Switzerland" }, { "CI", "Ivory Coast" }, { "CK", "Cook Islands" }, { "CL", "Chile" }, { "CM", "Cameroon" }, { "CN", "China" }, { "CO", "Colombia" }, { "CR", "Costa Rica" }, { "CU", "Cuba" }, { "CV", "Cape Verde" }, { "CX", "Christmas Island" }, { "CY", "Cyprus" }, { "CZ", "Czech Republic" }, { "DE", "Germany" }, { "DJ", "Djibouti" }, { "DK", "Denmark" }, { "DM", "Dominica" }, { "DO", "Dominican Republic" }, { "DZ", "Algeria" }, { "EC", "Ecuador" }, { "EE", "Estonia" }, { "EG", "Egypt" }, { "EH", "Western Sahara" }, { "ER", "Eritrea" }, { "ES", "Spain" }, { "ET", "Ethiopia" }, { "FI", "Finland" }, { "FJ", "Fiji" }, { "FK", "Falkland Islands" }, { "FM", "Micronesia" }, { "FO", "Faroe Islands" }, { "FR", "France" }, { "GA", "Gabon" }, { "GB", "United Kingdom" }, { "GD", "Grenada" }, { "GE", "Georgia" }, { "GF", "French Guiana" }, { "GG", "Guernsey" }, { "GH", "Ghana" }, { "GI", "Gibraltar" }, { "GL", "Greenland" }, { "GM", "Gambia" }, { "GN", "Guinea" }, { "GP", "Guadeloupe" }, { "GQ", "Equatorial Guinea" }, { "GR", "Greece" }, { "GS", "South Georgia and the South Sandwich Islands" }, { "GT", "Guatemala" }, { "GU", "Guam" }, { "GW", "Guinea-Bissau" }, { "GY", "Guyana" }, { "HK", "Hong Kong" }, { "HM", "Heard Island and McDonald Islands" }, { "HN", "Honduras" }, { "HR", "Croatia" }, { "HT", "Haiti" }, { "HU", "Hungary" }, { "ID", "Indonesia" }, { "IE", "Ireland" }, { "IL", "Israel" }, { "IM", "Isle of Man" }, { "IN", "India" }, { "IO", "British Indian Ocean Territory" }, { "IQ", "Iraq" }, { "IR", "Iran" }, { "IS", "Iceland" }, { "IT", "Italy" }, { "JE", "Jersey" }, { "JM", "Jamaica" }, { "JO", "Jordan" }, { "JP", "Japan" }, { "KE", "Kenya" }, { "KG", "Kyrgyzstan" }, { "KH", "Cambodia" }, { "KI", "Kiribati" }, { "KM", "Comoros" }, { "KN", "Saint Kitts and Nevis" }, { "KP", "North Korea" }, { "KR", "South Korea" }, { "KW", "Kuwait" }, { "KY", "Cayman Islands" }, { "KZ", "Kazakhstan" }, { "LA", "Laos" }, { "LB", "Lebanon" }, { "LC", "Saint Lucia" }, { "LI", "Liechtenstein" }, { "LK", "Sri Lanka" }, { "LR", "Liberia" }, { "LS", "Lesotho" }, { "LT", "Lithuania" }, { "LU", "Luxembourg" }, { "LV", "Latvia" }, { "LY", "Libya" }, { "MA", "Morocco" }, { "MC", "Monaco" }, { "MD", "Moldova" }, { "ME", "Montenegro" }, { "MF", "Saint Martin" }, { "MG", "Madagascar" }, { "MH", "Marshall Islands" }, { "MK", "Macedonia" }, { "ML", "Mali" }, { "MM", "Myanmar" }, { "MN", "Mongolia" }, { "MO", "Macao" }, { "MP", "Northern Mariana Islands" }, { "MQ", "Martinique" }, { "MR", "Mauritania" }, { "MS", "Montserrat" }, { "MT", "Malta" }, { "MU", "Mauritius" }, { "MV", "Maldives" }, { "MW", "Malawi" }, { "MX", "Mexico" }, { "MY", "Malaysia" }, { "MZ", "Mozambique" }, { "NA", "Namibia" }, { "NC", "New Caledonia" }, { "NE", "Niger" }, { "NF", "Norfolk Island" }, { "NG", "Nigeria" }, { "NI", "Nicaragua" }, { "NL", "Netherlands" }, { "NO", "Norway" }, { "NP", "Nepal" }, { "NR", "Nauru" }, { "NU", "Niue" }, { "NZ", "New Zealand" }, { "OM", "Oman" }, { "PA", "Panama" }, { "PE", "Peru" }, { "PF", "French Polynesia" }, { "PG", "Papua New Guinea" }, { "PH", "Philippines" }, { "PK", "Pakistan" }, { "PL", "Poland" }, { "PM", "Saint Pierre and Miquelon" }, { "PN", "Pitcairn" }, { "PR", "Puerto Rico" }, { "PS", "Palestinian Territory" }, { "PT", "Portugal" }, { "PW", "Palau" }, { "PY", "Paraguay" }, { "QA", "Qatar" }, { "RE", "Reunion" }, { "RO", "Romania" }, { "RS", "Serbia" }, { "RU", "Russia" }, { "RW", "Rwanda" }, { "SA", "Saudi Arabia" }, { "SB", "Solomon Islands" }, { "SC", "Seychelles" }, { "SD", "Sudan" }, { "SE", "Sweden" }, { "SG", "Singapore" }, { "SH", "Saint Helena" }, { "SI", "Slovenia" }, { "SJ", "Svalbard and Jan Mayen" }, { "SK", "Slovakia" }, { "SL", "Sierra Leone" }, { "SM", "San Marino" }, { "SN", "Senegal" }, { "SO", "Somalia" }, { "SR", "Suriname" }, { "ST", "Sao Tome and Principe" }, { "SV", "El Salvador" }, { "SY", "Syria" }, { "SZ", "Swaziland" }, { "TC", "Turks and Caicos Islands" }, { "TD", "Chad" }, { "TF", "French Southern Territories" }, { "TG", "Togo" }, { "TH", "Thailand" }, { "TJ", "Tajikistan" }, { "TK", "Tokelau" }, { "TL", "East Timor" }, { "TM", "Turkmenistan" }, { "TN", "Tunisia" }, { "TO", "Tonga" }, { "TR", "Turkey" }, { "TT", "Trinidad and Tobago" }, { "TV", "Tuvalu" }, { "TW", "Taiwan" }, { "TZ", "Tanzania" }, { "UA", "Ukraine" }, { "UG", "Uganda" }, { "UM", "United States Minor Outlying Islands" }, { "US", "United States" }, { "UY", "Uruguay" }, { "UZ", "Uzbekistan" }, { "VA", "Vatican" }, { "VC", "Saint Vincent and the Grenadines" }, { "VE", "Venezuela" }, { "VG", "British Virgin Islands" }, { "VI", "U.S. Virgin Islands" }, { "VN", "Vietnam" }, { "VU", "Vanuatu" }, { "WF", "Wallis and Futuna" }, { "WS", "Samoa" }, { "YE", "Yemen" }, { "YT", "Mayotte" }, { "ZA", "South Africa" }, { "ZM", "Zambia" }, { "ZW", "Zimbabwe" }, }; return countryData; } public static String solveCountryCode(String countryName) { if(countryName == null) return null; String countryCode = null; String[][] countryData = getCountryData(); for(int j=0; j<countryData.length; j++) { if(countryName.equalsIgnoreCase(countryData[j][1])) { countryCode = countryData[j][0]; break; } } return countryCode; } public static String solveCountryName(String countryCode) { if(countryCode == null) return null; String countryName = null; String[][] countryData = getCountryData(); for(int j=0; j<countryData.length; j++) { if(countryCode.equalsIgnoreCase(countryData[j][0])) { countryName = countryData[j][1]; break; } } return countryName; } // ------------------------------------------------------------------------- // ------------------------------------------------------------- WEATHER --- // ------------------------------------------------------------------------- protected static Topic getWeatherObservationTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, WEATHER_OBSERVATION_SI, "weather observation (geonames)"); Topic gnClass = getGeoNamesClassTopic(tm); makeSubclassOf(tm, type, gnClass); return type; } protected static Topic getWeatherObservationTimeTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, WEATHER_OBSERVATIONTIME_SI, "weather observation time (geonames)"); return type; } protected static Topic getWeatherStationTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, WEATHER_STATION_SI, "weather station (geonames)"); Topic gnClass = getGeoNamesClassTopic(tm); makeSubclassOf(tm, type, gnClass); return type; } protected static Topic getWeatherICAOTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, WEATHER_ICAO_SI, "weather station ICAO (geonames)"); return type; } protected static Topic getWeatherElevationTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, WEATHER_ELEVATION_SI, "weather station elevation (geonames)"); return type; } protected static Topic getWeatherTemperatureTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, WEATHER_TEMPERATURE_SI, "weather temperature (geonames)"); return type; } protected static Topic getWeatherDewPointTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, WEATHER_DEWPOINT_SI, "weather dew point (geonames)"); return type; } protected static Topic getWeatherHumidityTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, WEATHER_HUMIDITY_SI, "weather humidity (geonames)"); return type; } protected static Topic getWeatherCloudsTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, WEATHER_CLOUDS_SI, "weather clouds (geonames)"); return type; } protected static Topic getWeatherConditionTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, WEATHER_WEATHERCONDITION_SI, "weather condition (geonames)"); return type; } protected static Topic getWeatherHectoPascAltimeterTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, WEATHER_HECTOPASCALTIMETER_SI, "weather hectopascaltimeter (geonames)"); return type; } protected static Topic getWeatherWindDirectionTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, WEATHER_WINDDIRECTION_SI, "weather wind direction (geonames)"); return type; } protected static Topic getWeatherWindSpeedTypeTopic(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, WEATHER_WINDSPEED_SI, "weather wind speed (geonames)"); return type; } public static Topic getWeatherObservationTopic(TopicMap tm, String observation, String lang) throws TopicMapException { String observationSI = null; try { observationSI = WEATHER_OBSERVATION_SI + "/" + URLEncoder.encode(observation, "UTF-8"); } catch(Exception e) { observationSI = WEATHER_OBSERVATION_SI + "/" + observation; } Topic theObservation = null; if(USE_EXISTING_TOPICS) theObservation = tm.getTopic(observationSI); if(theObservation == null) { Topic observationType = getWeatherObservationTypeTopic(tm); theObservation=tm.createTopic(); theObservation.addSubjectIdentifier(tm.createLocator(observationSI)); if(observation != null && observation.length() > 0) theObservation.setBaseName(observation); theObservation.addType(observationType); } return theObservation; } public static Topic getWeatherStationTopic(TopicMap tm, String station, String lang) throws TopicMapException { String stationSI = null; try { stationSI = WEATHER_STATION_SI + "/" + URLEncoder.encode(station, "UTF-8"); } catch(Exception e) { stationSI = WEATHER_STATION_SI + "/" + station; } Topic theStation = null; if(USE_EXISTING_TOPICS) theStation = tm.getTopic(stationSI); if(theStation == null) { Topic stationType = getWeatherStationTypeTopic(tm); theStation=tm.createTopic(); theStation.addSubjectIdentifier(tm.createLocator(stationSI)); if(station != null && station.length() > 0) theStation.setBaseName(station); theStation.addType(stationType); } return theStation; } public static Topic getWeatherCloudsTopic(TopicMap tm, String clouds, String lang) throws TopicMapException { String cloudsSI = null; try { cloudsSI = WEATHER_CLOUDS_SI + "/" + URLEncoder.encode(clouds, "UTF-8"); } catch(Exception e) { cloudsSI = WEATHER_CLOUDS_SI + "/" + clouds; } Topic theClouds = null; if(USE_EXISTING_TOPICS) theClouds = tm.getTopic(cloudsSI); if(theClouds == null) { Topic cloudsType = getWeatherCloudsTypeTopic(tm); theClouds=tm.createTopic(); theClouds.addSubjectIdentifier(tm.createLocator(cloudsSI)); if(clouds != null && clouds.length() > 0) theClouds.setBaseName(clouds); theClouds.addType(cloudsType); } return theClouds; } public static void makeWeatherStation(Topic observation, Topic station, TopicMap tm) throws TopicMapException { if(observation == null || station == null || observation.mergesWithTopic(station)) return; Topic stationType=getWeatherStationTypeTopic(tm); Topic observationType=getWeatherObservationTypeTopic(tm); Association a=tm.createAssociation(stationType); a.addPlayer(station, stationType); a.addPlayer(observation, observationType); } public static void makeWeatherClouds(Topic observation, Topic clouds, TopicMap tm) throws TopicMapException { if(observation == null || clouds == null || observation.mergesWithTopic(clouds)) return; Topic cloudsType=getWeatherCloudsTypeTopic(tm); Topic observationType=getWeatherObservationTypeTopic(tm); Association a=tm.createAssociation(cloudsType); a.addPlayer(clouds, cloudsType); a.addPlayer(observation, observationType); } // ------------------------------------------------------------------------- }
58,280
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
GeoNamesWikipediaBBox.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/geonames/GeoNamesWikipediaBBox.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * GeoNamesWikipediaBBox.java * */ package org.wandora.application.tools.extractors.geonames; import java.io.InputStream; 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.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; /** * * @author akivela */ public class GeoNamesWikipediaBBox extends AbstractGeoNamesExtractor { private static final long serialVersionUID = 1L; public String dataLang = "en"; public String requestGeoObject = null; @Override public String getName() { return "GeoNames wikipedia bounding box extractor"; } @Override public String getDescription(){ return "Get wikipedia geo locations in given bounding box from GeoNames web api and convert 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(); GeoNamesWikipediaBBoxParser parserHandler = new GeoNamesWikipediaBBoxParser(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 geo objects found!"); else if(parserHandler.progress == 1) log("One geo object found!"); else log("Total " + parserHandler.progress + " geo objects found!"); requestGeoObject = null; // FORCE NULL AS THIS OBJECT IS REUSED. return true; } // ------------------------------------------------------------------------- // --- GEONAMES XML FEED PARSER -------------------------------------------- // ------------------------------------------------------------------------- private class GeoNamesWikipediaBBoxParser extends AbstractGeoNamesWikipediaParser { public GeoNamesWikipediaBBoxParser(TopicMap tm, AbstractGeoNamesExtractor parent, String lang){ super(tm, parent, lang); } public void handleEntryElement() { if(data_title.length() > 0) { try { Topic wikiGeoObject = getWikipediaGeoTopic(tm, data_title, data_wikipediaurl, lang); parent.setProgress(progress++); try { if(isValid(data_summary)) { Topic typeTopic = getWikipediaSummaryTypeTopic(tm); wikiGeoObject.setData(typeTopic, TMBox.getLangTopic(wikiGeoObject, lang), data_summary); } if(isValid(data_thumbnailimg)) { Topic img = tm.createTopic(); img.addSubjectIdentifier(new org.wandora.topicmap.Locator(data_thumbnailimg)); img.setSubjectLocator(new org.wandora.topicmap.Locator(data_thumbnailimg)); Topic imgTypeTopic = getWikipediaThumbnailTypeTopic(tm); Topic geoType = getWikipediaGeoObjectTypeTopic(tm); Association a = tm.createAssociation(imgTypeTopic); a.addPlayer(img, imgTypeTopic); a.addPlayer(wikiGeoObject, geoType); } if(isValid(data_feature)) { Topic featureTopic = getWikipediaGeoFeatureTopic(tm, data_feature); wikiGeoObject.addType(featureTopic); } if(isValid(data_countrycode)) { Topic countryTopic=getCountryTopic(tm, data_countrycode, lang); makeGeoCountry(wikiGeoObject, countryTopic, tm); } if(isValid(data_lat) && isValid(data_lng)) { makeLatLong(data_lat, data_lng, wikiGeoObject, tm); } if(isValid(data_population) && !data_population.equals("0")) { Topic populationTypeTopic = getPopulationTypeTopic(tm); wikiGeoObject.setData(populationTypeTopic, TMBox.getLangTopic(wikiGeoObject, lang), data_population); } } catch(Exception e) { parent.log(e); } } catch(TopicMapException tme){ parent.log(tme); } } } } }
6,807
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
GeoNamesChildren.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/geonames/GeoNamesChildren.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * GeoNamesChildren.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/children?geonameId=3175395&style=full * * @author akivela */ public class GeoNamesChildren extends AbstractGeoNamesExtractor { private static final long serialVersionUID = 1L; public String dataLang = "en"; public String requestGeoObject = null; @Override public String getName() { return "GeoNames children extractor"; } @Override public String getDescription(){ return "Get children of given geo location and convert 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(); ChildrenParser parserHandler = new ChildrenParser(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 childrens found!"); else if(parserHandler.progress == 1) log("One children found!"); else log("Total " + parserHandler.progress + " childrens found!"); requestGeoObject = null; // FORCE NULL AS THIS OBJECT IS REUSED. return true; } // ------------------------------------------------------------------------- // --- GEONAMES XML FEED PARSER -------------------------------------------- // ------------------------------------------------------------------------- private static class ChildrenParser extends AbstractGeoNamesParser { public ChildrenParser(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(data_fcode != null && data_fcode.length() > 0) { Topic fcodeTopic = getFCodeTopic(tm, data_fcode, data_fcodename); theGeoObject.addType(fcodeTopic); } if(data_fcl != null && data_fcl.length() > 0) { Topic fclTopic = getFCLTopic(tm, data_fcl, data_fclname); theGeoObject.addType(fclTopic); } if(data_countrycode != null && data_countrycode.length() > 0 && data_countryname != null && data_countryname.length() > 0) { Topic countryTopic=getCountryTopic(tm, data_countrycode, data_countryname, lang); if(theGeoObject.isRemoved()) theGeoObject=tm.getTopic(theGeoObjectSI); makeGeoCountry(theGeoObject, countryTopic, tm); } if(data_continentcode != null && data_continentcode.length() > 0) { Topic continentTopic=getContinentTopic(tm, data_continentcode); if(theGeoObject.isRemoved()) theGeoObject=tm.getTopic(theGeoObjectSI); makeGeoContinent(theGeoObject, continentTopic, tm); } if(requestGeoObject != null && requestGeoObject.length() > 0) { Topic requestTopic=getGeoTopic(tm, requestGeoObject); if(theGeoObject.isRemoved()) theGeoObject=tm.getTopic(theGeoObjectSI); makeChildParent(theGeoObject, requestTopic, tm); } if(data_lat!=null && data_lat.length()>0 && data_lng!=null && data_lng.length()>0) { 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(data_population != null && data_population.length() > 0) { 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,635
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
GeoNamesExtractorSelector.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/geonames/GeoNamesExtractorSelector.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * GeoNamesExtractorSelector.java * * Created on 11. lokakuuta 2008, 18:27 */ package org.wandora.application.tools.extractors.geonames; import java.awt.Component; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.application.gui.simple.SimpleButton; import org.wandora.application.gui.simple.SimpleLabel; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.utils.Tuples; /** * * @author akivela */ public class GeoNamesExtractorSelector extends javax.swing.JDialog { private static final long serialVersionUID = 1L; public static String BASE_URL = "http://api.geonames.org/"; private Wandora wandora = null; private Context context = null; private boolean accepted = false; /** Creates new form GeoNamesExtractorSelector */ public GeoNamesExtractorSelector(Wandora w) { super(w, true); initComponents(); initGUIDatas(); setSize(550,300); setTitle("GeoNames extractors"); w.centerWindow(this); this.wandora = w; accepted = false; } public void initGUIDatas() { searchCountryComboBox.setEditable(false); searchContinentComboBox.setEditable(false); searchFeatureClassComboBox.setEditable(false); findNearByFeatureComboBox.setEditable(false); // **** COUNTRIES **** String [][] countryData = AbstractGeoNamesExtractor.getCountryData(); ArrayList<String> countryNames = new ArrayList(); for(int i=0; i<countryData.length; i++) { countryNames.add(countryData[i][1]); } countryInfoComboBox.addItem(""); searchCountryComboBox.addItem(""); Collections.sort(countryNames); for(int i=0; i<countryNames.size(); i++) { countryInfoComboBox.addItem(countryNames.get(i)); searchCountryComboBox.addItem(countryNames.get(i)); } // **** CONTINENTS **** String [][] continentData = AbstractGeoNamesExtractor.getContinentData(); ArrayList<String> continentNames = new ArrayList(); for(int i=0; i<continentData.length; i++) { continentNames.add(continentData[i][1]); } searchContinentComboBox.addItem(""); Collections.sort(continentNames); for(int i=0; i<continentNames.size(); i++) { searchContinentComboBox.addItem(continentNames.get(i)); } // **** FEATURE CLASSES **** String [][] featureClassData = AbstractGeoNamesExtractor.getFeatureClassData(); ArrayList<String> featureClassNames = new ArrayList(); for(int i=0; i<featureClassData.length; i++) { featureClassNames.add(featureClassData[i][1]); } searchFeatureClassComboBox.addItem(""); findNearByFeatureComboBox.addItem(""); Collections.sort(featureClassNames); for(int i=0; i<featureClassNames.size(); i++) { searchFeatureClassComboBox.addItem(featureClassNames.get(i)); findNearByFeatureComboBox.addItem(featureClassNames.get(i)); } } public void setWandora(Wandora w) { this.wandora = w; } public void setContext(Context context) { this.context = context; } @Override public void setVisible(boolean v) { if(v) { if(apikey == null) forgetButton.setEnabled(false); else forgetButton.setEnabled(true); } super.setVisible(v); } public boolean wasAccepted() { return accepted; } public void setAccepted(boolean b) { accepted = b; } public WandoraTool getWandoraTool(WandoraTool parentTool) { Component component = geoNamesTabbedPane.getSelectedComponent(); WandoraTool wt = null; String requestLang = getRequestLanguage(); String username = solveAPIKey(); // ***** SEARCH ***** if(searchPanel.equals(component)) { String countryFilter = AbstractGeoNamesExtractor.solveCountryCode((String) searchCountryComboBox.getSelectedItem() ); String continentFilter = AbstractGeoNamesExtractor.solveContinentCode((String) searchContinentComboBox.getSelectedItem() ); String featureClassFilter = AbstractGeoNamesExtractor.solveFeatureClassCode((String) searchFeatureClassComboBox.getSelectedItem() ); boolean isNameRequired = searchIsNameRequiredCheckBox.isSelected(); String query = searchTextField.getText(); if(query == null) query = ""; String searchUrl = BASE_URL+"search?username="+username+"&style=full&maxRows=1000&lang="+urlEncode(requestLang); searchUrl += "&q="+urlEncode(query.trim()); if(countryFilter != null) { searchUrl += "&country="+countryFilter; } if(continentFilter != null) { searchUrl += "&continentCode="+continentFilter; } if(featureClassFilter != null) { searchUrl += "&featureClass="+featureClassFilter; } if(isNameRequired) { searchUrl += "&isNameRequired=true"; } GeoNamesSearch e = new GeoNamesSearch(); e.dataLang = requestLang; e.setForceUrls( new String[] { searchUrl } ); wt = e; } // ***** WIKIPEDIA SEARCH ***** if(wikiSearchPanel.equals(component)) { String query = wikiSearchTextField.getText(); if(query == null) query = ""; String searchUrl = BASE_URL+"wikipediaSearch?username="+username+"&maxRows=1000&lang="+urlEncode(requestLang); searchUrl += "&q="+urlEncode(query.trim()); GeoNamesWikipediaSearch e = new GeoNamesWikipediaSearch(); e.dataLang = requestLang; e.setForceUrls( new String[] { searchUrl } ); wt = e; } // ***** WIKIPEDIA BOUNDING BOX ***** if(wikiBoxPanel.equals(component)) { String northString = wikiBoxNorthTextField.getText(); String southString = wikiBoxSouthTextField.getText(); String westString = wikiBoxWestTextField.getText(); String eastString = wikiBoxEastTextField.getText(); if(!AbstractGeoNamesExtractor.isValidGPSCoordinate(northString)) { parentTool.log("Warning: North coordinate is not valid GPS number."); } if(!AbstractGeoNamesExtractor.isValidGPSCoordinate(southString)) { parentTool.log("Warning: South coordinate is not valid GPS number."); } if(!AbstractGeoNamesExtractor.isValidGPSCoordinate(westString)) { parentTool.log("Warning: West coordinate is not valid GPS number."); } if(!AbstractGeoNamesExtractor.isValidGPSCoordinate(eastString)) { parentTool.log("Warning: East coordinate is not valid GPS number."); } GeoNamesWikipediaBBox e = new GeoNamesWikipediaBBox(); e.dataLang = requestLang; e.setForceUrls( new String[] { BASE_URL+"wikipediaBoundingBox?username="+username+"&lang="+urlEncode(requestLang)+ "&maxRows=1000"+ "&north="+urlEncode(northString)+ "&south="+urlEncode(southString)+ "&east="+urlEncode(eastString)+ "&west="+urlEncode(westString) } ); wt = e; } // ***** FIND NEAR BY ***** else if(findNearByPanel.equals(component)) { String latString = findNearByLatTextField.getText(); String lonString = findNearByLonTextField.getText(); String featureClassFilter = AbstractGeoNamesExtractor.solveFeatureClassCode((String) searchFeatureClassComboBox.getSelectedItem() ); if(!AbstractGeoNamesExtractor.isValidGPSCoordinate(latString)) { parentTool.log("Warning: Latitude is not valid GPS number."); } if(!AbstractGeoNamesExtractor.isValidGPSCoordinate(lonString)) { parentTool.log("Warning: Longitude is not valid GPS number."); } FindNearByGeoNames e = new FindNearByGeoNames(); e.dataLang = requestLang; String urlStr = BASE_URL+"findNearby?username="+username+"&style=full&lang="+urlEncode(requestLang); urlStr += "&lat="+urlEncode(latString); urlStr += "&lng="+urlEncode(lonString); urlStr += "&maxRows=1000"; if(featureClassFilter != null && featureClassFilter.length()>0) { urlStr += "&featureClass="+featureClassFilter; } String radius = findNearByRadiusTextField.getText(); if(radius != null) { radius = radius.trim(); if(radius.length() > 0) { urlStr += "&radius="+urlEncode(radius); } } e.setForceUrls( new String[] { urlStr } ); wt = e; } // ***** COUNTRY INFO ***** else if(countryInfoPanel.equals(component)) { Object[] countryObjects = countryInfoComboBox.getSelectedObjects(); ArrayList<String> countries = new ArrayList<String>(); if(countryObjects == null || countryObjects.length == 0) { parentTool.log("No country codes given."); return null; } String country; String countryCode; String[][] countryData = AbstractGeoNamesExtractor.getCountryData(); for(int i=0; i<countryObjects.length; i++) { country = (String) countryObjects[i]; if("ALL".equalsIgnoreCase(country.trim())) { countries.add( BASE_URL+"countryInfo?username="+username+"&lang="+urlEncode(requestLang)); } else { String[] splitCountry = country.split(","); for(int k=0; k<splitCountry.length; k++) { countryCode = splitCountry[k].trim(); if(splitCountry[k] != null && splitCountry[k].length() > 0) { for(int j=0; j<countryData.length; j++) { if(splitCountry[k].equalsIgnoreCase(countryData[j][1])) { countryCode = countryData[j][0]; break; } } if(countryCode.length() != 2) parentTool.log("Warning: Found country code '"+countryCode+"' is not valid country code!"); countries.add( BASE_URL+"countryInfo?username="+username+"&lang="+urlEncode(requestLang)+"&country="+urlEncode(countryCode) ); } } } } GeoNamesCountryInfo cie = new GeoNamesCountryInfo(); cie.dataLang = requestLang; cie.setForceUrls( countries.toArray( new String[] {} )); wt = cie; } // ***** CITIES ***** else if(citiesPanel.equals(component)) { String northString = citiesNorthTextField.getText(); String southString = citiesSouthTextField.getText(); String westString = citiesWestTextField.getText(); String eastString = citiesEastTextField.getText(); if(!AbstractGeoNamesExtractor.isValidGPSCoordinate(northString)) { parentTool.log("Warning: North coordinate is not valid GPS number."); } if(!AbstractGeoNamesExtractor.isValidGPSCoordinate(southString)) { parentTool.log("Warning: South coordinate is not valid GPS number."); } if(!AbstractGeoNamesExtractor.isValidGPSCoordinate(westString)) { parentTool.log("Warning: West coordinate is not valid GPS number."); } if(!AbstractGeoNamesExtractor.isValidGPSCoordinate(eastString)) { parentTool.log("Warning: East coordinate is not valid GPS number."); } GeoNamesCities ce = new GeoNamesCities(); ce.dataLang = requestLang; ce.setForceUrls( new String[] { BASE_URL+"cities?username="+username+"&lang="+urlEncode(requestLang)+ "&north="+urlEncode(northString)+ "&south="+urlEncode(southString)+ "&east="+urlEncode(eastString)+ "&west="+urlEncode(westString) } ); wt = ce; } // ***** CHILDREN ***** else if(childrenPanel.equals(component)) { String geoidstr = childrenTextField.getText(); String[] geoids = urlEncode(commaSplitter(geoidstr)); String[] geoUrls = completeString(BASE_URL+"children?username="+username+"&style=full&lang="+urlEncode(requestLang)+"&geonameId=__1__", geoids); GeoNamesChildren che = new GeoNamesChildren(); che.dataLang = requestLang; che.setForceUrls( geoUrls ); wt = che; } // ***** HIERARCHY ***** else if(hierarchyPanel.equals(component)) { String geoidstr = hierarchyTextField.getText(); String[] geoids = urlEncode(commaSplitter(geoidstr)); String[] geoUrls = completeString(BASE_URL+"hierarchy?username="+username+"&style=full&lang="+urlEncode(requestLang)+"&geonameId=__1__", geoids); GeoNamesHierarchy hie = new GeoNamesHierarchy(); hie.dataLang = requestLang; hie.setForceUrls( geoUrls ); wt = hie; } // ***** NEIGHBOURS ***** else if(neighboursPanel.equals(component)) { String geoidstr = neighboursTextField.getText(); String[] geoids = urlEncode(commaSplitter(geoidstr)); String[] geoUrls = completeString(BASE_URL+"neighbours?username="+username+"&style=full&lang="+urlEncode(requestLang)+"&geonameId=__1__", geoids); GeoNamesNeighbours e = new GeoNamesNeighbours(); e.dataLang = requestLang; e.setForceUrls( geoUrls ); wt = e; } // ***** SIBLINGS ***** else if(siblingsPanel.equals(component)) { String geoidstr = siblingsTextField.getText(); String[] geoids = urlEncode(commaSplitter(geoidstr)); String[] geoUrls = completeString(BASE_URL+"siblings?username="+username+"&style=full&lang="+urlEncode(requestLang)+"&geonameId=__1__", geoids); GeoNamesSiblings e = new GeoNamesSiblings(); e.dataLang = requestLang; e.setForceUrls( geoUrls ); wt = e; } // ***** WEATHER ***** else if(weatherPanel.equals(component)) { String latString = weatherLatTextField.getText(); String lonString = weatherLonTextField.getText(); if(!AbstractGeoNamesExtractor.isValidGPSCoordinate(latString)) { parentTool.log("Warning: Latitude is not valid GPS number."); } if(!AbstractGeoNamesExtractor.isValidGPSCoordinate(lonString)) { parentTool.log("Warning: Longitude is not valid GPS number."); } GeoNamesNearByWeather e = new GeoNamesNearByWeather(); e.dataLang = requestLang; String urlStr = BASE_URL+"findNearByWeatherXML?username="+username+""; urlStr += "&lat="+urlEncode(latString); urlStr += "&lng="+urlEncode(lonString); e.setForceUrls( new String[] { urlStr } ); wt = e; } return wt; } public String[] commaSplitter(String str) { if(str.indexOf(',') != -1) { String[] strs = str.split(","); ArrayList<String> strList = new ArrayList<String>(); String s = null; for(int i=0; i<strs.length; i++) { s = strs[i]; s = s.trim(); if(s.length() > 0) { strList.add(s); } } return strList.toArray( new String[] {} ); } else { return new String[] { str }; } } public String[] completeString(String template, String[] strs) { if(strs == null || template == null) return null; String[] completed = new String[strs.length]; for(int i=0; i<strs.length; i++) { completed[i] = template.replaceAll("__1__", strs[i]); } return completed; } public String[] completeString(String template, String[] strs1, String[] strs2) { if(strs1 == null || strs2 == null || template == null) return null; if(strs1.length != strs2.length) return null; String[] completed = new String[strs1.length]; for(int i=0; i<strs1.length; i++) { completed[i] = template.replaceAll("__1__", strs1[i]); completed[i] = completed[i].replaceAll("__2__", strs2[i]); } return completed; } public String[] urlEncode(String[] urls) { if(urls == null) return null; String[] cleanUrls = new String[urls.length]; for(int i=0; i<urls.length; i++) { cleanUrls[i] = urlEncode(urls[i]); } return cleanUrls; } public String urlEncode(String url) { try { return URLEncoder.encode(url, "UTF-8"); } catch(Exception e) { return url; } } public void solveCountryContext() { 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(AbstractGeoNamesExtractor.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(); } } String contextStr= sb.toString(); if(contextStr != null || contextStr.length() == 0) { countryInfoComboBox.addItem(contextStr); countryInfoComboBox.setSelectedItem(contextStr); } } public Tuples.T2 solveGPSLocation() { if(context != null) { try { Iterator contextObjects = context.getContextObjects(); Object o = null; boolean found = false; while(contextObjects.hasNext() && !found) { o = contextObjects.next(); if(o instanceof Topic) { Topic t = (Topic) o; if(t != null && !t.isRemoved()) { Collection<Association> as = t.getAssociations(AbstractGeoNamesExtractor.getLocationTypeTopic(t.getTopicMap())); Association a = null; for(Iterator<Association> ai = as.iterator(); ai.hasNext() && !found; ) { a = ai.next(); if(a != null && !a.isRemoved()) { Topic lat = a.getPlayer(AbstractGeoNamesExtractor.getLatTypeTopic(t.getTopicMap())); Topic lon = a.getPlayer(AbstractGeoNamesExtractor.getLngTypeTopic(t.getTopicMap())); if(lat != null && !lat.isRemoved() && lon != null && !lon.isRemoved()) { String latStr = lat.getDisplayName(null); String lonStr = lon.getDisplayName(null); return new Tuples.T2(latStr, lonStr); } } } } } } } catch(Exception e) { e.printStackTrace(); } } return null; } public Tuples.T4 solveGPSBoundingBox() { if(context != null) { try { Iterator contextObjects = context.getContextObjects(); Object o = null; boolean found = false; while(contextObjects.hasNext() && !found) { o = contextObjects.next(); if(o instanceof Topic) { Topic t = (Topic) o; if(t != null && !t.isRemoved()) { Collection<Association> as = t.getAssociations(AbstractGeoNamesExtractor.getBBoxTypeTopic(t.getTopicMap())); Association a = null; for(Iterator<Association> ai = as.iterator(); ai.hasNext() && !found; ) { a = ai.next(); if(a != null && !a.isRemoved()) { Topic nt = a.getPlayer(AbstractGeoNamesExtractor.getBBoxNorthTypeTopic(t.getTopicMap())); Topic st = a.getPlayer(AbstractGeoNamesExtractor.getBBoxSouthTypeTopic(t.getTopicMap())); Topic et = a.getPlayer(AbstractGeoNamesExtractor.getBBoxEastTypeTopic(t.getTopicMap())); Topic wt = a.getPlayer(AbstractGeoNamesExtractor.getBBoxWestTypeTopic(t.getTopicMap())); if(nt != null && !nt.isRemoved() && st != null && !st.isRemoved() && et != null && !et.isRemoved() && wt != null && !wt.isRemoved()) { String nc = nt.getDisplayName(null); String sc = st.getDisplayName(null); String ec = et.getDisplayName(null); String wc = wt.getDisplayName(null); return new Tuples.T4(nc, wc, sc, ec); } } } } } } } catch(Exception e) { e.printStackTrace(); } } return null; } public String solveGeonameIdContext() { StringBuffer sb = new StringBuffer(""); if(context != null) { try { Iterator contextObjects = context.getContextObjects(); String str = null; String lstr = null; Object o = null; boolean isFirst = true; while(contextObjects.hasNext()) { str = null; o = contextObjects.next(); if(o instanceof Topic) { Topic t = (Topic) o; Collection<Locator> sis = t.getSubjectIdentifiers(); Locator l = null; for(Iterator<Locator> sii = sis.iterator(); sii.hasNext(); ) { l = sii.next(); if(l != null) { lstr = l.toExternalForm(); if(lstr != null && lstr.startsWith(AbstractGeoNamesExtractor.GEONAMEID_SI)) { str = lstr.substring(AbstractGeoNamesExtractor.GEONAMEID_SI.length()); while(str.startsWith("/")) str = str.substring(1); while(str.endsWith("/")) str = str.substring(0,str.length()-1); str = str.trim(); if(str.length() > 0) { if(!isFirst) { sb.append(", "); } sb.append(str); isFirst = false; } } else if(lstr != null && lstr.startsWith("http://sws.geonames.org/")) { str = lstr.substring("http://sws.geonames.org/".length()); while(str.startsWith("/")) str = str.substring(1); while(str.endsWith("/")) str = str.substring(0,str.length()-1); str = str.trim(); if(str.length() > 0) { if(!isFirst) { sb.append(", "); } sb.append(str); isFirst = false; } } } } } } } catch(Exception e) { e.printStackTrace(); } } return sb.toString(); } public String getRequestLanguage() { String lan = langTextField.getText(); if(lan != null) { lan = lan.trim(); return lan; } return "en"; } /** 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; geoNamesTabbedPane = new org.wandora.application.gui.simple.SimpleTabbedPane(); searchPanel = new javax.swing.JPanel(); searchPanelInner = new javax.swing.JPanel(); searchLabel = new org.wandora.application.gui.simple.SimpleLabel(); searchTextField = new org.wandora.application.gui.simple.SimpleField(); searchFilterPanel = new javax.swing.JPanel(); searchContinentLabel = new org.wandora.application.gui.simple.SimpleLabel(); searchContinentComboBox = new org.wandora.application.gui.simple.SimpleComboBox(); searchCountryLabel = new org.wandora.application.gui.simple.SimpleLabel(); searchCountryComboBox = new org.wandora.application.gui.simple.SimpleComboBox(); searchFeatureLabel = new org.wandora.application.gui.simple.SimpleLabel(); searchFeatureClassComboBox = new org.wandora.application.gui.simple.SimpleComboBox(); searchIsNameRequiredLabel = new org.wandora.application.gui.simple.SimpleLabel(); searchIsNameRequiredCheckBox = new javax.swing.JCheckBox(); findNearByPanel = new javax.swing.JPanel(); findNearByPanelInner = new javax.swing.JPanel(); findNearByLabel = new org.wandora.application.gui.simple.SimpleLabel(); findNearByCoordinatesPanel = new javax.swing.JPanel(); findNearByLatLabel = new org.wandora.application.gui.simple.SimpleLabel(); findNearByLatTextField = new org.wandora.application.gui.simple.SimpleField(); findNearByLonLabel = new org.wandora.application.gui.simple.SimpleLabel(); findNearByLonTextField = new org.wandora.application.gui.simple.SimpleField(); findNearByGetContextButton = new org.wandora.application.gui.simple.SimpleButton(); findNearByFilterPanel = new javax.swing.JPanel(); findNearByradiusLabel = new SimpleLabel(); findNearByRadiusTextField = new javax.swing.JTextField(); findNearByFeatureLabel = new org.wandora.application.gui.simple.SimpleLabel(); findNearByFeatureComboBox = new org.wandora.application.gui.simple.SimpleComboBox(); countryInfoPanel = new javax.swing.JPanel(); countryInfoPanelInner = new javax.swing.JPanel(); countryInfoLabel = new org.wandora.application.gui.simple.SimpleLabel(); countryInfoComboBox = new org.wandora.application.gui.simple.SimpleComboBox(); countryInfoButton = new org.wandora.application.gui.simple.SimpleButton(); citiesPanel = new javax.swing.JPanel(); citiesPanelInner = new javax.swing.JPanel(); citiesLabel = new org.wandora.application.gui.simple.SimpleLabel(); citiesCoordinatesPanel = new javax.swing.JPanel(); citiesNorthTextField = new org.wandora.application.gui.simple.SimpleField(); citiesSouthTextField = new org.wandora.application.gui.simple.SimpleField(); citiesEastTextField = new org.wandora.application.gui.simple.SimpleField(); citiesWestTextField = new org.wandora.application.gui.simple.SimpleField(); citiesGetContextButton = new org.wandora.application.gui.simple.SimpleButton(); childrenPanel = new javax.swing.JPanel(); childrenPanelInner = new javax.swing.JPanel(); childrenLabel = new org.wandora.application.gui.simple.SimpleLabel(); childrenTextField = new org.wandora.application.gui.simple.SimpleField(); childrenGetContextButton = new org.wandora.application.gui.simple.SimpleButton(); hierarchyPanel = new javax.swing.JPanel(); hierarchyPanelInner = new javax.swing.JPanel(); hierarchyLabel = new org.wandora.application.gui.simple.SimpleLabel(); hierarchyTextField = new org.wandora.application.gui.simple.SimpleField(); hierarchyGetContextButton = new org.wandora.application.gui.simple.SimpleButton(); neighboursPanel = new javax.swing.JPanel(); neighboursPanelInner = new javax.swing.JPanel(); neigboursLabel = new org.wandora.application.gui.simple.SimpleLabel(); neighboursTextField = new org.wandora.application.gui.simple.SimpleField(); neighboursGetContextButton = new org.wandora.application.gui.simple.SimpleButton(); siblingsPanel = new javax.swing.JPanel(); siblingsPanelInner = new javax.swing.JPanel(); siblingsLabel = new org.wandora.application.gui.simple.SimpleLabel(); siblingsTextField = new org.wandora.application.gui.simple.SimpleField(); siblingsGetContextButton = new org.wandora.application.gui.simple.SimpleButton(); weatherPanel = new javax.swing.JPanel(); weatherPanelInner = new javax.swing.JPanel(); weatherLabel = new javax.swing.JLabel(); weatherCoordinatesPanel = new javax.swing.JPanel(); weatherLatLabel = new org.wandora.application.gui.simple.SimpleLabel(); weatherLatTextField = new org.wandora.application.gui.simple.SimpleField(); weatherLonLabel = new org.wandora.application.gui.simple.SimpleLabel(); weatherLonTextField = new org.wandora.application.gui.simple.SimpleField(); weatherGetContextButton = new org.wandora.application.gui.simple.SimpleButton(); wikiSearchPanel = new javax.swing.JPanel(); wikiSearchPanelInner = new javax.swing.JPanel(); wikiSearchLabel = new org.wandora.application.gui.simple.SimpleLabel(); wikiSearchTextField = new org.wandora.application.gui.simple.SimpleField(); wikiBoxPanel = new javax.swing.JPanel(); wikiBoxPanelInner = new javax.swing.JPanel(); wikiBoxLabel = new org.wandora.application.gui.simple.SimpleLabel(); wikiBoxCoordinatesPanel = new javax.swing.JPanel(); wikiBoxNorthTextField = new org.wandora.application.gui.simple.SimpleField(); wikiBoxSouthTextField = new org.wandora.application.gui.simple.SimpleField(); wikiBoxEastTextField = new org.wandora.application.gui.simple.SimpleField(); wikiBoxWestTextField = new org.wandora.application.gui.simple.SimpleField(); wikiBoxGetContextButton = new org.wandora.application.gui.simple.SimpleButton(); buttonPanel = new javax.swing.JPanel(); langPanel = new javax.swing.JPanel(); langTextField = new org.wandora.application.gui.simple.SimpleField(); langLabel = new org.wandora.application.gui.simple.SimpleLabel(); fillerPanel = new javax.swing.JPanel(); forgetButton = new SimpleButton(); buttonSeparator = new javax.swing.JSeparator(); okButton = new SimpleButton(); cancelButton = new SimpleButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); getContentPane().setLayout(new java.awt.GridBagLayout()); searchPanel.setLayout(new java.awt.GridBagLayout()); searchPanelInner.setLayout(new java.awt.GridBagLayout()); searchLabel.setText("<html>This tab is used to perform GeoName searches. Write search word below and select possible filters.</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, 6, 0); searchPanelInner.add(searchLabel, 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, 3, 0); searchPanelInner.add(searchTextField, gridBagConstraints); searchFilterPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Filters", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, org.wandora.application.gui.UIConstants.tabFont)); searchFilterPanel.setLayout(new java.awt.GridBagLayout()); searchContinentLabel.setText("continent filter"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 5); searchFilterPanel.add(searchContinentLabel, 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, 1, 4); searchFilterPanel.add(searchContinentComboBox, gridBagConstraints); searchCountryLabel.setText("country filter"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 5); searchFilterPanel.add(searchCountryLabel, 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, 1, 4); searchFilterPanel.add(searchCountryComboBox, gridBagConstraints); searchFeatureLabel.setText("feature class filter"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 5); searchFilterPanel.add(searchFeatureLabel, 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, 1, 4); searchFilterPanel.add(searchFeatureClassComboBox, gridBagConstraints); searchIsNameRequiredLabel.setText("name is required"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 5); searchFilterPanel.add(searchIsNameRequiredLabel, gridBagConstraints); searchIsNameRequiredCheckBox.setMargin(new java.awt.Insets(1, 0, 1, 2)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 1, 4); searchFilterPanel.add(searchIsNameRequiredCheckBox, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; searchPanelInner.add(searchFilterPanel, 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, 10, 4, 10); searchPanel.add(searchPanelInner, gridBagConstraints); geoNamesTabbedPane.addTab("Search", searchPanel); findNearByPanel.setLayout(new java.awt.GridBagLayout()); findNearByPanelInner.setLayout(new java.awt.GridBagLayout()); findNearByLabel.setText("<html>Find geo names near given location. Location is specified by latitude and longitude coordinates. You can also filter result set with given feature class.</html>"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 6, 0); findNearByPanelInner.add(findNearByLabel, gridBagConstraints); findNearByCoordinatesPanel.setLayout(new java.awt.GridBagLayout()); findNearByLatLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); findNearByLatLabel.setText("latitude"); findNearByLatLabel.setMaximumSize(new java.awt.Dimension(90, 14)); findNearByLatLabel.setMinimumSize(new java.awt.Dimension(90, 14)); findNearByLatLabel.setPreferredSize(new java.awt.Dimension(90, 14)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 1, 5); findNearByCoordinatesPanel.add(findNearByLatLabel, 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, 1, 0); findNearByCoordinatesPanel.add(findNearByLatTextField, gridBagConstraints); findNearByLonLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); findNearByLonLabel.setText("longitude"); findNearByLonLabel.setMaximumSize(new java.awt.Dimension(90, 14)); findNearByLonLabel.setMinimumSize(new java.awt.Dimension(90, 14)); findNearByLonLabel.setPreferredSize(new java.awt.Dimension(90, 14)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); findNearByCoordinatesPanel.add(findNearByLonLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; findNearByCoordinatesPanel.add(findNearByLonTextField, gridBagConstraints); findNearByGetContextButton.setText("Get context"); findNearByGetContextButton.setMargin(new java.awt.Insets(2, 3, 2, 3)); findNearByGetContextButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { findNearByGetContextButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridheight = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 2, 1, 0); findNearByCoordinatesPanel.add(findNearByGetContextButton, 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, 1, 0); findNearByPanelInner.add(findNearByCoordinatesPanel, gridBagConstraints); findNearByFilterPanel.setLayout(new java.awt.GridBagLayout()); findNearByradiusLabel.setText("radius (km)"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 1, 5); findNearByFilterPanel.add(findNearByradiusLabel, 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, 1, 0); findNearByFilterPanel.add(findNearByRadiusTextField, gridBagConstraints); findNearByFeatureLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); findNearByFeatureLabel.setText("feature class"); findNearByFeatureLabel.setMaximumSize(new java.awt.Dimension(90, 14)); findNearByFeatureLabel.setMinimumSize(new java.awt.Dimension(90, 14)); findNearByFeatureLabel.setPreferredSize(new java.awt.Dimension(90, 14)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); findNearByFilterPanel.add(findNearByFeatureLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; findNearByFilterPanel.add(findNearByFeatureComboBox, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; findNearByPanelInner.add(findNearByFilterPanel, 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, 10, 4, 10); findNearByPanel.add(findNearByPanelInner, gridBagConstraints); geoNamesTabbedPane.addTab("Near by", findNearByPanel); countryInfoPanel.setLayout(new java.awt.GridBagLayout()); countryInfoPanelInner.setLayout(new java.awt.GridBagLayout()); countryInfoLabel.setText("<html>Get country related data from GeoNames. Select country name or write two letter geonames country code(s) below. Separate different country codes with comma (,) character. Use keyword ALL to get all available countries. You can also try to get country codes from context topics.</html>"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 8, 0); countryInfoPanelInner.add(countryInfoLabel, gridBagConstraints); countryInfoComboBox.setEditable(true); 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, 8, 0); countryInfoPanelInner.add(countryInfoComboBox, gridBagConstraints); countryInfoButton.setText("Get context"); countryInfoButton.setMargin(new java.awt.Insets(2, 6, 2, 6)); countryInfoButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { countryInfoButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; countryInfoPanelInner.add(countryInfoButton, 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, 10, 4, 10); countryInfoPanel.add(countryInfoPanelInner, gridBagConstraints); geoNamesTabbedPane.addTab("Country info", countryInfoPanel); citiesPanel.setLayout(new java.awt.GridBagLayout()); citiesPanelInner.setLayout(new java.awt.GridBagLayout()); citiesLabel.setText("<html>Get cities in bounding box. Write bounding box coordinates below. You can also try to get coordinates from context topics.</html>"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 12, 0); citiesPanelInner.add(citiesLabel, gridBagConstraints); citiesCoordinatesPanel.setPreferredSize(new java.awt.Dimension(400, 60)); citiesCoordinatesPanel.setLayout(new java.awt.GridBagLayout()); citiesNorthTextField.setHorizontalAlignment(javax.swing.JTextField.CENTER); citiesNorthTextField.setText("north"); citiesNorthTextField.setMinimumSize(new java.awt.Dimension(100, 23)); citiesNorthTextField.setPreferredSize(new java.awt.Dimension(100, 23)); citiesNorthTextField.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { citiesNorthTextFieldFocusGained(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; citiesCoordinatesPanel.add(citiesNorthTextField, gridBagConstraints); citiesSouthTextField.setHorizontalAlignment(javax.swing.JTextField.CENTER); citiesSouthTextField.setText("south"); citiesSouthTextField.setMinimumSize(new java.awt.Dimension(100, 23)); citiesSouthTextField.setPreferredSize(new java.awt.Dimension(100, 23)); citiesSouthTextField.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { citiesSouthTextFieldFocusGained(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; citiesCoordinatesPanel.add(citiesSouthTextField, gridBagConstraints); citiesEastTextField.setHorizontalAlignment(javax.swing.JTextField.CENTER); citiesEastTextField.setText("east"); citiesEastTextField.setMinimumSize(new java.awt.Dimension(100, 23)); citiesEastTextField.setPreferredSize(new java.awt.Dimension(100, 23)); citiesEastTextField.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { citiesEastTextFieldFocusGained(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 1; citiesCoordinatesPanel.add(citiesEastTextField, gridBagConstraints); citiesWestTextField.setHorizontalAlignment(javax.swing.JTextField.CENTER); citiesWestTextField.setText("west"); citiesWestTextField.setMinimumSize(new java.awt.Dimension(100, 23)); citiesWestTextField.setPreferredSize(new java.awt.Dimension(100, 23)); citiesWestTextField.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { citiesWestTextFieldFocusGained(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; citiesCoordinatesPanel.add(citiesWestTextField, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 20, 0); citiesPanelInner.add(citiesCoordinatesPanel, gridBagConstraints); citiesGetContextButton.setText("Get context"); citiesGetContextButton.setMargin(new java.awt.Insets(2, 6, 2, 6)); citiesGetContextButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { citiesGetContextButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; citiesPanelInner.add(citiesGetContextButton, 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, 10, 4, 10); citiesPanel.add(citiesPanelInner, gridBagConstraints); geoNamesTabbedPane.addTab("Cities", citiesPanel); childrenPanel.setLayout(new java.awt.GridBagLayout()); childrenPanelInner.setLayout(new java.awt.GridBagLayout()); childrenLabel.setText("<html>Get GeoName children of a given geonameId and convert the feed to a topic map. Please write geonameIds below. Use comma (,) character to separate ids. You can also try to get ids from the context.</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, 6, 0); childrenPanelInner.add(childrenLabel, 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); childrenPanelInner.add(childrenTextField, gridBagConstraints); childrenGetContextButton.setText("Get context"); childrenGetContextButton.setMargin(new java.awt.Insets(2, 6, 2, 6)); childrenGetContextButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { childrenGetContextButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; childrenPanelInner.add(childrenGetContextButton, 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, 10, 4, 10); childrenPanel.add(childrenPanelInner, gridBagConstraints); geoNamesTabbedPane.addTab("Children", childrenPanel); hierarchyPanel.setLayout(new java.awt.GridBagLayout()); hierarchyPanelInner.setLayout(new java.awt.GridBagLayout()); hierarchyLabel.setText("<html>Get GeoName hierarchy of a given geonameId and convert the feed to a topic map. Please write geonameIds below. Use comma (,) character to separate ids. You can also try to get ids from the context.</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, 6, 0); hierarchyPanelInner.add(hierarchyLabel, 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); hierarchyPanelInner.add(hierarchyTextField, gridBagConstraints); hierarchyGetContextButton.setLabel("Get context"); hierarchyGetContextButton.setMargin(new java.awt.Insets(2, 6, 2, 6)); hierarchyGetContextButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { hierarchyGetContextButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; hierarchyPanelInner.add(hierarchyGetContextButton, 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, 10, 4, 10); hierarchyPanel.add(hierarchyPanelInner, gridBagConstraints); geoNamesTabbedPane.addTab("Hierarchy", hierarchyPanel); neighboursPanel.setLayout(new java.awt.GridBagLayout()); neighboursPanelInner.setLayout(new java.awt.GridBagLayout()); neigboursLabel.setText("<html>Get neighbours of a given geonameId and convert the feed to a topic map. Please write ids below. Use comma (,) character as id separator. You can also try to get ids from the context.</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, 6, 0); neighboursPanelInner.add(neigboursLabel, 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); neighboursPanelInner.add(neighboursTextField, gridBagConstraints); neighboursGetContextButton.setText("Get context"); neighboursGetContextButton.setMargin(new java.awt.Insets(2, 6, 2, 6)); neighboursGetContextButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { neighboursGetContextButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; neighboursPanelInner.add(neighboursGetContextButton, 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, 10, 4, 10); neighboursPanel.add(neighboursPanelInner, gridBagConstraints); geoNamesTabbedPane.addTab("Neighbours", neighboursPanel); siblingsPanel.setLayout(new java.awt.GridBagLayout()); siblingsPanelInner.setLayout(new java.awt.GridBagLayout()); siblingsLabel.setText("<html>Get siblings of a given geonameId and convert the feed to a topic map. Please write ids below. Use comma (,) character as id separator. You can also try to get ids from the context.</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, 6, 0); siblingsPanelInner.add(siblingsLabel, 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); siblingsPanelInner.add(siblingsTextField, gridBagConstraints); siblingsGetContextButton.setText("Get context"); siblingsGetContextButton.setMargin(new java.awt.Insets(2, 6, 2, 6)); siblingsGetContextButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { siblingsGetContextButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; siblingsPanelInner.add(siblingsGetContextButton, 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, 10, 4, 10); siblingsPanel.add(siblingsPanelInner, gridBagConstraints); geoNamesTabbedPane.addTab("Siblings", siblingsPanel); weatherPanel.setLayout(new java.awt.GridBagLayout()); weatherPanelInner.setLayout(new java.awt.GridBagLayout()); weatherLabel.setText("<html>Fetch weather data for given geo location.The service will return weather station closest to given point.</html>"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 6, 0); weatherPanelInner.add(weatherLabel, gridBagConstraints); weatherCoordinatesPanel.setLayout(new java.awt.GridBagLayout()); weatherLatLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); weatherLatLabel.setText("latitude"); weatherLatLabel.setMaximumSize(new java.awt.Dimension(80, 14)); weatherLatLabel.setMinimumSize(new java.awt.Dimension(80, 14)); weatherLatLabel.setPreferredSize(new java.awt.Dimension(70, 15)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 1, 5); weatherCoordinatesPanel.add(weatherLatLabel, 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, 1, 0); weatherCoordinatesPanel.add(weatherLatTextField, gridBagConstraints); weatherLonLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); weatherLonLabel.setText("longitude"); weatherLonLabel.setMaximumSize(new java.awt.Dimension(80, 14)); weatherLonLabel.setMinimumSize(new java.awt.Dimension(80, 14)); weatherLonLabel.setPreferredSize(new java.awt.Dimension(70, 15)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); weatherCoordinatesPanel.add(weatherLonLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; weatherCoordinatesPanel.add(weatherLonTextField, gridBagConstraints); weatherGetContextButton.setText("Get context"); weatherGetContextButton.setMargin(new java.awt.Insets(2, 6, 2, 6)); weatherGetContextButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { weatherGetContextButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(6, 2, 1, 0); weatherCoordinatesPanel.add(weatherGetContextButton, 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, 1, 0); weatherPanelInner.add(weatherCoordinatesPanel, 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, 10, 4, 10); weatherPanel.add(weatherPanelInner, gridBagConstraints); geoNamesTabbedPane.addTab("Weather", weatherPanel); wikiSearchPanel.setLayout(new java.awt.GridBagLayout()); wikiSearchPanelInner.setLayout(new java.awt.GridBagLayout()); wikiSearchLabel.setText("<html>This tab is used to perform GeoName Wikipedia searches. Please write search word below.</html>"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 6, 0); wikiSearchPanelInner.add(wikiSearchLabel, 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, 3, 0); wikiSearchPanelInner.add(wikiSearchTextField, 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, 10, 4, 10); wikiSearchPanel.add(wikiSearchPanelInner, gridBagConstraints); geoNamesTabbedPane.addTab("Wikipedia search", wikiSearchPanel); wikiBoxPanel.setLayout(new java.awt.GridBagLayout()); wikiBoxPanelInner.setLayout(new java.awt.GridBagLayout()); wikiBoxLabel.setText("<html>Get Wikipedia geo articles in bounding box. Write bounding box coordinates below. You can also try to get coordinates from context topics.</html>"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 12, 0); wikiBoxPanelInner.add(wikiBoxLabel, gridBagConstraints); wikiBoxCoordinatesPanel.setPreferredSize(new java.awt.Dimension(400, 60)); wikiBoxCoordinatesPanel.setLayout(new java.awt.GridBagLayout()); wikiBoxNorthTextField.setHorizontalAlignment(javax.swing.JTextField.CENTER); wikiBoxNorthTextField.setText("north"); wikiBoxNorthTextField.setMinimumSize(new java.awt.Dimension(100, 23)); wikiBoxNorthTextField.setPreferredSize(new java.awt.Dimension(100, 23)); wikiBoxNorthTextField.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { wikiBoxNorthTextFieldFocusGained(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; wikiBoxCoordinatesPanel.add(wikiBoxNorthTextField, gridBagConstraints); wikiBoxSouthTextField.setHorizontalAlignment(javax.swing.JTextField.CENTER); wikiBoxSouthTextField.setText("south"); wikiBoxSouthTextField.setMinimumSize(new java.awt.Dimension(100, 23)); wikiBoxSouthTextField.setPreferredSize(new java.awt.Dimension(100, 23)); wikiBoxSouthTextField.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { wikiBoxSouthTextFieldFocusGained(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; wikiBoxCoordinatesPanel.add(wikiBoxSouthTextField, gridBagConstraints); wikiBoxEastTextField.setHorizontalAlignment(javax.swing.JTextField.CENTER); wikiBoxEastTextField.setText("east"); wikiBoxEastTextField.setMinimumSize(new java.awt.Dimension(100, 23)); wikiBoxEastTextField.setPreferredSize(new java.awt.Dimension(100, 23)); wikiBoxEastTextField.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { wikiBoxEastTextFieldFocusGained(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 1; wikiBoxCoordinatesPanel.add(wikiBoxEastTextField, gridBagConstraints); wikiBoxWestTextField.setHorizontalAlignment(javax.swing.JTextField.CENTER); wikiBoxWestTextField.setText("west"); wikiBoxWestTextField.setMinimumSize(new java.awt.Dimension(100, 23)); wikiBoxWestTextField.setPreferredSize(new java.awt.Dimension(100, 23)); wikiBoxWestTextField.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { wikiBoxWestTextFieldFocusGained(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; wikiBoxCoordinatesPanel.add(wikiBoxWestTextField, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 20, 0); wikiBoxPanelInner.add(wikiBoxCoordinatesPanel, gridBagConstraints); wikiBoxGetContextButton.setText("Get context"); wikiBoxGetContextButton.setMargin(new java.awt.Insets(2, 6, 2, 6)); wikiBoxGetContextButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { wikiBoxGetContextButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; wikiBoxPanelInner.add(wikiBoxGetContextButton, 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, 10, 4, 10); wikiBoxPanel.add(wikiBoxPanelInner, gridBagConstraints); geoNamesTabbedPane.addTab("Wikipedia b-box", wikiBoxPanel); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; getContentPane().add(geoNamesTabbedPane, gridBagConstraints); buttonPanel.setLayout(new java.awt.GridBagLayout()); langPanel.setLayout(new java.awt.GridBagLayout()); langTextField.setHorizontalAlignment(javax.swing.JTextField.CENTER); langTextField.setText("en"); langTextField.setMinimumSize(new java.awt.Dimension(30, 23)); langTextField.setPreferredSize(new java.awt.Dimension(30, 23)); langPanel.add(langTextField, new java.awt.GridBagConstraints()); langLabel.setText("request language"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 6, 0, 0); langPanel.add(langLabel, gridBagConstraints); buttonPanel.add(langPanel, new java.awt.GridBagConstraints()); fillerPanel.setPreferredSize(new java.awt.Dimension(5, 5)); javax.swing.GroupLayout fillerPanelLayout = new javax.swing.GroupLayout(fillerPanel); fillerPanel.setLayout(fillerPanelLayout); fillerPanelLayout.setHorizontalGroup( fillerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 116, Short.MAX_VALUE) ); fillerPanelLayout.setVerticalGroup( fillerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 5, Short.MAX_VALUE) ); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; buttonPanel.add(fillerPanel, gridBagConstraints); forgetButton.setText("Forget username"); forgetButton.setMargin(new java.awt.Insets(2, 2, 2, 2)); forgetButton.setMaximumSize(new java.awt.Dimension(110, 23)); forgetButton.setMinimumSize(new java.awt.Dimension(110, 23)); forgetButton.setPreferredSize(new java.awt.Dimension(110, 23)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 8); buttonPanel.add(forgetButton, gridBagConstraints); buttonSeparator.setOrientation(javax.swing.SwingConstants.VERTICAL); buttonSeparator.setMinimumSize(new java.awt.Dimension(1, 15)); buttonSeparator.setPreferredSize(new java.awt.Dimension(1, 15)); buttonPanel.add(buttonSeparator, new java.awt.GridBagConstraints()); okButton.setText("Extract"); okButton.setMargin(new java.awt.Insets(2, 2, 2, 2)); okButton.setPreferredSize(new java.awt.Dimension(75, 23)); okButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { okButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(4, 8, 4, 0); buttonPanel.add(okButton, gridBagConstraints); cancelButton.setText("Cancel"); cancelButton.setMargin(new java.awt.Insets(2, 2, 2, 2)); cancelButton.setPreferredSize(new java.awt.Dimension(75, 23)); cancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(4, 3, 4, 0); buttonPanel.add(cancelButton, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 4); getContentPane().add(buttonPanel, gridBagConstraints); pack(); }// </editor-fold>//GEN-END:initComponents private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed accepted = true; setVisible(false); }//GEN-LAST:event_okButtonActionPerformed private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed accepted = false; setVisible(false); }//GEN-LAST:event_cancelButtonActionPerformed private void countryInfoButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_countryInfoButtonActionPerformed solveCountryContext(); }//GEN-LAST:event_countryInfoButtonActionPerformed private void citiesNorthTextFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_citiesNorthTextFieldFocusGained if("north".equals(citiesNorthTextField.getText())) { citiesNorthTextField.setText(""); } }//GEN-LAST:event_citiesNorthTextFieldFocusGained private void citiesWestTextFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_citiesWestTextFieldFocusGained if("west".equals(citiesWestTextField.getText())) { citiesWestTextField.setText(""); } }//GEN-LAST:event_citiesWestTextFieldFocusGained private void citiesSouthTextFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_citiesSouthTextFieldFocusGained if("south".equals(citiesSouthTextField.getText())) { citiesSouthTextField.setText(""); } }//GEN-LAST:event_citiesSouthTextFieldFocusGained private void citiesEastTextFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_citiesEastTextFieldFocusGained if("east".equals(citiesEastTextField.getText())) { citiesEastTextField.setText(""); } }//GEN-LAST:event_citiesEastTextFieldFocusGained private void childrenGetContextButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_childrenGetContextButtonActionPerformed String str = solveGeonameIdContext(); if(str == null) str = ""; childrenTextField.setText(str); }//GEN-LAST:event_childrenGetContextButtonActionPerformed private void citiesGetContextButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_citiesGetContextButtonActionPerformed Tuples.T4 gpsRect = solveGPSBoundingBox(); if(gpsRect != null) { try { citiesNorthTextField.setText(gpsRect.e1.toString()); citiesWestTextField.setText(gpsRect.e2.toString()); citiesSouthTextField.setText(gpsRect.e3.toString()); citiesEastTextField.setText(gpsRect.e4.toString()); } catch(Exception e) {} } }//GEN-LAST:event_citiesGetContextButtonActionPerformed private void hierarchyGetContextButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_hierarchyGetContextButtonActionPerformed String str = solveGeonameIdContext(); if(str == null) str = ""; hierarchyTextField.setText(str); }//GEN-LAST:event_hierarchyGetContextButtonActionPerformed private void neighboursGetContextButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_neighboursGetContextButtonActionPerformed String str = solveGeonameIdContext(); if(str == null) str = ""; neighboursTextField.setText(str); }//GEN-LAST:event_neighboursGetContextButtonActionPerformed private void siblingsGetContextButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_siblingsGetContextButtonActionPerformed String str = solveGeonameIdContext(); if(str == null) str = ""; siblingsTextField.setText(str); }//GEN-LAST:event_siblingsGetContextButtonActionPerformed private void findNearByGetContextButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_findNearByGetContextButtonActionPerformed Tuples.T2 geoLocation = solveGPSLocation(); if(geoLocation != null) { try { findNearByLatTextField.setText(geoLocation.e1.toString()); findNearByLonTextField.setText(geoLocation.e2.toString()); }catch(Exception e) {} } else { Tuples.T4 gpsRect = solveGPSBoundingBox(); if(gpsRect != null) { try { double n = Double.parseDouble(gpsRect.e1.toString()); double w = Double.parseDouble(gpsRect.e2.toString()); double s = Double.parseDouble(gpsRect.e3.toString()); double e = Double.parseDouble(gpsRect.e4.toString()); double lat = n + ((s-n)/2); double lon = w + ((e-w)/2); findNearByLatTextField.setText("" + lat); findNearByLonTextField.setText("" + lon); } catch(Exception e) {} } } }//GEN-LAST:event_findNearByGetContextButtonActionPerformed private void weatherGetContextButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_weatherGetContextButtonActionPerformed Tuples.T2 geoLocation = solveGPSLocation(); if(geoLocation != null) { try { weatherLatTextField.setText(geoLocation.e1.toString()); weatherLonTextField.setText(geoLocation.e2.toString()); }catch(Exception e) {} } else { Tuples.T4 gpsRect = solveGPSBoundingBox(); if(gpsRect != null) { try { double n = Double.parseDouble(gpsRect.e1.toString()); double w = Double.parseDouble(gpsRect.e2.toString()); double s = Double.parseDouble(gpsRect.e3.toString()); double e = Double.parseDouble(gpsRect.e4.toString()); double lat = n + ((s-n)/2); double lon = w + ((e-w)/2); weatherLatTextField.setText("" + lat); weatherLonTextField.setText("" + lon); } catch(Exception e) {} } } }//GEN-LAST:event_weatherGetContextButtonActionPerformed private void wikiBoxNorthTextFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_wikiBoxNorthTextFieldFocusGained if("north".equals(wikiBoxNorthTextField.getText())) { wikiBoxNorthTextField.setText(""); } }//GEN-LAST:event_wikiBoxNorthTextFieldFocusGained private void wikiBoxSouthTextFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_wikiBoxSouthTextFieldFocusGained if("south".equals(wikiBoxNorthTextField.getText())) { wikiBoxNorthTextField.setText(""); } }//GEN-LAST:event_wikiBoxSouthTextFieldFocusGained private void wikiBoxEastTextFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_wikiBoxEastTextFieldFocusGained if("east".equals(wikiBoxNorthTextField.getText())) { wikiBoxNorthTextField.setText(""); } }//GEN-LAST:event_wikiBoxEastTextFieldFocusGained private void wikiBoxWestTextFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_wikiBoxWestTextFieldFocusGained if("west".equals(wikiBoxNorthTextField.getText())) { wikiBoxNorthTextField.setText(""); } }//GEN-LAST:event_wikiBoxWestTextFieldFocusGained private void wikiBoxGetContextButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_wikiBoxGetContextButtonActionPerformed Tuples.T4 gpsRect = solveGPSBoundingBox(); if(gpsRect != null) { try { wikiBoxNorthTextField.setText(gpsRect.e1.toString()); wikiBoxWestTextField.setText(gpsRect.e2.toString()); wikiBoxSouthTextField.setText(gpsRect.e3.toString()); wikiBoxEastTextField.setText(gpsRect.e4.toString()); } catch(Exception e) {} } else { Tuples.T2 geoLocation = solveGPSLocation(); if(geoLocation != null) { try { double c1 = Double.parseDouble(geoLocation.e1.toString()); double c2 = Double.parseDouble(geoLocation.e2.toString()); String radiusStr = WandoraOptionPane.showInputDialog(wandora, "Found only single geo location. To convert found geo location to bounding box give radius:", "1.0", "Radius?"); if(radiusStr != null && radiusStr.length() > 0) { double radius = Double.parseDouble(radiusStr); wikiBoxNorthTextField.setText(""+ (c1-radius)); wikiBoxWestTextField.setText(""+ (c2-radius)); wikiBoxSouthTextField.setText(""+ (c1+radius)); wikiBoxEastTextField.setText("" + (c2+radius)); } } catch(Exception e) {} } } }//GEN-LAST:event_wikiBoxGetContextButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel buttonPanel; private javax.swing.JSeparator buttonSeparator; private javax.swing.JButton cancelButton; private javax.swing.JButton childrenGetContextButton; private javax.swing.JLabel childrenLabel; private javax.swing.JPanel childrenPanel; private javax.swing.JPanel childrenPanelInner; private javax.swing.JTextField childrenTextField; private javax.swing.JPanel citiesCoordinatesPanel; private javax.swing.JTextField citiesEastTextField; private javax.swing.JButton citiesGetContextButton; private javax.swing.JLabel citiesLabel; private javax.swing.JTextField citiesNorthTextField; private javax.swing.JPanel citiesPanel; private javax.swing.JPanel citiesPanelInner; private javax.swing.JTextField citiesSouthTextField; private javax.swing.JTextField citiesWestTextField; private javax.swing.JButton countryInfoButton; private javax.swing.JComboBox countryInfoComboBox; private javax.swing.JLabel countryInfoLabel; private javax.swing.JPanel countryInfoPanel; private javax.swing.JPanel countryInfoPanelInner; private javax.swing.JPanel fillerPanel; private javax.swing.JPanel findNearByCoordinatesPanel; private javax.swing.JComboBox findNearByFeatureComboBox; private javax.swing.JLabel findNearByFeatureLabel; private javax.swing.JPanel findNearByFilterPanel; private javax.swing.JButton findNearByGetContextButton; private javax.swing.JLabel findNearByLabel; private javax.swing.JLabel findNearByLatLabel; private javax.swing.JTextField findNearByLatTextField; private javax.swing.JLabel findNearByLonLabel; private javax.swing.JTextField findNearByLonTextField; private javax.swing.JPanel findNearByPanel; private javax.swing.JPanel findNearByPanelInner; private javax.swing.JTextField findNearByRadiusTextField; private javax.swing.JLabel findNearByradiusLabel; private javax.swing.JButton forgetButton; private javax.swing.JTabbedPane geoNamesTabbedPane; private javax.swing.JButton hierarchyGetContextButton; private javax.swing.JLabel hierarchyLabel; private javax.swing.JPanel hierarchyPanel; private javax.swing.JPanel hierarchyPanelInner; private javax.swing.JTextField hierarchyTextField; private javax.swing.JLabel langLabel; private javax.swing.JPanel langPanel; private javax.swing.JTextField langTextField; private javax.swing.JLabel neigboursLabel; private javax.swing.JButton neighboursGetContextButton; private javax.swing.JPanel neighboursPanel; private javax.swing.JPanel neighboursPanelInner; private javax.swing.JTextField neighboursTextField; private javax.swing.JButton okButton; private javax.swing.JComboBox searchContinentComboBox; private javax.swing.JLabel searchContinentLabel; private javax.swing.JComboBox searchCountryComboBox; private javax.swing.JLabel searchCountryLabel; private javax.swing.JComboBox searchFeatureClassComboBox; private javax.swing.JLabel searchFeatureLabel; private javax.swing.JPanel searchFilterPanel; private javax.swing.JCheckBox searchIsNameRequiredCheckBox; private javax.swing.JLabel searchIsNameRequiredLabel; private javax.swing.JLabel searchLabel; private javax.swing.JPanel searchPanel; private javax.swing.JPanel searchPanelInner; private javax.swing.JTextField searchTextField; private javax.swing.JButton siblingsGetContextButton; private javax.swing.JLabel siblingsLabel; private javax.swing.JPanel siblingsPanel; private javax.swing.JPanel siblingsPanelInner; private javax.swing.JTextField siblingsTextField; private javax.swing.JPanel weatherCoordinatesPanel; private javax.swing.JButton weatherGetContextButton; private javax.swing.JLabel weatherLabel; private javax.swing.JLabel weatherLatLabel; private javax.swing.JTextField weatherLatTextField; private javax.swing.JLabel weatherLonLabel; private javax.swing.JTextField weatherLonTextField; private javax.swing.JPanel weatherPanel; private javax.swing.JPanel weatherPanelInner; private javax.swing.JPanel wikiBoxCoordinatesPanel; private javax.swing.JTextField wikiBoxEastTextField; private javax.swing.JButton wikiBoxGetContextButton; private javax.swing.JLabel wikiBoxLabel; private javax.swing.JTextField wikiBoxNorthTextField; private javax.swing.JPanel wikiBoxPanel; private javax.swing.JPanel wikiBoxPanelInner; private javax.swing.JTextField wikiBoxSouthTextField; private javax.swing.JTextField wikiBoxWestTextField; private javax.swing.JLabel wikiSearchLabel; private javax.swing.JPanel wikiSearchPanel; private javax.swing.JPanel wikiSearchPanelInner; private javax.swing.JTextField wikiSearchTextField; // End of variables declaration//GEN-END:variables // ------------------------------------------------------------------------- private static String apikey = null; public String solveAPIKey() { if(apikey == null) { apikey = ""; apikey = WandoraOptionPane.showInputDialog(Wandora.getWandora(), "Please give a valid Geonames username. You can register your username at http://www.geonames.org/login", apikey, "GeoName username", WandoraOptionPane.QUESTION_MESSAGE); } return apikey; } public void forgetAuthorization() { apikey = null; } }
91,389
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
GeoNamesCities.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/geonames/GeoNamesCities.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * GeoNamesCities.java * * */ package org.wandora.application.tools.extractors.geonames; import java.io.InputStream; 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; /** * See http://ws.geonames.org/cities?north=44.1&south=-9.9&east=-22.4&west=55.2 * * @author akivela */ public class GeoNamesCities extends AbstractGeoNamesExtractor { private static final long serialVersionUID = 1L; public String dataLang = "en"; @Override public String getName() { return "GeoNames cities extractor"; } @Override public String getDescription(){ return "Get cities within given bounding box and convert city data to a topic map."; } 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(); CitiesParser parserHandler = new CitiesParser(topicMap,this,dataLang); 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 cities found!"); else if(parserHandler.progress == 1) log("One city found!"); else log("Total " + parserHandler.progress + " cities found!"); return true; } // ------------------------------------------------------------------------- // --- GEONAMES XML FEED PARSER -------------------------------------------- // ------------------------------------------------------------------------- private static class CitiesParser implements org.xml.sax.ContentHandler, org.xml.sax.ErrorHandler { public CitiesParser(TopicMap tm, GeoNamesCities parent, String lang){ this.lang=lang; this.tm=tm; this.parent=parent; } private String lang = "en"; public int progress=0; private TopicMap tm; private GeoNamesCities parent; public static final String TAG_GEONAMES="geonames"; public static final String TAG_STATUS="status"; public static final String TAG_GEONAME="geoname"; public static final String TAG_NAME="name"; public static final String TAG_LAT="lat"; public static final String TAG_LNG="lng"; public static final String TAG_GEONAMEID="geonameId"; public static final String TAG_COUNTRYCODE="countryCode"; public static final String TAG_COUNTRYNAME="countryName"; public static final String TAG_FCL="fcl"; public static final String TAG_FCODE="fcode"; 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_GEONAME=3; private static final int STATE_GEONAME_NAME=4; private static final int STATE_GEONAME_LAT=5; private static final int STATE_GEONAME_LNG=6; private static final int STATE_GEONAME_GEONAMEID=7; private static final int STATE_GEONAME_COUNTRYCODE=8; private static final int STATE_GEONAME_COUNTRYNAME=9; private static final int STATE_GEONAME_FCL=10; private static final int STATE_GEONAME_FCODE=11; private int state=STATE_START; private String data_name; private String data_lat; private String data_lng; private String data_geonameid; private String data_countrycode; private String data_countryname; private String data_fcl; private String data_fcode; private Topic theCity; 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_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_GEONAME)) { data_name = ""; data_lat = ""; data_lng = ""; data_geonameid = ""; data_countrycode = ""; data_countryname = ""; data_fcl = ""; data_fcode = ""; state = STATE_GEONAME; } break; case STATE_GEONAME: if(qName.equals(TAG_NAME)) { state = STATE_GEONAME_NAME; data_name = ""; } else if(qName.equals(TAG_LAT)) { state = STATE_GEONAME_LAT; data_lat = ""; } else if(qName.equals(TAG_LNG)) { state = STATE_GEONAME_LNG; data_lng = ""; } else if(qName.equals(TAG_GEONAMEID)) { state = STATE_GEONAME_GEONAMEID; data_geonameid = ""; } else if(qName.equals(TAG_COUNTRYCODE)) { state = STATE_GEONAME_COUNTRYCODE; data_countrycode = ""; } else if(qName.equals(TAG_COUNTRYNAME)) { state = STATE_GEONAME_COUNTRYNAME; data_countryname = ""; } else if(qName.equals(TAG_FCL)) { state = STATE_GEONAME_FCL; data_fcl = ""; } else if(qName.equals(TAG_FCODE)) { state = STATE_GEONAME_FCODE; data_fcode = ""; } break; } } public void endElement(String uri, String localName, String qName) throws SAXException { switch(state) { case STATE_GEONAME: { if(TAG_GEONAME.equals(qName)) { if(data_geonameid.length() > 0 || data_name.length() > 0) { try { theCity=getCityTopic(tm, data_geonameid, data_name, lang); parent.setProgress(progress++); try { if(isValid(data_fcode)) { Topic fcodeTopic = getFCLTopic(tm, data_fcode, null); theCity.addType(fcodeTopic); } if(isValid(data_fcl)) { Topic fclTopic = getFCLTopic(tm, data_fcl, null); theCity.addType(fclTopic); } if(isValid(data_countrycode) && isValid(data_countryname)) { Topic countryTopic=getCountryTopic(tm, data_countrycode, data_countryname, lang); makeGeoCountry(theCity, countryTopic, tm); } if(isValid(data_lat) && isValid(data_lng)) { makeLatLong(data_lat, data_lng, theCity, tm); } } catch(Exception e) { parent.log(e); } } catch(TopicMapException tme){ parent.log(tme); } } 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_GEONAME_NAME: { if(TAG_NAME.equals(qName)) state=STATE_GEONAME; break; } case STATE_GEONAME_LAT: { if(TAG_LAT.equals(qName)) state=STATE_GEONAME; break; } case STATE_GEONAME_LNG: { if(TAG_LNG.equals(qName)) state=STATE_GEONAME; break; } case STATE_GEONAME_GEONAMEID: { if(TAG_GEONAMEID.equals(qName)) state=STATE_GEONAME; break; } case STATE_GEONAME_COUNTRYCODE: { if(TAG_COUNTRYCODE.equals(qName)) state=STATE_GEONAME; break; } case STATE_GEONAME_COUNTRYNAME: { if(TAG_COUNTRYNAME.equals(qName)) state=STATE_GEONAME; break; } case STATE_GEONAME_FCL: { if(TAG_FCL.equals(qName)) state=STATE_GEONAME; break; } case STATE_GEONAME_FCODE: { if(TAG_FCODE.equals(qName)) state=STATE_GEONAME; break; } } } public void characters(char[] ch, int start, int length) throws SAXException { switch(state){ case STATE_GEONAME_NAME: data_name+=new String(ch,start,length); break; case STATE_GEONAME_LAT: data_lat+=new String(ch,start,length); break; case STATE_GEONAME_LNG: data_lng+=new String(ch,start,length); break; case STATE_GEONAME_GEONAMEID: data_geonameid+=new String(ch,start,length); break; case STATE_GEONAME_COUNTRYCODE: data_countrycode+=new String(ch,start,length); break; case STATE_GEONAME_COUNTRYNAME: data_countryname+=new String(ch,start,length); break; case STATE_GEONAME_FCL: data_fcl+=new String(ch,start,length); break; case STATE_GEONAME_FCODE: data_fcode+=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 static boolean isValid(String str) { if(str != null && str.length() > 0) return true; else return false; } }
14,604
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
GeoNamesHierarchy.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/geonames/GeoNamesHierarchy.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * GeoNamesHierarchy.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/hierarchy?geonameId=2657896&style=full * * @author akivela */ public class GeoNamesHierarchy extends AbstractGeoNamesExtractor { private static final long serialVersionUID = 1L; public String dataLang = "en"; public String requestGeoObject = null; @Override public String getName() { return "GeoNames hierarchy extractor"; } @Override public String getDescription(){ return "Get geo name hierarchy of given geo location and convert the hierarchy 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(); HierarchyParser parserHandler = new HierarchyParser(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 geo objects found!"); else if(parserHandler.progress == 1) log("One geo object found!"); else log("Total " + parserHandler.progress + " geo objects found!"); requestGeoObject = null; // FORCE NULL AS THIS OBJECT IS REUSED. return true; } // ------------------------------------------------------------------------- // --- GEONAMES XML FEED PARSER -------------------------------------------- // ------------------------------------------------------------------------- private static class HierarchyParser extends AbstractGeoNamesParser { Topic theParent = null; String theParentSI = null; public HierarchyParser(TopicMap tm, GeoNamesHierarchy 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); if(theParent.isRemoved()) theParent=tm.getTopic(theParentSI); 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(theParent != null && !theParent.isRemoved()) { if(theGeoObject.isRemoved()) theGeoObject=tm.getTopic(theGeoObjectSI); makeChildParent(theGeoObject, theParent, tm); } /* if(requestGeoObject != null && requestGeoObject.length() > 0) { Topic requestTopic=getGeoTopic(tm, requestGeoObject); if(requestTopic != null && !requestTopic.mergesWithTopic(theChild)) { Topic parentType=getParentTypeTopic(tm); Topic childType=getChildTypeTopic(tm); Association childa=tm.createAssociation(childType); childa.addPlayer(theChild, childType); childa.addPlayer(requestTopic, parentType); } } */ 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)) { Topic populationTypeTopic = getPopulationTypeTopic(tm); if(theGeoObject.isRemoved()) theGeoObject=tm.getTopic(theGeoObjectSI); theGeoObject.setData(populationTypeTopic, TMBox.getLangTopic(theGeoObject, lang), data_population); } } catch(Exception e) { parent.log(e); } if(theGeoObject.isRemoved()) theGeoObject=tm.getTopic(theGeoObjectSI); theParent = theGeoObject; theParentSI = theGeoObjectSI; } catch(TopicMapException tme){ parent.log(tme); } } } } }
8,442
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
FindNearByGeoNames.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/geonames/FindNearByGeoNames.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * FindNearByGeoNames.java * */ package org.wandora.application.tools.extractors.geonames; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.regex.Matcher; import java.util.regex.Pattern; 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.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; /** * * @author akivela */ public class FindNearByGeoNames extends AbstractGeoNamesExtractor { private static final long serialVersionUID = 1L; public String dataLang = "en"; public String requestGeoObject = null; public static final String LOCATES_NEARBY_SI = GeoNamesExtractorSelector.BASE_URL+"findNearby"; @Override public String getName() { return "GeoNames find near by extractor"; } @Override public String getDescription(){ return "Find near by geo locations from GeoNames web api and converts found 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(); FindNearByParser parserHandler = new FindNearByParser(topicMap,this,dataLang); parserHandler.setRequestGeoObject(requestGeoObject); parserHandler.setMasterSubject(getMasterSubject()); reader.setContentHandler(parserHandler); reader.setErrorHandler(parserHandler); try { reader.parse(new InputSource(new InputStreamReader(in, "utf-8"))); } catch(Exception e) { if(!(e instanceof SAXException) || !e.getMessage().equals("User interrupt")) log(e); } if(parserHandler.progress == 0) log("No near by geo names found!"); else if(parserHandler.progress == 1) log("One near by geo name found!"); else log("Total " + parserHandler.progress + " near by geo names found!"); requestGeoObject = null; // FORCE NULL AS THIS OBJECT IS REUSED. clearMasterSubject(); return true; } public Topic getNearByType(TopicMap tm) throws TopicMapException { Topic type = getOrCreateTopic(tm, LOCATES_NEARBY_SI, "locates near by (geonames)"); return type; } // ------------------------------------------------------------------------- // --- GEONAMES XML FEED PARSER -------------------------------------------- // ------------------------------------------------------------------------- private class FindNearByParser extends AbstractGeoNamesParser { public FindNearByParser(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); } if(getMasterSubject() != null) { Topic mt = tm.getTopic(getMasterSubject()); if(mt != null) { Association a = tm.createAssociation( getNearByType(tm) ); a.addPlayer(theGeoObject, getGeoObjectTypeTopic(tm)); a.addPlayer(mt, getGenericTopic(tm)); } } } catch(TopicMapException tme){ parent.log(tme); } } } } }
7,914
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
GeoNamesNearByWeather.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/tools/extractors/geonames/GeoNamesNearByWeather.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * GeoNamesNearByWeather.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; /** * * @author akivela */ public class GeoNamesNearByWeather extends AbstractGeoNamesExtractor { private static final long serialVersionUID = 1L; public String dataLang = "en"; public String requestGeoObject = null; @Override public String getName() { return "GeoNames find near by extractor"; } @Override public String getDescription(){ return "Extractor finds near by geo locations from GeoNames web api and converts found 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(); NearByWeatherParser parserHandler = new NearByWeatherParser(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 near by weather observations found!"); else if(parserHandler.progress == 1) log("One near by weather observation found!"); else log("Total " + parserHandler.progress + " near by weather observations found!"); requestGeoObject = null; // FORCE NULL AS THIS OBJECT IS REUSED. return true; } // ------------------------------------------------------------------------- // --- GEONAMES XML FEED PARSER -------------------------------------------- // ------------------------------------------------------------------------- private class NearByWeatherParser extends AbstractGeoNamesWeatherParser { Topic theObservation = null; public NearByWeatherParser(TopicMap tm, AbstractGeoNamesExtractor parent, String lang){ super(tm, parent, lang); } public void handleObservationElement() { if(data_observation != null && data_observation.length() > 0) { try { theObservation=getWeatherObservationTopic(tm, data_observation, lang); parent.setProgress(progress++); try { if(isValid(data_observationtime)) { Topic observationTimeTypeTopic = getWeatherObservationTimeTypeTopic(tm); theObservation.setData(observationTimeTypeTopic, TMBox.getLangTopic(theObservation, lang), data_observationtime); } if(isValid(data_stationname)) { Topic stationTopic = getWeatherStationTopic(tm, data_stationname, lang); makeWeatherStation(theObservation, stationTopic, tm); if(data_countrycode != null && data_countrycode.length() > 0) { Topic countryTopic=getCountryTopic(tm, data_countrycode, lang); makeGeoCountry(stationTopic, countryTopic, tm); } if(isValid(data_lat) && isValid(data_lng)) { makeLatLong(data_lat, data_lng, stationTopic, tm); } if(isValid(data_icao)) { stationTopic.addSubjectIdentifier(new org.wandora.topicmap.Locator(WEATHER_ICAO_SI+"/"+data_icao)); } if(isValid(data_elevation)) { Topic elevationTopic=getElevationTopic(tm, data_elevation, lang); makeGeoElevation(stationTopic, elevationTopic, tm); } } if(isValid(data_temperature )) { Topic temperatureTypeTopic = getWeatherTemperatureTypeTopic(tm); theObservation.setData(temperatureTypeTopic, TMBox.getLangTopic(theObservation, lang), data_temperature); } if(isValid(data_dewpoint)) { Topic dewPointTypeTopic = getWeatherDewPointTypeTopic(tm); theObservation.setData(dewPointTypeTopic, TMBox.getLangTopic(theObservation, lang), data_dewpoint); } if(isValid(data_humidity)) { Topic humidityTypeTopic = getWeatherHumidityTypeTopic(tm); theObservation.setData(humidityTypeTopic, TMBox.getLangTopic(theObservation, lang), data_humidity); } if(isValid(data_clouds)) { Topic cloudsTopic = getWeatherCloudsTopic(tm, data_clouds, lang); makeWeatherClouds(theObservation, cloudsTopic, tm); } if(isValid(data_weathercondition)) { Topic weatherConditionTypeTopic = getWeatherConditionTypeTopic(tm); theObservation.setData(weatherConditionTypeTopic, TMBox.getLangTopic(theObservation, lang), data_weathercondition); } if(isValid(data_hectopascaltimeter)) { Topic hectoPascAltimeterTypeTopic = getWeatherHectoPascAltimeterTypeTopic(tm); theObservation.setData(hectoPascAltimeterTypeTopic, TMBox.getLangTopic(theObservation, lang), data_hectopascaltimeter); } if(isValid(data_winddirection)) { Topic windDirectionTypeTopic = getWeatherWindDirectionTypeTopic(tm); theObservation.setData(windDirectionTypeTopic, TMBox.getLangTopic(theObservation, lang), data_winddirection); } if(isValid(data_windspeed)) { Topic windSpeedTypeTopic = getWeatherWindSpeedTypeTopic(tm); theObservation.setData(windSpeedTypeTopic, TMBox.getLangTopic(theObservation, lang), data_windspeed); } } catch(Exception e) { parent.log(e); } } catch(TopicMapException tme){ parent.log(tme); } } } } }
8,928
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z