Skip to content

Distributed Peer-to-Peer Web Search Engine and Intranet Search Appliance

redesign of parser interface: some file types are containers for several files. These containers had been parsed in such a way that the set of resulting parsed content was merged into one single document before parsing. Using this parser infrastructure it is not possible to parse document containers that contain individual files. An example is a rss file where the rss messages can be treated as individual documents with their own url reference. Another example is a surrogate file which was treated with a special operation outside of the parser infrastructure. This commit introduces a redesigned parser interface and a new abstract parser implementation. The new parser interface has now only one entry point and returns always a set of parsed documents. In case of single documents the parser method returns a set of one documents. To be compliant with the new interface, the zip and tar parser had been also completely redesigned. All parsers are now much more simple and cleaner in its structure. The switchboard operations had been extended to operate with sets of parsed files, not single parsed files. additionally, parsing of jar manifest files had been added.

orbiterb6fb239e7490
diff --git a/defaults/httpd.mime b/defaults/httpd.mime
index 8838cccb5..995c99ccc 100644
--- a/defaults/httpd.mime
+++ b/defaults/httpd.mime
@@ -45,6 +45,7 @@ kml = application/vnd.google-earth.kml+xml
lha = application/x-lzh
lzh = application/x-lzh
m4v = video/x-m4v
+mf = application/octet-stream
mov = video/quicktime
mp2 = audio/mpeg
mp3 = audio/mpeg
diff --git a/htroot/Bookmarks.java b/htroot/Bookmarks.java
index 300b2640e..4f5fa9f8b 100644
--- a/htroot/Bookmarks.java
+++ b/htroot/Bookmarks.java
@@ -38,7 +38,7 @@ import java.util.Iterator;
import java.util.Set;
import net.yacy.document.Document;
-import net.yacy.document.ParserException;
+import net.yacy.document.Parser;
import net.yacy.kelondro.data.meta.DigestURI;
import net.yacy.kelondro.data.meta.URIMetadataRow;
import net.yacy.kelondro.logging.Log;
@@ -187,10 +187,11 @@ public class Bookmarks {
if (bookmark == null) {
// try to get the bookmark from the LURL database
final URIMetadataRow urlentry = sb.indexSegments.urlMetadata(Segments.Process.PUBLIC).load(urlHash.getBytes(), null, 0);
- Document document = null;
+ Document[] documents = null;
if (urlentry != null) try {
final URIMetadataRow.Components metadata = urlentry.metadata();
- document = sb.loader.loadDocument(sb.loader.request(metadata.url(), true, false), CrawlProfile.CacheStrategy.IFEXIST, 5000, Long.MAX_VALUE);
+ documents = sb.loader.loadDocuments(sb.loader.request(metadata.url(), true, false), CrawlProfile.CacheStrategy.IFEXIST, 5000, Long.MAX_VALUE);
+ Document document = Document.mergeDocuments(metadata.url(), null, documents);
prop.put("mode_edit", "0"); // create mode
prop.put("mode_url", metadata.url().toNormalform(false, true));
prop.putHTML("mode_title", metadata.dc_title());
@@ -200,8 +201,7 @@ public class Bookmarks {
prop.putHTML("mode_path","");
prop.put("mode_public", "0");
prop.put("mode_feed", "0"); //TODO: check if it IS a feed
- } catch (IOException e) {Log.logException(e);} catch (ParserException e) {Log.logException(e);}
- if (document != null) document.close();
+ } catch (IOException e) {Log.logException(e);} catch (Parser.Failure e) {Log.logException(e);}
} else {
// get from the bookmark database
prop.put("mode_edit", "1"); // edit mode
diff --git a/htroot/ConfigParser.java b/htroot/ConfigParser.java
index 6742636cb..a5b86b460 100644
--- a/htroot/ConfigParser.java
+++ b/htroot/ConfigParser.java
@@ -25,7 +25,7 @@
// javac -classpath .:../Classes Settings_p.java
// if the shell's current path is HTROOT
-import net.yacy.document.Idiom;
+import net.yacy.document.Parser;
import net.yacy.document.TextParser;
import de.anomic.http.server.RequestHeader;
import de.anomic.search.Switchboard;
@@ -52,7 +52,7 @@ public class ConfigParser {
if (post.containsKey("parserSettings")) {
post.remove("parserSettings");
- for (Idiom parser: TextParser.idioms()) {
+ for (Parser parser: TextParser.parsers()) {
for (String mimeType: parser.supportedMimeTypes()) {
TextParser.grantMime(mimeType, post.get("mimename_" + mimeType, "").equals("on"));
}
@@ -62,7 +62,7 @@ public class ConfigParser {
}
int i = 0;
- for (Idiom parser: TextParser.idioms()) {
+ for (Parser parser: TextParser.parsers()) {
prop.put("parser_" + i + "_name", parser.getName());
int mimeIdx = 0;
diff --git a/htroot/RSSLoader_p.java b/htroot/RSSLoader_p.java
index 3098fa3b8..5531d336b 100644
--- a/htroot/RSSLoader_p.java
+++ b/htroot/RSSLoader_p.java
@@ -29,7 +29,7 @@ import java.io.ByteArrayInputStream;
import java.net.MalformedURLException;
import net.yacy.document.Document;
-import net.yacy.document.ParserException;
+import net.yacy.document.Parser;
import net.yacy.document.parser.rssParser;
import net.yacy.kelondro.data.meta.DigestURI;
@@ -79,10 +79,10 @@ public class RSSLoader_p {
// now parse the content as rss
ByteArrayInputStream bais = new ByteArrayInputStream(resource);
rssParser parser = new rssParser();
- Document doc;
+ Document[] doc;
try {
doc = parser.parse(url, "text/rss", "UTF-8", bais);
- } catch (ParserException e) {
+ } catch (Parser.Failure e) {
return prop;
} catch (InterruptedException e) {
return prop;
diff --git a/htroot/ViewFile.java b/htroot/ViewFile.java
index 8719583aa..af67b31fa 100644
--- a/htroot/ViewFile.java
+++ b/htroot/ViewFile.java
@@ -37,7 +37,7 @@ import java.util.Map;
import net.yacy.cora.document.MultiProtocolURI;
import net.yacy.document.Condenser;
import net.yacy.document.Document;
-import net.yacy.document.ParserException;
+import net.yacy.document.Parser;
import net.yacy.document.parser.html.CharacterCoding;
import net.yacy.document.parser.html.ImageEntry;
import net.yacy.kelondro.data.meta.DigestURI;
@@ -213,14 +213,14 @@ public class ViewFile {
// parsing the resource content
Document document = null;
try {
- document = response.parse();
+ document = Document.mergeDocuments(response.url(), response.getMimeType(), response.parse());
if (document == null) {
prop.put("error", "5");
prop.put("error_errorText", "Unknown error");
prop.put("viewMode", VIEW_MODE_NO_TEXT);
return prop;
}
- } catch (final ParserException e) {
+ } catch (final Parser.Failure e) {
prop.put("error", "5");
prop.putHTML("error_errorText", e.getMessage());
prop.put("viewMode", VIEW_MODE_NO_TEXT);
@@ -238,7 +238,7 @@ public class ViewFile {
prop.put("viewMode_publisher", document.dc_publisher());
prop.put("viewMode_format", document.dc_format());
prop.put("viewMode_identifier", document.dc_identifier());
- prop.put("viewMode_source", document.dc_source().toString());
+ prop.put("viewMode_source", url.toString());
prop.put("viewMode_parsedText", markup(wordArray, content).replaceAll("\n", "<br />").replaceAll("\t", "&nbsp;&nbsp;&nbsp;&nbsp;"));
} else if (viewMode.equals("sentences")) {
diff --git a/htroot/api/feed.java b/htroot/api/feed.java
index 20883cd66..00b49fe61 100755
--- a/htroot/api/feed.java
+++ b/htroot/api/feed.java
@@ -9,6 +9,7 @@ import de.anomic.http.server.RequestHeader;
import de.anomic.search.Switchboard;
import de.anomic.server.serverObjects;
import de.anomic.server.serverSwitch;
+import de.anomic.yacy.yacyChannel;
public class feed {
@@ -35,7 +36,7 @@ public class feed {
RSSFeed feed;
channelIteration: for (String channel: channels) {
// prevent that unauthorized access to this servlet get results from private data
- if ((!authorized) && (RSSFeed.privateChannels.contains(channel))) continue channelIteration; // allow only public channels if not authorized
+ if ((!authorized) && (yacyChannel.privateChannels.contains(channel))) continue channelIteration; // allow only public channels if not authorized
if (channel.equals("TEST")) {
// for interface testing return at least one single result
@@ -53,7 +54,7 @@ public class feed {
}
// read the channel
- feed = RSSFeed.channels(channel);
+ feed = yacyChannel.channels(channel);
if (feed == null || feed.isEmpty()) continue channelIteration;
RSSMessage message = feed.getChannel();
diff --git a/htroot/yacy/search.java b/htroot/yacy/search.java
index 5d4099596..d67ac514f 100644
--- a/htroot/yacy/search.java
+++ b/htroot/yacy/search.java
@@ -35,7 +35,6 @@ import java.util.Map;
import java.util.TreeMap;
import java.util.TreeSet;
-import net.yacy.cora.document.RSSFeed;
import net.yacy.cora.document.RSSMessage;
import net.yacy.kelondro.data.meta.DigestURI;
import net.yacy.kelondro.data.word.WordReference;
@@ -65,6 +64,7 @@ import de.anomic.server.serverCore;
import de.anomic.server.serverObjects;
import de.anomic.server.serverSwitch;
import de.anomic.tools.crypt;
+import de.anomic.yacy.yacyChannel;
import de.anomic.yacy.yacyCore;
import de.anomic.yacy.yacyNetwork;
import de.anomic.yacy.yacySeed;
@@ -277,7 +277,7 @@ public final class search {
rankingProfile
);
yacyCore.log.logInfo("INIT HASH SEARCH (query-" + abstracts + "): " + QueryParams.anonymizedQueryHashes(theQuery.queryHashes) + " - " + theQuery.displayResults() + " links");
- RSSFeed.channels(RSSFeed.YaCyChannel.REMOTESEARCH).addMessage(new RSSMessage("Remote Search Request from " + ((remoteSeed == null) ? "unknown" : remoteSeed.getName()), QueryParams.anonymizedQueryHashes(theQuery.queryHashes), ""));
+ yacyChannel.channels(yacyChannel.REMOTESEARCH).addMessage(new RSSMessage("Remote Search Request from " + ((remoteSeed == null) ? "unknown" : remoteSeed.getName()), QueryParams.anonymizedQueryHashes(theQuery.queryHashes), ""));
// make event
theSearch = SearchEventCache.getEvent(theQuery, sb.peers, sb.crawlResults, null, true, sb.loader);
diff --git a/htroot/yacy/transferRWI.java b/htroot/yacy/transferRWI.java
index cb452cb01..88c1f31df 100644
--- a/htroot/yacy/transferRWI.java
+++ b/htroot/yacy/transferRWI.java
@@ -30,7 +30,6 @@
import java.util.ArrayList;
import java.util.Iterator;
-import net.yacy.cora.document.RSSFeed;
import net.yacy.cora.document.RSSMessage;
import net.yacy.kelondro.data.meta.URIMetadataRow;
import net.yacy.kelondro.data.word.WordReferenceRow;
@@ -46,6 +45,7 @@ import de.anomic.search.SwitchboardConstants;
import de.anomic.server.serverCore;
import de.anomic.server.serverObjects;
import de.anomic.server.serverSwitch;
+import de.anomic.yacy.yacyChannel;
import de.anomic.yacy.yacyCore;
import de.anomic.yacy.yacyNetwork;
import de.anomic.yacy.yacySeed;
@@ -219,7 +219,7 @@ public final class transferRWI {
String lastHash = wordhashes.get(wordhashes.size() - 1);
final long avdist = (FlatWordPartitionScheme.std.dhtDistance(firstHash.getBytes(), null, sb.peers.mySeed()) + FlatWordPartitionScheme.std.dhtDistance(lastHash.getBytes(), null, sb.peers.mySeed())) / 2;
sb.getLog().logInfo("Received " + received + " RWIs, " + wordc + " Words [" + firstHash + " .. " + lastHash + "]/" + avdist + ", blocked " + blocked + ", requesting " + unknownURL.size() + "/" + receivedURL + " URLs from " + otherPeerName);
- RSSFeed.channels(RSSFeed.YaCyChannel.DHTRECEIVE).addMessage(new RSSMessage("Received " + received + " RWIs, " + wordc + " Words [" + firstHash + " .. " + lastHash + "]/" + avdist + ", blocked " + blocked + ", requesting " + unknownURL.size() + "/" + receivedURL + " URLs from " + otherPeerName, "", otherPeer.hash));
+ yacyChannel.channels(yacyChannel.DHTRECEIVE).addMessage(new RSSMessage("Received " + received + " RWIs, " + wordc + " Words [" + firstHash + " .. " + lastHash + "]/" + avdist + ", blocked " + blocked + ", requesting " + unknownURL.size() + "/" + receivedURL + " URLs from " + otherPeerName, "", otherPeer.hash));
}
result = "ok";
diff --git a/htroot/yacy/transferURL.java b/htroot/yacy/transferURL.java
index c8c222f8f..9b539510c 100644
--- a/htroot/yacy/transferURL.java
+++ b/htroot/yacy/transferURL.java
@@ -29,7 +29,6 @@
import java.io.IOException;
import java.text.ParseException;
-import net.yacy.cora.document.RSSFeed;
import net.yacy.cora.document.RSSMessage;
import net.yacy.kelondro.data.meta.URIMetadataRow;
import net.yacy.kelondro.logging.Log;
@@ -46,6 +45,7 @@ import de.anomic.server.serverSwitch;
import de.anomic.yacy.yacyCore;
import de.anomic.yacy.yacyNetwork;
import de.anomic.yacy.yacySeed;
+import de.anomic.yacy.yacyChannel;
public final class transferURL {
@@ -157,7 +157,7 @@ public final class transferURL {
final int more = sb.indexSegments.urlMetadata(Segments.Process.DHTIN).size() - sizeBefore;
doublevalues = Integer.toString(received - more);
yacyCore.log.logInfo("Received " + received + " URLs from peer " + otherPeerName + " in " + (System.currentTimeMillis() - start) + " ms, blocked " + blocked + " URLs");
- RSSFeed.channels(RSSFeed.YaCyChannel.DHTRECEIVE).addMessage(new RSSMessage("Received " + received + ", blocked " + blocked + " URLs from peer " + otherPeerName, "", otherPeer.hash));
+ yacyChannel.channels(yacyChannel.DHTRECEIVE).addMessage(new RSSMessage("Received " + received + ", blocked " + blocked + " URLs from peer " + otherPeerName, "", otherPeer.hash));
if ((received - more) > 0) yacyCore.log.logSevere("Received " + doublevalues + " double URLs from peer " + otherPeerName);
result = "ok";
}
diff --git a/htroot/yacysearch.java b/htroot/yacysearch.java
index d3e2a13c3..301efb06a 100644
--- a/htroot/yacysearch.java
+++ b/htroot/yacysearch.java
@@ -32,11 +32,10 @@ import java.util.HashMap;
import java.util.Iterator;
import java.util.TreeSet;
-import net.yacy.cora.document.RSSFeed;
import net.yacy.cora.document.RSSMessage;
import net.yacy.document.Condenser;
import net.yacy.document.Document;
-import net.yacy.document.ParserException;
+import net.yacy.document.Parser;
import net.yacy.document.geolocalization.Location;
import net.yacy.kelondro.data.meta.DigestURI;
import net.yacy.kelondro.data.meta.URIMetadataRow;
@@ -70,6 +69,7 @@ import de.anomic.server.serverObjects;
import de.anomic.server.serverSwitch;
import de.anomic.yacy.yacyNewsPool;
import de.anomic.yacy.graphics.ProfilingGraph;
+import de.anomic.yacy.yacyChannel;
public class yacysearch {
@@ -435,22 +435,22 @@ public class yacysearch {
final URIMetadataRow urlentry = indexSegment.urlMetadata().load(recommendHash.getBytes(), null, 0);
if (urlentry != null) {
final URIMetadataRow.Components metadata = urlentry.metadata();
- Document document = null;
+ Document[] documents = null;
try {
- document = sb.loader.loadDocument(sb.loader.request(metadata.url(), true, false), CrawlProfile.CacheStrategy.IFEXIST, 5000, Long.MAX_VALUE);
+ documents = sb.loader.loadDocuments(sb.loader.request(metadata.url(), true, false), CrawlProfile.CacheStrategy.IFEXIST, 5000, Long.MAX_VALUE);
} catch (IOException e) {
- } catch (ParserException e) {
+ } catch (Parser.Failure e) {
}
- if (document != null) {
+ if (documents != null) {
// create a news message
final HashMap<String, String> map = new HashMap<String, String>();
map.put("url", metadata.url().toNormalform(false, true).replace(',', '|'));
map.put("title", metadata.dc_title().replace(',', ' '));
- map.put("description", document.dc_title().replace(',', ' '));
- map.put("author", document.dc_creator());
- map.put("tags", document.dc_subject(' '));
+ map.put("description", documents[0].dc_title().replace(',', ' '));
+ map.put("author", documents[0].dc_creator());
+ map.put("tags", documents[0].dc_subject(' '));
sb.peers.newsPool.publishMyNews(sb.peers.mySeed(), yacyNewsPool.CATEGORY_SURFTIPP_ADD, map);
- document.close();
+ documents[0].close();
}
}
}
@@ -498,7 +498,7 @@ public class yacysearch {
// log
Log.logInfo("LOCAL_SEARCH", "INIT WORD SEARCH: " + theQuery.queryString + ":" + QueryParams.hashSet2hashString(theQuery.queryHashes) + " - " + theQuery.neededResults() + " links to be computed, " + theQuery.displayResults() + " lines to be displayed");
- RSSFeed.channels(RSSFeed.YaCyChannel.LOCALSEARCH).addMessage(new RSSMessage("Local Search Request", theQuery.queryString, ""));
+ yacyChannel.channels(yacyChannel.LOCALSEARCH).addMessage(new RSSMessage("Local Search Request", theQuery.queryString, ""));
final long timestamp = System.currentTimeMillis();
// create a new search event
diff --git a/source/de/anomic/crawler/ResultImages.java b/source/de/anomic/crawler/ResultImages.java
index 2626384c0..352c961ea 100755
--- a/source/de/anomic/crawler/ResultImages.java
+++ b/source/de/anomic/crawler/ResultImages.java
@@ -33,6 +33,7 @@ import java.util.concurrent.ConcurrentLinkedQueue;
import net.yacy.cora.document.MultiProtocolURI;
import net.yacy.document.Document;
import net.yacy.document.parser.html.ImageEntry;
+import net.yacy.kelondro.data.meta.DigestURI;
public class ResultImages {
@@ -50,9 +51,9 @@ public class ResultImages {
// the same images may be linked from different pages
private static final ConcurrentHashMap<MultiProtocolURI, Long> doubleCheck = new ConcurrentHashMap<MultiProtocolURI, Long>(); // (url, time) when the url appeared first
- public static void registerImages(final Document document, final boolean privateEntry) {
+ public static void registerImages(final DigestURI source, final Document document, final boolean privateEntry) {
if (document == null) return;
- if (document.dc_source() == null) return;
+ if (source == null) return;
final HashMap<MultiProtocolURI, ImageEntry> images = document.getImages();
for (final ImageEntry image: images.values()) {
@@ -81,15 +82,15 @@ public class ResultImages {
}
if (good) {
if (privateEntry) {
- privateImageQueueHigh.add(new OriginEntry(image, document.dc_source()));
+ privateImageQueueHigh.add(new OriginEntry(image, source));
} else {
- publicImageQueueHigh.add(new OriginEntry(image, document.dc_source()));
+ publicImageQueueHigh.add(new OriginEntry(image, source));
}
} else {
if (privateEntry) {
- privateImageQueueLow.add(new OriginEntry(image, document.dc_source()));
+ privateImageQueueLow.add(new OriginEntry(image, source));
} else {
- publicImageQueueLow.add(new OriginEntry(image, document.dc_source()));
+ publicImageQueueLow.add(new OriginEntry(image, source));
}
}
}
diff --git a/source/de/anomic/crawler/retrieval/Response.java b/source/de/anomic/crawler/retrieval/Response.java
index 1c1df1a20..73ca3fa27 100755
--- a/source/de/anomic/crawler/retrieval/Response.java
+++ b/source/de/anomic/crawler/retrieval/Response.java
@@ -31,7 +31,7 @@ import java.util.Date;
import net.yacy.document.Classification;
import net.yacy.document.Document;
-import net.yacy.document.ParserException;
+import net.yacy.document.Parser;
import net.yacy.document.TextParser;
import net.yacy.kelondro.data.meta.DigestURI;
import net.yacy.kelondro.util.DateFormatter;
@@ -802,14 +802,12 @@ public class Response {
return processCase;
}
- public Document parse() throws ParserException {
-
+ public Document[] parse() throws Parser.Failure {
String supportError = TextParser.supports(url(), this.responseHeader == null ? null : this.responseHeader.mime());
- if (supportError != null) throw new ParserException("no parser support:" + supportError, url());
-
+ if (supportError != null) throw new Parser.Failure("no parser support:" + supportError, url());
try {
return TextParser.parseSource(url(), this.responseHeader == null ? null : this.responseHeader.mime(), this.responseHeader == null ? "UTF-8" : this.responseHeader.getCharacterEncoding(), this.content.length, new ByteArrayInputStream(this.content));
- } catch (InterruptedException e) {
+ } catch (Exception e) {
return null;
}
diff --git a/source/de/anomic/search/DocumentIndex.java b/source/de/anomic/search/DocumentIndex.java
index 2e0a0867f..f163bbd34 100644
--- a/source/de/anomic/search/DocumentIndex.java
+++ b/source/de/anomic/search/DocumentIndex.java
@@ -38,7 +38,6 @@ import java.util.concurrent.LinkedBlockingQueue;
import net.yacy.document.Condenser;
import net.yacy.document.Document;
import net.yacy.document.TextParser;
-import net.yacy.document.ParserException;
import net.yacy.kelondro.data.meta.DigestURI;
import net.yacy.kelondro.data.meta.URIMetadataRow;
import net.yacy.kelondro.data.meta.URIMetadataRow.Components;
@@ -121,14 +120,13 @@ public class DocumentIndex extends Segment {
if (url == null) throw new IOException("file = null");
if (url.isDirectory()) throw new IOException("file should be a document, not a path");
if (!url.canRead()) throw new IOException("cannot read file");
- Document document;
+ Document[] documents;
try {
- document = TextParser.parseSource(url, null, null, url.length(), url.getInputStream());
- } catch (InterruptedException e) {
- throw new IOException("cannot parse " + url.toString() + ": " + e.getMessage());
- } catch (ParserException e) {
+ documents = TextParser.parseSource(url, null, null, url.length(), url.getInputStream());
+ } catch (Exception e) {
throw new IOException("cannot parse " + url.toString() + ": " + e.getMessage());
}
+ Document document = Document.mergeDocuments(url, null, documents);
final Condenser condenser = new Condenser(document, true, true);
return super.storeDocument(
url,
diff --git a/source/de/anomic/search/MediaSnippet.java b/source/de/anomic/search/MediaSnippet.java
index 722a1840c..f6fa0fafc 100644
--- a/source/de/anomic/search/MediaSnippet.java
+++ b/source/de/anomic/search/MediaSnippet.java
@@ -36,7 +36,7 @@ import de.anomic.data.MimeTable;
import net.yacy.cora.document.MultiProtocolURI;
import net.yacy.document.Document;
-import net.yacy.document.ParserException;
+import net.yacy.document.Parser;
import net.yacy.document.parser.html.ImageEntry;
import net.yacy.kelondro.data.meta.DigestURI;
import net.yacy.kelondro.index.HandleSet;
@@ -121,25 +121,25 @@ public class MediaSnippet implements Comparable<MediaSnippet>, Comparator<MediaS
Document document;
try {
- document = Switchboard.getSwitchboard().loader.loadDocument(Switchboard.getSwitchboard().loader.request(url, false, reindexing), cacheStrategy, timeout, Long.MAX_VALUE);
+ document = Document.mergeDocuments(url, null, Switchboard.getSwitchboard().loader.loadDocuments(Switchboard.getSwitchboard().loader.request(url, false, reindexing), cacheStrategy, timeout, Long.MAX_VALUE));
} catch (IOException e) {
Log.logFine("snippet fetch", "load error: " + e.getMessage());
return new ArrayList<MediaSnippet>();
- } catch (ParserException e) {
+ } catch (Parser.Failure e) {
Log.logFine("snippet fetch", "parser error: " + e.getMessage());
return new ArrayList<MediaSnippet>();
}
final ArrayList<MediaSnippet> a = new ArrayList<MediaSnippet>();
if (document != null) {
- if ((mediatype == ContentDomain.ALL) || (mediatype == ContentDomain.AUDIO)) a.addAll(computeMediaSnippets(document, queryhashes, ContentDomain.AUDIO));
- if ((mediatype == ContentDomain.ALL) || (mediatype == ContentDomain.VIDEO)) a.addAll(computeMediaSnippets(document, queryhashes, ContentDomain.VIDEO));
- if ((mediatype == ContentDomain.ALL) || (mediatype == ContentDomain.APP)) a.addAll(computeMediaSnippets(document, queryhashes, ContentDomain.APP));
- if ((mediatype == ContentDomain.ALL) || (mediatype == ContentDomain.IMAGE)) a.addAll(computeImageSnippets(document, queryhashes));
+ if ((mediatype == ContentDomain.ALL) || (mediatype == ContentDomain.AUDIO)) a.addAll(computeMediaSnippets(url, document, queryhashes, ContentDomain.AUDIO));
+ if ((mediatype == ContentDomain.ALL) || (mediatype == ContentDomain.VIDEO)) a.addAll(computeMediaSnippets(url, document, queryhashes, ContentDomain.VIDEO));
+ if ((mediatype == ContentDomain.ALL) || (mediatype == ContentDomain.APP)) a.addAll(computeMediaSnippets(url, document, queryhashes, ContentDomain.APP));
+ if ((mediatype == ContentDomain.ALL) || (mediatype == ContentDomain.IMAGE)) a.addAll(computeImageSnippets(url, document, queryhashes));
}
return a;
}
- public static ArrayList<MediaSnippet> computeMediaSnippets(final Document document, final HandleSet queryhashes, final ContentDomain mediatype) {
+ public static ArrayList<MediaSnippet> computeMediaSnippets(final DigestURI source, final Document document, final HandleSet queryhashes, final ContentDomain mediatype) {
if (document == null) return new ArrayList<MediaSnippet>();
Map<MultiProtocolURI, String> media = null;
@@ -160,13 +160,13 @@ public class MediaSnippet implements Comparable<MediaSnippet>, Comparator<MediaS
int ranking = TextSnippet.removeAppearanceHashes(url.toNormalform(false, false), queryhashes).size() +
TextSnippet.removeAppearanceHashes(desc, queryhashes).size();
if (ranking < 2 * queryhashes.size()) {
- result.add(new MediaSnippet(mediatype, url, MimeTable.url2mime(url), desc, document.getTextLength(), null, ranking, new DigestURI(document.dc_source())));
+ result.add(new MediaSnippet(mediatype, url, MimeTable.url2mime(url), desc, document.getTextLength(), null, ranking, source));
}
}
return result;
}
- public static ArrayList<MediaSnippet> computeImageSnippets(final Document document, final HandleSet queryhashes) {
+ public static ArrayList<MediaSnippet> computeImageSnippets(final DigestURI source, final Document document, final HandleSet queryhashes) {
final TreeSet<ImageEntry> images = new TreeSet<ImageEntry>();
images.addAll(document.getImages().values()); // iterates images in descending size order!
@@ -189,7 +189,7 @@ public class MediaSnippet implements Comparable<MediaSnippet>, Comparator<MediaS
TextSnippet.removeAppearanceHashes(url.toNormalform(false, false), queryhashes).size() -
TextSnippet.removeAppearanceHashes(desc, queryhashes).size();
final int ranking = Integer.MAX_VALUE - (ientry.height() + 1) * (ientry.width() + 1) * (appcount + 1);
- result.add(new MediaSnippet(ContentDomain.IMAGE, url, MimeTable.url2mime(url), desc, ientry.fileSize(), ientry.width(), ientry.height(), ranking, new DigestURI(document.dc_source())));
+ result.add(new MediaSnippet(ContentDomain.IMAGE, url, MimeTable.url2mime(url), desc, ientry.fileSize(), ientry.width(), ientry.height(), ranking, source));
}
return result;
}
diff --git a/source/de/anomic/search/Segment.java b/source/de/anomic/search/Segment.java
index 74144c836..751db3ff2 100644
--- a/source/de/anomic/search/Segment.java
+++ b/source/de/anomic/search/Segment.java
@@ -38,7 +38,7 @@ import java.util.TreeSet;
import net.yacy.cora.document.MultiProtocolURI;
import net.yacy.document.Condenser;
import net.yacy.document.Document;
-import net.yacy.document.ParserException;
+import net.yacy.document.Parser;
import net.yacy.kelondro.data.meta.DigestURI;
import net.yacy.kelondro.data.meta.URIMetadataRow;
import net.yacy.kelondro.data.navigation.NavigationReference;
@@ -410,7 +410,7 @@ public class Segment {
try {
// parse the resource
- final Document document = loader.loadDocument(loader.request(metadata.url(), true, false), cacheStrategy, 10000, Long.MAX_VALUE);
+ final Document document = Document.mergeDocuments(metadata.url(), null, loader.loadDocuments(loader.request(metadata.url(), true, false), cacheStrategy, 10000, Long.MAX_VALUE));
if (document == null) {
// delete just the url entry
urlMetadata().remove(urlhash);
@@ -431,7 +431,7 @@ public class Segment {
// finally delete the url entry itself
urlMetadata().remove(urlhash);
return count;
- } catch (final ParserException e) {
+ } catch (final Parser.Failure e) {
return 0;
} catch (IOException e) {
Log.logException(e);
diff --git a/source/de/anomic/search/Switchboard.java b/source/de/anomic/search/Switchboard.java
index 9383c0b1e..ebee4d65d 100644
--- a/source/de/anomic/search/Switchboard.java
+++ b/source/de/anomic/search/Switchboard.java
@@ -71,17 +71,15 @@ import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import net.yacy.cora.document.MultiProtocolURI;
-import net.yacy.cora.document.RSSFeed;
import net.yacy.cora.document.RSSMessage;
import net.yacy.cora.protocol.ProxySettings;
import net.yacy.document.Condenser;
import net.yacy.document.Document;
+import net.yacy.document.Parser;
import net.yacy.document.TextParser;
-import net.yacy.document.ParserException;
import net.yacy.document.content.DCEntry;
import net.yacy.document.content.SurrogateReader;
import net.yacy.document.importer.OAIListFriendsLoader;
-import net.yacy.document.parser.html.ImageEntry;
import net.yacy.kelondro.data.meta.DigestURI;
import net.yacy.kelondro.data.meta.URIMetadataRow;
import net.yacy.kelondro.data.meta.URIMetadataRow.Components;
@@ -149,6 +147,7 @@ import de.anomic.server.serverCore;
import de.anomic.tools.crypt;
import de.anomic.tools.CryptoLib;
import de.anomic.yacy.yacyBuildProperties;
+import de.anomic.yacy.yacyChannel;
import de.anomic.yacy.yacyClient;
import de.anomic.yacy.yacyCore;
import de.anomic.yacy.yacyNewsPool;
@@ -1338,7 +1337,7 @@ public final class Switchboard extends serverSwitch {
0
);
response = new Response(request, null, null, "200", this.crawler.defaultSurrogateProfile);
- indexingQueueEntry queueEntry = new indexingQueueEntry(Segments.Process.SURROGATES, response, document, null);
+ indexingQueueEntry queueEntry = new indexingQueueEntry(Segments.Process.SURROGATES, response, new Document[]{document}, null);
// place the queue entry into the concurrent process of the condenser (document analysis)
try {
@@ -1402,17 +1401,17 @@ public final class Switchboard extends serverSwitch {
public static class indexingQueueEntry extends WorkflowJob {
public Segments.Process process;
public Response queueEntry;
- public Document document;
- public Condenser condenser;
+ public Document[] documents;
+ public Condenser[] condenser;
public indexingQueueEntry(
final Segments.Process process,
final Response queueEntry,
- final Document document,
- final Condenser condenser) {
+ final Document[] documents,
+ final Condenser[] condenser) {
super();
this.process = process;
this.queueEntry = queueEntry;
- this.document = document;
+ this.documents = documents;
this.condenser = condenser;
}
}
@@ -1670,22 +1669,22 @@ public final class Switchboard extends serverSwitch {
// debug
if (log.isFinest()) log.logFinest("PARSE "+ in.queueEntry);
- Document document = null;
+ Document[] documents = null;
try {
- document = parseDocument(in.queueEntry);
+ documents = parseDocument(in.queueEntry);
} catch (final InterruptedException e) {
- document = null;
+ documents = null;
} catch (final Exception e) {
- document = null;
+ documents = null;
}
- if (document == null) {
+ if (documents == null) {
return null;
}
- return new indexingQueueEntry(in.process, in.queueEntry, document, null);
+ return new indexingQueueEntry(in.process, in.queueEntry, documents, null);
}
- private Document parseDocument(final Response response) throws InterruptedException {
- Document document = null;
+ private Document[] parseDocument(final Response response) throws InterruptedException {
+ Document[] documents = null;
final EventOrigin processCase = response.processCase(peers.mySeed().hash);
if (this.log.isFine()) log.logFine("processResourceStack processCase=" + processCase +
@@ -1713,15 +1712,11 @@ public final class Switchboard extends serverSwitch {
try {
// parse the document
- document = TextParser.parseSource(response.url(), response.getMimeType(), response.getCharacterEncoding(), b);
- assert(document != null) : "Unexpected error. Parser returned null.";
- } catch (final ParserException e) {
+ documents = TextParser.parseSource(response.url(), response.getMimeType(), response.getCharacterEncoding(), b);
+ assert(documents != null) : "Unexpected error. Parser returned null.";
+ } catch (final Parser.Failure e) {
this.log.logWarning("Unable to parse the resource '" + response.url() + "'. " + e.getMessage());
addURLtoErrorDB(response.url(), response.referrerHash(), response.initiator(), response.name(), e.getMessage());
- if (document != null) {
- document.close();
- document = null;
- }
return null;
}
@@ -1734,12 +1729,10 @@ public final class Switchboard extends serverSwitch {
((response.profile() == null) || (response.depth() < response.profile().depth()))
) {
// get the hyperlinks
- final Map<MultiProtocolURI, String> hl = document.getHyperlinks();
+ final Map<MultiProtocolURI, String> hl = Document.getHyperlinks(documents);
// add all images also to the crawl stack
- for (ImageEntry imageReference : document.getImages().values()) {
- hl.put(imageReference.url(), imageReference.alt());
- }
+ hl.putAll(Document.getImagelinks(documents));
// insert those hyperlinks to the crawler
MultiProtocolURI nextUrl;
@@ -1773,50 +1766,69 @@ public final class Switchboard extends serverSwitch {
", STACKING TIME = " + (stackEndTime-stackStartTime) +
", PARSING TIME = " + (parsingEndTime-parsingStartTime));
}
- return document;
+ return documents;
}
public indexingQueueEntry condenseDocument(final indexingQueueEntry in) {
in.queueEntry.updateStatus(Response.QUEUE_STATE_CONDENSING);
-
- if (in.document.indexingDenied()) {
- if (log.isInfo()) log.logInfo("Not Condensed Resource '" + in.queueEntry.url().toNormalform(false, true) + "': denied by document-attached noindexing rule");
- return new indexingQueueEntry(in.process, in.queueEntry, in.document, null);
- }
-
if (!in.queueEntry.profile().indexText() && !in.queueEntry.profile().indexMedia()) {
if (log.isInfo()) log.logInfo("Not Condensed Resource '" + in.queueEntry.url().toNormalform(false, true) + "': indexing not wanted by crawl profile");
- return new indexingQueueEntry(in.process, in.queueEntry, in.document, null);
+ return new indexingQueueEntry(in.process, in.queueEntry, in.documents, null);
}
+ List<Document> doclist = new ArrayList<Document>();
- // strip out words and generate statistics
+ // check which files may take part in the indexing process
+ for (Document document: in.documents) {
+ if (document.indexingDenied()) {
+ if (log.isInfo()) log.logInfo("Not Condensed Resource '" + in.queueEntry.url().toNormalform(false, true) + "': denied by document-attached noindexing rule");
+ continue;
+ }
+ doclist.add(document);
+ }
+
+ if (doclist.size() == 0) return new indexingQueueEntry(in.process, in.queueEntry, in.documents, null);
+ in.documents = doclist.toArray(new Document[doclist.size()]);
+ Condenser[] condenser = new Condenser[in.documents.length];
if (this.log.isFine()) log.logFine("Condensing for '" + in.queueEntry.url().toNormalform(false, true) + "'");
- try {
- Condenser condenser = new Condenser(in.document, in.queueEntry.profile().indexText(), in.queueEntry.profile().indexMedia());
+ for (int i = 0; i < in.documents.length; i++) {
+ // strip out words and generate statistics
+ try {
+ condenser[i] = new Condenser(in.documents[i], in.queueEntry.profile().indexText(), in.queueEntry.profile().indexMedia());
+
+ // update image result list statistics
+ // its good to do this concurrently here, because it needs a DNS lookup
+ // to compute a URL hash which is necessary for a double-check
+ final CrawlProfile.entry profile = in.queueEntry.profile();
+ ResultImages.registerImages(in.queueEntry.url(), in.documents[i], (profile == null) ? true : !profile.remoteIndexing());
- // update image result list statistics
- // its good to do this concurrently here, because it needs a DNS lookup
- // to compute a URL hash which is necessary for a double-check
- final CrawlProfile.entry profile = in.queueEntry.profile();
- ResultImages.registerImages(in.document, (profile == null) ? true : !profile.remoteIndexing());
-
- return new indexingQueueEntry(in.process, in.queueEntry, in.document, condenser);
- } catch (final UnsupportedEncodingException e) {
- return null;
+ } catch (final UnsupportedEncodingException e) {
+ return null;
+ }
}
+ return new indexingQueueEntry(in.process, in.queueEntry, in.documents, condenser);
}
public indexingQueueEntry webStructureAnalysis(final indexingQueueEntry in) {
in.queueEntry.updateStatus(Response.QUEUE_STATE_STRUCTUREANALYSIS);
- final Integer[] ioLinks = webStructure.generateCitationReference(in.document, in.condenser, in.queueEntry.lastModified()); // [outlinksSame, outlinksOther]
- in.document.setInboundLinks(ioLinks[0].intValue());
- in.document.setOutboundLinks(ioLinks[1].intValue());
+ for (int i = 0; i < in.documents.length; i++) {
+ assert webStructure != null;
+ assert in != null;
+ assert in.queueEntry != null;
+ assert in.documents != null;
+ assert in.queueEntry != null;
+ final Integer[] ioLinks = webStructure.generateCitationReference(in.queueEntry.url(), in.documents[i], (in.condenser == null) ? null : in.condenser[i], in.queueEntry.lastModified()); // [outlinksSame, outlinksOther]
+ in.documents[i].setInboundLinks(ioLinks[0].intValue());
+ in.documents[i].setOutboundLinks(ioLinks[1].intValue());
+ }
return in;
}
public void storeDocumentIndex(final indexingQueueEntry in) {
in.queueEntry.updateStatus(Response.QUEUE_STATE_INDEXSTORAGE);
- storeDocumentIndex(in.process, in.queueEntry, in.document, in.condenser, null);
+ // the condenser may be null in case that an indexing is not wanted (there may be a no-indexing flag in the file)
+ if (in.condenser != null) for (int i = 0; i < in.documents.length; i++) {
+ storeDocumentIndex(in.process, in.queueEntry, in.documents[i], in.condenser[i], null);
+ }
in.queueEntry.updateStatus(Response.QUEUE_STATE_FINISHED);
}
@@ -1855,7 +1867,7 @@ public final class Switchboard extends serverSwitch {
document,
condenser,
searchEvent);
- RSSFeed.channels(Base64Order.enhancedCoder.equal(queueEntry.initiator(), peers.mySeed().hash.getBytes()) ? RSSFeed.YaCyChannel.LOCALINDEXING : RSSFeed.YaCyChannel.REMOTEINDEXING).addMessage(new RSSMessage("Indexed web page", dc_title, queueEntry.url().toNormalform(true, false)));
+ yacyChannel.channels(Base64Order.enhancedCoder.equal(queueEntry.initiator(), peers.mySeed().hash.getBytes()) ? yacyChannel.LOCALINDEXING : yacyChannel.REMOTEINDEXING).addMessage(new RSSMessage("Indexed web page", dc_title, queueEntry.url().toNormalform(true, false)));
} catch (final IOException e) {
if (this.log.isFine()) log.logFine("Not Indexed Resource '" + queueEntry.url().toNormalform(false, true) + "': process case=" + processCase);
addURLtoErrorDB(queueEntry.url(), (referrerURL == null) ? null : referrerURL.hash(), queueEntry.initiator(), dc_title, "error storing url: " + e.getMessage());
@@ -1899,7 +1911,7 @@ public final class Switchboard extends serverSwitch {
// add the landing page to the index. should not load that again since it should be in the cache
if (url != null) try {
this.addToIndex(url, searchEvent, heuristicName);
- } catch (IOException e) {} catch (ParserException e) {}
+ } catch (IOException e) {} catch (Parser.Failure e) {}
// check if some of the links match with the query
Map<MultiProtocolURI, String> matcher = searchEvent.getQuery().separateMatches(links);
@@ -1908,14 +1920,14 @@ public final class Switchboard extends serverSwitch {
for (Map.Entry<MultiProtocolURI, String> entry: matcher.entrySet()) {
try {
this.addToIndex(new DigestURI(entry.getKey(), (byte[]) null), searchEvent, heuristicName);
- } catch (IOException e) {} catch (ParserException e) {}
+ } catch (IOException e) {} catch (Parser.Failure e) {}
}
// take then the no-matcher and load them also
for (Map.Entry<MultiProtocolURI, String> entry: links.entrySet()) {
try {
this.addToIndex(new DigestURI(entry.getKey(), (byte[]) null), searchEvent, heuristicName);
- } catch (IOException e) {} catch (ParserException e) {}
+ } catch (IOException e) {} catch (Parser.Failure e) {}
}
}
@@ -1925,9 +1937,9 @@ public final class Switchboard extends serverSwitch {
* @param url the url that shall be indexed
* @param searchEvent (optional) a search event that shall get results from the indexed pages directly feeded. If object is null then it is ignored
* @throws IOException
- * @throws ParserException
+ * @throws Parser.Failure
*/
- public void addToIndex(final DigestURI url, final SearchEvent searchEvent, final String heuristicName) throws IOException, ParserException {
+ public void addToIndex(final DigestURI url, final SearchEvent searchEvent, final String heuristicName) throws IOException, Parser.Failure {
final Segments.Process process = Segments.Process.LOCALCRAWLING;
if (indexSegments.segment(process).urlMetadata.exists(url.hash())) {
searchEvent.addHeuristic(url.hash(), heuristicName, true);
@@ -1946,16 +1958,18 @@ public final class Switchboard extends serverSwitch {
if (response == null) throw new IOException("response == null");
if (response.getContent() == null) throw new IOException("content == null");
if (response.getResponseHeader() == null) throw new IOException("header == null");
- Document document = response.parse();
- if (document.indexingDenied()) throw new ParserException("indexing is denied", url);
- Condenser condenser = new Condenser(document, true, true);
- ResultImages.registerImages(document, true);
- webStructure.generateCitationReference(document, condenser, response.lastModified());
- storeDocumentIndex(process, response, document, condenser, searchEvent);
- log.logInfo("heuristic fill of url " + url.toNormalform(true, true) + " finished");
+ Document[] documents = response.parse();
+ if (documents != null) for (Document document: documents) {
+ if (document.indexingDenied()) throw new Parser.Failure("indexing is denied", url);
+ Condenser condenser = new Condenser(document, true, true);
+ ResultImages.registerImages(url, document, true);
+ webStructure.generateCitationReference(url, document, condenser, response.lastModified());
+ storeDocumentIndex(process, response, document, condenser, searchEvent);
+ log.logInfo("heuristic fill of url " + url.toNormalform(true, true) + " finished");
+ }
} catch (IOException e) {
//Log.logException(e);
- } catch (ParserException e) {
+ } catch (Parser.Failure e) {
//Log.logException(e);
}
}}.start();
diff --git a/source/de/anomic/search/TextSnippet.java b/source/de/anomic/search/TextSnippet.java
index 718d14f2b..c7dd53a14 100644
--- a/source/de/anomic/search/TextSnippet.java
+++ b/source/de/anomic/search/TextSnippet.java
@@ -33,7 +33,7 @@ import java.util.regex.Pattern;
import net.yacy.document.Condenser;
import net.yacy.document.Document;
-import net.yacy.document.ParserException;
+import net.yacy.document.Parser;
import net.yacy.document.parser.html.CharacterCoding;
import net.yacy.kelondro.data.meta.DigestURI;
import net.yacy.kelondro.data.meta.URIMetadataRow;
@@ -374,8 +374,8 @@ public class TextSnippet implements Comparable<TextSnippet>, Comparator<TextSnip
* =========================================================================== */
Document document = null;
try {
- document = response.parse();
- } catch (final ParserException e) {
+ document = Document.mergeDocuments(response.url(), response.getMimeType(), response.parse());
+ } catch (final Parser.Failure e) {
return new TextSnippet(url, null, ERROR_PARSER_FAILED, queryhashes, e.getMessage()); // cannot be parsed
}
if (document == null) return new TextSnippet(url, null, ERROR_PARSER_FAILED, queryhashes, "parser error/failed"); // cannot be parsed
diff --git a/source/de/anomic/yacy/graphics/NetworkGraph.java b/source/de/anomic/yacy/graphics/NetworkGraph.java
index 405cae361..3a7827314 100644
--- a/source/de/anomic/yacy/graphics/NetworkGraph.java
+++ b/source/de/anomic/yacy/graphics/NetworkGraph.java
@@ -36,8 +36,6 @@ import java.util.Date;
import java.util.Iterator;
import net.yacy.cora.document.Hit;
-import net.yacy.cora.document.RSSFeed;
-import net.yacy.cora.document.RSSFeed.YaCyChannel;
import net.yacy.visualization.PrintTool;
import net.yacy.visualization.RasterPlotter;
@@ -46,6 +44,7 @@ import de.anomic.search.SearchEvent;
import de.anomic.search.SearchEventCache;
import de.anomic.search.Switchboard;
import de.anomic.search.SwitchboardConstants;
+import de.anomic.yacy.yacyChannel;
import de.anomic.yacy.yacySearch;
import de.anomic.yacy.yacySeed;
import de.anomic.yacy.yacySeedDB;
@@ -236,7 +235,7 @@ public class NetworkGraph {
// draw DHT activity
if (communicationTimeout >= 0) {
Date horizon = new Date(System.currentTimeMillis() - communicationTimeout);
- for (Hit event: RSSFeed.channels(YaCyChannel.DHTRECEIVE)) {
+ for (Hit event: yacyChannel.channels(yacyChannel.DHTRECEIVE)) {
assert event != null;
assert event.getPubDate() != null;
if (event.getPubDate().after(horizon)) {
@@ -244,7 +243,7 @@ public class NetworkGraph {
drawNetworkPictureConnection(networkPicture, width / 2, height / 2 + 20, innerradius, seedDB.mySeed(), seedDB.get(event.getLink()), COL_DHTIN);
}
}
- for (Hit event: RSSFeed.channels(YaCyChannel.DHTSEND)) {
+ for (Hit event: yacyChannel.channels(yacyChannel.DHTSEND)) {
assert event != null;
assert event.getPubDate() != null;
if (event.getPubDate().after(horizon)) {
diff --git a/source/de/anomic/yacy/graphics/WebStructureGraph.java b/source/de/anomic/yacy/graphics/WebStructureGraph.java
index 546e0f482..48965992f 100644
--- a/source/de/anomic/yacy/graphics/WebStructureGraph.java
+++ b/source/de/anomic/yacy/graphics/WebStructureGraph.java
@@ -95,9 +95,7 @@ public class WebStructureGraph {
}
}
- public Integer[] /*(outlinksSame, outlinksOther)*/ generateCitationReference(final Document document, final Condenser condenser, final Date docDate) {
- final DigestURI url = new DigestURI(document.dc_source());
-
+ public Integer[] /*(outlinksSame, outlinksOther)*/ generateCitationReference(final DigestURI url, final Document document, final Condenser condenser, final Date docDate) {
// generate citation reference
final Map<MultiProtocolURI, String> hl = document.getHyperlinks();
final Iterator<MultiProtocolURI> it = hl.keySet().iterator();
diff --git a/source/de/anomic/yacy/yacyChannel.java b/source/de/anomic/yacy/yacyChannel.java
new file mode 100644
index 000000000..a9ebf5833
--- /dev/null
+++ b/source/de/anomic/yacy/yacyChannel.java
@@ -0,0 +1,73 @@
+/**
+ * yacyChannel
+ * Copyright 2010 by Michael Peter Christen
+ * First released 29.6.2010 at http://yacy.net
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program in the file lgpl21.txt
+ * If not, see <http://www.gnu.org/licenses/>.
+ */
+
+package de.anomic.yacy;
+
+import java.util.HashSet;
+import java.util.concurrent.ConcurrentHashMap;
+
+import net.yacy.cora.document.RSSFeed;
+import net.yacy.cora.document.RSSMessage;
+
+public enum yacyChannel {
+ TEST,
+ PEERNEWS,
+ REMOTESEARCH,
+ LOCALSEARCH,
+ REMOTEINDEXING,
+ LOCALINDEXING,
+ DHTRECEIVE,
+ DHTSEND;
+
+
+ // test:
+ // http://localhost:8080/xml/feed.rss?set=PEERNEWS,REMOTESEARCH,LOCALSEARCH,REMOTEINDEXING,LOCALINDEXING
+
+ /**
+ * the following private channels are declared to prevent that an access to the feed servlet
+ * gets results from news channels that are not for the public
+ */
+ public static final HashSet<yacyChannel> privateChannels = new HashSet<yacyChannel>();
+ static {
+ privateChannels.add(yacyChannel.LOCALSEARCH);
+ privateChannels.add(yacyChannel.LOCALINDEXING);
+ }
+
+
+ /**
+ * the following static channels object is used to organize a storage array for RSS feeds
+ */
+ private static final ConcurrentHashMap<yacyChannel, RSSFeed> channels = new ConcurrentHashMap<yacyChannel, RSSFeed>();
+ public static RSSFeed channels(final String channelName) {
+ for (yacyChannel channel: yacyChannel.values()) {
+ if (channel.name().equals(channelName)) return channels(channel);
+ }
+ return null;
+ }
+
+ public static RSSFeed channels(final yacyChannel channel) {
+ RSSFeed feed = channels.get(channel);
+ if (feed != null) return feed;
+ feed = new RSSFeed(200);
+ feed.setChannel(new RSSMessage(channel.name(), "", ""));
+ channels.put(channel, feed);
+ return feed;
+ }
+}
\ No newline at end of file
diff --git a/source/de/anomic/yacy/yacyClient.java b/source/de/anomic/yacy/yacyClient.java
index b8beb5d48..84980591e 100644
--- a/source/de/anomic/yacy/yacyClient.java
+++ b/source/de/anomic/yacy/yacyClient.java
@@ -874,7 +874,7 @@ public final class yacyClient {
if (uhss == null) {
return "no unknownURL tag in response";
}
- RSSFeed.channels(RSSFeed.YaCyChannel.DHTSEND).addMessage(new RSSMessage("Sent " + indexes.size() + " RWIs to " + targetSeed.getName(), "", targetSeed.hash));
+ yacyChannel.channels(yacyChannel.DHTSEND).addMessage(new RSSMessage("Sent " + indexes.size() + " RWIs to " + targetSeed.getName(), "", targetSeed.hash));
uhss = uhss.trim();
if (uhss.length() == 0 || uhss.equals(",")) { return null; } // all url's known, we are ready here
@@ -908,7 +908,7 @@ public final class yacyClient {
if (!result.equals("ok")) {
return result;
}
- RSSFeed.channels(RSSFeed.YaCyChannel.DHTSEND).addMessage(new RSSMessage("Sent " + uhs.length + " URLs to peer " + targetSeed.getName(), "", targetSeed.hash));
+ yacyChannel.channels(yacyChannel.DHTSEND).addMessage(new RSSMessage("Sent " + uhs.length + " URLs to peer " + targetSeed.getName(), "", targetSeed.hash));
return null;
} finally {
diff --git a/source/de/anomic/yacy/yacyCore.java b/source/de/anomic/yacy/yacyCore.java
index 7c27290db..c74129374 100644
--- a/source/de/anomic/yacy/yacyCore.java
+++ b/source/de/anomic/yacy/yacyCore.java
@@ -98,7 +98,7 @@ public class yacyCore {
sb.setConfig("yacyStatus", "");
// create a peer news channel
- final RSSFeed peernews = RSSFeed.channels(RSSFeed.YaCyChannel.PEERNEWS);
+ final RSSFeed peernews = yacyChannel.channels(yacyChannel.PEERNEWS);
peernews.addMessage(new RSSMessage("YaCy started", "", ""));
// ensure that correct IP is used
diff --git a/source/de/anomic/yacy/yacyPeerActions.java b/source/de/anomic/yacy/yacyPeerActions.java
index 416615c6e..88d23420b 100644
--- a/source/de/anomic/yacy/yacyPeerActions.java
+++ b/source/de/anomic/yacy/yacyPeerActions.java
@@ -27,7 +27,6 @@ package de.anomic.yacy;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
-import net.yacy.cora.document.RSSFeed;
import net.yacy.cora.document.RSSMessage;
import net.yacy.kelondro.logging.Log;
import net.yacy.kelondro.util.DateFormatter;
@@ -197,7 +196,7 @@ public class yacyPeerActions {
if (res) {
// perform all actions if peer is effective new
this.processPeerArrival(peer);
- RSSFeed.channels(RSSFeed.YaCyChannel.PEERNEWS).addMessage(new RSSMessage(peer.getName() + " joined the network", "", ""));
+ yacyChannel.channels(yacyChannel.PEERNEWS).addMessage(new RSSMessage(peer.getName() + " joined the network", "", ""));
}
return res;
}
@@ -211,7 +210,7 @@ public class yacyPeerActions {
peer.put("dct", Long.toString(System.currentTimeMillis()));
seedDB.addDisconnected(peer); // update info
}
- RSSFeed.channels(RSSFeed.YaCyChannel.PEERNEWS).addMessage(new RSSMessage(peer.getName() + " left the network", "", ""));
+ yacyChannel.channels(yacyChannel.PEERNEWS).addMessage(new RSSMessage(peer.getName() + " left the network", "", ""));
}
public void peerPing(final yacySeed peer) {
@@ -220,7 +219,7 @@ public class yacyPeerActions {
seedDB.addPotential(peer);
// perform all actions
processPeerArrival(peer);
- RSSFeed.channels(RSSFeed.YaCyChannel.PEERNEWS).addMessage(new RSSMessage(peer.getName() + " sent me a ping", "", ""));
+ yacyChannel.channels(yacyChannel.PEERNEWS).addMessage(new RSSMessage(peer.getName() + " sent me a ping", "", ""));
}
private void processPeerArrival(final yacySeed peer) {
diff --git a/source/net/yacy/cora/document/RSSFeed.java b/source/net/yacy/cora/document/RSSFeed.java
index 7e79ced7a..68756bf86 100644
--- a/source/net/yacy/cora/document/RSSFeed.java
+++ b/source/net/yacy/cora/document/RSSFeed.java
@@ -21,41 +21,12 @@
package net.yacy.cora.document;
import java.util.Collections;
-import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
public class RSSFeed implements Iterable<Hit> {
- public static final int maxMessagesPerChannel = 200; // to avoid a memory leak
-
- public static enum YaCyChannel {
- TEST,
- PEERNEWS,
- REMOTESEARCH,
- LOCALSEARCH,
- REMOTEINDEXING,
- LOCALINDEXING,
- DHTRECEIVE,
- DHTSEND;
- }
-
- // test:
- // http://localhost:8080/xml/feed.rss?set=PEERNEWS,REMOTESEARCH,LOCALSEARCH,REMOTEINDEXING,LOCALINDEXING
-
- /**
- * the following private channels are declared to prevent that an access to the feed servlet
- * gets results from news channels that are not for the public
- */
- public static final HashSet<YaCyChannel> privateChannels = new HashSet<YaCyChannel>();
- static {
- privateChannels.add(YaCyChannel.LOCALSEARCH);
- privateChannels.add(YaCyChannel.LOCALINDEXING);
- }
-
-
// class variables
private RSSMessage channel;
private String imageURL;
@@ -154,23 +125,4 @@ public class RSSFeed implements Iterable<Hit> {
}
}
- /**
- * the following static channels object is used to organize a storage array for RSS feeds
- */
- private static final ConcurrentHashMap<YaCyChannel, RSSFeed> channels = new ConcurrentHashMap<YaCyChannel, RSSFeed>();
- public static RSSFeed channels(final String channelName) {
- for (YaCyChannel channel: YaCyChannel.values()) {
- if (channel.name().equals(channelName)) return channels(channel);
- }
- return null;
- }
- public static RSSFeed channels(final YaCyChannel channel) {
- RSSFeed feed = channels.get(channel);
- if (feed != null) return feed;
- feed = new RSSFeed();
- feed.setChannel(new RSSMessage(channel.name(), "", ""));
- feed.maxsize = maxMessagesPerChannel;
- channels.put(channel, feed);
- return feed;
- }
}
diff --git a/source/net/yacy/document/AbstractParser.java b/source/net/yacy/document/AbstractParser.java
index 2e75b9e38..e168ff07a 100644
--- a/source/net/yacy/document/AbstractParser.java
+++ b/source/net/yacy/document/AbstractParser.java
@@ -1,242 +1,84 @@
-//AbstractParser.java
-//------------------------
-//part of YaCy
-//(C) by Michael Peter Christen; [email protected]
-//first published on http://www.anomic.de
-//Frankfurt, Germany, 2005
-//
-//this file was contributed by Martin Thelian
-//last major change: $LastChangedDate$ by $LastChangedBy$
-//Revision: $LastChangedRevision$
-//
-//This program is free software; you can redistribute it and/or modify
-//it under the terms of the GNU General Public License as published by
-//the Free Software Foundation; either version 2 of the License, or
-//(at your option) any later version.
-//
-//This program is distributed in the hope that it will be useful,
-//but WITHOUT ANY WARRANTY; without even the implied warranty of
-//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-//GNU General Public License for more details.
-//
-//You should have received a copy of the GNU General Public License
-//along with this program; if not, write to the Free Software
-//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+/**
+ * Parser
+ * Copyright 2010 by Michael Peter Christen, [email protected], Frankfurt am Main, Germany
+ * First released 29.6.2010 at http://yacy.net
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program in the file lgpl21.txt
+ * If not, see <http://www.gnu.org/licenses/>.
+ */
+
+// this is a new implementation of the parser interface using multiple documents as result set
+// and a much simpler method structure with only one single parser method to implement
package net.yacy.document;
-import java.io.BufferedInputStream;
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
+import java.util.HashSet;
+import java.util.Set;
-import net.yacy.cora.document.MultiProtocolURI;
import net.yacy.kelondro.logging.Log;
-import net.yacy.kelondro.workflow.WorkflowThread;
-
-/**
- * New classes implementing the {@link net.yacy.document.Idiom} interface
- * can extend this class to inherit all functions already implemented in this class.
- * @author Martin Thelian
- * @version $LastChangedRevision$ / $LastChangedDate$
- */
-public abstract class AbstractParser implements Idiom {
-
- /**
- * the logger class that should be used by the parser module for logging
- * purposes.
- */
- protected final Log theLogger = new Log("PARSER");
-
- /**
- * Parser name
- */
- private final String parserName;
+public abstract class AbstractParser implements Parser {
- /**
- * The source file file size in bytes if the source document was passed
- * in as file
- */
- protected long contentLength = -1;
+ protected final Log log = new Log("PARSER");
+ protected final Set<String> SUPPORTED_MIME_TYPES = new HashSet<String>();
+ protected final Set<String> SUPPORTED_EXTENSIONS = new HashSet<String>();
+ private final String name;
/**
- * The Constructor of this class.
+ * initialize a parser with a name
+ * @param name
*/
- public AbstractParser(String name) {
- this.parserName = name;
+ public AbstractParser(String name) {
+ this.name = name;
}
/**
- * Set the content length of the source file.
- * This value is needed by some parsers to decide
- * if the parsed text could be hold in memory
+ * return the name of the parser
*/
- public void setContentLength(final long length) {
- this.contentLength = length;
+ public String getName() {
+ return this.name;
}
-
+
/**
- * Check if the parser was interrupted.
- * @throws InterruptedException if the parser was interrupted
+ * each parser must define a set of supported mime types
+ * @return a set of mime type strings that are supported
*/
- public static final void checkInterruption() throws InterruptedException {
- final Thread currentThread = Thread.currentThread();
- if ((currentThread instanceof WorkflowThread) && ((WorkflowThread)currentThread).shutdownInProgress()) throw new InterruptedException("Shutdown in progress ...");
- if (currentThread.isInterrupted()) throw new InterruptedException("Shutdown in progress ...");
+ public Set<String> supportedMimeTypes() {
+ return this.SUPPORTED_MIME_TYPES;
}
- public final File createTempFile(final String name) throws IOException {
- String parserClassName = this.getClass().getName();
- int idx = parserClassName.lastIndexOf('.');
- if (idx != -1) {
- parserClassName = parserClassName.substring(idx+1);
- }
-
- // getting the file extension
- idx = name.lastIndexOf('/');
- final String fileName = (idx != -1) ? name.substring(idx+1) : name;
-
- idx = fileName.lastIndexOf('.');
- final String fileExt = (idx > -1) ? fileName.substring(idx+1) : "";
-
- // creates the temp file
- final File tempFile = File.createTempFile(parserClassName + "_" + ((idx>-1)?fileName.substring(0,idx):fileName), (fileExt.length()>0)?"."+fileExt:fileExt);
- return tempFile;
- }
-
- public int parseDir(final MultiProtocolURI location, final String prefix, final File dir, final Document doc)
- throws ParserException, InterruptedException, IOException {
- if (!dir.isDirectory())
- throw new ParserException("tried to parse ordinary file " + dir + " as directory", location);
-
- final String[] files = dir.list();
- int result = 0;
- for (int i=0; i<files.length; i++) {
- checkInterruption();
- final File file = new File(dir, files[i]);
- this.theLogger.logFine("parsing file " + location + "#" + file + " in archive...");
- if (file.isDirectory()) {
- result += parseDir(location, prefix, file, doc);
- } else try {
- final MultiProtocolURI url = MultiProtocolURI.newURL(location, "/" + prefix + "/"
- // XXX: workaround for relative paths within document
- + file.getPath().substring(file.getPath().indexOf(File.separatorChar) + 1)
- + "/" + file.getName());
- final Document subdoc = TextParser.parseSource(url, TextParser.mimeOf(url), null, file);
- // TODO: change anchors back to use '#' after archive name
- doc.addSubDocument(subdoc);
- subdoc.close();
- result++;
- } catch (final ParserException e) {
- this.theLogger.logInfo("unable to parse file " + file + " in " + location + ", skipping");
- }
- }
- return result;
- }
-
- /**
- * Parsing a document available as byte array.
- * @param location the origin of the document
- * @param mimeType the mimetype of the document
- * @param charset the supposed charset of the document or <code>null</code> if unkown
- * @param source the content byte array
- * @return a {@link Document} containing the extracted plain text of the document
- * and some additional metadata.
- * @throws ParserException if the content could not be parsed properly
- *
- * @see net.yacy.document.Idiom#parse(de.anomic.net.URL, java.lang.String, byte[])
- */
- public Document parse(
- final MultiProtocolURI location,
- final String mimeType,
- final String charset,
- final byte[] source
- ) throws ParserException, InterruptedException {
- ByteArrayInputStream contentInputStream = null;
- try {
- // convert the byte array into a stream
- contentInputStream = new ByteArrayInputStream(source);
-
- // parse the stream
- return this.parse(location,mimeType,charset,contentInputStream);
- } finally {
- if (contentInputStream != null) {
- try {
- contentInputStream.close();
- contentInputStream = null;
- } catch (final Exception e){ /* ignore this */}
- }
- }
- }
-
- /**
- * Parsing a document stored in a {@link File}
- * @param location the origin of the document
- * @param mimeType the mimetype of the document
- * @param charset the supposed charset of the document or <code>null</code> if unkown
- * @param sourceFile the file containing the content of the document
- * @return a {@link Document} containing the extracted plain text of the document
- * and some additional metadata.
- * @throws ParserException if the content could not be parsed properly
- *
- * @see net.yacy.document.Idiom#parse(de.anomic.net.URL, java.lang.String, java.io.File)
- */
- public Document parse(
- final MultiProtocolURI location,
- final String mimeType,
- final String charset,
- final File sourceFile
- ) throws ParserException, InterruptedException {
- BufferedInputStream contentInputStream = null;
- try {
- // getting the file size of the document
- this.contentLength = sourceFile.length();
-
- // create a stream from the file
- contentInputStream = new BufferedInputStream(new FileInputStream(sourceFile));
-
- // parse the stream
- return this.parse(location, mimeType, charset, contentInputStream);
- } catch (final FileNotFoundException e) {
- throw new ParserException("Unexpected error while parsing file. " + e.getMessage(),location);
- } finally {
- if (contentInputStream != null) try{contentInputStream.close();}catch(final Exception e){/* ignore this */}
- }
- }
-
/**
- * Parsing a document available as {@link InputStream}
- * @param location the origin of the document
- * @param mimeType the mimetype of the document
- * @param charset the supposed charset of the document or <code>null</code> if unkown
- * @param source the {@link InputStream} containing the document content
- * @return a {@link Document} containing the extracted plain text of the document
- * and some additional metadata.
- * @throws ParserException if the content could not be parsed properly
- *
- * @see net.yacy.document.Idiom#parse(de.anomic.net.URL, java.lang.String, java.io.InputStream)
+ * each parser must define a set of supported file extensions
+ * @return a set of file name extensions that are supported
*/
- public abstract Document parse(MultiProtocolURI location, String mimeType, String charset, InputStream source) throws ParserException, InterruptedException;
+ public Set<String> supportedExtensions() {
+ return this.SUPPORTED_EXTENSIONS;
+ }
/**
- * Return the name of the parser
+ * check equivalence of parsers; this simply tests equality of parser names
+ * @param o
+ * @return
*/
- public String getName() {
- return this.parserName;
- }
-
- public void reset() {
- this.contentLength = -1;
- }
-
public boolean equals(Object o) {
- return this.getName().equals(((Idiom) o).getName());
+ return this.getName().equals(((Parser) o).getName());
}
+ /**
+ * the hash code of a parser
+ * @return the hash code of the parser name string
+ */
public int hashCode() {
return this.getName().hashCode();
}
diff --git a/source/net/yacy/document/Classification.java b/source/net/yacy/document/Classification.java
index ad5500d98..9f0679942 100644
--- a/source/net/yacy/document/Classification.java
+++ b/source/net/yacy/document/Classification.java
@@ -1,26 +1,22 @@
-// Classification.java
-// (C) 2009 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany
-// first published 09.07.2009 on http://yacy.net
-//
-// $LastChangedDate$
-// $LastChangedRevision$
-// $LastChangedBy$
-//
-// LICENSE
-//
-// This program is free software; you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation; either version 2 of the License, or
-// (at your option) any later version.
-//
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU General Public License
-// along with this program; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+/**
+ * Classification.java
+ * Copyright 2009 by Michael Peter Christen, [email protected], Frankfurt am Main, Germany
+ * First released 09.07.2009 at http://yacy.net
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program in the file lgpl21.txt
+ * If not, see <http://www.gnu.org/licenses/>.
+ */
package net.yacy.document;
diff --git a/source/net/yacy/document/Condenser.java b/source/net/yacy/document/Condenser.java
index ed7304b56..486178727 100644
--- a/source/net/yacy/document/Condenser.java
+++ b/source/net/yacy/document/Condenser.java
@@ -1,27 +1,22 @@
-// plasmaCondenser.java
-// -----------------------
-// part of YaCy
-// (C) by Michael Peter Christen; [email protected]
-// first published on http://www.anomic.de
-// Frankfurt, Germany, 2004
-// last change: 09.01.2004
-//
-// This program is free software; you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation; either version 2 of the License, or
-// (at your option) any later version.
-//
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU General Public License
-// along with this program; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-
-// compile with javac -sourcepath source source/de/anomic/plasma/plasmaCondenser.java
-// execute with java -cp source de.anomic.plasma.plasmaCondenser
+/**
+ * Condenser.java
+ * Copyright 2004 by Michael Peter Christen, [email protected], Frankfurt am Main, Germany
+ * First released 09.01.2004 at http://yacy.net
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program in the file lgpl21.txt
+ * If not, see <http://www.gnu.org/licenses/>.
+ */
package net.yacy.document;
diff --git a/source/net/yacy/document/Document.java b/source/net/yacy/document/Document.java
index 7f7f32d03..36b54351e 100644
--- a/source/net/yacy/document/Document.java
+++ b/source/net/yacy/document/Document.java
@@ -49,13 +49,14 @@ import net.yacy.cora.document.MultiProtocolURI;
import net.yacy.document.parser.html.ContentScraper;
import net.yacy.document.parser.html.ImageEntry;
import net.yacy.kelondro.logging.Log;
+import net.yacy.kelondro.util.ByteBuffer;
import net.yacy.kelondro.util.DateFormatter;
import net.yacy.kelondro.util.FileUtils;
public class Document {
- private final MultiProtocolURI source; // the source url
+ private final MultiProtocolURI source; // the source url
private final String mimeType; // mimeType as taken from http header
private final String charset; // the charset of the document
private final List<String> keywords; // most resources provide a keyword field
@@ -487,24 +488,26 @@ dc_rights
return v;
}
- public void addSubDocument(final Document doc) throws IOException {
- this.sections.addAll(Arrays.asList(doc.getSectionTitles()));
-
- if (this.title.length() > 0) this.title.append('\n');
- this.title.append(doc.dc_title());
-
- this.keywords.addAll(doc.getKeywords());
-
- if (this.description.length() > 0) this.description.append('\n');
- this.description.append(doc.dc_description());
-
- if (!(this.text instanceof ByteArrayOutputStream)) {
- this.text = new ByteArrayOutputStream();
+ public void addSubDocuments(final Document[] docs) throws IOException {
+ for (Document doc: docs) {
+ this.sections.addAll(Arrays.asList(doc.getSectionTitles()));
+
+ if (this.title.length() > 0) this.title.append('\n');
+ this.title.append(doc.dc_title());
+
+ this.keywords.addAll(doc.getKeywords());
+
+ if (this.description.length() > 0) this.description.append('\n');
+ this.description.append(doc.dc_description());
+
+ if (!(this.text instanceof ByteArrayOutputStream)) {
+ this.text = new ByteArrayOutputStream();
+ }
+ FileUtils.copy(doc.getText(), (ByteArrayOutputStream) this.text);
+
+ anchors.putAll(doc.getAnchors());
+ ContentScraper.addAllImages(images, doc.getImages());
}
- FileUtils.copy(doc.getText(), (ByteArrayOutputStream) this.text);
-
- anchors.putAll(doc.getAnchors());
- ContentScraper.addAllImages(images, doc.getImages());
}
/**
@@ -597,5 +600,99 @@ dc_rights
}
}
}
+
+ /**
+ * merge documents: a helper method for all parsers that return multiple documents
+ * @param docs
+ * @return
+ */
+ public static Document mergeDocuments(final MultiProtocolURI location, final String globalMime, Document[] docs) {
+ if (docs == null || docs.length == 0) return null;
+ if (docs.length == 1) return docs[0];
+
+ long docTextLength = 0;
+ final ByteBuffer content = new ByteBuffer();
+ final StringBuilder authors = new StringBuilder();
+ final StringBuilder publishers = new StringBuilder();
+ final StringBuilder subjects = new StringBuilder();
+ final StringBuilder title = new StringBuilder();
+ final StringBuilder description = new StringBuilder();
+ final LinkedList<String> sectionTitles = new LinkedList<String>();
+
+ final Map<MultiProtocolURI, String> anchors = new HashMap<MultiProtocolURI, String>();
+ final HashMap<MultiProtocolURI, ImageEntry> images = new HashMap<MultiProtocolURI, ImageEntry>();
+
+ for (Document doc: docs) {
+
+ String author = doc.dc_creator();
+ if (author.length() > 0) {
+ if (authors.length() > 0) authors.append(",");
+ subjects.append(author);
+ }
+
+ String publisher = doc.dc_publisher();
+ if (publisher.length() > 0) {
+ if (publishers.length() > 0) publishers.append(",");
+ publishers.append(publisher);
+ }
+
+ String subject = doc.dc_subject(',');
+ if (subject.length() > 0) {
+ if (subjects.length() > 0) subjects.append(",");
+ subjects.append(subject);
+ }
+
+ if (title.length() > 0) title.append("\n");
+ title.append(doc.dc_title());
+
+ sectionTitles.addAll(Arrays.asList(doc.getSectionTitles()));
+
+ if (description.length() > 0) description.append("\n");
+ description.append(doc.dc_description());
+
+ if (doc.getTextLength() > 0) {
+ if (docTextLength > 0) content.write('\n');
+ try {
+ docTextLength += FileUtils.copy(doc.getText(), content);
+ } catch (IOException e) {
+ Log.logException(e);
+ }
+ }
+ anchors.putAll(doc.getAnchors());
+ ContentScraper.addAllImages(images, doc.getImages());
+ }
+ return new Document(
+ location,
+ globalMime,
+ null,
+ null,
+ subjects.toString().split(" |,"),
+ title.toString(),
+ authors.toString(),
+ publishers.toString(),
+ sectionTitles.toArray(new String[sectionTitles.size()]),
+ description.toString(),
+ content.getBytes(),
+ anchors,
+ images,
+ false);
+ }
+
+ public static Map<MultiProtocolURI, String> getHyperlinks(Document[] documents) {
+ Map<MultiProtocolURI, String> result = new HashMap<MultiProtocolURI, String>();
+ for (Document d: documents) result.putAll(d.getHyperlinks());
+ return result;
+ }
+
+ public static Map<MultiProtocolURI, String> getImagelinks(Document[] documents) {
+ Map<MultiProtocolURI, String> result = new HashMap<MultiProtocolURI, String>();
+ for (Document d: documents) {
+ for (ImageEntry imageReference : d.getImages().values()) {
+ result.put(imageReference.url(), imageReference.alt());
+ }
+ }
+ return result;
+ }
+
}
diff --git a/source/net/yacy/document/Idiom.java b/source/net/yacy/document/Idiom.java
deleted file mode 100644
index c24f02899..000000000
--- a/source/net/yacy/document/Idiom.java
+++ /dev/null
@@ -1,116 +0,0 @@
-//Idiom.java
-//------------------------
-//part of YaCy
-//(C) by Michael Peter Christen; [email protected]
-//first published on http://www.anomic.de
-//Frankfurt, Germany, 2005
-//
-//this file was contributed by Martin Thelian
-//last major change: $LastChangedDate$ by $LastChangedBy$
-//Revision: $LastChangedRevision$
-//
-//This program is free software; you can redistribute it and/or modify
-//it under the terms of the GNU General Public License as published by
-//the Free Software Foundation; either version 2 of the License, or
-//(at your option) any later version.
-//
-//This program is distributed in the hope that it will be useful,
-//but WITHOUT ANY WARRANTY; without even the implied warranty of
-//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-//GNU General Public License for more details.
-//
-//You should have received a copy of the GNU General Public License
-//along with this program; if not, write to the Free Software
-//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-
-package net.yacy.document;
-
-import java.io.File;
-import java.io.InputStream;
-import java.util.Set;
-
-import net.yacy.cora.document.MultiProtocolURI;
-
-
-/**
- * This interface defines a list of methods that needs to be implemented
- * by each content parser class.
- * @author Martin Thelian
- * @version $LastChangedRevision$ / $LastChangedDate$
- */
-public interface Idiom {
-
- /**
- * Parsing a document available as byte array
- * @param location the origin of the document
- * @param mimeType the mimetype of the document
- * @param charset the supposed charset of the document or <code>null</code> if unkown
- * @param source the content byte array
- * @return a {@link Document} containing the extracted plain text of the document
- * and some additional metadata.
- *
- * @throws ParserException if the content could not be parsed properly
- */
- public Document parse(MultiProtocolURI location, String mimeType, String charset, byte[] source)
- throws ParserException, InterruptedException;
-
- /**
- * Parsing a document stored in a {@link File}
- * @param location the origin of the document
- * @param mimeType the mimetype of the document
- * @param charset the supposed charset of the document or <code>null</code> if unkown
- * @param sourceFile the file containing the content of the document
- * @return a {@link Document} containing the extracted plain text of the document
- * and some additional metadata.
- *
- * @throws ParserException if the content could not be parsed properly
- */
- public Document parse(MultiProtocolURI location, String mimeType, String charset, File sourceFile)
- throws ParserException, InterruptedException;
-
- /**
- * Parsing a document available as {@link InputStream}
- * @param location the origin of the document
- * @param mimeType the mimetype of the document
- * @param charset the supposed charset of the document or <code>null</code> if unkown
- * @param source the {@link InputStream} containing the document content
- * @return a {@link Document} containing the extracted plain text of the document
- * and some additional metadata.
- *
- * @throws ParserException if the content could not be parsed properly
- */
- public Document parse(MultiProtocolURI location, String mimeType, String charset, InputStream source)
- throws ParserException, InterruptedException;
-
- /**
- * Get the MimeType(s) that are supported by the parser
- * @return a set of strings denoting the supported mime types
- */
- public Set<String> supportedMimeTypes();
-
- /**
- * Get the File extension(s) that are supported by the parser
- * @return a set of strings denoting the supported file extensions
- */
- public Set<String> supportedExtensions();
-
- /**
- * This function should be called before reusing the parser object.
- */
- public void reset();
-
- public void setContentLength(long length);
-
- /**
- * Returns the name of the parser
- * @return parser name
- */
- public String getName();
-
- public boolean equals(Object o);
-
- public int hashCode();
-
-}
-
-
diff --git a/source/net/yacy/document/ImageParser.java b/source/net/yacy/document/ImageParser.java
index 740631f92..af99250a5 100644
--- a/source/net/yacy/document/ImageParser.java
+++ b/source/net/yacy/document/ImageParser.java
@@ -1,3 +1,23 @@
+/**
+ * ImageParser
+ * Copyright 2010 by Michael Peter Christen, [email protected], Frankfurt am Main, Germany
+ * First released 29.6.2010 at http://yacy.net
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program in the file lgpl21.txt
+ * If not, see <http://www.gnu.org/licenses/>.
+ */
+
package net.yacy.document;
import java.awt.Container;
diff --git a/source/net/yacy/document/Parser.java b/source/net/yacy/document/Parser.java
new file mode 100644
index 000000000..ab6e6aea9
--- /dev/null
+++ b/source/net/yacy/document/Parser.java
@@ -0,0 +1,107 @@
+/**
+ * Parser.java
+ * Copyright 2010 by Michael Peter Christen, [email protected], Frankfurt am Main, Germany
+ * First released 29.6.2010 at http://yacy.net
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program in the file lgpl21.txt
+ * If not, see <http://www.gnu.org/licenses/>.
+ */
+
+// this is a new definition of the parser interface using multiple documents as result set
+// and a much simpler method structure with only one single parser method to implement
+
+package net.yacy.document;
+
+import java.io.InputStream;
+import java.util.Set;
+
+import net.yacy.cora.document.MultiProtocolURI;
+
+public interface Parser {
+
+ /**
+ * each parser must define a set of supported mime types
+ * @return a set of mime type strings that are supported
+ */
+ public Set<String> supportedMimeTypes();
+
+ /**
+ * each parser must define a set of supported file extensions
+ * @return a set of file name extensions that are supported
+ */
+ public Set<String> supportedExtensions();
+
+ /**
+ * parse an input stream
+ * @param url the url of the source
+ * @param mimeType the mime type of the source, if known
+ * @param charset the charset of the source, if known
+ * @param source a input stream
+ * @return a list of documents that result from parsing the source
+ * @throws Parser.Failure
+ * @throws InterruptedException
+ */
+ public Document[] parse(
+ MultiProtocolURI url,
+ String mimeType,
+ String charset,
+ InputStream source
+ ) throws Parser.Failure, InterruptedException;
+
+
+ // methods to that shall make it possible to put Parser objects into a hashtable
+
+ /**
+ * get the name of the parser
+ * @return the name of the parser
+ */
+ public String getName();
+
+ /**
+ * check equivalence of parsers; this simply tests equality of parser names
+ * @param o
+ * @return
+ */
+ public boolean equals(Object o);
+
+ /**
+ * the hash code of a parser
+ * @return the hash code of the parser name string
+ */
+ public int hashCode();
+
+ /**
+ * a parser waring
+ * thrown as an exception
+ */
+ public class Failure extends Exception {
+
+ private static final long serialVersionUID = 2278214953869122883L;
+ private MultiProtocolURI url = null;
+ public Failure() {
+ super();
+ }
+
+ public Failure(final String message, final MultiProtocolURI url) {
+ super(message + "; url = " + url.toNormalform(true, false));
+ this.url = url;
+ }
+
+ public MultiProtocolURI getURL() {
+ return this.url;
+ }
+ }
+}
+
+
diff --git a/source/net/yacy/document/ParserException.java b/source/net/yacy/document/ParserException.java
deleted file mode 100644
index a8f3520aa..000000000
--- a/source/net/yacy/document/ParserException.java
+++ /dev/null
@@ -1,46 +0,0 @@
-//ParserException.java
-//------------------------
-//part of YaCy
-//(C) by Michael Peter Christen; [email protected]
-//first published on http://www.anomic.de
-//Frankfurt, Germany, 2005
-//
-//this file is contributed by Martin Thelian
-//last major change: 24.04.2005
-//
-//This program is free software; you can redistribute it and/or modify
-//it under the terms of the GNU General Public License as published by
-//the Free Software Foundation; either version 2 of the License, or
-//(at your option) any later version.
-//
-//This program is distributed in the hope that it will be useful,
-//but WITHOUT ANY WARRANTY; without even the implied warranty of
-//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-//GNU General Public License for more details.
-//
-//You should have received a copy of the GNU General Public License
-//along with this program; if not, write to the Free Software
-//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-
-package net.yacy.document;
-
-import net.yacy.cora.document.MultiProtocolURI;
-
-public class ParserException extends Exception {
- private MultiProtocolURI url = null;
-
- private static final long serialVersionUID = 1L;
-
- public ParserException() {
- super();
- }
-
- public ParserException(final String message, final MultiProtocolURI url) {
- super(message + "; url = " + url.toNormalform(true, false));
- this.url = url;
- }
-
- public MultiProtocolURI getURL() {
- return this.url;
- }
-}
diff --git a/source/net/yacy/document/Phrase.java b/source/net/yacy/document/Phrase.java
index 87d1d4ae5..b0037ad2f 100644
--- a/source/net/yacy/document/Phrase.java
+++ b/source/net/yacy/document/Phrase.java
@@ -1,28 +1,22 @@
-// indexPhrase.java
-// (C) 2008 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany
-// first published 26.03.2008 on http://yacy.net
-//
-// This is a part of YaCy, a peer-to-peer based web search engine
-//
-// $LastChangedDate$
-// $LastChangedRevision$
-// $LastChangedBy$
-//
-// LICENSE
-//
-// This program is free software; you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation; either version 2 of the License, or
-// (at your option) any later version.
-//
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU General Public License
-// along with this program; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+/**
+ * Phrase.java
+ * Copyright 2008 by Michael Peter Christen, [email protected], Frankfurt am Main, Germany
+ * First released 26.03.2008 at http://yacy.net
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program in the file lgpl21.txt
+ * If not, see <http://www.gnu.org/licenses/>.
+ */
package net.yacy.document;
@@ -31,7 +25,7 @@ import java.util.HashSet;
public class Phrase {
// object carries statistics for words and sentences
- private int count; // number of occurrences
+ private int count; // number of occurrences
private final int handle; // unique handle, is initialized with sentence counter
private final HashSet<Integer> hash; //
diff --git a/source/net/yacy/document/TextParser.java b/source/net/yacy/document/TextParser.java
index a5813782b..5450a4367 100644
--- a/source/net/yacy/document/TextParser.java
+++ b/source/net/yacy/document/TextParser.java
@@ -1,28 +1,22 @@
-// Parser.java
-// (C) 2009 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany
-// first published 09.07.2009 on http://yacy.net
-//
-// This is a part of YaCy, a peer-to-peer based web search engine
-//
-// $LastChangedDate: 2009-03-20 16:44:59 +0100 (Fr, 20 Mrz 2009) $
-// $LastChangedRevision: 5736 $
-// $LastChangedBy: borg-0300 $
-//
-// LICENSE
-//
-// This program is free software; you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation; either version 2 of the License, or
-// (at your option) any later version.
-//
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU General Public License
-// along with this program; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+/**
+ * TextParser.java
+ * Copyright 2009 by Michael Peter Christen, [email protected], Frankfurt am Main, Germany
+ * First released 09.07.2009 at http://yacy.net
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program in the file lgpl21.txt
+ * If not, see <http://www.gnu.org/licenses/>.
+ */
package net.yacy.document;
@@ -65,14 +59,13 @@ import net.yacy.document.parser.images.genericImageParser;
import net.yacy.kelondro.logging.Log;
import net.yacy.kelondro.util.FileUtils;
-
public final class TextParser {
private static final Log log = new Log("PARSER");
private static final Object v = new Object();
- private static final Map<String, Idiom> mime2parser = new ConcurrentHashMap<String, Idiom>();
- private static final Map<String, Idiom> ext2parser = new ConcurrentHashMap<String, Idiom>();
+ private static final Map<String, Parser> mime2parser = new ConcurrentHashMap<String, Parser>();
+ private static final Map<String, Parser> ext2parser = new ConcurrentHashMap<String, Parser>();
private static final Map<String, String> ext2mime = new ConcurrentHashMap<String, String>();
private static final Map<String, Object> denyMime = new ConcurrentHashMap<String, Object>();
private static final Map<String, Object> denyExtensionx = new ConcurrentHashMap<String, Object>();
@@ -101,20 +94,20 @@ public final class TextParser {
initParser(new zipParser());
}
- public static Set<Idiom> idioms() {
- Set<Idiom> c = new HashSet<Idiom>();
+ public static Set<Parser> parsers() {
+ Set<Parser> c = new HashSet<Parser>();
c.addAll(ext2parser.values());
c.addAll(mime2parser.values());
return c;
}
- private static void initParser(Idiom parser) {
+ private static void initParser(Parser parser) {
String prototypeMime = null;
for (String mime: parser.supportedMimeTypes()) {
// process the mime types
final String mimeType = normalizeMimeType(mime);
if (prototypeMime == null) prototypeMime = mimeType;
- Idiom p0 = mime2parser.get(mimeType);
+ Parser p0 = mime2parser.get(mimeType);
if (p0 != null) log.logSevere("parser for mime '" + mimeType + "' was set to '" + p0.getName() + "', overwriting with new parser '" + parser.getName() + "'.");
mime2parser.put(mimeType, parser);
Log.logInfo("PARSER", "Parser for mime type '" + mimeType + "': " + parser.getName());
@@ -130,19 +123,19 @@ public final class TextParser {
for (String ext: parser.supportedExtensions()) {
// process the extensions
ext = ext.toLowerCase();
- Idiom p0 = ext2parser.get(ext);
+ Parser p0 = ext2parser.get(ext);
if (p0 != null) log.logSevere("parser for extension '" + ext + "' was set to '" + p0.getName() + "', overwriting with new parser '" + parser.getName() + "'.");
ext2parser.put(ext, parser);
Log.logInfo("PARSER", "Parser for extension '" + ext + "': " + parser.getName());
}
}
- public static Document parseSource(
+ public static Document[] parseSource(
final MultiProtocolURI location,
final String mimeType,
final String charset,
final File sourceFile
- ) throws InterruptedException, ParserException {
+ ) throws InterruptedException, Parser.Failure {
BufferedInputStream sourceStream = null;
try {
@@ -150,15 +143,15 @@ public final class TextParser {
if (!sourceFile.exists() || !sourceFile.canRead() || sourceFile.length() == 0) {
final String errorMsg = sourceFile.exists() ? "Empty resource file." : "No resource content available (2).";
log.logInfo("Unable to parse '" + location + "'. " + errorMsg);
- throw new ParserException(errorMsg, location);
+ throw new Parser.Failure(errorMsg, location);
}
sourceStream = new BufferedInputStream(new FileInputStream(sourceFile));
return parseSource(location, mimeType, charset, sourceFile.length(), sourceStream);
} catch (final Exception e) {
if (e instanceof InterruptedException) throw (InterruptedException) e;
- if (e instanceof ParserException) throw (ParserException) e;
+ if (e instanceof Parser.Failure) throw (Parser.Failure) e;
log.logSevere("Unexpected exception in parseSource from File: " + e.getMessage(), e);
- throw new ParserException("Unexpected exception: " + e.getMessage(), location);
+ throw new Parser.Failure("Unexpected exception: " + e.getMessage(), location);
} finally {
if (sourceStream != null)try {
sourceStream.close();
@@ -166,31 +159,31 @@ public final class TextParser {
}
}
- public static Document parseSource(
+ public static Document[] parseSource(
final MultiProtocolURI location,
String mimeType,
final String charset,
final byte[] content
- ) throws InterruptedException, ParserException {
+ ) throws Parser.Failure {
return parseSource(location, mimeType, charset, content.length, new ByteArrayInputStream(content));
}
- public static Document parseSource(
+ public static Document[] parseSource(
final MultiProtocolURI location,
String mimeType,
final String charset,
final long contentLength,
final InputStream sourceStream
- ) throws InterruptedException, ParserException {
+ ) throws Parser.Failure {
if (log.isFine()) log.logFine("Parsing '" + location + "' from stream");
mimeType = normalizeMimeType(mimeType);
- List<Idiom> idioms = null;
+ List<Parser> idioms = null;
try {
- idioms = idiomParser(location, mimeType);
- } catch (ParserException e) {
+ idioms = parsers(location, mimeType);
+ } catch (Parser.Failure e) {
final String errorMsg = "Parser Failure for extension '" + location.getFileExtension() + "' or mimetype '" + mimeType + "': " + e.getMessage();
log.logWarning(errorMsg);
- throw new ParserException(errorMsg, location);
+ throw new Parser.Failure(errorMsg, location);
}
assert !idioms.isEmpty();
@@ -206,53 +199,54 @@ public final class TextParser {
try {
return parseSource(location, mimeType, idioms, charset, FileUtils.read(sourceStream, (int) contentLength));
} catch (IOException e) {
- throw new ParserException(e.getMessage(), location);
+ throw new Parser.Failure(e.getMessage(), location);
}
}
- private static Document parseSource(
+ private static Document[] parseSource(
final MultiProtocolURI location,
String mimeType,
- Idiom idiom,
+ Parser parser,
final String charset,
final long contentLength,
final InputStream sourceStream
- ) throws InterruptedException, ParserException {
+ ) throws Parser.Failure {
if (log.isFine()) log.logFine("Parsing '" + location + "' from stream");
final String fileExt = location.getFileExtension();
final String documentCharset = htmlParser.patchCharsetEncoding(charset);
- assert idiom != null;
+ assert parser != null;
if (log.isFine()) log.logInfo("Parsing " + location + " with mimeType '" + mimeType + "' and file extension '" + fileExt + "'.");
- idiom.setContentLength(contentLength);
try {
- return idiom.parse(location, mimeType, documentCharset, sourceStream);
- } catch (ParserException e) {
- throw new ParserException("parser failed: " + idiom.getName(), location);
+ return parser.parse(location, mimeType, documentCharset, sourceStream);
+ } catch (Exception e) {
+ throw new Parser.Failure("parser failed: " + parser.getName(), location);
}
}
- private static Document parseSource(
+ private static Document[] parseSource(
final MultiProtocolURI location,
- String mimeType,
- List<Idiom> idioms,
+ final String mimeType,
+ final List<Parser> parsers,
final String charset,
final byte[] sourceArray
- ) throws InterruptedException, ParserException {
+ ) throws Parser.Failure {
final String fileExt = location.getFileExtension();
if (log.isFine()) log.logInfo("Parsing " + location + " with mimeType '" + mimeType + "' and file extension '" + fileExt + "' from byte[]");
final String documentCharset = htmlParser.patchCharsetEncoding(charset);
- assert !idioms.isEmpty();
+ assert !parsers.isEmpty();
- Document doc = null;
- HashMap<Idiom, ParserException> failedParser = new HashMap<Idiom, ParserException>();
- for (Idiom parser: idioms) {
- parser.setContentLength(sourceArray.length);
+ Document[] doc = null;
+ HashMap<Parser, Parser.Failure> failedParser = new HashMap<Parser, Parser.Failure>();
+ for (Parser parser: parsers) {
try {
doc = parser.parse(location, mimeType, documentCharset, new ByteArrayInputStream(sourceArray));
- } catch (ParserException e) {
+ } catch (Parser.Failure e) {
failedParser.put(parser, e);
//log.logWarning("tried parser '" + parser.getName() + "' to parse " + location.toNormalform(true, false) + " but failed: " + e.getMessage(), e);
+ } catch (Exception e) {
+ failedParser.put(parser, new Parser.Failure(e.getMessage(), location));
+ //log.logWarning("tried parser '" + parser.getName() + "' to parse " + location.toNormalform(true, false) + " but failed: " + e.getMessage(), e);
}
if (doc != null) break;
}
@@ -261,14 +255,14 @@ public final class TextParser {
if (failedParser.size() == 0) {
final String errorMsg = "Parsing content with file extension '" + location.getFileExtension() + "' and mimetype '" + mimeType + "' failed.";
//log.logWarning("Unable to parse '" + location + "'. " + errorMsg);
- throw new ParserException(errorMsg, location);
+ throw new Parser.Failure(errorMsg, location);
} else {
String failedParsers = "";
- for (Map.Entry<Idiom, ParserException> error: failedParser.entrySet()) {
+ for (Map.Entry<Parser, Parser.Failure> error: failedParser.entrySet()) {
log.logWarning("tried parser '" + error.getKey().getName() + "' to parse " + location.toNormalform(true, false) + " but failed: " + error.getValue().getMessage(), error.getValue());
failedParsers += error.getKey().getName() + " ";
}
- throw new ParserException("All parser failed: " + failedParsers, location);
+ throw new Parser.Failure("All parser failed: " + failedParsers, location);
}
}
return doc;
@@ -283,9 +277,9 @@ public final class TextParser {
public static String supports(final MultiProtocolURI url, String mimeType) {
try {
// try to get a parser. If this works, we don't need the parser itself, we just return null to show that everything is ok.
- List<Idiom> idioms = idiomParser(url, mimeType);
+ List<Parser> idioms = parsers(url, mimeType);
return (idioms == null || idioms.isEmpty()) ? "no parser found" : null;
- } catch (ParserException e) {
+ } catch (Parser.Failure e) {
// in case that a parser is not available, return a error string describing the problem.
return e.getMessage();
}
@@ -302,17 +296,17 @@ public final class TextParser {
* @param url the given url
* @param mimeType the given mime type
* @return a list of Idiom parsers that may be appropriate for the given criteria
- * @throws ParserException
+ * @throws Parser.Failure
*/
- private static List<Idiom> idiomParser(final MultiProtocolURI url, String mimeType1) throws ParserException {
- List<Idiom> idioms = new ArrayList<Idiom>(2);
+ private static List<Parser> parsers(final MultiProtocolURI url, String mimeType1) throws Parser.Failure {
+ List<Parser> idioms = new ArrayList<Parser>(2);
// check extension
String ext = url.getFileExtension();
- Idiom idiom;
+ Parser idiom;
if (ext != null && ext.length() > 0) {
ext = ext.toLowerCase();
- if (denyExtensionx.containsKey(ext)) throw new ParserException("file extension '" + ext + "' is denied (1)", url);
+ if (denyExtensionx.containsKey(ext)) throw new Parser.Failure("file extension '" + ext + "' is denied (1)", url);
idiom = ext2parser.get(ext);
if (idiom != null) idioms.add(idiom);
}
@@ -320,7 +314,7 @@ public final class TextParser {
// check given mime type
if (mimeType1 != null) {
mimeType1 = normalizeMimeType(mimeType1);
- if (denyMime.containsKey(mimeType1)) throw new ParserException("mime type '" + mimeType1 + "' is denied (1)", url);
+ if (denyMime.containsKey(mimeType1)) throw new Parser.Failure("mime type '" + mimeType1 + "' is denied (1)", url);
idiom = mime2parser.get(mimeType1);
if (idiom != null && !idioms.contains(idiom)) idioms.add(idiom);
}
@@ -332,7 +326,7 @@ public final class TextParser {
if (idiom != null && !idioms.contains(idiom)) idioms.add(idiom);
// finall check if we found any parser
- if (idioms.isEmpty()) throw new ParserException("no parser found for extension '" + ext + "' and mime type '" + mimeType1 + "'", url);
+ if (idioms.isEmpty()) throw new Parser.Failure("no parser found for extension '" + ext + "' and mime type '" + mimeType1 + "'", url);
return idioms;
}
@@ -351,7 +345,7 @@ public final class TextParser {
if (denyExtensionx.containsKey(ext)) return "file extension '" + ext + "' is denied (2)";
String mimeType = ext2mime.get(ext);
if (mimeType == null) return "no parser available";
- Idiom idiom = mime2parser.get(mimeType);
+ Parser idiom = mime2parser.get(mimeType);
assert idiom != null;
if (idiom == null) return "no parser available (internal error!)";
return null;
@@ -409,4 +403,5 @@ public final class TextParser {
public static void grantExtension(String ext, boolean grant) {
if (grant) denyExtensionx.remove(ext); else denyExtensionx.put(ext, v);
}
+
}
diff --git a/source/net/yacy/document/importer/MediawikiImporter.java b/source/net/yacy/document/importer/MediawikiImporter.java
index 0a6637eac..4f1de99dc 100644
--- a/source/net/yacy/document/importer/MediawikiImporter.java
+++ b/source/net/yacy/document/importer/MediawikiImporter.java
@@ -23,8 +23,8 @@
package net.yacy.document.importer;
import net.yacy.document.Document;
+import net.yacy.document.Parser;
import net.yacy.document.TextParser;
-import net.yacy.document.ParserException;
import net.yacy.kelondro.data.meta.DigestURI;
import net.yacy.kelondro.logging.Log;
import net.yacy.kelondro.util.ByteBuffer;
@@ -488,10 +488,10 @@ public class MediawikiImporter extends Thread implements Importer {
throw new IOException(e.getMessage());
}
}
- public void genDocument() throws InterruptedException, ParserException {
+ public void genDocument() throws Parser.Failure {
try {
url = new DigestURI(urlStub + title, null);
- document = TextParser.parseSource(url, "text/html", "utf-8", html.getBytes("UTF-8"));
+ document = Document.mergeDocuments(url, "text/html", TextParser.parseSource(url, "text/html", "utf-8", html.getBytes("UTF-8")));
// the wiki parser is not able to find the proper title in the source text, so it must be set here
document.setTitle(title);
} catch (UnsupportedEncodingException e) {
@@ -628,7 +628,7 @@ public class MediawikiImporter extends Thread implements Importer {
out.put(record);
} catch (RuntimeException e) {
Log.logException(e);
- } catch (ParserException e) {
+ } catch (Parser.Failure e) {
Log.logException(e);
} catch (IOException e) {
// TODO Auto-generated catch block
diff --git a/source/net/yacy/document/parser/bzipParser.java b/source/net/yacy/document/parser/bzipParser.java
index fc3ba0160..2ef4454e0 100644
--- a/source/net/yacy/document/parser/bzipParser.java
+++ b/source/net/yacy/document/parser/bzipParser.java
@@ -30,29 +30,21 @@ package net.yacy.document.parser;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
-import java.util.HashSet;
-import java.util.Set;
import net.yacy.cora.document.MultiProtocolURI;
import net.yacy.document.AbstractParser;
import net.yacy.document.Document;
-import net.yacy.document.Idiom;
+import net.yacy.document.Parser;
import net.yacy.document.TextParser;
-import net.yacy.document.ParserException;
import net.yacy.kelondro.util.FileUtils;
import org.apache.tools.bzip2.CBZip2InputStream;
-public class bzipParser extends AbstractParser implements Idiom {
-
- /**
- * a list of mime types that are supported by this parser class
- * @see #getSupportedMimeTypes()
- */
- public static final Set<String> SUPPORTED_MIME_TYPES = new HashSet<String>();
- public static final Set<String> SUPPORTED_EXTENSIONS = new HashSet<String>();
- static {
+public class bzipParser extends AbstractParser implements Parser {
+
+ public bzipParser() {
+ super("Bzip 2 UNIX Compressed File Parser");
SUPPORTED_EXTENSIONS.add("bz2");
SUPPORTED_EXTENSIONS.add("tbz");
SUPPORTED_EXTENSIONS.add("tbz2");
@@ -61,21 +53,9 @@ public class bzipParser extends AbstractParser implements Idiom {
SUPPORTED_MIME_TYPES.add("application/x-bz2");
SUPPORTED_MIME_TYPES.add("application/x-bzip");
SUPPORTED_MIME_TYPES.add("application/x-stuffit");
- }
-
- public bzipParser() {
- super("Bzip 2 UNIX Compressed File Parser");
}
- public Set<String> supportedMimeTypes() {
- return SUPPORTED_MIME_TYPES;
- }
-
- public Set<String> supportedExtensions() {
- return SUPPORTED_EXTENSIONS;
- }
-
- public Document parse(final MultiProtocolURI location, final String mimeType, final String charset, final InputStream source) throws ParserException, InterruptedException {
+ public Document[] parse(final MultiProtocolURI location, final String mimeType, final String charset, final InputStream source) throws Parser.Failure, InterruptedException {
File tempFile = null;
try {
@@ -108,25 +88,16 @@ public class bzipParser extends AbstractParser implements Idiom {
}
zippedContent.close();
out.close();
-
- // check for interruption
- checkInterruption();
// creating a new parser class to parse the unzipped content
- return TextParser.parseSource(location,null,null,tempFile);
+ return TextParser.parseSource(location, null, null, tempFile);
} catch (final Exception e) {
if (e instanceof InterruptedException) throw (InterruptedException) e;
- if (e instanceof ParserException) throw (ParserException) e;
+ if (e instanceof Parser.Failure) throw (Parser.Failure) e;
- throw new ParserException("Unexpected error while parsing bzip file. " + e.getMessage(),location);
+ throw new Parser.Failure("Unexpected error while parsing bzip file. " + e.getMessage(),location);
} finally {
if (tempFile != null) FileUtils.deletedelete(tempFile);
}
}
-
- @Override
- public void reset() {
- // Nothing todo here at the moment
- super.reset();
- }
}
diff --git a/source/net/yacy/document/parser/csvParser.java b/source/net/yacy/document/parser/csvParser.java
index 6f7fc1591..cea903d45 100644
--- a/source/net/yacy/document/parser/csvParser.java
+++ b/source/net/yacy/document/parser/csvParser.java
@@ -1,29 +1,22 @@
-// CSVParser
-// (C) 2009 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany
-// first published 02.10.2009 on http://yacy.net
-//
-// This is a part of YaCy, a peer-to-peer based web search engine
-//
-// $LastChangedDate: 2009-09-23 23:26:14 +0200 (Mi, 23 Sep 2009) $
-// $LastChangedRevision: 6340 $
-// $LastChangedBy: low012 $
-//
-// LICENSE
-//
-// This program is free software; you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation; either version 2 of the License, or
-// (at your option) any later version.
-//
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU General Public License
-// along with this program; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-
+/**
+ * tarParser
+ * Copyright 2009 by Michael Peter Christen, [email protected], Frankfurt am Main, Germany
+ * First released 02.10.2009 at http://yacy.net
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program in the file lgpl21.txt
+ * If not, see <http://www.gnu.org/licenses/>.
+ */
package net.yacy.document.parser;
@@ -33,56 +26,35 @@ import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
-import java.util.HashSet;
import java.util.List;
-import java.util.Set;
import net.yacy.cora.document.MultiProtocolURI;
import net.yacy.document.AbstractParser;
import net.yacy.document.Document;
-import net.yacy.document.Idiom;
-import net.yacy.document.ParserException;
+import net.yacy.document.Parser;
/**
* a parser for comma-separated values
* The values may also be separated by semicolon or tab,
* the separator character is detected automatically
*/
-public class csvParser extends AbstractParser implements Idiom {
+public class csvParser extends AbstractParser implements Parser {
- /**
- * a list of mime types that are supported by this parser class
- * @see #getSupportedMimeTypes()
- */
- public static final Set<String> SUPPORTED_MIME_TYPES = new HashSet<String>();
- public static final Set<String> SUPPORTED_EXTENSIONS = new HashSet<String>();
- static {
- SUPPORTED_EXTENSIONS.add("csv");
- }
-
public csvParser() {
super("Comma Separated Value Parser");
+ SUPPORTED_EXTENSIONS.add("csv");
}
- public Set<String> supportedMimeTypes() {
- return SUPPORTED_MIME_TYPES;
- }
-
- public Set<String> supportedExtensions() {
- return SUPPORTED_EXTENSIONS;
- }
-
- @Override
- public Document parse(MultiProtocolURI location, String mimeType, String charset, InputStream source) throws ParserException, InterruptedException {
+ public Document[] parse(MultiProtocolURI location, String mimeType, String charset, InputStream source) throws Parser.Failure, InterruptedException {
// construct a document using all cells of the document
// the first row is used as headline
// all lines are artificially terminated by a '.' to separate them as sentence for the condenser.
List<String[]> table = getTable(location, mimeType, charset, source);
- if (table.isEmpty()) throw new ParserException("document has no lines", location);
+ if (table.isEmpty()) throw new Parser.Failure("document has no lines", location);
StringBuilder sb = new StringBuilder();
for (String[] row: table) sb.append(concatRow(row)).append(' ');
try {
- return new Document(
+ return new Document[]{new Document(
location,
mimeType,
charset,
@@ -96,9 +68,9 @@ public class csvParser extends AbstractParser implements Idiom {
sb.toString().getBytes(charset),
null,
null,
- false);
+ false)};
} catch (UnsupportedEncodingException e) {
- throw new ParserException("error in csvParser, getBytes: " + e.getMessage(), location);
+ throw new Parser.Failure("error in csvParser, getBytes: " + e.getMessage(), location);
}
}
diff --git a/source/net/yacy/document/parser/docParser.java b/source/net/yacy/document/parser/docParser.java
index 4114146c0..7d33da415 100644
--- a/source/net/yacy/document/parser/docParser.java
+++ b/source/net/yacy/document/parser/docParser.java
@@ -29,26 +29,17 @@ package net.yacy.document.parser;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
-import java.util.HashSet;
-import java.util.Set;
import net.yacy.cora.document.MultiProtocolURI;
import net.yacy.document.AbstractParser;
import net.yacy.document.Document;
-import net.yacy.document.Idiom;
-import net.yacy.document.ParserException;
-
+import net.yacy.document.Parser;
import org.apache.poi.hwpf.extractor.WordExtractor;
-public class docParser extends AbstractParser implements Idiom {
+public class docParser extends AbstractParser implements Parser {
- /**
- * a list of mime types that are supported by this parser class
- * @see #getSupportedMimeTypes()
- */
- public static final Set<String> SUPPORTED_MIME_TYPES = new HashSet<String>();
- public static final Set<String> SUPPORTED_EXTENSIONS = new HashSet<String>();
- static {
+ public docParser() {
+ super("Word Document Parser");
SUPPORTED_EXTENSIONS.add("doc");
SUPPORTED_MIME_TYPES.add("application/msword");
SUPPORTED_MIME_TYPES.add("application/doc");
@@ -59,20 +50,16 @@ public class docParser extends AbstractParser implements Idiom {
SUPPORTED_MIME_TYPES.add("application/word");
SUPPORTED_MIME_TYPES.add("application/x-msw6");
SUPPORTED_MIME_TYPES.add("application/x-msword");
- }
-
- public docParser() {
- super("Word Document Parser");
}
- public Document parse(final MultiProtocolURI location, final String mimeType, final String charset, final InputStream source) throws ParserException, InterruptedException {
+ public Document[] parse(final MultiProtocolURI location, final String mimeType, final String charset, final InputStream source) throws Parser.Failure, InterruptedException {
final WordExtractor extractor;
try {
extractor = new WordExtractor(source);
} catch (Exception e) {
- throw new ParserException("error in docParser, WordTextExtractorFactory: " + e.getMessage(), location);
+ throw new Parser.Failure("error in docParser, WordTextExtractorFactory: " + e.getMessage(), location);
}
StringBuilder contents = new StringBuilder();
@@ -83,7 +70,7 @@ public class docParser extends AbstractParser implements Idiom {
contents.append(" ");
contents.append(extractor.getFooterText());
} catch (Exception e) {
- throw new ParserException("error in docParser, getText: " + e.getMessage(), location);
+ throw new Parser.Failure("error in docParser, getText: " + e.getMessage(), location);
}
String title = (contents.length() > 240) ? contents.substring(0,240) : contents.toString().trim();
title.replaceAll("\r"," ").replaceAll("\n"," ").replaceAll("\t"," ").trim();
@@ -95,9 +82,9 @@ public class docParser extends AbstractParser implements Idiom {
l = title.length();
}
- Document theDoc;
+ Document[] docs;
try {
- theDoc = new Document(
+ docs = new Document[]{new Document(
location,
mimeType,
"UTF-8",
@@ -111,26 +98,12 @@ public class docParser extends AbstractParser implements Idiom {
contents.toString().getBytes("UTF-8"),
null,
null,
- false);
+ false)};
} catch (UnsupportedEncodingException e) {
- throw new ParserException("error in docParser, getBytes: " + e.getMessage(), location);
+ throw new Parser.Failure("error in docParser, getBytes: " + e.getMessage(), location);
}
- return theDoc;
- }
-
- public Set<String> supportedMimeTypes() {
- return SUPPORTED_MIME_TYPES;
- }
-
- public Set<String> supportedExtensions() {
- return SUPPORTED_EXTENSIONS;
- }
-
- @Override
- public void reset() {
- // Nothing todo here at the moment
- super.reset();
+ return docs;
}
}
diff --git a/source/net/yacy/document/parser/gzipParser.java b/source/net/yacy/document/parser/gzipParser.java
index f15930019..4367437c9 100644
--- a/source/net/yacy/document/parser/gzipParser.java
+++ b/source/net/yacy/document/parser/gzipParser.java
@@ -30,28 +30,20 @@ package net.yacy.document.parser;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
-import java.util.HashSet;
-import java.util.Set;
import java.util.zip.GZIPInputStream;
import net.yacy.cora.document.MultiProtocolURI;
import net.yacy.document.AbstractParser;
import net.yacy.document.Document;
-import net.yacy.document.Idiom;
+import net.yacy.document.Parser;
import net.yacy.document.TextParser;
-import net.yacy.document.ParserException;
import net.yacy.kelondro.util.FileUtils;
-public class gzipParser extends AbstractParser implements Idiom {
+public class gzipParser extends AbstractParser implements Parser {
- /**
- * a list of mime types that are supported by this parser class
- * @see #getSupportedMimeTypes()
- */
- public static final Set<String> SUPPORTED_MIME_TYPES = new HashSet<String>();
- public static final Set<String> SUPPORTED_EXTENSIONS = new HashSet<String>();
- static {
+ public gzipParser() {
+ super("GNU Zip Compressed Archive Parser");
SUPPORTED_EXTENSIONS.add("gz");
SUPPORTED_EXTENSIONS.add("tgz");
SUPPORTED_MIME_TYPES.add("application/x-gzip");
@@ -60,21 +52,9 @@ public class gzipParser extends AbstractParser implements Idiom {
SUPPORTED_MIME_TYPES.add("application/gzipped");
SUPPORTED_MIME_TYPES.add("application/gzip-compressed");
SUPPORTED_MIME_TYPES.add("gzip/document");
- }
-
- public gzipParser() {
- super("GNU Zip Compressed Archive Parser");
}
- public Set<String> supportedMimeTypes() {
- return SUPPORTED_MIME_TYPES;
- }
-
- public Set<String> supportedExtensions() {
- return SUPPORTED_EXTENSIONS;
- }
-
- public Document parse(final MultiProtocolURI location, final String mimeType, final String charset, final InputStream source) throws ParserException, InterruptedException {
+ public Document[] parse(final MultiProtocolURI location, final String mimeType, final String charset, final InputStream source) throws Parser.Failure, InterruptedException {
File tempFile = null;
try {
@@ -90,30 +70,22 @@ public class gzipParser extends AbstractParser implements Idiom {
final FileOutputStream out = new FileOutputStream(tempFile);
// reading gzip file and store it uncompressed
- while((read = zippedContent.read(data, 0, 1024)) != -1) {
+ while ((read = zippedContent.read(data, 0, 1024)) != -1) {
out.write(data, 0, read);
}
zippedContent.close();
out.close();
-
- // check for interruption
- checkInterruption();
// creating a new parser class to parse the unzipped content
return TextParser.parseSource(location,null,null,tempFile);
} catch (final Exception e) {
if (e instanceof InterruptedException) throw (InterruptedException) e;
- if (e instanceof ParserException) throw (ParserException) e;
+ if (e instanceof Parser.Failure) throw (Parser.Failure) e;
- throw new ParserException("Unexpected error while parsing gzip file. " + e.getMessage(),location);
+ throw new Parser.Failure("Unexpected error while parsing gzip file. " + e.getMessage(),location);
} finally {
if (tempFile != null) FileUtils.deletedelete(tempFile);
}
}
-
- @Override
- public void reset() {
- // Nothing todo here at the moment
- super.reset();
- }
+
}
diff --git a/source/net/yacy/document/parser/htmlParser.java b/source/net/yacy/document/parser/htmlParser.java
index 1883aab80..109c346bf 100644
--- a/source/net/yacy/document/parser/htmlParser.java
+++ b/source/net/yacy/document/parser/htmlParser.java
@@ -1,28 +1,22 @@
-// htmlParser.java
-// (C) 2009 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany
-// first published 09.07.2009 on http://yacy.net
-//
-// This is a part of YaCy, a peer-to-peer based web search engine
-//
-// $LastChangedDate$
-// $LastChangedRevision$
-// $LastChangedBy$
-//
-// LICENSE
-//
-// This program is free software; you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation; either version 2 of the License, or
-// (at your option) any later version.
-//
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU General Public License
-// along with this program; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+/**
+ * htmlParser.java
+ * Copyright 2009 by Michael Peter Christen, [email protected], Frankfurt am Main, Germany
+ * First released 09.07.2009 at http://yacy.net
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program in the file lgpl21.txt
+ * If not, see <http://www.gnu.org/licenses/>.
+ */
package net.yacy.document.parser;
@@ -33,15 +27,12 @@ import java.net.MalformedURLException;
import java.nio.charset.Charset;
import java.nio.charset.IllegalCharsetNameException;
import java.nio.charset.UnsupportedCharsetException;
-import java.util.HashSet;
-import java.util.Set;
import net.yacy.cora.document.MultiProtocolURI;
import net.yacy.cora.protocol.HttpConnector;
import net.yacy.document.AbstractParser;
import net.yacy.document.Document;
-import net.yacy.document.Idiom;
-import net.yacy.document.ParserException;
+import net.yacy.document.Parser;
import net.yacy.document.parser.html.CharacterCoding;
import net.yacy.document.parser.html.ContentScraper;
import net.yacy.document.parser.html.ScraperInputStream;
@@ -49,15 +40,10 @@ import net.yacy.document.parser.html.TransformerWriter;
import net.yacy.kelondro.util.FileUtils;
-public class htmlParser extends AbstractParser implements Idiom {
+public class htmlParser extends AbstractParser implements Parser {
- /**
- * a list of mime types that are supported by this parser class
- * @see #getSupportedMimeTypes()
- */
- public static final Set<String> SUPPORTED_MIME_TYPES = new HashSet<String>();
- public static final Set<String> SUPPORTED_EXTENSIONS = new HashSet<String>();
- static {
+ public htmlParser() {
+ super("HTML Parser");
SUPPORTED_EXTENSIONS.add("htm");
SUPPORTED_EXTENSIONS.add("html");
SUPPORTED_EXTENSIONS.add("shtml");
@@ -72,6 +58,7 @@ public class htmlParser extends AbstractParser implements Idiom {
SUPPORTED_EXTENSIONS.add("tex");
SUPPORTED_EXTENSIONS.add("txt");
SUPPORTED_EXTENSIONS.add("jsp");
+ SUPPORTED_EXTENSIONS.add("mf");
SUPPORTED_EXTENSIONS.add("pl");
SUPPORTED_EXTENSIONS.add("py");
SUPPORTED_MIME_TYPES.add("text/html");
@@ -84,16 +71,11 @@ public class htmlParser extends AbstractParser implements Idiom {
SUPPORTED_MIME_TYPES.add("text/csv");
}
- public htmlParser() {
- super("HTML Parser");
- }
-
- @Override
- public Document parse(
+ public Document[] parse(
final MultiProtocolURI location,
final String mimeType,
final String documentCharset,
- final InputStream sourceStream) throws ParserException, InterruptedException {
+ final InputStream sourceStream) throws Parser.Failure, InterruptedException {
// make a scraper and transformer
final ScraperInputStream htmlFilter = new ScraperInputStream(sourceStream,documentCharset,location,null,false);
@@ -101,7 +83,7 @@ public class htmlParser extends AbstractParser implements Idiom {
try {
charset = htmlFilter.detectCharset();
} catch (IOException e1) {
- throw new ParserException("Charset error:" + e1.getMessage(), location);
+ throw new Parser.Failure("Charset error:" + e1.getMessage(), location);
}
if (charset == null) {
charset = documentCharset;
@@ -110,7 +92,7 @@ public class htmlParser extends AbstractParser implements Idiom {
}
if (documentCharset == null || !documentCharset.equalsIgnoreCase(charset)) {
- theLogger.logInfo("Charset transformation needed from '" + documentCharset + "' to '" + charset + "' for URL = " + location.toNormalform(true, true));
+ log.logInfo("Charset transformation needed from '" + documentCharset + "' to '" + charset + "' for URL = " + location.toNormalform(true, true));
}
Charset c;
@@ -129,24 +111,24 @@ public class htmlParser extends AbstractParser implements Idiom {
FileUtils.copy(htmlFilter, writer, c);
writer.close();
} catch (IOException e) {
- throw new ParserException("IO error:" + e.getMessage(), location);
+ throw new Parser.Failure("IO error:" + e.getMessage(), location);
}
//OutputStream hfos = new htmlFilterOutputStream(null, scraper, null, false);
//serverFileUtils.copy(sourceFile, hfos);
//hfos.close();
if (writer.binarySuspect()) {
final String errorMsg = "Binary data found in resource";
- theLogger.logSevere("Unable to parse '" + location + "'. " + errorMsg);
- throw new ParserException(errorMsg,location);
+ log.logSevere("Unable to parse '" + location + "'. " + errorMsg);
+ throw new Parser.Failure(errorMsg,location);
}
return transformScraper(location, mimeType, documentCharset, scraper);
}
- private static Document transformScraper(final MultiProtocolURI location, final String mimeType, final String charSet, final ContentScraper scraper) {
+ private static Document[] transformScraper(final MultiProtocolURI location, final String mimeType, final String charSet, final ContentScraper scraper) {
final String[] sections = new String[scraper.getHeadlines(1).length + scraper.getHeadlines(2).length + scraper.getHeadlines(3).length + scraper.getHeadlines(4).length];
int p = 0;
for (int i = 1; i <= 4; i++) for (int j = 0; j < scraper.getHeadlines(i).length; j++) sections[p++] = scraper.getHeadlines(i)[j];
- final Document ppd = new Document(
+ final Document[] ppds = new Document[]{new Document(
location,
mimeType,
charSet,
@@ -160,10 +142,10 @@ public class htmlParser extends AbstractParser implements Idiom {
scraper.getText(),
scraper.getAnchors(),
scraper.getImages(),
- scraper.indexingDenied());
+ scraper.indexingDenied())};
//scraper.close();
- ppd.setFavicon(scraper.getFavicon());
- return ppd;
+ for (Document ppd: ppds) ppd.setFavicon(scraper.getFavicon());
+ return ppds;
}
@@ -241,14 +223,6 @@ public class htmlParser extends AbstractParser implements Idiom {
return encoding;
}
-
- public Set<String> supportedMimeTypes() {
- return SUPPORTED_MIME_TYPES;
- }
-
- public Set<String> supportedExtensions() {
- return SUPPORTED_EXTENSIONS;
- }
public boolean indexingDenied() {
return false;
@@ -260,15 +234,15 @@ public class htmlParser extends AbstractParser implements Idiom {
try {
url = new MultiProtocolURI(args[0]);
byte[] content = HttpConnector.wget(url, 3000);
- Document document = new htmlParser().parse(url, "text/html", null, new ByteArrayInputStream(content));
- String title = document.dc_title();
+ Document[] document = new htmlParser().parse(url, "text/html", null, new ByteArrayInputStream(content));
+ String title = document[0].dc_title();
System.out.println(title);
System.out.println(CharacterCoding.unicode2html(title, false));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
- } catch (ParserException e) {
+ } catch (Parser.Failure e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
diff --git a/source/net/yacy/document/parser/images/genericImageParser.java b/source/net/yacy/document/parser/images/genericImageParser.java
index 07c8c4f0e..19da933a0 100644
--- a/source/net/yacy/document/parser/images/genericImageParser.java
+++ b/source/net/yacy/document/parser/images/genericImageParser.java
@@ -53,14 +53,13 @@ import com.sun.image.codec.jpeg.JPEGImageDecoder;
import net.yacy.cora.document.MultiProtocolURI;
import net.yacy.document.AbstractParser;
import net.yacy.document.Document;
-import net.yacy.document.Idiom;
-import net.yacy.document.ParserException;
+import net.yacy.document.Parser;
import net.yacy.document.parser.html.ImageEntry;
import net.yacy.document.parser.images.bmpParser.IMAGEMAP;
import net.yacy.kelondro.logging.Log;
import net.yacy.kelondro.util.FileUtils;
-public class genericImageParser extends AbstractParser implements Idiom {
+public class genericImageParser extends AbstractParser implements Parser {
/**
* a list of mime types that are supported by this parser class
@@ -85,13 +84,11 @@ public class genericImageParser extends AbstractParser implements Idiom {
super("Generic Image Parser");
}
- @SuppressWarnings("unchecked")
- @Override
- public Document parse(
+ public Document[] parse(
final MultiProtocolURI location,
final String mimeType,
final String documentCharset,
- final InputStream sourceStream) throws ParserException, InterruptedException {
+ final InputStream sourceStream) throws Parser.Failure, InterruptedException {
ImageInfo ii = null;
String title = null;
@@ -105,7 +102,7 @@ public class genericImageParser extends AbstractParser implements Idiom {
b = FileUtils.read(sourceStream);
} catch (IOException e) {
Log.logException(e);
- throw new ParserException(e.getMessage(), location);
+ throw new Parser.Failure(e.getMessage(), location);
}
IMAGEMAP imap = bmpParser.parse(b);
ii = parseJavaImage(location, imap.getImage());
@@ -122,19 +119,21 @@ public class genericImageParser extends AbstractParser implements Idiom {
try {
image = jpegDecoder.decodeAsBufferedImage();
} catch (ImageFormatException e) {
- throw new ParserException(e.getMessage(), location);
+ throw new Parser.Failure(e.getMessage(), location);
} catch (IOException e) {
- throw new ParserException(e.getMessage(), location);
+ throw new Parser.Failure(e.getMessage(), location);
}
JPEGDecodeParam decodeParam = jpegDecoder.getJPEGDecodeParam();
Metadata metadata = JpegMetadataReader.readMetadata(decodeParam);
ii = parseJavaImage(location, image);
- Iterator<Directory> directories = (Iterator<Directory>) metadata.getDirectoryIterator();
+ @SuppressWarnings("unchecked")
+ Iterator<Directory> directories = metadata.getDirectoryIterator();
HashMap<String, String> props = new HashMap<String, String>();
while (directories.hasNext()) {
Directory directory = directories.next();
- Iterator<Tag> tags = (Iterator<Tag>) directory.getTagIterator();
+ @SuppressWarnings("unchecked")
+ Iterator<Tag> tags = directory.getTagIterator();
while (tags.hasNext()) {
Tag tag = tags.next();
try {
@@ -176,7 +175,7 @@ public class genericImageParser extends AbstractParser implements Idiom {
if (title == null) title = location.toNormalform(true, true);
- return new Document(
+ return new Document[]{new Document(
location,
mimeType,
"UTF-8",
@@ -190,7 +189,7 @@ public class genericImageParser extends AbstractParser implements Idiom {
infoString.getBytes(), // content text
anchors, // anchors
images,
- false); // images
+ false)}; // images
}
public Set<String> supportedMimeTypes() {
@@ -203,19 +202,19 @@ public class genericImageParser extends AbstractParser implements Idiom {
public static ImageInfo parseJavaImage(
final MultiProtocolURI location,
- final InputStream sourceStream) throws ParserException {
+ final InputStream sourceStream) throws Parser.Failure {
BufferedImage image = null;
try {
ImageIO.setUseCache(false); // do not write a cache to disc; keep in RAM
image = ImageIO.read(sourceStream);
} catch (final EOFException e) {
Log.logException(e);
- throw new ParserException(e.getMessage(), location);
+ throw new Parser.Failure(e.getMessage(), location);
} catch (final IOException e) {
Log.logException(e);
- throw new ParserException(e.getMessage(), location);
+ throw new Parser.Failure(e.getMessage(), location);
}
- if (image == null) throw new ParserException("ImageIO returned NULL", location);
+ if (image == null) throw new Parser.Failure("ImageIO returned NULL", location);
return parseJavaImage(location, image);
}
@@ -279,13 +278,13 @@ public class genericImageParser extends AbstractParser implements Idiom {
MultiProtocolURI uri;
try {
uri = new MultiProtocolURI("http://localhost/" + image.getName());
- Document document = parser.parse(uri, "image/" + uri.getFileExtension(), "UTF-8", new FileInputStream(image));
- System.out.println(document.toString());
+ Document[] document = parser.parse(uri, "image/" + uri.getFileExtension(), "UTF-8", new FileInputStream(image));
+ System.out.println(document[0].toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
- } catch (ParserException e) {
+ } catch (Parser.Failure e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
diff --git a/source/net/yacy/document/parser/odtParser.java b/source/net/yacy/document/parser/odtParser.java
index d2f9ddc95..29651c4d3 100644
--- a/source/net/yacy/document/parser/odtParser.java
+++ b/source/net/yacy/document/parser/odtParser.java
@@ -41,24 +41,16 @@ import javax.xml.parsers.SAXParserFactory;
import net.yacy.cora.document.MultiProtocolURI;
import net.yacy.document.AbstractParser;
import net.yacy.document.Document;
-import net.yacy.document.Idiom;
-import net.yacy.document.ParserException;
+import net.yacy.document.Parser;
import net.yacy.document.parser.xml.ODContentHandler;
import net.yacy.document.parser.xml.ODMetaHandler;
import net.yacy.kelondro.io.CharBuffer;
import net.yacy.kelondro.util.FileUtils;
-
+public class odtParser extends AbstractParser implements Parser {
-public class odtParser extends AbstractParser implements Idiom {
-
- /**
- * a list of mime types that are supported by this parser class
- * @see #getSupportedMimeTypes()
- */
- public static final Set<String> SUPPORTED_MIME_TYPES = new HashSet<String>();
- public static final Set<String> SUPPORTED_EXTENSIONS = new HashSet<String>();
- static {
+ public odtParser() {
+ super("OASIS OpenDocument V2 Text Document Parser");
SUPPORTED_EXTENSIONS.add("odt");
SUPPORTED_EXTENSIONS.add("ods");
SUPPORTED_EXTENSIONS.add("odp");
@@ -91,21 +83,8 @@ public class odtParser extends AbstractParser implements Idiom {
SUPPORTED_MIME_TYPES.add("application/OOo-calc");
SUPPORTED_MIME_TYPES.add("application/OOo-writer");
}
-
- public odtParser() {
- super("OASIS OpenDocument V2 Text Document Parser");
- }
-
- public Set<String> supportedMimeTypes() {
- return SUPPORTED_MIME_TYPES;
- }
-
- public Set<String> supportedExtensions() {
- return SUPPORTED_EXTENSIONS;
- }
- @Override
- public Document parse(final MultiProtocolURI location, final String mimeType, final String charset, final File dest) throws ParserException, InterruptedException {
+ private Document[] parse(final MultiProtocolURI location, final String mimeType, final String charset, final File dest) throws Parser.Failure, InterruptedException {
CharBuffer writer = null;
try {
@@ -117,14 +96,12 @@ public class odtParser extends AbstractParser implements Idiom {
String docLanguage = null;
// opening the file as zip file
- final ZipFile zipFile= new ZipFile(dest);
+ final ZipFile zipFile = new ZipFile(dest);
final Enumeration<? extends ZipEntry> zipEnum = zipFile.entries();
final SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
// looping through all containing files
while (zipEnum.hasMoreElements()) {
- // check for interruption
- checkInterruption();
// getting the next zip file entry
final ZipEntry zipEntry= zipEnum.nextElement();
@@ -176,9 +153,9 @@ public class odtParser extends AbstractParser implements Idiom {
if (docKeywordStr != null) docKeywords = docKeywordStr.split(" |,");
// create the parser document
- Document theDoc = null;
+ Document[] docs = null;
final byte[] contentBytes = writer.toString().getBytes("UTF-8");
- theDoc = new Document(
+ docs = new Document[]{new Document(
location,
mimeType,
"UTF-8",
@@ -192,20 +169,20 @@ public class odtParser extends AbstractParser implements Idiom {
contentBytes,
null,
null,
- false);
- return theDoc;
+ false)};
+ return docs;
} catch (final Exception e) {
if (e instanceof InterruptedException) throw (InterruptedException) e;
- if (e instanceof ParserException) throw (ParserException) e;
+ if (e instanceof Parser.Failure) throw (Parser.Failure) e;
// close the writer
if (writer != null) try { writer.close(); } catch (final Exception ex) {/* ignore this */}
- throw new ParserException("Unexpected error while parsing odt file. " + e.getMessage(),location);
+ throw new Parser.Failure("Unexpected error while parsing odt file. " + e.getMessage(),location);
}
}
- public Document parse(final MultiProtocolURI location, final String mimeType, final String charset, final InputStream source) throws ParserException, InterruptedException {
+ public Document[] parse(final MultiProtocolURI location, final String mimeType, final String charset, final InputStream source) throws Parser.Failure, InterruptedException {
File dest = null;
try {
// creating a tempfile
@@ -219,17 +196,12 @@ public class odtParser extends AbstractParser implements Idiom {
return parse(location, mimeType, charset, dest);
} catch (final Exception e) {
if (e instanceof InterruptedException) throw (InterruptedException) e;
- if (e instanceof ParserException) throw (ParserException) e;
+ if (e instanceof Parser.Failure) throw (Parser.Failure) e;
- throw new ParserException("Unexpected error while parsing odt file. " + e.getMessage(),location);
+ throw new Parser.Failure("Unexpected error while parsing odt file. " + e.getMessage(),location);
} finally {
if (dest != null) FileUtils.deletedelete(dest);
}
}
-
- @Override
- public void reset() {
- // Nothing todo here at the moment
- super.reset();
- }
+
}
diff --git a/source/net/yacy/document/parser/ooxmlParser.java b/source/net/yacy/document/parser/ooxmlParser.java
index 7be61258d..376dd0a01 100644
--- a/source/net/yacy/document/parser/ooxmlParser.java
+++ b/source/net/yacy/document/parser/ooxmlParser.java
@@ -41,8 +41,7 @@ import javax.xml.parsers.SAXParserFactory;
import net.yacy.cora.document.MultiProtocolURI;
import net.yacy.document.AbstractParser;
import net.yacy.document.Document;
-import net.yacy.document.Idiom;
-import net.yacy.document.ParserException;
+import net.yacy.document.Parser;
import net.yacy.document.parser.xml.ODContentHandler;
import net.yacy.document.parser.xml.ODMetaHandler;
import net.yacy.kelondro.io.CharBuffer;
@@ -51,15 +50,10 @@ import net.yacy.kelondro.util.FileUtils;
-public class ooxmlParser extends AbstractParser implements Idiom {
+public class ooxmlParser extends AbstractParser implements Parser {
- /**
- * a list of mime types that are supported by this parser class
- * @see #getSupportedMimeTypes()
- */
- public static final Set<String> SUPPORTED_MIME_TYPES = new HashSet<String>();
- public static final Set<String> SUPPORTED_EXTENSIONS = new HashSet<String>();
- static {
+ public ooxmlParser() {
+ super("Open Office XML Document Parser");
SUPPORTED_EXTENSIONS.add("docx");
SUPPORTED_MIME_TYPES.add("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
SUPPORTED_EXTENSIONS.add("dotx");
@@ -75,21 +69,8 @@ public class ooxmlParser extends AbstractParser implements Idiom {
SUPPORTED_EXTENSIONS.add("xltx");
SUPPORTED_MIME_TYPES.add("application/vnd.openxmlformats-officedocument.spreadsheetml.template");
}
-
- public ooxmlParser() {
- super("Open Office XML Document Parser");
- }
- public Set<String> supportedMimeTypes() {
- return SUPPORTED_MIME_TYPES;
- }
-
- public Set<String> supportedExtensions() {
- return SUPPORTED_EXTENSIONS;
- }
-
- @Override
- public Document parse(final MultiProtocolURI location, final String mimeType, final String charset, final File dest) throws ParserException, InterruptedException {
+ private Document[] parse(final MultiProtocolURI location, final String mimeType, final String charset, final File dest) throws Parser.Failure, InterruptedException {
CharBuffer writer = null;
try {
@@ -107,10 +88,8 @@ public class ooxmlParser extends AbstractParser implements Idiom {
// looping through all containing files
while (zipEnum.hasMoreElements()) {
- // check for interruption
- checkInterruption();
- // getting the next zip file entry
+ // get next zip file entry
final ZipEntry zipEntry= zipEnum.nextElement();
final String entryName = zipEntry.getName();
@@ -163,9 +142,9 @@ public class ooxmlParser extends AbstractParser implements Idiom {
if (docKeywordStr != null) docKeywords = docKeywordStr.split(" |,");
// create the parser document
- Document theDoc = null;
+ Document[] docs = null;
final byte[] contentBytes = writer.toString().getBytes("UTF-8");
- theDoc = new Document(
+ docs = new Document[]{new Document(
location,
mimeType,
"UTF-8",
@@ -179,21 +158,21 @@ public class ooxmlParser extends AbstractParser implements Idiom {
contentBytes,
null,
null,
- false);
- return theDoc;
+ false)};
+ return docs;
} catch (final Exception e) {
if (e instanceof InterruptedException) throw (InterruptedException) e;
- if (e instanceof ParserException) throw (ParserException) e;
+ if (e instanceof Parser.Failure) throw (Parser.Failure) e;
// close the writer
if (writer != null) try { writer.close(); } catch (final Exception ex) {/* ignore this */}
Log.logException(e);
- throw new ParserException("Unexpected error while parsing odt file. " + e.getMessage(),location);
+ throw new Parser.Failure("Unexpected error while parsing odt file. " + e.getMessage(),location);
}
}
- public Document parse(final MultiProtocolURI location, final String mimeType, final String charset, final InputStream source) throws ParserException, InterruptedException {
+ public Document[] parse(final MultiProtocolURI location, final String mimeType, final String charset, final InputStream source) throws Parser.Failure, InterruptedException {
File dest = null;
try {
// creating a tempfile
@@ -207,17 +186,12 @@ public class ooxmlParser extends AbstractParser implements Idiom {
return parse(location, mimeType, charset, dest);
} catch (final Exception e) {
if (e instanceof InterruptedException) throw (InterruptedException) e;
- if (e instanceof ParserException) throw (ParserException) e;
+ if (e instanceof Parser.Failure) throw (Parser.Failure) e;
- throw new ParserException("Unexpected error while parsing odt file. " + e.getMessage(),location);
+ throw new Parser.Failure("Unexpected error while parsing odt file. " + e.getMessage(),location);
} finally {
if (dest != null) FileUtils.deletedelete(dest);
}
}
-
- @Override
- public void reset() {
- // Nothing todo here at the moment
- super.reset();
- }
+
}
diff --git a/source/net/yacy/document/parser/pdfParser.java b/source/net/yacy/document/parser/pdfParser.java
index d0c7c8aa5..55adbbbe3 100644
--- a/source/net/yacy/document/parser/pdfParser.java
+++ b/source/net/yacy/document/parser/pdfParser.java
@@ -28,11 +28,11 @@
package net.yacy.document.parser;
import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
-import java.util.HashSet;
-import java.util.Set;
import org.apache.pdfbox.exceptions.CryptographyException;
import org.apache.pdfbox.pdfparser.PDFParser;
@@ -46,22 +46,16 @@ import org.apache.pdfbox.util.PDFTextStripper;
import net.yacy.cora.document.MultiProtocolURI;
import net.yacy.document.AbstractParser;
import net.yacy.document.Document;
-import net.yacy.document.Idiom;
-import net.yacy.document.ParserException;
+import net.yacy.document.Parser;
import net.yacy.kelondro.io.CharBuffer;
import net.yacy.kelondro.logging.Log;
import net.yacy.kelondro.util.FileUtils;
-public class pdfParser extends AbstractParser implements Idiom {
-
- /**
- * a list of mime types that are supported by this parser class
- * @see #getSupportedMimeTypes()
- */
- public static final Set<String> SUPPORTED_MIME_TYPES = new HashSet<String>();
- public static final Set<String> SUPPORTED_EXTENSIONS = new HashSet<String>();
- static {
+public class pdfParser extends AbstractParser implements Parser {
+
+ public pdfParser() {
+ super("Acrobat Portable Document Parser");
SUPPORTED_EXTENSIONS.add("pdf");
SUPPORTED_MIME_TYPES.add("application/pdf");
SUPPORTED_MIME_TYPES.add("application/x-pdf");
@@ -69,59 +63,45 @@ public class pdfParser extends AbstractParser implements Idiom {
SUPPORTED_MIME_TYPES.add("applications/vnd.pdf");
SUPPORTED_MIME_TYPES.add("text/pdf");
SUPPORTED_MIME_TYPES.add("text/x-pdf");
- }
-
- public pdfParser() {
- super("Acrobat Portable Document Parser");
- }
-
- public Set<String> supportedMimeTypes() {
- return SUPPORTED_MIME_TYPES;
- }
-
- public Set<String> supportedExtensions() {
- return SUPPORTED_EXTENSIONS;
}
- public Document parse(final MultiProtocolURI location, final String mimeType, final String charset, final InputStream source) throws ParserException, InterruptedException {
+ public Document[] parse(final MultiProtocolURI location, final String mimeType, final String charset, final InputStream source) throws Parser.Failure, InterruptedException {
// create a pdf parser
- final PDDocument theDocument;
- final PDFParser parser;
+ PDDocument pdfDoc = null;
+ final PDFParser pdfParser;
try {
Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
- parser = new PDFParser(source);
- parser.parse();
- theDocument = parser.getPDDocument();
+ pdfParser = new PDFParser(source);
+ pdfParser.parse();
+ pdfDoc = pdfParser.getPDDocument();
} catch (IOException e) {
- Log.logException(e);
- throw new ParserException(e.getMessage(), location);
+ if (pdfDoc != null) try {pdfDoc.close();} catch (IOException ee) {}
+ throw new Parser.Failure(e.getMessage(), location);
} finally {
Thread.currentThread().setPriority(Thread.NORM_PRIORITY);
}
-
- checkInterruption();
- if (theDocument.isEncrypted()) {
+ if (pdfDoc.isEncrypted()) {
try {
- theDocument.openProtection(new StandardDecryptionMaterial(""));
+ pdfDoc.openProtection(new StandardDecryptionMaterial(""));
} catch (BadSecurityHandlerException e) {
- Log.logException(e);
- throw new ParserException("Document is encrypted (1): " + e.getMessage(), location);
+ try {pdfDoc.close();} catch (IOException ee) {}
+ throw new Parser.Failure("Document is encrypted (1): " + e.getMessage(), location);
} catch (IOException e) {
- Log.logException(e);
- throw new ParserException("Document is encrypted (2): " + e.getMessage(), location);
+ try {pdfDoc.close();} catch (IOException ee) {}
+ throw new Parser.Failure("Document is encrypted (2): " + e.getMessage(), location);
} catch (CryptographyException e) {
- Log.logException(e);
- throw new ParserException("Document is encrypted (3): " + e.getMessage(), location);
+ try {pdfDoc.close();} catch (IOException ee) {}
+ throw new Parser.Failure("Document is encrypted (3): " + e.getMessage(), location);
}
- final AccessPermission perm = theDocument.getCurrentAccessPermission();
+ final AccessPermission perm = pdfDoc.getCurrentAccessPermission();
if (perm == null || !perm.canExtractContent())
- throw new ParserException("Document is encrypted and cannot decrypted", location);
+ throw new Parser.Failure("Document is encrypted and cannot decrypted", location);
}
// extracting some metadata
- final PDDocumentInformation theDocInfo = theDocument.getDocumentInformation();
+ final PDDocumentInformation theDocInfo = pdfDoc.getDocumentInformation();
String docTitle = null, docSubject = null, docAuthor = null, docPublisher = null, docKeywordStr = null;
if (theDocInfo != null) {
docTitle = theDocInfo.getTitle();
@@ -137,21 +117,21 @@ public class pdfParser extends AbstractParser implements Idiom {
// create a writer for output
writer = new CharBuffer();
stripper = new PDFTextStripper();
- stripper.writeText(theDocument, writer); // may throw a NPE
- theDocument.close();
+ stripper.writeText(pdfDoc, writer); // may throw a NPE
+ pdfDoc.close();
writer.close();
} catch (IOException e) {
- Log.logException(e);
// close the writer
if (writer != null) try { writer.close(); } catch (final Exception ex) {}
-
- throw new ParserException(e.getMessage(), location);
+ try {pdfDoc.close();} catch (IOException ee) {}
+ throw new Parser.Failure(e.getMessage(), location);
+ } finally {
+ try {pdfDoc.close();} catch (IOException e) {}
}
String[] docKeywords = null;
if (docKeywordStr != null) docKeywords = docKeywordStr.split(" |,");
- Document theDoc = null;
if (docTitle == null) docTitle = docSubject;
byte[] contentBytes;
@@ -159,9 +139,11 @@ public class pdfParser extends AbstractParser implements Idiom {
contentBytes = writer.toString().getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
Log.logException(e);
- throw new ParserException(e.getMessage(), location);
+ throw new Parser.Failure(e.getMessage(), location);
+ } finally {
+ try {pdfDoc.close();} catch (IOException e) {}
}
- theDoc = new Document(
+ return new Document[]{new Document(
location,
mimeType,
"UTF-8",
@@ -175,15 +157,7 @@ public class pdfParser extends AbstractParser implements Idiom {
contentBytes,
null,
null,
- false);
-
- return theDoc;
- }
-
- @Override
- public void reset() {
- // Nothing todo here at the moment
- super.reset();
+ false)};
}
/**
@@ -191,7 +165,7 @@ public class pdfParser extends AbstractParser implements Idiom {
* @param args
*/
public static void main(final String[] args) {
- if(args.length > 0 && args[0].length() > 0) {
+ if (args.length > 0 && args[0].length() > 0) {
// file
final File pdfFile = new File(args[0]);
if(pdfFile.canRead()) {
@@ -203,23 +177,24 @@ public class pdfParser extends AbstractParser implements Idiom {
final AbstractParser parser = new pdfParser();
Document document = null;
try {
- document = parser.parse(null, "application/pdf", null, pdfFile);
-
- } catch (final ParserException e) {
- System.err.println("Cannot parse file "+ pdfFile.getAbsolutePath());
+ document = Document.mergeDocuments(null, "application/pdf", parser.parse(null, "application/pdf", null, new FileInputStream(pdfFile)));
+ } catch (final Parser.Failure e) {
+ System.err.println("Cannot parse file " + pdfFile.getAbsolutePath());
Log.logException(e);
} catch (final InterruptedException e) {
System.err.println("Interrupted while parsing!");
Log.logException(e);
} catch (final NoClassDefFoundError e) {
System.err.println("class not found: " + e.getMessage());
+ } catch (FileNotFoundException e) {
+ Log.logException(e);
}
// statistics
System.out.println("\ttime elapsed: " + (System.currentTimeMillis() - startTime) + " ms");
// output
- if(document == null) {
+ if (document == null) {
System.out.println("\t!!!Parsing without result!!!");
} else {
System.out.println("\tParsed text with " + document.getTextLength() + " chars of text and " + document.getAnchors().size() + " anchors");
diff --git a/source/net/yacy/document/parser/pptParser.java b/source/net/yacy/document/parser/pptParser.java
index 312441266..2400951de 100644
--- a/source/net/yacy/document/parser/pptParser.java
+++ b/source/net/yacy/document/parser/pptParser.java
@@ -29,29 +29,21 @@ package net.yacy.document.parser;
import java.io.BufferedInputStream;
import java.io.InputStream;
-import java.util.HashSet;
-import java.util.Set;
import net.yacy.cora.document.MultiProtocolURI;
import net.yacy.document.AbstractParser;
import net.yacy.document.Document;
-import net.yacy.document.Idiom;
-import net.yacy.document.ParserException;
+import net.yacy.document.Parser;
import net.yacy.kelondro.logging.Log;
import org.apache.poi.hslf.extractor.PowerPointExtractor;
-public class pptParser extends AbstractParser implements Idiom {
+public class pptParser extends AbstractParser implements Parser {
- /**
- * a list of mime types that are supported by this parser class
- * @see #getSupportedMimeTypes()
- */
- public static final Set<String> SUPPORTED_MIME_TYPES = new HashSet<String>();
- public static final Set<String> SUPPORTED_EXTENSIONS = new HashSet<String>();
- static {
+ public pptParser(){
+ super("Microsoft Powerpoint Parser");
SUPPORTED_EXTENSIONS.add("ppt");
- SUPPORTED_EXTENSIONS.add("pps");
+ SUPPORTED_EXTENSIONS.add("pps");
SUPPORTED_MIME_TYPES.add("application/mspowerpoint");
SUPPORTED_MIME_TYPES.add("application/powerpoint");
SUPPORTED_MIME_TYPES.add("application/vnd.ms-powerpoint");
@@ -60,18 +52,14 @@ public class pptParser extends AbstractParser implements Idiom {
SUPPORTED_MIME_TYPES.add("application/vnd-mspowerpoint");
SUPPORTED_MIME_TYPES.add("application/x-powerpoint");
SUPPORTED_MIME_TYPES.add("application/x-m");
- }
-
- public pptParser(){
- super("Microsoft Powerpoint Parser");
}
/*
* parses the source documents and returns a plasmaParserDocument containing
* all extracted information about the parsed document
*/
- public Document parse(final MultiProtocolURI location, final String mimeType,
- final String charset, final InputStream source) throws ParserException,
+ public Document[] parse(final MultiProtocolURI location, final String mimeType,
+ final String charset, final InputStream source) throws Parser.Failure,
InterruptedException {
try {
/*
@@ -93,7 +81,7 @@ public class pptParser extends AbstractParser implements Idiom {
* create the plasmaParserDocument for the database
* and set shortText and bodyText properly
*/
- final Document theDoc = new Document(
+ final Document[] docs = new Document[]{new Document(
location,
mimeType,
"UTF-8",
@@ -107,32 +95,19 @@ public class pptParser extends AbstractParser implements Idiom {
contents.getBytes("UTF-8"),
null,
null,
- false);
- return theDoc;
+ false)};
+ return docs;
} catch (final Exception e) {
if (e instanceof InterruptedException) throw (InterruptedException) e;
/*
- * an unexpected error occurred, log it and throw a ParserException
+ * an unexpected error occurred, log it and throw a Parser.Failure
*/
Log.logException(e);
final String errorMsg = "Unable to parse the ppt document '" + location + "':" + e.getMessage();
- this.theLogger.logSevere(errorMsg);
- throw new ParserException(errorMsg, location);
+ this.log.logSevere(errorMsg);
+ throw new Parser.Failure(errorMsg, location);
}
}
- public Set<String> supportedMimeTypes() {
- return SUPPORTED_MIME_TYPES;
- }
-
- public Set<String> supportedExtensions() {
- return SUPPORTED_EXTENSIONS;
- }
-
- @Override
- public void reset(){
- //nothing to do
- super.reset();
- }
}
diff --git a/source/net/yacy/document/parser/psParser.java b/source/net/yacy/document/parser/psParser.java
index ecc774afb..7bcb19887 100644
--- a/source/net/yacy/document/parser/psParser.java
+++ b/source/net/yacy/document/parser/psParser.java
@@ -34,33 +34,15 @@ import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
-import java.util.HashSet;
-import java.util.Set;
import net.yacy.cora.document.MultiProtocolURI;
import net.yacy.document.AbstractParser;
import net.yacy.document.Document;
-import net.yacy.document.Idiom;
-import net.yacy.document.ParserException;
+import net.yacy.document.Parser;
import net.yacy.kelondro.util.FileUtils;
-public class psParser extends AbstractParser implements Idiom {
-
- /**
- * a list of mime types that are supported by this parser class
- * @see #getSupportedMimeTypes()
- */
- public static final Set<String> SUPPORTED_MIME_TYPES = new HashSet<String>();
- public static final Set<String> SUPPORTED_EXTENSIONS = new HashSet<String>();
- static {
- SUPPORTED_EXTENSIONS.add("ps");
- SUPPORTED_MIME_TYPES.add("application/postscript");
- SUPPORTED_MIME_TYPES.add("application/ps");
- SUPPORTED_MIME_TYPES.add("application/x-postscript");
- SUPPORTED_MIME_TYPES.add("application/x-ps");
- SUPPORTED_MIME_TYPES.add("application/x-postscript-not-eps");
- }
+public class psParser extends AbstractParser implements Parser {
private final static Object modeScan = new Object();
private static boolean modeScanDone = false;
@@ -68,21 +50,19 @@ public class psParser extends AbstractParser implements Idiom {
public psParser() {
super("PostScript Document Parser");
+ SUPPORTED_EXTENSIONS.add("ps");
+ SUPPORTED_MIME_TYPES.add("application/postscript");
+ SUPPORTED_MIME_TYPES.add("application/ps");
+ SUPPORTED_MIME_TYPES.add("application/x-postscript");
+ SUPPORTED_MIME_TYPES.add("application/x-ps");
+ SUPPORTED_MIME_TYPES.add("application/x-postscript-not-eps");
if (!modeScanDone) synchronized (modeScan) {
if (testForPs2Ascii()) parserMode = "ps2ascii";
else parserMode = "java";
modeScanDone = true;
}
}
-
- public Set<String> supportedMimeTypes() {
- return SUPPORTED_MIME_TYPES;
- }
-
- public Set<String> supportedExtensions() {
- return SUPPORTED_EXTENSIONS;
- }
-
+
public boolean testForPs2Ascii() {
try {
String procOutputLine = null;
@@ -97,19 +77,18 @@ public class psParser extends AbstractParser implements Idiom {
final int returnCode = ps2asciiProc.waitFor();
return (returnCode == 0);
} catch (final Exception e) {
- if (this.theLogger != null) this.theLogger.logInfo("ps2ascii not found. Switching to java parser mode.");
+ if (this.log != null) this.log.logInfo("ps2ascii not found. Switching to java parser mode.");
return false;
}
}
- @Override
- public Document parse(final MultiProtocolURI location, final String mimeType, final String charset, final File sourceFile) throws ParserException, InterruptedException {
+ public Document[] parse(final MultiProtocolURI location, final String mimeType, final String charset, final File sourceFile) throws Parser.Failure, InterruptedException {
File outputFile = null;
try {
// creating a temp file for the output
- outputFile = super.createTempFile("ascii.txt");
+ outputFile = FileUtils.createTempFile(this.getClass(), "ascii.txt");
// decide with parser mode to use
if (parserMode.equals("ps2ascii")) {
@@ -119,7 +98,7 @@ public class psParser extends AbstractParser implements Idiom {
}
// return result
- final Document theDoc = new Document(
+ final Document[] docs = new Document[]{new Document(
location, // url
mimeType, // mime
"UTF-8", // charset
@@ -133,22 +112,22 @@ public class psParser extends AbstractParser implements Idiom {
outputFile, // fulltext
null, // anchors
null, // images
- false); // indexingdenied
+ false)}; // indexingdenied
- return theDoc;
+ return docs;
} catch (final Exception e) {
if (e instanceof InterruptedException) throw (InterruptedException) e;
- if (e instanceof ParserException) throw (ParserException) e;
+ if (e instanceof Parser.Failure) throw (Parser.Failure) e;
// delete temp file
if (outputFile != null) FileUtils.deletedelete(outputFile);
// throw exception
- throw new ParserException("Unexpected error while parsing ps file. " + e.getMessage(),location);
+ throw new Parser.Failure("Unexpected error while parsing ps file. " + e.getMessage(),location);
}
}
- public void parseUsingJava (final File inputFile, final File outputFile) throws Exception {
+ public void parseUsingJava(final File inputFile, final File outputFile) throws Exception {
BufferedReader reader = null;
BufferedWriter writer = null;
@@ -264,25 +243,19 @@ public class psParser extends AbstractParser implements Idiom {
execCode = ps2asciiProc.waitFor();
} catch (final Exception e) {
final String errorMsg = "Unable to convert ps to ascii. " + e.getMessage();
- this.theLogger.logSevere(errorMsg);
+ this.log.logSevere(errorMsg);
throw new Exception(errorMsg);
}
if (execCode != 0) throw new Exception("Unable to convert ps to ascii. ps2ascii returned statuscode " + execCode + "\n" + procErr.toString());
}
-
- @Override
- public void reset() {
- // Nothing todo here at the moment
- super.reset();
- }
- public Document parse(final MultiProtocolURI location, final String mimeType, final String charset, final InputStream source) throws ParserException, InterruptedException {
+ public Document[] parse(final MultiProtocolURI location, final String mimeType, final String charset, final InputStream source) throws Parser.Failure, InterruptedException {
File tempFile = null;
try {
// creating a tempfile
- tempFile = super.createTempFile("temp.ps");
+ tempFile = FileUtils.createTempFile(this.getClass(), "temp.ps");
tempFile.deleteOnExit();
// copying inputstream into file
@@ -292,9 +265,9 @@ public class psParser extends AbstractParser implements Idiom {
return parse(location,mimeType,charset,tempFile);
} catch (final Exception e) {
if (e instanceof InterruptedException) throw (InterruptedException) e;
- if (e instanceof ParserException) throw (ParserException) e;
+ if (e instanceof Parser.Failure) throw (Parser.Failure) e;
- throw new ParserException("Unable to parse the ps file. " + e.getMessage(), location);
+ throw new Parser.Failure("Unable to parse the ps file. " + e.getMessage(), location);
} finally {
if (tempFile != null) FileUtils.deletedelete(tempFile);
}
diff --git a/source/net/yacy/document/parser/rssParser.java b/source/net/yacy/document/parser/rssParser.java
index 668dd3ab9..d35ad89f2 100644
--- a/source/net/yacy/document/parser/rssParser.java
+++ b/source/net/yacy/document/parser/rssParser.java
@@ -35,10 +35,8 @@ import java.io.Writer;
import java.net.MalformedURLException;
import java.nio.charset.Charset;
import java.util.HashMap;
-import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
-import java.util.Set;
import net.yacy.cora.document.Hit;
import net.yacy.cora.document.MultiProtocolURI;
@@ -46,8 +44,7 @@ import net.yacy.cora.document.RSSFeed;
import net.yacy.cora.document.RSSReader;
import net.yacy.document.AbstractParser;
import net.yacy.document.Document;
-import net.yacy.document.Idiom;
-import net.yacy.document.ParserException;
+import net.yacy.document.Parser;
import net.yacy.document.parser.html.AbstractScraper;
import net.yacy.document.parser.html.ContentScraper;
import net.yacy.document.parser.html.ImageEntry;
@@ -57,28 +54,19 @@ import net.yacy.kelondro.util.ByteBuffer;
import net.yacy.kelondro.util.FileUtils;
-public class rssParser extends AbstractParser implements Idiom {
+public class rssParser extends AbstractParser implements Parser {
- /**
- * a list of mime types that are supported by this parser class
- * @see #getSupportedMimeTypes()
- */
- public static final Set<String> SUPPORTED_MIME_TYPES = new HashSet<String>();
- public static final Set<String> SUPPORTED_EXTENSIONS = new HashSet<String>();
- static {
+ public rssParser() {
+ super("Rich Site Summary/Atom Feed Parser");
SUPPORTED_EXTENSIONS.add("rss");
SUPPORTED_EXTENSIONS.add("xml");
SUPPORTED_MIME_TYPES.add("XML");
SUPPORTED_MIME_TYPES.add("text/rss");
SUPPORTED_MIME_TYPES.add("application/rss+xml");
SUPPORTED_MIME_TYPES.add("application/atom+xml");
- }
-
- public rssParser() {
- super("Rich Site Summary/Atom Feed Parser");
}
- public Document parse(final MultiProtocolURI location, final String mimeType, final String charset, final InputStream source) throws ParserException, InterruptedException {
+ public Document[] parse(final MultiProtocolURI location, final String mimeType, final String charset, final InputStream source) throws Parser.Failure, InterruptedException {
final LinkedList<String> feedSections = new LinkedList<String>();
final HashMap<MultiProtocolURI, String> anchors = new HashMap<MultiProtocolURI, String>();
@@ -90,15 +78,15 @@ public class rssParser extends AbstractParser implements Idiom {
try {
feed = new RSSReader(source).getFeed();
} catch (IOException e) {
- throw new ParserException("reading feed failed: " + e.getMessage(), location);
+ throw new Parser.Failure("reading feed failed: " + e.getMessage(), location);
}
- if (feed == null) throw new ParserException("no feed in document", location);
+ if (feed == null) throw new Parser.Failure("no feed in document", location);
String feedTitle = "";
String feedDescription = "";
String feedPublisher = "";
String[] feedSubject = {""};
- if (feed.getChannel() != null) {//throw new ParserException("no channel in document",location);
+ if (feed.getChannel() != null) {//throw new Parser.Failure("no channel in document",location);
// get the rss feed title and description
feedTitle = feed.getChannel().getTitle();
@@ -126,8 +114,6 @@ public class rssParser extends AbstractParser implements Idiom {
// loop through the feed items
for (final Hit item: feed) {
- // check for interruption
- checkInterruption();
final String itemTitle = item.getTitle();
MultiProtocolURI itemURL = null;
@@ -183,7 +169,7 @@ public class rssParser extends AbstractParser implements Idiom {
}
}
- final Document theDoc = new Document(
+ final Document[] docs = new Document[]{new Document(
location,
mimeType,
"UTF-8",
@@ -197,7 +183,7 @@ public class rssParser extends AbstractParser implements Idiom {
text.getBytes(),
anchors,
images,
- false);
+ false)};
// close streams
try {
text.close();
@@ -205,21 +191,6 @@ public class rssParser extends AbstractParser implements Idiom {
} catch (IOException e) {
}
- return theDoc;
- }
-
- public Set<String> supportedMimeTypes() {
- return SUPPORTED_MIME_TYPES;
- }
-
- public Set<String> supportedExtensions() {
- return SUPPORTED_EXTENSIONS;
- }
-
- @Override
- public void reset() {
- // Nothing todo here at the moment
- super.reset();
+ return docs;
}
-
}
diff --git a/source/net/yacy/document/parser/rtfParser.java b/source/net/yacy/document/parser/rtfParser.java
index ac2474f57..652a70162 100644
--- a/source/net/yacy/document/parser/rtfParser.java
+++ b/source/net/yacy/document/parser/rtfParser.java
@@ -28,8 +28,6 @@
package net.yacy.document.parser;
import java.io.InputStream;
-import java.util.HashSet;
-import java.util.Set;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.rtf.RTFEditorKit;
@@ -37,32 +35,22 @@ import javax.swing.text.rtf.RTFEditorKit;
import net.yacy.cora.document.MultiProtocolURI;
import net.yacy.document.AbstractParser;
import net.yacy.document.Document;
-import net.yacy.document.Idiom;
-import net.yacy.document.ParserException;
+import net.yacy.document.Parser;
-public class rtfParser extends AbstractParser implements Idiom {
+public class rtfParser extends AbstractParser implements Parser {
- /**
- * a list of mime types that are supported by this parser class
- * @see #getSupportedMimeTypes()
- */
- public static final Set<String> SUPPORTED_MIME_TYPES = new HashSet<String>();
- public static final Set<String> SUPPORTED_EXTENSIONS = new HashSet<String>();
- static {
+ public rtfParser() {
+ super("Rich Text Format Parser");
SUPPORTED_EXTENSIONS.add("rtf");
SUPPORTED_MIME_TYPES.add("text/rtf");
SUPPORTED_MIME_TYPES.add("text/richtext");
SUPPORTED_MIME_TYPES.add("application/rtf");
SUPPORTED_MIME_TYPES.add("application/x-rtf");
SUPPORTED_MIME_TYPES.add("application/x-soffice");
- }
-
- public rtfParser() {
- super("Rich Text Format Parser");
}
- public Document parse(final MultiProtocolURI location, final String mimeType, final String charset, final InputStream source) throws ParserException, InterruptedException {
+ public Document[] parse(final MultiProtocolURI location, final String mimeType, final String charset, final InputStream source) throws Parser.Failure, InterruptedException {
try {
@@ -73,7 +61,7 @@ public class rtfParser extends AbstractParser implements Idiom {
final String bodyText = doc.getText(0, doc.getLength());
- final Document theDoc = new Document(
+ return new Document[]{new Document(
location,
mimeType,
"UTF-8",
@@ -91,29 +79,14 @@ public class rtfParser extends AbstractParser implements Idiom {
bodyText.getBytes("UTF-8"),
null,
null,
- false);
-
- return theDoc;
+ false)};
}
catch (final Exception e) {
if (e instanceof InterruptedException) throw (InterruptedException) e;
- if (e instanceof ParserException) throw (ParserException) e;
+ if (e instanceof Parser.Failure) throw (Parser.Failure) e;
- throw new ParserException("Unexpected error while parsing rtf resource." + e.getMessage(),location);
+ throw new Parser.Failure("Unexpected error while parsing rtf resource." + e.getMessage(),location);
}
}
- public Set<String> supportedMimeTypes() {
- return SUPPORTED_MIME_TYPES;
- }
-
- public Set<String> supportedExtensions() {
- return SUPPORTED_EXTENSIONS;
- }
-
- public void reset() {
- // Nothing todo here at the moment
- super.reset();
- }
-
}
diff --git a/source/net/yacy/document/parser/sevenzipParser.java b/source/net/yacy/document/parser/sevenzipParser.java
index 482bb38d4..61ea53918 100644
--- a/source/net/yacy/document/parser/sevenzipParser.java
+++ b/source/net/yacy/document/parser/sevenzipParser.java
@@ -29,68 +29,53 @@ package net.yacy.document.parser;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
-import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
-import java.util.HashSet;
-import java.util.Set;
import net.yacy.cora.document.MultiProtocolURI;
import net.yacy.document.AbstractParser;
import net.yacy.document.Document;
-import net.yacy.document.Idiom;
+import net.yacy.document.Parser;
import net.yacy.document.TextParser;
-import net.yacy.document.ParserException;
import net.yacy.kelondro.logging.Log;
import net.yacy.kelondro.util.FileUtils;
import SevenZip.ArchiveExtractCallback;
import SevenZip.IInStream;
-import SevenZip.MyRandomAccessFile;
import SevenZip.Archive.IInArchive;
import SevenZip.Archive.SevenZipEntry;
import SevenZip.Archive.SevenZip.Handler;
-public class sevenzipParser extends AbstractParser implements Idiom {
-
- /**
- * a list of mime types that are supported by this parser class
- * @see #getSupportedMimeTypes()
- */
- public static final Set<String> SUPPORTED_MIME_TYPES = new HashSet<String>();
- public static final Set<String> SUPPORTED_EXTENSIONS = new HashSet<String>();
- static {
- SUPPORTED_EXTENSIONS.add("7z");
- SUPPORTED_MIME_TYPES.add("application/x-7z-compressed");
- }
+public class sevenzipParser extends AbstractParser implements Parser {
public sevenzipParser() {
super("7zip Archive Parser");
+ SUPPORTED_EXTENSIONS.add("7z");
+ SUPPORTED_MIME_TYPES.add("application/x-7z-compressed");
}
- public Document parse(final MultiProtocolURI location, final String mimeType, final String charset, final IInStream source) throws ParserException, InterruptedException {
+ public Document parse(final MultiProtocolURI location, final String mimeType, final String charset, final IInStream source) throws Parser.Failure, InterruptedException {
final Document doc = new Document(location, mimeType, charset, null, null, null, null, null, null, null, (Object)null, null, null, false);
Handler archive;
- super.theLogger.logFine("opening 7zip archive...");
+ super.log.logFine("opening 7zip archive...");
try {
archive = new Handler(source);
} catch (final IOException e) {
- throw new ParserException("error opening 7zip archive: " + e.getMessage(), location);
+ throw new Parser.Failure("error opening 7zip archive: " + e.getMessage(), location);
}
- checkInterruption();
- final SZParserExtractCallback aec = new SZParserExtractCallback(super.theLogger, archive,
+ final SZParserExtractCallback aec = new SZParserExtractCallback(super.log, archive,
doc, location.getFile());
- super.theLogger.logFine("processing archive contents...");
+ super.log.logFine("processing archive contents...");
try {
archive.Extract(null, -1, 0, aec);
return doc;
} catch (final IOException e) {
if (e.getCause() instanceof InterruptedException)
throw (InterruptedException)e.getCause();
- if (e.getCause() instanceof ParserException)
- throw (ParserException)e.getCause();
- throw new ParserException(
+ if (e.getCause() instanceof Parser.Failure)
+ throw (Parser.Failure)e.getCause();
+ throw new Parser.Failure(
"error processing 7zip archive at internal file " + aec.getCurrentFilePath() + ": " + e.getMessage(),
location);
} finally {
@@ -98,41 +83,16 @@ public class sevenzipParser extends AbstractParser implements Idiom {
}
}
- @Override
- public Document parse(final MultiProtocolURI location, final String mimeType, final String charset,
- final byte[] source) throws ParserException, InterruptedException {
- return parse(location, mimeType, charset, new ByteArrayIInStream(source));
- }
-
- @Override
- public Document parse(final MultiProtocolURI location, final String mimeType, final String charset,
- final File sourceFile) throws ParserException, InterruptedException {
- try {
- return parse(location, mimeType, charset, new MyRandomAccessFile(sourceFile, "r"));
- } catch (final IOException e) {
- throw new ParserException("error processing 7zip archive: " + e.getMessage(), location);
- }
- }
-
- public Document parse(final MultiProtocolURI location, final String mimeType, final String charset,
- final InputStream source) throws ParserException, InterruptedException {
+ public Document[] parse(final MultiProtocolURI location, final String mimeType, final String charset,
+ final InputStream source) throws Parser.Failure, InterruptedException {
try {
final ByteArrayOutputStream cfos = new ByteArrayOutputStream();
FileUtils.copy(source, cfos);
return parse(location, mimeType, charset, new ByteArrayInputStream(cfos.toByteArray()));
} catch (final IOException e) {
- throw new ParserException("error processing 7zip archive: " + e.getMessage(), location);
+ throw new Parser.Failure("error processing 7zip archive: " + e.getMessage(), location);
}
}
-
- public Set<String> supportedMimeTypes() {
- return SUPPORTED_MIME_TYPES;
- }
-
- public Set<String> supportedExtensions() {
- return SUPPORTED_EXTENSIONS;
- }
-
// wrapper class to redirect output of standard ArchiveExtractCallback to serverLog
// and parse the extracted content
@@ -182,27 +142,22 @@ public class sevenzipParser extends AbstractParser implements Idiom {
// throw new IOException("Unknown Error");
}
} else try {
- AbstractParser.checkInterruption();
if (this.cfos != null) {
// parse the file
- Document theDoc;
+ Document[] theDocs;
// workaround for relative links in file, normally '#' shall be used behind the location, see
// below for reversion of the effects
final MultiProtocolURI url = MultiProtocolURI.newURL(doc.dc_source(), this.prefix + "/" + super.filePath);
final String mime = TextParser.mimeOf(super.filePath.substring(super.filePath.lastIndexOf('.') + 1));
- theDoc = TextParser.parseSource(url, mime, null, this.cfos.toByteArray());
+ theDocs = TextParser.parseSource(url, mime, null, this.cfos.toByteArray());
- this.doc.addSubDocument(theDoc);
+ this.doc.addSubDocuments(theDocs);
}
- } catch (final ParserException e) {
+ } catch (final Exception e) {
final IOException ex = new IOException("error parsing extracted content of " + super.filePath + ": " + e.getMessage());
ex.initCause(e);
throw ex;
- } catch (final InterruptedException e) {
- final IOException ex = new IOException("interrupted");
- ex.initCause(e);
- throw ex;
}
}
@@ -210,13 +165,6 @@ public class sevenzipParser extends AbstractParser implements Idiom {
public OutputStream GetStream(final int index, final int askExtractMode) throws IOException {
final SevenZipEntry item = super.archiveHandler.getEntry(index);
super.filePath = item.getName();
- try {
- AbstractParser.checkInterruption();
- } catch (final InterruptedException e) {
- final IOException ex = new IOException("interrupted");
- ex.initCause(e);
- throw ex;
- }
this.cfos = (item.isDirectory()) ? null : new ByteArrayOutputStream();
return this.cfos;
}
@@ -226,43 +174,4 @@ public class sevenzipParser extends AbstractParser implements Idiom {
}
}
- private static class SeekableByteArrayInputStream extends ByteArrayInputStream {
- public SeekableByteArrayInputStream(final byte[] buf) { super(buf); }
- public SeekableByteArrayInputStream(final byte[] buf, final int off, final int len) { super(buf, off, len); }
-
- public int getPosition() { return super.pos; }
- public void seekRelative(final int offset) { seekAbsolute(super.pos + offset); }
- public void seekAbsolute(final int offset) {
- if (offset > super.count)
- throw new IndexOutOfBoundsException(Integer.toString(offset));
- super.pos = offset;
- }
- }
-
- private static class ByteArrayIInStream extends IInStream {
-
- private final SeekableByteArrayInputStream sbais;
-
- public ByteArrayIInStream(final byte[] buffer) {
- this.sbais = new SeekableByteArrayInputStream(buffer);
- }
-
- public long Seek(final long offset, final int origin) {
- switch (origin) {
- case STREAM_SEEK_SET: this.sbais.seekAbsolute((int)offset); break;
- case STREAM_SEEK_CUR: this.sbais.seekRelative((int)offset); break;
- }
- return this.sbais.getPosition();
- }
-
- public int read() throws IOException {
- return this.sbais.read();
- }
-
- @Override
- public int read(final byte[] b, final int off, final int len) throws IOException {
- return this.sbais.read(b, off, len);
- }
- }
-
}
diff --git a/source/net/yacy/document/parser/swfParser.java b/source/net/yacy/document/parser/swfParser.java
index 050e2633f..aac095016 100644
--- a/source/net/yacy/document/parser/swfParser.java
+++ b/source/net/yacy/document/parser/swfParser.java
@@ -30,27 +30,19 @@ package net.yacy.document.parser;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Set;
import net.yacy.cora.document.MultiProtocolURI;
import net.yacy.document.AbstractParser;
import net.yacy.document.Document;
-import net.yacy.document.Idiom;
-import net.yacy.document.ParserException;
+import net.yacy.document.Parser;
import net.yacy.kelondro.logging.Log;
import pt.tumba.parser.swf.SWF2HTML;
-public class swfParser extends AbstractParser implements Idiom {
+public class swfParser extends AbstractParser implements Parser {
- /**
- * a list of mime types that are supported by this parser class
- * @see #getSupportedMimeTypes()
- */
- public static final Set<String> SUPPORTED_MIME_TYPES = new HashSet<String>();
- public static final Set<String> SUPPORTED_EXTENSIONS = new HashSet<String>();
- static {
+ public swfParser() {
+ super("Adobe Flash Parser");
SUPPORTED_EXTENSIONS.add("swf");
SUPPORTED_MIME_TYPES.add("application/x-shockwave-flash");
SUPPORTED_MIME_TYPES.add("application/x-shockwave-flash2-preview");
@@ -58,23 +50,11 @@ public class swfParser extends AbstractParser implements Idiom {
SUPPORTED_MIME_TYPES.add("image/vnd.rn-realflash");
}
- public swfParser() {
- super("Adobe Flash Parser");
- }
-
- public Set<String> supportedMimeTypes() {
- return SUPPORTED_MIME_TYPES;
- }
-
- public Set<String> supportedExtensions() {
- return SUPPORTED_EXTENSIONS;
- }
-
/*
* parses the source documents and returns a plasmaParserDocument containing
* all extracted information about the parsed document
*/
- public Document parse(final MultiProtocolURI location, final String mimeType, final String charset, final InputStream source) throws ParserException, InterruptedException {
+ public Document[] parse(final MultiProtocolURI location, final String mimeType, final String charset, final InputStream source) throws Parser.Failure, InterruptedException {
try {
final SWF2HTML swf2html = new SWF2HTML();
@@ -83,13 +63,13 @@ public class swfParser extends AbstractParser implements Idiom {
contents = swf2html.convertSWFToHTML(source);
} catch (NegativeArraySizeException e) {
Log.logException(e);
- throw new ParserException(e.getMessage(), location);
+ throw new Parser.Failure(e.getMessage(), location);
} catch (IOException e) {
Log.logException(e);
- throw new ParserException(e.getMessage(), location);
+ throw new Parser.Failure(e.getMessage(), location);
} catch (Exception e) {
Log.logException(e);
- throw new ParserException(e.getMessage(), location);
+ throw new Parser.Failure(e.getMessage(), location);
}
String url = null;
String urlnr = null;
@@ -119,7 +99,7 @@ public class swfParser extends AbstractParser implements Idiom {
}
// As the result of parsing this function must return a plasmaParserDocument object
- final Document theDoc = new Document(
+ return new Document[]{new Document(
location, // url of the source document
mimeType, // the documents mime type
"UTF-8", // charset of the document text
@@ -137,22 +117,15 @@ public class swfParser extends AbstractParser implements Idiom {
contents.getBytes("UTF-8"), // the parsed document text
anchors, // a map of extracted anchors
null,
- false); // a treeset of image URLs
- return theDoc;
+ false)}; // a treeset of image URLs
} catch (final Exception e) {
if (e instanceof InterruptedException) throw (InterruptedException) e;
- // if an unexpected error occures just log the error and raise a new ParserException
+ // if an unexpected error occures just log the error and raise a new Parser.Failure
final String errorMsg = "Unable to parse the swf document '" + location + "':" + e.getMessage();
- this.theLogger.logSevere(errorMsg);
- throw new ParserException(errorMsg, location);
+ this.log.logSevere(errorMsg);
+ throw new Parser.Failure(errorMsg, location);
}
}
- @Override
- public void reset() {
- // this code is executed if the parser class is returned into the parser pool
- super.reset();
-
- }
}
\ No newline at end of file
diff --git a/source/net/yacy/document/parser/tarParser.java b/source/net/yacy/document/parser/tarParser.java
index 107e543c8..3bf0081da 100644
--- a/source/net/yacy/document/parser/tarParser.java
+++ b/source/net/yacy/document/parser/tarParser.java
@@ -1,212 +1,98 @@
-//tarParser.java
-//------------------------
-//part of YaCy
-//(C) by Michael Peter Christen; [email protected]
-//first published on http://www.anomic.de
-//Frankfurt, Germany, 2005
-//
-//this file is contributed by Martin Thelian
-//
-// $LastChangedDate$
-// $LastChangedRevision$
-// $LastChangedBy$
-//
-//This program is free software; you can redistribute it and/or modify
-//it under the terms of the GNU General Public License as published by
-//the Free Software Foundation; either version 2 of the License, or
-//(at your option) any later version.
-//
-//This program is distributed in the hope that it will be useful,
-//but WITHOUT ANY WARRANTY; without even the implied warranty of
-//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-//GNU General Public License for more details.
-//
-//You should have received a copy of the GNU General Public License
-//along with this program; if not, write to the Free Software
-//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+/**
+ * tarParser
+ * Copyright 2010 by Michael Peter Christen, [email protected], Frankfurt am Main, Germany
+ * First released 29.6.2010 at http://yacy.net
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program in the file lgpl21.txt
+ * If not, see <http://www.gnu.org/licenses/>.
+ */
package net.yacy.document.parser;
import java.io.File;
+import java.io.IOException;
import java.io.InputStream;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.Map;
-import java.util.Set;
+import java.util.ArrayList;
+import java.util.List;
import java.util.zip.GZIPInputStream;
import net.yacy.cora.document.MultiProtocolURI;
import net.yacy.document.AbstractParser;
import net.yacy.document.Document;
-import net.yacy.document.Idiom;
+import net.yacy.document.Parser;
import net.yacy.document.TextParser;
-import net.yacy.document.ParserException;
-import net.yacy.document.parser.html.ContentScraper;
-import net.yacy.document.parser.html.ImageEntry;
-import net.yacy.kelondro.util.ByteBuffer;
import net.yacy.kelondro.util.FileUtils;
import org.apache.tools.tar.TarEntry;
import org.apache.tools.tar.TarInputStream;
+// this is a new implementation of this parser idiom using multiple documents as result set
-public class tarParser extends AbstractParser implements Idiom {
+public class tarParser extends AbstractParser implements Parser {
- /**
- * a list of mime types that are supported by this parser class
- * @see #getSupportedMimeTypes()
- */
- public static final Set<String> SUPPORTED_MIME_TYPES = new HashSet<String>();
- public static final Set<String> SUPPORTED_EXTENSIONS = new HashSet<String>();
- static {
+ public tarParser() {
+ super("Tape Archive File Parser");
SUPPORTED_EXTENSIONS.add("tar");
SUPPORTED_MIME_TYPES.add("application/x-tar");
SUPPORTED_MIME_TYPES.add("application/tar");
SUPPORTED_MIME_TYPES.add("applicaton/x-gtar");
SUPPORTED_MIME_TYPES.add("multipart/x-tar");
- }
-
- public tarParser() {
- super("Tape Archive File Parser");
- }
-
- public Set<String> supportedMimeTypes() {
- return SUPPORTED_MIME_TYPES;
}
- public Set<String> supportedExtensions() {
- return SUPPORTED_EXTENSIONS;
- }
-
- public Document parse(final MultiProtocolURI location, final String mimeType, final String charset, InputStream source) throws ParserException, InterruptedException {
+ public Document[] parse(final MultiProtocolURI url, final String mimeType, final String charset, InputStream source) throws Parser.Failure, InterruptedException {
- long docTextLength = 0;
- ByteBuffer docText = null;
- Document subDoc = null;
- try {
- docText = new ByteBuffer();
-
- /*
- * If the mimeType was not reported correcly by the webserve we
- * have to decompress it first
- */
- final String ext = location.getFileExtension().toLowerCase();
- if (ext.equals("gz") || ext.equals("tgz")) {
+ List<Document> docacc = new ArrayList<Document>();
+ Document[] subDocs = null;
+ final String ext = url.getFileExtension().toLowerCase();
+ if (ext.equals("gz") || ext.equals("tgz")) {
+ try {
source = new GZIPInputStream(source);
+ } catch (IOException e) {
+ throw new Parser.Failure("tar parser: " + e.getMessage(), url);
}
-
- // TODO: what about bzip ....
-
- final StringBuilder docKeywords = new StringBuilder();
- final StringBuilder docLongTitle = new StringBuilder();
- final LinkedList<String> docSections = new LinkedList<String>();
- final StringBuilder docAbstrct = new StringBuilder();
-
- final Map<MultiProtocolURI, String> docAnchors = new HashMap<MultiProtocolURI, String>();
- final HashMap<MultiProtocolURI, ImageEntry> docImages = new HashMap<MultiProtocolURI, ImageEntry>();
-
- // looping through the contained files
- TarEntry entry;
- final TarInputStream tin = new TarInputStream(source);
- while ((entry = tin.getNextEntry()) !=null) {
- // check for interruption
- checkInterruption();
-
- // skip directories
- if (entry.isDirectory()) continue;
- if (entry.getSize() <= 0) continue;
-
- // Get the short entry name
- final String entryName = entry.getName();
-
- // getting the entry file extension
- final int idx = entryName.lastIndexOf('.');
- final String entryExt = (idx > -1) ? entryName.substring(idx+1) : "";
-
- // trying to determine the mimeType per file extension
- final String entryMime = TextParser.mimeOf(entryExt);
-
- // getting the entry content
- File subDocTempFile = null;
+ }
+ TarEntry entry;
+ final TarInputStream tis = new TarInputStream(source);
+ File tmp = null;
+
+ // loop through the elements in the tar file and parse every single file inside
+ while (true) {
+ try {
+ if (tis.available() <= 0) break;
+ entry = tis.getNextEntry();
+ if (entry == null) break;
+ if (entry.isDirectory() || entry.getSize() <= 0) continue;
+ final String name = entry.getName();
+ final int idx = name.lastIndexOf('.');
+ final String mime = TextParser.mimeOf((idx > -1) ? name.substring(idx+1) : "");
try {
- // create the temp file
- subDocTempFile = createTempFile(entryName);
-
- // copy the data into the file
- FileUtils.copy(tin,subDocTempFile,entry.getSize());
-
- // check for interruption
- checkInterruption();
-
- // parsing the content
- subDoc = TextParser.parseSource(MultiProtocolURI.newURL(location,"#" + entryName),entryMime,null,subDocTempFile);
- } catch (final ParserException e) {
- this.theLogger.logInfo("Unable to parse tar file entry '" + entryName + "'. " + e.getMessage());
+ tmp = FileUtils.createTempFile(this.getClass(), name);
+ FileUtils.copy(tis, tmp, entry.getSize());
+ subDocs = TextParser.parseSource(MultiProtocolURI.newURL(url,"#" + name), mime, null, tmp);
+ } catch (final Parser.Failure e) {
+ log.logWarning("tar parser entry " + name + ": " + e.getMessage());
} finally {
- if (subDocTempFile != null) FileUtils.deletedelete(subDocTempFile);
+ if (tmp != null) FileUtils.deletedelete(tmp);
}
- if (subDoc == null) continue;
-
- // merging all documents together
- if (docKeywords.length() > 0) docKeywords.append(",");
- docKeywords.append(subDoc.dc_subject(','));
-
- if (docLongTitle.length() > 0) docLongTitle.append("\n");
- docLongTitle.append(subDoc.dc_title());
+ if (subDocs == null) continue;
- docSections.addAll(Arrays.asList(subDoc.getSectionTitles()));
-
- if (docAbstrct.length() > 0) docAbstrct.append("\n");
- docAbstrct.append(subDoc.dc_description());
-
- if (subDoc.getTextLength() > 0) {
- if (docTextLength > 0) docText.write('\n');
- docTextLength += FileUtils.copy(subDoc.getText(), docText);
- }
-
- //docAnchors.putAll(subDoc.getAnchors());
- ContentScraper.addAllImages(docImages, subDoc.getImages());
-
- // release subdocument
- subDoc.close();
- subDoc = null;
+ for (Document d: subDocs) docacc.add(d);
+ } catch (IOException e) {
+ log.logWarning("tar parser:" + e.getMessage());
+ break;
}
-
- Document result = new Document(
- location,
- mimeType,
- null,
- null,
- docKeywords.toString().split(" |,"),
- docLongTitle.toString(),
- "", // TODO: AUTHOR
- "", // TODO: publisher
- docSections.toArray(new String[docSections.size()]),
- docAbstrct.toString(),
- docText.getBytes(),
- docAnchors,
- docImages,
- false);
-
- return result;
- } catch (final Exception e) {
- if (e instanceof InterruptedException) throw (InterruptedException) e;
- if (e instanceof ParserException) throw (ParserException) e;
-
- if (subDoc != null) subDoc.close();
-
- // close the writer
- if (docText != null) try { docText.close(); } catch (final Exception ex) {/* ignore this */}
-
- throw new ParserException("Unexpected error while parsing tar resource. " + e.getMessage(),location);
}
- }
-
- @Override
- public void reset() {
- // Nothing todo here at the moment
- super.reset();
+ return docacc.toArray(new Document[docacc.size()]);
}
}
diff --git a/source/net/yacy/document/parser/torrentParser.java b/source/net/yacy/document/parser/torrentParser.java
index 7d3346e9c..8395de7ec 100644
--- a/source/net/yacy/document/parser/torrentParser.java
+++ b/source/net/yacy/document/parser/torrentParser.java
@@ -1,47 +1,38 @@
-// TorrentParser
-// (C) 2010 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany
-// first published 03.01.2010 on http://yacy.net
-//
-// This is a part of YaCy, a peer-to-peer based web search engine
-//
-// $LastChangedDate: 2009-09-23 23:26:14 +0200 (Mi, 23 Sep 2009) $
-// $LastChangedRevision: 6340 $
-// $LastChangedBy: low012 $
-//
-// LICENSE
-//
-// This program is free software; you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation; either version 2 of the License, or
-// (at your option) any later version.
-//
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU General Public License
-// along with this program; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-
+/**
+ * torrentParser.java
+ * Copyright 2010 by Michael Peter Christen, [email protected], Frankfurt am Main, Germany
+ * First released 03.01.2010 at http://yacy.net
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program in the file lgpl21.txt
+ * If not, see <http://www.gnu.org/licenses/>.
+ */
package net.yacy.document.parser;
+import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
-import java.util.HashSet;
import java.util.List;
import java.util.Map;
-import java.util.Set;
import net.yacy.cora.document.MultiProtocolURI;
import net.yacy.document.AbstractParser;
import net.yacy.document.Condenser;
import net.yacy.document.Document;
-import net.yacy.document.Idiom;
-import net.yacy.document.ParserException;
+import net.yacy.document.Parser;
import net.yacy.kelondro.data.word.Word;
import net.yacy.kelondro.util.BDecoder;
import net.yacy.kelondro.util.FileUtils;
@@ -49,43 +40,25 @@ import net.yacy.kelondro.util.BDecoder.BObject;
import net.yacy.kelondro.util.BDecoder.BType;
// a BT parser according to http://wiki.theory.org/BitTorrentSpecification
-public class torrentParser extends AbstractParser implements Idiom {
-
- /**
- * a list of mime types that are supported by this parser class
- * @see #getSupportedMimeTypes()
- */
- public static final Set<String> SUPPORTED_MIME_TYPES = new HashSet<String>();
- public static final Set<String> SUPPORTED_EXTENSIONS = new HashSet<String>();
- static {
- SUPPORTED_EXTENSIONS.add("torrent");
- SUPPORTED_MIME_TYPES.add("application/x-bittorrent");
- }
+public class torrentParser extends AbstractParser implements Parser {
public torrentParser() {
super("Torrent Metadata Parser");
+ SUPPORTED_EXTENSIONS.add("torrent");
+ SUPPORTED_MIME_TYPES.add("application/x-bittorrent");
}
- public Set<String> supportedMimeTypes() {
- return SUPPORTED_MIME_TYPES;
- }
-
- public Set<String> supportedExtensions() {
- return SUPPORTED_EXTENSIONS;
- }
-
- @Override
- public Document parse(MultiProtocolURI location, String mimeType, String charset, InputStream source) throws ParserException, InterruptedException {
+ public Document[] parse(MultiProtocolURI location, String mimeType, String charset, InputStream source) throws Parser.Failure, InterruptedException {
byte[] b = null;
try {
b = FileUtils.read(source);
} catch (IOException e1) {
- throw new ParserException(e1.toString(), location);
+ throw new Parser.Failure(e1.toString(), location);
}
BDecoder bd = new BDecoder(b);
BObject bo = bd.parse();
- if (bo == null) throw new ParserException("BDecoder.parse returned null", location);
- if (bo.getType() != BType.dictionary) throw new ParserException("BDecoder object is not a dictionary", location);
+ if (bo == null) throw new Parser.Failure("BDecoder.parse returned null", location);
+ if (bo.getType() != BType.dictionary) throw new Parser.Failure("BDecoder object is not a dictionary", location);
Map<String, BObject> map = bo.getMap();
BObject commento = map.get("comment");
String comment = (commento == null) ? "" : new String(commento.getString());
@@ -110,7 +83,7 @@ public class torrentParser extends AbstractParser implements Idiom {
if (nameo != null) name = new String(nameo.getString());
}
try {
- return new Document(
+ return new Document[]{new Document(
location,
mimeType,
charset,
@@ -124,30 +97,23 @@ public class torrentParser extends AbstractParser implements Idiom {
filenames.toString().getBytes(charset),
null,
null,
- false);
+ false)};
} catch (UnsupportedEncodingException e) {
- throw new ParserException("error in torrentParser, getBytes: " + e.getMessage(), location);
+ throw new Parser.Failure("error in torrentParser, getBytes: " + e.getMessage(), location);
}
}
-/* public Document(final DigestURI location, final String mimeType, final String charset, final Set<String> languages,
- final String[] keywords, final String title, final String author,
- final String[] sections, final String abstrct,
- final byte[] text, final Map<DigestURI, String> anchors, final HashMap<String, ImageEntry> images) {
- this(location, mimeType, charset, languages, keywords, title, author, sections, abstrct, (Object)text, anchors, images);
- }
- */
public static void main(String[] args) {
try {
byte[] b = FileUtils.read(new File(args[0]));
torrentParser parser = new torrentParser();
- Document d = parser.parse(new MultiProtocolURI("http://localhost/test.torrent"), null, "utf-8", b);
- Condenser c = new Condenser(d, true, true);
+ Document[] d = parser.parse(new MultiProtocolURI("http://localhost/test.torrent"), null, "utf-8", new ByteArrayInputStream(b));
+ Condenser c = new Condenser(d[0], true, true);
Map<String, Word> w = c.words();
for (Map.Entry<String, Word> e: w.entrySet()) System.out.println("Word: " + e.getKey() + " - " + e.getValue().posInText);
} catch (IOException e) {
e.printStackTrace();
- } catch (ParserException e) {
+ } catch (Parser.Failure e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
diff --git a/source/net/yacy/document/parser/vcfParser.java b/source/net/yacy/document/parser/vcfParser.java
index 06610ccf9..53ba78860 100644
--- a/source/net/yacy/document/parser/vcfParser.java
+++ b/source/net/yacy/document/parser/vcfParser.java
@@ -32,16 +32,13 @@ import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.util.HashMap;
-import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
-import java.util.Set;
import net.yacy.cora.document.MultiProtocolURI;
import net.yacy.document.AbstractParser;
import net.yacy.document.Document;
-import net.yacy.document.Idiom;
-import net.yacy.document.ParserException;
+import net.yacy.document.Parser;
import net.yacy.kelondro.order.Base64Order;
/**
@@ -49,39 +46,20 @@ import net.yacy.kelondro.order.Base64Order;
* @author theli
*
*/
-public class vcfParser extends AbstractParser implements Idiom {
+public class vcfParser extends AbstractParser implements Parser {
- /**
- * a list of mime types that are supported by this parser class
- * @see #getSupportedMimeTypes()
- *
- * TODO: support of x-mozilla-cpt and x-mozilla-html tags
- */
- public static final Set<String> SUPPORTED_MIME_TYPES = new HashSet<String>();
- public static final Set<String> SUPPORTED_EXTENSIONS = new HashSet<String>();
- static {
+ public vcfParser() {
+ super("vCard Parser");
SUPPORTED_EXTENSIONS.add("vcf");
- SUPPORTED_MIME_TYPES.add("text/x-vcard");
+ SUPPORTED_MIME_TYPES.add("text/x-vcard");
SUPPORTED_MIME_TYPES.add("application/vcard");
SUPPORTED_MIME_TYPES.add("application/x-versit");
SUPPORTED_MIME_TYPES.add("text/x-versit");
SUPPORTED_MIME_TYPES.add("text/x-vcalendar");
- }
-
- public vcfParser() {
- super("vCard Parser");
- }
-
- public Set<String> supportedMimeTypes() {
- return SUPPORTED_MIME_TYPES;
}
- public Set<String> supportedExtensions() {
- return SUPPORTED_EXTENSIONS;
- }
-
- public Document parse(final MultiProtocolURI url, final String mimeType, final String charset, final InputStream source) throws ParserException, InterruptedException {
-
+ public Document[] parse(final MultiProtocolURI url, final String mimeType, final String charset, final InputStream source) throws Parser.Failure, InterruptedException {
+
try {
final StringBuilder parsedTitle = new StringBuilder();
final StringBuilder parsedDataText = new StringBuilder();
@@ -96,10 +74,8 @@ public class vcfParser extends AbstractParser implements Idiom {
? new BufferedReader(new InputStreamReader(source,charset))
: new BufferedReader(new InputStreamReader(source));
while (true) {
- // check for interruption
- checkInterruption();
- // getting the next line
+ // get the next line
if (!useLastLine) {
line = inputReader.readLine();
} else {
@@ -214,7 +190,7 @@ public class vcfParser extends AbstractParser implements Idiom {
}
} else {
- if (theLogger.isFinest()) this.theLogger.logFinest("Invalid data in vcf file" +
+ if (log.isFinest()) this.log.logFinest("Invalid data in vcf file" +
"\n\tURL: " + url +
"\n\tLine: " + line +
"\n\tLine-Nr: " + lineNr);
@@ -223,7 +199,7 @@ public class vcfParser extends AbstractParser implements Idiom {
final String[] sections = parsedNames.toArray(new String[parsedNames.size()]);
final byte[] text = parsedDataText.toString().getBytes();
- final Document theDoc = new Document(
+ return new Document[]{new Document(
url, // url of the source document
mimeType, // the documents mime type
null, // charset
@@ -237,22 +213,15 @@ public class vcfParser extends AbstractParser implements Idiom {
text, // the parsed document text
anchors, // a map of extracted anchors
null, // a treeset of image URLs
- false);
- return theDoc;
+ false)};
} catch (final Exception e) {
if (e instanceof InterruptedException) throw (InterruptedException) e;
- if (e instanceof ParserException) throw (ParserException) e;
+ if (e instanceof Parser.Failure) throw (Parser.Failure) e;
- throw new ParserException("Unexpected error while parsing vcf resource. " + e.getMessage(),url);
+ throw new Parser.Failure("Unexpected error while parsing vcf resource. " + e.getMessage(),url);
}
}
- @Override
- public void reset() {
- // Nothing todo here at the moment
- super.reset();
- }
-
public static final String decodeQuotedPrintable(final String s) {
if (s == null) return null;
final byte[] b = s.getBytes();
diff --git a/source/net/yacy/document/parser/vsdParser.java b/source/net/yacy/document/parser/vsdParser.java
index 44b601394..33c04a0e8 100644
--- a/source/net/yacy/document/parser/vsdParser.java
+++ b/source/net/yacy/document/parser/vsdParser.java
@@ -28,29 +28,21 @@
package net.yacy.document.parser;
import java.io.InputStream;
-import java.util.HashSet;
-import java.util.Set;
import net.yacy.cora.document.MultiProtocolURI;
import net.yacy.document.AbstractParser;
import net.yacy.document.Document;
-import net.yacy.document.Idiom;
-import net.yacy.document.ParserException;
+import net.yacy.document.Parser;
import net.yacy.kelondro.logging.Log;
import org.apache.poi.hdgf.extractor.VisioTextExtractor;
import org.apache.poi.hpsf.SummaryInformation;
-public class vsdParser extends AbstractParser implements Idiom {
+public class vsdParser extends AbstractParser implements Parser {
- /**
- * a list of mime types that are supported by this parser class
- * @see #getSupportedMimeTypes()
- */
- public static final Set<String> SUPPORTED_MIME_TYPES = new HashSet<String>();
- public static final Set<String> SUPPORTED_EXTENSIONS = new HashSet<String>();
- static {
+ public vsdParser() {
+ super("Microsoft Visio Parser");
SUPPORTED_EXTENSIONS.add("vsd");
SUPPORTED_EXTENSIONS.add("vss");
SUPPORTED_EXTENSIONS.add("vst");
@@ -65,24 +57,12 @@ public class vsdParser extends AbstractParser implements Idiom {
SUPPORTED_MIME_TYPES.add("image/x-vsd");
SUPPORTED_MIME_TYPES.add("zz-application/zz-winassoc-vsd");
}
-
- public vsdParser() {
- super("Microsoft Visio Parser");
- }
-
- public Set<String> supportedMimeTypes() {
- return SUPPORTED_MIME_TYPES;
- }
-
- public Set<String> supportedExtensions() {
- return SUPPORTED_EXTENSIONS;
- }
/*
* parses the source documents and returns a plasmaParserDocument containing
* all extracted information about the parsed document
*/
- public Document parse(final MultiProtocolURI location, final String mimeType, final String charset, final InputStream source) throws ParserException, InterruptedException {
+ public Document[] parse(final MultiProtocolURI location, final String mimeType, final String charset, final InputStream source) throws Parser.Failure, InterruptedException {
Document theDoc = null;
@@ -120,7 +100,7 @@ public class vsdParser extends AbstractParser implements Idiom {
}
// As the result of parsing this function must return a plasmaParserDocument object
- theDoc = new Document(
+ return new Document[]{new Document(
location, // url of the source document
mimeType, // the documents mime type
"UTF-8", // charset of the document text
@@ -134,29 +114,22 @@ public class vsdParser extends AbstractParser implements Idiom {
contents.getBytes("UTF-8"), // the parsed document text
null, // a map of extracted anchors
null, // a treeset of image URLs
- false);
- return theDoc;
+ false)};
} catch (final Exception e) {
if (e instanceof InterruptedException) throw (InterruptedException) e;
// if an unexpected error occures just log the error and raise a new ParserException
final String errorMsg = "Unable to parse the vsd document '" + location + "':" + e.getMessage();
- this.theLogger.logSevere(errorMsg);
- throw new ParserException(errorMsg, location);
+ this.log.logSevere(errorMsg);
+ throw new Parser.Failure(errorMsg, location);
} finally {
if (theDoc == null) {
- // if an unexpected error occures just log the error and raise a new ParserException
+ // if an unexpected error occures just log the error and raise a new Parser.Failure
final String errorMsg = "Unable to parse the vsd document '" + location + "': possibly out of memory";
- this.theLogger.logSevere(errorMsg);
- throw new ParserException(errorMsg, location);
+ this.log.logSevere(errorMsg);
+ throw new Parser.Failure(errorMsg, location);
}
}
}
- @Override
- public void reset() {
- // this code is executed if the parser class is returned into the parser pool
- super.reset();
-
- }
}
\ No newline at end of file
diff --git a/source/net/yacy/document/parser/xlsParser.java b/source/net/yacy/document/parser/xlsParser.java
index 0667c2025..63d9be29d 100644
--- a/source/net/yacy/document/parser/xlsParser.java
+++ b/source/net/yacy/document/parser/xlsParser.java
@@ -28,14 +28,11 @@
package net.yacy.document.parser;
import java.io.InputStream;
-import java.util.HashSet;
-import java.util.Set;
import net.yacy.cora.document.MultiProtocolURI;
import net.yacy.document.AbstractParser;
import net.yacy.document.Document;
-import net.yacy.document.Idiom;
-import net.yacy.document.ParserException;
+import net.yacy.document.Parser;
import net.yacy.kelondro.logging.Log;
import org.apache.poi.hssf.eventusermodel.HSSFEventFactory;
@@ -47,15 +44,10 @@ import org.apache.poi.hssf.record.SSTRecord;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
-public class xlsParser extends AbstractParser implements Idiom {
-
- /**
- * a list of mime types that are supported by this parser class
- * @see #getSupportedMimeTypes()
- */
- public static final Set<String> SUPPORTED_MIME_TYPES = new HashSet<String>();
- public static final Set<String> SUPPORTED_EXTENSIONS = new HashSet<String>();
- static {
+public class xlsParser extends AbstractParser implements Parser {
+
+ public xlsParser(){
+ super("Microsoft Excel Parser");
SUPPORTED_EXTENSIONS.add("xls");
SUPPORTED_EXTENSIONS.add("xla");
SUPPORTED_MIME_TYPES.add("application/msexcel");
@@ -66,37 +58,18 @@ public class xlsParser extends AbstractParser implements Idiom {
SUPPORTED_MIME_TYPES.add("application/x-ms-excel");
SUPPORTED_MIME_TYPES.add("application/x-dos_ms_excel");
SUPPORTED_MIME_TYPES.add("application/xls");
- }
-
- public xlsParser(){
- super("Microsoft Excel Parser");
}
/*
* parses the source documents and returns a plasmaParserDocument containing
* all extracted information about the parsed document
*/
- public Document parse(final MultiProtocolURI location, final String mimeType,
- final String charset, final InputStream source) throws ParserException,
+ public Document[] parse(final MultiProtocolURI location, final String mimeType,
+ final String charset, final InputStream source) throws Parser.Failure,
InterruptedException {
return new XLSHSSFListener().parse(location, mimeType, charset, source);
}
- public Set<String> supportedMimeTypes() {
- return SUPPORTED_MIME_TYPES;
- }
-
- public Set<String> supportedExtensions() {
- return SUPPORTED_EXTENSIONS;
- }
-
- @Override
- public void reset(){
- //nothing to do
- super.reset();
- }
-
-
public class XLSHSSFListener implements HSSFListener {
//StringBuilder for parsed text
@@ -111,8 +84,8 @@ public class xlsParser extends AbstractParser implements Idiom {
* parses the source documents and returns a Document containing
* all extracted information about the parsed document
*/
- public Document parse(final MultiProtocolURI location, final String mimeType,
- final String charset, final InputStream source) throws ParserException,
+ public Document[] parse(final MultiProtocolURI location, final String mimeType,
+ final String charset, final InputStream source) throws Parser.Failure,
InterruptedException {
try {
@@ -138,7 +111,7 @@ public class xlsParser extends AbstractParser implements Idiom {
* create the plasmaParserDocument for the database
* and set shortText and bodyText properly
*/
- final Document theDoc = new Document(
+ return new Document[]{new Document(
location,
mimeType,
"UTF-8",
@@ -152,17 +125,16 @@ public class xlsParser extends AbstractParser implements Idiom {
contents.getBytes("UTF-8"),
null,
null,
- false);
- return theDoc;
+ false)};
} catch (final Exception e) {
if (e instanceof InterruptedException) throw (InterruptedException) e;
/*
- * an unexpected error occurred, log it and throw a ParserException
+ * an unexpected error occurred, log it and throw a Parser.Failure
*/
Log.logException(e);
final String errorMsg = "Unable to parse the xls document '" + location + "':" + e.getMessage();
- throw new ParserException(errorMsg, location);
+ throw new Parser.Failure(errorMsg, location);
}
}
diff --git a/source/net/yacy/document/parser/zipParser.java b/source/net/yacy/document/parser/zipParser.java
index 15f16f10c..548d52d77 100644
--- a/source/net/yacy/document/parser/zipParser.java
+++ b/source/net/yacy/document/parser/zipParser.java
@@ -1,64 +1,46 @@
-//zipParser.java
-//------------------------
-//part of YaCy
-//(C) by Michael Peter Christen; [email protected]
-//first published on http://www.anomic.de
-//Frankfurt, Germany, 2005
-//
-//this file is contributed by Martin Thelian
-//
-// $LastChangedDate$
-// $LastChangedRevision$
-// $LastChangedBy$
-//
-//This program is free software; you can redistribute it and/or modify
-//it under the terms of the GNU General Public License as published by
-//the Free Software Foundation; either version 2 of the License, or
-//(at your option) any later version.
-//
-//This program is distributed in the hope that it will be useful,
-//but WITHOUT ANY WARRANTY; without even the implied warranty of
-//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-//GNU General Public License for more details.
-//
-//You should have received a copy of the GNU General Public License
-//along with this program; if not, write to the Free Software
-//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+/**
+ * zipParser
+ * Copyright 2010 by Michael Peter Christen, [email protected], Frankfurt am Main, Germany
+ * First released 29.6.2010 at http://yacy.net
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program in the file lgpl21.txt
+ * If not, see <http://www.gnu.org/licenses/>.
+ */
package net.yacy.document.parser;
import java.io.File;
+import java.io.IOException;
import java.io.InputStream;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.Map;
-import java.util.Set;
+import java.util.ArrayList;
+import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import net.yacy.cora.document.MultiProtocolURI;
import net.yacy.document.AbstractParser;
import net.yacy.document.Document;
-import net.yacy.document.Idiom;
+import net.yacy.document.Parser;
import net.yacy.document.TextParser;
-import net.yacy.document.ParserException;
-import net.yacy.document.parser.html.ContentScraper;
-import net.yacy.document.parser.html.ImageEntry;
-import net.yacy.kelondro.util.ByteBuffer;
import net.yacy.kelondro.util.FileUtils;
+// this is a new implementation of this parser idiom using multiple documents as result set
-public class zipParser extends AbstractParser implements Idiom {
+public class zipParser extends AbstractParser implements Parser {
- /**
- * a list of mime types that are supported by this parser class
- * @see #getSupportedMimeTypes()
- */
- public static final Set<String> SUPPORTED_MIME_TYPES = new HashSet<String>();
- public static final Set<String> SUPPORTED_EXTENSIONS = new HashSet<String>();
- static {
+ public zipParser() {
+ super("ZIP File Parser");
SUPPORTED_EXTENSIONS.add("zip");
SUPPORTED_EXTENSIONS.add("jar");
SUPPORTED_EXTENSIONS.add("apk"); // Android package
@@ -70,132 +52,42 @@ public class zipParser extends AbstractParser implements Idiom {
SUPPORTED_MIME_TYPES.add("multipart/x-zip");
SUPPORTED_MIME_TYPES.add("application/java-archive");
SUPPORTED_MIME_TYPES.add("application/vnd.android.package-archive");
- }
-
- public zipParser() {
- super("ZIP File Parser");
- }
-
- public Set<String> supportedMimeTypes() {
- return SUPPORTED_MIME_TYPES;
- }
-
- public Set<String> supportedExtensions() {
- return SUPPORTED_EXTENSIONS;
}
- public Document parse(final MultiProtocolURI location, final String mimeType, final String charset, final InputStream source) throws ParserException, InterruptedException {
+ public Document[] parse(final MultiProtocolURI url, final String mimeType, final String charset, final InputStream source) throws Parser.Failure, InterruptedException {
+ Document[] docs = null;
+ List<Document> docacc = new ArrayList<Document>();
+ ZipEntry entry;
+ final ZipInputStream zis = new ZipInputStream(source);
+ File tmp = null;
- long docTextLength = 0;
- ByteBuffer docText = null;
- Document subDoc = null;
- try {
- docText = new ByteBuffer();
-
- final StringBuilder docKeywords = new StringBuilder();
- final StringBuilder docLongTitle = new StringBuilder();
- final LinkedList<String> docSections = new LinkedList<String>();
- final StringBuilder docAbstrct = new StringBuilder();
- final Map<MultiProtocolURI, String> docAnchors = new HashMap<MultiProtocolURI, String>();
- final HashMap<MultiProtocolURI, ImageEntry> docImages = new HashMap<MultiProtocolURI, ImageEntry>();
-
- // looping through the contained files
- ZipEntry entry;
- final ZipInputStream zippedContent = new ZipInputStream(source);
- while ((entry = zippedContent.getNextEntry()) !=null) {
- // check for interruption
- checkInterruption();
-
- // skip directories
- if (entry.isDirectory()) continue;
- if (entry.getSize() <= 0) continue;
-
- // Get the entry name
- final String entryName = entry.getName();
- final int idx = entryName.lastIndexOf('.');
-
- // getting the file extension
- final String entryExt = (idx > -1) ? entryName.substring(idx+1) : "";
-
- // trying to determine the mimeType per file extension
- final String entryMime = TextParser.mimeOf(entryExt);
-
- // parsing the content
- File subDocTempFile = null;
+ // loop through the elements in the zip file and parse every single file inside
+ while (true) {
+ try {
+ if (zis.available() <= 0) break;
+ entry = zis.getNextEntry();
+ if (entry == null) break;
+ if (entry.isDirectory() || entry.getSize() <= 0) continue;
+ final String name = entry.getName();
+ final int idx = name.lastIndexOf('.');
+ final String mime = TextParser.mimeOf((idx >= 0) ? name.substring(idx + 1) : "");
try {
- // create the temp file
- subDocTempFile = createTempFile(entryName);
-
- // copy the data into the file
- FileUtils.copy(zippedContent,subDocTempFile,entry.getSize());
-
- // parsing the zip file entry
- subDoc = TextParser.parseSource(MultiProtocolURI.newURL(location,"#" + entryName),entryMime,null, subDocTempFile);
- } catch (final ParserException e) {
- this.theLogger.logInfo("Unable to parse zip file entry '" + entryName + "'. " + e.getMessage());
+ tmp = FileUtils.createTempFile(this.getClass(), name);
+ FileUtils.copy(zis, tmp, entry.getSize());
+ docs = TextParser.parseSource(MultiProtocolURI.newURL(url, "#" + name), mime, null, tmp);
+ } catch (final Parser.Failure e) {
+ log.logWarning("ZIP parser entry " + name + ": " + e.getMessage());
} finally {
- if (subDocTempFile != null) FileUtils.deletedelete(subDocTempFile);
- }
- if (subDoc == null) continue;
-
- // merging all documents together
- if (docKeywords.length() > 0) docKeywords.append(",");
- docKeywords.append(subDoc.dc_subject(','));
-
- if (docLongTitle.length() > 0) docLongTitle.append("\n");
- docLongTitle.append(subDoc.dc_title());
-
- docSections.addAll(Arrays.asList(subDoc.getSectionTitles()));
-
- if (docAbstrct.length() > 0) docAbstrct.append("\n");
- docAbstrct.append(subDoc.dc_description());
-
- if (subDoc.getTextLength() > 0) {
- if (docTextLength > 0) docText.write('\n');
- docTextLength += FileUtils.copy(subDoc.getText(), docText);
+ if (tmp != null) FileUtils.deletedelete(tmp);
}
-
- //docAnchors.putAll(subDoc.getAnchors());
- ContentScraper.addAllImages(docImages, subDoc.getImages());
-
- // release subdocument
- subDoc.close();
- subDoc = null;
+ if (docs == null) continue;
+ for (Document d: docs) docacc.add(d);
+ } catch (IOException e) {
+ log.logWarning("ZIP parser:" + e.getMessage());
+ break;
}
-
-
- Document result = new Document(
- location,
- mimeType,
- null,
- null,
- docKeywords.toString().split(" |,"),
- docLongTitle.toString(),
- "", // TODO: AUTHOR
- "", // TODO: Publisher
- docSections.toArray(new String[docSections.size()]),
- docAbstrct.toString(),
- docText.getBytes(),
- docAnchors,
- docImages,
- false);
- return result;
- } catch (final Exception e) {
- if (e instanceof InterruptedException) throw (InterruptedException) e;
- if (e instanceof ParserException) throw (ParserException) e;
-
- if (subDoc != null) subDoc.close();
-
- // close the writer
- if (docText != null) try { docText.close(); } catch (final Exception ex) {/* ignore this */}
-
- throw new ParserException("Unexpected error while parsing zip resource. " + e.getClass().getName() + ": "+ e.getMessage(),location);
}
- }
-
- @Override
- public void reset() {
- // Nothing todo here at the moment
- super.reset();
+ if (docacc.size() == 0) return null;
+ return docacc.toArray(new Document[docacc.size()]);
}
}
diff --git a/source/net/yacy/kelondro/util/FileUtils.java b/source/net/yacy/kelondro/util/FileUtils.java
index a71de7f29..1f90bbb19 100644
--- a/source/net/yacy/kelondro/util/FileUtils.java
+++ b/source/net/yacy/kelondro/util/FileUtils.java
@@ -821,14 +821,25 @@ public final class FileUtils {
}
}
- public static void main(final String[] args) {
- try {
- writeAndGZip("ein zwei drei, Zauberei".getBytes(), new File("zauberei.txt.gz"));
- } catch (final IOException e) {
- Log.logException(e);
- }
+ public static final File createTempFile(@SuppressWarnings("rawtypes") Class classObj, final String name) throws IOException {
+ String parserClassName = classObj.getName();
+ int idx = parserClassName.lastIndexOf('.');
+ if (idx != -1) {
+ parserClassName = parserClassName.substring(idx+1);
+ }
+
+ // get the file extension
+ idx = name.lastIndexOf('/');
+ final String fileName = (idx != -1) ? name.substring(idx+1) : name;
+
+ idx = fileName.lastIndexOf('.');
+ final String fileExt = (idx > -1) ? fileName.substring(idx+1) : "";
+
+ // create the temp file
+ final File tempFile = File.createTempFile(parserClassName + "_" + ((idx>-1)?fileName.substring(0,idx):fileName), (fileExt.length()>0)?"."+fileExt:fileExt);
+ return tempFile;
}
-
+
/**
* copies the input stream to one output stream (byte per byte)
* @param in
@@ -967,4 +978,13 @@ public final class FileUtils {
if (path.exists()) Log.logSevere("FileUtils", "cannot delete file " + p);
}
}
+
+ public static void main(final String[] args) {
+ try {
+ writeAndGZip("ein zwei drei, Zauberei".getBytes(), new File("zauberei.txt.gz"));
+ } catch (final IOException e) {
+ Log.logException(e);
+ }
+ }
+
}
diff --git a/source/net/yacy/repository/LoaderDispatcher.java b/source/net/yacy/repository/LoaderDispatcher.java
index cc8bd07b0..ac2b0e884 100644
--- a/source/net/yacy/repository/LoaderDispatcher.java
+++ b/source/net/yacy/repository/LoaderDispatcher.java
@@ -40,8 +40,8 @@ import java.util.concurrent.ConcurrentHashMap;
import net.yacy.cora.document.MultiProtocolURI;
import net.yacy.document.Document;
+import net.yacy.document.Parser;
import net.yacy.document.TextParser;
-import net.yacy.document.ParserException;
import net.yacy.document.parser.html.ContentScraper;
import net.yacy.document.parser.html.TransformerWriter;
import net.yacy.kelondro.data.meta.DigestURI;
@@ -277,7 +277,7 @@ public final class LoaderDispatcher {
return entry.getContent();
}
- public Document loadDocument(final Request request, final CrawlProfile.CacheStrategy cacheStrategy, final int timeout, long maxFileSize) throws IOException, ParserException {
+ public Document[] loadDocuments(final Request request, final CrawlProfile.CacheStrategy cacheStrategy, final int timeout, long maxFileSize) throws IOException, Parser.Failure {
// load resource
final Response response = load(request, cacheStrategy, maxFileSize);
@@ -320,23 +320,19 @@ public final class LoaderDispatcher {
if (resource == null) throw new IOException("resource == null");
if (responseHeader == null) throw new IOException("responseHeader == null");
- Document document = null;
+ Document[] documents = null;
String supportError = TextParser.supports(url, responseHeader.mime());
if (supportError != null) throw new IOException("no parser support: " + supportError);
try {
- document = TextParser.parseSource(url, responseHeader.mime(), responseHeader.getCharacterEncoding(), resource.length, new ByteArrayInputStream(resource));
- if (document == null) throw new IOException("document == null");
- } catch (final ParserException e) {
+ documents = TextParser.parseSource(url, responseHeader.mime(), responseHeader.getCharacterEncoding(), resource.length, new ByteArrayInputStream(resource));
+ if (documents == null) throw new IOException("document == null");
+ } catch (final Exception e) {
throw new IOException("parser error: " + e.getMessage());
- } catch (InterruptedException e) {
- throw new IOException("interrupted");
} finally {
resource = null;
}
- Map<MultiProtocolURI, String> result = document.getHyperlinks();
- document.close();
- return result;
+ return Document.getHyperlinks(documents);
}
public synchronized void cleanupAccessTimeTable(long timeout) {
diff --git a/test/de/anomic/document/ParserTest.java b/test/de/anomic/document/ParserTest.java
index 11d893abb..61901fcb6 100644
--- a/test/de/anomic/document/ParserTest.java
+++ b/test/de/anomic/document/ParserTest.java
@@ -3,6 +3,7 @@ package de.anomic.document;
import static org.junit.Assert.*;
import static org.junit.matchers.JUnitMatchers.*;
import net.yacy.document.Document;
+import net.yacy.document.Parser;
import net.yacy.document.TextParser;
import net.yacy.kelondro.data.meta.DigestURI;
@@ -10,15 +11,17 @@ import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
import java.io.Reader;
import java.io.InputStreamReader;
+import java.io.UnsupportedEncodingException;
+import java.net.MalformedURLException;
public class ParserTest {
- @Test public void testParsers() throws java.io.FileNotFoundException, java.lang.InterruptedException,
- net.yacy.document.ParserException, java.net.MalformedURLException,
- java.io.UnsupportedEncodingException, java.io.IOException {
+ @Test public void testParsers() throws FileNotFoundException, Parser.Failure, MalformedURLException, UnsupportedEncodingException, IOException {
String[][] testFiles = new String[][] {
// meaning: filename in test/parsertest, mimetype, title, creator, description,
new String[]{"umlaute_windows.docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "In München steht ein Hofbräuhaus, dort gibt es Bier in Maßkrügen", "", ""},
@@ -37,19 +40,20 @@ public class ParserTest {
String mimetype = testFiles[i][1];
DigestURI url = new DigestURI("http://localhost/"+filename);
- Document doc = TextParser.parseSource(url, mimetype, null, file.length(), new FileInputStream(file));
- Reader content = new InputStreamReader(doc.getText(), doc.getCharset());
- StringBuilder str = new StringBuilder();
- int c;
- while( (c = content.read()) != -1 )
- str.append((char)c);
-
- System.out.println("Parsed " + filename + ": " + str);
- assertThat(str.toString(), containsString("In München steht ein Hofbräuhaus, dort gibt es Bier in Maßkrügen"));
- assertThat(doc.dc_title(), containsString(testFiles[i][2]));
- assertThat(doc.dc_creator(), containsString(testFiles[i][3]));
- assertThat(doc.dc_description(), containsString(testFiles[i][4]));
-
+ Document[] docs = TextParser.parseSource(url, mimetype, null, file.length(), new FileInputStream(file));
+ for (Document doc: docs) {
+ Reader content = new InputStreamReader(doc.getText(), doc.getCharset());
+ StringBuilder str = new StringBuilder();
+ int c;
+ while( (c = content.read()) != -1 )
+ str.append((char)c);
+
+ System.out.println("Parsed " + filename + ": " + str);
+ assertThat(str.toString(), containsString("In München steht ein Hofbräuhaus, dort gibt es Bier in Maßkrügen"));
+ assertThat(doc.dc_title(), containsString(testFiles[i][2]));
+ assertThat(doc.dc_creator(), containsString(testFiles[i][3]));
+ assertThat(doc.dc_description(), containsString(testFiles[i][4]));
+ }
}
}
}