Skip to content

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

refactoring and new architecture to store the files of the web cache: - files are not stored any more as individual files - a new database structure using BLOBHeap files stores many cache entries in common files - all file-writing procedures had been migrated to generate byte[] objects which are written with the new database methods

orbiter826ca797358a
diff --git a/htroot/CacheAdmin_p.java b/htroot/CacheAdmin_p.java
index 5944b5f62..9c9115b5b 100644
--- a/htroot/CacheAdmin_p.java
+++ b/htroot/CacheAdmin_p.java
@@ -35,6 +35,7 @@ import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.Writer;
+import java.net.MalformedURLException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Iterator;
@@ -68,7 +69,7 @@ public class CacheAdmin_p {
private static final int SecurityError = 4;
public static final class Filter implements FilenameFilter {
- private static final String EXCLUDE_NAME = plasmaHTCache.DB_NAME;
+ private static final String EXCLUDE_NAME = plasmaHTCache.RESPONSE_HEADER_DB_NAME;
private final File EXCLUDE_DIR;
public Filter(final File path) { this.EXCLUDE_DIR = path; }
public boolean accept(final File dir, final String name) {
@@ -82,7 +83,6 @@ public class CacheAdmin_p {
final String action = ((post == null) ? "info" : post.get("action", "info"));
String pathString = ((post == null) ? "" : post.get("path", "/"));
-// String pathString = ((post == null) ? "" : post.get("path", "/").replaceAll("//", "/")); // where is the BUG ?
// don't leave the htCachePath
File file = new File(switchboard.htCachePath, pathString);
@@ -100,7 +100,12 @@ public class CacheAdmin_p {
final StringBuffer tree = new StringBuffer();
final StringBuffer info = new StringBuffer();
- final yacyURL url = plasmaHTCache.getURL(file);
+ yacyURL url = null;
+ try {
+ url = new yacyURL(pathString, null);
+ } catch (MalformedURLException e1) {
+ e1.printStackTrace();
+ }
String urlstr = "";
@@ -228,7 +233,7 @@ public class CacheAdmin_p {
}
}
- prop.putNum("cachesize", plasmaHTCache.curCacheSize/1024);
+ prop.putNum("cachesize", (plasmaHTCache.fileDBSize() + plasmaHTCache.responseHeaderDBSize()) / 1024);
prop.putNum("cachemax", plasmaHTCache.maxCacheSize/1024);
prop.put("path", path.toString());
prop.putHTML("info_info", info.toString());
diff --git a/htroot/CrawlResults.java b/htroot/CrawlResults.java
index 58edd793b..054f346ef 100644
--- a/htroot/CrawlResults.java
+++ b/htroot/CrawlResults.java
@@ -32,7 +32,6 @@ import java.util.Locale;
import de.anomic.http.httpRequestHeader;
import de.anomic.index.indexURLReference;
-import de.anomic.plasma.plasmaHTCache;
import de.anomic.plasma.plasmaSwitchboard;
import de.anomic.server.serverObjects;
import de.anomic.server.serverSwitch;
@@ -168,7 +167,7 @@ public class CrawlResults {
boolean dark = true;
String urlHash, initiatorHash, executorHash;
- String cachepath, urlstr, urltxt;
+ String urlstr, urltxt;
yacySeed initiatorSeed, executorSeed;
indexURLReference urle;
indexURLReference.Components comp;
@@ -184,13 +183,11 @@ public class CrawlResults {
serverLog.logWarning("PLASMA", "CrawlResults: URL not in index for crawl result "+ i +" with hash "+ urlHash);
urlstr = null;
urltxt = null;
- cachepath = null;
comp = null;
} else {
comp = urle.comp();
urlstr = comp.url().toNormalform(false, true);
urltxt = nxTools.shortenURLString(urlstr, 72); // shorten the string text like a URL
- cachepath = plasmaHTCache.getCachePath(new yacyURL(urlstr, null)).toString().replace('\\', '/').substring(plasmaHTCache.cachePath.toString().length() + 1);
}
initiatorSeed = sb.webIndex.seedDB.getConnected(initiatorHash);
executorSeed = sb.webIndex.seedDB.getConnected(executorHash);
@@ -226,9 +223,6 @@ public class CrawlResults {
if (showTitle) {
prop.put("table_indexed_" + cnt + "_showTitle", (showTitle) ? "1" : "0");
- if (cachepath == null) {
- prop.put("table_indexed_" + cnt + "_showTitle_available", "0");
- } else {
prop.put("table_indexed_" + cnt + "_showTitle_available", "1");
if (comp == null || comp.dc_title() == null || comp.dc_title().trim().length() == 0)
@@ -238,23 +232,18 @@ public class CrawlResults {
prop.putHTML("table_indexed_" + cnt + "_showTitle_available_nodescr_urldescr", comp.dc_title());
}
- prop.put("table_indexed_" + cnt + "_showTitle_available_cachepath", cachepath);
+ prop.put("table_indexed_" + cnt + "_showTitle_available_cachepath", "");
prop.putHTML("table_indexed_" + cnt + "_showTitle_available_urltitle", urlstr);
- }
} else
prop.put("table_indexed_" + cnt + "_showTitle", "0");
if (showURL) {
prop.put("table_indexed_" + cnt + "_showURL", "1");
- if (cachepath == null) {
- prop.put("table_indexed_" + cnt + "_showURL_available", "0");
- } else {
prop.put("table_indexed_" + cnt + "_showURL_available", "1");
- prop.put("table_indexed_" + cnt + "_showURL_available_cachepath", cachepath);
+ prop.put("table_indexed_" + cnt + "_showURL_available_cachepath", "");
prop.putHTML("table_indexed_" + cnt + "_showURL_available_urltitle", urlstr);
prop.put("table_indexed_" + cnt + "_showURL_available_url", urltxt);
- }
} else
prop.put("table_indexed_" + cnt + "_showURL", "0");
diff --git a/htroot/IndexCreateIndexingQueue_p.java b/htroot/IndexCreateIndexingQueue_p.java
index 603d927bf..dbb5ad876 100644
--- a/htroot/IndexCreateIndexingQueue_p.java
+++ b/htroot/IndexCreateIndexingQueue_p.java
@@ -67,7 +67,7 @@ public class IndexCreateIndexingQueue_p {
IndexingStack.QueueEntry entry = null;
while ((entry = sb.webIndex.queuePreStack.pop()) != null) {
if ((entry != null) && (entry.profile() != null) && (!(entry.profile().storeHTCache()))) {
- plasmaHTCache.deleteURLfromCache(entry.url(), false);
+ plasmaHTCache.deleteFromCache(entry.url());
}
}
sb.webIndex.queuePreStack.clear(); // reset file to clean up content completely
diff --git a/source/de/anomic/crawler/FTPLoader.java b/source/de/anomic/crawler/FTPLoader.java
index 4a251ef72..35a000d02 100644
--- a/source/de/anomic/crawler/FTPLoader.java
+++ b/source/de/anomic/crawler/FTPLoader.java
@@ -28,10 +28,7 @@
package de.anomic.crawler;
import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileOutputStream;
import java.io.PrintStream;
-import java.io.PrintWriter;
import java.util.Date;
import de.anomic.http.JakartaCommonsHttpClient;
@@ -80,7 +77,6 @@ public class FTPLoader {
public indexDocumentMetadata load(final CrawlEntry entry) {
final yacyURL entryUrl = entry.url();
final String fullPath = getPath(entryUrl);
- final File cacheFile = createCachefile(entryUrl);
// the return value
indexDocumentMetadata htCache = null;
@@ -124,13 +120,14 @@ public class FTPLoader {
// directory -> get list of files
// create a htcache entry
htCache = createCacheEntry(entry, "text/html", new Date());
- if (!generateDirlist(ftpClient, entry, path, cacheFile)) {
+ byte[] dirList = generateDirlist(ftpClient, entry, path);
+ if (dirList == null) {
htCache = null;
}
} else {
// file -> download
try {
- htCache = getFile(ftpClient, entry, cacheFile);
+ htCache = getFile(ftpClient, entry);
} catch (final Exception e) {
// add message to errorLog
(new PrintStream(berr)).print(e.getMessage());
@@ -147,39 +144,11 @@ public class FTPLoader {
final String detail = (berr.size() > 0) ? "\n Errorlog: " + berr.toString() : "";
log.logWarning("Unable to download URL " + entry.url().toString() + detail);
sb.crawlQueues.errorURL.newEntry(entry, sb.webIndex.seedDB.mySeed().hash, new Date(), 1, ErrorURL.DENIED_SERVER_DOWNLOAD_ERROR);
-
- // an error has occured. cleanup
- if (cacheFile.exists()) {
- cacheFile.delete();
- }
- } else {
- // announce the file
- plasmaHTCache.writeFileAnnouncement(cacheFile);
}
return htCache;
}
- /**
- * creating a cache file object
- *
- * @param entryUrl
- * @return
- */
- private File createCachefile(final yacyURL entryUrl) {
- final File cacheFile = plasmaHTCache.getCachePath(entryUrl);
-
- // testing if the file already exists
- if (cacheFile.isFile()) {
- // delete the file if it already exists
- plasmaHTCache.deleteURLfromCache(entryUrl, false);
- } else {
- // create parent directories
- cacheFile.getParentFile().mkdirs();
- }
- return cacheFile;
- }
-
/**
* @param ftpClient
*/
@@ -242,8 +211,7 @@ public class FTPLoader {
* @return
* @throws Exception
*/
- private indexDocumentMetadata getFile(final ftpc ftpClient, final CrawlEntry entry, final File cacheFile)
- throws Exception {
+ private indexDocumentMetadata getFile(final ftpc ftpClient, final CrawlEntry entry) throws Exception {
// determine the mimetype of the resource
final yacyURL entryUrl = entry.url();
final String extension = plasmaParser.getFileExt(entryUrl);
@@ -267,7 +235,8 @@ public class FTPLoader {
htCache = createCacheEntry(entry, mimeType, fileDate);
// download the remote file
- ftpClient.exec("get \"" + path + "\" \"" + cacheFile.getAbsolutePath() + "\"", false);
+ byte[] b = ftpClient.get(path);
+ htCache.setCacheArray(b);
} else {
log.logInfo("REJECTED TOO BIG FILE with size " + size + " Bytes for URL " + entry.url().toString());
sb.crawlQueues.errorURL.newEntry(entry, this.sb.webIndex.seedDB.mySeed().hash, new Date(), 1,
@@ -299,8 +268,7 @@ public class FTPLoader {
* @param cacheFile
* @return
*/
- private boolean generateDirlist(final ftpc ftpClient, final CrawlEntry entry, final String path,
- final File cacheFile) {
+ private byte[] generateDirlist(final ftpc ftpClient, final CrawlEntry entry, final String path) {
// getting the dirlist
final yacyURL entryUrl = entry.url();
@@ -309,17 +277,12 @@ public class FTPLoader {
if (dirList != null && dirList.length() > 0) {
try {
- // write it into a file
- final PrintWriter writer = new PrintWriter(new FileOutputStream(cacheFile), false);
- writer.write(dirList.toString());
- writer.flush();
- writer.close();
- return true;
+ return dirList.toString().getBytes();
} catch (final Exception e) {
log.logInfo("Unable to write dirlist for URL " + entryUrl.toString());
}
}
- return false;
+ return null;
}
/**
diff --git a/source/de/anomic/crawler/HTTPLoader.java b/source/de/anomic/crawler/HTTPLoader.java
index b0aa2ca76..6d91ce654 100644
--- a/source/de/anomic/crawler/HTTPLoader.java
+++ b/source/de/anomic/crawler/HTTPLoader.java
@@ -25,10 +25,7 @@
package de.anomic.crawler;
-import java.io.File;
-import java.io.FileOutputStream;
import java.io.IOException;
-import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.NoRouteToHostException;
import java.net.SocketException;
@@ -40,8 +37,6 @@ import de.anomic.http.JakartaCommonsHttpClient;
import de.anomic.http.JakartaCommonsHttpResponse;
import de.anomic.http.httpRequestHeader;
import de.anomic.http.httpResponseHeader;
-import de.anomic.http.httpdBoundedSizeOutputStream;
-import de.anomic.http.httpdByteCountOutputStream;
import de.anomic.http.httpdLimitExceededException;
import de.anomic.http.httpdProxyCacheEntry;
import de.anomic.index.indexDocumentMetadata;
@@ -50,7 +45,6 @@ import de.anomic.plasma.plasmaHTCache;
import de.anomic.plasma.plasmaParser;
import de.anomic.plasma.plasmaSwitchboard;
import de.anomic.plasma.plasmaSwitchboardConstants;
-import de.anomic.server.serverSystem;
import de.anomic.server.logging.serverLog;
import de.anomic.yacy.yacyURL;
@@ -166,70 +160,31 @@ public final class HTTPLoader {
// create a new cache entry
htCache = createCacheEntry(entry, requestDate, requestHeader, res.getResponseHeader(), res.getStatusLine());
- // aborting download if content is to long ...
- if (htCache.cacheFile().getAbsolutePath().length() > serverSystem.maxPathLength) {
- this.log.logInfo("REJECTED URL " + entry.url().toString() + " because path too long '" + plasmaHTCache.cachePath.getAbsolutePath() + "'");
- sb.crawlQueues.errorURL.newEntry(entry, sb.webIndex.seedDB.mySeed().hash, new Date(), 1, ErrorURL.DENIED_CACHEFILE_PATH_TOO_LONG);
- return (htCache = null);
- }
-
- // reserve cache entry
- if (!htCache.cacheFile().getCanonicalPath().startsWith(plasmaHTCache.cachePath.getCanonicalPath())) {
- // if the response has not the right file type then reject file
- this.log.logInfo("REJECTED URL " + entry.url().toString() + " because of an invalid file path ('" +
- htCache.cacheFile().getCanonicalPath() + "' does not start with '" +
- plasmaHTCache.cachePath.getAbsolutePath() + "').");
- sb.crawlQueues.errorURL.newEntry(entry, sb.webIndex.seedDB.mySeed().hash, new Date(), 1, ErrorURL.DENIED_INVALID_CACHEFILE_PATH);
- return (htCache = null);
- }
-
// request has been placed and result has been returned. work off response
- final File cacheFile = plasmaHTCache.getCachePath(entry.url());
try {
if (plasmaParser.supportedContent(parserMode, entry.url(), res.getResponseHeader().mime())) {
- // delete old content
- if (cacheFile.isFile()) {
- // TODO why is content and metadata so separated? htcache holds metadata, but deleteURLfromCache deletes it???
- plasmaHTCache.deleteURLfromCache(entry.url(), true);
- }
-
- // create parent directories
- cacheFile.getParentFile().mkdirs();
- OutputStream fos = null;
- try {
- // creating an output stream
- fos = new FileOutputStream(cacheFile);
-
- // getting content length
- final long contentLength = res.getResponseHeader().getContentLength();
-
- // check the maximum allowed file size
- if (contentLength == -1 || maxFileSize == -1) {
- if(maxFileSize == -1) {
- // unlimited
- fos = new httpdByteCountOutputStream(fos);
- } else {
- // check filesize while loading page
- fos = new httpdBoundedSizeOutputStream(fos, maxFileSize);
- }
- } else if (contentLength > maxFileSize) {
- this.log.logInfo("REJECTED URL " + entry.url() + " because file size '" + contentLength + "' exceeds max filesize limit of " + maxFileSize + " bytes.");
- sb.crawlQueues.errorURL.newEntry(entry, sb.webIndex.seedDB.mySeed().hash, new Date(), 1, ErrorURL.DENIED_FILESIZE_LIMIT_EXCEEDED);
- return null;
- }
+ // get the content length and check if the length is allowed
+ long contentLength = res.getResponseHeader().getContentLength();
+ if (maxFileSize >= 0 && contentLength > maxFileSize) {
+ this.log.logInfo("REJECTED URL " + entry.url() + " because file size '" + contentLength + "' exceeds max filesize limit of " + maxFileSize + " bytes.");
+ sb.crawlQueues.errorURL.newEntry(entry, sb.webIndex.seedDB.mySeed().hash, new Date(), 1, ErrorURL.DENIED_FILESIZE_LIMIT_EXCEEDED);
+ return null;
+ }
- // we write the new cache entry to file system directly
- res.setAccountingName("CRAWLER");
- final byte[] responseBody = res.getData();
- fos.write(responseBody);
- htCache.setCacheArray(responseBody);
- plasmaHTCache.writeFileAnnouncement(cacheFile);
- //htCache.writeResourceInfo(); // write header to header BLOB-database
- } finally {
- if (fos!=null)try{fos.close();}catch(final Exception e){/* ignore this */}
+ // we write the new cache entry to file system directly
+ res.setAccountingName("CRAWLER");
+ final byte[] responseBody = res.getData();
+ contentLength = responseBody.length;
+
+ // check length again in case it was not possible to get the length before loading
+ if (maxFileSize >= 0 && contentLength > maxFileSize) {
+ this.log.logInfo("REJECTED URL " + entry.url() + " because file size '" + contentLength + "' exceeds max filesize limit of " + maxFileSize + " bytes.");
+ sb.crawlQueues.errorURL.newEntry(entry, sb.webIndex.seedDB.mySeed().hash, new Date(), 1, ErrorURL.DENIED_FILESIZE_LIMIT_EXCEEDED);
+ return null;
}
+ htCache.setCacheArray(responseBody);
} else {
// if the response has not the right file type then reject file
this.log.logInfo("REJECTED WRONG MIME/EXT TYPE " + res.getResponseHeader().mime() + " for URL " + entry.url().toString());
@@ -243,7 +198,6 @@ public final class HTTPLoader {
// in that case, we are not responsible and just forget it
// but we clean the cache also, since it may be only partial
// and most possible corrupted
- if (cacheFile.exists()) cacheFile.delete();
this.log.logSevere("CRAWLER LOADER ERROR1: with URL=" + entry.url().toString() + ": " + e.toString());
sb.crawlQueues.errorURL.newEntry(entry, sb.webIndex.seedDB.mySeed().hash, new Date(), 1, ErrorURL.DENIED_CONNECTION_ERROR);
htCache = null;
@@ -288,7 +242,6 @@ public final class HTTPLoader {
// retry crawling with new url
entry.redirectURL(redirectionUrl);
return load(entry, plasmaParser.PARSER_MODE_URLREDIRECTOR, retryCount - 1);
-
}
} else {
// if the response has not the right response type then reject file
diff --git a/source/de/anomic/crawler/IndexingStack.java b/source/de/anomic/crawler/IndexingStack.java
index 66c7bd634..4791ccb43 100644
--- a/source/de/anomic/crawler/IndexingStack.java
+++ b/source/de/anomic/crawler/IndexingStack.java
@@ -308,10 +308,6 @@ public class IndexingStack {
return (flags & 1) == 1;
}
- public File cacheFile() {
- return plasmaHTCache.getCachePath(url);
- }
-
public boolean proxy() {
// FIXME the equals seems to be incorrect: String.equals(boolean)
return (initiator == null) || (initiator.equals(initiator.length() == 0));
@@ -336,8 +332,7 @@ public class IndexingStack {
}
public long size() {
- if (cacheFile().exists()) return cacheFile().length();
- return 0;
+ return plasmaHTCache.getResourceContentLength(this.url);
}
public CrawlProfile.entry profile() {
diff --git a/source/de/anomic/http/httpdProxyCacheEntry.java b/source/de/anomic/http/httpdProxyCacheEntry.java
index cf5dda4a7..cea934ed0 100755
--- a/source/de/anomic/http/httpdProxyCacheEntry.java
+++ b/source/de/anomic/http/httpdProxyCacheEntry.java
@@ -26,14 +26,12 @@
package de.anomic.http;
-import java.io.File;
import java.util.Date;
import de.anomic.crawler.CrawlProfile;
import de.anomic.index.indexDocumentMetadata;
import de.anomic.plasma.plasmaHTCache;
import de.anomic.server.serverDate;
-import de.anomic.server.serverSystem;
import de.anomic.yacy.yacyURL;
public class httpdProxyCacheEntry implements indexDocumentMetadata {
@@ -54,7 +52,6 @@ public class httpdProxyCacheEntry implements indexDocumentMetadata {
// the class objects
private final int depth; // the depth of pre-fetching
private final String responseStatus;
- private final File cacheFile; // the cache file
private byte[] cacheArray; // or the cache as byte-array
private final yacyURL url;
private final String name; // the name of the link, read as anchor from an <a>-tag
@@ -151,7 +148,6 @@ public class httpdProxyCacheEntry implements indexDocumentMetadata {
this.responseHeader = responseHeader;
this.url = url;
this.name = name;
- this.cacheFile = plasmaHTCache.getCachePath(this.url);
// assigned:
this.depth = depth;
@@ -221,19 +217,19 @@ public class httpdProxyCacheEntry implements indexDocumentMetadata {
}
public long size() {
- if (this.cacheArray == null)
- return 0;
- return this.cacheArray.length;
+ if (this.cacheArray != null) return this.cacheArray.length;
+ if (this.responseHeader != null) {
+ // take the size from the response header
+ return this.responseHeader.getContentLength();
+ }
+ // the size is unknown
+ return -1;
}
public int depth() {
return this.depth;
}
- public File cacheFile() {
- return this.cacheFile;
- }
-
public void setCacheArray(final byte[] data) {
this.cacheArray = data;
}
@@ -258,27 +254,15 @@ public class httpdProxyCacheEntry implements indexDocumentMetadata {
// the cache or not
// if the storage was requested by prefetching, the request map is null
+ // check storage size: all files will be handled in RAM before storage, so they must not exceed
+ // a given size, which we consider as 1MB
+ if (this.size() > 1024L * 1024L) return "too_large_for_caching_" + this.size();
+
// check status code
if (!validResponseStatus()) {
return "bad_status_" + this.responseStatus.substring(0, 3);
}
- // check storage location
- // sometimes a file name is equal to a path name in the same directory;
- // or sometimes a file name is equal a directory name created earlier;
- // we cannot match that here in the cache file path and therefore omit
- // writing into the cache
- if (this.cacheFile.getParentFile().isFile()
- || this.cacheFile.isDirectory()) {
- return "path_ambiguous";
- }
- if (this.cacheFile.toString().indexOf("..") >= 0) {
- return "path_dangerous";
- }
- if (this.cacheFile.getAbsolutePath().length() > serverSystem.maxPathLength) {
- return "path too long";
- }
-
// -CGI access in request
// CGI access makes the page very individual, and therefore not usable
// in caches
diff --git a/source/de/anomic/http/httpdProxyHandler.java b/source/de/anomic/http/httpdProxyHandler.java
index 0146ac7bb..0de8e6603 100644
--- a/source/de/anomic/http/httpdProxyHandler.java
+++ b/source/de/anomic/http/httpdProxyHandler.java
@@ -48,7 +48,6 @@ import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
-import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
@@ -386,11 +385,7 @@ public final class httpdProxyHandler {
prepareRequestHeader(conProp, requestHeader, hostlow);
- // decide whether to use a cache entry or connect to the network
- final File cacheFile = plasmaHTCache.getCachePath(url);
-
httpResponseHeader cachedResponseHeader = plasmaHTCache.loadResponseHeader(url);
- final boolean cacheExists = cacheFile.isFile() && (cachedResponseHeader != null);
// why are files unzipped upon arrival? why not zip all files in cache?
// This follows from the following premises
@@ -416,7 +411,7 @@ public final class httpdProxyHandler {
// case 1 and case 3
if (cachedResponseHeader == null) {
if (theLogger.isFinest()) theLogger.logFinest(reqID + " page not in cache: fulfill request from web");
- fulfillRequestFromWeb(conProp,url,ext,requestHeader,cachedResponseHeader,cacheFile,countedRespond);
+ fulfillRequestFromWeb(conProp, url, ext, requestHeader, cachedResponseHeader, countedRespond);
} else {
final indexDocumentMetadata cacheEntry = new httpdProxyCacheEntry(
0, // crawling depth
@@ -430,13 +425,14 @@ public final class httpdProxyHandler {
switchboard.webIndex.defaultProxyProfile // profile
);
plasmaHTCache.storeMetadata(cachedResponseHeader, cacheEntry); // TODO: check if this storeMetadata is necessary
-
- if (cacheExists && cacheEntry.shallUseCacheForProxy()) {
+
+ byte[] cacheContent = plasmaHTCache.getResourceContent(url);
+ if (cacheContent != null && cacheEntry.shallUseCacheForProxy()) {
if (theLogger.isFinest()) theLogger.logFinest(reqID + " fulfill request from cache");
- fulfillRequestFromCache(conProp,url,ext,requestHeader,cachedResponseHeader,cacheFile,countedRespond);
- } else {
+ fulfillRequestFromCache(conProp, url, ext, requestHeader, cachedResponseHeader, cacheContent, countedRespond);
+ } else {
if (theLogger.isFinest()) theLogger.logFinest(reqID + " fulfill request from web");
- fulfillRequestFromWeb(conProp,url,ext,requestHeader,cachedResponseHeader,cacheFile,countedRespond);
+ fulfillRequestFromWeb(conProp, url, ext, requestHeader, cachedResponseHeader, countedRespond);
}
}
@@ -466,7 +462,7 @@ public final class httpdProxyHandler {
}
}
- private static void fulfillRequestFromWeb(final Properties conProp, final yacyURL url,final String ext, final httpRequestHeader requestHeader, final httpResponseHeader cachedResponseHeader, final File cacheFile, final OutputStream respond) {
+ private static void fulfillRequestFromWeb(final Properties conProp, final yacyURL url,final String ext, final httpRequestHeader requestHeader, final httpResponseHeader cachedResponseHeader, final OutputStream respond) {
final GZIPOutputStream gzippedOut = null;
Writer textOutput = null;
@@ -520,21 +516,15 @@ public final class httpdProxyHandler {
throw new Exception(res.getStatusLine());
}
- final httpChunkedOutputStream chunkedOut = setTransferEncoding(conProp, responseHeader, res.getStatusCode(), respond);
-
-// if (((String)requestHeader.get(httpHeader.ACCEPT_ENCODING,"")).indexOf("gzip") != -1) {
-// zipped = new GZIPOutputStream((chunked != null) ? chunked : respond);
-// res.responseHeader.put(httpHeader.CONTENT_ENCODING, "gzip");
-// res.responseHeader.remove(httpHeader.CONTENT_LENGTH);
-// }
+ final httpChunkedOutputStream chunkedOut = setTransferEncoding(conProp, responseHeader, res.getStatusCode(), respond);
// the cache does either not exist or is (supposed to be) stale
long sizeBeforeDelete = -1;
- if ((cacheFile.isFile()) && (cachedResponseHeader != null)) {
+ if (cachedResponseHeader != null) {
// delete the cache
- sizeBeforeDelete = cacheFile.length();
- plasmaHTCache.deleteURLfromCache(url, false);
- conProp.setProperty(httpHeader.CONNECTION_PROP_PROXY_RESPOND_CODE,"TCP_REFRESH_MISS");
+ sizeBeforeDelete = plasmaHTCache.getResourceContentLength(url);
+ plasmaHTCache.deleteFromCache(url);
+ conProp.setProperty(httpHeader.CONNECTION_PROP_PROXY_RESPOND_CODE, "TCP_REFRESH_MISS");
}
// reserver cache entry
@@ -609,84 +599,47 @@ public final class httpdProxyHandler {
*/
((storeHTCache) || (isSupportedContent))
) {
- final long contentLength = responseHeader.getContentLength();
- // we write a new cache entry
- if ((contentLength > 0) && (contentLength < 1048576)) // if the length is known and < 1 MB
- {
- // ok, we don't write actually into a file, only to RAM, and schedule writing the file.
- final ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
- if(isBinary) {
- final OutputStream toClientAndMemory = new MultiOutputStream(new OutputStream[] {outStream, byteStream});
- serverFileUtils.copy(res.getDataAsStream(), toClientAndMemory);
- } else {
- writeTextContent(res, new BufferedWriter(textOutput), byteStream);
- }
- // cached bytes
- byte[] cacheArray;
- if(byteStream.size() > 0) {
- cacheArray = byteStream.toByteArray();
- } else {
- cacheArray = null;
- }
- if (theLogger.isFine()) theLogger.logFine(reqID +" writeContent of " + url + " produced cacheArray = " + ((cacheArray == null) ? "null" : ("size=" + cacheArray.length)));
+ // we don't write actually into a file, only to RAM, and schedule writing the file.
+ final ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
+ if(isBinary) {
+ final OutputStream toClientAndMemory = new MultiOutputStream(new OutputStream[] {outStream, byteStream});
+ serverFileUtils.copy(res.getDataAsStream(), toClientAndMemory);
+ } else {
+ writeTextContent(res, new BufferedWriter(textOutput), byteStream);
+ }
+ // cached bytes
+ byte[] cacheArray;
+ if(byteStream.size() > 0) {
+ cacheArray = byteStream.toByteArray();
+ } else {
+ cacheArray = null;
+ }
+ if (theLogger.isFine()) theLogger.logFine(reqID +" writeContent of " + url + " produced cacheArray = " + ((cacheArray == null) ? "null" : ("size=" + cacheArray.length)));
- if (textOutput instanceof htmlFilterWriter) ((htmlFilterWriter) textOutput).close();
+ if (textOutput instanceof htmlFilterWriter) ((htmlFilterWriter) textOutput).close();
- if (sizeBeforeDelete == -1) {
- // totally fresh file
- //cacheEntry.status = plasmaHTCache.CACHE_FILL; // it's an insert
- cacheEntry.setCacheArray(cacheArray);
- plasmaHTCache.push(cacheEntry);
- conProp.setProperty(httpHeader.CONNECTION_PROP_PROXY_RESPOND_CODE,"TCP_MISS");
- } else if (cacheArray != null && sizeBeforeDelete == cacheArray.length) {
- // before we came here we deleted a cache entry
- cacheArray = null;
- //cacheEntry.status = plasmaHTCache.CACHE_STALE_RELOAD_BAD;
- //cacheManager.push(cacheEntry); // unnecessary update
- conProp.setProperty(httpHeader.CONNECTION_PROP_PROXY_RESPOND_CODE,"TCP_REF_FAIL_HIT");
- } else {
- // before we came here we deleted a cache entry
- //cacheEntry.status = plasmaHTCache.CACHE_STALE_RELOAD_GOOD;
- cacheEntry.setCacheArray(cacheArray);
- plasmaHTCache.push(cacheEntry); // necessary update, write response header to cache
- conProp.setProperty(httpHeader.CONNECTION_PROP_PROXY_RESPOND_CODE,"TCP_REFRESH_MISS");
- }
+ if (sizeBeforeDelete == -1) {
+ // totally fresh file
+ //cacheEntry.status = plasmaHTCache.CACHE_FILL; // it's an insert
+ cacheEntry.setCacheArray(cacheArray);
+ plasmaHTCache.push(cacheEntry);
+ conProp.setProperty(httpHeader.CONNECTION_PROP_PROXY_RESPOND_CODE,"TCP_MISS");
+ } else if (cacheArray != null && sizeBeforeDelete == cacheArray.length) {
+ // before we came here we deleted a cache entry
+ cacheArray = null;
+ //cacheEntry.status = plasmaHTCache.CACHE_STALE_RELOAD_BAD;
+ //cacheManager.push(cacheEntry); // unnecessary update
+ conProp.setProperty(httpHeader.CONNECTION_PROP_PROXY_RESPOND_CODE,"TCP_REF_FAIL_HIT");
} else {
- // the file is too big to cache it in the ram, or the size is unknown
- // write to file right here.
- cacheFile.getParentFile().mkdirs();
- final OutputStream fileStream = new FileOutputStream(cacheFile);
- if(isBinary) {
- OutputStream toClientAndFile = new MultiOutputStream(new OutputStream[] {outStream, fileStream});
- serverFileUtils.copy(res.getDataAsStream(), toClientAndFile);
- } else {
- writeTextContent(res, new BufferedWriter(textOutput), fileStream);
- }
- if (textOutput instanceof htmlFilterWriter) ((htmlFilterWriter) textOutput).close();
- if (theLogger.isFine()) theLogger.logFine(reqID +" for write-file of " + url + ": contentLength = " + contentLength + ", sizeBeforeDelete = " + sizeBeforeDelete);
- plasmaHTCache.writeFileAnnouncement(cacheFile);
- if (sizeBeforeDelete == -1) {
- // totally fresh file
- //cacheEntry.status = plasmaHTCache.CACHE_FILL; // it's an insert
- plasmaHTCache.push(cacheEntry);
- conProp.setProperty(httpHeader.CONNECTION_PROP_PROXY_RESPOND_CODE,"TCP_MISS");
- } else if (sizeBeforeDelete == cacheFile.length()) {
- // before we came here we deleted a cache entry
- //cacheEntry.status = plasmaHTCache.CACHE_STALE_RELOAD_BAD;
- //cacheManager.push(cacheEntry); // unnecessary update
- conProp.setProperty(httpHeader.CONNECTION_PROP_PROXY_RESPOND_CODE,"TCP_REF_FAIL_HIT");
- } else {
- // before we came here we deleted a cache entry
- //cacheEntry.status = plasmaHTCache.CACHE_STALE_RELOAD_GOOD;
- plasmaHTCache.push(cacheEntry); // necessary update, write response header to cache
- conProp.setProperty(httpHeader.CONNECTION_PROP_PROXY_RESPOND_CODE,"TCP_REFRESH_MISS");
- }
- // beware! all these writings will not fill the cacheEntry.cacheArray
- // that means they are not available for the indexer (except they are scraped before)
+ // before we came here we deleted a cache entry
+ //cacheEntry.status = plasmaHTCache.CACHE_STALE_RELOAD_GOOD;
+ cacheEntry.setCacheArray(cacheArray);
+ plasmaHTCache.push(cacheEntry); // necessary update, write response header to cache
+ conProp.setProperty(httpHeader.CONNECTION_PROP_PROXY_RESPOND_CODE,"TCP_REFRESH_MISS");
}
} else {
// no caching
- if (theLogger.isFine()) theLogger.logFine(reqID +" "+ cacheFile.toString() + " not cached." +
+ if (theLogger.isFine()) theLogger.logFine(reqID +" "+ url.toString() + " not cached." +
" StoreError=" + ((storeError==null)?"None":storeError) +
" StoreHTCache=" + storeHTCache +
" SupportetContent=" + isSupportedContent);
@@ -699,15 +652,6 @@ public final class httpdProxyHandler {
writeTextContent(res, new BufferedWriter(textOutput));
}
if (textOutput instanceof htmlFilterWriter) ((htmlFilterWriter) textOutput).close();
- /*if (sizeBeforeDelete == -1) {
- // no old file and no load. just data passing
- //cacheEntry.status = plasmaHTCache.CACHE_PASSING;
- //cacheManager.push(cacheEntry);
- } else {
- // before we came here we deleted a cache entry
- //cacheEntry.status = plasmaHTCache.CACHE_STALE_NO_RELOAD;
- //cacheManager.push(cacheEntry);
- }*/
conProp.setProperty(httpHeader.CONNECTION_PROP_PROXY_RESPOND_CODE,"TCP_MISS");
}
@@ -727,8 +671,6 @@ public final class httpdProxyHandler {
}
}
} catch (final Exception e) {
- // deleting cached content
- if (cacheFile.exists()) cacheFile.delete();
handleProxyException(e,conProp,respond,url);
}
}
@@ -756,7 +698,7 @@ public final class httpdProxyHandler {
final String ext,
final httpRequestHeader requestHeader,
final httpResponseHeader cachedResponseHeader,
- final File cacheFile,
+ final byte[] cacheEntry,
final OutputStream respond
) throws IOException {
@@ -788,7 +730,7 @@ public final class httpdProxyHandler {
if (requestHeader.containsKey(httpRequestHeader.IF_MODIFIED_SINCE)) {
// conditional request: freshness of cache for that condition was already
// checked within shallUseCache(). Now send only a 304 response
- theLogger.logInfo("CACHE HIT/304 " + cacheFile.toString());
+ theLogger.logInfo("CACHE HIT/304 " + url.toString());
conProp.setProperty(httpHeader.CONNECTION_PROP_PROXY_RESPOND_CODE,"TCP_REFRESH_HIT");
// setting the content length header to 0
@@ -799,11 +741,11 @@ public final class httpdProxyHandler {
//respondHeader(respond, "304 OK", cachedResponseHeader); // respond with 'not modified'
} else {
// unconditional request: send content of cache
- theLogger.logInfo("CACHE HIT/203 " + cacheFile.toString());
+ theLogger.logInfo("CACHE HIT/203 " + url.toString());
conProp.setProperty(httpHeader.CONNECTION_PROP_PROXY_RESPOND_CODE,"TCP_HIT");
// setting the content header to the proper length
- cachedResponseHeader.put(httpResponseHeader.CONTENT_LENGTH, Long.toString(cacheFile.length()));
+ cachedResponseHeader.put(httpResponseHeader.CONTENT_LENGTH, Long.toString(cacheEntry.length));
// send cached header with replaced date and added length
httpd.sendRespondHeader(conProp,respond,httpVer,203,cachedResponseHeader);
@@ -822,12 +764,7 @@ public final class httpdProxyHandler {
// send also the complete body now from the cache
// simply read the file and transfer to out socket
- if(textOutput != null && !isBinary(cachedResponseHeader)) {
- // send as encoded text
- serverFileUtils.copy(cacheFile, charSet, textOutput);
- } else {
- serverFileUtils.copy(cacheFile, outStream);
- }
+ serverFileUtils.copy(cacheEntry, outStream);
if (textOutput != null) textOutput.close();
if (gzippedOut != null) gzippedOut.finish();
diff --git a/source/de/anomic/icap/icapd.java b/source/de/anomic/icap/icapd.java
index 601cec805..5859b1cec 100644
--- a/source/de/anomic/icap/icapd.java
+++ b/source/de/anomic/icap/icapd.java
@@ -28,7 +28,6 @@ import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
-import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
@@ -387,23 +386,15 @@ public class icapd implements serverHandler, Cloneable {
null,
switchboard.webIndex.defaultProxyProfile
);
- plasmaHTCache.storeMetadata(httpResHeader, cacheEntry);
-
- // getting the filename/path to store the response body
- final File cacheFile = plasmaHTCache.getCachePath(httpRequestURL);
-
- // if the file already exits we delete it
- if (cacheFile.isFile()) {
- plasmaHTCache.deleteURLfromCache(httpRequestURL, false);
- }
- // we write the new cache entry to file system directly
- cacheFile.getParentFile().mkdirs();
// copy the response body into the file
- serverFileUtils.copy(resBodyStream,cacheFile);
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ serverFileUtils.copy(resBodyStream, baos);
if(resBodyStream != null) {
resBodyStream.close(); resBodyStream = null;
}
+ cacheEntry.setCacheArray(baos.toByteArray());
+ plasmaHTCache.storeMetadata(httpResHeader, cacheEntry);
// indexing the response
plasmaHTCache.push(cacheEntry);
diff --git a/source/de/anomic/index/indexDocumentMetadata.java b/source/de/anomic/index/indexDocumentMetadata.java
index 93c8e242f..20bfac438 100755
--- a/source/de/anomic/index/indexDocumentMetadata.java
+++ b/source/de/anomic/index/indexDocumentMetadata.java
@@ -26,7 +26,6 @@
package de.anomic.index;
-import java.io.File;
import java.util.Date;
import de.anomic.crawler.CrawlProfile;
@@ -60,8 +59,6 @@ public interface indexDocumentMetadata {
public yacyURL referrerURL();
- public File cacheFile();
-
public void setCacheArray(final byte[] data);
public byte[] cacheArray();
diff --git a/source/de/anomic/kelondro/kelondroBLOB.java b/source/de/anomic/kelondro/kelondroBLOB.java
index 9ec431e9c..6fc611750 100644
--- a/source/de/anomic/kelondro/kelondroBLOB.java
+++ b/source/de/anomic/kelondro/kelondroBLOB.java
@@ -82,6 +82,14 @@ public interface kelondroBLOB {
*/
public byte[] get(byte[] key) throws IOException;
+ /**
+ * retrieve the size of the BLOB
+ * @param key
+ * @return the size of the BLOB or -1 if the BLOB does not exist
+ * @throws IOException
+ */
+ public long length(byte[] key) throws IOException;
+
/**
* write a whole byte array as BLOB to the table
* @param key the primary key
diff --git a/source/de/anomic/kelondro/kelondroBLOBArray.java b/source/de/anomic/kelondro/kelondroBLOBArray.java
index 2a7bd8dee..e203e261b 100755
--- a/source/de/anomic/kelondro/kelondroBLOBArray.java
+++ b/source/de/anomic/kelondro/kelondroBLOBArray.java
@@ -53,23 +53,30 @@ public class kelondroBLOBArray implements kelondroBLOB {
* time-out. Deletions are not made automatically, they must be triggered using this method.
*/
+ public static final long oneMonth = 1000L * 60L * 60L * 24L * 365L / 12L;
+ public static final long oneGigabyte = 1024 * 1024 * 1024;
+
private int keylength;
private kelondroByteOrder ordering;
private File heapLocation;
- private long maxage;
- private long maxsize;
+ private long fileAgeLimit;
+ private long fileSizeLimit;
+ private long repositoryAgeMax;
+ private long repositorySizeMax;
private List<blobItem> blobs;
public kelondroBLOBArray(
final File heapLocation,
final int keylength, final kelondroByteOrder ordering,
- long maxage, long maxsize
+ long agelimit, long sizelimit
) throws IOException {
this.keylength = keylength;
this.ordering = ordering;
this.heapLocation = heapLocation;
- this.maxage = maxage;
- this.maxsize = maxsize;
+ this.fileAgeLimit = agelimit;
+ this.fileSizeLimit = sizelimit;
+ this.repositoryAgeMax = Long.MAX_VALUE;
+ this.repositorySizeMax = Long.MAX_VALUE;
// check existence of the heap directory
if (heapLocation.exists()) {
@@ -85,9 +92,9 @@ public class kelondroBLOBArray implements kelondroBLOB {
kelondroBLOB oneBlob;
File f;
for (int i = 0; i < files.length; i++) {
- if (files[i].length() == 17 && files[i].endsWith("blob")) {
+ if (files[i].length() == 19 && files[i].endsWith("blob")) {
try {
- d = serverDate.parseShortSecond(files[i].substring(0, 12));
+ d = serverDate.parseShortSecond(files[i].substring(0, 14));
} catch (ParseException e) {continue;}
f = new File(heapLocation, files[i]);
oneBlob = new kelondroBLOBHeap(f, keylength, ordering);
@@ -102,6 +109,44 @@ public class kelondroBLOBArray implements kelondroBLOB {
}
}
+ public void setMaxAge(long maxAge) {
+ this.repositoryAgeMax = maxAge;
+ }
+
+ public void setMaxSize(long maxSize) {
+ this.repositorySizeMax = maxSize;
+ }
+
+ private void executeLimits() {
+ // check if storage limits are reached and execute consequences
+ if (blobs.size() == 0) return;
+
+ // age limit:
+ while (blobs.size() > 0 && System.currentTimeMillis() - blobs.get(0).creation.getTime() - this.fileAgeLimit > this.repositoryAgeMax) {
+ // too old
+ blobItem oldestBLOB = blobs.remove(0);
+ oldestBLOB.blob.close();
+ oldestBLOB.location.delete();
+ }
+
+ // size limit
+ while (blobs.size() > 0 && length() > this.repositorySizeMax) {
+ // too large
+ blobItem oldestBLOB = blobs.remove(0);
+ oldestBLOB.blob.close();
+ oldestBLOB.location.delete();
+ }
+ }
+
+ /*
+ * return the size of the repository
+ */
+ public long length() {
+ long s = 0;
+ for (int i = 0; i < blobs.size(); i++) s += blobs.get(i).location.length();
+ return s;
+ }
+
private class blobItem {
Date creation;
File location;
@@ -115,7 +160,7 @@ public class kelondroBLOBArray implements kelondroBLOB {
// make a new blob file and assign it in this item
this.creation = new Date();
this.location = new File(heapLocation, serverDate.formatShortSecond(creation) + ".blob");
- this.blob = new kelondroBLOBHeap(location, keylength, ordering);;
+ this.blob = new kelondroBLOBHeap(location, keylength, ordering);
}
}
@@ -205,6 +250,21 @@ public class kelondroBLOBArray implements kelondroBLOB {
return null;
}
+ /**
+ * retrieve the size of the BLOB
+ * @param key
+ * @return the size of the BLOB or -1 if the BLOB does not exist
+ * @throws IOException
+ */
+ public long length(byte[] key) throws IOException {
+ long l;
+ for (blobItem bi: blobs) {
+ l = bi.blob.length(key);
+ if (l >= 0) return l;
+ }
+ return -1;
+ }
+
/**
* write a whole byte array as BLOB to the table
* @param key the primary key
@@ -213,12 +273,19 @@ public class kelondroBLOBArray implements kelondroBLOB {
*/
public void put(byte[] key, byte[] b) throws IOException {
blobItem bi = (blobs.size() == 0) ? null : blobs.get(blobs.size() - 1);
- if ((bi == null) || (bi.creation.getTime() - System.currentTimeMillis() > this.maxage) || (bi.location.length() > this.maxsize)) {
+ if (bi == null)
+ System.out.println("bi == null");
+ else if (System.currentTimeMillis() - bi.creation.getTime() > this.fileAgeLimit)
+ System.out.println("System.currentTimeMillis() - bi.creation.getTime() > this.maxage");
+ else if (bi.location.length() > this.fileSizeLimit)
+ System.out.println("bi.location.length() > this.maxsize");
+ if ((bi == null) || (System.currentTimeMillis() - bi.creation.getTime() > this.fileAgeLimit) || (bi.location.length() > this.fileSizeLimit)) {
// add a new blob to the array
bi = new blobItem();
blobs.add(bi);
}
bi.blob.put(key, b);
+ executeLimits();
}
/**
@@ -239,4 +306,28 @@ public class kelondroBLOBArray implements kelondroBLOB {
blobs = null;
}
+
+ public static void main(final String[] args) {
+ final File f = new File("/Users/admin/blobarraytest");
+ try {
+ //f.delete();
+ final kelondroBLOBArray heap = new kelondroBLOBArray(f, 12, kelondroNaturalOrder.naturalOrder, oneMonth, oneGigabyte);
+ heap.put("aaaaaaaaaaaa".getBytes(), "eins zwei drei".getBytes());
+ heap.put("aaaaaaaaaaab".getBytes(), "vier fuenf sechs".getBytes());
+ heap.put("aaaaaaaaaaac".getBytes(), "sieben acht neun".getBytes());
+ heap.put("aaaaaaaaaaad".getBytes(), "zehn elf zwoelf".getBytes());
+ // iterate over keys
+ Iterator<byte[]> i = heap.keys(true, false);
+ while (i.hasNext()) {
+ System.out.println("key_b: " + new String(i.next()));
+ }
+ heap.remove("aaaaaaaaaaab".getBytes());
+ heap.remove("aaaaaaaaaaac".getBytes());
+ heap.put("aaaaaaaaaaaX".getBytes(), "WXYZ".getBytes());
+ heap.close();
+ } catch (final IOException e) {
+ e.printStackTrace();
+ }
+ }
+
}
diff --git a/source/de/anomic/kelondro/kelondroBLOBHeap.java b/source/de/anomic/kelondro/kelondroBLOBHeap.java
index e8496baf9..d9e2cdb74 100755
--- a/source/de/anomic/kelondro/kelondroBLOBHeap.java
+++ b/source/de/anomic/kelondro/kelondroBLOBHeap.java
@@ -94,9 +94,10 @@ public final class kelondroBLOBHeap implements kelondroBLOB {
// read length of the following record without the length of the record size bytes
reclen = file.readInt();
- assert reclen > 0;
+ //assert reclen > 0 : " reclen == 0 at seek pos " + seek;
if (reclen == 0) {
// very bad file inconsistency
+ serverLog.logSevere("kelondroBLOBHeap", "reclen == 0 at seek pos " + seek + " in file " + heapFile);
this.file.setLength(seek); // delete everything else at the remaining of the file :-(
break loop;
}
@@ -260,6 +261,24 @@ public final class kelondroBLOBHeap implements kelondroBLOB {
return blob;
}
+ /**
+ * retrieve the size of the BLOB
+ * @param key
+ * @return the size of the BLOB or -1 if the BLOB does not exist
+ * @throws IOException
+ */
+ public long length(byte[] key) throws IOException {
+ assert index.row().primaryKeyLength == key.length;
+
+ // check if the index contains the key
+ final long pos = index.getl(key);
+ if (pos < 0) return -1;
+
+ // access the file and read the size of the container
+ file.seek(pos);
+ return file.readInt() - index.row().primaryKeyLength;
+ }
+
/**
* clears the content of the database
* @throws IOException
diff --git a/source/de/anomic/kelondro/kelondroBLOBTree.java b/source/de/anomic/kelondro/kelondroBLOBTree.java
index 5d3febcd6..a1a5d48a5 100644
--- a/source/de/anomic/kelondro/kelondroBLOBTree.java
+++ b/source/de/anomic/kelondro/kelondroBLOBTree.java
@@ -453,4 +453,10 @@ public class kelondroBLOBTree implements kelondroBLOB {
return -1;
}
}
+
+ public long length(byte[] key) throws IOException {
+ byte[] b = get(key);
+ if (b == null) return -1;
+ return b.length;
+ }
}
\ No newline at end of file
diff --git a/source/de/anomic/net/ftpc.java b/source/de/anomic/net/ftpc.java
index fd4552efa..9272ca715 100644
--- a/source/de/anomic/net/ftpc.java
+++ b/source/de/anomic/net/ftpc.java
@@ -2319,6 +2319,58 @@ public class ftpc {
}
}
+ public byte[] get(final String fileName) throws IOException {
+
+ createDataSocket();
+
+ // set type of the transfer
+ sendTransferType(transferType);
+
+ // send command to the control port
+ send("RETR " + fileName);
+
+ // read status of the command from the control port
+ String reply = receive();
+
+ // get status code
+ final int status = getStatus(reply);
+
+ // starting data transaction
+ if (status == 1) {
+ Socket data = null;
+ InputStream ClientStream = null;
+ ByteArrayOutputStream os = new ByteArrayOutputStream();
+ int length = 0;
+ try {
+ data = getDataSocket();
+ ClientStream = data.getInputStream();
+
+ // write remote file to local file
+ final byte[] block = new byte[blockSize];
+ int numRead;
+
+ while ((numRead = ClientStream.read(block)) != -1) {
+ os.write(block, 0, numRead);
+ length = length + numRead;
+ }
+
+ // after stream is empty we should get control completion echo
+ /*reply =*/ receive();
+ // boolean success = !isNotPositiveCompletion(reply);
+ } finally {
+ // shutdown connection
+ if(ClientStream != null) {
+ ClientStream.close();
+ }
+ closeDataSocket();
+ }
+ return os.toByteArray();
+ } else {
+ throw new IOException(reply);
+ }
+ }
+
+
private void put(final String fileName, final String fileDest) throws IOException {
createDataSocket();
diff --git a/source/de/anomic/plasma/plasmaHTCache.java b/source/de/anomic/plasma/plasmaHTCache.java
index 2a6d201fd..df1076849 100644
--- a/source/de/anomic/plasma/plasmaHTCache.java
+++ b/source/de/anomic/plasma/plasmaHTCache.java
@@ -34,58 +34,41 @@
package de.anomic.plasma;
-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.net.InetAddress;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
-import java.util.SortedMap;
-import java.util.TreeMap;
import java.util.concurrent.ConcurrentLinkedQueue;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
import de.anomic.http.httpResponseHeader;
import de.anomic.index.indexDocumentMetadata;
import de.anomic.kelondro.kelondroBLOB;
+import de.anomic.kelondro.kelondroBLOBArray;
import de.anomic.kelondro.kelondroBLOBHeap;
-import de.anomic.kelondro.kelondroBLOBTree;
import de.anomic.kelondro.kelondroBase64Order;
-import de.anomic.kelondro.kelondroMScoreCluster;
import de.anomic.kelondro.kelondroMap;
-import de.anomic.server.serverCodings;
-import de.anomic.server.serverDomains;
-import de.anomic.server.serverFileUtils;
-import de.anomic.server.serverInstantBusyThread;
-import de.anomic.server.serverThread;
import de.anomic.server.logging.serverLog;
-import de.anomic.tools.enumerateFiles;
-import de.anomic.yacy.yacySeed;
import de.anomic.yacy.yacySeedDB;
import de.anomic.yacy.yacyURL;
public final class plasmaHTCache {
- public static final String DB_NAME = "responseHeader.heap";
+ public static final String RESPONSE_HEADER_DB_NAME = "responseHeader.heap";
+ public static final String FILE_DB_NAME = "file.array";
private static final int stackLimit = 150; // if we exceed that limit, we do not check idle
- public static final long oneday = 1000 * 60 * 60 * 24; // milliseconds of a day
+ public static final long oneday = 1000L * 60L * 60L * 24L; // milliseconds of a day
private static kelondroMap responseHeaderDB = null;
+ private static kelondroBLOBArray fileDB = null;
+
private static final ConcurrentLinkedQueue<indexDocumentMetadata> cacheStack = new ConcurrentLinkedQueue<indexDocumentMetadata>();
- private static final SortedMap<String, File> cacheAge = Collections.synchronizedSortedMap(new TreeMap<String, File>()); // a <date+hash, cache-path> - relation
- public static long curCacheSize = 0;
public static long maxCacheSize = 0l;
public static File cachePath = null;
public static final serverLog log = new serverLog("HTCACHE");
- private static long lastcleanup = System.currentTimeMillis();
- private static serverThread cacheScanThread = null;
// URL attributes
public static final int UA_LOCAL = 0; // URL was crawled locally
@@ -101,7 +84,6 @@ public final class plasmaHTCache {
cachePath = htCachePath;
maxCacheSize = CacheSizeMax;
-
// reset old HTCache ?
String[] list = cachePath.list();
@@ -110,37 +92,14 @@ public final class plasmaHTCache {
for (int i = list.length - 1; i >= 0; i--) {
object = new File(cachePath, list[i]);
- if (!object.isDirectory()) { continue; }
-
- if (!object.getName().equals("http") &&
- !object.getName().equals("yacy") &&
- !object.getName().equals("https") &&
- !object.getName().equals("ftp")) {
+ if (object.getName().equals("http") ||
+ object.getName().equals("yacy") ||
+ object.getName().equals("https") ||
+ object.getName().equals("ftp")) {
deleteOldHTCache(cachePath);
- break;
-
}
}
}
- File testpath = new File(cachePath, "/http/");
- list = testpath.list();
- if (list != null) {
- File object;
- for (int i = list.length - 1; i >= 0; i--) {
- object = new File(testpath, list[i]);
-
- if (!object.isDirectory()) { continue; }
-
- if (!object.getName().equals("ip") &&
- !object.getName().equals("other") &&
- !object.getName().equals("www")) {
- deleteOldHTCache(cachePath);
- break;
- }
- }
- }
- testpath = null;
-
// set/make cache path
if (!htCachePath.exists()) {
@@ -153,39 +112,32 @@ public final class plasmaHTCache {
}
// open the response header database
- openResponseHeaderDB();
-
- // start the cache startup thread
- // this will collect information about the current cache size and elements
- try {
- cacheScanThread = serverInstantBusyThread.oneTimeJob(Class.forName("de.anomic.plasma.plasmaHTCache"), "cacheScan", log, 120000);
- } catch (final ClassNotFoundException e) {
- e.printStackTrace();
- }
+ openDB();
}
- static void resetResponseHeaderDB() {
+ static void resetDB() {
log.logFine("reset responseHeader DB with "+ responseHeaderDB.size() +" entries");
if (responseHeaderDB != null) responseHeaderDB.close();
- final File dbfile = new File(cachePath, DB_NAME);
+ final File dbfile = new File(cachePath, RESPONSE_HEADER_DB_NAME);
if (dbfile.exists()) dbfile.delete();
- openResponseHeaderDB();
+ openDB();
}
- private static void openResponseHeaderDB() {
+ private static void openDB() {
// open the response header database
- final File dbfile = new File(cachePath, DB_NAME);
+ final File dbfile = new File(cachePath, RESPONSE_HEADER_DB_NAME);
kelondroBLOB blob = null;
- if (DB_NAME.endsWith("heap")) {
- try {
- blob = new kelondroBLOBHeap(dbfile, yacySeedDB.commonHashLength, kelondroBase64Order.enhancedCoder);
- } catch (final IOException e) {
- e.printStackTrace();
- }
- } else {
- blob = new kelondroBLOBTree(dbfile, true, true, yacySeedDB.commonHashLength, 150, '#', kelondroBase64Order.enhancedCoder, false, false, true);
+ try {
+ blob = new kelondroBLOBHeap(dbfile, yacySeedDB.commonHashLength, kelondroBase64Order.enhancedCoder);
+ } catch (final IOException e) {
+ e.printStackTrace();
}
responseHeaderDB = new kelondroMap(blob, 500);
+ try {
+ fileDB = new kelondroBLOBArray(new File(cachePath, FILE_DB_NAME), 12, kelondroBase64Order.enhancedCoder, kelondroBLOBArray.oneMonth, kelondroBLOBArray.oneGigabyte);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
}
private static void deleteOldHTCache(final File directory) {
@@ -208,10 +160,14 @@ public final class plasmaHTCache {
return cacheStack.size();
}
- public static int dbSize() {
+ public static int responseHeaderDBSize() {
return responseHeaderDB.size();
}
+ public static long fileDBSize() {
+ return fileDB.length();
+ }
+
public static void push(final indexDocumentMetadata entry) {
cacheStack.add(entry);
}
@@ -233,181 +189,13 @@ public final class plasmaHTCache {
* @return the cache size in bytes
*/
public static long getFreeSize() {
- return (curCacheSize >= maxCacheSize) ? 0 : maxCacheSize - curCacheSize;
- }
-
- private static boolean deleteFile(final File obj) {
- if (obj.exists()) {
- final long size = obj.length();
- if (obj.delete()) {
- curCacheSize -= size;
- return true;
- }
- }
- return false;
- }
-
- private static boolean deleteFileandDirs(File path, final String msg) {
- if (deleteFile(path)) {
- log.logInfo("DELETED " + msg + " CACHE: " + path.toString());
- path = path.getParentFile(); // returns null if the path does not have a parent
- // If the has been emptied, remove it
- // Loop as long as we produce empty directories, but stop at HTCACHE
- while (path != null && !(path.equals(cachePath)) && path.isDirectory() && path.list().length == 0) { // NPE
- if (path.delete()) if (log.isFine()) log.logFine("DELETED EMPTY DIRECTORY : " + path.toString());
- path = path.getParentFile(); // returns null if the path does not have a parent
- }
- return true;
- }
- return false;
- }
-
- private static void cleanupDoIt(final long newCacheSize) {
- File file;
- String key;
- while (!cacheAge.isEmpty() && curCacheSize >= newCacheSize) {
- if (Thread.currentThread().isInterrupted()) return;
- key = cacheAge.firstKey();
- file = cacheAge.get(key);
- final long t = Long.parseLong(key.substring(0, 16), 16);
- if (System.currentTimeMillis() - t < 300000) return; // files must have been at least 5 minutes in the cache before they are deleted
- if (file != null) {
- if (log.isFinest()) log.logFinest("Trying to delete [" + key + "] = old file: " + file.toString());
- // This needs to be called *before* the file is deleted
- final String urlHash = getHash(file);
- if (deleteFileandDirs(file, "OLD")) {
- try {
- // As the file is gone, the entry in responseHeader.db is not needed anymore
- if (urlHash != null) {
- if (log.isFinest()) log.logFinest("Trying to remove responseHeader for URLhash: " + urlHash);
- responseHeaderDB.remove(urlHash);
- } else {
- final yacyURL url = getURL(file);
- if (url != null) {
- if (log.isFinest()) log.logFinest("Trying to remove responseHeader for URL: " + url.toNormalform(false, true));
- responseHeaderDB.remove(url.hash());
- }
- }
- } catch (final IOException e) {
- log.logInfo("IOExeption removing response header from DB: " + e.getMessage(), e);
- }
- }
- }
- cacheAge.remove(key);
- }
+ long l = fileDB.length();
+ return (l >= maxCacheSize) ? 0 : maxCacheSize - l;
}
-
- private static void cleanup() {
- // clean up cache to have 4% (enough) space for next entries
- if (cacheAge.size() > 0 &&
- curCacheSize >= maxCacheSize &&
- maxCacheSize > 0) {
- cleanupDoIt(maxCacheSize - (maxCacheSize / 100) * 4);
- }
- }
-
+
public static void close() {
- // closing cache scan if still running
- if ((cacheScanThread != null) && (cacheScanThread.isAlive())) {
- cacheScanThread.terminate(true);
- }
-
- // closing DB
responseHeaderDB.close();
- }
-
- private static String ageString(final long date, final File f) {
- final StringBuffer sb = new StringBuffer(32);
- String s = Long.toHexString(date);
- for (int i = s.length(); i < 16; i++) sb.append('0');
- sb.append(s);
- s = Integer.toHexString(f.hashCode());
- for (int i = s.length(); i < 8; i++) sb.append('0');
- sb.append(s);
- return sb.toString();
- }
-
- public static void cacheScan() {
- log.logConfig("STARTING HTCACHE SCANNING");
- final kelondroMScoreCluster<String> doms = new kelondroMScoreCluster<String>();
- int fileCount = 0;
- final enumerateFiles fileEnum = new enumerateFiles(cachePath, true, false, true, true);
- final File dbfile = new File(cachePath, DB_NAME);
- while (fileEnum.hasMoreElements()) {
- if (Thread.currentThread().isInterrupted()) return;
- fileCount++;
- final File nextFile = fileEnum.nextElement();
- final long nextFileModDate = nextFile.lastModified();
- //System.out.println("Cache: " + dom(f));
- doms.incScore(dom(nextFile));
- curCacheSize += nextFile.length();
- if (!dbfile.equals(nextFile)) cacheAge.put(ageString(nextFileModDate, nextFile), nextFile);
- try {
- Thread.sleep(10);
- } catch (final InterruptedException e) {
- return;
- }
- }
- //System.out.println("%" + (String) cacheAge.firstKey() + "=" + cacheAge.get(cacheAge.firstKey()));
- long ageHours = 0;
- if (!cacheAge.isEmpty()) {
- try {
- ageHours = (System.currentTimeMillis() - Long.parseLong(cacheAge.firstKey().substring(0, 16), 16)) / 3600000;
- } catch (final NumberFormatException e) {
- ageHours = 0;
- }
- }
- log.logConfig("CACHE SCANNED, CONTAINS " + fileCount +
- " FILES = " + curCacheSize/1048576 + "MB, OLDEST IS " +
- ((ageHours < 24) ? (ageHours + " HOURS") : ((ageHours / 24) + " DAYS")) + " OLD");
- cleanup();
-
- log.logConfig("STARTING DNS PREFETCH");
- // start to prefetch IPs from DNS
- String dom;
- final long start = System.currentTimeMillis();
- String result = "";
- fileCount = 0;
- while ((doms.size() > 0) && (fileCount < 50) && ((System.currentTimeMillis() - start) < 60000)) {
- if (Thread.currentThread().isInterrupted()) return;
- dom = doms.getMaxObject();
- final InetAddress ip = serverDomains.dnsResolve(dom);
- if (ip == null) continue;
- result += ", " + dom + "=" + ip.getHostAddress();
- log.logConfig("PRE-FILLED " + dom + "=" + ip.getHostAddress());
- fileCount++;
- doms.deleteScore(dom);
- // wait a short while to prevent that this looks like a DoS
- try {
- Thread.sleep(100);
- } catch (final InterruptedException e) {
- return;
- }
- }
- if (result.length() > 2) log.logConfig("PRE-FILLED DNS CACHE, FETCHED " + fileCount +
- " ADDRESSES: " + result.substring(2));
- }
-
- private static String dom(final File f) {
- String s = f.toString().substring(cachePath.toString().length() + 1);
- int p = s.indexOf("/");
- if (p < 0) p = s.indexOf("\\");
- if (p < 0) return null;
- // remove the protokoll
- s = s.substring(p + 1);
- p = s.indexOf("/");
- if (p < 0) p = s.indexOf("\\");
- if (p < 0) return null;
- String prefix = "";
- if (s.startsWith("www")) prefix = "www.";
- // remove the www|other|ip directory
- s = s.substring(p + 1);
- p = s.indexOf("/");
- if (p < 0) p = s.indexOf("\\");
- if (p < 0) return null;
- final int e = s.indexOf("!");
- if ((e > 0) && (e < p)) p = e; // strip port
- return prefix + s.substring(0, p);
+ fileDB.close();
}
public static boolean full() {
@@ -446,259 +234,7 @@ public final class plasmaHTCache {
return plasmaParser.mediaExtContains(urlString);
}
- private static String replaceRegex(String input, final String regex, final String replacement) {
- if (input == null) { return ""; }
- if (input.length() > 0) {
- final Pattern searchPattern = Pattern.compile(regex);
- final Matcher matcher = searchPattern.matcher(input);
- while (matcher.find()) {
- input = matcher.replaceAll(replacement);
- matcher.reset(input);
- }
- }
- return input;
- }
-
- /**
- * this method creates from a given host and path a cache path
- * from a given host (which may also be an IPv4 - number, but not IPv6 or
- * a domain; all without leading 'http://') and a path (which must start
- * with a leading '/', and may also end in an '/') a path to a file
- * in the file system with root as given in cachePath is constructed
- * it will also be ensured, that the complete path exists; if necessary
- * that path will be generated
- * @return new File
- */
- public static File getCachePath(final yacyURL url) {
-// this.log.logFinest("plasmaHTCache: getCachePath: IN=" + url.toString());
-
- // peer.yacy || www.peer.yacy = http/yacy/peer
- // protocol://www.doamin.net = protocol/www/domain.net
- // protocol://other.doamin.net = protocol/other/other.domain.net
- // protocol://xxx.xxx.xxx.xxx = protocol/ip/xxx.xxx.xxx.xxx
-
- String host = url.getHost().toLowerCase();
-
- String path = url.getPath();
- final String query = url.getQuery();
- if (!path.startsWith("/")) { path = "/" + path; }
- if (path.endsWith("/") && query == null) { path = path + "ndx"; }
-
- // yes this is not reversible, but that is not needed
- path = replaceRegex(path, "/\\.\\./", "/!!/");
- path = replaceRegex(path, "(\"|\\\\|\\*|\\?|:|<|>|\\|+)", "_"); // hier wird kein '/' gefiltert
- String extention = null;
- final int d = path.lastIndexOf(".");
- final int s = path.lastIndexOf("/");
- if ((d >= 0) && (d > s)) {
- extention = path.substring(d);
- } else if (path.endsWith("/ndx")) {
- extention = ".html"; // Just a wild guess
- }
- path = path.concat(replaceRegex(query, "(\"|\\\\|\\*|\\?|/|:|<|>|\\|+)", "_"));
-
- // only set NO default ports
- int port = url.getPort();
- String protocol = url.getProtocol();
- if (port >= 0) {
- if ((port == 80 && protocol.equals("http" )) ||
- (port == 443 && protocol.equals("https")) ||
- (port == 21 && protocol.equals("ftp" ))) {
- port = -1;
- }
- }
- if (host.endsWith(".yacy")) {
- host = host.substring(0, host.length() - 5);
- if (host.startsWith("www.")) {
- host = host.substring(4);
- }
- protocol = "yacy";
- } else if (host.startsWith("www.")) {
- host = "www/" + host.substring(4);
- } else if (host.matches("\\d{2,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}")) {
- host = "ip/" + host;
- } else {
- host = "other/" + host;
- }
- final StringBuffer fileName = new StringBuffer();
- fileName.append(protocol).append('/').append(host);
- if (port >= 0) {
- fileName.append('!').append(port);
- }
-
- // generate cache path
- final File FileFlat = hashFile(fileName, "hash", extention, url.hash());
- return FileFlat;
- }
-
- private static File hashFile(final StringBuffer fileName, final String prefix, final String extention, final String urlhash) {
- final String hexHash = yacySeed.b64Hash2hexHash(urlhash);
- final StringBuffer f = new StringBuffer(fileName.length() + 30);
- f.append(fileName);
- if (prefix != null) f.append('/').append(prefix);
- f.append('/').append(hexHash.substring(0,2)).append('/').append(hexHash.substring(2,4)).append('/').append(hexHash);
- if (extention != null) fileName.append(extention);
- return new File(cachePath, f.toString());
- }
-
- /**
- * This is a helper function that extracts the Hash from the filename
- */
- public static String getHash(final File f) {
- if ((!f.isFile()) || (f.getPath().indexOf("hash") < 0)) return null;
- final String name = f.getName();
- if (name.length() < 18) return null; // not a hash file name
- final String hexHash = name.substring(0,18);
- if (hexHash.indexOf('.') >= 0) return null;
- try {
- final String hash = kelondroBase64Order.enhancedCoder.encode(serverCodings.decodeHex(hexHash));
- if (hash.length() == yacySeedDB.commonHashLength) return hash;
- return null;
- } catch (final Exception e) {
- //log.logWarning("getHash: " + e.getMessage(), e);
- return null;
- }
- }
-
- /**
- * this is the reverse function to getCachePath: it constructs the url as string
- * from a given storage path
- */
- public static yacyURL getURL(final File f) {
-// this.log.logFinest("plasmaHTCache: getURL: IN: Path=[" + cachePath + "] File=[" + f + "]");
- final String urlHash = getHash(f);
- if (urlHash != null) {
- yacyURL url = null;
- // try the urlPool
- try {
- url = plasmaSwitchboard.getSwitchboard().getURL(urlHash);
- } catch (final Exception e) {
- log.logWarning("getURL(" + urlHash + "): " /*+ e.getMessage()*/, e);
- url = null;
- }
- if (url != null) return url;
- // try responseHeaderDB
- Map<String, String> hdb;
- try {
- hdb = responseHeaderDB.get(urlHash);
- } catch (final IOException e1) {
- hdb = null;
- }
- if (hdb != null) {
- final Object origRequestLine = hdb.get(httpResponseHeader.X_YACY_ORIGINAL_REQUEST_LINE);
- if ((origRequestLine != null)&&(origRequestLine instanceof String)) {
- int i = ((String)origRequestLine).indexOf(" ");
- if (i >= 0) {
- final String s = ((String)origRequestLine).substring(i).trim();
- i = s.indexOf(" ");
- try {
- url = new yacyURL((i<0) ? s : s.substring(0,i), urlHash);
- } catch (final Exception e) {
- url = null;
- }
- }
- }
- }
- if (url != null) return url;
- }
- // If we can't get the correct URL, it seems to be a treeed file
- final String c = cachePath.toString().replace('\\', '/');
- String path = f.toString().replace('\\', '/');
- int pos;
- if ((pos = path.indexOf("/tree")) >= 0) path = path.substring(0, pos) + path.substring(pos + 5);
-
- if (path.endsWith("ndx")) { path = path.substring(0, path.length() - 3); }
-
- if ((pos = path.lastIndexOf(c)) == 0) {
- path = path.substring(pos + c.length());
- while (path.startsWith("/")) { path = path.substring(1); }
-
- pos = path.indexOf("!");
- if (pos >= 0) {
- path = path.substring(0, pos) + ":" + path.substring(pos + 1);
- }
-
- String protocol = "http://";
- String host = "";
- if (path.startsWith("yacy/")) {
- path = path.substring(5);
-
- pos = path.indexOf("/");
- if (pos > 0) {
- host = path.substring(0, pos);
- path = path.substring(pos);
- } else {
- host = path;
- path = "";
- }
- pos = host.indexOf(":");
- if (pos > 0) {
- host = host.substring(0, pos) + ".yacy" + host.substring(pos);
- } else {
- host = host + ".yacy";
- }
-
- } else {
- if (path.startsWith("http/")) {
- path = path.substring(5);
- } else if (path.startsWith("https/")) {
- protocol = "https://";
- path = path.substring(6);
- } else if (path.startsWith("ftp/")) {
- protocol = "ftp://";
- path = path.substring(4);
- } else {
- return null;
- }
- if (path.startsWith("www/")) {
- path = path.substring(4);
- host = "www.";
- } else if (path.startsWith("other/")) {
- path = path.substring(6);
- } else if (path.startsWith("ip/")) {
- path = path.substring(3);
- }
- pos = path.indexOf("/");
- if (pos > 0) {
- host = host + path.substring(0, pos);
- path = path.substring(pos);
- } else {
- host = host + path;
- path = "";
- }
- }
-
- if (!path.equals("")) {
- final Pattern pathPattern = Pattern.compile("/!!/");
- final Matcher matcher = pathPattern.matcher(path);
- while (matcher.find()) {
- path = matcher.replaceAll("/\\.\\./");
- matcher.reset(path);
- }
- }
-// this.log.logFinest("plasmaHTCache: getURL: OUT=" + s);
- try {
- return new yacyURL(protocol + host + path, null);
- } catch (final Exception e) {
- return null;
- }
- }
- return null;
- }
-
- /**
- * @return the responseHeaderDB
- */
- static kelondroMap getResponseHeaderDB() {
- return responseHeaderDB;
- }
-
-
- /*
- * ACCESS METHODS
- */
-
// Store to Cache
public static void storeMetadata(
@@ -715,62 +251,18 @@ public final class plasmaHTCache {
} catch (final Exception e) {
log.logWarning("could not write ResourceInfo: "
+ e.getClass() + ": " + e.getMessage());
- resetResponseHeaderDB();
+ resetDB();
}
}
- public static boolean writeResourceContent(final yacyURL url, final byte[] array) {
- if (array == null) return false;
- final File file = getCachePath(url);
+
+ public static void storeFile(yacyURL url, byte[] file) {
try {
- deleteFile(file);
- file.getParentFile().mkdirs();
- serverFileUtils.copy(array, file);
- } catch (final FileNotFoundException e) {
- // this is the case of a "(Not a directory)" error, which should be prohibited
- // by the shallStoreCache() property. However, sometimes the error still occurs
- // In this case do nothing.
- log.logSevere("File storage failed (not a directory): " + e.getMessage());
- return false;
- } catch (final IOException e) {
- log.logSevere("File storage failed (IO error): " + e.getMessage());
- return false;
- }
- writeFileAnnouncement(file);
- return true;
- }
-
- public static void writeFileAnnouncement(final File file) {
- if (file.exists()) {
- curCacheSize += file.length();
- if (System.currentTimeMillis() - lastcleanup > 300000) {
- // call the cleanup job only every 5 minutes
- cleanup();
- lastcleanup = System.currentTimeMillis();
- }
- cacheAge.put(ageString(file.lastModified(), file), file);
+ fileDB.put(url.hash().getBytes(), file);
+ } catch (IOException e) {
+ e.printStackTrace();
}
}
-
- // Delete from Cache
-
- public static boolean deleteURLfromCache(final yacyURL url, final boolean keepHeader) {
- if (deleteFileandDirs(getCachePath(url), "FROM") && !keepHeader) {
- try {
- // As the file is gone, the entry in responseHeader.db is not needed anymore
- if (log.isFinest()) log.logFinest("Trying to remove responseHeader from URL: " + url.toNormalform(false, true));
- responseHeaderDB.remove(url.hash());
- } catch (final IOException e) {
- resetResponseHeaderDB();
- log.logWarning("IOExeption removing response header from DB: " + e.getMessage(), e);
- }
- return true;
- }
- return false;
- }
-
-
- // Read from Cache
/**
* Returns an object containing metadata about a cached resource
@@ -804,24 +296,33 @@ public final class plasmaHTCache {
*/
public static InputStream getResourceContentStream(final yacyURL url) {
// load the url as resource from the cache
- final File f = getCachePath(url);
- if (f.exists() && f.canRead()) try {
- return new BufferedInputStream(new FileInputStream(f));
- } catch (final IOException e) {
- log.logSevere("Unable to create a BufferedInputStream from file " + f,e);
+ byte[] b = getResourceContent(url);
+ if (b == null) return null;
+ return new ByteArrayInputStream(b);
+ }
+
+ public static byte[] getResourceContent(final yacyURL url) {
+ // load the url as resource from the cache
+ try {
+ return fileDB.get(url.hash().getBytes());
+ } catch (IOException e) {
+ e.printStackTrace();
return null;
}
- return null;
}
public static long getResourceContentLength(final yacyURL url) {
// load the url as resource from the cache
- final File f = getCachePath(url);
- if (f.exists() && f.canRead()) {
- return f.length();
- }
- return 0;
+ try {
+ return fileDB.length(url.hash().getBytes());
+ } catch (IOException e) {
+ e.printStackTrace();
+ return -1;
+ }
}
-
+ public static void deleteFromCache(yacyURL url) throws IOException {
+ responseHeaderDB.remove(url.hash());
+ fileDB.remove(url.hash().getBytes());
+ }
}
diff --git a/source/de/anomic/plasma/plasmaSnippetCache.java b/source/de/anomic/plasma/plasmaSnippetCache.java
index b22f30fdf..f0668366e 100644
--- a/source/de/anomic/plasma/plasmaSnippetCache.java
+++ b/source/de/anomic/plasma/plasmaSnippetCache.java
@@ -796,7 +796,7 @@ public class plasmaSnippetCache {
// STEP 3: if the metadata is still null try to guess the mimeType of the resource
if (responseHeader == null) {
- final String filename = plasmaHTCache.getCachePath(url).getName();
+ final String filename = url.getFileName();
final int p = filename.lastIndexOf('.');
if ( // if no extension is available
(p < 0) ||
diff --git a/source/de/anomic/plasma/plasmaSwitchboard.java b/source/de/anomic/plasma/plasmaSwitchboard.java
index 04b350fbf..4831a0479 100644
--- a/source/de/anomic/plasma/plasmaSwitchboard.java
+++ b/source/de/anomic/plasma/plasmaSwitchboard.java
@@ -1041,10 +1041,10 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
if (entry.cacheArray() != null) {
final String error = entry.shallStoreCacheForProxy();
if (error == null) {
- plasmaHTCache.writeResourceContent(entry.url(), entry.cacheArray());
- if (this.log.isFine()) this.log.logFine("WROTE FILE (" + entry.cacheArray().length + " bytes) for " + entry.cacheFile());
+ plasmaHTCache.storeFile(entry.url(), entry.cacheArray());
+ if (this.log.isFine()) this.log.logFine("WROTE FILE (" + entry.cacheArray().length + " bytes) for " + entry.url());
} else {
- if (this.log.isFine()) this.log.logFine("WRITE OF FILE " + entry.cacheFile() + " FORBIDDEN: " + error);
+ if (this.log.isFine()) this.log.logFine("WRITE OF FILE " + entry.url() + " FORBIDDEN: " + error);
}
//} else {
//this.log.logFine("EXISTING FILE (" + entry.cacheFile.length() + " bytes) for " + entry.cacheFile);
@@ -1068,8 +1068,12 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
entry.name()
));
} else {
- if (!entry.profile().storeHTCache() && entry.cacheFile().exists()) {
- plasmaHTCache.deleteURLfromCache(entry.url(), false);
+ if (!entry.profile().storeHTCache()) {
+ try {
+ plasmaHTCache.deleteFromCache(entry.url());
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
}
}
}
@@ -1581,7 +1585,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
try {
// parse the document
- document = parser.parseSource(entry.url(), entry.getMimeType(), entry.getCharacterEncoding(), entry.cacheFile());
+ document = parser.parseSource(entry.url(), entry.getMimeType(), entry.getCharacterEncoding(), plasmaHTCache.getResourceContent(entry.url()));
assert(document != null) : "Unexpected error. Parser returned null.";
if (document == null) return null;
} catch (final ParserException e) {