Skip to content

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

added final where possible

danielr3bb870bfcd43
diff --git a/htroot/AccessTracker_p.java b/htroot/AccessTracker_p.java
index 41d664db9..286660674 100644
--- a/htroot/AccessTracker_p.java
+++ b/htroot/AccessTracker_p.java
@@ -45,28 +45,28 @@ import de.anomic.yacy.yacySeed;
public class AccessTracker_p {
- private static final TreeMap<Long, String> treemapclone(TreeMap<Long, String> m) {
- TreeMap<Long, String> accessClone = new TreeMap<Long, String>();
+ private static final TreeMap<Long, String> treemapclone(final TreeMap<Long, String> m) {
+ final TreeMap<Long, String> accessClone = new TreeMap<Long, String>();
try {
accessClone.putAll(m);
- } catch (ConcurrentModificationException e) {}
+ } catch (final ConcurrentModificationException e) {}
return accessClone;
}
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
// return variable that accumulates replacements
- serverObjects prop = new serverObjects();
+ final serverObjects prop = new serverObjects();
prop.setLocalized(!(header.get("PATH")).endsWith(".xml"));
int page = 0;
if (post != null) page = post.getInt("page", 0);
prop.put("page", page);
- int maxCount = 1000;
+ final int maxCount = 1000;
boolean dark = true;
if (page == 0) {
- Iterator<String> i = sb.accessHosts();
+ final Iterator<String> i = sb.accessHosts();
String host;
TreeMap<Long, String> access;
int entCount = 0;
@@ -81,18 +81,18 @@ public class AccessTracker_p {
prop.putNum("page_list_" + entCount + "_countHour", access.tailMap(new Long(System.currentTimeMillis() - 1000 * 60 * 60)).size());
entCount++;
}
- } catch (ConcurrentModificationException e) {} // we don't want to synchronize this
+ } catch (final ConcurrentModificationException e) {} // we don't want to synchronize this
prop.put("page_list", entCount);
prop.put("page_num", entCount);
entCount = 0;
try {
- for (Map.Entry<String, Integer> bfe: serverCore.bfHost.entrySet()) {
+ for (final Map.Entry<String, Integer> bfe: serverCore.bfHost.entrySet()) {
prop.putHTML("page_bflist_" + entCount + "_host", bfe.getKey());
prop.putNum("page_bflist_" + entCount + "_countSecond", bfe.getValue());
entCount++;
}
- } catch (ConcurrentModificationException e) {} // we dont want to synchronize this
+ } catch (final ConcurrentModificationException e) {} // we dont want to synchronize this
prop.put("page_bflist", entCount);
}
if (page == 1) {
@@ -104,7 +104,7 @@ public class AccessTracker_p {
access = sb.accessTrack(host);
if (access != null) {
try {
- Iterator<Map.Entry<Long, String>> ii = treemapclone(access).entrySet().iterator();
+ final Iterator<Map.Entry<Long, String>> ii = treemapclone(access).entrySet().iterator();
while (ii.hasNext()) {
entry = ii.next();
prop.putHTML("page_list_" + entCount + "_host", host);
@@ -112,15 +112,15 @@ public class AccessTracker_p {
prop.putHTML("page_list_" + entCount + "_path", entry.getValue());
entCount++;
}
- } catch (ConcurrentModificationException e) {} // we don't want to synchronize this
+ } catch (final ConcurrentModificationException e) {} // we don't want to synchronize this
}
} else {
try {
- Iterator<String> i = sb.accessHosts();
+ final Iterator<String> i = sb.accessHosts();
while ((entCount < maxCount) && (i.hasNext())) {
host = i.next();
access = sb.accessTrack(host);
- Iterator<Map.Entry<Long, String>> ii = treemapclone(access).entrySet().iterator();
+ final Iterator<Map.Entry<Long, String>> ii = treemapclone(access).entrySet().iterator();
while (ii.hasNext()) {
entry = ii.next();
prop.putHTML("page_list_" + entCount + "_host", host);
@@ -129,13 +129,13 @@ public class AccessTracker_p {
entCount++;
}
}
- } catch (ConcurrentModificationException e) {} // we dont want to synchronize this
+ } catch (final ConcurrentModificationException e) {} // we dont want to synchronize this
}
prop.put("page_list", entCount);
prop.put("page_num", entCount);
}
if ((page == 2) || (page == 4)) {
- ArrayList<plasmaSearchQuery> array = (page == 2) ? sb.localSearches : sb.remoteSearches;
+ final ArrayList<plasmaSearchQuery> array = (page == 2) ? sb.localSearches : sb.remoteSearches;
plasmaSearchQuery searchProfile;
int m = Math.min(maxCount, array.size());
long qcountSum = 0;
@@ -186,7 +186,7 @@ public class AccessTracker_p {
prop.putNum("page_total", (page == 2) ? sb.localSearches.size() : sb.remoteSearches.size());
}
if ((page == 3) || (page == 5)) {
- Iterator<Entry<String, TreeSet<Long>>> i = (page == 3) ? sb.localSearchTracker.entrySet().iterator() : sb.remoteSearchTracker.entrySet().iterator();
+ final Iterator<Entry<String, TreeSet<Long>>> i = (page == 3) ? sb.localSearchTracker.entrySet().iterator() : sb.remoteSearchTracker.entrySet().iterator();
String host;
TreeSet<Long> handles;
int entCount = 0;
@@ -199,22 +199,22 @@ public class AccessTracker_p {
handles = entry.getValue();
int dateCount = 0;
- Iterator<Long> ii = handles.iterator();
+ final Iterator<Long> ii = handles.iterator();
while (ii.hasNext()) {
- Long timestamp = ii.next();
+ final Long timestamp = ii.next();
prop.put("page_list_" + entCount + "_dates_" + dateCount + "_date", serverDate.formatShortSecond(new Date(timestamp.longValue())));
prop.put("page_list_" + entCount + "_dates_" + dateCount + "_timestamp", timestamp.toString());
dateCount++;
}
prop.put("page_list_" + entCount + "_dates", dateCount);
- int qph = handles.tailSet(new Long(System.currentTimeMillis() - 1000 * 60 * 60)).size();
+ final int qph = handles.tailSet(new Long(System.currentTimeMillis() - 1000 * 60 * 60)).size();
qphSum += qph;
prop.put("page_list_" + entCount + "_qph", qph);
prop.put("page_list_" + entCount + "_dark", ((dark) ? 1 : 0) ); dark =! dark;
prop.putHTML("page_list_" + entCount + "_host", host);
if (page == 5) {
- yacySeed remotepeer = sb.webIndex.seedDB.lookupByIP(natLib.getInetAddress(host), true, true, true);
+ final yacySeed remotepeer = sb.webIndex.seedDB.lookupByIP(natLib.getInetAddress(host), true, true, true);
prop.putHTML("page_list_" + entCount + "_peername", (remotepeer == null) ? "UNKNOWN" : remotepeer.getName());
}
prop.putNum("page_list_" + entCount + "_count", handles.size());
@@ -222,7 +222,7 @@ public class AccessTracker_p {
// next
entCount++;
}
- } catch (ConcurrentModificationException e) {} // we dont want to synchronize this
+ } catch (final ConcurrentModificationException e) {} // we dont want to synchronize this
prop.put("page_list", entCount);
prop.putNum("page_num", entCount);
prop.putNum("page_total", (page == 3) ? sb.localSearches.size() : sb.remoteSearches.size());
diff --git a/htroot/Banner.java b/htroot/Banner.java
index 7a25fcc04..bff20bcf0 100644
--- a/htroot/Banner.java
+++ b/htroot/Banner.java
@@ -42,8 +42,8 @@ import de.anomic.ymage.ymageMatrix;
/** draw a banner with information about the peer */
public class Banner {
- public static ymageMatrix respond(httpHeader header, serverObjects post, serverSwitch<?> env) throws IOException {
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ public static ymageMatrix respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) throws IOException {
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
final String IMAGE = "htroot/env/grafics/yacy.gif";
int width = 468;
int height = 60;
@@ -65,15 +65,15 @@ public class Banner {
int myppm = 0;
double myqph = 0;
String type = "";
- String network = env.getConfig("network.unit.name", "unspecified").toUpperCase();
- int peers = sb.webIndex.seedDB.sizeConnected() + 1; // the '+ 1': the own peer is not included in sizeConnected()
+ final String network = env.getConfig("network.unit.name", "unspecified").toUpperCase();
+ final int peers = sb.webIndex.seedDB.sizeConnected() + 1; // the '+ 1': the own peer is not included in sizeConnected()
long nlinks = sb.webIndex.seedDB.countActiveURL();
long nwords = sb.webIndex.seedDB.countActiveRWI();
- double nqpm = sb.webIndex.seedDB.countActiveQPM();
+ final double nqpm = sb.webIndex.seedDB.countActiveQPM();
long nppm = sb.webIndex.seedDB.countActivePPM();
double nqph = 0;
- yacySeed seed = sb.webIndex.seedDB.mySeed();
+ final yacySeed seed = sb.webIndex.seedDB.mySeed();
if (seed != null){
name = seed.get(yacySeed.NAME, "-").toUpperCase();
links = Long.parseLong(seed.get(yacySeed.LCOUNT, "0"));
@@ -103,7 +103,7 @@ public class Banner {
}
if (!plasmaGrafics.logoIsLoaded()) {
- BufferedImage logo = ImageIO.read(new File(IMAGE));
+ final BufferedImage logo = ImageIO.read(new File(IMAGE));
return plasmaGrafics.getBannerPicture(1000, width, height, bgcolor, textcolor, bordercolor, name, links, words, type, myppm, network, peers, nlinks, nwords, nqph, nppm, logo);
}
diff --git a/htroot/BlacklistCleaner_p.java b/htroot/BlacklistCleaner_p.java
index be742628f..5a367a34f 100644
--- a/htroot/BlacklistCleaner_p.java
+++ b/htroot/BlacklistCleaner_p.java
@@ -70,8 +70,8 @@ public class BlacklistCleaner_p {
indexDefaultReferenceBlacklist.class
};
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
- serverObjects prop = new serverObjects();
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
+ final serverObjects prop = new serverObjects();
// initialize the list manager
listManager.switchboard = (plasmaSwitchboard) env;
@@ -79,8 +79,8 @@ public class BlacklistCleaner_p {
String blacklistToUse = null;
// getting the list of supported blacklist types
- String supportedBlacklistTypesStr = indexAbstractReferenceBlacklist.BLACKLIST_TYPES_STRING;
- String[] supportedBlacklistTypes = supportedBlacklistTypesStr.split(",");
+ final String supportedBlacklistTypesStr = indexAbstractReferenceBlacklist.BLACKLIST_TYPES_STRING;
+ final String[] supportedBlacklistTypes = supportedBlacklistTypesStr.split(",");
if (post == null) {
prop.put("results", "0");
@@ -108,13 +108,13 @@ public class BlacklistCleaner_p {
}
// list illegal entries
- HashMap<String, Integer> ies = getIllegalEntries(blacklistToUse, supportedBlacklistTypes, plasmaSwitchboard.urlBlacklist);
+ final HashMap<String, Integer> ies = getIllegalEntries(blacklistToUse, supportedBlacklistTypes, plasmaSwitchboard.urlBlacklist);
prop.put(RESULTS + "entries", ies.size());
prop.putHTML(RESULTS + "blEngine", plasmaSwitchboard.urlBlacklist.getEngineInfo());
prop.put(RESULTS + "disabled", (ies.size() == 0) ? "1" : "0");
if (ies.size() > 0) {
prop.put(RESULTS + DISABLED + "entries", ies.size());
- Iterator<String> it = ies.keySet().iterator();
+ final Iterator<String> it = ies.keySet().iterator();
int i = 0;
String s;
while (it.hasNext()) {
@@ -129,7 +129,7 @@ public class BlacklistCleaner_p {
return prop;
}
- private static void putBlacklists(serverObjects prop, String[] lists, String selected) {
+ private static void putBlacklists(final serverObjects prop, final String[] lists, final String selected) {
boolean supported = false;
for (int i=0; i<supportedBLEngines.length && !supported; i++) {
supported |= (plasmaSwitchboard.urlBlacklist.getClass() == supportedBLEngines[i]);
@@ -155,7 +155,7 @@ public class BlacklistCleaner_p {
}
}
- private static String[] getByPrefix(serverObjects post, String prefix, boolean useKeys, boolean useHashSet) {
+ private static String[] getByPrefix(final serverObjects post, final String prefix, final boolean useKeys, final boolean useHashSet) {
Collection<String> r;
if (useHashSet) {
r = new HashSet<String>();
@@ -165,14 +165,14 @@ public class BlacklistCleaner_p {
String s;
if (useKeys) {
- Iterator<String> it = post.keySet().iterator();
+ final Iterator<String> it = post.keySet().iterator();
while (it.hasNext()) {
if ((s = it.next()).indexOf(prefix) == 0) {
r.add(s.substring(prefix.length()));
}
}
} else {
- Iterator<Map.Entry<String, String>> it = post.entrySet().iterator();
+ final Iterator<Map.Entry<String, String>> it = post.entrySet().iterator();
Map.Entry<String, String> entry;
while (it.hasNext()) {
entry = it.next();
@@ -185,12 +185,12 @@ public class BlacklistCleaner_p {
return r.toArray(new String[r.size()]);
}
- private static HashMap<String, Integer>/* entry, error-code */ getIllegalEntries(String blacklistToUse, String[] supportedBlacklistTypes, indexReferenceBlacklist blEngine) {
- HashMap<String, Integer> r = new HashMap<String, Integer>();
- HashSet<String> ok = new HashSet<String>();
+ private static HashMap<String, Integer>/* entry, error-code */ getIllegalEntries(final String blacklistToUse, final String[] supportedBlacklistTypes, final indexReferenceBlacklist blEngine) {
+ final HashMap<String, Integer> r = new HashMap<String, Integer>();
+ final HashSet<String> ok = new HashSet<String>();
- ArrayList<String> list = listManager.getListArray(new File(listManager.listsPath, blacklistToUse));
- Iterator<String> it = list.iterator();
+ final ArrayList<String> list = listManager.getListArray(new File(listManager.listsPath, blacklistToUse));
+ final Iterator<String> it = list.iterator();
String s, host, path;
if (blEngine instanceof indexDefaultReferenceBlacklist) {
@@ -213,7 +213,7 @@ public class BlacklistCleaner_p {
path = s.substring(slashPos + 1);
}
- int i = host.indexOf("*");
+ final int i = host.indexOf("*");
// check whether host begins illegally
if (!host.matches("([A-Za-z0-9_-]+|\\*)(\\.([A-Za-z0-9_-]+|\\*))*")) {
@@ -247,7 +247,7 @@ public class BlacklistCleaner_p {
// check for errors on regex-compiling path
try {
Pattern.compile(path);
- } catch (PatternSyntaxException e) {
+ } catch (final PatternSyntaxException e) {
r.put(s, new Integer(ERR_PATH_REGEX));
continue;
}
@@ -257,9 +257,9 @@ public class BlacklistCleaner_p {
return r;
}
- private static int removeEntries(String blacklistToUse, String[] supportedBlacklistTypes, String[] entries) {
+ private static int removeEntries(final String blacklistToUse, final String[] supportedBlacklistTypes, final String[] entries) {
// load blacklist data from file
- ArrayList<String> list = listManager.getListArray(new File(listManager.listsPath, blacklistToUse));
+ final ArrayList<String> list = listManager.getListArray(new File(listManager.listsPath, blacklistToUse));
// delete the old entry from file
String s;
@@ -274,12 +274,12 @@ public class BlacklistCleaner_p {
// remove the entry from the running blacklist engine
for (int blTypes=0; blTypes < supportedBlacklistTypes.length; blTypes++) {
if (listManager.listSetContains(supportedBlacklistTypes[blTypes] + ".BlackLists", blacklistToUse)) {
- String host = (s.indexOf("/") == -1) ? s : s.substring(0, s.indexOf("/"));
- String path = (s.indexOf("/") == -1) ? ".*" : s.substring(s.indexOf("/") + 1);
+ final String host = (s.indexOf("/") == -1) ? s : s.substring(0, s.indexOf("/"));
+ final String path = (s.indexOf("/") == -1) ? ".*" : s.substring(s.indexOf("/") + 1);
try {
plasmaSwitchboard.urlBlacklist.remove(supportedBlacklistTypes[blTypes],
host,path);
- } catch (RuntimeException e) {
+ } catch (final RuntimeException e) {
//System.err.println(e.getMessage() + ": " + host + "/" + path);
serverLog.logSevere("BLACKLIST-CLEANER", e.getMessage() + ": " + host + "/" + path);
}
@@ -293,10 +293,10 @@ public class BlacklistCleaner_p {
}
private static int alterEntries(
- String blacklistToUse,
- String[] supportedBlacklistTypes,
- String[] oldE,
- String[] newE) {
+ final String blacklistToUse,
+ final String[] supportedBlacklistTypes,
+ final String[] oldE,
+ final String[] newE) {
removeEntries(blacklistToUse, supportedBlacklistTypes, oldE);
PrintWriter pw = null;
try {
@@ -322,7 +322,7 @@ public class BlacklistCleaner_p {
}
}
pw.close();
- } catch (IOException e) {
+ } catch (final IOException e) {
serverLog.logSevere("BLACKLIST-CLEANER", "error on writing altered entries to blacklist", e);
}
return newE.length;
diff --git a/htroot/Blacklist_p.java b/htroot/Blacklist_p.java
index d3eba9630..8248a55b5 100644
--- a/htroot/Blacklist_p.java
+++ b/htroot/Blacklist_p.java
@@ -54,19 +54,19 @@ public class Blacklist_p {
private final static String BLACKLIST = "blackLists_";
private final static String BLACKLIST_SHARED = "BlackLists.Shared";
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
// initialize the list manager
listManager.switchboard = (plasmaSwitchboard) env;
listManager.listsPath = new File(listManager.switchboard.getRootPath(),listManager.switchboard.getConfig("listManager.listsPath", "DATA/LISTS"));
// getting the list of supported blacklist types
- String supportedBlacklistTypesStr = indexAbstractReferenceBlacklist.BLACKLIST_TYPES_STRING;
- String[] supportedBlacklistTypes = supportedBlacklistTypesStr.split(",");
+ final String supportedBlacklistTypesStr = indexAbstractReferenceBlacklist.BLACKLIST_TYPES_STRING;
+ final String[] supportedBlacklistTypes = supportedBlacklistTypesStr.split(",");
String blacklistToUse = null;
- serverObjects prop = new serverObjects();
+ final serverObjects prop = new serverObjects();
prop.putHTML("blacklistEngine", plasmaSwitchboard.urlBlacklist.getEngineInfo());
prop.putHTML("asd", "0");
// do all post operations
@@ -79,7 +79,7 @@ prop.putHTML("asd", "0");
yacyURL testurl = null;
try {
testurl = new yacyURL(urlstring, null);
- } catch (MalformedURLException e) { }
+ } catch (final MalformedURLException e) { }
if(testurl != null) {
prop.putHTML("testlist_url",testurl.toString());
if(plasmaSwitchboard.urlBlacklist.isListed(indexReferenceBlacklist.BLACKLIST_CRAWLER, testurl))
@@ -125,7 +125,7 @@ prop.putHTML("asd", "0");
for (int blTypes=0; blTypes < supportedBlacklistTypes.length; blTypes++) {
listManager.updateListSet(supportedBlacklistTypes[blTypes] + ".BlackLists",blacklistToUse);
}
- } catch (IOException e) {/* */}
+ } catch (final IOException e) {/* */}
} else if (post.containsKey("deleteList")) {
/* ===========================================================
@@ -138,7 +138,7 @@ prop.putHTML("asd", "0");
return prop;
}
- File BlackListFile = new File(listManager.listsPath, blacklistToUse);
+ final File BlackListFile = new File(listManager.listsPath, blacklistToUse);
BlackListFile.delete();
for (int blTypes=0; blTypes < supportedBlacklistTypes.length; blTypes++) {
@@ -194,7 +194,7 @@ prop.putHTML("asd", "0");
}
} else if (post.containsKey("deleteBlacklistEntry")) {
- String temp = deleteBlacklistEntry(post.get("currentBlacklist"),
+ final String temp = deleteBlacklistEntry(post.get("currentBlacklist"),
post.get("selectedEntry"), header, supportedBlacklistTypes);
if (temp != null) {
prop.put("LOCATION", temp);
@@ -203,7 +203,7 @@ prop.putHTML("asd", "0");
} else if (post.containsKey("addBlacklistEntry")) {
- String temp = addBlacklistEntry(post.get("currentBlacklist"),
+ final String temp = addBlacklistEntry(post.get("currentBlacklist"),
post.get("newEntry"), header, supportedBlacklistTypes);
if (temp != null) {
prop.put("LOCATION", temp);
@@ -258,8 +258,8 @@ prop.putHTML("asd", "0");
} else {
- String selectedEntry = post.get("selectedEntry");
- String currentBlacklist = post.get("currentBlacklist");
+ final String selectedEntry = post.get("selectedEntry");
+ final String currentBlacklist = post.get("currentBlacklist");
if (selectedEntry != null && currentBlacklist != null) {
prop.put(DISABLED + "edit_item", selectedEntry);
prop.put(DISABLED + "edit_currentBlacklist", currentBlacklist);
@@ -271,7 +271,7 @@ prop.putHTML("asd", "0");
}
// loading all blacklist files located in the directory
- String[] dirlist = listManager.getDirListing(listManager.listsPath);
+ final String[] dirlist = listManager.getDirListing(listManager.listsPath);
// if we have not chosen a blacklist until yet we use the first file
if (blacklistToUse == null && dirlist != null && dirlist.length > 0) {
@@ -285,12 +285,12 @@ prop.putHTML("asd", "0");
final ArrayList<String> list = listManager.getListArray(new File(listManager.listsPath, blacklistToUse));
// sort them
- String[] sortedlist = new String[list.size()];
+ final String[] sortedlist = new String[list.size()];
Arrays.sort(list.toArray(sortedlist));
// display them
for (int j=0;j<sortedlist.length;++j){
- String nextEntry = sortedlist[j];
+ final String nextEntry = sortedlist[j];
if (nextEntry.length() == 0) continue;
if (nextEntry.startsWith("#")) continue;
@@ -305,10 +305,10 @@ prop.putHTML("asd", "0");
if (sb.webIndex.seedDB != null && sb.webIndex.seedDB.sizeConnected() > 0) { // no nullpointer error
int peerCount = 0;
try {
- TreeMap<String, String> hostList = new TreeMap<String, String>();
+ final TreeMap<String, String> hostList = new TreeMap<String, String>();
final Iterator<yacySeed> e = sb.webIndex.seedDB.seedsConnected(true, false, null, (float) 0.0);
while (e.hasNext()) {
- yacySeed seed = e.next();
+ final yacySeed seed = e.next();
if (seed != null) hostList.put(seed.get(yacySeed.NAME, "nameless"),seed.hash);
}
@@ -320,7 +320,7 @@ prop.putHTML("asd", "0");
hostList.remove(peername);
peerCount++;
}
- } catch (Exception e) {/* */}
+ } catch (final Exception e) {/* */}
prop.put(DISABLED + "otherHosts", peerCount);
}
}
@@ -374,8 +374,8 @@ prop.putHTML("asd", "0");
* @param newEntry the entry that is to be added
* @return null if no error occured, else a String to put into LOCATION
*/
- private static String addBlacklistEntry(String blacklistToUse, String newEntry,
- httpHeader header, String[] supportedBlacklistTypes) {
+ private static String addBlacklistEntry(final String blacklistToUse, String newEntry,
+ final httpHeader header, final String[] supportedBlacklistTypes) {
if (blacklistToUse == null || blacklistToUse.trim().length() == 0) {
return "";
@@ -404,10 +404,10 @@ prop.putHTML("asd", "0");
pw = new PrintWriter(new FileWriter(new File(listManager.listsPath, blacklistToUse), true));
pw.println(newEntry);
pw.close();
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
} finally {
- if (pw != null) try { pw.close(); } catch (Exception e){ /* */}
+ if (pw != null) try { pw.close(); } catch (final Exception e){ /* */}
}
// add to blacklist
@@ -426,8 +426,8 @@ prop.putHTML("asd", "0");
* @param oldEntry the entry that is to be deleted
* @return null if no error occured, else a String to put into LOCATION
*/
- private static String deleteBlacklistEntry(String blacklistToUse, String oldEntry,
- httpHeader header, String[] supportedBlacklistTypes) {
+ private static String deleteBlacklistEntry(final String blacklistToUse, String oldEntry,
+ final httpHeader header, final String[] supportedBlacklistTypes) {
if (blacklistToUse == null || blacklistToUse.trim().length() == 0) {
return "";
@@ -438,7 +438,7 @@ prop.putHTML("asd", "0");
}
// load blacklist data from file
- ArrayList<String> list = listManager.getListArray(new File(listManager.listsPath, blacklistToUse));
+ final ArrayList<String> list = listManager.getListArray(new File(listManager.listsPath, blacklistToUse));
// delete the old entry from file
if (list != null) {
diff --git a/htroot/Blog.java b/htroot/Blog.java
index 8b5e801a4..442a11b2d 100644
--- a/htroot/Blog.java
+++ b/htroot/Blog.java
@@ -51,11 +51,11 @@ public class Blog {
private static SimpleDateFormat SimpleFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
// TODO: make userdefined date/time-strings (localisation)
- public static String dateString(Date date) {
+ public static String dateString(final Date date) {
return SimpleFormatter.format(date);
}
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
final plasmaSwitchboard sb = (plasmaSwitchboard) env;
final serverObjects prop = new serverObjects();
blogBoard.BlogEntry page = null;
@@ -115,7 +115,7 @@ public class Blog {
byte[] author;
try {
author = StrAuthor.getBytes("UTF-8");
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
author = StrAuthor.getBytes();
}
@@ -138,7 +138,7 @@ public class Blog {
byte[] content;
try {
content = post.get("content", "").getBytes("UTF-8");
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
content = post.get("content", "").getBytes();
}
@@ -158,7 +158,7 @@ public class Blog {
byte[] subject;
try {
subject = StrSubject.getBytes("UTF-8");
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
subject = StrSubject.getBytes();
}
@@ -184,7 +184,7 @@ public class Blog {
prop.put("mode_pageid", page.getKey());
prop.putHTML("mode_subject", new String(page.getSubject(), "UTF-8"), xml);
prop.put("mode_page-code", new String(page.getPage(), "UTF-8"));
- } catch (UnsupportedEncodingException e) {}
+ } catch (final UnsupportedEncodingException e) {}
}
else {
prop.put("mode", "3"); //access denied (no rights)
@@ -198,7 +198,7 @@ public class Blog {
prop.putHTML("mode_pageid", pagename, xml);
try {
prop.putHTML("mode_author", new String(author, "UTF-8"), xml);
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
prop.putHTML("mode_author", new String(author), xml);
}
prop.putHTML("mode_subject", post.get("subject",""), xml);
@@ -216,12 +216,12 @@ public class Blog {
prop.put("mode_pageid", pagename);
try {
prop.putHTML("mode_author",new String(page.getAuthor(), "UTF-8"), xml);
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
prop.putHTML("mode_author",new String(page.getAuthor()), xml);
}
try {
prop.putHTML("mode_subject",new String(page.getSubject(),"UTF-8"), xml);
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
prop.putHTML("mode_subject",new String(page.getSubject()), xml);
}
}
@@ -322,14 +322,14 @@ public class Blog {
// subject
try {
prop.putHTML("mode_entries_" + number + "_subject", new String(entry.getSubject(),"UTF-8"), xml);
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
prop.putHTML("mode_entries_" + number + "_subject", new String(entry.getSubject()), xml);
}
// author
try {
prop.putHTML("mode_entries_" + number + "_author", new String(entry.getAuthor(),"UTF-8"), xml);
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
prop.putHTML("mode_entries_" + number + "_author", new String(entry.getAuthor()), xml);
}
diff --git a/htroot/BlogComments.java b/htroot/BlogComments.java
index da853b27c..d826ad0fc 100644
--- a/htroot/BlogComments.java
+++ b/htroot/BlogComments.java
@@ -53,13 +53,13 @@ public class BlogComments {
private static SimpleDateFormat SimpleFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
// TODO: make userdefined date/time-strings (localisation)
- public static String dateString(Date date) {
+ public static String dateString(final Date date) {
return SimpleFormatter.format(date);
}
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
- serverObjects prop = new serverObjects();
+ public static serverObjects respond(final httpHeader header, serverObjects post, final serverSwitch<?> env) {
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ final serverObjects prop = new serverObjects();
blogBoard.BlogEntry page = null;
boolean hasRights = sb.verifyAuthentication(header, true);
@@ -72,7 +72,7 @@ public class BlogComments {
}
if(!hasRights){
- userDB.Entry userentry = sb.userDB.proxyAuth((String)header.get(httpHeader.AUTHORIZATION, "xxxxxx"));
+ final userDB.Entry userentry = sb.userDB.proxyAuth((String)header.get(httpHeader.AUTHORIZATION, "xxxxxx"));
if(userentry != null && userentry.hasRight(userDB.Entry.BLOG_RIGHT)){
hasRights=true;
}
@@ -82,8 +82,8 @@ public class BlogComments {
}
}
- String pagename = post.get("page", "blog_default");
- String ip = post.get(httpHeader.CONNECTION_PROP_CLIENTIP, "127.0.0.1");
+ final String pagename = post.get("page", "blog_default");
+ final String ip = post.get(httpHeader.CONNECTION_PROP_CLIENTIP, "127.0.0.1");
String StrAuthor = post.get("author", "anonymous");
@@ -103,7 +103,7 @@ public class BlogComments {
byte[] author;
try {
author = StrAuthor.getBytes("UTF-8");
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
author = StrAuthor.getBytes();
}
@@ -124,22 +124,22 @@ public class BlogComments {
if(post.get("subject", "").equals("")) post.putHTML("subject", "no title");
try {
content = post.get("content", "").getBytes("UTF-8");
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
content = post.get("content", "").getBytes();
}
- Date date = null;
+ final Date date = null;
//set name for new entry or date for old entry
- String StrSubject = post.get("subject", "");
+ final String StrSubject = post.get("subject", "");
byte[] subject;
try {
subject = StrSubject.getBytes("UTF-8");
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
subject = StrSubject.getBytes();
}
- String commentID = String.valueOf(System.currentTimeMillis());
- BlogEntry blogEntry = sb.blogDB.readBlogEntry(pagename);
+ final String commentID = String.valueOf(System.currentTimeMillis());
+ final BlogEntry blogEntry = sb.blogDB.readBlogEntry(pagename);
blogEntry.addComment(commentID);
sb.blogDB.writeBlogEntry(blogEntry);
sb.blogCommentDB.write(sb.blogCommentDB.newEntry(commentID, subject, author, ip, date, content));
@@ -153,7 +153,7 @@ public class BlogComments {
sb.webIndex.seedDB.mySeed().hash,
sb.webIndex.seedDB.mySeed().getName(), sb.webIndex.seedDB.mySeed().hash,
"new blog comment: " + new String(blogEntry.getSubject(),"UTF-8"), content));
- } catch (UnsupportedEncodingException e1) {
+ } catch (final UnsupportedEncodingException e1) {
sb.messageDB.write(msgEntry = sb.messageDB.newEntry(
"blogComment",
StrAuthor,
@@ -165,11 +165,11 @@ public class BlogComments {
messageForwardingViaEmail(sb, msgEntry);
// finally write notification
- File notifierSource = new File(sb.getRootPath(), sb.getConfig("htRootPath","htroot") + "/env/grafics/message.gif");
- File notifierDest = new File(sb.getConfigPath("htDocsPath", "DATA/HTDOCS"), "notifier.gif");
+ final File notifierSource = new File(sb.getRootPath(), sb.getConfig("htRootPath","htroot") + "/env/grafics/message.gif");
+ final File notifierDest = new File(sb.getConfigPath("htDocsPath", "DATA/HTDOCS"), "notifier.gif");
try {
serverFileUtils.copy(notifierSource, notifierDest);
- } catch (IOException e) {
+ } catch (final IOException e) {
serverLog.logSevere("MESSAGE", "NEW MESSAGE ARRIVED! (error: " + e.getMessage() + ")");
}
@@ -183,7 +183,7 @@ public class BlogComments {
}
if(hasRights && post.containsKey("allow") && post.containsKey("page") && post.containsKey("comment")) {
- blogBoardComments.CommentEntry entry = sb.blogCommentDB.read(post.get("comment"));
+ final blogBoardComments.CommentEntry entry = sb.blogCommentDB.read(post.get("comment"));
entry.allow();
sb.blogCommentDB.write(entry);
}
@@ -196,7 +196,7 @@ public class BlogComments {
try {
prop.putHTML("mode_author", new String(author, "UTF-8"));
prop.putHTML("mode_allow_author", new String(author, "UTF-8"));
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
prop.putHTML("mode_author", new String(author));
prop.putHTML("mode_allow_author", new String(author));
}
@@ -215,13 +215,13 @@ public class BlogComments {
prop.put("mode_allow_pageid", pagename);
try {
prop.putHTML("mode_subject", new String(page.getSubject(),"UTF-8"));
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
prop.putHTML("mode_subject", new String(page.getSubject()));
}
try {
prop.putHTML("mode_author", new String(page.getAuthor(),"UTF-8"));
prop.putHTML("mode_allow_author", new String(author, "UTF-8"));
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
prop.putHTML("mode_author", new String(page.getAuthor()));
prop.putHTML("mode_allow_author", new String(author));
}
@@ -234,8 +234,8 @@ public class BlogComments {
}
//show all commments
try {
- Iterator<String> i = page.getComments().iterator();
- int commentMode = page.getCommentMode();
+ final Iterator<String> i = page.getComments().iterator();
+ final int commentMode = page.getCommentMode();
String pageid;
blogBoardComments.CommentEntry entry;
boolean xml = false;
@@ -249,7 +249,7 @@ public class BlogComments {
if(xml) num = 0;
if (start < 0) start = 0;
if (start > 1) prev = true;
- int nextstart = start+num; //indicates the starting offset for next results
+ final int nextstart = start+num; //indicates the starting offset for next results
int prevstart = start-num; //indicates the starting offset for previous results
while(i.hasNext() && count < num) {
@@ -309,7 +309,7 @@ public class BlogComments {
prop.put("mode_preventries_num", num);
prop.put("mode_preventries_pageid", page.getKey());
} else prop.put("mode_preventries", "0");
- } catch (IOException e) {
+ } catch (final IOException e) {
}
}
@@ -319,19 +319,19 @@ public class BlogComments {
return prop;
}
- private static void messageForwardingViaEmail(plasmaSwitchboard sb, messageBoard.entry msgEntry) {
+ private static void messageForwardingViaEmail(final plasmaSwitchboard sb, final messageBoard.entry msgEntry) {
try {
if (!Boolean.valueOf(sb.getConfig("msgForwardingEnabled","false")).booleanValue()) return;
// getting the recipient address
- String sendMailTo = sb.getConfig("msgForwardingTo","root@localhost").trim();
+ final String sendMailTo = sb.getConfig("msgForwardingTo","root@localhost").trim();
// getting the sendmail configuration
- String sendMailStr = sb.getConfig("msgForwardingCmd","/usr/bin/sendmail")+" "+sendMailTo;
- String[] sendMail = sendMailStr.trim().split(" ");
+ final String sendMailStr = sb.getConfig("msgForwardingCmd","/usr/bin/sendmail")+" "+sendMailTo;
+ final String[] sendMail = sendMailStr.trim().split(" ");
// building the message text
- StringBuffer emailTxt = new StringBuffer();
+ final StringBuffer emailTxt = new StringBuffer();
emailTxt.append("To: ")
.append(sendMailTo)
.append("\nFrom: ")
@@ -355,11 +355,11 @@ public class BlogComments {
.append("\n===================================================================\n")
.append(new String(msgEntry.message()));
- Process process=Runtime.getRuntime().exec(sendMail);
- PrintWriter email = new PrintWriter(process.getOutputStream());
+ final Process process=Runtime.getRuntime().exec(sendMail);
+ final PrintWriter email = new PrintWriter(process.getOutputStream());
email.print(new String(emailTxt));
email.close();
- } catch (Exception e) {
+ } catch (final Exception e) {
yacyCore.log.logWarning("message: message forwarding via email failed. ",e);
}
}
diff --git a/htroot/Bookmarks.java b/htroot/Bookmarks.java
index 270bad99a..018447012 100644
--- a/htroot/Bookmarks.java
+++ b/htroot/Bookmarks.java
@@ -68,7 +68,7 @@ public class Bookmarks {
final static boolean TAGS = false;
final static boolean FOLDERS = true;
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
int max_count = 10;
int start=0;
@@ -118,7 +118,7 @@ public class Bookmarks {
prop.put("AUTHENTICATE","admin log-in");
}
}else if(post.containsKey("mode")){
- String mode=post.get("mode");
+ final String mode=post.get("mode");
if(mode.equals("add")){
prop.put("mode", "2");
}else if(mode.equals("importxml")){
@@ -127,17 +127,17 @@ public class Bookmarks {
prop.put("mode", "4");
}
}else if(post.containsKey("add")){ //add an Entry
- String url=post.get("url");
- String title=post.get("title");
- String description=post.get("description");
+ final String url=post.get("url");
+ final String title=post.get("title");
+ final String description=post.get("description");
String tagsString = post.get("tags");
- String pathString = post.get("path");
+ final String pathString = post.get("path");
tagsString=tagsString+","+pathString;
if(tagsString.equals("")){
tagsString="unsorted"; //default tag
}
- Set<String> tags=listManager.string2set(bookmarksDB.cleanTagsString(tagsString));
- bookmarksDB.Bookmark bookmark = sb.bookmarksDB.createBookmark(url, username);
+ final Set<String> tags=listManager.string2set(bookmarksDB.cleanTagsString(tagsString));
+ final bookmarksDB.Bookmark bookmark = sb.bookmarksDB.createBookmark(url, username);
if(bookmark != null){
bookmark.setProperty(bookmarksDB.Bookmark.BOOKMARK_TITLE, title);
bookmark.setProperty(bookmarksDB.Bookmark.BOOKMARK_DESCRIPTION, description);
@@ -161,7 +161,7 @@ public class Bookmarks {
//ERROR
}
}else if(post.containsKey("edit")){
- String urlHash=post.get("edit");
+ final String urlHash=post.get("edit");
prop.put("mode", "2");
if (urlHash.length() == 0) {
prop.put("mode_edit", "0"); // create mode
@@ -173,13 +173,13 @@ public class Bookmarks {
prop.put("mode_public", "0");
prop.put("mode_feed", "0");
} else {
- bookmarksDB.Bookmark bookmark = sb.bookmarksDB.getBookmark(urlHash);
+ final bookmarksDB.Bookmark bookmark = sb.bookmarksDB.getBookmark(urlHash);
if (bookmark == null) {
// try to get the bookmark from the LURL database
- indexURLReference urlentry = sb.webIndex.getURL(urlHash, null, 0);
+ final indexURLReference urlentry = sb.webIndex.getURL(urlHash, null, 0);
plasmaParserDocument document = null;
if (urlentry != null) {
- indexURLReference.Components comp = urlentry.comp();
+ final indexURLReference.Components comp = urlentry.comp();
document = plasmaSnippetCache.retrieveDocument(comp.url(), true, 5000, true, false);
prop.put("mode_edit", "0"); // create mode
prop.put("mode_url", comp.url().toNormalform(false, true));
@@ -223,9 +223,9 @@ public class Bookmarks {
}
serverLog.logInfo("BOOKMARKS", "I try to import bookmarks from HTML-file");
try {
- File file=new File(post.get("htmlfile"));
+ final File file=new File(post.get("htmlfile"));
sb.bookmarksDB.importFromBookmarks(new yacyURL(file) , post.get("htmlfile$file"), tags, isPublic);
- } catch (MalformedURLException e) {}
+ } catch (final MalformedURLException e) {}
serverLog.logInfo("BOOKMARKS", "success!!");
}else if(post.containsKey("xmlfile")){
boolean isPublic=false;
@@ -234,7 +234,7 @@ public class Bookmarks {
}
sb.bookmarksDB.importFromXML(post.get("xmlfile$file"), isPublic);
}else if(post.containsKey("delete")){
- String urlHash=post.get("delete");
+ final String urlHash=post.get("delete");
sb.bookmarksDB.removeBookmark(urlHash);
}
if(post.containsKey("tag")){
@@ -302,7 +302,7 @@ public class Bookmarks {
tagsIt=tags.iterator();
tagCount=0;
while (tagsIt.hasNext()) {
- String tname = tagsIt.next();
+ final String tname = tagsIt.next();
if ((!tname.startsWith("/")) && (!tname.equals(""))) {
prop.put("bookmarks_"+count+"_tags_"+tagCount+"_tag", tname);
tagCount++;
@@ -346,7 +346,7 @@ public class Bookmarks {
return prop; // return from serverObjects respond()
}
- private static void printTagList(String id, String tagName, int comp, int max, boolean opt){
+ private static void printTagList(final String id, final String tagName, final int comp, final int max, final boolean opt){
int count=0;
bookmarksDB.Tag tag;
Iterator<Tag> it = null;
@@ -378,7 +378,7 @@ public class Bookmarks {
prop.put(id, count);
}
- private static int recurseFolders(Iterator<String> it, String root, int count, boolean next, String prev){
+ private static int recurseFolders(final Iterator<String> it, String root, int count, final boolean next, final String prev){
String fn="";
bookmarksDB.Bookmark bookmark;
@@ -398,7 +398,7 @@ public class Bookmarks {
if(fn.startsWith(root)){
prop.put("folderlist_"+count+"_folder", "<li>"+fn.replaceFirst(root+"/*","")+"<ul class=\"folder\">");
count++;
- Iterator<String> bit=sb.bookmarksDB.getBookmarksIterator(fn, isAdmin);
+ final Iterator<String> bit=sb.bookmarksDB.getBookmarksIterator(fn, isAdmin);
while(bit.hasNext()){
bookmark=sb.bookmarksDB.getBookmark(bit.next());
prop.put("folderlist_"+count+"_folder", "<li><a href=\""+bookmark.getUrl()+"\" title=\""+bookmark.getDescription()+"\">"+ bookmark.getTitle()+"</a></li>");
@@ -417,9 +417,9 @@ public class Bookmarks {
return count;
}
- private static void publishNews(String url, String title, String description, String tagsString) {
+ private static void publishNews(final String url, final String title, final String description, final String tagsString) {
// create a news message
- HashMap<String, String> map = new HashMap<String, String>();
+ final HashMap<String, String> map = new HashMap<String, String>();
map.put("url", url.replace(',', '|'));
map.put("title", title.replace(',', ' '));
map.put("description", description.replace(',', ' '));
diff --git a/htroot/CacheAdmin_p.java b/htroot/CacheAdmin_p.java
index 7be7f9542..fb85d1845 100644
--- a/htroot/CacheAdmin_p.java
+++ b/htroot/CacheAdmin_p.java
@@ -70,13 +70,13 @@ public class CacheAdmin_p {
public static final class Filter implements FilenameFilter {
private static final String EXCLUDE_NAME = plasmaHTCache.DB_NAME;
private final File EXCLUDE_DIR;
- public Filter(File path) { this.EXCLUDE_DIR = path; }
- public boolean accept(File dir, String name) {
+ public Filter(final File path) { this.EXCLUDE_DIR = path; }
+ public boolean accept(final File dir, final String name) {
return !dir.equals(EXCLUDE_DIR) && !name.equals(EXCLUDE_NAME);
}
}
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
final plasmaSwitchboard switchboard = (plasmaSwitchboard) env;
final serverObjects prop = new serverObjects();
@@ -91,7 +91,7 @@ public class CacheAdmin_p {
pathString = "/";
file = new File(switchboard.htCachePath, pathString);
}
- } catch (IOException e) {
+ } catch (final IOException e) {
pathString = "/";
file = new File(switchboard.htCachePath, pathString);
}
@@ -134,10 +134,10 @@ public class CacheAdmin_p {
// to retrieve all needed information
final htmlFilterContentScraper scraper = new htmlFilterContentScraper(url);
//final OutputStream os = new htmlFilterOutputStream(null, scraper, null, false);
- Writer writer = new htmlFilterWriter(null,null,scraper,null,false);
+ final Writer writer = new htmlFilterWriter(null,null,scraper,null,false);
String sourceCharset = resInfo.getCharacterEncoding();
if (sourceCharset == null) sourceCharset = "UTF-8";
- String mimeType = resInfo.getMimeType();
+ final String mimeType = resInfo.getMimeType();
serverFileUtils.copy(file, sourceCharset, writer);
writer.close();
@@ -146,7 +146,7 @@ public class CacheAdmin_p {
prop.putHTML("info_type_title", scraper.getTitle());
int i;
- String[] t = document.getSectionTitles();
+ final String[] t = document.getSectionTitles();
prop.put("info_type_headlines", t.length);
for (i = 0; i < t.length; i++)
prop.putHTML("info_type_headlines_" + i + "_headline",
@@ -173,11 +173,11 @@ public class CacheAdmin_p {
if (document != null) document.close();
}
}
- } catch (IOException e) {
+ } catch (final IOException e) {
prop.put("info_type", NotCached);
- } catch (UnsupportedProtocolException e) {
+ } catch (final UnsupportedProtocolException e) {
prop.put("info_type", ProtocolError);
- } catch (IllegalAccessException e) {
+ } catch (final IllegalAccessException e) {
prop.put("info_type", SecurityError);
}
} else {
@@ -201,7 +201,8 @@ public class CacheAdmin_p {
prop.put("info_empty", "0");
final TreeSet<String> dList = new TreeSet<String>();
final TreeSet<String> fList = new TreeSet<String>();
- int size = list.length - 1, i;
+ final int size = list.length - 1;
+ int i;
for (i = size; i >= 0 ; i--) { // Rueckwaerts ist schneller
if (new File(dir, list[i]).isDirectory())
dList.add(list[i]);
@@ -239,7 +240,7 @@ public class CacheAdmin_p {
return prop;
}
- private static void formatHeader(serverObjects prop, Map<String, String> header) {
+ private static void formatHeader(final serverObjects prop, final Map<String, String> header) {
if (header == null) {
prop.put("info_header", "0");
} else {
@@ -257,7 +258,7 @@ public class CacheAdmin_p {
}
}
- private static void formatAnchor(serverObjects prop, Map<yacyURL, String> anchor, String extension) {
+ private static void formatAnchor(final serverObjects prop, final Map<yacyURL, String> anchor, final String extension) {
final Iterator<Map.Entry<yacyURL, String>> iter = anchor.entrySet().iterator();
String descr;
Map.Entry<yacyURL, String> entry;
@@ -276,7 +277,7 @@ public class CacheAdmin_p {
prop.put("info_type_use." + extension, (i == 0) ? 0 : 1);
}
- private static void formatEmail(serverObjects prop, Map<String, String> anchor, String extension) {
+ private static void formatEmail(final serverObjects prop, final Map<String, String> anchor, final String extension) {
final Iterator<Map.Entry<String, String>> iter = anchor.entrySet().iterator();
String descr;
Map.Entry<String, String> entry;
@@ -295,7 +296,7 @@ public class CacheAdmin_p {
prop.put("info_type_use." + extension, (i == 0) ? 0 : 1);
}
- private static void formatImageAnchor(serverObjects prop, HashMap<String, htmlFilterImageEntry> anchor) {
+ private static void formatImageAnchor(final serverObjects prop, final HashMap<String, htmlFilterImageEntry> anchor) {
final Iterator<htmlFilterImageEntry> iter = anchor.values().iterator();
htmlFilterImageEntry ie;
prop.put("info_type_use.images_images", anchor.size());
@@ -310,7 +311,7 @@ public class CacheAdmin_p {
prop.put("info_type_use.images", (i == 0) ? "0" : "1");
}
- private static void linkPathString(serverObjects prop, String path, boolean dir) {
+ private static void linkPathString(final serverObjects prop, final String path, final boolean dir) {
final String[] elements = path.split("/");
String dirs = "";
int i, e, count = 0;
diff --git a/htroot/CacheResource_p.java b/htroot/CacheResource_p.java
index 042468284..7e1593f10 100644
--- a/htroot/CacheResource_p.java
+++ b/htroot/CacheResource_p.java
@@ -35,22 +35,22 @@ import de.anomic.server.serverSwitch;
public class CacheResource_p {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
- plasmaSwitchboard switchboard = (plasmaSwitchboard) env;
- serverObjects prop = new serverObjects();
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
+ final plasmaSwitchboard switchboard = (plasmaSwitchboard) env;
+ final serverObjects prop = new serverObjects();
- String path = ((post == null) ? "" : post.get("path", ""));
+ final String path = ((post == null) ? "" : post.get("path", ""));
// we dont need check the path, because we have do that in plasmaSwitchboard.java - Borg-0300
- File cache = switchboard.getConfigPath(plasmaSwitchboard.HTCACHE_PATH, plasmaSwitchboard.HTCACHE_PATH_DEFAULT);
+ final File cache = switchboard.getConfigPath(plasmaSwitchboard.HTCACHE_PATH, plasmaSwitchboard.HTCACHE_PATH_DEFAULT);
- File f = new File(cache, path);
+ final File f = new File(cache, path);
byte[] resource;
try {
resource = serverFileUtils.read(f);
prop.put("resource", resource);
- } catch (IOException e) {
+ } catch (final IOException e) {
prop.put("resource", new byte[0]);
}
return prop;
diff --git a/htroot/Collage.java b/htroot/Collage.java
index 5dc8d04fe..4ff6bf21d 100755
--- a/htroot/Collage.java
+++ b/htroot/Collage.java
@@ -43,11 +43,11 @@ public class Collage {
private static long imgZIndex[] = new long[fifoMax];
private static final Random rand = new Random();
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
final serverObjects prop = new serverObjects();
final plasmaSwitchboard sb = (plasmaSwitchboard) env;
final boolean authenticated = sb.verifyAuthentication(header, false);
- ResultImages.OriginEntry nextOrigin = ResultImages.next(!authenticated);
+ final ResultImages.OriginEntry nextOrigin = ResultImages.next(!authenticated);
int posXMax = 800;
int posYMax = 500;
boolean embed = false;
@@ -67,7 +67,7 @@ public class Collage {
fifoSize = fifoSize + 1 > fifoMax ? fifoMax : fifoSize + 1;
origins[fifoPos] = nextOrigin;
- float scale = rand.nextFloat() * 1.5f + 1;
+ final float scale = rand.nextFloat() * 1.5f + 1;
imgWidth[fifoPos] = (int) ((nextOrigin.imageEntry.width()) / scale);
imgHeight[fifoPos] = (int) ((nextOrigin.imageEntry.height()) / scale);
@@ -82,18 +82,18 @@ public class Collage {
if (fifoSize > 0) {
prop.put("imgurl", "1");
int c = 0;
- int yOffset = embed ? 0 : 70;
+ final int yOffset = embed ? 0 : 70;
for (int i = 0; i < fifoSize; i++) {
- yacyURL baseURL = origins[i].baseURL;
- yacyURL imageURL = origins[i].imageEntry.url();
+ final yacyURL baseURL = origins[i].baseURL;
+ final yacyURL imageURL = origins[i].imageEntry.url();
// check if this loads a page from localhost, which must be prevented to protect the server
// against attacks to the administration interface when localhost access is granted
if ((serverCore.isLocalhost(baseURL.getHost()) || serverCore.isLocalhost(imageURL.getHost())) &&
sb.getConfigBool("adminAccountForLocalhost", false)) continue;
- long z = imgZIndex[i];
+ final long z = imgZIndex[i];
prop.put("imgurl_list_" + c + "_url",
"<a href=\"" + baseURL.toNormalform(true, false) + "\">"
+ "<img src=\"" + imageURL.toNormalform(true, false) + "\" "
diff --git a/htroot/ConfigAccounts_p.java b/htroot/ConfigAccounts_p.java
index 2da64901b..bde71f86b 100644
--- a/htroot/ConfigAccounts_p.java
+++ b/htroot/ConfigAccounts_p.java
@@ -41,18 +41,18 @@ import de.anomic.server.serverSwitch;
public class ConfigAccounts_p {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
- serverObjects prop = new serverObjects();
- plasmaSwitchboard sb = plasmaSwitchboard.getSwitchboard();
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
+ final serverObjects prop = new serverObjects();
+ final plasmaSwitchboard sb = plasmaSwitchboard.getSwitchboard();
userDB.Entry entry=null;
// admin password
boolean localhostAccess = sb.getConfigBool("adminAccountForLocalhost", false);
if ((post != null) && (post.containsKey("setAdmin"))) {
localhostAccess = post.get("access", "").equals("localhost");
- String user = (post == null) ? "" : (String) post.get("adminuser", "");
- String pw1 = (post == null) ? "" : (String) post.get("adminpw1", "");
- String pw2 = (post == null) ? "" : (String) post.get("adminpw2", "");
+ final String user = (post == null) ? "" : (String) post.get("adminuser", "");
+ final String pw1 = (post == null) ? "" : (String) post.get("adminpw1", "");
+ final String pw2 = (post == null) ? "" : (String) post.get("adminpw2", "");
// may be overwritten if new password is given
if ((user.length() > 0) && (pw1.length() > 3) && (pw1.equals(pw2))) {
@@ -103,8 +103,8 @@ public class ConfigAccounts_p {
prop.put("address", "");
prop.put("timelimit", "");
prop.put("timeused", "");
- String[] rightNames=userDB.Entry.RIGHT_NAMES.split(",");
- String[] rights=userDB.Entry.RIGHT_TYPES.split(",");
+ final String[] rightNames=userDB.Entry.RIGHT_NAMES.split(",");
+ final String[] rights=userDB.Entry.RIGHT_TYPES.split(",");
int i;
for(i=0;i<rights.length;i++){
prop.put("rights_"+i+"_name", rights[i]);
@@ -152,23 +152,23 @@ public class ConfigAccounts_p {
prop.put("error", "0");
- String username=post.get("username");
- String pw1=post.get("password");
- String pw2=post.get("password2");
+ final String username=post.get("username");
+ final String pw1=post.get("password");
+ final String pw2=post.get("password2");
if(! pw1.equals(pw2)){
prop.put("error", "2"); //PW does not match
return prop;
}
- String firstName=post.get("firstname");
- String lastName=post.get("lastname");
- String address=post.get("address");
- String timeLimit=post.get("timelimit");
- String timeUsed=post.get("timeused");
- HashMap<String, String> rightsSet=new HashMap<String, String>();
+ final String firstName=post.get("firstname");
+ final String lastName=post.get("lastname");
+ final String address=post.get("address");
+ final String timeLimit=post.get("timelimit");
+ final String timeUsed=post.get("timeused");
+ final HashMap<String, String> rightsSet=new HashMap<String, String>();
for(i=0;i<rights.length;i++){
rightsSet.put(rights[i], post.containsKey(rights[i])&&(post.get(rights[i])).equals("on") ? "true" : "false");
}
- HashMap<String, String> mem=new HashMap<String, String>();
+ final HashMap<String, String> mem=new HashMap<String, String>();
if( post.get("current_user").equals("newuser")){ //new user
if(!pw1.equals("")){ //change only if set
@@ -187,7 +187,7 @@ public class ConfigAccounts_p {
sb.userDB.addEntry(entry);
prop.putHTML("text_username", username);
prop.put("text", "1");
- }catch(IllegalArgumentException e){
+ }catch(final IllegalArgumentException e){
prop.put("error", "3");
}
@@ -207,7 +207,7 @@ public class ConfigAccounts_p {
entry.setProperty(userDB.Entry.TIME_USED, timeUsed);
for(i=0;i<rights.length;i++)
entry.setProperty(rights[i], rightsSet.get(rights[i]));
- }catch (IOException e){
+ }catch (final IOException e){
}
}else{
prop.put("error", "1");
@@ -219,7 +219,7 @@ public class ConfigAccounts_p {
}
//Generate Userlist
- Iterator<userDB.Entry> it = sb.userDB.iterator(true);
+ final Iterator<userDB.Entry> it = sb.userDB.iterator(true);
int numUsers=0;
while(it.hasNext()){
entry = it.next();
diff --git a/htroot/ConfigAppearance_p.java b/htroot/ConfigAppearance_p.java
index 4571b0633..2a13efd3f 100644
--- a/htroot/ConfigAppearance_p.java
+++ b/htroot/ConfigAppearance_p.java
@@ -46,10 +46,10 @@ import de.anomic.yacy.yacyURL;
public class ConfigAppearance_p {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
- serverObjects prop = new serverObjects();
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
- String skinPath = new File(env.getRootPath(), env.getConfig("skinPath", "DATA/SKINS")).toString();
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
+ final serverObjects prop = new serverObjects();
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ final String skinPath = new File(env.getRootPath(), env.getConfig("skinPath", "DATA/SKINS")).toString();
// Fallback
prop.put("currentskin", "");
@@ -66,7 +66,7 @@ public class ConfigAppearance_p {
try {
serverFileUtils.copy(new File(env.getRootPath(), "htroot/env/style.css"), new File(skinPath, "default.css"));
env.setConfig("currentSkin", "default");
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
}
@@ -79,34 +79,34 @@ public class ConfigAppearance_p {
}
if (post.containsKey("delete_button")) {
// delete skin
- File skinfile = new File(skinPath, post.get("skin"));
+ final File skinfile = new File(skinPath, post.get("skin"));
skinfile.delete();
}
if (post.containsKey("install_button")) {
// load skin from URL
- String url = post.get("url");
+ final String url = post.get("url");
ArrayList<String> skinVector;
try {
- yacyURL u = new yacyURL(url, null);
- httpHeader reqHeader = new httpHeader();
+ final yacyURL u = new yacyURL(url, null);
+ final httpHeader reqHeader = new httpHeader();
reqHeader.put(httpHeader.USER_AGENT, HTTPLoader.yacyUserAgent);
skinVector = nxTools.strings(HttpClient.wget(u.toString(), reqHeader, 10000), "UTF-8");
- } catch (IOException e) {
+ } catch (final IOException e) {
prop.put("status", "1");// unable to get URL
prop.put("status_url", url);
return prop;
}
try {
- Iterator<String> it = skinVector.iterator();
- File skinFile = new File(skinPath, url.substring(url.lastIndexOf("/"), url.length()));
- BufferedWriter bw = new BufferedWriter(new PrintWriter(new FileWriter(skinFile)));
+ final Iterator<String> it = skinVector.iterator();
+ final File skinFile = new File(skinPath, url.substring(url.lastIndexOf("/"), url.length()));
+ final BufferedWriter bw = new BufferedWriter(new PrintWriter(new FileWriter(skinFile)));
while (it.hasNext()) {
bw.write(it.next() + "\n");
}
bw.close();
- } catch (IOException e) {
+ } catch (final IOException e) {
prop.put("status", "2");// error saving the skin
return prop;
}
@@ -152,17 +152,17 @@ public class ConfigAppearance_p {
return prop;
}
- private static boolean changeSkin(plasmaSwitchboard sb, String skinPath, String skin) {
- File htdocsDir = new File(sb.getConfigPath("htDocsPath", "DATA/HTDOCS"), "env");
- File styleFile = new File(htdocsDir, "style.css");
- File skinFile = new File(skinPath, skin);
+ private static boolean changeSkin(final plasmaSwitchboard sb, final String skinPath, final String skin) {
+ final File htdocsDir = new File(sb.getConfigPath("htDocsPath", "DATA/HTDOCS"), "env");
+ final File styleFile = new File(htdocsDir, "style.css");
+ final File skinFile = new File(skinPath, skin);
styleFile.getParentFile().mkdirs();
try {
serverFileUtils.copy(skinFile, styleFile);
sb.setConfig("currentSkin", skin.substring(0, skin.length() - 4));
return true;
- } catch (IOException e) {
+ } catch (final IOException e) {
return false;
}
}
diff --git a/htroot/ConfigBasic.java b/htroot/ConfigBasic.java
index c6cde30b4..fba9e3cb5 100644
--- a/htroot/ConfigBasic.java
+++ b/htroot/ConfigBasic.java
@@ -50,15 +50,15 @@ public class ConfigBasic {
private static final int NEXTSTEP_PEERPORT = 3;
private static final int NEXTSTEP_RECONNECT = 4;
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
// return variable that accumulates replacements
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
- serverObjects prop = new serverObjects();
- String langPath = env.getConfigPath("locale.work", "DATA/LOCALE/locales").getAbsolutePath();
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ final serverObjects prop = new serverObjects();
+ final String langPath = env.getConfigPath("locale.work", "DATA/LOCALE/locales").getAbsolutePath();
String lang = env.getConfig("locale.language", "default");
- int authentication = sb.adminAuthenticated(header);
+ final int authentication = sb.adminAuthenticated(header);
if (authentication < 2) {
// must authenticate
prop.put("AUTHENTICATE", "admin log-in");
@@ -79,7 +79,7 @@ public class ConfigBasic {
}
// peer name settings
- String peerName = (post == null) ? env.getConfig("peerName","") : (String) post.get("peername", "");
+ final String peerName = (post == null) ? env.getConfig("peerName","") : (String) post.get("peername", "");
// port settings
String port = env.getConfig("port", "8080"); //this allows a low port, but it will only get one, if the user edits the config himself.
@@ -88,10 +88,10 @@ public class ConfigBasic {
}
// check if peer name already exists
- yacySeed oldSeed = sb.webIndex.seedDB.lookupByName(peerName);
+ final yacySeed oldSeed = sb.webIndex.seedDB.lookupByName(peerName);
if ((oldSeed == null) && (!(env.getConfig("peerName", "").equals(peerName)))) {
// the name is new
- boolean nameOK = Pattern.compile("[A-Za-z0-9\\-_]{3,80}").matcher(peerName).matches();
+ final boolean nameOK = Pattern.compile("[A-Za-z0-9\\-_]{3,80}").matcher(peerName).matches();
if (nameOK) env.setConfig("peerName", peerName);
}
@@ -99,7 +99,7 @@ public class ConfigBasic {
boolean reconnect = false;
if (!env.getConfig("port", port).equals(port)) {
// validate port
- serverCore theServerCore = (serverCore) env.getThread("10_httpd");
+ final serverCore theServerCore = (serverCore) env.getThread("10_httpd");
env.setConfig("port", port);
// redirect the browser to the new port
@@ -108,7 +108,7 @@ public class ConfigBasic {
String host = null;
if (header.containsKey(httpHeader.HOST)) {
host = header.get(httpHeader.HOST);
- int idx = host.indexOf(":");
+ final int idx = host.indexOf(":");
if (idx != -1) host = host.substring(0,idx);
} else {
host = serverDomains.myPublicLocalIP().getHostAddress();
@@ -174,9 +174,9 @@ public class ConfigBasic {
prop.put("setUseCase_port", port);
// check if values are proper
- boolean properPassword = (sb.getConfig(httpd.ADMIN_ACCOUNT_B64MD5, "").length() > 0) || sb.getConfigBool("adminAccountForLocalhost", false);
- boolean properName = (env.getConfig("peerName","").length() >= 3) && (!(yacySeed.isDefaultPeerName(env.getConfig("peerName",""))));
- boolean properPort = (sb.webIndex.seedDB.mySeed().isSenior()) || (sb.webIndex.seedDB.mySeed().isPrincipal());
+ final boolean properPassword = (sb.getConfig(httpd.ADMIN_ACCOUNT_B64MD5, "").length() > 0) || sb.getConfigBool("adminAccountForLocalhost", false);
+ final boolean properName = (env.getConfig("peerName","").length() >= 3) && (!(yacySeed.isDefaultPeerName(env.getConfig("peerName",""))));
+ final boolean properPort = (sb.webIndex.seedDB.mySeed().isSenior()) || (sb.webIndex.seedDB.mySeed().isPrincipal());
if ((env.getConfig("defaultFiles", "").startsWith("ConfigBasic.html,"))) {
env.setConfig("defaultFiles", env.getConfig("defaultFiles", "").substring(17));
diff --git a/htroot/ConfigLanguage_p.java b/htroot/ConfigLanguage_p.java
index 9831c5ac6..8cb467e74 100644
--- a/htroot/ConfigLanguage_p.java
+++ b/htroot/ConfigLanguage_p.java
@@ -48,10 +48,10 @@ import de.anomic.yacy.yacyURL;
public class ConfigLanguage_p {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
//listManager.switchboard = (plasmaSwitchboard) env;
- serverObjects prop = new serverObjects();
- String langPath = env.getConfigPath("locale.work", "DATA/LOCALE/locales").getAbsolutePath();
+ final serverObjects prop = new serverObjects();
+ final String langPath = env.getConfigPath("locale.work", "DATA/LOCALE/locales").getAbsolutePath();
//Fallback
//prop.put("currentlang", ""); //is done by Translationtemplate
@@ -69,33 +69,33 @@ public class ConfigLanguage_p {
//delete language file
}else if(post.containsKey("delete")){
- File langfile= new File(langPath, post.get("language"));
+ final File langfile= new File(langPath, post.get("language"));
langfile.delete();
//load language file from URL
} else if (post.containsKey("url")){
- String url = post.get("url");
+ final String url = post.get("url");
ArrayList<String> langVector;
try{
- yacyURL u = new yacyURL(url, null);
- httpHeader reqHeader = new httpHeader();
+ final yacyURL u = new yacyURL(url, null);
+ final httpHeader reqHeader = new httpHeader();
reqHeader.put(httpHeader.USER_AGENT, HTTPLoader.yacyUserAgent);
langVector = nxTools.strings(HttpClient.wget(u.toString(), reqHeader, 10000), "UTF-8");
- }catch(IOException e){
+ }catch(final IOException e){
prop.put("status", "1");//unable to get url
prop.put("status_url", url);
return prop;
}
try{
- Iterator<String> it = langVector.iterator();
- File langFile = new File(langPath, url.substring(url.lastIndexOf("/"), url.length()));
- BufferedWriter bw = new BufferedWriter(new PrintWriter(new FileWriter(langFile)));
+ final Iterator<String> it = langVector.iterator();
+ final File langFile = new File(langPath, url.substring(url.lastIndexOf("/"), url.length()));
+ final BufferedWriter bw = new BufferedWriter(new PrintWriter(new FileWriter(langFile)));
while (it.hasNext()) {
bw.write(it.next() + "\n");
}
bw.close();
- }catch(IOException e){
+ }catch(final IOException e){
prop.put("status", "2");//error saving the language file
return prop;
}
@@ -108,7 +108,7 @@ public class ConfigLanguage_p {
//reread language files
langFiles = listManager.getDirListing(langPath);
int i;
- HashMap<String, String> langNames = translator.langMap(env);
+ final HashMap<String, String> langNames = translator.langMap(env);
String langKey, langName;
//virtual entry
diff --git a/htroot/ConfigNetwork_p.java b/htroot/ConfigNetwork_p.java
index 9a9c921f5..841c67c13 100644
--- a/htroot/ConfigNetwork_p.java
+++ b/htroot/ConfigNetwork_p.java
@@ -39,21 +39,21 @@ import de.anomic.server.serverSwitch;
public class ConfigNetwork_p {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
- serverObjects prop = new serverObjects();
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ final serverObjects prop = new serverObjects();
int commit = 0;
// load all options for network definitions
- File networkBootstrapLocationsFile = new File(new File(sb.getRootPath(), "defaults"), "yacy.networks");
- HashSet<String> networkBootstrapLocations = serverFileUtils.loadList(networkBootstrapLocationsFile);
+ final File networkBootstrapLocationsFile = new File(new File(sb.getRootPath(), "defaults"), "yacy.networks");
+ final HashSet<String> networkBootstrapLocations = serverFileUtils.loadList(networkBootstrapLocationsFile);
if (post != null) {
if (post.containsKey("changeNetwork")) {
- String networkDefinition = post.get("networkDefinition", "defaults/yacy.network.freeworld.unit");
+ final String networkDefinition = post.get("networkDefinition", "defaults/yacy.network.freeworld.unit");
if (networkDefinition.equals(sb.getConfig("network.unit.definition", ""))) {
// no change
commit = 3;
@@ -74,8 +74,8 @@ public class ConfigNetwork_p {
// DHT control
boolean indexDistribute = post.get("indexDistribute", "").equals("on");
boolean indexReceive = post.get("indexReceive", "").equals("on");
- boolean robinsonmode = post.get("network", "").equals("robinson");
- String clustermode = post.get("cluster.mode", "publicpeer");
+ final boolean robinsonmode = post.get("network", "").equals("robinson");
+ final String clustermode = post.get("cluster.mode", "publicpeer");
if (robinsonmode) {
indexDistribute = false;
indexReceive = false;
@@ -146,9 +146,9 @@ public class ConfigNetwork_p {
int newppm = 1;
try {
newppm = Math.max(1, Integer.parseInt(post.get("acceptCrawlLimit", "1")));
- } catch (NumberFormatException e) {}
- long newBusySleep = Math.max(100, 60000 / newppm);
- serverBusyThread rct = sb.getThread(plasmaSwitchboard.CRAWLJOB_REMOTE_TRIGGERED_CRAWL);
+ } catch (final NumberFormatException e) {}
+ final long newBusySleep = Math.max(100, 60000 / newppm);
+ final serverBusyThread rct = sb.getThread(plasmaSwitchboard.CRAWLJOB_REMOTE_TRIGGERED_CRAWL);
rct.setBusySleep(newBusySleep);
sb.setConfig(plasmaSwitchboard.CRAWLJOB_REMOTE_TRIGGERED_CRAWL_BUSYSLEEP, Long.toString(newBusySleep));
@@ -168,12 +168,12 @@ public class ConfigNetwork_p {
long RTCbusySleep = 100;
try {
RTCbusySleep = Math.max(1, Integer.parseInt(env.getConfig(plasmaSwitchboard.CRAWLJOB_REMOTE_TRIGGERED_CRAWL_BUSYSLEEP, "100")));
- } catch (NumberFormatException e) {}
- int RTCppm = (int) (60000L / RTCbusySleep);
+ } catch (final NumberFormatException e) {}
+ final int RTCppm = (int) (60000L / RTCbusySleep);
prop.put("acceptCrawlLimit", RTCppm);
- boolean indexDistribute = sb.getConfig(plasmaSwitchboard.INDEX_DIST_ALLOW, "true").equals("true");
- boolean indexReceive = sb.getConfig(plasmaSwitchboard.INDEX_RECEIVE_ALLOW, "true").equals("true");
+ final boolean indexDistribute = sb.getConfig(plasmaSwitchboard.INDEX_DIST_ALLOW, "true").equals("true");
+ final boolean indexReceive = sb.getConfig(plasmaSwitchboard.INDEX_RECEIVE_ALLOW, "true").equals("true");
prop.put("indexDistributeChecked", (indexDistribute) ? "1" : "0");
prop.put("indexDistributeWhileCrawling.on", (sb.getConfig(plasmaSwitchboard.INDEX_DIST_ALLOW_WHILE_CRAWLING, "true").equals("true")) ? "1" : "0");
prop.put("indexDistributeWhileCrawling.off", (sb.getConfig(plasmaSwitchboard.INDEX_DIST_ALLOW_WHILE_CRAWLING, "true").equals("true")) ? "0" : "1");
@@ -209,7 +209,7 @@ public class ConfigNetwork_p {
prop.put("network.unit.dht", sb.getConfig("network.unit.dht", ""));
networkBootstrapLocations.remove(sb.getConfig("network.unit.definition", ""));
int c = 0;
- for (String s: networkBootstrapLocations) prop.put("networks_" + c++ + "_network", s);
+ for (final String s: networkBootstrapLocations) prop.put("networks_" + c++ + "_network", s);
prop.put("networks", c);
return prop;
@@ -226,7 +226,7 @@ public class ConfigNetwork_p {
public static String checkYaCyDomainList(String input) {
input = normalizedList(input);
- String[] s = input.split(",");
+ final String[] s = input.split(",");
input = "";
for (int i = 0; i < s.length; i++) {
if ((s[i].endsWith(".yacyh")) || (s[i].endsWith(".yacy")) ||
@@ -237,7 +237,7 @@ public class ConfigNetwork_p {
public static String checkIPPortList(String input) {
input = normalizedList(input);
- String[] s = input.split(",");
+ final String[] s = input.split(",");
input = "";
for (int i = 0; i < s.length; i++) {
if (s[i].indexOf(':') >= 9) input += "," + s[i];
diff --git a/htroot/ConfigProfile_p.java b/htroot/ConfigProfile_p.java
index e7edbb415..0921cd349 100644
--- a/htroot/ConfigProfile_p.java
+++ b/htroot/ConfigProfile_p.java
@@ -44,17 +44,17 @@ import de.anomic.yacy.yacyNewsRecord;
public class ConfigProfile_p {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
final serverObjects prop = new serverObjects();
final Properties profile = new Properties();
FileInputStream fileIn = null;
try {
fileIn = new FileInputStream(new File("DATA/SETTINGS/profile.txt"));
profile.load(fileIn);
- } catch(IOException e) {
+ } catch(final IOException e) {
} finally {
- if (fileIn != null) try { fileIn.close(); } catch (Exception e) {}
+ if (fileIn != null) try { fileIn.close(); } catch (final Exception e) {}
}
if (post != null && post.containsKey("set")) {
@@ -92,13 +92,13 @@ public class ConfigProfile_p {
profile.store(fileOut , null );
// generate a news message
- Properties news = profile;
+ final Properties news = profile;
news.remove("comment");
sb.webIndex.newsPool.publishMyNews(yacyNewsRecord.newRecord(sb.webIndex.seedDB.mySeed(), yacyNewsPool.CATEGORY_PROFILE_UPDATE, news));
//yacyCore.newsPool.publishMyNews(new yacyNewsRecord(yacyNewsRecord.CATEGORY_PROFILE_UPDATE, profile));
- } catch(IOException e) {
+ } catch(final IOException e) {
} finally {
- if (fileOut != null) try { fileOut.close(); } catch (Exception e) {}
+ if (fileOut != null) try { fileOut.close(); } catch (final Exception e) {}
}
}
diff --git a/htroot/ConfigProperties_p.java b/htroot/ConfigProperties_p.java
index 567a65597..4d7bd7144 100644
--- a/htroot/ConfigProperties_p.java
+++ b/htroot/ConfigProperties_p.java
@@ -39,7 +39,7 @@ import de.anomic.server.serverSwitch;
public class ConfigProperties_p {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
// return variable that accumulates replacements
final serverObjects prop = new serverObjects();
int count=0;
diff --git a/htroot/ConfigRobotsTxt_p.java b/htroot/ConfigRobotsTxt_p.java
index 4d83a4890..75b3a225f 100644
--- a/htroot/ConfigRobotsTxt_p.java
+++ b/htroot/ConfigRobotsTxt_p.java
@@ -38,11 +38,11 @@ import de.anomic.server.servletProperties;
public class ConfigRobotsTxt_p {
- public static servletProperties respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ public static servletProperties respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
final servletProperties prop = new servletProperties();
- httpdRobotsTxtConfig rbc = ((plasmaSwitchboard)env).robotstxtConfig;
+ final httpdRobotsTxtConfig rbc = ((plasmaSwitchboard)env).robotstxtConfig;
prop.put("clientname", sb.webIndex.seedDB.mySeed().getPublicAddress());
if (post != null) {
diff --git a/htroot/ConfigUpdate_p.java b/htroot/ConfigUpdate_p.java
index 139f292dd..3bc581252 100644
--- a/htroot/ConfigUpdate_p.java
+++ b/htroot/ConfigUpdate_p.java
@@ -40,7 +40,7 @@ import de.anomic.yacy.yacyVersion;
public class ConfigUpdate_p {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
// return variable that accumulates replacements
final serverObjects prop = new serverObjects();
final plasmaSwitchboard sb = (plasmaSwitchboard) env;
@@ -59,11 +59,11 @@ public class ConfigUpdate_p {
if (post.containsKey("downloadRelease")) {
// download a release
- String release = post.get("releasedownload", "");
+ final String release = post.get("releasedownload", "");
if (release.length() > 0) {
try {
yacyVersion.downloadRelease(new yacyVersion(new yacyURL(release, null)));
- } catch (IOException e) {
+ } catch (final IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
@@ -74,26 +74,26 @@ public class ConfigUpdate_p {
yacyVersion.allReleases(true);
}
if (post.containsKey("deleteRelease")) {
- String release = post.get("releaseinstall", "");
+ final String release = post.get("releaseinstall", "");
if(release.length() > 0) {
try {
new File(sb.releasePath, release).delete();
- } catch (NullPointerException e) {
+ } catch (final NullPointerException e) {
sb.getLog().logSevere("AUTO-UPDATE: could not delete release " + release + ": " + e.getMessage());
}
}
}
if (post.containsKey("autoUpdate")) {
- yacyVersion updateVersion = yacyVersion.rulebasedUpdateInfo(true);
+ final yacyVersion updateVersion = yacyVersion.rulebasedUpdateInfo(true);
if (updateVersion == null) {
prop.put("candeploy_autoUpdate", "2"); // no more recent release found
} else {
// there is a version that is more recent. Load it and re-start with it
sb.getLog().logInfo("AUTO-UPDATE: downloading more recent release " + updateVersion.url);
- File downloaded = yacyVersion.downloadRelease(updateVersion);
+ final File downloaded = yacyVersion.downloadRelease(updateVersion);
prop.put("candeploy_autoUpdate_downloadedRelease", updateVersion.name);
- boolean devenvironment = yacyVersion.combined2prettyVersion(sb.getConfig("version","0.1")).startsWith("dev");
+ final boolean devenvironment = yacyVersion.combined2prettyVersion(sb.getConfig("version","0.1")).startsWith("dev");
if (devenvironment) {
sb.getLog().logInfo("AUTO-UPDATE: omiting update because this is a development environment");
prop.put("candeploy_autoUpdate", "3");
@@ -128,29 +128,29 @@ public class ConfigUpdate_p {
}
// version information
- String versionstring = yacyVersion.combined2prettyVersion(sb.getConfig("version","0.1"));
+ final String versionstring = yacyVersion.combined2prettyVersion(sb.getConfig("version","0.1"));
prop.put("candeploy_versionpp", versionstring);
- boolean devenvironment = versionstring.startsWith("dev");
+ final boolean devenvironment = versionstring.startsWith("dev");
double thisVersion = Double.parseDouble(sb.getConfig("version","0.1"));
// cut off the SVN Rev in the Version
- try {thisVersion = Math.round(thisVersion*1000.0)/1000.0;} catch (NumberFormatException e) {}
+ try {thisVersion = Math.round(thisVersion*1000.0)/1000.0;} catch (final NumberFormatException e) {}
// list downloaded releases
yacyVersion release, dflt;
- String[] downloaded = sb.releasePath.list();
+ final String[] downloaded = sb.releasePath.list();
prop.put("candeploy_deployenabled", (downloaded.length == 0) ? "0" : ((devenvironment) ? "1" : "2")); // prevent that a developer-version is over-deployed
- TreeSet<yacyVersion> downloadedreleases = new TreeSet<yacyVersion>();
+ final TreeSet<yacyVersion> downloadedreleases = new TreeSet<yacyVersion>();
for (int j = 0; j < downloaded.length; j++) {
try {
release = new yacyVersion(downloaded[j]);
downloadedreleases.add(release);
- } catch (RuntimeException e) {
+ } catch (final RuntimeException e) {
// not a valid release
// can be also a restart- or deploy-file
- File invalid = new File(sb.releasePath, downloaded[j]);
+ final File invalid = new File(sb.releasePath, downloaded[j]);
if (!(invalid.getName().endsWith(".bat") || invalid.getName().endsWith(".sh"))) // Windows & Linux don't like deleted scripts while execution!
invalid.deleteOnExit();
}
@@ -168,7 +168,7 @@ public class ConfigUpdate_p {
prop.put("candeploy_downloadedreleases", relcount);
// list remotely available releases
- yacyVersion.DevMain releasess = yacyVersion.allReleases(false);
+ final yacyVersion.DevMain releasess = yacyVersion.allReleases(false);
relcount = 0;
// main
diff --git a/htroot/Connections_p.java b/htroot/Connections_p.java
index 2b50de520..7837d2240 100644
--- a/htroot/Connections_p.java
+++ b/htroot/Connections_p.java
@@ -50,21 +50,21 @@ import de.anomic.yacy.yacySeed;
public final class Connections_p {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
// return variable that accumulates replacements
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
- serverObjects prop = new serverObjects();
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ final serverObjects prop = new serverObjects();
// get the virtualHost string
- String virtualHost = sb.getConfig("fileHost","localhost");
+ final String virtualHost = sb.getConfig("fileHost","localhost");
// get the serverCore thread
- serverThread httpd = sb.getThread("10_httpd");
+ final serverThread httpd = sb.getThread("10_httpd");
/* waiting for all threads to finish */
int threadCount = serverCore.sessionThreadGroup.activeCount();
- Thread[] threadList = new Thread[((serverCore) httpd).getJobCount()];
+ final Thread[] threadList = new Thread[((serverCore) httpd).getJobCount()];
threadCount = serverCore.sessionThreadGroup.enumerate(threadList);
// determines if name lookup should be done or not
@@ -74,10 +74,10 @@ public final class Connections_p {
doNameLookup = true;
}
if (post.containsKey("closeSession")) {
- String sessionName = post.get("closeSession",null);
+ final String sessionName = post.get("closeSession",null);
if (sessionName != null) {
for ( int currentThreadIdx = 0; currentThreadIdx < threadCount; currentThreadIdx++ ) {
- Thread currentThread = threadList[currentThreadIdx];
+ final Thread currentThread = threadList[currentThreadIdx];
if (
(currentThread != null) &&
(currentThread instanceof serverCore.Session) &&
@@ -86,12 +86,12 @@ public final class Connections_p {
){
// trying to gracefull stop session
((Session)currentThread).setStopped(true);
- try { Thread.sleep(100); } catch (InterruptedException ex) {}
+ try { Thread.sleep(100); } catch (final InterruptedException ex) {}
// trying to interrupt session
if (currentThread.isAlive()) {
currentThread.interrupt();
- try { Thread.sleep(100); } catch (InterruptedException ex) {}
+ try { Thread.sleep(100); } catch (final InterruptedException ex) {}
}
// trying to close socket
@@ -101,7 +101,7 @@ public final class Connections_p {
// waiting for session to finish
if (currentThread.isAlive()) {
- try { currentThread.join(500); } catch (InterruptedException ex) {}
+ try { currentThread.join(500); } catch (final InterruptedException ex) {}
}
}
}
@@ -114,38 +114,38 @@ public final class Connections_p {
int idx = 0, numActiveRunning = 0, numActivePending = 0;
boolean dark = true;
for ( int currentThreadIdx = 0; currentThreadIdx < threadCount; currentThreadIdx++ ) {
- Thread currentThread = threadList[currentThreadIdx];
+ final Thread currentThread = threadList[currentThreadIdx];
if ((currentThread != null) && (currentThread instanceof serverCore.Session) && (currentThread.isAlive())) {
// getting the session object
- Session currentSession = ((Session)currentThread);
+ final Session currentSession = ((Session)currentThread);
// getting the session runtime
- long sessionTime = currentSession.getTime();
+ final long sessionTime = currentSession.getTime();
// getting the request command line
boolean blockingRequest = false;
String commandLine = currentSession.getCommandLine();
if (commandLine == null) blockingRequest = true;
- int commandCount = currentSession.getCommandCount();
+ final int commandCount = currentSession.getCommandCount();
// getting the source ip address and port
- InetAddress userAddress = currentSession.getUserAddress();
- int userPort = currentSession.getUserPort();
+ final InetAddress userAddress = currentSession.getUserAddress();
+ final int userPort = currentSession.getUserPort();
if (userAddress == null) continue;
- boolean isSSL = currentSession.isSSL();
+ final boolean isSSL = currentSession.isSSL();
String dest = null;
String prot = null;
- serverHandler cmdObj = currentSession.getCommandObj();
+ final serverHandler cmdObj = currentSession.getCommandObj();
if (cmdObj instanceof httpd) {
prot = isSSL ? "https":"http";
// getting the http command object
- httpd currentHttpd = (httpd)cmdObj;
+ final httpd currentHttpd = (httpd)cmdObj;
// getting the connection properties of this session
- Properties conProp = (Properties) currentHttpd.getConProp().clone();
+ final Properties conProp = (Properties) currentHttpd.getConProp().clone();
// getting the destination host
dest = conProp.getProperty(httpHeader.CONNECTION_PROP_HOST);
@@ -153,7 +153,7 @@ public final class Connections_p {
} else if (cmdObj instanceof urlRedirectord) {
prot = "urlRedirector";
- urlRedirectord urlRedir = (urlRedirectord)cmdObj;
+ final urlRedirectord urlRedir = (urlRedirectord)cmdObj;
commandLine = urlRedir.getURL();
}
@@ -175,7 +175,7 @@ public final class Connections_p {
dark=!dark;
try {
prop.put("list_" + idx + "_sessionID",URLEncoder.encode(currentSession.getName(),"UTF8"));
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
@@ -210,12 +210,12 @@ public final class Connections_p {
prop.putNum("numActivePending", numActivePending);
// client sessions
- Set<HttpConnectionInfo> allConnections = HttpConnectionInfo.getAllConnections();
+ final Set<HttpConnectionInfo> allConnections = HttpConnectionInfo.getAllConnections();
// TODO sorting
// Arrays.sort(a, httpc.connectionTimeComparatorInstance);
int c = 0;
synchronized (allConnections) {
- for (HttpConnectionInfo conInfo: allConnections) {
+ for (final HttpConnectionInfo conInfo: allConnections) {
prop.put("clientList_" + c + "_clientProtocol", conInfo.getProtocol());
prop.putNum("clientList_" + c + "_clientLifetime", conInfo.getLifetime());
prop.putNum("clientList_" + c + "_clientIdletime", conInfo.getIdletime());
diff --git a/htroot/CookieMonitorIncoming_p.java b/htroot/CookieMonitorIncoming_p.java
index 88c957146..aee74e590 100644
--- a/htroot/CookieMonitorIncoming_p.java
+++ b/htroot/CookieMonitorIncoming_p.java
@@ -36,11 +36,11 @@ import de.anomic.server.serverSwitch;
public class CookieMonitorIncoming_p {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> sb) {
- plasmaSwitchboard switchboard = (plasmaSwitchboard) sb;
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> sb) {
+ final plasmaSwitchboard switchboard = (plasmaSwitchboard) sb;
// return variable that accumulates replacements
- serverObjects prop = new serverObjects();
+ final serverObjects prop = new serverObjects();
// handle on/off button
if(post != null) {
@@ -55,11 +55,11 @@ public class CookieMonitorIncoming_p {
prop.put("monitorCookies.on", switchboard.getConfigBool("proxy.monitorCookies", false) ? "1":"0");
prop.put("monitorCookies.off", !switchboard.getConfigBool("proxy.monitorCookies", false) ? "1":"0");
- int maxCount = 100;
+ final int maxCount = 100;
int entCount = 0;
int tmpCount = 0;
boolean dark = true;
- Iterator<Map.Entry<String, Object[]>> i = switchboard.incomingCookies.entrySet().iterator();
+ final Iterator<Map.Entry<String, Object[]>> i = switchboard.incomingCookies.entrySet().iterator();
Map.Entry<String, Object[]> entry;
String host, client;
Object[] cookies;
diff --git a/htroot/CookieMonitorOutgoing_p.java b/htroot/CookieMonitorOutgoing_p.java
index 83e11a14f..faf033da2 100644
--- a/htroot/CookieMonitorOutgoing_p.java
+++ b/htroot/CookieMonitorOutgoing_p.java
@@ -36,11 +36,11 @@ import de.anomic.server.serverSwitch;
public class CookieMonitorOutgoing_p {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> sb) {
- plasmaSwitchboard switchboard = (plasmaSwitchboard) sb;
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> sb) {
+ final plasmaSwitchboard switchboard = (plasmaSwitchboard) sb;
// return variable that accumulates replacements
- serverObjects prop = new serverObjects();
+ final serverObjects prop = new serverObjects();
// handle on/off button
if(post != null) {
@@ -55,11 +55,11 @@ public class CookieMonitorOutgoing_p {
prop.put("monitorCookies.on", switchboard.getConfigBool("proxy.monitorCookies", false) ? "1":"0");
prop.put("monitorCookies.off", !switchboard.getConfigBool("proxy.monitorCookies", false) ? "1":"0");
- int maxCount = 100;
+ final int maxCount = 100;
int entCount = 0;
int tmpCount = 0;
boolean dark = true;
- Iterator<Map.Entry<String, Object[]>> i = switchboard.outgoingCookies.entrySet().iterator();
+ final Iterator<Map.Entry<String, Object[]>> i = switchboard.outgoingCookies.entrySet().iterator();
Map.Entry<String, Object[]> entry;
String host, client;
Object[] cookies;
diff --git a/htroot/CookieTest_p.java b/htroot/CookieTest_p.java
index 466be44d3..0329be0a1 100644
--- a/htroot/CookieTest_p.java
+++ b/htroot/CookieTest_p.java
@@ -37,7 +37,7 @@ import de.anomic.server.servletProperties;
public class CookieTest_p {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
// case if no values are requested
@@ -50,16 +50,16 @@ public class CookieTest_p {
final servletProperties prop = new servletProperties();
if(post.containsKey("act")&&post.get("act").equals("clear_cookie")) {
- httpHeader outgoingHeader = new httpHeader();
- Iterator<Map.Entry<String, String>> it = header.entrySet().iterator();
+ final httpHeader outgoingHeader = new httpHeader();
+ final Iterator<Map.Entry<String, String>> it = header.entrySet().iterator();
Map.Entry<String, String> e;
while (it.hasNext()) {
e = it.next();
if (e.getKey().equals("Cookie")) {
- String coockie[]=e.getValue().toString().split(";");
+ final String coockie[]=e.getValue().toString().split(";");
for(int i=0;i<coockie.length;i++)
{
- String nameValue[]=coockie[i].split("=");
+ final String nameValue[]=coockie[i].split("=");
outgoingHeader.setCookie(nameValue[0].trim(),nameValue.length>1?(nameValue[1].trim()):"","Thu, 01-Jan-99 00:00:01 GMT");
}
}
@@ -75,9 +75,9 @@ public class CookieTest_p {
}
else if(post.containsKey("act")&&post.get("act").equals("set_cookie"))
{
- String cookieName = post.get("cookie_name").toString().trim();
- String cookieValue = post.get("cookie_value").toString().trim();
- httpHeader outgoingHeader=new httpHeader();
+ final String cookieName = post.get("cookie_name").toString().trim();
+ final String cookieValue = post.get("cookie_value").toString().trim();
+ final httpHeader outgoingHeader=new httpHeader();
outgoingHeader.setCookie(cookieName,cookieValue);
prop.setOutgoingHeader(outgoingHeader);
diff --git a/htroot/CrawlProfileEditor_p.java b/htroot/CrawlProfileEditor_p.java
index bec12361e..cd429ff3b 100644
--- a/htroot/CrawlProfileEditor_p.java
+++ b/htroot/CrawlProfileEditor_p.java
@@ -49,7 +49,7 @@ public class CrawlProfileEditor_p {
public final boolean readonly;
public final int type;
- public eentry(String name, String label, boolean readonly, int type) {
+ public eentry(final String name, final String label, final boolean readonly, final int type) {
this.name = name;
this.label = label;
this.readonly = readonly;
@@ -79,16 +79,16 @@ public class CrawlProfileEditor_p {
labels.add(new eentry(entry.XPSTOPW, "Parent stop-words", false, eentry.BOOLEAN));
}
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
final servletProperties prop = new servletProperties();
final plasmaSwitchboard sb = (plasmaSwitchboard)env;
// read post for handle
- String handle = (post == null) ? "" : post.get("handle", "");
+ final String handle = (post == null) ? "" : post.get("handle", "");
if (post != null) {
if (post.containsKey("terminate")) {
// termination of a crawl: shift the crawl from active to passive
- CrawlProfile.entry entry = sb.webIndex.profilesActiveCrawls.getEntry(handle);
+ final CrawlProfile.entry entry = sb.webIndex.profilesActiveCrawls.getEntry(handle);
if (entry != null) sb.webIndex.profilesPassiveCrawls.newEntry(entry.map());
sb.webIndex.profilesActiveCrawls.removeEntry(handle);
// delete all entries from the crawl queue that are deleted here
@@ -132,15 +132,15 @@ public class CrawlProfileEditor_p {
if ((post != null) && (selentry != null)) {
if (post.containsKey("submit")) {
try {
- Iterator<eentry> lit = labels.iterator();
+ final Iterator<eentry> lit = labels.iterator();
eentry tee;
while (lit.hasNext()) {
tee = lit.next();
- String cval = selentry.map().get(tee.name);
- String val = (tee.type == eentry.BOOLEAN) ? Boolean.toString(post.containsKey(tee.name)) : post.get(tee.name, cval);
+ final String cval = selentry.map().get(tee.name);
+ final String val = (tee.type == eentry.BOOLEAN) ? Boolean.toString(post.containsKey(tee.name)) : post.get(tee.name, cval);
if (!cval.equals(val)) sb.webIndex.profilesActiveCrawls.changeEntry(selentry, tee.name, val);
}
- } catch (IOException ex) {
+ } catch (final IOException ex) {
prop.put("error", "1");
prop.putHTML("error_message", ex.getMessage());
}
@@ -150,7 +150,7 @@ public class CrawlProfileEditor_p {
// generate crawl profile table
count = 0;
boolean dark = true;
- int domlistlength = (post == null) ? 160 : post.getInt("domlistlength", 160);
+ final int domlistlength = (post == null) ? 160 : post.getInt("domlistlength", 160);
CrawlProfile.entry profile;
// put active crawls into list
it = sb.webIndex.profilesActiveCrawls.profiles(true);
@@ -185,11 +185,11 @@ public class CrawlProfileEditor_p {
prop.put("edit", "1");
prop.put("edit_name", selentry.name());
prop.put("edit_handle", selentry.handle());
- Iterator<eentry> lit = labels.iterator();
+ final Iterator<eentry> lit = labels.iterator();
count = 0;
while (lit.hasNext()) {
- eentry ee = lit.next();
- String val = selentry.map().get(ee.name);
+ final eentry ee = lit.next();
+ final String val = selentry.map().get(ee.name);
prop.put("edit_entries_" + count + "_readonly", ee.readonly ? "1" : "0");
prop.put("edit_entries_" + count + "_readonly_name", ee.name);
prop.put("edit_entries_" + count + "_readonly_label", ee.label);
@@ -207,7 +207,7 @@ public class CrawlProfileEditor_p {
return prop;
}
- private static void putProfileEntry(servletProperties prop, CrawlProfile.entry profile, boolean active, boolean dark, int count, int domlistlength) {
+ private static void putProfileEntry(final servletProperties prop, final CrawlProfile.entry profile, final boolean active, final boolean dark, final int count, final int domlistlength) {
prop.put("crawlProfiles_" + count + "_dark", dark ? "1" : "0");
prop.put("crawlProfiles_" + count + "_status", active ? "1" : "0");
prop.put("crawlProfiles_" + count + "_name", profile.name());
diff --git a/htroot/CrawlResults.java b/htroot/CrawlResults.java
index 8a754961c..a15b80acb 100644
--- a/htroot/CrawlResults.java
+++ b/htroot/CrawlResults.java
@@ -41,7 +41,7 @@ import de.anomic.yacy.yacyURL;
public class CrawlResults {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, serverObjects post, final serverSwitch<?> env) {
// return variable that accumulates replacements
final plasmaSwitchboard sb = (plasmaSwitchboard) env;
final serverObjects prop = new serverObjects();
@@ -64,7 +64,7 @@ public class CrawlResults {
int tabletype;
try {
tabletype = Integer.parseInt(post.get("process", "0"));
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
tabletype = 0;
}
@@ -77,7 +77,7 @@ public class CrawlResults {
if (((tabletype > 0) && (tabletype < 6)) ||
(post != null && (post.containsKey("clearlist") ||
post.containsKey("deleteentry")))) {
- String authorization = ((String) header.get(httpHeader.AUTHORIZATION, "xxxxxx"));
+ final String authorization = ((String) header.get(httpHeader.AUTHORIZATION, "xxxxxx"));
if (authorization.length() != 0) {
if (! sb.verifyAuthentication(header, true)){
// force log-in (again, because wrong password was given)
@@ -100,7 +100,7 @@ public class CrawlResults {
// do the commands
if (post.containsKey("clearlist")) sb.crawlResults.clearStack(tabletype);
if (post.containsKey("deleteentry")) {
- String hash = post.get("hash", null);
+ final String hash = post.get("hash", null);
if (hash != null) {
// delete from database
sb.webIndex.removeURL(hash);
@@ -255,7 +255,7 @@ public class CrawlResults {
dark = !dark;
cnt++;
- } catch (Exception e) {
+ } catch (final Exception e) {
serverLog.logSevere("PLASMA", "genTableProps", e);
}
}
@@ -267,7 +267,7 @@ public class CrawlResults {
}
private static SimpleDateFormat dayFormatter = new SimpleDateFormat("yyyy/MM/dd", Locale.US);
- private static String daydate(Date date) {
+ private static String daydate(final Date date) {
if (date == null) {
return "";
} else {
diff --git a/htroot/CrawlStart_p.java b/htroot/CrawlStart_p.java
index 5b0dedd0d..49b8d792f 100644
--- a/htroot/CrawlStart_p.java
+++ b/htroot/CrawlStart_p.java
@@ -31,16 +31,16 @@ import de.anomic.server.serverSwitch;
public class CrawlStart_p {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
// return variable that accumulates replacements
- serverObjects prop = new serverObjects();
+ final serverObjects prop = new serverObjects();
// define visible variables
prop.put("proxyPrefetchDepth", env.getConfig("proxyPrefetchDepth", "0"));
prop.put("crawlingDepth", env.getConfig("crawlingDepth", "0"));
prop.put("crawlingFilter", env.getConfig("crawlingFilter", "0"));
- int crawlingIfOlder = (int) env.getConfigLong("crawlingIfOlder", -1);
+ final int crawlingIfOlder = (int) env.getConfigLong("crawlingIfOlder", -1);
prop.put("crawlingIfOlderCheck", (crawlingIfOlder == -1) ? "0" : "1");
prop.put("crawlingIfOlderUnitYearCheck", "0");
prop.put("crawlingIfOlderUnitMonthCheck", "0");
@@ -62,10 +62,10 @@ public class CrawlStart_p {
prop.put("crawlingIfOlderNumber", Math.max(1, Math.round(crawlingIfOlder / 60f)));
prop.put("crawlingIfOlderUnitHourCheck", "1");
}
- int crawlingDomFilterDepth = (int) env.getConfigLong("crawlingDomFilterDepth", -1);
+ final int crawlingDomFilterDepth = (int) env.getConfigLong("crawlingDomFilterDepth", -1);
prop.put("crawlingDomFilterCheck", (crawlingDomFilterDepth == -1) ? "0" : "1");
prop.put("crawlingDomFilterDepth", (crawlingDomFilterDepth == -1) ? 1 : crawlingDomFilterDepth);
- int crawlingDomMaxPages = (int) env.getConfigLong("crawlingDomMaxPages", -1);
+ final int crawlingDomMaxPages = (int) env.getConfigLong("crawlingDomMaxPages", -1);
prop.put("crawlingDomMaxCheck", (crawlingDomMaxPages == -1) ? "0" : "1");
prop.put("crawlingDomMaxPages", (crawlingDomMaxPages == -1) ? 10000 : crawlingDomMaxPages);
prop.put("crawlingQChecked", env.getConfig("crawlingQ", "").equals("true") ? "1" : "0");
@@ -74,8 +74,8 @@ public class CrawlStart_p {
prop.put("indexingMediaChecked", env.getConfig("indexMedia", "").equals("true") ? "1" : "0");
prop.put("crawlOrderChecked", env.getConfig("crawlOrder", "").equals("true") ? "1" : "0");
- long LCbusySleep = Integer.parseInt(env.getConfig(plasmaSwitchboard.CRAWLJOB_LOCAL_CRAWL_BUSYSLEEP, "100"));
- int LCppm = (LCbusySleep == 0) ? 1000 : (int) (60000L / LCbusySleep);
+ final long LCbusySleep = Integer.parseInt(env.getConfig(plasmaSwitchboard.CRAWLJOB_LOCAL_CRAWL_BUSYSLEEP, "100"));
+ final int LCppm = (LCbusySleep == 0) ? 1000 : (int) (60000L / LCbusySleep);
prop.put("crawlingSpeedMaxChecked", (LCppm >= 1000) ? "1" : "0");
prop.put("crawlingSpeedCustChecked", ((LCppm > 10) && (LCppm < 1000)) ? "1" : "0");
prop.put("crawlingSpeedMinChecked", (LCppm <= 10) ? "1" : "0");
diff --git a/htroot/FeedReader_p.java b/htroot/FeedReader_p.java
index df98f4d02..f9a21ee0a 100644
--- a/htroot/FeedReader_p.java
+++ b/htroot/FeedReader_p.java
@@ -37,22 +37,22 @@ import de.anomic.yacy.yacyURL;
public class FeedReader_p {
- public static servletProperties respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
- servletProperties prop = new servletProperties();
+ public static servletProperties respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
+ final servletProperties prop = new servletProperties();
prop.put("page", "0");
if (post != null) {
yacyURL url;
try {
url = new yacyURL(post.get("url"), null);
- } catch (MalformedURLException e) {
+ } catch (final MalformedURLException e) {
prop.put("page", "2");
return prop;
}
// int maxitems=Integer.parseInt(post.get("max", "0"));
// int offset=Integer.parseInt(post.get("offset", "0")); //offset to the first displayed item
- RSSFeed feed = new RSSReader(url.toString()).getFeed();
+ final RSSFeed feed = new RSSReader(url.toString()).getFeed();
prop.putHTML("page_title", feed.getChannel().getTitle());
if (feed.getChannel().getAuthor() == null) {
@@ -64,7 +64,7 @@ public class FeedReader_p {
prop.putHTML("page_description", feed.getChannel().getDescription());
int i = 0;
- for (RSSMessage item: feed) {
+ for (final RSSMessage item: feed) {
prop.putHTML("page_items_" + i + "_author", item.getAuthor());
prop.putHTML("page_items_" + i + "_title", item.getTitle());
prop.put("page_items_" + i + "_link", item.getLink());
diff --git a/htroot/IndexCleaner_p.java b/htroot/IndexCleaner_p.java
index dc11582d7..21edcd93d 100755
--- a/htroot/IndexCleaner_p.java
+++ b/htroot/IndexCleaner_p.java
@@ -35,9 +35,9 @@ public class IndexCleaner_p {
private static indexRepositoryReference.BlacklistCleaner urldbCleanerThread = null;
private static plasmaWordIndex.ReferenceCleaner indexCleanerThread = null;
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
- serverObjects prop = new serverObjects();
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
+ final serverObjects prop = new serverObjects();
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
prop.put("title", "DbCleanup_p");
if (post!=null) {
//prop.putHTML("bla", "post!=null");
@@ -86,7 +86,7 @@ public class IndexCleaner_p {
prop.put("urldb_lastHash", urldbCleanerThread.lastHash);
prop.put("urldb_threadAlive", urldbCleanerThread.isAlive() + "");
prop.put("urldb_threadToString", urldbCleanerThread.toString());
- double percent = ((double)urldbCleanerThread.blacklistedUrls/urldbCleanerThread.totalSearchedUrls)*100;
+ final double percent = ((double)urldbCleanerThread.blacklistedUrls/urldbCleanerThread.totalSearchedUrls)*100;
prop.putNum("urldb_percent", percent);
}
if (indexCleanerThread!=null) {
diff --git a/htroot/IndexControlRWIs_p.java b/htroot/IndexControlRWIs_p.java
index 5bcf4a7f6..5544bdff5 100644
--- a/htroot/IndexControlRWIs_p.java
+++ b/htroot/IndexControlRWIs_p.java
@@ -55,10 +55,10 @@ import de.anomic.yacy.yacyURL;
public class IndexControlRWIs_p {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
// return variable that accumulates replacements
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
- serverObjects prop = new serverObjects();
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ final serverObjects prop = new serverObjects();
prop.putHTML("keystring", "");
prop.put("keyhash", "");
@@ -74,15 +74,15 @@ public class IndexControlRWIs_p {
if (post != null) {
// default values
- String keystring = post.get("keystring", "").trim();
+ final String keystring = post.get("keystring", "").trim();
String keyhash = post.get("keyhash", "").trim();
prop.putHTML("keystring", keystring);
prop.put("keyhash", keyhash);
// read values from checkboxes
String[] urlx = post.getAll("urlhx.*");
- boolean delurl = post.containsKey("delurl");
- boolean delurlref = post.containsKey("delurlref");
+ final boolean delurl = post.containsKey("delurl");
+ final boolean delurlref = post.containsKey("delurlref");
if (post.containsKey("keystringsearch")) {
keyhash = indexWord.word2hash(keystring);
@@ -111,12 +111,12 @@ public class IndexControlRWIs_p {
sb.crawlQueues.clear();
try {
sb.crawlStacker.clear();
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
try {
sb.robots.clear();
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
post.remove("deletecomplete");
@@ -128,7 +128,7 @@ public class IndexControlRWIs_p {
// generate an urlx array
indexContainer index = null;
index = sb.webIndex.getContainer(keyhash, null);
- Iterator<indexRWIRowEntry> en = index.entries();
+ final Iterator<indexRWIRowEntry> en = index.entries();
int i = 0;
urlx = new String[index.size()];
while (en.hasNext()) {
@@ -159,7 +159,7 @@ public class IndexControlRWIs_p {
sb.urlRemove(urlx[i]);
}
}
- Set<String> urlHashes = new HashSet<String>();
+ final Set<String> urlHashes = new HashSet<String>();
for (int i = 0; i < urlx.length; i++) urlHashes.add(urlx[i]);
sb.webIndex.removeEntries(keyhash, urlHashes);
// this shall lead to a presentation of the list; so handle that the remaining program
@@ -172,8 +172,8 @@ public class IndexControlRWIs_p {
if (keystring.length() == 0 || !indexWord.word2hash(keystring).equals(keyhash)) {
prop.put("keystring", "&lt;not possible to compute word from hash&gt;");
}
- kelondroBitfield flags = plasmaSearchAPI.compileFlags(post);
- int count = (post.get("lines", "all").equals("all")) ? -1 : post.getInt("lines", -1);
+ final kelondroBitfield flags = plasmaSearchAPI.compileFlags(post);
+ final int count = (post.get("lines", "all").equals("all")) ? -1 : post.getInt("lines", -1);
final plasmaSearchRankingProcess ranking = plasmaSearchAPI.genSearchresult(prop, sb, keyhash, flags);
plasmaSearchAPI.genURLList(prop, keyhash, keystring, ranking, flags, count);
}
@@ -203,12 +203,12 @@ public class IndexControlRWIs_p {
// prepare index
indexContainer index;
String result;
- long starttime = System.currentTimeMillis();
+ final long starttime = System.currentTimeMillis();
index = sb.webIndex.getContainer(keyhash, null);
// built urlCache
- Iterator<indexRWIRowEntry> urlIter = index.entries();
- HashMap<String, indexURLReference> knownURLs = new HashMap<String, indexURLReference>();
- HashSet<String> unknownURLEntries = new HashSet<String>();
+ final Iterator<indexRWIRowEntry> urlIter = index.entries();
+ final HashMap<String, indexURLReference> knownURLs = new HashMap<String, indexURLReference>();
+ final HashSet<String> unknownURLEntries = new HashSet<String>();
indexRWIEntry iEntry;
indexURLReference lurl;
while (urlIter.hasNext()) {
@@ -223,9 +223,9 @@ public class IndexControlRWIs_p {
}
// transport to other peer
- String gzipBody = sb.getConfig("indexControl.gzipBody","false");
- int timeout = (int) sb.getConfigLong("indexControl.timeout",60000);
- HashMap<String, Object> resultObj = yacyClient.transferIndex(
+ final String gzipBody = sb.getConfig("indexControl.gzipBody","false");
+ final int timeout = (int) sb.getConfigLong("indexControl.timeout",60000);
+ final HashMap<String, Object> resultObj = yacyClient.transferIndex(
sb.webIndex.seedDB,
seed,
new indexContainer[]{index},
@@ -261,17 +261,17 @@ public class IndexControlRWIs_p {
}
if (post.containsKey("blacklist")) {
- String blacklist = post.get("blacklist", "");
- Set<String> urlHashes = new HashSet<String>();
+ final String blacklist = post.get("blacklist", "");
+ final Set<String> urlHashes = new HashSet<String>();
if (post.containsKey("blacklisturls")) {
PrintWriter pw;
try {
- String[] supportedBlacklistTypes = env.getConfig("BlackLists.types", "").split(",");
+ final String[] supportedBlacklistTypes = env.getConfig("BlackLists.types", "").split(",");
pw = new PrintWriter(new FileWriter(new File(listManager.listsPath, blacklist), true));
yacyURL url;
for (int i=0; i<urlx.length; i++) {
urlHashes.add(urlx[i]);
- indexURLReference e = sb.webIndex.getURL(urlx[i], null, 0);
+ final indexURLReference e = sb.webIndex.getURL(urlx[i], null, 0);
sb.webIndex.removeURL(urlx[i]);
if (e != null) {
url = e.comp().url();
@@ -287,19 +287,19 @@ public class IndexControlRWIs_p {
}
}
pw.close();
- } catch (IOException e) {
+ } catch (final IOException e) {
}
}
if (post.containsKey("blacklistdomains")) {
PrintWriter pw;
try {
- String[] supportedBlacklistTypes = indexAbstractReferenceBlacklist.BLACKLIST_TYPES_STRING.split(",");
+ final String[] supportedBlacklistTypes = indexAbstractReferenceBlacklist.BLACKLIST_TYPES_STRING.split(",");
pw = new PrintWriter(new FileWriter(new File(listManager.listsPath, blacklist), true));
yacyURL url;
for (int i=0; i<urlx.length; i++) {
urlHashes.add(urlx[i]);
- indexURLReference e = sb.webIndex.getURL(urlx[i], null, 0);
+ final indexURLReference e = sb.webIndex.getURL(urlx[i], null, 0);
sb.webIndex.removeURL(urlx[i]);
if (e != null) {
url = e.comp().url();
@@ -314,7 +314,7 @@ public class IndexControlRWIs_p {
}
}
pw.close();
- } catch (IOException e) {
+ } catch (final IOException e) {
}
}
sb.webIndex.removeEntries(keyhash, urlHashes);
diff --git a/htroot/IndexControlURLs_p.java b/htroot/IndexControlURLs_p.java
index 4a6cef10d..7e70480e8 100644
--- a/htroot/IndexControlURLs_p.java
+++ b/htroot/IndexControlURLs_p.java
@@ -44,18 +44,18 @@ import de.anomic.yacy.yacyURL;
public class IndexControlURLs_p {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
// return variable that accumulates replacements
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
- serverObjects prop = new serverObjects();
+ final serverObjects prop = new serverObjects();
prop.put("urlstring", "");
prop.put("urlhash", "");
prop.put("result", "");
prop.put("ucount", Integer.toString(sb.webIndex.countURL()));
prop.put("otherHosts", "");
- indexRepositoryReference.Export export = sb.webIndex.exportURL();
+ final indexRepositoryReference.Export export = sb.webIndex.exportURL();
if ((export != null) && (export.isAlive())) {
// there is currently a running export
prop.put("lurlexportfinished", 0);
@@ -97,13 +97,13 @@ public class IndexControlURLs_p {
prop.put("result", " ");
if (post.containsKey("urlhashdeleteall")) {
- int i = sb.removeAllUrlReferences(urlhash, true);
+ final int i = sb.removeAllUrlReferences(urlhash, true);
prop.put("result", "Deleted URL and " + i + " references from " + i + " word indexes.");
prop.put("lurlexport", 0);
}
if (post.containsKey("urlhashdelete")) {
- indexURLReference entry = sb.webIndex.getURL(urlhash, null, 0);
+ final indexURLReference entry = sb.webIndex.getURL(urlhash, null, 0);
if (entry == null) {
prop.put("result", "No Entry for URL hash " + urlhash + "; nothing deleted.");
} else {
@@ -118,7 +118,7 @@ public class IndexControlURLs_p {
if (post.containsKey("urldelete")) {
try {
urlhash = (new yacyURL(urlstring, null)).hash();
- } catch (MalformedURLException e) {
+ } catch (final MalformedURLException e) {
urlhash = null;
}
if ((urlhash == null) || (urlstring == null)) {
@@ -132,17 +132,17 @@ public class IndexControlURLs_p {
if (post.containsKey("urlstringsearch")) {
try {
- yacyURL url = new yacyURL(urlstring, null);
+ final yacyURL url = new yacyURL(urlstring, null);
urlhash = url.hash();
prop.put("urlhash", urlhash);
- indexURLReference entry = sb.webIndex.getURL(urlhash, null, 0);
+ final indexURLReference entry = sb.webIndex.getURL(urlhash, null, 0);
if (entry == null) {
prop.putHTML("urlstring", "unknown url: " + urlstring);
prop.put("urlhash", "");
} else {
prop.putAll(genUrlProfile(sb, entry, urlhash));
}
- } catch (MalformedURLException e) {
+ } catch (final MalformedURLException e) {
prop.putHTML("urlstring", "bad url: " + urlstring);
prop.put("urlhash", "");
}
@@ -150,7 +150,7 @@ public class IndexControlURLs_p {
}
if (post.containsKey("urlhashsearch")) {
- indexURLReference entry = sb.webIndex.getURL(urlhash, null, 0);
+ final indexURLReference entry = sb.webIndex.getURL(urlhash, null, 0);
if (entry == null) {
prop.put("result", "No Entry for URL hash " + urlhash);
} else {
@@ -164,7 +164,7 @@ public class IndexControlURLs_p {
if (post.containsKey("urlhashsimilar")) {
try {
final Iterator<indexURLReference> entryIt = new kelondroRotateIterator<indexURLReference>(sb.webIndex.entriesURL(true, urlhash), new String(kelondroBase64Order.zero((urlhash == null ? 0 : urlhash.length()))), sb.webIndex.size());
- StringBuffer result = new StringBuffer("Sequential List of URL-Hashes:<br />");
+ final StringBuffer result = new StringBuffer("Sequential List of URL-Hashes:<br />");
indexURLReference entry;
int i = 0;
int rows = 0, cols = 0;
@@ -183,7 +183,7 @@ public class IndexControlURLs_p {
}
prop.put("urlhashsimilar_rows", rows);
prop.put("result", result.toString());
- } catch (IOException e) {
+ } catch (final IOException e) {
prop.put("result", "No Entries for URL hash " + urlhash);
}
prop.put("lurlexport", 0);
@@ -192,8 +192,8 @@ public class IndexControlURLs_p {
if (post.containsKey("lurlexport")) {
// parse format
int format = 0;
- String fname = post.get("format", "url-text");
- boolean dom = fname.startsWith("dom"); // if dom== false complete urls are exported, othervise only the domain
+ final String fname = post.get("format", "url-text");
+ final boolean dom = fname.startsWith("dom"); // if dom== false complete urls are exported, othervise only the domain
if (fname.endsWith("text")) format = 0;
if (fname.endsWith("html")) format = 1;
if (fname.endsWith("rss")) format = 2;
@@ -205,10 +205,10 @@ public class IndexControlURLs_p {
if (format == 1) s = s + ".html";
if (format == 2) s = s + ".xml";
}
- File f = new File(s);
+ final File f = new File(s);
f.getParentFile().mkdirs();
- String filter = post.get("exportfilter", ".*");
- indexRepositoryReference.Export running = sb.webIndex.exportURL(f, filter, format, dom);
+ final String filter = post.get("exportfilter", ".*");
+ final indexRepositoryReference.Export running = sb.webIndex.exportURL(f, filter, format, dom);
prop.put("lurlexport_exportfile", s);
prop.put("lurlexport_urlcount", running.count());
@@ -223,15 +223,15 @@ public class IndexControlURLs_p {
return prop;
}
- private static serverObjects genUrlProfile(plasmaSwitchboard switchboard, indexURLReference entry, String urlhash) {
- serverObjects prop = new serverObjects();
+ private static serverObjects genUrlProfile(final plasmaSwitchboard switchboard, final indexURLReference entry, final String urlhash) {
+ final serverObjects prop = new serverObjects();
if (entry == null) {
prop.put("genUrlProfile", "1");
prop.put("genUrlProfile_urlhash", urlhash);
return prop;
}
- indexURLReference.Components comp = entry.comp();
- indexURLReference le = ((entry.referrerHash() == null) || (entry.referrerHash().length() != yacySeedDB.commonHashLength)) ? null : switchboard.webIndex.getURL(entry.referrerHash(), null, 0);
+ final indexURLReference.Components comp = entry.comp();
+ final indexURLReference le = ((entry.referrerHash() == null) || (entry.referrerHash().length() != yacySeedDB.commonHashLength)) ? null : switchboard.webIndex.getURL(entry.referrerHash(), null, 0);
if (comp.url() == null) {
prop.put("genUrlProfile", "1");
prop.put("genUrlProfile_urlhash", urlhash);
diff --git a/htroot/IndexCreateIndexingQueue_p.java b/htroot/IndexCreateIndexingQueue_p.java
index 685910c96..ea59f6e9c 100644
--- a/htroot/IndexCreateIndexingQueue_p.java
+++ b/htroot/IndexCreateIndexingQueue_p.java
@@ -40,10 +40,10 @@ import de.anomic.yacy.yacyURL;
public class IndexCreateIndexingQueue_p {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
// return variable that accumulates replacements
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
- serverObjects prop = new serverObjects();
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ final serverObjects prop = new serverObjects();
prop.put("rejected", "0");
int showRejectedCount = 100;
@@ -52,7 +52,7 @@ public class IndexCreateIndexingQueue_p {
if (post.containsKey("limit")) {
try {
showLimit = Integer.valueOf(post.get("limit")).intValue();
- } catch (NumberFormatException e) {}
+ } catch (final NumberFormatException e) {}
}
if (post.containsKey("clearRejected")) {
@@ -72,12 +72,12 @@ public class IndexCreateIndexingQueue_p {
}
sb.webIndex.queuePreStack.clear(); // reset file to clean up content completely
}
- } catch (Exception e) {}
+ } catch (final Exception e) {}
} else if (post.containsKey("deleteEntry")) {
- String urlHash = post.get("deleteEntry");
+ final String urlHash = post.get("deleteEntry");
try {
sb.webIndex.queuePreStack.remove(urlHash);
- } catch (Exception e) {}
+ } catch (final Exception e) {}
prop.put("LOCATION","");
return prop;
}
@@ -97,24 +97,24 @@ public class IndexCreateIndexingQueue_p {
long totalSize = 0;
// getting all entries that are currently in process
- ArrayList<IndexingStack.QueueEntry> entryList = new ArrayList<IndexingStack.QueueEntry>();
+ final ArrayList<IndexingStack.QueueEntry> entryList = new ArrayList<IndexingStack.QueueEntry>();
entryList.addAll(sb.webIndex.queuePreStack.getActiveQueueEntries());
- int inProcessCount = entryList.size();
+ final int inProcessCount = entryList.size();
// getting all enqueued entries
if ((sb.webIndex.queuePreStack.size() > 0)) {
- Iterator<IndexingStack.QueueEntry> i = sb.webIndex.queuePreStack.entryIterator(false);
+ final Iterator<IndexingStack.QueueEntry> i = sb.webIndex.queuePreStack.entryIterator(false);
while (i.hasNext()) entryList.add(i.next());
}
- int count=entryList.size();
+ final int count=entryList.size();
totalCount = count;
for (int i = 0; (i < count) && (entryCount < showLimit); i++) {
- boolean inProcess = i < inProcessCount;
+ final boolean inProcess = i < inProcessCount;
pcentry = entryList.get(i);
if ((pcentry != null)&&(pcentry.url() != null)) {
- long entrySize = pcentry.size();
+ final long entrySize = pcentry.size();
totalSize += entrySize;
initiator = sb.webIndex.seedDB.getConnected(pcentry.initiator());
prop.put("indexing-queue_list_"+entryCount+"_dark", inProcess ? "2" : (dark ? "1" : "0"));
diff --git a/htroot/IndexCreateLoaderQueue_p.java b/htroot/IndexCreateLoaderQueue_p.java
index efc2ceebb..b1e950c90 100644
--- a/htroot/IndexCreateLoaderQueue_p.java
+++ b/htroot/IndexCreateLoaderQueue_p.java
@@ -33,10 +33,10 @@ import de.anomic.yacy.yacySeed;
public class IndexCreateLoaderQueue_p {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
// return variable that accumulates replacements
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
- serverObjects prop = new serverObjects();
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ final serverObjects prop = new serverObjects();
if (sb.crawlQueues.size() == 0) {
@@ -44,7 +44,7 @@ public class IndexCreateLoaderQueue_p {
} else {
prop.put("loader-set", "1");
boolean dark = true;
- CrawlEntry[] w = sb.crawlQueues.activeWorkerEntries();
+ final CrawlEntry[] w = sb.crawlQueues.activeWorkerEntries();
yacySeed initiator;
int count = 0;
for (int i = 0; i < w.length; i++) {
diff --git a/htroot/IndexCreateWWWGlobalQueue_p.java b/htroot/IndexCreateWWWGlobalQueue_p.java
index aa53958bb..703ed9fb0 100644
--- a/htroot/IndexCreateWWWGlobalQueue_p.java
+++ b/htroot/IndexCreateWWWGlobalQueue_p.java
@@ -41,28 +41,28 @@ import de.anomic.yacy.yacySeed;
public class IndexCreateWWWGlobalQueue_p {
private static SimpleDateFormat dayFormatter = new SimpleDateFormat("yyyy/MM/dd", Locale.US);
- private static String daydate(Date date) {
+ private static String daydate(final Date date) {
if (date == null) return "";
return dayFormatter.format(date);
}
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
// return variable that accumulates replacements
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
- serverObjects prop = new serverObjects();
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ final serverObjects prop = new serverObjects();
int showLimit = 100;
if (post != null) {
if (post.containsKey("limit")) {
try {
showLimit = Integer.valueOf(post.get("limit")).intValue();
- } catch (NumberFormatException e) {}
+ } catch (final NumberFormatException e) {}
}
if (post.containsKey("clearcrawlqueue")) {
- int c = sb.crawlQueues.noticeURL.stackSize(NoticedURL.STACK_TYPE_LIMIT);
+ final int c = sb.crawlQueues.noticeURL.stackSize(NoticedURL.STACK_TYPE_LIMIT);
sb.crawlQueues.noticeURL.clear(NoticedURL.STACK_TYPE_LIMIT);
- try { sb.cleanProfiles(); } catch (InterruptedException e) { /* Ignore this */}
+ try { sb.cleanProfiles(); } catch (final InterruptedException e) { /* Ignore this */}
/*
int c = 0;
while (switchboard.urlPool.noticeURL.stackSize(plasmaCrawlNURL.STACK_TYPE_LIMIT) > 0) {
@@ -73,7 +73,7 @@ public class IndexCreateWWWGlobalQueue_p {
prop.put("info", "3");//crawling queue cleared
prop.putNum("info_numEntries", c);
} else if (post.containsKey("deleteEntry")) {
- String urlHash = post.get("deleteEntry");
+ final String urlHash = post.get("deleteEntry");
sb.crawlQueues.noticeURL.removeByURLHash(urlHash);
prop.put("LOCATION","");
return prop;
@@ -85,7 +85,7 @@ public class IndexCreateWWWGlobalQueue_p {
prop.put("crawler-queue", "0");
} else {
prop.put("crawler-queue", "1");
- ArrayList<CrawlEntry> crawlerList = sb.crawlQueues.noticeURL.top(NoticedURL.STACK_TYPE_LIMIT, showLimit);
+ final ArrayList<CrawlEntry> crawlerList = sb.crawlQueues.noticeURL.top(NoticedURL.STACK_TYPE_LIMIT, showLimit);
CrawlEntry urle;
boolean dark = true;
diff --git a/htroot/IndexCreateWWWLocalQueue_p.java b/htroot/IndexCreateWWWLocalQueue_p.java
index ae66bee78..38903e4af 100644
--- a/htroot/IndexCreateWWWLocalQueue_p.java
+++ b/htroot/IndexCreateWWWLocalQueue_p.java
@@ -46,7 +46,7 @@ import de.anomic.yacy.yacySeed;
public class IndexCreateWWWLocalQueue_p {
private static SimpleDateFormat dayFormatter = new SimpleDateFormat("yyyy/MM/dd", Locale.US);
- private static String daydate(Date date) {
+ private static String daydate(final Date date) {
if (date == null) return "";
return dayFormatter.format(date);
}
@@ -59,28 +59,28 @@ public class IndexCreateWWWLocalQueue_p {
private static final int INITIATOR = 5;
private static final int MODIFIED = 6;
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
// return variable that accumulates replacements
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
- serverObjects prop = new serverObjects();
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ final serverObjects prop = new serverObjects();
int showLimit = 100;
if (post != null) {
if (post.containsKey("limit")) {
try {
showLimit = Integer.valueOf(post.get("limit")).intValue();
- } catch (NumberFormatException e) {}
+ } catch (final NumberFormatException e) {}
}
if (post.containsKey("deleteEntries")) {
int c = 0;
- String pattern = post.get("pattern", ".*").trim();
+ final String pattern = post.get("pattern", ".*").trim();
final int option = post.getInt("option", INVALID);
if (pattern.equals(".*")) {
c = sb.crawlQueues.noticeURL.stackSize(NoticedURL.STACK_TYPE_CORE);
sb.crawlQueues.noticeURL.clear(NoticedURL.STACK_TYPE_CORE);
- try { sb.cleanProfiles(); } catch (InterruptedException e) {/* ignore this */}
+ try { sb.cleanProfiles(); } catch (final InterruptedException e) {/* ignore this */}
} else if (option > INVALID) {
Pattern compiledPattern = null;
try {
@@ -90,7 +90,7 @@ public class IndexCreateWWWLocalQueue_p {
if (option == PROFILE) {
// search and delete the crawl profile (_much_ faster, independant of queue size)
// XXX: what to do about the annoying LOST PROFILE messages in the log?
- Iterator<CrawlProfile.entry> it = sb.webIndex.profilesActiveCrawls.profiles(true);
+ final Iterator<CrawlProfile.entry> it = sb.webIndex.profilesActiveCrawls.profiles(true);
CrawlProfile.entry entry;
while (it.hasNext()) {
entry = it.next();
@@ -108,7 +108,7 @@ public class IndexCreateWWWLocalQueue_p {
}
} else {
// iterating through the list of URLs
- Iterator<CrawlEntry> iter = sb.crawlQueues.noticeURL.iterator(NoticedURL.STACK_TYPE_CORE);
+ final Iterator<CrawlEntry> iter = sb.crawlQueues.noticeURL.iterator(NoticedURL.STACK_TYPE_CORE);
CrawlEntry entry;
while (iter.hasNext()) {
if ((entry = iter.next()) == null) continue;
@@ -126,14 +126,14 @@ public class IndexCreateWWWLocalQueue_p {
}
if (value != null) {
- Matcher matcher = compiledPattern.matcher(value);
+ final Matcher matcher = compiledPattern.matcher(value);
if (matcher.find()) {
sb.crawlQueues.noticeURL.removeByURLHash(entry.url().hash());
}
}
}
}
- } catch (PatternSyntaxException e) {
+ } catch (final PatternSyntaxException e) {
e.printStackTrace();
}
}
@@ -141,7 +141,7 @@ public class IndexCreateWWWLocalQueue_p {
prop.put("info", "3");//crawling queue cleared
prop.putNum("info_numEntries", c);
} else if (post.containsKey("deleteEntry")) {
- String urlHash = post.get("deleteEntry");
+ final String urlHash = post.get("deleteEntry");
sb.crawlQueues.noticeURL.removeByURLHash(urlHash);
prop.put("LOCATION","");
return prop;
@@ -153,7 +153,7 @@ public class IndexCreateWWWLocalQueue_p {
prop.put("crawler-queue", "0");
} else {
prop.put("crawler-queue", "1");
- ArrayList<CrawlEntry> crawlerList = sb.crawlQueues.noticeURL.top(NoticedURL.STACK_TYPE_CORE, (int) (showLimit * 1.20));
+ final ArrayList<CrawlEntry> crawlerList = sb.crawlQueues.noticeURL.top(NoticedURL.STACK_TYPE_CORE, (int) (showLimit * 1.20));
CrawlEntry urle;
boolean dark = true;
diff --git a/htroot/IndexCreateWWWRemoteQueue_p.java b/htroot/IndexCreateWWWRemoteQueue_p.java
index ee60617bc..c46fd41b9 100644
--- a/htroot/IndexCreateWWWRemoteQueue_p.java
+++ b/htroot/IndexCreateWWWRemoteQueue_p.java
@@ -42,12 +42,12 @@ import de.anomic.yacy.yacySeed;
public class IndexCreateWWWRemoteQueue_p {
private static SimpleDateFormat dayFormatter = new SimpleDateFormat("yyyy/MM/dd", Locale.US);
- private static String daydate(Date date) {
+ private static String daydate(final Date date) {
if (date == null) return "";
return dayFormatter.format(date);
}
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
final servletProperties prop = new servletProperties();
final plasmaSwitchboard sb = (plasmaSwitchboard)env;
@@ -56,13 +56,13 @@ public class IndexCreateWWWRemoteQueue_p {
if (post.containsKey("limit")) {
try {
showLimit = Integer.parseInt(post.get("limit"));
- } catch (NumberFormatException e) { }
+ } catch (final NumberFormatException e) { }
}
if (post.containsKey("clearcrawlqueue")) {
- int c = sb.crawlQueues.noticeURL.stackSize(NoticedURL.STACK_TYPE_REMOTE);
+ final int c = sb.crawlQueues.noticeURL.stackSize(NoticedURL.STACK_TYPE_REMOTE);
sb.crawlQueues.noticeURL.clear(NoticedURL.STACK_TYPE_REMOTE);
- try { sb.cleanProfiles(); } catch (InterruptedException e) { /* Ignore this */}
+ try { sb.cleanProfiles(); } catch (final InterruptedException e) { /* Ignore this */}
/*
int c = 0;
while (switchboard.urlPool.noticeURL.stackSize(plasmaCrawlNURL.STACK_TYPE_LIMIT) > 0) {
@@ -73,7 +73,7 @@ public class IndexCreateWWWRemoteQueue_p {
prop.put("info", "3"); // crawling queue cleared
prop.putNum("info_numEntries", c);
} else if (post.containsKey("deleteEntry")) {
- String urlHash = post.get("deleteEntry");
+ final String urlHash = post.get("deleteEntry");
sb.crawlQueues.noticeURL.removeByURLHash(urlHash);
prop.put("LOCATION","");
return prop;
@@ -85,7 +85,7 @@ public class IndexCreateWWWRemoteQueue_p {
prop.put("crawler-queue", "0");
} else {
prop.put("crawler-queue", "1");
- ArrayList<CrawlEntry> crawlerList = sb.crawlQueues.noticeURL.top(NoticedURL.STACK_TYPE_REMOTE, showLimit);
+ final ArrayList<CrawlEntry> crawlerList = sb.crawlQueues.noticeURL.top(NoticedURL.STACK_TYPE_REMOTE, showLimit);
CrawlEntry urle;
boolean dark = true;
diff --git a/htroot/IndexImport_p.java b/htroot/IndexImport_p.java
index 3145ceef2..7bba8af40 100644
--- a/htroot/IndexImport_p.java
+++ b/htroot/IndexImport_p.java
@@ -43,19 +43,19 @@ import de.anomic.server.serverSwitch;
public final class IndexImport_p {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
// return variable that accumulates replacements
- plasmaSwitchboard switchboard = (plasmaSwitchboard) env;
- serverObjects prop = new serverObjects();
+ final plasmaSwitchboard switchboard = (plasmaSwitchboard) env;
+ final serverObjects prop = new serverObjects();
int activeCount = 0;
if (post != null) {
if (post.containsKey("startIndexDbImport")) {
try {
- boolean startImport = true;
+ final boolean startImport = true;
if (startImport) {
- Importer importerThread = new NoticeURLImporter(switchboard.plasmaPath, switchboard.crawlQueues, switchboard.webIndex.profilesActiveCrawls, switchboard.dbImportManager);
+ final Importer importerThread = new NoticeURLImporter(switchboard.plasmaPath, switchboard.crawlQueues, switchboard.webIndex.profilesActiveCrawls, switchboard.dbImportManager);
if (importerThread != null) {
importerThread.setJobID(switchboard.dbImportManager.generateUniqueJobID());
@@ -64,9 +64,9 @@ public final class IndexImport_p {
prop.put("LOCATION","");
return prop;
}
- } catch (Exception e) {
- serverByteBuffer errorMsg = new serverByteBuffer(100);
- PrintStream errorOut = new PrintStream(errorMsg);
+ } catch (final Exception e) {
+ final serverByteBuffer errorMsg = new serverByteBuffer(100);
+ final PrintStream errorOut = new PrintStream(errorMsg);
e.printStackTrace(errorOut);
prop.put("error", "3");
@@ -85,13 +85,13 @@ public final class IndexImport_p {
(post.containsKey("continueIndexDbImport"))
) {
// getting the job nr of the thread
- String jobID = post.get("jobNr");
- Importer importer = switchboard.dbImportManager.getImporterByID(Integer.valueOf(jobID).intValue());
+ final String jobID = post.get("jobNr");
+ final Importer importer = switchboard.dbImportManager.getImporterByID(Integer.valueOf(jobID).intValue());
if (importer != null) {
if (post.containsKey("stopIndexDbImport")) {
try {
importer.stopIt();
- } catch (InterruptedException e) {
+ } catch (final InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
@@ -112,18 +112,18 @@ public final class IndexImport_p {
/*
* Loop over all currently running jobs
*/
- Importer[] importThreads = switchboard.dbImportManager.getRunningImporter();
+ final Importer[] importThreads = switchboard.dbImportManager.getRunningImporter();
activeCount = importThreads.length;
for (int i=0; i < activeCount; i++) {
- Importer currThread = importThreads[i];
+ final Importer currThread = importThreads[i];
// get import type
prop.put("running.jobs_" + i + "_type", currThread.getJobType());
// root path of the source db
- String fullName = currThread.getJobName().toString();
- String shortName = (fullName.length()>30)?fullName.substring(0,12) + "..." + fullName.substring(fullName.length()-22,fullName.length()):fullName;
+ final String fullName = currThread.getJobName().toString();
+ final String shortName = (fullName.length()>30)?fullName.substring(0,12) + "..." + fullName.substring(fullName.length()-22,fullName.length()):fullName;
prop.put("running.jobs_" + i + "_fullName",fullName);
prop.put("running.jobs_" + i + "_shortName",shortName);
@@ -150,12 +150,12 @@ public final class IndexImport_p {
/*
* Loop over all finished jobs
*/
- Importer[] finishedJobs = switchboard.dbImportManager.getFinishedImporter();
+ final Importer[] finishedJobs = switchboard.dbImportManager.getFinishedImporter();
for (int i=0; i<finishedJobs.length; i++) {
- Importer currThread = finishedJobs[i];
- String error = currThread.getError();
- String fullName = currThread.getJobName().toString();
- String shortName = (fullName.length()>30)?fullName.substring(0,12) + "..." + fullName.substring(fullName.length()-22,fullName.length()):fullName;
+ final Importer currThread = finishedJobs[i];
+ final String error = currThread.getError();
+ final String fullName = currThread.getJobName().toString();
+ final String shortName = (fullName.length()>30)?fullName.substring(0,12) + "..." + fullName.substring(fullName.length()-22,fullName.length()):fullName;
prop.put("finished.jobs_" + i + "_type", currThread.getJobType());
prop.put("finished.jobs_" + i + "_fullName", fullName);
prop.put("finished.jobs_" + i + "_shortName", shortName);
diff --git a/htroot/IndexShare_p.java b/htroot/IndexShare_p.java
index ff6b435e1..60d7c9b66 100644
--- a/htroot/IndexShare_p.java
+++ b/htroot/IndexShare_p.java
@@ -35,10 +35,10 @@ import de.anomic.server.serverSwitch;
public class IndexShare_p {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
// return variable that accumulates replacements
- plasmaSwitchboard switchboard = (plasmaSwitchboard) env;
- serverObjects prop = new serverObjects();
+ final plasmaSwitchboard switchboard = (plasmaSwitchboard) env;
+ final serverObjects prop = new serverObjects();
if ((post == null) || (env == null)) {
prop.put("linkfreq", switchboard.getConfig("defaultLinkReceiveFrequency","30"));
diff --git a/htroot/IndexTransfer_p.java b/htroot/IndexTransfer_p.java
index 6f08ccdb4..863dc02c4 100644
--- a/htroot/IndexTransfer_p.java
+++ b/htroot/IndexTransfer_p.java
@@ -43,18 +43,18 @@ import de.anomic.yacy.yacySeed;
public final class IndexTransfer_p {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
// return variable that accumulates replacements
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
- serverObjects prop = new serverObjects();
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ final serverObjects prop = new serverObjects();
if (post != null) {
if (post.containsKey("startIndexTransfer")) {
- yacySeed seed = sb.webIndex.seedDB.getConnected(post.get("hostHash", ""));
+ final yacySeed seed = sb.webIndex.seedDB.getConnected(post.get("hostHash", ""));
if (seed == null) {
prop.put("running_status","Disconnected peer");
} else {
- boolean deleteIndex = post.get("deleteIndex", "0").equals("1");
+ final boolean deleteIndex = post.get("deleteIndex", "0").equals("1");
if(prop.containsKey("overwriteIP") && ! (prop.get("overwriteIP")).equals("")){
seed.setIP(prop.get("overwriteIP"));
}
@@ -79,9 +79,9 @@ public final class IndexTransfer_p {
prop.putNum("ucount", sb.webIndex.countURL());
prop.put("running",(sb.transferIdxThread==null) ? "0" : "1");
if (sb.transferIdxThread != null) {
- String[] status = sb.transferIdxThread.getStatus();
- String[] range = sb.transferIdxThread.getRange();
- int[] chunk = sb.transferIdxThread.getIndexCount();
+ final String[] status = sb.transferIdxThread.getStatus();
+ final String[] range = sb.transferIdxThread.getRange();
+ final int[] chunk = sb.transferIdxThread.getIndexCount();
prop.put("running_selection.status",status[0]);
prop.put("running_selection.twrange", range[0]);
@@ -111,8 +111,8 @@ public final class IndexTransfer_p {
yacySeed seed;
int hc = 0;
if ((sb.webIndex.seedDB != null) && (sb.webIndex.seedDB.sizeConnected() > 0)) {
- Iterator<yacySeed> e = sb.webIndex.peerActions.dhtAction.getAcceptRemoteIndexSeeds("------------");
- TreeMap<String, String> hostList = new TreeMap<String, String>();
+ final Iterator<yacySeed> e = sb.webIndex.peerActions.dhtAction.getAcceptRemoteIndexSeeds("------------");
+ final TreeMap<String, String> hostList = new TreeMap<String, String>();
while (e.hasNext()) {
seed = e.next();
if (seed != null) hostList.put(seed.get(yacySeed.NAME, "nameless"), seed.hash);
@@ -126,7 +126,7 @@ public final class IndexTransfer_p {
hc++;
hostList.remove(hostName);
}
- } catch (NoSuchElementException ex) {}
+ } catch (final NoSuchElementException ex) {}
prop.put("running_hosts", hc);
} else {
prop.put("running_hosts", "0");
diff --git a/htroot/LogStatistics_p.java b/htroot/LogStatistics_p.java
index 72ac2ca35..c092c24c8 100644
--- a/htroot/LogStatistics_p.java
+++ b/htroot/LogStatistics_p.java
@@ -42,20 +42,20 @@ public class LogStatistics_p {
private static final String RESULTS = "results_";
@SuppressWarnings({ "unchecked", "boxing" })
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch env) {
final serverObjects prop = new serverObjects();
- Logger logger = Logger.getLogger("");
+ final Logger logger = Logger.getLogger("");
- Handler[] handlers = logger.getHandlers();
+ final Handler[] handlers = logger.getHandlers();
Hashtable<String, Object> r = null;
boolean displaySubmenu = false;
for (int i=0; i<handlers.length; i++) {
if (handlers[i] instanceof LogalizerHandler) {
displaySubmenu = true;
- LogalizerHandler h = ((LogalizerHandler)handlers[i]);
+ final LogalizerHandler h = ((LogalizerHandler)handlers[i]);
r = h.getParserResults(h.getParser(0));
break;
}
diff --git a/htroot/MessageSend_p.java b/htroot/MessageSend_p.java
index 483bae7b1..8a809d3e8 100644
--- a/htroot/MessageSend_p.java
+++ b/htroot/MessageSend_p.java
@@ -40,21 +40,21 @@ import de.anomic.yacy.yacySeed;
public class MessageSend_p {
private static SimpleDateFormat SimpleFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
- public static String dateString(Date date) {
+ public static String dateString(final Date date) {
return SimpleFormatter.format(date);
}
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
- serverObjects prop = new serverObjects();
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ final serverObjects prop = new serverObjects();
if ((post == null) || (post.get("hash","").length() == 0)) {
prop.put("mode", "2");
return prop;
}
- String hash = post.get("hash", "");
+ final String hash = post.get("hash", "");
String subject = post.get("subject", "");
String message = post.get("message", "");
@@ -67,7 +67,7 @@ public class MessageSend_p {
// open an editor page for the message
// first ask if the other peer is online, and also what kind of document it accepts
- HashMap<String, String> result = yacyClient.permissionMessage(sb.webIndex.seedDB, hash);
+ final HashMap<String, String> result = yacyClient.permissionMessage(sb.webIndex.seedDB, hash);
//System.out.println("DEBUG: permission request result = " + result.toString());
String peerName;
yacySeed targetPeer = null;
@@ -82,7 +82,7 @@ public class MessageSend_p {
}
prop.putHTML("mode_permission_peerName", peerName, true);
- String response = (result == null) ? null : (String) result.get("response");
+ final String response = (result == null) ? null : (String) result.get("response");
if (response == null || result == null) {
// we don't have permission or other peer does not exist
prop.put("mode_permission", "0");
@@ -95,8 +95,8 @@ public class MessageSend_p {
// write input form
try {
- int messagesize = Integer.parseInt(result.get("messagesize"));
- int attachmentsize = Integer.parseInt(result.get("attachmentsize"));
+ final int messagesize = Integer.parseInt(result.get("messagesize"));
+ final int attachmentsize = Integer.parseInt(result.get("attachmentsize"));
prop.putHTML("mode_permission_response", response, true);
prop.put("mode_permission_messagesize", messagesize);
@@ -109,7 +109,7 @@ public class MessageSend_p {
}
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
// "unresolved pattern", the remote peer is alive but had an exception
prop.put("mode_permission", "2");
}
@@ -128,15 +128,15 @@ public class MessageSend_p {
byte[] mb;
try {
mb = message.getBytes("UTF-8");
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
mb = message.getBytes();
}
- HashMap<String, String> result = yacyClient.postMessage(sb.webIndex.seedDB, hash, subject, mb);
+ final HashMap<String, String> result = yacyClient.postMessage(sb.webIndex.seedDB, hash, subject, mb);
//message has been sent
prop.put("mode_status_response", result.get("response"));
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
prop.put("mode_status", "1");
// "unresolved pattern", the remote peer is alive but had an exception
diff --git a/htroot/Messages_p.java b/htroot/Messages_p.java
index b3adbdbec..1e3e09e36 100644
--- a/htroot/Messages_p.java
+++ b/htroot/Messages_p.java
@@ -46,13 +46,13 @@ public class Messages_p {
private static SimpleDateFormat SimpleFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
private static final String PEERSKNOWN = "peersKnown_";
- public static String dateString(Date date) {
+ public static String dateString(final Date date) {
return SimpleFormatter.format(date);
}
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
- serverObjects prop = new serverObjects();
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ final serverObjects prop = new serverObjects();
// set peer address / name
final String peerAddress = sb.webIndex.seedDB.mySeed().getPublicAddress();
@@ -65,10 +65,10 @@ public class Messages_p {
prop.put("peersKnown", "1");
int peerCount = 0;
try {
- TreeMap<String, String> hostList = new TreeMap<String, String>();
+ final TreeMap<String, String> hostList = new TreeMap<String, String>();
final Iterator<yacySeed> e = sb.webIndex.seedDB.seedsConnected(true, false, null, (float) 0.0);
while (e.hasNext()) {
- yacySeed seed = e.next();
+ final yacySeed seed = e.next();
if (seed != null) hostList.put(seed.get(yacySeed.NAME, "nameless"),seed.hash);
}
@@ -80,7 +80,7 @@ public class Messages_p {
hostList.remove(peername);
peerCount++;
}
- } catch (Exception e) {/* */}
+ } catch (final Exception e) {/* */}
prop.put(PEERSKNOWN + "peers", peerCount);
} else {
prop.put("peersKnown", "0");
@@ -93,15 +93,15 @@ public class Messages_p {
messageBoard.entry message;
// first reset notification
- File notifierSource = new File(sb.getRootPath(), sb.getConfig("htRootPath", "htroot") + "/env/grafics/empty.gif");
- File notifierDest = new File(sb.getConfigPath("htDocsPath", "DATA/HTDOCS"), "notifier.gif");
+ final File notifierSource = new File(sb.getRootPath(), sb.getConfig("htRootPath", "htroot") + "/env/grafics/empty.gif");
+ final File notifierDest = new File(sb.getConfigPath("htDocsPath", "DATA/HTDOCS"), "notifier.gif");
try {
serverFileUtils.copy(notifierSource, notifierDest);
- } catch (IOException e) {
+ } catch (final IOException e) {
}
if (action.equals("delete")) {
- String key = (post == null ? "" : post.get("object", ""));
+ final String key = (post == null ? "" : post.get("object", ""));
sb.messageDB.remove(key);
action = "list";
}
@@ -109,7 +109,7 @@ public class Messages_p {
if (action.equals("list")) {
prop.put("mode", "0"); //list
try {
- Iterator<String> i = sb.messageDB.keys(null, true);
+ final Iterator<String> i = sb.messageDB.keys(null, true);
String key;
boolean dark = true;
@@ -136,7 +136,7 @@ public class Messages_p {
// also write out the message body (needed for the RSS feed)
try {
prop.putHTML("mode_messages_"+count+"_body",new String(message.message(), "UTF-8"), true);
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
// can not happen, because UTF-8 must be supported by every JVM
}
}
@@ -145,7 +145,7 @@ public class Messages_p {
count++;
}
prop.put("mode_messages", count);
- } catch (IOException e) {
+ } catch (final IOException e) {
prop.put("mode_error", "1");//I/O error reading message table
prop.putHTML("mode_error_message", e.getMessage());
}
@@ -153,7 +153,7 @@ public class Messages_p {
if (action.equals("view")) {
prop.put("mode", "1"); //view
- String key = (post == null ? "" : post.get("object", ""));
+ final String key = (post == null ? "" : post.get("object", ""));
message = sb.messageDB.read(key);
if (message == null) throw new NullPointerException("Message with ID " + key + " does not exist");
@@ -164,7 +164,7 @@ public class Messages_p {
String theMessage = null;
try {
theMessage = new String(message.message(), "UTF-8");
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
// can not happen, because UTF-8 must be supported by every JVM
}
prop.putWiki("mode_message", theMessage);
diff --git a/htroot/Network.java b/htroot/Network.java
index 6122c56e5..a65fb18be 100644
--- a/htroot/Network.java
+++ b/htroot/Network.java
@@ -53,8 +53,8 @@ public class Network {
private static final String STR_TABLE_LIST = "table_list_";
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> switchboard) {
- plasmaSwitchboard sb = (plasmaSwitchboard) switchboard;
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> switchboard) {
+ final plasmaSwitchboard sb = (plasmaSwitchboard) switchboard;
final long start = System.currentTimeMillis();
// return variable that accumulates replacements
@@ -86,7 +86,7 @@ public class Network {
double myqph = 0d;
// create own peer info
- yacySeed seed = sb.webIndex.seedDB.mySeed();
+ final yacySeed seed = sb.webIndex.seedDB.mySeed();
if (sb.webIndex.seedDB.mySeed() != null){ //our Peer
// update seed info
sb.updateMySeed();
@@ -98,7 +98,7 @@ public class Network {
LCount = Long.parseLong(seed.get(yacySeed.LCOUNT, "0"));
ICount = Long.parseLong(seed.get(yacySeed.ICOUNT, "0"));
RCount = Long.parseLong(seed.get(yacySeed.RCOUNT, "0"));
- } catch (Exception e) {LCount = 0; ICount = 0; RCount = 0;}
+ } catch (final Exception e) {LCount = 0; ICount = 0; RCount = 0;}
// my-info
prop.putHTML("table_my-name", seed.get(yacySeed.NAME, "-") );
@@ -251,7 +251,7 @@ public class Network {
final HashMap<String, Map<String, String>> updatedBlog = new HashMap<String, Map<String, String>>();
final HashMap<String, String> isCrawling = new HashMap<String, String>();
yacyNewsRecord record;
- Iterator<yacyNewsRecord> recordIterator = sb.webIndex.newsPool.recordIterator(yacyNewsPool.INCOMING_DB, true);
+ final Iterator<yacyNewsRecord> recordIterator = sb.webIndex.newsPool.recordIterator(yacyNewsPool.INCOMING_DB, true);
while (recordIterator.hasNext()) {
record = recordIterator.next();
if (record == null) {
@@ -291,7 +291,7 @@ public class Network {
if (post != null && post.containsKey("search")) {
try {
peerSearchPattern = Pattern.compile(post.get("match", ""), Pattern.CASE_INSENSITIVE);
- } catch (PatternSyntaxException pse){
+ } catch (final PatternSyntaxException pse){
prop.put("regexerror", 1);
prop.putHTML("regexerror_wrongregex", pse.getPattern());
}
@@ -424,7 +424,7 @@ public class Network {
if (seed.getFlagAcceptRemoteIndex()) {
prop.put(STR_TABLE_LIST + conCount + "_dhtreceive_peertags", "");
} else {
- String peertags = serverCodings.set2string(seed.getPeerTags(), ",", false);
+ final String peertags = serverCodings.set2string(seed.getPeerTags(), ",", false);
prop.putHTML(STR_TABLE_LIST + conCount + "_dhtreceive_peertags", ((peertags == null) || (peertags.length() == 0)) ? "no tags given" : ("tags = " + peertags));
}
prop.putHTML(STR_TABLE_LIST + conCount + "_version", yacyVersion.combined2prettyVersion(seed.get(yacySeed.VERSION, "0.1"), shortname));
diff --git a/htroot/NetworkPicture.java b/htroot/NetworkPicture.java
index b5de54a25..919835427 100644
--- a/htroot/NetworkPicture.java
+++ b/htroot/NetworkPicture.java
@@ -34,8 +34,8 @@ import de.anomic.ymage.ymageMatrix;
/** draw a picture of the yacy network */
public class NetworkPicture {
- public static ymageMatrix respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ public static ymageMatrix respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
int width = 768;
int height = 576;
diff --git a/htroot/News.java b/htroot/News.java
index e82ba56d1..cad27b034 100644
--- a/htroot/News.java
+++ b/htroot/News.java
@@ -40,11 +40,11 @@ import de.anomic.yacy.yacySeed;
public class News {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
- serverObjects prop = new serverObjects();
- boolean overview = (post == null) || (post.get("page", "0").equals("0"));
- int tableID = (overview) ? -1 : (post == null ? 0 : Integer.parseInt(post.get("page", "0"))) - 1;
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ final serverObjects prop = new serverObjects();
+ final boolean overview = (post == null) || (post.get("page", "0").equals("0"));
+ final int tableID = (overview) ? -1 : (post == null ? 0 : Integer.parseInt(post.get("page", "0"))) - 1;
// execute commands
if (post != null) {
@@ -54,7 +54,7 @@ public class News {
prop.put("AUTHENTICATE", "admin log-in");
return prop; // this button needs authentication, force log-in
}
- Iterator<String> e = post.keySet().iterator();
+ final Iterator<String> e = post.keySet().iterator();
String check;
String id;
while (e.hasNext()) {
@@ -63,7 +63,7 @@ public class News {
id = check.substring(4);
try {
sb.webIndex.newsPool.moveOff(tableID, id);
- } catch (IOException ee) {ee.printStackTrace();}
+ } catch (final IOException ee) {ee.printStackTrace();}
}
}
}
@@ -79,7 +79,7 @@ public class News {
} else {
sb.webIndex.newsPool.moveOffAll(tableID);
}
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
}
@@ -101,8 +101,8 @@ public class News {
prop.put("table_page", tableID + 1);
if (sb.webIndex.seedDB != null) {
- int maxCount = Math.min(1000, sb.webIndex.newsPool.size(tableID));
- Iterator<yacyNewsRecord> recordIterator = sb.webIndex.newsPool.recordIterator(tableID, false);
+ final int maxCount = Math.min(1000, sb.webIndex.newsPool.size(tableID));
+ final Iterator<yacyNewsRecord> recordIterator = sb.webIndex.newsPool.recordIterator(tableID, false);
yacyNewsRecord record;
yacySeed seed;
int i = 0;
@@ -112,7 +112,7 @@ public class News {
seed = sb.webIndex.seedDB.getConnected(record.originator());
if (seed == null) seed = sb.webIndex.seedDB.getDisconnected(record.originator());
- String category = record.category();
+ final String category = record.category();
prop.put("table_list_" + i + "_id", record.id());
prop.putHTML("table_list_" + i + "_ori", (seed == null) ? record.originator() : seed.getName());
prop.put("table_list_" + i + "_cre", serverDate.formatShortSecond(record.created()));
@@ -121,14 +121,14 @@ public class News {
prop.put("table_list_" + i + "_rec", (record.received() == null) ? "-" : serverDate.formatShortSecond(record.received()));
prop.put("table_list_" + i + "_dis", record.distributed());
- Map<String, String> attributeMap = record.attributes();
+ final Map<String, String> attributeMap = record.attributes();
prop.putHTML("table_list_" + i + "_att", attributeMap.toString());
int j = 0;
if (attributeMap.size() > 0) {
- Iterator<String> attributeKeys = attributeMap.keySet().iterator();
+ final Iterator<String> attributeKeys = attributeMap.keySet().iterator();
while (attributeKeys.hasNext()) {
- String key = attributeKeys.next();
- String value = attributeMap.get(key);
+ final String key = attributeKeys.next();
+ final String value = attributeMap.get(key);
prop.put("table_list_" + i + "_attributes_" + j + "_name",key);
prop.putHTML("table_list_" + i + "_attributes_" + j + "_value",value);
j++;
diff --git a/htroot/PeerLoadPicture.java b/htroot/PeerLoadPicture.java
index 400060b9b..24aae7a90 100644
--- a/htroot/PeerLoadPicture.java
+++ b/htroot/PeerLoadPicture.java
@@ -13,7 +13,7 @@ import de.anomic.server.serverSwitch;
public class PeerLoadPicture {
- public static Image respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static Image respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
int width = 800;
int height = 600;
@@ -34,7 +34,7 @@ public class PeerLoadPicture {
pieces.put(plasmaSwitchboard.INDEX_DIST, new CircleThreadPiece("DHT-Distribution", new Color(119, 136, 153)));
pieces.put(plasmaSwitchboard.PEER_PING, new CircleThreadPiece("YaCy Core", new Color(255, 230, 160)));
- Iterator<String> threads = env.threadNames();
+ final Iterator<String> threads = env.threadNames();
String threadname;
serverBusyThread thread;
@@ -51,7 +51,7 @@ public class PeerLoadPicture {
if (showidle) idle.addExecTime(thread.getSleepTime());
//count threadgroup-specific times
- CircleThreadPiece piece = pieces.get(threadname);
+ final CircleThreadPiece piece = pieces.get(threadname);
if (piece == null) {
misc.addExecTime(thread.getBlockTime()+thread.getExecTime());
} else {
@@ -61,7 +61,7 @@ public class PeerLoadPicture {
busy_time += idle.getExecTime();
// set respective angles
- Iterator<CircleThreadPiece> it = pieces.values().iterator();
+ final Iterator<CircleThreadPiece> it = pieces.values().iterator();
CircleThreadPiece current;
while (it.hasNext()) {
current = it.next();
diff --git a/htroot/PerformanceGraph.java b/htroot/PerformanceGraph.java
index 09b33582a..271fc6ed4 100644
--- a/htroot/PerformanceGraph.java
+++ b/htroot/PerformanceGraph.java
@@ -33,13 +33,13 @@ import de.anomic.ymage.ymageMatrix;
public class PerformanceGraph {
- public static ymageMatrix respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ public static ymageMatrix respond(final httpHeader header, serverObjects post, final serverSwitch<?> env) {
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
if (post == null) post = new serverObjects();
- int width = post.getInt("width", 660);
- int height = post.getInt("height", 240);
+ final int width = post.getInt("width", 660);
+ final int height = post.getInt("height", 240);
return plasmaProfiling.performanceGraph(width, height, sb.webIndex.countURL() + " URLS / " + sb.webIndex.collectionsSize() + " WORDS IN COLLECTIONS / " + sb.webIndex.cacheSize() + " WORDS IN CACHE");
}
diff --git a/htroot/PerformanceMemory_p.java b/htroot/PerformanceMemory_p.java
index 7c89dceee..9d6309ed1 100644
--- a/htroot/PerformanceMemory_p.java
+++ b/htroot/PerformanceMemory_p.java
@@ -47,9 +47,9 @@ public class PerformanceMemory_p {
private static final long MB = 1024 * KB;
private static Map<String, String> defaultSettings = null;
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
// return variable that accumulates replacements
- serverObjects prop = new serverObjects();
+ final serverObjects prop = new serverObjects();
if (defaultSettings == null) {
defaultSettings = serverFileUtils.loadHashMap(new File(env.getRootPath(), "defaults/yacy.init"));
}
@@ -57,7 +57,7 @@ public class PerformanceMemory_p {
if (post != null) {
int xmx = 96; // default maximum heap size
if (post.containsKey("Xmx")) {
- try { xmx = Integer.valueOf(post.get("Xmx", "64")).intValue(); } catch (NumberFormatException e){}
+ try { xmx = Integer.valueOf(post.get("Xmx", "64")).intValue(); } catch (final NumberFormatException e){}
env.setConfig("javastart_Xmx", "Xmx" + xmx + "m");
env.setConfig("javastart_Xms", "Xms" + xmx + "m");
prop.put("setStartupCommit", "1");
@@ -68,15 +68,15 @@ public class PerformanceMemory_p {
}
}
- long memoryFreeNow = serverMemory.free();
- long memoryFreeAfterInitBGC = Long.parseLong(env.getConfig("memoryFreeAfterInitBGC", "0"));
- long memoryFreeAfterInitAGC = Long.parseLong(env.getConfig("memoryFreeAfterInitAGC", "0"));
- long memoryFreeAfterStartup = Long.parseLong(env.getConfig("memoryFreeAfterStartup", "0"));
- long memoryTotalNow = serverMemory.total();
- long memoryTotalAfterInitBGC = Long.parseLong(env.getConfig("memoryTotalAfterInitBGC", "0"));
- long memoryTotalAfterInitAGC = Long.parseLong(env.getConfig("memoryTotalAfterInitAGC", "0"));
- long memoryTotalAfterStartup = Long.parseLong(env.getConfig("memoryTotalAfterStartup", "0"));
- long memoryMax = serverMemory.max();
+ final long memoryFreeNow = serverMemory.free();
+ final long memoryFreeAfterInitBGC = Long.parseLong(env.getConfig("memoryFreeAfterInitBGC", "0"));
+ final long memoryFreeAfterInitAGC = Long.parseLong(env.getConfig("memoryFreeAfterInitAGC", "0"));
+ final long memoryFreeAfterStartup = Long.parseLong(env.getConfig("memoryFreeAfterStartup", "0"));
+ final long memoryTotalNow = serverMemory.total();
+ final long memoryTotalAfterInitBGC = Long.parseLong(env.getConfig("memoryTotalAfterInitBGC", "0"));
+ final long memoryTotalAfterInitAGC = Long.parseLong(env.getConfig("memoryTotalAfterInitAGC", "0"));
+ final long memoryTotalAfterStartup = Long.parseLong(env.getConfig("memoryTotalAfterStartup", "0"));
+ final long memoryMax = serverMemory.max();
prop.putNum("memoryMax", memoryMax / MB);
prop.putNum("memoryAvailAfterStartup", (memoryMax - memoryTotalAfterStartup + memoryFreeAfterStartup) / MB);
@@ -211,9 +211,9 @@ public class PerformanceMemory_p {
prop.putNum("objectMissCacheTotalMem", totalmissmem / (1024 * 1024d));
// parse initialization memory settings
- String Xmx = env.getConfig("javastart_Xmx", "Xmx96m").substring(3);
+ final String Xmx = env.getConfig("javastart_Xmx", "Xmx96m").substring(3);
prop.put("Xmx", Xmx.substring(0, Xmx.length() - 1));
- String Xms = env.getConfig("javastart_Xms", "Xms96m").substring(3);
+ final String Xms = env.getConfig("javastart_Xms", "Xms96m").substring(3);
prop.put("Xms", Xms.substring(0, Xms.length() - 1));
// other caching structures
diff --git a/htroot/PerformanceQueues_p.java b/htroot/PerformanceQueues_p.java
index 598b50c2b..6120be808 100644
--- a/htroot/PerformanceQueues_p.java
+++ b/htroot/PerformanceQueues_p.java
@@ -50,10 +50,10 @@ public class PerformanceQueues_p {
performanceProfiles.put("defaults/performance_dht.profile", "prefer DHT");
}
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> sb) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> sb) {
// return variable that accumulates replacements
- plasmaSwitchboard switchboard = (plasmaSwitchboard) sb;
- serverObjects prop = new serverObjects();
+ final plasmaSwitchboard switchboard = (plasmaSwitchboard) sb;
+ final serverObjects prop = new serverObjects();
File defaultSettingsFile = new File(switchboard.getRootPath(), "defaults/yacy.init");
if(post != null && post.containsKey("defaultFile")) {
// TODO check file-path!
@@ -63,12 +63,12 @@ public class PerformanceQueues_p {
defaultSettingsFile = value;
}
}
- Map<String, String> defaultSettings = ((post == null) || (!(post.containsKey("submitdefault")))) ? null : serverFileUtils.loadHashMap(defaultSettingsFile);
+ final Map<String, String> defaultSettings = ((post == null) || (!(post.containsKey("submitdefault")))) ? null : serverFileUtils.loadHashMap(defaultSettingsFile);
Iterator<String> threads = switchboard.threadNames();
String threadName;
serverBusyThread thread;
- boolean xml = (header.get("PATH")).endsWith(".xml");
+ final boolean xml = (header.get("PATH")).endsWith(".xml");
prop.setLocalized(!xml);
// calculate totals
@@ -182,7 +182,7 @@ public class PerformanceQueues_p {
// performance profiles
c = 0;
final String usedfile = switchboard.getConfig("performanceProfile", "defaults/yacy.init");
- for(String filename: performanceProfiles.keySet()) {
+ for(final String filename: performanceProfiles.keySet()) {
prop.put("profile_" + c + "_filename", filename);
prop.put("profile_" + c + "_description", performanceProfiles.get(filename));
prop.put("profile_" + c + "_used", usedfile.equalsIgnoreCase(filename) ? "1" : "0");
@@ -191,11 +191,11 @@ public class PerformanceQueues_p {
prop.put("profile", c);
if ((post != null) && (post.containsKey("cacheSizeSubmit"))) {
- int wordCacheMaxCount = post.getInt("wordCacheMaxCount", 20000);
+ final int wordCacheMaxCount = post.getInt("wordCacheMaxCount", 20000);
switchboard.setConfig(plasmaSwitchboard.WORDCACHE_MAX_COUNT, Integer.toString(wordCacheMaxCount));
switchboard.webIndex.setMaxWordCount(wordCacheMaxCount);
- int wordCacheInitCount = post.getInt(plasmaSwitchboard.WORDCACHE_INIT_COUNT, 30000);
+ final int wordCacheInitCount = post.getInt(plasmaSwitchboard.WORDCACHE_INIT_COUNT, 30000);
switchboard.setConfig(plasmaSwitchboard.WORDCACHE_INIT_COUNT, Integer.toString(wordCacheInitCount));
}
@@ -214,10 +214,10 @@ public class PerformanceQueues_p {
/*
* configuring the http pool
*/
- serverThread httpd = switchboard.getThread("10_httpd");
+ final serverThread httpd = switchboard.getThread("10_httpd");
try {
maxBusy = Integer.parseInt(post.get("httpd Session Pool_maxActive","8"));
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
maxBusy = 8;
}
@@ -239,8 +239,8 @@ public class PerformanceQueues_p {
}
if ((post != null) && (post.containsKey("minimumDeltaSubmit"))) {
- long minimumLocalDelta = post.getLong("minimumLocalDelta", switchboard.crawlQueues.noticeURL.getMinimumLocalDelta());
- long minimumGlobalDelta = post.getLong("minimumGlobalDelta", switchboard.crawlQueues.noticeURL.getMinimumGlobalDelta());
+ final long minimumLocalDelta = post.getLong("minimumLocalDelta", switchboard.crawlQueues.noticeURL.getMinimumLocalDelta());
+ final long minimumGlobalDelta = post.getLong("minimumGlobalDelta", switchboard.crawlQueues.noticeURL.getMinimumGlobalDelta());
switchboard.setConfig("minimumLocalDelta", minimumLocalDelta);
switchboard.setConfig("minimumGlobalDelta", minimumGlobalDelta);
switchboard.crawlQueues.noticeURL.setMinimumLocalDelta(minimumLocalDelta);
@@ -278,14 +278,14 @@ public class PerformanceQueues_p {
prop.put("pool_0_maxActive", switchboard.getConfigLong("crawler.MaxActiveThreads", 0));
prop.put("pool_0_numActive",switchboard.crawlQueues.size());
- serverThread httpd = switchboard.getThread("10_httpd");
+ final serverThread httpd = switchboard.getThread("10_httpd");
prop.put("pool_1_name", "httpd Session Pool");
prop.put("pool_1_maxActive", ((serverCore)httpd).getMaxSessionCount());
prop.put("pool_1_numActive", ((serverCore)httpd).getJobCount());
prop.put("pool", "2");
- long curr_prio = switchboard.getConfigLong("javastart_priority",0);
+ final long curr_prio = switchboard.getConfigLong("javastart_priority",0);
prop.put("priority_normal",(curr_prio==0) ? "1" : "0");
prop.put("priority_below",(curr_prio==10) ? "1" : "0");
prop.put("priority_low",(curr_prio==20) ? "1" : "0");
@@ -301,8 +301,8 @@ public class PerformanceQueues_p {
* @param busysleep
* @param memprereq
*/
- private static void onTheFlyReconfiguration(plasmaSwitchboard switchboard, String threadName, long idlesleep,
- long busysleep, long memprereq) {
+ private static void onTheFlyReconfiguration(final plasmaSwitchboard switchboard, final String threadName, final long idlesleep,
+ final long busysleep, final long memprereq) {
// on-the-fly re-configuration
switchboard.setThreadPerformance(threadName, idlesleep, busysleep, memprereq);
switchboard.setConfig(threadName + "_idlesleep", idlesleep);
@@ -310,7 +310,7 @@ public class PerformanceQueues_p {
switchboard.setConfig(threadName + "_memprereq", memprereq);
}
- private static String d(String a, String b) {
+ private static String d(final String a, final String b) {
return (a == null) ? b : a;
}
}
diff --git a/htroot/PerformanceSearch_p.java b/htroot/PerformanceSearch_p.java
index de2c2df29..df05edfe7 100644
--- a/htroot/PerformanceSearch_p.java
+++ b/htroot/PerformanceSearch_p.java
@@ -35,11 +35,11 @@ import de.anomic.server.serverSwitch;
public class PerformanceSearch_p {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> sb) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> sb) {
// return variable that accumulates replacements
- serverObjects prop = new serverObjects();
+ final serverObjects prop = new serverObjects();
- Iterator<serverProfiling.Event> events = serverProfiling.history("SEARCH");
+ final Iterator<serverProfiling.Event> events = serverProfiling.history("SEARCH");
int c = 0;
serverProfiling.Event event;
plasmaProfiling.searchEvent search;
diff --git a/htroot/ProxyIndexingMonitor_p.java b/htroot/ProxyIndexingMonitor_p.java
index db8871d29..ed9b7633e 100644
--- a/htroot/ProxyIndexingMonitor_p.java
+++ b/htroot/ProxyIndexingMonitor_p.java
@@ -43,10 +43,10 @@ public class ProxyIndexingMonitor_p {
// if (date == null) return ""; else return dayFormatter.format(date);
// }
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
// return variable that accumulates replacements
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
- serverObjects prop = new serverObjects();
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ final serverObjects prop = new serverObjects();
// int showIndexedCount = 20;
// boolean se = false;
@@ -65,13 +65,13 @@ public class ProxyIndexingMonitor_p {
if (newProxyPrefetchDepth < 0) newProxyPrefetchDepth = 0;
if (newProxyPrefetchDepth > 20) newProxyPrefetchDepth = 20; // self protection ?
env.setConfig("proxyPrefetchDepth", Integer.toString(newProxyPrefetchDepth));
- boolean proxyStoreHTCache = post.containsKey("proxyStoreHTCache");
+ final boolean proxyStoreHTCache = post.containsKey("proxyStoreHTCache");
env.setConfig("proxyStoreHTCache", (proxyStoreHTCache) ? "true" : "false");
- boolean proxyIndexingRemote = post.containsKey("proxyIndexingRemote");
+ final boolean proxyIndexingRemote = post.containsKey("proxyIndexingRemote");
env.setConfig("proxyIndexingRemote", proxyIndexingRemote ? "true" : "false");
- boolean proxyIndexingLocalText = post.containsKey("proxyIndexingLocalText");
+ final boolean proxyIndexingLocalText = post.containsKey("proxyIndexingLocalText");
env.setConfig("proxyIndexingLocalText", proxyIndexingLocalText ? "true" : "false");
- boolean proxyIndexingLocalMedia = post.containsKey("proxyIndexingLocalMedia");
+ final boolean proxyIndexingLocalMedia = post.containsKey("proxyIndexingLocalMedia");
env.setConfig("proxyIndexingLocalMedia", proxyIndexingLocalMedia ? "true" : "false");
// added proxyCache, proxyCacheSize - Borg-0300
@@ -132,13 +132,13 @@ public class ProxyIndexingMonitor_p {
prop.put("info_restart_return", "0");
if (!oldProxyCachePath.equals(newProxyCachePath)) prop.put("info_restart", "1");
- } catch (IOException e) {
+ } catch (final IOException e) {
prop.put("info", "3"); //Error: errmsg
prop.putHTML("info_error", e.getMessage());
}
}
- } catch (Exception e) {
+ } catch (final Exception e) {
prop.put("info", "2"); //Error: errmsg
prop.putHTML("info_error", e.getMessage());
serverLog.logSevere("SERVLET", "ProxyIndexingMonitor.case3", e);
@@ -156,18 +156,18 @@ public class ProxyIndexingMonitor_p {
return prop;
}
- public static long getLong(String value) {
+ public static long getLong(final String value) {
try {
return Long.parseLong(value);
- } catch (Exception e) {
+ } catch (final Exception e) {
return 0;
}
}
- public static String getStringLong(String value) {
+ public static String getStringLong(final String value) {
try {
return Long.toString(Long.parseLong(value));
- } catch (Exception e) {
+ } catch (final Exception e) {
return "0";
}
}
diff --git a/htroot/QuickCrawlLink_p.java b/htroot/QuickCrawlLink_p.java
index ca5aebf6a..eee6d239c 100644
--- a/htroot/QuickCrawlLink_p.java
+++ b/htroot/QuickCrawlLink_p.java
@@ -51,20 +51,21 @@ public class QuickCrawlLink_p {
* @param env the serverSwitch object holding all runtime-data
* @return the rewrite-properties for the template
*/
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
- serverObjects prop = new serverObjects();
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ final serverObjects prop = new serverObjects();
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
if (post == null) {
// send back usage example
prop.put("mode", "0");
// getting the http host header
- String hostSocket = header.get(httpHeader.CONNECTION_PROP_HOST);
+ final String hostSocket = header.get(httpHeader.CONNECTION_PROP_HOST);
//String host = hostSocket;
- int port = 80, pos = hostSocket.indexOf(":");
+ int port = 80;
+ final int pos = hostSocket.indexOf(":");
if (pos != -1) {
port = Integer.parseInt(hostSocket.substring(pos + 1));
//host = hostSocket.substring(0, pos);
@@ -81,44 +82,44 @@ public class QuickCrawlLink_p {
String crawlingStart = post.get("url",null);
try {
crawlingStart = URLDecoder.decode(crawlingStart, "UTF-8");
- } catch (UnsupportedEncodingException e1) {
+ } catch (final UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// getting the browser title
- String title = post.get("title",null);
+ final String title = post.get("title",null);
// getting other parameters if set
- String crawlingFilter = post.get("crawlingFilter", ".*");
- int CrawlingDepth = Integer.parseInt(post.get("crawlingDepth", "0"));
- boolean crawlDynamic = post.get("crawlingQ", "").equals("on");
- boolean indexText = post.get("indexText", "on").equals("on");
- boolean indexMedia = post.get("indexMedia", "on").equals("on");
- boolean storeHTCache = post.get("storeHTCache", "").equals("on");
- boolean remoteIndexing = post.get("crawlOrder", "").equals("on");
- boolean xsstopw = post.get("xsstopw", "").equals("on");
- boolean xdstopw = post.get("xdstopw", "").equals("on");
- boolean xpstopw = post.get("xpstopw", "").equals("on");
+ final String crawlingFilter = post.get("crawlingFilter", ".*");
+ final int CrawlingDepth = Integer.parseInt(post.get("crawlingDepth", "0"));
+ final boolean crawlDynamic = post.get("crawlingQ", "").equals("on");
+ final boolean indexText = post.get("indexText", "on").equals("on");
+ final boolean indexMedia = post.get("indexMedia", "on").equals("on");
+ final boolean storeHTCache = post.get("storeHTCache", "").equals("on");
+ final boolean remoteIndexing = post.get("crawlOrder", "").equals("on");
+ final boolean xsstopw = post.get("xsstopw", "").equals("on");
+ final boolean xdstopw = post.get("xdstopw", "").equals("on");
+ final boolean xpstopw = post.get("xpstopw", "").equals("on");
prop.put("mode_url", (crawlingStart == null) ? "unknown" : crawlingStart);
prop.putHTML("mode_title", (title == null) ? "unknown" : title);
if (crawlingStart != null) {
crawlingStart = crawlingStart.trim();
- try {crawlingStart = new yacyURL(crawlingStart, null).toNormalform(true, true);} catch (MalformedURLException e1) {}
+ try {crawlingStart = new yacyURL(crawlingStart, null).toNormalform(true, true);} catch (final MalformedURLException e1) {}
// check if url is proper
yacyURL crawlingStartURL = null;
try {
crawlingStartURL = new yacyURL(crawlingStart, null);
- } catch (MalformedURLException e) {
+ } catch (final MalformedURLException e) {
prop.put("mode_status", "1");
prop.put("mode_code", "1");
return prop;
}
- String urlhash = crawlingStartURL.hash();
+ final String urlhash = crawlingStartURL.hash();
sb.webIndex.removeURL(urlhash);
sb.crawlQueues.noticeURL.removeByURLHash(urlhash);
sb.crawlQueues.errorURL.remove(urlhash);
@@ -146,7 +147,7 @@ public class QuickCrawlLink_p {
xdstopw,
xpstopw
);
- } catch (Exception e) {
+ } catch (final Exception e) {
// mist
prop.put("mode_status", "2");//Error with url
prop.put("mode_code", "2");
diff --git a/htroot/Ranking_p.java b/htroot/Ranking_p.java
index 2cb5e20c3..feddb7a07 100644
--- a/htroot/Ranking_p.java
+++ b/htroot/Ranking_p.java
@@ -97,14 +97,14 @@ public class Ranking_p {
return prop;
}
- private static void putRanking(serverObjects prop, plasmaSearchRankingProfile rankingProfile, String prefix) {
+ private static void putRanking(final serverObjects prop, final plasmaSearchRankingProfile rankingProfile, final String prefix) {
putRanking(prop, rankingProfile.preToExternalMap(prefix), prefix, "Pre");
putRanking(prop, rankingProfile.postToExternalMap(prefix), prefix, "Post");
}
- private static void putRanking(serverObjects prop, Map<String, String> map, String prefix, String attrExtension) {
+ private static void putRanking(final serverObjects prop, final Map<String, String> map, final String prefix, final String attrExtension) {
prop.put("attr" + attrExtension, map.size());
- Iterator<String> it = map.keySet().iterator();
+ final Iterator<String> it = map.keySet().iterator();
String key;
int i, j = 0;
while (it.hasNext()) {
@@ -118,7 +118,7 @@ public class Ranking_p {
try {
prop.put("attr" + attrExtension + "_" + j + "_select_" + i + "_checked",
(i == Integer.valueOf(map.get(key)).intValue()) ? "1" : "0");
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
prop.put("attr" + attrExtension + "_" + j + "_select_" + i + "_checked", "0");
}
}
@@ -128,7 +128,7 @@ public class Ranking_p {
}
}
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
final plasmaSwitchboard sb = (plasmaSwitchboard) env;
// clean up all search events
@@ -138,13 +138,13 @@ public class Ranking_p {
if ((post == null) || (env == null)) {
// we create empty entries for template strings
final serverObjects prop = defaultValues();
- plasmaSearchRankingProfile ranking = sb.getRanking();
+ final plasmaSearchRankingProfile ranking = sb.getRanking();
putRanking(prop, ranking, "local");
return prop;
}
if (post.containsKey("EnterRanking")) {
- plasmaSearchRankingProfile ranking = new plasmaSearchRankingProfile("local", post.toString());
+ final plasmaSearchRankingProfile ranking = new plasmaSearchRankingProfile("local", post.toString());
sb.setConfig("rankingProfile", crypt.simpleEncode(ranking.toExternalString()));
final serverObjects prop = defaultValues();
//prop.putAll(ranking.toExternalMap("local"));
@@ -154,14 +154,14 @@ public class Ranking_p {
if (post.containsKey("ResetRanking")) {
sb.setConfig("rankingProfile", "");
- plasmaSearchRankingProfile ranking = new plasmaSearchRankingProfile(plasmaSearchQuery.CONTENTDOM_TEXT);
+ final plasmaSearchRankingProfile ranking = new plasmaSearchRankingProfile(plasmaSearchQuery.CONTENTDOM_TEXT);
final serverObjects prop = defaultValues();
//prop.putAll(ranking.toExternalMap("local"));
putRanking(prop, ranking, "local");
return prop;
}
- plasmaSearchRankingProfile localRanking = new plasmaSearchRankingProfile("local", post.toString());
+ final plasmaSearchRankingProfile localRanking = new plasmaSearchRankingProfile("local", post.toString());
final serverObjects prop = new serverObjects();
putRanking(prop, localRanking, "local");
prop.putAll(localRanking.toExternalMap("local"));
diff --git a/htroot/SearchEventPicture.java b/htroot/SearchEventPicture.java
index 1f1e152cd..9372c9af0 100644
--- a/htroot/SearchEventPicture.java
+++ b/htroot/SearchEventPicture.java
@@ -37,11 +37,11 @@ import de.anomic.ymage.ymageMatrix;
public class SearchEventPicture {
- public static ymageMatrix respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
- String eventID = (String) header.get("event", plasmaSearchEvent.lastEventID);
+ public static ymageMatrix respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ final String eventID = (String) header.get("event", plasmaSearchEvent.lastEventID);
if (eventID == null) return null;
- ymageMatrix yp = plasmaGrafics.getSearchEventPicture(sb.webIndex.seedDB, eventID);
+ final ymageMatrix yp = plasmaGrafics.getSearchEventPicture(sb.webIndex.seedDB, eventID);
if (yp == null) return new ymageMatrix(1, 1, ymageMatrix.MODE_SUB, "000000"); // empty image
return yp;
diff --git a/htroot/SettingsAck_p.java b/htroot/SettingsAck_p.java
index 501083656..e67994632 100644
--- a/htroot/SettingsAck_p.java
+++ b/htroot/SettingsAck_p.java
@@ -59,13 +59,13 @@ public class SettingsAck_p {
private static boolean nothingChanged = false;
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
// return variable that accumulates replacements
- serverObjects prop = new serverObjects();
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ final serverObjects prop = new serverObjects();
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
// get referer for backlink
- String referer = header.get(httpHeader.REFERER);
+ final String referer = header.get(httpHeader.REFERER);
prop.put("referer", (referer == null) ? "Settings_p.html" : referer);
//if (post == null) System.out.println("POST: NULL"); else System.out.println("POST: " + post.toString());
@@ -78,9 +78,9 @@ public class SettingsAck_p {
// admin password
if (post.containsKey("adminaccount")) {
// read and process data
- String user = post.get("adminuser");
- String pw1 = post.get("adminpw1");
- String pw2 = post.get("adminpw2");
+ final String user = post.get("adminuser");
+ final String pw1 = post.get("adminpw1");
+ final String pw2 = post.get("adminpw2");
// do checks
if ((user == null) || (pw1 == null) || (pw2 == null)) {
prop.put("info", "1");//error with submitted information
@@ -108,14 +108,14 @@ public class SettingsAck_p {
/*
* set new port
*/
- String port = post.get("port");
+ final String port = post.get("port");
prop.putHTML("info_port", port);
if (!env.getConfig("port", port).equals(port)) {
// validation port
- serverCore theServerCore = (serverCore) env.getThread("10_httpd");
+ final serverCore theServerCore = (serverCore) env.getThread("10_httpd");
try {
- InetSocketAddress theNewAddress = theServerCore.generateSocketAddress(port);
- String hostName = theNewAddress.getHostName();
+ final InetSocketAddress theNewAddress = theServerCore.generateSocketAddress(port);
+ final String hostName = theNewAddress.getHostName();
prop.put("info_restart", "1");
prop.put("info_restart_ip",(hostName.equals("0.0.0.0"))? "localhost" : hostName);
prop.put("info_restart_port", theNewAddress.getPort());
@@ -123,7 +123,7 @@ public class SettingsAck_p {
env.setConfig("port", port);
theServerCore.reconnect(5000);
- } catch (SocketException e) {
+ } catch (final SocketException e) {
prop.put("info", "26");
return prop;
}
@@ -160,13 +160,13 @@ public class SettingsAck_p {
int patternCount = 0;
String patternStr = null;
try {
- StringTokenizer st = new StringTokenizer(filter,",");
+ final StringTokenizer st = new StringTokenizer(filter,",");
while (st.hasMoreTokens()) {
patternCount++;
patternStr = st.nextToken();
Pattern.compile(patternStr);
}
- } catch (PatternSyntaxException e) {
+ } catch (final PatternSyntaxException e) {
prop.put("info", "27");
prop.putHTML("info_filter", filter);
prop.put("info_nr", patternCount);
@@ -262,13 +262,13 @@ public class SettingsAck_p {
int patternCount = 0;
String patternStr = null;
try {
- StringTokenizer st = new StringTokenizer(filter,",");
+ final StringTokenizer st = new StringTokenizer(filter,",");
while (st.hasMoreTokens()) {
patternCount++;
patternStr = st.nextToken();
Pattern.compile(patternStr);
}
- } catch (PatternSyntaxException e) {
+ } catch (final PatternSyntaxException e) {
prop.put("info", "27");
prop.putHTML("info_filter", filter);
prop.put("info_nr", patternCount);
@@ -316,23 +316,23 @@ public class SettingsAck_p {
/* ====================================================================
* Reading out the remote proxy settings
* ==================================================================== */
- boolean useRemoteProxy = post.containsKey("remoteProxyUse");
- boolean useRemoteProxy4Yacy = post.containsKey("remoteProxyUse4Yacy");
- boolean useRemoteProxy4SSL = post.containsKey("remoteProxyUse4SSL");
+ final boolean useRemoteProxy = post.containsKey("remoteProxyUse");
+ final boolean useRemoteProxy4Yacy = post.containsKey("remoteProxyUse4Yacy");
+ final boolean useRemoteProxy4SSL = post.containsKey("remoteProxyUse4SSL");
- String remoteProxyHost = post.get("remoteProxyHost", "");
- String remoteProxyPortStr = post.get("remoteProxyPort", "");
+ final String remoteProxyHost = post.get("remoteProxyHost", "");
+ final String remoteProxyPortStr = post.get("remoteProxyPort", "");
int remoteProxyPort = 0;
try {
remoteProxyPort = Integer.parseInt(remoteProxyPortStr);
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
remoteProxyPort = 3128;
}
- String remoteProxyUser = post.get("remoteProxyUser", "");
- String remoteProxyPwd = post.get("remoteProxyPwd", "");
+ final String remoteProxyUser = post.get("remoteProxyUser", "");
+ final String remoteProxyPwd = post.get("remoteProxyPwd", "");
- String remoteProxyNoProxyStr = post.get("remoteProxyNoProxy", "");
+ final String remoteProxyNoProxyStr = post.get("remoteProxyNoProxy", "");
//String[] remoteProxyNoProxyPatterns = remoteProxyNoProxyStr.split(",");
/* ====================================================================
@@ -387,12 +387,12 @@ public class SettingsAck_p {
if (post.containsKey("seedSettings")) {
// getting the currently used uploading method
- String oldSeedUploadMethod = env.getConfig("seedUploadMethod","none");
- String newSeedUploadMethod = post.get("seedUploadMethod");
- String oldSeedURLStr = sb.webIndex.seedDB.mySeed().get(yacySeed.SEEDLIST, "");
- String newSeedURLStr = post.get("seedURL");
+ final String oldSeedUploadMethod = env.getConfig("seedUploadMethod","none");
+ final String newSeedUploadMethod = post.get("seedUploadMethod");
+ final String oldSeedURLStr = sb.webIndex.seedDB.mySeed().get(yacySeed.SEEDLIST, "");
+ final String newSeedURLStr = post.get("seedURL");
- boolean seedUrlChanged = !oldSeedURLStr.equals(newSeedURLStr);
+ final boolean seedUrlChanged = !oldSeedURLStr.equals(newSeedURLStr);
boolean uploadMethodChanged = !oldSeedUploadMethod.equals(newSeedUploadMethod);
if (uploadMethodChanged) {
uploadMethodChanged = yacyCore.changeSeedUploadMethod(newSeedUploadMethod);
@@ -423,22 +423,22 @@ public class SettingsAck_p {
* Loop through the available seed uploaders to see if the
* configuration of one of them has changed
*/
- HashMap<String, String> uploaders = yacyCore.getSeedUploadMethods();
- Iterator<String> uploaderKeys = uploaders.keySet().iterator();
+ final HashMap<String, String> uploaders = yacyCore.getSeedUploadMethods();
+ final Iterator<String> uploaderKeys = uploaders.keySet().iterator();
while (uploaderKeys.hasNext()) {
// getting the uploader module name
- String uploaderName = uploaderKeys.next();
+ final String uploaderName = uploaderKeys.next();
// determining if the user has reconfigured the settings of this uploader
if (post.containsKey("seed" + uploaderName + "Settings")) {
nothingChanged = true;
- yacySeedUploader theUploader = yacyCore.getSeedUploader(uploaderName);
- String[] configOptions = theUploader.getConfigurationOptions();
+ final yacySeedUploader theUploader = yacyCore.getSeedUploader(uploaderName);
+ final String[] configOptions = theUploader.getConfigurationOptions();
if (configOptions != null) {
for (int i=0; i<configOptions.length; i++) {
- String newSettings = post.get(configOptions[i],"");
- String oldSettings = env.getConfig(configOptions[i],"");
+ final String newSettings = post.get(configOptions[i],"");
+ final String oldSettings = env.getConfig(configOptions[i],"");
nothingChanged &= newSettings.equals(oldSettings);
if (!nothingChanged) {
env.setConfig(configOptions[i],newSettings);
@@ -495,22 +495,22 @@ public class SettingsAck_p {
if (post.containsKey("parserSettings")) {
post.remove("parserSettings");
- Set<String> parserModes = plasmaParser.getParserConfigList().keySet();
- HashMap<String, HashSet<String>> newConfigList = new HashMap<String, HashSet<String>>();
+ final Set<String> parserModes = plasmaParser.getParserConfigList().keySet();
+ final HashMap<String, HashSet<String>> newConfigList = new HashMap<String, HashSet<String>>();
Iterator<String> parserModeIter = parserModes.iterator();
while (parserModeIter.hasNext()) {
- String currParserMode = parserModeIter.next();
+ final String currParserMode = parserModeIter.next();
newConfigList.put(currParserMode, new HashSet<String>());
}
// looping through all received settings
int pos;
- Iterator<String> keyEnum = post.keySet().iterator();
+ final Iterator<String> keyEnum = post.keySet().iterator();
while (keyEnum.hasNext()) {
- String key = keyEnum.next();
+ final String key = keyEnum.next();
if ((pos = key.indexOf(".")) != -1) {
- String currParserMode = key.substring(0,pos).trim().toUpperCase();
- String currMimeType = key.substring(pos+1).replaceAll("\n", "");
+ final String currParserMode = key.substring(0,pos).trim().toUpperCase();
+ final String currMimeType = key.substring(pos+1).replaceAll("\n", "");
if (parserModes.contains(currParserMode)) {
HashSet<String> currEnabledMimeTypes;
assert (newConfigList.containsKey(currParserMode)) : "Unexpected Error";
@@ -521,11 +521,11 @@ public class SettingsAck_p {
}
int enabledMimesCount = 0;
- StringBuffer currEnabledMimesTxt = new StringBuffer();
+ final StringBuffer currEnabledMimesTxt = new StringBuffer();
parserModeIter = newConfigList.keySet().iterator();
while (parserModeIter.hasNext()) {
- String currParserMode = parserModeIter.next();
- String[] enabledMimes = plasmaParser.setEnabledParserList(currParserMode, newConfigList.get(currParserMode));
+ final String currParserMode = parserModeIter.next();
+ final String[] enabledMimes = plasmaParser.setEnabledParserList(currParserMode, newConfigList.get(currParserMode));
Arrays.sort(enabledMimes);
currEnabledMimesTxt.setLength(0);
@@ -556,7 +556,7 @@ public class SettingsAck_p {
crawlerTimeout = Integer.valueOf(timeoutStr).intValue();
if (crawlerTimeout < 0) crawlerTimeout = 0;
env.setConfig("crawler.clientTimeout", Integer.toString(crawlerTimeout));
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
prop.put("info", "29");
prop.put("info_crawler.clientTimeout",post.get("crawler.clientTimeout"));
return prop;
@@ -573,7 +573,7 @@ public class SettingsAck_p {
maxHttpSize = -1;
}
env.setConfig("crawler.http.maxFileSize", Long.toString(maxHttpSize));
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
prop.put("info", "30");
prop.put("info_crawler.http.maxFileSize",post.get("crawler.http.maxFileSize"));
return prop;
@@ -587,7 +587,7 @@ public class SettingsAck_p {
try {
maxFtpSize = Integer.valueOf(maxSizeStr).intValue();
env.setConfig("crawler.ftp.maxFileSize", Long.toString(maxFtpSize));
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
prop.put("info", "31");
prop.put("info_crawler.ftp.maxFileSize",post.get("crawler.ftp.maxFileSize"));
return prop;
diff --git a/htroot/Settings_p.java b/htroot/Settings_p.java
index dc696bb1a..7706270f0 100644
--- a/htroot/Settings_p.java
+++ b/htroot/Settings_p.java
@@ -42,14 +42,14 @@ import de.anomic.yacy.yacySeedUploader;
public final class Settings_p {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
// return variable that accumulates replacements
- serverObjects prop = new serverObjects();
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ final serverObjects prop = new serverObjects();
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
//if (post == null) System.out.println("POST: NULL"); else System.out.println("POST: " + post.toString());
- String page = (post == null) ? "general" : post.get("page", "general");
+ final String page = (post == null) ? "general" : post.get("page", "general");
if (page.equals("ProxyAccess")) {
prop.put("settingsTables", "Settings_ProxyAccess.inc");
@@ -179,23 +179,23 @@ public final class Settings_p {
env.setConfig("seedUploadMethod",enabledUploader);
}
- HashMap<String, String> uploaders = yacyCore.getSeedUploadMethods();
+ final HashMap<String, String> uploaders = yacyCore.getSeedUploadMethods();
prop.put("seedUploadMethods", uploaders.size() + 1);
prop.put("seedUploadMethods_0_name", "none");
prop.put("seedUploadMethods_0_selected", enabledUploader.equals("none") ? "1" : "0");
prop.put("seedUploadMethods_0_file", "");
int count = 0;
- Iterator<String> uploaderKeys = uploaders.keySet().iterator();
+ final Iterator<String> uploaderKeys = uploaders.keySet().iterator();
while (uploaderKeys.hasNext()) {
count++;
- String uploaderName = uploaderKeys.next();
+ final String uploaderName = uploaderKeys.next();
prop.put("seedUploadMethods_" +count+ "_name", uploaderName);
prop.put("seedUploadMethods_" +count+ "_selected", uploaderName.equals(enabledUploader) ? "1" : "0");
prop.put("seedUploadMethods_" +count+ "_file", "Settings_Seed_Upload" + uploaderName + ".inc");
- yacySeedUploader theUploader = yacyCore.getSeedUploader(uploaderName);
- String[] configOptions = theUploader.getConfigurationOptions();
+ final yacySeedUploader theUploader = yacyCore.getSeedUploader(uploaderName);
+ final String[] configOptions = theUploader.getConfigurationOptions();
if (configOptions != null) {
for (int i=0; i<configOptions.length; i++) {
prop.put("seedUploadMethods_" +count+ "_" + configOptions[i], env.getConfig(configOptions[i], ""));
@@ -218,10 +218,10 @@ public final class Settings_p {
* Parser Configuration
*/
- HashMap<String, plasmaParserConfig> configList = plasmaParser.getParserConfigList();
- plasmaParserConfig[] configArray = configList.values().toArray(new plasmaParserConfig[configList.size()]);
+ final HashMap<String, plasmaParserConfig> configList = plasmaParser.getParserConfigList();
+ final plasmaParserConfig[] configArray = configList.values().toArray(new plasmaParserConfig[configList.size()]);
- HashSet<ParserInfo> parserInfos = new HashSet<ParserInfo>(sb.parser.getAvailableParserList().values());
+ final HashSet<ParserInfo> parserInfos = new HashSet<ParserInfo>(sb.parser.getAvailableParserList().values());
// // fetching a list of all available mimetypes
// List availableParserKeys = Arrays.asList(availableParsers.entrySet().toArray(new ParserInfo[availableParsers.size()]));
@@ -230,29 +230,29 @@ public final class Settings_p {
// Collections.sort(availableParserKeys);
// loop through the mimeTypes and add it to the properties
- boolean[] allParsersEnabled = new boolean[configList.size()];
+ final boolean[] allParsersEnabled = new boolean[configList.size()];
for (int i=0; i<configArray.length; i++)
allParsersEnabled[i] = true;
int parserIdx = 0;
- Iterator<ParserInfo> availableParserIter = parserInfos.iterator();
+ final Iterator<ParserInfo> availableParserIter = parserInfos.iterator();
while (availableParserIter.hasNext()) {
- ParserInfo parserInfo = availableParserIter.next();
+ final ParserInfo parserInfo = availableParserIter.next();
prop.put("parser_" + parserIdx + "_name", parserInfo.parserName);
prop.putHTML("parser_" + parserIdx + "_version", parserInfo.parserVersionNr, true);
prop.put("parser_" + parserIdx + "_usage", parserInfo.usageCount);
prop.put("parser_" + parserIdx + "_colspan", configArray.length);
int mimeIdx = 0;
- Enumeration<String> mimeTypeIter = parserInfo.supportedMimeTypes.keys();
+ final Enumeration<String> mimeTypeIter = parserInfo.supportedMimeTypes.keys();
while (mimeTypeIter.hasMoreElements()) {
- String mimeType = mimeTypeIter.nextElement();
+ final String mimeType = mimeTypeIter.nextElement();
prop.put("parser_" + parserIdx + "_mime_" + mimeIdx + "_mimetype", mimeType);
//prop.put("parser_" + parserIdx + "_name", parserName);
//prop.put("parser_" + parserIdx + "_shortname", parserName.substring(parserName.lastIndexOf(".")+1));
for (int i=0; i<configArray.length; i++) {
- HashSet<String> enabledParsers = configArray[i].getEnabledParserList();
+ final HashSet<String> enabledParsers = configArray[i].getEnabledParserList();
prop.put("parser_" + parserIdx + "_mime_" + mimeIdx + "_parserMode_" + i + "_optionName", configArray[i].parserMode + "." + mimeType);
prop.put("parser_" + parserIdx + "_mime_" + mimeIdx + "_parserMode_" + i + "_status", enabledParsers.contains(mimeType) ? "1" : "0");
allParsersEnabled[i] &= enabledParsers.contains(mimeType);
diff --git a/htroot/Status.java b/htroot/Status.java
index 0c27d6487..4b0769a99 100644
--- a/htroot/Status.java
+++ b/htroot/Status.java
@@ -50,7 +50,7 @@ public class Status {
private static final String SEEDSERVER = "seedServer";
private static final String PEERSTATUS = "peerStatus";
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
// return variable that accumulates replacements
final serverObjects prop = new serverObjects();
final plasmaSwitchboard sb = (plasmaSwitchboard) env;
@@ -65,14 +65,14 @@ public class Status {
prop.put("LOCATION","");
return prop;
} else if (post.containsKey("pauseCrawlJob")) {
- String jobType = post.get("jobType");
+ final String jobType = post.get("jobType");
if (jobType.equals("localCrawl"))
sb.pauseCrawlJob(plasmaSwitchboard.CRAWLJOB_LOCAL_CRAWL);
else if (jobType.equals("remoteTriggeredCrawl"))
sb.pauseCrawlJob(plasmaSwitchboard.CRAWLJOB_REMOTE_TRIGGERED_CRAWL);
redirect = true;
} else if (post.containsKey("continueCrawlJob")) {
- String jobType = post.get("jobType");
+ final String jobType = post.get("jobType");
if (jobType.equals("localCrawl"))
sb.continueCrawlJob(plasmaSwitchboard.CRAWLJOB_LOCAL_CRAWL);
else if (jobType.equals("remoteTriggeredCrawl"))
@@ -83,7 +83,7 @@ public class Status {
httpdByteCountOutputStream.resetCount();
redirect = true;
} else if (post.containsKey("popup")) {
- String trigger_enabled = post.get("popup");
+ final String trigger_enabled = post.get("popup");
if (trigger_enabled.equals("false")) {
sb.setConfig("browserPopUpTrigger", "false");
} else if (trigger_enabled.equals("true")){
@@ -91,7 +91,7 @@ public class Status {
}
redirect = true;
} else if (post.containsKey("tray")) {
- String trigger_enabled = post.get("tray");
+ final String trigger_enabled = post.get("tray");
if (trigger_enabled.equals("false")) {
sb.setConfig("trayIcon", "false");
} else if (trigger_enabled.equals("true")){
@@ -109,7 +109,7 @@ public class Status {
// update seed info
sb.updateMySeed();
- boolean adminaccess = sb.adminAuthenticated(header) >= 2;
+ final boolean adminaccess = sb.adminAuthenticated(header) >= 2;
if (adminaccess) {
prop.put("showPrivateTable", "1");
prop.put("privateStatusTable", "Status_p.inc");
@@ -129,19 +129,19 @@ public class Status {
// free disk space
if ((adminaccess) && (!sb.observer.getDisksOK()))
{
- String minFree = serverMemory.bytesToString(sb.observer.getMinFreeDiskSpace());
+ final String minFree = serverMemory.bytesToString(sb.observer.getMinFreeDiskSpace());
prop.put("warningDiskSpaceLow", "1");
prop.put("warningDiskSpaceLow_minSpace", minFree);
}
// version information
- String versionstring = yacyVersion.combined2prettyVersion(sb.getConfig("version","0.1"));
+ final String versionstring = yacyVersion.combined2prettyVersion(sb.getConfig("version","0.1"));
prop.put("versionpp", versionstring);
double thisVersion = Double.parseDouble(sb.getConfig("version","0.1"));
// cut off the SVN Rev in the Version
- try {thisVersion = Math.round(thisVersion*1000.0)/1000.0;} catch (NumberFormatException e) {}
+ try {thisVersion = Math.round(thisVersion*1000.0)/1000.0;} catch (final NumberFormatException e) {}
// place some more hints
if ((adminaccess) && (sb.getThread(plasmaSwitchboard.CRAWLJOB_LOCAL_CRAWL).getJobCount() == 0) && (sb.getThread(plasmaSwitchboard.INDEXER).getJobCount() == 0)) {
@@ -153,8 +153,8 @@ public class Status {
}
// hostname and port
- String extendedPortString = sb.getConfig("port", "8080");
- int pos = extendedPortString.indexOf(":");
+ final String extendedPortString = sb.getConfig("port", "8080");
+ final int pos = extendedPortString.indexOf(":");
prop.put("port",serverCore.getPortNr(extendedPortString));
if (pos!=-1) {
prop.put("extPortFormat", "1");
@@ -289,21 +289,21 @@ public class Status {
prop.put("trafficCrawler", serverMemory.bytesToString(httpdByteCountInputStream.getAccountCount("CRAWLER")));
// connection information
- serverCore httpd = (serverCore) sb.getThread("10_httpd");
+ final serverCore httpd = (serverCore) sb.getThread("10_httpd");
prop.putNum("connectionsActive", httpd.getJobCount());
prop.putNum("connectionsMax", httpd.getMaxSessionCount());
// Queue information
- int indexingJobCount = sb.getThread("80_indexing").getJobCount() + sb.webIndex.queuePreStack.getActiveQueueSize();
- int indexingMaxCount = (int) sb.getConfigLong(plasmaSwitchboard.INDEXER_SLOTS, 30);
- int indexingPercent = (indexingMaxCount==0)?0:indexingJobCount*100/indexingMaxCount;
+ final int indexingJobCount = sb.getThread("80_indexing").getJobCount() + sb.webIndex.queuePreStack.getActiveQueueSize();
+ final int indexingMaxCount = (int) sb.getConfigLong(plasmaSwitchboard.INDEXER_SLOTS, 30);
+ final int indexingPercent = (indexingMaxCount==0)?0:indexingJobCount*100/indexingMaxCount;
prop.putNum("indexingQueueSize", indexingJobCount);
prop.putNum("indexingQueueMax", indexingMaxCount);
prop.put("indexingQueuePercent",(indexingPercent>100) ? 100 : indexingPercent);
- int loaderJobCount = sb.crawlQueues.size();
- int loaderMaxCount = Integer.parseInt(sb.getConfig(plasmaSwitchboard.CRAWLER_THREADS_ACTIVE_MAX, "10"));
- int loaderPercent = (loaderMaxCount==0)?0:loaderJobCount*100/loaderMaxCount;
+ final int loaderJobCount = sb.crawlQueues.size();
+ final int loaderMaxCount = Integer.parseInt(sb.getConfig(plasmaSwitchboard.CRAWLER_THREADS_ACTIVE_MAX, "10"));
+ final int loaderPercent = (loaderMaxCount==0)?0:loaderJobCount*100/loaderMaxCount;
prop.putNum("loaderQueueSize", loaderJobCount);
prop.putNum("loaderQueueMax", loaderMaxCount);
prop.put("loaderQueuePercent", (loaderPercent>100) ? 100 : loaderPercent);
diff --git a/htroot/Steering.java b/htroot/Steering.java
index e28a70648..ff55159a4 100644
--- a/htroot/Steering.java
+++ b/htroot/Steering.java
@@ -33,12 +33,11 @@ import de.anomic.http.httpHeader;
import de.anomic.plasma.plasmaSwitchboard;
import de.anomic.server.serverObjects;
import de.anomic.server.serverSwitch;
-import de.anomic.yacy.yacyTray;
import de.anomic.yacy.yacyVersion;
public class Steering {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> ss) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> ss) {
if (post == null || ss == null) { return new serverObjects(); }
final plasmaSwitchboard sb = (plasmaSwitchboard) ss;
@@ -67,9 +66,9 @@ public class Steering {
}
if (post.containsKey("update")) {
- boolean devenvironment = yacyVersion.combined2prettyVersion(sb.getConfig("version","0.1")).startsWith("dev");
- String releaseFileName = post.get("releaseinstall", "");
- File releaseFile = new File(sb.getRootPath(), "DATA/RELEASE/".replace("/", File.separator) + releaseFileName);
+ final boolean devenvironment = yacyVersion.combined2prettyVersion(sb.getConfig("version","0.1")).startsWith("dev");
+ final String releaseFileName = post.get("releaseinstall", "");
+ final File releaseFile = new File(sb.getRootPath(), "DATA/RELEASE/".replace("/", File.separator) + releaseFileName);
if ((!devenvironment) && (releaseFile.length() > 0) && (releaseFile.exists())) {
yacyVersion.deployRelease(releaseFile);
}
diff --git a/htroot/Supporter.java b/htroot/Supporter.java
index 486dcd030..a9b659d58 100644
--- a/htroot/Supporter.java
+++ b/htroot/Supporter.java
@@ -50,19 +50,19 @@ import de.anomic.yacy.yacyURL;
public class Supporter {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
final plasmaSwitchboard sb = (plasmaSwitchboard) env;
final serverObjects prop = new serverObjects();
- boolean authenticated = sb.adminAuthenticated(header) >= 2;
- int display = ((post == null) || (!authenticated)) ? 0 : post.getInt("display", 0);
+ final boolean authenticated = sb.adminAuthenticated(header) >= 2;
+ final int display = ((post == null) || (!authenticated)) ? 0 : post.getInt("display", 0);
prop.put("display", display);
- boolean showScore = ((post != null) && (post.containsKey("score")));
+ final boolean showScore = ((post != null) && (post.containsKey("score")));
// access control
- boolean publicPage = sb.getConfigBool("publicSurftips", true);
- boolean authorizedAccess = sb.verifyAuthentication(header, false);
+ final boolean publicPage = sb.getConfigBool("publicSurftips", true);
+ final boolean authorizedAccess = sb.verifyAuthentication(header, false);
if ((publicPage) || (authorizedAccess)) {
@@ -74,7 +74,7 @@ public class Supporter {
return prop;
}
// make new news message with voting
- HashMap<String, String> map = new HashMap<String, String>();
+ final HashMap<String, String> map = new HashMap<String, String>();
map.put("urlhash", hash);
map.put("vote", "negative");
map.put("refid", post.get("refid", ""));
@@ -86,7 +86,7 @@ public class Supporter {
return prop;
}
// make new news message with voting
- HashMap<String, String> map = new HashMap<String, String>();
+ final HashMap<String, String> map = new HashMap<String, String>();
map.put("urlhash", hash);
map.put("url", crypt.simpleDecode(post.get("url", ""), null));
map.put("title", crypt.simpleDecode(post.get("title", ""), null));
@@ -98,20 +98,20 @@ public class Supporter {
}
// create Supporter
- HashMap<String, Integer> negativeHashes = new HashMap<String, Integer>(); // a mapping from an url hash to Integer (count of votes)
- HashMap<String, Integer> positiveHashes = new HashMap<String, Integer>(); // a mapping from an url hash to Integer (count of votes)
+ final HashMap<String, Integer> negativeHashes = new HashMap<String, Integer>(); // a mapping from an url hash to Integer (count of votes)
+ final HashMap<String, Integer> positiveHashes = new HashMap<String, Integer>(); // a mapping from an url hash to Integer (count of votes)
accumulateVotes(sb, negativeHashes, positiveHashes, yacyNewsPool.INCOMING_DB);
//accumulateVotes(negativeHashes, positiveHashes, yacyNewsPool.OUTGOING_DB);
//accumulateVotes(negativeHashes, positiveHashes, yacyNewsPool.PUBLISHED_DB);
- kelondroMScoreCluster<String> ranking = new kelondroMScoreCluster<String>(); // score cluster for url hashes
- kelondroRow rowdef = new kelondroRow("String url-255, String title-120, String description-120, String refid-" + (serverDate.PATTERN_SHORT_SECOND.length() + 12), kelondroNaturalOrder.naturalOrder, 0);
- HashMap<String, Entry> Supporter = new HashMap<String, Entry>(); // a mapping from an url hash to a kelondroRow.Entry with display properties
+ final kelondroMScoreCluster<String> ranking = new kelondroMScoreCluster<String>(); // score cluster for url hashes
+ final kelondroRow rowdef = new kelondroRow("String url-255, String title-120, String description-120, String refid-" + (serverDate.PATTERN_SHORT_SECOND.length() + 12), kelondroNaturalOrder.naturalOrder, 0);
+ final HashMap<String, Entry> Supporter = new HashMap<String, Entry>(); // a mapping from an url hash to a kelondroRow.Entry with display properties
accumulateSupporter(sb, Supporter, ranking, rowdef, negativeHashes, positiveHashes, yacyNewsPool.INCOMING_DB);
//accumulateSupporter(Supporter, ranking, rowdef, negativeHashes, positiveHashes, yacyNewsPool.OUTGOING_DB);
//accumulateSupporter(Supporter, ranking, rowdef, negativeHashes, positiveHashes, yacyNewsPool.PUBLISHED_DB);
// read out surftipp array and create property entries
- Iterator<String> k = ranking.scores(false);
+ final Iterator<String> k = ranking.scores(false);
int i = 0;
kelondroRow.Entry row;
String url, urlhash, refid, title, description;
@@ -126,7 +126,7 @@ public class Supporter {
url = row.getColString(0, null);
try {
if (plasmaSwitchboard.urlBlacklist.isListed(indexReferenceBlacklist.BLACKLIST_SURFTIPS ,new yacyURL(url, urlhash))) continue;
- } catch(MalformedURLException e) {continue;}
+ } catch(final MalformedURLException e) {continue;}
title = row.getColString(1,"UTF-8");
description = row.getColString(2,"UTF-8");
if ((url == null) || (title == null) || (description == null)) continue;
@@ -163,30 +163,30 @@ public class Supporter {
return prop;
}
- private static int timeFactor(Date created) {
+ private static int timeFactor(final Date created) {
return (int) Math.max(0, 10 - ((System.currentTimeMillis() - created.getTime()) / 24 / 60 / 60 / 1000));
}
- private static void accumulateVotes(plasmaSwitchboard sb, HashMap<String, Integer> negativeHashes, HashMap<String, Integer> positiveHashes, int dbtype) {
- int maxCount = Math.min(1000, sb.webIndex.newsPool.size(dbtype));
+ private static void accumulateVotes(final plasmaSwitchboard sb, final HashMap<String, Integer> negativeHashes, final HashMap<String, Integer> positiveHashes, final int dbtype) {
+ final int maxCount = Math.min(1000, sb.webIndex.newsPool.size(dbtype));
yacyNewsRecord record;
- Iterator<yacyNewsRecord> recordIterator = sb.webIndex.newsPool.recordIterator(dbtype, true);
+ final Iterator<yacyNewsRecord> recordIterator = sb.webIndex.newsPool.recordIterator(dbtype, true);
int j = 0;
while ((recordIterator.hasNext()) && (j++ < maxCount)) {
record = recordIterator.next();
if (record == null) continue;
if (record.category().equals(yacyNewsPool.CATEGORY_SURFTIPP_VOTE_ADD)) {
- String urlhash = record.attribute("urlhash", "");
- String vote = record.attribute("vote", "");
- int factor = ((dbtype == yacyNewsPool.OUTGOING_DB) || (dbtype == yacyNewsPool.PUBLISHED_DB)) ? 2 : 1;
+ final String urlhash = record.attribute("urlhash", "");
+ final String vote = record.attribute("vote", "");
+ final int factor = ((dbtype == yacyNewsPool.OUTGOING_DB) || (dbtype == yacyNewsPool.PUBLISHED_DB)) ? 2 : 1;
if (vote.equals("negative")) {
- Integer i = negativeHashes.get(urlhash);
+ final Integer i = negativeHashes.get(urlhash);
if (i == null) negativeHashes.put(urlhash, new Integer(factor));
else negativeHashes.put(urlhash, new Integer(i.intValue() + factor));
}
if (vote.equals("positive")) {
- Integer i = positiveHashes.get(urlhash);
+ final Integer i = positiveHashes.get(urlhash);
if (i == null) positiveHashes.put(urlhash, new Integer(factor));
else positiveHashes.put(urlhash, new Integer(i.intValue() + factor));
}
@@ -195,12 +195,12 @@ public class Supporter {
}
private static void accumulateSupporter(
- plasmaSwitchboard sb,
- HashMap<String, Entry> Supporter, kelondroMScoreCluster<String> ranking, kelondroRow rowdef,
- HashMap<String, Integer> negativeHashes, HashMap<String, Integer> positiveHashes, int dbtype) {
- int maxCount = Math.min(1000, sb.webIndex.newsPool.size(dbtype));
+ final plasmaSwitchboard sb,
+ final HashMap<String, Entry> Supporter, final kelondroMScoreCluster<String> ranking, final kelondroRow rowdef,
+ final HashMap<String, Integer> negativeHashes, final HashMap<String, Integer> positiveHashes, final int dbtype) {
+ final int maxCount = Math.min(1000, sb.webIndex.newsPool.size(dbtype));
yacyNewsRecord record;
- Iterator<yacyNewsRecord> recordIterator = sb.webIndex.newsPool.recordIterator(dbtype, true);
+ final Iterator<yacyNewsRecord> recordIterator = sb.webIndex.newsPool.recordIterator(dbtype, true);
int j = 0;
String url = "", urlhash;
kelondroRow.Entry entry;
@@ -223,7 +223,7 @@ public class Supporter {
record.id().getBytes()
});
score = 1 + timeFactor(record.created());
- } catch (IOException e) {}
+ } catch (final IOException e) {}
if ((record.category().equals(yacyNewsPool.CATEGORY_PROFILE_BROADCAST)) &&
((seed = sb.webIndex.seedDB.getConnected(record.originator())) != null)) try {
@@ -236,19 +236,19 @@ public class Supporter {
record.id().getBytes()
});
score = 1 + timeFactor(record.created());
- } catch (IOException e) {}
+ } catch (final IOException e) {}
// add/subtract votes and write record
if (entry != null) {
try {
urlhash = (new yacyURL(url, null)).hash();
- } catch (MalformedURLException e) {
+ } catch (final MalformedURLException e) {
urlhash = null;
}
if (urlhash == null)
try {
urlhash = (new yacyURL("http://" + url, null)).hash();
- } catch (MalformedURLException e) {
+ } catch (final MalformedURLException e) {
urlhash = null;
}
if (urlhash==null) {
diff --git a/htroot/Surftips.java b/htroot/Surftips.java
index 310323fd5..3edd53b96 100644
--- a/htroot/Surftips.java
+++ b/htroot/Surftips.java
@@ -50,19 +50,19 @@ import de.anomic.yacy.yacyURL;
public class Surftips {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
final plasmaSwitchboard sb = (plasmaSwitchboard) env;
final serverObjects prop = new serverObjects();
- boolean authenticated = sb.adminAuthenticated(header) >= 2;
- int display = ((post == null) || (!authenticated)) ? 0 : post.getInt("display", 0);
+ final boolean authenticated = sb.adminAuthenticated(header) >= 2;
+ final int display = ((post == null) || (!authenticated)) ? 0 : post.getInt("display", 0);
prop.put("display", display);
- boolean showScore = ((post != null) && (post.containsKey("score")));
+ final boolean showScore = ((post != null) && (post.containsKey("score")));
// access control
boolean publicPage = sb.getConfigBool("publicSurftips", true);
- boolean authorizedAccess = sb.verifyAuthentication(header, false);
+ final boolean authorizedAccess = sb.verifyAuthentication(header, false);
if ((post != null) && (post.containsKey("publicPage"))) {
if (!authorizedAccess) {
prop.put("AUTHENTICATE", "admin log-in"); // force log-in
@@ -82,7 +82,7 @@ public class Surftips {
return prop;
}
// make new news message with voting
- HashMap<String, String> map = new HashMap<String, String>();
+ final HashMap<String, String> map = new HashMap<String, String>();
map.put("urlhash", hash);
map.put("vote", "negative");
map.put("refid", post.get("refid", ""));
@@ -94,7 +94,7 @@ public class Surftips {
return prop;
}
// make new news message with voting
- HashMap<String, String> map = new HashMap<String, String>();
+ final HashMap<String, String> map = new HashMap<String, String>();
map.put("urlhash", hash);
map.put("url", crypt.simpleDecode(post.get("url", ""), null));
map.put("title", crypt.simpleDecode(post.get("title", ""), null));
@@ -106,20 +106,20 @@ public class Surftips {
}
// create surftips
- HashMap<String, Integer> negativeHashes = new HashMap<String, Integer>(); // a mapping from an url hash to Integer (count of votes)
- HashMap<String, Integer> positiveHashes = new HashMap<String, Integer>(); // a mapping from an url hash to Integer (count of votes)
+ final HashMap<String, Integer> negativeHashes = new HashMap<String, Integer>(); // a mapping from an url hash to Integer (count of votes)
+ final HashMap<String, Integer> positiveHashes = new HashMap<String, Integer>(); // a mapping from an url hash to Integer (count of votes)
accumulateVotes(sb , negativeHashes, positiveHashes, yacyNewsPool.INCOMING_DB);
//accumulateVotes(negativeHashes, positiveHashes, yacyNewsPool.OUTGOING_DB);
//accumulateVotes(negativeHashes, positiveHashes, yacyNewsPool.PUBLISHED_DB);
- kelondroMScoreCluster<String> ranking = new kelondroMScoreCluster<String>(); // score cluster for url hashes
- kelondroRow rowdef = new kelondroRow("String url-255, String title-120, String description-120, String refid-" + (serverDate.PATTERN_SHORT_SECOND.length() + 12), kelondroNaturalOrder.naturalOrder, 0);
- HashMap<String, Entry> surftips = new HashMap<String, Entry>(); // a mapping from an url hash to a kelondroRow.Entry with display properties
+ final kelondroMScoreCluster<String> ranking = new kelondroMScoreCluster<String>(); // score cluster for url hashes
+ final kelondroRow rowdef = new kelondroRow("String url-255, String title-120, String description-120, String refid-" + (serverDate.PATTERN_SHORT_SECOND.length() + 12), kelondroNaturalOrder.naturalOrder, 0);
+ final HashMap<String, Entry> surftips = new HashMap<String, Entry>(); // a mapping from an url hash to a kelondroRow.Entry with display properties
accumulateSurftips(sb, surftips, ranking, rowdef, negativeHashes, positiveHashes, yacyNewsPool.INCOMING_DB);
//accumulateSurftips(surftips, ranking, rowdef, negativeHashes, positiveHashes, yacyNewsPool.OUTGOING_DB);
//accumulateSurftips(surftips, ranking, rowdef, negativeHashes, positiveHashes, yacyNewsPool.PUBLISHED_DB);
// read out surftipp array and create property entries
- Iterator<String> k = ranking.scores(false);
+ final Iterator<String> k = ranking.scores(false);
int i = 0;
kelondroRow.Entry row;
String url, urlhash, refid, title, description;
@@ -135,7 +135,7 @@ public class Surftips {
try{
if(plasmaSwitchboard.urlBlacklist.isListed(indexReferenceBlacklist.BLACKLIST_SURFTIPS ,new yacyURL(url, null)))
continue;
- }catch(MalformedURLException e){continue;};
+ }catch(final MalformedURLException e){continue;};
title = row.getColString(1,"UTF-8");
description = row.getColString(2,"UTF-8");
if ((url == null) || (title == null) || (description == null)) continue;
@@ -172,30 +172,30 @@ public class Surftips {
return prop;
}
- private static int timeFactor(Date created) {
+ private static int timeFactor(final Date created) {
return (int) Math.max(0, 10 - ((System.currentTimeMillis() - created.getTime()) / 24 / 60 / 60 / 1000));
}
- private static void accumulateVotes(plasmaSwitchboard sb, HashMap<String, Integer> negativeHashes, HashMap<String, Integer> positiveHashes, int dbtype) {
- int maxCount = Math.min(1000, sb.webIndex.newsPool.size(dbtype));
+ private static void accumulateVotes(final plasmaSwitchboard sb, final HashMap<String, Integer> negativeHashes, final HashMap<String, Integer> positiveHashes, final int dbtype) {
+ final int maxCount = Math.min(1000, sb.webIndex.newsPool.size(dbtype));
yacyNewsRecord record;
- Iterator<yacyNewsRecord> recordIterator = sb.webIndex.newsPool.recordIterator(dbtype, true);
+ final Iterator<yacyNewsRecord> recordIterator = sb.webIndex.newsPool.recordIterator(dbtype, true);
int j = 0;
while ((recordIterator.hasNext()) && (j++ < maxCount)) {
record = recordIterator.next();
if (record == null) continue;
if (record.category().equals(yacyNewsPool.CATEGORY_SURFTIPP_VOTE_ADD)) {
- String urlhash = record.attribute("urlhash", "");
- String vote = record.attribute("vote", "");
- int factor = ((dbtype == yacyNewsPool.OUTGOING_DB) || (dbtype == yacyNewsPool.PUBLISHED_DB)) ? 2 : 1;
+ final String urlhash = record.attribute("urlhash", "");
+ final String vote = record.attribute("vote", "");
+ final int factor = ((dbtype == yacyNewsPool.OUTGOING_DB) || (dbtype == yacyNewsPool.PUBLISHED_DB)) ? 2 : 1;
if (vote.equals("negative")) {
- Integer i = negativeHashes.get(urlhash);
+ final Integer i = negativeHashes.get(urlhash);
if (i == null) negativeHashes.put(urlhash, new Integer(factor));
else negativeHashes.put(urlhash, new Integer(i.intValue() + factor));
}
if (vote.equals("positive")) {
- Integer i = positiveHashes.get(urlhash);
+ final Integer i = positiveHashes.get(urlhash);
if (i == null) positiveHashes.put(urlhash, new Integer(factor));
else positiveHashes.put(urlhash, new Integer(i.intValue() + factor));
}
@@ -204,12 +204,12 @@ public class Surftips {
}
private static void accumulateSurftips(
- plasmaSwitchboard sb,
- HashMap<String, Entry> surftips, kelondroMScoreCluster<String> ranking, kelondroRow rowdef,
- HashMap<String, Integer> negativeHashes, HashMap<String, Integer> positiveHashes, int dbtype) {
- int maxCount = Math.min(1000, sb.webIndex.newsPool.size(dbtype));
+ final plasmaSwitchboard sb,
+ final HashMap<String, Entry> surftips, final kelondroMScoreCluster<String> ranking, final kelondroRow rowdef,
+ final HashMap<String, Integer> negativeHashes, final HashMap<String, Integer> positiveHashes, final int dbtype) {
+ final int maxCount = Math.min(1000, sb.webIndex.newsPool.size(dbtype));
yacyNewsRecord record;
- Iterator<yacyNewsRecord> recordIterator = sb.webIndex.newsPool.recordIterator(dbtype, true);
+ final Iterator<yacyNewsRecord> recordIterator = sb.webIndex.newsPool.recordIterator(dbtype, true);
int j = 0;
String url = "", urlhash;
kelondroRow.Entry entry;
@@ -221,7 +221,7 @@ public class Surftips {
entry = null;
if (record.category().equals(yacyNewsPool.CATEGORY_CRAWL_START)) try {
- String intention = record.attribute("intention", "");
+ final String intention = record.attribute("intention", "");
url = record.attribute("startURL", "");
if (url.length() < 12) continue;
entry = rowdef.newEntry(new byte[][]{
@@ -231,7 +231,7 @@ public class Surftips {
record.id().getBytes()
});
score = 2 + Math.min(10, intention.length() / 4) + timeFactor(record.created());
- } catch (IOException e) {}
+ } catch (final IOException e) {}
if (record.category().equals(yacyNewsPool.CATEGORY_BOOKMARK_ADD)) try {
url = record.attribute("url", "");
@@ -243,7 +243,7 @@ public class Surftips {
record.id().getBytes()
});
score = 8 + timeFactor(record.created());
- } catch (IOException e) {}
+ } catch (final IOException e) {}
if (record.category().equals(yacyNewsPool.CATEGORY_SURFTIPP_ADD)) try {
url = record.attribute("url", "");
@@ -255,7 +255,7 @@ public class Surftips {
record.id().getBytes()
});
score = 5 + timeFactor(record.created());
- } catch (IOException e) {}
+ } catch (final IOException e) {}
if (record.category().equals(yacyNewsPool.CATEGORY_SURFTIPP_VOTE_ADD)) try {
if (!(record.attribute("vote", "negative").equals("positive"))) continue;
@@ -268,7 +268,7 @@ public class Surftips {
record.attribute("refid", "").getBytes()
});
score = 5 + timeFactor(record.created());
- } catch (IOException e) {}
+ } catch (final IOException e) {}
if (record.category().equals(yacyNewsPool.CATEGORY_WIKI_UPDATE)) try {
yacySeed seed = sb.webIndex.seedDB.getConnected(record.originator());
@@ -283,7 +283,7 @@ public class Surftips {
});
score = 4 + timeFactor(record.created());
}
- } catch (IOException e) {}
+ } catch (final IOException e) {}
if (record.category().equals(yacyNewsPool.CATEGORY_BLOG_ADD)) try {
yacySeed seed = sb.webIndex.seedDB.getConnected(record.originator());
@@ -298,19 +298,19 @@ public class Surftips {
});
score = 4 + timeFactor(record.created());
}
- } catch (IOException e) {}
+ } catch (final IOException e) {}
// add/subtract votes and write record
if (entry != null) {
try {
urlhash = (new yacyURL(url, null)).hash();
- } catch (MalformedURLException e) {
+ } catch (final MalformedURLException e) {
urlhash = null;
}
if (urlhash == null)
try {
urlhash = (new yacyURL("http://"+url, null)).hash();
- } catch (MalformedURLException e) {
+ } catch (final MalformedURLException e) {
urlhash = null;
}
if (urlhash == null) {
diff --git a/htroot/Threaddump_p.java b/htroot/Threaddump_p.java
index 08365988f..80dd1e8e4 100644
--- a/htroot/Threaddump_p.java
+++ b/htroot/Threaddump_p.java
@@ -48,21 +48,21 @@ public class Threaddump_p {
private static final serverObjects prop = new serverObjects();
private static plasmaSwitchboard sb = null;
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
prop.clear();
sb = (plasmaSwitchboard) env;
- StringBuffer buffer = new StringBuffer(1000);
+ final StringBuffer buffer = new StringBuffer(1000);
if (post != null && post.containsKey("createThreaddump")) {
- boolean plain = post.get("plain", "false").equals("true");
- int sleep = post.getInt("sleep", 0); // a sleep before creation of a thread dump can be used for profiling
- if (sleep > 0) try {Thread.sleep(sleep);} catch (InterruptedException e) {}
+ final boolean plain = post.get("plain", "false").equals("true");
+ final int sleep = post.getInt("sleep", 0); // a sleep before creation of a thread dump can be used for profiling
+ if (sleep > 0) try {Thread.sleep(sleep);} catch (final InterruptedException e) {}
prop.put("dump", "1");
// Thread dump
- Map<Thread,StackTraceElement[]> stackTraces = Thread.getAllStackTraces();
- Date dt = new Date();
- String versionstring = yacyVersion.combined2prettyVersion(sb.getConfig("version","0.1"));
+ final Map<Thread,StackTraceElement[]> stackTraces = Thread.getAllStackTraces();
+ final Date dt = new Date();
+ final String versionstring = yacyVersion.combined2prettyVersion(sb.getConfig("version","0.1"));
bufferappend(buffer, plain, "************* Start Thread Dump " + dt + " *******************");
bufferappend(buffer, plain, "");
@@ -89,14 +89,14 @@ public class Threaddump_p {
return prop; // return from serverObjects respond()
}
- private static void appendStackTraces(File rootPath, StringBuffer buffer, Map<Thread,StackTraceElement[]> stackTraces, boolean plain, Thread.State stateIn) {
+ private static void appendStackTraces(final File rootPath, final StringBuffer buffer, final Map<Thread,StackTraceElement[]> stackTraces, final boolean plain, final Thread.State stateIn) {
bufferappend(buffer, plain, "THREADS WITH STATES: " + stateIn.toString());
bufferappend(buffer, plain, "");
- File classPath = new File(rootPath, "source");
+ final File classPath = new File(rootPath, "source");
- for (Thread thread: stackTraces.keySet()) {
- StackTraceElement[] stackTraceElements = stackTraces.get(thread);
+ for (final Thread thread: stackTraces.keySet()) {
+ final StackTraceElement[] stackTraceElements = stackTraces.get(thread);
StackTraceElement ste;
String line;
String tracename = "";
@@ -130,25 +130,25 @@ public class Threaddump_p {
bufferappend(buffer, plain, "");
}
- private static File getClassFile(File sourcePath, String classname) {
- String classPath = classname.replace('.', '/') + ".java";
- File file = new File(sourcePath, classPath);
+ private static File getClassFile(final File sourcePath, final String classname) {
+ final String classPath = classname.replace('.', '/') + ".java";
+ final File file = new File(sourcePath, classPath);
return file;
}
- private static String getLine(File file, int line) {
+ private static String getLine(final File file, final int line) {
// find class
if (!file.exists()) return "";
try {
- String lineString = nxTools.line(serverFileUtils.read(file), line);
+ final String lineString = nxTools.line(serverFileUtils.read(file), line);
if (lineString == null) return "@ERROR";
return lineString;
- } catch (IOException e) {
+ } catch (final IOException e) {
return "@EXCEPTION: " + e.getMessage();
}
}
- private static void bufferappend(StringBuffer buffer, boolean plain, String a) {
+ private static void bufferappend(final StringBuffer buffer, final boolean plain, final String a) {
buffer.append(a);
if (plain) {
buffer.append("\n");
diff --git a/htroot/User.java b/htroot/User.java
index e0af2f681..b53f065e8 100644
--- a/htroot/User.java
+++ b/htroot/User.java
@@ -41,9 +41,9 @@ import de.anomic.server.servletProperties;
public class User{
- public static servletProperties respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
- servletProperties prop = new servletProperties();
- plasmaSwitchboard sb = plasmaSwitchboard.getSwitchboard();
+ public static servletProperties respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
+ final servletProperties prop = new servletProperties();
+ final plasmaSwitchboard sb = plasmaSwitchboard.getSwitchboard();
userDB.Entry entry=null;
//default values
@@ -73,8 +73,8 @@ public class User{
prop.put("logged-in_username", entry.getUserName());
if(entry.getTimeLimit() > 0){
prop.put("logged-in_limit", "1");
- long limit=entry.getTimeLimit();
- long used=entry.getTimeUsed();
+ final long limit=entry.getTimeLimit();
+ final long used=entry.getTimeUsed();
prop.put("logged-in_limit_timelimit", limit);
prop.put("logged-in_limit_timeused", used);
int percent=0;
@@ -90,11 +90,11 @@ public class User{
//TODO: this does not work for a static admin, yet.
}else if(post != null && post.containsKey("username") && post.containsKey("password")){
//entry=sb.userDB.passwordAuth((String)post.get("username"), (String)post.get("password"), (String)header.get(httpHeader.CONNECTION_PROP_CLIENTIP, "xxxxxx"));
- String username=post.get("username");
- String password=post.get("password");
+ final String username=post.get("username");
+ final String password=post.get("password");
entry=sb.userDB.passwordAuth(username, password);
- boolean staticAdmin = sb.getConfig(httpd.ADMIN_ACCOUNT_B64MD5, "").equals(
+ final boolean staticAdmin = sb.getConfig(httpd.ADMIN_ACCOUNT_B64MD5, "").equals(
serverCodings.encodeMD5Hex(
kelondroBase64Order.standardCoder.encodeString(username + ":" + password)
)
@@ -107,7 +107,7 @@ public class User{
cookie=sb.userDB.getAdminCookie();
if(entry != null || staticAdmin){
- httpHeader outgoingHeader=new httpHeader();
+ final httpHeader outgoingHeader=new httpHeader();
outgoingHeader.setCookie("login", cookie);
prop.setOutgoingHeader(outgoingHeader);
@@ -129,7 +129,7 @@ public class User{
try {
entry.setProperty(userDB.Entry.MD5ENCODED_USERPWD_STRING, serverCodings.encodeMD5Hex(entry.getUserName()+":"+post.get("newpass", "")));
prop.put("status_password", "0"); //changes
- } catch (IOException e) {}
+ } catch (final IOException e) {}
}else{
prop.put("status_password", "3"); //empty
}
diff --git a/htroot/ViewFile.java b/htroot/ViewFile.java
index a5898c5be..90f9305b4 100644
--- a/htroot/ViewFile.java
+++ b/htroot/ViewFile.java
@@ -62,10 +62,10 @@ public class ViewFile {
private static final String HIGHLIGHT_CSS = "searchHighlight";
private static final int MAX_HIGHLIGHTS = 6;
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
- serverObjects prop = new serverObjects();
- plasmaSwitchboard sb = (plasmaSwitchboard)env;
+ final serverObjects prop = new serverObjects();
+ final plasmaSwitchboard sb = (plasmaSwitchboard)env;
if (post != null && post.containsKey("words"))
prop.putHTML("error_words", post.get("words"));
@@ -75,17 +75,17 @@ public class ViewFile {
return prop;
}
- String viewMode = post.get("viewMode","sentences");
+ final String viewMode = post.get("viewMode","sentences");
prop.put("error_vMode-" + viewMode, "1");
yacyURL url = null;
String descr = "";
- int wordCount = 0;
+ final int wordCount = 0;
int size = 0;
boolean pre = false;
// getting the url hash from which the content should be loaded
- String urlHash = post.get("urlHash","");
+ final String urlHash = post.get("urlHash","");
if (urlHash.length() > 0) {
// getting the urlEntry that belongs to the url hash
indexURLReference urlEntry = null;
@@ -97,7 +97,7 @@ public class ViewFile {
}
// gettin the url that belongs to the entry
- indexURLReference.Components comp = urlEntry.comp();
+ final indexURLReference.Components comp = urlEntry.comp();
if ((comp == null) || (comp.url() == null)) {
prop.put("error", "3");
prop.put("viewMode", VIEW_MODE_NO_TEXT);
@@ -112,7 +112,7 @@ public class ViewFile {
// alternatively, get the url simply from a url String
// this can be used as a simple tool to test the text parser
- String urlString = post.get("url", "");
+ final String urlString = post.get("url", "");
if (urlString.length() > 0) try {
// this call forces the peer to download web pages
// it is therefore protected by the admin password
@@ -125,7 +125,7 @@ public class ViewFile {
// define an url by post parameter
url = new yacyURL(urlString, null);
pre = post.get("pre", "false").equals("true");
- } catch (MalformedURLException e) {}
+ } catch (final MalformedURLException e) {}
if (url == null) {
@@ -148,7 +148,7 @@ public class ViewFile {
plasmaHTCache.Entry entry = null;
try {
entry = sb.crawlQueues.loadResourceFromWeb(url, 5000, false, true, false);
- } catch (Exception e) {
+ } catch (final Exception e) {
prop.put("error", "4");
prop.putHTML("error_errorText", e.getMessage());
prop.put("viewMode", VIEW_MODE_NO_TEXT);
@@ -175,20 +175,20 @@ public class ViewFile {
// try to load the metadata from cache
try {
resInfo = plasmaHTCache.loadResourceInfo(url);
- } catch (Exception e) {
+ } catch (final Exception e) {
/* ignore this */
}
// if the metadata was not cached try to load it from web
if (resInfo == null) {
- String protocol = url.getProtocol();
+ final String protocol = url.getProtocol();
if (!((protocol.equals("http") || protocol.equals("https")))) {
prop.put("error", "6");
prop.put("viewMode", VIEW_MODE_NO_TEXT);
return prop;
}
- httpHeader responseHeader = HttpClient.whead(url.toString());
+ final httpHeader responseHeader = HttpClient.whead(url.toString());
if (responseHeader == null) {
prop.put("error", "4");
prop.put("error_errorText", "Unable to load resource metadata.");
@@ -197,7 +197,7 @@ public class ViewFile {
}
try {
resInfo = plasmaHTCache.getResourceInfoFactory().buildResourceInfoObj(url, responseHeader);
- } catch (Exception e) {
+ } catch (final Exception e) {
prop.put("error", "4");
prop.putHTML("error_errorText", e.getMessage());
prop.put("viewMode", VIEW_MODE_NO_TEXT);
@@ -209,7 +209,7 @@ public class ViewFile {
resMime = resInfo.getMimeType();
}
- String[] wordArray = wordArray(post.get("words", null));
+ final String[] wordArray = wordArray(post.get("words", null));
if (viewMode.equals("plain")) {
@@ -217,7 +217,7 @@ public class ViewFile {
String content;
try {
content = new String(serverFileUtils.read(resource), "UTF-8");
- } catch (Exception e) {
+ } catch (final Exception e) {
prop.put("error", "4");
prop.putHTML("error_errorText", e.getMessage());
prop.put("viewMode", VIEW_MODE_NO_TEXT);
@@ -226,7 +226,7 @@ public class ViewFile {
if (resource != null)
try {
resource.close();
- } catch (Exception e) {
+ } catch (final Exception e) {
/* ignore this */
}
}
@@ -250,7 +250,7 @@ public class ViewFile {
prop.put("viewMode", VIEW_MODE_NO_TEXT);
return prop;
}
- } catch (ParserException e) {
+ } catch (final ParserException e) {
prop.put("error", "5");
prop.putHTML("error_errorText", e.getMessage());
prop.put("viewMode", VIEW_MODE_NO_TEXT);
@@ -259,7 +259,7 @@ public class ViewFile {
if (resource != null)
try {
resource.close();
- } catch (Exception e) {
+ } catch (final Exception e) {
/* ignore this */
}
}
@@ -267,7 +267,7 @@ public class ViewFile {
resMime = document.dc_format();
if (viewMode.equals("parsed")) {
- String content = new String(document.getTextBytes());
+ final String content = new String(document.getTextBytes());
// content = wikiCode.replaceHTML(content); // added by Marc Nause
prop.put("viewMode", VIEW_MODE_AS_PARSED_TEXT);
@@ -304,8 +304,8 @@ public class ViewFile {
i += putMediaInfo(prop, wordArray, i, document.getAudiolinks(), "audio", (i % 2 == 0));
dark = (i % 2 == 0);
- HashMap<String, htmlFilterImageEntry> ts = document.getImages();
- Iterator<htmlFilterImageEntry> tsi = ts.values().iterator();
+ final HashMap<String, htmlFilterImageEntry> ts = document.getImages();
+ final Iterator<htmlFilterImageEntry> tsi = ts.values().iterator();
htmlFilterImageEntry entry;
while (tsi.hasNext()) {
entry = tsi.next();
@@ -346,15 +346,15 @@ public class ViewFile {
words = URLDecoder.decode(words, "UTF-8");
w = words.substring(1, words.length() - 1).split(",");
if (w.length == 0) return null;
- } catch (UnsupportedEncodingException e) {}
+ } catch (final UnsupportedEncodingException e) {}
return w;
}
- private static final String markup(String[] wordArray, String message) {
+ private static final String markup(final String[] wordArray, String message) {
message = htmlTools.encodeUnicode2html(message, true);
if (wordArray != null)
for (int j = 0; j < wordArray.length; j++) {
- String currentWord = wordArray[j].trim();
+ final String currentWord = wordArray[j].trim();
// TODO: replace upper-/lowercase words as well
message = message.replaceAll(currentWord,
"<span class=\"" + HIGHLIGHT_CSS + ((j % MAX_HIGHLIGHTS) + 1) + "\">" +
@@ -364,8 +364,8 @@ public class ViewFile {
return message;
}
- private static int putMediaInfo(serverObjects prop, String[] wordArray, int c, Map<yacyURL, String> media, String name, boolean dark) {
- Iterator<Map.Entry<yacyURL, String>> mi = media.entrySet().iterator();
+ private static int putMediaInfo(final serverObjects prop, final String[] wordArray, int c, final Map<yacyURL, String> media, final String name, boolean dark) {
+ final Iterator<Map.Entry<yacyURL, String>> mi = media.entrySet().iterator();
Map.Entry<yacyURL, String> entry;
int i = 0;
while (mi.hasNext()) {
diff --git a/htroot/ViewImage.java b/htroot/ViewImage.java
index 1682b904e..d70c4d13a 100644
--- a/htroot/ViewImage.java
+++ b/htroot/ViewImage.java
@@ -43,22 +43,22 @@ public class ViewImage {
private static HashMap<String, Image> iconcache = new HashMap<String, Image>();
private static String defaulticon = "htroot/env/grafics/dfltfvcn.ico";
- public static Image respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static Image respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
- plasmaSwitchboard sb = (plasmaSwitchboard)env;
+ final plasmaSwitchboard sb = (plasmaSwitchboard)env;
// the url to the image can be either submitted with an url in clear text, or using a license key
// if the url is given as clear text, the user must be authorized as admin
// the license can be used also from non-authorized users
String urlString = post.get("url", "");
- String urlLicense = post.get("code", "");
- boolean auth = ((String) header.get(httpHeader.CONNECTION_PROP_CLIENTIP, "")).equals("localhost") || sb.verifyAuthentication(header, true); // handle access rights
+ final String urlLicense = post.get("code", "");
+ final boolean auth = ((String) header.get(httpHeader.CONNECTION_PROP_CLIENTIP, "")).equals("localhost") || sb.verifyAuthentication(header, true); // handle access rights
yacyURL url = null;
if ((urlString.length() > 0) && (auth)) try {
url = new yacyURL(urlString, null);
- } catch (MalformedURLException e1) {
+ } catch (final MalformedURLException e1) {
url = null;
}
@@ -74,48 +74,48 @@ public class ViewImage {
int height = post.getInt("height", 0);
int maxwidth = post.getInt("maxwidth", 0);
int maxheight = post.getInt("maxheight", 0);
- int timeout = post.getInt("timeout", 5000);
+ final int timeout = post.getInt("timeout", 5000);
// getting the image as stream
Image scaled = iconcache.get(urlString);
if (scaled == null) {
- Object[] resource = plasmaSnippetCache.getResource(url, true, timeout, false, true);
+ final Object[] resource = plasmaSnippetCache.getResource(url, true, timeout, false, true);
byte[] imgb = null;
if (resource == null) {
if (urlString.endsWith(".ico")) {
// load default favicon dfltfvcn.ico
try {
imgb = serverFileUtils.read(new File(sb.getRootPath(), defaulticon));
- } catch (IOException e) {
+ } catch (final IOException e) {
return null;
}
} else {
return null;
}
} else {
- InputStream imgStream = (InputStream) resource[0];
+ final InputStream imgStream = (InputStream) resource[0];
if (imgStream == null) return null;
// read image data
try {
imgb = serverFileUtils.read(imgStream);
- } catch (IOException e) {
+ } catch (final IOException e) {
return null;
} finally {
try {
imgStream.close();
- } catch (Exception e) {/* ignore this */}
+ } catch (final Exception e) {/* ignore this */}
}
}
// read image
- Image image = ymageImageParser.parse(urlString.toString(), imgb);
+ final Image image = ymageImageParser.parse(urlString.toString(), imgb);
if ((auth) && ((width == 0) || (height == 0)) && (maxwidth == 0) && (maxheight == 0)) return image;
// find original size
- int h = image.getHeight(null);
- int w = image.getWidth(null);
+ final int h = image.getHeight(null);
+ final int w = image.getWidth(null);
// in case of not-authorized access shrink the image to prevent
// copyright problems, so that images are not larger than thumbnails
@@ -133,8 +133,8 @@ public class ViewImage {
// calculate width & height from maxwidth & maxheight
if ((maxwidth < w) || (maxheight < h)) {
// scale image
- double hs = (w <= maxwidth) ? 1.0 : ((double) maxwidth) / ((double) w);
- double vs = (h <= maxheight) ? 1.0 : ((double) maxheight) / ((double) h);
+ final double hs = (w <= maxwidth) ? 1.0 : ((double) maxwidth) / ((double) w);
+ final double vs = (h <= maxheight) ? 1.0 : ((double) maxheight) / ((double) h);
double scale = Math.min(hs, vs);
if (!auth) scale = Math.min(scale, 0.6); // this is for copyright purpose
if (scale < 1.0) {
@@ -147,9 +147,9 @@ public class ViewImage {
// compute scaled image
scaled = ((w == width) && (h == height)) ? image : image.getScaledInstance(width, height, Image.SCALE_AREA_AVERAGING);
- MediaTracker mediaTracker = new MediaTracker(new Container());
+ final MediaTracker mediaTracker = new MediaTracker(new Container());
mediaTracker.addImage(scaled, 0);
- try {mediaTracker.waitForID(0);} catch (InterruptedException e) {}
+ try {mediaTracker.waitForID(0);} catch (final InterruptedException e) {}
} else {
// do not scale
width = w;
diff --git a/htroot/ViewLog_p.java b/htroot/ViewLog_p.java
index dfb12b6a6..c258af025 100644
--- a/htroot/ViewLog_p.java
+++ b/htroot/ViewLog_p.java
@@ -41,8 +41,8 @@ import de.anomic.server.logging.LogalizerHandler;
public class ViewLog_p {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
- serverObjects prop = new serverObjects();
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
+ final serverObjects prop = new serverObjects();
String[] log = new String[0];
boolean reversed = false;
int maxlines = 400, lines = 200;
@@ -61,8 +61,8 @@ public class ViewLog_p {
}
- Logger logger = Logger.getLogger("");
- Handler[] handlers = logger.getHandlers();
+ final Logger logger = Logger.getLogger("");
+ final Handler[] handlers = logger.getHandlers();
boolean displaySubmenu = false;
for (int i=0; i<handlers.length; i++) {
if (handlers[i] instanceof GuiHandler) {
@@ -83,9 +83,9 @@ public class ViewLog_p {
// trying to compile the regular expression filter expression
Matcher filterMatcher = null;
try {
- Pattern filterPattern = Pattern.compile(filter,Pattern.MULTILINE);
+ final Pattern filterPattern = Pattern.compile(filter,Pattern.MULTILINE);
filterMatcher = filterPattern.matcher("");
- } catch (PatternSyntaxException e) {
+ } catch (final PatternSyntaxException e) {
e.printStackTrace();
}
@@ -93,7 +93,7 @@ public class ViewLog_p {
int level = 0;
int lc = 0;
for (int i=0; i < log.length; i++) {
- String nextLogLine = log[i].trim();
+ final String nextLogLine = log[i].trim();
if (filterMatcher != null) {
filterMatcher.reset(nextLogLine);
diff --git a/htroot/ViewProfile.java b/htroot/ViewProfile.java
index 18605cca2..aac0c0f34 100644
--- a/htroot/ViewProfile.java
+++ b/htroot/ViewProfile.java
@@ -50,13 +50,13 @@ import de.anomic.yacy.yacySeed;
public class ViewProfile {
@SuppressWarnings("unchecked")
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) {
- serverObjects prop = new serverObjects();
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
- boolean authenticated = sb.adminAuthenticated(header) >= 2;
- int display = ((post == null) || (!authenticated)) ? 0 : post.getInt("display", 0);
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch env) {
+ final serverObjects prop = new serverObjects();
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ final boolean authenticated = sb.adminAuthenticated(header) >= 2;
+ final int display = ((post == null) || (!authenticated)) ? 0 : post.getInt("display", 0);
prop.put("display", display);
- String hash = (post == null) ? null : (String) post.get("hash");
+ final String hash = (post == null) ? null : (String) post.get("hash");
if ((hash == null) || (sb.webIndex.seedDB == null)) {
// wrong access
@@ -70,13 +70,13 @@ public class ViewProfile {
String address = null;
if (hash.equals("localhash")) {
// read the profile from local peer
- Properties p = new Properties();
+ final Properties p = new Properties();
FileInputStream fileIn = null;
try {
fileIn = new FileInputStream(new File("DATA/SETTINGS/profile.txt"));
p.load(fileIn);
- } catch(IOException e) {} finally {
- if (fileIn != null) try { fileIn.close(); fileIn = null; } catch (Exception e) {}
+ } catch(final IOException e) {} finally {
+ if (fileIn != null) try { fileIn.close(); fileIn = null; } catch (final Exception e) {}
}
profile = new HashMap();
profile.putAll(p);
@@ -94,9 +94,9 @@ public class ViewProfile {
} else {
// process news if existent
try {
- yacyNewsRecord record = sb.webIndex.newsPool.getByOriginator(yacyNewsPool.INCOMING_DB, yacyNewsPool.CATEGORY_PROFILE_UPDATE, seed.hash);
+ final yacyNewsRecord record = sb.webIndex.newsPool.getByOriginator(yacyNewsPool.INCOMING_DB, yacyNewsPool.CATEGORY_PROFILE_UPDATE, seed.hash);
if (record != null) sb.webIndex.newsPool.moveOff(yacyNewsPool.INCOMING_DB, record.id());
- } catch (IOException e) {}
+ } catch (final IOException e) {}
// try to get the profile from remote peer
if (sb.clusterhashes != null) seed.setAlternativeAddress(sb.clusterhashes.get(seed.hash));
@@ -123,7 +123,7 @@ public class ViewProfile {
}
Map.Entry entry;
// all known keys which should be set as they are
- HashSet<String> knownKeys = new HashSet<String>();
+ final HashSet<String> knownKeys = new HashSet<String>();
knownKeys.add("name");
knownKeys.add("nickname");
// knownKeys.add("homepage");//+http
@@ -136,7 +136,7 @@ public class ViewProfile {
knownKeys.add("comment");
//empty values
- Iterator<String> it = knownKeys.iterator();
+ final Iterator<String> it = knownKeys.iterator();
while (it.hasNext()) {
prop.put("success_" + it.next(), "0");
}
@@ -145,7 +145,7 @@ public class ViewProfile {
int numUnknown = 0;
while (i.hasNext()) {
entry = (Map.Entry) i.next();
- String key = ((String) entry.getKey());
+ final String key = ((String) entry.getKey());
String value = new String();
// this prevents broken links ending in <br>
diff --git a/htroot/WatchCrawler_p.java b/htroot/WatchCrawler_p.java
index eadd4cab4..b1920484a 100644
--- a/htroot/WatchCrawler_p.java
+++ b/htroot/WatchCrawler_p.java
@@ -60,11 +60,11 @@ public class WatchCrawler_p {
// this servlet does NOT create the WatchCrawler page content!
// this servlet starts a web crawl. The interface for entering the web crawl parameters is in IndexCreate_p.html
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
// return variable that accumulates replacements
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
// inital values for AJAX Elements (without JavaScript)
- serverObjects prop = queues_p.respond(header, post, env);
+ final serverObjects prop = queues_p.respond(header, post, env);
prop.put("forwardToCrawlStart", "0");
prop.put("info", "0");
@@ -80,7 +80,7 @@ public class WatchCrawler_p {
if (post.containsKey("continue")) {
// continue queue
- String queue = post.get("continue", "");
+ final String queue = post.get("continue", "");
if (queue.equals("localcrawler")) {
sb.continueCrawlJob(plasmaSwitchboard.CRAWLJOB_LOCAL_CRAWL);
} else if (queue.equals("remotecrawler")) {
@@ -90,7 +90,7 @@ public class WatchCrawler_p {
if (post.containsKey("pause")) {
// pause queue
- String queue = post.get("pause", "");
+ final String queue = post.get("pause", "");
if (queue.equals("localcrawler")) {
sb.pauseCrawlJob(plasmaSwitchboard.CRAWLJOB_LOCAL_CRAWL);
} else if (queue.equals("remotecrawler")) {
@@ -104,8 +104,8 @@ public class WatchCrawler_p {
prop.put("info", "3");
} else {
// set new properties
- boolean fullDomain = post.get("range", "wide").equals("domain"); // special property in simple crawl start
- boolean subPath = post.get("range", "wide").equals("subpath"); // special property in simple crawl start
+ final boolean fullDomain = post.get("range", "wide").equals("domain"); // special property in simple crawl start
+ final boolean subPath = post.get("range", "wide").equals("subpath"); // special property in simple crawl start
String crawlingStart = post.get("crawlingURL","").trim(); // the crawljob start url
@@ -115,7 +115,7 @@ public class WatchCrawler_p {
// normalizing URL
yacyURL crawlingStartURL = null;
- try {crawlingStartURL = new yacyURL(crawlingStart, null);} catch (MalformedURLException e1) {}
+ try {crawlingStartURL = new yacyURL(crawlingStart, null);} catch (final MalformedURLException e1) {}
crawlingStart = (crawlingStartURL == null) ? null : crawlingStartURL.toNormalform(true, true);
// set the crawling filter
@@ -130,49 +130,49 @@ public class WatchCrawler_p {
}
env.setConfig("crawlingFilter", newcrawlingfilter);
- boolean crawlOrder = post.get("crawlOrder", "off").equals("on");
+ final boolean crawlOrder = post.get("crawlOrder", "off").equals("on");
env.setConfig("crawlOrder", (crawlOrder) ? "true" : "false");
int newcrawlingdepth = Integer.parseInt(post.get("crawlingDepth", "8"));
env.setConfig("crawlingDepth", Integer.toString(newcrawlingdepth));
if ((crawlOrder) && (newcrawlingdepth > 8)) newcrawlingdepth = 8;
- boolean crawlingIfOlderCheck = post.get("crawlingIfOlderCheck", "off").equals("on");
- int crawlingIfOlderNumber = Integer.parseInt(post.get("crawlingIfOlderNumber", "-1"));
- String crawlingIfOlderUnit = post.get("crawlingIfOlderUnit","year");
- int crawlingIfOlder = recrawlIfOlderC(crawlingIfOlderCheck, crawlingIfOlderNumber, crawlingIfOlderUnit);
+ final boolean crawlingIfOlderCheck = post.get("crawlingIfOlderCheck", "off").equals("on");
+ final int crawlingIfOlderNumber = Integer.parseInt(post.get("crawlingIfOlderNumber", "-1"));
+ final String crawlingIfOlderUnit = post.get("crawlingIfOlderUnit","year");
+ final int crawlingIfOlder = recrawlIfOlderC(crawlingIfOlderCheck, crawlingIfOlderNumber, crawlingIfOlderUnit);
env.setConfig("crawlingIfOlder", crawlingIfOlder);
- boolean crawlingDomFilterCheck = post.get("crawlingDomFilterCheck", "off").equals("on");
- int crawlingDomFilterDepth = (crawlingDomFilterCheck) ? Integer.parseInt(post.get("crawlingDomFilterDepth", "-1")) : -1;
+ final boolean crawlingDomFilterCheck = post.get("crawlingDomFilterCheck", "off").equals("on");
+ final int crawlingDomFilterDepth = (crawlingDomFilterCheck) ? Integer.parseInt(post.get("crawlingDomFilterDepth", "-1")) : -1;
env.setConfig("crawlingDomFilterDepth", Integer.toString(crawlingDomFilterDepth));
- boolean crawlingDomMaxCheck = post.get("crawlingDomMaxCheck", "off").equals("on");
- int crawlingDomMaxPages = (crawlingDomMaxCheck) ? Integer.parseInt(post.get("crawlingDomMaxPages", "-1")) : -1;
+ final boolean crawlingDomMaxCheck = post.get("crawlingDomMaxCheck", "off").equals("on");
+ final int crawlingDomMaxPages = (crawlingDomMaxCheck) ? Integer.parseInt(post.get("crawlingDomMaxPages", "-1")) : -1;
env.setConfig("crawlingDomMaxPages", Integer.toString(crawlingDomMaxPages));
- boolean crawlingQ = post.get("crawlingQ", "off").equals("on");
+ final boolean crawlingQ = post.get("crawlingQ", "off").equals("on");
env.setConfig("crawlingQ", (crawlingQ) ? "true" : "false");
- boolean indexText = post.get("indexText", "off").equals("on");
+ final boolean indexText = post.get("indexText", "off").equals("on");
env.setConfig("indexText", (indexText) ? "true" : "false");
- boolean indexMedia = post.get("indexMedia", "off").equals("on");
+ final boolean indexMedia = post.get("indexMedia", "off").equals("on");
env.setConfig("indexMedia", (indexMedia) ? "true" : "false");
- boolean storeHTCache = post.get("storeHTCache", "off").equals("on");
+ final boolean storeHTCache = post.get("storeHTCache", "off").equals("on");
env.setConfig("storeHTCache", (storeHTCache) ? "true" : "false");
- boolean xsstopw = post.get("xsstopw", "off").equals("on");
+ final boolean xsstopw = post.get("xsstopw", "off").equals("on");
env.setConfig("xsstopw", (xsstopw) ? "true" : "false");
- boolean xdstopw = post.get("xdstopw", "off").equals("on");
+ final boolean xdstopw = post.get("xdstopw", "off").equals("on");
env.setConfig("xdstopw", (xdstopw) ? "true" : "false");
- boolean xpstopw = post.get("xpstopw", "off").equals("on");
+ final boolean xpstopw = post.get("xpstopw", "off").equals("on");
env.setConfig("xpstopw", (xpstopw) ? "true" : "false");
- String crawlingMode = post.get("crawlingMode","url");
+ final String crawlingMode = post.get("crawlingMode","url");
if (crawlingMode.equals(CRAWLING_MODE_URL)) {
// check if pattern matches
@@ -188,22 +188,22 @@ public class WatchCrawler_p {
// stack request
// first delete old entry, if exists
- yacyURL url = new yacyURL(crawlingStart, null);
- String urlhash = url.hash();
+ final yacyURL url = new yacyURL(crawlingStart, null);
+ final String urlhash = url.hash();
sb.webIndex.removeURL(urlhash);
sb.crawlQueues.noticeURL.removeByURLHash(urlhash);
sb.crawlQueues.errorURL.remove(urlhash);
// stack url
sb.webIndex.profilesPassiveCrawls.removeEntry(crawlingStartURL.hash()); // if there is an old entry, delete it
- CrawlProfile.entry pe = sb.webIndex.profilesActiveCrawls.newEntry(
+ final CrawlProfile.entry pe = sb.webIndex.profilesActiveCrawls.newEntry(
crawlingStartURL.getHost(), crawlingStartURL, newcrawlingfilter, newcrawlingfilter,
newcrawlingdepth, newcrawlingdepth,
crawlingIfOlder, crawlingDomFilterDepth, crawlingDomMaxPages,
crawlingQ,
indexText, indexMedia,
storeHTCache, true, crawlOrder, xsstopw, xdstopw, xpstopw);
- String reasonString = sb.crawlStacker.stackCrawl(url, null, sb.webIndex.seedDB.mySeed().hash, "CRAWLING-ROOT", new Date(), 0, pe);
+ final String reasonString = sb.crawlStacker.stackCrawl(url, null, sb.webIndex.seedDB.mySeed().hash, "CRAWLING-ROOT", new Date(), 0, pe);
if (reasonString == null) {
// liftoff!
@@ -212,7 +212,7 @@ public class WatchCrawler_p {
// generate a YaCyNews if the global flag was set
if (crawlOrder) {
- Map<String, String> m = new HashMap<String, String>(pe.map()); // must be cloned
+ final Map<String, String> m = new HashMap<String, String>(pe.map()); // must be cloned
m.remove("specificDepth");
m.remove("indexText");
m.remove("indexMedia");
@@ -233,7 +233,7 @@ public class WatchCrawler_p {
prop.putHTML("info_crawlingURL", (post.get("crawlingURL")));
prop.putHTML("info_reasonString", reasonString);
- ZURL.Entry ee = sb.crawlQueues.errorURL.newEntry(
+ final ZURL.Entry ee = sb.crawlQueues.errorURL.newEntry(
new CrawlEntry(
sb.webIndex.seedDB.mySeed().hash,
crawlingStartURL,
@@ -252,11 +252,11 @@ public class WatchCrawler_p {
ee.store();
sb.crawlQueues.errorURL.push(ee);
}
- } catch (PatternSyntaxException e) {
+ } catch (final PatternSyntaxException e) {
prop.put("info", "4"); //crawlfilter does not match url
prop.putHTML("info_newcrawlingfilter", newcrawlingfilter);
prop.putHTML("info_error", e.getMessage());
- } catch (Exception e) {
+ } catch (final Exception e) {
// mist
prop.put("info", "6");//Error with url
prop.putHTML("info_crawlingStart", crawlingStart);
@@ -267,39 +267,39 @@ public class WatchCrawler_p {
} else if (crawlingMode.equals(CRAWLING_MODE_FILE)) {
if (post.containsKey("crawlingFile")) {
// getting the name of the uploaded file
- String fileName = post.get("crawlingFile");
+ final String fileName = post.get("crawlingFile");
try {
// check if the crawl filter works correctly
Pattern.compile(newcrawlingfilter);
// loading the file content
- File file = new File(fileName);
+ final File file = new File(fileName);
// getting the content of the bookmark file
- String fileString = post.get("crawlingFile$file");
+ final String fileString = post.get("crawlingFile$file");
// parsing the bookmark file and fetching the headline and contained links
- htmlFilterContentScraper scraper = new htmlFilterContentScraper(new yacyURL(file));
+ final htmlFilterContentScraper scraper = new htmlFilterContentScraper(new yacyURL(file));
//OutputStream os = new htmlFilterOutputStream(null, scraper, null, false);
- Writer writer = new htmlFilterWriter(null,null,scraper,null,false);
+ final Writer writer = new htmlFilterWriter(null,null,scraper,null,false);
serverFileUtils.copy(fileString, writer);
writer.close();
//String headline = scraper.getHeadline();
- Map<yacyURL, String> hyperlinks = scraper.getAnchors();
+ final Map<yacyURL, String> hyperlinks = scraper.getAnchors();
// creating a crawler profile
- yacyURL crawlURL = new yacyURL("file://" + file.toString(), null);
- CrawlProfile.entry profile = sb.webIndex.profilesActiveCrawls.newEntry(fileName, crawlURL, newcrawlingfilter, newcrawlingfilter, newcrawlingdepth, newcrawlingdepth, crawlingIfOlder, crawlingDomFilterDepth, crawlingDomMaxPages, crawlingQ, indexText, indexMedia, storeHTCache, true, crawlOrder, xsstopw, xdstopw, xpstopw);
+ final yacyURL crawlURL = new yacyURL("file://" + file.toString(), null);
+ final CrawlProfile.entry profile = sb.webIndex.profilesActiveCrawls.newEntry(fileName, crawlURL, newcrawlingfilter, newcrawlingfilter, newcrawlingdepth, newcrawlingdepth, crawlingIfOlder, crawlingDomFilterDepth, crawlingDomMaxPages, crawlingQ, indexText, indexMedia, storeHTCache, true, crawlOrder, xsstopw, xdstopw, xpstopw);
// pause local crawl here
sb.pauseCrawlJob(plasmaSwitchboard.CRAWLJOB_LOCAL_CRAWL);
// loop through the contained links
- Iterator<Map.Entry<yacyURL, String>> linkiterator = hyperlinks.entrySet().iterator();
+ final Iterator<Map.Entry<yacyURL, String>> linkiterator = hyperlinks.entrySet().iterator();
yacyURL nexturl;
while (linkiterator.hasNext()) {
- Map.Entry<yacyURL, String> e = linkiterator.next();
+ final Map.Entry<yacyURL, String> e = linkiterator.next();
nexturl = e.getKey();
if (nexturl == null) continue;
@@ -314,12 +314,12 @@ public class WatchCrawler_p {
profile);
}
- } catch (PatternSyntaxException e) {
+ } catch (final PatternSyntaxException e) {
// print error message
prop.put("info", "4"); //crawlfilter does not match url
prop.putHTML("info_newcrawlingfilter", newcrawlingfilter);
prop.putHTML("info_error", e.getMessage());
- } catch (Exception e) {
+ } catch (final Exception e) {
// mist
prop.put("info", "7");//Error with file
prop.putHTML("info_crawlingStart", fileName);
@@ -333,10 +333,10 @@ public class WatchCrawler_p {
try {
// getting the sitemap URL
sitemapURLStr = post.get("sitemapURL","");
- yacyURL sitemapURL = new yacyURL(sitemapURLStr, null);
+ final yacyURL sitemapURL = new yacyURL(sitemapURLStr, null);
// create a new profile
- CrawlProfile.entry pe = sb.webIndex.profilesActiveCrawls.newEntry(
+ final CrawlProfile.entry pe = sb.webIndex.profilesActiveCrawls.newEntry(
sitemapURLStr, sitemapURL, newcrawlingfilter, newcrawlingfilter,
newcrawlingdepth, newcrawlingdepth,
crawlingIfOlder, crawlingDomFilterDepth, crawlingDomMaxPages,
@@ -345,12 +345,12 @@ public class WatchCrawler_p {
storeHTCache, true, crawlOrder, xsstopw, xdstopw, xpstopw);
// create a new sitemap importer
- SitemapImporter importerThread = new SitemapImporter(sb, sb.dbImportManager, new yacyURL(sitemapURLStr, null), pe);
+ final SitemapImporter importerThread = new SitemapImporter(sb, sb.dbImportManager, new yacyURL(sitemapURLStr, null), pe);
if (importerThread != null) {
importerThread.setJobID(sb.dbImportManager.generateUniqueJobID());
importerThread.startIt();
}
- } catch (Exception e) {
+ } catch (final Exception e) {
// mist
prop.put("info", "6");//Error with url
prop.putHTML("info_crawlingStart", sitemapURLStr);
@@ -367,8 +367,8 @@ public class WatchCrawler_p {
}
// performance settings
- long LCbusySleep = Integer.parseInt(env.getConfig(plasmaSwitchboard.CRAWLJOB_LOCAL_CRAWL_BUSYSLEEP, "100"));
- int LCppm = (int) (60000L / Math.max(1,LCbusySleep));
+ final long LCbusySleep = Integer.parseInt(env.getConfig(plasmaSwitchboard.CRAWLJOB_LOCAL_CRAWL_BUSYSLEEP, "100"));
+ final int LCppm = (int) (60000L / Math.max(1,LCbusySleep));
prop.put("crawlingSpeedMaxChecked", (LCppm >= 1000) ? "1" : "0");
prop.put("crawlingSpeedCustChecked", ((LCppm > 10) && (LCppm < 1000)) ? "1" : "0");
prop.put("crawlingSpeedMinChecked", (LCppm <= 10) ? "1" : "0");
@@ -378,7 +378,7 @@ public class WatchCrawler_p {
return prop;
}
- private static int recrawlIfOlderC(boolean recrawlIfOlderCheck, int recrawlIfOlderNumber, String crawlingIfOlderUnit) {
+ private static int recrawlIfOlderC(final boolean recrawlIfOlderCheck, final int recrawlIfOlderNumber, final String crawlingIfOlderUnit) {
if (!recrawlIfOlderCheck) return -1;
if (crawlingIfOlderUnit.equals("year")) return recrawlIfOlderNumber * 60 * 24 * 365;
if (crawlingIfOlderUnit.equals("month")) return recrawlIfOlderNumber * 60 * 24 * 30;
@@ -387,13 +387,13 @@ public class WatchCrawler_p {
return recrawlIfOlderNumber;
}
- private static void setPerformance(plasmaSwitchboard sb, serverObjects post) {
- String crawlingPerformance = post.get("crawlingPerformance","custom");
- long LCbusySleep = Integer.parseInt(sb.getConfig(plasmaSwitchboard.CRAWLJOB_LOCAL_CRAWL_BUSYSLEEP, "100"));
+ private static void setPerformance(final plasmaSwitchboard sb, final serverObjects post) {
+ final String crawlingPerformance = post.get("crawlingPerformance","custom");
+ final long LCbusySleep = Integer.parseInt(sb.getConfig(plasmaSwitchboard.CRAWLJOB_LOCAL_CRAWL_BUSYSLEEP, "100"));
int wantedPPM = (LCbusySleep == 0) ? 6000 : (int) (60000L / LCbusySleep);
try {
wantedPPM = Integer.parseInt(post.get("customPPM", Integer.toString(wantedPPM)));
- } catch (NumberFormatException e) {}
+ } catch (final NumberFormatException e) {}
if (crawlingPerformance.equals("minimum")) wantedPPM = 10;
if (crawlingPerformance.equals("maximum")) wantedPPM = 6000;
sb.setPerformance(wantedPPM);
diff --git a/htroot/WatchWebStructure_p.java b/htroot/WatchWebStructure_p.java
index a2dd5fbd3..81a104d02 100644
--- a/htroot/WatchWebStructure_p.java
+++ b/htroot/WatchWebStructure_p.java
@@ -10,9 +10,9 @@ import de.anomic.server.serverSwitch;
public class WatchWebStructure_p {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
- serverObjects prop = new serverObjects();
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ final serverObjects prop = new serverObjects();
int width = 768;
int height = 576;
@@ -32,7 +32,7 @@ public class WatchWebStructure_p {
if (host.equals("auto")) {
// try to find the host from the crawl profiles
- Iterator<entry> it = sb.webIndex.profilesActiveCrawls.profiles(true);
+ final Iterator<entry> it = sb.webIndex.profilesActiveCrawls.profiles(true);
entry e;
while (it.hasNext()) {
e = it.next();
diff --git a/htroot/WebStructurePicture_p.java b/htroot/WebStructurePicture_p.java
index 2d9645ede..b5a6c8aa6 100644
--- a/htroot/WebStructurePicture_p.java
+++ b/htroot/WebStructurePicture_p.java
@@ -45,8 +45,8 @@ public class WebStructurePicture_p {
private static final double maxlongd = Long.MAX_VALUE;
- public static ymageMatrix respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ public static ymageMatrix respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
int width = 768;
int height = 576;
@@ -73,7 +73,7 @@ public class WebStructurePicture_p {
if (depth < 0) depth = 0;
// calculate target time
- long timeout = (time < 0) ? Long.MAX_VALUE : System.currentTimeMillis() + (time * 8 / 10);
+ final long timeout = (time < 0) ? Long.MAX_VALUE : System.currentTimeMillis() + (time * 8 / 10);
// find start point
if ((host == null) || (host.length() == 0) || (host.equals("auto"))) {
@@ -91,11 +91,11 @@ public class WebStructurePicture_p {
String hash = null;
try {
hash = (new yacyURL("http://" + host, null)).hash().substring(6);
- } catch (MalformedURLException e) {e.printStackTrace();}
+ } catch (final MalformedURLException e) {e.printStackTrace();}
assert (sb.webStructure.references(hash) != null);
// recursively find domains, up to a specific depth
- ymageGraph graph = new ymageGraph();
+ final ymageGraph graph = new ymageGraph();
if (host != null) place(graph, sb.webStructure, hash, host, nodes, timeout, 0.0, 0.0, 0, depth);
//graph.print();
@@ -111,7 +111,7 @@ public class WebStructurePicture_p {
}
- private static final int place(ymageGraph graph, plasmaWebStructure structure, String centerhash, String centerhost, int maxnodes, long timeout, double x, double y, int nextlayer, int maxlayer) {
+ private static final int place(final ymageGraph graph, final plasmaWebStructure structure, final String centerhash, final String centerhost, int maxnodes, final long timeout, final double x, final double y, int nextlayer, final int maxlayer) {
// returns the number of nodes that had been placed
assert centerhost != null;
ymageGraph.coordinate center = graph.getPoint(centerhost);
@@ -123,13 +123,13 @@ public class WebStructurePicture_p {
}
if (nextlayer == maxlayer) return mynodes;
nextlayer++;
- double radius = 1.0 / (1 << nextlayer);
- Map<String, Integer> next = structure.references(centerhash);
+ final double radius = 1.0 / (1 << nextlayer);
+ final Map<String, Integer> next = structure.references(centerhash);
Map.Entry<String, Integer> entry;
String targethash, targethost;
// first set points to next hosts
- Iterator<Map.Entry<String, Integer>> i = next.entrySet().iterator();
- ArrayList<String[]> targets = new ArrayList<String[]>();
+ final Iterator<Map.Entry<String, Integer>> i = next.entrySet().iterator();
+ final ArrayList<String[]> targets = new ArrayList<String[]>();
int maxtargetrefs = 8, maxthisrefs = 8;
int targetrefs, thisrefs;
double rr, re;
@@ -145,7 +145,7 @@ public class WebStructurePicture_p {
targets.add(new String[] {targethash, targethost});
if (graph.getPoint(targethost) != null) continue;
// set a new point. It is placed on a circle around the host point
- double angle = kelondroBase64Order.enhancedCoder.cardinal((targethash + "____").getBytes()) / maxlongd * 2 * Math.PI;
+ final double angle = kelondroBase64Order.enhancedCoder.cardinal((targethash + "____").getBytes()) / maxlongd * 2 * Math.PI;
//System.out.println("ANGLE = " + angle);
rr = radius * 0.25 * (1 - targetrefs / maxtargetrefs);
re = radius * 0.5 * (thisrefs / maxthisrefs);
@@ -154,14 +154,14 @@ public class WebStructurePicture_p {
mynodes++;
}
// recursively set next hosts
- Iterator<String[]> j = targets.iterator();
+ final Iterator<String[]> j = targets.iterator();
String[] target;
int nextnodes;
while (j.hasNext()) {
target = j.next();
targethash = target[0];
targethost = target[1];
- ymageGraph.coordinate c = graph.getPoint(targethost);
+ final ymageGraph.coordinate c = graph.getPoint(targethost);
assert c != null;
nextnodes = ((maxnodes <= 0) || (System.currentTimeMillis() >= timeout)) ? 0 : place(graph, structure, targethash, targethost, maxnodes, timeout, c.x, c.y, nextlayer, maxlayer);
mynodes += nextnodes;
diff --git a/htroot/Wiki.java b/htroot/Wiki.java
index 9485581df..33c99824f 100644
--- a/htroot/Wiki.java
+++ b/htroot/Wiki.java
@@ -49,14 +49,14 @@ public class Wiki {
//private static String numListLevel = "";
private static SimpleDateFormat SimpleFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
- public static String dateString(Date date) {
+ public static String dateString(final Date date) {
return SimpleFormatter.format(date);
}
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) throws IOException {
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
- serverObjects prop = new serverObjects();
+ public static serverObjects respond(final httpHeader header, serverObjects post, final serverSwitch<?> env) throws IOException {
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ final serverObjects prop = new serverObjects();
if (post == null) {
post = new serverObjects();
post.put("page", "start");
@@ -67,8 +67,8 @@ public class Wiki {
prop.put("display", display);
String access = sb.getConfig("WikiAccess", "admin");
- String pagename = get(post, "page", "start");
- String ip = get(post, httpHeader.CONNECTION_PROP_CLIENTIP, "127.0.0.1");
+ final String pagename = get(post, "page", "start");
+ final String ip = get(post, httpHeader.CONNECTION_PROP_CLIENTIP, "127.0.0.1");
String author = get(post, "author", "anonymous");
if (author.equals("anonymous")) {
author = wikiBoard.guessAuthor(ip);
@@ -106,13 +106,13 @@ public class Wiki {
byte[] content;
try {
content = post.get("content", "").getBytes("UTF-8");
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
content = post.get("content", "").getBytes();
}
- wikiBoard.entry newEntry = sb.wikiDB.newEntry(pagename, author, ip, post.get("reason", "edit"), content);
+ final wikiBoard.entry newEntry = sb.wikiDB.newEntry(pagename, author, ip, post.get("reason", "edit"), content);
sb.wikiDB.write(newEntry);
// create a news message
- HashMap<String, String> map = new HashMap<String, String>();
+ final HashMap<String, String> map = new HashMap<String, String>();
map.put("page", pagename);
map.put("author", author.replace(',', ' '));
if (post.get("content", "").trim().length() > 0 && !page.page().equals(content))
@@ -134,7 +134,7 @@ public class Wiki {
prop.putHTML("mode_author", author);
prop.putHTML("mode_page-code", new String(page.page(), "UTF-8"));
prop.putHTML("mode_pagename", pagename);
- } catch (UnsupportedEncodingException e) {}
+ } catch (final UnsupportedEncodingException e) {}
}
//contributed by [MN]
@@ -154,7 +154,7 @@ public class Wiki {
prop.put("mode", "3"); //Index
String subject;
try {
- Iterator<byte[]> i = sb.wikiDB.keys(true);
+ final Iterator<byte[]> i = sb.wikiDB.keys(true);
wikiBoard.entry entry;
int count=0;
while (i.hasNext()) {
@@ -167,7 +167,7 @@ public class Wiki {
count++;
}
prop.put("mode_pages", count);
- } catch (IOException e) {
+ } catch (final IOException e) {
prop.put("mode_error", "1"); //IO Error reading Wiki
prop.putHTML("mode_error_message", e.getMessage());
}
@@ -181,7 +181,7 @@ public class Wiki {
prop.putHTML("mode_error_page", pagename);
try {
- Iterator<byte[]> it = sb.wikiDB.keysBkp(true);
+ final Iterator<byte[]> it = sb.wikiDB.keysBkp(true);
wikiBoard.entry entry;
wikiBoard.entry oentry = null;
wikiBoard.entry nentry = null;
@@ -224,7 +224,7 @@ public class Wiki {
if (nentry == null) nentry = entry;
if (post.containsKey("compare") && oentry != null && nentry != null) {
// TODO: split into paragraphs and compare them with the same diff-algo
- diff diff = new diff(
+ final diff diff = new diff(
new String(oentry.page(), "UTF-8"),
new String(nentry.page(), "UTF-8"), 3);
prop.put("mode_versioning_diff", de.anomic.data.diff.toHTML(new diff[] { diff }));
@@ -237,7 +237,7 @@ public class Wiki {
prop.putWiki("mode_versioning_page", oentry.page());
prop.putHTML("mode_versioning_page-code", new String(oentry.page(), "UTF-8"));
}
- } catch (IOException e) {
+ } catch (final IOException e) {
prop.put("mode_error", "1"); //IO Error reading Wiki
prop.putHTML("mode_error_message", e.getMessage());
}
@@ -268,7 +268,7 @@ public class Wiki {
* @param string2
* @return
*/
- private static String get(serverObjects post, String key, String dflt) {
+ private static String get(final serverObjects post, final String key, final String dflt) {
return (post == null ? dflt : post.get(key, dflt));
}
}
diff --git a/htroot/WikiHelp.java b/htroot/WikiHelp.java
index 41aab4762..24751f394 100644
--- a/htroot/WikiHelp.java
+++ b/htroot/WikiHelp.java
@@ -33,7 +33,7 @@ import de.anomic.server.serverSwitch;
public class WikiHelp {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
//final plasmaSwitchboard sb = (plasmaSwitchboard) env;
final serverObjects prop = new serverObjects();
return prop;
diff --git a/htroot/YaCySearchPluginFF.java b/htroot/YaCySearchPluginFF.java
index a9e45a8dc..df6244bbd 100644
--- a/htroot/YaCySearchPluginFF.java
+++ b/htroot/YaCySearchPluginFF.java
@@ -37,15 +37,16 @@ public class YaCySearchPluginFF {
* @param env the serverSwitch object holding all runtime-data
* @return the rewrite-properties for the template
*/
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
- serverObjects prop = new serverObjects();
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ final serverObjects prop = new serverObjects();
// getting the http host header
- String hostSocket = header.get(httpHeader.CONNECTION_PROP_HOST);
+ final String hostSocket = header.get(httpHeader.CONNECTION_PROP_HOST);
String host = hostSocket;
- int port = 80, pos = hostSocket.indexOf(":");
+ int port = 80;
+ final int pos = hostSocket.indexOf(":");
if (pos != -1) {
port = Integer.parseInt(hostSocket.substring(pos + 1));
host = hostSocket.substring(0, pos);
diff --git a/htroot/autoconfig.java b/htroot/autoconfig.java
index 952f8d643..42df22e72 100644
--- a/htroot/autoconfig.java
+++ b/htroot/autoconfig.java
@@ -38,15 +38,16 @@ public class autoconfig {
* @param env the serverSwitch object holding all runtime-data
* @return the rewrite-properties for the template
*/
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
- serverObjects prop = new serverObjects();
+ final serverObjects prop = new serverObjects();
// getting the http host header
- String hostSocket = header.get(httpHeader.CONNECTION_PROP_HOST);
+ final String hostSocket = header.get(httpHeader.CONNECTION_PROP_HOST);
String host = hostSocket;
- int port = 80, pos = hostSocket.indexOf(":");
+ int port = 80;
+ final int pos = hostSocket.indexOf(":");
if (pos != -1) {
port = Integer.parseInt(hostSocket.substring(pos + 1));
host = hostSocket.substring(0, pos);
diff --git a/htroot/imagetest.java b/htroot/imagetest.java
index 029ab25c4..372061fda 100644
--- a/htroot/imagetest.java
+++ b/htroot/imagetest.java
@@ -32,7 +32,7 @@ import de.anomic.ymage.ymageToolPrint;
public class imagetest {
- public static ymageMatrix respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static ymageMatrix respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
/*
BufferedImage bi = new BufferedImage(640, 400, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bi.createGraphics();
@@ -64,7 +64,7 @@ public class imagetest {
for (int i = 20; i < 100; i++) r.setPixel(i, 34, new int[]{0, 0, 255});
return bi;
*/
- ymageMatrix img = new ymageMatrix(800, 600, ymageMatrix.MODE_SUB, "FFFFFF");
+ final ymageMatrix img = new ymageMatrix(800, 600, ymageMatrix.MODE_SUB, "FFFFFF");
img.setColor(ymageMatrix.GREY);
for (int y = 0; y < 600; y = y + 50) ymageToolPrint.print(img, 0, 6 + y, 0, "" + y, -1);
for (int x = 0; x < 800; x = x + 50) ymageToolPrint.print(img, x, 6 , 0, "" + x, -1);
diff --git a/htroot/index.java b/htroot/index.java
index cb35110b3..7f42d5772 100644
--- a/htroot/index.java
+++ b/htroot/index.java
@@ -37,13 +37,13 @@ import de.anomic.server.serverSwitch;
public class index {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
final plasmaSwitchboard sb = (plasmaSwitchboard) env;
final serverObjects prop = new serverObjects();
// access control
boolean publicPage = sb.getConfigBool("publicSearchpage", true);
- boolean authorizedAccess = sb.verifyAuthentication(header, false);
+ final boolean authorizedAccess = sb.verifyAuthentication(header, false);
if ((post != null) && (post.containsKey("publicPage"))) {
if (!authorizedAccess) {
prop.put("AUTHENTICATE", "admin log-in"); // force log-in
@@ -53,7 +53,7 @@ public class index {
sb.setConfig("publicSearchpage", publicPage);
}
- boolean global = (post == null) ? true : post.get("resource", "global").equals("global");
+ final boolean global = (post == null) ? true : post.get("resource", "global").equals("global");
final boolean authenticated = sb.adminAuthenticated(header) >= 2;
final int display = ((post == null) || (!authenticated)) ? 0 : post.getInt("display", 0);
final int searchoptions = (post == null) ? 0 : post.getInt("searchoptions", 0);
@@ -71,7 +71,7 @@ public class index {
// search domain
int contentdom = plasmaSearchQuery.CONTENTDOM_TEXT;
- String cds = (post == null) ? "text" : post.get("contentdom", "text");
+ final String cds = (post == null) ? "text" : post.get("contentdom", "text");
if (cds.equals("text")) contentdom = plasmaSearchQuery.CONTENTDOM_TEXT;
if (cds.equals("audio")) contentdom = plasmaSearchQuery.CONTENTDOM_AUDIO;
if (cds.equals("video")) contentdom = plasmaSearchQuery.CONTENTDOM_VIDEO;
diff --git a/htroot/opensearchdescription.java b/htroot/opensearchdescription.java
index c4c1224da..c83637d6b 100644
--- a/htroot/opensearchdescription.java
+++ b/htroot/opensearchdescription.java
@@ -32,8 +32,8 @@ import de.anomic.server.serverSwitch;
public class opensearchdescription {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
// generate message content for open search description
String promoteSearchPageGreeting = env.getConfig("promoteSearchPageGreeting", "");
if (env.getConfigBool("promoteSearchPageGreeting.useNetworkName", false)) promoteSearchPageGreeting = env.getConfig("network.unit.description", "");
diff --git a/htroot/osm.java b/htroot/osm.java
index 4d5e57ef3..260afeedd 100644
--- a/htroot/osm.java
+++ b/htroot/osm.java
@@ -8,7 +8,7 @@ import de.anomic.ymage.ymageOSM;
public class osm {
- public static ymageMatrix respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static ymageMatrix respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
int zoom = 10;
double lat = 47.968056d;
@@ -20,7 +20,7 @@ public class osm {
lon = post.getDouble("lon", lon);
}
- ymageOSM.tileCoordinates coord = new ymageOSM.tileCoordinates(lat, lon, zoom);
+ final ymageOSM.tileCoordinates coord = new ymageOSM.tileCoordinates(lat, lon, zoom);
return ymageOSM.getCombinedTiles(coord);
}
diff --git a/htroot/rct_p.java b/htroot/rct_p.java
index 497ed7cd9..a68b44b7e 100644
--- a/htroot/rct_p.java
+++ b/htroot/rct_p.java
@@ -43,39 +43,39 @@ import de.anomic.yacy.yacyURL;
public class rct_p {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
// return variable that accumulates replacements
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
- serverObjects prop = new serverObjects();
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ final serverObjects prop = new serverObjects();
if (post != null) {
if (post.containsKey("retrieve")) {
- String peerhash = post.get("peer", null);
- yacySeed seed = (peerhash == null) ? null : sb.webIndex.seedDB.getConnected(peerhash);
- RSSFeed feed = (seed == null) ? null : yacyClient.queryRemoteCrawlURLs(sb.webIndex.seedDB, seed, 10);
+ final String peerhash = post.get("peer", null);
+ final yacySeed seed = (peerhash == null) ? null : sb.webIndex.seedDB.getConnected(peerhash);
+ final RSSFeed feed = (seed == null) ? null : yacyClient.queryRemoteCrawlURLs(sb.webIndex.seedDB, seed, 10);
if (feed != null) {
- for (RSSMessage item: feed) {
+ for (final RSSMessage item: feed) {
//System.out.println("URL=" + item.getLink() + ", desc=" + item.getDescription() + ", pubDate=" + item.getPubDate());
// put url on remote crawl stack
yacyURL url;
try {
url = new yacyURL(item.getLink(), null);
- } catch (MalformedURLException e) {
+ } catch (final MalformedURLException e) {
url = null;
}
Date loaddate;
try {
loaddate = serverDate.parseShortSecond(item.getPubDate());
- } catch (ParseException e) {
+ } catch (final ParseException e) {
loaddate = new Date();
}
- yacyURL referrer = null; // referrer needed!
- String urlRejectReason = sb.acceptURL(url);
+ final yacyURL referrer = null; // referrer needed!
+ final String urlRejectReason = sb.acceptURL(url);
if (urlRejectReason == null) {
// stack url
sb.getLog().logFinest("crawlOrder: stack: url='" + url + "'");
- String reasonString = sb.crawlStacker.stackCrawl(url, referrer, peerhash, "REMOTE-CRAWLING", loaddate, 0, sb.webIndex.defaultRemoteProfile);
+ final String reasonString = sb.crawlStacker.stackCrawl(url, referrer, peerhash, "REMOTE-CRAWLING", loaddate, 0, sb.webIndex.defaultRemoteProfile);
if (reasonString == null) {
// done
@@ -104,16 +104,16 @@ public class rct_p {
* @param url
* @return
*/
- private static String urlToString(yacyURL url) {
+ private static String urlToString(final yacyURL url) {
return (url == null ? "null" : url.toNormalform(true, false));
}
- private static void listHosts(plasmaSwitchboard sb, serverObjects prop) {
+ private static void listHosts(final plasmaSwitchboard sb, final serverObjects prop) {
// list known hosts
yacySeed seed;
int hc = 0;
if (sb.webIndex.seedDB != null && sb.webIndex.seedDB.sizeConnected() > 0) {
- Iterator<yacySeed> e = sb.webIndex.peerActions.dhtAction.getProvidesRemoteCrawlURLs();
+ final Iterator<yacySeed> e = sb.webIndex.peerActions.dhtAction.getProvidesRemoteCrawlURLs();
while (e.hasNext()) {
seed = e.next();
if (seed != null) {
diff --git a/htroot/robots.java b/htroot/robots.java
index ed7154765..899d4165f 100644
--- a/htroot/robots.java
+++ b/htroot/robots.java
@@ -12,7 +12,7 @@ import de.anomic.server.servletProperties;
public class robots {
- public static servletProperties respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static servletProperties respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
final servletProperties prop = new servletProperties();
final httpdRobotsTxtConfig rbc = ((plasmaSwitchboard)env).robotstxtConfig;
@@ -49,7 +49,7 @@ public class robots {
}
@SuppressWarnings("unchecked")
- private static ArrayList<String>[] getFiles(String htrootPath) {
+ private static ArrayList<String>[] getFiles(final String htrootPath) {
final File htroot = new File(htrootPath);
if (!htroot.exists()) return null;
final ArrayList<String> htrootFiles = new ArrayList<String>();
diff --git a/htroot/sharedBlacklist_p.java b/htroot/sharedBlacklist_p.java
index 7f2721cd0..caaccf0b4 100644
--- a/htroot/sharedBlacklist_p.java
+++ b/htroot/sharedBlacklist_p.java
@@ -57,10 +57,10 @@ public class sharedBlacklist_p {
public static final int STATUS_URL_PROBLEM = 4;
public static final int STATUS_WRONG_INVOCATION = 5;
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
// return variable that accumulates replacements
- serverObjects prop = new serverObjects();
+ final serverObjects prop = new serverObjects();
// getting the name of the destination blacklist
String selectedBlacklistName = "";
@@ -82,16 +82,16 @@ public class sharedBlacklist_p {
* ====================================================== */
// getting the source peer hash
- String Hash = post.get("hash");
+ final String Hash = post.get("hash");
// generate the download URL
String downloadURL = null;
if( sb.webIndex.seedDB != null ){ //no nullpointer error..
- yacySeed seed = sb.webIndex.seedDB.getConnected(Hash);
+ final yacySeed seed = sb.webIndex.seedDB.getConnected(Hash);
if (seed != null) {
- String IP = seed.getIP();
- String Port = seed.get(yacySeed.PORT, "8080");
- String peerName = seed.get(yacySeed.NAME, "<" + IP + ":" + Port + ">");
+ final String IP = seed.getIP();
+ final String Port = seed.get(yacySeed.PORT, "8080");
+ final String peerName = seed.get(yacySeed.NAME, "<" + IP + ":" + Port + ">");
prop.putHTML("page_source", peerName);
downloadURL = "http://" + IP + ":" + Port + "/yacy/list.html?col=black";
@@ -107,15 +107,15 @@ public class sharedBlacklist_p {
if (downloadURL != null) {
// download the blacklist
try {
- httpHeader reqHeader = new httpHeader();
+ final httpHeader reqHeader = new httpHeader();
reqHeader.put(httpHeader.PRAGMA,"no-cache");
reqHeader.put(httpHeader.CACHE_CONTROL,"no-cache");
reqHeader.put(httpHeader.USER_AGENT, HTTPLoader.yacyUserAgent);
// get List
- yacyURL u = new yacyURL(downloadURL, null);
+ final yacyURL u = new yacyURL(downloadURL, null);
otherBlacklist = nxTools.strings(HttpClient.wget(u.toString(), reqHeader, 1000), "UTF-8");
- } catch (Exception e) {
+ } catch (final Exception e) {
prop.put("status", STATUS_PEER_UNKNOWN);
prop.put("page", "1");
}
@@ -125,15 +125,15 @@ public class sharedBlacklist_p {
* Download the blacklist from URL
* ====================================================== */
- String downloadURL = post.get("url");
+ final String downloadURL = post.get("url");
prop.putHTML("page_source", downloadURL);
try {
- yacyURL u = new yacyURL(downloadURL, null);
- httpHeader reqHeader = new httpHeader();
+ final yacyURL u = new yacyURL(downloadURL, null);
+ final httpHeader reqHeader = new httpHeader();
reqHeader.put(httpHeader.USER_AGENT, HTTPLoader.yacyUserAgent);
otherBlacklist = nxTools.strings(HttpClient.wget(u.toString(), reqHeader, 10000), "UTF-8"); //get List
- } catch (Exception e) {
+ } catch (final Exception e) {
prop.put("status", STATUS_URL_PROBLEM);
prop.putHTML("status_address",downloadURL);
prop.put("page", "1");
@@ -142,10 +142,10 @@ public class sharedBlacklist_p {
/* ======================================================
* Import the blacklist from file
* ====================================================== */
- String sourceFileName = post.get("file");
+ final String sourceFileName = post.get("file");
prop.put("page_source", sourceFileName);
- File sourceFile = new File(listManager.listsPath, sourceFileName);
+ final File sourceFile = new File(listManager.listsPath, sourceFileName);
if (!sourceFile.exists() || !sourceFile.canRead() || !sourceFile.isFile()) {
prop.put("status", STATUS_FILE_ERROR);
prop.put("page", "1");
@@ -168,7 +168,7 @@ public class sharedBlacklist_p {
pw = new PrintWriter(new FileWriter(new File(listManager.listsPath, selectedBlacklistName), true));
// loop through the received entry list
- int num = Integer.parseInt( post.get("num") );
+ final int num = Integer.parseInt( post.get("num") );
for(int i=0;i < num; i++){
if( post.containsKey("item" + i) ){
String newItem = post.get("item" + i);
@@ -191,8 +191,8 @@ public class sharedBlacklist_p {
count++;
if (plasmaSwitchboard.urlBlacklist != null) {
- String supportedBlacklistTypesStr = indexAbstractReferenceBlacklist.BLACKLIST_TYPES_STRING;
- String[] supportedBlacklistTypes = supportedBlacklistTypesStr.split(",");
+ final String supportedBlacklistTypesStr = indexAbstractReferenceBlacklist.BLACKLIST_TYPES_STRING;
+ final String[] supportedBlacklistTypes = supportedBlacklistTypesStr.split(",");
for (int blTypes=0; blTypes < supportedBlacklistTypes.length; blTypes++) {
if (listManager.listSetContains(supportedBlacklistTypes[blTypes] + ".BlackLists",selectedBlacklistName)) {
@@ -202,11 +202,11 @@ public class sharedBlacklist_p {
}
}
}
- } catch (Exception e) {
+ } catch (final Exception e) {
prop.put("status", "1");
prop.putHTML("status_error", e.getLocalizedMessage());
} finally {
- if (pw != null) try { pw.close(); } catch (Exception e){ /* */}
+ if (pw != null) try { pw.close(); } catch (final Exception e){ /* */}
}
prop.put("LOCATION","Blacklist_p.html?selectedListName=" + selectedBlacklistName + "&selectList=");
@@ -216,15 +216,15 @@ public class sharedBlacklist_p {
// generate the html list
if (otherBlacklist != null) {
// loading the current blacklist content
- HashSet<String> Blacklist = new HashSet<String>(listManager.getListArray(new File(listManager.listsPath, selectedBlacklistName)));
+ final HashSet<String> Blacklist = new HashSet<String>(listManager.getListArray(new File(listManager.listsPath, selectedBlacklistName)));
// sort the loaded blacklist
- String[] sortedlist = otherBlacklist.toArray(new String[otherBlacklist.size()]);
+ final String[] sortedlist = otherBlacklist.toArray(new String[otherBlacklist.size()]);
Arrays.sort(sortedlist);
int count = 0;
for(int i = 0; i < sortedlist.length; i++){
- String tmp = sortedlist[i];
+ final String tmp = sortedlist[i];
if( !Blacklist.contains(tmp) && (!tmp.equals("")) ){
//newBlacklist.add(tmp);
prop.put("page_urllist_" + count + "_dark", count % 2 == 0 ? "0" : "1");
diff --git a/htroot/ssitestservlet.java b/htroot/ssitestservlet.java
index 56a0cc869..ec8f77b3d 100644
--- a/htroot/ssitestservlet.java
+++ b/htroot/ssitestservlet.java
@@ -31,19 +31,19 @@ import de.anomic.server.serverSwitch;
public class ssitestservlet {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
//plasmaSwitchboard sb = (plasmaSwitchboard) env;
- serverObjects prop = new serverObjects();
+ final serverObjects prop = new serverObjects();
int delay = 0;
- long start = System.currentTimeMillis();
+ final long start = System.currentTimeMillis();
if (post != null) {
delay = post.getInt("delay", 1000);
}
// make a delay to see how the ssi loads and displays this page
- try {Thread.sleep(delay);} catch (InterruptedException e) {}
+ try {Thread.sleep(delay);} catch (final InterruptedException e) {}
prop.put("delay", delay);
prop.put("start", start);
diff --git a/htroot/test.java b/htroot/test.java
index 06d189554..4c1398dc6 100644
--- a/htroot/test.java
+++ b/htroot/test.java
@@ -6,9 +6,9 @@ public class test {
// http://localhost:8080/test.xml?count=10
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
- serverObjects prop = new serverObjects();
- int count = Math.min(1000, (post == null) ? 0 : post.getInt("count", 0));
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
+ final serverObjects prop = new serverObjects();
+ final int count = Math.min(1000, (post == null) ? 0 : post.getInt("count", 0));
for (int i = 0; i < count; i++) {
prop.put("item_" + i + "_text", Integer.toString(i));
diff --git a/htroot/www/welcome.java b/htroot/www/welcome.java
index 59ca90dc2..e443c95e6 100644
--- a/htroot/www/welcome.java
+++ b/htroot/www/welcome.java
@@ -42,8 +42,8 @@ import de.anomic.yacy.yacySeed;
public class welcome {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
// return variable that accumulates replacements
final serverObjects prop = new serverObjects();
@@ -57,7 +57,7 @@ public class welcome {
prop.put("hostname", serverDomains.myPublicIP());
try{
prop.put("hostip", InetAddress.getByName(serverDomains.myPublicIP()).getHostAddress());
- }catch(UnknownHostException e){
+ }catch(final UnknownHostException e){
prop.put("hostip", "Unknown Host Exception");
}
prop.put("port", serverCore.getPortNr(env.getConfig("port","8080")));
@@ -67,7 +67,7 @@ public class welcome {
final boolean senior = (peertype.equals(yacySeed.PEERTYPE_SENIOR)) || (peertype.equals(yacySeed.PEERTYPE_PRINCIPAL));
if (senior) { prop.put("couldcan", "can"); } else { prop.put("couldcan", "could"); }
if (senior) { prop.put("seniorinfo", "This peer runs in senior mode which means that your peer can be accessed using the addresses shown above."); } else { prop.putHTML("seniorinfo", "<b>Nobody can access your peer from the outside of your intranet. You must open your firewall and/or set a 'virtual server' in the settings of your router to enable access to the addresses as shown below.</b>"); }
- File wwwpath = env.getConfigPath("htDocsPath", "DATA/HTDOCS");
+ final File wwwpath = env.getConfigPath("htDocsPath", "DATA/HTDOCS");
prop.putHTML("wwwpath", wwwpath.isAbsolute() ? wwwpath.getAbsolutePath() : "<application_root_path>/" + env.getConfig("htDocsPath", "DATA/HTDOCS"));
// return rewrite properties
diff --git a/htroot/xml/blacklists_p.java b/htroot/xml/blacklists_p.java
index ed7b1b60b..fee690ade 100644
--- a/htroot/xml/blacklists_p.java
+++ b/htroot/xml/blacklists_p.java
@@ -31,11 +31,11 @@ import de.anomic.server.serverSwitch;
public class blacklists_p {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
- serverObjects prop = new serverObjects();
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
+ final serverObjects prop = new serverObjects();
listManager.listsPath = new File(listManager.switchboard.getRootPath(),listManager.switchboard.getConfig("listManager.listsPath", "DATA/LISTS"));
- String[] dirlist = listManager.getDirListing(listManager.listsPath);
+ final String[] dirlist = listManager.getDirListing(listManager.listsPath);
int blacklistCount=0;
ArrayList<String> list;
@@ -50,7 +50,7 @@ public class blacklists_p {
prop.put("lists_" + blacklistCount + "_shared", "0");
}
- String[] types = indexAbstractReferenceBlacklist.BLACKLIST_TYPES_STRING.split(",");
+ final String[] types = indexAbstractReferenceBlacklist.BLACKLIST_TYPES_STRING.split(",");
for (int j=0; j<types.length; j++) {
prop.put("lists_" + blacklistCount + "_types_" + j + "_name", types[j]);
prop.put("lists_" + blacklistCount + "_types_" + j + "_value",
@@ -62,7 +62,7 @@ public class blacklists_p {
count=0;
for (int j=0;j<list.size();++j){
- String nextEntry = list.get(j);
+ final String nextEntry = list.get(j);
if (nextEntry.length() == 0) continue;
if (nextEntry.startsWith("#")) continue;
diff --git a/htroot/xml/bookmarks/posts/all.java b/htroot/xml/bookmarks/posts/all.java
index f93c32753..1aa49340a 100644
--- a/htroot/xml/bookmarks/posts/all.java
+++ b/htroot/xml/bookmarks/posts/all.java
@@ -38,11 +38,11 @@ import de.anomic.server.serverObjects;
import de.anomic.server.serverSwitch;
public class all {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
// return variable that accumulates replacements
- plasmaSwitchboard switchboard = (plasmaSwitchboard) env;
- boolean isAdmin=switchboard.verifyAuthentication(header, true);
- serverObjects prop = new serverObjects();
+ final plasmaSwitchboard switchboard = (plasmaSwitchboard) env;
+ final boolean isAdmin=switchboard.verifyAuthentication(header, true);
+ final serverObjects prop = new serverObjects();
Iterator<String> it;
if(post != null && post.containsKey("tag")){
@@ -52,7 +52,7 @@ public class all {
}
// if an extended xml should be used
- boolean extendedXML = (post != null && post.containsKey("extendedXML"));
+ final boolean extendedXML = (post != null && post.containsKey("extendedXML"));
int count=0;
bookmarksDB.Bookmark bookmark;
diff --git a/htroot/xml/bookmarks/posts/delete_p.java b/htroot/xml/bookmarks/posts/delete_p.java
index acaa50126..256b07d6b 100644
--- a/htroot/xml/bookmarks/posts/delete_p.java
+++ b/htroot/xml/bookmarks/posts/delete_p.java
@@ -32,10 +32,10 @@ import de.anomic.server.serverSwitch;
import de.anomic.yacy.yacyURL;
public class delete_p {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
// return variable that accumulates replacements
- plasmaSwitchboard switchboard = (plasmaSwitchboard) env;
- serverObjects prop = new serverObjects();
+ final plasmaSwitchboard switchboard = (plasmaSwitchboard) env;
+ final serverObjects prop = new serverObjects();
if(post!= null){
try {
if( post.containsKey("url") && switchboard.bookmarksDB.removeBookmark((new yacyURL(post.get("url", "nourl"), null)).hash())) {
@@ -45,7 +45,7 @@ public class delete_p {
}else{
prop.put("result", "0");
}
- } catch (MalformedURLException e) {
+ } catch (final MalformedURLException e) {
prop.put("result", "0");
}
}else{
diff --git a/htroot/xml/bookmarks/posts/get.java b/htroot/xml/bookmarks/posts/get.java
index ebb902e82..d38777c56 100644
--- a/htroot/xml/bookmarks/posts/get.java
+++ b/htroot/xml/bookmarks/posts/get.java
@@ -33,11 +33,11 @@ import de.anomic.server.serverObjects;
import de.anomic.server.serverSwitch;
public class get {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
// return variable that accumulates replacements
- plasmaSwitchboard switchboard = (plasmaSwitchboard) env;
- boolean isAdmin=switchboard.verifyAuthentication(header, true);
- serverObjects prop = new serverObjects();
+ final plasmaSwitchboard switchboard = (plasmaSwitchboard) env;
+ final boolean isAdmin=switchboard.verifyAuthentication(header, true);
+ final serverObjects prop = new serverObjects();
String tag=null;
String date;
//String url=""; //urlfilter not yet implemented
@@ -52,19 +52,19 @@ public class get {
}
// if an extended xml should be used
- boolean extendedXML = (post != null && post.containsKey("extendedXML"));
+ final boolean extendedXML = (post != null && post.containsKey("extendedXML"));
int count=0;
Date parsedDate = null;
try {
parsedDate = serverDate.parseISO8601(date);
- } catch (ParseException e) {
+ } catch (final ParseException e) {
parsedDate = new Date();
}
- ArrayList<String> bookmark_hashes=switchboard.bookmarksDB.getDate(Long.toString(parsedDate.getTime())).getBookmarkList();
- Iterator<String> it=bookmark_hashes.iterator();
+ final ArrayList<String> bookmark_hashes=switchboard.bookmarksDB.getDate(Long.toString(parsedDate.getTime())).getBookmarkList();
+ final Iterator<String> it=bookmark_hashes.iterator();
bookmarksDB.Bookmark bookmark=null;
while(it.hasNext()){
bookmark=switchboard.bookmarksDB.getBookmark(it.next());
diff --git a/htroot/xml/bookmarks/tags/get.java b/htroot/xml/bookmarks/tags/get.java
index bbd44bac1..ac42a14cd 100644
--- a/htroot/xml/bookmarks/tags/get.java
+++ b/htroot/xml/bookmarks/tags/get.java
@@ -42,11 +42,11 @@ public class get {
final static int SORT_SIZE = 2;
final static int SHOW_ALL = -1;
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
// return variable that accumulates replacements
- plasmaSwitchboard switchboard = (plasmaSwitchboard) env;
- boolean isAdmin=switchboard.verifyAuthentication(header, true);
- serverObjects prop = new serverObjects();
+ final plasmaSwitchboard switchboard = (plasmaSwitchboard) env;
+ final boolean isAdmin=switchboard.verifyAuthentication(header, true);
+ final serverObjects prop = new serverObjects();
Iterator<Tag> it = null;
String tagName = "";
int top = SHOW_ALL;
@@ -62,11 +62,11 @@ public class get {
}
if(post.containsKey("top")) {
- String s_top = post.get("top");
+ final String s_top = post.get("top");
top = Integer.parseInt(s_top);
}
if(post.containsKey("sort")) {
- String sort = post.get("sort");
+ final String sort = post.get("sort");
if (sort.equals("size"))
comp = SORT_SIZE;
}
diff --git a/htroot/xml/bookmarks/tags/rename_p.java b/htroot/xml/bookmarks/tags/rename_p.java
index 230280de9..1a640626c 100644
--- a/htroot/xml/bookmarks/tags/rename_p.java
+++ b/htroot/xml/bookmarks/tags/rename_p.java
@@ -33,10 +33,10 @@ import de.anomic.server.serverObjects;
import de.anomic.server.serverSwitch;
public class rename_p {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
// return variable that accumulates replacements
- plasmaSwitchboard switchboard = (plasmaSwitchboard) env;
- serverObjects prop = new serverObjects();
+ final plasmaSwitchboard switchboard = (plasmaSwitchboard) env;
+ final serverObjects prop = new serverObjects();
prop.put("result", "0");//error
//rename tags
if(post != null && post.containsKey("old") && post.containsKey("new")){
diff --git a/htroot/xml/bookmarks/xbel/xbel.java b/htroot/xml/bookmarks/xbel/xbel.java
index e4904b017..94cf2f25c 100644
--- a/htroot/xml/bookmarks/xbel/xbel.java
+++ b/htroot/xml/bookmarks/xbel/xbel.java
@@ -4,12 +4,12 @@ import java.util.Date;
import java.util.Iterator;
import de.anomic.data.bookmarksDB;
+import de.anomic.data.htmlTools;
import de.anomic.http.httpHeader;
import de.anomic.plasma.plasmaSwitchboard;
import de.anomic.server.serverDate;
import de.anomic.server.serverObjects;
import de.anomic.server.serverSwitch;
-import de.anomic.data.htmlTools;
public class xbel {
@@ -17,7 +17,7 @@ public class xbel {
private static plasmaSwitchboard switchboard = null;
private static boolean isAdmin = false;
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
int count = 0;;
@@ -32,10 +32,10 @@ public class xbel {
}
}
if(post.containsKey("tag")) {
- String tagName=post.get("tag");
+ final String tagName=post.get("tag");
prop.put("folder", tagName);
if (!tagName.equals("")) {
- Iterator<String> bit=switchboard.bookmarksDB.getBookmarksIterator(tagName, isAdmin);
+ final Iterator<String> bit=switchboard.bookmarksDB.getBookmarksIterator(tagName, isAdmin);
count = print_XBEL(bit, count);
prop.put("xbel", count);
return prop;
@@ -50,7 +50,7 @@ public class xbel {
}
- private static int recurseFolders(Iterator<String> it, String root, int count, boolean next, String prev){
+ private static int recurseFolders(final Iterator<String> it, String root, int count, final boolean next, final String prev){
String fn="";
if(next) fn = it.next().toString();
@@ -71,7 +71,7 @@ public class xbel {
count++;
prop.put("xbel_"+count+"_elements", "<title>" + htmlTools.encodeUnicode2xml(fn.replaceFirst(root+"/*","")) + "</title>");
count++;
- Iterator<String> bit=switchboard.bookmarksDB.getBookmarksIterator(fn, isAdmin);
+ final Iterator<String> bit=switchboard.bookmarksDB.getBookmarksIterator(fn, isAdmin);
count = print_XBEL(bit, count);
if(it.hasNext()){
count = recurseFolders(it, fn, count, true, fn);
@@ -85,7 +85,7 @@ public class xbel {
}
return count;
}
- private static int print_XBEL(Iterator<String> bit, int count) {
+ private static int print_XBEL(final Iterator<String> bit, int count) {
bookmarksDB.Bookmark bookmark;
Date date;
while(bit.hasNext()){
diff --git a/htroot/xml/config_p.java b/htroot/xml/config_p.java
index 85d5ef299..7df3c75a8 100644
--- a/htroot/xml/config_p.java
+++ b/htroot/xml/config_p.java
@@ -34,10 +34,10 @@ import de.anomic.server.serverSwitch;
public class config_p {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
// return variable that accumulates replacements
//plasmaSwitchboard switchboard = (plasmaSwitchboard) env;
- serverObjects prop = new serverObjects();
+ final serverObjects prop = new serverObjects();
String key;
//change a Key
@@ -51,7 +51,7 @@ public class config_p {
Iterator<String> keys = env.configKeys();
- List<String> list = new ArrayList<String>(250);
+ final List<String> list = new ArrayList<String>(250);
while(keys.hasNext()){
list.add(keys.next());
}
diff --git a/htroot/xml/feed.java b/htroot/xml/feed.java
index 854be72aa..31a801192 100755
--- a/htroot/xml/feed.java
+++ b/htroot/xml/feed.java
@@ -35,22 +35,22 @@ import de.anomic.xml.RSSMessage;
public class feed {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
// insert default values
- serverObjects prop = new serverObjects();
+ final serverObjects prop = new serverObjects();
prop.put("channel_title", "");
prop.put("channel_description", "");
prop.put("channel_pubDate", "");
prop.put("item", "0");
if ((post == null) || (env == null)) return prop;
- boolean authorized = sb.verifyAuthentication(header, false);
+ final boolean authorized = sb.verifyAuthentication(header, false);
- String channelNames = post.get("set");
+ final String channelNames = post.get("set");
if (channelNames == null) return prop;
- String[] channels = channelNames.split(","); // several channel names can be given and separated by comma
+ final String[] channels = channelNames.split(","); // several channel names can be given and separated by comma
int messageCount = 0;
int messageMaxCount = Math.min(post.getInt("count", 100), 1000);
diff --git a/htroot/xml/queues_p.java b/htroot/xml/queues_p.java
index 89ee4f4e3..b3ea43836 100644
--- a/htroot/xml/queues_p.java
+++ b/htroot/xml/queues_p.java
@@ -49,16 +49,16 @@ public class queues_p {
public static final String STATE_PAUSED = "paused";
private static SimpleDateFormat dayFormatter = new SimpleDateFormat("yyyy/MM/dd", Locale.US);
- private static String daydate(Date date) {
+ private static String daydate(final Date date) {
if (date == null) return "";
return dayFormatter.format(date);
}
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
// return variable that accumulates replacements
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
//wikiCode wikiTransformer = new wikiCode(switchboard);
- serverObjects prop = new serverObjects();
+ final serverObjects prop = new serverObjects();
if (post == null || !post.containsKey("html"))
prop.setLocalized(false);
prop.put("rejected", "0");
@@ -79,13 +79,13 @@ public class queues_p {
int i=0; //counter
// getting all entries that are currently in process
- ArrayList<IndexingStack.QueueEntry> entryList = new ArrayList<IndexingStack.QueueEntry>();
+ final ArrayList<IndexingStack.QueueEntry> entryList = new ArrayList<IndexingStack.QueueEntry>();
entryList.addAll(sb.webIndex.queuePreStack.getActiveQueueEntries());
- int inProcessCount = entryList.size();
+ final int inProcessCount = entryList.size();
// getting all enqueued entries
if ((sb.webIndex.queuePreStack.size() > 0)) {
- Iterator<IndexingStack.QueueEntry> i1 = sb.webIndex.queuePreStack.entryIterator(false);
+ final Iterator<IndexingStack.QueueEntry> i1 = sb.webIndex.queuePreStack.entryIterator(false);
while (i1.hasNext()) entryList.add(i1.next());
}
@@ -94,10 +94,10 @@ public class queues_p {
int ok = 0;
for (i = 0; i < size; i++) {
- boolean inProcess = i < inProcessCount;
+ final boolean inProcess = i < inProcessCount;
pcentry = entryList.get(i);
if ((pcentry != null) && (pcentry.url() != null)) {
- long entrySize = pcentry.size();
+ final long entrySize = pcentry.size();
totalSize += entrySize;
initiator = sb.webIndex.seedDB.getConnected(pcentry.initiator());
prop.put("list-indexing_"+i+"_profile", (pcentry.profile() != null) ? pcentry.profile().name() : "deleted");
@@ -121,7 +121,7 @@ public class queues_p {
if (sb.crawlQueues.size() == 0) {
prop.put("list-loader", "0");
} else {
- CrawlEntry[] w = sb.crawlQueues.activeWorkerEntries();
+ final CrawlEntry[] w = sb.crawlQueues.activeWorkerEntries();
int count = 0;
for (int i = 0; i < w.length; i++) {
if (w[i] == null) continue;
@@ -162,7 +162,7 @@ public class queues_p {
}
- public static final void addNTable(plasmaSwitchboard sb, serverObjects prop, String tableName, ArrayList<CrawlEntry> crawlerList) {
+ public static final void addNTable(final plasmaSwitchboard sb, final serverObjects prop, final String tableName, final ArrayList<CrawlEntry> crawlerList) {
int showNum = 0;
CrawlEntry urle;
diff --git a/htroot/xml/status_p.java b/htroot/xml/status_p.java
index 93d317398..7cd377580 100644
--- a/htroot/xml/status_p.java
+++ b/htroot/xml/status_p.java
@@ -32,10 +32,10 @@ import de.anomic.server.serverSwitch;
public class status_p {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
// return variable that accumulates replacements
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
- serverObjects prop = new serverObjects();
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ final serverObjects prop = new serverObjects();
if (post == null || !post.containsKey("html"))
prop.setLocalized(false);
prop.put("rejected", "0");
diff --git a/htroot/xml/util/getpageinfo_p.java b/htroot/xml/util/getpageinfo_p.java
index 3cb009f24..fe36e3c65 100644
--- a/htroot/xml/util/getpageinfo_p.java
+++ b/htroot/xml/util/getpageinfo_p.java
@@ -43,9 +43,9 @@ import de.anomic.yacy.yacyURL;
public class getpageinfo_p {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
- serverObjects prop = new serverObjects();
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ final serverObjects prop = new serverObjects();
prop.put("sitemap", "");
prop.put("title", "");
prop.put("favicon","");
@@ -64,16 +64,16 @@ public class getpageinfo_p {
}
if (actions.indexOf("title")>=0) {
try {
- yacyURL u = new yacyURL(url, null);
- httpHeader reqHeader = new httpHeader();
+ final yacyURL u = new yacyURL(url, null);
+ final httpHeader reqHeader = new httpHeader();
reqHeader.put(httpHeader.USER_AGENT, HTTPLoader.yacyUserAgent); // do not set the crawler user agent, because this page was loaded by manual entering of the url
- byte[] r = HttpClient.wget(u.toString(), reqHeader, 5000);
+ final byte[] r = HttpClient.wget(u.toString(), reqHeader, 5000);
if (r == null) return prop;
- String contentString=new String(r);
+ final String contentString=new String(r);
- htmlFilterContentScraper scraper = new htmlFilterContentScraper(u);
+ final htmlFilterContentScraper scraper = new htmlFilterContentScraper(u);
//OutputStream os = new htmlFilterOutputStream(null, scraper, null, false);
- Writer writer = new htmlFilterWriter(null,null,scraper,null,false);
+ final Writer writer = new htmlFilterWriter(null,null,scraper,null,false);
serverFileUtils.copy(contentString,writer);
writer.close();
@@ -84,7 +84,7 @@ public class getpageinfo_p {
prop.put("favicon", (scraper.getFavicon()==null) ? "" : scraper.getFavicon().toString());
// put keywords
- String list[]=scraper.getKeywords();
+ final String list[]=scraper.getKeywords();
int count = 0;
for(int i=0;i<list.length;i++){
String tag = list[i];
@@ -99,21 +99,21 @@ public class getpageinfo_p {
}
prop.put("tags", count);
- } catch (MalformedURLException e) { /* ignore this */
- } catch (IOException e) { /* ignore this */
+ } catch (final MalformedURLException e) { /* ignore this */
+ } catch (final IOException e) { /* ignore this */
}
}
if(actions.indexOf("robots")>=0){
try {
- yacyURL theURL = new yacyURL(url, null);
+ final yacyURL theURL = new yacyURL(url, null);
// determine if crawling of the current URL is allowed
prop.put("robots-allowed", sb.robots.isDisallowed(theURL) ? "0" : "1");
// get the sitemap URL of the domain
- yacyURL sitemapURL = sb.robots.getSitemapURL(theURL);
+ final yacyURL sitemapURL = sb.robots.getSitemapURL(theURL);
prop.putHTML("sitemap", (sitemapURL==null)?"":sitemapURL.toString(), true);
- } catch (MalformedURLException e) {}
+ } catch (final MalformedURLException e) {}
}
}
diff --git a/htroot/xml/util/ynetSearch.java b/htroot/xml/util/ynetSearch.java
index a912df5be..76a8b4e1d 100644
--- a/htroot/xml/util/ynetSearch.java
+++ b/htroot/xml/util/ynetSearch.java
@@ -37,10 +37,10 @@ import de.anomic.server.serverSwitch;
public class ynetSearch {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
- plasmaSwitchboard switchboard = (plasmaSwitchboard) env;
- boolean isAdmin=switchboard.verifyAuthentication(header, true);
- serverObjects prop = new serverObjects();
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
+ final plasmaSwitchboard switchboard = (plasmaSwitchboard) env;
+ final boolean isAdmin=switchboard.verifyAuthentication(header, true);
+ final serverObjects prop = new serverObjects();
if(post != null){
if(!isAdmin){
@@ -51,18 +51,18 @@ public class ynetSearch {
} else {
InputStream is = null;
try {
- String s = post.get("url")+"&search="+post.get("search")+"&count="+post.get("count")+"&offset="+post.get("offset");
- URL url = new URL(s);
+ final String s = post.get("url")+"&search="+post.get("search")+"&count="+post.get("count")+"&offset="+post.get("offset");
+ final URL url = new URL(s);
is = url.openStream();
- String httpout = new Scanner(is).useDelimiter( "\\Z" ).next();
+ final String httpout = new Scanner(is).useDelimiter( "\\Z" ).next();
prop.put("http", httpout);
}
- catch ( Exception e ) {
+ catch ( final Exception e ) {
prop.put("url", "error!");
}
finally {
if ( is != null )
- try { is.close(); } catch ( IOException e ) { }
+ try { is.close(); } catch ( final IOException e ) { }
}
}
}
diff --git a/htroot/xml/version.java b/htroot/xml/version.java
index 20c275ae1..63440b032 100644
--- a/htroot/xml/version.java
+++ b/htroot/xml/version.java
@@ -29,9 +29,9 @@ import de.anomic.server.serverSwitch;
public class version {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
// return variable that accumulates replacements
- serverObjects prop = new serverObjects();
+ final serverObjects prop = new serverObjects();
prop.put("version", env.getConfig("version", "0.0"));
prop.put("svnRev", env.getConfig("svnRevision", "0"));
diff --git a/htroot/xml/webstructure.java b/htroot/xml/webstructure.java
index c47851528..0af438e60 100644
--- a/htroot/xml/webstructure.java
+++ b/htroot/xml/webstructure.java
@@ -38,11 +38,11 @@ import de.anomic.server.serverSwitch;
public class webstructure {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
- serverObjects prop = new serverObjects();
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
- boolean latest = ((post == null) ? false : post.containsKey("latest"));
- Iterator<plasmaWebStructure.structureEntry> i = sb.webStructure.structureEntryIterator(latest);
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
+ final serverObjects prop = new serverObjects();
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ final boolean latest = ((post == null) ? false : post.containsKey("latest"));
+ final Iterator<plasmaWebStructure.structureEntry> i = sb.webStructure.structureEntryIterator(latest);
int c = 0, d;
plasmaWebStructure.structureEntry sentry;
Map.Entry<String, Integer> refentry;
diff --git a/htroot/yacy/crawlReceipt.java b/htroot/yacy/crawlReceipt.java
index 91cf4c86b..aa5ed1ec0 100644
--- a/htroot/yacy/crawlReceipt.java
+++ b/htroot/yacy/crawlReceipt.java
@@ -47,28 +47,28 @@ public final class crawlReceipt {
* this is used to respond on a remote crawling request
*/
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
// return variable that accumulates replacements
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
- serverObjects prop = new serverObjects();
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ final serverObjects prop = new serverObjects();
if ((post == null) || (env == null)) return prop;
if (!yacyNetwork.authentifyRequest(post, env)) return prop;
- serverLog log = sb.getLog();
+ final serverLog log = sb.getLog();
//int proxyPrefetchDepth = Integer.parseInt(env.getConfig("proxyPrefetchDepth", "0"));
//int crawlingDepth = Integer.parseInt(env.getConfig("crawlingDepth", "0"));
// request values
- String iam = post.get("iam", ""); // seed hash of requester
- String youare = post.get("youare", ""); // seed hash of the target peer, needed for network stability
+ final String iam = post.get("iam", ""); // seed hash of requester
+ final String youare = post.get("youare", ""); // seed hash of the target peer, needed for network stability
//String process = post.get("process", ""); // process type
- String key = post.get("key", ""); // transmission key
+ final String key = post.get("key", ""); // transmission key
//String receivedUrlhash = post.get("urlhash", ""); // the url hash that has been crawled
- String result = post.get("result", ""); // the result; either "ok" or "fail"
- String reason = post.get("reason", ""); // the reason for that result
+ final String result = post.get("result", ""); // the result; either "ok" or "fail"
+ final String reason = post.get("reason", ""); // the reason for that result
//String words = post.get("wordh", ""); // priority word hashes
- String propStr = crypt.simpleDecode(post.get("lurlEntry", ""), key);
+ final String propStr = crypt.simpleDecode(post.get("lurlEntry", ""), key);
/*
the result can have one of the following values:
@@ -112,14 +112,14 @@ public final class crawlReceipt {
}
// generating a new loaded URL entry
- indexURLReference entry = indexURLReference.importEntry(propStr);
+ final indexURLReference entry = indexURLReference.importEntry(propStr);
if (entry == null) {
log.logWarning("crawlReceipt: RECEIVED wrong RECEIPT (entry null) from peer " + iam + "\n\tURL properties: "+ propStr);
prop.put("delay", "3600");
return prop;
}
- indexURLReference.Components comp = entry.comp();
+ final indexURLReference.Components comp = entry.comp();
if (comp.url() == null) {
log.logWarning("crawlReceipt: RECEIVED wrong RECEIPT (url null) for hash " + entry.hash() + " from peer " + iam + "\n\tURL properties: "+ propStr);
prop.put("delay", "3600");
@@ -127,7 +127,7 @@ public final class crawlReceipt {
}
// check if the entry is in our network domain
- String urlRejectReason = sb.acceptURL(comp.url());
+ final String urlRejectReason = sb.acceptURL(comp.url());
if (urlRejectReason != null) {
log.logWarning("crawlReceipt: RECEIVED wrong RECEIPT (" + urlRejectReason + ") for hash " + entry.hash() + " from peer " + iam + "\n\tURL properties: "+ propStr);
prop.put("delay", "9999");
@@ -144,14 +144,14 @@ public final class crawlReceipt {
// ready for more
prop.put("delay", "10");
return prop;
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
prop.put("delay", "3600");
return prop;
}
sb.crawlQueues.delegatedURL.remove(entry.hash()); // the delegated work is transformed into an error case
- ZURL.Entry ee = sb.crawlQueues.errorURL.newEntry(
+ final ZURL.Entry ee = sb.crawlQueues.errorURL.newEntry(
entry.toBalancerEntry(iam),
youare,
null,
diff --git a/htroot/yacy/hello.java b/htroot/yacy/hello.java
index 4f9440a49..cb3a5214c 100644
--- a/htroot/yacy/hello.java
+++ b/htroot/yacy/hello.java
@@ -49,9 +49,9 @@ public final class hello {
// example:
// http://localhost:8080/yacy/hello.html?count=1&seed=p|{Hash=sCJ6Tq8T0N9x,IPType=&empty;,Port=8080,IP=,Uptime=8,rI=190,Version=0.10004882,PeerType=junior,UTC=+0200,RCount=0,sI=0,LastSeen=20080605103333,Name=intratest,CCount=5.0,SCount=40,news=,USpeed=0,CRTCnt=0,CRWCnt=0,BDate=20080605081349,rU=190,LCount=187,dct=1212668923654,ICount=2,sU=0,ISpeed=0,RSpeed=0.0,NCount=0,Flags=oooo}
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) throws InterruptedException {
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
- serverObjects prop = new serverObjects();
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) throws InterruptedException {
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ final serverObjects prop = new serverObjects();
prop.put("message", "none");
if ((post == null) || (env == null)) {
prop.put("message", "no post or no enviroment");
@@ -68,10 +68,10 @@ public final class hello {
final String seed = post.get("seed", "");
final String countStr = post.get("count", "0");
int count = 0;
- try {count = (countStr == null) ? 0 : Integer.parseInt(countStr);} catch (NumberFormatException e) {count = 0;}
+ try {count = (countStr == null) ? 0 : Integer.parseInt(countStr);} catch (final NumberFormatException e) {count = 0;}
// final Date remoteTime = yacyCore.parseUniversalDate((String) post.get(MYTIME)); // read remote time
final String clientip = (String) header.get(httpHeader.CONNECTION_PROP_CLIENTIP, "<unknown>"); // read an artificial header addendum
- InetAddress ias = serverDomains.dnsResolve(clientip);
+ final InetAddress ias = serverDomains.dnsResolve(clientip);
if (ias == null) {
prop.put("message", "cannot resolve your IP from your reported location " + clientip);
return prop;
@@ -192,7 +192,7 @@ public final class hello {
// attach other seeds
if (ySeeds != null) {
seeds.ensureCapacity((ySeeds.size() + 1) * 768);
- Iterator<yacySeed> si = ySeeds.values().iterator();
+ final Iterator<yacySeed> si = ySeeds.values().iterator();
yacySeed s;
String seedString;
while (si.hasNext()) {
@@ -203,7 +203,7 @@ public final class hello {
seeds.append("seed").append(count).append('=').append(seedString).append(serverCore.CRLF_STRING);
count++;
}
- } catch (ConcurrentModificationException e) {
+ } catch (final ConcurrentModificationException e) {
e.printStackTrace();
}
}
diff --git a/htroot/yacy/list.java b/htroot/yacy/list.java
index 35b3ebe1d..efa35370b 100644
--- a/htroot/yacy/list.java
+++ b/htroot/yacy/list.java
@@ -40,9 +40,9 @@ import de.anomic.yacy.yacySeed;
public final class list {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
if (post == null || env == null) throw new NullPointerException("post: " + post + ", sb: " + env);
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
// return variable that accumulates replacements
final serverObjects prop = new serverObjects();
@@ -54,7 +54,7 @@ public final class list {
String otherPeerName = null;
if (post.containsKey("iam")) {
- yacySeed bla = sb.webIndex.seedDB.get(post.get("iam", ""));
+ final yacySeed bla = sb.webIndex.seedDB.get(post.get("iam", ""));
if (bla != null) otherPeerName = bla.getName();
}
if (otherPeerName == null) otherPeerName = header.get(httpHeader.CONNECTION_PROP_CLIENTIP);
@@ -72,8 +72,8 @@ public final class list {
if (filenamesarray.length > 0){
for (int i = 0;i < filenamesarray.length; i++) {
- String filename = filenamesarray[i];
- File fileObj = new File(listsPath,filename);
+ final String filename = filenamesarray[i];
+ final File fileObj = new File(listsPath,filename);
out.append(listManager.getListString(fileObj, false)).append(serverCore.CRLF_STRING);
}
}
diff --git a/htroot/yacy/message.java b/htroot/yacy/message.java
index dd09b6750..813174070 100644
--- a/htroot/yacy/message.java
+++ b/htroot/yacy/message.java
@@ -49,29 +49,29 @@ import de.anomic.yacy.yacySeed;
public final class message {
private static SimpleDateFormat SimpleFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
- public static String dateString(Date date) {
+ public static String dateString(final Date date) {
return SimpleFormatter.format(date);
}
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
if (post == null || env == null) { return null; }
// return variable that accumulates replacements
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
- serverObjects prop = new serverObjects();
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ final serverObjects prop = new serverObjects();
if ((post == null) || (env == null)) return prop;
if (!yacyNetwork.authentifyRequest(post, env)) return prop;
- String process = post.get("process", "permission");
- String key = post.get("key", "");
+ final String process = post.get("process", "permission");
+ final String key = post.get("key", "");
- int messagesize = 10240;
- int attachmentsize = 0;
+ final int messagesize = 10240;
+ final int attachmentsize = 0;
prop.put("messagesize", "0");
prop.put("attachmentsize", "0");
- String youare = post.get("youare", ""); // seed hash of the target peer, needed for network stability
+ final String youare = post.get("youare", ""); // seed hash of the target peer, needed for network stability
// check if we are the right target and requester has correct information about this peer
if ((sb.webIndex.seedDB.mySeed() == null) || (!(sb.webIndex.seedDB.mySeed().hash.equals(youare)))) {
// this request has a wrong target
@@ -99,13 +99,13 @@ public final class message {
if (process.equals("post")) {
// post: post message to message board
- String otherSeedString = post.get("myseed", "");
+ final String otherSeedString = post.get("myseed", "");
if (otherSeedString.length() == 0) {
prop.put("response", "-1"); // request rejected
return prop;
}
//Date remoteTime = yacyCore.parseUniversalDate((String) post.get(yacySeed.MYTIME)); // read remote time
- yacySeed otherSeed = yacySeed.genRemoteSeed(otherSeedString, key, false);
+ final yacySeed otherSeed = yacySeed.genRemoteSeed(otherSeedString, key, false);
String subject = crypt.simpleDecode(post.get("subject", ""), key); // message's subject
String message = crypt.simpleDecode(post.get("message", ""), key); // message body
@@ -127,7 +127,7 @@ public final class message {
byte[] mb;
try {
mb = message.getBytes("UTF-8");
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
mb = message.getBytes();
}
sb.messageDB.write(msgEntry = sb.messageDB.newEntry(
@@ -139,11 +139,11 @@ public final class message {
messageForwardingViaEmail(sb, msgEntry);
// finally write notification
- File notifierSource = new File(sb.getRootPath(), sb.getConfig("htRootPath","htroot") + "/env/grafics/message.gif");
- File notifierDest = new File(sb.getConfigPath("htDocsPath", "DATA/HTDOCS"), "notifier.gif");
+ final File notifierSource = new File(sb.getRootPath(), sb.getConfig("htRootPath","htroot") + "/env/grafics/message.gif");
+ final File notifierDest = new File(sb.getConfigPath("htDocsPath", "DATA/HTDOCS"), "notifier.gif");
try {
serverFileUtils.copy(notifierSource, notifierDest);
- } catch (IOException e) {
+ } catch (final IOException e) {
serverLog.logSevere("MESSAGE", "NEW MESSAGE ARRIVED! (error: " + e.getMessage() + ")");
}
@@ -162,19 +162,19 @@ public final class message {
#[message]#
*/
- private static void messageForwardingViaEmail(plasmaSwitchboard sb, messageBoard.entry msgEntry) {
+ private static void messageForwardingViaEmail(final plasmaSwitchboard sb, final messageBoard.entry msgEntry) {
try {
if (!Boolean.valueOf(sb.getConfig("msgForwardingEnabled","false")).booleanValue()) return;
// getting the recipient address
- String sendMailTo = sb.getConfig("msgForwardingTo","root@localhost").trim();
+ final String sendMailTo = sb.getConfig("msgForwardingTo","root@localhost").trim();
// getting the sendmail configuration
- String sendMailStr = sb.getConfig("msgForwardingCmd","/usr/bin/sendmail")+" "+sendMailTo;
- String[] sendMail = sendMailStr.trim().split(" ");
+ final String sendMailStr = sb.getConfig("msgForwardingCmd","/usr/bin/sendmail")+" "+sendMailTo;
+ final String[] sendMail = sendMailStr.trim().split(" ");
// building the message text
- StringBuffer emailTxt = new StringBuffer();
+ final StringBuffer emailTxt = new StringBuffer();
emailTxt.append("To: ")
.append(sendMailTo)
.append("\nFrom: ")
@@ -198,11 +198,11 @@ public final class message {
.append("\n===================================================================\n")
.append(new String(msgEntry.message()));
- Process process=Runtime.getRuntime().exec(sendMail);
- PrintWriter email = new PrintWriter(process.getOutputStream());
+ final Process process=Runtime.getRuntime().exec(sendMail);
+ final PrintWriter email = new PrintWriter(process.getOutputStream());
email.print(new String(emailTxt));
email.close();
- } catch (Exception e) {
+ } catch (final Exception e) {
yacyCore.log.logWarning("message: message forwarding via email failed. ",e);
}
diff --git a/htroot/yacy/profile.java b/htroot/yacy/profile.java
index 7e4b27d06..498efc878 100644
--- a/htroot/yacy/profile.java
+++ b/htroot/yacy/profile.java
@@ -43,10 +43,10 @@ import de.anomic.yacy.yacyNetwork;
public final class profile {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
// return variable that accumulates replacements
- serverObjects prop = new serverObjects();
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ final serverObjects prop = new serverObjects();
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
if ((post == null) || (env == null)) return prop;
if (!yacyNetwork.authentifyRequest(post, env)) return prop;
@@ -58,7 +58,7 @@ public final class profile {
return prop;
}
- Properties profile = new Properties();
+ final Properties profile = new Properties();
int count=0;
String key="";
String value="";
@@ -67,12 +67,12 @@ public final class profile {
try {
fileIn = new FileInputStream(new File("DATA/SETTINGS/profile.txt"));
profile.load(fileIn);
- } catch(IOException e) {
+ } catch(final IOException e) {
} finally {
- if (fileIn != null) try { fileIn.close(); fileIn = null; } catch (Exception e) {}
+ if (fileIn != null) try { fileIn.close(); fileIn = null; } catch (final Exception e) {}
}
- Iterator<Object> it = profile.keySet().iterator();
+ final Iterator<Object> it = profile.keySet().iterator();
while (it.hasNext()) {
key = (String) it.next();
value=profile.getProperty(key, "").replaceAll("\r","").replaceAll("\n","\\\\n");
diff --git a/htroot/yacy/query.java b/htroot/yacy/query.java
index e08ada7c0..d91b7b41e 100644
--- a/htroot/yacy/query.java
+++ b/htroot/yacy/query.java
@@ -39,7 +39,7 @@ public final class query {
// example:
// http://localhost:8080/yacy/query.html?youare=sCJ6Tq8T0N9x&object=lurlcount
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> ss) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> ss) {
if (post == null || ss == null) { return null; }
// return variable that accumulates replacements
diff --git a/htroot/yacy/search.java b/htroot/yacy/search.java
index ab83b0658..8693a1028 100644
--- a/htroot/yacy/search.java
+++ b/htroot/yacy/search.java
@@ -60,15 +60,15 @@ import de.anomic.yacy.yacyURL;
public final class search {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
// return variable that accumulates replacements
final plasmaSwitchboard sb = (plasmaSwitchboard) env;
sb.remoteSearchLastAccess = System.currentTimeMillis();
- serverObjects prop = new serverObjects();
+ final serverObjects prop = new serverObjects();
if ((post == null) || (env == null)) return prop;
if (!yacyNetwork.authentifyRequest(post, env)) return prop;
- String client = header.get(httpHeader.CONNECTION_PROP_CLIENTIP);
+ final String client = header.get(httpHeader.CONNECTION_PROP_CLIENTIP);
//System.out.println("yacy: search received request = " + post.toString());
@@ -77,8 +77,8 @@ public final class search {
final String key = post.get("key", ""); // transmission key for response
final String query = post.get("query", ""); // a string of word hashes that shall be searched and combined
final String exclude= post.get("exclude", "");// a string of word hashes that shall not be within the search result
- String urls = post.get("urls", ""); // a string of url hashes that are preselected for the search: no other may be returned
- String abstracts = post.get("abstracts", ""); // a string of word hashes for abstracts that shall be generated, or 'auto' (for maxcount-word), or '' (for none)
+ final String urls = post.get("urls", ""); // a string of url hashes that are preselected for the search: no other may be returned
+ final String abstracts = post.get("abstracts", ""); // a string of word hashes for abstracts that shall be generated, or 'auto' (for maxcount-word), or '' (for none)
// final String fwdep = post.get("fwdep", ""); // forward depth. if "0" then peer may NOT ask another peer for more results
// final String fwden = post.get("fwden", ""); // forward deny, a list of seed hashes. They may NOT be target of forward hopping
final int count = Math.min(100, post.getInt("count", 10)); // maximum number of wanted results
@@ -128,15 +128,15 @@ public final class search {
if (trackerHandles.tailSet(new Long(System.currentTimeMillis() - 6000)).size() > 1) try {
Thread.sleep(3000);
block = true;
- } catch (InterruptedException e) { e.printStackTrace(); }
+ } catch (final InterruptedException e) { e.printStackTrace(); }
if (trackerHandles.tailSet(new Long(System.currentTimeMillis() - 60000)).size() > 12) try {
Thread.sleep(10000);
block = true;
- } catch (InterruptedException e) { e.printStackTrace(); }
+ } catch (final InterruptedException e) { e.printStackTrace(); }
if (trackerHandles.tailSet(new Long(System.currentTimeMillis() - 600000)).size() > 36) try {
Thread.sleep(30000);
block = true;
- } catch (InterruptedException e) { e.printStackTrace(); }
+ } catch (final InterruptedException e) { e.printStackTrace(); }
if (block) {
prop.put("links", "");
prop.put("linkcount", "0");
@@ -147,10 +147,10 @@ public final class search {
// tell all threads to do nothing for a specific time
sb.intermissionAllThreads(3000);
- TreeSet<String> abstractSet = ((abstracts.length() == 0) || (abstracts.equals("auto"))) ? null : plasmaSearchQuery.hashes2Set(abstracts);
+ final TreeSet<String> abstractSet = ((abstracts.length() == 0) || (abstracts.equals("auto"))) ? null : plasmaSearchQuery.hashes2Set(abstracts);
// store accessing peer
- yacySeed remoteSeed = yacySeed.genRemoteSeed(oseed, key, false);
+ final yacySeed remoteSeed = yacySeed.genRemoteSeed(oseed, key, false);
if (sb.webIndex.seedDB == null) {
yacyCore.log.logSevere("yacy.search: seed cache not initialized");
} else {
@@ -163,10 +163,10 @@ public final class search {
final long timestamp = System.currentTimeMillis();
// prepare a search profile
- plasmaSearchRankingProfile rankingProfile = (profile.length() == 0) ? new plasmaSearchRankingProfile(plasmaSearchQuery.contentdomParser(contentdom)) : new plasmaSearchRankingProfile("", profile);
+ final plasmaSearchRankingProfile rankingProfile = (profile.length() == 0) ? new plasmaSearchRankingProfile(plasmaSearchQuery.contentdomParser(contentdom)) : new plasmaSearchRankingProfile("", profile);
// prepare an abstract result
- StringBuffer indexabstract = new StringBuffer();
+ final StringBuffer indexabstract = new StringBuffer();
int indexabstractContainercount = 0;
int joincount = 0;
plasmaSearchQuery theQuery = null;
@@ -178,17 +178,17 @@ public final class search {
theQuery.domType = plasmaSearchQuery.SEARCHDOM_LOCAL;
yacyCore.log.logInfo("INIT HASH SEARCH (abstracts only): " + plasmaSearchQuery.anonymizedQueryHashes(theQuery.queryHashes) + " - " + theQuery.displayResults() + " links");
- long timer = System.currentTimeMillis();
- Map<String, indexContainer>[] containers = sb.webIndex.localSearchContainers(theQuery, plasmaSearchQuery.hashes2Set(urls));
+ final long timer = System.currentTimeMillis();
+ final Map<String, indexContainer>[] containers = sb.webIndex.localSearchContainers(theQuery, plasmaSearchQuery.hashes2Set(urls));
serverProfiling.update("SEARCH", new plasmaProfiling.searchEvent(theQuery.id(true), plasmaSearchEvent.COLLECTION, containers[0].size(), System.currentTimeMillis() - timer));
if (containers != null) {
- Iterator<Map.Entry<String, indexContainer>> ci = containers[0].entrySet().iterator();
+ final Iterator<Map.Entry<String, indexContainer>> ci = containers[0].entrySet().iterator();
Map.Entry<String, indexContainer> entry;
String wordhash;
while (ci.hasNext()) {
entry = ci.next();
wordhash = entry.getKey();
- indexContainer container = entry.getValue();
+ final indexContainer container = entry.getValue();
indexabstractContainercount += container.size();
indexabstract.append("indexabstract." + wordhash + "=").append(indexContainer.compressIndex(container, null, 1000).toString()).append(serverCore.CRLF_STRING);
}
@@ -214,16 +214,16 @@ public final class search {
prop.put("joincount", "0");
} else {
// attach information about index abstracts
- StringBuffer indexcount = new StringBuffer();
+ final StringBuffer indexcount = new StringBuffer();
Map.Entry<String, Integer> entry;
- Iterator<Map.Entry<String, Integer>> i = theSearch.IACount.entrySet().iterator();
+ final Iterator<Map.Entry<String, Integer>> i = theSearch.IACount.entrySet().iterator();
while (i.hasNext()) {
entry = i.next();
indexcount.append("indexcount.").append(entry.getKey()).append('=').append((entry.getValue()).toString()).append(serverCore.CRLF_STRING);
}
if (abstractSet != null) {
// if a specific index-abstract is demanded, attach it here
- Iterator<String> j = abstractSet.iterator();
+ final Iterator<String> j = abstractSet.iterator();
String wordhash;
while (j.hasNext()) {
wordhash = j.next();
@@ -264,10 +264,10 @@ public final class search {
if (partitions > 0) sb.requestedQueries = sb.requestedQueries + 1d / partitions; // increase query counter
// prepare reference hints
- long timer = System.currentTimeMillis();
- Set<String> ws = theSearch.references(10);
- StringBuffer refstr = new StringBuffer();
- Iterator<String> j = ws.iterator();
+ final long timer = System.currentTimeMillis();
+ final Set<String> ws = theSearch.references(10);
+ final StringBuffer refstr = new StringBuffer();
+ final Iterator<String> j = ws.iterator();
while (j.hasNext()) {
refstr.append(",").append(j.next());
}
@@ -286,8 +286,8 @@ public final class search {
} else {
// result is a List of urlEntry elements
- long timer = System.currentTimeMillis();
- StringBuffer links = new StringBuffer();
+ final long timer = System.currentTimeMillis();
+ final StringBuffer links = new StringBuffer();
String resource = null;
kelondroSortStack<plasmaSearchEvent.ResultEntry>.stackElement entry;
for (int i = 0; i < accu.size(); i++) {
diff --git a/htroot/yacy/transfer.java b/htroot/yacy/transfer.java
index 7af2ac845..6270f55cf 100644
--- a/htroot/yacy/transfer.java
+++ b/htroot/yacy/transfer.java
@@ -40,17 +40,17 @@ import de.anomic.yacy.yacySeed;
public final class transfer {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
- serverObjects prop = new serverObjects();
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ final serverObjects prop = new serverObjects();
if ((post == null) || (env == null)) return prop;
if (!yacyNetwork.authentifyRequest(post, env)) return prop;
- String process = post.get("process", ""); // permission or store
+ final String process = post.get("process", ""); // permission or store
//String key = post.get("key", ""); // a transmission key from the client
- String otherpeer = post.get("iam", ""); // identification of the client (a peer-hash)
- String purpose = post.get("purpose", ""); // declares how the file shall be treated
- String filename = post.get("filename", ""); // a name of a file without path
+ final String otherpeer = post.get("iam", ""); // identification of the client (a peer-hash)
+ final String purpose = post.get("purpose", ""); // declares how the file shall be treated
+ final String filename = post.get("filename", ""); // a name of a file without path
//long filesize = Long.parseLong((String) post.get("filesize", "")); // the size of the file
prop.put("process", "0");
@@ -66,7 +66,7 @@ public final class transfer {
return prop;
}
- yacySeed otherseed = sb.webIndex.seedDB.get(otherpeer);
+ final yacySeed otherseed = sb.webIndex.seedDB.get(otherpeer);
if ((otherseed == null) || (filename.indexOf("..") >= 0)) {
// reject unknown peers: this does not appear fair, but anonymous senders are dangerous
// reject paths that contain '..' because they are dangerous
@@ -75,7 +75,7 @@ public final class transfer {
return prop;
}
- String otherpeerName = otherseed.hash + ":" + otherseed.getName();
+ final String otherpeerName = otherseed.hash + ":" + otherseed.getName();
if (process.equals("permission")) {
prop.put("process", "0");
@@ -83,7 +83,7 @@ public final class transfer {
// consolidation of cr files
//System.out.println("yacy/transfer:post=" + post.toString());
//String cansendprotocol = (String) post.get("can-send-protocol", "http");
- String access = kelondroBase64Order.enhancedCoder.encode(serverCodings.encodeMD5Raw(otherpeer + ":" + filename)) + ":" + kelondroBase64Order.enhancedCoder.encode(serverCodings.encodeMD5Raw("" + System.currentTimeMillis()));
+ final String access = kelondroBase64Order.enhancedCoder.encode(serverCodings.encodeMD5Raw(otherpeer + ":" + filename)) + ":" + kelondroBase64Order.enhancedCoder.encode(serverCodings.encodeMD5Raw("" + System.currentTimeMillis()));
prop.put("response", "ok");
prop.put("process_access", access);
prop.put("process_address", sb.webIndex.seedDB.mySeed().getPublicAddress());
@@ -99,12 +99,12 @@ public final class transfer {
if (process.equals("store")) {
prop.put("process", "1");
if (purpose.equals("crcon")) {
- String fileString = post.get("filename$file");
- String accesscode = post.get("access", ""); // one-time authentication
- String md5 = post.get("md5", ""); // one-time authentication
+ final String fileString = post.get("filename$file");
+ final String accesscode = post.get("access", ""); // one-time authentication
+ final String md5 = post.get("md5", ""); // one-time authentication
//java.util.HashMap perm = sb.rankingPermissions;
//System.out.println("PERMISSIONDEBUG: accesscode=" + accesscode + ", permissions=" + perm.toString());
- String grantedFile = sb.rankingPermissions.get(accesscode);
+ final String grantedFile = sb.rankingPermissions.get(accesscode);
prop.put("process_tt", "");
if ((grantedFile == null) || (!(grantedFile.equals(filename)))) {
// fraud-access of this interface
@@ -112,13 +112,13 @@ public final class transfer {
sb.getLog().logFine("RankingTransmission: denied " + otherpeerName + " to send CR file " + filename + ": wrong access code");
} else {
sb.rankingPermissions.remove(accesscode); // not needed any more
- File path = new File(sb.rankingPath, plasmaRankingDistribution.CR_OTHER);
+ final File path = new File(sb.rankingPath, plasmaRankingDistribution.CR_OTHER);
path.mkdirs();
- File file = new File(path, filename);
+ final File file = new File(path, filename);
try {
if (file.getCanonicalPath().toString().startsWith(path.getCanonicalPath().toString())){
serverFileUtils.copy(fileString.getBytes(), file);
- String md5t = serverCodings.encodeMD5Hex(file);
+ final String md5t = serverCodings.encodeMD5Hex(file);
if (md5t.equals(md5)) {
prop.put("response", "ok");
sb.getLog().logFine("RankingTransmission: received from peer " + otherpeerName + " CR file " + filename);
@@ -131,7 +131,7 @@ public final class transfer {
prop.put("response", "io error");
return prop;
}
- } catch (IOException e) {
+ } catch (final IOException e) {
prop.put("response", "io error");
}
}
diff --git a/htroot/yacy/transferRWI.java b/htroot/yacy/transferRWI.java
index 68b66afa5..fbf64ac00 100644
--- a/htroot/yacy/transferRWI.java
+++ b/htroot/yacy/transferRWI.java
@@ -48,7 +48,7 @@ import de.anomic.yacy.yacySeed;
public final class transferRWI {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) throws InterruptedException {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) throws InterruptedException {
// return variable that accumulates replacements
final plasmaSwitchboard sb = (plasmaSwitchboard) env;
@@ -66,15 +66,15 @@ public final class transferRWI {
final int entryc = post.getInt("entryc", 0); // number of entries in indexes
byte[] indexes = post.get("indexes", "").getBytes(); // the indexes, as list of word entries
boolean granted = sb.getConfig("allowReceiveIndex", "false").equals("true");
- boolean blockBlacklist = sb.getConfig("indexReceiveBlockBlacklist", "false").equals("true");
- boolean checkLimit = sb.getConfigBool("indexDistribution.transferRWIReceiptLimitEnabled", true);
+ final boolean blockBlacklist = sb.getConfig("indexReceiveBlockBlacklist", "false").equals("true");
+ final boolean checkLimit = sb.getConfigBool("indexDistribution.transferRWIReceiptLimitEnabled", true);
final long cachelimit = sb.getConfigLong("indexDistribution.dhtReceiptLimit", 10000);
final yacySeed otherPeer = sb.webIndex.seedDB.get(iam);
final String otherPeerName = iam + ":" + ((otherPeer == null) ? "NULL" : (otherPeer.getName() + "/" + otherPeer.getVersion()));
// response values
String result = "ok";
- StringBuffer unknownURLs = new StringBuffer();
+ final StringBuffer unknownURLs = new StringBuffer();
int pause = 10000;
if ((youare == null) || (!youare.equals(sb.webIndex.seedDB.mySeed().hash))) {
@@ -121,11 +121,11 @@ public final class transferRWI {
indexRWIRowEntry iEntry;
final HashSet<String> unknownURL = new HashSet<String>();
final HashSet<String> knownURL = new HashSet<String>();
- String[] wordhashes = new String[v.size()];
+ final String[] wordhashes = new String[v.size()];
int received = 0;
int blocked = 0;
int receivedURL = 0;
- Iterator<String> i = v.iterator();
+ final Iterator<String> i = v.iterator();
while (i.hasNext()) {
serverCore.checkInterruption();
estring = i.next();
@@ -160,7 +160,7 @@ public final class transferRWI {
unknownURL.add(urlHash);
}
receivedURL++;
- } catch (Exception ex) {
+ } catch (final Exception ex) {
sb.getLog().logWarning(
"transferRWI: DB-Error while trying to determine if URL with hash '" +
urlHash + "' is known.", ex);
diff --git a/htroot/yacy/transferURL.java b/htroot/yacy/transferURL.java
index 98df2de49..0fba80c53 100644
--- a/htroot/yacy/transferURL.java
+++ b/htroot/yacy/transferURL.java
@@ -46,10 +46,10 @@ import de.anomic.yacy.yacySeed;
public final class transferURL {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) throws InterruptedException {
- long start = System.currentTimeMillis();
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) throws InterruptedException {
+ final long start = System.currentTimeMillis();
long freshdate = 0;
- try {freshdate = serverDate.parseShortDay("20061101").getTime();} catch (ParseException e1) {}
+ try {freshdate = serverDate.parseShortDay("20061101").getTime();} catch (final ParseException e1) {}
// return variable that accumulates replacements
final plasmaSwitchboard sb = (plasmaSwitchboard) env;
@@ -105,7 +105,7 @@ public final class transferURL {
}
// check if entry is well-formed
- indexURLReference.Components comp = lEntry.comp();
+ final indexURLReference.Components comp = lEntry.comp();
if (comp.url() == null) {
yacyCore.log.logWarning("transferURL: received invalid URL from peer " + otherPeerName + "\n\tURL Property: " + urls);
blocked++;
@@ -128,7 +128,7 @@ public final class transferURL {
}
// check if the entry is in our network domain
- String urlRejectReason = sb.acceptURL(comp.url());
+ final String urlRejectReason = sb.acceptURL(comp.url());
if (urlRejectReason != null) {
yacyCore.log.logFine("transferURL: blocked URL '" + comp.url() + "' (" + urlRejectReason + ") from peer " + otherPeerName);
lEntry = null;
@@ -142,7 +142,7 @@ public final class transferURL {
sb.crawlResults.stack(lEntry, iam, iam, 3);
yacyCore.log.logFine("transferURL: received URL '" + comp.url().toNormalform(false, true) + "' from peer " + otherPeerName);
received++;
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
}
diff --git a/htroot/yacy/ui/ymarks.java b/htroot/yacy/ui/ymarks.java
index b86c08a9f..df3092355 100644
--- a/htroot/yacy/ui/ymarks.java
+++ b/htroot/yacy/ui/ymarks.java
@@ -67,7 +67,7 @@ public class ymarks {
final static boolean TAGS = false;
final static boolean FOLDERS = true;
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
int max_count = 1000;
int start=0;
@@ -75,7 +75,7 @@ public class ymarks {
String username="";
prop.clear();
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
user = sb.userDB.getUser(header);
isAdmin=(sb.verifyAuthentication(header, true) || user!= null && user.hasRight(userDB.Entry.BOOKMARK_RIGHT));
@@ -117,7 +117,7 @@ public class ymarks {
prop.put("AUTHENTICATE","admin log-in");
}
}else if(post.containsKey("mode")){
- String mode=post.get("mode");
+ final String mode=post.get("mode");
if(mode.equals("add")){
prop.put("mode", "2");
}else if(mode.equals("importxml")){
@@ -126,17 +126,17 @@ public class ymarks {
prop.put("mode", "4");
}
}else if(post.containsKey("add")){ //add an Entry
- String url=post.get("url");
- String title=post.get("title");
- String description=post.get("description");
+ final String url=post.get("url");
+ final String title=post.get("title");
+ final String description=post.get("description");
String tagsString = post.get("tags");
- String pathString = post.get("path");
+ final String pathString = post.get("path");
tagsString=tagsString+","+pathString;
if(tagsString.equals("")){
tagsString="unsorted"; //default tag
}
- Set<String> tags=listManager.string2set(bookmarksDB.cleanTagsString(tagsString));
- bookmarksDB.Bookmark bookmark = sb.bookmarksDB.createBookmark(url, username);
+ final Set<String> tags=listManager.string2set(bookmarksDB.cleanTagsString(tagsString));
+ final bookmarksDB.Bookmark bookmark = sb.bookmarksDB.createBookmark(url, username);
if(bookmark != null){
bookmark.setProperty(bookmarksDB.Bookmark.BOOKMARK_TITLE, title);
bookmark.setProperty(bookmarksDB.Bookmark.BOOKMARK_DESCRIPTION, description);
@@ -160,7 +160,7 @@ public class ymarks {
//ERROR
}
}else if(post.containsKey("edit")){
- String urlHash=post.get("edit");
+ final String urlHash=post.get("edit");
prop.put("mode", "2");
if (urlHash.length() == 0) {
prop.put("mode_edit", "0"); // create mode
@@ -172,13 +172,13 @@ public class ymarks {
prop.put("mode_public", "0");
prop.put("mode_feed", "0");
} else {
- bookmarksDB.Bookmark bookmark = sb.bookmarksDB.getBookmark(urlHash);
+ final bookmarksDB.Bookmark bookmark = sb.bookmarksDB.getBookmark(urlHash);
if (bookmark == null) {
// try to get the bookmark from the LURL database
- indexURLReference urlentry = sb.webIndex.getURL(urlHash, null, 0);
+ final indexURLReference urlentry = sb.webIndex.getURL(urlHash, null, 0);
plasmaParserDocument document = null;
if (urlentry != null) {
- indexURLReference.Components comp = urlentry.comp();
+ final indexURLReference.Components comp = urlentry.comp();
document = plasmaSnippetCache.retrieveDocument(comp.url(), true, 5000, true, true);
prop.put("mode_edit", "0"); // create mode
prop.put("mode_url", comp.url().toNormalform(false, true));
@@ -222,9 +222,9 @@ public class ymarks {
}
serverLog.logInfo("BOOKMARKS", "I try to import bookmarks from HTML-file");
try {
- File file=new File(post.get("htmlfile"));
+ final File file=new File(post.get("htmlfile"));
sb.bookmarksDB.importFromBookmarks(new yacyURL(file) , post.get("htmlfile$file"), tags, isPublic);
- } catch (MalformedURLException e) {}
+ } catch (final MalformedURLException e) {}
serverLog.logInfo("BOOKMARKS", "success!!");
}else if(post.containsKey("xmlfile")){
boolean isPublic=false;
@@ -233,7 +233,7 @@ public class ymarks {
}
sb.bookmarksDB.importFromXML(post.get("xmlfile$file"), isPublic);
}else if(post.containsKey("delete")){
- String urlHash=post.get("delete");
+ final String urlHash=post.get("delete");
sb.bookmarksDB.removeBookmark(urlHash);
}
if(post.containsKey("tag")){
@@ -301,7 +301,7 @@ public class ymarks {
tagsIt=tags.iterator();
tagCount=0;
while (tagsIt.hasNext()) {
- String tname = tagsIt.next();
+ final String tname = tagsIt.next();
if ((!tname.startsWith("/")) && (!tname.equals(""))) {
prop.put("bookmarks_"+count+"_tags_"+tagCount+"_tag", tname);
tagCount++;
@@ -345,7 +345,7 @@ public class ymarks {
return prop; // return from serverObjects respond()
}
- private static void printTagList(plasmaSwitchboard sb, String id, String tagName, int comp, int max, boolean opt){
+ private static void printTagList(final plasmaSwitchboard sb, final String id, final String tagName, final int comp, final int max, final boolean opt){
int count=0;
bookmarksDB.Tag tag;
Iterator<Tag> it = null;
@@ -377,7 +377,7 @@ public class ymarks {
prop.put(id, count);
}
- private static int recurseFolders(plasmaSwitchboard sb, Iterator<String> it, String root, int count, boolean next, String prev){
+ private static int recurseFolders(final plasmaSwitchboard sb, final Iterator<String> it, String root, int count, final boolean next, final String prev){
String fn="";
bookmarksDB.Bookmark bookmark;
@@ -397,7 +397,7 @@ public class ymarks {
if(fn.startsWith(root)){
prop.put("folderlist_"+count+"_folder", "<li>"+fn.replaceFirst(root+"/*","")+"<ul class=\"folder\">");
count++;
- Iterator<String> bit=sb.bookmarksDB.getBookmarksIterator(fn, isAdmin);
+ final Iterator<String> bit=sb.bookmarksDB.getBookmarksIterator(fn, isAdmin);
while(bit.hasNext()){
bookmark=sb.bookmarksDB.getBookmark(bit.next());
prop.put("folderlist_"+count+"_folder", "<li><a href=\""+bookmark.getUrl()+"\" title=\""+bookmark.getDescription()+"\">"+ bookmark.getTitle()+"</a></li>");
@@ -416,9 +416,9 @@ public class ymarks {
return count;
}
- private static void publishNews(plasmaSwitchboard sb, String url, String title, String description, String tagsString) {
+ private static void publishNews(final plasmaSwitchboard sb, final String url, final String title, final String description, final String tagsString) {
// create a news message
- HashMap<String, String> map = new HashMap<String, String>();
+ final HashMap<String, String> map = new HashMap<String, String>();
map.put("url", url.replace(',', '|'));
map.put("title", title.replace(',', ' '));
map.put("description", description.replace(',', ' '));
diff --git a/htroot/yacy/urls.java b/htroot/yacy/urls.java
index 4e83fc4fb..6268b61cf 100644
--- a/htroot/yacy/urls.java
+++ b/htroot/yacy/urls.java
@@ -40,11 +40,11 @@ import de.anomic.yacy.yacyURL;
public class urls {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
- plasmaSwitchboard sb = (plasmaSwitchboard) env;
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
+ final plasmaSwitchboard sb = (plasmaSwitchboard) env;
// insert default values
- serverObjects prop = new serverObjects();
+ final serverObjects prop = new serverObjects();
prop.put("iam", sb.webIndex.seedDB.mySeed().hash);
prop.put("response", "rejected - insufficient call parameters");
prop.put("channel_title", "");
@@ -57,7 +57,7 @@ public class urls {
if (post.get("call", "").equals("remotecrawl")) {
// perform a remote crawl url handover
- int stackType = NoticedURL.STACK_TYPE_LIMIT;
+ final int stackType = NoticedURL.STACK_TYPE_LIMIT;
int count = Math.min(100, post.getInt("count", 0));
int c = 0;
CrawlEntry entry;
@@ -65,7 +65,7 @@ public class urls {
while ((count > 0) && (sb.crawlQueues.noticeURL.stackSize(stackType) > 0)) {
try {
entry = sb.crawlQueues.noticeURL.pop(stackType, false);
- } catch (IOException e) {
+ } catch (final IOException e) {
break;
}
if (entry == null) break;
@@ -100,9 +100,9 @@ public class urls {
if (post.get("call", "").equals("urlhashlist")) {
// retrieve a list of urls from the LURL-db by a given list of url hashes
- String urlhashes = post.get("hashes", "");
+ final String urlhashes = post.get("hashes", "");
if (urlhashes.length() % 12 != 0) return prop;
- int count = urlhashes.length() / 12;
+ final int count = urlhashes.length() / 12;
int c = 0;
indexURLReference entry;
indexURLReference.Components comp;
diff --git a/htroot/yacy/user/sidebar_history.java b/htroot/yacy/user/sidebar_history.java
index efbeefb9f..c1096ce14 100644
--- a/htroot/yacy/user/sidebar_history.java
+++ b/htroot/yacy/user/sidebar_history.java
@@ -35,16 +35,16 @@ import de.anomic.server.serverSwitch;
public class sidebar_history {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
final plasmaSwitchboard sb = (plasmaSwitchboard) env;
final serverObjects prop = new serverObjects();
// list search history
- Iterator<plasmaSearchQuery> i = sb.localSearches.iterator();
- String client = header.get(httpHeader.CONNECTION_PROP_CLIENTIP);
+ final Iterator<plasmaSearchQuery> i = sb.localSearches.iterator();
+ final String client = header.get(httpHeader.CONNECTION_PROP_CLIENTIP);
plasmaSearchQuery query;
int c = 0;
- HashSet<String> visibleQueries = new HashSet<String>();
+ final HashSet<String> visibleQueries = new HashSet<String>();
while (i.hasNext()) {
query = i.next();
if (query.resultcount == 0) continue;
diff --git a/htroot/yacy/user/sidebar_navigation.java b/htroot/yacy/user/sidebar_navigation.java
index 8304a21d0..56c44d48c 100644
--- a/htroot/yacy/user/sidebar_navigation.java
+++ b/htroot/yacy/user/sidebar_navigation.java
@@ -42,25 +42,25 @@ public class sidebar_navigation {
private static final int MAX_TOPWORDS = 24;
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
final serverObjects prop = new serverObjects();
- String eventID = post.get("eventID", "");
- boolean rss = post.get("rss", "false").equals("true");
+ final String eventID = post.get("eventID", "");
+ final boolean rss = post.get("rss", "false").equals("true");
// default settings for blank item
prop.put("navigation", "0");
prop.put("rssreferences", "0");
// find search event
- plasmaSearchEvent theSearch = plasmaSearchEvent.getEvent(eventID);
+ final plasmaSearchEvent theSearch = plasmaSearchEvent.getEvent(eventID);
if (theSearch == null) {
// the event does not exist, show empty page
return prop;
}
- plasmaSearchQuery theQuery = theSearch.getQuery();
- int offset = theQuery.neededResults() - theQuery.displayResults();
- int totalcount = theSearch.getRankingResult().getLocalResourceSize() + theSearch.getRankingResult().getRemoteResourceSize();
+ final plasmaSearchQuery theQuery = theSearch.getQuery();
+ final int offset = theQuery.neededResults() - theQuery.displayResults();
+ final int totalcount = theSearch.getRankingResult().getLocalResourceSize() + theSearch.getRankingResult().getRemoteResourceSize();
// attach the bottom line with search references (topwords)
final Set<String> references = theSearch.references(20);
@@ -68,7 +68,7 @@ public class sidebar_navigation {
// get the topwords
final TreeSet<String> topwords = new TreeSet<String>(kelondroNaturalOrder.naturalComparator);
String tmp = "";
- Iterator<String> i = references.iterator();
+ final Iterator<String> i = references.iterator();
while (i.hasNext()) {
tmp = i.next();
if (tmp.matches("[a-z]+")) {
@@ -149,13 +149,13 @@ public class sidebar_navigation {
prop.put("navigation_languagezone", (z) ? "1" : "0");
// compose page navigation
- StringBuffer resnav = new StringBuffer();
- int thispage = offset / theQuery.displayResults();
+ final StringBuffer resnav = new StringBuffer();
+ final int thispage = offset / theQuery.displayResults();
if (thispage == 0) resnav.append("&lt;&nbsp;"); else {
resnav.append(navurla(thispage - 1, theQuery));
resnav.append("<strong>&lt;</strong></a>&nbsp;");
}
- int numberofpages = Math.min(10, Math.max(thispage + 2, totalcount / theQuery.displayResults()));
+ final int numberofpages = Math.min(10, Math.max(thispage + 2, totalcount / theQuery.displayResults()));
for (int j = 0; j < numberofpages; j++) {
if (j == thispage) {
resnav.append("<strong>");
@@ -177,7 +177,7 @@ public class sidebar_navigation {
return prop;
}
- private static String navurla(int page, plasmaSearchQuery theQuery) {
+ private static String navurla(final int page, final plasmaSearchQuery theQuery) {
return
"<a href=\"ysearch.html?search=" + theQuery.queryString(true) +
"&amp;count="+ theQuery.displayResults() +
@@ -190,7 +190,7 @@ public class sidebar_navigation {
"&amp;former=" + theQuery.queryString(true) + "\">";
}
- private static void domzone(serverObjects prop, String zonename, int zonecount, plasmaSearchQuery theQuery) {
+ private static void domzone(final serverObjects prop, final String zonename, final int zonecount, final plasmaSearchQuery theQuery) {
prop.put("navigation_languagezone_" + zonename + "_count", zonecount);
prop.putHTML("navigation_languagezone_" + zonename + "_search", theQuery.queryString.replace(' ', '+'));
prop.put("navigation_languagezone_" + zonename + "_offset", "0");
diff --git a/htroot/yacy/user/ysearch.java b/htroot/yacy/user/ysearch.java
index 1167c65e2..d5ee8b5de 100644
--- a/htroot/yacy/user/ysearch.java
+++ b/htroot/yacy/user/ysearch.java
@@ -49,25 +49,25 @@ import de.anomic.yacy.yacyURL;
*/
public class ysearch {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
final plasmaSwitchboard sb = (plasmaSwitchboard) env;
sb.localSearchLastAccess = System.currentTimeMillis();
- boolean searchAllowed = sb.getConfigBool("publicSearchpage", true) || sb.verifyAuthentication(header, false);
- boolean authenticated = sb.adminAuthenticated(header) >= 2;
+ final boolean searchAllowed = sb.getConfigBool("publicSearchpage", true) || sb.verifyAuthentication(header, false);
+ final boolean authenticated = sb.adminAuthenticated(header) >= 2;
int display = (post == null) ? 0 : post.getInt("display", 0);
if ((display == 1) && (!authenticated)) display = 0;
- int input = (post == null) ? 2 : post.getInt("input", 2);
+ final int input = (post == null) ? 2 : post.getInt("input", 2);
String promoteSearchPageGreeting = env.getConfig("promoteSearchPageGreeting", "");
if (env.getConfigBool("promoteSearchPageGreeting.useNetworkName", false)) promoteSearchPageGreeting = env.getConfig("network.unit.description", "");
if (promoteSearchPageGreeting.length() == 0) promoteSearchPageGreeting = "P2P WEB SEARCH";
- String client = header.get(httpHeader.CONNECTION_PROP_CLIENTIP); // the search client who initiated the search
+ final String client = header.get(httpHeader.CONNECTION_PROP_CLIENTIP); // the search client who initiated the search
// get query
String querystring = (post == null) ? "" : post.get("search", "").trim();
final serverObjects prop = new serverObjects();
- boolean rss = (post == null) ? false : post.get("rss", "false").equals("true");
+ final boolean rss = (post == null) ? false : post.get("rss", "false").equals("true");
if ((post == null) || (env == null) || (querystring.length() == 0) || (!searchAllowed)) {
// we create empty entries for template strings
prop.put("searchagain", "0");
@@ -129,7 +129,7 @@ public class ysearch {
constraint.set(plasmaCondenser.flag_cat_indexof, true);
}
- int domainzone = (post == null ? yacyURL.TLD_any_zone_filter : post.getInt("zone", yacyURL.TLD_any_zone_filter));
+ final int domainzone = (post == null ? yacyURL.TLD_any_zone_filter : post.getInt("zone", yacyURL.TLD_any_zone_filter));
// SEARCH
//final boolean indexDistributeGranted = sb.getConfig(plasmaSwitchboard.INDEX_DIST_ALLOW, "true").equals("true");
@@ -142,7 +142,7 @@ public class ysearch {
if (clustersearch) global = true; // switches search on, but search target is limited to cluster nodes
// find search domain
- int contentdomCode = plasmaSearchQuery.contentdomParser((post == null ? "text" : post.get("contentdom", "text")));
+ final int contentdomCode = plasmaSearchQuery.contentdomParser((post == null ? "text" : post.get("contentdom", "text")));
// patch until better search profiles are available
if ((contentdomCode != plasmaSearchQuery.CONTENTDOM_TEXT) && (itemsPerPage <= 32)) itemsPerPage = 32;
@@ -154,19 +154,19 @@ public class ysearch {
if (trackerHandles.tailSet(new Long(System.currentTimeMillis() - 3000)).size() > 1) try {
Thread.sleep(3000);
block = true;
- } catch (InterruptedException e) { e.printStackTrace(); }
+ } catch (final InterruptedException e) { e.printStackTrace(); }
if (trackerHandles.tailSet(new Long(System.currentTimeMillis() - 60000)).size() > 12) try {
Thread.sleep(10000);
block = true;
- } catch (InterruptedException e) { e.printStackTrace(); }
+ } catch (final InterruptedException e) { e.printStackTrace(); }
if (trackerHandles.tailSet(new Long(System.currentTimeMillis() - 600000)).size() > 36) try {
Thread.sleep(30000);
block = true;
- } catch (InterruptedException e) { e.printStackTrace(); }
+ } catch (final InterruptedException e) { e.printStackTrace(); }
if ((!block) && (post == null || post.get("cat", "href").equals("href"))) {
- plasmaSearchRankingProfile ranking = sb.getRanking();
+ final plasmaSearchRankingProfile ranking = sb.getRanking();
final TreeSet<String>[] query = plasmaSearchQuery.cleanQuery(querystring); // converts also umlaute
if ((query[0].contains("near")) && (querystring.indexOf("NEAR") >= 0)) {
query[0].remove("near");
@@ -188,8 +188,8 @@ public class ysearch {
final boolean globalsearch = (global) && (yacyonline) && (sb.getConfigBool(plasmaSwitchboard.INDEX_RECEIVE_ALLOW, false));
// do the search
- TreeSet<String> queryHashes = indexWord.words2hashes(query[0]);
- plasmaSearchQuery theQuery = new plasmaSearchQuery(
+ final TreeSet<String> queryHashes = indexWord.words2hashes(query[0]);
+ final plasmaSearchQuery theQuery = new plasmaSearchQuery(
querystring,
queryHashes,
indexWord.words2hashes(query[1]),
@@ -221,14 +221,14 @@ public class ysearch {
// log
serverLog.logInfo("LOCAL_SEARCH", "INIT WORD SEARCH: " + theQuery.queryString + ":" + theQuery.queryHashes + " - " + theQuery.neededResults() + " links to be computed, " + theQuery.displayResults() + " lines to be displayed");
RSSFeed.channels(RSSFeed.LOCALSEARCH).addMessage(new RSSMessage("Local Search Request", theQuery.queryString, ""));
- long timestamp = System.currentTimeMillis();
+ final long timestamp = System.currentTimeMillis();
// create a new search event
if (plasmaSearchEvent.getEvent(theQuery.id(false)) == null) {
theQuery.setOffset(0); // in case that this is a new search, always start without a offset
offset = 0;
}
- plasmaSearchEvent theSearch = plasmaSearchEvent.getEvent(theQuery, ranking, sb.webIndex, sb.crawlResults, (sb.isRobinsonMode()) ? sb.clusterhashes : null, false);
+ final plasmaSearchEvent theSearch = plasmaSearchEvent.getEvent(theQuery, ranking, sb.webIndex, sb.crawlResults, (sb.isRobinsonMode()) ? sb.clusterhashes : null, false);
// generate result object
//serverLog.logFine("LOCAL_SEARCH", "SEARCH TIME AFTER ORDERING OF SEARCH RESULTS: " + (System.currentTimeMillis() - timestamp) + " ms");
@@ -253,7 +253,7 @@ public class ysearch {
trackerHandles.add(theQuery.handle);
sb.localSearchTracker.put(client, trackerHandles);
- int totalcount = theSearch.getRankingResult().getLocalResourceSize() + theSearch.getRankingResult().getRemoteResourceSize();
+ final int totalcount = theSearch.getRankingResult().getLocalResourceSize() + theSearch.getRankingResult().getRemoteResourceSize();
prop.put("num-results_offset", offset);
prop.put("num-results_itemscount", "0");
prop.put("num-results_itemsPerPage", itemsPerPage);
diff --git a/htroot/yacy/user/ysearchitem.java b/htroot/yacy/user/ysearchitem.java
index 357ff9573..41535edc0 100644
--- a/htroot/yacy/user/ysearchitem.java
+++ b/htroot/yacy/user/ysearchitem.java
@@ -49,14 +49,14 @@ public class ysearchitem {
private static final int namelength = 60;
private static final int urllength = 120;
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
final plasmaSwitchboard sb = (plasmaSwitchboard) env;
final serverObjects prop = new serverObjects();
- String eventID = post.get("eventID", "");
- boolean rss = post.get("rss", "false").equals("true");
- int item = post.getInt("item", -1);
- boolean auth = ((String) header.get(httpHeader.CONNECTION_PROP_CLIENTIP, "")).equals("localhost") || sb.verifyAuthentication(header, true);
+ final String eventID = post.get("eventID", "");
+ final boolean rss = post.get("rss", "false").equals("true");
+ final int item = post.getInt("item", -1);
+ final boolean auth = ((String) header.get(httpHeader.CONNECTION_PROP_CLIENTIP, "")).equals("localhost") || sb.verifyAuthentication(header, true);
// default settings for blank item
prop.put("content", "0");
@@ -65,13 +65,13 @@ public class ysearchitem {
prop.put("dynamic", "0");
// find search event
- plasmaSearchEvent theSearch = plasmaSearchEvent.getEvent(eventID);
+ final plasmaSearchEvent theSearch = plasmaSearchEvent.getEvent(eventID);
if (theSearch == null) {
// the event does not exist, show empty page
return prop;
}
- plasmaSearchQuery theQuery = theSearch.getQuery();
- int offset = theQuery.neededResults() - theQuery.displayResults();
+ final plasmaSearchQuery theQuery = theSearch.getQuery();
+ final int offset = theQuery.neededResults() - theQuery.displayResults();
// dynamically update count values
if (!rss) {
@@ -90,7 +90,7 @@ public class ysearchitem {
// text search
// generate result object
- plasmaSearchEvent.ResultEntry result = theSearch.oneResult(item);
+ final plasmaSearchEvent.ResultEntry result = theSearch.oneResult(item);
if (result == null) return prop; // no content
if (rss) {
@@ -108,11 +108,11 @@ public class ysearchitem {
prop.putHTML("content_description", result.title());
prop.put("content_url", result.urlstring());
- int port=result.url().getPort();
+ final int port=result.url().getPort();
yacyURL faviconURL;
try {
faviconURL = new yacyURL(result.url().getProtocol() + "://" + result.url().getHost() + ((port != -1) ? (":" + String.valueOf(port)) : "") + "/favicon.ico", null);
- } catch (MalformedURLException e1) {
+ } catch (final MalformedURLException e1) {
faviconURL = null;
}
@@ -124,16 +124,16 @@ public class ysearchitem {
prop.put("content_ybr", plasmaSearchRankingProcess.ybr(result.hash()));
prop.putNum("content_size", result.filesize());
- TreeSet<String>[] query = theQuery.queryWords();
+ final TreeSet<String>[] query = theQuery.queryWords();
yacyURL wordURL = null;
try {
prop.putHTML("content_words", URLEncoder.encode(query[0].toString(),"UTF-8"));
- } catch (UnsupportedEncodingException e) {}
+ } catch (final UnsupportedEncodingException e) {}
prop.putHTML("content_former", theQuery.queryString);
prop.put("content_rankingprops", result.word().toPropertyForm() + ", domLengthEstimated=" + yacyURL.domLengthEstimation(result.hash()) +
((yacyURL.probablyRootURL(result.hash())) ? ", probablyRootURL" : "") +
(((wordURL = yacyURL.probablyWordURL(result.hash(), query[0])) != null) ? ", probablyWordURL=" + wordURL.toNormalform(false, true) : ""));
- plasmaSnippetCache.TextSnippet snippet = result.textSnippet();
+ final plasmaSnippetCache.TextSnippet snippet = result.textSnippet();
prop.put("content_snippet", (snippet == null) ? "(snippet not found)" : snippet.getLineMarked(theQuery.queryHashes));
return prop;
}
@@ -142,7 +142,7 @@ public class ysearchitem {
// image search; shows thumbnails
prop.put("content", theQuery.contentdom + 1); // switch on specific content
- plasmaSnippetCache.MediaSnippet ms = theSearch.oneImage(item);
+ final plasmaSnippetCache.MediaSnippet ms = theSearch.oneImage(item);
if (ms == null) {
prop.put("content_items", "0");
} else {
@@ -164,11 +164,11 @@ public class ysearchitem {
// any other media content
// generate result object
- plasmaSearchEvent.ResultEntry result = theSearch.oneResult(item);
+ final plasmaSearchEvent.ResultEntry result = theSearch.oneResult(item);
if (result == null) return prop; // no content
prop.put("content", theQuery.contentdom + 1); // switch on specific content
- ArrayList<plasmaSnippetCache.MediaSnippet> media = result.mediaSnippets();
+ final ArrayList<plasmaSnippetCache.MediaSnippet> media = result.mediaSnippets();
if (item == 0) col = true;
if (media != null) {
plasmaSnippetCache.MediaSnippet ms;
@@ -192,9 +192,9 @@ public class ysearchitem {
return prop;
}
- private static String shorten(String s, int length) {
+ private static String shorten(final String s, final int length) {
if (s.length() <= length) return s;
- int p = s.lastIndexOf('.');
+ final int p = s.lastIndexOf('.');
if (p < 0) return s.substring(0, length - 3) + "...";
return s.substring(0, length - (s.length() - p) - 3) + "..." + s.substring(p);
}
diff --git a/htroot/yacysearch.java b/htroot/yacysearch.java
index f3632dcf4..66526e7e1 100644
--- a/htroot/yacysearch.java
+++ b/htroot/yacysearch.java
@@ -58,27 +58,27 @@ import de.anomic.yacy.yacyURL;
public class yacysearch {
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
final plasmaSwitchboard sb = (plasmaSwitchboard) env;
sb.localSearchLastAccess = System.currentTimeMillis();
- boolean searchAllowed = sb.getConfigBool("publicSearchpage", true) || sb.verifyAuthentication(header, false);
+ final boolean searchAllowed = sb.getConfigBool("publicSearchpage", true) || sb.verifyAuthentication(header, false);
- boolean authenticated = sb.adminAuthenticated(header) >= 2;
+ final boolean authenticated = sb.adminAuthenticated(header) >= 2;
int display = (post == null) ? 0 : post.getInt("display", 0);
if ((display == 1) && (!authenticated)) display = 0;
- int input = (post == null) ? 2 : post.getInt("input", 2);
+ final int input = (post == null) ? 2 : post.getInt("input", 2);
String promoteSearchPageGreeting = env.getConfig("promoteSearchPageGreeting", "");
if (env.getConfigBool("promoteSearchPageGreeting.useNetworkName", false)) promoteSearchPageGreeting = env.getConfig("network.unit.description", "");
if (promoteSearchPageGreeting.length() == 0) promoteSearchPageGreeting = "P2P Web Search";
- String client = header.get(httpHeader.CONNECTION_PROP_CLIENTIP); // the search client who initiated the search
+ final String client = header.get(httpHeader.CONNECTION_PROP_CLIENTIP); // the search client who initiated the search
// get query
String querystring = (post == null) ? "" : post.get("query", post.get("search", "")).trim(); // SRU compliance
- boolean fetchSnippets = (post != null && post.get("verify", "false").equals("true"));
+ final boolean fetchSnippets = (post != null && post.get("verify", "false").equals("true"));
final serverObjects prop = new serverObjects();
- boolean rss = (post == null) ? false : post.get("rss", "false").equals("true");
+ final boolean rss = (post == null) ? false : post.get("rss", "false").equals("true");
prop.put("input_promoteSearchPageGreeting", promoteSearchPageGreeting);
prop.put("input_promoteSearchPageGreeting.homepage", sb.getConfig("promoteSearchPageGreeting.homepage", ""));
prop.put("input_promoteSearchPageGreeting.smallImage", sb.getConfig("promoteSearchPageGreeting.smallImage", ""));
@@ -154,7 +154,7 @@ public class yacysearch {
if (clustersearch) global = true; // switches search on, but search target is limited to cluster nodes
// find search domain
- int contentdomCode = plasmaSearchQuery.contentdomParser((post == null ? "text" : post.get("contentdom", "text")));
+ final int contentdomCode = plasmaSearchQuery.contentdomParser((post == null ? "text" : post.get("contentdom", "text")));
// patch until better search profiles are available
if ((contentdomCode != plasmaSearchQuery.CONTENTDOM_TEXT) && (itemsPerPage <= 32)) itemsPerPage = 32;
@@ -168,15 +168,15 @@ public class yacysearch {
if (trackerHandles.tailSet(new Long(System.currentTimeMillis() - 3000)).size() > 1) try {
Thread.sleep(3000);
block = true;
- } catch (InterruptedException e) { e.printStackTrace(); }
+ } catch (final InterruptedException e) { e.printStackTrace(); }
if (trackerHandles.tailSet(new Long(System.currentTimeMillis() - 60000)).size() > 12) try {
Thread.sleep(10000);
block = true;
- } catch (InterruptedException e) { e.printStackTrace(); }
+ } catch (final InterruptedException e) { e.printStackTrace(); }
if (trackerHandles.tailSet(new Long(System.currentTimeMillis() - 600000)).size() > 36) try {
Thread.sleep(30000);
block = true;
- } catch (InterruptedException e) { e.printStackTrace(); }
+ } catch (final InterruptedException e) { e.printStackTrace(); }
}
if ((!block) && (post == null || post.get("cat", "href").equals("href"))) {
@@ -186,7 +186,7 @@ public class yacysearch {
plasmaSearchEvent.cleanupEvents(true);
}
- plasmaSearchRankingProfile ranking = sb.getRanking();
+ final plasmaSearchRankingProfile ranking = sb.getRanking();
final TreeSet<String>[] query = plasmaSearchQuery.cleanQuery(querystring); // converts also umlaute
if ((query[0].contains("near")) && (querystring.indexOf("NEAR") >= 0)) {
query[0].remove("near");
@@ -215,7 +215,7 @@ public class yacysearch {
sb.webIndex.removeWordReferences(query[0], delHash);
// make new news message with negative voting
- HashMap<String, String> map = new HashMap<String, String>();
+ final HashMap<String, String> map = new HashMap<String, String>();
map.put("urlhash", delHash);
map.put("vote", "negative");
map.put("refid", "");
@@ -229,14 +229,14 @@ public class yacysearch {
return prop;
}
final String recommendHash = post.get("recommendref", ""); // urlhash
- indexURLReference urlentry = sb.webIndex.getURL(recommendHash, null, 0);
+ final indexURLReference urlentry = sb.webIndex.getURL(recommendHash, null, 0);
if (urlentry != null) {
- indexURLReference.Components comp = urlentry.comp();
+ final indexURLReference.Components comp = urlentry.comp();
plasmaParserDocument document;
document = plasmaSnippetCache.retrieveDocument(comp.url(), true, 5000, true, false);
if (document != null) {
// create a news message
- HashMap<String, String> map = new HashMap<String, String>();
+ final HashMap<String, String> map = new HashMap<String, String>();
map.put("url", comp.url().toNormalform(false, true).replace(',', '|'));
map.put("title", comp.dc_title().replace(',', ' '));
map.put("description", document.dc_title().replace(',', ' '));
@@ -253,8 +253,8 @@ public class yacysearch {
final boolean globalsearch = (global) /* && (yacyonline)*/ && (sb.getConfigBool(plasmaSwitchboard.INDEX_RECEIVE_ALLOW, false));
// do the search
- TreeSet<String> queryHashes = indexWord.words2hashes(query[0]);
- plasmaSearchQuery theQuery = new plasmaSearchQuery(
+ final TreeSet<String> queryHashes = indexWord.words2hashes(query[0]);
+ final plasmaSearchQuery theQuery = new plasmaSearchQuery(
querystring,
queryHashes,
indexWord.words2hashes(query[1]),
@@ -286,14 +286,14 @@ public class yacysearch {
// log
serverLog.logInfo("LOCAL_SEARCH", "INIT WORD SEARCH: " + theQuery.queryString + ":" + theQuery.queryHashes + " - " + theQuery.neededResults() + " links to be computed, " + theQuery.displayResults() + " lines to be displayed");
RSSFeed.channels(RSSFeed.LOCALSEARCH).addMessage(new RSSMessage("Local Search Request", theQuery.queryString, ""));
- long timestamp = System.currentTimeMillis();
+ final long timestamp = System.currentTimeMillis();
// create a new search event
if (plasmaSearchEvent.getEvent(theQuery.id(false)) == null) {
theQuery.setOffset(0); // in case that this is a new search, always start without a offset
offset = 0;
}
- plasmaSearchEvent theSearch = plasmaSearchEvent.getEvent(theQuery, ranking, sb.webIndex, sb.crawlResults, (sb.isRobinsonMode()) ? sb.clusterhashes : null, false);
+ final plasmaSearchEvent theSearch = plasmaSearchEvent.getEvent(theQuery, ranking, sb.webIndex, sb.crawlResults, (sb.isRobinsonMode()) ? sb.clusterhashes : null, false);
// generate result object
//serverLog.logFine("LOCAL_SEARCH", "SEARCH TIME AFTER ORDERING OF SEARCH RESULTS: " + (System.currentTimeMillis() - timestamp) + " ms");
@@ -318,7 +318,7 @@ public class yacysearch {
trackerHandles.add(theQuery.handle);
sb.localSearchTracker.put(client, trackerHandles);
- int totalcount = theSearch.getRankingResult().getLocalResourceSize() + theSearch.getRankingResult().getRemoteResourceSize();
+ final int totalcount = theSearch.getRankingResult().getLocalResourceSize() + theSearch.getRankingResult().getRemoteResourceSize();
prop.put("num-results_offset", offset);
prop.put("num-results_itemscount", "0");
prop.put("num-results_itemsPerPage", itemsPerPage);
@@ -330,13 +330,13 @@ public class yacysearch {
prop.put("num-results_globalresults_remotePeerCount", yFormatter.number(theSearch.getRankingResult().getRemotePeerCount(), !rss));
// compose page navigation
- StringBuffer resnav = new StringBuffer();
- int thispage = offset / theQuery.displayResults();
+ final StringBuffer resnav = new StringBuffer();
+ final int thispage = offset / theQuery.displayResults();
if (thispage == 0) resnav.append("&lt;&nbsp;"); else {
resnav.append(navurla(thispage - 1, display, theQuery));
resnav.append("<strong>&lt;</strong></a>&nbsp;");
}
- int numberofpages = Math.min(10, Math.max(thispage + 2, totalcount / theQuery.displayResults()));
+ final int numberofpages = Math.min(10, Math.max(thispage + 2, totalcount / theQuery.displayResults()));
for (int i = 0; i < numberofpages; i++) {
if (i == thispage) {
resnav.append("<strong>");
@@ -422,7 +422,7 @@ public class yacysearch {
return prop;
}
- private static String navurla(int page, int display, plasmaSearchQuery theQuery) {
+ private static String navurla(final int page, final int display, final plasmaSearchQuery theQuery) {
return
"<a href=\"yacysearch.html?display=" + display +
"&amp;search=" + theQuery.queryString(true) +
diff --git a/htroot/yacysearchitem.java b/htroot/yacysearchitem.java
index bccddbfd6..38e63ccfc 100644
--- a/htroot/yacysearchitem.java
+++ b/htroot/yacysearchitem.java
@@ -59,16 +59,16 @@ public class yacysearchitem {
private static final int urllength = 120;
private static final int MAX_TOPWORDS = 24;
- public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
+ public static serverObjects respond(final httpHeader header, final serverObjects post, final serverSwitch<?> env) {
final plasmaSwitchboard sb = (plasmaSwitchboard) env;
final serverObjects prop = new serverObjects();
- String eventID = post.get("eventID", "");
- boolean bottomline = post.get("bottomline", "false").equals("true");
- boolean rss = post.get("rss", "false").equals("true");
- boolean authenticated = sb.adminAuthenticated(header) >= 2;
- int item = post.getInt("item", -1);
- boolean auth = ((String) header.get(httpHeader.CONNECTION_PROP_CLIENTIP, "")).equals("localhost") || sb.verifyAuthentication(header, true);
+ final String eventID = post.get("eventID", "");
+ final boolean bottomline = post.get("bottomline", "false").equals("true");
+ final boolean rss = post.get("rss", "false").equals("true");
+ final boolean authenticated = sb.adminAuthenticated(header) >= 2;
+ final int item = post.getInt("item", -1);
+ final boolean auth = ((String) header.get(httpHeader.CONNECTION_PROP_CLIENTIP, "")).equals("localhost") || sb.verifyAuthentication(header, true);
// default settings for blank item
prop.put("content", "0");
@@ -78,16 +78,16 @@ public class yacysearchitem {
prop.put("dynamic", "0");
// find search event
- plasmaSearchEvent theSearch = plasmaSearchEvent.getEvent(eventID);
+ final plasmaSearchEvent theSearch = plasmaSearchEvent.getEvent(eventID);
if (theSearch == null) {
// the event does not exist, show empty page
return prop;
}
- plasmaSearchQuery theQuery = theSearch.getQuery();
+ final plasmaSearchQuery theQuery = theSearch.getQuery();
// dynamically update count values
if (!rss) {
- int offset = theQuery.neededResults() - theQuery.displayResults() + 1;
+ final int offset = theQuery.neededResults() - theQuery.displayResults() + 1;
prop.put("dynamic_offset", offset);
prop.put("dynamic_itemscount", (item < 0) ? theQuery.neededResults() : item + 1);
prop.put("dynamic_totalcount", yFormatter.number(theSearch.getRankingResult().getLocalResourceSize() + theSearch.getRankingResult().getRemoteResourceSize(), !rss));
@@ -105,7 +105,7 @@ public class yacysearchitem {
// get the topwords
final TreeSet<String> topwords = new TreeSet<String>(kelondroNaturalOrder.naturalComparator);
String tmp = "";
- Iterator<String> i = references.iterator();
+ final Iterator<String> i = references.iterator();
while (i.hasNext()) {
tmp = i.next();
if (tmp.matches("[a-z]+")) {
@@ -175,14 +175,14 @@ public class yacysearchitem {
// text search
// generate result object
- plasmaSearchEvent.ResultEntry result = theSearch.oneResult(item);
+ final plasmaSearchEvent.ResultEntry result = theSearch.oneResult(item);
if (result == null) return prop; // no content
if (rss) {
// text search for rss output
prop.put("rss", "1"); // switch on specific content
prop.putHTML("rss_title", result.title(), true);
- plasmaSnippetCache.TextSnippet snippet = result.textSnippet();
+ final plasmaSnippetCache.TextSnippet snippet = result.textSnippet();
prop.putHTML("rss_description", (snippet == null) ? "" : snippet.getLineRaw(), true);
prop.putHTML("rss_link", result.urlstring(), true);
prop.put("rss_urlhash", result.hash());
@@ -199,11 +199,11 @@ public class yacysearchitem {
prop.putHTML("content_description", result.title());
prop.put("content_url", result.urlstring());
- int port=result.url().getPort();
+ final int port=result.url().getPort();
yacyURL faviconURL;
try {
faviconURL = new yacyURL(result.url().getProtocol() + "://" + result.url().getHost() + ((port != -1) ? (":" + String.valueOf(port)) : "") + "/favicon.ico", null);
- } catch (MalformedURLException e1) {
+ } catch (final MalformedURLException e1) {
faviconURL = null;
}
@@ -215,16 +215,16 @@ public class yacysearchitem {
prop.put("content_ybr", plasmaSearchRankingProcess.ybr(result.hash()));
prop.putNum("content_size", result.filesize());
- TreeSet<String>[] query = theQuery.queryWords();
+ final TreeSet<String>[] query = theQuery.queryWords();
yacyURL wordURL = null;
try {
prop.putHTML("content_words", URLEncoder.encode(query[0].toString(),"UTF-8"));
- } catch (UnsupportedEncodingException e) {}
+ } catch (final UnsupportedEncodingException e) {}
prop.putHTML("content_former", theQuery.queryString);
prop.put("content_rankingprops", result.word().toPropertyForm() + ", domLengthEstimated=" + yacyURL.domLengthEstimation(result.hash()) +
((yacyURL.probablyRootURL(result.hash())) ? ", probablyRootURL" : "") +
(((wordURL = yacyURL.probablyWordURL(result.hash(), query[0])) != null) ? ", probablyWordURL=" + wordURL.toNormalform(false, true) : ""));
- plasmaSnippetCache.TextSnippet snippet = result.textSnippet();
+ final plasmaSnippetCache.TextSnippet snippet = result.textSnippet();
prop.put("content_snippet", (snippet == null) ? "" : snippet.getLineMarked(theQuery.queryHashes));
serverProfiling.update("SEARCH", new plasmaProfiling.searchEvent(theQuery.id(true), plasmaSearchEvent.FINALIZATION + "-" + item, 0, 0));
@@ -235,7 +235,7 @@ public class yacysearchitem {
// image search; shows thumbnails
prop.put("content", theQuery.contentdom + 1); // switch on specific content
- plasmaSnippetCache.MediaSnippet ms = theSearch.oneImage(item);
+ final plasmaSnippetCache.MediaSnippet ms = theSearch.oneImage(item);
if (ms == null) {
prop.put("content_items", "0");
} else {
@@ -257,11 +257,11 @@ public class yacysearchitem {
// any other media content
// generate result object
- plasmaSearchEvent.ResultEntry result = theSearch.oneResult(item);
+ final plasmaSearchEvent.ResultEntry result = theSearch.oneResult(item);
if (result == null) return prop; // no content
prop.put("content", theQuery.contentdom + 1); // switch on specific content
- ArrayList<plasmaSnippetCache.MediaSnippet> media = result.mediaSnippets();
+ final ArrayList<plasmaSnippetCache.MediaSnippet> media = result.mediaSnippets();
if (item == 0) col = true;
if (media != null) {
plasmaSnippetCache.MediaSnippet ms;
@@ -285,9 +285,9 @@ public class yacysearchitem {
return prop;
}
- private static String shorten(String s, int length) {
+ private static String shorten(final String s, final int length) {
if (s.length() <= length) return s;
- int p = s.lastIndexOf('.');
+ final int p = s.lastIndexOf('.');
if (p < 0) return s.substring(0, length - 3) + "...";
return s.substring(0, length - (s.length() - p) - 3) + "..." + s.substring(p);
}
diff --git a/source/dbtest.java b/source/dbtest.java
index c4c11b335..827edc2bd 100644
--- a/source/dbtest.java
+++ b/source/dbtest.java
@@ -45,12 +45,12 @@ public class dbtest {
public static byte[] randomHash(final long r0, final long r1) {
// a long can have 64 bit, but a 12-byte hash can have 6 * 12 = 72 bits
// so we construct a generic Hash using two long values
- String s = (kelondroBase64Order.enhancedCoder.encodeLong(Math.abs(r0), 6) +
+ final String s = (kelondroBase64Order.enhancedCoder.encodeLong(Math.abs(r0), 6) +
kelondroBase64Order.enhancedCoder.encodeLong(Math.abs(r1), 6));
return s.getBytes();
}
- public static byte[] randomHash(Random r) {
+ public static byte[] randomHash(final Random r) {
return randomHash(r.nextLong(), r.nextLong());
}
@@ -72,7 +72,7 @@ public class dbtest {
}
public boolean isValid() {
- String s = new String(this.value).trim();
+ final String s = new String(this.value).trim();
if (s.length() == 0) return false;
final long source = new Long(s).longValue();
return new String(this.key).equals(new String(randomHash(source, source)));
@@ -129,7 +129,7 @@ public class dbtest {
try {
getTable_test().put(getTable_test().row().newEntry(new byte[][] { entry.getKey(), entry.getValue() , entry.getValue() }));
if (getTable_reference() != null) getTable_reference().put(getTable_test().row().newEntry(new byte[][] { entry.getKey(), entry.getValue() , entry.getValue() }));
- } catch (IOException e) {
+ } catch (final IOException e) {
System.err.println(e);
e.printStackTrace();
System.exit(0);
@@ -148,7 +148,7 @@ public class dbtest {
try {
getTable_test().remove(entry.getKey());
if (getTable_reference() != null) getTable_reference().remove(entry.getKey());
- } catch (IOException e) {
+ } catch (final IOException e) {
System.err.println(e);
e.printStackTrace();
System.exit(0);
@@ -186,7 +186,7 @@ public class dbtest {
} */
}
}
- } catch (IOException e) {
+ } catch (final IOException e) {
System.err.println(e);
e.printStackTrace();
System.exit(0);
@@ -194,20 +194,20 @@ public class dbtest {
}
}
- public static kelondroIndex selectTableType(String dbe, String tablename, kelondroRow testRow) throws Exception {
+ public static kelondroIndex selectTableType(final String dbe, final String tablename, final kelondroRow testRow) throws Exception {
if (dbe.equals("kelondroRowSet")) {
return new kelondroRowSet(testRow, 0);
}
if (dbe.equals("kelondroTree")) {
- File tablefile = new File(tablename + ".kelondro.db");
+ final File tablefile = new File(tablename + ".kelondro.db");
return new kelondroCache(new kelondroTree(tablefile, true, 0, testRow));
}
if (dbe.equals("kelondroFlexTable")) {
- File tablepath = new File(tablename).getParentFile();
+ final File tablepath = new File(tablename).getParentFile();
return new kelondroFlexTable(tablepath, new File(tablename).getName(), testRow, 0, true);
}
if (dbe.equals("kelondroSplitTable")) {
- File tablepath = new File(tablename).getParentFile();
+ final File tablepath = new File(tablename).getParentFile();
return new kelondroSplitTable(tablepath, new File(tablename).getName(), testRow, true);
}
if (dbe.equals("kelondroEcoTable")) {
@@ -222,7 +222,7 @@ public class dbtest {
return null;
}
- public static boolean checkEquivalence(kelondroIndex test, kelondroIndex reference) throws IOException {
+ public static boolean checkEquivalence(final kelondroIndex test, final kelondroIndex reference) throws IOException {
if (reference == null) return true;
if (test.size() == reference.size()) {
System.out.println("* Testing equivalence of test table to reference table, " + test.size() + " entries");
@@ -235,7 +235,7 @@ public class dbtest {
Iterator<kelondroRow.Entry> i = test.rows(true, null);
System.out.println("* Testing now by enumeration over test table");
- long ts = System.currentTimeMillis();
+ final long ts = System.currentTimeMillis();
while (i.hasNext()) {
test_entry = i.next();
reference_entry = reference.get(test_entry.getPrimaryKeyBytes());
@@ -247,7 +247,7 @@ public class dbtest {
i = reference.rows(true, null);
System.out.println("* Testing now by enumeration over reference table");
- long rs = System.currentTimeMillis();
+ final long rs = System.currentTimeMillis();
while (i.hasNext()) {
reference_entry = i.next();
test_entry = test.get(reference_entry.getPrimaryKeyBytes());
@@ -262,7 +262,7 @@ public class dbtest {
return eq;
}
- public static void main(String[] args) {
+ public static void main(final String[] args) {
System.setProperty("java.awt.headless", "true");
System.out.println("*** YaCy Database Test");
@@ -270,7 +270,7 @@ public class dbtest {
boolean assertionenabled = false;
assert assertionenabled = true;
if (assertionenabled) System.out.println("*** Asserts are enabled"); else System.out.println("*** HINT: YOU SHOULD ENABLE ASSERTS! (include -ea in start arguments");
- long mb = serverMemory.available() / 1024 / 1024;
+ final long mb = serverMemory.available() / 1024 / 1024;
System.out.println("*** RAM = " + mb + " MB");
System.out.print(">java " +
((assertionenabled) ? "-ea " : "") +
@@ -280,26 +280,26 @@ public class dbtest {
System.out.println();
// read command options
- String command = args[0]; // test command
- String dbe_test = args[1]; // the database engine that shall be tested
+ final String command = args[0]; // test command
+ final String dbe_test = args[1]; // the database engine that shall be tested
String dbe_reference = args[2]; // the reference database engine (may be null)
- String tablename_test = args[3]; // name of test-table
+ final String tablename_test = args[3]; // name of test-table
if (dbe_reference.toLowerCase().equals("null")) dbe_reference = null;
- String tablename_reference = (dbe_reference == null) ? null : (tablename_test + ".reference");
+ final String tablename_reference = (dbe_reference == null) ? null : (tablename_test + ".reference");
// start test
- long startup = System.currentTimeMillis();
+ final long startup = System.currentTimeMillis();
try {
// create a memory profiler
- memprofiler profiler = new memprofiler(1024, 320, 120, new File(tablename_test + ".profile.png"));
+ final memprofiler profiler = new memprofiler(1024, 320, 120, new File(tablename_test + ".profile.png"));
profiler.start();
// create the database access
- kelondroRow testRow = new kelondroRow("byte[] key-" + keylength + ", byte[] dummy-" + keylength + ", value-" + valuelength, kelondroBase64Order.enhancedCoder, 0);
- kelondroIndex table_test = selectTableType(dbe_test, tablename_test, testRow);
- kelondroIndex table_reference = (dbe_reference == null) ? null : selectTableType(dbe_reference, tablename_reference, testRow);
+ final kelondroRow testRow = new kelondroRow("byte[] key-" + keylength + ", byte[] dummy-" + keylength + ", value-" + valuelength, kelondroBase64Order.enhancedCoder, 0);
+ final kelondroIndex table_test = selectTableType(dbe_test, tablename_test, testRow);
+ final kelondroIndex table_reference = (dbe_reference == null) ? null : selectTableType(dbe_reference, tablename_reference, testRow);
- long afterinit = System.currentTimeMillis();
+ final long afterinit = System.currentTimeMillis();
System.out.println("Test for db-engine " + dbe_test + " started to create file " + tablename_test + " with test " + command);
// execute command
@@ -312,9 +312,9 @@ public class dbtest {
// fill database with random entries;
// args: <number-of-entries> <random-startpoint>
// example: java -ea -Xmx200m fill kelondroEcoTable kelondroFlexTable filldbtest 50000 0
- long count = Long.parseLong(args[4]);
- long randomstart = Long.parseLong(args[5]);
- Random random = new Random(randomstart);
+ final long count = Long.parseLong(args[4]);
+ final long randomstart = Long.parseLong(args[5]);
+ final Random random = new Random(randomstart);
byte[] key;
kelondroProfile ioProfileAcc = new kelondroProfile();
kelondroProfile cacheProfileAcc = new kelondroProfile();
@@ -339,9 +339,9 @@ public class dbtest {
if (command.equals("read")) {
// read the database and compare with random entries;
// args: <number-of-entries> <random-startpoint>
- long count = Long.parseLong(args[4]);
- long randomstart = Long.parseLong(args[5]);
- Random random = new Random(randomstart);
+ final long count = Long.parseLong(args[4]);
+ final long randomstart = Long.parseLong(args[5]);
+ final Random random = new Random(randomstart);
kelondroRow.Entry entry;
byte[] key;
for (int i = 0; i < count; i++) {
@@ -370,8 +370,8 @@ public class dbtest {
// this is repeated without termination; after each loop
// the current ram is printed out
// args: <number-of-entries> <random-startpoint>
- long count = Long.parseLong(args[4]);
- long randomstart = Long.parseLong(args[5]);
+ final long count = Long.parseLong(args[4]);
+ final long randomstart = Long.parseLong(args[5]);
byte[] key;
Random random;
long start, write, remove;
@@ -437,16 +437,16 @@ public class dbtest {
Database size = 354 unique entries.
Execution time: open=1324, command=34032, close=1, total=35357
*/
- long writeCount = Long.parseLong(args[4]);
- long readCount = Long.parseLong(args[5]);
- long randomstart = Long.parseLong(args[6]);
+ final long writeCount = Long.parseLong(args[4]);
+ final long readCount = Long.parseLong(args[5]);
+ final long randomstart = Long.parseLong(args[6]);
final Random random = new Random(randomstart);
long r;
Long R;
int p, rc=0;
- ArrayList<Long> ra = new ArrayList<Long>();
- HashSet<Long> jcontrol = new HashSet<Long>();
- kelondroIntBytesMap kcontrol = new kelondroIntBytesMap(1, 0);
+ final ArrayList<Long> ra = new ArrayList<Long>();
+ final HashSet<Long> jcontrol = new HashSet<Long>();
+ final kelondroIntBytesMap kcontrol = new kelondroIntBytesMap(1, 0);
for (int i = 0; i < writeCount; i++) {
r = Math.abs(random.nextLong() % 1000);
jcontrol.add(new Long(r));
@@ -468,25 +468,25 @@ public class dbtest {
}
System.out.println("removed: " + rc + ", size of jcontrol set: " + jcontrol.size() + ", size of kcontrol set: " + kcontrol.size());
while (serverInstantBusyThread.instantThreadCounter > 0) {
- try {Thread.sleep(1000);} catch (InterruptedException e) {} // wait for all tasks to finish
+ try {Thread.sleep(1000);} catch (final InterruptedException e) {} // wait for all tasks to finish
System.out.println("count: " + serverInstantBusyThread.instantThreadCounter + ", jobs: " + serverInstantBusyThread.jobs.toString());
}
- try {Thread.sleep(6000);} catch (InterruptedException e) {}
+ try {Thread.sleep(6000);} catch (final InterruptedException e) {}
}
if (command.equals("stressSequential")) {
//
// args: <number-of-writes> <number-of-reads> <random-startpoint>
- long writeCount = Long.parseLong(args[4]);
- long readCount = Long.parseLong(args[5]);
- long randomstart = Long.parseLong(args[6]);
- Random random = new Random(randomstart);
+ final long writeCount = Long.parseLong(args[4]);
+ final long readCount = Long.parseLong(args[5]);
+ final long randomstart = Long.parseLong(args[6]);
+ final Random random = new Random(randomstart);
long r;
Long R;
int p, rc=0;
- ArrayList<Long> ra = new ArrayList<Long>();
- HashSet<Long> jcontrol = new HashSet<Long>();
- kelondroIntBytesMap kcontrol = new kelondroIntBytesMap(1, 0);
+ final ArrayList<Long> ra = new ArrayList<Long>();
+ final HashSet<Long> jcontrol = new HashSet<Long>();
+ final kelondroIntBytesMap kcontrol = new kelondroIntBytesMap(1, 0);
for (int i = 0; i < writeCount; i++) {
//if (i == 30) random = new Random(randomstart);
r = Math.abs(random.nextLong() % 1000);
@@ -506,13 +506,13 @@ public class dbtest {
new RemoveJob(table_test, table_reference, (ra.remove(p)).longValue()).run();
}
}
- try {Thread.sleep(1000);} catch (InterruptedException e) {}
+ try {Thread.sleep(1000);} catch (final InterruptedException e) {}
System.out.println("removed: " + rc + ", size of jcontrol set: " + jcontrol.size() + ", size of kcontrol set: " + kcontrol.size());
}
- long aftercommand = System.currentTimeMillis();
+ final long aftercommand = System.currentTimeMillis();
checkEquivalence(table_test, table_reference);
- long afterequiv = System.currentTimeMillis();
+ final long afterequiv = System.currentTimeMillis();
// final report
System.out.println("Database size = " + table_test.size() + " unique entries.");
@@ -520,7 +520,7 @@ public class dbtest {
table_test.close();
if (table_reference != null) table_reference.close();
- long afterclose = System.currentTimeMillis();
+ final long afterclose = System.currentTimeMillis();
System.out.println("Execution time: open=" + (afterinit - startup) +
", command=" + (aftercommand - afterinit) +
@@ -528,7 +528,7 @@ public class dbtest {
", close=" + (afterclose - afterequiv) +
", total=" + (afterclose - startup));
profiler.terminate();
- } catch (Exception e) {
+ } catch (final Exception e) {
e.printStackTrace();
}
}
@@ -541,12 +541,12 @@ final class memprofiler extends Thread {
File outputFile;
long start;
- public memprofiler(int width, int height, int expectedTimeSeconds, File outputFile) {
+ public memprofiler(final int width, final int height, final int expectedTimeSeconds, final File outputFile) {
this.outputFile = outputFile;
- int expectedKilobytes = 20 * 1024;//(Runtime.getRuntime().totalMemory() / 1024);
+ final int expectedKilobytes = 20 * 1024;//(Runtime.getRuntime().totalMemory() / 1024);
memChart = new ymageChart(width, height, "FFFFFF", "000000", "000000", 50, 20, 20, 20, "MEMORY CHART FROM EXECUTION AT " + new Date(), null);
- int timescale = 10; // steps with each 10 seconds
- int memscale = 1024;
+ final int timescale = 10; // steps with each 10 seconds
+ final int memscale = 1024;
memChart.declareDimension(ymageChart.DIMENSION_BOTTOM, timescale, (width - 40) * timescale / expectedTimeSeconds, 0, "FFFFFF", "555555", "SECONDS");
memChart.declareDimension(ymageChart.DIMENSION_LEFT, memscale, (height - 40) * memscale / expectedKilobytes, 0, "FFFFFF", "555555", "KILOBYTES");
run = true;
@@ -563,17 +563,17 @@ final class memprofiler extends Thread {
memChart.chartLine(ymageChart.DIMENSION_BOTTOM, ymageChart.DIMENSION_LEFT, seconds0, kilobytes0, seconds1, kilobytes1);
seconds0 = seconds1;
kilobytes0 = kilobytes1;
- try {Thread.sleep(100);} catch (InterruptedException e) {}
+ try {Thread.sleep(100);} catch (final InterruptedException e) {}
}
try {
ImageIO.write(memChart.getImage(), "png", outputFile);
- } catch (IOException e) {}
+ } catch (final IOException e) {}
}
public void terminate() {
run = false;
while (this.isAlive()) {
- try {Thread.sleep(1000);} catch (InterruptedException e) {}
+ try {Thread.sleep(1000);} catch (final InterruptedException e) {}
}
}
}
diff --git a/source/de/anomic/crawler/AbstractImporter.java b/source/de/anomic/crawler/AbstractImporter.java
index 909445637..988e1e3b9 100644
--- a/source/de/anomic/crawler/AbstractImporter.java
+++ b/source/de/anomic/crawler/AbstractImporter.java
@@ -15,7 +15,7 @@ public abstract class AbstractImporter extends Thread implements Importer {
protected long globalPauseDuration;
protected String error;
- public AbstractImporter(String theJobType) {
+ public AbstractImporter(final String theJobType) {
this.jobType = theJobType;
// initializing the logger and setting a more verbose thread name
@@ -66,7 +66,7 @@ public abstract class AbstractImporter extends Thread implements Importer {
try {
this.wait();
}
- catch (InterruptedException e){}
+ catch (final InterruptedException e){}
}
}
@@ -81,7 +81,7 @@ public abstract class AbstractImporter extends Thread implements Importer {
return this.jobID;
}
- public void setJobID(int id) {
+ public void setJobID(final int id) {
if (this.jobID != -1) throw new IllegalStateException("job ID already assigned");
this.jobID = id;
}
diff --git a/source/de/anomic/crawler/Balancer.java b/source/de/anomic/crawler/Balancer.java
index 5865c8481..1ff7427b7 100644
--- a/source/de/anomic/crawler/Balancer.java
+++ b/source/de/anomic/crawler/Balancer.java
@@ -55,14 +55,14 @@ public class Balancer {
private static final kelondroRow stackrow = new kelondroRow("byte[] urlhash-" + yacySeedDB.commonHashLength, kelondroBase64Order.enhancedCoder, 0);
// class variables
- private ArrayList<String> urlRAMStack; // a list that is flushed first
+ private final ArrayList<String> urlRAMStack; // a list that is flushed first
private kelondroStack urlFileStack; // a file with url hashes
kelondroIndex urlFileIndex;
- private HashMap<String, LinkedList<String>> domainStacks; // a map from domain name part to Lists with url hashs
- private File cacheStacksPath;
- private String stackname;
+ private final HashMap<String, LinkedList<String>> domainStacks; // a map from domain name part to Lists with url hashs
+ private final File cacheStacksPath;
+ private final String stackname;
private boolean top; // to alternate between top and bottom of the file stack
- private boolean fullram;
+ private final boolean fullram;
public static class domaccess {
long time;
@@ -83,10 +83,10 @@ public class Balancer {
}
}
- public Balancer(File cachePath, String stackname, boolean fullram) {
+ public Balancer(final File cachePath, final String stackname, final boolean fullram) {
this.cacheStacksPath = cachePath;
this.stackname = stackname;
- File stackFile = new File(cachePath, stackname + stackSuffix);
+ final File stackFile = new File(cachePath, stackname + stackSuffix);
this.urlFileStack = kelondroStack.open(stackFile, stackrow);
this.domainStacks = new HashMap<String, LinkedList<String>>();
this.urlRAMStack = new ArrayList<String>();
@@ -101,13 +101,13 @@ public class Balancer {
serverLog.logInfo("Balancer", "re-creating the " + stackname + " balancer stack, size = " + urlFileIndex.size() + ((urlFileStack.size() == urlFileIndex.size()) ? "" : " (the old stack size was wrong)" ));
urlFileStack = kelondroStack.reset(urlFileStack);
try {
- Iterator<byte[]> i = urlFileIndex.keys(true, null);
+ final Iterator<byte[]> i = urlFileIndex.keys(true, null);
byte[] hash;
while (i.hasNext()) {
hash = i.next();
pushHash(new String(hash));
}
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
}
@@ -116,7 +116,7 @@ public class Balancer {
public synchronized void close() {
while (domainStacksNotEmpty()) flushOnceDomStacks(0, true); // flush to ram, because the ram flush is optimized
size();
- try { flushAllRamStack(); } catch (IOException e) {}
+ try { flushAllRamStack(); } catch (final IOException e) {}
if (urlFileIndex != null) {
urlFileIndex.close();
urlFileIndex = null;
@@ -155,25 +155,25 @@ public class Balancer {
openFileIndex();
}
- public synchronized CrawlEntry get(String urlhash) throws IOException {
+ public synchronized CrawlEntry get(final String urlhash) throws IOException {
assert urlhash != null;
if (urlFileIndex == null) return null; // case occurs during shutdown
- kelondroRow.Entry entry = urlFileIndex.get(urlhash.getBytes());
+ final kelondroRow.Entry entry = urlFileIndex.get(urlhash.getBytes());
if (entry == null) return null;
return new CrawlEntry(entry);
}
- public synchronized int removeAllByProfileHandle(String profileHandle, long timeout) throws IOException {
+ public synchronized int removeAllByProfileHandle(final String profileHandle, final long timeout) throws IOException {
// removes all entries with a specific profile hash.
// this may last some time
// returns number of deletions
// first find a list of url hashes that shall be deleted
- Iterator<kelondroRow.Entry> i = urlFileIndex.rows(true, null);
- HashSet<String> urlHashes = new HashSet<String>();
+ final Iterator<kelondroRow.Entry> i = urlFileIndex.rows(true, null);
+ final HashSet<String> urlHashes = new HashSet<String>();
kelondroRow.Entry rowEntry;
CrawlEntry crawlEntry;
- long terminate = (timeout > 0) ? System.currentTimeMillis() + timeout : Long.MAX_VALUE;
+ final long terminate = (timeout > 0) ? System.currentTimeMillis() + timeout : Long.MAX_VALUE;
while (i.hasNext() && (System.currentTimeMillis() < terminate)) {
rowEntry = i.next();
crawlEntry = new CrawlEntry(rowEntry);
@@ -194,11 +194,11 @@ public class Balancer {
* @return number of entries that had been removed
* @throws IOException
*/
- public synchronized int remove(HashSet<String> urlHashes) throws IOException {
- int s = urlFileIndex.size();
+ public synchronized int remove(final HashSet<String> urlHashes) throws IOException {
+ final int s = urlFileIndex.size();
int removedCounter = 0;
- for (String urlhash: urlHashes) {
- kelondroRow.Entry entry = urlFileIndex.remove(urlhash.getBytes());
+ for (final String urlhash: urlHashes) {
+ final kelondroRow.Entry entry = urlFileIndex.remove(urlhash.getBytes());
if (entry != null) removedCounter++;
}
if (removedCounter == 0) return 0;
@@ -216,14 +216,14 @@ public class Balancer {
// iterate through the file stack
// in general this is a bad idea. But this can only be avoided by avoidance of this method
- Iterator<kelondroRow.Entry> j = urlFileStack.stackIterator(true);
+ final Iterator<kelondroRow.Entry> j = urlFileStack.stackIterator(true);
while (j.hasNext()) {
h = new String(j.next().getColBytes(0));
if (urlHashes.contains(h)) j.remove();
}
// iterate through the domain stacks
- Iterator<Map.Entry<String, LinkedList<String>>> k = domainStacks.entrySet().iterator();
+ final Iterator<Map.Entry<String, LinkedList<String>>> k = domainStacks.entrySet().iterator();
Map.Entry<String, LinkedList<String>> se;
LinkedList<String> stack;
while (k.hasNext()) {
@@ -239,7 +239,7 @@ public class Balancer {
return removedCounter;
}
- public synchronized boolean has(String urlhash) {
+ public synchronized boolean has(final String urlhash) {
return urlFileIndex.has(urlhash.getBytes());
}
@@ -250,7 +250,7 @@ public class Balancer {
}
public int size() {
- int componentsize = urlFileIndex.size();
+ final int componentsize = urlFileIndex.size();
/*
assert componentsize == urlFileStack.size() + urlRAMStack.size() + sizeDomainStacks() :
"size wrong in " + stackname +
@@ -266,7 +266,7 @@ public class Balancer {
private boolean domainStacksNotEmpty() {
if (domainStacks == null) return false;
synchronized (domainStacks) {
- Iterator<LinkedList<String>> i = domainStacks.values().iterator();
+ final Iterator<LinkedList<String>> i = domainStacks.values().iterator();
while (i.hasNext()) {
if (i.next().size() > 0) return true;
}
@@ -278,18 +278,18 @@ public class Balancer {
if (domainStacks == null) return 0;
int sum = 0;
synchronized (domainStacks) {
- Iterator<LinkedList<String>> i = domainStacks.values().iterator();
+ final Iterator<LinkedList<String>> i = domainStacks.values().iterator();
while (i.hasNext()) sum += i.next().size();
}
return sum;
}
- private void flushOnceDomStacks(int minimumleft, boolean ram) {
+ private void flushOnceDomStacks(final int minimumleft, final boolean ram) {
// takes one entry from every domain stack and puts it on the ram or file stack
// the minimumleft value is a limit for the number of entries that should be left
if (domainStacks.size() == 0) return;
synchronized (domainStacks) {
- Iterator<Map.Entry<String, LinkedList<String>>> i = domainStacks.entrySet().iterator();
+ final Iterator<Map.Entry<String, LinkedList<String>>> i = domainStacks.entrySet().iterator();
Map.Entry<String, LinkedList<String>> entry;
LinkedList<String> list;
while (i.hasNext()) {
@@ -300,7 +300,7 @@ public class Balancer {
urlRAMStack.add(list.removeFirst());
} else try {
urlFileStack.push(urlFileStack.row().newEntry(new byte[][] { (list.removeFirst()).getBytes() }));
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
}
@@ -319,7 +319,7 @@ public class Balancer {
urlFileStack.push(urlFileStack.row().newEntry(new byte[][]{(urlRAMStack.get(urlRAMStack.size() / 2)).getBytes()}));
}
- public synchronized void push(CrawlEntry entry) throws IOException {
+ public synchronized void push(final CrawlEntry entry) throws IOException {
assert entry != null;
if (urlFileIndex.has(entry.url().hash().getBytes())) {
serverLog.logWarning("PLASMA BALANCER", "double-check has failed for urlhash " + entry.url().hash() + " in " + stackname + " - fixed");
@@ -333,9 +333,9 @@ public class Balancer {
pushHash(entry.url().hash());
}
- private void pushHash(String hash) throws IOException {
+ private void pushHash(final String hash) throws IOException {
// extend domain stack
- String dom = hash.substring(6);
+ final String dom = hash.substring(6);
LinkedList<String> domainList = domainStacks.get(dom);
if (domainList == null) {
// create new list
@@ -355,7 +355,7 @@ public class Balancer {
}
}
- public synchronized CrawlEntry pop(long minimumLocalDelta, long minimumGlobalDelta, long maximumAge) throws IOException {
+ public synchronized CrawlEntry pop(final long minimumLocalDelta, final long minimumGlobalDelta, final long maximumAge) throws IOException {
// returns an url-hash from the stack and ensures minimum delta times
// we have 3 sources to choose from: the ramStack, the domainStacks and the fileStack
@@ -371,7 +371,7 @@ public class Balancer {
// we select specific domains that have not been used for a long time
// i.e. 60 seconds. Latest arrivals that have not yet been crawled
// fit also in that scheme
- Iterator<Map.Entry<String, LinkedList<String>>> i = domainStacks.entrySet().iterator();
+ final Iterator<Map.Entry<String, LinkedList<String>>> i = domainStacks.entrySet().iterator();
Map.Entry<String, LinkedList<String>> entry;
String domhash;
long delta, maxdelta = 0;
@@ -406,11 +406,11 @@ public class Balancer {
// we order all domains by the number of entries per domain
// then we iterate through these domains in descending entry order
// and that that one, that has a delta > minimumDelta
- Iterator<Map.Entry<String, LinkedList<String>>> i = domainStacks.entrySet().iterator();
+ final Iterator<Map.Entry<String, LinkedList<String>>> i = domainStacks.entrySet().iterator();
Map.Entry<String, LinkedList<String>> entry;
String domhash;
LinkedList<String> domlist;
- TreeMap<Integer, String> hitlist = new TreeMap<Integer, String>();
+ final TreeMap<Integer, String> hitlist = new TreeMap<Integer, String>();
int count = 0;
// first collect information about sizes of the domain lists
while (i.hasNext()) {
@@ -446,14 +446,14 @@ public class Balancer {
// 3rd: take entry from file
if ((result == null) && (urlFileStack.size() > 0)) {
- kelondroRow.Entry nextentry = (top) ? urlFileStack.top() : urlFileStack.bot();
+ final kelondroRow.Entry nextentry = (top) ? urlFileStack.top() : urlFileStack.bot();
if (nextentry == null) {
// emergency case: this means that something with the stack organization is wrong
// the file appears to be broken. We kill the file.
kelondroStack.reset(urlFileStack);
serverLog.logSevere("PLASMA BALANCER", "get() failed to fetch entry from file stack. reset stack file.");
} else {
- String nexthash = new String(nextentry.getColBytes(0));
+ final String nexthash = new String(nextentry.getColBytes(0));
// check if the time after retrieval of last hash from same
// domain is not shorter than the minimumDelta
@@ -477,10 +477,10 @@ public class Balancer {
}
// finally: check minimumDelta and if necessary force a sleep
- long delta = lastAccessDelta(result);
+ final long delta = lastAccessDelta(result);
assert delta >= 0: "delta = " + delta;
- int s = urlFileIndex.size();
- kelondroRow.Entry rowEntry = urlFileIndex.remove(result.getBytes());
+ final int s = urlFileIndex.size();
+ final kelondroRow.Entry rowEntry = urlFileIndex.remove(result.getBytes());
assert (rowEntry == null) || (urlFileIndex.size() + 1 == s) : "urlFileIndex.size() = " + urlFileIndex.size() + ", s = " + s + ", result = " + result;
if (rowEntry == null) {
serverLog.logSevere("PLASMA BALANCER", "get() found a valid urlhash, but failed to fetch the corresponding url entry - total size = " + size() + ", fileStack.size() = " + urlFileStack.size() + ", ramStack.size() = " + urlRAMStack.size() + ", domainStacks.size() = " + domainStacks.size());
@@ -488,8 +488,8 @@ public class Balancer {
} else {
assert urlFileIndex.size() + 1 == s : "urlFileIndex.size() = " + urlFileIndex.size() + ", s = " + s + ", result = " + result;
}
- CrawlEntry crawlEntry = new CrawlEntry(rowEntry);
- long genericDelta = Math.min(
+ final CrawlEntry crawlEntry = new CrawlEntry(rowEntry);
+ final long genericDelta = Math.min(
15000,
Math.max(
(crawlEntry.url().isLocal()) ? minimumLocalDelta : minimumGlobalDelta,
@@ -500,8 +500,8 @@ public class Balancer {
// in best case, this should never happen if the balancer works propertly
// this is only to protect against the worst case, where the crawler could
// behave in a DoS-manner
- long sleeptime = genericDelta - delta;
- try {synchronized(this) { this.wait(sleeptime); }} catch (InterruptedException e) {}
+ final long sleeptime = genericDelta - delta;
+ try {synchronized(this) { this.wait(sleeptime); }} catch (final InterruptedException e) {}
}
// update statistical data
@@ -512,9 +512,9 @@ public class Balancer {
return crawlEntry;
}
- private long lastAccessDelta(String hash) {
+ private long lastAccessDelta(final String hash) {
assert hash != null;
- domaccess lastAccess = domainAccess.get((hash.length() > 6) ? hash.substring(6) : hash);
+ final domaccess lastAccess = domainAccess.get((hash.length() > 6) ? hash.substring(6) : hash);
if (lastAccess == null) return Long.MAX_VALUE; // never accessed
return System.currentTimeMillis() - lastAccess.time();
}
@@ -539,16 +539,16 @@ public class Balancer {
t = urlFileStack.pot();
if (t == null) break;
urlRAMStack.add(new String(t.getColBytes(0)));
- } catch (IOException e) {
+ } catch (final IOException e) {
break;
}
}
count = Math.min(count, urlRAMStack.size());
- ArrayList<CrawlEntry> list = new ArrayList<CrawlEntry>();
+ final ArrayList<CrawlEntry> list = new ArrayList<CrawlEntry>();
for (int i = 0; i < count; i++) {
- String urlhash = urlRAMStack.get(i);
- kelondroRow.Entry entry = urlFileIndex.get(urlhash.getBytes());
+ final String urlhash = urlRAMStack.get(i);
+ final kelondroRow.Entry entry = urlFileIndex.get(urlhash.getBytes());
if (entry == null) break;
list.add(new CrawlEntry(entry));
}
@@ -572,10 +572,10 @@ public class Balancer {
}
public CrawlEntry next() {
- kelondroRow.Entry entry = rowIterator.next();
+ final kelondroRow.Entry entry = rowIterator.next();
try {
return (entry == null) ? null : new CrawlEntry(entry);
- } catch (IOException e) {
+ } catch (final IOException e) {
rowIterator = null;
return null;
}
diff --git a/source/de/anomic/crawler/CrawlEntry.java b/source/de/anomic/crawler/CrawlEntry.java
index ae0559c31..0bbab332b 100755
--- a/source/de/anomic/crawler/CrawlEntry.java
+++ b/source/de/anomic/crawler/CrawlEntry.java
@@ -90,15 +90,15 @@ public class CrawlEntry {
* @param forkfactor sum of anchors of all ancestors
*/
public CrawlEntry(
- String initiator,
- yacyURL url,
- String referrerhash,
- String name,
- Date appdate,
- String profileHandle,
- int depth,
- int anchors,
- int forkfactor
+ final String initiator,
+ final yacyURL url,
+ final String referrerhash,
+ final String name,
+ final Date appdate,
+ final String profileHandle,
+ final int depth,
+ final int anchors,
+ final int forkfactor
) {
// create new entry and store it into database
assert appdate != null;
@@ -124,13 +124,13 @@ public class CrawlEntry {
this.initialHash = url.hashCode();
}
- public CrawlEntry(kelondroRow.Entry entry) throws IOException {
+ public CrawlEntry(final kelondroRow.Entry entry) throws IOException {
assert (entry != null);
insertEntry(entry);
}
- private void insertEntry(kelondroRow.Entry entry) throws IOException {
- String urlstring = entry.getColString(2, null);
+ private void insertEntry(final kelondroRow.Entry entry) throws IOException {
+ final String urlstring = entry.getColString(2, null);
if (urlstring == null) throw new IOException ("url string is null");
this.initiator = entry.getColString(1, null);
this.url = new yacyURL(urlstring, entry.getColString(0, null));
@@ -156,7 +156,7 @@ public class CrawlEntry {
return this.initialHash;
}
- public void setStatus(String s) {
+ public void setStatus(final String s) {
this.status = s;
}
@@ -164,25 +164,25 @@ public class CrawlEntry {
return this.status;
}
- private static String normalizeHandle(int h) {
+ private static String normalizeHandle(final int h) {
String d = Integer.toHexString(h);
while (d.length() < rowdef.width(11)) d = "0" + d;
return d;
}
public kelondroRow.Entry toRow() {
- byte[] appdatestr = kelondroNaturalOrder.encodeLong(appdate, rowdef.width(5));
- byte[] loaddatestr = kelondroNaturalOrder.encodeLong(loaddate, rowdef.width(12));
- byte[] serverdatestr = kelondroNaturalOrder.encodeLong(serverdate, rowdef.width(13));
- byte[] imsdatestr = kelondroNaturalOrder.encodeLong(imsdate, rowdef.width(14));
+ final byte[] appdatestr = kelondroNaturalOrder.encodeLong(appdate, rowdef.width(5));
+ final byte[] loaddatestr = kelondroNaturalOrder.encodeLong(loaddate, rowdef.width(12));
+ final byte[] serverdatestr = kelondroNaturalOrder.encodeLong(serverdate, rowdef.width(13));
+ final byte[] imsdatestr = kelondroNaturalOrder.encodeLong(imsdate, rowdef.width(14));
// store the hash in the hash cache
byte[] namebytes;
try {
namebytes = this.name.getBytes("UTF-8");
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
namebytes = this.name.getBytes();
}
- byte[][] entry = new byte[][] {
+ final byte[][] entry = new byte[][] {
this.url.hash().getBytes(),
(initiator == null) ? "".getBytes() : this.initiator.getBytes(),
this.url.toString().getBytes(),
@@ -206,7 +206,7 @@ public class CrawlEntry {
return url;
}
- public void redirectURL(yacyURL redirectedURL) {
+ public void redirectURL(final yacyURL redirectedURL) {
// replace old URL by new one. This should only be used in case of url redirection
this.url = redirectedURL;
}
diff --git a/source/de/anomic/crawler/CrawlProfile.java b/source/de/anomic/crawler/CrawlProfile.java
index 0d40a7e5a..b11988367 100644
--- a/source/de/anomic/crawler/CrawlProfile.java
+++ b/source/de/anomic/crawler/CrawlProfile.java
@@ -45,12 +45,12 @@ public class CrawlProfile {
static HashMap<String, Map<String, DomProfile>> domsCache = new HashMap<String, Map<String, DomProfile>>();
kelondroMap profileTable;
- private File profileTableFile;
+ private final File profileTableFile;
- public CrawlProfile(File file) {
+ public CrawlProfile(final File file) {
this.profileTableFile = file;
profileTableFile.getParentFile().mkdirs();
- kelondroBLOB dyn = new kelondroBLOBTree(profileTableFile, true, true, yacySeedDB.commonHashLength, 2000, '#', kelondroNaturalOrder.naturalOrder, false, false, true);
+ final kelondroBLOB dyn = new kelondroBLOBTree(profileTableFile, true, true, yacySeedDB.commonHashLength, 2000, '#', kelondroNaturalOrder.naturalOrder, false, false, true);
profileTable = new kelondroMap(dyn, 500);
}
@@ -59,7 +59,7 @@ public class CrawlProfile {
if (profileTable != null) profileTable.close();
if (!(profileTableFile.delete())) throw new RuntimeException("cannot delete crawl profile database");
profileTableFile.getParentFile().mkdirs();
- kelondroBLOB dyn = new kelondroBLOBTree(profileTableFile, true, true, yacySeedDB.commonHashLength, 2000, '#', kelondroNaturalOrder.naturalOrder, false, false, true);
+ final kelondroBLOB dyn = new kelondroBLOBTree(profileTableFile, true, true, yacySeedDB.commonHashLength, 2000, '#', kelondroNaturalOrder.naturalOrder, false, false, true);
profileTable = new kelondroMap(dyn, 500);
}
@@ -71,11 +71,11 @@ public class CrawlProfile {
return profileTable.size();
}
- public Iterator<entry> profiles(boolean up) {
+ public Iterator<entry> profiles(final boolean up) {
// enumerates profile entries
try {
return new profileIterator(up);
- } catch (IOException e) {
+ } catch (final IOException e) {
return new HashSet<entry>().iterator();
}
}
@@ -84,14 +84,14 @@ public class CrawlProfile {
// the iterator iterates all keys, which are byte[] objects
kelondroCloneableIterator<byte[]> handleIterator;
String lastkey;
- public profileIterator(boolean up) throws IOException {
+ public profileIterator(final boolean up) throws IOException {
handleIterator = profileTable.keys(up, false);
lastkey = null;
}
public boolean hasNext() {
try {
return handleIterator.hasNext();
- } catch (kelondroException e) {
+ } catch (final kelondroException e) {
clear();
return false;
}
@@ -100,7 +100,7 @@ public class CrawlProfile {
try {
lastkey = new String(handleIterator.next());
return getEntry(lastkey);
- } catch (kelondroException e) {
+ } catch (final kelondroException e) {
clear();
return null;
}
@@ -108,35 +108,35 @@ public class CrawlProfile {
public void remove() {
if (lastkey != null) try {
removeEntry(lastkey);
- } catch (kelondroException e) {
+ } catch (final kelondroException e) {
clear();
}
}
}
- public void removeEntry(String handle) {
+ public void removeEntry(final String handle) {
try {
profileTable.remove(handle);
- } catch (IOException e) {}
+ } catch (final IOException e) {}
}
- public entry newEntry(HashMap<String, String> mem) {
- entry ne = new entry(mem);
+ public entry newEntry(final HashMap<String, String> mem) {
+ final entry ne = new entry(mem);
try {
profileTable.put(ne.handle(), ne.map());
- } catch (kelondroException e) {
+ } catch (final kelondroException e) {
clear();
try {
profileTable.put(ne.handle(), ne.map());
- } catch (IOException ee) {
+ } catch (final IOException ee) {
e.printStackTrace();
System.exit(0);
}
- } catch (IOException e) {
+ } catch (final IOException e) {
clear();
try {
profileTable.put(ne.handle(), ne.map());
- } catch (IOException ee) {
+ } catch (final IOException ee) {
e.printStackTrace();
System.exit(0);
}
@@ -144,16 +144,16 @@ public class CrawlProfile {
return ne;
}
- public entry newEntry(String name, yacyURL startURL, String generalFilter, String specificFilter,
- int generalDepth, int specificDepth,
- int recrawlIfOlder /*minutes*/, int domFilterDepth, int domMaxPages,
- boolean crawlingQ,
- boolean indexText, boolean indexMedia,
- boolean storeHTCache, boolean storeTXCache,
- boolean remoteIndexing,
- boolean xsstopw, boolean xdstopw, boolean xpstopw) {
+ public entry newEntry(final String name, final yacyURL startURL, final String generalFilter, final String specificFilter,
+ final int generalDepth, final int specificDepth,
+ final int recrawlIfOlder /*minutes*/, final int domFilterDepth, final int domMaxPages,
+ final boolean crawlingQ,
+ final boolean indexText, final boolean indexMedia,
+ final boolean storeHTCache, final boolean storeTXCache,
+ final boolean remoteIndexing,
+ final boolean xsstopw, final boolean xdstopw, final boolean xpstopw) {
- entry ne = new entry(name, startURL, generalFilter, specificFilter,
+ final entry ne = new entry(name, startURL, generalFilter, specificFilter,
generalDepth, specificDepth,
recrawlIfOlder, domFilterDepth, domMaxPages,
crawlingQ,
@@ -163,19 +163,19 @@ public class CrawlProfile {
xsstopw, xdstopw, xpstopw);
try {
profileTable.put(ne.handle(), ne.map());
- } catch (kelondroException e) {
+ } catch (final kelondroException e) {
clear();
try {
profileTable.put(ne.handle(), ne.map());
- } catch (IOException ee) {
+ } catch (final IOException ee) {
e.printStackTrace();
System.exit(0);
}
- } catch (IOException e) {
+ } catch (final IOException e) {
clear();
try {
profileTable.put(ne.handle(), ne.map());
- } catch (IOException ee) {
+ } catch (final IOException ee) {
e.printStackTrace();
System.exit(0);
}
@@ -183,18 +183,18 @@ public class CrawlProfile {
return ne;
}
- public entry getEntry(String handle) {
+ public entry getEntry(final String handle) {
HashMap<String, String> m;
try {
m = profileTable.get(handle);
- } catch (IOException e) {
+ } catch (final IOException e) {
return null;
}
if (m == null) return null;
return new entry(m);
}
- public void changeEntry(entry e, String propName, String newValue) throws IOException {
+ public void changeEntry(final entry e, final String propName, final String newValue) throws IOException {
e.mem.put(propName, newValue);
profileTable.put(e.handle(), e.mem);
}
@@ -204,7 +204,7 @@ public class CrawlProfile {
public String referrer;
public int depth, count;
- public DomProfile(String ref, int d) {
+ public DomProfile(final String ref, final int d) {
this.referrer = ref;
this.depth = d;
this.count = 1;
@@ -242,16 +242,16 @@ public class CrawlProfile {
HashMap<String, String> mem;
private Map<String, DomProfile> doms;
- public entry(String name, yacyURL startURL, String generalFilter, String specificFilter,
- int generalDepth, int specificDepth,
- int recrawlIfOlder /*minutes*/, int domFilterDepth, int domMaxPages,
- boolean crawlingQ,
- boolean indexText, boolean indexMedia,
- boolean storeHTCache, boolean storeTXCache,
- boolean remoteIndexing,
- boolean xsstopw, boolean xdstopw, boolean xpstopw) {
+ public entry(final String name, final yacyURL startURL, final String generalFilter, final String specificFilter,
+ final int generalDepth, final int specificDepth,
+ final int recrawlIfOlder /*minutes*/, final int domFilterDepth, final int domMaxPages,
+ final boolean crawlingQ,
+ final boolean indexText, final boolean indexMedia,
+ final boolean storeHTCache, final boolean storeTXCache,
+ final boolean remoteIndexing,
+ final boolean xsstopw, final boolean xdstopw, final boolean xpstopw) {
if (name == null || name.length() == 0) throw new NullPointerException("name must not be null");
- String handle = (startURL == null) ? kelondroBase64Order.enhancedCoder.encode(serverCodings.encodeMD5Raw(Long.toString(System.currentTimeMillis()))).substring(0, yacySeedDB.commonHashLength) : startURL.hash();
+ final String handle = (startURL == null) ? kelondroBase64Order.enhancedCoder.encode(serverCodings.encodeMD5Raw(Long.toString(System.currentTimeMillis()))).substring(0, yacySeedDB.commonHashLength) : startURL.hash();
mem = new HashMap<String, String>();
mem.put(HANDLE, handle);
mem.put(NAME, name);
@@ -277,7 +277,7 @@ public class CrawlProfile {
}
public String toString() {
- StringBuffer str = new StringBuffer();
+ final StringBuffer str = new StringBuffer();
if (this.mem != null) {
str.append(this.mem.toString());
@@ -286,7 +286,7 @@ public class CrawlProfile {
return str.toString();
}
- public entry(HashMap<String, String> mem) {
+ public entry(final HashMap<String, String> mem) {
this.mem = mem;
this.doms = domsCache.get(this.mem.get(HANDLE));
if (this.doms == null) this.doms = new HashMap<String, DomProfile>();
@@ -296,49 +296,49 @@ public class CrawlProfile {
return mem;
}
public String handle() {
- String r = mem.get(HANDLE);
+ final String r = mem.get(HANDLE);
if (r == null) return null; else return r;
}
public String name() {
- String r = mem.get(NAME);
+ final String r = mem.get(NAME);
if (r == null) return ""; else return r;
}
public String startURL() {
- String r = mem.get(START_URL);
+ final String r = mem.get(START_URL);
if (r == null) return null; else return r;
}
public String generalFilter() {
- String r = mem.get(GENERAL_FILTER);
+ final String r = mem.get(GENERAL_FILTER);
if (r == null) return ".*"; else return r;
}
public String specificFilter() {
- String r = mem.get(SPECIFIC_FILTER);
+ final String r = mem.get(SPECIFIC_FILTER);
if (r == null) return ".*"; else return r;
}
public int generalDepth() {
- String r = mem.get(GENERAL_DEPTH);
+ final String r = mem.get(GENERAL_DEPTH);
if (r == null) return 0; else try {
return Integer.parseInt(r);
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
return 0;
}
}
public int specificDepth() {
- String r = mem.get(SPECIFIC_DEPTH);
+ final String r = mem.get(SPECIFIC_DEPTH);
if (r == null) return 0; else try {
return Integer.parseInt(r);
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
return 0;
}
}
public long recrawlIfOlder() {
// returns a long (millis) that is the minimum age that
// an antry must have to be re-crawled
- String r = mem.get(RECRAWL_IF_OLDER);
+ final String r = mem.get(RECRAWL_IF_OLDER);
if (r == null) return Long.MAX_VALUE; else try {
- long l = Long.parseLong(r) * 60000L;
+ final long l = Long.parseLong(r) * 60000L;
return (l < 0) ? Long.MAX_VALUE : l;
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
return Long.MAX_VALUE;
}
}
@@ -346,66 +346,66 @@ public class CrawlProfile {
// if the depth is equal or less to this depth,
// then the current url feeds with its domain the crawl filter
// if this is -1, all domains are feeded
- String r = mem.get(DOM_FILTER_DEPTH);
+ final String r = mem.get(DOM_FILTER_DEPTH);
if (r == null) return Integer.MAX_VALUE; else try {
- int i = Integer.parseInt(r);
+ final int i = Integer.parseInt(r);
if (i < 0) return Integer.MAX_VALUE;
return i;
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
return Integer.MAX_VALUE;
}
}
public int domMaxPages() {
// this is the maximum number of pages that are crawled for a single domain
// if -1, this means no limit
- String r = mem.get(DOM_MAX_PAGES);
+ final String r = mem.get(DOM_MAX_PAGES);
if (r == null) return Integer.MAX_VALUE; else try {
- int i = Integer.parseInt(r);
+ final int i = Integer.parseInt(r);
if (i < 0) return Integer.MAX_VALUE;
return i;
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
return Integer.MAX_VALUE;
}
}
public boolean crawlingQ() {
- String r = mem.get(CRAWLING_Q);
+ final String r = mem.get(CRAWLING_Q);
if (r == null) return false; else return (r.equals(Boolean.TRUE.toString()));
}
public boolean indexText() {
- String r = mem.get(INDEX_TEXT);
+ final String r = mem.get(INDEX_TEXT);
if (r == null) return true; else return (r.equals(Boolean.TRUE.toString()));
}
public boolean indexMedia() {
- String r = mem.get(INDEX_MEDIA);
+ final String r = mem.get(INDEX_MEDIA);
if (r == null) return true; else return (r.equals(Boolean.TRUE.toString()));
}
public boolean storeHTCache() {
- String r = mem.get(STORE_HTCACHE);
+ final String r = mem.get(STORE_HTCACHE);
if (r == null) return false; else return (r.equals(Boolean.TRUE.toString()));
}
public boolean storeTXCache() {
- String r = mem.get(STORE_TXCACHE);
+ final String r = mem.get(STORE_TXCACHE);
if (r == null) return false; else return (r.equals(Boolean.TRUE.toString()));
}
public boolean remoteIndexing() {
- String r = mem.get(REMOTE_INDEXING);
+ final String r = mem.get(REMOTE_INDEXING);
if (r == null) return false; else return (r.equals(Boolean.TRUE.toString()));
}
public boolean excludeStaticStopwords() {
- String r = mem.get(XSSTOPW);
+ final String r = mem.get(XSSTOPW);
if (r == null) return false; else return (r.equals(Boolean.TRUE.toString()));
}
public boolean excludeDynamicStopwords() {
- String r = mem.get(XDSTOPW);
+ final String r = mem.get(XDSTOPW);
if (r == null) return false; else return (r.equals(Boolean.TRUE.toString()));
}
public boolean excludeParentStopwords() {
- String r = mem.get(XPSTOPW);
+ final String r = mem.get(XPSTOPW);
if (r == null) return false; else return (r.equals(Boolean.TRUE.toString()));
}
- public void domInc(String domain, String referrer, int depth) {
+ public void domInc(final String domain, final String referrer, final int depth) {
synchronized (domain.intern()) {
- DomProfile dp = doms.get(domain);
+ final DomProfile dp = doms.get(domain);
if (dp == null) {
// new domain
doms.put(domain, new DomProfile(referrer, depth));
@@ -417,11 +417,11 @@ public class CrawlProfile {
}
domsCache.put(this.mem.get(HANDLE), doms);
}
- public boolean grantedDomAppearance(String domain) {
- int max = domFilterDepth();
+ public boolean grantedDomAppearance(final String domain) {
+ final int max = domFilterDepth();
if (max == Integer.MAX_VALUE) return true;
synchronized (domain.intern()) {
- DomProfile dp = doms.get(domain);
+ final DomProfile dp = doms.get(domain);
if (dp == null) {
return 0 < max;
} else {
@@ -430,11 +430,11 @@ public class CrawlProfile {
}
}
- public boolean grantedDomCount(String domain) {
- int max = domMaxPages();
+ public boolean grantedDomCount(final String domain) {
+ final int max = domMaxPages();
if (max == Integer.MAX_VALUE) return true;
synchronized (domain.intern()) {
- DomProfile dp = doms.get(domain);
+ final DomProfile dp = doms.get(domain);
if (dp == null) {
return 0 < max;
} else {
@@ -445,13 +445,13 @@ public class CrawlProfile {
public int domSize() {
return doms.size();
}
- public boolean domExists(String domain) {
+ public boolean domExists(final String domain) {
if (domFilterDepth() == Integer.MAX_VALUE) return true;
return doms.containsKey(domain);
}
- public String domName(boolean attr, int index){
- Iterator<Map.Entry<String, DomProfile>> domnamesi = doms.entrySet().iterator();
+ public String domName(final boolean attr, final int index){
+ final Iterator<Map.Entry<String, DomProfile>> domnamesi = doms.entrySet().iterator();
String domname="";
Map.Entry<String, DomProfile> ey;
DomProfile dp;
diff --git a/source/de/anomic/crawler/CrawlQueues.java b/source/de/anomic/crawler/CrawlQueues.java
index f871fd874..721a7965b 100644
--- a/source/de/anomic/crawler/CrawlQueues.java
+++ b/source/de/anomic/crawler/CrawlQueues.java
@@ -54,12 +54,12 @@ public class CrawlQueues {
serverLog log;
Map<Integer, crawlWorker> workers; // mapping from url hash to Worker thread object
ProtocolLoader loader;
- private ArrayList<String> remoteCrawlProviderHashes;
+ private final ArrayList<String> remoteCrawlProviderHashes;
public NoticedURL noticeURL;
public ZURL errorURL, delegatedURL;
- public CrawlQueues(plasmaSwitchboard sb, File plasmaPath) {
+ public CrawlQueues(final plasmaSwitchboard sb, final File plasmaPath) {
this.sb = sb;
this.log = new serverLog("CRAWLER");
this.workers = new ConcurrentHashMap<Integer, crawlWorker>();
@@ -70,7 +70,7 @@ public class CrawlQueues {
log.logConfig("Starting Crawling Management");
noticeURL = new NoticedURL(plasmaPath);
//errorURL = new plasmaCrawlZURL(); // fresh error DB each startup; can be hold in RAM and reduces IO;
- File errorDBFile = new File(plasmaPath, "urlError2.db");
+ final File errorDBFile = new File(plasmaPath, "urlError2.db");
if (errorDBFile.exists()) {
// delete the error db to get a fresh each time on startup
// this is useful because there is currently no re-use of the data in this table.
@@ -80,35 +80,35 @@ public class CrawlQueues {
delegatedURL = new ZURL(plasmaPath, "urlDelegated2.db", true);
}
- public String urlExists(String hash) {
+ public String urlExists(final String hash) {
// tests if hash occurrs in any database
// if it exists, the name of the database is returned,
// if it not exists, null is returned
if (noticeURL.existsInStack(hash)) return "crawler";
if (delegatedURL.exists(hash)) return "delegated";
if (errorURL.exists(hash)) return "errors";
- for (crawlWorker worker: workers.values()) {
+ for (final crawlWorker worker: workers.values()) {
if (worker.entry.url().hash().equals(hash)) return "worker";
}
return null;
}
- public void urlRemove(String hash) {
+ public void urlRemove(final String hash) {
noticeURL.removeByURLHash(hash);
delegatedURL.remove(hash);
errorURL.remove(hash);
}
- public yacyURL getURL(String urlhash) {
+ public yacyURL getURL(final String urlhash) {
assert urlhash != null;
if (urlhash == null || urlhash.length() == 0) return null;
- CrawlEntry ne = noticeURL.get(urlhash);
+ final CrawlEntry ne = noticeURL.get(urlhash);
if (ne != null) return ne.url();
ZURL.Entry ee = delegatedURL.getEntry(urlhash);
if (ee != null) return ee.url();
ee = errorURL.getEntry(urlhash);
if (ee != null) return ee.url();
- for (crawlWorker w: workers.values()) {
+ for (final crawlWorker w: workers.values()) {
if (w.entry.url().hash().equals(urlhash)) return w.entry.url();
}
return null;
@@ -116,7 +116,7 @@ public class CrawlQueues {
public void clear() {
// wait for all workers to finish
- for (crawlWorker w: workers.values()) {
+ for (final crawlWorker w: workers.values()) {
w.interrupt();
}
// TODO: wait some more time until all threads are finished
@@ -125,19 +125,19 @@ public class CrawlQueues {
noticeURL.clear();
try {
errorURL.clear();
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
try {
delegatedURL.clear();
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
}
public void close() {
// wait for all workers to finish
- for (crawlWorker w: workers.values()) {
+ for (final crawlWorker w: workers.values()) {
w.interrupt();
}
// TODO: wait some more time until all threads are finished
@@ -148,14 +148,14 @@ public class CrawlQueues {
public CrawlEntry[] activeWorkerEntries() {
synchronized (workers) {
- CrawlEntry[] e = new CrawlEntry[workers.size()];
+ final CrawlEntry[] e = new CrawlEntry[workers.size()];
int i = 0;
- for (crawlWorker w: workers.values()) e[i++] = w.entry;
+ for (final crawlWorker w: workers.values()) e[i++] = w.entry;
return e;
}
}
- public boolean isSupportedProtocol(String protocol) {
+ public boolean isSupportedProtocol(final String protocol) {
return loader.isSupportedProtocol(protocol);
}
@@ -165,13 +165,13 @@ public class CrawlQueues {
public boolean coreCrawlJob() {
- boolean robinsonPrivateCase = ((sb.isRobinsonMode()) &&
+ final boolean robinsonPrivateCase = ((sb.isRobinsonMode()) &&
(!sb.getConfig(plasmaSwitchboard.CLUSTER_MODE, "").equals(plasmaSwitchboard.CLUSTER_MODE_PUBLIC_CLUSTER)) &&
(!sb.getConfig(plasmaSwitchboard.CLUSTER_MODE, "").equals(plasmaSwitchboard.CLUSTER_MODE_PRIVATE_CLUSTER)));
if (((robinsonPrivateCase) || (coreCrawlJobSize() <= 20)) && (limitCrawlJobSize() > 0)) {
// move some tasks to the core crawl job so we have something to do
- int toshift = Math.min(10, limitCrawlJobSize()); // this cannot be a big number because the balancer makes a forced waiting if it cannot balance
+ final int toshift = Math.min(10, limitCrawlJobSize()); // this cannot be a big number because the balancer makes a forced waiting if it cannot balance
for (int i = 0; i < toshift; i++) {
noticeURL.shift(NoticedURL.STACK_TYPE_LIMIT, NoticedURL.STACK_TYPE_CORE);
}
@@ -198,38 +198,38 @@ public class CrawlQueues {
}
// if crawling was paused we have to wait until we wer notified to continue
- Object[] status = sb.crawlJobsStatus.get(plasmaSwitchboard.CRAWLJOB_LOCAL_CRAWL);
+ final Object[] status = sb.crawlJobsStatus.get(plasmaSwitchboard.CRAWLJOB_LOCAL_CRAWL);
synchronized(status[plasmaSwitchboard.CRAWLJOB_SYNC]) {
if (((Boolean)status[plasmaSwitchboard.CRAWLJOB_STATUS]).booleanValue()) {
try {
status[plasmaSwitchboard.CRAWLJOB_SYNC].wait();
}
- catch (InterruptedException e) {return false;}
+ catch (final InterruptedException e) {return false;}
}
}
// do a local crawl
CrawlEntry urlEntry = null;
while (urlEntry == null && noticeURL.stackSize(NoticedURL.STACK_TYPE_CORE) > 0) {
- String stats = "LOCALCRAWL[" + noticeURL.stackSize(NoticedURL.STACK_TYPE_CORE) + ", " + noticeURL.stackSize(NoticedURL.STACK_TYPE_LIMIT) + ", " + noticeURL.stackSize(NoticedURL.STACK_TYPE_OVERHANG) + ", " + noticeURL.stackSize(NoticedURL.STACK_TYPE_REMOTE) + "]";
+ final String stats = "LOCALCRAWL[" + noticeURL.stackSize(NoticedURL.STACK_TYPE_CORE) + ", " + noticeURL.stackSize(NoticedURL.STACK_TYPE_LIMIT) + ", " + noticeURL.stackSize(NoticedURL.STACK_TYPE_OVERHANG) + ", " + noticeURL.stackSize(NoticedURL.STACK_TYPE_REMOTE) + "]";
try {
urlEntry = noticeURL.pop(NoticedURL.STACK_TYPE_CORE, true);
- String profileHandle = urlEntry.profileHandle();
+ final String profileHandle = urlEntry.profileHandle();
// System.out.println("DEBUG plasmaSwitchboard.processCrawling:
// profileHandle = " + profileHandle + ", urlEntry.url = " + urlEntry.url());
if (profileHandle == null) {
log.logSevere(stats + ": NULL PROFILE HANDLE '" + urlEntry.profileHandle() + "' for URL " + urlEntry.url());
return true;
}
- CrawlProfile.entry profile = sb.webIndex.profilesActiveCrawls.getEntry(profileHandle);
+ final CrawlProfile.entry profile = sb.webIndex.profilesActiveCrawls.getEntry(profileHandle);
if (profile == null) {
log.logWarning(stats + ": LOST PROFILE HANDLE '" + urlEntry.profileHandle() + "' for URL " + urlEntry.url());
return true;
}
// check if the protocol is supported
- yacyURL url = urlEntry.url();
- String urlProtocol = url.getProtocol();
+ final yacyURL url = urlEntry.url();
+ final String urlProtocol = url.getProtocol();
if (!this.sb.crawlQueues.isSupportedProtocol(urlProtocol)) {
this.log.logSevere("Unsupported protocol in URL '" + url.toString());
return true;
@@ -240,7 +240,7 @@ public class CrawlQueues {
processLocalCrawling(urlEntry, stats);
return true;
- } catch (IOException e) {
+ } catch (final IOException e) {
log.logSevere(stats + ": CANNOT FETCH ENTRY: " + e.getMessage(), e);
if (e.getMessage().indexOf("hash is null") > 0) noticeURL.clear(NoticedURL.STACK_TYPE_CORE);
}
@@ -292,7 +292,7 @@ public class CrawlQueues {
yacySeed seed;
if (remoteCrawlProviderHashes.size() == 0) {
if (sb.webIndex.seedDB != null && sb.webIndex.seedDB.sizeConnected() > 0) {
- Iterator<yacySeed> e = sb.webIndex.peerActions.dhtAction.getProvidesRemoteCrawlURLs();
+ final Iterator<yacySeed> e = sb.webIndex.peerActions.dhtAction.getProvidesRemoteCrawlURLs();
while (e.hasNext()) {
seed = e.next();
if (seed != null) {
@@ -321,35 +321,35 @@ public class CrawlQueues {
if (seed == null) return false;
// we know a peer which should provide remote crawl entries. load them now.
- RSSFeed feed = (seed == null) ? null : yacyClient.queryRemoteCrawlURLs(sb.webIndex.seedDB, seed, 20);
+ final RSSFeed feed = (seed == null) ? null : yacyClient.queryRemoteCrawlURLs(sb.webIndex.seedDB, seed, 20);
if (feed == null) return true;
// parse the rss
yacyURL url, referrer;
Date loaddate;
- for (RSSMessage item: feed) {
+ for (final RSSMessage item: feed) {
//System.out.println("URL=" + item.getLink() + ", desc=" + item.getDescription() + ", pubDate=" + item.getPubDate());
// put url on remote crawl stack
try {
url = new yacyURL(item.getLink(), null);
- } catch (MalformedURLException e) {
+ } catch (final MalformedURLException e) {
url = null;
}
try {
referrer = new yacyURL(item.getReferrer(), null);
- } catch (MalformedURLException e) {
+ } catch (final MalformedURLException e) {
referrer = null;
}
try {
loaddate = serverDate.parseShortSecond(item.getPubDate());
- } catch (ParseException e) {
+ } catch (final ParseException e) {
loaddate = new Date();
}
- String urlRejectReason = sb.acceptURL(url);
+ final String urlRejectReason = sb.acceptURL(url);
if (urlRejectReason == null) {
// stack url
sb.getLog().logFinest("crawlOrder: stack: url='" + url + "'");
- String reasonString = sb.crawlStacker.stackCrawl(url, referrer, hash, item.getDescription(), loaddate, 0, sb.webIndex.defaultRemoteProfile);
+ final String reasonString = sb.crawlStacker.stackCrawl(url, referrer, hash, item.getDescription(), loaddate, 0, sb.webIndex.defaultRemoteProfile);
if (reasonString == null) {
// done
@@ -371,7 +371,7 @@ public class CrawlQueues {
* @param url
* @return
*/
- private String urlToString(yacyURL url) {
+ private String urlToString(final yacyURL url) {
return (url == null ? "null" : url.toNormalform(true, false));
}
@@ -406,26 +406,26 @@ public class CrawlQueues {
}
// if crawling was paused we have to wait until we wer notified to continue
- Object[] status = sb.crawlJobsStatus.get(plasmaSwitchboard.CRAWLJOB_REMOTE_TRIGGERED_CRAWL);
+ final Object[] status = sb.crawlJobsStatus.get(plasmaSwitchboard.CRAWLJOB_REMOTE_TRIGGERED_CRAWL);
synchronized(status[plasmaSwitchboard.CRAWLJOB_SYNC]) {
if (((Boolean)status[plasmaSwitchboard.CRAWLJOB_STATUS]).booleanValue()) {
try {
status[plasmaSwitchboard.CRAWLJOB_SYNC].wait();
}
- catch (InterruptedException e){ return false;}
+ catch (final InterruptedException e){ return false;}
}
}
// we don't want to crawl a global URL globally, since WE are the global part. (from this point of view)
- String stats = "REMOTETRIGGEREDCRAWL[" + noticeURL.stackSize(NoticedURL.STACK_TYPE_CORE) + ", " + noticeURL.stackSize(NoticedURL.STACK_TYPE_LIMIT) + ", " + noticeURL.stackSize(NoticedURL.STACK_TYPE_OVERHANG) + ", "
+ final String stats = "REMOTETRIGGEREDCRAWL[" + noticeURL.stackSize(NoticedURL.STACK_TYPE_CORE) + ", " + noticeURL.stackSize(NoticedURL.STACK_TYPE_LIMIT) + ", " + noticeURL.stackSize(NoticedURL.STACK_TYPE_OVERHANG) + ", "
+ noticeURL.stackSize(NoticedURL.STACK_TYPE_REMOTE) + "]";
try {
- CrawlEntry urlEntry = noticeURL.pop(NoticedURL.STACK_TYPE_REMOTE, true);
- String profileHandle = urlEntry.profileHandle();
+ final CrawlEntry urlEntry = noticeURL.pop(NoticedURL.STACK_TYPE_REMOTE, true);
+ final String profileHandle = urlEntry.profileHandle();
// System.out.println("DEBUG plasmaSwitchboard.processCrawling:
// profileHandle = " + profileHandle + ", urlEntry.url = " +
// urlEntry.url());
- CrawlProfile.entry profile = sb.webIndex.profilesActiveCrawls.getEntry(profileHandle);
+ final CrawlProfile.entry profile = sb.webIndex.profilesActiveCrawls.getEntry(profileHandle);
if (profile == null) {
log.logWarning(stats + ": LOST PROFILE HANDLE '" + urlEntry.profileHandle() + "' for URL " + urlEntry.url());
@@ -433,8 +433,8 @@ public class CrawlQueues {
}
// check if the protocol is supported
- yacyURL url = urlEntry.url();
- String urlProtocol = url.getProtocol();
+ final yacyURL url = urlEntry.url();
+ final String urlProtocol = url.getProtocol();
if (!this.sb.crawlQueues.isSupportedProtocol(urlProtocol)) {
this.log.logSevere("Unsupported protocol in URL '" + url.toString());
return true;
@@ -445,14 +445,14 @@ public class CrawlQueues {
processLocalCrawling(urlEntry, stats);
return true;
- } catch (IOException e) {
+ } catch (final IOException e) {
log.logSevere(stats + ": CANNOT FETCH ENTRY: " + e.getMessage(), e);
if (e.getMessage().indexOf("hash is null") > 0) noticeURL.clear(NoticedURL.STACK_TYPE_REMOTE);
return true;
}
}
- private void processLocalCrawling(CrawlEntry entry, String stats) {
+ private void processLocalCrawling(final CrawlEntry entry, final String stats) {
// work off one Crawl stack entry
if ((entry == null) || (entry.url() == null)) {
log.logInfo(stats + ": urlEntry = null");
@@ -465,14 +465,14 @@ public class CrawlQueues {
}
public plasmaHTCache.Entry loadResourceFromWeb(
- yacyURL url,
- int socketTimeout,
- boolean keepInMemory,
- boolean forText,
- boolean global
+ final yacyURL url,
+ final int socketTimeout,
+ final boolean keepInMemory,
+ final boolean forText,
+ final boolean global
) {
- CrawlEntry centry = new CrawlEntry(
+ final CrawlEntry centry = new CrawlEntry(
sb.webIndex.seedDB.mySeed().hash,
url,
"",
@@ -500,9 +500,9 @@ public class CrawlQueues {
protected class crawlWorker extends Thread {
public CrawlEntry entry;
- private Integer code;
+ private final Integer code;
- public crawlWorker(CrawlEntry entry) {
+ public crawlWorker(final CrawlEntry entry) {
this.entry = entry;
this.entry.setStatus("worker-initialized");
this.code = new Integer(entry.hashCode());
@@ -518,7 +518,7 @@ public class CrawlQueues {
this.entry.setStatus("worker-checkingrobots");
if ((entry.url().getProtocol().equals("http") || entry.url().getProtocol().equals("https")) && sb.robots.isDisallowed(entry.url())) {
if (log.isFine()) log.logFine("Crawling of URL '" + entry.url().toString() + "' disallowed by robots.txt.");
- ZURL.Entry eentry = errorURL.newEntry(
+ final ZURL.Entry eentry = errorURL.newEntry(
this.entry,
sb.webIndex.seedDB.mySeed().hash,
new Date(),
@@ -529,9 +529,9 @@ public class CrawlQueues {
} else {
// starting a load from the internet
this.entry.setStatus("worker-loading");
- String result = loader.process(this.entry, plasmaParser.PARSER_MODE_CRAWLER);
+ final String result = loader.process(this.entry, plasmaParser.PARSER_MODE_CRAWLER);
if (result != null) {
- ZURL.Entry eentry = errorURL.newEntry(
+ final ZURL.Entry eentry = errorURL.newEntry(
this.entry,
sb.webIndex.seedDB.mySeed().hash,
new Date(),
@@ -543,8 +543,8 @@ public class CrawlQueues {
this.entry.setStatus("worker-processed");
}
}
- } catch (Exception e) {
- ZURL.Entry eentry = errorURL.newEntry(
+ } catch (final Exception e) {
+ final ZURL.Entry eentry = errorURL.newEntry(
this.entry,
sb.webIndex.seedDB.mySeed().hash,
new Date(),
diff --git a/source/de/anomic/crawler/CrawlStacker.java b/source/de/anomic/crawler/CrawlStacker.java
index 0899ea408..c5abf5f0e 100644
--- a/source/de/anomic/crawler/CrawlStacker.java
+++ b/source/de/anomic/crawler/CrawlStacker.java
@@ -62,20 +62,20 @@ public final class CrawlStacker extends Thread {
final serverLog log = new serverLog("STACKCRAWL");
- private plasmaSwitchboard sb;
+ private final plasmaSwitchboard sb;
private final LinkedList<String> urlEntryHashCache;
private kelondroIndex urlEntryCache;
- private File cacheStacksPath;
- private int dbtype;
- private boolean prequeue;
+ private final File cacheStacksPath;
+ private final int dbtype;
+ private final boolean prequeue;
private long dnsHit, dnsMiss;
private int alternateCount;
// objects for the prefetch task
- private ArrayList<String> dnsfetchHosts = new ArrayList<String>();
+ private final ArrayList<String> dnsfetchHosts = new ArrayList<String>();
- public CrawlStacker(plasmaSwitchboard sb, File dbPath, int dbtype, boolean prequeue) {
+ public CrawlStacker(final plasmaSwitchboard sb, final File dbPath, final int dbtype, final boolean prequeue) {
this.sb = sb;
this.prequeue = prequeue;
this.dnsHit = 0;
@@ -92,7 +92,7 @@ public final class CrawlStacker extends Thread {
openDB();
try {
// loop through the list and fill the messageList with url hashs
- Iterator<kelondroRow.Entry> rows = this.urlEntryCache.rows(true, null);
+ final Iterator<kelondroRow.Entry> rows = this.urlEntryCache.rows(true, null);
kelondroRow.Entry entry;
while (rows.hasNext()) {
entry = rows.next();
@@ -102,20 +102,20 @@ public final class CrawlStacker extends Thread {
}
this.urlEntryHashCache.add(entry.getColString(0, null));
}
- } catch (kelondroException e) {
+ } catch (final kelondroException e) {
/* if we have an error, we start with a fresh database */
CrawlStacker.this.log.logSevere("Unable to initialize crawl stacker queue, kelondroException:" + e.getMessage() + ". Reseting DB.\n", e);
// deleting old db and creating a new db
- try {this.urlEntryCache.close();} catch (Exception ex) {}
+ try {this.urlEntryCache.close();} catch (final Exception ex) {}
deleteDB();
openDB();
- } catch (IOException e) {
+ } catch (final IOException e) {
/* if we have an error, we start with a fresh database */
CrawlStacker.this.log.logSevere("Unable to initialize crawl stacker queue, IOException:" + e.getMessage() + ". Reseting DB.\n", e);
// deleting old db and creating a new db
- try {this.urlEntryCache.close();} catch (Exception ex) {}
+ try {this.urlEntryCache.close();} catch (final Exception ex) {}
deleteDB();
openDB();
}
@@ -134,18 +134,18 @@ public final class CrawlStacker extends Thread {
}
try {
serverDomains.dnsResolve(nextHost);
- } catch (Exception e) {}
+ } catch (final Exception e) {}
}
- } catch (InterruptedException e) {}
+ } catch (final InterruptedException e) {}
}
- public boolean prefetchHost(String host) {
+ public boolean prefetchHost(final String host) {
// returns true when the host was known in the dns cache.
// If not, the host is stacked on the fetch stack and false is returned
try {
serverDomains.dnsResolveFromCache(host);
return true;
- } catch (UnknownHostException e) {
+ } catch (final UnknownHostException e) {
synchronized (this) {
dnsfetchHosts.add(host);
notifyAll();
@@ -187,7 +187,7 @@ public final class CrawlStacker extends Thread {
CrawlEntry entry;
try {
entry = dequeueEntry();
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
return false;
}
@@ -195,15 +195,15 @@ public final class CrawlStacker extends Thread {
try {
- String rejectReason = sb.crawlStacker.stackCrawl(entry);
+ final String rejectReason = sb.crawlStacker.stackCrawl(entry);
// if the url was rejected we store it into the error URL db
if (rejectReason != null) {
- ZURL.Entry ee = sb.crawlQueues.errorURL.newEntry(entry, sb.webIndex.seedDB.mySeed().hash, new Date(), 1, rejectReason);
+ final ZURL.Entry ee = sb.crawlQueues.errorURL.newEntry(entry, sb.webIndex.seedDB.mySeed().hash, new Date(), 1, rejectReason);
ee.store();
sb.crawlQueues.errorURL.push(ee);
}
- } catch (Exception e) {
+ } catch (final Exception e) {
CrawlStacker.this.log.logWarning("Error while processing stackCrawl entry.\n" + "Entry: " + entry.toString() + "Error: " + e.toString(), e);
return false;
}
@@ -211,20 +211,20 @@ public final class CrawlStacker extends Thread {
}
public void enqueueEntry(
- yacyURL nexturl,
- String referrerhash,
- String initiatorHash,
- String name,
- Date loadDate,
- int currentdepth,
- CrawlProfile.entry profile) {
+ final yacyURL nexturl,
+ final String referrerhash,
+ final String initiatorHash,
+ final String name,
+ final Date loadDate,
+ final int currentdepth,
+ final CrawlProfile.entry profile) {
if (profile == null) return;
// check first before we create a big object
if (this.urlEntryCache.has(nexturl.hash().getBytes())) return;
// now create the big object before we enter the synchronized block
- CrawlEntry newEntry = new CrawlEntry(
+ final CrawlEntry newEntry = new CrawlEntry(
initiatorHash,
nexturl,
referrerhash,
@@ -236,7 +236,7 @@ public final class CrawlStacker extends Thread {
0
);
if (newEntry == null) return;
- kelondroRow.Entry newEntryRow = newEntry.toRow();
+ final kelondroRow.Entry newEntryRow = newEntry.toRow();
synchronized(this.urlEntryHashCache) {
kelondroRow.Entry oldValue;
@@ -244,7 +244,7 @@ public final class CrawlStacker extends Thread {
if (prequeue) hostknown = prefetchHost(nexturl.getHost());
try {
oldValue = this.urlEntryCache.put(newEntryRow);
- } catch (IOException e) {
+ } catch (final IOException e) {
oldValue = null;
}
if (oldValue == null) {
@@ -277,7 +277,7 @@ public final class CrawlStacker extends Thread {
//kelondroFlexWidthArray.delete(cacheStacksPath, stackfile);
}
if (this.dbtype == QUEUE_DB_TYPE_TREE) {
- File cacheFile = new File(cacheStacksPath, stackfile);
+ final File cacheFile = new File(cacheStacksPath, stackfile);
cacheFile.delete();
}
}
@@ -290,11 +290,11 @@ public final class CrawlStacker extends Thread {
}
if (this.dbtype == QUEUE_DB_TYPE_ECO) {
cacheStacksPath.mkdirs();
- File f = new File(cacheStacksPath, stackfile);
+ final File f = new File(cacheStacksPath, stackfile);
try {
this.urlEntryCache = new kelondroEcoTable(f, CrawlEntry.rowdef, kelondroEcoTable.tailCacheUsageAuto, EcoFSBufferSize, 0);
//this.urlEntryCache = new kelondroCache(new kelondroFlexTable(cacheStacksPath, newCacheName, preloadTime, CrawlEntry.rowdef, 0, true));
- } catch (Exception e) {
+ } catch (final Exception e) {
e.printStackTrace();
// kill DB and try again
f.delete();
@@ -302,14 +302,14 @@ public final class CrawlStacker extends Thread {
try {
this.urlEntryCache = new kelondroEcoTable(f, CrawlEntry.rowdef, kelondroEcoTable.tailCacheUsageAuto, EcoFSBufferSize, 0);
//this.urlEntryCache = new kelondroCache(new kelondroFlexTable(cacheStacksPath, newCacheName, preloadTime, CrawlEntry.rowdef, 0, true));
- } catch (Exception ee) {
+ } catch (final Exception ee) {
ee.printStackTrace();
System.exit(-1);
}
}
}
if (this.dbtype == QUEUE_DB_TYPE_TREE) {
- File cacheFile = new File(cacheStacksPath, stackfile);
+ final File cacheFile = new File(cacheStacksPath, stackfile);
cacheFile.getParentFile().mkdirs();
this.urlEntryCache = new kelondroCache(kelondroTree.open(cacheFile, true, 0, CrawlEntry.rowdef));
}
@@ -339,13 +339,13 @@ public final class CrawlStacker extends Thread {
return new CrawlEntry(entry);
}
- public String stackCrawl(yacyURL url, yacyURL referrer, String initiatorHash, String name, Date loadDate, int currentdepth, CrawlProfile.entry profile) {
+ public String stackCrawl(final yacyURL url, final yacyURL referrer, final String initiatorHash, final String name, final Date loadDate, final int currentdepth, final CrawlProfile.entry profile) {
// stacks a crawl item. The position can also be remote
// returns null if successful, a reason string if not successful
//this.log.logFinest("stackCrawl: nexturlString='" + nexturlString + "'");
// add the url into the crawling queue
- CrawlEntry entry = new CrawlEntry(
+ final CrawlEntry entry = new CrawlEntry(
initiatorHash, // initiator, needed for p2p-feedback
url, // url clear text string
(referrer == null) ? "" : referrer.hash(), // last url in crawling queue
@@ -359,16 +359,16 @@ public final class CrawlStacker extends Thread {
return stackCrawl(entry);
}
- public String stackCrawl(CrawlEntry entry) {
+ public String stackCrawl(final CrawlEntry entry) {
// stacks a crawl item. The position can also be remote
// returns null if successful, a reason string if not successful
//this.log.logFinest("stackCrawl: nexturlString='" + nexturlString + "'");
- long startTime = System.currentTimeMillis();
+ final long startTime = System.currentTimeMillis();
String reason = null; // failure reason
// check if the protocol is supported
- String urlProtocol = entry.url().getProtocol();
+ final String urlProtocol = entry.url().getProtocol();
if (!sb.crawlQueues.isSupportedProtocol(urlProtocol)) {
reason = ErrorURL.DENIED_UNSUPPORTED_PROTOCOL;
this.log.logSevere("Unsupported protocol in URL '" + entry.url().toString() + "'. " +
@@ -377,7 +377,7 @@ public final class CrawlStacker extends Thread {
}
// check if ip is local ip address
- String urlRejectReason = sb.acceptURL(entry.url());
+ final String urlRejectReason = sb.acceptURL(entry.url());
if (urlRejectReason != null) {
reason = "denied_(" + urlRejectReason + ")_domain=" + sb.getConfig("network.unit.domain", "unknown");
if (this.log.isFine()) this.log.logFine(reason + "Stack processing time: " + (System.currentTimeMillis()-startTime) + "ms");
@@ -392,9 +392,9 @@ public final class CrawlStacker extends Thread {
return reason;
}
- CrawlProfile.entry profile = sb.webIndex.profilesActiveCrawls.getEntry(entry.profileHandle());
+ final CrawlProfile.entry profile = sb.webIndex.profilesActiveCrawls.getEntry(entry.profileHandle());
if (profile == null) {
- String errorMsg = "LOST PROFILE HANDLE '" + entry.profileHandle() + "' for URL " + entry.url();
+ final String errorMsg = "LOST PROFILE HANDLE '" + entry.profileHandle() + "' for URL " + entry.url();
log.logWarning(errorMsg);
return errorMsg;
} else {
@@ -426,7 +426,7 @@ public final class CrawlStacker extends Thread {
return reason;
}
- yacyURL referrerURL = (entry.referrerhash() == null) ? null : sb.crawlQueues.getURL(entry.referrerhash());
+ final yacyURL referrerURL = (entry.referrerhash() == null) ? null : sb.crawlQueues.getURL(entry.referrerhash());
// add domain to profile domain list
if ((profile.domFilterDepth() != Integer.MAX_VALUE) || (profile.domMaxPages() != Integer.MAX_VALUE)) {
@@ -450,9 +450,9 @@ public final class CrawlStacker extends Thread {
}
// check if the url is double registered
- String dbocc = sb.crawlQueues.urlExists(entry.url().hash());
- indexURLReference oldEntry = this.sb.webIndex.getURL(entry.url().hash(), null, 0);
- boolean recrawl = (oldEntry != null) && ((System.currentTimeMillis() - oldEntry.loaddate().getTime()) > profile.recrawlIfOlder());
+ final String dbocc = sb.crawlQueues.urlExists(entry.url().hash());
+ final indexURLReference oldEntry = this.sb.webIndex.getURL(entry.url().hash(), null, 0);
+ final boolean recrawl = (oldEntry != null) && ((System.currentTimeMillis() - oldEntry.loaddate().getTime()) > profile.recrawlIfOlder());
// do double-check
if ((dbocc != null) && (!recrawl)) {
reason = ErrorURL.DOUBLE_REGISTERED + dbocc + ")";
@@ -472,8 +472,8 @@ public final class CrawlStacker extends Thread {
}
// store information
- boolean local = entry.initiator().equals(sb.webIndex.seedDB.mySeed().hash);
- boolean global =
+ final boolean local = entry.initiator().equals(sb.webIndex.seedDB.mySeed().hash);
+ final boolean global =
(profile.remoteIndexing()) /* granted */ &&
(entry.depth() == profile.generalDepth()) /* leaf node */ &&
//(initiatorHash.equals(yacyCore.seedDB.mySeed.hash)) /* not proxy */ &&
diff --git a/source/de/anomic/crawler/HTTPLoader.java b/source/de/anomic/crawler/HTTPLoader.java
index c708c826e..e5babd5c5 100644
--- a/source/de/anomic/crawler/HTTPLoader.java
+++ b/source/de/anomic/crawler/HTTPLoader.java
@@ -65,7 +65,7 @@ public final class HTTPLoader {
/**
* The socket timeout that should be used
*/
- private int socketTimeout;
+ private final int socketTimeout;
/**
* The maximum allowed file size
@@ -75,10 +75,10 @@ public final class HTTPLoader {
//private String acceptEncoding;
//private String acceptLanguage;
//private String acceptCharset;
- private plasmaSwitchboard sb;
- private serverLog log;
+ private final plasmaSwitchboard sb;
+ private final serverLog log;
- public HTTPLoader(plasmaSwitchboard sb, serverLog theLog) {
+ public HTTPLoader(final plasmaSwitchboard sb, final serverLog theLog) {
this.sb = sb;
this.log = theLog;
@@ -94,8 +94,8 @@ public final class HTTPLoader {
* @param responseStatus Status-Code SPACE Reason-Phrase
* @return
*/
- protected plasmaHTCache.Entry createCacheEntry(CrawlEntry entry, Date requestDate, httpHeader requestHeader, httpHeader responseHeader, final String responseStatus) {
- IResourceInfo resourceInfo = new ResourceInfo(entry.url(), requestHeader, responseHeader);
+ protected plasmaHTCache.Entry createCacheEntry(final CrawlEntry entry, final Date requestDate, final httpHeader requestHeader, final httpHeader responseHeader, final String responseStatus) {
+ final IResourceInfo resourceInfo = new ResourceInfo(entry.url(), requestHeader, responseHeader);
return plasmaHTCache.newEntry(
requestDate,
entry.depth(),
@@ -108,11 +108,11 @@ public final class HTTPLoader {
);
}
- public plasmaHTCache.Entry load(CrawlEntry entry, String parserMode) {
+ public plasmaHTCache.Entry load(final CrawlEntry entry, final String parserMode) {
return load(entry, parserMode, DEFAULT_CRAWLING_RETRY_COUNT);
}
- private plasmaHTCache.Entry load(CrawlEntry entry, String parserMode, int retryCount) {
+ private plasmaHTCache.Entry load(final CrawlEntry entry, final String parserMode, final int retryCount) {
if (retryCount < 0) {
this.log.logInfo("Redirection counter exceeded for URL " + entry.url().toString() + ". Processing aborted.");
@@ -120,15 +120,15 @@ public final class HTTPLoader {
return null;
}
- Date requestDate = new Date(); // remember the time...
- String host = entry.url().getHost();
- String path = entry.url().getFile();
+ final Date requestDate = new Date(); // remember the time...
+ final String host = entry.url().getHost();
+ final String path = entry.url().getFile();
int port = entry.url().getPort();
- boolean ssl = entry.url().getProtocol().equals("https");
+ final boolean ssl = entry.url().getProtocol().equals("https");
if (port < 0) port = (ssl) ? 443 : 80;
// check if url is in blacklist
- String hostlow = host.toLowerCase();
+ final String hostlow = host.toLowerCase();
if (plasmaSwitchboard.urlBlacklist.isListed(indexReferenceBlacklist.BLACKLIST_CRAWLER, hostlow, path)) {
this.log.logInfo("CRAWLER Rejecting URL '" + entry.url().toString() + "'. URL is in blacklist.");
sb.crawlQueues.errorURL.newEntry(entry, sb.webIndex.seedDB.mySeed().hash, new Date(), 1, ErrorURL.DENIED_URL_IN_BLACKLIST).store();
@@ -140,7 +140,7 @@ public final class HTTPLoader {
final long maxFileSize = sb.getConfigLong("crawler.http.maxFileSize", DEFAULT_MAXFILESIZE);
try {
// create a request header
- httpHeader requestHeader = new httpHeader();
+ final httpHeader requestHeader = new httpHeader();
requestHeader.put(httpHeader.USER_AGENT, crawlerUserAgent);
yacyURL refererURL = null;
if (entry.referrerhash() != null) refererURL = sb.getURL(entry.referrerhash());
@@ -150,7 +150,7 @@ public final class HTTPLoader {
requestHeader.put(httpHeader.ACCEPT_ENCODING, sb.getConfig("crawler.http.acceptEncoding", DEFAULT_ENCODING));
// HTTP-Client
- JakartaCommonsHttpClient client = new JakartaCommonsHttpClient(socketTimeout, requestHeader, null);
+ final JakartaCommonsHttpClient client = new JakartaCommonsHttpClient(socketTimeout, requestHeader, null);
JakartaCommonsHttpResponse res = null;
try {
@@ -181,7 +181,7 @@ public final class HTTPLoader {
}
// request has been placed and result has been returned. work off response
- File cacheFile = plasmaHTCache.getCachePath(entry.url());
+ final File cacheFile = plasmaHTCache.getCachePath(entry.url());
try {
if (plasmaParser.supportedContent(parserMode, entry.url(), res.getResponseHeader().mime())) {
// delete old content
@@ -198,7 +198,7 @@ public final class HTTPLoader {
fos = new FileOutputStream(cacheFile);
// getting content length
- long contentLength = res.getResponseHeader().contentLength();
+ final long contentLength = res.getResponseHeader().contentLength();
// check the maximum allowed file size
if (contentLength == -1 || maxFileSize == -1) {
@@ -217,13 +217,13 @@ public final class HTTPLoader {
// we write the new cache entry to file system directly
(res).setAccountingName("CRAWLER");
- byte[] responseBody = res.getData();
+ 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(Exception e){/* ignore this */}
+ if (fos!=null)try{fos.close();}catch(final Exception e){/* ignore this */}
}
return htCache;
@@ -233,7 +233,7 @@ public final class HTTPLoader {
sb.crawlQueues.errorURL.newEntry(entry, sb.webIndex.seedDB.mySeed().hash, new Date(), 1, ErrorURL.DENIED_WRONG_MIMETYPE_OR_EXT);
return null;
}
- } catch (SocketException e) {
+ } catch (final SocketException e) {
// this may happen if the client suddenly closes its connection
// maybe the user has stopped loading
// in that case, we are not responsible and just forget it
@@ -257,7 +257,7 @@ public final class HTTPLoader {
}
// normalizing URL
- yacyURL redirectionUrl = yacyURL.newURL(entry.url(), redirectionUrlString);
+ final yacyURL redirectionUrl = yacyURL.newURL(entry.url(), redirectionUrlString);
// restart crawling with new url
this.log.logInfo("CRAWLER Redirection detected ('" + res.getStatusLine() + "') for URL " + entry.url().toString());
@@ -271,10 +271,10 @@ public final class HTTPLoader {
}
// generating url hash
- String urlhash = redirectionUrl.hash();
+ final String urlhash = redirectionUrl.hash();
// check if the url was already indexed
- String dbname = sb.urlExists(urlhash);
+ final String dbname = sb.urlExists(urlhash);
if (dbname != null) {
this.log.logWarning("CRAWLER Redirection of URL=" + entry.url().toString() + " ignored. The url appears already in db " + dbname);
sb.crawlQueues.errorURL.newEntry(entry, sb.webIndex.seedDB.mySeed().hash, new Date(), 1, ErrorURL.DENIED_REDIRECTION_TO_DOUBLE_CONTENT);
@@ -301,8 +301,8 @@ public final class HTTPLoader {
}
}
return htCache;
- } catch (Exception e) {
- String errorMsg = e.getMessage();
+ } catch (final Exception e) {
+ final String errorMsg = e.getMessage();
String failreason = null;
if ((e instanceof IOException) &&
@@ -323,7 +323,7 @@ public final class HTTPLoader {
failreason = ErrorURL.DENIED_NO_ROUTE_TO_HOST;
} else if ((e instanceof UnknownHostException) ||
((errorMsg != null) && (errorMsg.indexOf("unknown host") >= 0))) {
- yacyURL u = (entry.referrerhash() == null) ? null : sb.getURL(entry.referrerhash());
+ final yacyURL u = (entry.referrerhash() == null) ? null : sb.getURL(entry.referrerhash());
this.log.logWarning("CRAWLER Unknown host in URL '" + entry.url() + "'. " +
"Referer URL: " + ((u == null) ? "Unknown" : u.toNormalform(true, true)));
failreason = ErrorURL.DENIED_UNKNOWN_HOST;
diff --git a/source/de/anomic/crawler/ImporterException.java b/source/de/anomic/crawler/ImporterException.java
index 6c302f09d..809314132 100644
--- a/source/de/anomic/crawler/ImporterException.java
+++ b/source/de/anomic/crawler/ImporterException.java
@@ -4,11 +4,11 @@ public class ImporterException extends Exception {
private static final long serialVersionUID = 6070972210596234670L;
- public ImporterException(String message) {
+ public ImporterException(final String message) {
super(message);
}
- public ImporterException(String message, Throwable cause) {
+ public ImporterException(final String message, final Throwable cause) {
super(message, cause);
}
}
diff --git a/source/de/anomic/crawler/ImporterManager.java b/source/de/anomic/crawler/ImporterManager.java
index c97550b57..f8782eba6 100644
--- a/source/de/anomic/crawler/ImporterManager.java
+++ b/source/de/anomic/crawler/ImporterManager.java
@@ -23,9 +23,9 @@ public class ImporterManager {
}
public Importer[] getRunningImporter() {
- Thread[] importThreads = new Thread[this.runningJobs.activeCount()*2];
- int activeCount = this.runningJobs.enumerate(importThreads);
- Importer[] importers = new Importer[activeCount];
+ final Thread[] importThreads = new Thread[this.runningJobs.activeCount()*2];
+ final int activeCount = this.runningJobs.enumerate(importThreads);
+ final Importer[] importers = new Importer[activeCount];
for (int i=0; i<activeCount; i++) {
importers[i] = (Importer) importThreads[i];
}
@@ -36,13 +36,13 @@ public class ImporterManager {
return this.finishedJobs.toArray(new Importer[this.finishedJobs.size()]);
}
- public Importer getImporterByID(int jobID) {
+ public Importer getImporterByID(final int jobID) {
- Thread[] importThreads = new Thread[this.runningJobs.activeCount()*2];
- int activeCount = this.runningJobs.enumerate(importThreads);
+ final Thread[] importThreads = new Thread[this.runningJobs.activeCount()*2];
+ final int activeCount = this.runningJobs.enumerate(importThreads);
for (int i=0; i < activeCount; i++) {
- Importer currThread = (Importer) importThreads[i];
+ final Importer currThread = (Importer) importThreads[i];
if (currThread.getJobID() == jobID) {
return currThread;
}
@@ -60,24 +60,24 @@ public class ImporterManager {
/* waiting for all threads to finish */
int threadCount = this.runningJobs.activeCount();
- Thread[] threadList = new Thread[threadCount];
+ final Thread[] threadList = new Thread[threadCount];
threadCount = this.runningJobs.enumerate(threadList);
if (threadCount == 0) return;
- serverLog log = new serverLog("DB-IMPORT");
+ final serverLog log = new serverLog("DB-IMPORT");
try {
// trying to gracefull stop all still running sessions ...
log.logInfo("Signaling shutdown to " + threadCount + " remaining dbImporter threads ...");
for ( int currentThreadIdx = 0; currentThreadIdx < threadCount; currentThreadIdx++ ) {
- Thread currentThread = threadList[currentThreadIdx];
+ final Thread currentThread = threadList[currentThreadIdx];
if (currentThread.isAlive()) {
((Importer)currentThread).stopIt();
}
}
// waiting a few ms for the session objects to continue processing
- try { Thread.sleep(500); } catch (InterruptedException ex) {}
+ try { Thread.sleep(500); } catch (final InterruptedException ex) {}
// interrupting all still running or pooled threads ...
log.logInfo("Sending interruption signal to " + runningJobs.activeCount() + " remaining dbImporter threads ...");
@@ -86,15 +86,15 @@ public class ImporterManager {
// we need to use a timeout here because of missing interruptable session threads ...
if (log.isFine()) log.logFine("Waiting for " + runningJobs.activeCount() + " remaining dbImporter threads to finish shutdown ...");
for ( int currentThreadIdx = 0; currentThreadIdx < threadCount; currentThreadIdx++ ) {
- Thread currentThread = threadList[currentThreadIdx];
+ final Thread currentThread = threadList[currentThreadIdx];
if (currentThread.isAlive()) {
if (log.isFine()) log.logFine("Waiting for dbImporter thread '" + currentThread.getName() + "' [" + currentThreadIdx + "] to finish shutdown.");
- try { currentThread.join(500); } catch (InterruptedException ex) {}
+ try { currentThread.join(500); } catch (final InterruptedException ex) {}
}
}
log.logInfo("Shutdown of remaining dbImporter threads finished.");
- } catch (Exception e) {
+ } catch (final Exception e) {
log.logSevere("Unexpected error while trying to shutdown all remaining dbImporter threads.",e);
}
}
diff --git a/source/de/anomic/crawler/IndexingStack.java b/source/de/anomic/crawler/IndexingStack.java
index 4cda8c167..83302459b 100644
--- a/source/de/anomic/crawler/IndexingStack.java
+++ b/source/de/anomic/crawler/IndexingStack.java
@@ -53,10 +53,10 @@ public class IndexingStack {
kelondroStack sbQueueStack;
CrawlProfile profiles;
plasmaWordIndex wordIndex;
- private File sbQueueStackPath;
+ private final File sbQueueStackPath;
ConcurrentHashMap<String, QueueEntry> queueInProcess;
- public IndexingStack(plasmaWordIndex wordIndex, File sbQueueStackPath, CrawlProfile profiles) {
+ public IndexingStack(final plasmaWordIndex wordIndex, final File sbQueueStackPath, final CrawlProfile profiles) {
this.sbQueueStackPath = sbQueueStackPath;
this.profiles = profiles;
this.wordIndex = wordIndex;
@@ -92,7 +92,7 @@ public class IndexingStack {
return (sbQueueStack == null) ? 0 : sbQueueStack.size();
}
- public synchronized void push(QueueEntry entry) throws IOException {
+ public synchronized void push(final QueueEntry entry) throws IOException {
if (entry == null) return;
if (sbQueueStack == null) return; // may occur during shutdown
sbQueueStack.push(sbQueueStack.row().newEntry(new byte[][]{
@@ -109,13 +109,13 @@ public class IndexingStack {
public synchronized QueueEntry pop() throws IOException {
if (sbQueueStack.size() == 0) return null;
- kelondroRow.Entry b = sbQueueStack.pot();
+ final kelondroRow.Entry b = sbQueueStack.pot();
if (b == null) return null;
return new QueueEntry(b);
}
- public synchronized QueueEntry remove(String urlHash) {
- Iterator<kelondroRow.Entry> i = sbQueueStack.stackIterator(true);
+ public synchronized QueueEntry remove(final String urlHash) {
+ final Iterator<kelondroRow.Entry> i = sbQueueStack.stackIterator(true);
kelondroRow.Entry rowentry;
QueueEntry entry;
while (i.hasNext()) {
@@ -143,13 +143,13 @@ public class IndexingStack {
protected void finalize() throws Throwable {
try {
close();
- } catch (Exception e) {
+ } catch (final Exception e) {
throw new IOException("plasmaSwitchboardQueue.finalize()" + e.getMessage());
}
super.finalize();
}
- public Iterator<QueueEntry> entryIterator(boolean up) {
+ public Iterator<QueueEntry> entryIterator(final boolean up) {
// iterates the elements in an ordered way.
// returns plasmaSwitchboardQueue.Entry - type Objects
return new entryIterator(up);
@@ -159,7 +159,7 @@ public class IndexingStack {
Iterator<kelondroRow.Entry> rows;
- public entryIterator(boolean up) {
+ public entryIterator(final boolean up) {
rows = sbQueueStack.stackIterator(up);
}
@@ -176,16 +176,16 @@ public class IndexingStack {
}
}
- public QueueEntry newEntry(yacyURL url, String referrer, Date ifModifiedSince, boolean requestWithCookie,
- String initiator, int depth, String profilehandle, String anchorName) {
+ public QueueEntry newEntry(final yacyURL url, final String referrer, final Date ifModifiedSince, final boolean requestWithCookie,
+ final String initiator, final int depth, final String profilehandle, final String anchorName) {
return new QueueEntry(url, referrer, ifModifiedSince, requestWithCookie, initiator, depth, profilehandle, anchorName);
}
- public void enQueueToActive(QueueEntry entry) {
+ public void enQueueToActive(final QueueEntry entry) {
queueInProcess.put(entry.urlHash(), entry);
}
- public QueueEntry getActiveEntry(String urlhash) {
+ public QueueEntry getActiveEntry(final String urlhash) {
// show one entry from the queue
return this.queueInProcess.get(urlhash);
}
@@ -222,8 +222,8 @@ public class IndexingStack {
private IResourceInfo contentInfo;
private yacyURL referrerURL;
- public QueueEntry(yacyURL url, String referrer, Date ifModifiedSince, boolean requestWithCookie,
- String initiator, int depth, String profileHandle, String anchorName) {
+ public QueueEntry(final yacyURL url, final String referrer, final Date ifModifiedSince, final boolean requestWithCookie,
+ final String initiator, final int depth, final String profileHandle, final String anchorName) {
this.url = url;
this.referrerHash = referrer;
this.ifModifiedSince = ifModifiedSince;
@@ -239,12 +239,12 @@ public class IndexingStack {
this.status = QUEUE_STATE_FRESH;
}
- public QueueEntry(kelondroRow.Entry row) {
- long ims = row.getColLong(2);
- byte flags = row.getColByte(3);
+ public QueueEntry(final kelondroRow.Entry row) {
+ final long ims = row.getColLong(2);
+ final byte flags = row.getColByte(3);
try {
this.url = new yacyURL(row.getColString(0, "UTF-8"), null);
- } catch (MalformedURLException e) {
+ } catch (final MalformedURLException e) {
this.url = null;
}
this.referrerHash = row.getColString(1, "UTF-8");
@@ -261,12 +261,12 @@ public class IndexingStack {
this.status = QUEUE_STATE_FRESH;
}
- public QueueEntry(byte[][] row) throws IOException {
- long ims = (row[2] == null) ? 0 : kelondroBase64Order.enhancedCoder.decodeLong(new String(row[2], "UTF-8"));
- byte flags = (row[3] == null) ? 0 : row[3][0];
+ public QueueEntry(final byte[][] row) throws IOException {
+ final long ims = (row[2] == null) ? 0 : kelondroBase64Order.enhancedCoder.decodeLong(new String(row[2], "UTF-8"));
+ final byte flags = (row[3] == null) ? 0 : row[3][0];
try {
this.url = new yacyURL(new String(row[0], "UTF-8"), null);
- } catch (MalformedURLException e) {
+ } catch (final MalformedURLException e) {
this.url = null;
}
this.referrerHash = (row[1] == null) ? null : new String(row[1], "UTF-8");
@@ -283,7 +283,7 @@ public class IndexingStack {
this.status = QUEUE_STATE_FRESH;
}
- public void updateStatus(int newStatus) {
+ public void updateStatus(final int newStatus) {
this.status = newStatus;
}
@@ -346,7 +346,7 @@ public class IndexingStack {
private IResourceInfo getCachedObjectInfo() {
if (this.contentInfo == null) try {
this.contentInfo = plasmaHTCache.loadResourceInfo(this.url);
- } catch (Exception e) {
+ } catch (final Exception e) {
serverLog.logSevere("PLASMA", "responseHeader: failed to get header", e);
return null;
}
@@ -354,24 +354,24 @@ public class IndexingStack {
}
public String getMimeType() {
- IResourceInfo info = this.getCachedObjectInfo();
+ final IResourceInfo info = this.getCachedObjectInfo();
return (info == null) ? null : info.getMimeType();
}
public String getCharacterEncoding() {
- IResourceInfo info = this.getCachedObjectInfo();
+ final IResourceInfo info = this.getCachedObjectInfo();
return (info == null) ? null : info.getCharacterEncoding();
}
public Date getModificationDate() {
- IResourceInfo info = this.getCachedObjectInfo();
+ final IResourceInfo info = this.getCachedObjectInfo();
return (info == null) ? new Date() : info.getModificationDate();
}
public yacyURL referrerURL() {
if (referrerURL == null) {
if ((referrerHash == null) || ((initiator != null) && (referrerHash.equals(initiator.length() == 0)))) return null;
- indexURLReference entry = wordIndex.getURL(referrerHash, null, 0);
+ final indexURLReference entry = wordIndex.getURL(referrerHash, null, 0);
if (entry == null) referrerURL = null; else referrerURL = entry.comp().url();
}
return referrerURL;
@@ -494,7 +494,7 @@ public class IndexingStack {
// a picture cannot be indexed
if (getCachedObjectInfo() != null) {
- String status = this.getCachedObjectInfo().shallIndexCacheForCrawler();
+ final String status = this.getCachedObjectInfo().shallIndexCacheForCrawler();
if (status != null) return status;
}
if (plasmaHTCache.noIndexingURL(url())) { return "Media_Content_(forbidden)"; }
diff --git a/source/de/anomic/crawler/LoaderMessage.java b/source/de/anomic/crawler/LoaderMessage.java
index b304b4f71..54ed0a4b2 100644
--- a/source/de/anomic/crawler/LoaderMessage.java
+++ b/source/de/anomic/crawler/LoaderMessage.java
@@ -46,16 +46,16 @@ public final class LoaderMessage {
// loadParallel(URL url, String referer, String initiator, int depth, plasmaCrawlProfile.entry profile) {
public LoaderMessage(
- yacyURL url,
- String name, // the name of the url, from anchor tag <a>name</a>
- String referer,
- String initiator,
- int depth,
- CrawlProfile.entry profile,
- int crawlingPriority,
- boolean acceptAllContent,
- int timeout,
- boolean keepInMemory
+ final yacyURL url,
+ final String name, // the name of the url, from anchor tag <a>name</a>
+ final String referer,
+ final String initiator,
+ final int depth,
+ final CrawlProfile.entry profile,
+ final int crawlingPriority,
+ final boolean acceptAllContent,
+ final int timeout,
+ final boolean keepInMemory
) {
this.url = url;
this.name = name;
@@ -72,7 +72,7 @@ public final class LoaderMessage {
this.result = null;
}
- public void setError(String errorMessage) {
+ public void setError(final String errorMessage) {
this.errorMessage = errorMessage;
}
@@ -80,7 +80,7 @@ public final class LoaderMessage {
return this.errorMessage;
}
- public void setResult(plasmaHTCache.Entry theResult) {
+ public void setResult(final plasmaHTCache.Entry theResult) {
// store the result
this.result = theResult;
diff --git a/source/de/anomic/crawler/NoticeURLImporter.java b/source/de/anomic/crawler/NoticeURLImporter.java
index 294e26f79..7a8d0348b 100644
--- a/source/de/anomic/crawler/NoticeURLImporter.java
+++ b/source/de/anomic/crawler/NoticeURLImporter.java
@@ -11,17 +11,17 @@ import de.anomic.plasma.plasmaWordIndex;
public class NoticeURLImporter extends AbstractImporter implements Importer {
private File plasmaPath = null;
- private HashSet<String> importProfileHandleCache = new HashSet<String>();
- private CrawlProfile importProfileDB;
- private NoticedURL importNurlDB;
- private int importStartSize;
+ private final HashSet<String> importProfileHandleCache = new HashSet<String>();
+ private final CrawlProfile importProfileDB;
+ private final NoticedURL importNurlDB;
+ private final int importStartSize;
private int urlCount = 0;
private int profileCount = 0;
- private CrawlQueues crawlQueues;
- private CrawlProfile activeCrawls;
- private ImporterManager dbImportManager;
+ private final CrawlQueues crawlQueues;
+ private final CrawlProfile activeCrawls;
+ private final ImporterManager dbImportManager;
- public NoticeURLImporter(File crawlerPath, CrawlQueues crawlQueues, CrawlProfile activeCrawls, ImporterManager dbImportManager) {
+ public NoticeURLImporter(final File crawlerPath, final CrawlQueues crawlQueues, final CrawlProfile activeCrawls, final ImporterManager dbImportManager) {
super("NURL");
this.crawlQueues = crawlQueues;
this.activeCrawls = activeCrawls;
@@ -29,8 +29,8 @@ public class NoticeURLImporter extends AbstractImporter implements Importer {
// TODO: we need more error handling here
this.plasmaPath = crawlerPath;
- File noticeUrlDbFile = new File(plasmaPath,"urlNotice1.db");
- File profileDbFile = new File(plasmaPath, plasmaWordIndex.DBFILE_ACTIVE_CRAWL_PROFILES);
+ final File noticeUrlDbFile = new File(plasmaPath,"urlNotice1.db");
+ final File profileDbFile = new File(plasmaPath, plasmaWordIndex.DBFILE_ACTIVE_CRAWL_PROFILES);
String errorMsg = null;
if (!plasmaPath.exists())
@@ -89,7 +89,7 @@ public class NoticeURLImporter extends AbstractImporter implements Importer {
}
public String getStatus() {
- StringBuffer theStatus = new StringBuffer();
+ final StringBuffer theStatus = new StringBuffer();
theStatus.append("#URLs=").append(this.urlCount).append("\n");
theStatus.append("#Profiles=").append(this.profileCount);
@@ -104,7 +104,7 @@ public class NoticeURLImporter extends AbstractImporter implements Importer {
//this.importNurlDB.waitOnInitThread();
// the stack types we want to import
- int[] stackTypes = new int[] {
+ final int[] stackTypes = new int[] {
NoticedURL.STACK_TYPE_CORE,
NoticedURL.STACK_TYPE_LIMIT,
NoticedURL.STACK_TYPE_REMOTE,
@@ -119,7 +119,7 @@ public class NoticeURLImporter extends AbstractImporter implements Importer {
}
// getting an iterator and loop through the URL entries
- Iterator<CrawlEntry> entryIter = (stackTypes[stackType] == -1) ? this.importNurlDB.iterator(stackType) : null;
+ final Iterator<CrawlEntry> entryIter = (stackTypes[stackType] == -1) ? this.importNurlDB.iterator(stackType) : null;
while (true) {
String nextHash = null;
@@ -139,7 +139,7 @@ public class NoticeURLImporter extends AbstractImporter implements Importer {
nextEntry = entryIter.next();
nextHash = nextEntry.url().hash();
}
- } catch (IOException e) {
+ } catch (final IOException e) {
this.log.logWarning("Unable to import entry: " + e.toString());
if ((stackTypes[stackType] != -1) &&(this.importNurlDB.stackSize(stackTypes[stackType]) == 0)) break;
@@ -148,7 +148,7 @@ public class NoticeURLImporter extends AbstractImporter implements Importer {
// getting a handler to the crawling profile the url belongs to
try {
- String profileHandle = nextEntry.profileHandle();
+ final String profileHandle = nextEntry.profileHandle();
if (profileHandle == null) {
this.log.logWarning("Profile handle of url entry '" + nextHash + "' unknown.");
continue;
@@ -158,12 +158,12 @@ public class NoticeURLImporter extends AbstractImporter implements Importer {
if (!this.importProfileHandleCache.contains(profileHandle)) {
// testing if the profile is already known
- CrawlProfile.entry profileEntry = this.activeCrawls.getEntry(profileHandle);
+ final CrawlProfile.entry profileEntry = this.activeCrawls.getEntry(profileHandle);
// if not we need to import it
if (profileEntry == null) {
// copy and store the source profile entry into the destination db
- CrawlProfile.entry sourceEntry = this.importProfileDB.getEntry(profileHandle);
+ final CrawlProfile.entry sourceEntry = this.importProfileDB.getEntry(profileHandle);
if (sourceEntry != null) {
this.profileCount++;
this.importProfileHandleCache.add(profileHandle);
@@ -198,7 +198,7 @@ public class NoticeURLImporter extends AbstractImporter implements Importer {
// TODO: what todo with nurlDB entries that do not exist in any stack?
- } catch (Exception e) {
+ } catch (final Exception e) {
this.error = e.toString();
this.log.logSevere("Import process had detected an error",e);
} finally {
diff --git a/source/de/anomic/crawler/NoticedURL.java b/source/de/anomic/crawler/NoticedURL.java
index 94821ff6a..99825746e 100755
--- a/source/de/anomic/crawler/NoticedURL.java
+++ b/source/de/anomic/crawler/NoticedURL.java
@@ -57,7 +57,7 @@ public class NoticedURL {
private long minimumLocalDelta;
private long minimumGlobalDelta;
- public NoticedURL(File cachePath) {
+ public NoticedURL(final File cachePath) {
this.coreStack = new Balancer(cachePath, "urlNoticeCoreStack", false);
this.limitStack = new Balancer(cachePath, "urlNoticeLimitStack", false);
//overhangStack = new plasmaCrawlBalancer(overhangStackFile);
@@ -74,11 +74,11 @@ public class NoticedURL {
return this.minimumGlobalDelta;
}
- public void setMinimumLocalDelta(long newDelta) {
+ public void setMinimumLocalDelta(final long newDelta) {
this.minimumLocalDelta = Math.max(minimumLocalDeltaInit, newDelta);
}
- public void setMinimumGlobalDelta(long newDelta) {
+ public void setMinimumGlobalDelta(final long newDelta) {
this.minimumGlobalDelta = Math.max(minimumGlobalDeltaInit, newDelta);
}
@@ -120,7 +120,7 @@ public class NoticedURL {
return ((coreStack == null) ? 0 : coreStack.size()) + ((limitStack == null) ? 0 : limitStack.size()) + ((remoteStack == null) ? 0 : remoteStack.size());
}
- public int stackSize(int stackType) {
+ public int stackSize(final int stackType) {
switch (stackType) {
case STACK_TYPE_CORE: return (coreStack == null) ? 0 : coreStack.size();
case STACK_TYPE_LIMIT: return (limitStack == null) ? 0 : limitStack.size();
@@ -130,7 +130,7 @@ public class NoticedURL {
}
}
- public boolean existsInStack(String urlhash) {
+ public boolean existsInStack(final String urlhash) {
return
coreStack.has(urlhash) ||
limitStack.has(urlhash) ||
@@ -138,7 +138,7 @@ public class NoticedURL {
remoteStack.has(urlhash);
}
- public void push(int stackType, CrawlEntry entry) {
+ public void push(final int stackType, final CrawlEntry entry) {
try {
switch (stackType) {
case STACK_TYPE_CORE:
@@ -152,14 +152,14 @@ public class NoticedURL {
break;
default: break;
}
- } catch (IOException er) {}
+ } catch (final IOException er) {}
}
- public CrawlEntry get(String urlhash) {
+ public CrawlEntry get(final String urlhash) {
CrawlEntry entry = null;
- try {if ((entry = coreStack.get(urlhash)) != null) return entry;} catch (IOException e) {}
- try {if ((entry = limitStack.get(urlhash)) != null) return entry;} catch (IOException e) {}
- try {if ((entry = remoteStack.get(urlhash)) != null) return entry;} catch (IOException e) {}
+ try {if ((entry = coreStack.get(urlhash)) != null) return entry;} catch (final IOException e) {}
+ try {if ((entry = limitStack.get(urlhash)) != null) return entry;} catch (final IOException e) {}
+ try {if ((entry = remoteStack.get(urlhash)) != null) return entry;} catch (final IOException e) {}
return null;
}
@@ -169,24 +169,24 @@ public class NoticedURL {
* @param urlhash
* @return true, if the entry was removed; false if not
*/
- public boolean removeByURLHash(String urlhash) {
- HashSet<String> urlHashes = new HashSet<String>();
+ public boolean removeByURLHash(final String urlhash) {
+ final HashSet<String> urlHashes = new HashSet<String>();
urlHashes.add(urlhash);
- try {return coreStack.remove(urlHashes) > 0;} catch (IOException e) {}
- try {return limitStack.remove(urlHashes) > 0;} catch (IOException e) {}
- try {return remoteStack.remove(urlHashes) > 0;} catch (IOException e) {}
+ try {return coreStack.remove(urlHashes) > 0;} catch (final IOException e) {}
+ try {return limitStack.remove(urlHashes) > 0;} catch (final IOException e) {}
+ try {return remoteStack.remove(urlHashes) > 0;} catch (final IOException e) {}
return false;
}
- public int removeByProfileHandle(String handle, long timeout) {
+ public int removeByProfileHandle(final String handle, final long timeout) {
int removed = 0;
- try {removed += coreStack.removeAllByProfileHandle(handle, timeout);} catch (IOException e) {}
- try {removed += limitStack.removeAllByProfileHandle(handle, timeout);} catch (IOException e) {}
- try {removed += remoteStack.removeAllByProfileHandle(handle, timeout);} catch (IOException e) {}
+ try {removed += coreStack.removeAllByProfileHandle(handle, timeout);} catch (final IOException e) {}
+ try {removed += limitStack.removeAllByProfileHandle(handle, timeout);} catch (final IOException e) {}
+ try {removed += remoteStack.removeAllByProfileHandle(handle, timeout);} catch (final IOException e) {}
return removed;
}
- public ArrayList<CrawlEntry> top(int stackType, int count) {
+ public ArrayList<CrawlEntry> top(final int stackType, final int count) {
switch (stackType) {
case STACK_TYPE_CORE: return top(coreStack, count);
case STACK_TYPE_LIMIT: return top(limitStack, count);
@@ -195,7 +195,7 @@ public class NoticedURL {
}
}
- public CrawlEntry pop(int stackType, boolean delay) throws IOException {
+ public CrawlEntry pop(final int stackType, final boolean delay) throws IOException {
switch (stackType) {
case STACK_TYPE_CORE: return pop(coreStack, delay);
case STACK_TYPE_LIMIT: return pop(limitStack, delay);
@@ -204,16 +204,16 @@ public class NoticedURL {
}
}
- public void shift(int fromStack, int toStack) {
+ public void shift(final int fromStack, final int toStack) {
try {
- CrawlEntry entry = pop(fromStack, false);
+ final CrawlEntry entry = pop(fromStack, false);
if (entry != null) push(toStack, entry);
- } catch (IOException e) {
+ } catch (final IOException e) {
return;
}
}
- public void clear(int stackType) {
+ public void clear(final int stackType) {
switch (stackType) {
case STACK_TYPE_CORE: coreStack.clear(); break;
case STACK_TYPE_LIMIT: limitStack.clear(); break;
@@ -222,7 +222,7 @@ public class NoticedURL {
}
}
- private CrawlEntry pop(Balancer balancer, boolean delay) throws IOException {
+ private CrawlEntry pop(final Balancer balancer, final boolean delay) throws IOException {
// this is a filo - pop
int s;
CrawlEntry entry;
@@ -231,7 +231,7 @@ public class NoticedURL {
entry = balancer.pop((delay) ? minimumLocalDelta : 0, (delay) ? minimumGlobalDelta : 0, maximumDomAge);
if (entry == null) {
if (s > balancer.size()) continue;
- int aftersize = balancer.size();
+ final int aftersize = balancer.size();
balancer.clear(); // the balancer is broken and cannot shrink
throw new IOException("entry is null, balancer cannot shrink (bevore pop = " + s + ", after pop = " + aftersize + "); reset of balancer");
}
@@ -241,26 +241,26 @@ public class NoticedURL {
throw new IOException("balancer stack is empty");
}
- private ArrayList<CrawlEntry> top(Balancer balancer, int count) {
+ private ArrayList<CrawlEntry> top(final Balancer balancer, int count) {
// this is a filo - top
if (count > balancer.size()) count = balancer.size();
ArrayList<CrawlEntry> list;
try {
list = balancer.top(count);
- } catch (IOException e) {
+ } catch (final IOException e) {
list = new ArrayList<CrawlEntry>(0);
}
return list;
}
- public Iterator<CrawlEntry> iterator(int stackType) {
+ public Iterator<CrawlEntry> iterator(final int stackType) {
// returns an iterator of plasmaCrawlBalancerEntry Objects
try {switch (stackType) {
case STACK_TYPE_CORE: return coreStack.iterator();
case STACK_TYPE_LIMIT: return limitStack.iterator();
case STACK_TYPE_REMOTE: return remoteStack.iterator();
default: return null;
- }} catch (IOException e) {
+ }} catch (final IOException e) {
return new HashSet<CrawlEntry>().iterator();
}
}
diff --git a/source/de/anomic/crawler/ProtocolLoader.java b/source/de/anomic/crawler/ProtocolLoader.java
index e82a45faf..e6653c03f 100644
--- a/source/de/anomic/crawler/ProtocolLoader.java
+++ b/source/de/anomic/crawler/ProtocolLoader.java
@@ -42,13 +42,13 @@ public final class ProtocolLoader {
private static final long minDelay = 250; // milliseconds; 4 accesses per second
private static final ConcurrentHashMap<String, Long> accessTime = new ConcurrentHashMap<String, Long>(); // to protect targets from DDoS
- private plasmaSwitchboard sb;
- private serverLog log;
- private HashSet<String> supportedProtocols;
- private HTTPLoader httpLoader;
- private FTPLoader ftpLoader;
+ private final plasmaSwitchboard sb;
+ private final serverLog log;
+ private final HashSet<String> supportedProtocols;
+ private final HTTPLoader httpLoader;
+ private final FTPLoader ftpLoader;
- public ProtocolLoader(plasmaSwitchboard sb, serverLog log) {
+ public ProtocolLoader(final plasmaSwitchboard sb, final serverLog log) {
this.sb = sb;
this.log = log;
this.supportedProtocols = new HashSet<String>(Arrays.asList(new String[]{"http","https","ftp"}));
@@ -58,7 +58,7 @@ public final class ProtocolLoader {
ftpLoader = new FTPLoader(sb, log);
}
- public boolean isSupportedProtocol(String protocol) {
+ public boolean isSupportedProtocol(final String protocol) {
if ((protocol == null) || (protocol.length() == 0)) return false;
return this.supportedProtocols.contains(protocol.trim().toLowerCase());
}
@@ -68,10 +68,10 @@ public final class ProtocolLoader {
return (HashSet<String>) this.supportedProtocols.clone();
}
- public plasmaHTCache.Entry load(CrawlEntry entry, String parserMode) {
+ public plasmaHTCache.Entry load(final CrawlEntry entry, final String parserMode) {
// getting the protocol of the next URL
- String protocol = entry.url().getProtocol();
- String host = entry.url().getHost();
+ final String protocol = entry.url().getProtocol();
+ final String host = entry.url().getHost();
// check if this loads a page from localhost, which must be prevented to protect the server
// against attacks to the administration interface when localhost access is granted
@@ -79,13 +79,13 @@ public final class ProtocolLoader {
// check access time
if (!entry.url().isLocal()) {
- Long lastAccess = accessTime.get(host);
+ final Long lastAccess = accessTime.get(host);
long wait = 0;
if (lastAccess != null) wait = Math.max(0, minDelay + lastAccess.longValue() - System.currentTimeMillis());
if (wait > 0) {
// force a sleep here. Instead just sleep we clean up the accessTime map
- long untilTime = System.currentTimeMillis() + wait;
- Iterator<Map.Entry<String, Long>> i = accessTime.entrySet().iterator();
+ final long untilTime = System.currentTimeMillis() + wait;
+ final Iterator<Map.Entry<String, Long>> i = accessTime.entrySet().iterator();
Map.Entry<String, Long> e;
while (i.hasNext()) {
e = i.next();
@@ -93,7 +93,7 @@ public final class ProtocolLoader {
if (System.currentTimeMillis() - e.getValue().longValue() > minDelay) i.remove();
}
if (System.currentTimeMillis() < untilTime)
- try {Thread.sleep(untilTime - System.currentTimeMillis());} catch (InterruptedException ee) {}
+ try {Thread.sleep(untilTime - System.currentTimeMillis());} catch (final InterruptedException ee) {}
}
}
accessTime.put(host, System.currentTimeMillis());
@@ -106,7 +106,7 @@ public final class ProtocolLoader {
return null;
}
- public String process(CrawlEntry entry, String parserMode) {
+ public String process(final CrawlEntry entry, final String parserMode) {
// load a resource, store it to htcache and push queue entry to switchboard queue
// returns null if everything went fine, a fail reason string if a problem occurred
plasmaHTCache.Entry h;
@@ -114,10 +114,10 @@ public final class ProtocolLoader {
h = load(entry, parserMode);
entry.setStatus("loaded");
if (h == null) return "load failed";
- boolean stored = sb.htEntryStoreProcess(h);
+ final boolean stored = sb.htEntryStoreProcess(h);
entry.setStatus("stored-" + ((stored) ? "ok" : "fail"));
return (stored) ? null : "not stored";
- } catch (Exception e) {
+ } catch (final Exception e) {
log.logWarning("problem loading " + entry.url().toString(), e);
return "load error - " + e.getMessage();
}
diff --git a/source/de/anomic/crawler/ResourceObserver.java b/source/de/anomic/crawler/ResourceObserver.java
index acd992ab9..9c9a75f8d 100644
--- a/source/de/anomic/crawler/ResourceObserver.java
+++ b/source/de/anomic/crawler/ResourceObserver.java
@@ -50,11 +50,11 @@ public final class ResourceObserver {
private boolean disksOK;
private boolean memoryOK;
- public ResourceObserver(plasmaSwitchboard sb) {
+ public ResourceObserver(final plasmaSwitchboard sb) {
this.sb = sb;
this.log.logInfo("initializing the resource observer");
- ArrayList<String> pathsToCheck = new ArrayList<String>();
+ final ArrayList<String> pathsToCheck = new ArrayList<String>();
// FIXME whats about the secondary path???
// = (getConfig(plasmaSwitchboard.INDEX_SECONDARY_PATH, "");
final String[] pathes = {plasmaSwitchboard.HTDOCS_PATH,
@@ -142,7 +142,7 @@ public final class ResourceObserver {
final HashMap<String, long[]> usage = diskUsage.getDiskUsage();
long[] val;
- for (Map.Entry<String, long[]> entry: usage.entrySet()) {
+ for (final Map.Entry<String, long[]> entry: usage.entrySet()) {
val = entry.getValue();
this.log.logInfo("df of Volume " + entry.getKey() + ": " + (val[1] / 1024 / 1024) + " MB");
if (val[1] < MIN_FREE_DISK_SPACE) {
diff --git a/source/de/anomic/crawler/ResultImages.java b/source/de/anomic/crawler/ResultImages.java
index 87aa267cc..dff202d46 100755
--- a/source/de/anomic/crawler/ResultImages.java
+++ b/source/de/anomic/crawler/ResultImages.java
@@ -49,17 +49,17 @@ public class ResultImages {
// the same images may be linked from different pages
private static final ConcurrentHashMap<String, Long> doubleCheck = new ConcurrentHashMap<String, Long>(); // (url-hash, time) when the url appeared first
- public static void registerImages(plasmaParserDocument document, boolean privateEntry) {
+ public static void registerImages(final plasmaParserDocument document, final boolean privateEntry) {
if (document == null) return;
if (document.dc_source() == null) return;
- HashMap<String, htmlFilterImageEntry> images = document.getImages();
- for (htmlFilterImageEntry image: images.values()) {
+ final HashMap<String, htmlFilterImageEntry> images = document.getImages();
+ for (final htmlFilterImageEntry image: images.values()) {
// do a double-check; attention: this can be time-consuming since this possibly needs a DNS-lookup
if (doubleCheck.containsKey(image.url().hash())) continue;
doubleCheck.put(image.url().hash(), System.currentTimeMillis());
- String name = image.url().getFile();
+ final String name = image.url().getFile();
boolean good = false;
if (image.width() > 120 &&
image.height() > 100 &&
@@ -94,7 +94,7 @@ public class ResultImages {
}
}
- public static OriginEntry next(boolean privateEntryOnly) {
+ public static OriginEntry next(final boolean privateEntryOnly) {
OriginEntry e = null;
if (privateEntryOnly) {
e = privateImageQueueHigh.poll();
@@ -108,7 +108,7 @@ public class ResultImages {
return e;
}
- public static int queueSize(boolean privateEntryOnly) {
+ public static int queueSize(final boolean privateEntryOnly) {
if (privateEntryOnly) {
return privateImageQueueHigh.size() + privateImageQueueLow.size();
} else {
@@ -144,7 +144,7 @@ public class ResultImages {
public static class OriginEntry {
public htmlFilterImageEntry imageEntry;
public yacyURL baseURL;
- public OriginEntry(htmlFilterImageEntry imageEntry, yacyURL baseURL) {
+ public OriginEntry(final htmlFilterImageEntry imageEntry, final yacyURL baseURL) {
this.imageEntry = imageEntry;
this.baseURL = baseURL;
}
diff --git a/source/de/anomic/crawler/ResultURLs.java b/source/de/anomic/crawler/ResultURLs.java
index 19b9b384c..eb3acc3b4 100644
--- a/source/de/anomic/crawler/ResultURLs.java
+++ b/source/de/anomic/crawler/ResultURLs.java
@@ -66,7 +66,7 @@ public final class ResultURLs {
gcrawlResultStack = new LinkedList<String>();
}
- public synchronized void stack(indexURLReference e, String initiatorHash, String executorHash, int stackType) {
+ public synchronized void stack(final indexURLReference e, final String initiatorHash, final String executorHash, final int stackType) {
assert initiatorHash != null;
assert executorHash != null;
if (e == null) { return; }
@@ -76,17 +76,17 @@ public final class ResultURLs {
resultStack.add(e.hash() + initiatorHash + executorHash);
}
return;
- } catch (Exception ex) {
+ } catch (final Exception ex) {
System.out.println("INTERNAL ERROR in newEntry/2: " + ex.toString());
return;
}
}
- public synchronized void notifyGCrawl(String urlHash, String initiatorHash, String executorHash) {
+ public synchronized void notifyGCrawl(final String urlHash, final String initiatorHash, final String executorHash) {
gcrawlResultStack.add(urlHash + initiatorHash + executorHash);
}
- public synchronized int getStackSize(int stack) {
+ public synchronized int getStackSize(final int stack) {
final List<String> resultStack = getStack(stack);
if(resultStack != null) {
return resultStack.size();
@@ -95,15 +95,15 @@ public final class ResultURLs {
}
}
- public synchronized String getUrlHash(int stack, int pos) {
+ public synchronized String getUrlHash(final int stack, final int pos) {
return getHashNo(stack, pos, 0);
}
- public synchronized String getInitiatorHash(int stack, int pos) {
+ public synchronized String getInitiatorHash(final int stack, final int pos) {
return getHashNo(stack, pos, 1);
}
- public synchronized String getExecutorHash(final int stack, int pos) {
+ public synchronized String getExecutorHash(final int stack, final int pos) {
return getHashNo(stack, pos, 2);
}
@@ -152,7 +152,7 @@ public final class ResultURLs {
* @param pos
* @return null if either stack or element do not exist
*/
- private String getResultStackAt(final int stack, int pos) {
+ private String getResultStackAt(final int stack, final int pos) {
assert pos >= 0 : "precondition violated: " + pos + " >= 0";
final List<String> resultStack = getStack(stack);
@@ -196,7 +196,7 @@ public final class ResultURLs {
return getStack(stack) != null;
}
- public synchronized boolean removeStack(int stack, int pos) {
+ public synchronized boolean removeStack(final int stack, final int pos) {
// Object prevElement = null;
// switch (stack) {
// case 1: prevElement = externResultStack.remove(pos); break;
@@ -215,7 +215,7 @@ public final class ResultURLs {
}
}
- public synchronized void clearStack(int stack) {
+ public synchronized void clearStack(final int stack) {
final List<String> resultStack = getStack(stack);
if(resultStack != null) {
resultStack.clear();
@@ -230,7 +230,7 @@ public final class ResultURLs {
// }
}
- public synchronized boolean remove(String urlHash) {
+ public synchronized boolean remove(final String urlHash) {
if (urlHash == null) return false;
for (int stack = 1; stack <= 6; stack++) {
for (int i = getStackSize(stack) - 1; i >= 0; i--) {
@@ -247,7 +247,7 @@ public final class ResultURLs {
* test and benchmark
* @param args
*/
- public static void main(String[] args) {
+ public static void main(final String[] args) {
final ResultURLs results = new ResultURLs();
try {
final yacyURL url = new yacyURL("http", "www.yacy.net", 80, "/");
@@ -291,7 +291,7 @@ public final class ResultURLs {
}
}
System.out.println("benschmark: "+ (System.currentTimeMillis() - start) + " ms");
- } catch (MalformedURLException e) {
+ } catch (final MalformedURLException e) {
e.printStackTrace();
}
}
diff --git a/source/de/anomic/crawler/RobotsTxt.java b/source/de/anomic/crawler/RobotsTxt.java
index d616bb166..ca9918e3b 100644
--- a/source/de/anomic/crawler/RobotsTxt.java
+++ b/source/de/anomic/crawler/RobotsTxt.java
@@ -60,17 +60,17 @@ public class RobotsTxt {
kelondroMap robotsTable;
private final File robotsTableFile;
- private ConcurrentHashMap<String, Long> syncObjects;
+ private final ConcurrentHashMap<String, Long> syncObjects;
//private static final HashSet<String> loadedRobots = new HashSet<String>(); // only for debugging
- public RobotsTxt(File robotsTableFile) {
+ public RobotsTxt(final File robotsTableFile) {
this.robotsTableFile = robotsTableFile;
robotsTableFile.getParentFile().mkdirs();
kelondroBLOB blob = null;
if (robotsTableFile.getName().endsWith(".heap")) {
try {
blob = new kelondroBLOBHeap(robotsTableFile, 64, kelondroNaturalOrder.naturalOrder);
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
} else {
@@ -101,15 +101,15 @@ public class RobotsTxt {
}
@SuppressWarnings("unchecked")
- private Entry getEntry(String urlHostPort, boolean fetchOnlineIfNotAvailableOrNotFresh) {
+ private Entry getEntry(final String urlHostPort, final boolean fetchOnlineIfNotAvailableOrNotFresh) {
// this method will always return a non-null value
Entry robotsTxt4Host = null;
try {
- HashMap<String, String> record = this.robotsTable.get(urlHostPort);
+ final HashMap<String, String> record = this.robotsTable.get(urlHostPort);
if (record != null) robotsTxt4Host = new Entry(urlHostPort, record);
- } catch (kelondroException e) {
+ } catch (final kelondroException e) {
resetDatabase();
- } catch (IOException e) {
+ } catch (final IOException e) {
resetDatabase();
}
@@ -134,11 +134,11 @@ public class RobotsTxt {
// check the robots table again for all threads that come here because they waited for another one
// to complete a download
try {
- HashMap<String, String> record = this.robotsTable.get(urlHostPort);
+ final HashMap<String, String> record = this.robotsTable.get(urlHostPort);
if (record != null) robotsTxt4Host = new Entry(urlHostPort, record);
- } catch (kelondroException e) {
+ } catch (final kelondroException e) {
resetDatabase();
- } catch (IOException e) {
+ } catch (final IOException e) {
resetDatabase();
}
if (robotsTxt4Host != null &&
@@ -151,7 +151,7 @@ public class RobotsTxt {
yacyURL robotsURL = null;
try {
robotsURL = new yacyURL("http://" + urlHostPort + "/robots.txt", null);
- } catch (MalformedURLException e) {
+ } catch (final MalformedURLException e) {
serverLog.logSevere("ROBOTS","Unable to generate robots.txt URL for host:port '" + urlHostPort + "'.");
robotsURL = null;
}
@@ -161,7 +161,7 @@ public class RobotsTxt {
serverLog.logFine("ROBOTS","Trying to download the robots.txt file from URL '" + robotsURL + "'.");
try {
result = downloadRobotsTxt(robotsURL, 5, robotsTxt4Host);
- } catch (Exception e) {
+ } catch (final Exception e) {
result = null;
}
}
@@ -193,7 +193,7 @@ public class RobotsTxt {
// store the data into the robots DB
addEntry(robotsTxt4Host);
} else {
- robotsParser parserResult = new robotsParser((byte[]) result[DOWNLOAD_ROBOTS_TXT]);
+ final robotsParser parserResult = new robotsParser((byte[]) result[DOWNLOAD_ROBOTS_TXT]);
ArrayList<String> denyPath = parserResult.denyList();
if (((Boolean) result[DOWNLOAD_ACCESS_RESTRICTED]).booleanValue()) {
denyPath = new ArrayList<String>();
@@ -217,35 +217,35 @@ public class RobotsTxt {
return robotsTxt4Host;
}
- public int crawlDelay(yacyURL theURL) {
- String urlHostPort = getHostPort(theURL);
- RobotsTxt.Entry robotsEntry = getEntry(urlHostPort, true);
+ public int crawlDelay(final yacyURL theURL) {
+ final String urlHostPort = getHostPort(theURL);
+ final RobotsTxt.Entry robotsEntry = getEntry(urlHostPort, true);
return robotsEntry.getCrawlDelay();
}
private Entry addEntry(
- String hostName,
- ArrayList<String> allowPathList,
- ArrayList<String> denyPathList,
- Date loadedDate,
- Date modDate,
- String eTag,
- String sitemap,
- int crawlDelay
+ final String hostName,
+ final ArrayList<String> allowPathList,
+ final ArrayList<String> denyPathList,
+ final Date loadedDate,
+ final Date modDate,
+ final String eTag,
+ final String sitemap,
+ final int crawlDelay
) {
- Entry entry = new Entry(
+ final Entry entry = new Entry(
hostName, allowPathList, denyPathList, loadedDate, modDate,
eTag, sitemap, crawlDelay);
addEntry(entry);
return entry;
}
- private String addEntry(Entry entry) {
+ private String addEntry(final Entry entry) {
// writes a new page and returns key
try {
this.robotsTable.put(entry.hostName, entry.mem);
return entry.hostName;
- } catch (IOException e) {
+ } catch (final IOException e) {
return null;
}
}
@@ -264,15 +264,15 @@ public class RobotsTxt {
private LinkedList<String> allowPathList, denyPathList;
String hostName;
- public Entry(String hostName, HashMap<String, String> mem) {
+ public Entry(final String hostName, final HashMap<String, String> mem) {
this.hostName = hostName.toLowerCase();
this.mem = mem;
if (this.mem.containsKey(DISALLOW_PATH_LIST)) {
this.denyPathList = new LinkedList<String>();
- String csPl = this.mem.get(DISALLOW_PATH_LIST);
+ final String csPl = this.mem.get(DISALLOW_PATH_LIST);
if (csPl.length() > 0){
- String[] pathArray = csPl.split(ROBOTS_DB_PATH_SEPARATOR);
+ final String[] pathArray = csPl.split(ROBOTS_DB_PATH_SEPARATOR);
if ((pathArray != null)&&(pathArray.length > 0)) {
this.denyPathList.addAll(Arrays.asList(pathArray));
}
@@ -282,9 +282,9 @@ public class RobotsTxt {
}
if (this.mem.containsKey(ALLOW_PATH_LIST)) {
this.allowPathList = new LinkedList<String>();
- String csPl = this.mem.get(ALLOW_PATH_LIST);
+ final String csPl = this.mem.get(ALLOW_PATH_LIST);
if (csPl.length() > 0){
- String[] pathArray = csPl.split(ROBOTS_DB_PATH_SEPARATOR);
+ final String[] pathArray = csPl.split(ROBOTS_DB_PATH_SEPARATOR);
if ((pathArray != null)&&(pathArray.length > 0)) {
this.allowPathList.addAll(Arrays.asList(pathArray));
}
@@ -295,14 +295,14 @@ public class RobotsTxt {
}
public Entry(
- String hostName,
- ArrayList<String> allowPathList,
- ArrayList<String> disallowPathList,
- Date loadedDate,
- Date modDate,
- String eTag,
- String sitemap,
- int crawlDelay
+ final String hostName,
+ final ArrayList<String> allowPathList,
+ final ArrayList<String> disallowPathList,
+ final Date loadedDate,
+ final Date modDate,
+ final String eTag,
+ final String sitemap,
+ final int crawlDelay
) {
if ((hostName == null) || (hostName.length() == 0)) throw new IllegalArgumentException("The hostname is missing");
@@ -320,7 +320,7 @@ public class RobotsTxt {
if ((allowPathList != null)&&(allowPathList.size()>0)) {
this.allowPathList.addAll(allowPathList);
- StringBuffer pathListStr = new StringBuffer();
+ final StringBuffer pathListStr = new StringBuffer();
for (int i=0; i<allowPathList.size();i++) {
pathListStr.append(allowPathList.get(i))
.append(ROBOTS_DB_PATH_SEPARATOR);
@@ -331,7 +331,7 @@ public class RobotsTxt {
if ((disallowPathList != null)&&(disallowPathList.size()>0)) {
this.denyPathList.addAll(disallowPathList);
- StringBuffer pathListStr = new StringBuffer();
+ final StringBuffer pathListStr = new StringBuffer();
for (int i=0; i<disallowPathList.size();i++) {
pathListStr.append(disallowPathList.get(i))
.append(ROBOTS_DB_PATH_SEPARATOR);
@@ -341,7 +341,7 @@ public class RobotsTxt {
}
public String toString() {
- StringBuffer str = new StringBuffer();
+ final StringBuffer str = new StringBuffer();
str.append((this.hostName==null)?"null":this.hostName)
.append(": ");
@@ -363,7 +363,7 @@ public class RobotsTxt {
return null;
}
- public void setLoadedDate(Date newLoadedDate) {
+ public void setLoadedDate(final Date newLoadedDate) {
if (newLoadedDate != null) {
this.mem.put(LOADED_DATE,Long.toString(newLoadedDate.getTime()));
}
@@ -386,7 +386,7 @@ public class RobotsTxt {
public int getCrawlDelay() {
if (this.mem.containsKey(CRAWL_DELAY)) try {
return Integer.parseInt(this.mem.get(CRAWL_DELAY));
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
return 0;
}
return 0;
@@ -400,9 +400,9 @@ public class RobotsTxt {
// escaping all occurences of ; because this char is used as special char in the Robots DB
else path = path.replaceAll(ROBOTS_DB_PATH_SEPARATOR,"%3B");
- Iterator<String> pathIter = this.denyPathList.iterator();
+ final Iterator<String> pathIter = this.denyPathList.iterator();
while (pathIter.hasNext()) {
- String nextPath = pathIter.next();
+ final String nextPath = pathIter.next();
// disallow rule
if (path.startsWith(nextPath)) {
@@ -421,16 +421,16 @@ public class RobotsTxt {
public static final int DOWNLOAD_ETAG = 2;
public static final int DOWNLOAD_MODDATE = 3;
- private static final String getHostPort(yacyURL theURL) {
+ private static final String getHostPort(final yacyURL theURL) {
String urlHostPort = null;
- int port = getPort(theURL);
+ final int port = getPort(theURL);
urlHostPort = theURL.getHost() + ":" + port;
urlHostPort = urlHostPort.toLowerCase().intern();
return urlHostPort;
}
- private static final int getPort(yacyURL theURL) {
+ private static final int getPort(final yacyURL theURL) {
int port = theURL.getPort();
if (port == -1) {
if (theURL.getProtocol().equalsIgnoreCase("http")) {
@@ -443,48 +443,48 @@ public class RobotsTxt {
return port;
}
- public yacyURL getSitemapURL(yacyURL theURL) {
+ public yacyURL getSitemapURL(final yacyURL theURL) {
if (theURL == null) throw new IllegalArgumentException();
yacyURL sitemapURL = null;
// generating the hostname:poart string needed to do a DB lookup
- String urlHostPort = getHostPort(theURL);
- RobotsTxt.Entry robotsTxt4Host = this.getEntry(urlHostPort, true);
+ final String urlHostPort = getHostPort(theURL);
+ final RobotsTxt.Entry robotsTxt4Host = this.getEntry(urlHostPort, true);
try {
- String sitemapUrlStr = robotsTxt4Host.getSitemap();
+ final String sitemapUrlStr = robotsTxt4Host.getSitemap();
if (sitemapUrlStr != null) sitemapURL = new yacyURL(sitemapUrlStr, null);
- } catch (MalformedURLException e) {/* ignore this */}
+ } catch (final MalformedURLException e) {/* ignore this */}
return sitemapURL;
}
- public Integer getCrawlDelay(yacyURL theURL) {
+ public Integer getCrawlDelay(final yacyURL theURL) {
if (theURL == null) throw new IllegalArgumentException();
Integer crawlDelay = null;
// generating the hostname:poart string needed to do a DB lookup
- String urlHostPort = getHostPort(theURL);
- RobotsTxt.Entry robotsTxt4Host = getEntry(urlHostPort, true);
+ final String urlHostPort = getHostPort(theURL);
+ final RobotsTxt.Entry robotsTxt4Host = getEntry(urlHostPort, true);
try {
crawlDelay = robotsTxt4Host.getCrawlDelay();
- } catch (NumberFormatException e) {/* ignore this */}
+ } catch (final NumberFormatException e) {/* ignore this */}
return crawlDelay;
}
- public boolean isDisallowed(yacyURL nexturl) {
+ public boolean isDisallowed(final yacyURL nexturl) {
if (nexturl == null) throw new IllegalArgumentException();
// generating the hostname:port string needed to do a DB lookup
- String urlHostPort = getHostPort(nexturl);
+ final String urlHostPort = getHostPort(nexturl);
RobotsTxt.Entry robotsTxt4Host = null;
robotsTxt4Host = getEntry(urlHostPort, true);
return robotsTxt4Host.isDisallowed(nexturl.getFile());
}
- private static Object[] downloadRobotsTxt(yacyURL robotsURL, int redirectionCount, RobotsTxt.Entry entry) throws Exception {
+ private static Object[] downloadRobotsTxt(final yacyURL robotsURL, int redirectionCount, final RobotsTxt.Entry entry) throws Exception {
if (redirectionCount < 0) return new Object[]{Boolean.FALSE,null,null};
redirectionCount--;
@@ -508,14 +508,14 @@ public class RobotsTxt {
if (entry != null) {
oldEtag = entry.getETag();
reqHeaders = new httpHeader();
- Date modDate = entry.getModDate();
+ final Date modDate = entry.getModDate();
if (modDate != null) reqHeaders.put(httpHeader.IF_MODIFIED_SINCE,HttpClient.dateString(entry.getModDate()));
}
// setup http-client
//TODO: adding Traffic statistic for robots download?
- JakartaCommonsHttpClient client = new JakartaCommonsHttpClient(10000, reqHeaders, null);
+ final JakartaCommonsHttpClient client = new JakartaCommonsHttpClient(10000, reqHeaders, null);
JakartaCommonsHttpResponse res = null;
try {
// sending the get request
@@ -542,7 +542,7 @@ public class RobotsTxt {
}
// downloading the content
- serverByteBuffer sbb = new serverByteBuffer();
+ final serverByteBuffer sbb = new serverByteBuffer();
try {
serverFileUtils.copyToStream(new BufferedInputStream(res.getDataAsStream()), new BufferedOutputStream(sbb));
} finally {
@@ -566,7 +566,7 @@ public class RobotsTxt {
redirectionUrlString = redirectionUrlString.trim();
// generating the new URL object
- yacyURL redirectionUrl = yacyURL.newURL(robotsURL, redirectionUrlString);
+ final yacyURL redirectionUrl = yacyURL.newURL(robotsURL, redirectionUrlString);
// following the redirection
serverLog.logFinest("ROBOTS","Redirection detected for robots.txt with URL '" + robotsURL + "'." +
@@ -580,7 +580,7 @@ public class RobotsTxt {
serverLog.logFinest("ROBOTS","robots.txt could not be downloaded from URL '" + robotsURL + "'. [" + res.getStatusLine() + "].");
robotsTxt = null;
}
- } catch (Exception e) {
+ } catch (final Exception e) {
throw e;
} finally {
if(res != null) {
diff --git a/source/de/anomic/crawler/SitemapImporter.java b/source/de/anomic/crawler/SitemapImporter.java
index 3b3cf5c73..6ea03dbb6 100644
--- a/source/de/anomic/crawler/SitemapImporter.java
+++ b/source/de/anomic/crawler/SitemapImporter.java
@@ -33,9 +33,9 @@ public class SitemapImporter extends AbstractImporter implements Importer {
private SitemapParser parser = null;
private yacyURL sitemapURL = null;
- private ImporterManager superviser;
+ private final ImporterManager superviser;
- public SitemapImporter(plasmaSwitchboard sb, ImporterManager importManager, yacyURL sitemapURL, CrawlProfile.entry profileEntry) throws ImporterException {
+ public SitemapImporter(final plasmaSwitchboard sb, final ImporterManager importManager, final yacyURL sitemapURL, final CrawlProfile.entry profileEntry) throws ImporterException {
super("sitemap");
this.superviser = importManager;
try {
@@ -44,7 +44,7 @@ public class SitemapImporter extends AbstractImporter implements Importer {
// creating the sitemap parser
this.parser = new SitemapParser(sb, this.sitemapURL, profileEntry);
- } catch (Exception e) {
+ } catch (final Exception e) {
throw new ImporterException("Unable to initialize Importer",e);
}
}
@@ -52,8 +52,8 @@ public class SitemapImporter extends AbstractImporter implements Importer {
public long getEstimatedTime() {
- long t = getElapsedTime();
- int p = getProcessingStatusPercent();
+ final long t = getElapsedTime();
+ final int p = getProcessingStatusPercent();
return (p==0)?0:(t/p)*(100-p);
}
@@ -70,8 +70,8 @@ public class SitemapImporter extends AbstractImporter implements Importer {
public int getProcessingStatusPercent() {
if (this.parser == null) return 0;
- long total = this.parser.getTotalLength();
- long processed = this.parser.getProcessedLength();
+ final long total = this.parser.getTotalLength();
+ final long processed = this.parser.getProcessedLength();
if (total <= 1) return 0;
return (int) ((processed*100)/ total);
@@ -81,7 +81,7 @@ public class SitemapImporter extends AbstractImporter implements Importer {
* @see Importer#getStatus()
*/
public String getStatus() {
- StringBuffer theStatus = new StringBuffer();
+ final StringBuffer theStatus = new StringBuffer();
theStatus.append("#URLs=").append((this.parser==null)?0:this.parser.getUrlcount());
diff --git a/source/de/anomic/crawler/ZURL.java b/source/de/anomic/crawler/ZURL.java
index 2b6445566..26b6c93f1 100755
--- a/source/de/anomic/crawler/ZURL.java
+++ b/source/de/anomic/crawler/ZURL.java
@@ -57,12 +57,12 @@ public class ZURL {
// the class object
kelondroIndex urlIndex = null;
- private LinkedList<String> stack = new LinkedList<String>(); // strings: url
+ private final LinkedList<String> stack = new LinkedList<String>(); // strings: url
- public ZURL(File cachePath, String tablename, boolean startWithEmptyFile) {
+ public ZURL(final File cachePath, final String tablename, final boolean startWithEmptyFile) {
// creates a new ZURL in a file
cachePath.mkdirs();
- File f = new File(cachePath, tablename);
+ final File f = new File(cachePath, tablename);
if (startWithEmptyFile) {
if (f.exists()) {
if (f.isDirectory()) kelondroFlexWidthArray.delete(cachePath, tablename); else f.delete();
@@ -94,10 +94,10 @@ public class ZURL {
}
public synchronized Entry newEntry(
- CrawlEntry bentry,
- String executor,
- Date workdate,
- int workcount,
+ final CrawlEntry bentry,
+ final String executor,
+ final Date workdate,
+ final int workcount,
String anycause) {
assert executor != null;
assert executor.length() > 0;
@@ -105,21 +105,21 @@ public class ZURL {
return new Entry(bentry, executor, workdate, workcount, anycause);
}
- public boolean remove(String hash) {
+ public boolean remove(final String hash) {
if (hash == null) return false;
try {
urlIndex.remove(hash.getBytes());
return true;
- } catch (IOException e) {
+ } catch (final IOException e) {
return false;
}
}
- public synchronized void push(Entry e) {
+ public synchronized void push(final Entry e) {
stack.add(e.hash());
}
- public Entry top(int pos) {
+ public Entry top(final int pos) {
String urlhash;
synchronized (stack) {
if (pos >= stack.size()) return null;
@@ -129,18 +129,18 @@ public class ZURL {
return getEntry(urlhash);
}
- public synchronized Entry getEntry(String urlhash) {
+ public synchronized Entry getEntry(final String urlhash) {
try {
- kelondroRow.Entry entry = urlIndex.get(urlhash.getBytes());
+ final kelondroRow.Entry entry = urlIndex.get(urlhash.getBytes());
if (entry == null) return null;
return new Entry(entry);
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
return null;
}
}
- public boolean exists(String urlHash) {
+ public boolean exists(final String urlHash) {
return urlIndex.has(urlHash.getBytes());
}
@@ -155,18 +155,18 @@ public class ZURL {
public class Entry {
CrawlEntry bentry; // the balancer entry
- private String executor; // the crawling executor
- private Date workdate; // the time when the url was last time tried to load
- private int workcount; // number of tryings
- private String anycause; // string describing reason for load fail
+ private final String executor; // the crawling executor
+ private final Date workdate; // the time when the url was last time tried to load
+ private final int workcount; // number of tryings
+ private final String anycause; // string describing reason for load fail
private boolean stored;
public Entry(
- CrawlEntry bentry,
- String executor,
- Date workdate,
- int workcount,
- String anycause) {
+ final CrawlEntry bentry,
+ final String executor,
+ final Date workdate,
+ final int workcount,
+ final String anycause) {
// create new entry
assert bentry != null;
assert executor != null;
@@ -178,7 +178,7 @@ public class ZURL {
stored = false;
}
- public Entry(kelondroRow.Entry entry) throws IOException {
+ public Entry(final kelondroRow.Entry entry) throws IOException {
assert (entry != null);
this.executor = entry.getColString(1, "UTF-8");
this.workdate = new Date(entry.getColLong(2));
@@ -194,7 +194,7 @@ public class ZURL {
// stores the values from the object variables into the database
if (this.stored) return;
if (this.bentry == null) return;
- kelondroRow.Entry newrow = rowdef.newEntry();
+ final kelondroRow.Entry newrow = rowdef.newEntry();
newrow.setCol(0, this.bentry.url().hash().getBytes());
newrow.setCol(1, this.executor.getBytes());
newrow.setCol(2, this.workdate.getTime());
@@ -204,7 +204,7 @@ public class ZURL {
try {
if (urlIndex != null) urlIndex.put(newrow);
this.stored = true;
- } catch (IOException e) {
+ } catch (final IOException e) {
System.out.println("INTERNAL ERROR AT plasmaEURL:url2hash:" + e.toString());
}
}
@@ -245,7 +245,7 @@ public class ZURL {
Iterator<kelondroRow.Entry> i;
boolean error = false;
- public kiter(boolean up, String firstHash) throws IOException {
+ public kiter(final boolean up, final String firstHash) throws IOException {
i = urlIndex.rows(up, (firstHash == null) ? null : firstHash.getBytes());
error = false;
}
@@ -256,11 +256,11 @@ public class ZURL {
}
public Entry next() throws RuntimeException {
- kelondroRow.Entry e = i.next();
+ final kelondroRow.Entry e = i.next();
if (e == null) return null;
try {
return new Entry(e);
- } catch (IOException ex) {
+ } catch (final IOException ex) {
throw new RuntimeException("error '" + ex.getMessage() + "' for hash " + e.getColString(0, null));
}
}
@@ -271,7 +271,7 @@ public class ZURL {
}
- public Iterator<Entry> entries(boolean up, String firstHash) throws IOException {
+ public Iterator<Entry> entries(final boolean up, final String firstHash) throws IOException {
// enumerates entry elements
return new kiter(up, firstHash);
}
diff --git a/source/de/anomic/crawler/robotsParser.java b/source/de/anomic/crawler/robotsParser.java
index 3914b477c..29fa2da6d 100644
--- a/source/de/anomic/crawler/robotsParser.java
+++ b/source/de/anomic/crawler/robotsParser.java
@@ -67,20 +67,20 @@ public final class robotsParser {
private String sitemap;
private int crawlDelay;
- public robotsParser(byte[] robotsTxt) {
+ public robotsParser(final byte[] robotsTxt) {
if ((robotsTxt == null)||(robotsTxt.length == 0)) {
allowList = new ArrayList<String>(0);
denyList = new ArrayList<String>(0);
sitemap = "";
crawlDelay = 0;
} else {
- ByteArrayInputStream bin = new ByteArrayInputStream(robotsTxt);
- BufferedReader reader = new BufferedReader(new InputStreamReader(bin));
+ final ByteArrayInputStream bin = new ByteArrayInputStream(robotsTxt);
+ final BufferedReader reader = new BufferedReader(new InputStreamReader(bin));
parse(reader);
}
}
- public robotsParser(BufferedReader reader) {
+ public robotsParser(final BufferedReader reader) {
if (reader == null) {
allowList = new ArrayList<String>(0);
denyList = new ArrayList<String>(0);
@@ -91,11 +91,11 @@ public final class robotsParser {
}
}
- private void parse(BufferedReader reader) {
- ArrayList<String> deny4AllAgents = new ArrayList<String>();
- ArrayList<String> deny4YaCyAgent = new ArrayList<String>();
- ArrayList<String> allow4AllAgents = new ArrayList<String>();
- ArrayList<String> allow4YaCyAgent = new ArrayList<String>();
+ private void parse(final BufferedReader reader) {
+ final ArrayList<String> deny4AllAgents = new ArrayList<String>();
+ final ArrayList<String> deny4YaCyAgent = new ArrayList<String>();
+ final ArrayList<String> allow4AllAgents = new ArrayList<String>();
+ final ArrayList<String> allow4YaCyAgent = new ArrayList<String>();
int pos;
String line = null, lineUpper = null;
@@ -143,7 +143,7 @@ public final class robotsParser {
// getting out the robots name
pos = line.indexOf(" ");
if (pos != -1) {
- String userAgent = line.substring(pos).trim();
+ final String userAgent = line.substring(pos).trim();
isRule4AllAgents |= userAgent.equals("*");
isRule4YaCyAgent |= userAgent.toLowerCase().indexOf("yacy") >=0;
if (isRule4YaCyAgent) rule4YaCyFound = true;
@@ -153,14 +153,14 @@ public final class robotsParser {
if (pos != -1) {
try {
crawlDelay = Integer.parseInt(line.substring(pos).trim());
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
// invalid crawling delay
}
}
} else if (lineUpper.startsWith(ROBOTS_DISALLOW) ||
lineUpper.startsWith(ROBOTS_ALLOW)) {
inBlock = true;
- boolean isDisallowRule = lineUpper.startsWith(ROBOTS_DISALLOW);
+ final boolean isDisallowRule = lineUpper.startsWith(ROBOTS_DISALLOW);
if (isRule4YaCyAgent || isRule4AllAgents) {
// cutting off comments at the line end
@@ -182,7 +182,7 @@ public final class robotsParser {
// unencoding all special charsx
try {
path = URLDecoder.decode(path,"UTF-8");
- } catch (Exception e) {
+ } catch (final Exception e) {
/*
* url decoding failed. E.g. because of
* "Incomplete trailing escape (%) pattern"
@@ -204,7 +204,7 @@ public final class robotsParser {
}
}
}
- } catch (IOException e) {}
+ } catch (final IOException e) {}
allowList = (rule4YaCyFound) ? allow4YaCyAgent : allow4AllAgents;
denyList = (rule4YaCyFound) ? deny4YaCyAgent : deny4AllAgents;
diff --git a/source/de/anomic/data/SitemapParser.java b/source/de/anomic/data/SitemapParser.java
index bc3935db4..68189464b 100644
--- a/source/de/anomic/data/SitemapParser.java
+++ b/source/de/anomic/data/SitemapParser.java
@@ -34,6 +34,7 @@ import java.util.zip.GZIPInputStream;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
+import org.apache.commons.httpclient.protocol.Protocol;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
@@ -115,7 +116,7 @@ public class SitemapParser extends DefaultHandler {
/**
* the logger
*/
- private serverLog logger = new serverLog("SITEMAP");
+ private final serverLog logger = new serverLog("SITEMAP");
/**
* The location of the sitemap file
@@ -131,9 +132,9 @@ public class SitemapParser extends DefaultHandler {
* last modification date of the {@link #nextURL}
*/
private Date lastMod = null;
- private plasmaSwitchboard sb;
+ private final plasmaSwitchboard sb;
- public SitemapParser(plasmaSwitchboard sb, yacyURL sitemap, CrawlProfile.entry theCrawlingProfile) {
+ public SitemapParser(final plasmaSwitchboard sb, final yacyURL sitemap, final CrawlProfile.entry theCrawlingProfile) {
assert sitemap != null;
this.sb = sb;
this.siteMapURL = sitemap;
@@ -152,9 +153,9 @@ public class SitemapParser extends DefaultHandler {
*/
public void parse() {
// download document
- httpHeader header = new httpHeader();
+ final httpHeader header = new httpHeader();
header.put(httpHeader.USER_AGENT, HTTPLoader.crawlerUserAgent);
- JakartaCommonsHttpClient client = new JakartaCommonsHttpClient(5000, header, null);
+ final JakartaCommonsHttpClient client = new JakartaCommonsHttpClient(5000, header, null);
JakartaCommonsHttpResponse res = null;
try {
res = client.GET(siteMapURL.toString());
@@ -165,7 +166,7 @@ public class SitemapParser extends DefaultHandler {
}
// getting some metadata
- String contentMimeType = res.getResponseHeader().mime();
+ final String contentMimeType = res.getResponseHeader().mime();
this.contentLength = res.getResponseHeader().contentLength();
try {
@@ -176,17 +177,17 @@ public class SitemapParser extends DefaultHandler {
contentStream = new GZIPInputStream(contentStream);
}
- httpdByteCountInputStream counterStream = new httpdByteCountInputStream(contentStream, null);
+ final httpdByteCountInputStream counterStream = new httpdByteCountInputStream(contentStream, null);
// parse it
this.logger.logInfo("Start parsing sitemap file " + this.siteMapURL + "\n\tMimeType: " + contentMimeType +
"\n\tLength: " + this.contentLength);
- SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
+ final SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
saxParser.parse(counterStream, this);
streamCounter += counterStream.getCount();
} finally {
res.closeStream();
}
- } catch (Exception e) {
+ } catch (final Exception e) {
this.logger.logWarning("Unable to parse sitemap file " + this.siteMapURL, e);
} finally {
if (res != null) {
@@ -222,12 +223,12 @@ public class SitemapParser extends DefaultHandler {
* @param qName qualified name
* @see DefaultHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)
*/
- public void startElement(String namespaceURI, String localName, String qName, Attributes attrs) throws SAXException {
+ public void startElement(final String namespaceURI, final String localName, final String qName, final Attributes attrs) throws SAXException {
this.currentElement = qName;
// testing if the namespace is known
if (qName.equalsIgnoreCase(SITEMAP_URLSET)) {
- String namespace = attrs.getValue(SITEMAP_XMLNS);
+ final String namespace = attrs.getValue(SITEMAP_XMLNS);
if ((namespace == null) ||
((!namespace.equals(XMLNS_SITEMAPS_ORG)) && (!namespace.equals(XMLNS_SITEMAPS_GOOGLE))))
throw new SAXException("Unknown sitemap namespace: " + namespace);
@@ -240,7 +241,7 @@ public class SitemapParser extends DefaultHandler {
* @throws SAXException
* @see DefaultHandler#endElement(java.lang.String, java.lang.String, java.lang.String)
*/
- public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
+ public void endElement(final String namespaceURI, final String localName, final String qName) throws SAXException {
this.currentElement = "";
if (qName.equalsIgnoreCase(SITEMAP_URL)) {
@@ -253,17 +254,17 @@ public class SitemapParser extends DefaultHandler {
try {
url = new yacyURL(this.nextURL, null);
nexturlhash = url.hash();
- } catch (MalformedURLException e1) {
+ } catch (final MalformedURLException e1) {
}
// check if the url is known and needs to be recrawled
if (this.lastMod != null) {
- String dbocc = this.sb.urlExists(nexturlhash);
+ final String dbocc = this.sb.urlExists(nexturlhash);
if ((dbocc != null) && (dbocc.equalsIgnoreCase("loaded"))) {
// the url was already loaded. we need to check the date
- indexURLReference oldEntry = this.sb.webIndex.getURL(nexturlhash, null, 0);
+ final indexURLReference oldEntry = this.sb.webIndex.getURL(nexturlhash, null, 0);
if (oldEntry != null) {
- Date modDate = oldEntry.moddate();
+ final Date modDate = oldEntry.moddate();
// check if modDate is null
if (modDate.after(this.lastMod))
return;
@@ -283,7 +284,7 @@ public class SitemapParser extends DefaultHandler {
this.logger.logInfo("The URL '" + this.nextURL + "' can not be crawled. Reason: " + error);
// insert URL into the error DB
- ZURL.Entry ee = this.sb.crawlQueues.errorURL.newEntry(
+ final ZURL.Entry ee = this.sb.crawlQueues.errorURL.newEntry(
new CrawlEntry(
sb.webIndex.seedDB.mySeed().hash,
new yacyURL(this.nextURL, null),
@@ -300,7 +301,7 @@ public class SitemapParser extends DefaultHandler {
error);
ee.store();
this.sb.crawlQueues.errorURL.push(ee);
- } catch (MalformedURLException e) {/* ignore this */
+ } catch (final MalformedURLException e) {/* ignore this */
}
} else {
this.logger.logInfo("New URL '" + this.nextURL + "' added for crawling.");
@@ -311,7 +312,7 @@ public class SitemapParser extends DefaultHandler {
}
}
- public void characters(char[] buf, int offset, int len) throws SAXException {
+ public void characters(final char[] buf, final int offset, final int len) throws SAXException {
if (this.currentElement.equalsIgnoreCase(SITEMAP_URL_LOC)) {
// TODO: we need to decode the URL here
this.nextURL = (new String(buf, offset, len)).trim();
@@ -320,16 +321,16 @@ public class SitemapParser extends DefaultHandler {
this.nextURL = null;
}
} else if (this.currentElement.equalsIgnoreCase(SITEMAP_URL_LASTMOD)) {
- String dateStr = new String(buf, offset, len);
+ final String dateStr = new String(buf, offset, len);
try {
this.lastMod = serverDate.parseISO8601(dateStr);
- } catch (ParseException e) {
+ } catch (final ParseException e) {
this.logger.logInfo("Unable to parse datestring '" + dateStr + "'");
}
}
}
- private CrawlProfile.entry createProfile(String domainName, yacyURL sitemapURL) {
+ private CrawlProfile.entry createProfile(final String domainName, final yacyURL sitemapURL) {
return this.sb.webIndex.profilesActiveCrawls.newEntry(domainName, sitemapURL,
// crawlingFilter
".*", ".*",
diff --git a/source/de/anomic/data/URLFetcherStack.java b/source/de/anomic/data/URLFetcherStack.java
index 80fc4fce0..c75d3857c 100644
--- a/source/de/anomic/data/URLFetcherStack.java
+++ b/source/de/anomic/data/URLFetcherStack.java
@@ -51,7 +51,7 @@ public class URLFetcherStack {
private int popped = 0;
private int pushed = 0;
- public URLFetcherStack(File path) throws IOException {
+ public URLFetcherStack(final File path) throws IOException {
this.db = new kelondroStack(new File(path, DBFILE), rowdef);
this.log = new serverLog("URLFETCHERSTACK");
}
@@ -64,14 +64,14 @@ public class URLFetcherStack {
this.db.close();
}
- public boolean push(yacyURL url) {
+ public boolean push(final yacyURL url) {
try {
this.db.push(this.db.row().newEntry(
new byte[][] { url.toNormalform(true, true).getBytes() }
));
this.pushed++;
return true;
- } catch (IOException e) {
+ } catch (final IOException e) {
this.log.logSevere("error storing entry", e);
return false;
}
@@ -79,26 +79,26 @@ public class URLFetcherStack {
public yacyURL pop() {
try {
- kelondroRow.Entry r = this.db.pop();
+ final kelondroRow.Entry r = this.db.pop();
if (r == null) return null;
final String url = r.getColString(0, null);
try {
this.popped++;
return new yacyURL(url, null);
- } catch (MalformedURLException e) {
+ } catch (final MalformedURLException e) {
this.log.logSevere("found invalid URL-entry: " + url);
return null;
}
- } catch (IOException e) {
+ } catch (final IOException e) {
this.log.logSevere("error retrieving entry", e);
return null;
}
}
- public String[] top(int count) {
+ public String[] top(final int count) {
try {
final ArrayList<String> ar = new ArrayList<String>();
- Iterator<EntryIndex> it = db.contentRows(500);
+ final Iterator<EntryIndex> it = db.contentRows(500);
kelondroRow.EntryIndex ei;
for (int i=0; i<count && it.hasNext(); i++) {
ei = it.next();
@@ -106,7 +106,7 @@ public class URLFetcherStack {
ar.add(ei.getColString(0, null));
}
return ar.toArray(new String[ar.size()]);
- } catch (kelondroException e) {
+ } catch (final kelondroException e) {
this.log.logSevere("error retrieving entry", e);
return null;
}
diff --git a/source/de/anomic/data/URLLicense.java b/source/de/anomic/data/URLLicense.java
index c78580abd..3a955b297 100644
--- a/source/de/anomic/data/URLLicense.java
+++ b/source/de/anomic/data/URLLicense.java
@@ -36,17 +36,17 @@ public class URLLicense {
// this class defines a license-generation for URLs
// it is used in case of snippet- and preview-Image-fetching to grant also non-authorized users the usage of a image-fetcher servlet
- private Random random;
- private HashMap<String, yacyURL> permissions;
- private int keylen;
+ private final Random random;
+ private final HashMap<String, yacyURL> permissions;
+ private final int keylen;
- public URLLicense(int keylen) {
+ public URLLicense(final int keylen) {
this.permissions = new HashMap<String, yacyURL>();
this.random = new Random(System.currentTimeMillis());
this.keylen = keylen;
}
- public String aquireLicense(yacyURL url) {
+ public String aquireLicense(final yacyURL url) {
// generate license key
String license = "";
while (license.length() < keylen) license += Integer.toHexString(random.nextInt());
@@ -59,7 +59,7 @@ public class URLLicense {
return license;
}
- public yacyURL releaseLicense(String license) {
+ public yacyURL releaseLicense(final String license) {
yacyURL url = null;
synchronized (permissions) {
url = permissions.remove(license);
diff --git a/source/de/anomic/data/blogBoard.java b/source/de/anomic/data/blogBoard.java
index 399835d72..6e9e190c3 100644
--- a/source/de/anomic/data/blogBoard.java
+++ b/source/de/anomic/data/blogBoard.java
@@ -61,7 +61,7 @@ public class blogBoard {
kelondroMap database = null;
- public blogBoard(File actpath) {
+ public blogBoard(final File actpath) {
new File(actpath.getParent()).mkdir();
if (database == null) {
database = new kelondroMap(new kelondroBLOBTree(actpath, true, true, keyLength, recordSize, '_', kelondroNaturalOrder.naturalOrder, true, false, false), 500);
@@ -73,7 +73,7 @@ public class blogBoard {
public void close() {
database.close();
}
- private static String normalize(String key) {
+ private static String normalize(final String key) {
if (key == null) return "null";
return key.trim().toLowerCase();
}
@@ -85,7 +85,7 @@ public class blogBoard {
key = key.substring(0, p) + "%20" + key.substring(p +1);
return key;
}
- public String guessAuthor(String ip) {
+ public String guessAuthor(final String ip) {
return wikiBoard.guessAuthor(ip);
}
/**
@@ -100,54 +100,54 @@ public class blogBoard {
* @param commentMode possible params are: 0 - no comments allowed, 1 - comments allowed, 2 - comments moderated
* @return BlogEntry
*/
- public BlogEntry newEntry(String key, byte[] subject, byte[] author, String ip, Date date, byte[] page, ArrayList<String> comments, String commentMode) {
+ public BlogEntry newEntry(final String key, final byte[] subject, final byte[] author, final String ip, final Date date, final byte[] page, final ArrayList<String> comments, final String commentMode) {
return new BlogEntry(normalize(key), subject, author, ip, date, page, comments, commentMode);
}
/*
* writes a new page and return the key
*/
- public String writeBlogEntry(BlogEntry page) {
+ public String writeBlogEntry(final BlogEntry page) {
try {
database.put(page.key, page.record);
return page.key;
- } catch (IOException e) {
+ } catch (final IOException e) {
return null;
}
}
- public BlogEntry readBlogEntry(String key) {
+ public BlogEntry readBlogEntry(final String key) {
return readBlogEntry(key, database);
}
- private BlogEntry readBlogEntry(String key, kelondroMap base) {
+ private BlogEntry readBlogEntry(String key, final kelondroMap base) {
key = normalize(key);
if (key.length() > keyLength) key = key.substring(0, keyLength);
HashMap<String, String> record;
try {
record = base.get(key);
- } catch (IOException e) {
+ } catch (final IOException e) {
record = null;
}
if (record == null)
return newEntry(key, "".getBytes(), "anonymous".getBytes(), "127.0.0.1", new Date(), "".getBytes(), null, null);
return new BlogEntry(key, record);
}
- public boolean importXML(String input) {
- DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+ public boolean importXML(final String input) {
+ final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
- DocumentBuilder builder = factory.newDocumentBuilder();
- Document doc = builder.parse(new ByteArrayInputStream(input.getBytes()));
+ final DocumentBuilder builder = factory.newDocumentBuilder();
+ final Document doc = builder.parse(new ByteArrayInputStream(input.getBytes()));
return parseXMLimport(doc);
- } catch (ParserConfigurationException e) {
- } catch (SAXException e) {
- } catch (IOException e) {}
+ } catch (final ParserConfigurationException e) {
+ } catch (final SAXException e) {
+ } catch (final IOException e) {}
return false;
}
- private boolean parseXMLimport(Document doc) {
+ private boolean parseXMLimport(final Document doc) {
if(!doc.getDocumentElement().getTagName().equals("blog"))
return false;
- NodeList items = doc.getDocumentElement().getElementsByTagName("item");
+ final NodeList items = doc.getDocumentElement().getElementsByTagName("item");
if(items.getLength() == 0)
return false;
@@ -158,10 +158,10 @@ public class blogBoard {
if(!items.item(i).getNodeName().equals("item"))
continue;
- NodeList currentNodeChildren = items.item(i).getChildNodes();
+ final NodeList currentNodeChildren = items.item(i).getChildNodes();
for(int j=0;j<currentNodeChildren.getLength();++j) {
- Node currentNode = currentNodeChildren.item(j);
+ final Node currentNode = currentNodeChildren.item(j);
if(currentNode.getNodeName().equals("id"))
key = currentNode.getFirstChild().getNodeValue();
else if(currentNode.getNodeName().equals("ip"))
@@ -178,7 +178,7 @@ public class blogBoard {
try {
date = serverDate.parseShortSecond(StrDate);
- } catch (ParseException e1) {
+ } catch (final ParseException e1) {
date = new Date();
}
@@ -188,17 +188,17 @@ public class blogBoard {
byte[] subject,author,page;
try {
subject = StrSubject.getBytes("UTF-8");
- } catch (UnsupportedEncodingException e1) {
+ } catch (final UnsupportedEncodingException e1) {
subject = StrSubject.getBytes();
}
try {
author = StrAuthor.getBytes("UTF-8");
- } catch (UnsupportedEncodingException e1) {
+ } catch (final UnsupportedEncodingException e1) {
author = StrAuthor.getBytes();
}
try {
page = StrPage.getBytes("UTF-8");
- } catch (UnsupportedEncodingException e1) {
+ } catch (final UnsupportedEncodingException e1) {
page = StrPage.getBytes();
}
@@ -210,9 +210,9 @@ public class blogBoard {
key = normalize(key);
try {
database.remove(key);
- } catch (IOException e) { }
+ } catch (final IOException e) { }
}
- public Iterator<byte[]> keys(boolean up) throws IOException {
+ public Iterator<byte[]> keys(final boolean up) throws IOException {
return database.keys(up, false);
}
/**
@@ -220,18 +220,18 @@ public class blogBoard {
*/
public class BlogComparator implements Comparator<String> {
- private boolean newestFirst;
+ private final boolean newestFirst;
/**
* @param newestFirst newest first, or oldest first?
*/
- public BlogComparator(boolean newestFirst){
+ public BlogComparator(final boolean newestFirst){
this.newestFirst = newestFirst;
}
- public int compare(String obj1, String obj2) {
- BlogEntry blogEntry1 = readBlogEntry(obj1);
- BlogEntry blogEntry2 = readBlogEntry(obj2);
+ public int compare(final String obj1, final String obj2) {
+ final BlogEntry blogEntry1 = readBlogEntry(obj1);
+ final BlogEntry blogEntry2 = readBlogEntry(obj2);
if(blogEntry1 == null || blogEntry2 == null)
return 0;
if (this.newestFirst) {
@@ -244,9 +244,9 @@ public class blogBoard {
return -1;
}
}
- public Iterator<String> getBlogIterator(boolean priv){
- TreeSet<String> set = new TreeSet<String>(new BlogComparator(true));
- Iterator<BlogEntry> iterator = blogIterator(true);
+ public Iterator<String> getBlogIterator(final boolean priv){
+ final TreeSet<String> set = new TreeSet<String>(new BlogComparator(true));
+ final Iterator<BlogEntry> iterator = blogIterator(true);
BlogEntry blogEntry;
while(iterator.hasNext()){
blogEntry=iterator.next();
@@ -256,10 +256,10 @@ public class blogBoard {
}
return set.iterator();
}
- public Iterator<BlogEntry> blogIterator(boolean up){
+ public Iterator<BlogEntry> blogIterator(final boolean up){
try {
return new BlogIterator(up);
- } catch (IOException e) {
+ } catch (final IOException e) {
return new HashSet<BlogEntry>().iterator();
}
}
@@ -269,7 +269,7 @@ public class blogBoard {
public class BlogIterator implements Iterator<BlogEntry> {
Iterator<byte[]> blogIter;
blogBoard.BlogEntry nextEntry;
- public BlogIterator(boolean up) throws IOException {
+ public BlogIterator(final boolean up) throws IOException {
this.blogIter = blogBoard.this.database.keys(up, false);
this.nextEntry = null;
}
@@ -277,7 +277,7 @@ public class blogBoard {
public boolean hasNext() {
try {
return this.blogIter.hasNext();
- } catch (kelondroException e) {
+ } catch (final kelondroException e) {
//resetDatabase();
return false;
}
@@ -286,7 +286,7 @@ public class blogBoard {
public BlogEntry next() {
try {
return readBlogEntry(new String(this.blogIter.next()));
- } catch (kelondroException e) {
+ } catch (final kelondroException e) {
//resetDatabase();
return null;
}
@@ -295,9 +295,9 @@ public class blogBoard {
public void remove() {
if (this.nextEntry != null) {
try {
- Object blogKey = this.nextEntry.getKey();
+ final Object blogKey = this.nextEntry.getKey();
if (blogKey != null) deleteBlogEntry((String) blogKey);
- } catch (kelondroException e) {
+ } catch (final kelondroException e) {
//resetDatabase();
}
}
@@ -309,7 +309,7 @@ public class blogBoard {
String key;
HashMap<String, String> record;
- public BlogEntry(String nkey, byte[] subject, byte[] author, String ip, Date date, byte[] page, ArrayList<String> comments, String commentMode) {
+ public BlogEntry(final String nkey, final byte[] subject, final byte[] author, final String ip, final Date date, final byte[] page, final ArrayList<String> comments, final String commentMode) {
record = new HashMap<String, String>();
setKey(nkey);
setDate(date);
@@ -325,13 +325,13 @@ public class blogBoard {
wikiBoard.setAuthor(ip, new String(author));
}
- BlogEntry(String key, HashMap<String, String> record) {
+ BlogEntry(final String key, final HashMap<String, String> record) {
this.key = key;
this.record = record;
if (this.record.get("comments")==null) this.record.put("comments", listManager.collection2string(new ArrayList<String>()));
if (this.record.get("commentMode")==null || this.record.get("commentMode").equals("")) this.record.put("commentMode", "1");
}
- private void setKey(String key) {
+ private void setKey(final String key) {
if (key.length() > keyLength)
this.key = key.substring(0, keyLength);
this.key = key;
@@ -340,13 +340,13 @@ public class blogBoard {
return key;
}
public byte[] getSubject() {
- String m = record.get("subject");
+ final String m = record.get("subject");
if (m == null) return new byte[0];
- byte[] b = kelondroBase64Order.enhancedCoder.decode(m, "de.anomic.data.blogBoard.subject()");
+ final byte[] b = kelondroBase64Order.enhancedCoder.decode(m, "de.anomic.data.blogBoard.subject()");
if (b == null) return "".getBytes();
return b;
}
- private void setSubject(byte[] subject) {
+ private void setSubject(final byte[] subject) {
if (subject == null)
record.put("subject","");
else
@@ -354,13 +354,13 @@ public class blogBoard {
}
public Date getDate() {
try {
- String date = record.get("date");
+ final String date = record.get("date");
if (date == null) {
serverLog.logFinest("Blog", "ERROR: date field missing in blogBoard");
return new Date();
}
return serverDate.parseShortSecond(date);
- } catch (ParseException e) {
+ } catch (final ParseException e) {
return new Date();
}
}
@@ -370,7 +370,7 @@ public class blogBoard {
record.put("date", serverDate.formatShortSecond(date));
}
public String getTimestamp() {
- String timestamp = record.get("date");
+ final String timestamp = record.get("date");
if (timestamp == null) {
serverLog.logFinest("Blog", "ERROR: date field missing in blogBoard");
return serverDate.formatShortSecond();
@@ -378,13 +378,13 @@ public class blogBoard {
return timestamp;
}
public byte[] getAuthor() {
- String author = record.get("author");
+ final String author = record.get("author");
if (author == null) return new byte[0];
- byte[] b = kelondroBase64Order.enhancedCoder.decode(author, "de.anomic.data.blogBoard.author()");
+ final byte[] b = kelondroBase64Order.enhancedCoder.decode(author, "de.anomic.data.blogBoard.author()");
if (b == null) return "".getBytes();
return b;
}
- private void setAuthor(byte[] author) {
+ private void setAuthor(final byte[] author) {
if (author == null)
record.put("author","");
else
@@ -396,21 +396,21 @@ public class blogBoard {
record.put("comments", record.get("comments").substring(1));
writeBlogEntry(this);
}
- ArrayList<String> commentsize = listManager.string2arraylist(record.get("comments"));
+ final ArrayList<String> commentsize = listManager.string2arraylist(record.get("comments"));
return commentsize.size();
}
public ArrayList<String> getComments() {
- ArrayList<String> comments = listManager.string2arraylist(record.get("comments"));
+ final ArrayList<String> comments = listManager.string2arraylist(record.get("comments"));
return comments;
}
- private void setComments(ArrayList<String> comments) {
+ private void setComments(final ArrayList<String> comments) {
if (comments == null)
record.put("comments", listManager.collection2string(new ArrayList<String>()));
else
record.put("comments", listManager.collection2string(comments));
}
public String getIp() {
- String ip = record.get("ip");
+ final String ip = record.get("ip");
if (ip == null) return "127.0.0.1";
return ip;
}
@@ -420,26 +420,26 @@ public class blogBoard {
record.put("ip", ip);
}
public byte[] getPage() {
- String page = record.get("page");
+ final String page = record.get("page");
if (page == null) return new byte[0];
- byte[] page_as_byte = kelondroBase64Order.enhancedCoder.decode(page, "de.anomic.data.blogBoard.page()");
+ final byte[] page_as_byte = kelondroBase64Order.enhancedCoder.decode(page, "de.anomic.data.blogBoard.page()");
if (page_as_byte == null) return "".getBytes();
return page_as_byte;
}
- private void setPage(byte[] page) {
+ private void setPage(final byte[] page) {
if (page == null)
record.put("page", "");
else
record.put("page", kelondroBase64Order.enhancedCoder.encode(page));
}
- public void addComment(String commentID) {
- ArrayList<String> comments = listManager.string2arraylist(record.get("comments"));
+ public void addComment(final String commentID) {
+ final ArrayList<String> comments = listManager.string2arraylist(record.get("comments"));
comments.add(commentID);
record.put("comments", listManager.collection2string(comments));
}
- public boolean removeComment(String commentID) {
- ArrayList<String> comments = listManager.string2arraylist(record.get("comments"));
- boolean success = comments.remove(commentID);
+ public boolean removeComment(final String commentID) {
+ final ArrayList<String> comments = listManager.string2arraylist(record.get("comments"));
+ final boolean success = comments.remove(commentID);
record.put("comments", listManager.collection2string(comments));
return success;
}
@@ -453,14 +453,14 @@ public class blogBoard {
public int getCommentMode(){
return Integer.parseInt(record.get("commentMode"));
}
- private void setCommentMode(String mode) {
+ private void setCommentMode(final String mode) {
if (mode == null)
record.put("commentMode", "1");
else
record.put("commentMode", mode);
}
public boolean isPublic() {
- String privacy = record.get("privacy");
+ final String privacy = record.get("privacy");
if (privacy == null)
return true;
if(privacy.equalsIgnoreCase("public"))
diff --git a/source/de/anomic/data/blogBoardComments.java b/source/de/anomic/data/blogBoardComments.java
index fd94af7dc..d16041790 100644
--- a/source/de/anomic/data/blogBoardComments.java
+++ b/source/de/anomic/data/blogBoardComments.java
@@ -63,7 +63,7 @@ public class blogBoardComments {
SimpleFormatter.setTimeZone(TimeZone.getTimeZone("GMT"));
}
private kelondroMap database = null;
- public blogBoardComments(File actpath) {
+ public blogBoardComments(final File actpath) {
new File(actpath.getParent()).mkdir();
if (database == null) {
database = new kelondroMap(new kelondroBLOBTree(actpath, true, true, keyLength, recordSize, '_', kelondroNaturalOrder.naturalOrder, false, false, false), 500);
@@ -75,12 +75,12 @@ public class blogBoardComments {
public void close() {
database.close();
}
- static String dateString(Date date) {
+ static String dateString(final Date date) {
synchronized (SimpleFormatter) {
return SimpleFormatter.format(date);
}
}
- private static String normalize(String key) {
+ private static String normalize(final String key) {
if (key == null) return "null";
return key.trim().toLowerCase();
}
@@ -92,54 +92,54 @@ public class blogBoardComments {
key = key.substring(0, p) + "%20" + key.substring(p +1);
return key;
}
- public String guessAuthor(String ip) {
+ public String guessAuthor(final String ip) {
return wikiBoard.guessAuthor(ip);
}
- public CommentEntry newEntry(String key, byte[] subject, byte[] author, String ip, Date date, byte[] page) {
+ public CommentEntry newEntry(final String key, final byte[] subject, final byte[] author, final String ip, final Date date, final byte[] page) {
return new CommentEntry(normalize(key), subject, author, ip, date, page);
}
- public String write(CommentEntry page) {
+ public String write(final CommentEntry page) {
// writes a new page and returns key
try {
database.put(page.key, page.record);
return page.key;
- } catch (IOException e) {
+ } catch (final IOException e) {
return null;
}
}
- public CommentEntry read(String key) {
+ public CommentEntry read(final String key) {
//System.out.println("DEBUG: read from blogBoardComments");
return read(key, database);
}
- private CommentEntry read(String key, kelondroMap base) {
+ private CommentEntry read(String key, final kelondroMap base) {
key = normalize(key);
if (key.length() > keyLength) key = key.substring(0, keyLength);
HashMap<String, String> record;
try {
record = base.get(key);
- } catch (IOException e) {
+ } catch (final IOException e) {
record = null;
}
if (record == null) return newEntry(key, "".getBytes(), "anonymous".getBytes(), "127.0.0.1", new Date(), "".getBytes());
return new CommentEntry(key, record);
}
- public boolean importXML(String input) {
- DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+ public boolean importXML(final String input) {
+ final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
- DocumentBuilder builder = factory.newDocumentBuilder();
- Document doc = builder.parse(new ByteArrayInputStream(input.getBytes()));
+ final DocumentBuilder builder = factory.newDocumentBuilder();
+ final Document doc = builder.parse(new ByteArrayInputStream(input.getBytes()));
return parseXMLimport(doc);
- } catch (ParserConfigurationException e) {
- } catch (SAXException e) {
- } catch (IOException e) {}
+ } catch (final ParserConfigurationException e) {
+ } catch (final SAXException e) {
+ } catch (final IOException e) {}
return false;
}
- private boolean parseXMLimport(Document doc) {
+ private boolean parseXMLimport(final Document doc) {
if(!doc.getDocumentElement().getTagName().equals("blog"))
return false;
- NodeList items = doc.getDocumentElement().getElementsByTagName("item");
+ final NodeList items = doc.getDocumentElement().getElementsByTagName("item");
if(items.getLength() == 0)
return false;
@@ -150,10 +150,10 @@ public class blogBoardComments {
if(!items.item(i).getNodeName().equals("item"))
continue;
- NodeList currentNodeChildren = items.item(i).getChildNodes();
+ final NodeList currentNodeChildren = items.item(i).getChildNodes();
for(int j=0;j<currentNodeChildren.getLength();++j) {
- Node currentNode = currentNodeChildren.item(j);
+ final Node currentNode = currentNodeChildren.item(j);
if(currentNode.getNodeName().equals("id"))
key = currentNode.getFirstChild().getNodeValue();
else if(currentNode.getNodeName().equals("ip"))
@@ -170,7 +170,7 @@ public class blogBoardComments {
try {
date = SimpleFormatter.parse(StrDate);
- } catch (ParseException e1) {
+ } catch (final ParseException e1) {
date = new Date();
}
@@ -180,17 +180,17 @@ public class blogBoardComments {
byte[] subject,author,page;
try {
subject = StrSubject.getBytes("UTF-8");
- } catch (UnsupportedEncodingException e1) {
+ } catch (final UnsupportedEncodingException e1) {
subject = StrSubject.getBytes();
}
try {
author = StrAuthor.getBytes("UTF-8");
- } catch (UnsupportedEncodingException e1) {
+ } catch (final UnsupportedEncodingException e1) {
author = StrAuthor.getBytes();
}
try {
page = StrPage.getBytes("UTF-8");
- } catch (UnsupportedEncodingException e1) {
+ } catch (final UnsupportedEncodingException e1) {
page = StrPage.getBytes();
}
@@ -202,9 +202,9 @@ public class blogBoardComments {
key = normalize(key);
try {
database.remove(key);
- } catch (IOException e) { }
+ } catch (final IOException e) { }
}
- public Iterator<byte[]> keys(boolean up) throws IOException {
+ public Iterator<byte[]> keys(final boolean up) throws IOException {
return database.keys(up, false);
}
@@ -213,7 +213,7 @@ public class blogBoardComments {
String key;
HashMap<String, String> record;
- public CommentEntry(String nkey, byte[] subject, byte[] author, String ip, Date date, byte[] page) {
+ public CommentEntry(final String nkey, final byte[] subject, final byte[] author, final String ip, final Date date, final byte[] page) {
record = new HashMap<String, String>();
setKey(nkey);
@@ -226,7 +226,7 @@ public class blogBoardComments {
wikiBoard.setAuthor(ip, new String(author));
}
- CommentEntry(String key, HashMap<String, String> record) {
+ CommentEntry(final String key, final HashMap<String, String> record) {
this.key = key;
this.record = record;
if (this.record.get("comments")==null) this.record.put("comments", listManager.collection2string(new ArrayList<String>()));
@@ -235,21 +235,21 @@ public class blogBoardComments {
public String getKey() {
return key;
}
- private void setKey(String var) {
+ private void setKey(final String var) {
key = var;
if (key.length() > keyLength)
key = var.substring(0, keyLength);
}
- private void setSubject(byte[] subject) {
+ private void setSubject(final byte[] subject) {
if (subject == null)
record.put("subject","");
else
record.put("subject", kelondroBase64Order.enhancedCoder.encode(subject));
}
public byte[] getSubject() {
- String subject = record.get("subject");
+ final String subject = record.get("subject");
if (subject == null) return new byte[0];
- byte[] subject_bytes = kelondroBase64Order.enhancedCoder.decode(subject, "de.anomic.data.blogBoardComments.subject()");
+ final byte[] subject_bytes = kelondroBase64Order.enhancedCoder.decode(subject, "de.anomic.data.blogBoardComments.subject()");
if (subject_bytes == null) return "".getBytes();
return subject_bytes;
}
@@ -260,7 +260,7 @@ public class blogBoardComments {
}
public Date getDate() {
try {
- String date = record.get("date");
+ final String date = record.get("date");
if (date == null) {
serverLog.logFinest("Blog", "ERROR: date field missing in blogBoard");
return new Date();
@@ -268,30 +268,30 @@ public class blogBoardComments {
synchronized (SimpleFormatter) {
return SimpleFormatter.parse(date);
}
- } catch (ParseException e) {
+ } catch (final ParseException e) {
return new Date();
}
}
public String getTimestamp() {
- String timestamp = record.get("date");
+ final String timestamp = record.get("date");
if (timestamp == null) {
serverLog.logFinest("Blog", "ERROR: date field missing in blogBoard");
return dateString(new Date());
}
return timestamp;
}
- private void setAuthor(byte[] author) {
+ private void setAuthor(final byte[] author) {
if (author == null)
record.put("author","");
else
record.put("author", kelondroBase64Order.enhancedCoder.encode(author));
}
public byte[] getAuthor() {
- String author = record.get("author");
+ final String author = record.get("author");
if (author == null)
return new byte[0];
- byte[] author_byte = kelondroBase64Order.enhancedCoder.decode(author, "de.anomic.data.blogBoardComments.author()");
+ final byte[] author_byte = kelondroBase64Order.enhancedCoder.decode(author, "de.anomic.data.blogBoardComments.author()");
if (author_byte == null)
return "".getBytes();
return author_byte;
@@ -302,22 +302,22 @@ public class blogBoardComments {
record.put("ip", ip);
}
public String getIp() {
- String ip = record.get("ip");
+ final String ip = record.get("ip");
if (ip == null)
return "127.0.0.1";
return ip;
}
- private void setPage(byte[] page) {
+ private void setPage(final byte[] page) {
if (page == null)
record.put("page", "");
else
record.put("page", kelondroBase64Order.enhancedCoder.encode(page));
}
public byte[] getPage() {
- String page = record.get("page");
+ final String page = record.get("page");
if (page == null)
return new byte[0];
- byte[] page_byte = kelondroBase64Order.enhancedCoder.decode(page, "de.anomic.data.blogBoardComments.page()");
+ final byte[] page_byte = kelondroBase64Order.enhancedCoder.decode(page, "de.anomic.data.blogBoardComments.page()");
if (page_byte == null)
return "".getBytes();
return page_byte;
diff --git a/source/de/anomic/data/bookmarksDB.java b/source/de/anomic/data/bookmarksDB.java
index c837027d3..a5cb169da 100644
--- a/source/de/anomic/data/bookmarksDB.java
+++ b/source/de/anomic/data/bookmarksDB.java
@@ -60,8 +60,8 @@ import de.anomic.index.indexWord;
import de.anomic.kelondro.kelondroBLOBTree;
import de.anomic.kelondro.kelondroCloneableIterator;
import de.anomic.kelondro.kelondroException;
-import de.anomic.kelondro.kelondroNaturalOrder;
import de.anomic.kelondro.kelondroMap;
+import de.anomic.kelondro.kelondroNaturalOrder;
import de.anomic.server.serverDate;
import de.anomic.server.serverFileUtils;
import de.anomic.server.logging.serverLog;
@@ -91,7 +91,7 @@ public class bookmarksDB {
// bookmarksDB's class constructor
// ------------------------------------
- public bookmarksDB(File bookmarksFile, File tagsFile, File datesFile) {
+ public bookmarksDB(final File bookmarksFile, final File tagsFile, final File datesFile) {
// bookmarks
tagCache=new HashMap<String, Tag>();
bookmarksFile.getParentFile().mkdirs();
@@ -100,12 +100,12 @@ public class bookmarksDB {
// tags
tagsFile.getParentFile().mkdirs();
- boolean tagsFileExisted = tagsFile.exists();
+ final boolean tagsFileExisted = tagsFile.exists();
this.tagsTable = new kelondroMap(new kelondroBLOBTree(tagsFile, true, true, 12, 256, '_', kelondroNaturalOrder.naturalOrder, true, false, false), 500);
if (!tagsFileExisted) rebuildTags();
// dates
- boolean datesExisted = datesFile.exists();
+ final boolean datesExisted = datesFile.exists();
this.datesTable = new kelondroMap(new kelondroBLOBTree(datesFile, true, true, 20, 256, '_', kelondroNaturalOrder.naturalOrder, true, false, false), 500);
if (!datesExisted) rebuildDates();
@@ -131,18 +131,18 @@ public class bookmarksDB {
* @param tagName an object of type String with the name of the tag.
* tagName is converted to lower case before hash is generated!
*/
- public static String tagHash(String tagName){
+ public static String tagHash(final String tagName){
return indexWord.word2hash(tagName.toLowerCase());
}
- public static String tagHash(String tagName, String user){
+ public static String tagHash(final String tagName, final String user){
return indexWord.word2hash(user+":"+tagName.toLowerCase());
}
- public Iterator<String> getFolderList(boolean priv){
+ public Iterator<String> getFolderList(final boolean priv){
- Set<String> folders = new TreeSet<String>();
+ final Set<String> folders = new TreeSet<String>();
String path = "";
- Iterator<Tag> it = this.getTagIterator(priv);
+ final Iterator<Tag> it = this.getTagIterator(priv);
Tag tag;
while(it.hasNext()){
@@ -192,9 +192,9 @@ public class bookmarksDB {
// bookmarksDB's functions for bookmarksTable / bookmarkCache
// -----------------------------------------------------------
- public Bookmark createBookmark(String url, String user){
+ public Bookmark createBookmark(final String url, final String user){
if (url == null || url.length() == 0) return null;
- Bookmark bk = new Bookmark(url);
+ final Bookmark bk = new Bookmark(url);
bk.setOwner(user);
return (bk.getUrlHash() == null || bk.toMap() == null) ? null : bk;
}
@@ -205,36 +205,36 @@ public class bookmarksDB {
}
// adding a bookmark to the bookmarksDB
- public void saveBookmark(Bookmark bookmark){
+ public void saveBookmark(final Bookmark bookmark){
try {
bookmarksTable.put(bookmark.getUrlHash(), bookmark.entry);
- } catch (IOException e) {
+ } catch (final IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
- public String addBookmark(Bookmark bookmark){
+ public String addBookmark(final Bookmark bookmark){
saveBookmark(bookmark);
return bookmark.getUrlHash();
}
- public Bookmark getBookmark(String urlHash){
+ public Bookmark getBookmark(final String urlHash){
try {
- HashMap<String, String> map = bookmarksTable.get(urlHash);
+ final HashMap<String, String> map = bookmarksTable.get(urlHash);
if (map == null) return null;
return new Bookmark(map);
- } catch (IOException e) {
+ } catch (final IOException e) {
return null;
}
}
- public boolean removeBookmark(String urlHash){
- Bookmark bookmark = getBookmark(urlHash);
+ public boolean removeBookmark(final String urlHash){
+ final Bookmark bookmark = getBookmark(urlHash);
if(bookmark == null) return false; //does not exist
- Set<String> tags = bookmark.getTags();
+ final Set<String> tags = bookmark.getTags();
bookmarksDB.Tag tag=null;
- Iterator<String> it=tags.iterator();
+ final Iterator<String> it=tags.iterator();
while(it.hasNext()){
tag=getTag(tagHash(it.next()));
if(tag!=null){
@@ -246,23 +246,23 @@ public class bookmarksDB {
try {
b = getBookmark(urlHash);
bookmarksTable.remove(urlHash);
- } catch (IOException e) {
+ } catch (final IOException e) {
b = null;
}
return b != null;
}
- public Iterator<Bookmark> bookmarkIterator(boolean up){
+ public Iterator<Bookmark> bookmarkIterator(final boolean up){
try {
return new bookmarkIterator(up);
- } catch (IOException e) {
+ } catch (final IOException e) {
return new HashSet<Bookmark>().iterator();
}
}
- public Iterator<String> getBookmarksIterator(boolean priv){
- TreeSet<String> set=new TreeSet<String>(new bookmarkComparator(true));
- Iterator<Bookmark> it=bookmarkIterator(true);
+ public Iterator<String> getBookmarksIterator(final boolean priv){
+ final TreeSet<String> set=new TreeSet<String>(new bookmarkComparator(true));
+ final Iterator<Bookmark> it=bookmarkIterator(true);
Bookmark bm;
while(it.hasNext()){
bm=it.next();
@@ -273,10 +273,10 @@ public class bookmarksDB {
return set.iterator();
}
- public Iterator<String> getBookmarksIterator(String tagName, boolean priv){
- TreeSet<String> set=new TreeSet<String>(new bookmarkComparator(true));
- String tagHash=tagHash(tagName);
- Tag tag=getTag(tagHash);
+ public Iterator<String> getBookmarksIterator(final String tagName, final boolean priv){
+ final TreeSet<String> set=new TreeSet<String>(new bookmarkComparator(true));
+ final String tagHash=tagHash(tagName);
+ final Tag tag=getTag(tagHash);
Set<String> hashes=new HashSet<String>();
if(tag != null){
hashes=getTag(tagHash).getUrlHashes();
@@ -284,7 +284,7 @@ public class bookmarksDB {
if(priv){
set.addAll(hashes);
}else{
- Iterator<String> it=hashes.iterator();
+ final Iterator<String> it=hashes.iterator();
Bookmark bm;
while(it.hasNext()){
bm=getBookmark(it.next());
@@ -305,7 +305,7 @@ public class bookmarksDB {
return tagSize(false);
}
- public int tagSize(boolean flushed){
+ public int tagSize(final boolean flushed){
if(flushed)
flushTagCache();
return tagsTable.size();
@@ -315,12 +315,12 @@ public class bookmarksDB {
* load/retrieve an object of type Tag from the tagsTable (also save it in tagCache)
* @param hash an object of type String, containing a tagHash
*/
- private Tag loadTag(String hash){
+ private Tag loadTag(final String hash){
HashMap<String, String> map;
Tag ret=null;
try {
map = tagsTable.get(hash);
- } catch (IOException e) {
+ } catch (final IOException e) {
return null;
}
if(map!=null){
@@ -334,7 +334,7 @@ public class bookmarksDB {
* retrieve an object of type Tag from the the tagCache, if object is not cached return loadTag(hash)
* @param hash an object of type String, containing a tagHash
*/
- public Tag getTag(String hash){
+ public Tag getTag(final String hash){
if(tagCache.containsKey(hash)){
return tagCache.get(hash);
}
@@ -344,67 +344,67 @@ public class bookmarksDB {
* store a Tag in tagsTable or remove an empty tag
* @param tag an object of type Tag to be stored/removed
*/
- public void storeTag(Tag tag){
+ public void storeTag(final Tag tag){
try {
if(tag.size() >0){
bookmarksDB.this.tagsTable.put(tag.getTagHash(), tag.getMap());
}else{
bookmarksDB.this.tagsTable.remove(tag.getTagHash());
}
- } catch (IOException e) {}
+ } catch (final IOException e) {}
}
/**
* save a Tag in tagCache; see also flushTagCache(), addTag(), loadTag()
* @param tag an object of type Tag to be saved in tagCache
*/
- public void saveTag(Tag tag) {
+ public void saveTag(final Tag tag) {
if(tag!=null){
tagCache.put(tag.getTagHash(), tag);
}
}
public void flushTagCache() {
- Iterator<String> it=tagCache.keySet().iterator();
+ final Iterator<String> it=tagCache.keySet().iterator();
while(it.hasNext()){
storeTag(tagCache.get(it.next()));
}
tagCache=new HashMap<String, Tag>();
}
- public String addTag(Tag tag) { // TODO: is addTag() really needed - check storeTag() and saveTag()
+ public String addTag(final Tag tag) { // TODO: is addTag() really needed - check storeTag() and saveTag()
//tagsTable.set(tag.getTagName(), tag.getMap());
//tagCache.put(tag.getTagHash(), tag);
saveTag(tag);
return tag.getTagName();
}
- public void removeTag(String hash) {
+ public void removeTag(final String hash) {
try {
if(tagCache.containsKey(hash)){
tagCache.remove(hash);
}
tagsTable.remove(hash);
- } catch (IOException e) {}
+ } catch (final IOException e) {}
}
- public Iterator<Tag> tagIterator(boolean up) {
+ public Iterator<Tag> tagIterator(final boolean up) {
try {
return new tagIterator(up);
- } catch (IOException e) {
+ } catch (final IOException e) {
return new HashSet<Tag>().iterator();
}
}
- public Iterator<Tag> getTagIterator(boolean priv) {
+ public Iterator<Tag> getTagIterator(final boolean priv) {
return getTagIterator(priv,1);
}
- public Iterator<Tag> getTagIterator(boolean priv, int c) {
+ public Iterator<Tag> getTagIterator(final boolean priv, final int c) {
Comparator<Tag> comp;
if (c == SORT_SIZE) comp = new tagSizeComparator();
else comp = new tagComparator();
- TreeSet<Tag> set=new TreeSet<Tag>(comp);
- Iterator<Tag> it = tagIterator(true);
+ final TreeSet<Tag> set=new TreeSet<Tag>(comp);
+ final Iterator<Tag> it = tagIterator(true);
Tag tag;
while(it.hasNext()){
tag=it.next();
@@ -415,14 +415,14 @@ public class bookmarksDB {
return set.iterator();
}
- public Iterator<Tag> getTagIterator(boolean priv, int comp, int max){
+ public Iterator<Tag> getTagIterator(final boolean priv, final int comp, final int max){
if (max==SHOW_ALL)
return getTagIterator(priv, comp);
- Iterator<Tag> it = getTagIterator(priv, SORT_SIZE);
+ final Iterator<Tag> it = getTagIterator(priv, SORT_SIZE);
Comparator<Tag> c;
if (comp == SORT_SIZE) c = new tagSizeComparator();
else c = new tagComparator();
- TreeSet<Tag> set=new TreeSet<Tag>(c);
+ final TreeSet<Tag> set=new TreeSet<Tag>(c);
int count = 0;
while (it.hasNext() && count<=max) {
set.add(it.next());
@@ -435,13 +435,13 @@ public class bookmarksDB {
return getTagIterator(tagName, priv, SORT_ALPHA);
}
*/
- public Iterator<Tag> getTagIterator(String tagName, boolean priv, int comp){
+ public Iterator<Tag> getTagIterator(final String tagName, final boolean priv, final int comp){
Comparator<Tag> c;
if (comp == SORT_SIZE) c = new tagSizeComparator();
else c = new tagComparator();
- TreeSet<Tag> set=new TreeSet<Tag>(c);
+ final TreeSet<Tag> set=new TreeSet<Tag>(c);
Iterator<String> it=null;
- Iterator<String> bit=getBookmarksIterator(tagName, priv);
+ final Iterator<String> bit=getBookmarksIterator(tagName, priv);
Bookmark bm;
Tag tag;
Set<String> tags;
@@ -459,14 +459,14 @@ public class bookmarksDB {
return set.iterator();
}
- public Iterator<Tag> getTagIterator(String tagName, boolean priv, int comp, int max){
+ public Iterator<Tag> getTagIterator(final String tagName, final boolean priv, final int comp, final int max){
if (max==SHOW_ALL)
return getTagIterator(priv, comp);
- Iterator<Tag> it = getTagIterator(tagName, priv, SORT_SIZE);
+ final Iterator<Tag> it = getTagIterator(tagName, priv, SORT_SIZE);
Comparator<Tag> c;
if (comp == SORT_SIZE) c = new tagSizeComparator();
else c = new tagComparator();
- TreeSet<Tag> set=new TreeSet<Tag>(c);
+ final TreeSet<Tag> set=new TreeSet<Tag>(c);
int count = 0;
while (it.hasNext() && count<=max) {
set.add(it.next());
@@ -478,7 +478,7 @@ public class bookmarksDB {
// rebuilds the tagsDB from the bookmarksDB
public void rebuildTags(){
serverLog.logInfo("BOOKMARKS", "rebuilding tags.db from bookmarks.db...");
- Iterator<Bookmark> it = bookmarkIterator(true);
+ final Iterator<Bookmark> it = bookmarkIterator(true);
Bookmark bookmark;
Tag tag;
String[] tags;
@@ -503,11 +503,11 @@ public class bookmarksDB {
// bookmarksDB's functions for datesTable
// ---------------------------------------
- public bookmarksDate getDate(String date){
+ public bookmarksDate getDate(final String date){
HashMap<String, String> map;
try {
map=datesTable.get(date);
- } catch (IOException e) {
+ } catch (final IOException e) {
map = null;
}
if(map==null) return new bookmarksDate(date);
@@ -516,7 +516,7 @@ public class bookmarksDB {
// rebuilds the datesDB from the bookmarksDB
public void rebuildDates(){
serverLog.logInfo("BOOKMARKS", "rebuilding dates.db from bookmarks.db...");
- Iterator<Bookmark> it=bookmarkIterator(true);
+ final Iterator<Bookmark> it=bookmarkIterator(true);
Bookmark bookmark;
String date;
bookmarksDate bmDate;
@@ -537,15 +537,15 @@ public class bookmarksDB {
// bookmarksDB's experimental functions
// -------------------------------------
- public boolean renameTag(String oldName, String newName){
+ public boolean renameTag(final String oldName, final String newName){
- String oldHash=tagHash(oldName);
+ final String oldHash=tagHash(oldName);
//String newHash=tagHash(newName);
- Tag tag=getTag(oldHash); // set tag to oldHash
+ final Tag tag=getTag(oldHash); // set tag to oldHash
if (tag != null) {
- Set<String> urlHashes = tag.getUrlHashes(); // preserve urlHashes of tag
+ final Set<String> urlHashes = tag.getUrlHashes(); // preserve urlHashes of tag
removeTag(oldHash);
- Iterator<String> it = urlHashes.iterator();
+ final Iterator<String> it = urlHashes.iterator();
Bookmark bookmark;
Set<String> tags = new HashSet<String>();
String tagsString;
@@ -569,20 +569,20 @@ public class bookmarksDB {
// bookmarksDB's Import/Export functions
// --------------------------------------
- public int importFromBookmarks(yacyURL baseURL, String input, String tag, boolean importPublic){
+ public int importFromBookmarks(final yacyURL baseURL, final String input, final String tag, final boolean importPublic){
try {
// convert string to input stream
- ByteArrayInputStream byteIn = new ByteArrayInputStream(input.getBytes("UTF-8"));
- InputStreamReader reader = new InputStreamReader(byteIn,"UTF-8");
+ final ByteArrayInputStream byteIn = new ByteArrayInputStream(input.getBytes("UTF-8"));
+ final InputStreamReader reader = new InputStreamReader(byteIn,"UTF-8");
// import stream
return this.importFromBookmarks(baseURL,reader,tag,importPublic);
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
return 0;
}
}
- public int importFromBookmarks(yacyURL baseURL, InputStreamReader input, String tag, boolean importPublic){
+ public int importFromBookmarks(final yacyURL baseURL, final InputStreamReader input, final String tag, final boolean importPublic){
int importCount = 0;
@@ -590,17 +590,17 @@ public class bookmarksDB {
String title;
yacyURL url;
Bookmark bm;
- Set<String> tags=listManager.string2set(tag); //this allow multiple default tags
+ final Set<String> tags=listManager.string2set(tag); //this allow multiple default tags
try {
//load the links
- htmlFilterContentScraper scraper = new htmlFilterContentScraper(baseURL);
+ final htmlFilterContentScraper scraper = new htmlFilterContentScraper(baseURL);
//OutputStream os = new htmlFilterOutputStream(null, scraper, null, false);
- Writer writer= new htmlFilterWriter(null,null,scraper, null, false);
+ final Writer writer= new htmlFilterWriter(null,null,scraper, null, false);
serverFileUtils.copy(input,writer);
writer.close();
links = scraper.getAnchors();
- } catch (IOException e) {}
- Iterator<yacyURL> it = links.keySet().iterator();
+ } catch (final IOException e) {}
+ final Iterator<yacyURL> it = links.keySet().iterator();
while (it.hasNext()) {
url= it.next();
title=links.get(url);
@@ -622,44 +622,44 @@ public class bookmarksDB {
return importCount;
}
- public int importFromXML(String input, boolean importPublic){
+ public int importFromXML(final String input, final boolean importPublic){
try {
// convert string to input stream
- ByteArrayInputStream byteIn = new ByteArrayInputStream(input.getBytes("UTF-8"));
+ final ByteArrayInputStream byteIn = new ByteArrayInputStream(input.getBytes("UTF-8"));
// import stream
return this.importFromXML(byteIn,importPublic);
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
return 0;
}
}
- public int importFromXML(InputStream input, boolean importPublic){
- DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
+ public int importFromXML(final InputStream input, final boolean importPublic){
+ final DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
factory.setValidating(false);
factory.setNamespaceAware(false);
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
- Document doc=builder.parse(input);
+ final Document doc=builder.parse(input);
return parseXMLimport(doc, importPublic);
- } catch (ParserConfigurationException e) {
- } catch (SAXException e) {
- } catch (IOException e) {
+ } catch (final ParserConfigurationException e) {
+ } catch (final SAXException e) {
+ } catch (final IOException e) {
}
return 0;
}
- public int parseXMLimport(Node doc, boolean importPublic){
+ public int parseXMLimport(final Node doc, final boolean importPublic){
int importCount = 0;
if(doc.getNodeName()=="post"){
- NamedNodeMap attributes = doc.getAttributes();
- String url=attributes.getNamedItem("href").getNodeValue();
+ final NamedNodeMap attributes = doc.getAttributes();
+ final String url=attributes.getNamedItem("href").getNodeValue();
if(url.equals("")){
return 0;
}
- Bookmark bm=new Bookmark(url);
+ final Bookmark bm=new Bookmark(url);
String tagsString="";
String title="";
String description="";
@@ -690,7 +690,7 @@ public class bookmarksDB {
Date parsedDate = null;
try {
parsedDate = serverDate.parseISO8601(time);
- } catch (ParseException e) {
+ } catch (final ParseException e) {
parsedDate = new Date();
}
bm.setTimeStamp(parsedDate.getTime());
@@ -703,7 +703,7 @@ public class bookmarksDB {
importCount++;
}
- NodeList children=doc.getChildNodes();
+ final NodeList children=doc.getChildNodes();
if(children != null){
for (int i=0; i<children.getLength(); i++) {
importCount += parseXMLimport(children.item(i), importPublic);
@@ -724,11 +724,11 @@ public class bookmarksDB {
public class Tag{
public static final String URL_HASHES="urlHashes";
public static final String TAG_NAME="tagName";
- private String tagHash;
- private HashMap<String, String> mem;
+ private final String tagHash;
+ private final HashMap<String, String> mem;
private Set<String> urlHashes;
- public Tag(String hash, HashMap<String, String> map){
+ public Tag(final String hash, final HashMap<String, String> map){
tagHash=hash;
mem=map;
if(mem.containsKey(URL_HASHES))
@@ -736,14 +736,14 @@ public class bookmarksDB {
else
urlHashes = new HashSet<String>();
}
- public Tag(String name, HashSet<String> entries){
+ public Tag(final String name, final HashSet<String> entries){
tagHash=tagHash(name);
mem=new HashMap<String, String>();
//mem.put(URL_HASHES, listManager.arraylist2string(entries));
urlHashes=entries;
mem.put(TAG_NAME, name);
}
- public Tag(String name){
+ public Tag(final String name){
tagHash=tagHash(name);
mem=new HashMap<String, String>();
//mem.put(URL_HASHES, "");
@@ -784,16 +784,16 @@ public class bookmarksDB {
return urlHashes;
}
public boolean hasPublicItems(){
- Iterator<String> it=getBookmarksIterator(this.getTagHash(), false);
+ final Iterator<String> it=getBookmarksIterator(this.getTagHash(), false);
if(it.hasNext()){
return true;
}
return false;
}
- public void addUrl(String urlHash){
+ public void addUrl(final String urlHash){
urlHashes.add(urlHash);
}
- public void delete(String urlHash){
+ public void delete(final String urlHash){
urlHashes.remove(urlHash);
}
public int size(){
@@ -805,29 +805,29 @@ public class bookmarksDB {
*/
public class bookmarksDate{
public static final String URL_HASHES="urlHashes";
- private HashMap<String, String> mem;
+ private final HashMap<String, String> mem;
String date;
- public bookmarksDate(String mydate){
+ public bookmarksDate(final String mydate){
//round to seconds, but store as milliseconds (java timestamp)
date=String.valueOf((Long.parseLong(mydate)/1000)*1000);
mem=new HashMap<String, String>();
mem.put(URL_HASHES, "");
}
- public bookmarksDate(String mydate, HashMap<String, String> map){
+ public bookmarksDate(final String mydate, final HashMap<String, String> map){
//round to seconds, but store as milliseconds (java timestamp)
date=String.valueOf((Long.parseLong(mydate)/1000)*1000);
mem=map;
}
- public bookmarksDate(String mydate, ArrayList<String> entries){
+ public bookmarksDate(final String mydate, final ArrayList<String> entries){
//round to seconds, but store as milliseconds (java timestamp)
date=String.valueOf((Long.parseLong(mydate)/1000)*1000);
mem=new HashMap<String, String>();
mem.put(URL_HASHES, listManager.collection2string(entries));
}
- public void add(String urlHash){
- String urlHashes = mem.get(URL_HASHES);
+ public void add(final String urlHash){
+ final String urlHashes = mem.get(URL_HASHES);
ArrayList<String> list;
if(urlHashes != null && !urlHashes.equals("")){
list=listManager.string2arraylist(urlHashes);
@@ -846,8 +846,8 @@ public class bookmarksDB {
this.mem.put(URL_HASHES, urlHash);
}*/
}
- public void delete(String urlHash){
- ArrayList<String> list=listManager.string2arraylist(this.mem.get(URL_HASHES));
+ public void delete(final String urlHash){
+ final ArrayList<String> list=listManager.string2arraylist(this.mem.get(URL_HASHES));
if(list.contains(urlHash)){
list.remove(urlHash);
}
@@ -860,7 +860,7 @@ public class bookmarksDB {
}else{
bookmarksDB.this.datesTable.remove(getDateString());
}
- } catch (IOException e) {}
+ } catch (final IOException e) {}
}
public String getDateString(){
return date;
@@ -889,7 +889,7 @@ public class bookmarksDB {
private long timestamp;
HashMap<String, String> entry;
- public Bookmark(String urlHash, HashMap<String, String> map) {
+ public Bookmark(final String urlHash, final HashMap<String, String> map) {
this.entry = map;
this.urlHash=urlHash;
if(map.containsKey(BOOKMARK_TAGS))
@@ -906,26 +906,26 @@ public class bookmarksDB {
}
try {
this.urlHash=(new yacyURL(url, null)).hash();
- } catch (MalformedURLException e) {
+ } catch (final MalformedURLException e) {
this.urlHash = null;
}
entry.put(BOOKMARK_URL, url);
this.timestamp=System.currentTimeMillis();
tags=new HashSet<String>();
- Bookmark oldBm=getBookmark(this.urlHash);
+ final Bookmark oldBm=getBookmark(this.urlHash);
if(oldBm!=null && oldBm.entry.containsKey(BOOKMARK_TIMESTAMP)){
entry.put(BOOKMARK_TIMESTAMP, oldBm.entry.get(BOOKMARK_TIMESTAMP)); //preserve timestamp on edit
}else{
entry.put(BOOKMARK_TIMESTAMP, String.valueOf(System.currentTimeMillis()));
}
- bookmarksDate bmDate=getDate(entry.get(BOOKMARK_TIMESTAMP));
+ final bookmarksDate bmDate=getDate(entry.get(BOOKMARK_TIMESTAMP));
bmDate.add(this.urlHash);
bmDate.setDatesTable();
removeBookmark(this.urlHash); //prevent empty tags
}
- public Bookmark(String urlHash, yacyURL url) {
+ public Bookmark(final String urlHash, final yacyURL url) {
entry = new HashMap<String, String>();
this.urlHash=urlHash;
entry.put(BOOKMARK_URL, url.toNormalform(false, true));
@@ -933,7 +933,7 @@ public class bookmarksDB {
timestamp=System.currentTimeMillis();
}
- public Bookmark(String urlHash, String url) {
+ public Bookmark(final String urlHash, final String url) {
entry = new HashMap<String, String>();
this.urlHash=urlHash;
entry.put(BOOKMARK_URL, url);
@@ -941,7 +941,7 @@ public class bookmarksDB {
timestamp=System.currentTimeMillis();
}
- public Bookmark(HashMap<String, String> map) throws MalformedURLException {
+ public Bookmark(final HashMap<String, String> map) throws MalformedURLException {
this((new yacyURL(map.get(BOOKMARK_URL), null)).hash(), map);
}
@@ -969,7 +969,7 @@ public class bookmarksDB {
}
public String getTagsString() {
- String s[] = listManager.collection2string(getTags()).split(",");
+ final String s[] = listManager.collection2string(getTags()).split(",");
String tagsString="";
for (int i=0; i<s.length; i++){
if(!s[i].startsWith("/")){
@@ -980,7 +980,7 @@ public class bookmarksDB {
}
public String getFoldersString(){
- String s[] = listManager.collection2string(getTags()).split(",");
+ final String s[] = listManager.collection2string(getTags()).split(",");
String foldersString="";
for (int i=0; i<s.length; i++){
if(s[i].startsWith("/")){
@@ -1011,7 +1011,7 @@ public class bookmarksDB {
return null; //null means admin
}
- public void setOwner(String owner){
+ public void setOwner(final String owner){
entry.put(BOOKMARK_OWNER, owner);
}
@@ -1029,7 +1029,7 @@ public class bookmarksDB {
return false;
}
- public void setPublic(boolean isPublic){
+ public void setPublic(final boolean isPublic){
if(isPublic){
entry.put(BOOKMARK_PUBLIC, "public");
}else{
@@ -1037,7 +1037,7 @@ public class bookmarksDB {
}
}
- public void setFeed(boolean isFeed){
+ public void setFeed(final boolean isFeed){
if(isFeed){
entry.put(BOOKMARK_IS_FEED, "true");
}else{
@@ -1045,12 +1045,12 @@ public class bookmarksDB {
}
}
- public void setProperty(String name, String value){
+ public void setProperty(final String name, final String value){
entry.put(name, value);
//setBookmarksTable();
}
- public void addTag(String tag){
+ public void addTag(final String tag){
tags.add(tag);
}
@@ -1058,7 +1058,7 @@ public class bookmarksDB {
* set the Tags of the bookmark, and write them into the tags table.
* @param tags2 a ArrayList with the tags
*/
- public void setTags(Set<String> tags2){
+ public void setTags(final Set<String> tags2){
setTags(tags2, true);
}
@@ -1067,12 +1067,12 @@ public class bookmarksDB {
* @param tags ArrayList with the tagnames
* @param local sets, whether the updated tags should be stored to tagsDB
*/
- public void setTags(Set<String> tags2, boolean local){
+ public void setTags(final Set<String> tags2, final boolean local){
tags = tags2; // TODO: check if this is safe
// tags.addAll(tags2); // in order for renameTag() to work I had to change this form 'add' to 'set'
- Iterator<String> it=tags.iterator();
+ final Iterator<String> it=tags.iterator();
while(it.hasNext()){
- String tagName=it.next();
+ final String tagName=it.next();
Tag tag=getTag(tagHash(tagName));
if(tag == null){
tag=new Tag(tagName);
@@ -1089,7 +1089,7 @@ public class bookmarksDB {
return timestamp;
}
- public void setTimeStamp(long ts){
+ public void setTimeStamp(final long ts){
this.timestamp=ts;
}
}
@@ -1100,7 +1100,7 @@ public class bookmarksDB {
kelondroCloneableIterator<byte[]> tagIter;
bookmarksDB.Tag nextEntry;
- public tagIterator(boolean up) throws IOException {
+ public tagIterator(final boolean up) throws IOException {
flushTagCache(); //XXX: This costs performace :-((
this.tagIter = bookmarksDB.this.tagsTable.keys(up, false);
this.nextEntry = null;
@@ -1109,7 +1109,7 @@ public class bookmarksDB {
public boolean hasNext() {
try {
return this.tagIter.hasNext();
- } catch (kelondroException e) {
+ } catch (final kelondroException e) {
//resetDatabase();
return false;
}
@@ -1118,7 +1118,7 @@ public class bookmarksDB {
public Tag next() {
try {
return getTag(new String(this.tagIter.next()));
- } catch (kelondroException e) {
+ } catch (final kelondroException e) {
//resetDatabase();
return null;
}
@@ -1127,9 +1127,9 @@ public class bookmarksDB {
public void remove() {
if (this.nextEntry != null) {
try {
- String tagHash = this.nextEntry.getTagHash();
+ final String tagHash = this.nextEntry.getTagHash();
if (tagHash != null) removeTag(tagHash);
- } catch (kelondroException e) {
+ } catch (final kelondroException e) {
//resetDatabase();
}
}
@@ -1142,7 +1142,7 @@ public class bookmarksDB {
public class bookmarkIterator implements Iterator<Bookmark> {
Iterator<byte[]> bookmarkIter;
bookmarksDB.Bookmark nextEntry;
- public bookmarkIterator(boolean up) throws IOException {
+ public bookmarkIterator(final boolean up) throws IOException {
//flushBookmarkCache(); //XXX: this will cost performance
this.bookmarkIter = bookmarksDB.this.bookmarksTable.keys(up, false);
this.nextEntry = null;
@@ -1151,7 +1151,7 @@ public class bookmarksDB {
public boolean hasNext() {
try {
return this.bookmarkIter.hasNext();
- } catch (kelondroException e) {
+ } catch (final kelondroException e) {
//resetDatabase();
return false;
}
@@ -1160,7 +1160,7 @@ public class bookmarksDB {
public Bookmark next() {
try {
return getBookmark(new String(this.bookmarkIter.next()));
- } catch (kelondroException e) {
+ } catch (final kelondroException e) {
//resetDatabase();
return null;
}
@@ -1169,9 +1169,9 @@ public class bookmarksDB {
public void remove() {
if (this.nextEntry != null) {
try {
- Object bookmarkName = this.nextEntry.getUrlHash();
+ final Object bookmarkName = this.nextEntry.getUrlHash();
if (bookmarkName != null) removeBookmark((String) bookmarkName);
- } catch (kelondroException e) {
+ } catch (final kelondroException e) {
//resetDatabase();
}
}
@@ -1183,18 +1183,18 @@ public class bookmarksDB {
*/
public class bookmarkComparator implements Comparator<String> {
- private boolean newestFirst;
+ private final boolean newestFirst;
/**
* @param newestFirst newest first, or oldest first?
*/
- public bookmarkComparator(boolean newestFirst){
+ public bookmarkComparator(final boolean newestFirst){
this.newestFirst=newestFirst;
}
- public int compare(String obj1, String obj2) {
- Bookmark bm1=getBookmark(obj1);
- Bookmark bm2=getBookmark(obj2);
+ public int compare(final String obj1, final String obj2) {
+ final Bookmark bm1=getBookmark(obj1);
+ final Bookmark bm2=getBookmark(obj2);
if(bm1==null || bm2==null)
return 0; //XXX: i think this should not happen? maybe this needs further tracing of the bug
if(this.newestFirst){
@@ -1211,7 +1211,7 @@ public class bookmarksDB {
*/
public class tagComparator implements Comparator<Tag> {
- public int compare(Tag obj1, Tag obj2){
+ public int compare(final Tag obj1, final Tag obj2){
return obj1.getTagName().compareTo(obj2.getTagName());
}
@@ -1219,7 +1219,7 @@ public class bookmarksDB {
public class tagSizeComparator implements Comparator<Tag> {
- public int compare(Tag obj1, Tag obj2) {
+ public int compare(final Tag obj1, final Tag obj2) {
if (obj1.size() < obj2.size()) return 1;
else if (obj1.getTagName().equals(obj2.getTagName())) return 0;
else return -1;
diff --git a/source/de/anomic/data/diff.java b/source/de/anomic/data/diff.java
index 24589d4d4..cca137b4e 100644
--- a/source/de/anomic/data/diff.java
+++ b/source/de/anomic/data/diff.java
@@ -44,7 +44,7 @@ public class diff {
* @param n the new <code>String</code>
* @throws NullPointerException if one of the arguments is <code>null</code>
*/
- public diff(String o, String n) {
+ public diff(final String o, final String n) {
this(o, n, 1);
}
@@ -57,7 +57,7 @@ public class diff {
* @throws NullPointerException if <code>o</code> or <code>n</code> is
* <code>null</code>
*/
- public diff(String o, String n, int minConsecutive) {
+ public diff(final String o, final String n, final int minConsecutive) {
if (o == null || n == null) throw new NullPointerException("neither o nor n must be null");
this.o = new Comparable[o.length()];
for (int i=0; i<o.length(); i++)
@@ -68,14 +68,14 @@ public class diff {
parse((minConsecutive > 0) ? minConsecutive : 1);
}
- public diff(Object[] o, Object[] n, int minConsecutive) {
+ public diff(final Object[] o, final Object[] n, final int minConsecutive) {
if (o == null || n == null) throw new NullPointerException("neither o nor n must be null");
this.o = o;
this.n = n;
parse((minConsecutive > 0) ? minConsecutive : 1);
}
- private void parse(int minLength) {
+ private void parse(final int minLength) {
/* Matrix: find as long diagonals as possible,
* delete the old horizontally and add the new vertically
*
@@ -99,7 +99,7 @@ public class diff {
* C| | | | | | | | | | | | | | | | |#| |
* E| | |#| | | | | | | | |#| | |#| | |#|
*/
- boolean[][] matrix = new boolean[this.n.length][this.o.length];
+ final boolean[][] matrix = new boolean[this.n.length][this.o.length];
for (int y=0; y<this.n.length; y++)
for (int x=0; x<this.o.length; x++)
matrix[y][x] = this.o[x].equals(this.n[y]);
@@ -114,7 +114,7 @@ public class diff {
addReplacementParts(s, t, this.o.length, this.n.length);
}
- private void addReplacementParts(int startx, int starty, int endx, int endy) {
+ private void addReplacementParts(final int startx, final int starty, final int endx, final int endy) {
if (startx < endx) this.parts.add(new Part(Part.DELETED, startx, endx));
if (starty < endy) this.parts.add(new Part(Part.ADDED, starty, endy));
}
@@ -137,7 +137,7 @@ public class diff {
* @param minLength the minimal desired length of a diagonal to find
* @return a vector in the form <code>{ diagStartX, diagStartY, diagLength }</code> where <code> diagLength >= minLength</code>
*/
- private static int[] findDiagonal(int x, int y, boolean[][] matrix, int minLength) {
+ private static int[] findDiagonal(final int x, final int y, final boolean[][] matrix, final int minLength) {
int rx, ry, yy, xx, i;
for (yy=y; yy<matrix.length; yy++)
for (xx=x; xx<matrix[yy].length; xx++)
@@ -175,7 +175,7 @@ public class diff {
public Part[] getParts() { return this.parts.toArray(new Part[this.parts.size()]); }
public String toString() {
- StringBuffer sb = new StringBuffer(this.parts.size() * 20);
+ final StringBuffer sb = new StringBuffer(this.parts.size() * 20);
for (int j=0; j<this.parts.size(); j++)
sb.append(this.parts.get(j).toString()).append("\n");
return new String(sb);
@@ -198,7 +198,7 @@ public class diff {
private final int posOld;
private final int posNew;
- Part(int action, int posOld, int posNew) {
+ Part(final int action, final int posOld, final int posNew) {
this.action = action;
this.posOld = posOld;
this.posNew = posNew;
@@ -240,8 +240,8 @@ public class diff {
}
}
- public static String toHTML(diff[] diffs) {
- StringBuffer sb = new StringBuffer(diffs.length * 60);
+ public static String toHTML(final diff[] diffs) {
+ final StringBuffer sb = new StringBuffer(diffs.length * 60);
diff.Part[] ps;
for (int i=0; i<diffs.length; i++) {
sb.append("<p class=\"diff\">\n");
diff --git a/source/de/anomic/data/htmlTools.java b/source/de/anomic/data/htmlTools.java
index e1ee55c74..f8616d6d4 100644
--- a/source/de/anomic/data/htmlTools.java
+++ b/source/de/anomic/data/htmlTools.java
@@ -34,14 +34,14 @@ public class htmlTools {
* be transcoded.
* @return the string with all characters replaced by the corresponding character from array
*/
- public static String encodeUnicode2html(String text, boolean includingAmpersand, boolean forXML) {
+ public static String encodeUnicode2html(final String text, final boolean includingAmpersand, final boolean forXML) {
if (text == null)
return null;
- int spos = (includingAmpersand ? 0 : 2);
+ final int spos = (includingAmpersand ? 0 : 2);
// if (forXML), then only encode ampersand, quotation mark, less than and
// greather than which are the first 4 pairs in default mapping table
- int epos = (forXML ? 8 : mapping.length);
+ final int epos = (forXML ? 8 : mapping.length);
return encode(text, mapping, spos, epos);
}
@@ -49,7 +49,7 @@ public class htmlTools {
/**
* Like {@link #encodeUnicode2html(String, boolean, boolean)} with <code>forXML = false</code>
*/
- public static String encodeUnicode2html(String text, boolean includingAmpersand) {
+ public static String encodeUnicode2html(final String text, final boolean includingAmpersand) {
return encodeUnicode2html(text, includingAmpersand, false);
}
@@ -64,7 +64,7 @@ public class htmlTools {
* @param text the original String
* @return the encoded String
*/
- public static String encodeUnicode2xml(String text) {
+ public static String encodeUnicode2xml(final String text) {
return encodeUnicode2html(text, true, true);
}
@@ -78,8 +78,8 @@ public class htmlTools {
* @param epos The ending point, see above.
* @return A copy of the original String with all entities defined in map replaced.
*/
- public static String encode(String text, final String[] map, int spos, int epos) {
- StringBuffer sb = new StringBuffer(text.length());
+ public static String encode(final String text, final String[] map, final int spos, final int epos) {
+ final StringBuffer sb = new StringBuffer(text.length());
int textpos = 0;
search: while (textpos < text.length()) {
// find a (forward) mapping
@@ -98,10 +98,10 @@ public class htmlTools {
return sb.toString();
}
- public static String decodeHtml2Unicode(String text) {
+ public static String decodeHtml2Unicode(final String text) {
if (text == null) return null;
int pos = 0;
- StringBuffer sb = new StringBuffer(text.length());
+ final StringBuffer sb = new StringBuffer(text.length());
search: while (pos < text.length()) {
// find a reverse mapping. TODO: replace matching with hashtable(s)
loop: for (int i = 0; i < mapping.length; i += 2) {
@@ -267,9 +267,9 @@ public class htmlTools {
"\u00FF","&yuml;"
};
- public static void main(String[] args) {
- String text = "Test-Text mit & um zyklische &uuml; &amp; Ersetzungen auszuschliessen";
- String txet = encodeUnicode2html(text, true);
+ public static void main(final String[] args) {
+ final String text = "Test-Text mit & um zyklische &uuml; &amp; Ersetzungen auszuschliessen";
+ final String txet = encodeUnicode2html(text, true);
System.out.println(txet);
System.out.println(decodeHtml2Unicode(txet));
if (decodeHtml2Unicode(txet).equals(text)) System.out.println("correct");
diff --git a/source/de/anomic/data/listManager.java b/source/de/anomic/data/listManager.java
index 802e5daaf..282938c6e 100644
--- a/source/de/anomic/data/listManager.java
+++ b/source/de/anomic/data/listManager.java
@@ -62,7 +62,7 @@ public class listManager {
* @param setName name of the ListSet
* @return a ListSet from configuration file
*/
- public static Set<String> getListSet(String setName) {
+ public static Set<String> getListSet(final String setName) {
return string2set(switchboard.getConfig(setName, ""));
}
@@ -73,8 +73,8 @@ public class listManager {
* @param setName name of the ListSet.
* @param listName name of the element to remove from the ListSet.
*/
- public static void removeFromListSet(String setName, String listName) {
- Set<String> listSet = getListSet(setName);
+ public static void removeFromListSet(final String setName, final String listName) {
+ final Set<String> listSet = getListSet(setName);
if (listSet.size() > 0) {
listSet.remove(listName);
@@ -92,8 +92,8 @@ public class listManager {
* @param setName
* @param newListName
*/
- public static void updateListSet(String setName, String newListName) {
- Set<String> listSet = getListSet(setName);
+ public static void updateListSet(final String setName, final String newListName) {
+ final Set<String> listSet = getListSet(setName);
listSet.add(newListName);
switchboard.setConfig(setName, collection2string(listSet));
@@ -105,8 +105,8 @@ public class listManager {
* @return <code>true</code> if the ListSet "setName" contains an element
* "listName", <code>false</code> otherwise.
*/
- public static boolean listSetContains(String setName, String listName) {
- Set<String> Lists = getListSet(setName);
+ public static boolean listSetContains(final String setName, final String listName) {
+ final Set<String> Lists = getListSet(setName);
return Lists.contains(listName);
}
@@ -120,9 +120,9 @@ public class listManager {
* @param listFile the file
* @return the resulting array as an ArrayList
*/
- public static ArrayList<String> getListArray(File listFile){
+ public static ArrayList<String> getListArray(final File listFile){
String line;
- ArrayList<String> list = new ArrayList<String>();
+ final ArrayList<String> list = new ArrayList<String>();
int count = 0;
BufferedReader br = null;
try {
@@ -133,10 +133,10 @@ public class listManager {
count++;
}
br.close();
- } catch(IOException e) {
+ } catch(final IOException e) {
// list is empty
} finally {
- if (br!=null) try { br.close(); } catch (Exception e) {}
+ if (br!=null) try { br.close(); } catch (final Exception e) {}
}
return list;
}
@@ -148,17 +148,17 @@ public class listManager {
* @param out the String to write
* @return returns <code>true</code> if successful, <code>false</code> otherwise
*/
- public static boolean writeList(File listFile, String out) {
+ public static boolean writeList(final File listFile, final String out) {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new PrintWriter(new FileWriter(listFile)));
bw.write(out);
bw.close();
return true;
- } catch(IOException e) {
+ } catch(final IOException e) {
return false;
} finally {
- if (bw!=null) try { bw.close(); } catch (Exception e) {}
+ if (bw!=null) try { bw.close(); } catch (final Exception e) {}
}
}
@@ -169,8 +169,8 @@ public class listManager {
* @param list the Array to write
* @return returns <code>true</code> if successful, <code>false</code> otherwise
*/
- public static boolean writeList(File listFile, String[] list){
- StringBuffer out = new StringBuffer();
+ public static boolean writeList(final File listFile, final String[] list){
+ final StringBuffer out = new StringBuffer();
for(int i=0;i < list.length; i++){
out
.append(list[i])
@@ -180,8 +180,8 @@ public class listManager {
}
// same as below
- public static String getListString(String filename, boolean withcomments) {
- File listFile = new File(listsPath ,filename);
+ public static String getListString(final String filename, final boolean withcomments) {
+ final File listFile = new File(listsPath ,filename);
return getListString(listFile, withcomments);
}
@@ -192,8 +192,8 @@ public class listManager {
* @param withcomments If <code>false</code> ignore lines starting with '#'.
* @return String representation of the file content.
*/
- public static String getListString(File listFile, boolean withcomments){
- StringBuffer temp = new StringBuffer();
+ public static String getListString(final File listFile, final boolean withcomments){
+ final StringBuffer temp = new StringBuffer();
BufferedReader br = null;
try{
@@ -210,16 +210,16 @@ public class listManager {
}
}
br.close();
- } catch (IOException e) {
+ } catch (final IOException e) {
} finally {
- if (br!=null) try { br.close(); } catch (Exception e) {}
+ if (br!=null) try { br.close(); } catch (final Exception e) {}
}
return new String(temp);
}
// get a Directory Listing as a String Array
- public static String[] getDirListing(String dirname){
+ public static String[] getDirListing(final String dirname){
final File dir = new File(dirname);
return getDirListing(dir);
}
@@ -231,7 +231,7 @@ public class listManager {
* it will be created.
* @return array of file names
*/
- public static String[] getDirListing(File dir){
+ public static String[] getDirListing(final File dir){
String[] fileListString;
File[] fileList;
@@ -250,7 +250,7 @@ public class listManager {
}
// same as below
- public static ArrayList<File> getDirsRecursive(File dir, String notdir){
+ public static ArrayList<File> getDirsRecursive(final File dir, final String notdir){
return getDirsRecursive(dir, notdir, true);
}
@@ -259,7 +259,7 @@ public class listManager {
*
* Warning: untested
*/
- public static ArrayList<File> getDirsRecursive(File dir, String notdir, boolean excludeDotfiles){
+ public static ArrayList<File> getDirsRecursive(final File dir, final String notdir, final boolean excludeDotfiles){
final File[] dirList = dir.listFiles();
final ArrayList<File> resultList = new ArrayList<File>();
ArrayList<File> recursive;
@@ -288,11 +288,11 @@ public class listManager {
* @param col a Collection of Strings.
* @return String with elements from set separated by comma.
*/
- public static String collection2string(Collection<String> col){
- StringBuffer str = new StringBuffer();
+ public static String collection2string(final Collection<String> col){
+ final StringBuffer str = new StringBuffer();
if (col != null && (col.size() > 0)) {
- Iterator<String> it = col.iterator();
+ final Iterator<String> it = col.iterator();
str.append(it.next());
while(it.hasNext()) {
str.append(",").append(it.next());
@@ -305,7 +305,7 @@ public class listManager {
/**
* @see listManager#string2vector(String)
*/
- public static ArrayList<String> string2arraylist(String string){
+ public static ArrayList<String> string2arraylist(final String string){
ArrayList<String> l;
if (string != null && string.length() > 0) {
@@ -323,7 +323,7 @@ public class listManager {
* @param string list of comma separated Strings
* @return resulting Set or empty Set if string is <code>null</code>
*/
- public static Set<String> string2set(String string){
+ public static Set<String> string2set(final String string){
HashSet<String> set;
if (string != null) {
@@ -342,7 +342,7 @@ public class listManager {
* @param string list of comma separated Strings
* @return resulting Vector or empty Vector if string is <code>null</code>
*/
- public static Vector<String> string2vector(String string){
+ public static Vector<String> string2vector(final String string){
Vector<String> v;
if (string != null) {
@@ -360,12 +360,12 @@ public class listManager {
* Load or reload all active Blacklists
*/
public static void reloadBlacklists(){
- String supportedBlacklistTypesStr = indexAbstractReferenceBlacklist.BLACKLIST_TYPES_STRING;
- String[] supportedBlacklistTypes = supportedBlacklistTypesStr.split(",");
+ final String supportedBlacklistTypesStr = indexAbstractReferenceBlacklist.BLACKLIST_TYPES_STRING;
+ final String[] supportedBlacklistTypes = supportedBlacklistTypesStr.split(",");
- ArrayList<blacklistFile> blacklistFiles = new ArrayList<blacklistFile>(supportedBlacklistTypes.length);
+ final ArrayList<blacklistFile> blacklistFiles = new ArrayList<blacklistFile>(supportedBlacklistTypes.length);
for (int i=0; i < supportedBlacklistTypes.length; i++) {
- blacklistFile blFile = new blacklistFile(
+ final blacklistFile blFile = new blacklistFile(
switchboard.getConfig(
supportedBlacklistTypes[i] + ".BlackLists", switchboard.getConfig("BlackLists.DefaultList", "url.default.black")),
supportedBlacklistTypes[i]);
diff --git a/source/de/anomic/data/messageBoard.java b/source/de/anomic/data/messageBoard.java
index ecff50cd5..0a5af7666 100644
--- a/source/de/anomic/data/messageBoard.java
+++ b/source/de/anomic/data/messageBoard.java
@@ -50,7 +50,7 @@ public class messageBoard {
kelondroMap database = null;
private int sn = 0;
- public messageBoard(File path) {
+ public messageBoard(final File path) {
new File(path.getParent()).mkdir();
if (database == null) {
database = new kelondroMap(new kelondroBLOBTree(path, true, true, categoryLength + dateFormat.length() + 2, recordSize, '_', kelondroNaturalOrder.naturalOrder, true, false, false), 500);
@@ -80,10 +80,10 @@ public class messageBoard {
return s;
}
- public entry newEntry(String category,
- String authorName, String authorHash,
- String recName, String recHash,
- String subject, byte[] message) {
+ public entry newEntry(final String category,
+ final String authorName, final String authorHash,
+ final String recName, final String recHash,
+ final String subject, final byte[] message) {
return new entry(category, authorName, authorHash, recName, recHash, subject, message);
}
@@ -92,10 +92,10 @@ public class messageBoard {
String key; // composed by category and date
HashMap<String, String> record; // contains author, target hash, subject and message
- public entry(String category,
+ public entry(final String category,
String authorName, String authorHash,
String recName, String recHash,
- String subject, byte[] message) {
+ String subject, final byte[] message) {
record = new HashMap<String, String>();
key = category;
if (key.length() > categoryLength) key = key.substring(0, categoryLength);
@@ -118,7 +118,7 @@ public class messageBoard {
record.put("read", "false");
}
- entry(String key, HashMap<String, String> record) {
+ entry(final String key, final HashMap<String, String> record) {
this.key = key;
this.record = record;
}
@@ -130,7 +130,7 @@ public class messageBoard {
synchronized (SimpleFormatter) {
return SimpleFormatter.parse(c);
}
- } catch (ParseException e) {
+ } catch (final ParseException e) {
return new Date();
}
}
@@ -142,78 +142,78 @@ public class messageBoard {
}
public String author() {
- String a = record.get("author");
+ final String a = record.get("author");
if (a == null) return "anonymous";
return a;
}
public String recipient() {
- String a = record.get("recipient");
+ final String a = record.get("recipient");
if (a == null) return "anonymous";
return a;
}
public String authorHash() {
- String a = record.get("ahash");
+ final String a = record.get("ahash");
if (a == null) return null;
return a;
}
public String recipientHash() {
- String a = record.get("rhash");
+ final String a = record.get("rhash");
if (a == null) return null;
return a;
}
public String subject() {
- String s = record.get("subject");
+ final String s = record.get("subject");
if (s == null) return "";
return s;
}
public byte[] message() {
- String m = record.get("message");
+ final String m = record.get("message");
if (m == null) return new byte[0];
record.put("read", "true");
return kelondroBase64Order.enhancedCoder.decode(m, "de.anomic.data.messageBoard.message()");
}
public boolean read() {
- String r = record.get("read");
+ final String r = record.get("read");
if (r == null) return false;
if (r.equals("false")) return false;
return true;
}
}
- public String write(entry message) {
+ public String write(final entry message) {
// writes a message and returns key
try {
database.put(message.key, message.record);
return message.key;
- } catch (IOException e) {
+ } catch (final IOException e) {
return null;
}
}
- public entry read(String key) {
+ public entry read(final String key) {
HashMap<String, String> record;
try {
record = database.get(key);
- } catch (IOException e) {
+ } catch (final IOException e) {
return null;
}
return new entry(key, record);
}
- public void remove(String key) {
+ public void remove(final String key) {
try {
database.remove(key);
- } catch (IOException e) {
+ } catch (final IOException e) {
}
}
- public Iterator<String> keys(String category, boolean up) throws IOException {
+ public Iterator<String> keys(final String category, final boolean up) throws IOException {
//return database.keys();
return new catIter(category, up);
}
@@ -224,7 +224,7 @@ public class messageBoard {
String nextKey = null;
String category = "";
- public catIter(String category, boolean up) throws IOException {
+ public catIter(final String category, final boolean up) throws IOException {
this.allIter = database.keys(up, false);
this.category = category;
findNext();
@@ -243,7 +243,7 @@ public class messageBoard {
}
public String next() {
- String next = nextKey;
+ final String next = nextKey;
findNext();
return next;
}
diff --git a/source/de/anomic/data/translator.java b/source/de/anomic/data/translator.java
index 1bb80358b..60b2ae39b 100644
--- a/source/de/anomic/data/translator.java
+++ b/source/de/anomic/data/translator.java
@@ -58,14 +58,14 @@ import de.anomic.tools.yFormatter;
* Uses a Property like file with phrases or single words to translate a string or a file
* */
public class translator {
- public static String translate(String source, Hashtable<String, String> translationList){
- Enumeration<String> keys = translationList.keys();
+ public static String translate(final String source, final Hashtable<String, String> translationList){
+ final Enumeration<String> keys = translationList.keys();
String result = source;
String key = "";
while(keys.hasMoreElements()){
key = keys.nextElement();
- Pattern pattern = Pattern.compile(key);
- Matcher matcher = pattern.matcher(result);
+ final Pattern pattern = Pattern.compile(key);
+ final Matcher matcher = pattern.matcher(result);
if (matcher.find()) {
result = matcher.replaceAll(translationList.get(key));
} else {
@@ -81,12 +81,12 @@ public class translator {
* @param translationFile the File, which contains the Lists
* @return a Hashtable, which contains for each File a Hashtable with translations.
*/
- public static Hashtable<String, Hashtable<String, String>> loadTranslationsLists(File translationFile){
- Hashtable<String, Hashtable<String, String>> lists = new Hashtable<String, Hashtable<String, String>>(); //list of translationLists for different files.
+ public static Hashtable<String, Hashtable<String, String>> loadTranslationsLists(final File translationFile){
+ final Hashtable<String, Hashtable<String, String>> lists = new Hashtable<String, Hashtable<String, String>>(); //list of translationLists for different files.
Hashtable<String, String> translationList = new Hashtable<String, String>(); //current Translation Table
- ArrayList<String> list = listManager.getListArray(translationFile);
- Iterator<String> it = list.iterator();
+ final ArrayList<String> list = listManager.getListArray(translationFile);
+ final Iterator<String> it = list.iterator();
String line = "";
String[] splitted;
String forFile="";
@@ -119,12 +119,12 @@ public class translator {
return lists;
}
- public static boolean translateFile(File sourceFile, File destFile, File translationFile){
- Hashtable<String, String> translationList = loadTranslationsLists(translationFile).get(sourceFile.getName());
+ public static boolean translateFile(final File sourceFile, final File destFile, final File translationFile){
+ final Hashtable<String, String> translationList = loadTranslationsLists(translationFile).get(sourceFile.getName());
return translateFile(sourceFile, destFile, translationList);
}
- public static boolean translateFile(File sourceFile, File destFile, Hashtable<String, String> translationList){
+ public static boolean translateFile(final File sourceFile, final File destFile, final Hashtable<String, String> translationList){
String content = "";
String line = "";
@@ -135,10 +135,10 @@ public class translator {
content += line + de.anomic.server.serverCore.CRLF_STRING;
}
br.close();
- }catch(IOException e){
+ }catch(final IOException e){
return false;
} finally {
- if (br!=null)try{br.close();}catch(Exception e){}
+ if (br!=null)try{br.close();}catch(final Exception e){}
}
content = translate(content, translationList);
@@ -147,24 +147,24 @@ public class translator {
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(destFile),"UTF-8"));
bw.write(content);
bw.close();
- }catch(IOException e){
+ }catch(final IOException e){
return false;
} finally {
- if(bw!=null)try{bw.close();}catch(Exception e){}
+ if(bw!=null)try{bw.close();}catch(final Exception e){}
}
return true;
}
- public static boolean translateFiles(File sourceDir, File destDir, File baseDir, File translationFile, String extensions){
- Hashtable<String, Hashtable<String, String>> translationLists = loadTranslationsLists(translationFile);
+ public static boolean translateFiles(final File sourceDir, final File destDir, final File baseDir, final File translationFile, final String extensions){
+ final Hashtable<String, Hashtable<String, String>> translationLists = loadTranslationsLists(translationFile);
return translateFiles(sourceDir, destDir, baseDir, translationLists, extensions);
}
- public static boolean translateFiles(File sourceDir, File destDir, File baseDir, Hashtable<String, Hashtable<String, String>> translationLists, String extensions){
+ public static boolean translateFiles(final File sourceDir, final File destDir, final File baseDir, final Hashtable<String, Hashtable<String, String>> translationLists, final String extensions){
destDir.mkdirs();
- File[] sourceFiles = sourceDir.listFiles();
- Vector<String> exts=listManager.string2vector(extensions);
+ final File[] sourceFiles = sourceDir.listFiles();
+ final Vector<String> exts=listManager.string2vector(extensions);
boolean rightExtension;
Iterator<String> it;
String relativePath;
@@ -181,7 +181,7 @@ public class translator {
try{
relativePath=sourceFiles[i].getAbsolutePath().substring(baseDir.getAbsolutePath().length()+1); //+1 to get the "/"
relativePath = relativePath.replace(File.separatorChar, '/');
- }catch(IndexOutOfBoundsException e){
+ }catch(final IndexOutOfBoundsException e){
serverLog.logSevere("TRANSLATOR", "Error creating relative Path for "+sourceFiles[i].getAbsolutePath());
relativePath="wrong path"; //not in translationLists
}
@@ -202,10 +202,10 @@ public class translator {
return true;
}
- public static boolean translateFilesRecursive(File sourceDir, File destDir, File translationFile, String extensions, String notdir){
- ArrayList<File> dirList=listManager.getDirsRecursive(sourceDir, notdir);
+ public static boolean translateFilesRecursive(final File sourceDir, final File destDir, final File translationFile, final String extensions, final String notdir){
+ final ArrayList<File> dirList=listManager.getDirsRecursive(sourceDir, notdir);
dirList.add(sourceDir);
- Iterator<File> it=dirList.iterator();
+ final Iterator<File> it=dirList.iterator();
File file=null;
File file2=null;
while(it.hasNext()){
@@ -219,9 +219,9 @@ public class translator {
return true;
}
- public static HashMap<String, String> langMap(serverSwitch<?> env) {
- String[] ms = env.getConfig("locale.lang", "").split(",");
- HashMap<String, String> map = new HashMap<String, String>();
+ public static HashMap<String, String> langMap(final serverSwitch<?> env) {
+ final String[] ms = env.getConfig("locale.lang", "").split(",");
+ final HashMap<String, String> map = new HashMap<String, String>();
int p;
for (int i = 0; i < ms.length; i++) {
p = ms[i].indexOf("/");
@@ -231,18 +231,18 @@ public class translator {
return map;
}
- public static boolean changeLang(serverSwitch<?> env, String langPath, String lang) {
+ public static boolean changeLang(final serverSwitch<?> env, final String langPath, final String lang) {
if ((lang.equals("default")) || (lang.equals("default.lng"))) {
env.setConfig("locale.language", "default");
return true;
}
- String htRootPath = env.getConfig("htRootPath", "htroot");
- File sourceDir = new File(env.getRootPath(), htRootPath);
- File destDir = new File(env.getConfigPath("locale.translated_html","DATA/LOCALE/htroot"), lang.substring(0, lang.length() - 4));// cut
+ final String htRootPath = env.getConfig("htRootPath", "htroot");
+ final File sourceDir = new File(env.getRootPath(), htRootPath);
+ final File destDir = new File(env.getConfigPath("locale.translated_html","DATA/LOCALE/htroot"), lang.substring(0, lang.length() - 4));// cut
// .lng
//File destDir = new File(env.getRootPath(), htRootPath + "/locale/" + lang.substring(0, lang.length() - 4));// cut
// .lng
- File translationFile = new File(langPath, lang);
+ final File translationFile = new File(langPath, lang);
//if (translator.translateFiles(sourceDir, destDir, translationFile, "html")) {
if(translator.translateFilesRecursive(sourceDir, destDir,
@@ -250,10 +250,10 @@ public class translator {
env.setConfig("locale.language", lang.substring(0, lang.length() - 4));
yFormatter.setLocale(env.getConfig("locale.language", "en"));
try {
- BufferedWriter bw = new BufferedWriter(new PrintWriter(new FileWriter(new File(destDir, "version"))));
+ final BufferedWriter bw = new BufferedWriter(new PrintWriter(new FileWriter(new File(destDir, "version"))));
bw.write(env.getConfig("svnRevision", "Error getting Version"));
bw.close();
- } catch (IOException e) {
+ } catch (final IOException e) {
// Error
}
return true;
diff --git a/source/de/anomic/data/userDB.java b/source/de/anomic/data/userDB.java
index b7cc082ba..e903abbd8 100644
--- a/source/de/anomic/data/userDB.java
+++ b/source/de/anomic/data/userDB.java
@@ -54,7 +54,7 @@ public final class userDB {
HashMap<String, String> ipUsers = new HashMap<String, String>();
HashMap<String, Object> cookieUsers = new HashMap<String, Object>();
- public userDB(File userTableFile) {
+ public userDB(final File userTableFile) {
this.userTableFile = userTableFile;
userTableFile.getParentFile().mkdirs();
this.userTable = new kelondroMap(new kelondroBLOBTree(userTableFile, true, true, 128, 256, '_', kelondroNaturalOrder.naturalOrder, true, false, false), 10);
@@ -76,10 +76,10 @@ public final class userDB {
return userTable.size();
}
- public void removeEntry(String hostName) {
+ public void removeEntry(final String hostName) {
try {
userTable.remove(hostName.toLowerCase());
- } catch (IOException e) {}
+ } catch (final IOException e) {}
}
public Entry getEntry(String userName) {
@@ -89,23 +89,23 @@ public final class userDB {
HashMap<String, String> record;
try {
record = userTable.get(userName);
- } catch (IOException e) {
+ } catch (final IOException e) {
return null;
}
if (record == null) return null;
return new Entry(userName, record);
}
- public Entry createEntry(String userName, HashMap<String, String> userProps) throws IllegalArgumentException{
- Entry entry = new Entry(userName,userProps);
+ public Entry createEntry(final String userName, final HashMap<String, String> userProps) throws IllegalArgumentException{
+ final Entry entry = new Entry(userName,userProps);
return entry;
}
- public String addEntry(Entry entry) {
+ public String addEntry(final Entry entry) {
try {
userTable.put(entry.userName,entry.mem);
return entry.userName;
- } catch (IOException e) {
+ } catch (final IOException e) {
return null;
}
}
@@ -122,8 +122,8 @@ public final class userDB {
try{
auth=kelondroBase64Order.standardCoder.decodeString(auth, "de.anomic.data.userDB.proxyAuth()");
- }catch(RuntimeException e){} //no valid Base64
- String[] tmp=auth.split(":");
+ }catch(final RuntimeException e){} //no valid Base64
+ final String[] tmp=auth.split(":");
if(tmp.length == 2){
entry=this.passwordAuth(tmp[0], tmp[1]);
// if(entry != null){
@@ -138,10 +138,10 @@ public final class userDB {
}
return null;
}
- public Entry getUser(httpHeader header){
+ public Entry getUser(final httpHeader header){
return getUser(header.get(httpHeader.AUTHORIZATION), header.get(httpHeader.CONNECTION_PROP_CLIENTIP), header.getHeaderCookies());
}
- public Entry getUser(String auth, String ip, String cookies){
+ public Entry getUser(final String auth, final String ip, final String cookies){
Entry entry=null;
if(auth != null)
entry=proxyAuth(auth);
@@ -154,8 +154,8 @@ public final class userDB {
* it tests both userDB and oldstyle adminpw.
* @param auth the http-headerline for authorisation
*/
- public boolean hasAdminRight(String auth, String ip, String cookies){
- Entry entry=getUser(auth, ip, cookies);
+ public boolean hasAdminRight(final String auth, final String ip, final String cookies){
+ final Entry entry=getUser(auth, ip, cookies);
if(entry != null)
return entry.hasAdminRight();
else if(entry != null && cookieAdminAuth(cookies))
@@ -169,8 +169,8 @@ public final class userDB {
* @param auth a base64 Encoded String, which contains "username:pw".
* @param ip an ip.
*/
- public Entry proxyAuth(String auth, String ip){
- Entry entry=proxyAuth(auth);
+ public Entry proxyAuth(final String auth, final String ip){
+ final Entry entry=proxyAuth(auth);
if(entry == null){
return null;
}
@@ -182,11 +182,11 @@ public final class userDB {
* authenticate a user by ip, if he had used proxyAuth in the last 10 Minutes
* @param ip the IP of the User
*/
- public Entry ipAuth(String ip) {
+ public Entry ipAuth(final String ip) {
if(this.ipUsers.containsKey(ip)){
- String user=this.ipUsers.get(ip);
- Entry entry=this.getEntry(user);
- Long entryTimestamp=entry.getLastAccess();
+ final String user=this.ipUsers.get(ip);
+ final Entry entry=this.getEntry(user);
+ final Long entryTimestamp=entry.getLastAccess();
if(entryTimestamp == null || (System.currentTimeMillis()-entryTimestamp.longValue()) > (1000*60*10) ){ //no timestamp or older than 10 Minutes
return null;
}
@@ -194,21 +194,21 @@ public final class userDB {
}
return null;
}
- public Entry passwordAuth(String user, String password){
- Entry entry=this.getEntry(user);
+ public Entry passwordAuth(final String user, final String password){
+ final Entry entry=this.getEntry(user);
if( entry != null && entry.getMD5EncodedUserPwd().equals(serverCodings.encodeMD5Hex(user+":"+password)) ){
if(entry.isLoggedOut()){
try{
entry.setProperty(Entry.LOGGED_OUT, "false");
- }catch(IOException e){}
+ }catch(final IOException e){}
return null;
}
return entry;
}
return null;
}
- public Entry passwordAuth(String user, String password, String ip){
- Entry entry=passwordAuth(user, password);
+ public Entry passwordAuth(final String user, final String password, final String ip){
+ final Entry entry=passwordAuth(user, password);
if(entry == null){
return null;
}
@@ -216,52 +216,52 @@ public final class userDB {
this.ipUsers.put(ip, entry.getUserName()); //XXX: This is insecure. TODO: use cookieauth
return entry;
}
- public Entry md5Auth(String user, String md5){
- Entry entry=this.getEntry(user);
+ public Entry md5Auth(final String user, final String md5){
+ final Entry entry=this.getEntry(user);
if( entry != null && entry.getMD5EncodedUserPwd().equals(md5)){
if(entry.isLoggedOut()){
try{
entry.setProperty(Entry.LOGGED_OUT, "false");
- }catch(IOException e){}
+ }catch(final IOException e){}
return null;
}
return entry;
}
return null;
}
- public Entry cookieAuth(String cookieString){
- String token=getLoginToken(cookieString);
+ public Entry cookieAuth(final String cookieString){
+ final String token=getLoginToken(cookieString);
if(cookieUsers.containsKey(token)){
- Object entry=cookieUsers.get(token);
+ final Object entry=cookieUsers.get(token);
if(entry instanceof Entry) //String would mean static Admin
return (Entry)entry;
}
return null;
}
- public boolean cookieAdminAuth(String cookieString){
- String token=getLoginToken(cookieString);
+ public boolean cookieAdminAuth(final String cookieString){
+ final String token=getLoginToken(cookieString);
if(cookieUsers.containsKey(token)){
- Object entry=cookieUsers.get(token);
+ final Object entry=cookieUsers.get(token);
if(entry instanceof String && entry.equals("admin"))
return true;
}
return false;
}
- public String getCookie(Entry entry){
- Random r = new Random();
- String token = Long.toString(Math.abs(r.nextLong()), 36);
+ public String getCookie(final Entry entry){
+ final Random r = new Random();
+ final String token = Long.toString(Math.abs(r.nextLong()), 36);
cookieUsers.put(token, entry);
return token;
}
public String getAdminCookie(){
- Random r = new Random();
- String token = Long.toString(Math.abs(r.nextLong()), 36);
+ final Random r = new Random();
+ final String token = Long.toString(Math.abs(r.nextLong()), 36);
cookieUsers.put(token, "admin");
return token;
}
- public static String getLoginToken(String cookies){
- String[] cookie=cookies.split(";"); //TODO: Mozilla uses "; "
+ public static String getLoginToken(final String cookies){
+ final String[] cookie=cookies.split(";"); //TODO: Mozilla uses "; "
String[] pair;
for(int i=0;i<cookie.length;i++){
pair=cookie[i].split("=");
@@ -271,7 +271,7 @@ public final class userDB {
}
return "";
}
- public void adminLogout(String logintoken){
+ public void adminLogout(final String logintoken){
if(cookieUsers.containsKey(logintoken)){
//XXX: We could check, if its == "admin", but we want to logout anyway.
cookieUsers.remove(logintoken);
@@ -313,9 +313,9 @@ public final class userDB {
// this is a simple record structure that hold all properties of a user
HashMap<String, String> mem;
String userName;
- private Calendar oldDate, newDate;
+ private final Calendar oldDate, newDate;
- public Entry(String userName, HashMap<String, String> mem) throws IllegalArgumentException {
+ public Entry(final String userName, final HashMap<String, String> mem) throws IllegalArgumentException {
if ((userName == null) || (userName.length() == 0))
throw new IllegalArgumentException("Username needed.");
if(userName.length()>128){
@@ -354,13 +354,13 @@ public final class userDB {
if (this.mem.containsKey(TIME_USED)) {
try{
return Long.valueOf(this.mem.get(TIME_USED)).longValue();
- }catch(NumberFormatException e){
+ }catch(final NumberFormatException e){
return 0;
}
}
try {
this.setProperty(TIME_USED,"0");
- } catch (IOException e) {}
+ } catch (final IOException e) {}
return 0;
}
@@ -368,13 +368,13 @@ public final class userDB {
if (this.mem.containsKey(TIME_LIMIT)) {
try{
return Long.valueOf(this.mem.get(TIME_LIMIT)).longValue();
- }catch(NumberFormatException e){
+ }catch(final NumberFormatException e){
return 0;
}
}
try {
this.setProperty(TIME_LIMIT,"0");
- } catch (IOException e) {}
+ } catch (final IOException e) {}
return 0;
}
@@ -384,7 +384,7 @@ public final class userDB {
}
try {
this.setProperty(TRAFFIC_SIZE,"0");
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
return 0;
@@ -394,14 +394,14 @@ public final class userDB {
return (this.mem.containsKey(TRAFFIC_LIMIT)?Long.valueOf(this.mem.get(TRAFFIC_LIMIT)):null);
}
- public long updateTrafficSize(long responseSize) {
+ public long updateTrafficSize(final long responseSize) {
if (responseSize < 0) throw new IllegalArgumentException("responseSize must be greater or equal zero.");
- long currentTrafficSize = getTrafficSize();
- long newTrafficSize = currentTrafficSize + responseSize;
+ final long currentTrafficSize = getTrafficSize();
+ final long newTrafficSize = currentTrafficSize + responseSize;
try {
this.setProperty(TRAFFIC_SIZE,Long.toString(newTrafficSize));
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
return newTrafficSize;
@@ -412,7 +412,7 @@ public final class userDB {
}
public int surfRight(){
- long timeUsed=this.updateLastAccess(true);
+ final long timeUsed=this.updateLastAccess(true);
if(this.hasProxyRight() == false)
return PROXY_NORIGHT;
@@ -425,13 +425,13 @@ public final class userDB {
if(this.surfRight()==PROXY_ALLOK) return true;
return false;
}
- public long updateLastAccess(boolean incrementTimeUsed) {
+ public long updateLastAccess(final boolean incrementTimeUsed) {
return updateLastAccess(System.currentTimeMillis(), incrementTimeUsed);
}
- public long updateLastAccess(long timeStamp, boolean incrementTimeUsed) {
+ public long updateLastAccess(final long timeStamp, final boolean incrementTimeUsed) {
if (timeStamp < 0) throw new IllegalArgumentException();
- Long lastAccess = this.getLastAccess();
+ final Long lastAccess = this.getLastAccess();
long oldTimeUsed = getTimeUsed();
long newTimeUsed = oldTimeUsed;
@@ -461,7 +461,7 @@ public final class userDB {
try {
userDB.this.userTable.put(getUserName(), this.mem);
- } catch(Exception e){
+ } catch(final Exception e){
e.printStackTrace();
}
return newTimeUsed;
@@ -475,15 +475,15 @@ public final class userDB {
return this.mem;
}
- public void setProperty(String propName, String newValue) throws IOException {
+ public void setProperty(final String propName, final String newValue) throws IOException {
this.mem.put(propName, newValue);
userDB.this.userTable.put(getUserName(), this.mem);
}
- public String getProperty(String propName, String defaultValue) {
+ public String getProperty(final String propName, final String defaultValue) {
return (this.mem.containsKey(propName)?this.mem.get(propName):defaultValue);
}
- public boolean hasRight(String rightName){
+ public boolean hasRight(final String rightName){
return (this.mem.containsKey(rightName)?this.mem.get(rightName).equals("true"):false);
}
/**
@@ -531,25 +531,25 @@ public final class userDB {
public boolean isLoggedOut(){
return (this.mem.containsKey(LOGGED_OUT)?this.mem.get(LOGGED_OUT).equals("true"):false);
}
- public void logout(String ip, String logintoken){
+ public void logout(final String ip, final String logintoken){
logout(ip);
if(cookieUsers.containsKey(logintoken)){
cookieUsers.remove(logintoken);
}
}
- public void logout(String ip){
+ public void logout(final String ip){
try{
setProperty(LOGGED_OUT, "true");
if(ipUsers.containsKey(ip)){
ipUsers.remove(ip);
}
- }catch(IOException e){}
+ }catch(final IOException e){}
}
public void logout(){
logout("xxxxxx");
}
public String toString() {
- StringBuffer str = new StringBuffer();
+ final StringBuffer str = new StringBuffer();
str.append((this.userName==null)?"null":this.userName)
.append(": ");
@@ -562,11 +562,11 @@ public final class userDB {
}
- public Iterator<Entry> iterator(boolean up) {
+ public Iterator<Entry> iterator(final boolean up) {
// enumerates users
try {
return new userIterator(up);
- } catch (IOException e) {
+ } catch (final IOException e) {
return new HashSet<Entry>().iterator();
}
}
@@ -577,14 +577,14 @@ public final class userDB {
kelondroCloneableIterator<byte[]> userIter;
userDB.Entry nextEntry;
- public userIterator(boolean up) throws IOException {
+ public userIterator(final boolean up) throws IOException {
this.userIter = userDB.this.userTable.keys(up, false);
this.nextEntry = null;
}
public boolean hasNext() {
try {
return this.userIter.hasNext();
- } catch (kelondroException e) {
+ } catch (final kelondroException e) {
resetDatabase();
return false;
}
@@ -592,7 +592,7 @@ public final class userDB {
public Entry next() {
try {
return getEntry(new String(this.userIter.next()));
- } catch (kelondroException e) {
+ } catch (final kelondroException e) {
resetDatabase();
return null;
}
@@ -600,9 +600,9 @@ public final class userDB {
public void remove() {
if (this.nextEntry != null) {
try {
- Object userName = this.nextEntry.getUserName();
+ final Object userName = this.nextEntry.getUserName();
if (userName != null) removeEntry((String) userName);
- } catch (kelondroException e) {
+ } catch (final kelondroException e) {
resetDatabase();
}
}
diff --git a/source/de/anomic/data/wiki/abstractWikiParser.java b/source/de/anomic/data/wiki/abstractWikiParser.java
index 5059f56d3..5db2dc4c6 100644
--- a/source/de/anomic/data/wiki/abstractWikiParser.java
+++ b/source/de/anomic/data/wiki/abstractWikiParser.java
@@ -11,72 +11,72 @@ import de.anomic.plasma.plasmaSwitchboard;
public abstract class abstractWikiParser implements wikiParser {
- private plasmaSwitchboard sb;
+ private final plasmaSwitchboard sb;
- public abstractWikiParser(plasmaSwitchboard sb) {
+ public abstractWikiParser(final plasmaSwitchboard sb) {
this.sb = sb;
}
protected abstract String transform(BufferedReader reader, int length, String publicAddress, plasmaSwitchboard sb) throws IOException;
- public String transform(String content) {
+ public String transform(final String content) {
return transform(content, this.sb);
}
- public String transform(String content, plasmaSwitchboard sb) {
+ public String transform(final String content, final plasmaSwitchboard sb) {
try {
return transform(
new BufferedReader(new StringReader(content)),
content.length(),
sb.webIndex.seedDB.mySeed().getPublicAddress(),
sb);
- } catch (IOException e) {
+ } catch (final IOException e) {
return "internal error: " + e.getMessage();
}
}
- public String transform(String content, String publicAddress) {
+ public String transform(final String content, final String publicAddress) {
try {
return transform(
new BufferedReader(new StringReader(content)),
content.length(),
publicAddress,
null);
- } catch (IOException e) {
+ } catch (final IOException e) {
return "internal error: " + e.getMessage();
}
}
- public String transform(byte[] content) throws UnsupportedEncodingException {
+ public String transform(final byte[] content) throws UnsupportedEncodingException {
return transform(content, "UTF-8", this.sb);
}
- public String transform(byte[] content, String encoding) throws UnsupportedEncodingException {
+ public String transform(final byte[] content, final String encoding) throws UnsupportedEncodingException {
return transform(content, encoding, this.sb);
}
- public String transform(byte[] content, String encoding, String publicAddress) throws UnsupportedEncodingException {
- ByteArrayInputStream bais = new ByteArrayInputStream(content);
+ public String transform(final byte[] content, final String encoding, final String publicAddress) throws UnsupportedEncodingException {
+ final ByteArrayInputStream bais = new ByteArrayInputStream(content);
try {
return transform(
new BufferedReader(new InputStreamReader(bais, encoding)),
content.length,
publicAddress,
null);
- } catch (IOException e) {
+ } catch (final IOException e) {
return "internal error: " + e.getMessage();
}
}
- public String transform(byte[] content, String encoding, plasmaSwitchboard switchboard) throws UnsupportedEncodingException {
- ByteArrayInputStream bais = new ByteArrayInputStream(content);
+ public String transform(final byte[] content, final String encoding, final plasmaSwitchboard switchboard) throws UnsupportedEncodingException {
+ final ByteArrayInputStream bais = new ByteArrayInputStream(content);
try {
return transform(
new BufferedReader(new InputStreamReader(bais, encoding)),
content.length,
sb.webIndex.seedDB.mySeed().getPublicAddress(),
switchboard);
- } catch (IOException e) {
+ } catch (final IOException e) {
return "internal error: " + e.getMessage();
}
}
diff --git a/source/de/anomic/data/wiki/knwikiParser.java b/source/de/anomic/data/wiki/knwikiParser.java
index 5d6740283..16affe353 100644
--- a/source/de/anomic/data/wiki/knwikiParser.java
+++ b/source/de/anomic/data/wiki/knwikiParser.java
@@ -46,12 +46,12 @@ public class knwikiParser implements wikiParser {
private String[] BEs;
private final plasmaSwitchboard sb;
- public knwikiParser(plasmaSwitchboard sb) {
+ public knwikiParser(final plasmaSwitchboard sb) {
this.sb = sb;
}
- public static void main(String[] args) {
- String text = "===T<pre>itle===\n" +
+ public static void main(final String[] args) {
+ final String text = "===T<pre>itle===\n" +
"==blubb== was ==ein '''shice'''==...och.bla\n" +
"* ein \n" +
"*==test=</pre>=\n" +
@@ -85,44 +85,44 @@ public class knwikiParser implements wikiParser {
// text = "[=\n=]* bla";
String t = "[=] ein fucking [= test =]-text[=,ne?!=] joa, [=alles=]wunderbar," +
"[=denk ich=] mal =]";
- long l = System.currentTimeMillis();
+ final long l = System.currentTimeMillis();
t = new knwikiParser(null).parse((args.length > 0) ? args[0] : text, "localhost:8080");
System.out.println("parsing time: " + (System.currentTimeMillis() - l) + " ms");
System.out.println("--- --- ---");
System.out.println(t);
}
- public String transform(String content) {
+ public String transform(final String content) {
return parse(content, null);
}
- public String transform(String content, plasmaSwitchboard sb) {
+ public String transform(final String content, final plasmaSwitchboard sb) {
return parse(content, null);
}
- public String transform(byte[] content) throws UnsupportedEncodingException {
+ public String transform(final byte[] content) throws UnsupportedEncodingException {
return parse(new String(content, "UTF-8"), null);
}
public String transform(
- byte[] content, String encoding,
- plasmaSwitchboard switchboard) throws UnsupportedEncodingException {
+ final byte[] content, final String encoding,
+ final plasmaSwitchboard switchboard) throws UnsupportedEncodingException {
return parse(new String(content, encoding), null);
}
- public String transform(byte[] content, String encoding) throws UnsupportedEncodingException {
+ public String transform(final byte[] content, final String encoding) throws UnsupportedEncodingException {
return parse(new String(content, encoding), null);
}
- public String transform(byte[] text, String encoding, String publicAddress) throws UnsupportedEncodingException {
+ public String transform(final byte[] text, final String encoding, final String publicAddress) throws UnsupportedEncodingException {
return parse(new String(text, encoding), publicAddress);
}
- public String transform(String text, String publicAddress) {
+ public String transform(final String text, final String publicAddress) {
return parse(text, publicAddress);
}
- public String parse(String text, String publicAddress) {
+ public String parse(String text, final String publicAddress) {
tokens = new Token[] {
new SimpleToken('=', '=', new String[][] { null, { "h2" }, { "h3" }, { "h4" } }, true),
new SimpleToken('\'', '\'', new String[][] { null, { "i" }, { "b" }, null, { "b", "i" } }, false),
@@ -134,7 +134,7 @@ public class knwikiParser implements wikiParser {
new DefinitionListToken(),
new TableToken()
};
- ArrayList<String> r = new ArrayList<String>();
+ final ArrayList<String> r = new ArrayList<String>();
for (int i = 0, k, j; i < tokens.length; i++)
if (tokens[i].getBlockElementNames() != null)
for (j = 0; j < tokens[i].getBlockElementNames().length; j++) {
@@ -178,7 +178,7 @@ public class knwikiParser implements wikiParser {
// System.out.println("usable");
}
m.appendReplacement(sb, (st.getMarkup() == null) ? m.group() : st.getMarkup());
- } catch (wikiParserException e) {
+ } catch (final wikiParserException e) {
m.appendReplacement(sb, st.getText());
}
text = new String(m.appendTail(sb));
@@ -187,9 +187,9 @@ public class knwikiParser implements wikiParser {
return text.replaceAll("----", "<hr />");
}
- private String replaceBRs(String text) {
- StringBuffer sb = new StringBuffer(text.length());
- String[] tt = text.split("\n");
+ private String replaceBRs(final String text) {
+ final StringBuffer sb = new StringBuffer(text.length());
+ final String[] tt = text.split("\n");
boolean replace;
for (int i=0, j; i<tt.length; i++) {
replace = true;
@@ -212,14 +212,14 @@ public class knwikiParser implements wikiParser {
private final boolean escaped;
private final boolean nl;
- public Text(String text, boolean escaped, boolean newLineBefore) {
+ public Text(final String text, final boolean escaped, final boolean newLineBefore) {
this.text = text;
this.escaped = escaped;
this.nl = newLineBefore;
}
- public String setTextPlain(String text) { return this.text = text; }
- public String setText(String text) {
+ public String setTextPlain(final String text) { return this.text = text; }
+ public String setText(final String text) {
if (this.nl)
this.text = text.substring(escapeNewLine.length());
else
@@ -239,13 +239,13 @@ public class knwikiParser implements wikiParser {
public boolean isEscaped() { return this.escaped; }
public boolean isNewLineBefore() { return this.nl; }
- static Text[] split2Texts(String text, String escapeBegin, String escapeEnd) {
+ static Text[] split2Texts(final String text, final String escapeBegin, final String escapeEnd) {
if (text == null) return null;
if (text.length() < 2) return new Text[] { new Text(text, false, true) };
- int startLen = escapeBegin.length();
- int endLen = escapeEnd.length();
- ArrayList<Text> r = new ArrayList<Text>();
+ final int startLen = escapeBegin.length();
+ final int endLen = escapeEnd.length();
+ final ArrayList<Text> r = new ArrayList<Text>();
boolean escaped = text.startsWith(escapeBegin);
if (escaped) r.add(new Text("", false, true));
int i, j = 0;
@@ -258,7 +258,7 @@ public class knwikiParser implements wikiParser {
return r.toArray(new Text[r.size()]);
}
- private static Text resolve2Text(String text, boolean escaped, int from, int to, String escapeEnd) {
+ private static Text resolve2Text(final String text, final boolean escaped, final int from, int to, final String escapeEnd) {
if (to == -1) to = text.length();
return new Text(
text.substring(from, to),
@@ -266,8 +266,8 @@ public class knwikiParser implements wikiParser {
from < escapeEnd.length() + 2 || (!escaped && text.charAt(from - escapeEnd.length() - 1) == '\n'));
}
- static String mergeTexts(Text[] texts) {
- StringBuffer sb = new StringBuffer();
+ static String mergeTexts(final Text[] texts) {
+ final StringBuffer sb = new StringBuffer();
for (int n=0; n < texts.length; n++)
sb.append(texts[n].getTextPlain());
return new String(sb);
diff --git a/source/de/anomic/data/wiki/tokens/AbstractToken.java b/source/de/anomic/data/wiki/tokens/AbstractToken.java
index 9051f726d..e7b4b9013 100644
--- a/source/de/anomic/data/wiki/tokens/AbstractToken.java
+++ b/source/de/anomic/data/wiki/tokens/AbstractToken.java
@@ -47,5 +47,5 @@ public abstract class AbstractToken implements Token {
public String getText() { return this.text; }
- public String toString() { try { return getMarkup(); } catch (wikiParserException e) { return null; } }
+ public String toString() { try { return getMarkup(); } catch (final wikiParserException e) { return null; } }
}
diff --git a/source/de/anomic/data/wiki/tokens/DefinitionListToken.java b/source/de/anomic/data/wiki/tokens/DefinitionListToken.java
index f880891fa..b5eebee1d 100644
--- a/source/de/anomic/data/wiki/tokens/DefinitionListToken.java
+++ b/source/de/anomic/data/wiki/tokens/DefinitionListToken.java
@@ -36,7 +36,7 @@ public class DefinitionListToken extends ListToken {
super(';', null, null);
}
- protected StringBuffer parse(String[] t, int depth, StringBuffer sb) {
+ protected StringBuffer parse(final String[] t, final int depth, final StringBuffer sb) {
sb.append("<dl>\n");
while (super.aktline < t.length && getGrade(t[super.aktline]) >= depth) {
for (int j=0; j<depth + 1; j++) sb.append("\t");
diff --git a/source/de/anomic/data/wiki/tokens/LinkToken.java b/source/de/anomic/data/wiki/tokens/LinkToken.java
index 4479d5fc4..8e77919a8 100644
--- a/source/de/anomic/data/wiki/tokens/LinkToken.java
+++ b/source/de/anomic/data/wiki/tokens/LinkToken.java
@@ -81,17 +81,17 @@ public class LinkToken extends AbstractToken {
private final plasmaSwitchboard sb;
private int patternNr = 0;
- public LinkToken(String localhost, String wikiPath, plasmaSwitchboard sb) {
+ public LinkToken(final String localhost, final String wikiPath, final plasmaSwitchboard sb) {
this.localhost = localhost;
this.wikiPath = wikiPath;
this.sb = sb;
}
protected void parse() throws wikiParserException {
- StringBuffer sb = new StringBuffer();
+ final StringBuffer sb = new StringBuffer();
if (this.patternNr < 0 || this.patternNr >= patterns.length)
throw new wikiParserException("patternNr was not set correctly: " + this.patternNr);
- Matcher m = patterns[this.patternNr].matcher(this.text);
+ final Matcher m = patterns[this.patternNr].matcher(this.text);
if (!m.find())
throw new wikiParserException("Didn't find match for: (" + this.patternNr + ") " + this.text);
@@ -104,7 +104,7 @@ public class LinkToken extends AbstractToken {
break;
case BKM:
- Link[] links = getLinksFromBookmarkTag(m.group(2));
+ final Link[] links = getLinksFromBookmarkTag(m.group(2));
if (links == null) {
sb.append("<span class=\"error\">Couldn't find Bookmark-Tag '").append(m.group(2)).append("'.</span>");
} else {
@@ -132,7 +132,7 @@ public class LinkToken extends AbstractToken {
this.markup = new String(sb);
}
- private String formatHref(String link) {
+ private String formatHref(final String link) {
if (link.indexOf("://") == -1) { // DATA/HTDOCS-link
return "http://" + this.localhost + "/share/" + link;
} else { // 'normal' link
@@ -140,17 +140,17 @@ public class LinkToken extends AbstractToken {
}
}
- private StringBuffer appendLinks(Link[] links, StringBuffer sb) {
+ private StringBuffer appendLinks(final Link[] links, final StringBuffer sb) {
for (int i=0; i<links.length; i++)
sb.append(links[i].toString());
return sb;
}
- private Link[] getLinksFromBookmarkTag(String tagName) {
- Tag tag = this.sb.bookmarksDB.getTag(bookmarksDB.tagHash(tagName));
+ private Link[] getLinksFromBookmarkTag(final String tagName) {
+ final Tag tag = this.sb.bookmarksDB.getTag(bookmarksDB.tagHash(tagName));
if (tag == null) return null;
- ArrayList<Link> r = new ArrayList<Link>();
- Iterator<String> it = tag.getUrlHashes().iterator();
+ final ArrayList<Link> r = new ArrayList<Link>();
+ final Iterator<String> it = tag.getUrlHashes().iterator();
String hash;
Bookmark bm;
while (it.hasNext())
@@ -166,14 +166,14 @@ public class LinkToken extends AbstractToken {
private final String title;
private final String desc;
- public Link(String href, String title, String desc) {
+ public Link(final String href, final String title, final String desc) {
this.href = href;
this.title = title;
this.desc = desc;
}
public String toString() {
- StringBuffer sb = new StringBuffer();
+ final StringBuffer sb = new StringBuffer();
sb.append("<a href=\"").append(this.href).append("\"");
if (this.title != null) sb.append(" title=\"").append(this.title).append("\"");
sb.append(">");
@@ -186,7 +186,7 @@ public class LinkToken extends AbstractToken {
public String[] getBlockElementNames() { return null; }
public Pattern[] getRegex() { return patterns; }
- public boolean setText(String text, int patternNr) {
+ public boolean setText(final String text, final int patternNr) {
this.text = text;
this.patternNr = patternNr;
this.parsed = false;
diff --git a/source/de/anomic/data/wiki/tokens/ListToken.java b/source/de/anomic/data/wiki/tokens/ListToken.java
index ea87a0ca1..9bd2f6afe 100644
--- a/source/de/anomic/data/wiki/tokens/ListToken.java
+++ b/source/de/anomic/data/wiki/tokens/ListToken.java
@@ -43,13 +43,13 @@ public class ListToken extends AbstractToken {
protected int aktline = 0;
- public ListToken(char firstChar, String listBlockElement) {
+ public ListToken(final char firstChar, final String listBlockElement) {
this.firstChar = firstChar;
this.listBlockElement = listBlockElement;
this.listElement = "li";
this.recursion = true;
this.pattern = new Pattern[] { Pattern.compile("^[" + firstChar + "]([^\n]|\n[" + firstChar + "])*", Pattern.MULTILINE) };
- ArrayList<String> r = new ArrayList<String>();
+ final ArrayList<String> r = new ArrayList<String>();
if (this.listBlockElement != null) {
if (this.recursion) r.add(this.listBlockElement);
if (this.listElement != null) r.add(this.listElement);
@@ -57,13 +57,13 @@ public class ListToken extends AbstractToken {
blockElements = r.toArray(new String[r.size()]);
}
- public ListToken(char firstChar, String listBlockElement, String listElement) {
+ public ListToken(final char firstChar, final String listBlockElement, final String listElement) {
this.firstChar = firstChar;
this.listBlockElement = listBlockElement;
this.listElement = listElement;
this.recursion = true;
this.pattern = new Pattern[] { Pattern.compile("^[" + firstChar + "]([^\n]|\n[" + firstChar + "])*", Pattern.MULTILINE) };
- ArrayList<String> r = new ArrayList<String>();
+ final ArrayList<String> r = new ArrayList<String>();
if (this.listBlockElement != null) {
if (this.recursion) r.add(this.listBlockElement);
if (this.listElement != null) r.add(this.listElement);
@@ -71,13 +71,13 @@ public class ListToken extends AbstractToken {
blockElements = r.toArray(new String[r.size()]);
}
- public ListToken(char firstChar, String listBlockElement, String listElement, boolean recursion) {
+ public ListToken(final char firstChar, final String listBlockElement, final String listElement, final boolean recursion) {
this.firstChar = firstChar;
this.listBlockElement = listBlockElement;
this.listElement = listElement;
this.recursion = recursion;
this.pattern = new Pattern[] { Pattern.compile("^[" + firstChar + "]([^\n]|\n[" + firstChar + "])*", Pattern.MULTILINE) };
- ArrayList<String> r = new ArrayList<String>();
+ final ArrayList<String> r = new ArrayList<String>();
if (this.listBlockElement != null) {
if (this.recursion) r.add(this.listBlockElement);
if (this.listElement != null) r.add(this.listElement);
@@ -86,13 +86,13 @@ public class ListToken extends AbstractToken {
}
protected void parse() {
- StringBuffer sb = new StringBuffer(this.text.length());
+ final StringBuffer sb = new StringBuffer(this.text.length());
parse(this.text.split("\n"), 0, sb);
this.markup = new String(sb);
this.parsed = true;
}
- protected StringBuffer parse(String[] t, int depth, StringBuffer sb) {
+ protected StringBuffer parse(final String[] t, final int depth, final StringBuffer sb) {
if (this.listBlockElement != null) sb.append("<").append(this.listBlockElement).append(">\n");
while (this.aktline < t.length && getGrade(t[this.aktline]) >= depth) {
if (recursion) for (int j=0; j<depth + 1; j++) sb.append("\t");
@@ -114,7 +114,7 @@ public class ListToken extends AbstractToken {
return sb;
}
- protected int getGrade(String t) {
+ protected int getGrade(final String t) {
int i = 0;
for (i=0; i<t.length(); i++)
if (t.charAt(i) != this.firstChar) break;
@@ -133,7 +133,7 @@ public class ListToken extends AbstractToken {
return this.firstChar;
}
- public boolean setText(String text, int patternNr) {
+ public boolean setText(final String text, final int patternNr) {
this.text = text;
this.markup = null;
this.parsed = false;
diff --git a/source/de/anomic/data/wiki/tokens/SimpleToken.java b/source/de/anomic/data/wiki/tokens/SimpleToken.java
index 2dc8f631c..0b3b8ccce 100644
--- a/source/de/anomic/data/wiki/tokens/SimpleToken.java
+++ b/source/de/anomic/data/wiki/tokens/SimpleToken.java
@@ -43,11 +43,11 @@ public class SimpleToken extends AbstractToken {
private final String[][] definitionList;
private final String[] blockElements;
- public SimpleToken(char firstChar, char lastChar, String[][] definitionList, boolean isBlockElements) {
+ public SimpleToken(final char firstChar, final char lastChar, final String[][] definitionList, final boolean isBlockElements) {
this.definitionList = definitionList;
int i;
if (isBlockElements) {
- ArrayList<String> r = new ArrayList<String>();
+ final ArrayList<String> r = new ArrayList<String>();
int j;
for (i = 0; i < definitionList.length; i++)
if (definitionList[i] != null)
@@ -89,12 +89,12 @@ public class SimpleToken extends AbstractToken {
this.parsed = true;
}
- protected String getMarkup(String[] es) {
+ protected String getMarkup(final String[] es) {
return getMarkup(es, false) + this.content + getMarkup(es, true);
}
- protected String getMarkup(String[] es, boolean closing) {
- StringBuffer result = new StringBuffer();
+ protected String getMarkup(final String[] es, final boolean closing) {
+ final StringBuffer result = new StringBuffer();
// backwards if closing
for (
int i = (closing) ? es.length - 1 : 0, j;
@@ -117,12 +117,12 @@ public class SimpleToken extends AbstractToken {
return new String(result);
}
- public boolean setText(String text, int patternNr) {
+ public boolean setText(final String text, final int patternNr) {
this.text = text;
this.markup = null;
this.parsed = false;
if (text != null) {
- Matcher m = getRegex()[0].matcher(text);
+ final Matcher m = getRegex()[0].matcher(text);
if (
(m.matches()) &&
(m.group(1).length() == m.group(3).length()) &&
diff --git a/source/de/anomic/data/wiki/tokens/TableToken.java b/source/de/anomic/data/wiki/tokens/TableToken.java
index b47d857ae..460f5ca23 100644
--- a/source/de/anomic/data/wiki/tokens/TableToken.java
+++ b/source/de/anomic/data/wiki/tokens/TableToken.java
@@ -43,9 +43,9 @@ public class TableToken extends AbstractToken {
private static final String[] blockElementNames = new String[] { "table", "tr", "td" };
protected void parse() {
- String[] t = text.split("\n");
+ final String[] t = text.split("\n");
String[] tds;
- StringBuffer sb = new StringBuffer();
+ final StringBuffer sb = new StringBuffer();
sb.append("<table");
if (t[0].length() > 2) sb.append(parseTableProperties(t[0].substring(2)));
sb.append(">\n");
@@ -96,11 +96,11 @@ public class TableToken extends AbstractToken {
* @return A string that only contains table properties.
*/
private static StringBuffer parseTableProperties(final String properties) {
- String[] values = properties.replaceAll("&quot;", "").split("[= ]"); //splitting the string at = and blanks
- StringBuffer sb = new StringBuffer(properties.length());
+ final String[] values = properties.replaceAll("&quot;", "").split("[= ]"); //splitting the string at = and blanks
+ final StringBuffer sb = new StringBuffer(properties.length());
String key, value;
String[] posVals;
- int numberofvalues = values.length;
+ final int numberofvalues = values.length;
for (int i=0; i<numberofvalues; i++) {
key = values[i].trim();
if (key.equals("nowrap")) {
@@ -121,14 +121,14 @@ public class TableToken extends AbstractToken {
return sb;
}
- private static StringBuffer addPair(String key, String value, StringBuffer sb) {
+ private static StringBuffer addPair(final String key, final String value, final StringBuffer sb) {
return sb.append(" ").append(key).append("=\"").append(value).append("\"");
}
public Pattern[] getRegex() { return pattern; }
public String[] getBlockElementNames() { return blockElementNames; }
- public boolean setText(String text, int patternNr) {
+ public boolean setText(final String text, final int patternNr) {
this.text = text;
this.parsed = false;
this.markup = null;
diff --git a/source/de/anomic/data/wiki/wikiParserException.java b/source/de/anomic/data/wiki/wikiParserException.java
index a6c9c560c..7a7a7822b 100644
--- a/source/de/anomic/data/wiki/wikiParserException.java
+++ b/source/de/anomic/data/wiki/wikiParserException.java
@@ -6,15 +6,15 @@ public class wikiParserException extends Exception {
public wikiParserException() { }
- public wikiParserException(String message) {
+ public wikiParserException(final String message) {
super(message);
}
- public wikiParserException(Throwable cause) {
+ public wikiParserException(final Throwable cause) {
super(cause);
}
- public wikiParserException(String message, Throwable cause) {
+ public wikiParserException(final String message, final Throwable cause) {
super(message, cause);
}
}
diff --git a/source/de/anomic/data/wikiBoard.java b/source/de/anomic/data/wikiBoard.java
index 8cb7c5313..4ce477180 100644
--- a/source/de/anomic/data/wikiBoard.java
+++ b/source/de/anomic/data/wikiBoard.java
@@ -51,7 +51,7 @@ public class wikiBoard {
kelondroMap bkpbase = null;
static HashMap<String, String> authors = new HashMap<String, String>();
- public wikiBoard(File actpath, File bkppath) {
+ public wikiBoard(final File actpath, final File bkppath) {
new File(actpath.getParent()).mkdirs();
if (datbase == null) {
datbase = new kelondroMap(new kelondroBLOBTree(actpath, true, true, keyLength, recordSize, '_', kelondroNaturalOrder.naturalOrder, true, false, false), 500);
@@ -79,13 +79,13 @@ public class wikiBoard {
return dateString(new Date());
}
- public static String dateString(Date date) {
+ public static String dateString(final Date date) {
synchronized (SimpleFormatter) {
return SimpleFormatter.format(date);
}
}
- private static String normalize(String key) {
+ private static String normalize(final String key) {
if (key == null) return "null";
return key.trim().toLowerCase();
}
@@ -99,17 +99,17 @@ public class wikiBoard {
return key;
}
- public static String guessAuthor(String ip) {
- String author = authors.get(ip);
+ public static String guessAuthor(final String ip) {
+ final String author = authors.get(ip);
//yacyCore.log.logDebug("DEBUG: guessing author for ip = " + ip + " is '" + author + "', authors = " + authors.toString());
return author;
}
- public static void setAuthor(String ip, String author) {
+ public static void setAuthor(final String ip, final String author) {
authors.put(ip,author);
}
- public entry newEntry(String subject, String author, String ip, String reason, byte[] page) throws IOException {
+ public entry newEntry(final String subject, final String author, final String ip, final String reason, final byte[] page) throws IOException {
return new entry(normalize(subject), author, ip, reason, page);
}
@@ -118,7 +118,7 @@ public class wikiBoard {
String key;
HashMap<String, String> record;
- public entry(String subject, String author, String ip, String reason, byte[] page) throws IOException {
+ public entry(final String subject, String author, String ip, String reason, final byte[] page) throws IOException {
record = new HashMap<String, String>();
key = subject;
if (key.length() > keyLength) key = key.substring(0, keyLength);
@@ -137,7 +137,7 @@ public class wikiBoard {
//System.out.println("DEBUG: setting author " + author + " for ip = " + ip + ", authors = " + authors.toString());
}
- entry(String key, HashMap<String, String> record) {
+ entry(final String key, final HashMap<String, String> record) {
this.key = key;
this.record = record;
}
@@ -148,7 +148,7 @@ public class wikiBoard {
public Date date() {
try {
- String c = record.get("date");
+ final String c = record.get("date");
if (c == null) {
System.out.println("DEBUG - ERROR: date field missing in wikiBoard");
return new Date();
@@ -156,47 +156,47 @@ public class wikiBoard {
synchronized (SimpleFormatter) {
return SimpleFormatter.parse(c);
}
- } catch (ParseException e) {
+ } catch (final ParseException e) {
return new Date();
}
}
public String author() {
- String a = record.get("author");
+ final String a = record.get("author");
if (a == null) return "anonymous";
- byte[] b = kelondroBase64Order.enhancedCoder.decode(a, "de.anomic.data.wikiBoard.author()");
+ final byte[] b = kelondroBase64Order.enhancedCoder.decode(a, "de.anomic.data.wikiBoard.author()");
if (b == null) return "anonymous";
return new String(b);
}
public String reason() {
- String r = record.get("reason");
+ final String r = record.get("reason");
if (r == null) return "";
- byte[] b = kelondroBase64Order.enhancedCoder.decode(r, "de.anomic.data.wikiBoard.reason()");
+ final byte[] b = kelondroBase64Order.enhancedCoder.decode(r, "de.anomic.data.wikiBoard.reason()");
if (b == null) return "unknown";
return new String(b);
}
public byte[] page() {
- String m = record.get("page");
+ final String m = record.get("page");
if (m == null) return new byte[0];
- byte[] b = kelondroBase64Order.enhancedCoder.decode(m, "de.anomic.data.wikiBoard.page()");
+ final byte[] b = kelondroBase64Order.enhancedCoder.decode(m, "de.anomic.data.wikiBoard.page()");
if (b == null) return "".getBytes();
return b;
}
- void setAncestorDate(Date date) {
+ void setAncestorDate(final Date date) {
record.put("bkp", dateString(date));
}
private Date getAncestorDate() {
try {
- String c = record.get("date");
+ final String c = record.get("date");
if (c == null) return null;
synchronized (SimpleFormatter) {
return SimpleFormatter.parse(c);
}
- } catch (ParseException e) {
+ } catch (final ParseException e) {
return null;
}
}
@@ -214,44 +214,44 @@ public class wikiBoard {
*/
public entry getAncestor() {
- Date ancDate = getAncestorDate();
+ final Date ancDate = getAncestorDate();
if (ancDate == null) return null;
return read(key + dateString(ancDate), bkpbase);
}
- void setChild(String subject) {
+ void setChild(final String subject) {
record.put("child", kelondroBase64Order.enhancedCoder.encode(subject.getBytes()));
}
private String getChildName() {
- String c = record.get("child");
+ final String c = record.get("child");
if (c == null) return null;
- byte[] subject = kelondroBase64Order.enhancedCoder.decode(c, "de.anomic.data.wikiBoard.getChildName()");
+ final byte[] subject = kelondroBase64Order.enhancedCoder.decode(c, "de.anomic.data.wikiBoard.getChildName()");
if (subject == null) return null;
return new String(subject);
}
public boolean hasChild() {
- String c = record.get("child");
+ final String c = record.get("child");
if (c == null) return false;
- byte[] subject = kelondroBase64Order.enhancedCoder.decode(c, "de.anomic.data.wikiBoard.hasChild()");
+ final byte[] subject = kelondroBase64Order.enhancedCoder.decode(c, "de.anomic.data.wikiBoard.hasChild()");
return (subject != null);
}
public entry getChild() {
- String childName = getChildName();
+ final String childName = getChildName();
if (childName == null) return null;
return read(childName, datbase);
}
}
- public String write(entry page) {
+ public String write(final entry page) {
// writes a new page and returns key
try {
// first load the old page
- entry oldEntry = read(page.key);
+ final entry oldEntry = read(page.key);
// set the bkp date of the new page to the date of the old page
- Date oldDate = oldEntry.date();
+ final Date oldDate = oldEntry.date();
page.setAncestorDate(oldDate);
oldEntry.setChild(page.subject());
// write the backup
@@ -262,28 +262,28 @@ public class wikiBoard {
// write the new page
datbase.put(page.key, page.record);
return page.key;
- } catch (IOException e) {
+ } catch (final IOException e) {
return null;
}
}
- public entry read(String key) {
+ public entry read(final String key) {
return read(key, datbase);
}
- entry read(String key, kelondroMap base) {
+ entry read(String key, final kelondroMap base) {
try {
key = normalize(key);
if (key.length() > keyLength) key = key.substring(0, keyLength);
- HashMap<String, String> record = base.get(key);
+ final HashMap<String, String> record = base.get(key);
if (record == null) return newEntry(key, "anonymous", "127.0.0.1", "New Page", "".getBytes());
return new entry(key, record);
- } catch (IOException e) {
+ } catch (final IOException e) {
return null;
}
}
- public entry readBkp(String key) {
+ public entry readBkp(final String key) {
return read(key, bkpbase);
}
@@ -297,11 +297,11 @@ public class wikiBoard {
}
*/
- public Iterator<byte[]> keys(boolean up) throws IOException {
+ public Iterator<byte[]> keys(final boolean up) throws IOException {
return datbase.keys(up, false);
}
- public Iterator<byte[]> keysBkp(boolean up) throws IOException {
+ public Iterator<byte[]> keysBkp(final boolean up) throws IOException {
return bkpbase.keys(up, false);
}
}
diff --git a/source/de/anomic/data/wikiCode.java b/source/de/anomic/data/wikiCode.java
index 0842dd6ca..d8f82a384 100644
--- a/source/de/anomic/data/wikiCode.java
+++ b/source/de/anomic/data/wikiCode.java
@@ -76,19 +76,19 @@ public class wikiCode extends abstractWikiParser implements wikiParser {
private int preindented = 0; //needed for indented <pre>s
private int escindented = 0; //needed for indented [=s
private int headlines = 0; //number of headlines in page
- private ArrayList<String> dirElements = new ArrayList<String>(); //list of headlines used to create diectory of page
+ private final ArrayList<String> dirElements = new ArrayList<String>(); //list of headlines used to create diectory of page
/** Constructor of the class wikiCode */
- public wikiCode(plasmaSwitchboard switchboard){
+ public wikiCode(final plasmaSwitchboard switchboard){
super(switchboard);
}
protected String transform(
- BufferedReader reader,
- int length,
- String publicAddress,
- plasmaSwitchboard switchboard) throws IOException {
- StringBuffer out = new StringBuffer(length);
+ final BufferedReader reader,
+ final int length,
+ final String publicAddress,
+ final plasmaSwitchboard switchboard) throws IOException {
+ final StringBuffer out = new StringBuffer(length);
String line;
while ((line = reader.readLine()) != null)
out.append(transformLine(line, publicAddress, switchboard)).append(serverCore.CRLF_STRING);
@@ -100,18 +100,18 @@ public class wikiCode extends abstractWikiParser implements wikiParser {
* @return a string with wiki code of parts of table replaced by HTML code for table
*/
//[FB], changes by [MN]
- private String processTable(String result, plasmaSwitchboard switchboard){
+ private String processTable(String result, final plasmaSwitchboard switchboard){
//some variables that make it easier to change codes for the table
String line = "";
- String tableStart = "&#123;&#124;"; // {|
- String newLine = "&#124;-"; // |-
- String cellDivider = "&#124;&#124;"; // ||
- String tableEnd = "&#124;&#125;"; // |}
- String attribDivider = "&#124;"; // |
- int lenTableStart = tableStart.length();
- int lenCellDivider = cellDivider.length();
- int lenTableEnd = tableEnd.length();
- int lenAttribDivider = attribDivider.length();
+ final String tableStart = "&#123;&#124;"; // {|
+ final String newLine = "&#124;-"; // |-
+ final String cellDivider = "&#124;&#124;"; // ||
+ final String tableEnd = "&#124;&#125;"; // |}
+ final String attribDivider = "&#124;"; // |
+ final int lenTableStart = tableStart.length();
+ final int lenCellDivider = cellDivider.length();
+ final int lenTableEnd = tableEnd.length();
+ final int lenAttribDivider = attribDivider.length();
if ((result.startsWith(tableStart)) && (!table)) {
table=true;
@@ -134,10 +134,10 @@ public class wikiCode extends abstractWikiParser implements wikiParser {
}
else if ((result.startsWith(cellDivider)) && (table)) {
line+="\t\t<td";
- int cellEnd=(result.indexOf(cellDivider,lenCellDivider)>0)?(result.indexOf(cellDivider,lenCellDivider)):(result.length());
+ final int cellEnd=(result.indexOf(cellDivider,lenCellDivider)>0)?(result.indexOf(cellDivider,lenCellDivider)):(result.length());
int propEnd = result.indexOf(attribDivider,lenCellDivider);
- int occImage = result.indexOf("[[Image:",lenCellDivider);
- int occEscape = result.indexOf("[=",lenCellDivider);
+ final int occImage = result.indexOf("[[Image:",lenCellDivider);
+ final int occEscape = result.indexOf("[=",lenCellDivider);
//If resultOf("[[Image:") is less than propEnd, that means that there is no
//property for this cell, only an image. Without this, YaCy could get confused
//by a | in [[Image:picture.png|alt-text]] or [[Image:picture.png|alt-text]]
@@ -212,7 +212,7 @@ public class wikiCode extends abstractWikiParser implements wikiParser {
return sb;
}
- private static StringBuffer addPair(String key, String value, StringBuffer sb) {
+ private static StringBuffer addPair(final String key, final String value, final StringBuffer sb) {
return sb.append(" ").append(key).append("=\"").append(value).append("\"");
}
@@ -324,7 +324,7 @@ public class wikiCode extends abstractWikiParser implements wikiParser {
String dd = "";
p0 = result.indexOf(defListLevel);
p1 = result.length();
- String resultCopy = result.substring(defListLevel.length() + 1, p1);
+ final String resultCopy = result.substring(defListLevel.length() + 1, p1);
if((p0 = resultCopy.indexOf(":")) > 0){
dt = resultCopy.substring(0,p0);
dd = resultCopy.substring(p0+1);
@@ -337,7 +337,7 @@ public class wikiCode extends abstractWikiParser implements wikiParser {
String dd = "";
p0 = result.indexOf(defListLevel);
p1 = result.length();
- String resultCopy = result.substring(defListLevel.length(), p1);
+ final String resultCopy = result.substring(defListLevel.length(), p1);
if((p0 = resultCopy.indexOf(":")) > 0){
dt = resultCopy.substring(0,p0);
dd = resultCopy.substring(p0+1);
@@ -357,7 +357,7 @@ public class wikiCode extends abstractWikiParser implements wikiParser {
p0 = defListLevel.length();
p1 = result.length();
if(defListLevel.length() > 0){
- String resultCopy = result.substring(p0, p1);
+ final String resultCopy = result.substring(p0, p1);
if((p0 = resultCopy.indexOf(":")) > 0){
dt = resultCopy.substring(0,p0);
dd = resultCopy.substring(p0+1);
@@ -375,7 +375,7 @@ public class wikiCode extends abstractWikiParser implements wikiParser {
/** This method processes links and images.
*/
//contributed by [AS] except where stated otherwise
- private String linksAndImages(String result, String publicAddress, plasmaSwitchboard switchboard) {
+ private String linksAndImages(String result, final String publicAddress, final plasmaSwitchboard switchboard) {
// create links
String kl, kv, alt, align;
@@ -479,7 +479,7 @@ public class wikiCode extends abstractWikiParser implements wikiParser {
/** This method handles the escape tags [= =] */
//contributed by [MN]
- private String escapeTag(String result, String publicAddress, plasmaSwitchboard switchboard){
+ private String escapeTag(String result, final String publicAddress, final plasmaSwitchboard switchboard){
int p0 = 0;
int p1 = 0;
//both [= and =] in the same line
@@ -494,9 +494,9 @@ public class wikiCode extends abstractWikiParser implements wikiParser {
//handles cases like [=[= =]=] [= =] that would cause an exception otherwise
else{
escape = true;
- String temp1 = transformLine(result.substring(0,p0-1).replaceAll("!tmp!","!tmp!!")+"!tmp!txt!", publicAddress, switchboard);
+ final String temp1 = transformLine(result.substring(0,p0-1).replaceAll("!tmp!","!tmp!!")+"!tmp!txt!", publicAddress, switchboard);
nolist = true;
- String temp2 = transformLine(result.substring(p0), publicAddress, switchboard);
+ final String temp2 = transformLine(result.substring(p0), publicAddress, switchboard);
nolist = false;
result = temp1.replaceAll("!tmp!txt!",temp2);
result = result.replaceAll("!tmp!!", "!tmp!");
@@ -551,7 +551,7 @@ public class wikiCode extends abstractWikiParser implements wikiParser {
/** This method handles the preformatted tags <pre> </pre> */
//contributed by [MN]
- private String preformattedTag(String result, String publicAddress, plasmaSwitchboard switchboard){
+ private String preformattedTag(String result, final String publicAddress, final plasmaSwitchboard switchboard){
int p0 = 0;
int p1 = 0;
//implementation very similar to escape code (see above)
@@ -567,9 +567,9 @@ public class wikiCode extends abstractWikiParser implements wikiParser {
//handles cases like <pre><pre> </pre></pre> <pre> </pre> that would cause an exception otherwise
else{
preformatted = true;
- String temp1 = transformLine(result.substring(0,p0-1).replaceAll("!tmp!","!tmp!!")+"!tmp!txt!", publicAddress, switchboard);
+ final String temp1 = transformLine(result.substring(0,p0-1).replaceAll("!tmp!","!tmp!!")+"!tmp!txt!", publicAddress, switchboard);
nolist = true;
- String temp2 = transformLine(result.substring(p0), publicAddress, switchboard);
+ final String temp2 = transformLine(result.substring(p0), publicAddress, switchboard);
nolist = false;
result = temp1.replaceAll("!tmp!txt!",temp2);
result = result.replaceAll("!tmp!!", "!tmp!");
@@ -655,7 +655,7 @@ public class wikiCode extends abstractWikiParser implements wikiParser {
level3 = 0;
}
level3++;
- String temp = element.substring(1);
+ final String temp = element.substring(1);
element=level1+"."+level2+"."+level3+" "+temp;
directory = directory + "&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"#"+temp.replaceAll(" ","_").replaceAll("[^a-zA-Z0-9_]","")+anchorext+"\" class=\"WikiTOC\">"+element+"</a><br />\n";
}
@@ -668,7 +668,7 @@ public class wikiCode extends abstractWikiParser implements wikiParser {
level = 2;
}
level2++;
- String temp = element.substring(1);
+ final String temp = element.substring(1);
element=level1+"."+level2+" "+temp;
directory = directory + "&nbsp;&nbsp;<a href=\"#"+temp.replaceAll(" ","_").replaceAll("[^a-zA-Z0-9_]","")+anchorext+"\" class=\"WikiTOC\">"+element+"</a><br />\n";
}
@@ -679,7 +679,7 @@ public class wikiCode extends abstractWikiParser implements wikiParser {
level3 = 0;
}
level1++;
- String temp = element.substring(1);
+ final String temp = element.substring(1);
element=level1+". "+temp;
directory = directory + "<a href=\"#"+temp.replaceAll(" ","_").replaceAll("[^a-zA-Z0-9_]","")+anchorext+"\" class=\"WikiTOC\">"+element+"</a><br />\n";
}
@@ -705,11 +705,11 @@ public class wikiCode extends abstractWikiParser implements wikiParser {
* @param repl2 string substring gets replaced by on even occurences
*/
//[MN]
- private String pairReplace(String input, String pat, String repl1, String repl2){
+ private String pairReplace(String input, final String pat, final String repl1, final String repl2){
String direlem = ""; //string to keep headlines until they get added to List dirElements
int p0 = 0;
int p1 = 0;
- int l = pat.length();
+ final int l = pat.length();
//replace pattern if a pair of the pattern can be found in the line
if( ((p0 = input.indexOf(pat)) >= 0) && ((p1 = input.indexOf(pat, p0 + l)) >= 0) ) {
//extra treatment for headlines
@@ -754,7 +754,7 @@ public class wikiCode extends abstractWikiParser implements wikiParser {
* @param switchboard
* @return the line of text with HTML tags instead of wiki tags
*/
- public String transformLine(String result, String publicAddress, plasmaSwitchboard switchboard) {
+ public String transformLine(String result, final String publicAddress, final plasmaSwitchboard switchboard) {
//If HTML has not bee replaced yet (can happen if method gets called in recursion), replace now!
if (!replacedHTML || preformattedSpan){
result = htmlTools.encodeUnicode2html(result, true);
diff --git a/source/de/anomic/htmlFilter/htmlFilterAbstractScraper.java b/source/de/anomic/htmlFilter/htmlFilterAbstractScraper.java
index de2bede5e..4f907646c 100644
--- a/source/de/anomic/htmlFilter/htmlFilterAbstractScraper.java
+++ b/source/de/anomic/htmlFilter/htmlFilterAbstractScraper.java
@@ -294,16 +294,16 @@ public abstract class htmlFilterAbstractScraper implements htmlFilterScraper {
* @param tags0
* @param tags1
*/
- public htmlFilterAbstractScraper(HashSet<String> tags0, HashSet<String> tags1) {
+ public htmlFilterAbstractScraper(final HashSet<String> tags0, final HashSet<String> tags1) {
this.tags0 = tags0;
this.tags1 = tags1;
}
- public boolean isTag0(String tag) {
+ public boolean isTag0(final String tag) {
return (tags0 != null) && (tags0.contains(tag.toLowerCase()));
}
- public boolean isTag1(String tag) {
+ public boolean isTag1(final String tag) {
return (tags1 != null) && (tags1.contains(tag.toLowerCase()));
}
@@ -316,7 +316,7 @@ public abstract class htmlFilterAbstractScraper implements htmlFilterScraper {
public abstract void scrapeTag1(String tagname, Properties tagopts, char[] text);
// string conversions
- private static String code_iso8859s(char c) {
+ private static String code_iso8859s(final char c) {
switch (c) {
// german umlaute and ligaturen
@@ -357,14 +357,14 @@ public abstract class htmlFilterAbstractScraper implements htmlFilterScraper {
}
}
- public static serverCharBuffer convertUmlaute(serverCharBuffer bb) {
+ public static serverCharBuffer convertUmlaute(final serverCharBuffer bb) {
if (bb.length() == 0) return bb;
- serverCharBuffer t = new serverCharBuffer(bb.length() + 20);
+ final serverCharBuffer t = new serverCharBuffer(bb.length() + 20);
char c;
for (int i = 0; i < bb.length(); i++) {
c = bb.charAt(i);
- String z = code_iso8859s(c);
+ final String z = code_iso8859s(c);
if (z == null) t.append((int)c);
else t.append(z);
}
@@ -410,7 +410,7 @@ public abstract class htmlFilterAbstractScraper implements htmlFilterScraper {
// return t;
}
- private static char[] transscript(char[] code) {
+ private static char[] transscript(final char[] code) {
if (code[1] == '#') {
if (code[2] == 'x' || code[2] == 'X') {
return new char[] {(char) Integer.parseInt((new String(code)).substring(3, code.length - 1), 16)};
@@ -418,7 +418,7 @@ public abstract class htmlFilterAbstractScraper implements htmlFilterScraper {
return new char[] {(char) Integer.parseInt((new String(code)).substring(2, code.length - 1))};
}
} else {
- String t = trans.get(new String(code));
+ final String t = trans.get(new String(code));
if (t == null) return new char[0];
return t.toCharArray();
}
@@ -453,7 +453,7 @@ public abstract class htmlFilterAbstractScraper implements htmlFilterScraper {
return bb.trim();
}
- public static serverCharBuffer stripAll(serverCharBuffer bb) {
+ public static serverCharBuffer stripAll(final serverCharBuffer bb) {
//return stripAllTags(s);
return convertUmlaute(transscriptAll(stripAllTags(bb)));
}
diff --git a/source/de/anomic/htmlFilter/htmlFilterAbstractTransformer.java b/source/de/anomic/htmlFilter/htmlFilterAbstractTransformer.java
index e10834a8f..fd0fac919 100644
--- a/source/de/anomic/htmlFilter/htmlFilterAbstractTransformer.java
+++ b/source/de/anomic/htmlFilter/htmlFilterAbstractTransformer.java
@@ -29,16 +29,16 @@ public abstract class htmlFilterAbstractTransformer implements htmlFilterTransfo
private TreeSet<String> tags0;
private TreeSet<String> tags1;
- public htmlFilterAbstractTransformer(TreeSet<String> tags0, TreeSet<String> tags1) {
+ public htmlFilterAbstractTransformer(final TreeSet<String> tags0, final TreeSet<String> tags1) {
this.tags0 = tags0;
this.tags1 = tags1;
}
- public boolean isTag0(String tag) {
+ public boolean isTag0(final String tag) {
return tags0.contains(tag);
}
- public boolean isTag1(String tag) {
+ public boolean isTag1(final String tag) {
return tags1.contains(tag);
}
@@ -51,11 +51,11 @@ public abstract class htmlFilterAbstractTransformer implements htmlFilterTransfo
*/
// the other methods must take into account to construct the return value correctly
- public char[] transformTag0(String tagname, Properties tagopts, char quotechar) {
+ public char[] transformTag0(final String tagname, final Properties tagopts, final char quotechar) {
return htmlFilterWriter.genTag0(tagname, tagopts, quotechar);
}
- public char[] transformTag1(String tagname, Properties tagopts, char[] text, char quotechar) {
+ public char[] transformTag1(final String tagname, final Properties tagopts, final char[] text, final char quotechar) {
return htmlFilterWriter.genTag1(tagname, tagopts, text, quotechar);
}
diff --git a/source/de/anomic/htmlFilter/htmlFilterContentScraper.java b/source/de/anomic/htmlFilter/htmlFilterContentScraper.java
index 4239750c6..3ec4df99b 100644
--- a/source/de/anomic/htmlFilter/htmlFilterContentScraper.java
+++ b/source/de/anomic/htmlFilter/htmlFilterContentScraper.java
@@ -78,12 +78,12 @@ public class htmlFilterContentScraper extends htmlFilterAbstractScraper implemen
// class variables: collectors for links
private HashMap<yacyURL, String> anchors;
private HashMap<String, htmlFilterImageEntry> images; // urlhash/image relation
- private HashMap<String, String> metas;
+ private final HashMap<String, String> metas;
private String title;
//private String headline;
private List<String>[] headlines;
private serverCharBuffer content;
- private EventListenerList htmlFilterEventListeners = new EventListenerList();
+ private final EventListenerList htmlFilterEventListeners = new EventListenerList();
/**
* {@link yacyURL} to the favicon that belongs to the document
@@ -96,7 +96,7 @@ public class htmlFilterContentScraper extends htmlFilterAbstractScraper implemen
private yacyURL root;
@SuppressWarnings("unchecked")
- public htmlFilterContentScraper(yacyURL root) {
+ public htmlFilterContentScraper(final yacyURL root) {
// the root value here will not be used to load the resource.
// it is only the reference for relative links
super(linkTags0, linkTags1);
@@ -110,13 +110,13 @@ public class htmlFilterContentScraper extends htmlFilterAbstractScraper implemen
this.content = new serverCharBuffer(1024);
}
- public final static boolean punctuation(char c) {
+ public final static boolean punctuation(final char c) {
return (c == '.') || (c == '!') || (c == '?');
}
- public void scrapeText(char[] newtext, String insideTag) {
+ public void scrapeText(final char[] newtext, final String insideTag) {
// System.out.println("SCRAPE: " + new String(newtext));
- serverCharBuffer b = super.stripAll(new serverCharBuffer(newtext, newtext.length + 1)).trim();
+ final serverCharBuffer b = super.stripAll(new serverCharBuffer(newtext, newtext.length + 1)).trim();
if ((insideTag != null) && (!(insideTag.equals("a")))) {
// texts inside tags sometimes have no punctuation at the line end
// this is bad for the text sematics, because it is not possible for the
@@ -131,33 +131,33 @@ public class htmlFilterContentScraper extends htmlFilterAbstractScraper implemen
public static final String splitrex = " |/|\\(|\\)|-|\\:|_|\\.|,|\\?|!|'|" + '"';
public static String[] urlComps(String normalizedURL) {
- int p = normalizedURL.indexOf("//");
+ final int p = normalizedURL.indexOf("//");
if (p > 0) normalizedURL = normalizedURL.substring(p + 2);
return normalizedURL.toLowerCase().split(splitrex); // word components of the url
}
- private yacyURL absolutePath(String relativePath) {
+ private yacyURL absolutePath(final String relativePath) {
try {
return yacyURL.newURL(root, relativePath);
- } catch (Exception e) {
+ } catch (final Exception e) {
return null;
}
}
- public void scrapeTag0(String tagname, Properties tagopts) {
+ public void scrapeTag0(final String tagname, final Properties tagopts) {
if (tagname.equalsIgnoreCase("img")) {
int width = -1, height = -1;
try {
width = Integer.parseInt(tagopts.getProperty("width", "-1"));
height = Integer.parseInt(tagopts.getProperty("height", "-1"));
- } catch (NumberFormatException e) {}
- yacyURL url = absolutePath(tagopts.getProperty("src", ""));
- htmlFilterImageEntry ie = new htmlFilterImageEntry(url, tagopts.getProperty("alt",""), width, height);
+ } catch (final NumberFormatException e) {}
+ final yacyURL url = absolutePath(tagopts.getProperty("src", ""));
+ final htmlFilterImageEntry ie = new htmlFilterImageEntry(url, tagopts.getProperty("alt",""), width, height);
addImage(images, ie);
}
if (tagname.equalsIgnoreCase("base")) try {
root = new yacyURL(tagopts.getProperty("href", ""), null);
- } catch (MalformedURLException e) {}
+ } catch (final MalformedURLException e) {}
if (tagname.equalsIgnoreCase("frame")) {
anchors.put(absolutePath(tagopts.getProperty("src", "")), tagopts.getProperty("name",""));
}
@@ -173,20 +173,20 @@ public class htmlFilterContentScraper extends htmlFilterAbstractScraper implemen
}
}
if (tagname.equalsIgnoreCase("area")) {
- String areatitle = cleanLine(tagopts.getProperty("title",""));
+ final String areatitle = cleanLine(tagopts.getProperty("title",""));
//String alt = tagopts.getProperty("alt","");
- String href = tagopts.getProperty("href", "");
+ final String href = tagopts.getProperty("href", "");
if (href.length() > 0) anchors.put(absolutePath(href), areatitle);
}
if (tagname.equalsIgnoreCase("link")) {
- yacyURL newLink = absolutePath(tagopts.getProperty("href", ""));
+ final yacyURL newLink = absolutePath(tagopts.getProperty("href", ""));
if (newLink != null) {
- String type = tagopts.getProperty("rel", "");
- String linktitle = tagopts.getProperty("title", "");
+ final String type = tagopts.getProperty("rel", "");
+ final String linktitle = tagopts.getProperty("title", "");
if (type.equalsIgnoreCase("shortcut icon")) {
- htmlFilterImageEntry ie = new htmlFilterImageEntry(newLink, linktitle, -1,-1);
+ final htmlFilterImageEntry ie = new htmlFilterImageEntry(newLink, linktitle, -1,-1);
images.put(ie.url().hash(), ie);
this.favicon = newLink;
} else if (!type.equalsIgnoreCase("stylesheet") && !type.equalsIgnoreCase("alternate stylesheet")) {
@@ -199,7 +199,7 @@ public class htmlFilterContentScraper extends htmlFilterAbstractScraper implemen
anchors.put(absolutePath(tagopts.getProperty("src", "")), tagopts.getProperty("name",""));
}
if (tagname.equalsIgnoreCase("param")) {
- String name = tagopts.getProperty("name", "");
+ final String name = tagopts.getProperty("name", "");
if (name.equalsIgnoreCase("movie")) {
anchors.put(absolutePath(tagopts.getProperty("value", "")),name);
}
@@ -210,18 +210,18 @@ public class htmlFilterContentScraper extends htmlFilterAbstractScraper implemen
fireScrapeTag0(tagname, tagopts);
}
- public void scrapeTag1(String tagname, Properties tagopts, char[] text) {
+ public void scrapeTag1(final String tagname, final Properties tagopts, final char[] text) {
// System.out.println("ScrapeTag1: tagname=" + tagname + ", opts=" + tagopts.toString() + ", text=" + new String(text));
if ((tagname.equalsIgnoreCase("a")) && (text.length < 2048)) {
- String href = tagopts.getProperty("href", "");
+ final String href = tagopts.getProperty("href", "");
yacyURL url;
if ((href.length() > 0) && ((url = absolutePath(href)) != null)) {
- String f = url.getFile();
- int p = f.lastIndexOf('.');
- String type = (p < 0) ? "" : f.substring(p + 1);
+ final String f = url.getFile();
+ final int p = f.lastIndexOf('.');
+ final String type = (p < 0) ? "" : f.substring(p + 1);
if (type.equals("png") || type.equals("gif") || type.equals("jpg") || type.equals("jpeg")) {
// special handling of such urls: put them to the image urls
- htmlFilterImageEntry ie = new htmlFilterImageEntry(url, super.stripAll(new serverCharBuffer(text)).trim().toString(), -1, -1);
+ final htmlFilterImageEntry ie = new htmlFilterImageEntry(url, super.stripAll(new serverCharBuffer(text)).trim().toString(), -1, -1);
addImage(images, ie);
} else {
anchors.put(url, super.stripAll(new serverCharBuffer(text)).trim().toString());
@@ -311,9 +311,9 @@ public class htmlFilterContentScraper extends htmlFilterAbstractScraper implemen
return cleanLine(content.trim().toString());
}
- public String[] getHeadlines(int i) {
+ public String[] getHeadlines(final int i) {
assert ((i >= 1) && (i <= 4));
- String[] s = new String[headlines[i - 1].size()];
+ final String[] s = new String[headlines[i - 1].size()];
for (int j = 0; j < headlines[i - 1].size(); j++) s[j] = headlines[i - 1].get(j);
return s;
}
@@ -322,10 +322,10 @@ public class htmlFilterContentScraper extends htmlFilterAbstractScraper implemen
return this.getText("UTF-8");
}
- public byte[] getText(String charSet) {
+ public byte[] getText(final String charSet) {
try {
return content.toString().getBytes(charSet);
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
return content.toString().getBytes();
}
}
@@ -367,7 +367,7 @@ public class htmlFilterContentScraper extends htmlFilterAbstractScraper implemen
}
public String getContentType() {
- String s = metas.get("content-type");
+ final String s = metas.get("content-type");
if (s == null) return ""; else return s;
}
@@ -398,13 +398,13 @@ public class htmlFilterContentScraper extends htmlFilterAbstractScraper implemen
}
public int getRefreshSeconds() {
- String s = metas.get("refresh");
+ final String s = metas.get("refresh");
if (s == null) return 9999; else try {
- int pos = s.indexOf(';');
+ final int pos = s.indexOf(';');
if (pos < 0) return 9999;
- int i = Integer.parseInt(s.substring(0, pos));
+ final int i = Integer.parseInt(s.substring(0, pos));
return i;
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
return 9999;
}
}
@@ -412,7 +412,7 @@ public class htmlFilterContentScraper extends htmlFilterAbstractScraper implemen
public String getRefreshPath() {
String s = metas.get("refresh");
if (s == null) return ""; else {
- int pos = s.indexOf(';');
+ final int pos = s.indexOf(';');
if (pos < 0) return "";
s = s.substring(pos + 1);
if (s.toLowerCase().startsWith("url=")) return s.substring(4).trim(); else return "";
@@ -445,20 +445,20 @@ public class htmlFilterContentScraper extends htmlFilterAbstractScraper implemen
System.out.println("TEXT :" + content.toString());
}
- public void registerHtmlFilterEventListener(htmlFilterEventListener listener) {
+ public void registerHtmlFilterEventListener(final htmlFilterEventListener listener) {
if (listener != null) {
this.htmlFilterEventListeners.add(htmlFilterEventListener.class, listener);
}
}
- public void deregisterHtmlFilterEventListener(htmlFilterEventListener listener) {
+ public void deregisterHtmlFilterEventListener(final htmlFilterEventListener listener) {
if (listener != null) {
this.htmlFilterEventListeners.remove(htmlFilterEventListener.class, listener);
}
}
- void fireScrapeTag0(String tagname, Properties tagopts) {
- Object[] listeners = this.htmlFilterEventListeners.getListenerList();
+ void fireScrapeTag0(final String tagname, final Properties tagopts) {
+ final Object[] listeners = this.htmlFilterEventListeners.getListenerList();
for (int i=0; i<listeners.length; i+=2) {
if (listeners[i]==htmlFilterEventListener.class) {
((htmlFilterEventListener)listeners[i+1]).scrapeTag0(tagname, tagopts);
@@ -466,8 +466,8 @@ public class htmlFilterContentScraper extends htmlFilterAbstractScraper implemen
}
}
- void fireScrapeTag1(String tagname, Properties tagopts, char[] text) {
- Object[] listeners = this.htmlFilterEventListeners.getListenerList();
+ void fireScrapeTag1(final String tagname, final Properties tagopts, final char[] text) {
+ final Object[] listeners = this.htmlFilterEventListeners.getListenerList();
for (int i=0; i<listeners.length; i+=2) {
if (listeners[i]==htmlFilterEventListener.class) {
((htmlFilterEventListener)listeners[i+1]).scrapeTag1(tagname, tagopts, text);
@@ -475,36 +475,36 @@ public class htmlFilterContentScraper extends htmlFilterAbstractScraper implemen
}
}
- public static htmlFilterContentScraper parseResource(File file) throws IOException {
+ public static htmlFilterContentScraper parseResource(final File file) throws IOException {
// load page
- byte[] page = serverFileUtils.read(file);
+ final byte[] page = serverFileUtils.read(file);
if (page == null) throw new IOException("no content in file " + file.toString());
// scrape content
- htmlFilterContentScraper scraper = new htmlFilterContentScraper(new yacyURL("http://localhost", null));
- Writer writer = new htmlFilterWriter(null, null, scraper, null, false);
+ final htmlFilterContentScraper scraper = new htmlFilterContentScraper(new yacyURL("http://localhost", null));
+ final Writer writer = new htmlFilterWriter(null, null, scraper, null, false);
serverFileUtils.copy(new ByteArrayInputStream(page), writer, "UTF-8");
return scraper;
}
- public static htmlFilterContentScraper parseResource(yacyURL location) throws IOException {
+ public static htmlFilterContentScraper parseResource(final yacyURL location) throws IOException {
// load page
- httpHeader reqHeader = new httpHeader();
+ final httpHeader reqHeader = new httpHeader();
reqHeader.put(httpHeader.USER_AGENT, HTTPLoader.crawlerUserAgent);
- byte[] page = HttpClient.wget(location.toString(), reqHeader, 10000);
+ final byte[] page = HttpClient.wget(location.toString(), reqHeader, 10000);
if (page == null) throw new IOException("no response from url " + location.toString());
// scrape content
- htmlFilterContentScraper scraper = new htmlFilterContentScraper(location);
- Writer writer = new htmlFilterWriter(null, null, scraper, null, false);
+ final htmlFilterContentScraper scraper = new htmlFilterContentScraper(location);
+ final Writer writer = new htmlFilterWriter(null, null, scraper, null, false);
serverFileUtils.copy(new ByteArrayInputStream(page), writer, "UTF-8");
return scraper;
}
- public static void addAllImages(HashMap<String, htmlFilterImageEntry> a, HashMap<String, htmlFilterImageEntry> b) {
- Iterator<Map.Entry<String, htmlFilterImageEntry>> i = b.entrySet().iterator();
+ public static void addAllImages(final HashMap<String, htmlFilterImageEntry> a, final HashMap<String, htmlFilterImageEntry> b) {
+ final Iterator<Map.Entry<String, htmlFilterImageEntry>> i = b.entrySet().iterator();
Map.Entry<String, htmlFilterImageEntry> ie;
while (i.hasNext()) {
ie = i.next();
@@ -512,7 +512,7 @@ public class htmlFilterContentScraper extends htmlFilterAbstractScraper implemen
}
}
- public static void addImage(HashMap<String, htmlFilterImageEntry> a, htmlFilterImageEntry ie) {
+ public static void addImage(final HashMap<String, htmlFilterImageEntry> a, final htmlFilterImageEntry ie) {
if (a.containsKey(ie.url().hash())) {
// in case of a collision, take that image that has the better image size tags
if ((ie.height() > 0) && (ie.width() > 0)) a.put(ie.url().hash(), ie);
diff --git a/source/de/anomic/htmlFilter/htmlFilterContentTransformer.java b/source/de/anomic/htmlFilter/htmlFilterContentTransformer.java
index 561a8dfba..a20874cc0 100644
--- a/source/de/anomic/htmlFilter/htmlFilterContentTransformer.java
+++ b/source/de/anomic/htmlFilter/htmlFilterContentTransformer.java
@@ -62,20 +62,20 @@ public class htmlFilterContentTransformer extends htmlFilterAbstractTransformer
super(linkTags0, linkTags1);
}
- public void init(String initarg) {
+ public void init(final String initarg) {
if (bluelist == null) {
// here, the init arg is used to load a list of blue-listed words
bluelist = new ArrayList<String>();
- File f = new File(initarg);
+ final File f = new File(initarg);
if (f.canRead()) {
try {
- BufferedReader r = new BufferedReader(new FileReader(f));
+ final BufferedReader r = new BufferedReader(new FileReader(f));
String s;
while ((s = r.readLine()) != null) {
if (!s.startsWith("#") && s.length() > 0) bluelist.add(s.toLowerCase());
}
r.close();
- } catch (Exception e) {
+ } catch (final Exception e) {
}
// if (bluelist.size() == 0) System.out.println("BLUELIST is empty");
}
@@ -87,7 +87,7 @@ public class htmlFilterContentTransformer extends htmlFilterAbstractTransformer
}
private static char[] genBlueLetters(int length) {
- serverCharBuffer bb = new serverCharBuffer(" <FONT COLOR=#0000FF>".toCharArray());
+ final serverCharBuffer bb = new serverCharBuffer(" <FONT COLOR=#0000FF>".toCharArray());
length = length / 2;
if (length > 10) length = 7;
while (length-- > 0) {
@@ -97,20 +97,20 @@ public class htmlFilterContentTransformer extends htmlFilterAbstractTransformer
return bb.getChars();
}
- private boolean bluelistHit(char[] text) {
+ private boolean bluelistHit(final char[] text) {
if (text == null || bluelist == null) return false;
- String lc = new String(text).toLowerCase();
+ final String lc = new String(text).toLowerCase();
for (int i = 0; i < bluelist.size(); i++) {
if (lc.indexOf(bluelist.get(i)) >= 0) return true;
}
return false;
}
- public ArrayList<String> getStrings(byte[] text){
- ArrayList<String> result = new ArrayList<String>();
+ public ArrayList<String> getStrings(final byte[] text){
+ final ArrayList<String> result = new ArrayList<String>();
- serverByteBuffer sbb = new serverByteBuffer(text);
- serverByteBuffer[] sbbs = httpTemplate.splitQuotations(sbb);
+ final serverByteBuffer sbb = new serverByteBuffer(text);
+ final serverByteBuffer[] sbbs = httpTemplate.splitQuotations(sbb);
//sbb = new serverByteBuffer();
for (int i = 0; i < sbbs.length; i++) {
// TODO: avoid empty if statements
@@ -122,14 +122,14 @@ public class htmlFilterContentTransformer extends htmlFilterAbstractTransformer
//sbb.append(sbbs[i]);
} else {
// this is a text fragment, generate gettext quotation
- int ws = sbbs[i].whitespaceStart(true);
- int we = sbbs[i].whitespaceEnd(true);
+ final int ws = sbbs[i].whitespaceStart(true);
+ final int we = sbbs[i].whitespaceEnd(true);
result.add(new String(sbbs[i].getBytes(ws, we - ws)));
}
}
return result;
}
- public char[] transformText(char[] text) {
+ public char[] transformText(final char[] text) {
if (bluelist != null) {
if (bluelistHit(text)) {
// System.out.println("FILTERHIT: " + text);
@@ -140,7 +140,7 @@ public class htmlFilterContentTransformer extends htmlFilterAbstractTransformer
return text;
}
- public char[] transformTag0(String tagname, Properties tagopts, char quotechar) {
+ public char[] transformTag0(final String tagname, final Properties tagopts, final char quotechar) {
if (tagname.equals("img")) {
// check bluelist
if (bluelistHit(tagopts.getProperty("src", "").toCharArray())) return genBlueLetters(5);
@@ -156,7 +156,7 @@ public class htmlFilterContentTransformer extends htmlFilterAbstractTransformer
return htmlFilterWriter.genTag0(tagname, tagopts, quotechar);
}
- public char[] transformTag1(String tagname, Properties tagopts, char[] text, char quotechar) {
+ public char[] transformTag1(final String tagname, final Properties tagopts, final char[] text, final char quotechar) {
if (bluelistHit(tagopts.getProperty("href","").toCharArray())) return genBlueLetters(text.length);
if (bluelistHit(text)) return genBlueLetters(text.length);
return htmlFilterWriter.genTag1(tagname, tagopts, text, quotechar);
diff --git a/source/de/anomic/htmlFilter/htmlFilterImageEntry.java b/source/de/anomic/htmlFilter/htmlFilterImageEntry.java
index 52ffd9d83..de495fb96 100644
--- a/source/de/anomic/htmlFilter/htmlFilterImageEntry.java
+++ b/source/de/anomic/htmlFilter/htmlFilterImageEntry.java
@@ -25,11 +25,11 @@ import de.anomic.yacy.yacyURL;
public class htmlFilterImageEntry implements Comparable<htmlFilterImageEntry> {
- private yacyURL url;
- private String alt;
- private int width, height;
+ private final yacyURL url;
+ private final String alt;
+ private final int width, height;
- public htmlFilterImageEntry(yacyURL url, String alt, int width, int height) {
+ public htmlFilterImageEntry(final yacyURL url, final String alt, final int width, final int height) {
this.url = url;
this.alt = alt;
this.width = width;
@@ -67,21 +67,21 @@ public class htmlFilterImageEntry implements Comparable<htmlFilterImageEntry> {
return 0x7FFF0000 | (url.hashCode() & 0xFFFF);
}
- public int compareTo(htmlFilterImageEntry h) {
+ public int compareTo(final htmlFilterImageEntry h) {
// this is needed if this object is stored in a TreeSet
// this method uses the image-size ordering from the hashCode method
// assuming that hashCode would return a 'perfect hash' this method would
// create a total ordering on images with respect on the image size
assert (url != null);
if (this.url.toNormalform(true, true).equals((h).url.toNormalform(true, true))) return 0;
- int thc = this.hashCode();
- int ohc = (h).hashCode();
+ final int thc = this.hashCode();
+ final int ohc = (h).hashCode();
if (thc < ohc) return -1;
if (thc > ohc) return 1;
return this.url.toString().compareTo((h).url.toString());
}
- public boolean equals(htmlFilterImageEntry o) {
+ public boolean equals(final htmlFilterImageEntry o) {
return compareTo(o) == 0;
}
}
diff --git a/source/de/anomic/htmlFilter/htmlFilterInputStream.java b/source/de/anomic/htmlFilter/htmlFilterInputStream.java
index 97eb4856a..9c0fa60dd 100644
--- a/source/de/anomic/htmlFilter/htmlFilterInputStream.java
+++ b/source/de/anomic/htmlFilter/htmlFilterInputStream.java
@@ -44,43 +44,43 @@ public class htmlFilterInputStream extends InputStream implements htmlFilterEven
private static final int MODE_PRESCAN_FINISHED = 1;
private int mode = 1;
- private long preBufferSize = 2048;
+ private final long preBufferSize = 2048;
private long preRead = 0;
- private BufferedInputStream bufferedIn;
+ private final BufferedInputStream bufferedIn;
private String detectedCharset;
private boolean charsetChanged = false;
private boolean endOfHead = false;
- private Reader reader;
+ private final Reader reader;
private Writer writer;
public htmlFilterInputStream(
- InputStream inStream,
- String inputStreamCharset,
- yacyURL rooturl,
- htmlFilterTransformer transformer,
- boolean passbyIfBinarySuspect
+ final InputStream inStream,
+ final String inputStreamCharset,
+ final yacyURL rooturl,
+ final htmlFilterTransformer transformer,
+ final boolean passbyIfBinarySuspect
) throws UnsupportedEncodingException {
// create a input stream for buffereing
this.bufferedIn = new BufferedInputStream(inStream,(int)this.preBufferSize);
this.bufferedIn.mark((int)this.preBufferSize);
- htmlFilterContentScraper scraper = new htmlFilterContentScraper(rooturl);
+ final htmlFilterContentScraper scraper = new htmlFilterContentScraper(rooturl);
scraper.registerHtmlFilterEventListener(this);
this.reader = new InputStreamReader(this,inputStreamCharset);
this.writer = new htmlFilterWriter(null,null,scraper,transformer,passbyIfBinarySuspect);
}
- public void scrapeTag0(String tagname, Properties tagopts) {
+ public void scrapeTag0(final String tagname, final Properties tagopts) {
if (tagname == null || tagname.length() == 0) return;
if (tagname.equalsIgnoreCase("meta")) {
if (tagopts.containsKey("http-equiv")) {
- String value = tagopts.getProperty("http-equiv");
+ final String value = tagopts.getProperty("http-equiv");
if (value.equalsIgnoreCase("Content-Type")) {
- String contentType = tagopts.getProperty("content","");
+ final String contentType = tagopts.getProperty("content","");
this.detectedCharset = httpHeader.extractCharsetFromMimetypeHeader(contentType);
if (this.detectedCharset != null && this.detectedCharset.length() > 0) {
this.charsetChanged = true;
@@ -94,7 +94,7 @@ public class htmlFilterInputStream extends InputStream implements htmlFilterEven
}
}
- public void scrapeTag1(String tagname, Properties tagopts, char[] text) {
+ public void scrapeTag1(final String tagname, final Properties tagopts, final char[] text) {
if (tagname == null || tagname.length() == 0) return;
if (tagname.equalsIgnoreCase("head")) {
diff --git a/source/de/anomic/htmlFilter/htmlFilterWriter.java b/source/de/anomic/htmlFilter/htmlFilterWriter.java
index e597e7e46..9d0c17c01 100644
--- a/source/de/anomic/htmlFilter/htmlFilterWriter.java
+++ b/source/de/anomic/htmlFilter/htmlFilterWriter.java
@@ -56,27 +56,27 @@ public final class htmlFilterWriter extends Writer {
public static final char singlequote = '\'';
public static final char doublequote = '"';
- private OutputStream outStream;
+ private final OutputStream outStream;
private OutputStreamWriter out;
private serverCharBuffer buffer;
private String filterTag;
private Properties filterOpts;
private serverCharBuffer filterCont;
- private htmlFilterScraper scraper;
- private htmlFilterTransformer transformer;
+ private final htmlFilterScraper scraper;
+ private final htmlFilterTransformer transformer;
private boolean inSingleQuote;
private boolean inDoubleQuote;
private boolean inComment;
private boolean inScript;
private boolean binaryUnsuspect;
- private boolean passbyIfBinarySuspect;
+ private final boolean passbyIfBinarySuspect;
public htmlFilterWriter(
- OutputStream outStream,
- String outputStreamCharset,
- htmlFilterScraper scraper,
- htmlFilterTransformer transformer,
- boolean passbyIfBinarySuspect
+ final OutputStream outStream,
+ final String outputStreamCharset,
+ final htmlFilterScraper scraper,
+ final htmlFilterTransformer transformer,
+ final boolean passbyIfBinarySuspect
) throws UnsupportedEncodingException {
this.outStream = outStream;
this.scraper = scraper;
@@ -97,8 +97,8 @@ public final class htmlFilterWriter extends Writer {
}
}
- public static char[] genTag0raw(String tagname, boolean opening, char[] tagopts) {
- serverCharBuffer bb = new serverCharBuffer(tagname.length() + tagopts.length + 3);
+ public static char[] genTag0raw(final String tagname, final boolean opening, final char[] tagopts) {
+ final serverCharBuffer bb = new serverCharBuffer(tagname.length() + tagopts.length + 3);
bb.append((int)'<');
if (!opening) {
bb.append((int)'/');
@@ -113,8 +113,8 @@ public final class htmlFilterWriter extends Writer {
return bb.getChars();
}
- public static char[] genTag1raw(String tagname, char[] tagopts, char[] text) {
- serverCharBuffer bb = new serverCharBuffer(2 * tagname.length() + tagopts.length + text.length + 5);
+ public static char[] genTag1raw(final String tagname, final char[] tagopts, final char[] text) {
+ final serverCharBuffer bb = new serverCharBuffer(2 * tagname.length() + tagopts.length + text.length + 5);
bb.append((int)'<').append(tagname);
if (tagopts.length > 0) {
// if (tagopts[0] == (byte) 32)
@@ -127,9 +127,9 @@ public final class htmlFilterWriter extends Writer {
return bb.getChars();
}
- public static char[] genTag0(String tagname, Properties tagopts, char quotechar) {
- char[] tagoptsx = (tagopts.size() == 0) ? null : genOpts(tagopts, quotechar);
- serverCharBuffer bb = new serverCharBuffer(tagname.length() + ((tagoptsx == null) ? 0 : (tagoptsx.length + 1)) + tagname.length() + 2);
+ public static char[] genTag0(final String tagname, final Properties tagopts, final char quotechar) {
+ final char[] tagoptsx = (tagopts.size() == 0) ? null : genOpts(tagopts, quotechar);
+ final serverCharBuffer bb = new serverCharBuffer(tagname.length() + ((tagoptsx == null) ? 0 : (tagoptsx.length + 1)) + tagname.length() + 2);
bb.append((int)'<').append(tagname);
if (tagoptsx != null) {
bb.append(32);
@@ -139,17 +139,17 @@ public final class htmlFilterWriter extends Writer {
return bb.getChars();
}
- public static char[] genTag1(String tagname, Properties tagopts, char[] text, char quotechar) {
- char[] gt0 = genTag0(tagname, tagopts, quotechar);
- serverCharBuffer cb = new serverCharBuffer(gt0, gt0.length + text.length + tagname.length() + 3);
+ public static char[] genTag1(final String tagname, final Properties tagopts, final char[] text, final char quotechar) {
+ final char[] gt0 = genTag0(tagname, tagopts, quotechar);
+ final serverCharBuffer cb = new serverCharBuffer(gt0, gt0.length + text.length + tagname.length() + 3);
cb.append(text).append((int)'<').append((int)'/').append(tagname).append((int)'>');
return cb.getChars();
}
// a helper method for pretty-printing of properties for html tags
- public static char[] genOpts(Properties prop, char quotechar) {
- Enumeration<?> e = prop.propertyNames();
- serverCharBuffer bb = new serverCharBuffer(prop.size() * 40);
+ public static char[] genOpts(final Properties prop, final char quotechar) {
+ final Enumeration<?> e = prop.propertyNames();
+ final serverCharBuffer bb = new serverCharBuffer(prop.size() * 40);
String key;
while (e.hasMoreElements()) {
key = (String) e.nextElement();
@@ -161,7 +161,7 @@ public final class htmlFilterWriter extends Writer {
return bb.getChars();
}
- private char[] filterTag(String tag, boolean opening, char[] content, char quotechar) {
+ private char[] filterTag(final String tag, final boolean opening, final char[] content, final char quotechar) {
// System.out.println("FILTER1: filterTag=" + ((filterTag == null) ? "null" : filterTag) + ", tag=" + tag + ", opening=" + ((opening) ? "true" : "false") + ", content=" + new String(content)); // debug
if (filterTag == null) {
// we are not collection tag text
@@ -232,7 +232,7 @@ public final class htmlFilterWriter extends Writer {
return ret;
}
- private char[] filterFinalize(char quotechar) {
+ private char[] filterFinalize(final char quotechar) {
if (filterTag == null) {
return new char[0];
}
@@ -251,7 +251,7 @@ public final class htmlFilterWriter extends Writer {
return ret;
}
- private char[] filterSentence(char[] in, char quotechar) {
+ private char[] filterSentence(final char[] in, final char quotechar) {
if (in.length == 0) return in;
// System.out.println("FILTER0: " + new String(in)); // debug
// scan the string and parse structure
@@ -264,7 +264,7 @@ public final class htmlFilterWriter extends Writer {
// a closing tag
tagend = tagEnd(in, 2);
tag = new String(in, 2, tagend - 2);
- char[] text = new char[in.length - tagend - 1];
+ final char[] text = new char[in.length - tagend - 1];
System.arraycopy(in, tagend, text, 0, in.length - tagend - 1);
return filterTag(tag, false, text, quotechar);
}
@@ -272,7 +272,7 @@ public final class htmlFilterWriter extends Writer {
// an opening tag
tagend = tagEnd(in, 1);
tag = new String(in, 1, tagend - 1);
- char[] text = new char[in.length - tagend - 1];
+ final char[] text = new char[in.length - tagend - 1];
System.arraycopy(in, tagend, text, 0, in.length - tagend - 1);
return filterTag(tag, true, text, quotechar);
}
@@ -281,7 +281,7 @@ public final class htmlFilterWriter extends Writer {
return filterTag(null, true, in, quotechar);
}
- private static int tagEnd(char[] tag, int start) {
+ private static int tagEnd(final char[] tag, final int start) {
char c;
for (int i = start; i < tag.length; i++) {
c = tag[i];
@@ -294,7 +294,7 @@ public final class htmlFilterWriter extends Writer {
return tag.length - 1;
}
- public void write(int c) throws IOException {
+ public void write(final int c) throws IOException {
// System.out.println((char) c);
if ((binaryUnsuspect) && (binaryHint((char)c))) {
binaryUnsuspect = false;
@@ -340,7 +340,7 @@ public final class htmlFilterWriter extends Writer {
}
} else if (inScript) {
buffer.append(c);
- int bufferLength = buffer.length();
+ final int bufferLength = buffer.length();
if ((c == rb) && (bufferLength > 14) &&
(buffer.charAt(bufferLength - 8) == '/') &&
(buffer.charAt(bufferLength - 7) == 's') &&
@@ -424,11 +424,11 @@ public final class htmlFilterWriter extends Writer {
}
}
- public void write(char b[]) throws IOException {
+ public void write(final char b[]) throws IOException {
write(b, 0, b.length);
}
- public void write(char b[], int off, int len) throws IOException {
+ public void write(final char b[], final int off, final int len) throws IOException {
// System.out.println(new String(b, off, len));
if ((off | len | (b.length - (len + off)) | (off + len)) < 0) throw new IndexOutOfBoundsException();
for (int i = off ; i < (len - off) ; i++) this.write(b[i]);
@@ -449,15 +449,15 @@ public final class htmlFilterWriter extends Writer {
}
public void close() throws IOException {
- char quotechar = (inSingleQuote) ? singlequote : doublequote;
+ final char quotechar = (inSingleQuote) ? singlequote : doublequote;
if (buffer != null) {
if (buffer.length() > 0) {
- char[] filtered = filterSentence(buffer.getChars(), quotechar);
+ final char[] filtered = filterSentence(buffer.getChars(), quotechar);
if (out != null) out.write(filtered);
}
buffer = null;
}
- char[] finalized = filterFinalize(quotechar);
+ final char[] finalized = filterFinalize(quotechar);
if (out != null) {
if (finalized != null) out.write(finalized);
out.flush();
@@ -491,27 +491,27 @@ public final class htmlFilterWriter extends Writer {
return !binaryUnsuspect;
}
- public static void main(String[] args) {
+ public static void main(final String[] args) {
// takes one argument: a file name
if (args.length != 1) return;
- char[] buffer = new char[512];
+ final char[] buffer = new char[512];
try {
- htmlFilterContentScraper scraper = new htmlFilterContentScraper(new yacyURL("http://localhost:8080", null));
- htmlFilterTransformer transformer = new htmlFilterContentTransformer();
+ final htmlFilterContentScraper scraper = new htmlFilterContentScraper(new yacyURL("http://localhost:8080", null));
+ final htmlFilterTransformer transformer = new htmlFilterContentTransformer();
// TODO: this does not work at the moment
System.exit(0);
- Reader is = new FileReader(args[0]);
- FileOutputStream fos = new FileOutputStream(new File(args[0] + ".out"));
- Writer os = new htmlFilterWriter(fos, "UTF-8",scraper, transformer, false);
+ final Reader is = new FileReader(args[0]);
+ final FileOutputStream fos = new FileOutputStream(new File(args[0] + ".out"));
+ final Writer os = new htmlFilterWriter(fos, "UTF-8",scraper, transformer, false);
int i;
while ((i = is.read(buffer)) > 0) os.write(buffer, 0, i);
os.close();
fos.close();
is.close();
scraper.print();
- } catch (MalformedURLException e) {
+ } catch (final MalformedURLException e) {
e.printStackTrace();
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
}
diff --git a/source/de/anomic/http/EasySSLProtocolSocketFactory.java b/source/de/anomic/http/EasySSLProtocolSocketFactory.java
index 334d0c516..533b42c09 100644
--- a/source/de/anomic/http/EasySSLProtocolSocketFactory.java
+++ b/source/de/anomic/http/EasySSLProtocolSocketFactory.java
@@ -113,13 +113,13 @@ public class EasySSLProtocolSocketFactory implements SecureProtocolSocketFactory
private static SSLContext createEasySSLContext() {
try {
- SSLContext context = SSLContext.getInstance("SSL");
+ final SSLContext context = SSLContext.getInstance("SSL");
context.init(
null,
new TrustManager[] {new EasyX509TrustManager(null)},
null);
return context;
- } catch (Exception e) {
+ } catch (final Exception e) {
LOG.error(e.getMessage(), e);
throw new HttpClientError(e.toString());
}
@@ -136,10 +136,10 @@ public class EasySSLProtocolSocketFactory implements SecureProtocolSocketFactory
* @see SecureProtocolSocketFactory#createSocket(java.lang.String,int,java.net.InetAddress,int)
*/
public Socket createSocket(
- String host,
- int port,
- InetAddress clientHost,
- int clientPort)
+ final String host,
+ final int port,
+ final InetAddress clientHost,
+ final int clientPort)
throws IOException, UnknownHostException {
return getSSLContext().getSocketFactory().createSocket(
@@ -181,14 +181,14 @@ public class EasySSLProtocolSocketFactory implements SecureProtocolSocketFactory
if (params == null) {
throw new IllegalArgumentException("Parameters may not be null");
}
- int timeout = params.getConnectionTimeout();
- SocketFactory socketfactory = getSSLContext().getSocketFactory();
+ final int timeout = params.getConnectionTimeout();
+ final SocketFactory socketfactory = getSSLContext().getSocketFactory();
if (timeout == 0) {
return socketfactory.createSocket(host, port, localAddress, localPort);
} else {
- Socket socket = socketfactory.createSocket();
- SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
- SocketAddress remoteaddr = new InetSocketAddress(host, port);
+ final Socket socket = socketfactory.createSocket();
+ final SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
+ final SocketAddress remoteaddr = new InetSocketAddress(host, port);
socket.bind(localaddr);
socket.connect(remoteaddr, timeout);
return socket;
@@ -198,7 +198,7 @@ public class EasySSLProtocolSocketFactory implements SecureProtocolSocketFactory
/**
* @see SecureProtocolSocketFactory#createSocket(java.lang.String,int)
*/
- public Socket createSocket(String host, int port)
+ public Socket createSocket(final String host, final int port)
throws IOException, UnknownHostException {
return getSSLContext().getSocketFactory().createSocket(
host,
@@ -210,10 +210,10 @@ public class EasySSLProtocolSocketFactory implements SecureProtocolSocketFactory
* @see SecureProtocolSocketFactory#createSocket(java.net.Socket,java.lang.String,int,boolean)
*/
public Socket createSocket(
- Socket socket,
- String host,
- int port,
- boolean autoClose)
+ final Socket socket,
+ final String host,
+ final int port,
+ final boolean autoClose)
throws IOException, UnknownHostException {
return getSSLContext().getSocketFactory().createSocket(
socket,
@@ -223,7 +223,7 @@ public class EasySSLProtocolSocketFactory implements SecureProtocolSocketFactory
);
}
- public boolean equals(Object obj) {
+ public boolean equals(final Object obj) {
return ((obj != null) && obj.getClass().equals(EasySSLProtocolSocketFactory.class));
}
diff --git a/source/de/anomic/http/EasyX509TrustManager.java b/source/de/anomic/http/EasyX509TrustManager.java
index bd5a8c4d0..0812aedb1 100644
--- a/source/de/anomic/http/EasyX509TrustManager.java
+++ b/source/de/anomic/http/EasyX509TrustManager.java
@@ -75,11 +75,11 @@ public class EasyX509TrustManager implements X509TrustManager
/**
* Constructor for EasyX509TrustManager.
*/
- public EasyX509TrustManager(KeyStore keystore) throws NoSuchAlgorithmException, KeyStoreException {
+ public EasyX509TrustManager(final KeyStore keystore) throws NoSuchAlgorithmException, KeyStoreException {
super();
- TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
+ final TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
factory.init(keystore);
- TrustManager[] trustmanagers = factory.getTrustManagers();
+ final TrustManager[] trustmanagers = factory.getTrustManagers();
if (trustmanagers.length == 0) {
throw new NoSuchAlgorithmException("no trust manager found");
}
@@ -89,14 +89,14 @@ public class EasyX509TrustManager implements X509TrustManager
/**
* @see javax.net.ssl.X509TrustManager#checkClientTrusted(X509Certificate[],String authType)
*/
- public void checkClientTrusted(X509Certificate[] certificates,String authType) throws CertificateException {
+ public void checkClientTrusted(final X509Certificate[] certificates,final String authType) throws CertificateException {
standardTrustManager.checkClientTrusted(certificates,authType);
}
/**
* @see javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[],String authType)
*/
- public void checkServerTrusted(X509Certificate[] certificates,String authType) throws CertificateException {
+ public void checkServerTrusted(final X509Certificate[] certificates,final String authType) throws CertificateException {
if ((certificates != null) && LOG.isDebugEnabled()) {
LOG.debug("Server certificate chain:");
for (int i = 0; i < certificates.length; i++) {
diff --git a/source/de/anomic/http/HttpClient.java b/source/de/anomic/http/HttpClient.java
index a9db3a94a..afd665ff6 100644
--- a/source/de/anomic/http/HttpClient.java
+++ b/source/de/anomic/http/HttpClient.java
@@ -88,10 +88,10 @@ public abstract class HttpClient {
* @param timeout in milliseconds
* @return
*/
- public static byte[] wget(final String uri, final httpHeader header, int timeout) {
+ public static byte[] wget(final String uri, final httpHeader header, final int timeout) {
return wget(uri, header, timeout, null);
}
- public static byte[] wget(final String uri, httpHeader header, final int timeout, final String vhost) {
+ public static byte[] wget(final String uri, final httpHeader header, final int timeout, final String vhost) {
assert uri != null : "precondition violated: uri != null";
addHostHeader(header, vhost);
final JakartaCommonsHttpClient client = new JakartaCommonsHttpClient(timeout, header, null);
diff --git a/source/de/anomic/http/HttpConnectionInfo.java b/source/de/anomic/http/HttpConnectionInfo.java
index cb3c18f13..3c5960534 100644
--- a/source/de/anomic/http/HttpConnectionInfo.java
+++ b/source/de/anomic/http/HttpConnectionInfo.java
@@ -158,14 +158,14 @@ public class HttpConnectionInfo {
try {
synchronized (allConnections) {
final int sizeBefore = allConnections.size();
- for(HttpConnectionInfo con: allConnections) {
+ for(final HttpConnectionInfo con: allConnections) {
if(con.getLifetime() > staleAfterMillis) {
allConnections.remove(con);
}
}
serverLog.logFine("HTTPC", "cleanUp ConnectionInfo removed "+ (sizeBefore - allConnections.size()));
}
- } catch (java.util.ConcurrentModificationException e) {
+ } catch (final java.util.ConcurrentModificationException e) {
serverLog.logWarning("HTTPC", "cleanUp ConnectionInfo interrupted by ConcurrentModificationException");
}
}
@@ -175,7 +175,7 @@ public class HttpConnectionInfo {
*/
@Override
public String toString() {
- StringBuilder string = new StringBuilder(50);
+ final StringBuilder string = new StringBuilder(50);
string.append("ID ");
string.append(getID());
string.append(", ");
diff --git a/source/de/anomic/http/httpChunkedInputStream.java b/source/de/anomic/http/httpChunkedInputStream.java
index 5ccef5e6a..6d42be802 100644
--- a/source/de/anomic/http/httpChunkedInputStream.java
+++ b/source/de/anomic/http/httpChunkedInputStream.java
@@ -56,7 +56,7 @@ public final class httpChunkedInputStream extends InputStream {
private boolean isClosed = false;
- public httpChunkedInputStream(InputStream in) {
+ public httpChunkedInputStream(final InputStream in) {
if (in == null)throw new IllegalArgumentException("InputStream must not be null");
@@ -78,7 +78,7 @@ public final class httpChunkedInputStream extends InputStream {
}
- public int read (byte[] b, int off, int len) throws IOException {
+ public int read (final byte[] b, final int off, int len) throws IOException {
if (this.isClosed) throw new IOException("Inputstream already closed.");
if (this.isEOF) return -1;
@@ -87,12 +87,12 @@ public final class httpChunkedInputStream extends InputStream {
if (this.isEOF) return -1;
}
len = Math.min(len, this.currChunkSize - this.currPos);
- int count = this.inputStream.read(b, off, len);
+ final int count = this.inputStream.read(b, off, len);
this.currPos += count;
return count;
}
- public int read (byte[] b) throws IOException {
+ public int read (final byte[] b) throws IOException {
return read(b, 0, b.length);
}
@@ -101,8 +101,8 @@ public final class httpChunkedInputStream extends InputStream {
* @throws IOException If an IO error occurs.
*/
private void readCRLF() throws IOException {
- int cr = this.inputStream.read();
- int lf = this.inputStream.read();
+ final int cr = this.inputStream.read();
+ final int lf = this.inputStream.read();
if ((cr != CR) || (lf != LF)) {
throw new IOException("Malformed chunk. CRLF expected but '" + cr + lf + "' found");
}
@@ -138,12 +138,12 @@ public final class httpChunkedInputStream extends InputStream {
if (bout.length() <= 2) break;
} while(true);
- ByteArrayInputStream bin = new ByteArrayInputStream(bout.getBytes());
+ final ByteArrayInputStream bin = new ByteArrayInputStream(bout.getBytes());
reader = new BufferedReader(new InputStreamReader(bin));
this.httpTrailer = httpHeader.readHttpHeader(reader);
} finally {
- if (reader != null) try {reader.close();}catch(Exception e){}
- if (bout != null) try {bout.close();}catch(Exception e){}
+ if (reader != null) try {reader.close();}catch(final Exception e){}
+ if (bout != null) try {bout.close();}catch(final Exception e){}
}
}
@@ -154,10 +154,10 @@ public final class httpChunkedInputStream extends InputStream {
private static int readChunkFromStream(final InputStream in)
throws IOException {
- serverByteBuffer baos = new serverByteBuffer();
+ final serverByteBuffer baos = new serverByteBuffer();
int state = READ_CHUNK_STATE_NORMAL;
while (state != READ_CHUNK_STATE_FINISHED) {
- int b = in.read();
+ final int b = in.read();
if (b == -1) throw new IOException("Malformed chunk. Unexpected end");
switch (state) {
@@ -202,7 +202,7 @@ public final class httpChunkedInputStream extends InputStream {
int result;
try {
result = Integer.parseInt(baos.toString().trim(), 16);
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
throw new IOException ("Malformed chunk. Bad chunk size: " + baos.toString());
}
return result;
@@ -222,8 +222,8 @@ public final class httpChunkedInputStream extends InputStream {
}
- static void exhaustInputStream(InputStream inStream) throws IOException {
- byte buffer[] = new byte[1024];
+ static void exhaustInputStream(final InputStream inStream) throws IOException {
+ final byte buffer[] = new byte[1024];
while (inStream.read(buffer) >= 0) {
}
}
diff --git a/source/de/anomic/http/httpChunkedOutputStream.java b/source/de/anomic/http/httpChunkedOutputStream.java
index 83be740cf..d96536260 100644
--- a/source/de/anomic/http/httpChunkedOutputStream.java
+++ b/source/de/anomic/http/httpChunkedOutputStream.java
@@ -36,7 +36,7 @@ import de.anomic.server.serverFileUtils;
public final class httpChunkedOutputStream extends FilterOutputStream {
private boolean finished = false;
- public httpChunkedOutputStream(OutputStream out) {
+ public httpChunkedOutputStream(final OutputStream out) {
super(out);
}
@@ -55,7 +55,7 @@ public final class httpChunkedOutputStream extends FilterOutputStream {
}
}
- public void write(byte[] b) throws IOException {
+ public void write(final byte[] b) throws IOException {
if (this.finished) throw new IOException("ChunkedOutputStream already finalized.");
if (b.length == 0) return;
@@ -66,7 +66,7 @@ public final class httpChunkedOutputStream extends FilterOutputStream {
this.out.flush();
}
- public void write(byte[] b, int off, int len) throws IOException {
+ public void write(final byte[] b, final int off, final int len) throws IOException {
if (this.finished) throw new IOException("ChunkedOutputStream already finalized.");
if (len == 0) return;
@@ -77,7 +77,7 @@ public final class httpChunkedOutputStream extends FilterOutputStream {
this.out.flush();
}
- public void write(serverByteBuffer b, int off, int len) throws IOException {
+ public void write(final serverByteBuffer b, final int off, final int len) throws IOException {
if (this.finished) throw new IOException("ChunkedOutputStream already finalized.");
if (len == 0) return;
@@ -88,9 +88,9 @@ public final class httpChunkedOutputStream extends FilterOutputStream {
this.out.flush();
}
- public void write(InputStream b) throws IOException {
+ public void write(final InputStream b) throws IOException {
if (this.finished) throw new IOException("ChunkedOutputStream already finalized.");
- int len = b.available();
+ final int len = b.available();
if (len == 0) return;
this.out.write(Integer.toHexString(len).getBytes());
@@ -100,7 +100,7 @@ public final class httpChunkedOutputStream extends FilterOutputStream {
this.out.flush();
}
- public void write(int b) throws IOException {
+ public void write(final int b) throws IOException {
if (this.finished) throw new IOException("ChunkedOutputStream already finalized.");
this.out.write("1".getBytes());
diff --git a/source/de/anomic/http/httpHeader.java b/source/de/anomic/http/httpHeader.java
index 5beaee2c0..41ac99cff 100644
--- a/source/de/anomic/http/httpHeader.java
+++ b/source/de/anomic/http/httpHeader.java
@@ -246,7 +246,7 @@ public final class httpHeader extends TreeMap<String, String> implements Map<Str
this(null);
}
- public httpHeader(HashMap<String, String> reverseMappingCache) {
+ public httpHeader(final HashMap<String, String> reverseMappingCache) {
// this creates a new TreeMap with a case insensitive mapping
// to provide a put-method that translates given keys into their
// 'proper' appearance, a translation cache is needed.
@@ -256,14 +256,14 @@ public final class httpHeader extends TreeMap<String, String> implements Map<Str
this.reverseMappingCache = reverseMappingCache;
}
- public httpHeader(HashMap<String, String> reverseMappingCache, File f) throws IOException {
+ public httpHeader(final HashMap<String, String> reverseMappingCache, final File f) throws IOException {
// creates also a case insensitive map and loads it initially
// with some values
super((Collator) insensitiveCollator.clone());
this.reverseMappingCache = reverseMappingCache;
// load with data
- BufferedReader br = new BufferedReader(new FileReader(f));
+ final BufferedReader br = new BufferedReader(new FileReader(f));
String line;
int pos;
while ((line = br.readLine()) != null) {
@@ -273,7 +273,7 @@ public final class httpHeader extends TreeMap<String, String> implements Map<Str
br.close();
}
- public httpHeader(HashMap<String, String> reverseMappingCache, Map<String, String> othermap) {
+ public httpHeader(final HashMap<String, String> reverseMappingCache, final Map<String, String> othermap) {
// creates a case insensitive map from another map
super((Collator) insensitiveCollator.clone());
this.reverseMappingCache = reverseMappingCache;
@@ -284,8 +284,8 @@ public final class httpHeader extends TreeMap<String, String> implements Map<Str
// we override the put method to make use of the reverseMappingCache
- public String put(String key, String value) {
- String upperK = key.toUpperCase();
+ public String put(final String key, final String value) {
+ final String upperK = key.toUpperCase();
if (reverseMappingCache == null) {
return super.put(key, value);
@@ -297,19 +297,19 @@ public final class httpHeader extends TreeMap<String, String> implements Map<Str
}
// we put in without a cached key and store the key afterwards
- String r = super.put(key, value);
+ final String r = super.put(key, value);
reverseMappingCache.put(upperK, key);
return r;
}
// to make the occurrence of multiple keys possible, we add them using a counter
- public String add(String key, String value) {
- int c = keyCount(key);
+ public String add(final String key, final String value) {
+ final int c = keyCount(key);
if (c == 0) return put(key, value);
return put("*" + key + "-" + c, value);
}
- public int keyCount(String key) {
+ public int keyCount(final String key) {
if (!(containsKey(key))) return 0;
int c = 1;
while (containsKey("*" + key + "-" + c)) c++;
@@ -317,31 +317,31 @@ public final class httpHeader extends TreeMap<String, String> implements Map<Str
}
// a convenience method to access the map with fail-over defaults
- public Object get(Object key, Object dflt) {
- Object result = get(key);
+ public Object get(final Object key, final Object dflt) {
+ final Object result = get(key);
if (result == null) return dflt;
return result;
}
// return multiple results
- public Object getSingle(Object key, int count) {
+ public Object getSingle(final Object key, final int count) {
if (count == 0) return get(key, null);
return get("*" + key + "-" + count, null);
}
- public Object[] getMultiple(String key) {
- int count = keyCount(key);
- Object[] result = new Object[count];
+ public Object[] getMultiple(final String key) {
+ final int count = keyCount(key);
+ final Object[] result = new Object[count];
for (int i = 0; i < count; i++) result[i] = getSingle(key, i);
return result;
}
// convenience methods for storing and loading to a file system
- public void store(File f) throws IOException {
+ public void store(final File f) throws IOException {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(f);
- Iterator<String> i = keySet().iterator();
+ final Iterator<String> i = keySet().iterator();
String key, value;
while (i.hasNext()) {
key = i.next();
@@ -350,7 +350,7 @@ public final class httpHeader extends TreeMap<String, String> implements Map<Str
}
fos.flush();
} finally {
- if (fos != null) try{fos.close();}catch(Exception e){}
+ if (fos != null) try{fos.close();}catch(final Exception e){}
}
}
@@ -367,7 +367,7 @@ public final class httpHeader extends TreeMap<String, String> implements Map<Str
Server=Apache/1.3.26
*/
- private Date headerDate(String kind) {
+ private Date headerDate(final String kind) {
if (containsKey(kind)) {
Date parsedDate = serverDate.parseHTTPDate(get(kind));
if (parsedDate == null) parsedDate = new Date();
@@ -382,8 +382,8 @@ public final class httpHeader extends TreeMap<String, String> implements Map<Str
public String refererHost() {
String refererHost = "";
- String referer = referer();
- if (referer.length() > 0) try { refererHost = (new URL(referer)).getHost(); } catch (MalformedURLException e) {}
+ final String referer = referer();
+ if (referer.length() > 0) try { refererHost = (new URL(referer)).getHost(); } catch (final MalformedURLException e) {}
return refererHost;
}
@@ -392,18 +392,18 @@ public final class httpHeader extends TreeMap<String, String> implements Map<Str
}
public String getCharacterEncoding() {
- String mimeType = mime();
+ final String mimeType = mime();
return extractCharsetFromMimetypeHeader(mimeType);
}
- public static String extractCharsetFromMimetypeHeader(String mimeType) {
+ public static String extractCharsetFromMimetypeHeader(final String mimeType) {
if (mimeType == null) return null;
- String[] parts = mimeType.split(";");
+ final String[] parts = mimeType.split(";");
if (parts == null || parts.length <= 1) return null;
for (int i=1; i < parts.length; i++) {
- String param = parts[i].trim();
+ final String param = parts[i].trim();
if (param.startsWith("charset=")) {
String charset = param.substring("charset=".length()).trim();
if (charset.startsWith("\"") || charset.startsWith("'")) charset = charset.substring(1);
@@ -433,7 +433,7 @@ public final class httpHeader extends TreeMap<String, String> implements Map<Str
public Object ifRange() {
if (containsKey(httpHeader.IF_RANGE)) {
- Date rangeDate = serverDate.parseHTTPDate(get(httpHeader.IF_RANGE));
+ final Date rangeDate = serverDate.parseHTTPDate(get(httpHeader.IF_RANGE));
if (rangeDate != null)
return rangeDate;
@@ -447,8 +447,8 @@ public final class httpHeader extends TreeMap<String, String> implements Map<Str
}
public long age() {
- Date lm = lastModified();
- Date sd = date();
+ final Date lm = lastModified();
+ final Date sd = date();
if (lm == null) return Long.MAX_VALUE;
return ((sd == null) ? new Date() : sd).getTime() - lm.getTime();
}
@@ -457,7 +457,7 @@ public final class httpHeader extends TreeMap<String, String> implements Map<Str
if (containsKey(httpHeader.CONTENT_LENGTH)) {
try {
return Long.parseLong(get(httpHeader.CONTENT_LENGTH));
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
return -1;
}
}
@@ -474,7 +474,7 @@ public final class httpHeader extends TreeMap<String, String> implements Map<Str
((get(httpHeader.CONTENT_ENCODING)).toUpperCase().startsWith("GZIP")));
}
- public static Object[] parseResponseLine(String respLine) {
+ public static Object[] parseResponseLine(final String respLine) {
if ((respLine == null) || (respLine.length() == 0)) {
return new Object[]{"HTTP/1.0",new Integer(500),"status line parse error"};
@@ -499,7 +499,7 @@ public final class httpHeader extends TreeMap<String, String> implements Map<Str
try {
statusCode = Integer.valueOf((p < 0) ? status.trim() : status.substring(0,p).trim());
statusText = (p < 0) ? "" : status.substring(p+1).trim();
- } catch (Exception e) {
+ } catch (final Exception e) {
statusCode = new Integer(500);
statusText = status;
}
@@ -507,20 +507,20 @@ public final class httpHeader extends TreeMap<String, String> implements Map<Str
return new Object[]{httpVer,statusCode,statusText};
}
- public static Properties parseRequestLine(String s, Properties prop, String virtualHost) {
- int p = s.indexOf(" ");
+ public static Properties parseRequestLine(final String s, final Properties prop, final String virtualHost) {
+ final int p = s.indexOf(" ");
if (p >= 0) {
- String cmd = s.substring(0,p);
- String args = s.substring(p+1);
+ final String cmd = s.substring(0,p);
+ final String args = s.substring(p+1);
return parseRequestLine(cmd,args, prop,virtualHost);
}
return prop;
}
- public static Properties parseRequestLine(String cmd, String args, Properties prop, String virtualHost) {
+ public static Properties parseRequestLine(final String cmd, String args, final Properties prop, final String virtualHost) {
// getting the last request line for debugging purposes
- String prevRequestLine = prop.containsKey(CONNECTION_PROP_REQUESTLINE)?
+ final String prevRequestLine = prop.containsKey(CONNECTION_PROP_REQUESTLINE)?
prop.getProperty(CONNECTION_PROP_REQUESTLINE) : "";
// reset property from previous run
@@ -589,7 +589,7 @@ public final class httpHeader extends TreeMap<String, String> implements Map<Str
} else {
// THIS IS THE "GOOD" CASE
// a perfect formulated url
- String dstHostSocket = args.substring(0, sep);
+ final String dstHostSocket = args.substring(0, sep);
prop.setProperty(CONNECTION_PROP_HOST, (httpd.isThisHostName(dstHostSocket)?virtualHost:dstHostSocket));
path = args.substring(sep); // yes, including beginning "/"
}
@@ -615,7 +615,7 @@ public final class httpHeader extends TreeMap<String, String> implements Map<Str
String ext = ""; // default when no file extension
sep = path.lastIndexOf(".");
if (sep >= 0) {
- int ancpos = path.indexOf("#", sep + 1);
+ final int ancpos = path.indexOf("#", sep + 1);
if (ancpos >= sep) {
// ex: /foo/bar.html#xy => html
ext = path.substring(sep + 1, ancpos).toLowerCase();
@@ -629,9 +629,9 @@ public final class httpHeader extends TreeMap<String, String> implements Map<Str
return prop;
}
- public static boolean supportChunkedEncoding(Properties conProp) {
+ public static boolean supportChunkedEncoding(final Properties conProp) {
// getting the http version of the client
- String httpVer = conProp.getProperty(CONNECTION_PROP_HTTP_VER);
+ final String httpVer = conProp.getProperty(CONNECTION_PROP_HTTP_VER);
// only clients with http version 1.1 supports chunk
return !(httpVer.equals(HTTP_VERSION_0_9) || httpVer.equals(HTTP_VERSION_1_0));
@@ -643,9 +643,9 @@ public final class httpHeader extends TreeMap<String, String> implements Map<Str
* @return a {@link httpHeader}-Object containing all parsed headers
* @throws IOException
*/
- public static httpHeader readHttpHeader(BufferedReader reader) throws IOException {
+ public static httpHeader readHttpHeader(final BufferedReader reader) throws IOException {
// reading all request headers
- httpHeader httpHeader = new httpHeader(httpd.reverseMappingCache);
+ final httpHeader httpHeader = new httpHeader(httpd.reverseMappingCache);
int p;
String line;
while ((line = reader.readLine()) != null) {
@@ -658,10 +658,10 @@ public final class httpHeader extends TreeMap<String, String> implements Map<Str
return httpHeader;
}
- public static httpHeader readHeader(Properties prop, serverCore.Session theSession) throws IOException {
+ public static httpHeader readHeader(final Properties prop, final serverCore.Session theSession) throws IOException {
// reading all headers
- httpHeader header = new httpHeader(httpd.reverseMappingCache);
+ final httpHeader header = new httpHeader(httpd.reverseMappingCache);
int p;
String line;
while ((line = theSession.readLineAsString()) != null) {
@@ -676,7 +676,7 @@ public final class httpHeader extends TreeMap<String, String> implements Map<Str
/*
* doing some header validation here ...
*/
- String httpVersion = prop.getProperty(httpHeader.CONNECTION_PROP_HTTP_VER, "HTTP/0.9");
+ final String httpVersion = prop.getProperty(httpHeader.CONNECTION_PROP_HTTP_VER, "HTTP/0.9");
if (httpVersion.equals("HTTP/1.1") && !header.containsKey(httpHeader.HOST)) {
// the HTTP/1.1 specification requires that an HTTP/1.1 server must reject any
// HTTP/1.1 message that does not contain a Host header.
@@ -689,11 +689,11 @@ public final class httpHeader extends TreeMap<String, String> implements Map<Str
public StringBuffer toHeaderString(
- String httpVersion,
- int httpStatusCode,
- String httpStatusText) {
+ final String httpVersion,
+ final int httpStatusCode,
+ final String httpStatusText) {
// creating a new buffer to store the header as string
- StringBuffer theHeader = new StringBuffer();
+ final StringBuffer theHeader = new StringBuffer();
// generating the header string
this.toHeaderString(httpVersion,httpStatusCode,httpStatusText,theHeader);
@@ -705,9 +705,9 @@ public final class httpHeader extends TreeMap<String, String> implements Map<Str
public void toHeaderString(
String httpVersion,
- int httpStatusCode,
+ final int httpStatusCode,
String httpStatusText,
- StringBuffer theHeader) {
+ final StringBuffer theHeader) {
if (theHeader == null) throw new IllegalArgumentException();
@@ -730,7 +730,7 @@ public final class httpHeader extends TreeMap<String, String> implements Map<Str
.append(httpStatusText).append("\r\n");
// write header
- Iterator<String> i = keySet().iterator();
+ final Iterator<String> i = keySet().iterator();
String key;
char tag;
int count;
@@ -748,10 +748,10 @@ public final class httpHeader extends TreeMap<String, String> implements Map<Str
theHeader.append("\r\n");
}
- public static yacyURL getRequestURL(Properties conProp) throws MalformedURLException {
+ public static yacyURL getRequestURL(final Properties conProp) throws MalformedURLException {
String host = conProp.getProperty(httpHeader.CONNECTION_PROP_HOST);
- String path = conProp.getProperty(httpHeader.CONNECTION_PROP_PATH); // always starts with leading '/'
- String args = conProp.getProperty(httpHeader.CONNECTION_PROP_ARGS); // may be null if no args were given
+ final String path = conProp.getProperty(httpHeader.CONNECTION_PROP_PATH); // always starts with leading '/'
+ final String args = conProp.getProperty(httpHeader.CONNECTION_PROP_ARGS); // may be null if no args were given
//String ip = conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP); // the ip from the connecting peer
int port, pos;
@@ -762,11 +762,11 @@ public final class httpHeader extends TreeMap<String, String> implements Map<Str
host = host.substring(0, pos);
}
- yacyURL url = new yacyURL("http", host, port, (args == null) ? path : path + "?" + args);
+ final yacyURL url = new yacyURL("http", host, port, (args == null) ? path : path + "?" + args);
return url;
}
- public static void handleTransparentProxySupport(httpHeader header, Properties prop, String virtualHost, boolean isTransparentProxy) {
+ public static void handleTransparentProxySupport(final httpHeader header, final Properties prop, final String virtualHost, final boolean isTransparentProxy) {
// transparent proxy support is only available for http 1.0 and above connections
if (prop.getProperty(CONNECTION_PROP_HTTP_VER, "HTTP/0.9").equals("HTTP/0.9")) return;
@@ -778,7 +778,7 @@ public final class httpHeader extends TreeMap<String, String> implements Map<Str
if (!prop.getProperty(CONNECTION_PROP_HOST).equals(virtualHost)) return;
// TODO: we could have problems with connections from extern here ...
- String dstHostSocket = header.get(httpHeader.HOST);
+ final String dstHostSocket = header.get(httpHeader.HOST);
prop.setProperty(CONNECTION_PROP_HOST,(httpd.isThisHostName(dstHostSocket)?virtualHost:dstHostSocket));
}
/*
@@ -799,9 +799,9 @@ public final class httpHeader extends TreeMap<String, String> implements Map<Str
* Implementation of Map.Entry. Structure that hold two values - exactly what we need!
*/
class Entry implements Map.Entry<String, String> {
- private String k;
+ private final String k;
private String v;
- Entry(String k, String v) {
+ Entry(final String k, final String v) {
this.k = k;
this.v = v;
}
@@ -811,8 +811,8 @@ public final class httpHeader extends TreeMap<String, String> implements Map<Str
public String getValue() {
return v;
}
- public String setValue(String v) {
- String r = this.v;
+ public String setValue(final String v) {
+ final String r = this.v;
this.v = v;
return r;
}
@@ -829,7 +829,7 @@ public final class httpHeader extends TreeMap<String, String> implements Map<Str
* @param secure If true cookie will be send only over safe connection such as https
* @see further documentation: <a href="http://docs.sun.com/source/816-6408-10/cookies.htm">docs.sun.com</a>
*/
- public void setCookie(String name, String value, String expires, String path, String domain, boolean secure)
+ public void setCookie(final String name, final String value, final String expires, final String path, final String domain, final boolean secure)
{
/*
* TODO:Here every value can be validated for correctness if needed
@@ -855,7 +855,7 @@ public final class httpHeader extends TreeMap<String, String> implements Map<Str
* Note: this cookie will be sent over each connection independend if it is safe connection or not.
* @see further documentation: <a href="http://docs.sun.com/source/816-6408-10/cookies.htm">docs.sun.com</a>
*/
- public void setCookie(String name, String value, String expires, String path, String domain)
+ public void setCookie(final String name, final String value, final String expires, final String path, final String domain)
{
setCookie( name, value, expires, path, domain, false);
}
@@ -870,7 +870,7 @@ public final class httpHeader extends TreeMap<String, String> implements Map<Str
* Note: this cookie will be sent over each connection independend if it is safe connection or not.
* @see further documentation: <a href="http://docs.sun.com/source/816-6408-10/cookies.htm">docs.sun.com</a>
*/
- public void setCookie(String name, String value, String expires, String path)
+ public void setCookie(final String name, final String value, final String expires, final String path)
{
setCookie( name, value, expires, path, null, false);
}
@@ -884,7 +884,7 @@ public final class httpHeader extends TreeMap<String, String> implements Map<Str
* Note: this cookie will be sent over each connection independend if it is safe connection or not.
* @see further documentation: <a href="http://docs.sun.com/source/816-6408-10/cookies.htm">docs.sun.com</a>
*/
- public void setCookie(String name, String value, String expires)
+ public void setCookie(final String name, final String value, final String expires)
{
setCookie( name, value, expires, null, null, false);
}
@@ -897,15 +897,15 @@ public final class httpHeader extends TreeMap<String, String> implements Map<Str
* Note: this cookie will be sent over each connection independend if it is safe connection or not. This cookie never expires
* @see further documentation: <a href="http://docs.sun.com/source/816-6408-10/cookies.htm">docs.sun.com</a>
*/
- public void setCookie(String name, String value )
+ public void setCookie(final String name, final String value )
{
setCookie( name, value, null, null, null, false);
}
public String getHeaderCookies(){
- Iterator<Map.Entry<String, String>> it = this.entrySet().iterator();
+ final Iterator<Map.Entry<String, String>> it = this.entrySet().iterator();
while(it.hasNext())
{
- Map.Entry<String, String> e = it.next();
+ final Map.Entry<String, String> e = it.next();
//System.out.println(""+e.getKey()+" : "+e.getValue());
if(e.getKey().equals("Cookie"))
{
@@ -917,7 +917,7 @@ public final class httpHeader extends TreeMap<String, String> implements Map<Str
public Vector<Entry> getCookieVector(){
return cookies;
}
- public void setCookieVector(Vector<Entry> mycookies){
+ public void setCookieVector(final Vector<Entry> mycookies){
cookies=mycookies;
}
/**
diff --git a/source/de/anomic/http/httpRemoteProxyConfig.java b/source/de/anomic/http/httpRemoteProxyConfig.java
index 869707316..a75f62a30 100644
--- a/source/de/anomic/http/httpRemoteProxyConfig.java
+++ b/source/de/anomic/http/httpRemoteProxyConfig.java
@@ -110,10 +110,10 @@ public final class httpRemoteProxyConfig {
}
public static httpRemoteProxyConfig init(
- String proxyHostName,
- int proxyHostPort
+ final String proxyHostName,
+ final int proxyHostPort
) {
- httpRemoteProxyConfig newConfig = new httpRemoteProxyConfig();
+ final httpRemoteProxyConfig newConfig = new httpRemoteProxyConfig();
newConfig.remoteProxyUse = true;
newConfig.remoteProxyUse4SSL = true;
@@ -127,8 +127,8 @@ public final class httpRemoteProxyConfig {
return newConfig;
}
- public static httpRemoteProxyConfig init(plasmaSwitchboard sb) {
- httpRemoteProxyConfig newConfig = new httpRemoteProxyConfig();
+ public static httpRemoteProxyConfig init(final plasmaSwitchboard sb) {
+ final httpRemoteProxyConfig newConfig = new httpRemoteProxyConfig();
// determining if remote proxy usage is enabled
newConfig.remoteProxyUse = sb.getConfig("remoteProxyUse", "false").equalsIgnoreCase("true");
@@ -148,7 +148,7 @@ public final class httpRemoteProxyConfig {
// reading the proxy host port
try {
newConfig.remoteProxyPort = Integer.parseInt(sb.getConfig("remoteProxyPort", "3128"));
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
newConfig.remoteProxyPort = 3128;
}
diff --git a/source/de/anomic/http/httpSSI.java b/source/de/anomic/http/httpSSI.java
index 4cae78c22..64ca09463 100644
--- a/source/de/anomic/http/httpSSI.java
+++ b/source/de/anomic/http/httpSSI.java
@@ -35,14 +35,14 @@ import de.anomic.server.serverByteBuffer;
public class httpSSI {
- public static void writeSSI(serverByteBuffer in, OutputStream out, String authorization, String requesthost) throws IOException {
+ public static void writeSSI(final serverByteBuffer in, final OutputStream out, final String authorization, final String requesthost) throws IOException {
writeSSI(in, 0, out, authorization, requesthost);
}
- public static void writeSSI(serverByteBuffer in, int off, OutputStream out, String authorization, String requesthost) throws IOException {
- int p = in.indexOf("<!--#".getBytes(), off);
+ public static void writeSSI(final serverByteBuffer in, final int off, final OutputStream out, final String authorization, final String requesthost) throws IOException {
+ final int p = in.indexOf("<!--#".getBytes(), off);
if (p >= 0) {
- int q = in.indexOf("-->".getBytes(), p + 10);
+ final int q = in.indexOf("-->".getBytes(), p + 10);
if (out instanceof httpChunkedOutputStream) {
((httpChunkedOutputStream) out).write(in, off, p - off);
} else {
@@ -59,28 +59,28 @@ public class httpSSI {
}
}
- private static void parseSSI(serverByteBuffer in, int off, int len, OutputStream out, String authorization, String requesthost) {
+ private static void parseSSI(final serverByteBuffer in, final int off, final int len, final OutputStream out, final String authorization, final String requesthost) {
if (in.startsWith("<!--#include virtual=\"".getBytes(), off)) {
- int q = in.indexOf("\"".getBytes(), off + 22);
+ final int q = in.indexOf("\"".getBytes(), off + 22);
if (q > 0) {
- String path = in.toString(off + 22, q);
+ final String path = in.toString(off + 22, q);
writeContent(path, out, authorization, requesthost);
}
}
}
- private static void writeContent(String path, OutputStream out, String authorization, String requesthost) {
+ private static void writeContent(String path, final OutputStream out, final String authorization, final String requesthost) {
// check if there are arguments in path string
String args = "";
- int argpos = path.indexOf('?');
+ final int argpos = path.indexOf('?');
if (argpos > 0) {
args = path.substring(argpos + 1);
path = path.substring(0, argpos);
}
// set up virtual connection properties to call httpdFileHander.doGet()
- Properties conProp = new Properties();
- httpHeader header = new httpHeader(httpd.reverseMappingCache);
+ final Properties conProp = new Properties();
+ final httpHeader header = new httpHeader(httpd.reverseMappingCache);
conProp.setProperty(httpHeader.CONNECTION_PROP_METHOD, httpHeader.METHOD_GET);
conProp.setProperty(httpHeader.CONNECTION_PROP_PATH, path);
conProp.setProperty(httpHeader.CONNECTION_PROP_ARGS, args);
diff --git a/source/de/anomic/http/httpTemplate.java b/source/de/anomic/http/httpTemplate.java
index 55d8e3f9c..aa1548b2e 100644
--- a/source/de/anomic/http/httpTemplate.java
+++ b/source/de/anomic/http/httpTemplate.java
@@ -156,22 +156,22 @@ public final class httpTemplate {
new Object[] {iOpen, iClose}
};
- public static serverByteBuffer[] splitQuotations(serverByteBuffer text) {
- List<serverByteBuffer> l = splitQuotation(text, 0);
- serverByteBuffer[] sbbs = new serverByteBuffer[l.size()];
+ public static serverByteBuffer[] splitQuotations(final serverByteBuffer text) {
+ final List<serverByteBuffer> l = splitQuotation(text, 0);
+ final serverByteBuffer[] sbbs = new serverByteBuffer[l.size()];
for (int i = 0; i < l.size(); i++) sbbs[i] = l.get(i);
return sbbs;
}
public static List<serverByteBuffer> splitQuotation(serverByteBuffer text, int qoff) {
- ArrayList<serverByteBuffer> l = new ArrayList<serverByteBuffer>();
+ final ArrayList<serverByteBuffer> l = new ArrayList<serverByteBuffer>();
if (qoff >= meta_quotation.length) {
if (text.length() > 0) l.add(text);
return l;
}
int p = -1, q;
- byte[] left = (byte[]) ((Object[]) meta_quotation[qoff])[0];
- byte[] right = (byte[]) ((Object[]) meta_quotation[qoff])[1];
+ final byte[] left = (byte[]) ((Object[]) meta_quotation[qoff])[0];
+ final byte[] right = (byte[]) ((Object[]) meta_quotation[qoff])[1];
qoff++;
while ((text.length() > 0) && ((p = text.indexOf(left)) >= 0)) {
q = text.indexOf(right, p + 1);
@@ -205,7 +205,7 @@ public final class httpTemplate {
* transfer until a specified pattern is found; everything but the pattern is transfered so far
* the function returns true, if the pattern is found
*/
- private static boolean transferUntil(PushbackInputStream i, OutputStream o, byte[] pattern) throws IOException {
+ private static boolean transferUntil(final PushbackInputStream i, final OutputStream o, final byte[] pattern) throws IOException {
int b, bb;
boolean equal;
while ((b = i.read()) > 0) {
@@ -228,21 +228,21 @@ public final class httpTemplate {
return false;
}
- public static void writeTemplate(InputStream in, OutputStream out, HashMap<String, String> pattern, byte[] dflt) throws IOException {
+ public static void writeTemplate(final InputStream in, final OutputStream out, final HashMap<String, String> pattern, final byte[] dflt) throws IOException {
writeTemplate(in, out, pattern, dflt, new byte[0]);
}
/**
* Reads a input stream, and writes the data with replaced templates on a output stream
*/
- public static byte[] writeTemplate(InputStream in, OutputStream out, HashMap<String, String> pattern, byte[] dflt, byte[] prefix) throws IOException {
- PushbackInputStream pis = new PushbackInputStream(in, 100);
+ public static byte[] writeTemplate(final InputStream in, final OutputStream out, final HashMap<String, String> pattern, final byte[] dflt, final byte[] prefix) throws IOException {
+ final PushbackInputStream pis = new PushbackInputStream(in, 100);
ByteArrayOutputStream keyStream;
byte[] key;
byte[] multi_key;
byte[] replacement;
int bb;
- serverByteBuffer structure=new serverByteBuffer();
+ final serverByteBuffer structure=new serverByteBuffer();
while (transferUntil(pis, out, hasha)) {
bb = pis.read();
@@ -273,13 +273,13 @@ public final class httpTemplate {
pis.unread(bb);
}
- byte[] text=keyStream.toByteArray(); //text between #{key}# an #{/key}#
+ final byte[] text=keyStream.toByteArray(); //text between #{key}# an #{/key}#
int num=0;
- String patternKey = getPatternKey(prefix, multi_key);
+ final String patternKey = getPatternKey(prefix, multi_key);
if(pattern.containsKey(patternKey) && pattern.get(patternKey) != null){
try{
num=Integer.parseInt(pattern.get(patternKey)); // Key contains the iteration number as string
- }catch(NumberFormatException e){
+ }catch(final NumberFormatException e){
num=0;
}
//System.out.println(multi_key + ": " + num); //DEBUG
@@ -292,7 +292,7 @@ public final class httpTemplate {
.append(Integer.toString(num).getBytes("UTF-8"))
.append("\">\n".getBytes("UTF-8"));
for(int i=0;i < num;i++ ){
- PushbackInputStream pis2 = new PushbackInputStream(new ByteArrayInputStream(text));
+ final PushbackInputStream pis2 = new PushbackInputStream(new ByteArrayInputStream(text));
//System.out.println("recursing with text(prefix="+ multi_key + "_" + i + "_" +"):"); //DEBUG
//System.out.println(text);
structure.append(writeTemplate(pis2, out, pattern, dflt, newPrefix(prefix,multi_key,i)));
@@ -304,7 +304,7 @@ public final class httpTemplate {
}
}else if( (bb & 0xFF) == lrbr ){ //alternatives
int others=0;
- serverByteBuffer text= new serverByteBuffer();
+ final serverByteBuffer text= new serverByteBuffer();
PushbackInputStream pis2;
transferUntil(pis, keyStream, aClose);
@@ -323,12 +323,12 @@ public final class httpTemplate {
boolean byName=false;
int whichPattern=0;
byte[] patternName = new byte[0];
- String patternKey = getPatternKey(prefix, key);
+ final String patternKey = getPatternKey(prefix, key);
if(pattern.containsKey(patternKey) && pattern.get(patternKey) != null){
- String patternId=pattern.get(patternKey);
+ final String patternId=pattern.get(patternKey);
try{
whichPattern=Integer.parseInt(patternId); //index
- }catch(NumberFormatException e){
+ }catch(final NumberFormatException e){
whichPattern=0;
byName=true;
patternName=patternId.getBytes("UTF-8");
@@ -416,7 +416,7 @@ public final class httpTemplate {
if (transferUntil(pis, keyStream, pClose)) {
// pattern detected, write replacement
key = keyStream.toByteArray();
- String patternKey = getPatternKey(prefix, key);
+ final String patternKey = getPatternKey(prefix, key);
replacement = replacePattern(patternKey, pattern, dflt); //replace
structure.append("<".getBytes("UTF-8")).append(key).append(" type=\"normal\">\n".getBytes("UTF-8"));
structure.append(replacement);
@@ -437,15 +437,15 @@ public final class httpTemplate {
return structure.getBytes();
}
}else if( (bb & 0xFF) == ps){ //include
- serverByteBuffer include = new serverByteBuffer();
+ final serverByteBuffer include = new serverByteBuffer();
keyStream = new ByteArrayOutputStream(); //reset stream
if(transferUntil(pis, keyStream, iClose)){
byte[] filename = keyStream.toByteArray();
//if(filename.startsWith( Character.toString((char)lbr) ) && filename.endsWith( Character.toString((char)rbr) )){ //simple pattern for filename
if((filename[0] == lbr) && (filename[filename.length-1] == rbr)){ //simple pattern for filename
- byte[] newFilename = new byte[filename.length-2];
+ final byte[] newFilename = new byte[filename.length-2];
System.arraycopy(filename, 1, newFilename, 0, newFilename.length);
- String patternkey = getPatternKey(prefix, newFilename);
+ final String patternkey = getPatternKey(prefix, newFilename);
filename= replacePattern(patternkey, pattern, dflt);
}
if (filename.length > 0 && !java.util.Arrays.equals(filename, dflt)) {
@@ -458,20 +458,20 @@ public final class httpTemplate {
while( (line = br.readLine()) != null ){
include.append(line.getBytes("UTF-8")).append(de.anomic.server.serverCore.CRLF_STRING.getBytes("UTF-8"));
}
- } catch (IOException e) {
+ } catch (final IOException e) {
//file not found?
serverLog.logSevere("FILEHANDLER","Include Error with file " + new String(filename, "UTF-8") + ": " + e.getMessage());
} finally {
- if (br != null) try { br.close(); br=null; } catch (Exception e) {}
+ if (br != null) try { br.close(); br=null; } catch (final Exception e) {}
}
- PushbackInputStream pis2 = new PushbackInputStream(new ByteArrayInputStream(include.getBytes()));
+ final PushbackInputStream pis2 = new PushbackInputStream(new ByteArrayInputStream(include.getBytes()));
structure.append("<fileinclude file=\"".getBytes("UTF-8")).append(filename).append(">\n".getBytes("UTF-8"));
structure.append(writeTemplate(pis2, out, pattern, dflt, prefix));
structure.append("</fileinclude>\n".getBytes("UTF-8"));
}
}
}else{ //no match, but a single hash (output # + bb)
- byte[] tmp=new byte[2];
+ final byte[] tmp=new byte[2];
tmp[0]=hash;
tmp[1]=(byte)bb;
serverFileUtils.copy(tmp, out);
@@ -481,7 +481,7 @@ public final class httpTemplate {
return structure.getBytes();
}
- public static byte[] replacePattern(String key, HashMap<String, String> pattern, byte dflt[]) {
+ public static byte[] replacePattern(final String key, final HashMap<String, String> pattern, final byte dflt[]) {
byte[] replacement;
Object value;
if (pattern.containsKey(key)) {
@@ -496,7 +496,7 @@ public final class httpTemplate {
//replacement = value.toString().getBytes();
replacement = value.toString().getBytes("UTF-8");
}
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
replacement = dflt;
}
} else {
@@ -505,15 +505,15 @@ public final class httpTemplate {
return replacement;
}
- public static void main(String[] args) {
+ public static void main(final String[] args) {
// arg1 = test input; arg2 = replacement for pattern 'test'; arg3 = default replacement
try {
- InputStream i = new ByteArrayInputStream(args[0].getBytes());
- HashMap<String, String> h = new HashMap<String, String>();
+ final InputStream i = new ByteArrayInputStream(args[0].getBytes());
+ final HashMap<String, String> h = new HashMap<String, String>();
h.put("test", args[1]);
writeTemplate(new PushbackInputStream(i, 100), System.out, h, args[2].getBytes());
System.out.flush();
- } catch (Exception e) {
+ } catch (final Exception e) {
e.printStackTrace();
}
}
@@ -523,32 +523,32 @@ public final class httpTemplate {
public static HashMap<String, String> loadTemplates(File path) {
// reads all templates from a path
// we use only the folder from the given file path
- HashMap<String, String> result = new HashMap<String, String>();
+ final HashMap<String, String> result = new HashMap<String, String>();
if (path == null) return result;
if (!(path.isDirectory())) path = path.getParentFile();
if ((path == null) || (!(path.isDirectory()))) return result;
- String[] templates = path.list();
+ final String[] templates = path.list();
for (int i = 0; i < templates.length; i++) {
if (templates[i].endsWith(".template"))
try {
//System.out.println("TEMPLATE " + templates[i].substring(0, templates[i].length() - 9) + ": " + new String(buf, 0, c));
result.put(templates[i].substring(0, templates[i].length() - 9),
new String(serverFileUtils.read(new File(path, templates[i]))));
- } catch (Exception e) {}
+ } catch (final Exception e) {}
}
return result;
}
- public static byte[] newPrefix(byte[] oldPrefix, byte[] key) {
- serverByteBuffer newPrefix = new serverByteBuffer();
+ public static byte[] newPrefix(final byte[] oldPrefix, final byte[] key) {
+ final serverByteBuffer newPrefix = new serverByteBuffer();
newPrefix.append(oldPrefix)
.append(key)
.append("_".getBytes());
return newPrefix.getBytes();
}
- public static byte[] newPrefix(byte[] oldPrefix, byte[] multi_key, int i) {
- serverByteBuffer newPrefix = new serverByteBuffer();
+ public static byte[] newPrefix(final byte[] oldPrefix, final byte[] multi_key, final int i) {
+ final serverByteBuffer newPrefix = new serverByteBuffer();
try {
newPrefix.append(oldPrefix)
.append(multi_key)
@@ -556,23 +556,23 @@ public final class httpTemplate {
.append(Integer.toString(i).getBytes("UTF-8"))
.append("_".getBytes());
- } catch (UnsupportedEncodingException e) {}
+ } catch (final UnsupportedEncodingException e) {}
return newPrefix.getBytes();
}
- public static String getPatternKey(byte[] prefix, byte[] key) {
- serverByteBuffer patternKey = new serverByteBuffer();
+ public static String getPatternKey(final byte[] prefix, final byte[] key) {
+ final serverByteBuffer patternKey = new serverByteBuffer();
patternKey.append(prefix)
.append(key);
try {
return new String(patternKey.getBytes(),"UTF-8");
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
return null;
}
}
- public static byte[] appendBytes(byte[] b1, byte[] b2, byte[] b3, byte[] b4) {
- serverByteBuffer byteArray = new serverByteBuffer();
+ public static byte[] appendBytes(final byte[] b1, final byte[] b2, final byte[] b3, final byte[] b4) {
+ final serverByteBuffer byteArray = new serverByteBuffer();
byteArray.append(b1)
.append(b2);
if (b3 != null) byteArray.append(b3);
diff --git a/source/de/anomic/http/httpd.java b/source/de/anomic/http/httpd.java
index c8f0311ca..0902716bd 100644
--- a/source/de/anomic/http/httpd.java
+++ b/source/de/anomic/http/httpd.java
@@ -35,6 +35,7 @@ import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.MalformedURLException;
+import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Date;
@@ -129,7 +130,7 @@ public final class httpd implements serverHandler {
private final serverLog log = new serverLog("HTTPD");
// class methods
- public httpd(serverSwitch<?> s) {
+ public httpd(final serverSwitch<?> s) {
// handler info
httpd.switchboard = (plasmaSwitchboard)s;
httpd.virtualHost = switchboard.getConfig("fileHost","localhost");
@@ -172,7 +173,7 @@ public final class httpd implements serverHandler {
* Must be called at least once, but can be called again to re-use the object.
* @see de.anomic.server.serverHandler#initSession(de.anomic.server.serverCore.Session)
*/
- public void initSession(serverCore.Session newsession) throws IOException {
+ public void initSession(final serverCore.Session newsession) throws IOException {
this.session = newsession;
this.userAddress = session.userAddress; // client InetAddress
this.clientIP = this.userAddress.getHostAddress();
@@ -197,10 +198,10 @@ public final class httpd implements serverHandler {
this.serverAccountBase64MD5 = null;
}
- private static boolean match(String key, String latch) {
+ private static boolean match(final String key, final String latch) {
// the latch is a comma-separated list of patterns
// each pattern may contain one wildcard-character '*' which matches anything
- StringTokenizer st = new StringTokenizer(latch,",");
+ final StringTokenizer st = new StringTokenizer(latch,",");
String pattern;
while (st.hasMoreTokens()) {
pattern = st.nextToken();
@@ -226,11 +227,11 @@ public final class httpd implements serverHandler {
return null;
}
- public String error(Throwable e) { // OBLIGATORIC FUNCTION
+ public String error(final Throwable e) { // OBLIGATORIC FUNCTION
// return string in case of any error that occurs during communication
// is always (but not only) called if an IO-dependent exception occurrs.
this.log.logSevere("Unexpected Error. " + e.getClass().getName(),e);
- String message = e.getMessage();
+ final String message = e.getMessage();
if (message.indexOf("heap space") > 0) e.printStackTrace();
return "501 Exception occurred: " + message;
}
@@ -240,7 +241,7 @@ public final class httpd implements serverHandler {
* @param header the received http-headers
* @return <code>true</code> if a persistent connection was requested or <code>false</code> otherwise
*/
- private boolean handlePersistentConnection(httpHeader header) {
+ private boolean handlePersistentConnection(final httpHeader header) {
if (!keepAliveSupport) {
this.prop.put(httpHeader.CONNECTION_PROP_PERSISTENT,"close");
@@ -248,7 +249,7 @@ public final class httpd implements serverHandler {
}
// getting the http version that is used by the client
- String httpVersion = this.prop.getProperty(httpHeader.CONNECTION_PROP_HTTP_VER, "HTTP/0.9");
+ final String httpVersion = this.prop.getProperty(httpHeader.CONNECTION_PROP_HTTP_VER, "HTTP/0.9");
// managing keep-alive: in HTTP/0.9 and HTTP/1.0 every connection is closed
// afterwards. In HTTP/1.1 (and above, in the future?) connections are
@@ -260,10 +261,10 @@ public final class httpd implements serverHandler {
persistent = false;
}
- String transferEncoding = (String) header.get(httpHeader.TRANSFER_ENCODING, "identity");
- boolean isPostRequest = this.prop.getProperty(httpHeader.CONNECTION_PROP_METHOD).equals(httpHeader.METHOD_POST);
- boolean hasContentLength = header.containsKey(httpHeader.CONTENT_LENGTH);
- boolean hasTransferEncoding = header.containsKey(httpHeader.TRANSFER_ENCODING) && !transferEncoding.equalsIgnoreCase("identity");
+ final String transferEncoding = (String) header.get(httpHeader.TRANSFER_ENCODING, "identity");
+ final boolean isPostRequest = this.prop.getProperty(httpHeader.CONNECTION_PROP_METHOD).equals(httpHeader.METHOD_POST);
+ final boolean hasContentLength = header.containsKey(httpHeader.CONTENT_LENGTH);
+ final boolean hasTransferEncoding = header.containsKey(httpHeader.TRANSFER_ENCODING) && !transferEncoding.equalsIgnoreCase("identity");
// if the request does not contain a content-length we have to close the connection
// independently of the value of the connection header
@@ -274,26 +275,26 @@ public final class httpd implements serverHandler {
return persistent;
}
- public static int staticAdminAuthenticated(String authorization, serverSwitch<?> sw) {
+ public static int staticAdminAuthenticated(final String authorization, final serverSwitch<?> sw) {
// the authorization string must be given with the truncated 6 bytes at the beginning
if (authorization == null) return 1;
//if (authorization.length() < 6) return 1; // no authentication information given
- String adminAccountBase64MD5 = sw.getConfig(ADMIN_ACCOUNT_B64MD5, "");
+ final String adminAccountBase64MD5 = sw.getConfig(ADMIN_ACCOUNT_B64MD5, "");
if (adminAccountBase64MD5.length() == 0) return 2; // no password stored
if (adminAccountBase64MD5.equals(serverCodings.encodeMD5Hex(authorization))) return 4; // hard-authenticated, all ok
return 1;
}
- private boolean handleServerAuthentication(httpHeader header) throws IOException {
+ private boolean handleServerAuthentication(final httpHeader header) throws IOException {
// getting the http version that is used by the client
- String httpVersion = this.prop.getProperty(httpHeader.CONNECTION_PROP_HTTP_VER, "HTTP/0.9");
+ final String httpVersion = this.prop.getProperty(httpHeader.CONNECTION_PROP_HTTP_VER, "HTTP/0.9");
// reading the authentication settings from switchboard
if (this.serverAccountBase64MD5 == null)
this.serverAccountBase64MD5 = switchboard.getConfig("serverAccountBase64MD5", "");
if (this.serverAccountBase64MD5.length() > 0) {
- String auth = header.get(httpHeader.AUTHORIZATION);
+ final String auth = header.get(httpHeader.AUTHORIZATION);
if (auth == null) {
// authorization requested, but no authorizeation given in header. Ask for authenticate:
this.session.out.write((httpVersion + " 401 log-in required" + serverCore.CRLF_STRING +
@@ -317,14 +318,14 @@ public final class httpd implements serverHandler {
return true;
}
- private boolean handleYaCyHopAuthentication(httpHeader header) {
+ private boolean handleYaCyHopAuthentication(final httpHeader header) {
// check if the user has allowed that his/her peer is used for hops
if (!this.allowYaCyHop) return false;
// proxy hops must identify with 4 criteria:
// the accessed port must not be port 80
- String host = this.prop.getProperty(httpHeader.CONNECTION_PROP_HOST);
+ final String host = this.prop.getProperty(httpHeader.CONNECTION_PROP_HOST);
if (host == null) return false;
int pos;
if ((pos = host.indexOf(":")) < 0) {
@@ -340,9 +341,9 @@ public final class httpd implements serverHandler {
// the accessing client must identify with user:password, where
// user = addressed peer name
// pw = addressed peer hash (b64-hash)
- String auth = (String) header.get(httpHeader.PROXY_AUTHORIZATION,"xxxxxx");
+ final String auth = (String) header.get(httpHeader.PROXY_AUTHORIZATION,"xxxxxx");
if (alternativeResolver != null) {
- String test = kelondroBase64Order.standardCoder.encodeString(alternativeResolver.myName() + ":" + alternativeResolver.myID());
+ final String test = kelondroBase64Order.standardCoder.encodeString(alternativeResolver.myName() + ":" + alternativeResolver.myID());
if (!test.equals(auth.trim().substring(6))) return false;
}
@@ -352,7 +353,7 @@ public final class httpd implements serverHandler {
// furthermore, YaCy hops must not exceed a specific access frequency
// check access requester frequency: protection against DoS against this peer
- String requester = this.prop.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP);
+ final String requester = this.prop.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP);
if (requester == null) return false;
if (lastAccessDelta(YaCyHopAccessRequester, requester) < 10000) return false;
YaCyHopAccessRequester.put(requester, new Long(System.currentTimeMillis()));
@@ -365,15 +366,15 @@ public final class httpd implements serverHandler {
return true;
}
- private static long lastAccessDelta(HashMap<String, Long> accessTable, String domain) {
- Long lastAccess = accessTable.get(domain);
+ private static long lastAccessDelta(final HashMap<String, Long> accessTable, final String domain) {
+ final Long lastAccess = accessTable.get(domain);
if (lastAccess == null) return Long.MAX_VALUE; // never accessed
return System.currentTimeMillis() - lastAccess.longValue();
}
- private boolean handleProxyAuthentication(httpHeader header) throws IOException {
+ private boolean handleProxyAuthentication(final httpHeader header) throws IOException {
// getting the http version that is used by the client
- String httpVersion = this.prop.getProperty("HTTP", "HTTP/0.9");
+ final String httpVersion = this.prop.getProperty("HTTP", "HTTP/0.9");
// reading the authentication settings from switchboard
if (!this.proxyAccounts_init) {
@@ -382,17 +383,17 @@ public final class httpd implements serverHandler {
}
if (this.use_proxyAccounts) {
- String auth = (String) header.get(httpHeader.PROXY_AUTHORIZATION,"xxxxxx");
+ final String auth = (String) header.get(httpHeader.PROXY_AUTHORIZATION,"xxxxxx");
userDB.Entry entry=switchboard.userDB.ipAuth(this.clientIP);
if(entry == null){
entry=switchboard.userDB.proxyAuth(auth, this.clientIP);
}
if(entry != null){
- int returncode=entry.surfRight();
+ final int returncode=entry.surfRight();
if(returncode==userDB.Entry.PROXY_ALLOK){
return true;
}
- serverObjects tp=new serverObjects();
+ final serverObjects tp=new serverObjects();
if(returncode==userDB.Entry.PROXY_TIMELIMIT_REACHED){
tp.put("limit", "1");//time per day
tp.put("limit_timelimit", entry.getTimeLimit());
@@ -415,7 +416,7 @@ public final class httpd implements serverHandler {
return true;
}
- public Boolean UNKNOWN(String requestLine) throws IOException {
+ public Boolean UNKNOWN(final String requestLine) throws IOException {
int pos;
String unknownCommand = null, args = null;
@@ -434,30 +435,30 @@ public final class httpd implements serverHandler {
return serverCore.TERMINATE_CONNECTION;
}
- public Boolean EMPTY(String arg) throws IOException {
+ public Boolean EMPTY(final String arg) throws IOException {
if (++this.emptyRequestCount > 10) return serverCore.TERMINATE_CONNECTION;
return serverCore.RESUME_CONNECTION;
}
- public Boolean TRACE(String arg) throws IOException {
+ public Boolean TRACE(final String arg) throws IOException {
sendRespondError(this.prop,this.session.out,0,501,null,"TRACE method not implemented",null);
return serverCore.TERMINATE_CONNECTION;
}
- public Boolean OPTIONS(String arg) throws IOException {
+ public Boolean OPTIONS(final String arg) throws IOException {
sendRespondError(this.prop,this.session.out,0,501,null,"OPTIONS method not implemented",null);
return serverCore.TERMINATE_CONNECTION;
}
- public Boolean GET(String arg) {
+ public Boolean GET(final String arg) {
try {
// parsing the http request line
parseRequestLine(httpHeader.METHOD_GET,arg);
// we now know the HTTP version. depending on that, we read the header
- String httpVersion = this.prop.getProperty(httpHeader.CONNECTION_PROP_HTTP_VER, httpHeader.HTTP_VERSION_0_9);
- httpHeader header = (httpVersion.equals(httpHeader.HTTP_VERSION_0_9))
+ final String httpVersion = this.prop.getProperty(httpHeader.CONNECTION_PROP_HTTP_VER, httpHeader.HTTP_VERSION_0_9);
+ final httpHeader header = (httpVersion.equals(httpHeader.HTTP_VERSION_0_9))
? new httpHeader(reverseMappingCache)
: httpHeader.readHeader(this.prop,this.session);
@@ -491,7 +492,7 @@ public final class httpd implements serverHandler {
}
return this.prop.getProperty(httpHeader.CONNECTION_PROP_PERSISTENT).equals("keep-alive") ? serverCore.RESUME_CONNECTION : serverCore.TERMINATE_CONNECTION;
- } catch (Exception e) {
+ } catch (final Exception e) {
logUnexpectedError(e);
return serverCore.TERMINATE_CONNECTION;
} finally {
@@ -499,11 +500,11 @@ public final class httpd implements serverHandler {
}
}
- private void logUnexpectedError(Exception e) {
+ private void logUnexpectedError(final Exception e) {
if (e instanceof InterruptedException) {
this.log.logInfo("Interruption detected");
} else {
- String errorMsg = e.getMessage();
+ final String errorMsg = e.getMessage();
if (errorMsg != null) {
if (errorMsg.startsWith("Socket closed")) {
this.log.logInfo("httpd shutdown detected ...");
@@ -521,13 +522,13 @@ public final class httpd implements serverHandler {
}
}
- public Boolean HEAD(String arg) {
+ public Boolean HEAD(final String arg) {
try {
parseRequestLine(httpHeader.METHOD_HEAD,arg);
// we now know the HTTP version. depending on that, we read the header
httpHeader header;
- String httpVersion = this.prop.getProperty(httpHeader.CONNECTION_PROP_HTTP_VER, httpHeader.HTTP_VERSION_0_9);
+ final String httpVersion = this.prop.getProperty(httpHeader.CONNECTION_PROP_HTTP_VER, httpHeader.HTTP_VERSION_0_9);
if (httpVersion.equals(httpHeader.HTTP_VERSION_0_9)) header = new httpHeader(reverseMappingCache);
else header = httpHeader.readHeader(this.prop,this.session);
@@ -563,7 +564,7 @@ public final class httpd implements serverHandler {
}
}
return this.prop.getProperty(httpHeader.CONNECTION_PROP_PERSISTENT).equals("keep-alive") ? serverCore.RESUME_CONNECTION : serverCore.TERMINATE_CONNECTION;
- } catch (Exception e) {
+ } catch (final Exception e) {
logUnexpectedError(e);
return serverCore.TERMINATE_CONNECTION;
} finally {
@@ -571,13 +572,13 @@ public final class httpd implements serverHandler {
}
}
- public Boolean POST(String arg) {
+ public Boolean POST(final String arg) {
try {
parseRequestLine(httpHeader.METHOD_POST,arg);
// we now know the HTTP version. depending on that, we read the header
httpHeader header;
- String httpVersion = this.prop.getProperty(httpHeader.CONNECTION_PROP_HTTP_VER, httpHeader.HTTP_VERSION_0_9);
+ final String httpVersion = this.prop.getProperty(httpHeader.CONNECTION_PROP_HTTP_VER, httpHeader.HTTP_VERSION_0_9);
if (httpVersion.equals(httpHeader.HTTP_VERSION_0_9)) header = new httpHeader(reverseMappingCache);
else header = httpHeader.readHeader(this.prop,this.session);
@@ -632,7 +633,7 @@ public final class httpd implements serverHandler {
}
//return serverCore.RESUME_CONNECTION;
return this.prop.getProperty(httpHeader.CONNECTION_PROP_PERSISTENT).equals("keep-alive") ? serverCore.RESUME_CONNECTION : serverCore.TERMINATE_CONNECTION;
- } catch (Exception e) {
+ } catch (final Exception e) {
logUnexpectedError(e);
return serverCore.TERMINATE_CONNECTION;
} finally {
@@ -671,7 +672,7 @@ public final class httpd implements serverHandler {
prop.setProperty(httpHeader.CONNECTION_PROP_URL, "");
// parse remaining lines
- httpHeader header = httpHeader.readHeader(this.prop,this.session);
+ final httpHeader header = httpHeader.readHeader(this.prop,this.session);
if (!(allowProxy)) {
// not authorized through firewall blocking (ip does not match filter)
@@ -699,14 +700,14 @@ public final class httpd implements serverHandler {
return serverCore.TERMINATE_CONNECTION;
}
- private final void parseRequestLine(String cmd, String s) {
+ private final void parseRequestLine(final String cmd, final String s) {
// parsing the header
httpHeader.parseRequestLine(cmd,s,this.prop,virtualHost);
// track the request
- String path = this.prop.getProperty(httpHeader.CONNECTION_PROP_URL);
- String args = this.prop.getProperty(httpHeader.CONNECTION_PROP_ARGS, "");
+ final String path = this.prop.getProperty(httpHeader.CONNECTION_PROP_URL);
+ final String args = this.prop.getProperty(httpHeader.CONNECTION_PROP_ARGS, "");
switchboard.track(this.userAddress.getHostName(), (args.length() > 0) ? path + "?" + args : path);
// reseting the empty request counter
@@ -723,7 +724,7 @@ public final class httpd implements serverHandler {
// and also by the httpdFileHandler
// but this belongs to the protocol handler, this class.
- public static int parseArgs(serverObjects args, InputStream in, int length) throws IOException {
+ public static int parseArgs(final serverObjects args, final InputStream in, final int length) throws IOException {
// this is a quick hack using a previously coded parseMultipart based on a buffer
// should be replaced sometime by a 'right' implementation
byte[] buffer = null;
@@ -740,12 +741,12 @@ public final class httpd implements serverHandler {
bout.close(); bout = null;
}
- int argc = parseArgs(args, new String(buffer, "UTF-8"));
+ final int argc = parseArgs(args, new String(buffer, "UTF-8"));
buffer = null;
return argc;
}
- public static int parseArgs(serverObjects args, String argsString) {
+ public static int parseArgs(final serverObjects args, String argsString) {
// this parses a arg string that can either be attached to a URL query
// or can be given as result of a post method
// the String argsString is supposed to be constructed as
@@ -793,7 +794,7 @@ public final class httpd implements serverHandler {
*/
private static String parseArg(String s) {
int pos = 0;
- ByteArrayOutputStream baos = new ByteArrayOutputStream(s.length());
+ final ByteArrayOutputStream baos = new ByteArrayOutputStream(s.length());
while (pos < s.length()) {
if (s.charAt(pos) == '+') {
@@ -803,8 +804,8 @@ public final class httpd implements serverHandler {
try {
if (s.length() >= pos + 6 && (s.charAt(pos + 1) == 'u' || s.charAt(pos + 1) == 'U')) {
// non-standard encoding of IE for unicode-chars
- int bh = Integer.parseInt(s.substring(pos + 2, pos + 4), 16);
- int bl = Integer.parseInt(s.substring(pos + 4, pos + 6), 16);
+ final int bh = Integer.parseInt(s.substring(pos + 2, pos + 4), 16);
+ final int bl = Integer.parseInt(s.substring(pos + 4, pos + 6), 16);
// TODO: needs conversion from UTF-16 to UTF-8
baos.write(bh);
baos.write(bl);
@@ -815,7 +816,7 @@ public final class httpd implements serverHandler {
} else {
baos.write(s.charAt(pos++));
}
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
baos.write(s.charAt(pos++));
}
} else if (s.charAt(pos) > 127) {
@@ -823,7 +824,7 @@ public final class httpd implements serverHandler {
try {
// don't write anything but url-encode the unicode char
s = s.substring(0, pos) + URLEncoder.encode(s.substring(pos, pos + 1), "UTF-8") + s.substring(pos + 1);
- } catch (UnsupportedEncodingException e) { return null; }
+ } catch (final UnsupportedEncodingException e) { return null; }
} else {
baos.write(s.charAt(pos++));
}
@@ -831,7 +832,7 @@ public final class httpd implements serverHandler {
try {
return new String(baos.toByteArray(), "UTF-8");
- } catch (UnsupportedEncodingException e) { return null; }
+ } catch (final UnsupportedEncodingException e) { return null; }
}
// 06.01.2007: decode HTML entities by [FB]
@@ -840,7 +841,7 @@ public final class httpd implements serverHandler {
s = htmlTools.decodeHtml2Unicode(s);
// replace all other
- CharArrayWriter b = new CharArrayWriter(s.length());
+ final CharArrayWriter b = new CharArrayWriter(s.length());
int end;
for (int i=0; i<s.length(); i++) {
if (s.charAt(i) == '&' && (end = s.indexOf(';', i + 1)) > i) {
@@ -858,7 +859,7 @@ public final class httpd implements serverHandler {
return b.toString();
}
- public static HashMap<String, byte[]> parseMultipart(httpHeader header, serverObjects args, InputStream in, int length) throws IOException {
+ public static HashMap<String, byte[]> parseMultipart(final httpHeader header, final serverObjects args, final InputStream in, final int length) throws IOException {
// this is a quick hack using a previously coded parseMultipart based on a buffer
// should be replaced sometime by a 'right' implementation
@@ -882,22 +883,22 @@ public final class httpd implements serverHandler {
}
//System.out.println("MULTIPART-BUFFER=" + new String(buffer));
- HashMap<String, byte[]> files = parseMultipart(header, args, buffer);
+ final HashMap<String, byte[]> files = parseMultipart(header, args, buffer);
buffer = null;
return files;
}
- public static HashMap<String, byte[]> parseMultipart(httpHeader header, serverObjects args, byte[] buffer) throws IOException {
+ public static HashMap<String, byte[]> parseMultipart(final httpHeader header, final serverObjects args, final byte[] buffer) throws IOException {
// we parse a multipart message and put results into the properties
// find/identify boundary marker
//System.out.println("DEBUG parseMultipart = <<" + new String(buffer) + ">>");
- String s = header.get(httpHeader.CONTENT_TYPE);
+ final String s = header.get(httpHeader.CONTENT_TYPE);
if (s == null) return null;
int q;
int p = s.toLowerCase().indexOf("boundary=");
if (p < 0) throw new IOException("boundary marker in multipart not found");
// boundaries start with additional leading "--", see RFC1867
- byte[] boundary = ("--" + s.substring(p + 9)).getBytes();
+ final byte[] boundary = ("--" + s.substring(p + 9)).getBytes();
// eat up first boundary
// the buffer must start with a boundary
@@ -907,15 +908,15 @@ public final class httpd implements serverHandler {
throw new IOException("boundary not recognized: " + ((line == null) ? "NULL" : new String(line, "UTF-8")) + ", boundary = " + new String(boundary));
// we need some constants
- byte[] namec = (new String("name=")).getBytes();
- byte[] filenamec = (new String("filename=")).getBytes();
+ final byte[] namec = (new String("name=")).getBytes();
+ final byte[] filenamec = (new String("filename=")).getBytes();
//byte[] semicolonc = (new String(";")).getBytes();
- byte[] quotec = new byte[] {(byte) '"'};
+ final byte[] quotec = new byte[] {(byte) '"'};
// now loop over boundaries
byte [] name;
byte [] filename;
- HashMap<String, byte[]> files = new HashMap<String, byte[]>();
+ final HashMap<String, byte[]> files = new HashMap<String, byte[]>();
int argc = 0;
//System.out.println("DEBUG: parsing multipart body:" + new String(buffer));
while (pos < buffer.length) { // boundary enumerator
@@ -1009,7 +1010,7 @@ public final class httpd implements serverHandler {
*/
static int nextPos = -1;
- private static byte[] readLine(int start, byte[] array) {
+ private static byte[] readLine(final int start, final byte[] array) {
// read a string from an array; line ending is always CRLF
// but we are also fuzzy with that: may also be only CR or LF
// if no remaining CR, CRLF or LF can be found, return null
@@ -1018,12 +1019,12 @@ public final class httpd implements serverHandler {
if (pos < 0) {pos = indexOf(start, array, new byte[] {serverCore.CR}); nextPos = pos + 1;}
if (pos < 0) {pos = indexOf(start, array, new byte[] {serverCore.LF}); nextPos = pos + 1;}
if (pos < 0) {nextPos = start; return null;}
- byte[] result = new byte[pos - start];
+ final byte[] result = new byte[pos - start];
java.lang.System.arraycopy(array, start, result, 0, pos - start);
return result;
}
- public static int indexOf(int start, byte[] array, byte[] pattern) {
+ public static int indexOf(final int start, final byte[] array, final byte[] pattern) {
// return a position of a pattern in an array
if (start > array.length - pattern.length) return -1;
if (pattern.length == 0) return start;
@@ -1033,7 +1034,7 @@ public final class httpd implements serverHandler {
return -1;
}
- public static boolean equals(byte[] a, int aoff, byte[] b, int boff, int len) {
+ public static boolean equals(final byte[] a, final int aoff, final byte[] b, final int boff, final int len) {
//System.out.println("equals: a = " + new String(a) + ", aoff = " + aoff + ", b = " + new String(b) + ", boff = " + boff + ", length = " + len);
if ((aoff + len > a.length) || (boff + len > b.length)) return false;
for (int i = 0; i < len; i++) if (a[aoff + i] != b[boff + i]) return false;
@@ -1046,9 +1047,9 @@ public final class httpd implements serverHandler {
}
public static final void sendRespondBody(
- Properties conProp,
- OutputStream respond,
- byte[] body
+ final Properties conProp,
+ final OutputStream respond,
+ final byte[] body
) throws IOException {
respond.write(body);
respond.flush();
@@ -1056,13 +1057,13 @@ public final class httpd implements serverHandler {
public static final void sendRespondError(
- Properties conProp,
- OutputStream respond,
- int errorcase,
- int httpStatusCode,
- String httpStatusText,
- String detailedErrorMsg,
- Throwable stackTrace
+ final Properties conProp,
+ final OutputStream respond,
+ final int errorcase,
+ final int httpStatusCode,
+ final String httpStatusText,
+ final String detailedErrorMsg,
+ final Throwable stackTrace
) throws IOException {
sendRespondError(
conProp,
@@ -1079,13 +1080,13 @@ public final class httpd implements serverHandler {
}
public static final void sendRespondError(
- Properties conProp,
- OutputStream respond,
- int httpStatusCode,
- String httpStatusText,
- File detailedErrorMsgFile,
- serverObjects detailedErrorMsgValues,
- Throwable stackTrace
+ final Properties conProp,
+ final OutputStream respond,
+ final int httpStatusCode,
+ final String httpStatusText,
+ final File detailedErrorMsgFile,
+ final serverObjects detailedErrorMsgValues,
+ final Throwable stackTrace
) throws IOException {
sendRespondError(
conProp,
@@ -1102,15 +1103,15 @@ public final class httpd implements serverHandler {
}
public static final void sendRespondError(
- Properties conProp,
- OutputStream respond,
- int errorcase,
- int httpStatusCode,
+ final Properties conProp,
+ final OutputStream respond,
+ final int errorcase,
+ final int httpStatusCode,
String httpStatusText,
- String detailedErrorMsgText,
- Object detailedErrorMsgFile,
- serverObjects detailedErrorMsgValues,
- Throwable stackTrace,
+ final String detailedErrorMsgText,
+ final Object detailedErrorMsgFile,
+ final serverObjects detailedErrorMsgValues,
+ final Throwable stackTrace,
httpHeader header
) throws IOException {
@@ -1118,7 +1119,7 @@ public final class httpd implements serverHandler {
ByteArrayOutputStream o = null;
try {
// setting the proper http status message
- String httpVersion = conProp.getProperty(httpHeader.CONNECTION_PROP_HTTP_VER,"HTTP/1.1");
+ final String httpVersion = conProp.getProperty(httpHeader.CONNECTION_PROP_HTTP_VER,"HTTP/1.1");
if ((httpStatusText == null)||(httpStatusText.length()==0)) {
if (httpVersion.equals("HTTP/1.0") && httpHeader.http1_0.containsKey(Integer.toString(httpStatusCode)))
httpStatusText = httpHeader.http1_0.get(Integer.toString(httpStatusCode));
@@ -1129,11 +1130,12 @@ public final class httpd implements serverHandler {
// generating the desired request url
String host = conProp.getProperty(httpHeader.CONNECTION_PROP_HOST);
- String path = conProp.getProperty(httpHeader.CONNECTION_PROP_PATH,"/");
- String args = conProp.getProperty(httpHeader.CONNECTION_PROP_ARGS);
- String method = conProp.getProperty(httpHeader.CONNECTION_PROP_METHOD);
+ final String path = conProp.getProperty(httpHeader.CONNECTION_PROP_PATH,"/");
+ final String args = conProp.getProperty(httpHeader.CONNECTION_PROP_ARGS);
+ final String method = conProp.getProperty(httpHeader.CONNECTION_PROP_METHOD);
- int port = 80, pos = host.indexOf(":");
+ int port = 80;
+ final int pos = host.indexOf(":");
if (pos != -1) {
port = Integer.parseInt(host.substring(pos + 1));
host = host.substring(0, pos);
@@ -1142,20 +1144,20 @@ public final class httpd implements serverHandler {
String urlString;
try {
urlString = (new yacyURL((method.equals(httpHeader.METHOD_CONNECT)?"https":"http"), host, port, (args == null) ? path : path + "?" + args)).toString();
- } catch (MalformedURLException e) {
+ } catch (final MalformedURLException e) {
urlString = "invalid URL";
}
// set rewrite values
- serverObjects tp = new serverObjects();
+ final serverObjects tp = new serverObjects();
// tp.put("host", serverCore.publicIP().getHostAddress());
// tp.put("port", switchboard.getConfig("port", "8080"));
- String clientIP = conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP, "127.0.0.1");
+ final String clientIP = conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP, "127.0.0.1");
// check if ip is local ip address
- InetAddress hostAddress = serverDomains.dnsResolve(clientIP);
+ final InetAddress hostAddress = serverDomains.dnsResolve(clientIP);
if (hostAddress == null) {
tp.put("host", serverDomains.myPublicLocalIP().getHostAddress());
tp.put("port", serverCore.getPortNr(switchboard.getConfig("port", "8080")));
@@ -1187,9 +1189,9 @@ public final class httpd implements serverHandler {
tp.put("errorMessageType_file", (detailedErrorMsgFile == null) ? "" : detailedErrorMsgFile.toString());
if ((detailedErrorMsgValues != null) && (detailedErrorMsgValues.size() > 0)) {
// rewriting the value-names and add the proper name prefix:
- Iterator<String> nameIter = detailedErrorMsgValues.keySet().iterator();
+ final Iterator<String> nameIter = detailedErrorMsgValues.keySet().iterator();
while (nameIter.hasNext()) {
- String name = nameIter.next();
+ final String name = nameIter.next();
tp.put("errorMessageType_" + name, detailedErrorMsgValues.get(name));
}
}
@@ -1203,7 +1205,7 @@ public final class httpd implements serverHandler {
// building the stacktrace
if (stackTrace != null) {
tp.put("printStackTrace",1);
- serverByteBuffer errorMsg = new serverByteBuffer(100);
+ final serverByteBuffer errorMsg = new serverByteBuffer(100);
stackTrace.printStackTrace(new PrintStream(errorMsg));
tp.put("printStackTrace_exception", stackTrace.toString());
tp.put("printStackTrace_stacktrace", new String(errorMsg.getBytes(),"UTF-8"));
@@ -1213,11 +1215,11 @@ public final class httpd implements serverHandler {
// Generated Tue, 23 Aug 2005 11:19:14 GMT by brain.wg (squid/2.5.STABLE3)
// adding some system information
- String systemDate = HttpClient.dateString(new Date());
+ final String systemDate = HttpClient.dateString(new Date());
tp.put("date", systemDate);
// rewrite the file
- File htRootPath = new File(switchboard.getRootPath(), switchboard.getConfig("htRootPath","htroot"));
+ final File htRootPath = new File(switchboard.getRootPath(), switchboard.getConfig("htRootPath","htroot"));
httpTemplate.writeTemplate(
fis = new FileInputStream(new File(htRootPath, "/proxymsg/error.html")),
@@ -1225,7 +1227,7 @@ public final class httpd implements serverHandler {
tp,
"-UNRESOLVED_PATTERN-".getBytes()
);
- byte[] result = o.toByteArray();
+ final byte[] result = o.toByteArray();
o.close(); o = null;
if(header == null)
@@ -1242,59 +1244,59 @@ public final class httpd implements serverHandler {
serverFileUtils.copy(result, respond);
}
respond.flush();
- } catch (Exception e) {
+ } catch (final Exception e) {
throw new IOException(e.getMessage());
} finally {
- if (fis != null) try { fis.close(); } catch (Exception e) {}
- if (o != null) try { o.close(); } catch (Exception e) {}
+ if (fis != null) try { fis.close(); } catch (final Exception e) {}
+ if (o != null) try { o.close(); } catch (final Exception e) {}
}
}
public static final void sendRespondHeader(
- Properties conProp,
- OutputStream respond,
- String httpVersion,
- int httpStatusCode,
- String httpStatusText,
- long contentLength
+ final Properties conProp,
+ final OutputStream respond,
+ final String httpVersion,
+ final int httpStatusCode,
+ final String httpStatusText,
+ final long contentLength
) throws IOException {
sendRespondHeader(conProp,respond,httpVersion,httpStatusCode,httpStatusText,null,contentLength,null,null,null,null,null);
}
public static final void sendRespondHeader(
- Properties conProp,
- OutputStream respond,
- String httpVersion,
- int httpStatusCode,
- String httpStatusText,
- String contentType,
- long contentLength,
- Date moddate,
- Date expires,
- httpHeader headers,
- String contentEnc,
- String transferEnc
+ final Properties conProp,
+ final OutputStream respond,
+ final String httpVersion,
+ final int httpStatusCode,
+ final String httpStatusText,
+ final String contentType,
+ final long contentLength,
+ final Date moddate,
+ final Date expires,
+ final httpHeader headers,
+ final String contentEnc,
+ final String transferEnc
) throws IOException {
sendRespondHeader(conProp,respond,httpVersion,httpStatusCode,httpStatusText,contentType,contentLength,moddate,expires,headers,contentEnc,transferEnc,true);
}
public static final void sendRespondHeader(
- Properties conProp,
- OutputStream respond,
- String httpVersion,
- int httpStatusCode,
- String httpStatusText,
+ final Properties conProp,
+ final OutputStream respond,
+ final String httpVersion,
+ final int httpStatusCode,
+ final String httpStatusText,
String contentType,
- long contentLength,
+ final long contentLength,
Date moddate,
- Date expires,
+ final Date expires,
httpHeader headers,
- String contentEnc,
- String transferEnc,
- boolean nocache
+ final String contentEnc,
+ final String transferEnc,
+ final boolean nocache
) throws IOException {
- String reqMethod = conProp.getProperty(httpHeader.CONNECTION_PROP_METHOD);
+ final String reqMethod = conProp.getProperty(httpHeader.CONNECTION_PROP_METHOD);
if ((transferEnc != null) && !httpVersion.equals(httpHeader.HTTP_VERSION_1_1)) {
throw new IllegalArgumentException("Transfer encoding is only supported for http/1.1 connections. The current connection version is " + httpVersion);
@@ -1312,7 +1314,7 @@ public final class httpd implements serverHandler {
}
if(headers==null) headers = new httpHeader();
- Date now = new Date(System.currentTimeMillis());
+ final Date now = new Date(System.currentTimeMillis());
headers.put(httpHeader.SERVER, "AnomicHTTPD (www.anomic.de)");
headers.put(httpHeader.DATE, HttpClient.dateString(now));
@@ -1339,20 +1341,20 @@ public final class httpd implements serverHandler {
}
public static final void sendRespondHeader(
- Properties conProp,
- OutputStream respond,
- String httpVersion,
- int httpStatusCode,
- httpHeader header
+ final Properties conProp,
+ final OutputStream respond,
+ final String httpVersion,
+ final int httpStatusCode,
+ final httpHeader header
) throws IOException {
sendRespondHeader(conProp,respond,httpVersion,httpStatusCode,null,header);
}
public static final void sendRespondHeader(
- Properties conProp,
- OutputStream respond,
+ final Properties conProp,
+ final OutputStream respond,
String httpVersion,
- int httpStatusCode,
+ final int httpStatusCode,
String httpStatusText,
httpHeader header
) throws IOException {
@@ -1371,7 +1373,7 @@ public final class httpd implements serverHandler {
else httpStatusText = "Unknown";
}
- StringBuffer headerStringBuffer = new StringBuffer(560);
+ final StringBuffer headerStringBuffer = new StringBuffer(560);
// "HTTP/0.9" does not have a status line or header in the response
if (! httpVersion.toUpperCase().equals(httpHeader.HTTP_VERSION_0_9)) {
@@ -1408,11 +1410,11 @@ public final class httpd implements serverHandler {
httpHeader outgoingHeader=requestProperties.getOutgoingHeader();
if (outgoingHeader!=null)
{*/
- Iterator<httpHeader.Entry> it = header.getCookies();
+ final Iterator<httpHeader.Entry> it = header.getCookies();
while(it.hasNext()) {
//Append user properties to the main String
//TODO: Should we check for user properites. What if they intersect properties that are already in header?
- httpHeader.Entry e = it.next();
+ final httpHeader.Entry e = it.next();
headerStringBuffer.append(e.getKey()).append(": ").append(e.getValue()).append("\r\n");
}
@@ -1421,7 +1423,7 @@ public final class httpd implements serverHandler {
}*/
// write header
- Iterator<String> i = header.keySet().iterator();
+ final Iterator<String> i = header.keySet().iterator();
String key;
char tag;
int count;
@@ -1450,14 +1452,14 @@ public final class httpd implements serverHandler {
conProp.put(httpHeader.CONNECTION_PROP_PROXY_RESPOND_HEADER,header);
conProp.put(httpHeader.CONNECTION_PROP_PROXY_RESPOND_STATUS,Integer.toString(httpStatusCode));
- } catch (Exception e) {
+ } catch (final Exception e) {
// any interruption may be caused be network error or because the user has closed
// the windows during transmission. We simply pass it as IOException
throw new IOException(e.getMessage());
}
}
- public static boolean shallTransportZipped(String path) {
+ public static boolean shallTransportZipped(final String path) {
if ((path == null) || (path.length() == 0)) return true;
int pos;
@@ -1467,7 +1469,7 @@ public final class httpd implements serverHandler {
return true;
}
- public void doUserAccounting(Properties conProps) {
+ public void doUserAccounting(final Properties conProps) {
// TODO: validation of conprop fields
// httpHeader.CONNECTION_PROP_USER
// httpHeader.CONNECTION_PROP_CLIENTIP
@@ -1475,22 +1477,22 @@ public final class httpd implements serverHandler {
// httpHeader.CONNECTION_PROP_PROXY_RESPOND_STATUS
}
- public static boolean isThisSeedIP(String hostName) {
+ public static boolean isThisSeedIP(final String hostName) {
if ((hostName == null) || (hostName.length() == 0)) return false;
// getting ip address and port of this seed
if (alternativeResolver == null) return false;
// resolve ip addresses
- InetAddress seedInetAddress = serverDomains.dnsResolve(alternativeResolver.myIP());
- InetAddress hostInetAddress = serverDomains.dnsResolve(hostName);
+ final InetAddress seedInetAddress = serverDomains.dnsResolve(alternativeResolver.myIP());
+ final InetAddress hostInetAddress = serverDomains.dnsResolve(hostName);
if (seedInetAddress == null || hostInetAddress == null) return false;
// if it's equal, the hostname points to this seed
return (seedInetAddress.equals(hostInetAddress));
}
- public static boolean isThisHostIP(String hostName) {
+ public static boolean isThisHostIP(final String hostName) {
if ((hostName == null) || (hostName.length() == 0)) return false;
boolean isThisHostIP = false;
@@ -1508,11 +1510,11 @@ public final class httpd implements serverHandler {
break;
}
}
- } catch (Exception e) {}
+ } catch (final Exception e) {}
return isThisHostIP;
}
- public static boolean isThisHostIP(InetAddress clientAddress) {
+ public static boolean isThisHostIP(final InetAddress clientAddress) {
if (clientAddress == null) return false;
boolean isThisHostIP = false;
@@ -1526,11 +1528,11 @@ public final class httpd implements serverHandler {
break;
}
}
- } catch (Exception e) {}
+ } catch (final Exception e) {}
return isThisHostIP;
}
- public static boolean isThisHostName(String hostName) {
+ public static boolean isThisHostName(final String hostName) {
if ((hostName == null) || (hostName.length() == 0)) return false;
try {
@@ -1539,7 +1541,7 @@ public final class httpd implements serverHandler {
final Integer dstPort = (idx != -1) ? Integer.valueOf(hostName.substring(idx+1).trim()) : new Integer(80);
// if the hostname endswith thisPeerName.yacy ...
- String alternativeAddress = (alternativeResolver == null) ? null : alternativeResolver.myAlternativeAddress();
+ final String alternativeAddress = (alternativeResolver == null) ? null : alternativeResolver.myAlternativeAddress();
if ((alternativeAddress != null) && (dstHost.endsWith(alternativeAddress))) {
return true;
/*
@@ -1558,7 +1560,7 @@ public final class httpd implements serverHandler {
) {
return true;
}
- } catch (Exception e) {}
+ } catch (final Exception e) {}
return false;
}
}
diff --git a/source/de/anomic/http/httpdBoundedSizeOutputStream.java b/source/de/anomic/http/httpdBoundedSizeOutputStream.java
index 14e835303..a638897af 100644
--- a/source/de/anomic/http/httpdBoundedSizeOutputStream.java
+++ b/source/de/anomic/http/httpdBoundedSizeOutputStream.java
@@ -31,19 +31,19 @@ public class httpdBoundedSizeOutputStream extends httpdByteCountOutputStream {
protected final long maxSize;
- public httpdBoundedSizeOutputStream(OutputStream outputStream, long sizeLimit) {
+ public httpdBoundedSizeOutputStream(final OutputStream outputStream, final long sizeLimit) {
this(outputStream,0,sizeLimit);
}
- public httpdBoundedSizeOutputStream(OutputStream outputStream, long initByteCount, long sizeLimit) {
+ public httpdBoundedSizeOutputStream(final OutputStream outputStream, final long initByteCount, final long sizeLimit) {
super(outputStream,initByteCount,null);
this.maxSize = sizeLimit;
}
- public void write(byte[] b) throws IOException {
+ public void write(final byte[] b) throws IOException {
if (this.byteCount + b.length > this.maxSize) {
// write out the rest until we have reached the limit
- long rest = this.maxSize-this.byteCount;
+ final long rest = this.maxSize-this.byteCount;
if (rest > 0) this.write(b, 0, (int)rest);
// throw an exception
@@ -52,10 +52,10 @@ public class httpdBoundedSizeOutputStream extends httpdByteCountOutputStream {
super.write(b);
}
- public void write(byte[] b, int off, int len) throws IOException {
+ public void write(final byte[] b, final int off, final int len) throws IOException {
if (this.byteCount + len > this.maxSize) {
// write out the rest until we reach the limit
- long rest = this.maxSize-this.byteCount;
+ final long rest = this.maxSize-this.byteCount;
if (rest > 0) this.write(b, 0, (int)rest);
// throw an exception
@@ -64,7 +64,7 @@ public class httpdBoundedSizeOutputStream extends httpdByteCountOutputStream {
super.write(b, off, len);
}
- public void write(int b) throws IOException {
+ public void write(final int b) throws IOException {
if (this.byteCount + 1 > this.maxSize) {
// throw an exception
throw new httpdLimitExceededException("Limit exceeded",this.maxSize);
diff --git a/source/de/anomic/http/httpdByteCountInputStream.java b/source/de/anomic/http/httpdByteCountInputStream.java
index 917feea54..7107d1296 100644
--- a/source/de/anomic/http/httpdByteCountInputStream.java
+++ b/source/de/anomic/http/httpdByteCountInputStream.java
@@ -41,7 +41,7 @@ public class httpdByteCountInputStream extends FilterInputStream {
protected long byteCount;
private String byteCountAccountName = null;
- protected httpdByteCountInputStream(InputStream inputStream) {
+ protected httpdByteCountInputStream(final InputStream inputStream) {
this(inputStream,null);
}
@@ -49,7 +49,7 @@ public class httpdByteCountInputStream extends FilterInputStream {
* Constructor of this class
* @param inputStream the {@link InputStream} to read from
*/
- public httpdByteCountInputStream(InputStream inputStream, String accountName) {
+ public httpdByteCountInputStream(final InputStream inputStream, final String accountName) {
this(inputStream,0,accountName);
}
@@ -58,24 +58,24 @@ public class httpdByteCountInputStream extends FilterInputStream {
* @param inputStream the {@link InputStream} to read from
* @param initByteCount to initialize the bytecount with a given value
*/
- public httpdByteCountInputStream(InputStream inputStream, int initByteCount, String accountName) {
+ public httpdByteCountInputStream(final InputStream inputStream, final int initByteCount, final String accountName) {
super(inputStream);
this.byteCount = initByteCount;
this.byteCountAccountName = accountName;
}
- public int read(byte[] b) throws IOException {
- int readCount = super.read(b);
+ public int read(final byte[] b) throws IOException {
+ final int readCount = super.read(b);
if (readCount > 0) this.byteCount += readCount;
return readCount;
}
- public int read(byte[] b, int off, int len) throws IOException {
+ public int read(final byte[] b, final int off, final int len) throws IOException {
try {
- int readCount = super.read(b, off, len);
+ final int readCount = super.read(b, off, len);
if (readCount > 0) this.byteCount += readCount;
return readCount;
- } catch (IOException e) {
+ } catch (final IOException e) {
throw new IOException(e.getMessage() + "; b.length = " + b.length + ", off = " + off + ", len = " + len);
}
}
@@ -85,8 +85,8 @@ public class httpdByteCountInputStream extends FilterInputStream {
return super.read();
}
- public long skip(long len) throws IOException {
- long skipCount = super.skip(len);
+ public long skip(final long len) throws IOException {
+ final long skipCount = super.skip(len);
if (skipCount > 0) this.byteCount += skipCount;
return skipCount;
}
@@ -105,7 +105,7 @@ public class httpdByteCountInputStream extends FilterInputStream {
}
}
- public static long getAccountCount(String accountName) {
+ public static long getAccountCount(final String accountName) {
synchronized (syncObject) {
if (byteCountInfo.containsKey(accountName)) {
return (byteCountInfo.get(accountName)).longValue();
diff --git a/source/de/anomic/http/httpdByteCountOutputStream.java b/source/de/anomic/http/httpdByteCountOutputStream.java
index 57a98821c..2833a0e30 100644
--- a/source/de/anomic/http/httpdByteCountOutputStream.java
+++ b/source/de/anomic/http/httpdByteCountOutputStream.java
@@ -43,11 +43,11 @@ public class httpdByteCountOutputStream extends BufferedOutputStream {
* Constructor of this class
* @param outputStream the {@link OutputStream} to write to
*/
- public httpdByteCountOutputStream(OutputStream outputStream) {
+ public httpdByteCountOutputStream(final OutputStream outputStream) {
this(outputStream,null);
}
- public httpdByteCountOutputStream(OutputStream outputStream, String accountName) {
+ public httpdByteCountOutputStream(final OutputStream outputStream, final String accountName) {
this(outputStream,0,accountName);
}
@@ -56,26 +56,26 @@ public class httpdByteCountOutputStream extends BufferedOutputStream {
* @param outputStream the {@link OutputStream} to write to
* @param initByteCount to initialize the bytecount with a given value
*/
- public httpdByteCountOutputStream(OutputStream outputStream, long initByteCount, String accountName) {
+ public httpdByteCountOutputStream(final OutputStream outputStream, final long initByteCount, final String accountName) {
super(outputStream);
this.byteCount = initByteCount;
this.byteCountAccountName = accountName;
}
/** @see java.io.OutputStream#write(byte[]) */
- public void write(byte[] b) throws IOException {
+ public void write(final byte[] b) throws IOException {
super.write(b);
this.byteCount += b.length;
}
/** @see java.io.OutputStream#write(byte[], int, int) */
- public synchronized void write(byte[] b, int off, int len) throws IOException {
+ public synchronized void write(final byte[] b, final int off, final int len) throws IOException {
super.write(b, off, len);
this.byteCount += len;
}
/** @see java.io.OutputStream#write(int) */
- public synchronized void write(int b) throws IOException {
+ public synchronized void write(final int b) throws IOException {
super.write(b);
this.byteCount++;
}
@@ -98,7 +98,7 @@ public class httpdByteCountOutputStream extends BufferedOutputStream {
}
}
- public static long getAccountCount(String accountName) {
+ public static long getAccountCount(final String accountName) {
synchronized (syncObject) {
if (byteCountInfo.containsKey(accountName)) {
return (byteCountInfo.get(accountName)).longValue();
diff --git a/source/de/anomic/http/httpdFileHandler.java b/source/de/anomic/http/httpdFileHandler.java
index 7efdc94e3..9e2669c16 100644
--- a/source/de/anomic/http/httpdFileHandler.java
+++ b/source/de/anomic/http/httpdFileHandler.java
@@ -128,17 +128,17 @@ public final class httpdFileHandler {
if (mimeTable.size() == 0) {
// load the mime table
- String mimeTablePath = theSwitchboard.getConfig("mimeConfig","");
+ final String mimeTablePath = theSwitchboard.getConfig("mimeConfig","");
BufferedInputStream mimeTableInputStream = null;
try {
serverLog.logConfig("HTTPDFiles", "Loading mime mapping file " + mimeTablePath);
mimeTableInputStream = new BufferedInputStream(new FileInputStream(new File(theSwitchboard.getRootPath(), mimeTablePath)));
mimeTable.load(mimeTableInputStream);
- } catch (Exception e) {
+ } catch (final Exception e) {
serverLog.logSevere("HTTPDFiles", "ERROR: path to configuration file or configuration invalid\n" + e);
System.exit(1);
} finally {
- if (mimeTableInputStream != null) try { mimeTableInputStream.close(); } catch (Exception e1) {}
+ if (mimeTableInputStream != null) try { mimeTableInputStream.close(); } catch (final Exception e1) {}
}
}
@@ -158,7 +158,7 @@ public final class httpdFileHandler {
}
// create a repository path
- File repository = new File(htDocsPath, "repository");
+ final File repository = new File(htDocsPath, "repository");
if (!repository.exists()) repository.mkdirs();
// create a htTemplatePath
@@ -184,19 +184,19 @@ public final class httpdFileHandler {
/** Returns a path to the localized or default file according to the locale.language (from he switchboard)
* @param path relative from htroot */
- public static File getLocalizedFile(String path){
+ public static File getLocalizedFile(final String path){
return getLocalizedFile(path, switchboard.getConfig("locale.language","default"));
}
/** Returns a path to the localized or default file according to the parameter localeSelection
* @param path relative from htroot
* @param localeSelection language of localized file; locale.language from switchboard is used if localeSelection.equals("") */
- public static File getLocalizedFile(String path, String localeSelection){
+ public static File getLocalizedFile(final String path, final String localeSelection){
if (htDefaultPath == null) htDefaultPath = switchboard.getConfigPath("htDefaultPath","htroot");
if (htLocalePath == null) htLocalePath = switchboard.getConfigPath("locale.translated_html","DATA/LOCALE/htroot");
if (!(localeSelection.equals("default"))) {
- File localePath = new File(htLocalePath, localeSelection + '/' + path);
+ final File localePath = new File(htLocalePath, localeSelection + '/' + path);
if (localePath.exists()) // avoid "NoSuchFile" troubles if the "localeSelection" is misspelled
return localePath;
}
@@ -221,8 +221,8 @@ public final class httpdFileHandler {
// out.flush();
// }
- private static final httpHeader getDefaultHeaders(String path) {
- httpHeader headers = new httpHeader();
+ private static final httpHeader getDefaultHeaders(final String path) {
+ final httpHeader headers = new httpHeader();
String ext;
int pos;
if ((pos = path.lastIndexOf('.')) < 0) {
@@ -238,28 +238,28 @@ public final class httpdFileHandler {
return headers;
}
- public static void doGet(Properties conProp, httpHeader requestHeader, OutputStream response) {
+ public static void doGet(final Properties conProp, final httpHeader requestHeader, final OutputStream response) {
doResponse(conProp, requestHeader, response, null);
}
- public static void doHead(Properties conProp, httpHeader requestHeader, OutputStream response) {
+ public static void doHead(final Properties conProp, final httpHeader requestHeader, final OutputStream response) {
doResponse(conProp, requestHeader, response, null);
}
- public static void doPost(Properties conProp, httpHeader requestHeader, OutputStream response, InputStream body) {
+ public static void doPost(final Properties conProp, final httpHeader requestHeader, final OutputStream response, final InputStream body) {
doResponse(conProp, requestHeader, response, body);
}
- public static void doResponse(Properties conProp, httpHeader requestHeader, OutputStream out, InputStream body) {
+ public static void doResponse(final Properties conProp, final httpHeader requestHeader, final OutputStream out, final InputStream body) {
String path = null;
try {
// getting some connection properties
- String method = conProp.getProperty(httpHeader.CONNECTION_PROP_METHOD);
+ final String method = conProp.getProperty(httpHeader.CONNECTION_PROP_METHOD);
path = conProp.getProperty(httpHeader.CONNECTION_PROP_PATH);
String argsString = conProp.getProperty(httpHeader.CONNECTION_PROP_ARGS); // is null if no args were given
- String httpVersion = conProp.getProperty(httpHeader.CONNECTION_PROP_HTTP_VER);
- String clientIP = conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP, "unknown-host");
+ final String httpVersion = conProp.getProperty(httpHeader.CONNECTION_PROP_HTTP_VER);
+ final String clientIP = conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP, "unknown-host");
// check hack attacks in path
if (path.indexOf("..") >= 0) {
@@ -270,7 +270,7 @@ public final class httpdFileHandler {
// url decoding of path
try {
path = URLDecoder.decode(path, "UTF-8");
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
// This should never occur
assert(false) : "UnsupportedEncodingException: " + e.getMessage();
}
@@ -284,25 +284,25 @@ public final class httpdFileHandler {
// check permission/granted access
String authorization = requestHeader.get(httpHeader.AUTHORIZATION);
if (authorization != null && authorization.length() == 0) authorization = null;
- String adminAccountBase64MD5 = switchboard.getConfig(httpd.ADMIN_ACCOUNT_B64MD5, "");
+ final String adminAccountBase64MD5 = switchboard.getConfig(httpd.ADMIN_ACCOUNT_B64MD5, "");
int pos = path.lastIndexOf(".");
- boolean adminAccountForLocalhost = sb.getConfigBool("adminAccountForLocalhost", false);
- String refererHost = requestHeader.refererHost();
- boolean accessFromLocalhost = serverCore.isLocalhost(clientIP) && (refererHost.length() == 0 || serverCore.isLocalhost(refererHost));
- boolean grantedForLocalhost = adminAccountForLocalhost && accessFromLocalhost;
- boolean protectedPage = (path.substring(0,(pos==-1)?path.length():pos)).endsWith("_p");
- boolean accountEmpty = adminAccountBase64MD5.length() == 0;
+ final boolean adminAccountForLocalhost = sb.getConfigBool("adminAccountForLocalhost", false);
+ final String refererHost = requestHeader.refererHost();
+ final boolean accessFromLocalhost = serverCore.isLocalhost(clientIP) && (refererHost.length() == 0 || serverCore.isLocalhost(refererHost));
+ final boolean grantedForLocalhost = adminAccountForLocalhost && accessFromLocalhost;
+ final boolean protectedPage = (path.substring(0,(pos==-1)?path.length():pos)).endsWith("_p");
+ final boolean accountEmpty = adminAccountBase64MD5.length() == 0;
if (!grantedForLocalhost && protectedPage && !accountEmpty) {
// authentication required
if (authorization == null) {
// no authorization given in response. Ask for that
- httpHeader headers = getDefaultHeaders(path);
+ final httpHeader headers = getDefaultHeaders(path);
headers.put(httpHeader.WWW_AUTHENTICATE,"Basic realm=\"admin log-in\"");
//httpd.sendRespondHeader(conProp,out,httpVersion,401,headers);
- servletProperties tp=new servletProperties();
+ final servletProperties tp=new servletProperties();
tp.put("returnto", path);
//TODO: separate errorpage Wrong Login / No Login
httpd.sendRespondError(conProp, out, 5, 401, "Wrong Authentication", "", new File("proxymsg/authfail.inc"), tp, null, headers);
@@ -315,13 +315,13 @@ public final class httpdFileHandler {
} else {
// a wrong authentication was given or the userDB user does not have admin access. Ask again
serverLog.logInfo("HTTPD", "Wrong log-in for account 'admin' in http file handler for path '" + path + "' from host '" + clientIP + "'");
- Integer attempts = serverCore.bfHost.get(clientIP);
+ final Integer attempts = serverCore.bfHost.get(clientIP);
if (attempts == null)
serverCore.bfHost.put(clientIP, new Integer(1));
else
serverCore.bfHost.put(clientIP, new Integer(attempts.intValue() + 1));
- httpHeader headers = getDefaultHeaders(path);
+ final httpHeader headers = getDefaultHeaders(path);
headers.put(httpHeader.WWW_AUTHENTICATE,"Basic realm=\"admin log-in\"");
httpd.sendRespondHeader(conProp,out,httpVersion,401,headers);
return;
@@ -356,10 +356,10 @@ public final class httpdFileHandler {
if ((requestHeader.containsKey(httpHeader.CONTENT_TYPE)) &&
(requestHeader.get(httpHeader.CONTENT_TYPE).toLowerCase().startsWith("multipart"))) {
// parse multipart
- HashMap<String, byte[]> files = httpd.parseMultipart(requestHeader, args, (gzipBody!=null)?gzipBody:body, length);
+ final HashMap<String, byte[]> files = httpd.parseMultipart(requestHeader, args, (gzipBody!=null)?gzipBody:body, length);
// integrate these files into the args
if (files != null) {
- Iterator<Map.Entry<String, byte[]>> fit = files.entrySet().iterator();
+ final Iterator<Map.Entry<String, byte[]>> fit = files.entrySet().iterator();
Map.Entry<String, byte[]> entry;
while (fit.hasNext()) {
entry = fit.next();
@@ -385,7 +385,7 @@ public final class httpdFileHandler {
// check for cross site scripting - attacks in request arguments
if (args != null && argc > 0) {
// check all values for occurrences of script values
- Iterator<String> e = args.values().iterator(); // enumeration of values
+ final Iterator<String> e = args.values().iterator(); // enumeration of values
String val;
while (e.hasNext()) {
val = e.next();
@@ -421,7 +421,7 @@ public final class httpdFileHandler {
}
File targetFile = getLocalizedFile(path, localeSelection);
- String targetExt = conProp.getProperty("EXT","");
+ final String targetExt = conProp.getProperty("EXT","");
targetClass = rewriteClassFile(new File(htDefaultPath, path));
if (path.endsWith("/")) {
String testpath;
@@ -438,9 +438,9 @@ public final class httpdFileHandler {
//no defaultfile, send a dirlisting
if (targetFile == null || !targetFile.exists()) {
- StringBuffer aBuffer = new StringBuffer();
+ final StringBuffer aBuffer = new StringBuffer();
aBuffer.append("<html>\n<head>\n</head>\n<body>\n<h1>Index of " + path + "</h1>\n <ul>\n");
- File dir = new File(htDocsPath, path);
+ final File dir = new File(htDocsPath, path);
String[] list = dir.list();
if (list == null) list = new String[0]; // should not occur!
File f;
@@ -515,7 +515,7 @@ public final class httpdFileHandler {
requestHeader.put(httpHeader.CONNECTION_PROP_PATH, path);
// in case that there are no args given, args = null or empty hashmap
img = invokeServlet(targetClass, requestHeader, args);
- } catch (InvocationTargetException e) {
+ } catch (final InvocationTargetException e) {
theLogger.logSevere("INTERNAL ERROR: " + e.toString() + ":" +
e.getMessage() +
" target exception at " + targetClass + ": " +
@@ -529,12 +529,12 @@ public final class httpdFileHandler {
httpd.sendRespondError(conProp, out, 3, 404, "File not Found", null, null);
} else {
if (img instanceof ymageMatrix) {
- ymageMatrix yp = (ymageMatrix) img;
+ final ymageMatrix yp = (ymageMatrix) img;
// send an image to client
targetDate = new Date(System.currentTimeMillis());
nocache = true;
- String mimeType = mimeTable.getProperty(targetExt, "text/html");
- serverByteBuffer result = ymageMatrix.exportImage(yp.getImage(), targetExt);
+ final String mimeType = mimeTable.getProperty(targetExt, "text/html");
+ final serverByteBuffer result = ymageMatrix.exportImage(yp.getImage(), targetExt);
// write the array to the client
httpd.sendRespondHeader(conProp, out, httpVersion, 200, null, mimeType, result.length(), targetDate, null, null, null, null, nocache);
@@ -543,18 +543,18 @@ public final class httpdFileHandler {
}
}
if (img instanceof Image) {
- Image i = (Image) img;
+ final Image i = (Image) img;
// send an image to client
targetDate = new Date(System.currentTimeMillis());
nocache = true;
- String mimeType = mimeTable.getProperty(targetExt, "text/html");
+ final String mimeType = mimeTable.getProperty(targetExt, "text/html");
// generate an byte array from the generated image
int width = i.getWidth(null); if (width < 0) width = 96; // bad hack
int height = i.getHeight(null); if (height < 0) height = 96; // bad hack
- BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
+ final BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
bi.createGraphics().drawImage(i, 0, 0, width, height, null);
- serverByteBuffer result = ymageMatrix.exportImage(bi, targetExt);
+ final serverByteBuffer result = ymageMatrix.exportImage(bi, targetExt);
// write the array to the client
httpd.sendRespondHeader(conProp, out, httpVersion, 200, null, mimeType, result.length(), targetDate, null, null, null, null, nocache);
@@ -580,8 +580,8 @@ public final class httpdFileHandler {
// we have found a file that can be written to the client
// if this file uses templates, then we use the template
// re-write - method to create an result
- String mimeType = mimeTable.getProperty(targetExt,"text/html");
- boolean zipContent = requestHeader.acceptGzip() && httpd.shallTransportZipped("." + conProp.getProperty("EXT",""));
+ final String mimeType = mimeTable.getProperty(targetExt,"text/html");
+ final boolean zipContent = requestHeader.acceptGzip() && httpd.shallTransportZipped("." + conProp.getProperty("EXT",""));
if (path.endsWith("html") ||
path.endsWith("xml") ||
path.endsWith("rdf") ||
@@ -611,7 +611,7 @@ public final class httpdFileHandler {
requestHeader.put(httpHeader.CONNECTION_PROP_CLIENTIP, conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP));
requestHeader.put(httpHeader.CONNECTION_PROP_PATH, path);
// in case that there are no args given, args = null or empty hashmap
- Object tmp = invokeServlet(targetClass, requestHeader, args);
+ final Object tmp = invokeServlet(targetClass, requestHeader, args);
if (tmp == null) {
// if no args given, then tp will be an empty Hashtable object (not null)
tp = new servletProperties();
@@ -625,14 +625,14 @@ public final class httpdFileHandler {
// handle brute-force protection
if (authorization != null) {
serverLog.logInfo("HTTPD", "dynamic log-in for account 'admin' in http file handler for path '" + path + "' from host '" + clientIP + "'");
- Integer attempts = serverCore.bfHost.get(clientIP);
+ final Integer attempts = serverCore.bfHost.get(clientIP);
if (attempts == null)
serverCore.bfHost.put(clientIP, new Integer(1));
else
serverCore.bfHost.put(clientIP, new Integer(attempts.intValue() + 1));
}
// send authentication request to browser
- httpHeader headers = getDefaultHeaders(path);
+ final httpHeader headers = getDefaultHeaders(path);
headers.put(httpHeader.WWW_AUTHENTICATE,"Basic realm=\"" + tp.get(servletProperties.ACTION_AUTHENTICATE, "") + "\"");
httpd.sendRespondHeader(conProp,out,httpVersion,401,headers);
return;
@@ -640,7 +640,7 @@ public final class httpdFileHandler {
String location = tp.get(servletProperties.ACTION_LOCATION, "");
if (location.length() == 0) location = path;
- httpHeader headers = getDefaultHeaders(path);
+ final httpHeader headers = getDefaultHeaders(path);
headers.setCookieVector(tp.getOutgoingHeader().getCookieVector()); //put the cookies into the new header TODO: can we put all headerlines, without trouble?
headers.put(httpHeader.LOCATION,location);
httpd.sendRespondHeader(conProp,out,httpVersion,302,headers);
@@ -652,7 +652,7 @@ public final class httpdFileHandler {
tp.putHTML(servletProperties.PEER_STAT_CLIENTNAME, switchboard.getConfig("peerName", "anomic"));
tp.put(servletProperties.PEER_STAT_MYTIME, serverDate.formatShortSecond());
//System.out.println("respond props: " + ((tp == null) ? "null" : tp.toString())); // debug
- } catch (InvocationTargetException e) {
+ } catch (final InvocationTargetException e) {
if (e.getCause() instanceof InterruptedException) {
throw new InterruptedException(e.getCause().getMessage());
}
@@ -675,7 +675,7 @@ public final class httpdFileHandler {
// read the file/template
byte[] templateContent = null;
if (useTemplateCache) {
- long fileSize = targetFile.length();
+ final long fileSize = targetFile.length();
if (fileSize <= 512 * 1024) {
// read from cache
SoftReference<byte[]> ref = templateCache.get(targetFile);
@@ -714,27 +714,27 @@ public final class httpdFileHandler {
// write the array to the client
// we can do that either in standard mode (whole thing completely) or in chunked mode
// since yacy clients do not understand chunked mode (yet), we use this only for communication with the administrator
- boolean yacyClient = requestHeader.userAgent().startsWith("yacy");
- boolean chunked = !method.equals(httpHeader.METHOD_HEAD) && !yacyClient && httpVersion.equals(httpHeader.HTTP_VERSION_1_1);
+ final boolean yacyClient = requestHeader.userAgent().startsWith("yacy");
+ final boolean chunked = !method.equals(httpHeader.METHOD_HEAD) && !yacyClient && httpVersion.equals(httpHeader.HTTP_VERSION_1_1);
if (chunked) {
// send page in chunks and parse SSIs
- serverByteBuffer o = new serverByteBuffer();
+ final serverByteBuffer o = new serverByteBuffer();
// apply templates
httpTemplate.writeTemplate(fis, o, tp, "-UNRESOLVED_PATTERN-".getBytes("UTF-8"));
httpd.sendRespondHeader(conProp, out, httpVersion, 200, null, mimeType, -1, targetDate, null, tp.getOutgoingHeader(), null, "chunked", nocache);
// send the content in chunked parts, see RFC 2616 section 3.6.1
- httpChunkedOutputStream chos = new httpChunkedOutputStream(out);
+ final httpChunkedOutputStream chos = new httpChunkedOutputStream(out);
httpSSI.writeSSI(o, chos, authorization, clientIP);
//chos.write(result);
chos.finish();
} else {
// send page as whole thing, SSIs are not possible
- String contentEncoding = (zipContent) ? "gzip" : null;
+ final String contentEncoding = (zipContent) ? "gzip" : null;
// apply templates
- serverByteBuffer o1 = new serverByteBuffer();
+ final serverByteBuffer o1 = new serverByteBuffer();
httpTemplate.writeTemplate(fis, o1, tp, "-UNRESOLVED_PATTERN-".getBytes("UTF-8"));
- serverByteBuffer o = new serverByteBuffer();
+ final serverByteBuffer o = new serverByteBuffer();
if (zipContent) {
GZIPOutputStream zippedOut = new GZIPOutputStream(o);
@@ -754,7 +754,7 @@ public final class httpdFileHandler {
targetDate, null, tp.getOutgoingHeader(),
contentEncoding, null, nocache);
} else {
- byte[] result = o.getBytes(); // this interrupts streaming (bad idea!)
+ final byte[] result = o.getBytes(); // this interrupts streaming (bad idea!)
httpd.sendRespondHeader(conProp, out,
httpVersion, 200, null, mimeType, result.length,
targetDate, null, tp.getOutgoingHeader(),
@@ -773,7 +773,7 @@ public final class httpdFileHandler {
// reading the files md5 hash if availabe and use it as ETAG of the resource
String targetMD5 = null;
- File targetMd5File = new File(targetFile + ".md5");
+ final File targetMd5File = new File(targetFile + ".md5");
try {
if (targetMd5File.exists()) {
//String description = null;
@@ -787,19 +787,19 @@ public final class httpdFileHandler {
// using the checksum as ETAG header
header.put(httpHeader.ETAG, targetMD5);
}
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
if (requestHeader.containsKey(httpHeader.RANGE)) {
- Object ifRange = requestHeader.ifRange();
+ final Object ifRange = requestHeader.ifRange();
if ((ifRange == null)||
(ifRange instanceof Date && targetFile.lastModified() == ((Date)ifRange).getTime()) ||
(ifRange instanceof String && ifRange.equals(targetMD5))) {
- String rangeHeaderVal = requestHeader.get(httpHeader.RANGE).trim();
+ final String rangeHeaderVal = requestHeader.get(httpHeader.RANGE).trim();
if (rangeHeaderVal.startsWith("bytes=")) {
- String rangesVal = rangeHeaderVal.substring("bytes=".length());
- String[] ranges = rangesVal.split(",");
+ final String rangesVal = rangeHeaderVal.substring("bytes=".length());
+ final String[] ranges = rangesVal.split(",");
if ((ranges.length == 1)&&(ranges[0].endsWith("-"))) {
rangeStartOffset = Integer.valueOf(ranges[0].substring(0,ranges[0].length()-1)).intValue();
statusCode = 206;
@@ -812,9 +812,9 @@ public final class httpdFileHandler {
// write the file to the client
targetDate = new Date(targetFile.lastModified());
- long contentLength = (zipContent)?-1:targetFile.length()-rangeStartOffset;
- String contentEncoding = (zipContent)?"gzip":null;
- String transferEncoding = (!httpVersion.equals(httpHeader.HTTP_VERSION_1_1))?null:(zipContent)?"chunked":null;
+ final long contentLength = (zipContent)?-1:targetFile.length()-rangeStartOffset;
+ final String contentEncoding = (zipContent)?"gzip":null;
+ final String transferEncoding = (!httpVersion.equals(httpHeader.HTTP_VERSION_1_1))?null:(zipContent)?"chunked":null;
if (!httpVersion.equals(httpHeader.HTTP_VERSION_1_1) && zipContent) forceConnectionClose(conProp);
httpd.sendRespondHeader(conProp, out, httpVersion, statusCode, null, mimeType, contentLength, targetDate, null, header, contentEncoding, transferEncoding, nocache);
@@ -844,13 +844,13 @@ public final class httpdFileHandler {
}
// flush all
- try {newOut.flush();}catch (Exception e) {}
+ try {newOut.flush();}catch (final Exception e) {}
// wait a little time until everything closes so that clients can read from the streams/sockets
if ((contentLength >= 0) && ((String)requestHeader.get(httpHeader.CONNECTION, "close")).indexOf("keep-alive") == -1) {
// in case that the client knows the size in advance (contentLength present) the waiting will have no effect on the interface performance
// but if the client waits on a connection interruption this will slow down.
- try {Thread.sleep(2000);} catch (InterruptedException e) {} // FIXME: is this necessary?
+ try {Thread.sleep(2000);} catch (final InterruptedException e) {} // FIXME: is this necessary?
}
}
@@ -864,15 +864,15 @@ public final class httpdFileHandler {
httpd.sendRespondError(conProp,out,3,404,"File not Found",null,null);
return;
}
- } catch (Exception e) {
+ } catch (final Exception e) {
try {
// doing some errorhandling ...
int httpStatusCode = 400;
- String httpStatusText = null;
- StringBuffer errorMessage = new StringBuffer();
+ final String httpStatusText = null;
+ final StringBuffer errorMessage = new StringBuffer();
Exception errorExc = null;
- String errorMsg = e.getMessage();
+ final String errorMsg = e.getMessage();
if (
(e instanceof InterruptedException) ||
((errorMsg != null) && (errorMsg.startsWith("Socket closed")) && (Thread.currentThread().isInterrupted()))
@@ -916,16 +916,16 @@ public final class httpdFileHandler {
theLogger.logWarning(new String(errorMessage),e);
}
- } catch (Exception ee) {
+ } catch (final Exception ee) {
forceConnectionClose(conProp);
}
} finally {
- try {out.flush();}catch (Exception e) {}
+ try {out.flush();}catch (final Exception e) {}
}
}
- public static final File getOverlayedClass(String path) {
+ public static final File getOverlayedClass(final String path) {
File targetClass;
targetClass = rewriteClassFile(new File(htDefaultPath, path)); //works for default and localized files
if (targetClass == null || !targetClass.exists()) {
@@ -935,7 +935,7 @@ public final class httpdFileHandler {
return targetClass;
}
- public static final File getOverlayedFile(String path) {
+ public static final File getOverlayedFile(final String path) {
File targetFile;
targetFile = getLocalizedFile(path);
if (!targetFile.exists()) {
@@ -944,33 +944,33 @@ public final class httpdFileHandler {
return targetFile;
}
- private static final void forceConnectionClose(Properties conprop) {
+ private static final void forceConnectionClose(final Properties conprop) {
if (conprop != null) {
conprop.setProperty(httpHeader.CONNECTION_PROP_PERSISTENT,"close");
}
}
- private static final File rewriteClassFile(File template) {
+ private static final File rewriteClassFile(final File template) {
try {
String f = template.getCanonicalPath();
- int p = f.lastIndexOf(".");
+ final int p = f.lastIndexOf(".");
if (p < 0) return null;
f = f.substring(0, p) + ".class";
//System.out.println("constructed class path " + f);
- File cf = new File(f);
+ final File cf = new File(f);
if (cf.exists()) return cf;
return null;
- } catch (IOException e) {
+ } catch (final IOException e) {
return null;
}
}
- private static final Method rewriteMethod(File classFile) {
+ private static final Method rewriteMethod(final File classFile) {
Method m = null;
// now make a class out of the stream
try {
if (useTemplateCache) {
- SoftReference<Method> ref = templateMethodCache.get(classFile);
+ final SoftReference<Method> ref = templateMethodCache.get(classFile);
if (ref != null) {
m = ref.get();
if (m == null) {
@@ -982,8 +982,8 @@ public final class httpdFileHandler {
}
}
- Class<?> c = provider.loadClass(classFile);
- Class<?>[] params = new Class[] {
+ final Class<?> c = provider.loadClass(classFile);
+ final Class<?>[] params = new Class[] {
httpHeader.class,
serverObjects.class,
serverSwitch.class };
@@ -991,20 +991,20 @@ public final class httpdFileHandler {
if (useTemplateCache) {
// storing the method into the cache
- SoftReference<Method> ref = new SoftReference<Method>(m);
+ final SoftReference<Method> ref = new SoftReference<Method>(m);
templateMethodCache.put(classFile, ref);
}
- } catch (ClassNotFoundException e) {
+ } catch (final ClassNotFoundException e) {
System.out.println("INTERNAL ERROR: class " + classFile + " is missing:" + e.getMessage());
- } catch (NoSuchMethodException e) {
+ } catch (final NoSuchMethodException e) {
System.out.println("INTERNAL ERROR: method respond not found in class " + classFile + ": " + e.getMessage());
}
//System.out.println("found method: " + m.toString());
return m;
}
- public static final Object invokeServlet(File targetClass, httpHeader request, serverObjects args) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
+ public static final Object invokeServlet(final File targetClass, final httpHeader request, final serverObjects args) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
Object result;
if (safeServletsMode) synchronized (switchboard) {
result = rewriteMethod(targetClass).invoke(null, new Object[] {request, args, switchboard});
@@ -1014,7 +1014,7 @@ public final class httpdFileHandler {
return result;
}
- public void doConnect(Properties conProp, httpHeader requestHeader, InputStream clientIn, OutputStream clientOut) {
+ public void doConnect(final Properties conProp, final httpHeader requestHeader, final InputStream clientIn, final OutputStream clientOut) {
throw new UnsupportedOperationException();
}
diff --git a/source/de/anomic/http/httpdLimitExceededException.java b/source/de/anomic/http/httpdLimitExceededException.java
index 061ea078b..a51317c11 100644
--- a/source/de/anomic/http/httpdLimitExceededException.java
+++ b/source/de/anomic/http/httpdLimitExceededException.java
@@ -29,9 +29,9 @@ import java.io.IOException;
public class httpdLimitExceededException extends IOException {
private static final long serialVersionUID = 1L;
- private long limit;
+ private final long limit;
- public httpdLimitExceededException(String errorMsg, long limit) {
+ public httpdLimitExceededException(final String errorMsg, final long limit) {
super(errorMsg);
this.limit = limit;
}
diff --git a/source/de/anomic/http/httpdProxyHandler.java b/source/de/anomic/http/httpdProxyHandler.java
index 29db52763..729aeeccd 100644
--- a/source/de/anomic/http/httpdProxyHandler.java
+++ b/source/de/anomic/http/httpdProxyHandler.java
@@ -130,11 +130,11 @@ public final class httpdProxyHandler {
theLogger.logInfo("Configuring proxy access logging ...");
// getting the logging manager
- LogManager manager = LogManager.getLogManager();
- String className = httpdProxyHandler.class.getName();
+ final LogManager manager = LogManager.getLogManager();
+ final String className = httpdProxyHandler.class.getName();
// determining if proxy access logging is enabled
- String enabled = manager.getProperty("de.anomic.http.httpdProxyHandler.logging.enabled");
+ final String enabled = manager.getProperty("de.anomic.http.httpdProxyHandler.logging.enabled");
if ("true".equalsIgnoreCase(enabled)) {
// reading out some needed configuration properties
@@ -142,18 +142,18 @@ public final class httpdProxyHandler {
String pattern = manager.getProperty(className + ".logging.FileHandler.pattern");
if (pattern == null) pattern = "DATA/LOG/proxyAccess%u%g.log";
- String limitStr = manager.getProperty(className + ".logging.FileHandler.limit");
- if (limitStr != null) try { limit = Integer.valueOf(limitStr).intValue(); } catch (NumberFormatException e) {}
+ final String limitStr = manager.getProperty(className + ".logging.FileHandler.limit");
+ if (limitStr != null) try { limit = Integer.valueOf(limitStr).intValue(); } catch (final NumberFormatException e) {}
- String countStr = manager.getProperty(className + ".logging.FileHandler.count");
- if (countStr != null) try { count = Integer.valueOf(countStr).intValue(); } catch (NumberFormatException e) {}
+ final String countStr = manager.getProperty(className + ".logging.FileHandler.count");
+ if (countStr != null) try { count = Integer.valueOf(countStr).intValue(); } catch (final NumberFormatException e) {}
// creating the proxy access logger
- Logger proxyLogger = Logger.getLogger("PROXY.access");
+ final Logger proxyLogger = Logger.getLogger("PROXY.access");
proxyLogger.setUseParentHandlers(false);
proxyLogger.setLevel(Level.FINEST);
- FileHandler txtLog = new FileHandler(pattern,limit,count,true);
+ final FileHandler txtLog = new FileHandler(pattern,limit,count,true);
txtLog.setFormatter(new serverMiniLogFormatter());
txtLog.setLevel(Level.FINEST);
proxyLogger.addHandler(txtLog);
@@ -166,7 +166,7 @@ public final class httpdProxyHandler {
} else {
theLogger.logInfo("Proxy access logging is deactivated.");
}
- } catch (Exception e) {
+ } catch (final Exception e) {
theLogger.logSevere("Unable to configure proxy access logging.",e);
}
@@ -196,14 +196,14 @@ public final class httpdProxyHandler {
yellowList = new HashSet<String>();
}
- String redirectorPath = switchboard.getConfig("externalRedirector", "");
+ final String redirectorPath = switchboard.getConfig("externalRedirector", "");
if (redirectorPath.length() > 0 && redirectorEnabled == false){
try {
redirectorProcess=Runtime.getRuntime().exec(redirectorPath);
redirectorWriter = new PrintWriter(redirectorProcess.getOutputStream());
redirectorReader = new BufferedReader(new InputStreamReader(redirectorProcess.getInputStream()));
redirectorEnabled=true;
- } catch (IOException e) {
+ } catch (final IOException e) {
System.out.println("redirector not Found");
}
}
@@ -227,7 +227,7 @@ public final class httpdProxyHandler {
private static final StringBuffer userAgentStr = new StringBuffer();
- public static void handleOutgoingCookies(httpHeader requestHeader, String targethost, String clienthost) {
+ public static void handleOutgoingCookies(final httpHeader requestHeader, final String targethost, final String clienthost) {
/*
The syntax for the header is:
@@ -242,7 +242,7 @@ public final class httpdProxyHandler {
*/
if (switchboard.getConfigBool("proxy.monitorCookies", false)) {
if (requestHeader.containsKey(httpHeader.COOKIE)) {
- Object[] entry = new Object[]{new Date(), clienthost, requestHeader.getMultiple(httpHeader.COOKIE)};
+ final Object[] entry = new Object[]{new Date(), clienthost, requestHeader.getMultiple(httpHeader.COOKIE)};
synchronized(switchboard.outgoingCookies) {
switchboard.outgoingCookies.put(targethost, entry);
}
@@ -250,7 +250,7 @@ public final class httpdProxyHandler {
}
}
- public static void handleIncomingCookies(httpHeader respondHeader, String serverhost, String targetclient) {
+ public static void handleIncomingCookies(final httpHeader respondHeader, final String serverhost, final String targetclient) {
/*
The syntax for the Set-Cookie response header is
@@ -268,7 +268,7 @@ public final class httpdProxyHandler {
*/
if (switchboard.getConfigBool("proxy.monitorCookies", false)) {
if (respondHeader.containsKey(httpHeader.SET_COOKIE)) {
- Object[] entry = new Object[]{new Date(), targetclient, respondHeader.getMultiple(httpHeader.SET_COOKIE)};
+ final Object[] entry = new Object[]{new Date(), targetclient, respondHeader.getMultiple(httpHeader.SET_COOKIE)};
synchronized(switchboard.incomingCookies) {
switchboard.incomingCookies.put(serverhost, entry);
}
@@ -282,7 +282,7 @@ public final class httpdProxyHandler {
* @param respond the OutputStream to the client
* @see de.anomic.http.httpdHandler#doGet(java.util.Properties, de.anomic.http.httpHeader, java.io.OutputStream)
*/
- public static void doGet(Properties conProp, httpHeader requestHeader, OutputStream respond) {
+ public static void doGet(final Properties conProp, final httpHeader requestHeader, final OutputStream respond) {
httpdByteCountOutputStream countedRespond = null;
try {
final int reqID = requestHeader.hashCode();
@@ -314,11 +314,11 @@ public final class httpdProxyHandler {
redirectorWriter.println(url.toNormalform(false, true));
redirectorWriter.flush();
}
- String newUrl = redirectorReader.readLine();
+ final String newUrl = redirectorReader.readLine();
if (!newUrl.equals("")) {
try {
url = new yacyURL(newUrl, null);
- } catch(MalformedURLException e){}//just keep the old one
+ } catch(final MalformedURLException e){}//just keep the old one
}
theLogger.logFinest(reqID +" using redirector to "+ url);
conProp.setProperty(httpHeader.CONNECTION_PROP_HOST, url.getHost()+":"+url.getPort());
@@ -326,8 +326,8 @@ public final class httpdProxyHandler {
requestHeader.put(httpHeader.HOST, url.getHost()+":"+url.getPort());
requestHeader.put(httpHeader.CONNECTION_PROP_PATH, url.getPath());
}
- } catch (MalformedURLException e) {
- String errorMsg = "ERROR: internal error with url generation: host=" +
+ } catch (final MalformedURLException e) {
+ final String errorMsg = "ERROR: internal error with url generation: host=" +
host + ", port=" + port + ", path=" + path + ", args=" + args;
theLogger.logSevere(errorMsg);
httpd.sendRespondError(conProp,countedRespond,4,501,null,errorMsg,e);
@@ -351,7 +351,7 @@ public final class httpdProxyHandler {
// check the blacklist
// blacklist idea inspired by [AS]:
// respond a 404 for all AGIS ("all you get is shit") servers
- String hostlow = host.toLowerCase();
+ final String hostlow = host.toLowerCase();
if (args != null) { path = path + "?" + args; }
if (plasmaSwitchboard.urlBlacklist.isListed(indexReferenceBlacklist.BLACKLIST_PROXY, hostlow, path)) {
theLogger.logInfo("AGIS blocking of host '" + hostlow + "'");
@@ -366,10 +366,10 @@ public final class httpdProxyHandler {
prepareRequestHeader(conProp, requestHeader, hostlow);
// decide whether to use a cache entry or connect to the network
- File cacheFile = plasmaHTCache.getCachePath(url);
+ final File cacheFile = plasmaHTCache.getCachePath(url);
httpHeader cachedResponseHeader = null;
- ResourceInfo cachedResInfo = (ResourceInfo) plasmaHTCache.loadResourceInfo(url);
+ final ResourceInfo cachedResInfo = (ResourceInfo) plasmaHTCache.loadResourceInfo(url);
if (cachedResInfo != null) {
// set the new request header (needed by function shallUseCacheForProxy)
cachedResInfo.setRequestHeader(requestHeader);
@@ -377,7 +377,7 @@ public final class httpdProxyHandler {
// get the cached response header
cachedResponseHeader = cachedResInfo.getResponseHeader();
}
- boolean cacheExists = cacheFile.isFile() && (cachedResponseHeader != null);
+ 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
@@ -401,7 +401,7 @@ public final class httpdProxyHandler {
// 4. cache stale - refill - superfluous
// in two of these cases we trigger a scheduler to handle newly arrived files:
// case 1 and case 3
- plasmaHTCache.Entry cacheEntry = (cachedResponseHeader == null) ? null :
+ final plasmaHTCache.Entry cacheEntry = (cachedResponseHeader == null) ? null :
plasmaHTCache.newEntry(
requestDate, // init date
0, // crawling depth
@@ -430,23 +430,23 @@ public final class httpdProxyHandler {
fulfillRequestFromWeb(conProp,url,ext,requestHeader,cachedResponseHeader,cacheFile,countedRespond);
}
- } catch (Exception e) {
+ } catch (final Exception e) {
try {
- String exTxt = e.getMessage();
+ final String exTxt = e.getMessage();
if ((exTxt!=null)&&(exTxt.startsWith("Socket closed"))) {
forceConnectionClose(conProp);
} else if (!conProp.containsKey(httpHeader.CONNECTION_PROP_PROXY_RESPOND_HEADER)) {
- String errorMsg = "Unexpected Error. " + e.getClass().getName() + ": " + e.getMessage();
+ final String errorMsg = "Unexpected Error. " + e.getClass().getName() + ": " + e.getMessage();
httpd.sendRespondError(conProp,countedRespond,4,501,null,errorMsg,e);
theLogger.logSevere(errorMsg);
} else {
forceConnectionClose(conProp);
}
- } catch (Exception ee) {
+ } catch (final Exception ee) {
forceConnectionClose(conProp);
}
} finally {
- try { if(countedRespond != null) countedRespond.flush(); else if(respond != null) respond.flush(); } catch (Exception e) {}
+ try { if(countedRespond != null) countedRespond.flush(); else if(respond != null) respond.flush(); } catch (final Exception e) {}
if (countedRespond != null) countedRespond.finish();
conProp.put(httpHeader.CONNECTION_PROP_REQUEST_END,new Long(System.currentTimeMillis()));
@@ -455,9 +455,9 @@ public final class httpdProxyHandler {
}
}
- private static void fulfillRequestFromWeb(Properties conProp, yacyURL url,String ext, httpHeader requestHeader, httpHeader cachedResponseHeader, File cacheFile, OutputStream respond) {
+ private static void fulfillRequestFromWeb(final Properties conProp, final yacyURL url,final String ext, final httpHeader requestHeader, final httpHeader cachedResponseHeader, final File cacheFile, final OutputStream respond) {
- GZIPOutputStream gzippedOut = null;
+ final GZIPOutputStream gzippedOut = null;
Writer hfos = null;
JakartaCommonsHttpResponse res = null;
@@ -465,10 +465,10 @@ public final class httpdProxyHandler {
final int reqID = requestHeader.hashCode();
String host = conProp.getProperty(httpHeader.CONNECTION_PROP_HOST);
- String path = conProp.getProperty(httpHeader.CONNECTION_PROP_PATH); // always starts with leading '/'
- String args = conProp.getProperty(httpHeader.CONNECTION_PROP_ARGS); // may be null if no args were given
- String ip = conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP); // the ip from the connecting peer
- String httpVer = conProp.getProperty(httpHeader.CONNECTION_PROP_HTTP_VER); // the ip from the connecting peer
+ final String path = conProp.getProperty(httpHeader.CONNECTION_PROP_PATH); // always starts with leading '/'
+ final String args = conProp.getProperty(httpHeader.CONNECTION_PROP_ARGS); // may be null if no args were given
+ final String ip = conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP); // the ip from the connecting peer
+ final String httpVer = conProp.getProperty(httpHeader.CONNECTION_PROP_HTTP_VER); // the ip from the connecting peer
int port, pos;
if ((pos = host.indexOf(":")) < 0) {
@@ -479,7 +479,7 @@ public final class httpdProxyHandler {
}
// resolve yacy and yacyh domains
- String yAddress = resolveYacyDomains(host);
+ final String yAddress = resolveYacyDomains(host);
// re-calc the url path
String remotePath = (args == null) ? path : (path + "?" + args); // with leading '/'
@@ -527,9 +527,9 @@ public final class httpdProxyHandler {
}
// reserver cache entry
- Date requestDate = new Date(((Long)conProp.get(httpHeader.CONNECTION_PROP_REQUEST_START)).longValue());
- IResourceInfo resInfo = new ResourceInfo(url,requestHeader,responseHeader);
- plasmaHTCache.Entry cacheEntry = plasmaHTCache.newEntry(
+ final Date requestDate = new Date(((Long)conProp.get(httpHeader.CONNECTION_PROP_REQUEST_START)).longValue());
+ final IResourceInfo resInfo = new ResourceInfo(url,requestHeader,responseHeader);
+ final plasmaHTCache.Entry cacheEntry = plasmaHTCache.newEntry(
requestDate,
0,
url,
@@ -578,9 +578,9 @@ public final class httpdProxyHandler {
res.getStatusLine().substring(4), // status text
responseHeader);
- String storeError = cacheEntry.shallStoreCacheForProxy();
- boolean storeHTCache = cacheEntry.profile().storeHTCache();
- boolean isSupportedContent = plasmaParser.supportedContent(plasmaParser.PARSER_MODE_PROXY,cacheEntry.url(),cacheEntry.getMimeType());
+ final String storeError = cacheEntry.shallStoreCacheForProxy();
+ final boolean storeHTCache = cacheEntry.profile().storeHTCache();
+ final boolean isSupportedContent = plasmaParser.supportedContent(plasmaParser.PARSER_MODE_PROXY,cacheEntry.url(),cacheEntry.getMimeType());
if (
/*
* Now we store the response into the htcache directory if
@@ -598,7 +598,7 @@ public final class httpdProxyHandler {
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.
- ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
+ final ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
writeContent(res, new BufferedWriter(hfos), byteStream);
// cached bytes
byte[] cacheArray;
@@ -692,7 +692,7 @@ public final class httpdProxyHandler {
res.closeStream();
}
}
- } catch (Exception e) {
+ } catch (final Exception e) {
// deleting cached content
if (cacheFile.exists()) cacheFile.delete();
handleProxyException(e,conProp,respond,url);
@@ -700,19 +700,19 @@ public final class httpdProxyHandler {
}
private static void fulfillRequestFromCache(
- Properties conProp,
- yacyURL url,
- String ext,
- httpHeader requestHeader,
- httpHeader cachedResponseHeader,
- File cacheFile,
- OutputStream respond
+ final Properties conProp,
+ final yacyURL url,
+ final String ext,
+ final httpHeader requestHeader,
+ final httpHeader cachedResponseHeader,
+ final File cacheFile,
+ final OutputStream respond
) throws IOException {
- String httpVer = conProp.getProperty(httpHeader.CONNECTION_PROP_HTTP_VER);
+ final String httpVer = conProp.getProperty(httpHeader.CONNECTION_PROP_HTTP_VER);
- httpChunkedOutputStream chunkedOut = null;
- GZIPOutputStream gzippedOut = null;
+ final httpChunkedOutputStream chunkedOut = null;
+ final GZIPOutputStream gzippedOut = null;
Object hfos = null;
// we respond on the request by using the cache, the cache is fresh
@@ -759,7 +759,7 @@ public final class httpdProxyHandler {
//respondHeader(respond, "203 OK", cachedResponseHeader); // respond with 'non-authoritative'
// determine the content charset
- String charSet = httpHeader.getCharSet(cachedResponseHeader);
+ final String charSet = httpHeader.getCharSet(cachedResponseHeader);
// make a transformer
final OutputStream outStream = (gzippedOut != null) ? gzippedOut : ((chunkedOut != null)? chunkedOut : respond);
@@ -784,7 +784,7 @@ public final class httpdProxyHandler {
if (chunkedOut != null) chunkedOut.finish();
}
// that's it!
- } catch (Exception e) {
+ } catch (final Exception e) {
// this happens if the client stops loading the file
// we do nothing here
if (conProp.containsKey(httpHeader.CONNECTION_PROP_PROXY_RESPOND_HEADER)) {
@@ -794,42 +794,42 @@ public final class httpdProxyHandler {
httpd.sendRespondError(conProp,respond,4,503,"socket error: " + e.getMessage(),"socket error: " + e.getMessage(), e);
}
} finally {
- try { respond.flush(); } catch (Exception e) {}
+ try { respond.flush(); } catch (final Exception e) {}
}
return;
}
- public static void writeContent(JakartaCommonsHttpResponse res, BufferedWriter hfos) throws IOException, UnsupportedEncodingException {
+ public static void writeContent(final JakartaCommonsHttpResponse res, final BufferedWriter hfos) throws IOException, UnsupportedEncodingException {
try {
- InputStream data = res.getDataAsStream();
+ final InputStream data = res.getDataAsStream();
if (data == null) return;
- String charSet = httpHeader.getCharSet(res.getResponseHeader());
+ final String charSet = httpHeader.getCharSet(res.getResponseHeader());
serverFileUtils.copyToWriter(new BufferedInputStream(data), hfos, charSet);
} finally {
res.closeStream();
}
}
- public static void writeContent(JakartaCommonsHttpResponse res, BufferedWriter hfos, OutputStream byteStream) throws IOException, UnsupportedEncodingException {
+ public static void writeContent(final JakartaCommonsHttpResponse res, final BufferedWriter hfos, final OutputStream byteStream) throws IOException, UnsupportedEncodingException {
assert byteStream != null;
try {
- InputStream data = res.getDataAsStream();
+ final InputStream data = res.getDataAsStream();
if (data == null) return;
- String charSet = httpHeader.getCharSet(res.getResponseHeader());
+ final String charSet = httpHeader.getCharSet(res.getResponseHeader());
serverFileUtils.copyToWriters(new BufferedInputStream(data), hfos, new BufferedWriter(new OutputStreamWriter(byteStream, charSet)) , charSet);
} finally {
res.closeStream();
}
}
- public static void doHead(Properties conProp, httpHeader requestHeader, OutputStream respond) {
+ public static void doHead(final Properties conProp, final httpHeader requestHeader, OutputStream respond) {
JakartaCommonsHttpResponse res = null;
yacyURL url = null;
try {
final int reqID = requestHeader.hashCode();
// remembering the starting time of the request
- Date requestDate = new Date(); // remember the time...
+ final Date requestDate = new Date(); // remember the time...
conProp.put(httpHeader.CONNECTION_PROP_REQUEST_START,new Long(requestDate.getTime()));
if (yacyTrigger) de.anomic.yacy.yacyCore.triggerOnlineAction();
switchboard.proxyLastAccess = System.currentTimeMillis();
@@ -838,9 +838,9 @@ public final class httpdProxyHandler {
respond = new httpdByteCountOutputStream(respond,conProp.getProperty(httpHeader.CONNECTION_PROP_REQUESTLINE).length() + 2,"PROXY");
String host = conProp.getProperty(httpHeader.CONNECTION_PROP_HOST);
- String path = conProp.getProperty(httpHeader.CONNECTION_PROP_PATH);
- String args = conProp.getProperty(httpHeader.CONNECTION_PROP_ARGS);
- String httpVer = conProp.getProperty(httpHeader.CONNECTION_PROP_HTTP_VER);
+ final String path = conProp.getProperty(httpHeader.CONNECTION_PROP_PATH);
+ final String args = conProp.getProperty(httpHeader.CONNECTION_PROP_ARGS);
+ final String httpVer = conProp.getProperty(httpHeader.CONNECTION_PROP_HTTP_VER);
int port, pos;
if ((pos = host.indexOf(":")) < 0) {
@@ -852,8 +852,8 @@ public final class httpdProxyHandler {
try {
url = new yacyURL("http", host, port, (args == null) ? path : path + "?" + args);
- } catch (MalformedURLException e) {
- String errorMsg = "ERROR: internal error with url generation: host=" +
+ } catch (final MalformedURLException e) {
+ final String errorMsg = "ERROR: internal error with url generation: host=" +
host + ", port=" + port + ", path=" + path + ", args=" + args;
theLogger.logSevere(errorMsg);
httpd.sendRespondError(conProp,respond,4,501,null,errorMsg,e);
@@ -863,7 +863,7 @@ public final class httpdProxyHandler {
theLogger.logFinest(reqID +" header: "+ requestHeader);
// check the blacklist, inspired by [AS]: respond a 404 for all AGIS (all you get is shit) servers
- String hostlow = host.toLowerCase();
+ final String hostlow = host.toLowerCase();
// re-calc the url path
String remotePath = (args == null) ? path : (path + "?" + args);
@@ -878,7 +878,7 @@ public final class httpdProxyHandler {
prepareRequestHeader(conProp, requestHeader, hostlow);
// resolve yacy and yacyh domains
- String yAddress = resolveYacyDomains(host);
+ final String yAddress = resolveYacyDomains(host);
// attach possible yacy-sublevel-domain
if ((yAddress != null) && ((pos = yAddress.indexOf("/")) >= 0)) remotePath = yAddress.substring(pos) + remotePath;
@@ -915,12 +915,12 @@ public final class httpdProxyHandler {
res.closeStream();
}
}
- } catch (Exception e) {
+ } catch (final Exception e) {
handleProxyException(e,conProp,respond,url);
}
}
- public static void doPost(Properties conProp, httpHeader requestHeader, OutputStream respond, InputStream body) throws IOException {
+ public static void doPost(final Properties conProp, final httpHeader requestHeader, final OutputStream respond, InputStream body) throws IOException {
assert conProp != null : "precondition violated: conProp != null";
assert requestHeader != null : "precondition violated: requestHeader != null";
assert body != null : "precondition violated: body != null";
@@ -929,7 +929,7 @@ public final class httpdProxyHandler {
try {
final int reqID = requestHeader.hashCode();
// remembering the starting time of the request
- Date requestDate = new Date(); // remember the time...
+ final Date requestDate = new Date(); // remember the time...
conProp.put(httpHeader.CONNECTION_PROP_REQUEST_START,new Long(requestDate.getTime()));
if (yacyTrigger) de.anomic.yacy.yacyCore.triggerOnlineAction();
switchboard.proxyLastAccess = System.currentTimeMillis();
@@ -938,9 +938,9 @@ public final class httpdProxyHandler {
countedRespond = new httpdByteCountOutputStream(respond,conProp.getProperty(httpHeader.CONNECTION_PROP_REQUESTLINE).length() + 2,"PROXY");
String host = conProp.getProperty(httpHeader.CONNECTION_PROP_HOST);
- String path = conProp.getProperty(httpHeader.CONNECTION_PROP_PATH);
- String args = conProp.getProperty(httpHeader.CONNECTION_PROP_ARGS); // may be null if no args were given
- String httpVer = conProp.getProperty(httpHeader.CONNECTION_PROP_HTTP_VER);
+ final String path = conProp.getProperty(httpHeader.CONNECTION_PROP_PATH);
+ final String args = conProp.getProperty(httpHeader.CONNECTION_PROP_ARGS); // may be null if no args were given
+ final String httpVer = conProp.getProperty(httpHeader.CONNECTION_PROP_HTTP_VER);
int port, pos;
if ((pos = host.indexOf(":")) < 0) {
@@ -952,8 +952,8 @@ public final class httpdProxyHandler {
try {
url = new yacyURL("http", host, port, (args == null) ? path : path + "?" + args);
- } catch (MalformedURLException e) {
- String errorMsg = "ERROR: internal error with url generation: host=" +
+ } catch (final MalformedURLException e) {
+ final String errorMsg = "ERROR: internal error with url generation: host=" +
host + ", port=" + port + ", path=" + path + ", args=" + args;
theLogger.logSevere(errorMsg);
httpd.sendRespondError(conProp,countedRespond,4,501,null,errorMsg,e);
@@ -964,7 +964,7 @@ public final class httpdProxyHandler {
prepareRequestHeader(conProp, requestHeader, host.toLowerCase());
- String yAddress = resolveYacyDomains(host);
+ final String yAddress = resolveYacyDomains(host);
// re-calc the url path
String remotePath = (args == null) ? path : (path + "?" + args);
@@ -990,7 +990,7 @@ public final class httpdProxyHandler {
// input so we have to end it to do the request
final long requestLength = requestHeader.contentLength();
if(requestLength > -1) {
- ByteArrayOutputStream buffer = new ByteArrayOutputStream();
+ final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
serverFileUtils.copy(body, buffer, requestLength);
body = new ByteArrayInputStream(buffer.toByteArray());
}
@@ -1045,7 +1045,7 @@ public final class httpdProxyHandler {
res.closeStream();
}
}
- } catch (Exception e) {
+ } catch (final Exception e) {
handleProxyException(e,conProp,countedRespond,url);
} finally {
if(countedRespond != null) {
@@ -1068,7 +1068,7 @@ public final class httpdProxyHandler {
* @param host
* @return
*/
- private static String resolveYacyDomains(String host) {
+ private static String resolveYacyDomains(final String host) {
return (httpd.alternativeResolver == null) ? null : httpd.alternativeResolver.resolve(host);
}
@@ -1078,7 +1078,7 @@ public final class httpdProxyHandler {
* @param yAddress
* @return
*/
- private static String hostPart(String host, int port, String yAddress) {
+ private static String hostPart(final String host, final int port, final String yAddress) {
final String connectHost = (yAddress == null) ? host +":"+ port : yAddress;
return connectHost;
}
@@ -1088,7 +1088,7 @@ public final class httpdProxyHandler {
* @param requestHeader
* @param hostlow
*/
- private static void prepareRequestHeader(Properties conProp, httpHeader requestHeader, String hostlow) {
+ private static void prepareRequestHeader(final Properties conProp, final httpHeader requestHeader, final String hostlow) {
// set another userAgent, if not yellow-listed
if ((yellowList != null) && (!(yellowList.contains(domain(hostlow))))) {
// change the User-Agent
@@ -1098,7 +1098,7 @@ public final class httpdProxyHandler {
addXForwardedForHeader(conProp, requestHeader);
}
- private static String domain(String host) {
+ private static String domain(final String host) {
String domain = host;
int pos = domain.lastIndexOf(".");
if (pos >= 0) {
@@ -1149,8 +1149,8 @@ public final class httpdProxyHandler {
* @param respond
* @return
*/
- private static httpChunkedOutputStream setTransferEncoding(Properties conProp, final httpHeader responseHeader,
- int statusCode, OutputStream respond) {
+ private static httpChunkedOutputStream setTransferEncoding(final Properties conProp, final httpHeader responseHeader,
+ final int statusCode, final OutputStream respond) {
final String httpVer = conProp.getProperty(httpHeader.CONNECTION_PROP_HTTP_VER);
httpChunkedOutputStream chunkedOut = null;
// gzipped response is ungzipped an therefor the length is unknown
@@ -1199,7 +1199,7 @@ public final class httpdProxyHandler {
* @param conProp
* @param requestHeader
*/
- private static void addXForwardedForHeader(Properties conProp, httpHeader requestHeader) {
+ private static void addXForwardedForHeader(final Properties conProp, final httpHeader requestHeader) {
// setting the X-Forwarded-For Header
if (switchboard.getConfigBool("proxy.sendXForwardedForHeader", true)) {
requestHeader.put(httpHeader.X_FORWARDED_FOR, conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP));
@@ -1217,7 +1217,7 @@ public final class httpdProxyHandler {
setViaHeader(requestHeader, httpVer);
}
- private static void removeHopByHopHeaders(httpHeader headers) {
+ private static void removeHopByHopHeaders(final httpHeader headers) {
/*
- Trailers
*/
@@ -1242,13 +1242,13 @@ public final class httpdProxyHandler {
headers.remove(httpHeader.X_YACY_ORIGINAL_REQUEST_LINE);
}
- private static void setViaHeader(httpHeader header, String httpVer) {
+ private static void setViaHeader(final httpHeader header, final String httpVer) {
if (!switchboard.getConfigBool("proxy.sendViaHeader", true)) return;
- String myAddress = (httpd.alternativeResolver == null) ? null : httpd.alternativeResolver.myAlternativeAddress();
+ final String myAddress = (httpd.alternativeResolver == null) ? null : httpd.alternativeResolver.myAlternativeAddress();
if (myAddress != null) {
// getting header set by other proxies in the chain
- StringBuffer viaValue = new StringBuffer();
+ final StringBuffer viaValue = new StringBuffer();
if (header.containsKey(httpHeader.VIA)) viaValue.append(header.get(httpHeader.VIA));
if (viaValue.length() > 0) viaValue.append(", ");
@@ -1263,12 +1263,12 @@ public final class httpdProxyHandler {
}
}
- public static void doConnect(Properties conProp, de.anomic.http.httpHeader requestHeader, InputStream clientIn, OutputStream clientOut) throws IOException {
+ public static void doConnect(final Properties conProp, final de.anomic.http.httpHeader requestHeader, final InputStream clientIn, final OutputStream clientOut) throws IOException {
switchboard.proxyLastAccess = System.currentTimeMillis();
String host = conProp.getProperty(httpHeader.CONNECTION_PROP_HOST);
- String httpVersion = conProp.getProperty(httpHeader.CONNECTION_PROP_HTTP_VER);
+ final String httpVersion = conProp.getProperty(httpHeader.CONNECTION_PROP_HTTP_VER);
String path = conProp.getProperty(httpHeader.CONNECTION_PROP_PATH);
final String args = conProp.getProperty(httpHeader.CONNECTION_PROP_ARGS);
if (args != null) { path = path + "?" + args; }
@@ -1300,7 +1300,7 @@ public final class httpdProxyHandler {
(proxyConfig.useProxy()) &&
(proxyConfig.useProxy4SSL())
) {
- JakartaCommonsHttpClient remoteProxy = new JakartaCommonsHttpClient(timeout, requestHeader, proxyConfig);
+ final JakartaCommonsHttpClient remoteProxy = new JakartaCommonsHttpClient(timeout, requestHeader, proxyConfig);
remoteProxy.setFollowRedirects(false); // should not be needed, but safe is safe
JakartaCommonsHttpResponse response = null;
@@ -1322,7 +1322,7 @@ public final class httpdProxyHandler {
forceConnectionClose(conProp);
return;
}
- } catch (Exception e) {
+ } catch (final Exception e) {
throw new IOException(e.getMessage());
} finally {
if(response != null) {
@@ -1333,11 +1333,11 @@ public final class httpdProxyHandler {
}
// try to establish connection to remote host
- Socket sslSocket = new Socket(host, port);
+ final Socket sslSocket = new Socket(host, port);
sslSocket.setSoTimeout(timeout); // waiting time for write
sslSocket.setSoLinger(true, timeout); // waiting time for read
- InputStream promiscuousIn = sslSocket.getInputStream();
- OutputStream promiscuousOut = sslSocket.getOutputStream();
+ final InputStream promiscuousIn = sslSocket.getInputStream();
+ final OutputStream promiscuousOut = sslSocket.getOutputStream();
// now then we can return a success message
clientOut.write((httpVersion + " 200 Connection established" + serverCore.CRLF_STRING +
@@ -1347,8 +1347,8 @@ public final class httpdProxyHandler {
theLogger.logInfo("SSL connection to " + host + ":" + port + " established.");
// start stream passing with mediate processes
- Mediate cs = new Mediate(sslSocket, clientIn, promiscuousOut);
- Mediate sc = new Mediate(sslSocket, promiscuousIn, clientOut);
+ final Mediate cs = new Mediate(sslSocket, clientIn, promiscuousOut);
+ final Mediate sc = new Mediate(sslSocket, promiscuousIn, clientOut);
cs.start();
sc.start();
while ((sslSocket != null) &&
@@ -1357,7 +1357,7 @@ public final class httpdProxyHandler {
(sslSocket.isConnected()) &&
((cs.isAlive()) || (sc.isAlive()))) {
// idle
- try {Thread.sleep(1000);} catch (InterruptedException e) {} // wait a while
+ try {Thread.sleep(1000);} catch (final InterruptedException e) {} // wait a while
}
// set stop mode
cs.pleaseTerminate();
@@ -1375,7 +1375,7 @@ public final class httpdProxyHandler {
InputStream in;
OutputStream out;
- public Mediate(Socket socket, InputStream in, OutputStream out) {
+ public Mediate(final Socket socket, final InputStream in, final OutputStream out) {
this.terminate = false;
this.in = in;
this.out = out;
@@ -1383,7 +1383,7 @@ public final class httpdProxyHandler {
}
public void run() {
- byte[] buffer = new byte[512];
+ final byte[] buffer = new byte[512];
int len;
try {
while ((socket != null) &&
@@ -1397,7 +1397,7 @@ public final class httpdProxyHandler {
) {
out.write(buffer, 0, len);
}
- } catch (IOException e) {}
+ } catch (final IOException e) {}
}
public void pleaseTerminate() {
@@ -1464,7 +1464,7 @@ public final class httpdProxyHandler {
* @param address full address with host and optionally port or path <host>:<port>/<path>
* @return null if no proxy should be used
*/
- public static httpRemoteProxyConfig getProxyConfig(String address) {
+ public static httpRemoteProxyConfig getProxyConfig(final String address) {
// host goes to port
int p = address.indexOf(":");
if (p < 0) {
@@ -1473,7 +1473,7 @@ public final class httpdProxyHandler {
}
// host should have minimum 1 character ;)
if(p > 0) {
- String server = address.substring(0, p);
+ final String server = address.substring(0, p);
return getProxyConfig(server, 0);
} else {
// check if full address is in allow/deny-list
@@ -1481,7 +1481,7 @@ public final class httpdProxyHandler {
}
}
- private static void handleProxyException(Exception e, Properties conProp, OutputStream respond, yacyURL url) {
+ private static void handleProxyException(final Exception e, final Properties conProp, final OutputStream respond, final yacyURL url) {
// this may happen if
// - the targeted host does not exist
// - anything with the remote server was wrong.
@@ -1515,13 +1515,13 @@ public final class httpdProxyHandler {
httpStatusText = "Unknown Host";
detailedErrorMsg = true;
detailedErrorMsgFile = "proxymsg/unknownHost.inc";
- } catch (Exception e1) {
+ } catch (final Exception e1) {
errorMessage = "IP address of the destination host could not be determined";
}
} else if (e instanceof SocketTimeoutException) {
errorMessage = "Unable to establish a connection to the destination host. Connect timed out.";
} else {
- String exceptionMsg = e.getMessage();
+ final String exceptionMsg = e.getMessage();
if ((exceptionMsg != null) && (exceptionMsg.indexOf("Corrupt GZIP trailer") >= 0)) {
// just do nothing, we leave it this way
theLogger.logFine("ignoring bad gzip trail for URL " + url + " (" + e.getMessage() + ")");
@@ -1534,7 +1534,7 @@ public final class httpdProxyHandler {
httpStatusText = "Unknown Host";
detailedErrorMsg = true;
detailedErrorMsgFile = "proxymsg/unknownHost.inc";
- } catch (Exception e1) {
+ } catch (final Exception e1) {
errorMessage = "IP address of the destination host could not be determined";
}
} else if ((exceptionMsg != null) &&
@@ -1574,23 +1574,23 @@ public final class httpdProxyHandler {
}
forceConnectionClose(conProp);
}
- } catch (Exception ee) {
+ } catch (final Exception ee) {
forceConnectionClose(conProp);
}
}
- private static void forceConnectionClose(Properties conProp) {
+ private static void forceConnectionClose(final Properties conProp) {
if (conProp != null) {
conProp.setProperty(httpHeader.CONNECTION_PROP_PERSISTENT,"close");
}
}
- private static serverObjects unknownHostHandling(Properties conProp) throws Exception {
- serverObjects detailedErrorMsgMap = new serverObjects();
+ private static serverObjects unknownHostHandling(final Properties conProp) throws Exception {
+ final serverObjects detailedErrorMsgMap = new serverObjects();
// generic toplevel domains
- HashSet<String> topLevelDomains = new HashSet<String>(Arrays.asList(new String[]{
+ final HashSet<String> topLevelDomains = new HashSet<String>(Arrays.asList(new String[]{
"aero", // Fluggesellschaften/Luftfahrt
"arpa", // Einrichtung des ARPANet
"biz", // Business
@@ -1626,42 +1626,42 @@ public final class httpdProxyHandler {
orgHostPort = orgHostName.substring(pos+1);
orgHostName = orgHostName.substring(0,pos);
}
- String orgHostPath = conProp.getProperty(httpHeader.CONNECTION_PROP_PATH,"");
+ final String orgHostPath = conProp.getProperty(httpHeader.CONNECTION_PROP_PATH,"");
String orgHostArgs = conProp.getProperty(httpHeader.CONNECTION_PROP_ARGS,"");
if (orgHostArgs.length() > 0) orgHostArgs = "?" + orgHostArgs;
detailedErrorMsgMap.put("hostName", orgHostName);
// guessing hostnames
- HashSet<String> testHostNames = new HashSet<String>();
+ final HashSet<String> testHostNames = new HashSet<String>();
String testHostName = null;
if (!orgHostName.startsWith("www.")) {
testHostName = "www." + orgHostName;
- InetAddress addr = serverDomains.dnsResolve(testHostName);
+ final InetAddress addr = serverDomains.dnsResolve(testHostName);
if (addr != null) testHostNames.add(testHostName);
} else if (orgHostName.startsWith("www.")) {
testHostName = orgHostName.substring(4);
- InetAddress addr = serverDomains.dnsResolve(testHostName);
+ final InetAddress addr = serverDomains.dnsResolve(testHostName);
if (addr != null) if (addr != null) testHostNames.add(testHostName);
}
if (orgHostName.length()>4 && orgHostName.startsWith("www") && (orgHostName.charAt(3) != '.')) {
testHostName = orgHostName.substring(0,3) + "." + orgHostName.substring(3);
- InetAddress addr = serverDomains.dnsResolve(testHostName);
+ final InetAddress addr = serverDomains.dnsResolve(testHostName);
if (addr != null) if (addr != null) testHostNames.add(testHostName);
}
pos = orgHostName.lastIndexOf(".");
if (pos != -1) {
- Iterator<String> iter = topLevelDomains.iterator();
+ final Iterator<String> iter = topLevelDomains.iterator();
while (iter.hasNext()) {
- String topLevelDomain = iter.next();
+ final String topLevelDomain = iter.next();
testHostName = orgHostName.substring(0,pos) + "." + topLevelDomain;
- InetAddress addr = serverDomains.dnsResolve(testHostName);
+ final InetAddress addr = serverDomains.dnsResolve(testHostName);
if (addr != null) if (addr != null) testHostNames.add(testHostName);
}
}
int hostNameCount = 0;
- Iterator<String> iter = testHostNames.iterator();
+ final Iterator<String> iter = testHostNames.iterator();
while (iter.hasNext()) {
testHostName = iter.next();
detailedErrorMsgMap.put("list_" + hostNameCount + "_hostName",testHostName);
@@ -1682,11 +1682,11 @@ public final class httpdProxyHandler {
return detailedErrorMsgMap;
}
- private static synchronized String generateUserAgent(httpHeader requestHeaders) {
+ private static synchronized String generateUserAgent(final httpHeader requestHeaders) {
userAgentStr.setLength(0);
- String browserUserAgent = (String) requestHeaders.get(httpHeader.USER_AGENT, HTTPLoader.yacyUserAgent);
- int pos = browserUserAgent.lastIndexOf(')');
+ final String browserUserAgent = (String) requestHeaders.get(httpHeader.USER_AGENT, HTTPLoader.yacyUserAgent);
+ final int pos = browserUserAgent.lastIndexOf(')');
if (pos >= 0) {
userAgentStr
.append(browserUserAgent.substring(0,pos))
@@ -1707,15 +1707,15 @@ public final class httpdProxyHandler {
* e.g.<br>
* <code>1117528623.857 178 192.168.1.201 TCP_MISS/200 1069 GET http://www.yacy.de/ - DIRECT/81.169.145.74 text/html</code>
*/
- private final static synchronized void logProxyAccess(Properties conProp) {
+ private final static synchronized void logProxyAccess(final Properties conProp) {
if (!doAccessLogging) return;
logMessage.setLength(0);
// Timestamp
- String currentTimestamp = Long.toString(System.currentTimeMillis());
- int offset = currentTimestamp.length()-3;
+ final String currentTimestamp = Long.toString(System.currentTimeMillis());
+ final int offset = currentTimestamp.length()-3;
logMessage.append(currentTimestamp.substring(0,offset));
logMessage.append('.');
@@ -1723,40 +1723,40 @@ public final class httpdProxyHandler {
logMessage.append(' ');
// Elapsed time
- Long requestStart = (Long) conProp.get(httpHeader.CONNECTION_PROP_REQUEST_START);
- Long requestEnd = (Long) conProp.get(httpHeader.CONNECTION_PROP_REQUEST_END);
- String elapsed = Long.toString(requestEnd.longValue()-requestStart.longValue());
+ final Long requestStart = (Long) conProp.get(httpHeader.CONNECTION_PROP_REQUEST_START);
+ final Long requestEnd = (Long) conProp.get(httpHeader.CONNECTION_PROP_REQUEST_END);
+ final String elapsed = Long.toString(requestEnd.longValue()-requestStart.longValue());
for (int i=0; i<6-elapsed.length(); i++) logMessage.append(' ');
logMessage.append(elapsed);
logMessage.append(' ');
// Remote Host
- String clientIP = conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP);
+ final String clientIP = conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP);
logMessage.append(clientIP);
logMessage.append(' ');
// Code/Status
- String respondStatus = conProp.getProperty(httpHeader.CONNECTION_PROP_PROXY_RESPOND_STATUS);
- String respondCode = conProp.getProperty(httpHeader.CONNECTION_PROP_PROXY_RESPOND_CODE,"UNKNOWN");
+ final String respondStatus = conProp.getProperty(httpHeader.CONNECTION_PROP_PROXY_RESPOND_STATUS);
+ final String respondCode = conProp.getProperty(httpHeader.CONNECTION_PROP_PROXY_RESPOND_CODE,"UNKNOWN");
logMessage.append(respondCode);
logMessage.append("/");
logMessage.append(respondStatus);
logMessage.append(' ');
// Bytes
- Long bytes = (Long) conProp.get(httpHeader.CONNECTION_PROP_PROXY_RESPOND_SIZE);
+ final Long bytes = (Long) conProp.get(httpHeader.CONNECTION_PROP_PROXY_RESPOND_SIZE);
logMessage.append(bytes.toString());
logMessage.append(' ');
// Method
- String requestMethod = conProp.getProperty(httpHeader.CONNECTION_PROP_METHOD);
+ final String requestMethod = conProp.getProperty(httpHeader.CONNECTION_PROP_METHOD);
logMessage.append(requestMethod);
logMessage.append(' ');
// URL
- String requestURL = conProp.getProperty(httpHeader.CONNECTION_PROP_URL);
- String requestArgs = conProp.getProperty(httpHeader.CONNECTION_PROP_ARGS);
+ final String requestURL = conProp.getProperty(httpHeader.CONNECTION_PROP_URL);
+ final String requestArgs = conProp.getProperty(httpHeader.CONNECTION_PROP_ARGS);
logMessage.append(requestURL);
if (requestArgs != null) {
logMessage.append("?")
@@ -1769,7 +1769,7 @@ public final class httpdProxyHandler {
logMessage.append(' ');
// Peerstatus/Peerhost
- String host = conProp.getProperty(httpHeader.CONNECTION_PROP_HOST);
+ final String host = conProp.getProperty(httpHeader.CONNECTION_PROP_HOST);
logMessage.append("DIRECT/");
logMessage.append(host);
logMessage.append(' ');
@@ -1777,7 +1777,7 @@ public final class httpdProxyHandler {
// Type
String mime = "-";
if (conProp.containsKey(httpHeader.CONNECTION_PROP_PROXY_RESPOND_HEADER)) {
- httpHeader proxyRespondHeader = (httpHeader) conProp.get(httpHeader.CONNECTION_PROP_PROXY_RESPOND_HEADER);
+ final httpHeader proxyRespondHeader = (httpHeader) conProp.get(httpHeader.CONNECTION_PROP_PROXY_RESPOND_HEADER);
mime = proxyRespondHeader.mime();
if (mime.indexOf(";") != -1) {
mime = mime.substring(0,mime.indexOf(";"));
@@ -1792,7 +1792,7 @@ public final class httpdProxyHandler {
/**
* @param remoteProxyConfig the remoteProxyConfig to set
*/
- public static synchronized void setRemoteProxyConfig(httpRemoteProxyConfig remoteProxyConfig) {
+ public static synchronized void setRemoteProxyConfig(final httpRemoteProxyConfig remoteProxyConfig) {
httpdProxyHandler.remoteProxyConfig = remoteProxyConfig;
}
diff --git a/source/de/anomic/http/httpdRobotsTxtConfig.java b/source/de/anomic/http/httpdRobotsTxtConfig.java
index c816fa9aa..e58c288db 100644
--- a/source/de/anomic/http/httpdRobotsTxtConfig.java
+++ b/source/de/anomic/http/httpdRobotsTxtConfig.java
@@ -63,7 +63,7 @@ public final class httpdRobotsTxtConfig {
public httpdRobotsTxtConfig() { }
- public httpdRobotsTxtConfig(String[] active) {
+ public httpdRobotsTxtConfig(final String[] active) {
if (active == null) return;
for (int i=0; i<active.length; i++) {
if (active[i] == null) continue;
@@ -83,15 +83,15 @@ public final class httpdRobotsTxtConfig {
}
}
- public static httpdRobotsTxtConfig init(serverSwitch<?> env) {
- String cfg = env.getConfig(plasmaSwitchboard.ROBOTS_TXT, plasmaSwitchboard.ROBOTS_TXT_DEFAULT);
+ public static httpdRobotsTxtConfig init(final serverSwitch<?> env) {
+ final String cfg = env.getConfig(plasmaSwitchboard.ROBOTS_TXT, plasmaSwitchboard.ROBOTS_TXT_DEFAULT);
if (cfg == null) return new httpdRobotsTxtConfig();
return new httpdRobotsTxtConfig(cfg.split(","));
}
public String toString() {
if (this.allDisallowed) return ALL;
- StringBuffer sb = new StringBuffer();
+ final StringBuffer sb = new StringBuffer();
if (this.blogDisallowed) sb.append(BLOG).append(",");
if (this.bookmarksDisallowed) sb.append(BOOKMARKS).append(",");
if (this.dirsDisallowed) sb.append(DIRS).append(",");
@@ -111,7 +111,7 @@ public final class httpdRobotsTxtConfig {
return allDisallowed;
}
- public void setAllDisallowed(boolean allDisallowed) {
+ public void setAllDisallowed(final boolean allDisallowed) {
this.allDisallowed = allDisallowed;
}
@@ -119,7 +119,7 @@ public final class httpdRobotsTxtConfig {
return lockedDisallowed || this.allDisallowed;
}
- public void setLockedDisallowed(boolean lockedDisallowed) {
+ public void setLockedDisallowed(final boolean lockedDisallowed) {
this.lockedDisallowed = lockedDisallowed;
}
@@ -127,7 +127,7 @@ public final class httpdRobotsTxtConfig {
return dirsDisallowed || this.allDisallowed;
}
- public void setDirsDisallowed(boolean dirsDisallowed) {
+ public void setDirsDisallowed(final boolean dirsDisallowed) {
this.dirsDisallowed = dirsDisallowed;
}
@@ -135,7 +135,7 @@ public final class httpdRobotsTxtConfig {
return blogDisallowed || this.allDisallowed;
}
- public void setBlogDisallowed(boolean blogDisallowed) {
+ public void setBlogDisallowed(final boolean blogDisallowed) {
this.blogDisallowed = blogDisallowed;
}
@@ -143,7 +143,7 @@ public final class httpdRobotsTxtConfig {
return bookmarksDisallowed || this.allDisallowed;
}
- public void setBookmarksDisallowed(boolean bookmarksDisallowed) {
+ public void setBookmarksDisallowed(final boolean bookmarksDisallowed) {
this.bookmarksDisallowed = bookmarksDisallowed;
}
@@ -151,7 +151,7 @@ public final class httpdRobotsTxtConfig {
return fileshareDisallowed || this.allDisallowed;
}
- public void setFileshareDisallowed(boolean fileshareDisallowed) {
+ public void setFileshareDisallowed(final boolean fileshareDisallowed) {
this.fileshareDisallowed = fileshareDisallowed;
}
@@ -159,7 +159,7 @@ public final class httpdRobotsTxtConfig {
return homepageDisallowed || this.allDisallowed;
}
- public void setHomepageDisallowed(boolean homepageDisallowed) {
+ public void setHomepageDisallowed(final boolean homepageDisallowed) {
this.homepageDisallowed = homepageDisallowed;
}
@@ -167,7 +167,7 @@ public final class httpdRobotsTxtConfig {
return networkDisallowed || this.allDisallowed;
}
- public void setNetworkDisallowed(boolean networkDisallowed) {
+ public void setNetworkDisallowed(final boolean networkDisallowed) {
this.networkDisallowed = networkDisallowed;
}
@@ -175,7 +175,7 @@ public final class httpdRobotsTxtConfig {
return newsDisallowed || this.allDisallowed;
}
- public void setNewsDisallowed(boolean newsDisallowed) {
+ public void setNewsDisallowed(final boolean newsDisallowed) {
this.newsDisallowed = newsDisallowed;
}
@@ -183,7 +183,7 @@ public final class httpdRobotsTxtConfig {
return statusDisallowed || this.allDisallowed;
}
- public void setStatusDisallowed(boolean statusDisallowed) {
+ public void setStatusDisallowed(final boolean statusDisallowed) {
this.statusDisallowed = statusDisallowed;
}
@@ -191,7 +191,7 @@ public final class httpdRobotsTxtConfig {
return surftipsDisallowed || this.allDisallowed;
}
- public void setSurftipsDisallowed(boolean surftipsDisallowed) {
+ public void setSurftipsDisallowed(final boolean surftipsDisallowed) {
this.surftipsDisallowed = surftipsDisallowed;
}
@@ -199,7 +199,7 @@ public final class httpdRobotsTxtConfig {
return wikiDisallowed || this.allDisallowed;
}
- public void setWikiDisallowed(boolean wikiDisallowed) {
+ public void setWikiDisallowed(final boolean wikiDisallowed) {
this.wikiDisallowed = wikiDisallowed;
}
@@ -207,7 +207,7 @@ public final class httpdRobotsTxtConfig {
return profileDisallowed || this.allDisallowed;
}
- public void setProfileDisallowed(boolean profileDisallowed) {
+ public void setProfileDisallowed(final boolean profileDisallowed) {
this.profileDisallowed = profileDisallowed;
}
}
diff --git a/source/de/anomic/icap/icapHeader.java b/source/de/anomic/icap/icapHeader.java
index 828ebbc56..1abef8698 100644
--- a/source/de/anomic/icap/icapHeader.java
+++ b/source/de/anomic/icap/icapHeader.java
@@ -117,21 +117,21 @@ public class icapHeader extends TreeMap<String, String> implements Map<String, S
super(insensitiveCollator);
}
- public boolean allow(int statusCode) {
+ public boolean allow(final int statusCode) {
if (!super.containsKey("Allow")) return false;
- String allow = get("Allow");
+ final String allow = get("Allow");
return (allow.indexOf(Integer.toString(statusCode))!=-1);
}
// to make the occurrence of multiple keys possible, we add them using a counter
- public String add(String key, String value) {
- int c = keyCount(key);
+ public String add(final String key, final String value) {
+ final int c = keyCount(key);
if (c == 0) return put(key, value);
return put("*" + key + "-" + c, value);
}
- public int keyCount(String key) {
+ public int keyCount(final String key) {
if (!(containsKey(key))) return 0;
int c = 1;
while (containsKey("*" + key + "-" + c)) c++;
@@ -139,26 +139,26 @@ public class icapHeader extends TreeMap<String, String> implements Map<String, S
}
// a convenience method to access the map with fail-over defaults
- public Object get(Object key, Object dflt) {
- Object result = get(key);
+ public Object get(final Object key, final Object dflt) {
+ final Object result = get(key);
if (result == null) return dflt;
return result;
}
// return multiple results
- public Object getSingle(Object key, int count) {
+ public Object getSingle(final Object key, final int count) {
if (count == 0) return get(key, null);
return get("*" + key + "-" + count, null);
}
- public StringBuffer toHeaderString(String icapVersion, int icapStatusCode, String icapStatusText) {
+ public StringBuffer toHeaderString(final String icapVersion, final int icapStatusCode, String icapStatusText) {
if ((icapStatusText == null)||(icapStatusText.length()==0)) {
if (icapVersion.equals("ICAP/1.0") && icapHeader.icap1_0.containsKey(Integer.toString(icapStatusCode)))
icapStatusText = icapHeader.icap1_0.get(Integer.toString(icapStatusCode));
}
- StringBuffer theHeader = new StringBuffer();
+ final StringBuffer theHeader = new StringBuffer();
// write status line
theHeader.append(icapVersion).append(" ")
@@ -166,7 +166,7 @@ public class icapHeader extends TreeMap<String, String> implements Map<String, S
.append(icapStatusText).append("\r\n");
// write header
- Iterator<String> i = keySet().iterator();
+ final Iterator<String> i = keySet().iterator();
String key;
char tag;
int count;
@@ -187,7 +187,7 @@ public class icapHeader extends TreeMap<String, String> implements Map<String, S
return theHeader;
}
- public static Properties parseRequestLine(String cmd, String s, Properties prop, String virtualHost) {
+ public static Properties parseRequestLine(final String cmd, String s, final Properties prop, final String virtualHost) {
// reset property from previous run
prop.clear();
@@ -267,9 +267,9 @@ public class icapHeader extends TreeMap<String, String> implements Map<String, S
}
- public static icapHeader readHeader(Properties prop, serverCore.Session theSession) {
+ public static icapHeader readHeader(final Properties prop, final serverCore.Session theSession) {
// reading all headers
- icapHeader header = new icapHeader();
+ final icapHeader header = new icapHeader();
int p;
String line;
while ((line = theSession.readLineAsString()) != null) {
diff --git a/source/de/anomic/icap/icapd.java b/source/de/anomic/icap/icapd.java
index a49346347..1724334d4 100644
--- a/source/de/anomic/icap/icapd.java
+++ b/source/de/anomic/icap/icapd.java
@@ -89,7 +89,7 @@ public class icapd implements serverHandler {
return new icapd();
}
- public void initSession(Session aSession) throws IOException {
+ public void initSession(final Session aSession) throws IOException {
this.session = aSession;
this.userAddress = aSession.userAddress; // client InetAddress
this.clientIP = this.userAddress.getHostAddress();
@@ -103,7 +103,7 @@ public class icapd implements serverHandler {
return null;
}
- public String error(Throwable e) {
+ public String error(final Throwable e) {
// TODO Auto-generated method stub
return null;
}
@@ -111,18 +111,18 @@ public class icapd implements serverHandler {
public void reset() {
}
- public Boolean EMPTY(String arg) throws IOException {
+ public Boolean EMPTY(final String arg) throws IOException {
// TODO Auto-generated method stub
return serverCore.TERMINATE_CONNECTION;
}
- public Boolean UNKNOWN(String requestLine) throws IOException {
+ public Boolean UNKNOWN(final String requestLine) throws IOException {
// TODO Auto-generated method stub
return serverCore.TERMINATE_CONNECTION;
}
public icapHeader getDefaultHeaders() {
- icapHeader newHeaders = new icapHeader();
+ final icapHeader newHeaders = new icapHeader();
newHeaders.put(icapHeader.SERVER,"YaCy/" + switchboard.getConfig("vString",""));
newHeaders.put(icapHeader.DATE, HttpClient.dateString(new Date()));
@@ -131,21 +131,21 @@ public class icapd implements serverHandler {
return newHeaders;
}
- public Boolean OPTIONS(String arg) throws IOException {
+ public Boolean OPTIONS(final String arg) throws IOException {
- BufferedOutputStream out = new BufferedOutputStream(this.session.out);
+ final BufferedOutputStream out = new BufferedOutputStream(this.session.out);
// parsing the http request line
parseRequestLine(icapHeader.METHOD_OPTIONS,arg);
// reading the headers
- icapHeader icapReqHeader = icapHeader.readHeader(this.prop,this.session);
+ final icapHeader icapReqHeader = icapHeader.readHeader(this.prop,this.session);
// determines if the connection should be kept alive
- boolean persistent = handlePersistentConnection(icapReqHeader);
+ final boolean persistent = handlePersistentConnection(icapReqHeader);
// setting the icap response headers
- icapHeader resHeader = getDefaultHeaders();
+ final icapHeader resHeader = getDefaultHeaders();
resHeader.put(icapHeader.ALLOW,"204");
resHeader.put(icapHeader.ENCAPSULATED,"null-body=0");
resHeader.put(icapHeader.MAX_CONNECTIONS,"1000");
@@ -158,7 +158,7 @@ public class icapd implements serverHandler {
// determining the requested service and call it or send back an error message
- String reqService = this.prop.getProperty(icapHeader.CONNECTION_PROP_PATH,"");
+ final String reqService = this.prop.getProperty(icapHeader.CONNECTION_PROP_PATH,"");
if (reqService.equalsIgnoreCase("/resIndexing")) {
resHeader.put(icapHeader.SERVICE, "YaCy ICAP Indexing Service 1.0");
resHeader.put(icapHeader.METHODS,icapHeader.METHOD_RESPMOD);
@@ -171,49 +171,49 @@ public class icapd implements serverHandler {
}
- StringBuffer headerStringBuffer = resHeader.toHeaderString("ICAP/1.0",200,null);
+ final StringBuffer headerStringBuffer = resHeader.toHeaderString("ICAP/1.0",200,null);
out.write(headerStringBuffer.toString().getBytes());
out.flush();
return this.prop.getProperty(icapHeader.CONNECTION_PROP_PERSISTENT).equals("keep-alive") ? serverCore.RESUME_CONNECTION : serverCore.TERMINATE_CONNECTION;
}
- public Boolean REQMOD(String arg) {
+ public Boolean REQMOD(final String arg) {
return serverCore.TERMINATE_CONNECTION;
}
- public Boolean RESPMOD(String arg) {
+ public Boolean RESPMOD(final String arg) {
try {
- InputStream in = this.session.in;
- OutputStream out = this.session.out;
+ final InputStream in = this.session.in;
+ final OutputStream out = this.session.out;
// parsing the icap request line
parseRequestLine(icapHeader.METHOD_RESPMOD,arg);
// reading the icap request header
- icapHeader icapReqHeader = icapHeader.readHeader(this.prop,this.session);
+ final icapHeader icapReqHeader = icapHeader.readHeader(this.prop,this.session);
// determines if the connection should be kept alive
handlePersistentConnection(icapReqHeader);
// determining the requested service and call it or send back an error message
- String reqService = this.prop.getProperty(icapHeader.CONNECTION_PROP_PATH,"");
+ final String reqService = this.prop.getProperty(icapHeader.CONNECTION_PROP_PATH,"");
if (reqService.equalsIgnoreCase("/resIndexing")) {
indexingService(icapReqHeader,in,out);
} else {
- icapHeader icapResHeader = getDefaultHeaders();
+ final icapHeader icapResHeader = getDefaultHeaders();
icapResHeader.put(icapHeader.ENCAPSULATED,icapReqHeader.get(icapHeader.ENCAPSULATED));
icapResHeader.put(icapHeader.SERVICE, "YaCy ICAP Service 1.0");
// icapResHeader.put(icapHeader.CONNECTION, "close");
- StringBuffer headerStringBuffer = icapResHeader.toHeaderString("ICAP/1.0",404,null);
+ final StringBuffer headerStringBuffer = icapResHeader.toHeaderString("ICAP/1.0",404,null);
out.write((new String(headerStringBuffer)).getBytes());
out.flush();
}
- } catch (Exception e) {
+ } catch (final Exception e) {
e.printStackTrace();
} finally {
@@ -231,14 +231,14 @@ public class icapd implements serverHandler {
}
*/
- private void indexingService(icapHeader reqHeader, InputStream in, OutputStream out) {
+ private void indexingService(final icapHeader reqHeader, final InputStream in, final OutputStream out) {
try {
/* =========================================================================
* Reading the various message parts into buffers
* ========================================================================= */
ByteArrayInputStream reqHdrStream = null, resHdrStream = null, resBodyStream = null;
- String[] encapsulated = (reqHeader.get(icapHeader.ENCAPSULATED)).split(",");
+ final String[] encapsulated = (reqHeader.get(icapHeader.ENCAPSULATED)).split(",");
int prevLength = 0, currLength=0;
for (int i=0; i < encapsulated.length; i++) {
// reading the request header
@@ -246,7 +246,7 @@ public class icapd implements serverHandler {
prevLength = currLength;
currLength = Integer.parseInt(encapsulated[i+1].split("=")[1]);
- byte[] buffer = new byte[currLength-prevLength];
+ final byte[] buffer = new byte[currLength-prevLength];
in.read(buffer, 0, buffer.length);
reqHdrStream = new ByteArrayInputStream(buffer);
@@ -256,17 +256,17 @@ public class icapd implements serverHandler {
prevLength = currLength;
currLength = Integer.parseInt(encapsulated[i+1].split("=")[1]);
- byte[] buffer = new byte[currLength-prevLength];
+ final byte[] buffer = new byte[currLength-prevLength];
in.read(buffer, 0, buffer.length);
resHdrStream = new ByteArrayInputStream(buffer);
// reading the response body
} else if (encapsulated[i].indexOf("res-body")>=0) {
- httpChunkedInputStream chunkedIn = new httpChunkedInputStream(in);
- ByteArrayOutputStream bout = new ByteArrayOutputStream();
+ final httpChunkedInputStream chunkedIn = new httpChunkedInputStream(in);
+ final ByteArrayOutputStream bout = new ByteArrayOutputStream();
int l = 0,len = 0;
- byte[] buffer = new byte[2048];
+ final byte[] buffer = new byte[2048];
while ((l = chunkedIn.read(buffer)) >= 0) {
len += l;
bout.write(buffer,0,l);
@@ -278,13 +278,13 @@ public class icapd implements serverHandler {
/* =========================================================================
* sending back the icap status
* ========================================================================= */
- icapHeader icapResHeader = getDefaultHeaders();
+ final icapHeader icapResHeader = getDefaultHeaders();
if (reqHeader.allow(204)) {
icapResHeader.put(icapHeader.ENCAPSULATED,reqHeader.get(icapHeader.ENCAPSULATED));
icapResHeader.put(icapHeader.SERVICE, "YaCy ICAP Service 1.0");
// resHeader.put(icapHeader.CONNECTION, "close");
- StringBuffer headerStringBuffer = icapResHeader.toHeaderString("ICAP/1.0",204,null);
+ final StringBuffer headerStringBuffer = icapResHeader.toHeaderString("ICAP/1.0",204,null);
out.write((new String(headerStringBuffer)).getBytes());
out.flush();
} else {
@@ -292,7 +292,7 @@ public class icapd implements serverHandler {
icapResHeader.put(icapHeader.SERVICE, "YaCy ICAP Service 1.0");
// icapResHeader.put(icapHeader.CONNECTION, "close");
- StringBuffer headerStringBuffer = icapResHeader.toHeaderString("ICAP/1.0",503,null);
+ final StringBuffer headerStringBuffer = icapResHeader.toHeaderString("ICAP/1.0",503,null);
out.write((new String(headerStringBuffer)).getBytes());
out.flush();
}
@@ -302,10 +302,10 @@ public class icapd implements serverHandler {
* ========================================================================= */
// reading the requestline
BufferedReader reader = new BufferedReader(new InputStreamReader(reqHdrStream));
- String httpRequestLine = reader.readLine();
+ final String httpRequestLine = reader.readLine();
// parsing the requestline
- Properties httpReqProps = new Properties();
+ final Properties httpReqProps = new Properties();
httpHeader.parseRequestLine(httpRequestLine,httpReqProps,virtualHost);
if (!httpReqProps.getProperty(httpHeader.CONNECTION_PROP_METHOD).equals(httpHeader.METHOD_GET)) {
@@ -320,7 +320,7 @@ public class icapd implements serverHandler {
}
// reading all request headers
- httpHeader httpReqHeader = httpHeader.readHttpHeader(reader);
+ final httpHeader httpReqHeader = httpHeader.readHttpHeader(reader);
reader.close();
if(reqHdrStream != null) {
reqHdrStream.close();
@@ -330,16 +330,16 @@ public class icapd implements serverHandler {
httpHeader.handleTransparentProxySupport(httpReqHeader,httpReqProps,virtualHost,true);
// getting the request URL
- yacyURL httpRequestURL = httpHeader.getRequestURL(httpReqProps);
+ final yacyURL httpRequestURL = httpHeader.getRequestURL(httpReqProps);
/* =========================================================================
* Parsing response data
* ========================================================================= */
// getting the response status
reader = new BufferedReader(new InputStreamReader(resHdrStream));
- String httpRespStatusLine = reader.readLine();
+ final String httpRespStatusLine = reader.readLine();
- Object[] httpRespStatus = httpHeader.parseResponseLine(httpRespStatusLine);
+ final Object[] httpRespStatus = httpHeader.parseResponseLine(httpRespStatusLine);
if (!(httpRespStatus[1].equals(new Integer(200)) || httpRespStatus[1].equals(new Integer(203)))) {
this.log.logInfo("Wrong status code for indexing:" +
@@ -354,7 +354,7 @@ public class icapd implements serverHandler {
}
// reading all response headers
- httpHeader httpResHeader = httpHeader.readHttpHeader(reader);
+ final httpHeader httpResHeader = httpHeader.readHttpHeader(reader);
reader.close();
if(resHdrStream != null) {
resHdrStream.close();
@@ -373,8 +373,8 @@ public class icapd implements serverHandler {
* ========================================================================= */
// generating a htcache entry object
- IResourceInfo resInfo = new ResourceInfo(httpRequestURL,httpReqHeader,httpResHeader);
- plasmaHTCache.Entry cacheEntry = plasmaHTCache.newEntry(
+ final IResourceInfo resInfo = new ResourceInfo(httpRequestURL,httpReqHeader,httpResHeader);
+ final plasmaHTCache.Entry cacheEntry = plasmaHTCache.newEntry(
new Date(),
0,
httpRequestURL,
@@ -386,7 +386,7 @@ public class icapd implements serverHandler {
);
// getting the filename/path to store the response body
- File cacheFile = plasmaHTCache.getCachePath(httpRequestURL);
+ final File cacheFile = plasmaHTCache.getCachePath(httpRequestURL);
// if the file already exits we delete it
if (cacheFile.isFile()) {
@@ -403,12 +403,12 @@ public class icapd implements serverHandler {
// indexing the response
plasmaHTCache.push(cacheEntry);
- } catch (Exception e) {
+ } catch (final Exception e) {
e.printStackTrace();
}
}
- private final void parseRequestLine(String cmd, String s) {
+ private final void parseRequestLine(final String cmd, final String s) {
// parsing the requestlin
icapHeader.parseRequestLine(cmd,s, this.prop,virtualHost);
@@ -419,7 +419,7 @@ public class icapd implements serverHandler {
this.prop.setProperty(icapHeader.CONNECTION_PROP_KEEP_ALIVE_COUNT, Integer.toString(++this.keepAliveRequestCount));
}
- private boolean handlePersistentConnection(icapHeader header) {
+ private boolean handlePersistentConnection(final icapHeader header) {
if (!keepAliveSupport) {
this.prop.put(icapHeader.CONNECTION_PROP_PERSISTENT,"close");
diff --git a/source/de/anomic/index/indexAbstractReferenceBlacklist.java b/source/de/anomic/index/indexAbstractReferenceBlacklist.java
index 701ee7331..ca4b70702 100644
--- a/source/de/anomic/index/indexAbstractReferenceBlacklist.java
+++ b/source/de/anomic/index/indexAbstractReferenceBlacklist.java
@@ -61,7 +61,7 @@ public abstract class indexAbstractReferenceBlacklist implements indexReferenceB
protected HashMap<String, HashMap<String, ArrayList<String>>> hostpaths_matchable = null; // key=host, value=path; mapped url is http://host/path; path does not start with '/' here
protected HashMap<String, HashMap<String, ArrayList<String>>> hostpaths_notmatchable = null; // key=host, value=path; mapped url is http://host/path; path does not start with '/' here
- public indexAbstractReferenceBlacklist(File rootPath) {
+ public indexAbstractReferenceBlacklist(final File rootPath) {
this.setRootPath(rootPath);
this.blacklistRootPath = rootPath;
@@ -72,9 +72,9 @@ public abstract class indexAbstractReferenceBlacklist implements indexReferenceB
this.hostpaths_notmatchable = new HashMap<String, HashMap<String, ArrayList<String>>>();
this.cachedUrlHashs = new HashMap<String, Set<String>>();
- Iterator<String> iter = BLACKLIST_TYPES.iterator();
+ final Iterator<String> iter = BLACKLIST_TYPES.iterator();
while (iter.hasNext()) {
- String blacklistType = iter.next();
+ final String blacklistType = iter.next();
//this.hostpaths.put(blacklistType, new HashMap<String, ArrayList<String>>());
this.hostpaths_matchable.put(blacklistType, new HashMap<String, ArrayList<String>>());
this.hostpaths_notmatchable.put(blacklistType, new HashMap<String, ArrayList<String>>());
@@ -82,7 +82,7 @@ public abstract class indexAbstractReferenceBlacklist implements indexReferenceB
}
}
- public void setRootPath(File rootPath) {
+ public void setRootPath(final File rootPath) {
if (rootPath == null)
throw new NullPointerException("The blacklist root path must not be null.");
if (!rootPath.isDirectory())
@@ -93,14 +93,14 @@ public abstract class indexAbstractReferenceBlacklist implements indexReferenceB
this.blacklistRootPath = rootPath;
}
- protected HashMap<String, ArrayList<String>> getBlacklistMap(String blacklistType,boolean matchable) {
+ protected HashMap<String, ArrayList<String>> getBlacklistMap(final String blacklistType,final boolean matchable) {
if (blacklistType == null) throw new IllegalArgumentException();
if (!BLACKLIST_TYPES.contains(blacklistType)) throw new IllegalArgumentException("Unknown blacklist type: "+blacklistType+".");
return (matchable)? this.hostpaths_matchable.get(blacklistType) : this.hostpaths_notmatchable.get(blacklistType);
}
- protected Set<String> getCacheUrlHashsSet(String blacklistType) {
+ protected Set<String> getCacheUrlHashsSet(final String blacklistType) {
if (blacklistType == null) throw new IllegalArgumentException();
if (!BLACKLIST_TYPES.contains(blacklistType)) throw new IllegalArgumentException("Unknown backlist type.");
@@ -108,59 +108,59 @@ public abstract class indexAbstractReferenceBlacklist implements indexReferenceB
}
public void clear() {
- for(HashMap<String, ArrayList<String>> entry: this.hostpaths_matchable.values()) {
+ for(final HashMap<String, ArrayList<String>> entry: this.hostpaths_matchable.values()) {
entry.clear();
}
- for(HashMap<String, ArrayList<String>> entry: this.hostpaths_notmatchable.values()) {
+ for(final HashMap<String, ArrayList<String>> entry: this.hostpaths_notmatchable.values()) {
entry.clear();
}
- for(Set<String> entry: this.cachedUrlHashs.values()) {
+ for(final Set<String> entry: this.cachedUrlHashs.values()) {
entry.clear();
}
}
public int size() {
int size = 0;
- for(String entry: this.hostpaths_matchable.keySet()) {
- for(ArrayList<String> ientry: this.hostpaths_matchable.get(entry).values()) {
+ for(final String entry: this.hostpaths_matchable.keySet()) {
+ for(final ArrayList<String> ientry: this.hostpaths_matchable.get(entry).values()) {
size += ientry.size();
}
}
- for(String entry: this.hostpaths_notmatchable.keySet()) {
- for(ArrayList<String> ientry: this.hostpaths_notmatchable.get(entry).values()) {
+ for(final String entry: this.hostpaths_notmatchable.keySet()) {
+ for(final ArrayList<String> ientry: this.hostpaths_notmatchable.get(entry).values()) {
size += ientry.size();
}
}
return size;
}
- public void loadList(blacklistFile[] blFiles, String sep) {
+ public void loadList(final blacklistFile[] blFiles, final String sep) {
for (int j = 0; j < blFiles.length; j++) {
- blacklistFile blf = blFiles[j];
+ final blacklistFile blf = blFiles[j];
loadList(blf.getType(), blf.getFileName(), sep);
}
}
- public void loadList(blacklistFile blFile, String sep) {
- HashMap<String, ArrayList<String>> blacklistMapMatch = getBlacklistMap(blFile.getType(),true);
- HashMap<String, ArrayList<String>> blacklistMapNotMatch = getBlacklistMap(blFile.getType(),false);
+ public void loadList(final blacklistFile blFile, final String sep) {
+ final HashMap<String, ArrayList<String>> blacklistMapMatch = getBlacklistMap(blFile.getType(),true);
+ final HashMap<String, ArrayList<String>> blacklistMapNotMatch = getBlacklistMap(blFile.getType(),false);
Set<Map.Entry<String, ArrayList<String>>> loadedBlacklist;
Map.Entry<String, ArrayList<String>> loadedEntry;
ArrayList<String> paths;
ArrayList<String> loadedPaths;
- String[] fileNames = blFile.getFileNamesUnified();
+ final String[] fileNames = blFile.getFileNamesUnified();
if (fileNames.length > 0) {
for (int i = 0; i < fileNames.length; i++) {
// make sure all requested blacklist files exist
- File file = new File(this.blacklistRootPath, fileNames[i]);
+ final File file = new File(this.blacklistRootPath, fileNames[i]);
try {
file.createNewFile();
- } catch (IOException e) { /* */ }
+ } catch (final IOException e) { /* */ }
// join all blacklists from files into one internal blacklist map
loadedBlacklist = kelondroMSetTools.loadMapMultiValsPerKey(file.toString(), sep).entrySet();
- for (Iterator<Map.Entry<String, ArrayList<String>>> mi = loadedBlacklist.iterator(); mi.hasNext(); ) {
+ for (final Iterator<Map.Entry<String, ArrayList<String>>> mi = loadedBlacklist.iterator(); mi.hasNext(); ) {
loadedEntry = mi.next();
loadedPaths = loadedEntry.getValue();
@@ -181,28 +181,28 @@ public abstract class indexAbstractReferenceBlacklist implements indexReferenceB
}
}
- public void loadList(String blacklistType, String fileNames, String sep) {
+ public void loadList(final String blacklistType, final String fileNames, final String sep) {
// method for not breaking older plasmaURLPattern interface
- blacklistFile blFile = new blacklistFile(fileNames, blacklistType);
+ final blacklistFile blFile = new blacklistFile(fileNames, blacklistType);
loadList(blFile, sep);
}
- public void removeAll(String blacklistType, String host) {
+ public void removeAll(final String blacklistType, final String host) {
getBlacklistMap(blacklistType,true).remove(host);
getBlacklistMap(blacklistType,false).remove(host);
}
- public void remove(String blacklistType, String host, String path) {
+ public void remove(final String blacklistType, final String host, final String path) {
- HashMap<String, ArrayList<String>> blacklistMap = getBlacklistMap(blacklistType,true);
+ final HashMap<String, ArrayList<String>> blacklistMap = getBlacklistMap(blacklistType,true);
ArrayList<String> hostList = blacklistMap.get(host);
if(hostList != null) {
hostList.remove(path);
if (hostList.size() == 0)
blacklistMap.remove(host);
}
- HashMap<String, ArrayList<String>> blacklistMapNotMatch = getBlacklistMap(blacklistType,false);
+ final HashMap<String, ArrayList<String>> blacklistMapNotMatch = getBlacklistMap(blacklistType,false);
hostList = blacklistMapNotMatch.get(host);
if(hostList != null) {
hostList.remove(path);
@@ -211,7 +211,7 @@ public abstract class indexAbstractReferenceBlacklist implements indexReferenceB
}
}
- public void add(String blacklistType, String host, String path) {
+ public void add(final String blacklistType, String host, String path) {
if (host == null) throw new NullPointerException();
if (path == null) throw new NullPointerException();
@@ -231,24 +231,24 @@ public abstract class indexAbstractReferenceBlacklist implements indexReferenceB
public int blacklistCacheSize() {
int size = 0;
- Iterator<String> iter = this.cachedUrlHashs.keySet().iterator();
+ final Iterator<String> iter = this.cachedUrlHashs.keySet().iterator();
while (iter.hasNext()) {
- Set<String> blacklistMap = this.cachedUrlHashs.get(iter.next());
+ final Set<String> blacklistMap = this.cachedUrlHashs.get(iter.next());
size += blacklistMap.size();
}
return size;
}
- public boolean hashInBlacklistedCache(String blacklistType, String urlHash) {
- Set<String> urlHashCache = getCacheUrlHashsSet(blacklistType);
+ public boolean hashInBlacklistedCache(final String blacklistType, final String urlHash) {
+ final Set<String> urlHashCache = getCacheUrlHashsSet(blacklistType);
return urlHashCache.contains(urlHash);
}
- public boolean isListed(String blacklistType, yacyURL url) {
+ public boolean isListed(final String blacklistType, final yacyURL url) {
- Set<String> urlHashCache = getCacheUrlHashsSet(blacklistType);
+ final Set<String> urlHashCache = getCacheUrlHashsSet(blacklistType);
if (!urlHashCache.contains(url.hash())) {
- boolean temp = isListed(blacklistType, url.getHost().toLowerCase(), url.getFile());
+ final boolean temp = isListed(blacklistType, url.getHost().toLowerCase(), url.getFile());
if (temp) {
urlHashCache.add(url.hash());
}
@@ -256,7 +256,7 @@ public abstract class indexAbstractReferenceBlacklist implements indexReferenceB
}
return true;
}
- public static boolean isMatchable (String host) {
+ public static boolean isMatchable (final String host) {
try {
if(Pattern.matches("^[a-z0-9.-]*$", host)) // simple Domain (yacy.net or www.yacy.net)
return true;
@@ -264,7 +264,7 @@ public abstract class indexAbstractReferenceBlacklist implements indexReferenceB
return true;
if(Pattern.matches("^[a-z0-9-.]*\\.\\*$", host)) // ends with .* (not *. and befor * must be a dot)
return true;
- } catch (PatternSyntaxException e) {
+ } catch (final PatternSyntaxException e) {
//System.out.println(e.toString());
return false;
}
diff --git a/source/de/anomic/index/indexCollectionRI.java b/source/de/anomic/index/indexCollectionRI.java
index d22fa632c..48aff91ad 100644
--- a/source/de/anomic/index/indexCollectionRI.java
+++ b/source/de/anomic/index/indexCollectionRI.java
@@ -44,7 +44,7 @@ public class indexCollectionRI implements indexRI {
kelondroCollectionIndex collectionIndex;
- public indexCollectionRI(File path, String filenameStub, int maxpartition, kelondroRow payloadrow) {
+ public indexCollectionRI(final File path, final String filenameStub, final int maxpartition, final kelondroRow payloadrow) {
try {
collectionIndex = new kelondroCollectionIndex(
path,
@@ -54,7 +54,7 @@ public class indexCollectionRI implements indexRI {
4 /*loadfactor*/,
maxpartition,
payloadrow);
- } catch (IOException e) {
+ } catch (final IOException e) {
serverLog.logSevere("PLASMA", "unable to open collection index at " + path.toString() + ":" + e.getMessage());
}
}
@@ -62,13 +62,13 @@ public class indexCollectionRI implements indexRI {
public void clear() {
try {
collectionIndex.clear();
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
}
- public long getUpdateTime(String wordHash) {
- indexContainer entries = getContainer(wordHash, null);
+ public long getUpdateTime(final String wordHash) {
+ final indexContainer entries = getContainer(wordHash, null);
if (entries == null) return 0;
return entries.updated();
}
@@ -77,10 +77,10 @@ public class indexCollectionRI implements indexRI {
return collectionIndex.size();
}
- public int indexSize(String wordHash) {
+ public int indexSize(final String wordHash) {
try {
return collectionIndex.indexSize(wordHash.getBytes());
- } catch (IOException e) {
+ } catch (final IOException e) {
return 0;
}
}
@@ -91,21 +91,21 @@ public class indexCollectionRI implements indexRI {
return 100 * 1024 /* overhead here */ + collectionIndex.minMem();
}
- public synchronized kelondroCloneableIterator<indexContainer> wordContainers(String startWordHash, boolean rot) {
+ public synchronized kelondroCloneableIterator<indexContainer> wordContainers(final String startWordHash, final boolean rot) {
return new wordContainersIterator(startWordHash, rot);
}
public class wordContainersIterator implements kelondroCloneableIterator<indexContainer> {
- private Iterator<Object[]> wci;
- private boolean rot;
+ private final Iterator<Object[]> wci;
+ private final boolean rot;
- public wordContainersIterator(String startWordHash, boolean rot) {
+ public wordContainersIterator(final String startWordHash, final boolean rot) {
this.rot = rot;
this.wci = collectionIndex.keycollections(startWordHash.getBytes(), kelondroBase64Order.zero(startWordHash.length()), rot);
}
- public wordContainersIterator clone(Object secondWordHash) {
+ public wordContainersIterator clone(final Object secondWordHash) {
return new wordContainersIterator((String) secondWordHash, rot);
}
@@ -114,10 +114,10 @@ public class indexCollectionRI implements indexRI {
}
public indexContainer next() {
- Object[] oo = wci.next();
+ final Object[] oo = wci.next();
if (oo == null) return null;
- byte[] key = (byte[]) oo[0];
- kelondroRowSet collection = (kelondroRowSet) oo[1];
+ final byte[] key = (byte[]) oo[0];
+ final kelondroRowSet collection = (kelondroRowSet) oo[1];
if (collection == null) return null;
return new indexContainer(new String(key), collection);
}
@@ -128,59 +128,59 @@ public class indexCollectionRI implements indexRI {
}
- public boolean hasContainer(String wordHash) {
+ public boolean hasContainer(final String wordHash) {
try {
return collectionIndex.has(wordHash.getBytes());
- } catch (IOException e) {
+ } catch (final IOException e) {
return false;
}
}
- public indexContainer getContainer(String wordHash, Set<String> urlselection) {
+ public indexContainer getContainer(final String wordHash, final Set<String> urlselection) {
try {
- kelondroRowSet collection = collectionIndex.get(wordHash.getBytes());
+ final kelondroRowSet collection = collectionIndex.get(wordHash.getBytes());
if (collection != null) collection.select(urlselection);
if ((collection == null) || (collection.size() == 0)) return null;
return new indexContainer(wordHash, collection);
- } catch (IOException e) {
+ } catch (final IOException e) {
return null;
}
}
- public indexContainer deleteContainer(String wordHash) {
+ public indexContainer deleteContainer(final String wordHash) {
try {
- kelondroRowSet collection = collectionIndex.delete(wordHash.getBytes());
+ final kelondroRowSet collection = collectionIndex.delete(wordHash.getBytes());
if (collection == null) return null;
return new indexContainer(wordHash, collection);
- } catch (IOException e) {
+ } catch (final IOException e) {
return null;
}
}
- public boolean removeEntry(String wordHash, String urlHash) {
- HashSet<String> hs = new HashSet<String>();
+ public boolean removeEntry(final String wordHash, final String urlHash) {
+ final HashSet<String> hs = new HashSet<String>();
hs.add(urlHash);
return removeEntries(wordHash, hs) == 1;
}
- public int removeEntries(String wordHash, Set<String> urlHashes) {
+ public int removeEntries(final String wordHash, final Set<String> urlHashes) {
try {
return collectionIndex.remove(wordHash.getBytes(), urlHashes);
- } catch (kelondroOutOfLimitsException e) {
+ } catch (final kelondroOutOfLimitsException e) {
e.printStackTrace();
return 0;
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
return 0;
}
}
- public void addEntries(indexContainer newEntries) {
+ public void addEntries(final indexContainer newEntries) {
try {
collectionIndex.merge(newEntries);
- } catch (kelondroOutOfLimitsException e) {
+ } catch (final kelondroOutOfLimitsException e) {
e.printStackTrace();
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
}
diff --git a/source/de/anomic/index/indexContainer.java b/source/de/anomic/index/indexContainer.java
index c2e898451..a5200b840 100644
--- a/source/de/anomic/index/indexContainer.java
+++ b/source/de/anomic/index/indexContainer.java
@@ -44,24 +44,24 @@ public class indexContainer extends kelondroRowSet {
private String wordHash;
- public indexContainer(String wordHash, kelondroRowSet collection) {
+ public indexContainer(final String wordHash, final kelondroRowSet collection) {
super(collection);
this.wordHash = wordHash;
}
- public indexContainer(String wordHash, kelondroRow rowdef, int objectCount) {
+ public indexContainer(final String wordHash, final kelondroRow rowdef, final int objectCount) {
super(rowdef, objectCount);
this.wordHash = wordHash;
this.lastTimeWrote = 0;
}
public indexContainer topLevelClone() {
- indexContainer newContainer = new indexContainer(this.wordHash, this.rowdef, this.size());
+ final indexContainer newContainer = new indexContainer(this.wordHash, this.rowdef, this.size());
newContainer.addAllUnique(this);
return newContainer;
}
- public void setWordHash(String newWordHash) {
+ public void setWordHash(final String newWordHash) {
this.wordHash = newWordHash;
}
@@ -73,13 +73,13 @@ public class indexContainer extends kelondroRowSet {
return wordHash;
}
- public void add(indexRWIRowEntry entry) {
+ public void add(final indexRWIRowEntry entry) {
// add without double-occurrence test
assert entry.toKelondroEntry().objectsize() == super.rowdef.objectsize;
this.addUnique(entry.toKelondroEntry());
}
- public void add(indexRWIEntry entry, long updateTime) {
+ public void add(final indexRWIEntry entry, final long updateTime) {
// add without double-occurrence test
if (entry instanceof indexRWIRowEntry) {
assert ((indexRWIRowEntry) entry).toKelondroEntry().objectsize() == super.rowdef.objectsize;
@@ -90,7 +90,7 @@ public class indexContainer extends kelondroRowSet {
this.lastTimeWrote = updateTime;
}
- public static final indexContainer mergeUnique(indexContainer a, boolean aIsClone, indexContainer b, boolean bIsClone) {
+ public static final indexContainer mergeUnique(final indexContainer a, final boolean aIsClone, final indexContainer b, final boolean bIsClone) {
if ((aIsClone) && (bIsClone)) {
if (a.size() > b.size()) return (indexContainer) mergeUnique(a, b); else return (indexContainer) mergeUnique(b, a);
}
@@ -99,27 +99,27 @@ public class indexContainer extends kelondroRowSet {
if (a.size() > b.size()) return (indexContainer) mergeUnique(a, b); else return (indexContainer) mergeUnique(b, a);
}
- public static Object mergeUnique(Object a, Object b) {
- indexContainer c = (indexContainer) a;
+ public static Object mergeUnique(final Object a, final Object b) {
+ final indexContainer c = (indexContainer) a;
c.addAllUnique((indexContainer) b);
return c;
}
- public indexRWIEntry put(indexRWIRowEntry entry) {
+ public indexRWIEntry put(final indexRWIRowEntry entry) {
assert entry.toKelondroEntry().objectsize() == super.rowdef.objectsize;
- kelondroRow.Entry r = super.put(entry.toKelondroEntry());
+ final kelondroRow.Entry r = super.put(entry.toKelondroEntry());
if (r == null) return null;
return new indexRWIRowEntry(r);
}
- public boolean putRecent(indexRWIRowEntry entry) {
+ public boolean putRecent(final indexRWIRowEntry entry) {
assert entry.toKelondroEntry().objectsize() == super.rowdef.objectsize;
// returns true if the new entry was added, false if it already existed
- kelondroRow.Entry oldEntryRow = this.put(entry.toKelondroEntry());
+ final kelondroRow.Entry oldEntryRow = this.put(entry.toKelondroEntry());
if (oldEntryRow == null) {
return true;
} else {
- indexRWIRowEntry oldEntry = new indexRWIRowEntry(oldEntryRow);
+ final indexRWIRowEntry oldEntry = new indexRWIRowEntry(oldEntryRow);
if (entry.isOlder(oldEntry)) { // A more recent Entry is already in this container
this.put(oldEntry.toKelondroEntry()); // put it back
return false;
@@ -129,17 +129,17 @@ public class indexContainer extends kelondroRowSet {
}
}
- public int putAllRecent(indexContainer c) {
+ public int putAllRecent(final indexContainer c) {
// adds all entries in c and checks every entry for double-occurrence
// returns the number of new elements
if (c == null) return 0;
int x = 0;
synchronized (c) {
- Iterator<indexRWIRowEntry> i = c.entries();
+ final Iterator<indexRWIRowEntry> i = c.entries();
while (i.hasNext()) {
try {
if (putRecent(i.next())) x++;
- } catch (ConcurrentModificationException e) {
+ } catch (final ConcurrentModificationException e) {
e.printStackTrace();
}
}
@@ -148,21 +148,21 @@ public class indexContainer extends kelondroRowSet {
return x;
}
- public indexRWIEntry get(String urlHash) {
- kelondroRow.Entry entry = this.get(urlHash.getBytes());
+ public indexRWIEntry get(final String urlHash) {
+ final kelondroRow.Entry entry = this.get(urlHash.getBytes());
if (entry == null) return null;
return new indexRWIRowEntry(entry);
}
- public indexRWIEntry remove(String urlHash) {
- kelondroRow.Entry entry = remove(urlHash.getBytes());
+ public indexRWIEntry remove(final String urlHash) {
+ final kelondroRow.Entry entry = remove(urlHash.getBytes());
if (entry == null) return null;
return new indexRWIRowEntry(entry);
}
- public int removeEntries(Set<String> urlHashes) {
+ public int removeEntries(final Set<String> urlHashes) {
int count = 0;
- Iterator<String> i = urlHashes.iterator();
+ final Iterator<String> i = urlHashes.iterator();
while (i.hasNext()) count += (remove(i.next()) == null) ? 0 : 1;
return count;
}
@@ -185,7 +185,7 @@ public class indexContainer extends kelondroRowSet {
}
public indexRWIRowEntry next() {
- kelondroRow.Entry rentry = rowEntryIterator.next();
+ final kelondroRow.Entry rentry = rowEntryIterator.next();
if (rentry == null) return null;
return new indexRWIRowEntry(rentry);
}
@@ -199,43 +199,43 @@ public class indexContainer extends kelondroRowSet {
public static Method containerMergeMethod = null;
static {
try {
- Class<?> c = Class.forName("de.anomic.index.indexContainer");
+ final Class<?> c = Class.forName("de.anomic.index.indexContainer");
containerMergeMethod = c.getMethod("mergeUnique", new Class[]{Object.class, Object.class});
- } catch (SecurityException e) {
+ } catch (final SecurityException e) {
System.out.println("Error while initializing containerMerge.SecurityException: " + e.getMessage());
containerMergeMethod = null;
- } catch (ClassNotFoundException e) {
+ } catch (final ClassNotFoundException e) {
System.out.println("Error while initializing containerMerge.ClassNotFoundException: " + e.getMessage());
containerMergeMethod = null;
- } catch (NoSuchMethodException e) {
+ } catch (final NoSuchMethodException e) {
System.out.println("Error while initializing containerMerge.NoSuchMethodException: " + e.getMessage());
containerMergeMethod = null;
}
}
public static indexContainer joinExcludeContainers(
- Collection<indexContainer> includeContainers,
- Collection<indexContainer> excludeContainers,
- int maxDistance) {
+ final Collection<indexContainer> includeContainers,
+ final Collection<indexContainer> excludeContainers,
+ final int maxDistance) {
// join a search result and return the joincount (number of pages after join)
// since this is a conjunction we return an empty entity if any word is not known
if (includeContainers == null) return plasmaWordIndex.emptyContainer(null, 0);
// join the result
- indexContainer rcLocal = indexContainer.joinContainers(includeContainers, maxDistance);
+ final indexContainer rcLocal = indexContainer.joinContainers(includeContainers, maxDistance);
if (rcLocal == null) return plasmaWordIndex.emptyContainer(null, 0);
excludeContainers(rcLocal, excludeContainers);
return rcLocal;
}
- public static indexContainer joinContainers(Collection<indexContainer> containers, int maxDistance) {
+ public static indexContainer joinContainers(final Collection<indexContainer> containers, final int maxDistance) {
// order entities by their size
- TreeMap<Long, indexContainer> map = new TreeMap<Long, indexContainer>();
+ final TreeMap<Long, indexContainer> map = new TreeMap<Long, indexContainer>();
indexContainer singleContainer;
- Iterator<indexContainer> i = containers.iterator();
+ final Iterator<indexContainer> i = containers.iterator();
int count = 0;
while (i.hasNext()) {
// get next entity:
@@ -272,12 +272,12 @@ public class indexContainer extends kelondroRowSet {
return searchResult;
}
- public static indexContainer excludeContainers(indexContainer pivot, Collection<indexContainer> containers) {
+ public static indexContainer excludeContainers(indexContainer pivot, final Collection<indexContainer> containers) {
// check if there is any result
if ((containers == null) || (containers.size() == 0)) return pivot; // no result, nothing found
- Iterator<indexContainer> i = containers.iterator();
+ final Iterator<indexContainer> i = containers.iterator();
while (i.hasNext()) {
pivot = excludeDestructive(pivot, i.next());
if ((pivot == null) || (pivot.size() == 0)) return null;
@@ -293,15 +293,15 @@ public class indexContainer extends kelondroRowSet {
return l;
}
- public static indexContainer joinConstructive(indexContainer i1, indexContainer i2, int maxDistance) {
+ public static indexContainer joinConstructive(final indexContainer i1, final indexContainer i2, final int maxDistance) {
if ((i1 == null) || (i2 == null)) return null;
if ((i1.size() == 0) || (i2.size() == 0)) return null;
// decide which method to use
- int high = ((i1.size() > i2.size()) ? i1.size() : i2.size());
- int low = ((i1.size() > i2.size()) ? i2.size() : i1.size());
- int stepsEnum = 10 * (high + low - 1);
- int stepsTest = 12 * log2(high) * low;
+ final int high = ((i1.size() > i2.size()) ? i1.size() : i2.size());
+ final int low = ((i1.size() > i2.size()) ? i2.size() : i1.size());
+ final int stepsEnum = 10 * (high + low - 1);
+ final int stepsTest = 12 * log2(high) * low;
// start most efficient method
if (stepsEnum > stepsTest) {
@@ -314,13 +314,13 @@ public class indexContainer extends kelondroRowSet {
}
}
- private static indexContainer joinConstructiveByTest(indexContainer small, indexContainer large, int maxDistance) {
+ private static indexContainer joinConstructiveByTest(final indexContainer small, final indexContainer large, final int maxDistance) {
System.out.println("DEBUG: JOIN METHOD BY TEST");
assert small.rowdef.equals(large.rowdef) : "small = " + small.rowdef.toString() + "; large = " + large.rowdef.toString();
- int keylength = small.rowdef.width(0);
+ final int keylength = small.rowdef.width(0);
assert (keylength == large.rowdef.width(0));
- indexContainer conj = new indexContainer(null, small.rowdef, 0); // start with empty search result
- Iterator<indexRWIRowEntry> se = small.entries();
+ final indexContainer conj = new indexContainer(null, small.rowdef, 0); // start with empty search result
+ final Iterator<indexRWIRowEntry> se = small.entries();
indexRWIVarEntry ie0;
indexRWIEntry ie1;
while (se.hasNext()) {
@@ -337,16 +337,16 @@ public class indexContainer extends kelondroRowSet {
return conj;
}
- private static indexContainer joinConstructiveByEnumeration(indexContainer i1, indexContainer i2, int maxDistance) {
+ private static indexContainer joinConstructiveByEnumeration(final indexContainer i1, final indexContainer i2, final int maxDistance) {
System.out.println("DEBUG: JOIN METHOD BY ENUMERATION");
assert i1.rowdef.equals(i2.rowdef) : "i1 = " + i1.rowdef.toString() + "; i2 = " + i2.rowdef.toString();
- int keylength = i1.rowdef.width(0);
+ final int keylength = i1.rowdef.width(0);
assert (keylength == i2.rowdef.width(0));
- indexContainer conj = new indexContainer(null, i1.rowdef, 0); // start with empty search result
+ final indexContainer conj = new indexContainer(null, i1.rowdef, 0); // start with empty search result
if (!((i1.rowdef.getOrdering().signature().equals(i2.rowdef.getOrdering().signature())) &&
(i1.rowdef.primaryKeyIndex == i2.rowdef.primaryKeyIndex))) return conj; // ordering must be equal
- Iterator<indexRWIRowEntry> e1 = i1.entries();
- Iterator<indexRWIRowEntry> e2 = i2.entries();
+ final Iterator<indexRWIRowEntry> e1 = i1.entries();
+ final Iterator<indexRWIRowEntry> e2 = i2.entries();
int c;
if ((e1.hasNext()) && (e2.hasNext())) {
indexRWIVarEntry ie1;
@@ -375,17 +375,17 @@ public class indexContainer extends kelondroRowSet {
return conj;
}
- public static indexContainer excludeDestructive(indexContainer pivot, indexContainer excl) {
+ public static indexContainer excludeDestructive(final indexContainer pivot, final indexContainer excl) {
if (pivot == null) return null;
if (excl == null) return pivot;
if (pivot.size() == 0) return null;
if (excl.size() == 0) return pivot;
// decide which method to use
- int high = ((pivot.size() > excl.size()) ? pivot.size() : excl.size());
- int low = ((pivot.size() > excl.size()) ? excl.size() : pivot.size());
- int stepsEnum = 10 * (high + low - 1);
- int stepsTest = 12 * log2(high) * low;
+ final int high = ((pivot.size() > excl.size()) ? pivot.size() : excl.size());
+ final int low = ((pivot.size() > excl.size()) ? excl.size() : pivot.size());
+ final int stepsEnum = 10 * (high + low - 1);
+ final int stepsTest = 12 * log2(high) * low;
// start most efficient method
if (stepsEnum > stepsTest) {
@@ -395,12 +395,12 @@ public class indexContainer extends kelondroRowSet {
}
}
- private static indexContainer excludeDestructiveByTest(indexContainer pivot, indexContainer excl) {
+ private static indexContainer excludeDestructiveByTest(final indexContainer pivot, final indexContainer excl) {
assert pivot.rowdef.equals(excl.rowdef) : "small = " + pivot.rowdef.toString() + "; large = " + excl.rowdef.toString();
- int keylength = pivot.rowdef.width(0);
+ final int keylength = pivot.rowdef.width(0);
assert (keylength == excl.rowdef.width(0));
- boolean iterate_pivot = pivot.size() < excl.size();
- Iterator<indexRWIRowEntry> se = (iterate_pivot) ? pivot.entries() : excl.entries();
+ final boolean iterate_pivot = pivot.size() < excl.size();
+ final Iterator<indexRWIRowEntry> se = (iterate_pivot) ? pivot.entries() : excl.entries();
indexRWIEntry ie0, ie1;
while (se.hasNext()) {
ie0 = se.next();
@@ -414,14 +414,14 @@ public class indexContainer extends kelondroRowSet {
return pivot;
}
- private static indexContainer excludeDestructiveByEnumeration(indexContainer pivot, indexContainer excl) {
+ private static indexContainer excludeDestructiveByEnumeration(final indexContainer pivot, final indexContainer excl) {
assert pivot.rowdef.equals(excl.rowdef) : "i1 = " + pivot.rowdef.toString() + "; i2 = " + excl.rowdef.toString();
- int keylength = pivot.rowdef.width(0);
+ final int keylength = pivot.rowdef.width(0);
assert (keylength == excl.rowdef.width(0));
if (!((pivot.rowdef.getOrdering().signature().equals(excl.rowdef.getOrdering().signature())) &&
(pivot.rowdef.primaryKeyIndex == excl.rowdef.primaryKeyIndex))) return pivot; // ordering must be equal
- Iterator<indexRWIRowEntry> e1 = pivot.entries();
- Iterator<indexRWIRowEntry> e2 = excl.entries();
+ final Iterator<indexRWIRowEntry> e1 = pivot.entries();
+ final Iterator<indexRWIRowEntry> e2 = excl.entries();
int c;
if ((e1.hasNext()) && (e2.hasNext())) {
indexRWIVarEntry ie1;
@@ -459,12 +459,12 @@ public class indexContainer extends kelondroRowSet {
}
- public static final serverByteBuffer compressIndex(indexContainer inputContainer, indexContainer excludeContainer, long maxtime) {
+ public static final serverByteBuffer compressIndex(final indexContainer inputContainer, final indexContainer excludeContainer, final long maxtime) {
// collect references according to domains
- long timeout = (maxtime < 0) ? Long.MAX_VALUE : System.currentTimeMillis() + maxtime;
- TreeMap<String, String> doms = new TreeMap<String, String>();
+ final long timeout = (maxtime < 0) ? Long.MAX_VALUE : System.currentTimeMillis() + maxtime;
+ final TreeMap<String, String> doms = new TreeMap<String, String>();
synchronized (inputContainer) {
- Iterator<indexRWIRowEntry> i = inputContainer.entries();
+ final Iterator<indexRWIRowEntry> i = inputContainer.entries();
indexRWIEntry iEntry;
String dom, paths;
while (i.hasNext()) {
@@ -481,9 +481,9 @@ public class indexContainer extends kelondroRowSet {
}
}
// construct a result string
- serverByteBuffer bb = new serverByteBuffer(inputContainer.size() * 6);
+ final serverByteBuffer bb = new serverByteBuffer(inputContainer.size() * 6);
bb.append('{');
- Iterator<Map.Entry<String, String>> i = doms.entrySet().iterator();
+ final Iterator<Map.Entry<String, String>> i = doms.entrySet().iterator();
Map.Entry<String, String> entry;
while (i.hasNext()) {
entry = i.next();
@@ -499,7 +499,7 @@ public class indexContainer extends kelondroRowSet {
return bb;
}
- public static final void decompressIndex(TreeMap<String, String> target, serverByteBuffer ci, String peerhash) {
+ public static final void decompressIndex(final TreeMap<String, String> target, serverByteBuffer ci, final String peerhash) {
// target is a mapping from url-hashes to a string of peer-hashes
if ((ci.byteAt(0) == '{') && (ci.byteAt(ci.length() - 1) == '}')) {
//System.out.println("DEBUG-DECOMPRESS: input is " + ci.toString());
diff --git a/source/de/anomic/index/indexContainerHeap.java b/source/de/anomic/index/indexContainerHeap.java
index 1e0542495..531bf7bad 100755
--- a/source/de/anomic/index/indexContainerHeap.java
+++ b/source/de/anomic/index/indexContainerHeap.java
@@ -51,8 +51,8 @@ import de.anomic.server.logging.serverLog;
public final class indexContainerHeap {
- private kelondroRow payloadrow;
- private serverLog log;
+ private final kelondroRow payloadrow;
+ private final serverLog log;
private kelondroBytesLongMap index;
SortedMap<String, indexContainer> cache;
private File backupFile;
@@ -79,7 +79,7 @@ public final class indexContainerHeap {
* @param payloadrow
* @param log
*/
- public indexContainerHeap(kelondroRow payloadrow, serverLog log) {
+ public indexContainerHeap(final kelondroRow payloadrow, final serverLog log) {
this.payloadrow = payloadrow;
this.log = log;
this.cache = null;
@@ -110,14 +110,14 @@ public final class indexContainerHeap {
* @param heapFile
* @throws IOException
*/
- public void initWriteMode(File heapFile) throws IOException {
+ public void initWriteMode(final File heapFile) throws IOException {
this.readOnlyMode = false;
if (log != null) log.logInfo("restoring dump for rwi heap '" + heapFile.getName() + "'");
- long start = System.currentTimeMillis();
+ final long start = System.currentTimeMillis();
this.cache = Collections.synchronizedSortedMap(new TreeMap<String, indexContainer>(new kelondroByteOrder.StringOrder(payloadrow.getOrdering())));
int urlCount = 0;
synchronized (cache) {
- for (indexContainer container : new heapFileEntries(heapFile, this.payloadrow)) {
+ for (final indexContainer container : new heapFileEntries(heapFile, this.payloadrow)) {
if (container == null) break;
cache.put(container.getWordHash(), container);
urlCount += container.size();
@@ -134,7 +134,7 @@ public final class indexContainerHeap {
* @param heapFile
* @throws IOException
*/
- public void initReadMode(File heapFile) throws IOException {
+ public void initReadMode(final File heapFile) throws IOException {
this.readOnlyMode = true;
assert this.cache == null;
assert this.index == null;
@@ -143,12 +143,12 @@ public final class indexContainerHeap {
if (heapFile.length() >= Integer.MAX_VALUE) throw new IOException("file " + heapFile + " too large, index can only be crated for files less than 2GB");
if (log != null) log.logInfo("creating index for rwi heap '" + heapFile.getName() + "'");
- long start = System.currentTimeMillis();
+ final long start = System.currentTimeMillis();
this.index = new kelondroBytesLongMap(payloadrow.primaryKeyLength, (kelondroByteOrder) payloadrow.getOrdering(), 0);
DataInputStream is = null;
- long urlCount = 0;
+ final long urlCount = 0;
String wordHash;
- byte[] word = new byte[payloadrow.primaryKeyLength];
+ final byte[] word = new byte[payloadrow.primaryKeyLength];
long seek = 0, seek0;
synchronized (index) {
is = new DataInputStream(new BufferedInputStream(new FileInputStream(heapFile), 64*1024));
@@ -161,7 +161,7 @@ public final class indexContainerHeap {
// read word
try {
is.readFully(word);
- } catch (IOException e) {
+ } catch (final IOException e) {
break loop; // terminate loop
}
wordHash = new String(word);
@@ -170,7 +170,7 @@ public final class indexContainerHeap {
// read collection
try {
seek += kelondroRowSet.skipNextRowSet(is, payloadrow);
- } catch (IOException e) {
+ } catch (final IOException e) {
break loop; // terminate loop
}
index.addl(word, seek0);
@@ -180,19 +180,19 @@ public final class indexContainerHeap {
if (log != null) log.logInfo("finished rwi heap indexing: " + urlCount + " word/URL relations in " + ((System.currentTimeMillis() - start) / 1000) + " seconds");
}
- public void dump(File heapFile) throws IOException {
+ public void dump(final File heapFile) throws IOException {
assert this.cache != null;
if (log != null) log.logInfo("creating rwi heap dump '" + heapFile.getName() + "', " + cache.size() + " rwi's");
if (heapFile.exists()) heapFile.delete();
- DataOutputStream os = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(heapFile), 64 * 1024));
- long startTime = System.currentTimeMillis();
+ final DataOutputStream os = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(heapFile), 64 * 1024));
+ final long startTime = System.currentTimeMillis();
long wordcount = 0, urlcount = 0;
String wordHash;
indexContainer container;
// write wCache
synchronized (cache) {
- for (Map.Entry<String, indexContainer> entry: cache.entrySet()) {
+ for (final Map.Entry<String, indexContainer> entry: cache.entrySet()) {
// get entries
wordHash = entry.getKey();
container = entry.getValue();
@@ -231,7 +231,7 @@ public final class indexContainerHeap {
kelondroRow payloadrow;
indexContainer nextContainer;
- public heapFileEntries(File heapFile, kelondroRow payloadrow) throws IOException {
+ public heapFileEntries(final File heapFile, final kelondroRow payloadrow) throws IOException {
if (!(heapFile.exists())) throw new IOException("file " + heapFile + " does not exist");
is = new DataInputStream(new BufferedInputStream(new FileInputStream(heapFile), 64*1024));
word = new byte[payloadrow.primaryKeyLength];
@@ -247,13 +247,13 @@ public final class indexContainerHeap {
try {
is.readFully(word);
return new indexContainer(new String(word), kelondroRowSet.importRowSet(is, payloadrow));
- } catch (IOException e) {
+ } catch (final IOException e) {
return null;
}
}
public indexContainer next() {
- indexContainer n = this.nextContainer;
+ final indexContainer n = this.nextContainer;
this.nextContainer = next0();
return n;
}
@@ -267,7 +267,7 @@ public final class indexContainerHeap {
}
public void close() {
- if (is != null) try { is.close(); } catch (IOException e) {}
+ if (is != null) try { is.close(); } catch (final IOException e) {}
is = null;
}
@@ -281,7 +281,7 @@ public final class indexContainerHeap {
* in the cache, so that manipulations of the iterated objects do not change
* objects in the cache.
*/
- public synchronized kelondroCloneableIterator<indexContainer> wordContainers(String startWordHash, boolean rot) {
+ public synchronized kelondroCloneableIterator<indexContainer> wordContainers(final String startWordHash, final boolean rot) {
return new heapCacheIterator(startWordHash, rot);
}
@@ -296,16 +296,16 @@ public final class indexContainerHeap {
// so this class simulates wCache.tailMap(startWordHash).values().iterator()
// plus the mentioned features
- private boolean rot;
+ private final boolean rot;
private Iterator<indexContainer> iterator;
- public heapCacheIterator(String startWordHash, boolean rot) {
+ public heapCacheIterator(final String startWordHash, final boolean rot) {
this.rot = rot;
this.iterator = (startWordHash == null) ? cache.values().iterator() : cache.tailMap(startWordHash).values().iterator();
// The collection's iterator will return the values in the order that their corresponding keys appear in the tree.
}
- public heapCacheIterator clone(Object secondWordHash) {
+ public heapCacheIterator clone(final Object secondWordHash) {
return new heapCacheIterator((String) secondWordHash, rot);
}
@@ -344,7 +344,7 @@ public final class indexContainerHeap {
* @param key
* @return true, if the key is used in the heap; false othervise
*/
- public boolean has(String key) {
+ public boolean has(final String key) {
if (this.readOnlyMode) {
assert index != null;
assert index.row().primaryKeyLength == key.length();
@@ -352,7 +352,7 @@ public final class indexContainerHeap {
// check if the index contains the key
try {
return index.getl(key.getBytes()) >= 0;
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
return false;
}
@@ -366,28 +366,28 @@ public final class indexContainerHeap {
* @param key
* @return the indexContainer if one exist, null otherwise
*/
- public indexContainer get(String key) {
+ public indexContainer get(final String key) {
if (this.readOnlyMode) try {
assert index != null;
assert index.row().primaryKeyLength == key.length();
// check if the index contains the key
- long pos = index.getl(key.getBytes());
+ final long pos = index.getl(key.getBytes());
if (pos < 0) return null;
// access the file and read the container
- RandomAccessFile raf = new RandomAccessFile(backupFile, "r");
- byte[] word = new byte[index.row().primaryKeyLength];
+ final RandomAccessFile raf = new RandomAccessFile(backupFile, "r");
+ final byte[] word = new byte[index.row().primaryKeyLength];
raf.seek(pos);
raf.read(word);
assert key.equals(new String(word));
// read collection
- indexContainer container = new indexContainer(key, kelondroRowSet.importRowSet(raf, payloadrow));
+ final indexContainer container = new indexContainer(key, kelondroRowSet.importRowSet(raf, payloadrow));
raf.close();
return container;
- } catch (IOException e) {
+ } catch (final IOException e) {
log.logSevere("error accessing entry in heap file " + this.backupFile + ": " + e.getMessage());
return null;
} else {
@@ -400,7 +400,7 @@ public final class indexContainerHeap {
* @param wordHash
* @return the indexContainer if the cache contained the container, null othervise
*/
- public synchronized indexContainer delete(String wordHash) {
+ public synchronized indexContainer delete(final String wordHash) {
// returns the index that had been deleted
assert this.cache != null;
assert !this.readOnlyMode;
@@ -408,10 +408,10 @@ public final class indexContainerHeap {
}
- public synchronized boolean removeReference(String wordHash, String urlHash) {
+ public synchronized boolean removeReference(final String wordHash, final String urlHash) {
assert this.cache != null;
assert !this.readOnlyMode;
- indexContainer c = cache.get(wordHash);
+ final indexContainer c = cache.get(wordHash);
if ((c != null) && (c.remove(urlHash) != null)) {
// removal successful
if (c.size() == 0) {
@@ -424,11 +424,11 @@ public final class indexContainerHeap {
return false;
}
- public synchronized int removeReferences(String wordHash, Set<String> urlHashes) {
+ public synchronized int removeReferences(final String wordHash, final Set<String> urlHashes) {
assert this.cache != null;
assert !this.readOnlyMode;
if (urlHashes.size() == 0) return 0;
- indexContainer c = cache.get(wordHash);
+ final indexContainer c = cache.get(wordHash);
int count;
if ((c != null) && ((count = c.removeEntries(urlHashes)) > 0)) {
// removal successful
@@ -442,7 +442,7 @@ public final class indexContainerHeap {
return 0;
}
- public synchronized int add(indexContainer container) {
+ public synchronized int add(final indexContainer container) {
// this puts the entries into the cache
int added = 0;
if ((container == null) || (container.size() == 0)) return 0;
@@ -450,7 +450,7 @@ public final class indexContainerHeap {
assert !this.readOnlyMode;
// put new words into cache
- String wordHash = container.getWordHash();
+ final String wordHash = container.getWordHash();
indexContainer entries = cache.get(wordHash); // null pointer exception? wordhash != null! must be cache==null
if (entries == null) {
entries = container.topLevelClone();
@@ -465,7 +465,7 @@ public final class indexContainerHeap {
return added;
}
- public synchronized void addEntry(String wordHash, indexRWIRowEntry newEntry) {
+ public synchronized void addEntry(final String wordHash, final indexRWIRowEntry newEntry) {
assert this.cache != null;
assert !this.readOnlyMode;
indexContainer container = cache.get(wordHash);
diff --git a/source/de/anomic/index/indexContainerOrder.java b/source/de/anomic/index/indexContainerOrder.java
index 97bfdfabf..25e212753 100644
--- a/source/de/anomic/index/indexContainerOrder.java
+++ b/source/de/anomic/index/indexContainerOrder.java
@@ -31,29 +31,29 @@ import de.anomic.kelondro.kelondroOrder;
public class indexContainerOrder extends kelondroAbstractOrder<indexContainer> implements kelondroOrder<indexContainer> {
- private kelondroOrder<byte[]> embeddedOrder;
+ private final kelondroOrder<byte[]> embeddedOrder;
- public indexContainerOrder(kelondroOrder<byte[]> embedOrder) {
+ public indexContainerOrder(final kelondroOrder<byte[]> embedOrder) {
this.embeddedOrder = embedOrder;
}
- public boolean wellformed(indexContainer a) {
+ public boolean wellformed(final indexContainer a) {
return embeddedOrder.wellformed(a.getWordHash().getBytes());
}
- public void direction(boolean ascending) {
+ public void direction(final boolean ascending) {
this.embeddedOrder.direction(ascending);
}
- public long partition(byte[] key, int forks) {
+ public long partition(final byte[] key, final int forks) {
return this.embeddedOrder.partition(key, forks);
}
- public int compare(indexContainer a, indexContainer b) {
+ public int compare(final indexContainer a, final indexContainer b) {
return this.embeddedOrder.compare(a.getWordHash().getBytes(), b.getWordHash().getBytes());
}
- public void rotate(indexContainer zero) {
+ public void rotate(final indexContainer zero) {
this.embeddedOrder.rotate(zero.getWordHash().getBytes());
this.zero = new indexContainer(new String(this.embeddedOrder.zero()), zero);
}
@@ -66,16 +66,16 @@ public class indexContainerOrder extends kelondroAbstractOrder<indexContainer> i
return this.embeddedOrder.signature();
}
- public long cardinal(byte[] key) {
+ public long cardinal(final byte[] key) {
return this.embeddedOrder.cardinal(key);
}
- public boolean equals(kelondroOrder<indexContainer> otherOrder) {
+ public boolean equals(final kelondroOrder<indexContainer> otherOrder) {
if (!(otherOrder instanceof indexContainerOrder)) return false;
return this.embeddedOrder.equals(((indexContainerOrder) otherOrder).embeddedOrder);
}
- public long cardinal(indexContainer key) {
+ public long cardinal(final indexContainer key) {
return this.embeddedOrder.cardinal(key.getWordHash().getBytes());
}
diff --git a/source/de/anomic/index/indexDefaultReferenceBlacklist.java b/source/de/anomic/index/indexDefaultReferenceBlacklist.java
index 3c1f9efb8..bad842090 100644
--- a/source/de/anomic/index/indexDefaultReferenceBlacklist.java
+++ b/source/de/anomic/index/indexDefaultReferenceBlacklist.java
@@ -35,7 +35,7 @@ import java.util.regex.PatternSyntaxException;
public class indexDefaultReferenceBlacklist extends indexAbstractReferenceBlacklist implements indexReferenceBlacklist {
- public indexDefaultReferenceBlacklist(File rootPath) {
+ public indexDefaultReferenceBlacklist(final File rootPath) {
super(rootPath);
}
@@ -43,12 +43,12 @@ public class indexDefaultReferenceBlacklist extends indexAbstractReferenceBlackl
return "Default YaCy Blacklist Engine";
}
- public boolean isListed(String blacklistType, String hostlow, String path) {
+ public boolean isListed(final String blacklistType, final String hostlow, String path) {
if (hostlow == null) throw new NullPointerException();
if (path == null) throw new NullPointerException();
// getting the proper blacklist
- HashMap<String, ArrayList<String>> blacklistMapMatched = super.getBlacklistMap(blacklistType,true);
+ final HashMap<String, ArrayList<String>> blacklistMapMatched = super.getBlacklistMap(blacklistType,true);
if (path.length() > 0 && path.charAt(0) == '/') path = path.substring(1);
ArrayList<String> app;
@@ -98,8 +98,8 @@ public class indexDefaultReferenceBlacklist extends indexAbstractReferenceBlackl
// loop over all Regexentrys
if(!matched) {
- HashMap<String, ArrayList<String>> blacklistMapNotMatched = super.getBlacklistMap(blacklistType,false);
- for(String key: blacklistMapNotMatched.keySet()) {
+ final HashMap<String, ArrayList<String>> blacklistMapNotMatched = super.getBlacklistMap(blacklistType,false);
+ for(final String key: blacklistMapNotMatched.keySet()) {
try {
if(Pattern.matches(key, hostlow)) {
@@ -109,7 +109,7 @@ public class indexDefaultReferenceBlacklist extends indexAbstractReferenceBlackl
return true;
}
}
- } catch (PatternSyntaxException e) {
+ } catch (final PatternSyntaxException e) {
//System.out.println(e.toString());
}
}
diff --git a/source/de/anomic/index/indexPhrase.java b/source/de/anomic/index/indexPhrase.java
index a29e17c3c..e55e262fc 100644
--- a/source/de/anomic/index/indexPhrase.java
+++ b/source/de/anomic/index/indexPhrase.java
@@ -32,10 +32,10 @@ public class indexPhrase {
// object carries statistics for words and sentences
private int count; // number of occurrences
- private int handle; // unique handle, is initialized with sentence counter
- private HashSet<Integer> hash; //
+ private final int handle; // unique handle, is initialized with sentence counter
+ private final HashSet<Integer> hash; //
- public indexPhrase(int handle) {
+ public indexPhrase(final int handle) {
this.count = 1;
this.handle = handle;
this.hash = new HashSet<Integer>();
@@ -53,7 +53,7 @@ public class indexPhrase {
count++;
}
- public void check(int i) {
+ public void check(final int i) {
hash.add(new Integer(i));
}
diff --git a/source/de/anomic/index/indexRAMRI.java b/source/de/anomic/index/indexRAMRI.java
index a11a90cc5..c89808d69 100644
--- a/source/de/anomic/index/indexRAMRI.java
+++ b/source/de/anomic/index/indexRAMRI.java
@@ -47,11 +47,11 @@ public final class indexRAMRI implements indexRI, indexRIReader {
public int cacheReferenceCountLimit; // the maximum number of references to a single RWI entity
public long cacheReferenceAgeLimit; // the maximum age (= time not changed) of a RWI entity
private final serverLog log;
- private File indexHeapFile;
+ private final File indexHeapFile;
private indexContainerHeap heap;
@SuppressWarnings("unchecked")
- public indexRAMRI(File databaseRoot, kelondroRow payloadrow, int entityCacheMaxSize, int wCacheReferenceCountLimitInit, long wCacheReferenceAgeLimitInit, String oldArrayName, String newHeapName, serverLog log) {
+ public indexRAMRI(final File databaseRoot, final kelondroRow payloadrow, final int entityCacheMaxSize, final int wCacheReferenceCountLimitInit, final long wCacheReferenceAgeLimitInit, final String oldArrayName, final String newHeapName, final serverLog log) {
// creates a new index cache
// the cache has a back-end where indexes that do not fit in the cache are flushed
@@ -69,11 +69,11 @@ public final class indexRAMRI implements indexRI, indexRIReader {
if (indexHeapFile.exists()) {
try {
heap.initWriteMode(indexHeapFile);
- for (indexContainer ic : (Iterable<indexContainer>) heap.wordContainers(null, false)) {
+ for (final indexContainer ic : (Iterable<indexContainer>) heap.wordContainers(null, false)) {
this.hashDate.setScore(ic.getWordHash(), intTime(ic.lastWrote()));
this.hashScore.setScore(ic.getWordHash(), ic.size());
}
- } catch (IOException e){
+ } catch (final IOException e){
log.logSevere("unable to restore cache dump: " + e.getMessage(), e);
}
} else {
@@ -91,7 +91,7 @@ public final class indexRAMRI implements indexRI, indexRIReader {
initTime = System.currentTimeMillis();
try {
heap.clear();
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
}
@@ -102,8 +102,8 @@ public final class indexRAMRI implements indexRI, indexRIReader {
return 100 * 1024; // 100 kb
}
- public synchronized long getUpdateTime(String wordHash) {
- indexContainer entries = getContainer(wordHash, null);
+ public synchronized long getUpdateTime(final String wordHash) {
+ final indexContainer entries = getContainer(wordHash, null);
if (entries == null) return 0;
return entries.updated();
}
@@ -124,7 +124,7 @@ public final class indexRAMRI implements indexRI, indexRIReader {
return System.currentTimeMillis() - longEmit(hashDate.getMinScore());
}
- public void setMaxWordCount(int maxWords) {
+ public void setMaxWordCount(final int maxWords) {
this.cacheEntityMaxCount = maxWords;
}
@@ -136,13 +136,13 @@ public final class indexRAMRI implements indexRI, indexRIReader {
return heap.size();
}
- public synchronized int indexSize(String wordHash) {
- indexContainer cacheIndex = heap.get(wordHash);
+ public synchronized int indexSize(final String wordHash) {
+ final indexContainer cacheIndex = heap.get(wordHash);
if (cacheIndex == null) return 0;
return cacheIndex.size();
}
- public synchronized kelondroCloneableIterator<indexContainer> wordContainers(String startWordHash, boolean rot) {
+ public synchronized kelondroCloneableIterator<indexContainer> wordContainers(final String startWordHash, final boolean rot) {
// we return an iterator object that creates top-level-clones of the indexContainers
// in the cache, so that manipulations of the iterated objects do not change
// objects in the cache.
@@ -154,7 +154,7 @@ public final class indexRAMRI implements indexRI, indexRIReader {
if (heap.size() == 0) return null;
try {
return hashScore.getMaxObject();
- } catch (Exception e) {
+ } catch (final Exception e) {
log.logSevere("flushFromMem: " + e.getMessage(), e);
}
return null;
@@ -168,14 +168,14 @@ public final class indexRAMRI implements indexRI, indexRIReader {
if (heap.size() == 0) return null;
try {
String hash = null;
- int count = hashScore.getMaxScore();
+ final int count = hashScore.getMaxScore();
if ((count >= cacheReferenceCountLimit) &&
((hash = hashScore.getMaxObject()) != null)) {
// we MUST flush high-score entries, because a loop deletes entries in cache until this condition fails
// in this cache we MUST NOT check wCacheMinAge
return hash;
}
- long oldestTime = longEmit(hashDate.getMinScore());
+ final long oldestTime = longEmit(hashDate.getMinScore());
if (((System.currentTimeMillis() - oldestTime) > cacheReferenceAgeLimit) &&
((hash = hashDate.getMinObject()) != null)) {
// flush out-dated entries
@@ -190,18 +190,18 @@ public final class indexRAMRI implements indexRI, indexRIReader {
hash = hashDate.getMinObject(); // flush oldest entries
}
if (hash == null) {
- indexContainer ic = heap.wordContainers(null, false).next();
+ final indexContainer ic = heap.wordContainers(null, false).next();
if (ic != null) hash = ic.getWordHash();
}
return hash;
- } catch (Exception e) {
+ } catch (final Exception e) {
log.logSevere("flushFromMem: " + e.getMessage(), e);
}
return null;
}
- public synchronized ArrayList<indexContainer> bestFlushContainers(int count) {
- ArrayList<indexContainer> containerList = new ArrayList<indexContainer>();
+ public synchronized ArrayList<indexContainer> bestFlushContainers(final int count) {
+ final ArrayList<indexContainer> containerList = new ArrayList<indexContainer>();
String hash;
indexContainer container;
for (int i = 0; i < count; i++) {
@@ -217,24 +217,24 @@ public final class indexRAMRI implements indexRI, indexRIReader {
return containerList;
}
- private int intTime(long longTime) {
+ private int intTime(final long longTime) {
return (int) Math.max(0, ((longTime - initTime) / 1000));
}
- private long longEmit(int intTime) {
+ private long longEmit(final int intTime) {
return (((long) intTime) * (long) 1000) + initTime;
}
- public boolean hasContainer(String wordHash) {
+ public boolean hasContainer(final String wordHash) {
return heap.has(wordHash);
}
- public int sizeContainer(String wordHash) {
- indexContainer c = heap.get(wordHash);
+ public int sizeContainer(final String wordHash) {
+ final indexContainer c = heap.get(wordHash);
return (c == null) ? 0 : c.size();
}
- public synchronized indexContainer getContainer(String wordHash, Set<String> urlselection) {
+ public synchronized indexContainer getContainer(final String wordHash, final Set<String> urlselection) {
if (wordHash == null) return null;
// retrieve container
@@ -252,16 +252,16 @@ public final class indexRAMRI implements indexRI, indexRIReader {
return container;
}
- public synchronized indexContainer deleteContainer(String wordHash) {
+ public synchronized indexContainer deleteContainer(final String wordHash) {
// returns the index that had been deleted
- indexContainer container = heap.delete(wordHash);
+ final indexContainer container = heap.delete(wordHash);
hashScore.deleteScore(wordHash);
hashDate.deleteScore(wordHash);
return container;
}
- public synchronized boolean removeEntry(String wordHash, String urlHash) {
- boolean removed = heap.removeReference(wordHash, urlHash);
+ public synchronized boolean removeEntry(final String wordHash, final String urlHash) {
+ final boolean removed = heap.removeReference(wordHash, urlHash);
if (removed) {
if (heap.has(wordHash)) {
hashScore.decScore(wordHash);
@@ -275,9 +275,9 @@ public final class indexRAMRI implements indexRI, indexRIReader {
return false;
}
- public synchronized int removeEntries(String wordHash, Set<String> urlHashes) {
+ public synchronized int removeEntries(final String wordHash, final Set<String> urlHashes) {
if (urlHashes.size() == 0) return 0;
- int c = heap.removeReferences(wordHash, urlHashes);
+ final int c = heap.removeReferences(wordHash, urlHashes);
if (c > 0) {
// removal successful
if (heap.has(wordHash)) {
@@ -292,19 +292,19 @@ public final class indexRAMRI implements indexRI, indexRIReader {
return 0;
}
- public synchronized void addEntries(indexContainer container) {
+ public synchronized void addEntries(final indexContainer container) {
// this puts the entries into the cache, not into the assortment directly
if ((container == null) || (container.size() == 0)) return;
// put new words into cache
- int added = heap.add(container);
+ final int added = heap.add(container);
if (added > 0) {
hashScore.addScore(container.getWordHash(), added);
hashDate.setScore(container.getWordHash(), intTime(System.currentTimeMillis()));
}
}
- public synchronized void addEntry(String wordHash, indexRWIRowEntry newEntry, long updateTime, boolean dhtCase) {
+ public synchronized void addEntry(final String wordHash, final indexRWIRowEntry newEntry, final long updateTime, final boolean dhtCase) {
heap.addEntry(wordHash, newEntry);
hashScore.incScore(wordHash);
hashDate.setScore(wordHash, intTime(updateTime));
@@ -314,7 +314,7 @@ public final class indexRAMRI implements indexRI, indexRIReader {
// dump cache
try {
heap.dump(this.indexHeapFile);
- } catch (IOException e){
+ } catch (final IOException e){
log.logSevere("unable to dump cache: " + e.getMessage(), e);
}
heap = null;
diff --git a/source/de/anomic/index/indexRWIEntryOrder.java b/source/de/anomic/index/indexRWIEntryOrder.java
index de09b98fc..3632871e0 100644
--- a/source/de/anomic/index/indexRWIEntryOrder.java
+++ b/source/de/anomic/index/indexRWIEntryOrder.java
@@ -41,11 +41,11 @@ import de.anomic.yacy.yacyURL;
public class indexRWIEntryOrder {
private indexRWIVarEntry min, max;
- private plasmaSearchRankingProfile ranking;
- private kelondroMScoreCluster<String> doms; // collected for "authority" heuristic
+ private final plasmaSearchRankingProfile ranking;
+ private final kelondroMScoreCluster<String> doms; // collected for "authority" heuristic
private int maxdomcount;
- public indexRWIEntryOrder(plasmaSearchRankingProfile profile) {
+ public indexRWIEntryOrder(final plasmaSearchRankingProfile profile) {
this.min = null;
this.max = null;
this.ranking = profile;
@@ -53,7 +53,7 @@ public class indexRWIEntryOrder {
this.maxdomcount = 0;
}
- public ArrayList<indexRWIVarEntry> normalizeWith(indexContainer container) {
+ public ArrayList<indexRWIVarEntry> normalizeWith(final indexContainer container) {
// normalize ranking: find minimum and maxiumum of separate ranking criteria
assert (container != null);
ArrayList<indexRWIVarEntry> result = null;
@@ -61,10 +61,10 @@ public class indexRWIEntryOrder {
//long s0 = System.currentTimeMillis();
if ((serverProcessor.useCPU > 1) && (container.size() > 600)) {
// run minmax with two threads
- int middle = container.size() / 2;
- minmaxfinder mmf0 = new minmaxfinder(container, 0, middle);
+ final int middle = container.size() / 2;
+ final minmaxfinder mmf0 = new minmaxfinder(container, 0, middle);
mmf0.start(); // fork here
- minmaxfinder mmf1 = new minmaxfinder(container, middle, container.size());
+ final minmaxfinder mmf1 = new minmaxfinder(container, middle, container.size());
mmf1.run(); // execute other fork in this thread
if (this.min == null) this.min = mmf1.entryMin.clone(); else this.min.min(mmf1.entryMin);
if (this.max == null) this.max = mmf1.entryMax.clone(); else this.max.max(mmf1.entryMax);
@@ -74,7 +74,7 @@ public class indexRWIEntryOrder {
entry = di.next();
this.doms.addScore(entry.getKey(), (entry.getValue()).intValue());
}
- try {mmf0.join();} catch (InterruptedException e) {} // wait for fork thread to finish
+ try {mmf0.join();} catch (final InterruptedException e) {} // wait for fork thread to finish
if (this.min == null) this.min = mmf0.entryMin.clone(); else this.min.min(mmf0.entryMin);
if (this.max == null) this.max = mmf0.entryMax.clone(); else this.max.max(mmf0.entryMax);
di = mmf0.domcount().entrySet().iterator();
@@ -88,12 +88,12 @@ public class indexRWIEntryOrder {
//System.out.println("***DEBUG*** indexRWIEntry.Order (2-THREADED): " + sc + " milliseconds for " + container.size() + " entries, " + (container.size() / sc) + " entries/millisecond");
} else if (container.size() > 0) {
// run minmax in one thread
- minmaxfinder mmf = new minmaxfinder(container, 0, container.size());
+ final minmaxfinder mmf = new minmaxfinder(container, 0, container.size());
mmf.run(); // execute without multi-threading
if (this.min == null) this.min = mmf.entryMin.clone(); else this.min.min(mmf.entryMin);
if (this.max == null) this.max = mmf.entryMax.clone(); else this.max.max(mmf.entryMax);
Map.Entry<String, Integer> entry;
- Iterator<Map.Entry<String, Integer>> di = mmf.domcount().entrySet().iterator();
+ final Iterator<Map.Entry<String, Integer>> di = mmf.domcount().entrySet().iterator();
while (di.hasNext()) {
entry = di.next();
this.doms.addScore(entry.getKey(), (entry.getValue()).intValue());
@@ -106,17 +106,17 @@ public class indexRWIEntryOrder {
return result;
}
- public int authority(String urlHash) {
+ public int authority(final String urlHash) {
return (doms.getScore(urlHash.substring(6)) << 8) / (1 + this.maxdomcount);
}
- public long cardinal(indexRWIVarEntry t) {
+ public long cardinal(final indexRWIVarEntry t) {
//return Long.MAX_VALUE - preRanking(ranking, iEntry, this.entryMin, this.entryMax, this.searchWords);
// the normalizedEntry must be a normalized indexEntry
- kelondroBitfield flags = t.flags();
- long tf = ((max.termFrequency() == min.termFrequency()) ? 0 : (((int)(((t.termFrequency()-min.termFrequency())*256.0)/(max.termFrequency() - min.termFrequency())))) << ranking.coeff_termfrequency);
+ final kelondroBitfield flags = t.flags();
+ final long tf = ((max.termFrequency() == min.termFrequency()) ? 0 : (((int)(((t.termFrequency()-min.termFrequency())*256.0)/(max.termFrequency() - min.termFrequency())))) << ranking.coeff_termfrequency);
//System.out.println("tf(" + t.urlHash + ") = " + Math.floor(1000 * t.termFrequency()) + ", min = " + Math.floor(1000 * min.termFrequency()) + ", max = " + Math.floor(1000 * max.termFrequency()) + ", tf-normed = " + tf);
- long r =
+ final long r =
((256 - yacyURL.domLengthNormalized(t.urlHash())) << ranking.coeff_domlength)
+ ((ranking.coeff_ybr > 12) ? ((256 - (plasmaSearchRankingProcess.ybr(t.urlHash()) << 4)) << ranking.coeff_ybr) : 0)
+ ((max.urlcomps() == min.urlcomps() ) ? 0 : (256 - (((t.urlcomps() - min.urlcomps() ) << 8) / (max.urlcomps() - min.urlcomps()) )) << ranking.coeff_urlcomps)
@@ -155,13 +155,13 @@ public class indexRWIEntryOrder {
indexRWIVarEntry entryMin;
indexRWIVarEntry entryMax;
- private indexContainer container;
- private int start, end;
- private HashMap<String, Integer> doms;
- private Integer int1;
+ private final indexContainer container;
+ private final int start, end;
+ private final HashMap<String, Integer> doms;
+ private final Integer int1;
ArrayList<indexRWIVarEntry> decodedEntries;
- public minmaxfinder(indexContainer container, int start /*including*/, int end /*excluding*/) {
+ public minmaxfinder(final indexContainer container, final int start /*including*/, final int end /*excluding*/) {
this.container = container;
this.start = start;
this.end = end;
diff --git a/source/de/anomic/index/indexRWIRowEntry.java b/source/de/anomic/index/indexRWIRowEntry.java
index 83afefca3..77b7250cd 100644
--- a/source/de/anomic/index/indexRWIRowEntry.java
+++ b/source/de/anomic/index/indexRWIRowEntry.java
@@ -88,32 +88,32 @@ public final class indexRWIRowEntry implements indexRWIEntry {
private static final int col_reserve1 = 18; // i 1 reserve1
private static final int col_reserve2 = 19; // k 1 reserve2
- private kelondroRow.Entry entry;
+ private final kelondroRow.Entry entry;
- public indexRWIRowEntry(String urlHash,
- int urlLength, // byte-length of complete URL
- int urlComps, // number of path components
- int titleLength, // length of description/length (longer are better?)
- int hitcount, // how often appears this word in the text
- int wordcount, // total number of words
- int phrasecount, // total number of phrases
- int posintext, // position of word in all words
- int posinphrase, // position of word in its phrase
- int posofphrase, // number of the phrase where word appears
- long lastmodified, // last-modified time of the document where word appears
- long updatetime, // update time; this is needed to compute a TTL for the word, so it can be removed easily if the TTL is short
+ public indexRWIRowEntry(final String urlHash,
+ final int urlLength, // byte-length of complete URL
+ final int urlComps, // number of path components
+ final int titleLength, // length of description/length (longer are better?)
+ final int hitcount, // how often appears this word in the text
+ final int wordcount, // total number of words
+ final int phrasecount, // total number of phrases
+ final int posintext, // position of word in all words
+ final int posinphrase, // position of word in its phrase
+ final int posofphrase, // number of the phrase where word appears
+ final long lastmodified, // last-modified time of the document where word appears
+ final long updatetime, // update time; this is needed to compute a TTL for the word, so it can be removed easily if the TTL is short
String language, // (guessed) language of document
- char doctype, // type of document
- int outlinksSame, // outlinks to same domain
- int outlinksOther, // outlinks to other domain
- kelondroBitfield flags // attributes to the url and to the word according the url
+ final char doctype, // type of document
+ final int outlinksSame, // outlinks to same domain
+ final int outlinksOther, // outlinks to other domain
+ final kelondroBitfield flags // attributes to the url and to the word according the url
) {
assert (urlHash.length() == 12) : "urlhash = " + urlHash;
if ((language == null) || (language.length() != urlEntryRow.width(col_language))) language = "uk";
this.entry = urlEntryRow.newEntry();
- int mddlm = kelondroMicroDate.microDateDays(lastmodified);
- int mddct = kelondroMicroDate.microDateDays(updatetime);
+ final int mddlm = kelondroMicroDate.microDateDays(lastmodified);
+ final int mddct = kelondroMicroDate.microDateDays(updatetime);
this.entry.setCol(col_urlhash, urlHash, null);
this.entry.setCol(col_lastModified, mddlm);
this.entry.setCol(col_freshUntil, Math.max(0, mddlm + (mddct - mddlm) * 2)); // TTL computation
@@ -136,30 +136,30 @@ public final class indexRWIRowEntry implements indexRWIEntry {
this.entry.setCol(col_reserve2, 0);
}
- public indexRWIRowEntry(String urlHash, String code) {
+ public indexRWIRowEntry(final String urlHash, final String code) {
// the code is the external form of the row minus the leading urlHash entry
this.entry = urlEntryRow.newEntry((urlHash + code).getBytes());
}
- public indexRWIRowEntry(String external) {
+ public indexRWIRowEntry(final String external) {
this.entry = urlEntryRow.newEntry(external, true);
}
- public indexRWIRowEntry(byte[] row) {
+ public indexRWIRowEntry(final byte[] row) {
this.entry = urlEntryRow.newEntry(row);
}
- public indexRWIRowEntry(byte[] row, int offset, boolean clone) {
+ public indexRWIRowEntry(final byte[] row, final int offset, final boolean clone) {
this.entry = urlEntryRow.newEntry(row, offset, clone);
}
- public indexRWIRowEntry(kelondroRow.Entry rentry) {
+ public indexRWIRowEntry(final kelondroRow.Entry rentry) {
// FIXME: see if cloning is necessary
this.entry = rentry;
}
public indexRWIRowEntry clone() {
- byte[] b = new byte[urlEntryRow.objectsize];
+ final byte[] b = new byte[urlEntryRow.objectsize];
System.arraycopy(entry.bytes(), 0, b, 0, urlEntryRow.objectsize);
return new indexRWIRowEntry(b);
}
@@ -252,13 +252,13 @@ public final class indexRWIRowEntry implements indexRWIEntry {
return toPropertyForm();
}
- public boolean isNewer(indexRWIEntry other) {
+ public boolean isNewer(final indexRWIEntry other) {
if (other == null) return true;
if (this.lastModified() > other.lastModified()) return true;
return false;
}
- public boolean isOlder(indexRWIEntry other) {
+ public boolean isOlder(final indexRWIEntry other) {
if (other == null) return false;
if (this.lastModified() < other.lastModified()) return true;
return false;
diff --git a/source/de/anomic/index/indexRWIVarEntry.java b/source/de/anomic/index/indexRWIVarEntry.java
index bfd2eaf2a..df533ada9 100644
--- a/source/de/anomic/index/indexRWIVarEntry.java
+++ b/source/de/anomic/index/indexRWIVarEntry.java
@@ -41,29 +41,29 @@ public class indexRWIVarEntry implements indexRWIEntry {
worddistance, wordsintext, wordsintitle;
public double termFrequency;
- public indexRWIVarEntry(String urlHash,
- int urlLength, // byte-length of complete URL
- int urlComps, // number of path components
- int titleLength, // length of description/length (longer are better?)
- int hitcount, // how often appears this word in the text
- int wordcount, // total number of words
- int phrasecount, // total number of phrases
- int posintext, // position of word in all words
- int posinphrase, // position of word in its phrase
- int posofphrase, // number of the phrase where word appears
- long lastmodified, // last-modified time of the document where word appears
- long updatetime, // update time; this is needed to compute a TTL for the word, so it can be removed easily if the TTL is short
+ public indexRWIVarEntry(final String urlHash,
+ final int urlLength, // byte-length of complete URL
+ final int urlComps, // number of path components
+ final int titleLength, // length of description/length (longer are better?)
+ final int hitcount, // how often appears this word in the text
+ final int wordcount, // total number of words
+ final int phrasecount, // total number of phrases
+ final int posintext, // position of word in all words
+ final int posinphrase, // position of word in its phrase
+ final int posofphrase, // number of the phrase where word appears
+ final long lastmodified, // last-modified time of the document where word appears
+ final long updatetime, // update time; this is needed to compute a TTL for the word, so it can be removed easily if the TTL is short
String language, // (guessed) language of document
- char doctype, // type of document
- int outlinksSame, // outlinks to same domain
- int outlinksOther, // outlinks to other domain
- kelondroBitfield flags, // attributes to the url and to the word according the url
- int worddistance,
- double termfrequency
+ final char doctype, // type of document
+ final int outlinksSame, // outlinks to same domain
+ final int outlinksOther, // outlinks to other domain
+ final kelondroBitfield flags, // attributes to the url and to the word according the url
+ final int worddistance,
+ final double termfrequency
) {
if ((language == null) || (language.length() != 2)) language = "uk";
- int mddlm = kelondroMicroDate.microDateDays(lastmodified);
- int mddct = kelondroMicroDate.microDateDays(updatetime);
+ final int mddlm = kelondroMicroDate.microDateDays(lastmodified);
+ final int mddct = kelondroMicroDate.microDateDays(updatetime);
this.flags = flags;
this.freshUntil = Math.max(0, mddlm + (mddct - mddlm) * 2);
this.lastModified = lastmodified;
@@ -86,7 +86,7 @@ public class indexRWIVarEntry implements indexRWIEntry {
this.termFrequency = termfrequency;
}
- public indexRWIVarEntry(indexRWIRowEntry e) {
+ public indexRWIVarEntry(final indexRWIRowEntry e) {
this.flags = e.flags();
this.freshUntil = e.freshUntil();
this.lastModified = e.lastModified();
@@ -110,7 +110,7 @@ public class indexRWIVarEntry implements indexRWIEntry {
}
public indexRWIVarEntry clone() {
- indexRWIVarEntry c = new indexRWIVarEntry(
+ final indexRWIVarEntry c = new indexRWIVarEntry(
this.urlHash,
this.urllength,
this.urlcomps,
@@ -133,7 +133,7 @@ public class indexRWIVarEntry implements indexRWIEntry {
return c;
}
- public void join(indexRWIVarEntry oe) {
+ public void join(final indexRWIVarEntry oe) {
// combine the distance
this.worddistance = this.worddistance + oe.worddistance + Math.abs(this.posintext - oe.posintext);
this.posintext = Math.min(this.posintext, oe.posintext);
@@ -165,12 +165,12 @@ public class indexRWIVarEntry implements indexRWIEntry {
return hitcount;
}
- public boolean isNewer(indexRWIEntry other) {
+ public boolean isNewer(final indexRWIEntry other) {
assert false; // should not be used
return false;
}
- public boolean isOlder(indexRWIEntry other) {
+ public boolean isOlder(final indexRWIEntry other) {
assert false; // should not be used
return false;
}
@@ -262,7 +262,7 @@ public class indexRWIVarEntry implements indexRWIEntry {
return this.termFrequency;
}
- public final void min(indexRWIVarEntry other) {
+ public final void min(final indexRWIVarEntry other) {
int v;
long w;
double d;
@@ -284,7 +284,7 @@ public class indexRWIVarEntry implements indexRWIEntry {
if (this.termFrequency > (d = other.termFrequency)) this.termFrequency = d;
}
- public final void max(indexRWIVarEntry other) {
+ public final void max(final indexRWIVarEntry other) {
int v;
long w;
double d;
@@ -306,7 +306,7 @@ public class indexRWIVarEntry implements indexRWIEntry {
if (this.termFrequency < (d = other.termFrequency)) this.termFrequency = d;
}
- public void join(indexRWIEntry oe) {
+ public void join(final indexRWIEntry oe) {
// joins two entries into one entry
// combine the distance
diff --git a/source/de/anomic/index/indexReferenceBlacklist.java b/source/de/anomic/index/indexReferenceBlacklist.java
index f816853e7..4a1900e4b 100644
--- a/source/de/anomic/index/indexReferenceBlacklist.java
+++ b/source/de/anomic/index/indexReferenceBlacklist.java
@@ -46,7 +46,7 @@ public interface indexReferenceBlacklist {
private final String filename;
private final String type;
- public blacklistFile(String filename, String type) {
+ public blacklistFile(final String filename, final String type) {
this.filename = filename;
this.type = type;
}
@@ -61,7 +61,7 @@ public interface indexReferenceBlacklist {
* @return unified String array of file names
*/
public String[] getFileNamesUnified() {
- HashSet<String> hs = new HashSet<String>(Arrays.asList(this.filename.split(",")));
+ final HashSet<String> hs = new HashSet<String>(Arrays.asList(this.filename.split(",")));
return hs.toArray(new String[hs.size()]);
}
diff --git a/source/de/anomic/index/indexRepositoryReference.java b/source/de/anomic/index/indexRepositoryReference.java
index a62b92dcc..ace200e55 100644
--- a/source/de/anomic/index/indexRepositoryReference.java
+++ b/source/de/anomic/index/indexRepositoryReference.java
@@ -58,7 +58,7 @@ public final class indexRepositoryReference {
private Export exportthread = null; // will habe a export thread assigned if exporter is running
private File location = null;
- public indexRepositoryReference(File indexSecondaryPath) {
+ public indexRepositoryReference(final File indexSecondaryPath) {
super();
this.location = new File(indexSecondaryPath, "TEXT");
urlIndexFile = new kelondroCache(new kelondroSplitTable(this.location, "urls", indexURLReference.rowdef, false));
@@ -90,16 +90,16 @@ public final class indexRepositoryReference {
return 0;
}
- public synchronized indexURLReference load(String urlHash, indexRWIEntry searchedWord, long ranking) {
+ public synchronized indexURLReference load(final String urlHash, final indexRWIEntry searchedWord, final long ranking) {
// generates an plasmaLURLEntry using the url hash
// if the url cannot be found, this returns null
if (urlHash == null) return null;
assert urlIndexFile != null;
try {
- kelondroRow.Entry entry = urlIndexFile.get(urlHash.getBytes());
+ final kelondroRow.Entry entry = urlIndexFile.get(urlHash.getBytes());
if (entry == null) return null;
return new indexURLReference(entry, searchedWord, ranking);
- } catch (IOException e) {
+ } catch (final IOException e) {
return null;
}
}
@@ -113,7 +113,7 @@ public final class indexRepositoryReference {
} else {
oldEntry = null;
}
- } catch (Exception e) {
+ } catch (final Exception e) {
e.printStackTrace();
oldEntry = null;
}
@@ -128,10 +128,10 @@ public final class indexRepositoryReference {
urlIndexFile.put(entry.toRowEntry(), new Date() /*entry.loaddate()*/);
}
- public synchronized indexURLReference newEntry(String propStr) {
+ public synchronized indexURLReference newEntry(final String propStr) {
if (propStr != null && propStr.startsWith("{") && propStr.endsWith("}")) try {
return new indexURLReference(serverCodings.s2p(propStr.substring(1, propStr.length() - 1)));
- } catch (kelondroException e) {
+ } catch (final kelondroException e) {
// wrong format
return null;
} else {
@@ -139,42 +139,42 @@ public final class indexRepositoryReference {
}
}
- public synchronized boolean remove(String urlHash) {
+ public synchronized boolean remove(final String urlHash) {
if (urlHash == null) return false;
try {
- kelondroRow.Entry r = urlIndexFile.remove(urlHash.getBytes());
+ final kelondroRow.Entry r = urlIndexFile.remove(urlHash.getBytes());
return r != null;
- } catch (IOException e) {
+ } catch (final IOException e) {
return false;
}
}
- public synchronized boolean exists(String urlHash) {
+ public synchronized boolean exists(final String urlHash) {
if (urlIndexFile == null) return false; // case may happen during shutdown
return urlIndexFile.has(urlHash.getBytes());
}
- public kelondroCloneableIterator<indexURLReference> entries(boolean up, String firstHash) throws IOException {
+ public kelondroCloneableIterator<indexURLReference> entries(final boolean up, final String firstHash) throws IOException {
// enumerates entry elements
return new kiter(up, firstHash);
}
public class kiter implements kelondroCloneableIterator<indexURLReference> {
// enumerates entry elements
- private Iterator<kelondroRow.Entry> iter;
- private boolean error;
+ private final Iterator<kelondroRow.Entry> iter;
+ private final boolean error;
boolean up;
- public kiter(boolean up, String firstHash) throws IOException {
+ public kiter(final boolean up, final String firstHash) throws IOException {
this.up = up;
this.iter = urlIndexFile.rows(up, (firstHash == null) ? null : firstHash.getBytes());
this.error = false;
}
- public kiter clone(Object secondHash) {
+ public kiter clone(final Object secondHash) {
try {
return new kiter(up, (String) secondHash);
- } catch (IOException e) {
+ } catch (final IOException e) {
return null;
}
}
@@ -205,27 +205,27 @@ public final class indexRepositoryReference {
*
* @param proxyConfig
*/
- public void deadlinkCleaner(httpRemoteProxyConfig proxyConfig) {
- serverLog log = new serverLog("URLDBCLEANUP");
- HashSet<String> damagedURLS = new HashSet<String>();
+ public void deadlinkCleaner(final httpRemoteProxyConfig proxyConfig) {
+ final serverLog log = new serverLog("URLDBCLEANUP");
+ final HashSet<String> damagedURLS = new HashSet<String>();
try {
- Iterator<indexURLReference> eiter = entries(true, null);
+ final Iterator<indexURLReference> eiter = entries(true, null);
int iteratorCount = 0;
while (eiter.hasNext()) try {
eiter.next();
iteratorCount++;
- } catch (RuntimeException e) {
+ } catch (final RuntimeException e) {
if(e.getMessage() != null) {
- String m = e.getMessage();
+ final String m = e.getMessage();
damagedURLS.add(m.substring(m.length() - 12));
} else {
log.logSevere("RuntimeException:", e);
}
}
- try { Thread.sleep(1000); } catch (InterruptedException e) { }
+ try { Thread.sleep(1000); } catch (final InterruptedException e) { }
log.logInfo("URLs vorher: " + urlIndexFile.size() + " Entries loaded during Iteratorloop: " + iteratorCount + " kaputte URLs: " + damagedURLS.size());
- Iterator<String> eiter2 = damagedURLS.iterator();
+ final Iterator<String> eiter2 = damagedURLS.iterator();
String urlHash;
while (eiter2.hasNext()) {
urlHash = eiter2.next();
@@ -234,7 +234,7 @@ public final class indexRepositoryReference {
String oldUrlStr = null;
try {
// getting the url data as byte array
- kelondroRow.Entry entry = urlIndexFile.get(urlHash.getBytes());
+ final kelondroRow.Entry entry = urlIndexFile.get(urlHash.getBytes());
// getting the wrong url string
oldUrlStr = entry.getColString(1, null).trim();
@@ -242,11 +242,11 @@ public final class indexRepositoryReference {
int pos = -1;
if ((pos = oldUrlStr.indexOf("://")) != -1) {
// trying to correct the url
- String newUrlStr = "http://" + oldUrlStr.substring(pos + 3);
- yacyURL newUrl = new yacyURL(newUrlStr, null);
+ final String newUrlStr = "http://" + oldUrlStr.substring(pos + 3);
+ final yacyURL newUrl = new yacyURL(newUrlStr, null);
// doing a http head request to test if the url is correct
- JakartaCommonsHttpClient client = new JakartaCommonsHttpClient(10000, null, null);
+ final JakartaCommonsHttpClient client = new JakartaCommonsHttpClient(10000, null, null);
client.setProxy(proxyConfig);
JakartaCommonsHttpResponse res = null;
try {
@@ -267,19 +267,19 @@ public final class indexRepositoryReference {
log.logInfo("UrlDB-Entry with urlHash '" + urlHash + "' removed\n\tURL: " + oldUrlStr + "\n\tConnection Status: " + (res == null ? "null" : res.getStatusLine()));
}
}
- } catch (Exception e) {
+ } catch (final Exception e) {
remove(urlHash);
log.logInfo("UrlDB-Entry with urlHash '" + urlHash + "' removed\n\tURL: " + oldUrlStr + "\n\tExecption: " + e.getMessage());
}
}
log.logInfo("URLs nachher: " + size() + " kaputte URLs: " + damagedURLS.size());
- } catch (IOException e) {
+ } catch (final IOException e) {
log.logSevere("IOException", e);
}
}
- public BlacklistCleaner getBlacklistCleaner(indexReferenceBlacklist blacklist) {
+ public BlacklistCleaner getBlacklistCleaner(final indexReferenceBlacklist blacklist) {
return new BlacklistCleaner(blacklist);
}
@@ -293,9 +293,9 @@ public final class indexRepositoryReference {
public String lastBlacklistedHash = "";
public String lastUrl = "";
public String lastHash = "";
- private indexReferenceBlacklist blacklist;
+ private final indexReferenceBlacklist blacklist;
- public BlacklistCleaner(indexReferenceBlacklist blacklist) {
+ public BlacklistCleaner(final indexReferenceBlacklist blacklist) {
this.blacklist = blacklist;
}
@@ -308,7 +308,7 @@ public final class indexRepositoryReference {
if (this.pause) {
try {
this.wait();
- } catch (InterruptedException e) {
+ } catch (final InterruptedException e) {
serverLog.logWarning("URLDBCLEANER", "InterruptedException", e);
this.run = false;
return;
@@ -340,7 +340,7 @@ public final class indexRepositoryReference {
lastHash = entry.hash();
}
}
- } catch (RuntimeException e) {
+ } catch (final RuntimeException e) {
if (e.getMessage() != null && e.getMessage().indexOf("not found in LURL") != -1) {
serverLog.logWarning("URLDBCLEANER", "urlHash not found in LURL", e);
}
@@ -348,7 +348,7 @@ public final class indexRepositoryReference {
serverLog.logWarning("URLDBCLEANER", "RuntimeException", e);
run = false;
}
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
run = false;
}
@@ -383,7 +383,7 @@ public final class indexRepositoryReference {
}
// export methods
- public Export export(File f, String filter, int format, boolean dom) {
+ public Export export(final File f, final String filter, final int format, final boolean dom) {
if ((exportthread != null) && (exportthread.isAlive())) {
serverLog.logWarning("LURL-EXPORT", "cannot start another export thread, already one running");
return exportthread;
@@ -398,15 +398,15 @@ public final class indexRepositoryReference {
}
public class Export extends Thread {
- private File f;
- private String filter;
+ private final File f;
+ private final String filter;
private int count;
private String failure;
- private int format;
- private boolean dom;
- private kelondroRowSet doms;
+ private final int format;
+ private final boolean dom;
+ private final kelondroRowSet doms;
- public Export(File f, String filter, int format, boolean dom) {
+ public Export(final File f, final String filter, final int format, boolean dom) {
// format: 0=text, 1=html, 2=rss/xml
this.f = f;
this.filter = filter;
@@ -421,7 +421,7 @@ public final class indexRepositoryReference {
public void run() {
try {
f.getParentFile().mkdirs();
- PrintWriter pw = new PrintWriter(new BufferedOutputStream(new FileOutputStream(f)));
+ final PrintWriter pw = new PrintWriter(new BufferedOutputStream(new FileOutputStream(f)));
if (format == 1) {
pw.println("<html><head></head><body>");
}
@@ -435,7 +435,7 @@ public final class indexRepositoryReference {
pw.println("<link>http://yacy.net</link>");
}
- Iterator<indexURLReference> i = entries(true, null); // iterates indexURLEntry objects
+ final Iterator<indexURLReference> i = entries(true, null); // iterates indexURLEntry objects
indexURLReference entry;
indexURLReference.Components comp;
String url;
@@ -482,7 +482,7 @@ public final class indexRepositoryReference {
pw.println("</rss>");
}
pw.close();
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
this.failure = e.getMessage();
}
diff --git a/source/de/anomic/index/indexURLReference.java b/source/de/anomic/index/indexURLReference.java
index 328f85b4b..75f908337 100644
--- a/source/de/anomic/index/indexURLReference.java
+++ b/source/de/anomic/index/indexURLReference.java
@@ -112,33 +112,33 @@ public class indexURLReference {
/** of embedded links to applications */
private static final int col_lapp = 17;
- private kelondroRow.Entry entry;
- private String snippet;
+ private final kelondroRow.Entry entry;
+ private final String snippet;
private indexRWIEntry word; // this is only used if the url is transported via remote search requests
- private long ranking; // during generation of a search result this value is set
+ private final long ranking; // during generation of a search result this value is set
public indexURLReference(
- yacyURL url,
- String dc_title,
- String dc_creator,
- String dc_subject,
- String ETag,
- Date mod,
- Date load,
- Date fresh,
- String referrer,
- byte[] md5,
- long size,
- int wc,
- char dt,
- kelondroBitfield flags,
- String lang,
- int llocal,
- int lother,
- int laudio,
- int limage,
- int lvideo,
- int lapp) {
+ final yacyURL url,
+ final String dc_title,
+ final String dc_creator,
+ final String dc_subject,
+ final String ETag,
+ final Date mod,
+ final Date load,
+ final Date fresh,
+ final String referrer,
+ final byte[] md5,
+ final long size,
+ final int wc,
+ final char dt,
+ final kelondroBitfield flags,
+ final String lang,
+ final int llocal,
+ final int lother,
+ final int laudio,
+ final int limage,
+ final int lvideo,
+ final int lapp) {
// create new entry and store it into database
this.entry = rowdef.newEntry();
this.entry.setCol(col_hash, url.hash(), null);
@@ -165,17 +165,17 @@ public class indexURLReference {
this.ranking = 0;
}
- private void encodeDate(int col, Date d) {
+ private void encodeDate(final int col, final Date d) {
// calculates the number of days since 1.1.1970 and returns this as 4-byte array
this.entry.setCol(col, kelondroNaturalOrder.encodeLong(d.getTime() / 86400000, 4));
}
- private Date decodeDate(int col) {
+ private Date decodeDate(final int col) {
return new Date(86400000 * this.entry.getColLong(col));
}
- public static byte[] encodeComp(yacyURL url, String dc_title, String dc_creator, String dc_subject, String ETag) {
- serverCharBuffer s = new serverCharBuffer(200);
+ public static byte[] encodeComp(final yacyURL url, final String dc_title, final String dc_creator, final String dc_subject, final String ETag) {
+ final serverCharBuffer s = new serverCharBuffer(200);
s.append(url.toNormalform(false, true)).append(10);
s.append(dc_title).append(10);
s.append(dc_creator).append(10);
@@ -184,21 +184,21 @@ public class indexURLReference {
return s.toString().getBytes();
}
- public indexURLReference(kelondroRow.Entry entry, indexRWIEntry searchedWord, long ranking) {
+ public indexURLReference(final kelondroRow.Entry entry, final indexRWIEntry searchedWord, final long ranking) {
this.entry = entry;
this.snippet = null;
this.word = searchedWord;
this.ranking = ranking;
}
- public indexURLReference(Properties prop) {
+ public indexURLReference(final Properties prop) {
// generates an plasmaLURLEntry using the properties from the argument
// the property names must correspond to the one from toString
//System.out.println("DEBUG-ENTRY: prop=" + prop.toString());
yacyURL url;
try {
url = new yacyURL(crypt.simpleDecode(prop.getProperty("url", ""), null), prop.getProperty("hash"));
- } catch (MalformedURLException e) {
+ } catch (final MalformedURLException e) {
url = null;
}
String descr = crypt.simpleDecode(prop.getProperty("descr", ""), null); if (descr == null) descr = "";
@@ -211,17 +211,17 @@ public class indexURLReference {
this.entry.setCol(col_comp, encodeComp(url, descr, dc_creator, tags, ETag));
try {
encodeDate(col_mod, serverDate.parseShortDay(prop.getProperty("mod", "20000101")));
- } catch (ParseException e) {
+ } catch (final ParseException e) {
encodeDate(col_mod, new Date());
}
try {
encodeDate(col_load, serverDate.parseShortDay(prop.getProperty("load", "20000101")));
- } catch (ParseException e) {
+ } catch (final ParseException e) {
encodeDate(col_load, new Date());
}
try {
encodeDate(col_fresh, serverDate.parseShortDay(prop.getProperty("fresh", "20000101")));
- } catch (ParseException e) {
+ } catch (final ParseException e) {
encodeDate(col_fresh, new Date());
}
this.entry.setCol(col_referrer, prop.getProperty("referrer", "").getBytes());
@@ -229,7 +229,7 @@ public class indexURLReference {
this.entry.setCol(col_size, Integer.parseInt(prop.getProperty("size", "0")));
this.entry.setCol(col_wc, Integer.parseInt(prop.getProperty("wc", "0")));
this.entry.setCol(col_dt, new byte[]{(byte) prop.getProperty("dt", "t").charAt(0)});
- String flags = prop.getProperty("flags", "AAAAAA");
+ final String flags = prop.getProperty("flags", "AAAAAA");
this.entry.setCol(col_flags, (flags.length() > 6) ? plasmaSearchQuery.empty_constraint.bytes() : (new kelondroBitfield(4, flags)).bytes());
this.entry.setCol(col_lang, prop.getProperty("lang", "uk").getBytes());
this.entry.setCol(col_llocal, Integer.parseInt(prop.getProperty("llocal", "0")));
@@ -247,10 +247,10 @@ public class indexURLReference {
this.ranking = 0;
}
- public static indexURLReference importEntry(String propStr) {
+ public static indexURLReference importEntry(final String propStr) {
if (propStr != null && propStr.startsWith("{") && propStr.endsWith("}")) try {
return new indexURLReference(serverCodings.s2p(propStr.substring(1, propStr.length() - 1)));
- } catch (kelondroException e) {
+ } catch (final kelondroException e) {
// wrong format
return null;
} else {
@@ -260,7 +260,7 @@ public class indexURLReference {
private StringBuffer corePropList() {
// generate a parseable string; this is a simple property-list
- indexURLReference.Components comp = this.comp();
+ final indexURLReference.Components comp = this.comp();
final StringBuffer s = new StringBuffer(300);
//System.out.println("author=" + comp.author());
try {
@@ -293,7 +293,7 @@ public class indexURLReference {
}
return s;
- } catch (Exception e) {
+ } catch (final Exception e) {
// serverLog.logFailure("plasmaLURL.corePropList", e.getMessage());
// if (moddate == null) serverLog.logFailure("plasmaLURL.corePropList", "moddate=null");
// if (loaddate == null) serverLog.logFailure("plasmaLURL.corePropList", "loaddate=null");
@@ -319,7 +319,7 @@ public class indexURLReference {
}
public indexURLReference.Components comp() {
- ArrayList<String> cl = nxTools.strings(this.entry.getCol("comp", null), "UTF-8");
+ final ArrayList<String> cl = nxTools.strings(this.entry.getCol("comp", null), "UTF-8");
return new indexURLReference.Components(
(cl.size() > 0) ? (cl.get(0)).trim() : "",
hash(),
@@ -405,21 +405,21 @@ public class indexURLReference {
return word;
}
- public boolean isOlder(indexURLReference other) {
+ public boolean isOlder(final indexURLReference other) {
if (other == null) return false;
- Date tmoddate = moddate();
- Date omoddate = other.moddate();
+ final Date tmoddate = moddate();
+ final Date omoddate = other.moddate();
if (tmoddate.before(omoddate)) return true;
if (tmoddate.equals(omoddate)) {
- Date tloaddate = loaddate();
- Date oloaddate = other.loaddate();
+ final Date tloaddate = loaddate();
+ final Date oloaddate = other.loaddate();
if (tloaddate.before(oloaddate)) return true;
if (tloaddate.equals(oloaddate)) return true;
}
return false;
}
- public String toString(String snippet) {
+ public String toString(final String snippet) {
// add information needed for remote transport
final StringBuffer core = corePropList();
if (core == null)
@@ -434,7 +434,7 @@ public class indexURLReference {
//return "{" + core + ",snippet=" + crypt.simpleEncode(snippet) + "}";
}
- public CrawlEntry toBalancerEntry(String initiatorHash) {
+ public CrawlEntry toBalancerEntry(final String initiatorHash) {
return new CrawlEntry(
initiatorHash,
comp().url(),
@@ -465,12 +465,12 @@ public class indexURLReference {
public class Components {
private yacyURL url;
- private String dc_title, dc_creator, dc_subject, ETag;
+ private final String dc_title, dc_creator, dc_subject, ETag;
- public Components(String url, String urlhash, String title, String author, String tags, String ETag) {
+ public Components(final String url, final String urlhash, final String title, final String author, final String tags, final String ETag) {
try {
this.url = new yacyURL(url, urlhash);
- } catch (MalformedURLException e) {
+ } catch (final MalformedURLException e) {
this.url = null;
}
this.dc_title = title;
@@ -478,7 +478,7 @@ public class indexURLReference {
this.dc_subject = tags;
this.ETag = ETag;
}
- public Components(yacyURL url, String descr, String author, String tags, String ETag) {
+ public Components(final yacyURL url, final String descr, final String author, final String tags, final String ETag) {
this.url = url;
this.dc_title = descr;
this.dc_creator = author;
diff --git a/source/de/anomic/index/indexWord.java b/source/de/anomic/index/indexWord.java
index d74852818..d64224bfe 100644
--- a/source/de/anomic/index/indexWord.java
+++ b/source/de/anomic/index/indexWord.java
@@ -47,7 +47,7 @@ public class indexWord {
HashSet<Integer> phrases; // a set of handles to all phrases where this word appears
public kelondroBitfield flags; // the flag bits for each word
- public indexWord(int handle, int pip, int nop) {
+ public indexWord(final int handle, final int pip, final int nop) {
this.count = 1;
this.posInText = handle;
this.posInPhrase = pip;
@@ -64,7 +64,7 @@ public class indexWord {
return count;
}
- public void check(int i) {
+ public void check(final int i) {
phrases.add(new Integer(i));
}
@@ -76,25 +76,25 @@ public class indexWord {
// static methods
// create a word hash
- public static final String word2hash(String word) {
+ public static final String word2hash(final String word) {
return kelondroBase64Order.enhancedCoder.encode(serverCodings.encodeMD5Raw(word.toLowerCase())).substring(0, yacySeedDB.commonHashLength);
}
- public static final Set<String> words2hashSet(String[] words) {
- TreeSet<String> hashes = new TreeSet<String>(kelondroBase64Order.enhancedComparator);
+ public static final Set<String> words2hashSet(final String[] words) {
+ final TreeSet<String> hashes = new TreeSet<String>(kelondroBase64Order.enhancedComparator);
for (int i = 0; i < words.length; i++) hashes.add(word2hash(words[i]));
return hashes;
}
- public static final String words2hashString(String[] words) {
- StringBuffer sb = new StringBuffer();
+ public static final String words2hashString(final String[] words) {
+ final StringBuffer sb = new StringBuffer();
for (int i = 0; i < words.length; i++) sb.append(word2hash(words[i]));
return new String(sb);
}
- public static final TreeSet<String> words2hashes(Set<String> words) {
- Iterator<String> i = words.iterator();
- TreeSet<String> hashes = new TreeSet<String>(kelondroBase64Order.enhancedComparator);
+ public static final TreeSet<String> words2hashes(final Set<String> words) {
+ final Iterator<String> i = words.iterator();
+ final TreeSet<String> hashes = new TreeSet<String>(kelondroBase64Order.enhancedComparator);
while (i.hasNext()) hashes.add(word2hash(i.next()));
return hashes;
}
diff --git a/source/de/anomic/kelondro/kelondroAbstractIOChunks.java b/source/de/anomic/kelondro/kelondroAbstractIOChunks.java
index efadfd79d..c1a622da1 100644
--- a/source/de/anomic/kelondro/kelondroAbstractIOChunks.java
+++ b/source/de/anomic/kelondro/kelondroAbstractIOChunks.java
@@ -46,12 +46,12 @@ public abstract class kelondroAbstractIOChunks {
// derived methods:
- public synchronized void readFully(long pos, byte[] b, int off, int len) throws IOException {
- long handle = profile.startRead();
+ public synchronized void readFully(long pos, final byte[] b, int off, int len) throws IOException {
+ final long handle = profile.startRead();
if (len < 0) throw new IndexOutOfBoundsException("length is negative:" + len);
if (b.length < off + len) throw new IndexOutOfBoundsException("bounds do not fit: b.length=" + b.length + ", off=" + off + ", len=" + len);
while (len > 0) {
- int r = read(pos, b, off, len); // blocks until at least one byte is available
+ final int r = read(pos, b, off, len); // blocks until at least one byte is available
if (r < 0) throw new IOException("EOF"); // read exceeded EOF
if (r == 0) throw new IOException("readFully cannot read remaining " + len + " bytes"); // security exception to prevent endless loops
pos += r;
@@ -61,38 +61,38 @@ public abstract class kelondroAbstractIOChunks {
profile.stopRead(handle);
}
- public synchronized byte readByte(long pos) throws IOException {
- byte[] b = new byte[1];
+ public synchronized byte readByte(final long pos) throws IOException {
+ final byte[] b = new byte[1];
this.readFully(pos, b, 0, 1);
return b[0];
}
- public synchronized void writeByte(long pos, final int v) throws IOException {
- long handle = profile.startWrite();
+ public synchronized void writeByte(final long pos, final int v) throws IOException {
+ final long handle = profile.startWrite();
this.write(pos, new byte[]{(byte) (v & 0xFF)});
profile.stopWrite(handle);
}
- public synchronized short readShort(long pos) throws IOException {
- byte[] b = new byte[2];
+ public synchronized short readShort(final long pos) throws IOException {
+ final byte[] b = new byte[2];
this.readFully(pos, b, 0, 2);
return (short) (((b[0] & 0xFF) << 8) | ((b[1] & 0xFF) << 0));
}
- public synchronized void writeShort(long pos, final int v) throws IOException {
- long handle = profile.startWrite();
+ public synchronized void writeShort(final long pos, final int v) throws IOException {
+ final long handle = profile.startWrite();
this.write(pos, new byte[]{(byte) ((v >>> 8) & 0xFF), (byte) ((v >>> 0) & 0xFF)});
profile.stopWrite(handle);
}
- public synchronized int readInt(long pos) throws IOException {
- byte[] b = new byte[4];
+ public synchronized int readInt(final long pos) throws IOException {
+ final byte[] b = new byte[4];
this.readFully(pos, b, 0, 4);
return ((b[0] & 0xFF) << 24) | ((b[1] & 0xFF) << 16) | ((b[2] & 0xFF) << 8) | (b[3] & 0xFF);
}
- public synchronized void writeInt(long pos, final int v) throws IOException {
- long handle = profile.startWrite();
+ public synchronized void writeInt(final long pos, final int v) throws IOException {
+ final long handle = profile.startWrite();
this.write(pos, new byte[]{
(byte) ((v >>> 24) & 0xFF),
(byte) ((v >>> 16) & 0xFF),
@@ -102,14 +102,14 @@ public abstract class kelondroAbstractIOChunks {
profile.stopWrite(handle);
}
- public synchronized long readLong(long pos) throws IOException {
- byte[] b = new byte[8];
+ public synchronized long readLong(final long pos) throws IOException {
+ final byte[] b = new byte[8];
this.readFully(pos, b, 0, 8);
return (((long) b[0] & 0xFF) << 56) | (((long) b[1] & 0xFF) << 48) | (((long) b[2]) << 40) | (((long) b[3] & 0xFF) << 32) | (((long) b[4] & 0xFF) << 24) | (((long) b[5] & 0xFF) << 16) | (((long) b[6] & 0xFF) << 8) | ((long) b[7] & 0xFF);
}
- public synchronized void writeLong(long pos, final long v) throws IOException {
- long handle = profile.startWrite();
+ public synchronized void writeLong(final long pos, final long v) throws IOException {
+ final long handle = profile.startWrite();
this.write(pos, new byte[]{
(byte) ((v >>> 56) & 0xFF),
(byte) ((v >>> 48) & 0xFF),
@@ -123,8 +123,8 @@ public abstract class kelondroAbstractIOChunks {
profile.stopWrite(handle);
}
- public synchronized void write(long pos, final byte[] b) throws IOException {
- long handle = profile.startWrite();
+ public synchronized void write(final long pos, final byte[] b) throws IOException {
+ final long handle = profile.startWrite();
this.write(pos, b, 0, b.length);
profile.stopWrite(handle);
}
diff --git a/source/de/anomic/kelondro/kelondroAbstractOrder.java b/source/de/anomic/kelondro/kelondroAbstractOrder.java
index 4f66136ba..96055579e 100644
--- a/source/de/anomic/kelondro/kelondroAbstractOrder.java
+++ b/source/de/anomic/kelondro/kelondroAbstractOrder.java
@@ -38,23 +38,23 @@ public abstract class kelondroAbstractOrder<A> implements kelondroOrder<A> {
return zero;
}
- public void direction(boolean ascending) {
+ public void direction(final boolean ascending) {
asc = ascending;
}
- public long partition(A key, int forks) {
+ public long partition(final A key, final int forks) {
final long d = (Long.MAX_VALUE / forks) + ((Long.MAX_VALUE % forks) + 1) / forks;
return cardinal(key) / d;
}
- public void rotate(A newzero) {
+ public void rotate(final A newzero) {
this.zero = newzero;
}
- public boolean equals(kelondroOrder<A> otherOrder) {
+ public boolean equals(final kelondroOrder<A> otherOrder) {
if (otherOrder == null) return false;
- String thisSig = this.signature();
- String otherSig = otherOrder.signature();
+ final String thisSig = this.signature();
+ final String otherSig = otherOrder.signature();
if ((thisSig == null) || (otherSig == null)) return false;
return thisSig.equals(otherSig);
}
diff --git a/source/de/anomic/kelondro/kelondroAbstractRA.java b/source/de/anomic/kelondro/kelondroAbstractRA.java
index 0edbada7e..752a96042 100644
--- a/source/de/anomic/kelondro/kelondroAbstractRA.java
+++ b/source/de/anomic/kelondro/kelondroAbstractRA.java
@@ -63,11 +63,11 @@ abstract class kelondroAbstractRA implements kelondroRA {
abstract public void close() throws IOException;
// derived methods:
- public void readFully(byte[] b, int off, int len) throws IOException {
+ public void readFully(final byte[] b, int off, int len) throws IOException {
if (len < 0) throw new IndexOutOfBoundsException("length is negative:" + len);
if (b.length < off + len) throw new IndexOutOfBoundsException("bounds do not fit: b.length=" + b.length + ", off=" + off + ", len=" + len);
while (len > 0) {
- int r = read(b, off, len);
+ final int r = read(b, off, len);
if (r < 0) throw new IOException("EOF"); // read exceeded EOF
off += r;
len -= r;
@@ -75,8 +75,8 @@ abstract class kelondroAbstractRA implements kelondroRA {
}
public byte[] readFully() throws IOException {
- ByteArrayOutputStream dest = new ByteArrayOutputStream();
- byte[] buffer = new byte[1024];
+ final ByteArrayOutputStream dest = new ByteArrayOutputStream();
+ final byte[] buffer = new byte[1024];
int c, total = 0;
while ((c = read(buffer, 0, 1024)) > 0) {
@@ -142,7 +142,7 @@ abstract class kelondroAbstractRA implements kelondroRA {
private static final byte lf = 10;
public void writeLine(final String line) throws IOException {
- byte[] b = new byte[line.length() + 2];
+ final byte[] b = new byte[line.length() + 2];
System.arraycopy(line.getBytes(), 0, b, 0, line.length());
b[b.length - 2] = cr;
b[b.length - 1] = lf;
@@ -150,7 +150,7 @@ abstract class kelondroAbstractRA implements kelondroRA {
}
public void writeLine(final byte[] line) throws IOException {
- byte[] b = new byte[line.length + 2];
+ final byte[] b = new byte[line.length + 2];
System.arraycopy(line, 0, b, 0, line.length);
b[b.length - 2] = cr;
b[b.length - 1] = lf;
@@ -201,8 +201,8 @@ abstract class kelondroAbstractRA implements kelondroRA {
public HashMap<String, String> readMap() throws IOException {
this.seek(0);
- byte[] b = readFully();
- BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(b)));
+ final byte[] b = readFully();
+ final BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(b)));
final HashMap<String, String> map = new HashMap<String, String>();
String line;
int pos;
diff --git a/source/de/anomic/kelondro/kelondroAbstractRecords.java b/source/de/anomic/kelondro/kelondroAbstractRecords.java
index df6a25106..9143cf696 100644
--- a/source/de/anomic/kelondro/kelondroAbstractRecords.java
+++ b/source/de/anomic/kelondro/kelondroAbstractRecords.java
@@ -111,7 +111,7 @@ public abstract class kelondroAbstractRecords implements kelondroRecords {
protected int FREEC; // counter of free elements in list of free Nodes
protected kelondroHandle FREEH; // pointer to first element in list of free Nodes, empty = NUL
- protected usageControl(boolean init) throws IOException {
+ protected usageControl(final boolean init) throws IOException {
if (init) {
this.USEDC = 0;
this.FREEC = 0;
@@ -120,8 +120,8 @@ public abstract class kelondroAbstractRecords implements kelondroRecords {
readfree();
readused();
try {
- int rest = (int) ((entryFile.length() - POS_NODES) % recordsize);// == 0 : "rest = " + ((entryFile.length() - POS_NODES) % ((long) recordsize)) + ", USEDC = " + this.USEDC + ", FREEC = " + this.FREEC + ", recordsize = " + recordsize + ", file = " + filename;
- int calculated_used = (int) ((entryFile.length() - POS_NODES) / recordsize);
+ final int rest = (int) ((entryFile.length() - POS_NODES) % recordsize);// == 0 : "rest = " + ((entryFile.length() - POS_NODES) % ((long) recordsize)) + ", USEDC = " + this.USEDC + ", FREEC = " + this.FREEC + ", recordsize = " + recordsize + ", file = " + filename;
+ final int calculated_used = (int) ((entryFile.length() - POS_NODES) / recordsize);
if ((rest != 0) || (calculated_used != this.USEDC + this.FREEC)) {
theLogger.log(Level.WARNING, "USEDC inconsistency at startup: calculated_used = " + calculated_used + ", USEDC = " + this.USEDC + ", FREEC = " + this.FREEC + ", recordsize = " + recordsize + ", file = " + filename);
this.USEDC = calculated_used - this.FREEC;
@@ -131,13 +131,13 @@ public abstract class kelondroAbstractRecords implements kelondroRecords {
}
writeused(true);
}
- } catch (IOException e) {
+ } catch (final IOException e) {
assert false;
}
}
}
- synchronized void writeused(boolean finalwrite) throws IOException {
+ synchronized void writeused(final boolean finalwrite) throws IOException {
// we write only at close time, not in between. othervise, the read/write head
// needs to run up and own all the way between the beginning and the end of the
// file for each record. We check consistency beteen file size and
@@ -181,7 +181,7 @@ public abstract class kelondroAbstractRecords implements kelondroRecords {
return this.USEDC;
}
- protected synchronized void dispose(kelondroHandle h) throws IOException {
+ protected synchronized void dispose(final kelondroHandle h) throws IOException {
// delete element with handle h
// this element is then connected to the deleted-chain and can be
// re-used change counter
@@ -190,7 +190,7 @@ public abstract class kelondroAbstractRecords implements kelondroRecords {
//synchronized (USAGE) {
synchronized (entryFile) {
assert (h.index < USEDC + FREEC) : "USEDC = " + USEDC + ", FREEC = " + FREEC + ", h.index = " + h.index;
- long sp = seekpos(h);
+ final long sp = seekpos(h);
assert (sp <= entryFile.length() + ROW.objectsize) : h.index + "/" + sp + " exceeds file size " + entryFile.length();
USEDC--;
FREEC++;
@@ -216,7 +216,7 @@ public abstract class kelondroAbstractRecords implements kelondroRecords {
synchronized (entryFile) {
if (USAGE.FREEC == 0) {
// generate new entry
- int index = USAGE.allCount();
+ final int index = USAGE.allCount();
entryFile.write(seekpos(index) + overhead, chunk, 0, ROW.objectsize); // occupy space, othervise the USAGE computaton does not work
USAGE.USEDC++;
writeused(false);
@@ -236,7 +236,7 @@ public abstract class kelondroAbstractRecords implements kelondroRecords {
} else {
//System.out.println("*DEBUG* ALLOCATED DELETED INDEX " + index);
// check for valid seek position
- long seekp = seekpos(USAGE.FREEH);
+ final long seekp = seekpos(USAGE.FREEH);
if (seekp >= entryFile.length()) {
// this is a severe inconsistency. try to heal..
serverLog.logSevere("kelondroTray/" + filename, "new Handle: lost " + USAGE.FREEC + " marked nodes; seek position " + seekp + "/" + USAGE.FREEH.index + " out of file size " + entryFile.length() + "/" + ((entryFile.length() - POS_NODES) / recordsize));
@@ -259,7 +259,7 @@ public abstract class kelondroAbstractRecords implements kelondroRecords {
//}
}
- protected synchronized void allocateRecord(int index, byte[] bulkchunk, int offset) throws IOException {
+ protected synchronized void allocateRecord(final int index, byte[] bulkchunk, int offset) throws IOException {
// in case that the handle index was created outside this class,
// this method ensures that the USAGE counters are consistent with the
// new handle index
@@ -309,37 +309,37 @@ public abstract class kelondroAbstractRecords implements kelondroRecords {
private synchronized void checkConsistency() {
if ((debugmode) && (entryFile != null)) try { // in debug mode
- long efl = entryFile.length();
+ final long efl = entryFile.length();
assert ((efl - POS_NODES) % (recordsize)) == 0 : "rest = " + ((entryFile.length() - POS_NODES) % (recordsize)) + ", USEDC = " + this.USEDC + ", FREEC = " + this.FREEC + ", recordsize = " + recordsize + ", file = " + filename;
- long calculated_used = (efl - POS_NODES) / (recordsize);
+ final long calculated_used = (efl - POS_NODES) / (recordsize);
if (calculated_used != this.USEDC + this.FREEC) logFailure("INCONSISTENCY in USED computation: calculated_used = " + calculated_used + ", USEDC = " + this.USEDC + ", FREEC = " + this.FREEC + ", recordsize = " + recordsize + ", file = " + filename);
- } catch (IOException e) {
+ } catch (final IOException e) {
assert false;
}
}
}
- public static int staticsize(File file) {
+ public static int staticsize(final File file) {
if (!(file.exists())) return 0;
try {
- kelondroRA ra = new kelondroFileRA(file.getCanonicalPath());
- kelondroIOChunks entryFile = new kelondroRAIOChunks(ra, ra.name());
+ final kelondroRA ra = new kelondroFileRA(file.getCanonicalPath());
+ final kelondroIOChunks entryFile = new kelondroRAIOChunks(ra, ra.name());
- int used = entryFile.readInt(POS_USEDC); // works only if consistency with file size is given
+ final int used = entryFile.readInt(POS_USEDC); // works only if consistency with file size is given
entryFile.close();
ra.close();
return used;
- } catch (FileNotFoundException e) {
+ } catch (final FileNotFoundException e) {
return 0;
- } catch (IOException e) {
+ } catch (final IOException e) {
return 0;
}
}
- public kelondroAbstractRecords(File file, boolean useNodeCache,
- short ohbytec, short ohhandlec,
- kelondroRow rowdef, int FHandles, int txtProps, int txtPropWidth) throws IOException {
+ public kelondroAbstractRecords(final File file, final boolean useNodeCache,
+ final short ohbytec, final short ohhandlec,
+ final kelondroRow rowdef, final int FHandles, final int txtProps, final int txtPropWidth) throws IOException {
// opens an existing file or creates a new file
// file: the file that shall be created
// oha : overhead size array of four bytes: oha[0]=# of bytes, oha[1]=# of shorts, oha[2]=# of ints, oha[3]=# of longs,
@@ -356,21 +356,21 @@ public abstract class kelondroAbstractRecords implements kelondroRecords {
if (file.exists()) {
// opens an existing tree
this.filename = file.getCanonicalPath();
- kelondroRA raf = new kelondroFileRA(this.filename);
+ final kelondroRA raf = new kelondroFileRA(this.filename);
//kelondroRA raf = new kelondroBufferedRA(new kelondroFileRA(this.filename), 1024, 100);
//kelondroRA raf = new kelondroCachedRA(new kelondroFileRA(this.filename), 5000000, 1000);
//kelondroRA raf = new kelondroNIOFileRA(this.filename, (file.length() < 4000000), 10000);
initExistingFile(raf, useNodeCache);
} else {
this.filename = file.getCanonicalPath();
- kelondroRA raf = new kelondroFileRA(this.filename);
+ final kelondroRA raf = new kelondroFileRA(this.filename);
// kelondroRA raf = new kelondroBufferedRA(new kelondroFileRA(this.filename), 1024, 100);
// kelondroRA raf = new kelondroNIOFileRA(this.filename, false, 10000);
initNewFile(raf, FHandles, txtProps);
}
assignRowdef(rowdef);
if (fileExisted) {
- kelondroByteOrder oldOrder = readOrderType();
+ final kelondroByteOrder oldOrder = readOrderType();
if ((oldOrder != null) && (!(oldOrder.equals(rowdef.objectOrder)))) {
writeOrderType(); // write new order type
//throw new IOException("wrong object order upon initialization. new order is " + rowdef.objectOrder.toString() + ", old order was " + oldOrder.toString());
@@ -381,10 +381,10 @@ public abstract class kelondroAbstractRecords implements kelondroRecords {
}
}
- public kelondroAbstractRecords(kelondroRA ra, String filename, boolean useCache,
- short ohbytec, short ohhandlec,
- kelondroRow rowdef, int FHandles, int txtProps, int txtPropWidth,
- boolean exitOnFail) {
+ public kelondroAbstractRecords(final kelondroRA ra, final String filename, final boolean useCache,
+ final short ohbytec, final short ohhandlec,
+ final kelondroRow rowdef, final int FHandles, final int txtProps, final int txtPropWidth,
+ final boolean exitOnFail) {
// this always creates a new file
this.fileExisted = false;
this.filename = filename;
@@ -395,7 +395,7 @@ public abstract class kelondroAbstractRecords implements kelondroRecords {
try {
initNewFile(ra, FHandles, txtProps);
- } catch (IOException e) {
+ } catch (final IOException e) {
logFailure("cannot create / " + e.getMessage());
if (exitOnFail) System.exit(-1);
}
@@ -405,7 +405,7 @@ public abstract class kelondroAbstractRecords implements kelondroRecords {
public void clear() throws IOException {
kelondroRA ra = this.entryFile.getRA();
- File f = ra.file();
+ final File f = ra.file();
assert f != null;
this.entryFile.close();
f.delete();
@@ -413,7 +413,7 @@ public abstract class kelondroAbstractRecords implements kelondroRecords {
initNewFile(ra, this.HANDLES.length, this.TXTPROPS.length);
}
- private void initNewFile(kelondroRA ra, int FHandles, int txtProps) throws IOException {
+ private void initNewFile(final kelondroRA ra, final int FHandles, final int txtProps) throws IOException {
// create new Chunked IO
this.entryFile = new kelondroRAIOChunks(ra, ra.name());
@@ -464,7 +464,7 @@ public abstract class kelondroAbstractRecords implements kelondroRecords {
entryFile.writeInt(POS_HANDLES + 4 * i, kelondroHandle.NUL);
HANDLES[i] = new kelondroHandle(kelondroHandle.NUL);
}
- byte[] ea = new byte[TXTPROPW];
+ final byte[] ea = new byte[TXTPROPW];
for (int j = 0; j < TXTPROPW; j++) ea[j] = 0;
for (int i = 0; i < this.TXTPROPS.length; i++) {
entryFile.write(POS_TXTPROPS + TXTPROPW * i, ea);
@@ -474,12 +474,12 @@ public abstract class kelondroAbstractRecords implements kelondroRecords {
}
private static final byte[] fillSpaceChunk(int size) {
- byte[] chunk = new byte[size];
+ final byte[] chunk = new byte[size];
while (--size >= 0) chunk[size] = (byte) 0xff;
return chunk;
}
- public void setDescription(byte[] description) throws IOException {
+ public void setDescription(final byte[] description) throws IOException {
if (description.length > LEN_DESCR)
entryFile.write(POS_DESCR, description, 0, LEN_DESCR);
else
@@ -487,44 +487,44 @@ public abstract class kelondroAbstractRecords implements kelondroRecords {
}
public byte[] getDescription() throws IOException {
- byte[] b = new byte[LEN_DESCR];
+ final byte[] b = new byte[LEN_DESCR];
entryFile.readFully(POS_DESCR, b, 0, LEN_DESCR);
return b;
}
- public void setLogger(Logger newLogger) {
+ public void setLogger(final Logger newLogger) {
this.theLogger = newLogger;
}
- public void logWarning(String message) {
+ public void logWarning(final String message) {
if (this.theLogger == null)
System.err.println("KELONDRO WARNING " + this.filename + ": " + message);
else
this.theLogger.warning("KELONDRO WARNING " + this.filename + ": " + message);
}
- public void logFailure(String message) {
+ public void logFailure(final String message) {
if (this.theLogger == null)
System.err.println("KELONDRO FAILURE " + this.filename + ": " + message);
else
this.theLogger.severe("KELONDRO FAILURE " + this.filename + ": " + message);
}
- public void logFine(String message) {
+ public void logFine(final String message) {
if (this.theLogger == null)
System.out.println("KELONDRO DEBUG " + this.filename + ": " + message);
else
this.theLogger.fine("KELONDRO DEBUG " + this.filename + ": " + message);
}
- public kelondroAbstractRecords(kelondroRA ra, String filename, boolean useNodeCache) throws IOException{
+ public kelondroAbstractRecords(final kelondroRA ra, final String filename, final boolean useNodeCache) throws IOException{
this.fileExisted = false;
this.filename = filename;
initExistingFile(ra, useNodeCache);
readOrderType();
}
- private void initExistingFile(kelondroRA ra, boolean useBuffer) throws IOException {
+ private void initExistingFile(final kelondroRA ra, final boolean useBuffer) throws IOException {
// read from Chunked IO
if (useBuffer) {
this.entryFile = new kelondroBufferedIOChunks(ra, ra.name(), 0, 30000 + random.nextLong() % 30000);
@@ -538,7 +538,7 @@ public abstract class kelondroAbstractRecords implements kelondroRecords {
this.OHBYTEC = entryFile.readShort(POS_OHBYTEC);
this.OHHANDLEC = entryFile.readShort(POS_OHHANDLEC);
- kelondroColumn[] COLDEFS = new kelondroColumn[entryFile.readShort(POS_COLUMNS)];
+ final kelondroColumn[] COLDEFS = new kelondroColumn[entryFile.readShort(POS_COLUMNS)];
this.HANDLES = new kelondroHandle[entryFile.readInt(POS_INTPROPC)];
this.TXTPROPS = new byte[entryFile.readInt(POS_TXTPROPC)][];
this.TXTPROPW = entryFile.readInt(POS_TXTPROPW);
@@ -578,15 +578,15 @@ public abstract class kelondroAbstractRecords implements kelondroRecords {
private void writeOrderType() {
try {
setDescription((this.ROW.objectOrder == null) ? "__".getBytes() : this.ROW.objectOrder.signature().getBytes());
- } catch (IOException e) {}
+ } catch (final IOException e) {}
}
private kelondroByteOrder readOrderType() {
try {
- byte[] d = getDescription();
- String s = new String(d).substring(0, 2);
+ final byte[] d = getDescription();
+ final String s = new String(d).substring(0, 2);
return kelondroNaturalOrder.orderBySignature(s);
- } catch (IOException e) {
+ } catch (final IOException e) {
return null;
}
}
@@ -595,7 +595,7 @@ public abstract class kelondroAbstractRecords implements kelondroRecords {
return filename;
}
- public synchronized final byte[] bulkRead(int start, int end) throws IOException {
+ public synchronized final byte[] bulkRead(final int start, final int end) throws IOException {
// a bulk read simply reads a piece of memory from the record file
// this makes only sense if there are no overhead bytes or pointer
// the end value is OUTSIDE the record interval
@@ -603,17 +603,17 @@ public abstract class kelondroAbstractRecords implements kelondroRecords {
assert OHHANDLEC == 0;
assert start >= 0;
assert end <= USAGE.allCount();
- byte[] bulk = new byte[(end - start) * recordsize];
- long bulkstart = POS_NODES + ((long) recordsize * (long) start);
+ final byte[] bulk = new byte[(end - start) * recordsize];
+ final long bulkstart = POS_NODES + ((long) recordsize * (long) start);
entryFile.readFully(bulkstart, bulk, 0, bulk.length);
return bulk;
}
- protected synchronized void deleteNode(kelondroHandle handle) throws IOException {
+ protected synchronized void deleteNode(final kelondroHandle handle) throws IOException {
USAGE.dispose(handle);
}
- protected void printChunk(kelondroRow.Entry chunk) {
+ protected void printChunk(final kelondroRow.Entry chunk) {
for (int j = 0; j < chunk.columns(); j++)
System.out.print(new String(chunk.getColBytes(j)) + ", ");
}
@@ -622,7 +622,7 @@ public abstract class kelondroAbstractRecords implements kelondroRecords {
return this.ROW;
}
- private final void assignRowdef(kelondroRow rowdef) {
+ private final void assignRowdef(final kelondroRow rowdef) {
// overwrites a given rowdef
// the new rowdef must be compatible
/*
@@ -643,12 +643,12 @@ public abstract class kelondroAbstractRecords implements kelondroRecords {
this.ROW = rowdef;
}
- protected final long seekpos(kelondroHandle handle) {
+ protected final long seekpos(final kelondroHandle handle) {
assert (handle.index >= 0): "handle index too low: " + handle.index;
return POS_NODES + ((long) recordsize * (long) handle.index);
}
- protected final long seekpos(int index) {
+ protected final long seekpos(final int index) {
assert (index >= 0): "handle index too low: " + index;
return POS_NODES + ((long) recordsize * index);
}
@@ -658,20 +658,20 @@ public abstract class kelondroAbstractRecords implements kelondroRecords {
return this.HANDLES.length;
}
- protected final void setHandle(int pos, kelondroHandle handle) throws IOException {
+ protected final void setHandle(final int pos, kelondroHandle handle) throws IOException {
if (pos >= HANDLES.length) throw new IllegalArgumentException("setHandle: handle array exceeded");
if (handle == null) handle = new kelondroHandle(kelondroHandle.NUL);
HANDLES[pos] = handle;
entryFile.writeInt(POS_HANDLES + 4 * pos, handle.index);
}
- protected final kelondroHandle getHandle(int pos) {
+ protected final kelondroHandle getHandle(final int pos) {
if (pos >= HANDLES.length) throw new IllegalArgumentException("getHandle: handle array exceeded");
return (HANDLES[pos].index == kelondroHandle.NUL) ? null : HANDLES[pos];
}
// custom texts
- public final void setText(int pos, byte[] text) throws IOException {
+ public final void setText(final int pos, byte[] text) throws IOException {
if (pos >= TXTPROPS.length) throw new IllegalArgumentException("setText: text array exceeded");
if (text.length > TXTPROPW) throw new IllegalArgumentException("setText: text lemgth exceeded");
if (text == null) text = new byte[0];
@@ -679,7 +679,7 @@ public abstract class kelondroAbstractRecords implements kelondroRecords {
entryFile.write(POS_TXTPROPS + TXTPROPW * pos, text);
}
- public final byte[] getText(int pos) {
+ public final byte[] getText(final int pos) {
if (pos >= TXTPROPS.length) throw new IllegalArgumentException("getText: text array exceeded");
return TXTPROPS[pos];
}
@@ -698,12 +698,12 @@ public abstract class kelondroAbstractRecords implements kelondroRecords {
return USAGE.FREEC;
}
- protected final Set<kelondroHandle> deletedHandles(long maxTime) throws kelondroException, IOException {
+ protected final Set<kelondroHandle> deletedHandles(final long maxTime) throws kelondroException, IOException {
// initialize set with deleted nodes; the set contains Handle-Objects
// this may last only the given maxInitTime
// if the initTime is exceeded, the method throws an kelondroException
- TreeSet<kelondroHandle> markedDeleted = new TreeSet<kelondroHandle>();
- long timeLimit = (maxTime < 0) ? Long.MAX_VALUE : System.currentTimeMillis() + maxTime;
+ final TreeSet<kelondroHandle> markedDeleted = new TreeSet<kelondroHandle>();
+ final long timeLimit = (maxTime < 0) ? Long.MAX_VALUE : System.currentTimeMillis() + maxTime;
long seekp;
synchronized (USAGE) {
if (USAGE.FREEC != 0) {
@@ -752,7 +752,7 @@ public abstract class kelondroAbstractRecords implements kelondroRecords {
USAGE.writeused(true);
this.entryFile.close();
theLogger.fine("file '" + this.filename + "' closed.");
- } catch (IOException e) {
+ } catch (final IOException e) {
theLogger.severe("file '" + this.filename + "': failed to close.");
e.printStackTrace();
}
@@ -764,7 +764,7 @@ public abstract class kelondroAbstractRecords implements kelondroRecords {
this.entryFile = null;
}
- protected final static String[] line2args(String line) {
+ protected final static String[] line2args(final String line) {
// parse the command line
if ((line == null) || (line.length() == 0)) return null;
String args[];
@@ -778,7 +778,7 @@ public abstract class kelondroAbstractRecords implements kelondroRecords {
return args;
}
- protected final static boolean equals(byte[] a, byte[] b) {
+ protected final static boolean equals(final byte[] a, final byte[] b) {
if (a == b) return true;
if ((a == null) || (b == null)) return false;
if (a.length != b.length) return false;
@@ -786,21 +786,21 @@ public abstract class kelondroAbstractRecords implements kelondroRecords {
return true;
}
- public final static void NUL2bytes(byte[] b, int offset) {
+ public final static void NUL2bytes(final byte[] b, final int offset) {
b[offset ] = (byte) (0XFF & (kelondroHandle.NUL >> 24));
b[offset + 1] = (byte) (0XFF & (kelondroHandle.NUL >> 16));
b[offset + 2] = (byte) (0XFF & (kelondroHandle.NUL >> 8));
b[offset + 3] = (byte) (0XFF & kelondroHandle.NUL);
}
- public final static void int2bytes(long i, byte[] b, int offset) {
+ public final static void int2bytes(final long i, final byte[] b, final int offset) {
b[offset ] = (byte) (0XFF & (i >> 24));
b[offset + 1] = (byte) (0XFF & (i >> 16));
b[offset + 2] = (byte) (0XFF & (i >> 8));
b[offset + 3] = (byte) (0XFF & i);
}
- public final static int bytes2int(byte[] b, int offset) {
+ public final static int bytes2int(final byte[] b, final int offset) {
return (
((b[offset ] & 0xff) << 24) |
((b[offset + 1] & 0xff) << 16) |
@@ -845,8 +845,8 @@ public abstract class kelondroAbstractRecords implements kelondroRecords {
System.out.println(" Recordsize : " + this.recordsize + " bytes");
System.out.println("--");
System.out.println("DELETED HANDLES");
- Set<kelondroHandle> dh = deletedHandles(-1);
- Iterator<kelondroHandle> dhi = dh.iterator();
+ final Set<kelondroHandle> dh = deletedHandles(-1);
+ final Iterator<kelondroHandle> dhi = dh.iterator();
kelondroHandle h;
while (dhi.hasNext()) {
h = dhi.next();
@@ -860,7 +860,7 @@ public abstract class kelondroAbstractRecords implements kelondroRecords {
}
- public final Iterator<EntryIndex> contentRows(long maxInitTime) throws kelondroException {
+ public final Iterator<EntryIndex> contentRows(final long maxInitTime) throws kelondroException {
return new contentRowIterator(maxInitTime);
}
@@ -868,10 +868,10 @@ public abstract class kelondroAbstractRecords implements kelondroRecords {
// iterator that iterates all kelondroRow.Entry-objects in the file
// all records that are marked as deleted are omitted
- private Iterator<kelondroNode> nodeIterator;
+ private final Iterator<kelondroNode> nodeIterator;
private EntryIndex nextEntry;
- public contentRowIterator(long maxInitTime) {
+ public contentRowIterator(final long maxInitTime) {
nodeIterator = contentNodes(maxInitTime);
if (nodeIterator.hasNext()) nextEntry = next0(); else nextEntry = null;
}
@@ -885,15 +885,15 @@ public abstract class kelondroAbstractRecords implements kelondroRecords {
return null;
}
try {
- kelondroNode n = nodeIterator.next();
+ final kelondroNode n = nodeIterator.next();
return row().newEntryIndex(n.getValueRow(), n.handle().index);
- } catch (IOException e) {
+ } catch (final IOException e) {
throw new kelondroException(filename, e.getMessage());
}
}
public EntryIndex next() {
- EntryIndex ni = nextEntry;
+ final EntryIndex ni = nextEntry;
byte[] b;
nextEntry = null;
while (nodeIterator.hasNext()) {
@@ -911,11 +911,11 @@ public abstract class kelondroAbstractRecords implements kelondroRecords {
}
- protected final Iterator<kelondroNode> contentNodes(long maxInitTime) throws kelondroException {
+ protected final Iterator<kelondroNode> contentNodes(final long maxInitTime) throws kelondroException {
// returns an iterator of Node-objects that are not marked as 'deleted'
try {
return new contentNodeIterator(maxInitTime);
- } catch (IOException e) {
+ } catch (final IOException e) {
return new HashSet<kelondroNode>().iterator();
}
}
@@ -925,15 +925,15 @@ public abstract class kelondroAbstractRecords implements kelondroRecords {
// all records that are marked as deleted are ommitted
// this is probably also the fastest way to iterate all objects
- private Set<kelondroHandle> markedDeleted;
- private kelondroHandle pos;
- private byte[] bulk;
- private int bulksize;
+ private final Set<kelondroHandle> markedDeleted;
+ private final kelondroHandle pos;
+ private final byte[] bulk;
+ private final int bulksize;
private int bulkstart; // the offset of the bulk array to the node position
- private boolean fullyMarked;
+ private final boolean fullyMarked;
private kelondroNode next;
- public contentNodeIterator(long maxInitTime) throws IOException, kelondroException {
+ public contentNodeIterator(final long maxInitTime) throws IOException, kelondroException {
// initialize markedDeleted set of deleted Handles
markedDeleted = deletedHandles(maxInitTime);
fullyMarked = (maxInitTime < 0);
@@ -950,7 +950,7 @@ public abstract class kelondroAbstractRecords implements kelondroRecords {
}
public kelondroNode next() {
- kelondroNode n = next;
+ final kelondroNode n = next;
next = next0();
return n;
}
@@ -969,11 +969,11 @@ public abstract class kelondroAbstractRecords implements kelondroRecords {
kelondroNode nn;
try {
nn = next00();
- } catch (IOException e) {
+ } catch (final IOException e) {
serverLog.logSevere("kelondroCachedRecords", filename + " failed with " + e.getMessage(), e);
return null;
}
- byte[] key = nn.getKey();
+ final byte[] key = nn.getKey();
if ((key == null) ||
((key.length == 1) && (key[0] == (byte) 0x80)) || // the NUL pointer ('lost' chain terminator)
(key.length < 3) ||
@@ -982,7 +982,7 @@ public abstract class kelondroAbstractRecords implements kelondroRecords {
((key.length > 0) && (key[0] == 0)) // a 'lost' pointer within a deleted-chain
) {
// this is a deleted node; probably not commited with dispose
- if (fullyMarked) try {USAGE.dispose(nn.handle());} catch (IOException e) {} // mark this now as deleted
+ if (fullyMarked) try {USAGE.dispose(nn.handle());} catch (final IOException e) {} // mark this now as deleted
continue;
}
return nn;
@@ -994,7 +994,7 @@ public abstract class kelondroAbstractRecords implements kelondroRecords {
// see if the next record is in the bulk, and if not re-fill the bulk
if (pos.index >= (bulkstart + bulksize)) {
bulkstart = pos.index;
- int maxlength = Math.min(USAGE.allCount() - bulkstart, bulksize);
+ final int maxlength = Math.min(USAGE.allCount() - bulkstart, bulksize);
if (((POS_NODES) + ((long) bulkstart) * ((long) recordsize)) < 0)
serverLog.logSevere("kelondroCachedRecords", "DEBUG: negative offset. POS_NODES = " + POS_NODES + ", bulkstart = " + bulkstart + ", recordsize = " + recordsize);
if ((maxlength * recordsize) < 0)
@@ -1005,7 +1005,7 @@ public abstract class kelondroAbstractRecords implements kelondroRecords {
POS_NODES = 302, bulkstart = 820, recordsize = 2621466
POS_NODES = 302, bulkstart = 13106, recordsize = 163866 */
// read node from bulk
- kelondroNode n = newNode(new kelondroHandle(pos.index), bulk, (pos.index - bulkstart) * recordsize);
+ final kelondroNode n = newNode(new kelondroHandle(pos.index), bulk, (pos.index - bulkstart) * recordsize);
pos.index++;
while ((markedDeleted.contains(pos)) && (pos.index < USAGE.allCount())) pos.index++;
return n;
@@ -1017,11 +1017,11 @@ public abstract class kelondroAbstractRecords implements kelondroRecords {
}
- public static byte[] trimCopy(byte[] a, int offset, int length) {
+ public static byte[] trimCopy(final byte[] a, final int offset, int length) {
if (length > a.length - offset) length = a.length - offset;
while ((length > 0) && (a[offset + length - 1] == 0)) length--;
if (length == 0) return null;
- byte[] b = new byte[length];
+ final byte[] b = new byte[length];
System.arraycopy(a, offset, b, 0, length);
return b;
}
diff --git a/source/de/anomic/kelondro/kelondroAttrSeq.java b/source/de/anomic/kelondro/kelondroAttrSeq.java
index 0b78a6cdf..a36b6d8e3 100644
--- a/source/de/anomic/kelondro/kelondroAttrSeq.java
+++ b/source/de/anomic/kelondro/kelondroAttrSeq.java
@@ -49,8 +49,8 @@ import de.anomic.server.serverMemory;
public class kelondroAttrSeq {
// class objects
- private File file;
- private Map<String, Object> entries; // value may be of type String or of type Entry
+ private final File file;
+ private final Map<String, Object> entries; // value may be of type String or of type Entry
protected Structure structure;
private String name;
private long created;
@@ -58,7 +58,7 @@ public class kelondroAttrSeq {
// optional logger
protected Logger theLogger = null;
- public kelondroAttrSeq(File file, boolean tree) throws IOException {
+ public kelondroAttrSeq(final File file, final boolean tree) throws IOException {
this.file = file;
this.structure = null;
this.created = -1;
@@ -67,7 +67,7 @@ public class kelondroAttrSeq {
readAttrFile(file);
}
- public kelondroAttrSeq(String name, String struct, boolean tree) {
+ public kelondroAttrSeq(final String name, final String struct, final boolean tree) {
this.file = null;
this.structure = new Structure(struct);
this.created = System.currentTimeMillis();
@@ -75,25 +75,25 @@ public class kelondroAttrSeq {
this.entries = (tree) ? (Map<String, Object>) new TreeMap<String, Object>() : (Map<String, Object>) new HashMap<String, Object>();
}
- public void setLogger(Logger newLogger) {
+ public void setLogger(final Logger newLogger) {
this.theLogger = newLogger;
}
- public void logInfo(String message) {
+ public void logInfo(final String message) {
if (this.theLogger == null)
System.err.println("ATTRSEQ INFO for file " + this.file + ": " + message);
else
this.theLogger.info("ATTRSEQ INFO for file " + this.file + ": " + message);
}
- public void logWarning(String message) {
+ public void logWarning(final String message) {
if (this.theLogger == null)
System.err.println("ATTRSEQ WARNING for file " + this.file + ": " + message);
else
this.theLogger.warning("ATTRSEQ WARNING for file " + this.file + ": " + message);
}
- private void readAttrFile(File loadfile) throws IOException {
+ private void readAttrFile(final File loadfile) throws IOException {
BufferedReader br = null;
int p;
if (loadfile.toString().endsWith(".gz")) {
@@ -162,14 +162,14 @@ public class kelondroAttrSeq {
return this.created;
}
- public void toFile(File out) throws IOException {
+ public void toFile(final File out) throws IOException {
// generate header
- StringBuffer sb = new StringBuffer(2000);
+ final StringBuffer sb = new StringBuffer(2000);
sb.append("# Name=" + this.name); sb.append((char) 13); sb.append((char) 10);
sb.append("# Created=" + this.created); sb.append((char) 13); sb.append((char) 10);
sb.append("# Structure=" + this.structure.toString()); sb.append((char) 13); sb.append((char) 10);
sb.append("# ---"); sb.append((char) 13); sb.append((char) 10);
- Iterator<Map.Entry<String, Object>> i = entries.entrySet().iterator();
+ final Iterator<Map.Entry<String, Object>> i = entries.entrySet().iterator();
Map.Entry<String, Object> entry;
String k;
Object v;
@@ -193,11 +193,11 @@ public class kelondroAttrSeq {
return entries.keySet().iterator();
}
- public Entry newEntry(String pivot, boolean tree) {
+ public Entry newEntry(final String pivot, final boolean tree) {
return new Entry(pivot, new HashMap<String, Long>(), (tree) ? (Set<String>) new TreeSet<String>() : (Set<String>) new HashSet<String>());
}
- public Entry newEntry(String pivot, HashMap<String, Long> props, Set<String> seq) {
+ public Entry newEntry(final String pivot, final HashMap<String, Long> props, final Set<String> seq) {
return new Entry(pivot, props, seq);
}
@@ -207,27 +207,27 @@ public class kelondroAttrSeq {
}
*/
- public void putEntry(Entry entry) {
+ public void putEntry(final Entry entry) {
if (shortmem())
entries.put(entry.pivot, entry.toString());
else
entries.put(entry.pivot, entry);
}
- public void putEntrySmall(Entry entry) {
+ public void putEntrySmall(final Entry entry) {
entries.put(entry.pivot, entry.toString());
}
- public Entry getEntry(String pivot) {
- Object e = entries.get(pivot);
+ public Entry getEntry(final String pivot) {
+ final Object e = entries.get(pivot);
if (e == null) return null;
if (e instanceof String) return new Entry(pivot, (String) e, false);
if (e instanceof Entry) return (Entry) e;
return null;
}
- public Entry removeEntry(String pivot) {
- Object e = entries.remove(pivot);
+ public Entry removeEntry(final String pivot) {
+ final Object e = entries.remove(pivot);
if (e == null) return null;
if (e instanceof String) return new Entry(pivot, (String) e, false);
if (e instanceof Entry) return (Entry) e;
@@ -252,7 +252,7 @@ public class kelondroAttrSeq {
// parse pivot definition:
int p = structure.indexOf(",'='");
if (p < 0) return;
- String pivot = structure.substring(0, p);
+ final String pivot = structure.substring(0, p);
structure = structure.substring(p + 5);
kelondroColumn a = new kelondroColumn(pivot);
pivot_name = a.nickname;
@@ -262,7 +262,7 @@ public class kelondroAttrSeq {
p = structure.indexOf(",'|'");
if (p < 0) return;
ArrayList<kelondroColumn> l = new ArrayList<kelondroColumn>();
- String attr = structure.substring(0, p);
+ final String attr = structure.substring(0, p);
String seqs = structure.substring(p + 5);
StringTokenizer st = new StringTokenizer(attr, ",");
while (st.hasMoreTokens()) {
@@ -302,7 +302,7 @@ public class kelondroAttrSeq {
}
// generate rowdef for seq row definition
- StringBuffer rowdef = new StringBuffer();
+ final StringBuffer rowdef = new StringBuffer();
rowdef.append("byte[] ");
rowdef.append(seq_names[0]);
rowdef.append('-');
@@ -318,7 +318,7 @@ public class kelondroAttrSeq {
}
public String toString() {
- StringBuffer sb = new StringBuffer(100);
+ final StringBuffer sb = new StringBuffer(100);
sb.append('<'); sb.append(pivot_name); sb.append('-'); sb.append(Integer.toString(pivot_len)); sb.append(">,'=',");
if (prop_names.length > 0) {
for (int i = 0; i < prop_names.length; i++) {
@@ -340,13 +340,13 @@ public class kelondroAttrSeq {
HashMap<String, Long> attrs;
Set<String> seq;
- public Entry(String pivot, HashMap<String, Long> attrs, Set<String> seq) {
+ public Entry(final String pivot, final HashMap<String, Long> attrs, final Set<String> seq) {
this.pivot = pivot;
this.attrs = attrs;
this.seq = seq;
}
- public Entry(String pivot, String attrseq, boolean tree) {
+ public Entry(final String pivot, final String attrseq, final boolean tree) {
this.pivot = pivot;
attrs = new HashMap<String, Long>();
seq = (tree) ? (Set<String>) new TreeSet<String>() : (Set<String>) new HashSet<String>();
@@ -372,13 +372,13 @@ public class kelondroAttrSeq {
return attrs;
}
- public long getAttr(String key, long dflt) {
- Long i = attrs.get(key);
+ public long getAttr(final String key, final long dflt) {
+ final Long i = attrs.get(key);
if (i == null) return dflt;
return i.longValue();
}
- public void setAttr(String key, long attr) {
+ public void setAttr(final String key, final long attr) {
attrs.put(key, new Long(attr));
}
@@ -387,32 +387,32 @@ public class kelondroAttrSeq {
}
public kelondroRowCollection getSeqCollection() {
- kelondroRowCollection collection = new kelondroRowCollection(structure.seqrow, seq.size());
- Iterator<String> i = seq.iterator();
+ final kelondroRowCollection collection = new kelondroRowCollection(structure.seqrow, seq.size());
+ final Iterator<String> i = seq.iterator();
while (i.hasNext()) {
collection.addUnique(structure.seqrow.newEntry(i.next().getBytes()));
}
return collection;
}
- public void setSeq(Set<String> seq) {
+ public void setSeq(final Set<String> seq) {
this.seq = seq;
}
- public void addSeq(String s/*, long[] seqattrs*/) {
+ public void addSeq(final String s/*, long[] seqattrs*/) {
this.seq.add(s/*, seqattrs*/);
}
public String toString() {
// creates only the attribute field and the sequence, not the pivot
- StringBuffer sb = new StringBuffer(100 + structure.seq_len[0] * seq.size());
+ final StringBuffer sb = new StringBuffer(100 + structure.seq_len[0] * seq.size());
Long val;
for (int i = 0; i < structure.prop_names.length; i++) {
val = attrs.get(structure.prop_names[i]);
sb.append(kelondroBase64Order.enhancedCoder.encodeLongSmart((val == null) ? 0 : val.longValue(), structure.prop_len[i]));
}
sb.append('|');
- Iterator<String> q = seq.iterator();
+ final Iterator<String> q = seq.iterator();
//long[] seqattrs;
while (q.hasNext()) {
sb.append(q.next());
@@ -436,24 +436,24 @@ public class kelondroAttrSeq {
return shortmemstate;
}
- public static void transcode(File from_file, File to_file) throws IOException {
- kelondroAttrSeq crp = new kelondroAttrSeq(from_file, true);
+ public static void transcode(final File from_file, final File to_file) throws IOException {
+ final kelondroAttrSeq crp = new kelondroAttrSeq(from_file, true);
//crp.toFile(new File(args[1]));
- kelondroAttrSeq cro = new kelondroAttrSeq(crp.name + "/Transcoded from " + crp.file.getName(), crp.structure.toString(), true);
- Iterator<String> i = crp.entries.keySet().iterator();
+ final kelondroAttrSeq cro = new kelondroAttrSeq(crp.name + "/Transcoded from " + crp.file.getName(), crp.structure.toString(), true);
+ final Iterator<String> i = crp.entries.keySet().iterator();
while (i.hasNext()) {
cro.putEntry(crp.getEntry(i.next()));
}
cro.toFile(to_file);
}
- public static void main(String[] args) {
+ public static void main(final String[] args) {
// java -classpath source de.anomic.kelondro.kelondroPropFile -transcode DATA/RANKING/GLOBAL/CRG-test-unsorted-original.cr DATA/RANKING/GLOBAL/CRG-test-generated.cr
try {
if ((args.length == 3) && (args[0].equals("-transcode"))) {
transcode(new File(args[1]), new File(args[2]));
}
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
}
diff --git a/source/de/anomic/kelondro/kelondroBLOBHeap.java b/source/de/anomic/kelondro/kelondroBLOBHeap.java
index 02845f17d..9907871cd 100755
--- a/source/de/anomic/kelondro/kelondroBLOBHeap.java
+++ b/source/de/anomic/kelondro/kelondroBLOBHeap.java
@@ -39,14 +39,14 @@ public final class kelondroBLOBHeap implements kelondroBLOB {
private kelondroBytesLongMap index; // key/seek relation for used records
private ArrayList<gap> free; // list of {size, seek} pairs denoting space and position of free records
- private File heapFile; // the file of the heap
- private kelondroByteOrder ordering; // the ordering on keys
+ private final File heapFile; // the file of the heap
+ private final kelondroByteOrder ordering; // the ordering on keys
private RandomAccessFile file; // a random access to the file
public class gap {
public long seek;
public int size;
- public gap(long seek, int size) {
+ public gap(final long seek, final int size) {
this.seek = seek;
this.size = size;
}
@@ -82,14 +82,14 @@ public final class kelondroBLOBHeap implements kelondroBLOB {
* @param ordering
* @throws IOException
*/
- public kelondroBLOBHeap(File heapFile, int keylength, kelondroByteOrder ordering) throws IOException {
+ public kelondroBLOBHeap(final File heapFile, final int keylength, final kelondroByteOrder ordering) throws IOException {
this.ordering = ordering;
this.heapFile = heapFile;
this.index = new kelondroBytesLongMap(keylength, this.ordering, 0);
this.free = new ArrayList<gap>();
this.file = new RandomAccessFile(heapFile, "rw");
- byte[] key = new byte[keylength];
+ final byte[] key = new byte[keylength];
int reclen;
long seek = 0;
@@ -111,7 +111,7 @@ public final class kelondroBLOBHeap implements kelondroBLOB {
// read key
file.readFully(key);
- } catch (IOException e) {
+ } catch (final IOException e) {
// EOF reached
break loop; // terminate loop
}
@@ -128,7 +128,7 @@ public final class kelondroBLOBHeap implements kelondroBLOB {
} else {
serverLog.logWarning("kelondroBLOBHeap", "BLOB " + heapFile.getName() + ": skiped not wellformed key " + new String(key) + " at seek pos " + seek);
}
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
break loop;
}
@@ -141,7 +141,7 @@ public final class kelondroBLOBHeap implements kelondroBLOB {
if (this.free.size() > 1) {
int merged = 0;
gap lastFree, nextFree;
- Iterator<gap> i = this.free.iterator();
+ final Iterator<gap> i = this.free.iterator();
lastFree = i.next();
while (i.hasNext()) {
nextFree = i.next();
@@ -193,14 +193,14 @@ public final class kelondroBLOBHeap implements kelondroBLOB {
* @param key
* @return true if the key exists, false othervise
*/
- public boolean has(byte[] key) {
+ public boolean has(final byte[] key) {
assert index != null;
assert index.row().primaryKeyLength == key.length;
// check if the index contains the key
try {
return index.getl(key) >= 0;
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
return false;
}
@@ -212,7 +212,7 @@ public final class kelondroBLOBHeap implements kelondroBLOB {
* @param blob
* @throws IOException
*/
- private void add(byte[] key, byte[] blob) throws IOException {
+ private void add(final byte[] key, final byte[] blob) throws IOException {
add(key, blob, 0, blob.length);
}
@@ -222,12 +222,12 @@ public final class kelondroBLOBHeap implements kelondroBLOB {
* @param blob
* @throws IOException
*/
- private void add(byte[] key, byte[] blob, int offset, int len) throws IOException {
+ private void add(final byte[] key, final byte[] blob, final int offset, final int len) throws IOException {
assert len > 0;
assert index.row().primaryKeyLength == key.length;
assert blob == null || blob.length - offset >= len;
if ((blob == null) || (blob.length == 0)) return;
- int pos = (int) file.length();
+ final int pos = (int) file.length();
file.seek(file.length());
file.writeInt(len + key.length);
file.write(key);
@@ -241,23 +241,23 @@ public final class kelondroBLOBHeap implements kelondroBLOB {
* @return
* @throws IOException
*/
- public synchronized byte[] get(byte[] key) throws IOException {
+ public synchronized byte[] get(final byte[] key) throws IOException {
assert index.row().primaryKeyLength == key.length;
// check if the index contains the key
- long pos = index.getl(key);
+ final long pos = index.getl(key);
if (pos < 0) return null;
// access the file and read the container
file.seek(pos);
- int len = file.readInt() - index.row().primaryKeyLength;
+ final int len = file.readInt() - index.row().primaryKeyLength;
if (serverMemory.available() < len) {
if (!serverMemory.request(len, false)) return null; // not enough memory available for this blob
}
- byte[] blob = new byte[len];
+ final byte[] blob = new byte[len];
// read the key
- byte[] keyf = new byte[index.row().primaryKeyLength];
+ final byte[] keyf = new byte[index.row().primaryKeyLength];
file.readFully(keyf);
assert this.ordering.compare(key, keyf) == 0;
@@ -276,7 +276,7 @@ public final class kelondroBLOBHeap implements kelondroBLOB {
free.clear();
try {
file.close();
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
this.heapFile.delete();
@@ -291,7 +291,7 @@ public final class kelondroBLOBHeap implements kelondroBLOB {
free.clear();
try {
file.close();
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
index = null;
@@ -313,7 +313,7 @@ public final class kelondroBLOBHeap implements kelondroBLOB {
* @param b
* @throws IOException
*/
- public synchronized void put(byte[] key, byte[] b) throws IOException {
+ public synchronized void put(final byte[] key, final byte[] b) throws IOException {
assert key.length == index.row().primaryKeyLength;
// first remove the old entry
@@ -324,7 +324,7 @@ public final class kelondroBLOBHeap implements kelondroBLOB {
// find the largest entry
long lseek = -1;
int lsize = 0;
- int reclen = b.length + index.row().primaryKeyLength;
+ final int reclen = b.length + index.row().primaryKeyLength;
gap entry;
Iterator<gap> i = this.free.iterator();
while (i.hasNext()) {
@@ -333,7 +333,7 @@ public final class kelondroBLOBHeap implements kelondroBLOB {
// we found an entry that has exactly the size that we need!
// we use that entry and stop looking for a larger entry
file.seek(entry.seek);
- int reclenf = file.readInt();
+ final int reclenf = file.readInt();
assert reclenf == reclen;
file.write(key);
file.write(b);
@@ -373,7 +373,7 @@ public final class kelondroBLOBHeap implements kelondroBLOB {
index.putl(key, lseek);
// define the new empty entry
- int newfreereclen = lsize - reclen - 4;
+ final int newfreereclen = lsize - reclen - 4;
assert newfreereclen > 0;
file.writeInt(newfreereclen);
@@ -407,11 +407,11 @@ public final class kelondroBLOBHeap implements kelondroBLOB {
* @param key the primary key
* @throws IOException
*/
- public synchronized void remove(byte[] key) throws IOException {
+ public synchronized void remove(final byte[] key) throws IOException {
assert index.row().primaryKeyLength == key.length;
// check if the index contains the key
- long pos = index.getl(key);
+ final long pos = index.getl(key);
if (pos < 0) return;
// access the file and read the container
@@ -435,7 +435,7 @@ public final class kelondroBLOBHeap implements kelondroBLOB {
* @return
* @throws IOException
*/
- public synchronized kelondroCloneableIterator<byte[]> keys(boolean up, boolean rotating) throws IOException {
+ public synchronized kelondroCloneableIterator<byte[]> keys(final boolean up, final boolean rotating) throws IOException {
return new kelondroRotateIterator<byte[]>(this.index.keys(up, null), null, 1);
}
@@ -446,15 +446,15 @@ public final class kelondroBLOBHeap implements kelondroBLOB {
* @return
* @throws IOException
*/
- public synchronized kelondroCloneableIterator<byte[]> keys(boolean up, byte[] firstKey) throws IOException {
+ public synchronized kelondroCloneableIterator<byte[]> keys(final boolean up, final byte[] firstKey) throws IOException {
return this.index.keys(up, firstKey);
}
- public static void main(String[] args) {
- File f = new File("/Users/admin/blobtest.heap");
+ public static void main(final String[] args) {
+ final File f = new File("/Users/admin/blobtest.heap");
try {
//f.delete();
- kelondroBLOBHeap heap = new kelondroBLOBHeap(f, 12, kelondroNaturalOrder.naturalOrder);
+ final kelondroBLOBHeap heap = new kelondroBLOBHeap(f, 12, kelondroNaturalOrder.naturalOrder);
heap.put("aaaaaaaaaaaa".getBytes(), "eins zwei drei".getBytes());
heap.put("aaaaaaaaaaab".getBytes(), "vier fuenf sechs".getBytes());
heap.put("aaaaaaaaaaac".getBytes(), "sieben acht neun".getBytes());
@@ -462,7 +462,7 @@ public final class kelondroBLOBHeap implements kelondroBLOB {
heap.remove("aaaaaaaaaaab".getBytes());
heap.remove("aaaaaaaaaaac".getBytes());
heap.close();
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
}
diff --git a/source/de/anomic/kelondro/kelondroBLOBTree.java b/source/de/anomic/kelondro/kelondroBLOBTree.java
index 1dd421f9d..d947478a5 100644
--- a/source/de/anomic/kelondro/kelondroBLOBTree.java
+++ b/source/de/anomic/kelondro/kelondroBLOBTree.java
@@ -47,28 +47,28 @@ public class kelondroBLOBTree implements kelondroBLOB {
private static final int EcoFSBufferSize = 20;
protected int keylen;
- private int reclen;
+ private final int reclen;
//private int segmentCount;
- private char fillChar;
- private kelondroIndex index;
+ private final char fillChar;
+ private final kelondroIndex index;
private kelondroObjectBuffer buffer;
- private kelondroRow rowdef;
+ private final kelondroRow rowdef;
- public kelondroBLOBTree(File file, boolean useNodeCache, boolean useObjectCache, int key,
- int nodesize, char fillChar, kelondroByteOrder objectOrder, boolean usetree, boolean writebuffer, boolean resetOnFail) {
+ public kelondroBLOBTree(final File file, final boolean useNodeCache, final boolean useObjectCache, final int key,
+ final int nodesize, final char fillChar, final kelondroByteOrder objectOrder, final boolean usetree, final boolean writebuffer, final boolean resetOnFail) {
// creates or opens a dynamic tree
rowdef = new kelondroRow("byte[] key-" + (key + counterlen) + ", byte[] node-" + nodesize, objectOrder, 0);
kelondroIndex fbi;
if (usetree) {
try {
fbi = new kelondroTree(file, useNodeCache, 0, rowdef, 1, 8);
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
if (resetOnFail) {
file.delete();
try {
fbi = new kelondroTree(file, useNodeCache, -1, rowdef, 1, 8);
- } catch (IOException e1) {
+ } catch (final IOException e1) {
e1.printStackTrace();
throw new kelondroException(e.getMessage());
}
@@ -97,7 +97,7 @@ public class kelondroBLOBTree implements kelondroBLOB {
buffer = new kelondroObjectBuffer(file.toString());
}
- public static final void delete(File file) {
+ public static final void delete(final File file) {
if (file.isFile()) {
file.delete();
if (file.exists()) file.deleteOnExit();
@@ -107,7 +107,7 @@ public class kelondroBLOBTree implements kelondroBLOB {
}
public void clear() throws IOException {
- String name = this.index.filename();
+ final String name = this.index.filename();
this.index.clear();
this.buffer = new kelondroObjectBuffer(name);
}
@@ -120,20 +120,20 @@ public class kelondroBLOBTree implements kelondroBLOB {
return index.size();
}
- private static String counter(int c) {
+ private static String counter(final int c) {
String s = Integer.toHexString(c);
while (s.length() < counterlen) s = "0" + s;
return s;
}
- private byte[] elementKey(String key, int record) {
+ private byte[] elementKey(String key, final int record) {
if (key.length() > keylen) throw new RuntimeException("key len (" + key.length() + ") out of limit (" + keylen + "): '" + key + "'");
while (key.length() < keylen) key = key + fillChar;
key = key + counter(record);
return key.getBytes();
}
- String origKey(byte[] rawKey) {
+ String origKey(final byte[] rawKey) {
int n = keylen - 1;
if (n >= rawKey.length) n = rawKey.length - 1;
while ((n > 0) && (rawKey[n] == (byte) fillChar)) n--;
@@ -145,12 +145,12 @@ public class kelondroBLOBTree implements kelondroBLOB {
kelondroCloneableIterator<kelondroRow.Entry> ri;
String nextKey;
- public keyIterator(kelondroCloneableIterator<kelondroRow.Entry> iter) {
+ public keyIterator(final kelondroCloneableIterator<kelondroRow.Entry> iter) {
ri = iter;
nextKey = n();
}
- public keyIterator clone(Object modifier) {
+ public keyIterator clone(final Object modifier) {
return new keyIterator(ri.clone(modifier));
}
@@ -159,7 +159,7 @@ public class kelondroBLOBTree implements kelondroBLOB {
}
public byte[] next() {
- String result = nextKey;
+ final String result = nextKey;
nextKey = n();
return origKey(result.getBytes()).getBytes();
}
@@ -183,7 +183,7 @@ public class kelondroBLOBTree implements kelondroBLOB {
v = new String(g, keylen, counterlen);
try {
c = Integer.parseInt(v, 16);
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
c = -1;
}
if (c == 0) return k;
@@ -193,32 +193,32 @@ public class kelondroBLOBTree implements kelondroBLOB {
}
- public synchronized kelondroCloneableIterator<byte[]> keys(boolean up, boolean rotating) throws IOException {
+ public synchronized kelondroCloneableIterator<byte[]> keys(final boolean up, final boolean rotating) throws IOException {
// iterates only the keys of the Nodes
// enumerated objects are of type String
- keyIterator i = new keyIterator(index.rows(up, null));
+ final keyIterator i = new keyIterator(index.rows(up, null));
if (rotating) return new kelondroRotateIterator<byte[]>(i, null, index.size()); else return i;
}
- public synchronized kelondroCloneableIterator<byte[]> keys(boolean up, byte[] firstKey) throws IOException {
+ public synchronized kelondroCloneableIterator<byte[]> keys(final boolean up, final byte[] firstKey) throws IOException {
return new keyIterator(index.rows(up, firstKey));
}
- private byte[] getValueCached(byte[] key) throws IOException {
+ private byte[] getValueCached(final byte[] key) throws IOException {
// read from buffer
- byte[] buffered = (byte[]) buffer.get(key);
+ final byte[] buffered = (byte[]) buffer.get(key);
if (buffered != null) return buffered;
// read from db
- kelondroRow.Entry result = index.get(key);
+ final kelondroRow.Entry result = index.get(key);
if (result == null) return null;
// return result
return result.getColBytes(1);
}
- private synchronized void setValueCached(byte[] key, byte[] value) throws IOException {
+ private synchronized void setValueCached(final byte[] key, final byte[] value) throws IOException {
// update storage
synchronized (this) {
index.put(rowdef.newEntry(new byte[][]{key, value}));
@@ -226,25 +226,25 @@ public class kelondroBLOBTree implements kelondroBLOB {
}
}
- private synchronized int get(String key, int pos) throws IOException {
- int reccnt = pos / reclen;
+ private synchronized int get(final String key, final int pos) throws IOException {
+ final int reccnt = pos / reclen;
// read within a single record
- byte[] buf = getValueCached(elementKey(key, reccnt));
+ final byte[] buf = getValueCached(elementKey(key, reccnt));
if (buf == null) return -1;
- int recpos = pos % reclen;
+ final int recpos = pos % reclen;
if (buf.length <= recpos) return -1;
return buf[recpos] & 0xFF;
}
- public synchronized byte[] get(byte[] key) throws IOException {
- kelondroRA ra = getRA(new String(key));
+ public synchronized byte[] get(final byte[] key) throws IOException {
+ final kelondroRA ra = getRA(new String(key));
if (ra == null) return null;
return ra.readFully();
}
- private synchronized byte[] get(String key, int pos, int len) throws IOException {
- int recpos = pos % reclen;
- int reccnt = pos / reclen;
+ private synchronized byte[] get(final String key, final int pos, final int len) throws IOException {
+ final int recpos = pos % reclen;
+ final int reccnt = pos / reclen;
byte[] segment1;
// read first within a single record
if ((recpos == 0) && (reclen == len)) {
@@ -277,22 +277,22 @@ public class kelondroBLOBTree implements kelondroBLOB {
// segment 1 in record <reccnt> : start = recpos, length = reclen - recpos
// segment 2 in record <reccnt>+1: start = 0, length = len - reclen + recpos
// recursively step further
- byte[] segment2 = get(key, pos + segment1.length, len - segment1.length);
+ final byte[] segment2 = get(key, pos + segment1.length, len - segment1.length);
if (segment2 == null) return segment1;
// now combine the two segments into the result
- byte[] result = new byte[segment1.length + segment2.length];
+ final byte[] result = new byte[segment1.length + segment2.length];
System.arraycopy(segment1, 0, result, 0, segment1.length);
System.arraycopy(segment2, 0, result, segment1.length, segment2.length);
return result;
}
- public synchronized void put(byte[] key, byte[] b) throws IOException {
+ public synchronized void put(final byte[] key, final byte[] b) throws IOException {
put(new String(key), 0, b, 0, b.length);
}
- private synchronized void put(String key, int pos, byte[] b, int off, int len) throws IOException {
- int recpos = pos % reclen;
- int reccnt = pos / reclen;
+ private synchronized void put(final String key, final int pos, final byte[] b, final int off, final int len) throws IOException {
+ final int recpos = pos % reclen;
+ final int reccnt = pos / reclen;
byte[] buf;
// first write current record
if ((recpos == 0) && (reclen == len)) {
@@ -327,9 +327,9 @@ public class kelondroBLOBTree implements kelondroBLOB {
}
}
- private synchronized void put(String key, int pos, int b) throws IOException {
- int recpos = pos % reclen;
- int reccnt = pos / reclen;
+ private synchronized void put(final String key, final int pos, final int b) throws IOException {
+ final int recpos = pos % reclen;
+ final int reccnt = pos / reclen;
byte[] buf;
// first write current record
buf = getValueCached(elementKey(key, reccnt));
@@ -345,7 +345,7 @@ public class kelondroBLOBTree implements kelondroBLOB {
setValueCached(elementKey(key, reccnt), buf);
}
- public synchronized void remove(byte[] key) throws IOException {
+ public synchronized void remove(final byte[] key) throws IOException {
// remove value in cache and tree
if (key == null) return;
int recpos = 0;
@@ -358,11 +358,11 @@ public class kelondroBLOBTree implements kelondroBLOB {
//segmentCount--; writeSegmentCount();
}
- public synchronized boolean has(byte[] key) throws IOException {
+ public synchronized boolean has(final byte[] key) throws IOException {
return (key != null) && (getValueCached(elementKey(new String(key), 0)) != null);
}
- public synchronized kelondroRA getRA(String filekey) {
+ public synchronized kelondroRA getRA(final String filekey) {
// this returns always a RARecord, even if no existed bevore
//return new kelondroBufferedRA(new RARecord(filekey), 512, 0);
return new RARecord(filekey);
@@ -374,7 +374,7 @@ public class kelondroBLOBTree implements kelondroBLOB {
String filekey;
- public RARecord(String filekey) {
+ public RARecord(final String filekey) {
this.filekey = filekey;
}
@@ -390,13 +390,13 @@ public class kelondroBLOBTree implements kelondroBLOB {
return get(filekey, seekpos++);
}
- public void write(int i) throws IOException {
+ public void write(final int i) throws IOException {
put(filekey, seekpos++, i);
}
- public int read(byte[] b, int off, int len) throws IOException {
+ public int read(final byte[] b, final int off, final int len) throws IOException {
int l = Math.min(b.length - off, len);
- byte[] buf = get(filekey, seekpos, l);
+ final byte[] buf = get(filekey, seekpos, l);
if (buf == null) return -1;
l = Math.min(buf.length, l);
System.arraycopy(buf, 0, b, off, l);
@@ -404,12 +404,12 @@ public class kelondroBLOBTree implements kelondroBLOB {
return l;
}
- public void write(byte[] b, int off, int len) throws IOException {
+ public void write(final byte[] b, final int off, final int len) throws IOException {
put(filekey, seekpos, b, off, len);
seekpos += len;
}
- public void seek(long pos) throws IOException {
+ public void seek(final long pos) throws IOException {
seekpos = (int) pos;
}
@@ -423,7 +423,7 @@ public class kelondroBLOBTree implements kelondroBLOB {
index.close();
}
- public static void main(String[] args) {
+ public static void main(final String[] args) {
// test app for DB functions
// reads/writes files to a database table
// arguments:
@@ -432,25 +432,25 @@ public class kelondroBLOBTree implements kelondroBLOB {
if (args.length == 1) {
// open a db and list keys
try {
- kelondroBLOB kd = new kelondroBLOBTree(new File(args[0]), true, true, 4 ,100, '_', kelondroNaturalOrder.naturalOrder, false, false, true);
+ final kelondroBLOB kd = new kelondroBLOBTree(new File(args[0]), true, true, 4 ,100, '_', kelondroNaturalOrder.naturalOrder, false, false, true);
System.out.println(kd.size() + " elements in DB");
- Iterator<byte[]> i = kd.keys(true, false);
+ final Iterator<byte[]> i = kd.keys(true, false);
while (i.hasNext())
System.out.println(new String(i.next()));
kd.close();
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
}
}
- public static int countElements(kelondroBLOBTree t) {
+ public static int countElements(final kelondroBLOBTree t) {
int count = 0;
try {
- Iterator<byte[]> iter = t.keys(true, false);
+ final Iterator<byte[]> iter = t.keys(true, false);
while (iter.hasNext()) {count++; if (iter.next() == null) System.out.println("ERROR! null element found");}
return count;
- } catch (IOException e) {
+ } catch (final IOException e) {
return -1;
}
}
diff --git a/source/de/anomic/kelondro/kelondroBase64Order.java b/source/de/anomic/kelondro/kelondroBase64Order.java
index c4e6e52be..f83edf652 100644
--- a/source/de/anomic/kelondro/kelondroBase64Order.java
+++ b/source/de/anomic/kelondro/kelondroBase64Order.java
@@ -57,11 +57,11 @@ public class kelondroBase64Order extends kelondroAbstractOrder<byte[]> implement
public static final Comparator<String> standardComparator = new kelondroByteOrder.StringOrder(standardCoder);
public static final Comparator<String> enhancedComparator = new kelondroByteOrder.StringOrder(enhancedCoder);
- private boolean rfc1113compliant;
+ private final boolean rfc1113compliant;
private final char[] alpha;
private final byte[] ahpla;
- public kelondroBase64Order(boolean up, boolean rfc1113compliant) {
+ public kelondroBase64Order(final boolean up, final boolean rfc1113compliant) {
// if we choose not to be rfc1113compliant,
// then we get shorter base64 results which are also filename-compatible
this.rfc1113compliant = rfc1113compliant;
@@ -73,22 +73,22 @@ public class kelondroBase64Order extends kelondroAbstractOrder<byte[]> implement
}
public static byte[] zero(int length) {
- byte[] z = new byte[length];
+ final byte[] z = new byte[length];
while (length > 0) { length--; z[length] = (byte) alpha_standard[0]; }
return z;
}
public kelondroOrder<byte[]> clone() {
- kelondroBase64Order o = new kelondroBase64Order(this.asc, this.rfc1113compliant);
+ final kelondroBase64Order o = new kelondroBase64Order(this.asc, this.rfc1113compliant);
o.rotate(zero);
return o;
}
- public final boolean wellformed(byte[] a) {
+ public final boolean wellformed(final byte[] a) {
return wellformed(a, 0, a.length);
}
- public final boolean wellformed(byte[] a, int astart, int alength) {
+ public final boolean wellformed(final byte[] a, final int astart, final int alength) {
assert (astart + alength <= a.length) : "astart = " + astart + ", alength = " + alength + ", a.length = " + a.length;
int b;
for (int i = astart + alength - 1; i >= astart; i--) {
@@ -98,7 +98,7 @@ public class kelondroBase64Order extends kelondroAbstractOrder<byte[]> implement
return true;
}
- public final static kelondroByteOrder bySignature(String signature) {
+ public final static kelondroByteOrder bySignature(final String signature) {
if (signature.equals("Bd")) return new kelondroBase64Order(false, false);
if (signature.equals("bd")) return new kelondroBase64Order(false, true);
if (signature.equals("Bu")) return new kelondroBase64Order(true, false);
@@ -114,17 +114,17 @@ public class kelondroBase64Order extends kelondroAbstractOrder<byte[]> implement
return null;
}
- public final char encodeByte(byte b) {
+ public final char encodeByte(final byte b) {
return alpha[b];
}
- public final byte decodeByte(char b) {
+ public final byte decodeByte(final char b) {
return ahpla[b];
}
- public final String encodeLongSmart(long c, int length) {
+ public final String encodeLongSmart(final long c, int length) {
if (c >= max(length)) {
- StringBuffer s = new StringBuffer(length);
+ final StringBuffer s = new StringBuffer(length);
s.setLength(length);
while (length > 0) s.setCharAt(--length, alpha[63]);
return new String(s);
@@ -133,7 +133,7 @@ public class kelondroBase64Order extends kelondroAbstractOrder<byte[]> implement
}
public final String encodeLong(long c, int length) {
- StringBuffer s = new StringBuffer(length);
+ final StringBuffer s = new StringBuffer(length);
s.setLength(length);
while (length > 0) {
s.setCharAt(--length, alpha[(byte) (c & 0x3F)]);
@@ -142,7 +142,7 @@ public class kelondroBase64Order extends kelondroAbstractOrder<byte[]> implement
return new String(s);
}
- public final void encodeLong(long c, byte[] b, int offset, int length) {
+ public final void encodeLong(long c, final byte[] b, final int offset, int length) {
assert offset + length <= b.length;
while (length > 0) {
b[--length + offset] = (byte) alpha[(byte) (c & 0x3F)];
@@ -157,14 +157,14 @@ public class kelondroBase64Order extends kelondroAbstractOrder<byte[]> implement
return c;
}
- public final long decodeLong(byte[] s, int offset, int length) {
+ public final long decodeLong(final byte[] s, final int offset, int length) {
while ((length > 0) && (s[offset + length - 1] == '=')) length--;
long c = 0;
for (int i = 0; i < length; i++) c = (c << 6) | ahpla[s[offset + i]];
return c;
}
- public static long max(int len) {
+ public static long max(final int len) {
// computes the maximum number that can be coded with a base64-encoded
// String of base len
long c = 0;
@@ -172,10 +172,10 @@ public class kelondroBase64Order extends kelondroAbstractOrder<byte[]> implement
return c;
}
- public final String encodeString(String in) {
+ public final String encodeString(final String in) {
try {
return encode(in.getBytes("UTF-8"));
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
return "";
}
}
@@ -183,7 +183,7 @@ public class kelondroBase64Order extends kelondroAbstractOrder<byte[]> implement
// we will use this encoding to encode strings with 2^8 values to
// b64-Strings
// we will do that by grouping each three input bytes to four output bytes.
- public final String encode(byte[] in) {
+ public final String encode(final byte[] in) {
if (in.length == 0) return "";
StringBuffer out = new StringBuffer(in.length / 3 * 4 + 3);
int pos = 0;
@@ -200,23 +200,23 @@ public class kelondroBase64Order extends kelondroAbstractOrder<byte[]> implement
return new String(out);
}
- public final String decodeString(String in, String info) {
+ public final String decodeString(final String in, final String info) {
try {
//return new String(decode(in), "ISO-8859-1");
return new String(decode(in, info), "UTF-8");
- } catch (java.io.UnsupportedEncodingException e) {
+ } catch (final java.io.UnsupportedEncodingException e) {
System.out.println("internal error in base64: " + e.getMessage());
return null;
}
}
- public final byte[] decode(String in, String info) {
+ public final byte[] decode(String in, final String info) {
if ((in == null) || (in.length() == 0)) return new byte[0];
try {
int posIn = 0;
int posOut = 0;
if (rfc1113compliant) while (in.charAt(in.length() - 1) == '=') in = in.substring(0, in.length() - 1);
- byte[] out = new byte[in.length() / 4 * 3 + (((in.length() % 4) == 0) ? 0 : in.length() % 4 - 1)];
+ final byte[] out = new byte[in.length() / 4 * 3 + (((in.length() % 4) == 0) ? 0 : in.length() % 4 - 1)];
long l;
while (posIn + 3 < in.length()) {
l = decodeLong(in.substring(posIn, posIn + 4));
@@ -245,7 +245,7 @@ public class kelondroBase64Order extends kelondroAbstractOrder<byte[]> implement
}
}
return out;
- } catch (ArrayIndexOutOfBoundsException e) {
+ } catch (final ArrayIndexOutOfBoundsException e) {
// maybe the input was not base64
// throw new RuntimeException("input probably not base64");
if (this.log.isFine()) this.log.logFine("wrong string receive: " + in + ", call: " + info);
@@ -253,7 +253,7 @@ public class kelondroBase64Order extends kelondroAbstractOrder<byte[]> implement
}
}
- private final long cardinalI(byte[] key) {
+ private final long cardinalI(final byte[] key) {
// returns a cardinal number in the range of 0 .. Long.MAX_VALUE
long c = 0;
int p = 0;
@@ -263,36 +263,36 @@ public class kelondroBase64Order extends kelondroAbstractOrder<byte[]> implement
return c;
}
- public final long cardinal(byte[] key) {
+ public final long cardinal(final byte[] key) {
if (this.zero == null) return cardinalI(key);
- long zeroCardinal = cardinalI(this.zero);
- long keyCardinal = cardinalI(key);
+ final long zeroCardinal = cardinalI(this.zero);
+ final long keyCardinal = cardinalI(key);
if (keyCardinal > zeroCardinal) return keyCardinal - zeroCardinal;
return Long.MAX_VALUE - keyCardinal + zeroCardinal;
}
- private static final int sig(int x) {
+ private static final int sig(final int x) {
return (x > 0) ? 1 : (x < 0) ? -1 : 0;
}
- public final int compare(byte[] a, byte[] b) {
+ public final int compare(final byte[] a, final byte[] b) {
return (asc) ? compare0(a, 0, a.length, b, 0, b.length) : compare0(b, 0, b.length, a, 0, a.length);
}
- public final int compare(byte[] a, int aoffset, int alength, byte[] b, int boffset, int blength) {
+ public final int compare(final byte[] a, final int aoffset, final int alength, final byte[] b, final int boffset, final int blength) {
return (asc) ? compare0(a, aoffset, alength, b, boffset, blength) : compare0(b, boffset, blength, a, aoffset, alength);
}
- public final int compare0(byte[] a, int aoffset, int alength, byte[] b, int boffset, int blength) {
+ public final int compare0(final byte[] a, final int aoffset, final int alength, final byte[] b, final int boffset, final int blength) {
if (zero == null) return compares(a, aoffset, alength, b, boffset, blength);
// we have an artificial start point. check all combinations
- int az = compares(a, aoffset, alength, zero, 0, Math.min(alength, zero.length)); // -1 if a < z; 0 if a == z; 1 if a > z
- int bz = compares(b, boffset, blength, zero, 0, Math.min(blength, zero.length)); // -1 if b < z; 0 if b == z; 1 if b > z
+ final int az = compares(a, aoffset, alength, zero, 0, Math.min(alength, zero.length)); // -1 if a < z; 0 if a == z; 1 if a > z
+ final int bz = compares(b, boffset, blength, zero, 0, Math.min(blength, zero.length)); // -1 if b < z; 0 if b == z; 1 if b > z
if (az == bz) return compares(a, aoffset, alength, b, boffset, blength);
return sig(az - bz);
}
- public final int compares(byte[] a, int aoffset, int alength, byte[] b, int boffset, int blength) {
+ public final int compares(final byte[] a, final int aoffset, final int alength, final byte[] b, final int boffset, final int blength) {
assert (aoffset + alength <= a.length) : "a.length = " + a.length + ", aoffset = " + aoffset + ", alength = " + alength;
assert (boffset + blength <= b.length) : "b.length = " + b.length + ", boffset = " + boffset + ", blength = " + blength;
assert (ahpla.length == 128);
@@ -325,7 +325,7 @@ public class kelondroBase64Order extends kelondroAbstractOrder<byte[]> implement
return 0;
}
- public final int comparePivot(byte[] compiledPivot, byte[] b, int boffset, int blength) {
+ public final int comparePivot(final byte[] compiledPivot, final byte[] b, final int boffset, final int blength) {
assert zero == null;
assert asc;
assert (boffset + blength <= b.length) : "b.length = " + b.length + ", boffset = " + boffset + ", blength = " + blength;
@@ -358,9 +358,9 @@ public class kelondroBase64Order extends kelondroAbstractOrder<byte[]> implement
return 0;
}
- public final byte[] compilePivot(byte[] a, int aoffset, int alength) {
+ public final byte[] compilePivot(final byte[] a, final int aoffset, final int alength) {
assert (aoffset + alength <= a.length) : "a.length = " + a.length + ", aoffset = " + aoffset + ", alength = " + alength;
- byte[] cp = new byte[Math.min(alength, a.length - aoffset)];
+ final byte[] cp = new byte[Math.min(alength, a.length - aoffset)];
byte aa;
for (int i = cp.length - 1; i >= 0; i--) {
aa = a[aoffset + i];
@@ -372,8 +372,8 @@ public class kelondroBase64Order extends kelondroAbstractOrder<byte[]> implement
return cp;
}
- public static void main(String[] s) {
- kelondroBase64Order b64 = new kelondroBase64Order(true, true);
+ public static void main(final String[] s) {
+ final kelondroBase64Order b64 = new kelondroBase64Order(true, true);
if (s.length == 0) {
System.out.println("usage: -[ec|dc|es|ds|s2m] <arg>");
System.exit(0);
diff --git a/source/de/anomic/kelondro/kelondroBinSearch.java b/source/de/anomic/kelondro/kelondroBinSearch.java
index e60dc9e82..229aa8b1c 100644
--- a/source/de/anomic/kelondro/kelondroBinSearch.java
+++ b/source/de/anomic/kelondro/kelondroBinSearch.java
@@ -29,29 +29,29 @@ package de.anomic.kelondro;
public class kelondroBinSearch {
- private byte[] chunks;
- private int chunksize;
- private int count;
- private kelondroByteOrder objectOrder = new kelondroNaturalOrder(true);
+ private final byte[] chunks;
+ private final int chunksize;
+ private final int count;
+ private final kelondroByteOrder objectOrder = new kelondroNaturalOrder(true);
- public kelondroBinSearch(byte[] chunks, int chunksize) {
+ public kelondroBinSearch(final byte[] chunks, final int chunksize) {
this.chunks = chunks;
this.chunksize = chunksize;
this.count = chunks.length / chunksize;
}
- public boolean contains(byte[] t) {
+ public boolean contains(final byte[] t) {
return contains(t, 0, this.count);
}
- private synchronized boolean contains(byte[] t, int beginPos, int endPos) {
+ private synchronized boolean contains(final byte[] t, final int beginPos, final int endPos) {
// the endPos is exclusive, beginPos is inclusive
// this method is synchronized to make the use of the buffer possible
assert t.length == this.chunksize;
if (beginPos >= endPos) return false;
- int pivot = (beginPos + endPos) / 2;
+ final int pivot = (beginPos + endPos) / 2;
if ((pivot < 0) || (pivot >= this.count)) return false;
- int c = objectOrder.compare(this.chunks, pivot * this.chunksize, this.chunksize, t, 0, t.length);
+ final int c = objectOrder.compare(this.chunks, pivot * this.chunksize, this.chunksize, t, 0, t.length);
if (c == 0) return true;
if (c < 0) /* buffer < t */ return contains(t, pivot + 1, endPos);
if (c > 0) /* buffer > t */ return contains(t, beginPos, pivot);
@@ -62,15 +62,15 @@ public class kelondroBinSearch {
return count;
}
- public byte[] get(int element) {
- byte[] a = new byte[chunksize];
+ public byte[] get(final int element) {
+ final byte[] a = new byte[chunksize];
System.arraycopy(this.chunks, element * this.chunksize, a, 0, chunksize);
return a;
}
- public static void main(String[] args) {
- String s = "4CEvsI8FRczRBo_ApRCkwfEbFLn1pIFXg39QGMgj5RHM6HpIMJq67QX3M5iQYr_LyI_5aGDaa_bYbRgJ9XnQjpmq6QkOoGWAoEaihRqhV3kItLFHjRtqauUR";
- kelondroBinSearch bs = new kelondroBinSearch(s.getBytes(), 6);
+ public static void main(final String[] args) {
+ final String s = "4CEvsI8FRczRBo_ApRCkwfEbFLn1pIFXg39QGMgj5RHM6HpIMJq67QX3M5iQYr_LyI_5aGDaa_bYbRgJ9XnQjpmq6QkOoGWAoEaihRqhV3kItLFHjRtqauUR";
+ final kelondroBinSearch bs = new kelondroBinSearch(s.getBytes(), 6);
for (int i = 0; i + 6 <= s.length(); i = i + 6) {
System.out.println(s.substring(i, i + 6) + ":" + ((bs.contains(s.substring(i, i + 6).getBytes())) ? "drin" : "draussen"));
}
diff --git a/source/de/anomic/kelondro/kelondroBitfield.java b/source/de/anomic/kelondro/kelondroBitfield.java
index 155644269..bd0f1f305 100644
--- a/source/de/anomic/kelondro/kelondroBitfield.java
+++ b/source/de/anomic/kelondro/kelondroBitfield.java
@@ -34,18 +34,18 @@ public class kelondroBitfield implements Cloneable {
this(0);
}
- public kelondroBitfield(byte[] b) {
+ public kelondroBitfield(final byte[] b) {
if (b == null) this.bb = new byte[0]; else this.bb = b;
}
- public kelondroBitfield(int bytelength) {
+ public kelondroBitfield(final int bytelength) {
this.bb= new byte[bytelength];
for (int i = 0 ; i < bytelength; i++) bb[i] = 0;
}
- public kelondroBitfield(int bytelength, String exported) {
+ public kelondroBitfield(final int bytelength, final String exported) {
// imports a b64-encoded bitfield
- byte[] b = kelondroBase64Order.enhancedCoder.decode(exported, "de.anomic.kelondro.kelondroBitfield.kelondroBitfield(...)");
+ final byte[] b = kelondroBase64Order.enhancedCoder.decode(exported, "de.anomic.kelondro.kelondroBitfield.kelondroBitfield(...)");
if (b.length == bytelength) {
bb = b;
} else {
@@ -56,14 +56,14 @@ public class kelondroBitfield implements Cloneable {
}
public kelondroBitfield clone() {
- kelondroBitfield theClone = new kelondroBitfield(new byte[this.bb.length]);
+ final kelondroBitfield theClone = new kelondroBitfield(new byte[this.bb.length]);
System.arraycopy(this.bb, 0, theClone.bb, 0, this.bb.length);
return theClone;
}
- public void set(int pos, boolean value) {
+ public void set(final int pos, final boolean value) {
assert (pos >= 0);
- int slot = pos >> 3; // /8
+ final int slot = pos >> 3; // /8
if (slot >= bb.length) {
// extend capacity
byte[] nb = new byte[slot + 1];
@@ -79,9 +79,9 @@ public class kelondroBitfield implements Cloneable {
}
}
- public boolean get(int pos) {
+ public boolean get(final int pos) {
assert (pos >= 0);
- int slot = pos >> 3; // /8
+ final int slot = pos >> 3; // /8
if (slot > bb.length) return false;
return (bb[slot] & (1 << (pos % 8))) > 0;
}
@@ -99,46 +99,46 @@ public class kelondroBitfield implements Cloneable {
}
public String toString() {
- StringBuffer sb = new StringBuffer(length());
+ final StringBuffer sb = new StringBuffer(length());
for (int i = length() - 1; i >= 0; i--) sb.append((this.get(i)) ? '1' : '0');
return new String(sb);
}
- public boolean equals(kelondroBitfield x) {
+ public boolean equals(final kelondroBitfield x) {
if (x.bb.length != bb.length) return false;
for (int i = 0; i < bb.length; i++) if (bb[i] != x.bb[i]) return false;
return true;
}
- public void and(kelondroBitfield x) {
- int c = Math.min(x.length(), this.length());
+ public void and(final kelondroBitfield x) {
+ final int c = Math.min(x.length(), this.length());
for (int i = 0; i < c; i++) set(i, this.get(i) && x.get(i));
}
- public void or(kelondroBitfield x) {
- int c = Math.min(x.length(), this.length());
+ public void or(final kelondroBitfield x) {
+ final int c = Math.min(x.length(), this.length());
for (int i = 0; i < c; i++) set(i, this.get(i) || x.get(i));
if (x.length() > c) {
for (int i = c; i < x.length(); i++) set(i, x.get(i));
}
}
- public void xor(kelondroBitfield x) {
- int c = Math.min(x.length(), this.length());
+ public void xor(final kelondroBitfield x) {
+ final int c = Math.min(x.length(), this.length());
for (int i = 0; i < c; i++) set(i, this.get(i) != x.get(i));
if (x.length() > c) {
for (int i = c; i < x.length(); i++) set(i, x.get(i));
}
}
- public boolean anyOf(kelondroBitfield x) {
- int c = Math.min(x.length(), this.length());
+ public boolean anyOf(final kelondroBitfield x) {
+ final int c = Math.min(x.length(), this.length());
for (int i = 0; i < c; i++) if ((x.get(i)) && (this.get(i))) return true;
return false;
}
- public boolean allOf(kelondroBitfield x) {
- int c = Math.min(x.length(), this.length());
+ public boolean allOf(final kelondroBitfield x) {
+ final int c = Math.min(x.length(), this.length());
for (int i = 0; i < c; i++) if ((x.get(i)) && (!(this.get(i)))) return false;
if (x.length() > c) {
for (int i = c; i < x.length(); i++) if (x.get(i)) return false;
@@ -146,9 +146,9 @@ public class kelondroBitfield implements Cloneable {
return true;
}
- public static void main(String[] args) {
+ public static void main(final String[] args) {
kelondroBitfield test = new kelondroBitfield(4);
- int l = test.length();
+ final int l = test.length();
System.out.println("available: " + l);
System.out.println("bevore: " + test.toString());
for (int i = 0; i < l/2; i++) {
diff --git a/source/de/anomic/kelondro/kelondroBufferedEcoFS.java b/source/de/anomic/kelondro/kelondroBufferedEcoFS.java
index 2fdc17422..1f90cb297 100644
--- a/source/de/anomic/kelondro/kelondroBufferedEcoFS.java
+++ b/source/de/anomic/kelondro/kelondroBufferedEcoFS.java
@@ -39,10 +39,10 @@ import java.util.TreeMap;
public class kelondroBufferedEcoFS {
private kelondroEcoFS efs;
- private int maxEntries;
- private TreeMap<Long, byte[]> buffer;
+ private final int maxEntries;
+ private final TreeMap<Long, byte[]> buffer;
- public kelondroBufferedEcoFS(kelondroEcoFS efs, int maxEntries) {
+ public kelondroBufferedEcoFS(final kelondroEcoFS efs, final int maxEntries) {
this.efs = efs;
this.maxEntries = maxEntries;
this.buffer = new TreeMap<Long, byte[]>();
@@ -50,7 +50,7 @@ public class kelondroBufferedEcoFS {
private void flushBuffer() throws IOException {
if (efs == null) return;
- Iterator<Map.Entry<Long, byte[]>> i = buffer.entrySet().iterator();
+ final Iterator<Map.Entry<Long, byte[]>> i = buffer.entrySet().iterator();
Map.Entry<Long, byte[]> entry;
while (i.hasNext()) {
entry = i.next();
@@ -70,7 +70,7 @@ public class kelondroBufferedEcoFS {
public synchronized void close() {
try {
flushBuffer();
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
if (efs != null) efs.close();
@@ -81,10 +81,10 @@ public class kelondroBufferedEcoFS {
if (this.efs != null) this.close();
}
- public synchronized void get(long index, byte[] b, int start) throws IOException {
+ public synchronized void get(final long index, final byte[] b, final int start) throws IOException {
assert b.length - start >= efs.recordsize;
if (index >= size()) throw new IndexOutOfBoundsException("kelondroBufferedEcoFS.get(" + index + ") outside bounds (" + this.size() + ")");
- byte[] bb = buffer.get(new Long(index));
+ final byte[] bb = buffer.get(new Long(index));
if (bb == null) {
efs.get(index, b, start);
} else {
@@ -92,29 +92,29 @@ public class kelondroBufferedEcoFS {
}
}
- public synchronized void put(long index, byte[] b, int start) throws IOException {
+ public synchronized void put(final long index, final byte[] b, final int start) throws IOException {
assert b.length - start >= efs.recordsize;
- long s = size();
+ final long s = size();
if (index > s) throw new IndexOutOfBoundsException("kelondroBufferedEcoFS.put(" + index + ") outside bounds (" + this.size() + ")");
if (index == s) {
efs.add(b, start);
} else {
- byte[] bb = new byte[efs.recordsize];
+ final byte[] bb = new byte[efs.recordsize];
System.arraycopy(b, start, bb, 0, efs.recordsize);
buffer.put(new Long(index), bb);
if (buffer.size() > this.maxEntries) flushBuffer();
}
}
- public synchronized void add(byte[] b, int start) throws IOException {
+ public synchronized void add(final byte[] b, final int start) throws IOException {
assert b.length - start >= efs.recordsize;
// index == size() == efs.size();
efs.add(b, start);
}
- public synchronized void cleanLast(byte[] b, int start) throws IOException {
+ public synchronized void cleanLast(final byte[] b, final int start) throws IOException {
assert b.length - start >= efs.recordsize;
- byte[] bb = buffer.remove(new Long(size() - 1));
+ final byte[] bb = buffer.remove(new Long(size() - 1));
if (bb == null) {
efs.cleanLast(b, start);
} else {
diff --git a/source/de/anomic/kelondro/kelondroBufferedIOChunks.java b/source/de/anomic/kelondro/kelondroBufferedIOChunks.java
index 391ed2854..7f3b4d73b 100644
--- a/source/de/anomic/kelondro/kelondroBufferedIOChunks.java
+++ b/source/de/anomic/kelondro/kelondroBufferedIOChunks.java
@@ -33,15 +33,16 @@ import java.util.TreeMap;
public final class kelondroBufferedIOChunks extends kelondroAbstractIOChunks implements kelondroIOChunks {
protected kelondroRA ra;
- private long bufferMaxSize, bufferCurrSize;
- private long commitTimeout;
- private TreeMap<Long, byte[]> buffer;
+ private final long bufferMaxSize;
+ private long bufferCurrSize;
+ private final long commitTimeout;
+ private final TreeMap<Long, byte[]> buffer;
private long lastCommit = 0;
private static final int overhead = 40;
- public kelondroBufferedIOChunks(kelondroRA ra, String name, long buffer, long commitTimeout) {
+ public kelondroBufferedIOChunks(final kelondroRA ra, final String name, final long buffer, final long commitTimeout) {
this.name = name;
this.ra = ra;
this.bufferMaxSize = buffer;
@@ -59,7 +60,7 @@ public final class kelondroBufferedIOChunks extends kelondroAbstractIOChunks imp
return ra.length();
}
- public synchronized int read(long pos, byte[] b, int off, int len) throws IOException {
+ public synchronized int read(final long pos, final byte[] b, final int off, final int len) throws IOException {
assert (b.length >= off + len): "read pos=" + pos + ", b.length=" + b.length + ", off=" + off + ", len=" + len;
// check commit time
@@ -71,7 +72,7 @@ public final class kelondroBufferedIOChunks extends kelondroAbstractIOChunks imp
// do the read
synchronized (this.buffer) {
- byte[] bb = buffer.get(new Long(pos));
+ final byte[] bb = buffer.get(new Long(pos));
if (bb == null) {
// entry not known, read directly from IO
synchronized (this.ra) {
@@ -91,13 +92,13 @@ public final class kelondroBufferedIOChunks extends kelondroAbstractIOChunks imp
}
}
- public synchronized void write(long pos, byte[] b, int off, int len) throws IOException {
+ public synchronized void write(final long pos, final byte[] b, final int off, final int len) throws IOException {
assert (b.length >= off + len): "write pos=" + pos + ", b.length=" + b.length + ", b='" + new String(b) + "', off=" + off + ", len=" + len;
//if (len > 10) System.out.println("WRITE(" + name + ", " + pos + ", " + b.length + ", " + off + ", " + len + ")");
// do the write into buffer
- byte[] bb = kelondroObjectSpace.alloc(len);
+ final byte[] bb = kelondroObjectSpace.alloc(len);
System.arraycopy(b, off, bb, 0, len);
synchronized (buffer) {
buffer.put(new Long(pos + off), bb);
@@ -115,7 +116,7 @@ public final class kelondroBufferedIOChunks extends kelondroAbstractIOChunks imp
public synchronized void commit() throws IOException {
synchronized (buffer) {
if (buffer.size() == 0) return;
- Iterator<Map.Entry<Long, byte[]>> i = buffer.entrySet().iterator();
+ final Iterator<Map.Entry<Long, byte[]>> i = buffer.entrySet().iterator();
Map.Entry<Long, byte[]> entry = i.next();
long lastPos = (entry.getKey()).longValue();
byte[] lastChunk = entry.getValue();
diff --git a/source/de/anomic/kelondro/kelondroBufferedRA.java b/source/de/anomic/kelondro/kelondroBufferedRA.java
index 9c09c2714..9b3635524 100644
--- a/source/de/anomic/kelondro/kelondroBufferedRA.java
+++ b/source/de/anomic/kelondro/kelondroBufferedRA.java
@@ -36,7 +36,7 @@ public class kelondroBufferedRA extends kelondroAbstractRA implements kelondroRA
pos = 0;
}
- public kelondroBufferedRA(serverByteBuffer bb) {
+ public kelondroBufferedRA(final serverByteBuffer bb) {
sbb = bb;
pos = 0;
}
@@ -61,23 +61,23 @@ public class kelondroBufferedRA extends kelondroAbstractRA implements kelondroRA
return 0xff & sbb.byteAt((int) pos++);
}
- public int read(byte[] b, int off, int len) throws IOException {
- byte[] g = sbb.getBytes((int) pos, len);
+ public int read(final byte[] b, final int off, final int len) throws IOException {
+ final byte[] g = sbb.getBytes((int) pos, len);
pos += g.length;
System.arraycopy(g, 0, b, off, g.length);
return g.length;
}
- public void seek(long pos) throws IOException {
+ public void seek(final long pos) throws IOException {
this.pos = pos;
}
- public void write(int b) throws IOException {
+ public void write(final int b) throws IOException {
this.sbb.overwrite((int) pos, b);
pos++;
}
- public void write(byte[] b, int off, int len) throws IOException {
+ public void write(final byte[] b, final int off, final int len) throws IOException {
this.sbb.overwrite((int) pos, b, off, len);
pos += len;
}
diff --git a/source/de/anomic/kelondro/kelondroByteArray.java b/source/de/anomic/kelondro/kelondroByteArray.java
index 3a8e3ee2e..bb0d8648b 100644
--- a/source/de/anomic/kelondro/kelondroByteArray.java
+++ b/source/de/anomic/kelondro/kelondroByteArray.java
@@ -40,31 +40,31 @@ public class kelondroByteArray {
private int offset;
private int length;
- public kelondroByteArray(int initLength) {
+ public kelondroByteArray(final int initLength) {
this.buffer = new byte[initLength];
this.length = 0;
this.offset = 0;
}
- public kelondroByteArray(byte[] bb) {
+ public kelondroByteArray(final byte[] bb) {
this.buffer = bb;
this.length = bb.length;
this.offset = 0;
}
- public kelondroByteArray(byte[] bb, int offset, int length) {
+ public kelondroByteArray(final byte[] bb, final int offset, final int length) {
this.buffer = bb;
this.length = length;
this.offset = offset;
}
- public kelondroByteArray(kelondroByteArray ba, int offset, int length) {
+ public kelondroByteArray(final kelondroByteArray ba, final int offset, final int length) {
this.buffer = ba.buffer;
this.length = length;
this.offset = ba.offset + offset;
}
- public void ensureSize(int needed) {
+ public void ensureSize(final int needed) {
if (buffer.length - offset >= needed) return;
byte[] newbuffer = new byte[needed];
System.arraycopy(buffer, offset, newbuffer, 0, length);
@@ -73,7 +73,7 @@ public class kelondroByteArray {
newbuffer = null;
}
- public void trim(int needed) {
+ public void trim(final int needed) {
if (buffer.length - offset < needed) return;
if (buffer.length - offset == length) return;
byte[] newbuffer = new byte[needed];
@@ -83,7 +83,7 @@ public class kelondroByteArray {
newbuffer = null;
}
- public final void removeShift(int pos, int dist, int upBound) {
+ public final void removeShift(final int pos, final int dist, final int upBound) {
assert (pos + dist >= 0) : "pos = " + pos + ", dist = " + dist;
assert (pos >= 0) : "pos = " + pos;
assert (this.offset + upBound <= buffer.length) : "upBound = " + upBound + ", buffer.length = " + buffer.length;
@@ -91,7 +91,7 @@ public class kelondroByteArray {
System.arraycopy(buffer, this.offset + pos + dist, buffer, this.offset + pos, upBound - pos - dist);
}
- public final void swap(int i, int j, int size) {
+ public final void swap(final int i, final int j, final int size) {
if (this.offset + this.length + size <= buffer.length) {
// there is space in the chunkcache that we can use as buffer
System.arraycopy(buffer, this.offset + size * i, buffer, buffer.length - size, size);
@@ -99,7 +99,7 @@ public class kelondroByteArray {
System.arraycopy(buffer, buffer.length - size, buffer, this.offset + size * j, size);
} else {
// allocate a chunk to use as buffer
- byte[] a = new byte[size];
+ final byte[] a = new byte[size];
System.arraycopy(buffer, this.offset + size * i, a, 0, size);
System.arraycopy(buffer, this.offset + size * j, buffer, this.offset + size * i, size);
System.arraycopy(a, 0, buffer, this.offset + size * j, size);
@@ -116,71 +116,71 @@ public class kelondroByteArray {
}
public byte[] asBytes() {
- byte[] tmp = new byte[length];
+ final byte[] tmp = new byte[length];
System.arraycopy(buffer, offset, tmp, 0, length);
return tmp;
}
- public byte readByte(int pos) {
+ public byte readByte(final int pos) {
return buffer[this.offset + pos];
}
- public long readLongB64e(int pos, int length) {
+ public long readLongB64e(final int pos, final int length) {
return kelondroBase64Order.enhancedCoder.decodeLong(buffer, this.offset + pos, length);
}
- public long readLongB256(int pos, int length) {
+ public long readLongB256(final int pos, final int length) {
return kelondroNaturalOrder.decodeLong(buffer, this.offset + pos, length);
}
- public byte[] readBytes(int from_pos, int length) {
- byte[] buf = new byte[length];
+ public byte[] readBytes(final int from_pos, final int length) {
+ final byte[] buf = new byte[length];
System.arraycopy(buffer, this.offset + from_pos, buf, 0, length);
return buf;
}
- public String readString(int from_pos, int length) {
+ public String readString(final int from_pos, final int length) {
return new String(buffer, this.offset + from_pos, length);
}
- public String readString(int from_pos, int length, String encoding) {
+ public String readString(final int from_pos, final int length, final String encoding) {
try {
return new String(buffer, this.offset + from_pos, length, encoding);
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
return "";
}
}
- public void readToRA(int from_pos, kelondroRA to_file, int len) throws IOException {
+ public void readToRA(final int from_pos, final kelondroRA to_file, final int len) throws IOException {
to_file.write(this.buffer, from_pos, len);
}
- public void write(int to_position, byte b) {
+ public void write(final int to_position, final byte b) {
buffer[this.offset + to_position] = b;
}
- public void write(int to_position, byte[] from_array, int from_offset, int from_length) {
+ public void write(final int to_position, final byte[] from_array, final int from_offset, final int from_length) {
System.arraycopy(from_array, from_offset, this.buffer, this.offset + to_position, from_length);
}
- public void write(int to_position, kelondroByteArray from_array) {
+ public void write(final int to_position, final kelondroByteArray from_array) {
System.arraycopy(from_array.buffer, from_array.offset, this.buffer, this.offset + to_position, from_array.length);
}
- public void write(int to_position, kelondroByteArray from_array, int from_offset, int from_length) {
+ public void write(final int to_position, final kelondroByteArray from_array, final int from_offset, final int from_length) {
System.arraycopy(from_array.buffer, from_array.offset + from_offset, this.buffer, this.offset + to_position, from_length);
}
- public int write(int to_position, kelondroRA from_file, int len) throws IOException {
+ public int write(final int to_position, final kelondroRA from_file, final int len) throws IOException {
if (len == 0) return 0;
return from_file.read(this.buffer, to_position, len);
}
- public static boolean equals(byte[] buffer, byte[] pattern) {
+ public static boolean equals(final byte[] buffer, final byte[] pattern) {
return equals(buffer, 0, pattern);
}
- public static boolean equals(byte[] buffer, int offset, byte[] pattern) {
+ public static boolean equals(final byte[] buffer, final int offset, final byte[] pattern) {
// compares two byte arrays: true, if pattern appears completely at offset position
if (buffer.length < offset + pattern.length) return false;
for (int i = 0; i < pattern.length; i++) if (buffer[offset + i] != pattern[i]) return false;
@@ -192,11 +192,11 @@ public class kelondroByteArray {
this.offset = 0;
}
- public int compareTo(kelondroByteArray b, kelondroByteOrder order) {
+ public int compareTo(final kelondroByteArray b, final kelondroByteOrder order) {
return order.compare(this.buffer, this.offset, this.length, b.buffer, b.offset, b.length);
}
- public int compareTo(int aoffset, int alength, kelondroByteArray b, int boffset, int blength, kelondroByteOrder order) {
+ public int compareTo(final int aoffset, final int alength, final kelondroByteArray b, final int boffset, final int blength, final kelondroByteOrder order) {
return order.compare(this.buffer, this.offset + aoffset, alength, b.buffer, b.offset + boffset, blength);
}
}
diff --git a/source/de/anomic/kelondro/kelondroByteOrder.java b/source/de/anomic/kelondro/kelondroByteOrder.java
index 246d37020..41632f540 100644
--- a/source/de/anomic/kelondro/kelondroByteOrder.java
+++ b/source/de/anomic/kelondro/kelondroByteOrder.java
@@ -38,15 +38,15 @@ public interface kelondroByteOrder extends kelondroOrder<byte[]> {
public static class StringOrder implements Comparator<String> {
public kelondroByteOrder baseOrder;
- public StringOrder(kelondroByteOrder base) {
+ public StringOrder(final kelondroByteOrder base) {
this.baseOrder = base;
}
- public StringOrder(kelondroOrder<byte[]> base) {
+ public StringOrder(final kelondroOrder<byte[]> base) {
this.baseOrder = (kelondroByteOrder) base;
}
- public int compare(String s1, String s2) {
+ public int compare(final String s1, final String s2) {
return baseOrder.compare(s1.getBytes(), s2.getBytes());
}
diff --git a/source/de/anomic/kelondro/kelondroBytesIntMap.java b/source/de/anomic/kelondro/kelondroBytesIntMap.java
index 872a15f7d..20b939010 100644
--- a/source/de/anomic/kelondro/kelondroBytesIntMap.java
+++ b/source/de/anomic/kelondro/kelondroBytesIntMap.java
@@ -30,17 +30,17 @@ import java.util.Iterator;
public class kelondroBytesIntMap {
- private kelondroRow rowdef;
+ private final kelondroRow rowdef;
private kelondroIndex index;
- public kelondroBytesIntMap(kelondroIndex ki) {
+ public kelondroBytesIntMap(final kelondroIndex ki) {
assert (ki.row().columns() == 2); // must be a key/index relation
assert (ki.row().width(1) == 4); // the value must be a b256-encoded int, 4 bytes long
this.index = ki;
this.rowdef = ki.row();
}
- public kelondroBytesIntMap(int keylength, kelondroByteOrder objectOrder, int space) {
+ public kelondroBytesIntMap(final int keylength, final kelondroByteOrder objectOrder, final int space) {
this.rowdef = new kelondroRow(new kelondroColumn[]{new kelondroColumn("key", kelondroColumn.celltype_binary, kelondroColumn.encoder_bytes, keylength, "key"), new kelondroColumn("int c-4 {b256}")}, objectOrder, 0);
this.index = new kelondroRAMIndex(rowdef, space);
}
@@ -49,45 +49,45 @@ public class kelondroBytesIntMap {
return index.row();
}
- public synchronized boolean has(byte[] key) {
+ public synchronized boolean has(final byte[] key) {
assert (key != null);
return index.has(key);
}
- public synchronized int geti(byte[] key) throws IOException {
+ public synchronized int geti(final byte[] key) throws IOException {
assert (key != null);
- kelondroRow.Entry indexentry = index.get(key);
+ final kelondroRow.Entry indexentry = index.get(key);
if (indexentry == null) return -1;
return (int) indexentry.getColLong(1);
}
- public synchronized int puti(byte[] key, int i) throws IOException {
+ public synchronized int puti(final byte[] key, final int i) throws IOException {
assert i >= 0 : "i = " + i;
assert (key != null);
- kelondroRow.Entry newentry = index.row().newEntry();
+ final kelondroRow.Entry newentry = index.row().newEntry();
newentry.setCol(0, key);
newentry.setCol(1, i);
- kelondroRow.Entry oldentry = index.put(newentry);
+ final kelondroRow.Entry oldentry = index.put(newentry);
if (oldentry == null) return -1;
return (int) oldentry.getColLong(1);
}
- public synchronized boolean addi(byte[] key, int i) throws IOException {
+ public synchronized boolean addi(final byte[] key, final int i) throws IOException {
assert i >= 0 : "i = " + i;
assert (key != null);
- kelondroRow.Entry newentry = this.rowdef.newEntry();
+ final kelondroRow.Entry newentry = this.rowdef.newEntry();
newentry.setCol(0, key);
newentry.setCol(1, i);
return index.addUnique(newentry);
}
public synchronized ArrayList<Integer[]> removeDoubles() throws IOException {
- ArrayList<Integer[]> report = new ArrayList<Integer[]>();
+ final ArrayList<Integer[]> report = new ArrayList<Integer[]>();
Integer[] is;
Iterator<kelondroRow.Entry> ei;
int c, i;
- int initialSize = this.size();
- for (kelondroRowCollection delset: index.removeDoubles()) {
+ final int initialSize = this.size();
+ for (final kelondroRowCollection delset: index.removeDoubles()) {
is = new Integer[delset.size()];
ei = delset.rows();
c = 0;
@@ -101,15 +101,15 @@ public class kelondroBytesIntMap {
return report;
}
- public synchronized int removei(byte[] key) throws IOException {
+ public synchronized int removei(final byte[] key) throws IOException {
assert (key != null);
- kelondroRow.Entry indexentry = index.remove(key);
+ final kelondroRow.Entry indexentry = index.remove(key);
if (indexentry == null) return -1;
return (int) indexentry.getColLong(1);
}
public synchronized int removeonei() throws IOException {
- kelondroRow.Entry indexentry = index.removeOne();
+ final kelondroRow.Entry indexentry = index.removeOne();
if (indexentry == null) return -1;
return (int) indexentry.getColLong(1);
}
@@ -118,11 +118,11 @@ public class kelondroBytesIntMap {
return index.size();
}
- public synchronized kelondroCloneableIterator<byte[]> keys(boolean up, byte[] firstKey) throws IOException {
+ public synchronized kelondroCloneableIterator<byte[]> keys(final boolean up, final byte[] firstKey) throws IOException {
return index.keys(up, firstKey);
}
- public synchronized kelondroCloneableIterator<kelondroRow.Entry> rows(boolean up, byte[] firstKey) throws IOException {
+ public synchronized kelondroCloneableIterator<kelondroRow.Entry> rows(final boolean up, final byte[] firstKey) throws IOException {
return index.rows(up, firstKey);
}
diff --git a/source/de/anomic/kelondro/kelondroBytesLongMap.java b/source/de/anomic/kelondro/kelondroBytesLongMap.java
index 34ea874a4..b6f61e400 100644
--- a/source/de/anomic/kelondro/kelondroBytesLongMap.java
+++ b/source/de/anomic/kelondro/kelondroBytesLongMap.java
@@ -30,17 +30,17 @@ import java.util.Iterator;
public class kelondroBytesLongMap {
- private kelondroRow rowdef;
+ private final kelondroRow rowdef;
private kelondroIndex index;
- public kelondroBytesLongMap(kelondroIndex ki) {
+ public kelondroBytesLongMap(final kelondroIndex ki) {
assert (ki.row().columns() == 2); // must be a key/index relation
assert (ki.row().width(1) == 8); // the value must be a b256-encoded int, 4 bytes long
this.index = ki;
this.rowdef = ki.row();
}
- public kelondroBytesLongMap(int keylength, kelondroByteOrder objectOrder, int space) {
+ public kelondroBytesLongMap(final int keylength, final kelondroByteOrder objectOrder, final int space) {
this.rowdef = new kelondroRow(new kelondroColumn[]{new kelondroColumn("key", kelondroColumn.celltype_binary, kelondroColumn.encoder_bytes, keylength, "key"), new kelondroColumn("long c-8 {b256}")}, objectOrder, 0);
this.index = new kelondroRAMIndex(rowdef, space);
}
@@ -53,40 +53,40 @@ public class kelondroBytesLongMap {
index.clear();
}
- public synchronized long getl(byte[] key) throws IOException {
+ public synchronized long getl(final byte[] key) throws IOException {
assert (key != null);
- kelondroRow.Entry indexentry = index.get(key);
+ final kelondroRow.Entry indexentry = index.get(key);
if (indexentry == null) return -1;
return indexentry.getColLong(1);
}
- public synchronized long putl(byte[] key, long l) throws IOException {
+ public synchronized long putl(final byte[] key, final long l) throws IOException {
assert l >= 0 : "l = " + l;
assert (key != null);
- kelondroRow.Entry newentry = index.row().newEntry();
+ final kelondroRow.Entry newentry = index.row().newEntry();
newentry.setCol(0, key);
newentry.setCol(1, l);
- kelondroRow.Entry oldentry = index.put(newentry);
+ final kelondroRow.Entry oldentry = index.put(newentry);
if (oldentry == null) return -1;
return oldentry.getColLong(1);
}
- public synchronized boolean addl(byte[] key, long l) throws IOException {
+ public synchronized boolean addl(final byte[] key, final long l) throws IOException {
assert l >= 0 : "l = " + l;
assert (key != null);
- kelondroRow.Entry newentry = this.rowdef.newEntry();
+ final kelondroRow.Entry newentry = this.rowdef.newEntry();
newentry.setCol(0, key);
newentry.setCol(1, l);
return index.addUnique(newentry);
}
public synchronized ArrayList<Long[]> removeDoubles() throws IOException {
- ArrayList<kelondroRowCollection> indexreport = index.removeDoubles();
- ArrayList<Long[]> report = new ArrayList<Long[]>();
+ final ArrayList<kelondroRowCollection> indexreport = index.removeDoubles();
+ final ArrayList<Long[]> report = new ArrayList<Long[]>();
Long[] is;
Iterator<kelondroRow.Entry> ei;
int c;
- for (kelondroRowCollection rowset: indexreport) {
+ for (final kelondroRowCollection rowset: indexreport) {
is = new Long[rowset.size()];
ei = rowset.rows();
c = 0;
@@ -98,15 +98,15 @@ public class kelondroBytesLongMap {
return report;
}
- public synchronized long removel(byte[] key) throws IOException {
+ public synchronized long removel(final byte[] key) throws IOException {
assert (key != null);
- kelondroRow.Entry indexentry = index.remove(key);
+ final kelondroRow.Entry indexentry = index.remove(key);
if (indexentry == null) return -1;
return indexentry.getColLong(1);
}
public synchronized long removeonel() throws IOException {
- kelondroRow.Entry indexentry = index.removeOne();
+ final kelondroRow.Entry indexentry = index.removeOne();
if (indexentry == null) return -1;
return indexentry.getColLong(1);
}
@@ -115,11 +115,11 @@ public class kelondroBytesLongMap {
return index.size();
}
- public synchronized kelondroCloneableIterator<byte[]> keys(boolean up, byte[] firstKey) throws IOException {
+ public synchronized kelondroCloneableIterator<byte[]> keys(final boolean up, final byte[] firstKey) throws IOException {
return index.keys(up, firstKey);
}
- public synchronized kelondroCloneableIterator<kelondroRow.Entry> rows(boolean up, byte[] firstKey) throws IOException {
+ public synchronized kelondroCloneableIterator<kelondroRow.Entry> rows(final boolean up, final byte[] firstKey) throws IOException {
return index.rows(up, firstKey);
}
diff --git a/source/de/anomic/kelondro/kelondroCache.java b/source/de/anomic/kelondro/kelondroCache.java
index 816d3db21..647dd58dc 100644
--- a/source/de/anomic/kelondro/kelondroCache.java
+++ b/source/de/anomic/kelondro/kelondroCache.java
@@ -57,12 +57,12 @@ public class kelondroCache implements kelondroIndex {
// class objects
private kelondroRowSet readHitCache;
private kelondroRowSet readMissCache;
- private kelondroIndex index;
+ private final kelondroIndex index;
private kelondroRow keyrow;
private int readHit, readMiss, writeUnique, writeDouble, cacheDelete, cacheFlush;
private int hasnotHit, hasnotMiss, hasnotUnique, hasnotDouble, hasnotDelete;
- public kelondroCache(kelondroIndex backupIndex) {
+ public kelondroCache(final kelondroIndex backupIndex) {
this.index = backupIndex;
init();
objectTracker.put(backupIndex.filename(), this);
@@ -97,7 +97,7 @@ public class kelondroCache implements kelondroIndex {
return index.profile(); // TODO: implement own profile and merge with global
}
- public static void setCacheGrowStati(long memStopGrowNew, long memStartShrinkNew) {
+ public static void setCacheGrowStati(final long memStopGrowNew, final long memStartShrinkNew) {
memStopGrow = memStopGrowNew;
memStartShrink = memStartShrinkNew;
}
@@ -115,17 +115,17 @@ public class kelondroCache implements kelondroIndex {
return objectTracker.keySet().iterator();
}
- public static final Map<String, String> memoryStats(String filename) {
+ public static final Map<String, String> memoryStats(final String filename) {
// returns a map for each file in the tracker;
// the map represents properties for each record oobjects,
// i.e. for cache memory allocation
- kelondroCache theObjectsCache = objectTracker.get(filename);
+ final kelondroCache theObjectsCache = objectTracker.get(filename);
return theObjectsCache.memoryStats();
}
private final Map<String, String> memoryStats() {
// returns statistical data about this object
- HashMap<String, String> map = new HashMap<String, String>();
+ final HashMap<String, String> map = new HashMap<String, String>();
map.put("objectHitChunkSize", (readHitCache == null) ? "0" : Integer.toString(readHitCache.rowdef.objectsize));
map.put("objectHitCacheCount", (readHitCache == null) ? "0" : Integer.toString(readHitCache.size()));
map.put("objectHitMem", (readHitCache == null) ? "0" : Integer.toString((int) (readHitCache.rowdef.objectsize * readHitCache.size() * kelondroRowCollection.growfactor)));
@@ -167,7 +167,7 @@ public class kelondroCache implements kelondroIndex {
private boolean checkHitSpace() {
// returns true if it is allowed to write into this cache
- int status = cacheGrowStatus();
+ final int status = cacheGrowStatus();
if (status < 1) {
if (readHitCache != null) {
readHitCache.clear();
@@ -191,7 +191,7 @@ public class kelondroCache implements kelondroIndex {
readMissCache = null;
}
- public boolean has(byte[] key) {
+ public boolean has(final byte[] key) {
// first look into the miss cache
if (readMissCache != null) {
if (readMissCache.get(key) != null) {
@@ -215,7 +215,7 @@ public class kelondroCache implements kelondroIndex {
return index.has(key);
}
- public synchronized Entry get(byte[] key) throws IOException {
+ public synchronized Entry get(final byte[] key) throws IOException {
// first look into the miss cache
if (readMissCache != null) {
if (readMissCache.get(key) != null) {
@@ -243,35 +243,35 @@ public class kelondroCache implements kelondroIndex {
// learn from result
if (entry == null) {
if ((checkMissSpace()) && (readMissCache != null)) {
- kelondroRow.Entry dummy = readMissCache.put(readMissCache.row().newEntry(key));
+ final kelondroRow.Entry dummy = readMissCache.put(readMissCache.row().newEntry(key));
if (dummy == null) this.hasnotUnique++; else this.hasnotDouble++;
}
return null;
} else {
if ((checkHitSpace()) && (readHitCache != null)) {
- kelondroRow.Entry dummy = readHitCache.put(entry);
+ final kelondroRow.Entry dummy = readHitCache.put(entry);
if (dummy == null) this.writeUnique++; else this.writeDouble++;
}
return entry;
}
}
- public synchronized void putMultiple(List<Entry> rows) throws IOException {
- Iterator<Entry> i = rows.iterator();
+ public synchronized void putMultiple(final List<Entry> rows) throws IOException {
+ final Iterator<Entry> i = rows.iterator();
while (i.hasNext()) put(i.next());
}
- public synchronized void putMultiple(List<Entry> rows, Date entryDate) throws IOException {
- Iterator<Entry> i = rows.iterator();
+ public synchronized void putMultiple(final List<Entry> rows, final Date entryDate) throws IOException {
+ final Iterator<Entry> i = rows.iterator();
while (i.hasNext()) put(i.next(), entryDate);
}
- public synchronized Entry put(Entry row) throws IOException {
+ public synchronized Entry put(final Entry row) throws IOException {
assert (row != null);
assert (row.columns() == row().columns());
//assert (!(serverLog.allZero(row.getColBytes(index.primarykey()))));
- byte[] key = row.getPrimaryKeyBytes();
+ final byte[] key = row.getPrimaryKeyBytes();
checkHitSpace();
// remove entry from miss- and hit-cache
@@ -281,7 +281,7 @@ public class kelondroCache implements kelondroIndex {
// the entry does not exist before
index.put(row); // write to backend
if (readHitCache != null) {
- kelondroRow.Entry dummy = readHitCache.put(row); // learn that entry
+ final kelondroRow.Entry dummy = readHitCache.put(row); // learn that entry
if (dummy == null) this.writeUnique++; else this.writeDouble++;
}
return null;
@@ -297,7 +297,7 @@ public class kelondroCache implements kelondroIndex {
// write directly to backend index
index.put(row);
// learn from situation
- kelondroRow.Entry dummy = readHitCache.put(row); // overwrite old entry
+ final kelondroRow.Entry dummy = readHitCache.put(row); // overwrite old entry
if (dummy == null) this.writeUnique++; else this.writeDouble++;
return entry;
}
@@ -306,24 +306,24 @@ public class kelondroCache implements kelondroIndex {
// the worst case: we must write to the back-end directly
entry = index.put(row);
if (readHitCache != null) {
- kelondroRow.Entry dummy = readHitCache.put(row); // learn that entry
+ final kelondroRow.Entry dummy = readHitCache.put(row); // learn that entry
if (dummy == null) this.writeUnique++; else this.writeDouble++;
}
return entry;
}
- public synchronized Entry put(Entry row, Date entryDate) throws IOException {
+ public synchronized Entry put(final Entry row, final Date entryDate) throws IOException {
// a put with a date is bad for the cache: the date cannot be handled
// we omit the date here and use the current Date everywhere
return this.put(row);
}
- public synchronized boolean addUnique(Entry row) throws IOException {
+ public synchronized boolean addUnique(final Entry row) throws IOException {
assert (row != null);
assert (row.columns() == row().columns());
//assert (!(serverLog.allZero(row.getColBytes(index.primarykey()))));
- byte[] key = row.getPrimaryKeyBytes();
+ final byte[] key = row.getPrimaryKeyBytes();
checkHitSpace();
// remove entry from miss- and hit-cache
@@ -331,24 +331,24 @@ public class kelondroCache implements kelondroIndex {
this.readMissCache.remove(key);
this.hasnotDelete++;
// the entry does not exist before
- boolean added = index.addUnique(row); // write to backend
+ final boolean added = index.addUnique(row); // write to backend
if (added && (readHitCache != null)) {
- kelondroRow.Entry dummy = readHitCache.put(row); // learn that entry
+ final kelondroRow.Entry dummy = readHitCache.put(row); // learn that entry
if (dummy == null) this.writeUnique++; else this.writeDouble++;
}
return added;
}
// the worst case: we must write to the back-end directly
- boolean added = index.addUnique(row);
+ final boolean added = index.addUnique(row);
if (added && (readHitCache != null)) {
- kelondroRow.Entry dummy = readHitCache.put(row); // learn that entry
+ final kelondroRow.Entry dummy = readHitCache.put(row); // learn that entry
if (dummy == null) this.writeUnique++; else this.writeDouble++;
}
return added;
}
- public synchronized void addUnique(Entry row, Date entryDate) throws IOException {
+ public synchronized void addUnique(final Entry row, final Date entryDate) throws IOException {
if (entryDate == null) {
addUnique(row);
return;
@@ -357,7 +357,7 @@ public class kelondroCache implements kelondroIndex {
assert (row != null);
assert (row.columns() == row().columns());
- byte[] key = row.getPrimaryKeyBytes();
+ final byte[] key = row.getPrimaryKeyBytes();
checkHitSpace();
// remove entry from miss- and hit-cache
@@ -369,13 +369,13 @@ public class kelondroCache implements kelondroIndex {
// the worst case: we must write to the backend directly
index.addUnique(row);
if (readHitCache != null) {
- kelondroRow.Entry dummy = readHitCache.put(row); // learn that entry
+ final kelondroRow.Entry dummy = readHitCache.put(row); // learn that entry
if (dummy == null) this.writeUnique++; else this.writeDouble++;
}
}
- public synchronized int addUniqueMultiple(List<Entry> rows) throws IOException {
- Iterator<Entry> i = rows.iterator();
+ public synchronized int addUniqueMultiple(final List<Entry> rows) throws IOException {
+ final Iterator<Entry> i = rows.iterator();
int c = 0;
while (i.hasNext()) {
if (addUnique(i.next())) c++;
@@ -388,13 +388,13 @@ public class kelondroCache implements kelondroIndex {
// todo: remove reported entries from the cache!!!
}
- public synchronized Entry remove(byte[] key) throws IOException {
+ public synchronized Entry remove(final byte[] key) throws IOException {
checkMissSpace();
// add entry to miss-cache
if (readMissCache != null) {
// set the miss cache; if there was already an entry we know that the return value must be null
- kelondroRow.Entry dummy = readMissCache.put(readMissCache.row().newEntry(key));
+ final kelondroRow.Entry dummy = readMissCache.put(readMissCache.row().newEntry(key));
if (dummy == null) {
this.hasnotUnique++;
} else {
@@ -405,7 +405,7 @@ public class kelondroCache implements kelondroIndex {
// remove entry from hit-cache
if (readHitCache != null) {
- Entry entry = readHitCache.remove(key);
+ final Entry entry = readHitCache.remove(key);
if (entry == null) {
this.readMiss++;
} else {
@@ -421,15 +421,15 @@ public class kelondroCache implements kelondroIndex {
checkMissSpace();
- Entry entry = index.removeOne();
+ final Entry entry = index.removeOne();
if (entry == null) return null;
- byte[] key = entry.getPrimaryKeyBytes();
+ final byte[] key = entry.getPrimaryKeyBytes();
if (readMissCache != null) {
- kelondroRow.Entry dummy = readMissCache.put(readMissCache.row().newEntry(key));
+ final kelondroRow.Entry dummy = readMissCache.put(readMissCache.row().newEntry(key));
if (dummy == null) this.hasnotUnique++; else this.hasnotDouble++;
}
if (readHitCache != null) {
- kelondroRow.Entry dummy = readHitCache.remove(key);
+ final kelondroRow.Entry dummy = readHitCache.remove(key);
if (dummy != null) this.cacheDelete++;
}
return entry;
@@ -439,11 +439,11 @@ public class kelondroCache implements kelondroIndex {
return index.row();
}
- public synchronized kelondroCloneableIterator<byte[]> keys(boolean up, byte[] firstKey) throws IOException {
+ public synchronized kelondroCloneableIterator<byte[]> keys(final boolean up, final byte[] firstKey) throws IOException {
return index.keys(up, firstKey);
}
- public synchronized kelondroCloneableIterator<kelondroRow.Entry> rows(boolean up, byte[] firstKey) throws IOException {
+ public synchronized kelondroCloneableIterator<kelondroRow.Entry> rows(final boolean up, final byte[] firstKey) throws IOException {
return index.rows(up, firstKey);
}
diff --git a/source/de/anomic/kelondro/kelondroCachedRA.java b/source/de/anomic/kelondro/kelondroCachedRA.java
index b84189443..b7c26279f 100644
--- a/source/de/anomic/kelondro/kelondroCachedRA.java
+++ b/source/de/anomic/kelondro/kelondroCachedRA.java
@@ -32,11 +32,11 @@ public class kelondroCachedRA extends kelondroAbstractRA implements kelondroRA {
protected kelondroRA ra;
protected kelondroMScoreCluster<Integer> cacheScore;
protected HashMap<Integer, byte[]> cacheMemory;
- private int cacheMaxElements;
- private int cacheElementSize;
+ private final int cacheMaxElements;
+ private final int cacheElementSize;
private long seekpos;
- public kelondroCachedRA(kelondroRA ra, int cachesize, int elementsize) {
+ public kelondroCachedRA(final kelondroRA ra, final int cachesize, final int elementsize) {
this.ra = ra;
this.name = ra.name();
this.file = ra.file();
@@ -58,25 +58,25 @@ public class kelondroCachedRA extends kelondroAbstractRA implements kelondroRA {
}
}
- private int cacheElementNumber(long address) {
+ private int cacheElementNumber(final long address) {
return (int) address / cacheElementSize;
}
- private int cacheElementOffset(long address) {
+ private int cacheElementOffset(final long address) {
return (int) address % cacheElementSize;
}
- private byte[] readCache(int cacheNr) throws IOException {
- Integer cacheNrI = new Integer(cacheNr);
+ private byte[] readCache(final int cacheNr) throws IOException {
+ final Integer cacheNrI = new Integer(cacheNr);
byte[] cache = cacheMemory.get(cacheNrI);
if (cache == null) {
if (cacheMemory.size() >= cacheMaxElements) {
// delete elements in buffer if buffer too big
- Iterator<Integer> it = cacheScore.scores(true);
- Integer element = it.next();
+ final Iterator<Integer> it = cacheScore.scores(true);
+ final Integer element = it.next();
writeCache(cacheMemory.get(element), element.intValue());
cacheMemory.remove(element);
- int age = cacheScore.deleteScore(element);
+ final int age = cacheScore.deleteScore(element);
de.anomic.server.logging.serverLog.logFine("CACHE: " + name, "GC; age=" + ((((int) (0xFFFFFFFFL & System.currentTimeMillis())) - age) / 1000));
}
// add new element
@@ -90,9 +90,9 @@ public class kelondroCachedRA extends kelondroAbstractRA implements kelondroRA {
return cache;
}
- private void writeCache(byte[] cache, int cacheNr) throws IOException {
+ private void writeCache(final byte[] cache, final int cacheNr) throws IOException {
if (cache == null) return;
- Integer cacheNrI = new Integer(cacheNr);
+ final Integer cacheNrI = new Integer(cacheNr);
ra.seek(cacheNr * cacheElementSize);
ra.write(cache, 0, cacheElementSize);
cacheScore.setScore(cacheNrI, (int) (0xFFFFFFFFL & System.currentTimeMillis()));
@@ -100,27 +100,27 @@ public class kelondroCachedRA extends kelondroAbstractRA implements kelondroRA {
// pseudo-native method read
public int read() throws IOException {
- int bn = cacheElementNumber(seekpos);
- int offset = cacheElementOffset(seekpos);
+ final int bn = cacheElementNumber(seekpos);
+ final int offset = cacheElementOffset(seekpos);
seekpos++;
return 0xFF & readCache(bn)[offset];
}
// pseudo-native method write
- public void write(int b) throws IOException {
- int bn = cacheElementNumber(seekpos);
- int offset = cacheElementOffset(seekpos);
- byte[] cache = readCache(bn);
+ public void write(final int b) throws IOException {
+ final int bn = cacheElementNumber(seekpos);
+ final int offset = cacheElementOffset(seekpos);
+ final byte[] cache = readCache(bn);
seekpos++;
cache[offset] = (byte) b;
//writeBuffer(buffer, bn);
}
- public int read(byte[] b, int off, int len) throws IOException {
- int bn1 = cacheElementNumber(seekpos);
- int bn2 = cacheElementNumber(seekpos + len - 1);
- int offset = cacheElementOffset(seekpos);
- byte[] buffer = readCache(bn1);
+ public int read(final byte[] b, final int off, final int len) throws IOException {
+ final int bn1 = cacheElementNumber(seekpos);
+ final int bn2 = cacheElementNumber(seekpos + len - 1);
+ final int offset = cacheElementOffset(seekpos);
+ final byte[] buffer = readCache(bn1);
if (bn1 == bn2) {
// simple case
//System.out.println("C1: bn1=" + bn1 + ", offset=" + offset + ", off=" + off + ", len=" + len);
@@ -130,18 +130,18 @@ public class kelondroCachedRA extends kelondroAbstractRA implements kelondroRA {
}
// do recursively
- int thislen = cacheElementSize - offset;
+ final int thislen = cacheElementSize - offset;
//System.out.println("C2: bn1=" + bn1 + ", bn2=" + bn2 +", offset=" + offset + ", off=" + off + ", len=" + len + ", thislen=" + thislen);
System.arraycopy(buffer, offset, b, off, thislen);
seekpos += thislen;
return thislen + read(b, off + thislen, len - thislen);
}
- public void write(byte[] b, int off, int len) throws IOException {
- int bn1 = cacheElementNumber(seekpos);
- int bn2 = cacheElementNumber(seekpos + len - 1);
- int offset = cacheElementOffset(seekpos);
- byte[] cache = readCache(bn1);
+ public void write(final byte[] b, final int off, final int len) throws IOException {
+ final int bn1 = cacheElementNumber(seekpos);
+ final int bn2 = cacheElementNumber(seekpos + len - 1);
+ final int offset = cacheElementOffset(seekpos);
+ final byte[] cache = readCache(bn1);
if (bn1 == bn2) {
// simple case
System.arraycopy(b, off, cache, offset, len);
@@ -149,7 +149,7 @@ public class kelondroCachedRA extends kelondroAbstractRA implements kelondroRA {
//writeBuffer(buffer, bn1);
} else {
// do recursively
- int thislen = cacheElementSize - offset;
+ final int thislen = cacheElementSize - offset;
System.arraycopy(b, off, cache, offset, thislen);
seekpos += thislen;
//writeBuffer(buffer, bn1);
@@ -157,16 +157,16 @@ public class kelondroCachedRA extends kelondroAbstractRA implements kelondroRA {
}
}
- public void seek(long pos) throws IOException {
+ public void seek(final long pos) throws IOException {
seekpos = pos;
}
public void close() throws IOException {
// write all unwritten buffers
if (cacheMemory == null) return;
- Iterator<Integer> it = cacheScore.scores(true);
+ final Iterator<Integer> it = cacheScore.scores(true);
while (it.hasNext()) {
- Integer element = it.next();
+ final Integer element = it.next();
writeCache(cacheMemory.get(element), element.intValue());
cacheMemory.remove(element);
}
@@ -178,6 +178,6 @@ public class kelondroCachedRA extends kelondroAbstractRA implements kelondroRA {
public void finalize() {
try {
close();
- } catch (IOException e) {}
+ } catch (final IOException e) {}
}
}
diff --git a/source/de/anomic/kelondro/kelondroCachedRecords.java b/source/de/anomic/kelondro/kelondroCachedRecords.java
index 477321e7c..9f56b54f9 100644
--- a/source/de/anomic/kelondro/kelondroCachedRecords.java
+++ b/source/de/anomic/kelondro/kelondroCachedRecords.java
@@ -61,32 +61,32 @@ public class kelondroCachedRecords extends kelondroAbstractRecords implements ke
public kelondroCachedRecords(
- File file, boolean useNodeCache, long preloadTime,
- short ohbytec, short ohhandlec,
- kelondroRow rowdef, int FHandles, int txtProps, int txtPropWidth) throws IOException {
+ final File file, final boolean useNodeCache, final long preloadTime,
+ final short ohbytec, final short ohhandlec,
+ final kelondroRow rowdef, final int FHandles, final int txtProps, final int txtPropWidth) throws IOException {
super(file, useNodeCache, ohbytec, ohhandlec, rowdef, FHandles, txtProps, txtPropWidth);
initCache(useNodeCache, preloadTime);
if (useNodeCache) recordTracker.put(this.filename, this);
}
public kelondroCachedRecords(
- kelondroRA ra, String filename, boolean useNodeCache, long preloadTime,
- short ohbytec, short ohhandlec,
- kelondroRow rowdef, int FHandles, int txtProps, int txtPropWidth,
- boolean exitOnFail) {
+ final kelondroRA ra, final String filename, final boolean useNodeCache, final long preloadTime,
+ final short ohbytec, final short ohhandlec,
+ final kelondroRow rowdef, final int FHandles, final int txtProps, final int txtPropWidth,
+ final boolean exitOnFail) {
super(ra, filename, useNodeCache, ohbytec, ohhandlec, rowdef, FHandles, txtProps, txtPropWidth, exitOnFail);
initCache(useNodeCache, preloadTime);
if (useNodeCache) recordTracker.put(this.filename, this);
}
public kelondroCachedRecords(
- kelondroRA ra, String filename, boolean useNodeCache, long preloadTime) throws IOException{
+ final kelondroRA ra, final String filename, final boolean useNodeCache, final long preloadTime) throws IOException{
super(ra, filename, useNodeCache);
initCache(useNodeCache, preloadTime);
if (useNodeCache) recordTracker.put(this.filename, this);
}
- private void initCache(boolean useNodeCache, long preloadTime) {
+ private void initCache(final boolean useNodeCache, final long preloadTime) {
if (useNodeCache) {
this.cacheHeaders = new kelondroIntBytesMap(this.headchunksize, 0);
} else {
@@ -100,10 +100,10 @@ public class kelondroCachedRecords extends kelondroAbstractRecords implements ke
this.cacheFlush = 0;
// pre-load node cache
if ((preloadTime > 0) && (useNodeCache)) {
- long stop = System.currentTimeMillis() + preloadTime;
+ final long stop = System.currentTimeMillis() + preloadTime;
int count = 0;
try {
- Iterator<kelondroNode> i = contentNodes(preloadTime);
+ final Iterator<kelondroNode> i = contentNodes(preloadTime);
CacheNode n;
while ((System.currentTimeMillis() < stop) && (cacheGrowStatus() == 2) && (i.hasNext())) {
n = (CacheNode) i.next();
@@ -112,7 +112,7 @@ public class kelondroCachedRecords extends kelondroAbstractRecords implements ke
}
cacheHeaders.flush();
logFine("preloaded " + count + " records into cache");
- } catch (kelondroException e) {
+ } catch (final kelondroException e) {
// the contentNodes iterator had a time-out; we don't do a preload
logFine("could not preload records: " + e.getMessage());
}
@@ -121,12 +121,12 @@ public class kelondroCachedRecords extends kelondroAbstractRecords implements ke
}
int cacheGrowStatus() {
- long available = serverMemory.available();
+ final long available = serverMemory.available();
if ((cacheHeaders != null) && (available < cacheHeaders.memoryNeededForGrow())) return 0;
return cacheGrowStatus(available, memStopGrow, memStartShrink);
}
- public static final int cacheGrowStatus(long available, long stopGrow, long startShrink) {
+ public static final int cacheGrowStatus(final long available, final long stopGrow, final long startShrink) {
// returns either 0, 1 or 2:
// 0: cache is not allowed to grow, but shall shrink
// 1: cache is allowed to grow, but need not to shrink
@@ -140,7 +140,7 @@ public class kelondroCachedRecords extends kelondroAbstractRecords implements ke
return 0;
}
- public static void setCacheGrowStati(long memStopGrowNew, long memStartShrinkNew) {
+ public static void setCacheGrowStati(final long memStopGrowNew, final long memStartShrinkNew) {
memStopGrow = memStopGrowNew;
memStartShrink = memStartShrinkNew;
}
@@ -158,18 +158,18 @@ public class kelondroCachedRecords extends kelondroAbstractRecords implements ke
return recordTracker.keySet().iterator();
}
- public static final Map<String, String> memoryStats(String filename) {
+ public static final Map<String, String> memoryStats(final String filename) {
// returns a map for each file in the tracker;
// the map represents properties for each record oobjects,
// i.e. for cache memory allocation
- kelondroCachedRecords theRecord = recordTracker.get(filename);
+ final kelondroCachedRecords theRecord = recordTracker.get(filename);
return theRecord.memoryStats();
}
private final Map<String, String> memoryStats() {
// returns statistical data about this object
if (cacheHeaders == null) return null;
- HashMap<String, String> map = new HashMap<String, String>();
+ final HashMap<String, String> map = new HashMap<String, String>();
map.put("nodeChunkSize", Integer.toString(this.headchunksize + element_in_cache));
map.put("nodeCacheCount", Integer.toString(cacheHeaders.size()));
map.put("nodeCacheMem", Integer.toString(cacheHeaders.size() * (this.headchunksize + element_in_cache)));
@@ -182,7 +182,7 @@ public class kelondroCachedRecords extends kelondroAbstractRecords implements ke
return map;
}
- protected synchronized void deleteNode(kelondroHandle handle) throws IOException {
+ protected synchronized void deleteNode(final kelondroHandle handle) throws IOException {
if (cacheHeaders == null) {
super.deleteNode(handle);
} else synchronized (cacheHeaders) {
@@ -205,14 +205,14 @@ public class kelondroCachedRecords extends kelondroAbstractRecords implements ke
try {
for (int j = 0; j < headchunksize; j++)
System.out.print(Integer.toHexString(0xff & entryFile.readByte(j + seekpos(new kelondroHandle(i)))) + " ");
- } catch (IOException e) {}
+ } catch (final IOException e) {}
System.out.println();
}
} else {
System.out.println("### cache report: " + cacheHeaders.size() + " entries");
- Iterator<kelondroRow.Entry> i = cacheHeaders.rows();
+ final Iterator<kelondroRow.Entry> i = cacheHeaders.rows();
kelondroRow.Entry entry;
while (i.hasNext()) {
entry = i.next();
@@ -270,7 +270,7 @@ public class kelondroCachedRecords extends kelondroAbstractRecords implements ke
printCache();
System.out.println("--");
System.out.println("NODES");
- Iterator<kelondroNode> i = new contentNodeIterator(-1);
+ final Iterator<kelondroNode> i = new contentNodeIterator(-1);
kelondroNode n;
while (i.hasNext()) {
n = i.next();
@@ -278,7 +278,7 @@ public class kelondroCachedRecords extends kelondroAbstractRecords implements ke
}
}
- public kelondroNode newNode(kelondroHandle handle, byte[] bulk, int offset) throws IOException {
+ public kelondroNode newNode(final kelondroHandle handle, final byte[] bulk, final int offset) throws IOException {
return new CacheNode(handle, bulk, offset);
}
@@ -315,7 +315,7 @@ public class kelondroCachedRecords extends kelondroAbstractRecords implements ke
private boolean headChanged = false;
private boolean tailChanged = false;
- public CacheNode(byte[] rowinstance) throws IOException {
+ public CacheNode(final byte[] rowinstance) throws IOException {
// this initializer is used to create nodes from bulk-read byte arrays
assert ((rowinstance == null) || (rowinstance.length == ROW.objectsize)) : "bulkchunk.length = " + (rowinstance == null ? "null" : rowinstance.length) + ", ROW.width(0) = " + ROW.width(0);
this.handle = new kelondroHandle(USAGE.allocatePayload(rowinstance));
@@ -345,7 +345,7 @@ public class kelondroCachedRecords extends kelondroAbstractRecords implements ke
this.tailChanged = false; // we write the tail already during allocate
}
- public CacheNode(kelondroHandle handle, byte[] bulkchunk, int offset) throws IOException {
+ public CacheNode(final kelondroHandle handle, final byte[] bulkchunk, final int offset) throws IOException {
// this initializer is used to create nodes from bulk-read byte arrays
// if write is true, then the chunk in bulkchunk is written to the file
// othervise it is considered equal to what is stored in the file
@@ -376,11 +376,11 @@ public class kelondroCachedRecords extends kelondroAbstractRecords implements ke
this.tailChanged = changed;
}
- public CacheNode(kelondroHandle handle, boolean fillTail) throws IOException {
+ public CacheNode(final kelondroHandle handle, final boolean fillTail) throws IOException {
this(handle, null, 0, fillTail);
}
- public CacheNode(kelondroHandle handle, CacheNode parentNode, int referenceInParent, boolean fillTail) throws IOException {
+ public CacheNode(final kelondroHandle handle, final CacheNode parentNode, final int referenceInParent, boolean fillTail) throws IOException {
// this creates an entry with an pre-reserved entry position.
// values can be written using the setValues() method,
// but we expect that values are already there in the file.
@@ -396,7 +396,7 @@ public class kelondroCachedRecords extends kelondroAbstractRecords implements ke
parentNode.setOHHandle(referenceInParent, null);
parentNode.commit();
logWarning("INTERNAL ERROR, Node/init in " + filename + ": node handle index " + handle.index + " exceeds size. The bad node has been auto-fixed");
- } catch (IOException ee) {
+ } catch (final IOException ee) {
throw new kelondroException(filename, "INTERNAL ERROR, Node/init: node handle index " + handle.index + " exceeds size. It was tried to fix the bad node, but failed with an IOException: " + ee.getMessage());
}
}
@@ -457,7 +457,7 @@ public class kelondroCachedRecords extends kelondroAbstractRecords implements ke
}
}
- private void setValue(byte[] value, int valueoffset, int valuewidth, byte[] targetarray, int targetoffset) {
+ private void setValue(final byte[] value, final int valueoffset, int valuewidth, final byte[] targetarray, int targetoffset) {
if (value == null) {
while (valuewidth-- > 0) targetarray[targetoffset++] = 0;
} else {
@@ -476,14 +476,14 @@ public class kelondroCachedRecords extends kelondroAbstractRecords implements ke
return this.handle;
}
- public void setOHByte(int i, byte b) {
+ public void setOHByte(final int i, final byte b) {
if (i >= OHBYTEC) throw new IllegalArgumentException("setOHByte: wrong index " + i);
if (this.handle.index == kelondroHandle.NUL) throw new kelondroException(filename, "setOHByte: no handle assigned");
this.headChunk[i] = b;
this.headChanged = true;
}
- public void setOHHandle(int i, kelondroHandle otherhandle) {
+ public void setOHHandle(final int i, final kelondroHandle otherhandle) {
assert (i < OHHANDLEC): "setOHHandle: wrong array size " + i;
assert (this.handle.index != kelondroHandle.NUL): "setOHHandle: no handle assigned ind file" + filename;
if (otherhandle == null) {
@@ -495,20 +495,20 @@ public class kelondroCachedRecords extends kelondroAbstractRecords implements ke
this.headChanged = true;
}
- public byte getOHByte(int i) {
+ public byte getOHByte(final int i) {
if (i >= OHBYTEC) throw new IllegalArgumentException("getOHByte: wrong index " + i);
if (this.handle.index == kelondroHandle.NUL) throw new kelondroException(filename, "Cannot load OH values");
return this.headChunk[i];
}
- public kelondroHandle getOHHandle(int i) {
+ public kelondroHandle getOHHandle(final int i) {
if (this.handle.index == kelondroHandle.NUL) throw new kelondroException(filename, "Cannot load OH values");
assert (i < OHHANDLEC): "handle index out of bounds: " + i + " in file " + filename;
- int h = bytes2int(this.headChunk, OHBYTEC + 4 * i);
+ final int h = bytes2int(this.headChunk, OHBYTEC + 4 * i);
return (h == kelondroHandle.NUL) ? null : new kelondroHandle(h);
}
- public synchronized void setValueRow(byte[] row) throws IOException {
+ public synchronized void setValueRow(final byte[] row) throws IOException {
// if the index is defined, then write values directly to the file, else only to the object
if ((row != null) && (row.length != ROW.objectsize)) throw new IOException("setValueRow with wrong (" + row.length + ") row length instead correct: " + ROW.objectsize);
@@ -542,7 +542,7 @@ public class kelondroCachedRecords extends kelondroAbstractRecords implements ke
}
// create return value
- byte[] row = new byte[ROW.objectsize];
+ final byte[] row = new byte[ROW.objectsize];
// read key
System.arraycopy(headChunk, overhead, row, 0, ROW.width(0));
@@ -564,7 +564,7 @@ public class kelondroCachedRecords extends kelondroAbstractRecords implements ke
throw new kelondroException(filename, "no values to save (header missing)");
}
- boolean doCommit = this.headChanged || this.tailChanged;
+ final boolean doCommit = this.headChanged || this.tailChanged;
// save head
synchronized (entryFile) {
@@ -599,9 +599,9 @@ public class kelondroCachedRecords extends kelondroAbstractRecords implements ke
h = getOHHandle(i);
if (h == null) s = s + ":hNULL"; else s = s + ":h" + h.toString();
}
- kelondroRow.Entry content = row().newEntry(getValueRow());
+ final kelondroRow.Entry content = row().newEntry(getValueRow());
for (int i = 0; i < row().columns(); i++) s = s + ":" + ((content.empty(i)) ? "NULL" : content.getColString(i, "UTF-8").trim());
- } catch (IOException e) {
+ } catch (final IOException e) {
s = s + ":***LOAD ERROR***:" + e.getMessage();
}
return s;
diff --git a/source/de/anomic/kelondro/kelondroCloneableMapIterator.java b/source/de/anomic/kelondro/kelondroCloneableMapIterator.java
index eaf2d45d3..bc4ed2320 100644
--- a/source/de/anomic/kelondro/kelondroCloneableMapIterator.java
+++ b/source/de/anomic/kelondro/kelondroCloneableMapIterator.java
@@ -38,7 +38,7 @@ public class kelondroCloneableMapIterator<E> implements kelondroCloneableIterato
Iterator<E> iter;
- public kelondroCloneableMapIterator(TreeMap<E, ?> map, E start) {
+ public kelondroCloneableMapIterator(final TreeMap<E, ?> map, final E start) {
// map must contain eiter a byte[]/Object or a String/Object mapping.
// start must be either of type byte[] or String
// this iterator iterates then only the key elements of the map
@@ -55,7 +55,7 @@ public class kelondroCloneableMapIterator<E> implements kelondroCloneableIterato
}
@SuppressWarnings("unchecked")
- public kelondroCloneableMapIterator<E> clone(Object modifier) {
+ public kelondroCloneableMapIterator<E> clone(final Object modifier) {
return new kelondroCloneableMapIterator(map, modifier);
}
diff --git a/source/de/anomic/kelondro/kelondroCollectionIndex.java b/source/de/anomic/kelondro/kelondroCollectionIndex.java
index 0611ad2e1..2ebe66515 100644
--- a/source/de/anomic/kelondro/kelondroCollectionIndex.java
+++ b/source/de/anomic/kelondro/kelondroCollectionIndex.java
@@ -55,14 +55,14 @@ public class kelondroCollectionIndex {
private static final int EcoFSBufferSize = 1000;
kelondroIndex index;
- private int keylength;
- private File path;
- private String filenameStub;
- private File commonsPath;
- private int loadfactor;
+ private final int keylength;
+ private final File path;
+ private final String filenameStub;
+ private final File commonsPath;
+ private final int loadfactor;
private Map<String, kelondroFixedWidthArray> arrays; // Map of (partitionNumber"-"chunksize)/kelondroFixedWidthArray - Objects
- private kelondroRow payloadrow; // definition of the payload (chunks inside the collections)
- private int maxPartitions; // this is the maxmimum number of array files
+ private final kelondroRow payloadrow; // definition of the payload (chunks inside the collections)
+ private final int maxPartitions; // this is the maxmimum number of array files
private static final int idx_col_key = 0; // the index
private static final int idx_col_chunksize = 1; // chunksize (number of bytes in a single chunk, needed for migration option)
@@ -73,7 +73,7 @@ public class kelondroCollectionIndex {
private static final int idx_col_lastread = 6; // a time stamp, update time in days since 1.1.2000
private static final int idx_col_lastwrote = 7; // a time stamp, update time in days since 1.1.2000
- private static kelondroRow indexRow(int keylength, kelondroByteOrder payloadOrder) {
+ private static kelondroRow indexRow(final int keylength, final kelondroByteOrder payloadOrder) {
return new kelondroRow(
"byte[] key-" + keylength + "," +
"int chunksize-4 {b256}," +
@@ -91,27 +91,27 @@ public class kelondroCollectionIndex {
return this.payloadrow;
}
- private static String fillZ(String s, int len) {
+ private static String fillZ(String s, final int len) {
while (s.length() < len) s = "0" + s;
return s;
}
- private static File arrayFile(File path, String filenameStub, int loadfactor, int chunksize, int partitionNumber, int serialNumber) {
- String lf = fillZ(Integer.toHexString(loadfactor).toUpperCase(), 2);
- String cs = fillZ(Integer.toHexString(chunksize).toUpperCase(), 4);
- String pn = fillZ(Integer.toHexString(partitionNumber).toUpperCase(), 2);
- String sn = fillZ(Integer.toHexString(serialNumber).toUpperCase(), 2);
+ private static File arrayFile(final File path, final String filenameStub, final int loadfactor, final int chunksize, final int partitionNumber, final int serialNumber) {
+ final String lf = fillZ(Integer.toHexString(loadfactor).toUpperCase(), 2);
+ final String cs = fillZ(Integer.toHexString(chunksize).toUpperCase(), 4);
+ final String pn = fillZ(Integer.toHexString(partitionNumber).toUpperCase(), 2);
+ final String sn = fillZ(Integer.toHexString(serialNumber).toUpperCase(), 2);
return new File(path, filenameStub + "." + lf + "." + cs + "." + pn + "." + sn + ".kca"); // kelondro collection array
}
- private static File propertyFile(File path, String filenameStub, int loadfactor, int chunksize) {
- String lf = fillZ(Integer.toHexString(loadfactor).toUpperCase(), 2);
- String cs = fillZ(Integer.toHexString(chunksize).toUpperCase(), 4);
+ private static File propertyFile(final File path, final String filenameStub, final int loadfactor, final int chunksize) {
+ final String lf = fillZ(Integer.toHexString(loadfactor).toUpperCase(), 2);
+ final String cs = fillZ(Integer.toHexString(chunksize).toUpperCase(), 4);
return new File(path, filenameStub + "." + lf + "." + cs + ".properties");
}
- public kelondroCollectionIndex(File path, String filenameStub, int keyLength, kelondroByteOrder indexOrder,
- int loadfactor, int maxpartitions, kelondroRow rowdef) throws IOException {
+ public kelondroCollectionIndex(final File path, final String filenameStub, final int keyLength, final kelondroByteOrder indexOrder,
+ final int loadfactor, final int maxpartitions, final kelondroRow rowdef) throws IOException {
// the buffersize is number of bytes that are only used if the kelondroFlexTable is backed up with a kelondroTree
this.path = path;
this.filenameStub = filenameStub;
@@ -121,7 +121,7 @@ public class kelondroCollectionIndex {
this.maxPartitions = maxpartitions;
this.commonsPath = new File(path, filenameStub + "." + fillZ(Integer.toHexString(rowdef.objectsize).toUpperCase(), 4) + ".commons");
this.commonsPath.mkdirs();
- File f = new File(path, filenameStub + ".index");
+ final File f = new File(path, filenameStub + ".index");
if (f.exists()) {
serverLog.logFine("STARTUP", "OPENING COLLECTION INDEX");
@@ -132,28 +132,28 @@ public class kelondroCollectionIndex {
openAllArrayFiles(false, indexOrder);
} else {
// calculate initialSpace
- String[] list = this.path.list();
+ final String[] list = this.path.list();
kelondroFixedWidthArray array;
int initialSpace = 0;
for (int i = 0; i < list.length; i++) if (list[i].endsWith(".kca")) {
// open array
- int pos = list[i].indexOf('.');
+ final int pos = list[i].indexOf('.');
if (pos < 0) continue;
- int partitionNumber = Integer.parseInt(list[i].substring(pos + 9, pos + 11), 16);
- int serialNumber = Integer.parseInt(list[i].substring(pos + 12, pos + 14), 16);
+ final int partitionNumber = Integer.parseInt(list[i].substring(pos + 9, pos + 11), 16);
+ final int serialNumber = Integer.parseInt(list[i].substring(pos + 12, pos + 14), 16);
try {
array = openArrayFile(partitionNumber, serialNumber, indexOrder, true);
initialSpace += array.size();
array.close();
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
continue;
}
}
serverLog.logFine("STARTUP", "STARTED INITIALIZATION OF NEW COLLECTION INDEX WITH " + initialSpace + " ENTRIES. THIS WILL TAKE SOME TIME. " + (serverMemory.available() / 1024 / 1024) + "MB AVAILABLE.");
- kelondroRow indexRowdef = indexRow(keyLength, indexOrder);
- long necessaryRAM4fullTable = minimumRAM4Eco + (indexRowdef.objectsize + 4) * initialSpace * 3 / 2;
- long necessaryRAM4fullIndex = minimumRAM4Eco + (indexRowdef.primaryKeyLength + 4) * initialSpace * 3 / 2;
+ final kelondroRow indexRowdef = indexRow(keyLength, indexOrder);
+ final long necessaryRAM4fullTable = minimumRAM4Eco + (indexRowdef.objectsize + 4) * initialSpace * 3 / 2;
+ final long necessaryRAM4fullIndex = minimumRAM4Eco + (indexRowdef.primaryKeyLength + 4) * initialSpace * 3 / 2;
// initialize (new generation) index table from file
if (serverMemory.request(necessaryRAM4fullTable, false)) {
@@ -172,29 +172,29 @@ public class kelondroCollectionIndex {
public void clear() throws IOException {
index.clear();
- for (kelondroFixedWidthArray array: arrays.values()) {
+ for (final kelondroFixedWidthArray array: arrays.values()) {
array.clear();
}
}
- private void openAllArrayFiles(boolean indexGeneration, kelondroByteOrder indexOrder) throws IOException {
+ private void openAllArrayFiles(final boolean indexGeneration, final kelondroByteOrder indexOrder) throws IOException {
- String[] list = this.path.list();
+ final String[] list = this.path.list();
kelondroFixedWidthArray array;
- kelondroRow irow = indexRow(keylength, indexOrder);
- int t = kelondroRowCollection.daysSince2000(System.currentTimeMillis());
+ final kelondroRow irow = indexRow(keylength, indexOrder);
+ final int t = kelondroRowCollection.daysSince2000(System.currentTimeMillis());
for (int i = 0; i < list.length; i++) if (list[i].endsWith(".kca")) {
// open array
- int pos = list[i].indexOf('.');
+ final int pos = list[i].indexOf('.');
if (pos < 0) continue;
- int chunksize = Integer.parseInt(list[i].substring(pos + 4, pos + 8), 16);
- int partitionNumber = Integer.parseInt(list[i].substring(pos + 9, pos + 11), 16);
- int serialNumber = Integer.parseInt(list[i].substring(pos + 12, pos + 14), 16);
+ final int chunksize = Integer.parseInt(list[i].substring(pos + 4, pos + 8), 16);
+ final int partitionNumber = Integer.parseInt(list[i].substring(pos + 9, pos + 11), 16);
+ final int serialNumber = Integer.parseInt(list[i].substring(pos + 12, pos + 14), 16);
try {
array = openArrayFile(partitionNumber, serialNumber, indexOrder, true);
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
continue;
}
@@ -206,9 +206,9 @@ public class kelondroCollectionIndex {
// loop over all elements in array and create index entry for each row
kelondroRow.EntryIndex aentry;
kelondroRow.Entry ientry;
- Iterator<EntryIndex> ei = array.contentRows(-1);
+ final Iterator<EntryIndex> ei = array.contentRows(-1);
byte[] key;
- long start = System.currentTimeMillis();
+ final long start = System.currentTimeMillis();
long lastlog = start;
int count = 0;
while (ei.hasNext()) {
@@ -241,7 +241,7 @@ public class kelondroCollectionIndex {
int partition, maxpartition;
kelondroRow.Entry entry, maxentry;
int doublecount = 0;
- for (kelondroRowCollection doubleset: index.removeDoubles()) {
+ for (final kelondroRowCollection doubleset: index.removeDoubles()) {
// for each entry in doubleset choose one which we want to keep
rowiter = doubleset.rows();
maxentry = null;
@@ -263,22 +263,22 @@ public class kelondroCollectionIndex {
if (doublecount > 0) serverLog.logWarning("STARTUP", "found " + doublecount + " RWI entries with references to several collections. All have been fixed (zombies still exists).");
}
- private kelondroIndex openIndexFile(File path, String filenameStub, kelondroByteOrder indexOrder,
- int loadfactor, kelondroRow rowdef, int initialSpace) throws IOException {
+ private kelondroIndex openIndexFile(final File path, final String filenameStub, final kelondroByteOrder indexOrder,
+ final int loadfactor, final kelondroRow rowdef, final int initialSpace) throws IOException {
// open/create index table
- File f = new File(path, filenameStub + ".index");
- kelondroRow indexRowdef = indexRow(keylength, indexOrder);
+ final File f = new File(path, filenameStub + ".index");
+ final kelondroRow indexRowdef = indexRow(keylength, indexOrder);
kelondroIndex theindex;
if (f.isDirectory()) {
// use a flextable
theindex = new kelondroCache(new kelondroFlexTable(path, filenameStub + ".index", indexRowdef, initialSpace, true));
// save/check property file for this array
- File propfile = propertyFile(path, filenameStub, loadfactor, rowdef.objectsize);
+ final File propfile = propertyFile(path, filenameStub, loadfactor, rowdef.objectsize);
Map<String, String> props = new HashMap<String, String>();
if (propfile.exists()) {
props = serverFileUtils.loadHashMap(propfile);
- String stored_rowdef = props.get("rowdef");
+ final String stored_rowdef = props.get("rowdef");
if ((stored_rowdef == null) || (!(rowdef.subsumes(new kelondroRow(stored_rowdef, rowdef.objectOrder, 0))))) {
System.out.println("FATAL ERROR: stored rowdef '" + stored_rowdef + "' does not match with new rowdef '" +
rowdef + "' for array cluster '" + path + "/" + filenameStub + "'");
@@ -289,9 +289,9 @@ public class kelondroCollectionIndex {
serverFileUtils.saveMap(propfile, props, "CollectionIndex properties");
} else {
// open a ecotable
- long records = f.length() / indexRowdef.objectsize;
- long necessaryRAM4fullTable = minimumRAM4Eco + (indexRowdef.objectsize + 4) * records * 3 / 2;
- boolean fullCache = serverMemory.request(necessaryRAM4fullTable, false);
+ final long records = f.length() / indexRowdef.objectsize;
+ final long necessaryRAM4fullTable = minimumRAM4Eco + (indexRowdef.objectsize + 4) * records * 3 / 2;
+ final boolean fullCache = serverMemory.request(necessaryRAM4fullTable, false);
if (fullCache) {
theindex = new kelondroEcoTable(f, indexRowdef, kelondroEcoTable.tailCacheUsageAuto, EcoFSBufferSize, initialSpace);
//if (!((kelondroEcoTable) theindex).usesFullCopy()) theindex = new kelondroCache(theindex);
@@ -303,28 +303,28 @@ public class kelondroCollectionIndex {
return theindex;
}
- private kelondroFixedWidthArray openArrayFile(int partitionNumber, int serialNumber, kelondroByteOrder indexOrder, boolean create) throws IOException {
- File f = arrayFile(path, filenameStub, loadfactor, payloadrow.objectsize, partitionNumber, serialNumber);
- int load = arrayCapacity(partitionNumber);
- kelondroRow rowdef = new kelondroRow(
+ private kelondroFixedWidthArray openArrayFile(final int partitionNumber, final int serialNumber, final kelondroByteOrder indexOrder, final boolean create) throws IOException {
+ final File f = arrayFile(path, filenameStub, loadfactor, payloadrow.objectsize, partitionNumber, serialNumber);
+ final int load = arrayCapacity(partitionNumber);
+ final kelondroRow rowdef = new kelondroRow(
"byte[] key-" + keylength + "," +
"byte[] collection-" + (kelondroRowCollection.exportOverheadSize + load * this.payloadrow.objectsize),
indexOrder,
0
);
if ((!(f.exists())) && (!create)) return null;
- kelondroFixedWidthArray a = new kelondroFixedWidthArray(f, rowdef, 0);
+ final kelondroFixedWidthArray a = new kelondroFixedWidthArray(f, rowdef, 0);
serverLog.logFine("STARTUP", "opened array file " + f + " with " + a.size() + " RWIs");
return a;
}
- private kelondroFixedWidthArray getArray(int partitionNumber, int serialNumber, kelondroByteOrder indexOrder, int chunksize) {
- String accessKey = partitionNumber + "-" + chunksize;
+ private kelondroFixedWidthArray getArray(final int partitionNumber, final int serialNumber, final kelondroByteOrder indexOrder, final int chunksize) {
+ final String accessKey = partitionNumber + "-" + chunksize;
kelondroFixedWidthArray array = arrays.get(accessKey);
if (array != null) return array;
try {
array = openArrayFile(partitionNumber, serialNumber, indexOrder, true);
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
return null;
}
@@ -332,14 +332,14 @@ public class kelondroCollectionIndex {
return array;
}
- private int arrayCapacity(int arrayCounter) {
+ private int arrayCapacity(final int arrayCounter) {
if (arrayCounter < 0) return 0;
int load = this.loadfactor;
for (int i = 0; i < arrayCounter; i++) load = load * this.loadfactor;
return load;
}
- private int arrayIndex(int requestedCapacity) throws kelondroOutOfLimitsException{
+ private int arrayIndex(final int requestedCapacity) throws kelondroOutOfLimitsException{
// the requestedCapacity is the number of wanted chunks
int load = 1, i = 0;
while (true) {
@@ -365,30 +365,30 @@ public class kelondroCollectionIndex {
}
private void array_remove(
- int oldPartitionNumber, int serialNumber, int chunkSize,
- int oldRownumber) throws IOException {
+ final int oldPartitionNumber, final int serialNumber, final int chunkSize,
+ final int oldRownumber) throws IOException {
// we need a new slot, that means we must first delete the old entry
// find array file
- kelondroFixedWidthArray array = getArray(oldPartitionNumber, serialNumber, index.row().objectOrder, chunkSize);
+ final kelondroFixedWidthArray array = getArray(oldPartitionNumber, serialNumber, index.row().objectOrder, chunkSize);
// delete old entry
array.remove(oldRownumber);
}
private kelondroRow.Entry array_new(
- byte[] key, kelondroRowCollection collection) throws IOException {
+ final byte[] key, final kelondroRowCollection collection) throws IOException {
// the collection is new
- int partitionNumber = arrayIndex(collection.size());
- kelondroRow.Entry indexrow = index.row().newEntry();
- kelondroFixedWidthArray array = getArray(partitionNumber, serialNumber, index.row().objectOrder, this.payloadrow.objectsize);
+ final int partitionNumber = arrayIndex(collection.size());
+ final kelondroRow.Entry indexrow = index.row().newEntry();
+ final kelondroFixedWidthArray array = getArray(partitionNumber, serialNumber, index.row().objectOrder, this.payloadrow.objectsize);
// define row
- kelondroRow.Entry arrayEntry = array.row().newEntry();
+ final kelondroRow.Entry arrayEntry = array.row().newEntry();
arrayEntry.setCol(0, key);
arrayEntry.setCol(1, collection.exportCollection());
// write a new entry in this array
- int newRowNumber = array.add(arrayEntry);
+ final int newRowNumber = array.add(arrayEntry);
// store the new row number in the index
indexrow.setCol(idx_col_key, key);
@@ -405,19 +405,19 @@ public class kelondroCollectionIndex {
}
private void array_add(
- byte[] key, kelondroRowCollection collection, kelondroRow.Entry indexrow,
- int partitionNumber, int serialNumber, int chunkSize) throws IOException {
+ final byte[] key, final kelondroRowCollection collection, final kelondroRow.Entry indexrow,
+ final int partitionNumber, final int serialNumber, final int chunkSize) throws IOException {
// write a new entry in the other array
- kelondroFixedWidthArray array = getArray(partitionNumber, serialNumber, index.row().objectOrder, chunkSize);
+ final kelondroFixedWidthArray array = getArray(partitionNumber, serialNumber, index.row().objectOrder, chunkSize);
// define new row
- kelondroRow.Entry arrayEntry = array.row().newEntry();
+ final kelondroRow.Entry arrayEntry = array.row().newEntry();
arrayEntry.setCol(0, key);
arrayEntry.setCol(1, collection.exportCollection());
// write a new entry in this array
- int rowNumber = array.add(arrayEntry);
+ final int rowNumber = array.add(arrayEntry);
// store the new row number in the index
indexrow.setCol(idx_col_chunkcount, collection.size());
@@ -429,16 +429,16 @@ public class kelondroCollectionIndex {
}
private void array_replace(
- byte[] key, kelondroRowCollection collection, kelondroRow.Entry indexrow,
- int partitionNumber, int serialNumber, int chunkSize,
- int rowNumber) throws IOException {
+ final byte[] key, final kelondroRowCollection collection, final kelondroRow.Entry indexrow,
+ final int partitionNumber, final int serialNumber, final int chunkSize,
+ final int rowNumber) throws IOException {
// we don't need a new slot, just write collection into the old one
// find array file
- kelondroFixedWidthArray array = getArray(partitionNumber, serialNumber, index.row().objectOrder, chunkSize);
+ final kelondroFixedWidthArray array = getArray(partitionNumber, serialNumber, index.row().objectOrder, chunkSize);
// define new row
- kelondroRow.Entry arrayEntry = array.row().newEntry();
+ final kelondroRow.Entry arrayEntry = array.row().newEntry();
arrayEntry.setCol(0, key);
arrayEntry.setCol(1, collection.exportCollection());
@@ -454,7 +454,7 @@ public class kelondroCollectionIndex {
// after calling this method there must be a index.put(indexrow);
}
- public synchronized void put(byte[] key, kelondroRowCollection collection) throws IOException, kelondroOutOfLimitsException {
+ public synchronized void put(final byte[] key, final kelondroRowCollection collection) throws IOException, kelondroOutOfLimitsException {
assert (key != null);
assert (collection != null);
assert (collection.size() != 0);
@@ -474,12 +474,12 @@ public class kelondroCollectionIndex {
// overwrite the old collection
// read old information
//int oldchunksize = (int) indexrow.getColLong(idx_col_chunksize); // needed only for migration
- int oldchunkcount = (int) indexrow.getColLong(idx_col_chunkcount); // the number if rows in the collection
- int oldrownumber = (int) indexrow.getColLong(idx_col_indexpos); // index of the entry in array
- int oldPartitionNumber = indexrow.getColByte(idx_col_clusteridx); // points to array file
+ final int oldchunkcount = (int) indexrow.getColLong(idx_col_chunkcount); // the number if rows in the collection
+ final int oldrownumber = (int) indexrow.getColLong(idx_col_indexpos); // index of the entry in array
+ final int oldPartitionNumber = indexrow.getColByte(idx_col_clusteridx); // points to array file
assert (oldPartitionNumber >= arrayIndex(oldchunkcount));
- int newPartitionNumber = arrayIndex(collection.size());
+ final int newPartitionNumber = arrayIndex(collection.size());
// see if we need new space or if we can overwrite the old space
if (oldPartitionNumber == newPartitionNumber) {
@@ -502,9 +502,9 @@ public class kelondroCollectionIndex {
index.put(indexrow); // write modified indexrow
}
- public synchronized void merge(indexContainer container) throws IOException, kelondroOutOfLimitsException {
+ public synchronized void merge(final indexContainer container) throws IOException, kelondroOutOfLimitsException {
if ((container == null) || (container.size() == 0)) return;
- byte[] key = container.getWordHash().getBytes();
+ final byte[] key = container.getWordHash().getBytes();
// first find an old entry, if one exists
kelondroRow.Entry indexrow = index.get(key);
@@ -514,15 +514,15 @@ public class kelondroCollectionIndex {
} else {
// merge with the old collection
// attention! this modifies the indexrow entry which must be written with index.put(indexrow) afterwards!
- kelondroRowCollection collection = container;
+ final kelondroRowCollection collection = container;
// read old information
- int oldchunksize = (int) indexrow.getColLong(idx_col_chunksize); // needed only for migration
- int oldchunkcount = (int) indexrow.getColLong(idx_col_chunkcount); // the number if rows in the collection
- int oldrownumber = (int) indexrow.getColLong(idx_col_indexpos); // index of the entry in array
- int oldPartitionNumber = indexrow.getColByte(idx_col_clusteridx); // points to array file
+ final int oldchunksize = (int) indexrow.getColLong(idx_col_chunksize); // needed only for migration
+ final int oldchunkcount = (int) indexrow.getColLong(idx_col_chunkcount); // the number if rows in the collection
+ final int oldrownumber = (int) indexrow.getColLong(idx_col_indexpos); // index of the entry in array
+ final int oldPartitionNumber = indexrow.getColByte(idx_col_clusteridx); // points to array file
assert (oldPartitionNumber >= arrayIndex(oldchunkcount)) : "oldPartitionNumber = " + oldPartitionNumber + ", arrayIndex(oldchunkcount) = " + arrayIndex(oldchunkcount);
- int oldSerialNumber = 0;
+ final int oldSerialNumber = 0;
// load the old collection and join it
collection.addAllUnique(getwithparams(indexrow, oldchunksize, oldchunkcount, oldPartitionNumber, oldrownumber, oldSerialNumber, false));
@@ -538,7 +538,7 @@ public class kelondroCollectionIndex {
}
// determine new partition location
- int newPartitionNumber = arrayIndex(collection.size());
+ final int newPartitionNumber = arrayIndex(collection.size());
// see if we need new space or if we can overwrite the old space
if (oldPartitionNumber == newPartitionNumber) {
@@ -564,16 +564,16 @@ public class kelondroCollectionIndex {
}
}
- private void shrinkCollection(byte[] key, kelondroRowCollection collection, int targetSize) {
+ private void shrinkCollection(final byte[] key, final kelondroRowCollection collection, final int targetSize) {
//TODO Remove timing before release
// removes entries from collection
// the removed entries are stored in a 'commons' dump file
if (key.length != 12) return;
// check if the collection is already small enough
- int oldsize = collection.size();
+ final int oldsize = collection.size();
if (oldsize <= targetSize) return;
- kelondroRowSet newcommon = new kelondroRowSet(collection.rowdef, 0);
+ final kelondroRowSet newcommon = new kelondroRowSet(collection.rowdef, 0);
long sadd1 = 0, srem1 = 0, sadd2 = 0, srem2 = 0, tot1 = 0, tot2 = 0;
long t1 = 0, t2 = 0;
@@ -594,11 +594,11 @@ public class kelondroCollectionIndex {
srem1 += System.currentTimeMillis() - t2;
}
}
- int firstnewcommon = newcommon.size();
+ final int firstnewcommon = newcommon.size();
tot1 = System.currentTimeMillis() - t1;
// check if we shrinked enough
- Random rand = new Random(System.currentTimeMillis());
+ final Random rand = new Random(System.currentTimeMillis());
t1 = System.currentTimeMillis();
while (collection.size() > targetSize) {
// now delete randomly more entries from the survival collection
@@ -624,46 +624,46 @@ public class kelondroCollectionIndex {
// finally dump the removed entries to a file
newcommon.sort();
- SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
+ final SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
- String filename = serverCodings.encodeHex(kelondroBase64Order.enhancedCoder.decode(new String(key), "de.anomic.kelondro.kelondroCollectionIndex.shrinkCollection(...)")) + "_" + formatter.format(new Date()) + ".collection";
- File storagePath = new File(commonsPath, filename.substring(0, 2)); // make a subpath
+ final String filename = serverCodings.encodeHex(kelondroBase64Order.enhancedCoder.decode(new String(key), "de.anomic.kelondro.kelondroCollectionIndex.shrinkCollection(...)")) + "_" + formatter.format(new Date()) + ".collection";
+ final File storagePath = new File(commonsPath, filename.substring(0, 2)); // make a subpath
storagePath.mkdirs();
- File file = new File(storagePath, filename);
+ final File file = new File(storagePath, filename);
try {
newcommon.saveCollection(file);
serverLog.logInfo("kelondroCollectionIndex", "dumped common word " + new String(key) + " to " + file.toString() + "; size = " + newcommon.size());
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
serverLog.logWarning("kelondroCollectionIndex", "failed to dump common word " + new String(key) + " to " + file.toString() + "; size = " + newcommon.size());
}
}
- public synchronized int remove(byte[] key, Set<String> removekeys) throws IOException, kelondroOutOfLimitsException {
+ public synchronized int remove(final byte[] key, final Set<String> removekeys) throws IOException, kelondroOutOfLimitsException {
if ((removekeys == null) || (removekeys.size() == 0)) return 0;
// first find an old entry, if one exists
- kelondroRow.Entry indexrow = index.get(key);
+ final kelondroRow.Entry indexrow = index.get(key);
if (indexrow == null) return 0;
// overwrite the old collection
// read old information
- int oldchunksize = (int) indexrow.getColLong(idx_col_chunksize); // needed only for migration
- int oldchunkcount = (int) indexrow.getColLong(idx_col_chunkcount); // the number if rows in the collection
- int oldrownumber = (int) indexrow.getColLong(idx_col_indexpos); // index of the entry in array
- int oldPartitionNumber = indexrow.getColByte(idx_col_clusteridx); // points to array file
+ final int oldchunksize = (int) indexrow.getColLong(idx_col_chunksize); // needed only for migration
+ final int oldchunkcount = (int) indexrow.getColLong(idx_col_chunkcount); // the number if rows in the collection
+ final int oldrownumber = (int) indexrow.getColLong(idx_col_indexpos); // index of the entry in array
+ final int oldPartitionNumber = indexrow.getColByte(idx_col_clusteridx); // points to array file
assert (oldPartitionNumber >= arrayIndex(oldchunkcount));
int removed = 0;
assert (removekeys != null);
// load the old collection and remove keys
- kelondroRowSet oldcollection = getwithparams(indexrow, oldchunksize, oldchunkcount, oldPartitionNumber, oldrownumber, serialNumber, false);
+ final kelondroRowSet oldcollection = getwithparams(indexrow, oldchunksize, oldchunkcount, oldPartitionNumber, oldrownumber, serialNumber, false);
// remove the keys from the set
- Iterator<String> i = removekeys.iterator();
+ final Iterator<String> i = removekeys.iterator();
while (i.hasNext()) {
if (oldcollection.remove(i.next().getBytes()) != null) removed++;
}
@@ -679,7 +679,7 @@ public class kelondroCollectionIndex {
return removed;
}
- int newPartitionNumber = arrayIndex(oldcollection.size());
+ final int newPartitionNumber = arrayIndex(oldcollection.size());
// see if we need new space or if we can overwrite the old space
if (oldPartitionNumber == newPartitionNumber) {
@@ -699,57 +699,57 @@ public class kelondroCollectionIndex {
return removed;
}
- public synchronized int indexSize(byte[] key) throws IOException {
- kelondroRow.Entry indexrow = index.get(key);
+ public synchronized int indexSize(final byte[] key) throws IOException {
+ final kelondroRow.Entry indexrow = index.get(key);
if (indexrow == null) return 0;
return (int) indexrow.getColLong(idx_col_chunkcount);
}
- public synchronized boolean has(byte[] key) throws IOException {
+ public synchronized boolean has(final byte[] key) throws IOException {
return index.has(key);
}
- public synchronized kelondroRowSet get(byte[] key) throws IOException {
+ public synchronized kelondroRowSet get(final byte[] key) throws IOException {
// find an entry, if one exists
- kelondroRow.Entry indexrow = index.get(key);
+ final kelondroRow.Entry indexrow = index.get(key);
if (indexrow == null) return null;
- kelondroRowSet col = getdelete(indexrow, false);
+ final kelondroRowSet col = getdelete(indexrow, false);
assert (col != null);
return col;
}
- public synchronized kelondroRowSet delete(byte[] key) throws IOException {
+ public synchronized kelondroRowSet delete(final byte[] key) throws IOException {
// find an entry, if one exists
- kelondroRow.Entry indexrow = index.remove(key);
+ final kelondroRow.Entry indexrow = index.remove(key);
if (indexrow == null) return null;
- kelondroRowSet removedCollection = getdelete(indexrow, true);
+ final kelondroRowSet removedCollection = getdelete(indexrow, true);
assert (removedCollection != null);
return removedCollection;
}
- protected kelondroRowSet getdelete(kelondroRow.Entry indexrow, boolean remove) throws IOException {
+ protected kelondroRowSet getdelete(final kelondroRow.Entry indexrow, final boolean remove) throws IOException {
// call this only within a synchronized(index) environment
// read values
- int chunksize = (int) indexrow.getColLong(idx_col_chunksize);
- int chunkcount = (int) indexrow.getColLong(idx_col_chunkcount);
- int rownumber = (int) indexrow.getColLong(idx_col_indexpos);
- int partitionnumber = indexrow.getColByte(idx_col_clusteridx);
+ final int chunksize = (int) indexrow.getColLong(idx_col_chunksize);
+ final int chunkcount = (int) indexrow.getColLong(idx_col_chunkcount);
+ final int rownumber = (int) indexrow.getColLong(idx_col_indexpos);
+ final int partitionnumber = indexrow.getColByte(idx_col_clusteridx);
assert(partitionnumber >= arrayIndex(chunkcount)) : "partitionnumber = " + partitionnumber + ", arrayIndex(chunkcount) = " + arrayIndex(chunkcount);
- int serialnumber = 0;
+ final int serialnumber = 0;
return getwithparams(indexrow, chunksize, chunkcount, partitionnumber, rownumber, serialnumber, remove);
}
- private synchronized kelondroRowSet getwithparams(kelondroRow.Entry indexrow, int chunksize, int chunkcount, int clusteridx, int rownumber, int serialnumber, boolean remove) throws IOException {
+ private synchronized kelondroRowSet getwithparams(final kelondroRow.Entry indexrow, final int chunksize, final int chunkcount, final int clusteridx, final int rownumber, final int serialnumber, final boolean remove) throws IOException {
// open array entry
- kelondroFixedWidthArray array = getArray(clusteridx, serialnumber, index.row().objectOrder, chunksize);
- kelondroRow.Entry arrayrow = array.get(rownumber);
+ final kelondroFixedWidthArray array = getArray(clusteridx, serialnumber, index.row().objectOrder, chunksize);
+ final kelondroRow.Entry arrayrow = array.get(rownumber);
if (arrayrow == null) throw new kelondroException(arrayFile(this.path, this.filenameStub, this.loadfactor, chunksize, clusteridx, serialnumber).toString(), "array does not contain expected row");
// read the row and define a collection
- byte[] indexkey = indexrow.getColBytes(idx_col_key);
- byte[] arraykey = arrayrow.getColBytes(0);
+ final byte[] indexkey = indexrow.getColBytes(idx_col_key);
+ final byte[] arraykey = arrayrow.getColBytes(0);
if (!(index.row().objectOrder.wellformed(arraykey))) {
// cleanup for a bad bug that corrupted the database
index.remove(indexkey); // the RowCollection must be considered lost
@@ -757,12 +757,12 @@ public class kelondroCollectionIndex {
serverLog.logSevere("kelondroCollectionIndex." + array.filename, "lost a RowCollection because of a bad arraykey");
return new kelondroRowSet(this.payloadrow, 0);
}
- kelondroRowSet collection = new kelondroRowSet(this.payloadrow, arrayrow, 1); // FIXME: this does not yet work with different rowdef in case of several rowdef.objectsize()
+ final kelondroRowSet collection = new kelondroRowSet(this.payloadrow, arrayrow, 1); // FIXME: this does not yet work with different rowdef in case of several rowdef.objectsize()
if ((!(index.row().objectOrder.wellformed(indexkey))) || (index.row().objectOrder.compare(arraykey, indexkey) != 0)) {
// check if we got the right row; this row is wrong. Fix it:
index.remove(indexkey); // the wrong row cannot be fixed
// store the row number in the index; this may be a double-entry, but better than nothing
- kelondroRow.Entry indexEntry = index.row().newEntry();
+ final kelondroRow.Entry indexEntry = index.row().newEntry();
indexEntry.setCol(idx_col_key, arrayrow.getColBytes(0));
indexEntry.setCol(idx_col_chunksize, this.payloadrow.objectsize);
indexEntry.setCol(idx_col_chunkcount, collection.size());
@@ -774,7 +774,7 @@ public class kelondroCollectionIndex {
index.put(indexEntry);
serverLog.logSevere("kelondroCollectionIndex." + array.filename, "array contains wrong row '" + new String(arrayrow.getColBytes(0)) + "', expected is '" + new String(indexrow.getColBytes(idx_col_key)) + "', the row has been fixed");
}
- int chunkcountInArray = collection.size();
+ final int chunkcountInArray = collection.size();
if (chunkcountInArray != chunkcount) {
// fix the entry in index
indexrow.setCol(idx_col_chunkcount, chunkcountInArray);
@@ -785,11 +785,11 @@ public class kelondroCollectionIndex {
return collection;
}
- public synchronized Iterator<Object[]> keycollections(byte[] startKey, byte[] secondKey, boolean rot) {
+ public synchronized Iterator<Object[]> keycollections(final byte[] startKey, final byte[] secondKey, final boolean rot) {
// returns an iteration of {byte[], kelondroRowSet} Objects
try {
return new keycollectionIterator(startKey, secondKey, rot);
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
return null;
}
@@ -799,9 +799,9 @@ public class kelondroCollectionIndex {
Iterator<kelondroRow.Entry> indexRowIterator;
- public keycollectionIterator(byte[] startKey, byte[] secondKey, boolean rot) throws IOException {
+ public keycollectionIterator(final byte[] startKey, final byte[] secondKey, final boolean rot) throws IOException {
// iterator of {byte[], kelondroRowSet} Objects
- kelondroCloneableIterator<kelondroRow.Entry> i = index.rows(true, startKey);
+ final kelondroCloneableIterator<kelondroRow.Entry> i = index.rows(true, startKey);
indexRowIterator = (rot) ? new kelondroRotateIterator<kelondroRow.Entry>(i, secondKey, index.size()) : i;
}
@@ -810,12 +810,12 @@ public class kelondroCollectionIndex {
}
public Object[] next() {
- kelondroRow.Entry indexrow = indexRowIterator.next();
+ final kelondroRow.Entry indexrow = indexRowIterator.next();
assert (indexrow != null);
if (indexrow == null) return null;
try {
return new Object[]{indexrow.getColBytes(0), getdelete(indexrow, false)};
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
return null;
}
@@ -829,20 +829,20 @@ public class kelondroCollectionIndex {
public synchronized void close() {
this.index.close();
- Iterator<kelondroFixedWidthArray> i = arrays.values().iterator();
+ final Iterator<kelondroFixedWidthArray> i = arrays.values().iterator();
while (i.hasNext()) i.next().close();
}
- public static void main(String[] args) {
+ public static void main(final String[] args) {
// define payload structure
- kelondroRow rowdef = new kelondroRow("byte[] a-10, byte[] b-80", kelondroNaturalOrder.naturalOrder, 0);
+ final kelondroRow rowdef = new kelondroRow("byte[] a-10, byte[] b-80", kelondroNaturalOrder.naturalOrder, 0);
- File path = new File(args[0]);
- String filenameStub = args[1];
+ final File path = new File(args[0]);
+ final String filenameStub = args[1];
try {
// initialize collection index
- kelondroCollectionIndex collectionIndex = new kelondroCollectionIndex(
+ final kelondroCollectionIndex collectionIndex = new kelondroCollectionIndex(
path, filenameStub, 9 /*keyLength*/,
kelondroNaturalOrder.naturalOrder,
4 /*loadfactor*/, 7, rowdef);
@@ -872,10 +872,10 @@ public class kelondroCollectionIndex {
// printout of index
collectionIndex.close();
- kelondroFlexTable index = new kelondroFlexTable(path, filenameStub + ".index", kelondroCollectionIndex.indexRow(9, kelondroNaturalOrder.naturalOrder), 0, true);
+ final kelondroFlexTable index = new kelondroFlexTable(path, filenameStub + ".index", kelondroCollectionIndex.indexRow(9, kelondroNaturalOrder.naturalOrder), 0, true);
index.print();
index.close();
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
diff --git a/source/de/anomic/kelondro/kelondroColumn.java b/source/de/anomic/kelondro/kelondroColumn.java
index 78eef616a..de5ba05f1 100644
--- a/source/de/anomic/kelondro/kelondroColumn.java
+++ b/source/de/anomic/kelondro/kelondroColumn.java
@@ -44,7 +44,7 @@ public class kelondroColumn {
public int celltype, cellwidth, encoder;
public String nickname, description;
- public kelondroColumn(String nickname, int celltype, int encoder, int cellwidth, String description) {
+ public kelondroColumn(final String nickname, final int celltype, final int encoder, final int cellwidth, final String description) {
this.celltype = celltype;
this.cellwidth = cellwidth;
this.encoder = encoder;
@@ -112,7 +112,7 @@ public class kelondroColumn {
if (p < 0) {
// if the cell was defined with a type, we dont need to give an explicit with definition
if (this.cellwidth < 0) throw new kelondroException("kelondroColumn - no cell width definition given");
- int q = celldef.indexOf(' ');
+ final int q = celldef.indexOf(' ');
if (q < 0) {
this.nickname = celldef;
celldef = "";
@@ -122,18 +122,18 @@ public class kelondroColumn {
}
} else {
this.nickname = celldef.substring(0, p);
- int q = celldef.indexOf(' ');
+ final int q = celldef.indexOf(' ');
if (q < 0) {
try {
this.cellwidth = Integer.parseInt(celldef.substring(p + 1));
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
throw new kelondroException("kelondroColumn - cellwidth description wrong:" + celldef.substring(p + 1));
}
celldef = "";
} else {
try {
this.cellwidth = Integer.parseInt(celldef.substring(p + 1, q));
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
throw new kelondroException("kelondroColumn - cellwidth description wrong:" + celldef.substring(p + 1, q));
}
celldef = celldef.substring(q + 1);
@@ -157,7 +157,7 @@ public class kelondroColumn {
// parse/check encoder type
if ((celldef.length() > 0) && (celldef.charAt(0) == '{')) {
p = celldef.indexOf('}');
- String expf = celldef.substring(1, p);
+ final String expf = celldef.substring(1, p);
celldef = celldef.substring(p + 1).trim();
if (expf.equals("b64e")) this.encoder = encoder_b64e;
else if (expf.equals("b256")) this.encoder = encoder_b256;
@@ -186,14 +186,14 @@ public class kelondroColumn {
}
}
- public void setAttributes(String nickname, int celltype, int encoder) {
+ public void setAttributes(final String nickname, final int celltype, final int encoder) {
this.celltype = celltype;
this.encoder = encoder;
this.nickname = nickname;
}
public String toString() {
- StringBuffer s = new StringBuffer();
+ final StringBuffer s = new StringBuffer();
switch (celltype) {
case celltype_undefined:
s.append(nickname);
@@ -241,7 +241,7 @@ public class kelondroColumn {
return new String(s);
}
- public boolean equals(kelondroColumn otherCol) {
+ public boolean equals(final kelondroColumn otherCol) {
return
(this.celltype == otherCol.celltype) &&
(this.cellwidth == otherCol.cellwidth) &&
diff --git a/source/de/anomic/kelondro/kelondroEcoFS.java b/source/de/anomic/kelondro/kelondroEcoFS.java
index 1266f0ac6..c20dc1d32 100644
--- a/source/de/anomic/kelondro/kelondroEcoFS.java
+++ b/source/de/anomic/kelondro/kelondroEcoFS.java
@@ -53,7 +53,7 @@ import java.util.Iterator;
public class kelondroEcoFS {
private RandomAccessFile raf;
- private File tablefile;
+ private final File tablefile;
/**
* number of bytes in one record
*/
@@ -63,7 +63,8 @@ public class kelondroEcoFS {
* number of entries in buffer
*/
private int cachecount, buffercount;
- private byte[] cache, buffer, zero;
+ private byte[] cache, buffer;
+ final byte[] zero;
/**
* stay below hard disc cache (is that necessary?)
@@ -72,7 +73,7 @@ public class kelondroEcoFS {
private static final int maxWriteBuffer = 4 * 1024;
- public kelondroEcoFS(File tablefile, int recordsize) throws IOException {
+ public kelondroEcoFS(final File tablefile, final int recordsize) throws IOException {
this.tablefile = tablefile;
this.recordsize = recordsize;
@@ -86,17 +87,17 @@ public class kelondroEcoFS {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(tablefile);
- } catch (FileNotFoundException e) {
+ } catch (final FileNotFoundException e) {
// should not happen
e.printStackTrace();
}
- try { if (fos != null) fos.close(); } catch (IOException e) {}
+ try { if (fos != null) fos.close(); } catch (final IOException e) {}
}
// open an existing table file
try {
raf = new RandomAccessFile(tablefile, "rw");
- } catch (FileNotFoundException e) {
+ } catch (final FileNotFoundException e) {
// should never happen
e.printStackTrace();
}
@@ -115,9 +116,9 @@ public class kelondroEcoFS {
* @param recordsize
* @return number of records in table
*/
- public static long tableSize(File tablefile, long recordsize) {
+ public static long tableSize(final File tablefile, final long recordsize) {
if (!tablefile.exists()) return 0;
- long size = tablefile.length();
+ final long size = tablefile.length();
assert size % recordsize == 0;
return size / recordsize;
}
@@ -148,7 +149,7 @@ public class kelondroEcoFS {
* @param index
* @return the index offset inside the cache or -1 if the index is not in the cache
*/
- private int inCache(long index) {
+ private int inCache(final long index) {
if ((index >= this.cacheindex) && (index < this.cacheindex + this.cachecount)) {
return (int) (index - this.cacheindex);
}
@@ -162,8 +163,8 @@ public class kelondroEcoFS {
* @return the index offset inside the buffer or -1 if the index is not in the buffer
* @throws IOException
*/
- private int inBuffer(long index) throws IOException {
- long fs = filesize();
+ private int inBuffer(final long index) throws IOException {
+ final long fs = filesize();
if ((index >= fs) && (index < fs + this.buffercount)) {
return (int) (index - fs);
}
@@ -185,7 +186,7 @@ public class kelondroEcoFS {
if (inCache(index) >= 0) return;
// calculate new start position
- long fs = this.filesize();
+ final long fs = this.filesize();
if (index + this.cache.length / this.recordsize > fs) {
index = fs - this.cache.length / this.recordsize;
}
@@ -211,7 +212,7 @@ public class kelondroEcoFS {
try {
raf.seek(raf.length());
raf.write(this.buffer, 0, this.recordsize * this.buffercount);
- } catch (IOException e) {
+ } catch (final IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
@@ -224,7 +225,7 @@ public class kelondroEcoFS {
// then close the file
try {
raf.close();
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
raf = null;
@@ -238,12 +239,12 @@ public class kelondroEcoFS {
* @param start offset in b to store data
* @throws IOException
*/
- public synchronized void get(long index, byte[] b, int start) throws IOException {
+ public synchronized void get(final long index, final byte[] b, final int start) throws IOException {
assert b.length - start >= this.recordsize;
if (index >= size()) throw new IndexOutOfBoundsException("kelondroEcoFS.get(" + index + ") outside bounds (" + this.size() + ")");
// check if index is inside of cache
int p = inCache(index);
- int q = (p >= 0) ? -1 : inBuffer(index);
+ final int q = (p >= 0) ? -1 : inBuffer(index);
if ((p < 0) && (q < 0)) {
// the index is outside of cache and buffer index. shift cache window
fillCache(index);
@@ -263,9 +264,9 @@ public class kelondroEcoFS {
assert false;
}
- public synchronized void put(long index, byte[] b, int start) throws IOException {
+ public synchronized void put(final long index, final byte[] b, final int start) throws IOException {
assert b.length - start >= this.recordsize;
- long s = size();
+ final long s = size();
if (index > s) throw new IndexOutOfBoundsException("kelondroEcoFS.put(" + index + ") outside bounds (" + this.size() + ")");
// check if this is an empty entry
@@ -275,8 +276,8 @@ public class kelondroEcoFS {
}
// check if index is inside of cache
- int p = inCache(index);
- int q = (p >= 0) ? -1 : inBuffer(index);
+ final int p = inCache(index);
+ final int q = (p >= 0) ? -1 : inBuffer(index);
if (p >= 0) {
// write entry to the cache and to the file
System.arraycopy(b, start, this.cache, p * this.recordsize, this.recordsize);
@@ -314,7 +315,7 @@ public class kelondroEcoFS {
}
}
- public synchronized void add(byte[] b, int start) throws IOException {
+ public synchronized void add(final byte[] b, final int start) throws IOException {
// index == size() == filesize() + (long) this.buffercount
assert b.length - start >= this.recordsize;
@@ -343,18 +344,18 @@ public class kelondroEcoFS {
assert this.buffercount <= this.buffer.length / this.recordsize;
}
- private boolean isClean(byte[] b, int offset, int length) {
+ private boolean isClean(final byte[] b, final int offset, final int length) {
for (int i = 0; i < length; i++) {
if (b[i + offset] != 0) return false;
}
return true;
}
- private boolean isClean(long index) throws IOException {
+ private boolean isClean(final long index) throws IOException {
assert index < size();
// check if index is inside of cache
int p = inCache(index);
- int q = (p >= 0) ? -1 : inBuffer(index);
+ final int q = (p >= 0) ? -1 : inBuffer(index);
if ((p < 0) && (q < 0)) {
// the index is outside of cache and buffer index. shift cache window
fillCache(index);
@@ -389,9 +390,9 @@ public class kelondroEcoFS {
* @param start offset in record to start reading
* @throws IOException
*/
- public synchronized void clean(long index, byte[] b, int start) throws IOException {
+ public synchronized void clean(final long index, final byte[] b, final int start) throws IOException {
assert b.length - start >= this.recordsize;
- long s = size();
+ final long s = size();
if (index >= s) throw new IndexOutOfBoundsException("kelondroEcoFS.clean(" + index + ") outside bounds (" + s + ")");
if (index == s - 1) {
cleanLast(b, start);
@@ -400,7 +401,7 @@ public class kelondroEcoFS {
// check if index is inside of cache
int p = inCache(index);
- int q = (p >= 0) ? -1 : inBuffer(index);
+ final int q = (p >= 0) ? -1 : inBuffer(index);
if ((p < 0) && (q < 0)) {
// the index is outside of cache and buffer index. shift cache window
fillCache(index);
@@ -432,8 +433,8 @@ public class kelondroEcoFS {
* @param index
* @throws IOException
*/
- public synchronized void clean(long index) throws IOException {
- long s = size();
+ public synchronized void clean(final long index) throws IOException {
+ final long s = size();
if (index >= s) throw new IndexOutOfBoundsException("kelondroEcoFS.clean(" + index + ") outside bounds (" + s + ")");
if (index == s - 1) {
cleanLast();
@@ -441,8 +442,8 @@ public class kelondroEcoFS {
}
// check if index is inside of cache
- int p = inCache(index);
- int q = (p >= 0) ? -1 : inBuffer(index);
+ final int p = inCache(index);
+ final int q = (p >= 0) ? -1 : inBuffer(index);
if (p >= 0) {
// write zero bytes to the cache and to the file
System.arraycopy(zero, 0, this.cache, p * this.recordsize, this.recordsize);
@@ -466,7 +467,7 @@ public class kelondroEcoFS {
* @param start
* @throws IOException
*/
- public synchronized void cleanLast(byte[] b, int start) throws IOException {
+ public synchronized void cleanLast(final byte[] b, final int start) throws IOException {
cleanLast0(b, start);
long i;
while (((i = size()) > 0) && (isClean(i - 1))) {
@@ -485,12 +486,12 @@ public class kelondroEcoFS {
* @param start
* @throws IOException
*/
- private synchronized void cleanLast0(byte[] b, int start) throws IOException {
+ private synchronized void cleanLast0(final byte[] b, final int start) throws IOException {
assert b.length - start >= this.recordsize;
// check if index is inside of cache
- long s = this.size();
+ final long s = this.size();
int p = inCache(s - 1);
- int q = (p >= 0) ? -1 : inBuffer(s - 1);
+ final int q = (p >= 0) ? -1 : inBuffer(s - 1);
if ((p < 0) && (q < 0)) {
// the index is outside of cache and buffer index. shift cache window
fillCache(this.size() - 1);
@@ -534,9 +535,9 @@ public class kelondroEcoFS {
private synchronized void cleanLast0() throws IOException {
// check if index is inside of cache
- long s = this.size();
- long p = inCache(s - 1);
- long q = (p >= 0) ? -1 : inBuffer(s - 1);
+ final long s = this.size();
+ final long p = inCache(s - 1);
+ final long q = (p >= 0) ? -1 : inBuffer(s - 1);
if (p >= 0) {
// shrink cache and file
assert this.buffercount == 0;
@@ -557,8 +558,8 @@ public class kelondroEcoFS {
public static class ChunkIterator implements Iterator<byte[]> {
- private int recordsize, chunksize;
- private DataInputStream stream;
+ private final int recordsize, chunksize;
+ private final DataInputStream stream;
private byte[] nextBytes;
/**
@@ -570,7 +571,7 @@ public class kelondroEcoFS {
* @param chunksize: the size of the chunks that are returned by next(). remaining bytes until the lenght of recordsize are skipped
* @throws FileNotFoundException
*/
- public ChunkIterator(File file, int recordsize, int chunksize) throws FileNotFoundException {
+ public ChunkIterator(final File file, final int recordsize, final int chunksize) throws FileNotFoundException {
assert (file.exists());
assert file.length() % recordsize == 0;
this.recordsize = recordsize;
@@ -584,7 +585,7 @@ public class kelondroEcoFS {
}
public byte[] next0() {
- byte[] chunk = new byte[chunksize];
+ final byte[] chunk = new byte[chunksize];
int r, s;
try {
// read the chunk
@@ -597,13 +598,13 @@ public class kelondroEcoFS {
r += s;
}
return chunk;
- } catch (IOException e) {
+ } catch (final IOException e) {
return null;
}
}
public byte[] next() {
- byte[] n = this.nextBytes;
+ final byte[] n = this.nextBytes;
this.nextBytes = next0();
return n;
}
@@ -618,13 +619,13 @@ public class kelondroEcoFS {
* main - writes some data and checks the tables size (with time measureing)
* @param args
*/
- public static void main(String[] args) {
+ public static void main(final String[] args) {
// open a file, add one entry and exit
- File f = new File(args[0]);
+ final File f = new File(args[0]);
if (f.exists()) f.delete();
try {
- kelondroEcoFS t = new kelondroEcoFS(f, 8);
- byte[] b = new byte[8];
+ final kelondroEcoFS t = new kelondroEcoFS(f, 8);
+ final byte[] b = new byte[8];
t.add("01234567".getBytes(), 0);
t.add("ABCDEFGH".getBytes(), 0);
t.add("abcdefgh".getBytes(), 0);
@@ -650,7 +651,7 @@ public class kelondroEcoFS {
System.out.println("size = " + t.size());
//t.clean(t.size() - 2);
t.cleanLast();
- long start = System.currentTimeMillis();
+ final long start = System.currentTimeMillis();
long c = 0;
for (int i = 0; i < 100000; i++) {
c = t.size();
@@ -659,7 +660,7 @@ public class kelondroEcoFS {
System.out.println("size = " + c);
t.close();
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
}
diff --git a/source/de/anomic/kelondro/kelondroEcoTable.java b/source/de/anomic/kelondro/kelondroEcoTable.java
index 4dcf369c0..2300a82eb 100644
--- a/source/de/anomic/kelondro/kelondroEcoTable.java
+++ b/source/de/anomic/kelondro/kelondroEcoTable.java
@@ -68,15 +68,15 @@ public class kelondroEcoTable implements kelondroIndex {
int fail;
kelondroRow taildef;
- private int buffersize;
+ private final int buffersize;
- public kelondroEcoTable(File tablefile, kelondroRow rowdef, int useTailCache, int buffersize, int initialSpace) {
+ public kelondroEcoTable(final File tablefile, final kelondroRow rowdef, final int useTailCache, final int buffersize, final int initialSpace) {
this.rowdef = rowdef;
this.buffersize = buffersize;
this.fail = 0;
assert rowdef.primaryKeyIndex == 0;
// define the taildef, a row like the rowdef but without the first column
- kelondroColumn[] cols = new kelondroColumn[rowdef.columns() - 1];
+ final kelondroColumn[] cols = new kelondroColumn[rowdef.columns() - 1];
for (int i = 0; i < cols.length; i++) {
cols[i] = rowdef.column(i + 1);
}
@@ -88,26 +88,26 @@ public class kelondroEcoTable implements kelondroIndex {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(tablefile);
- } catch (FileNotFoundException e) {
+ } catch (final FileNotFoundException e) {
// should not happen
e.printStackTrace();
}
- if (fos != null) try { fos.close(); } catch (IOException e) {}
+ if (fos != null) try { fos.close(); } catch (final IOException e) {}
}
try {
// open an existing table file
- int fileSize = (int) tableSize(tablefile, rowdef.objectsize);
+ final int fileSize = (int) tableSize(tablefile, rowdef.objectsize);
// initialize index and copy table
- int records = Math.max(fileSize, initialSpace);
- long neededRAM4table = (records) * ((rowdef.objectsize) + 4L) * 3L;
+ final int records = Math.max(fileSize, initialSpace);
+ final long neededRAM4table = (records) * ((rowdef.objectsize) + 4L) * 3L;
table = ((neededRAM4table < maxarraylength) &&
((useTailCache == tailCacheForceUsage) ||
((useTailCache == tailCacheUsageAuto) && (serverMemory.free() > neededRAM4table + 200 * 1024 * 1024)))) ?
new kelondroRowSet(taildef, records) : null;
System.out.println("*** DEBUG " + tablefile + ": available RAM: " + (serverMemory.available() / 1024 / 1024) + "MB, allocating space for " + records + " entries");
- long neededRAM4index = 2 * 1024 * 1024 + records * (rowdef.primaryKeyLength + 4) * 3 / 2;
+ final long neededRAM4index = 2 * 1024 * 1024 + records * (rowdef.primaryKeyLength + 4) * 3 / 2;
if (!serverMemory.request(neededRAM4index, false)) {
// despite calculations seemed to show that there is enough memory for the table AND the index
// there is now not enough memory left for the index. So delete the table again to free the memory
@@ -124,7 +124,7 @@ public class kelondroEcoTable implements kelondroIndex {
int i = 0;
byte[] key;
if (table == null) {
- Iterator<byte[]> ki = keyIterator(tablefile, rowdef);
+ final Iterator<byte[]> ki = keyIterator(tablefile, rowdef);
while (ki.hasNext()) {
key = ki.next();
@@ -142,7 +142,7 @@ public class kelondroEcoTable implements kelondroIndex {
} else {
byte[] record;
key = new byte[rowdef.primaryKeyLength];
- Iterator<byte[]> ri = new kelondroEcoFS.ChunkIterator(tablefile, rowdef.objectsize, rowdef.objectsize);
+ final Iterator<byte[]> ri = new kelondroEcoFS.ChunkIterator(tablefile, rowdef.objectsize, rowdef.objectsize);
while (ri.hasNext()) {
record = ri.next();
assert record != null;
@@ -166,24 +166,24 @@ public class kelondroEcoTable implements kelondroIndex {
System.out.print(" -ordering- ..");
System.out.flush();
this.file = new kelondroBufferedEcoFS(new kelondroEcoFS(tablefile, rowdef.objectsize), this.buffersize);
- ArrayList<Integer[]> doubles = index.removeDoubles();
+ final ArrayList<Integer[]> doubles = index.removeDoubles();
//assert index.size() + doubles.size() + fail == i;
System.out.println(" -removed " + doubles.size() + " doubles- done.");
if (doubles.size() > 0) {
System.out.println("DEBUG " + tablefile + ": WARNING - EcoTable " + tablefile + " has " + doubles.size() + " doubles");
// from all the doubles take one, put it back to the index and remove the others from the file
// first put back one element each
- byte[] record = new byte[rowdef.objectsize];
+ final byte[] record = new byte[rowdef.objectsize];
key = new byte[rowdef.primaryKeyLength];
- for (Integer[] ds: doubles) {
+ for (final Integer[] ds: doubles) {
file.get(ds[0].intValue(), record, 0);
System.arraycopy(record, 0, key, 0, rowdef.primaryKeyLength);
if (!index.addi(key, ds[0].intValue())) fail++;
}
// then remove the other doubles by removing them from the table, but do a re-indexing while doing that
// first aggregate all the delete positions because the elements from the top positions must be removed first
- TreeSet<Integer> delpos = new TreeSet<Integer>();
- for (Integer[] ds: doubles) {
+ final TreeSet<Integer> delpos = new TreeSet<Integer>();
+ for (final Integer[] ds: doubles) {
for (int j = 1; j < ds.length; j++) delpos.add(ds[j]);
}
// now remove the entries in a sorted way (top-down)
@@ -199,11 +199,11 @@ public class kelondroEcoTable implements kelondroIndex {
} catch (IOException e) {
e.printStackTrace();
}*/
- } catch (FileNotFoundException e) {
+ } catch (final FileNotFoundException e) {
// should never happen
e.printStackTrace();
throw new kelondroException(e.getMessage());
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
throw new kelondroException(e.getMessage());
}
@@ -219,12 +219,12 @@ public class kelondroEcoTable implements kelondroIndex {
* @throws FileNotFoundException
* @return an iterator for all keys in the file
*/
- public Iterator<byte[]> keyIterator(File file, kelondroRow rowdef) throws FileNotFoundException {
+ public Iterator<byte[]> keyIterator(final File file, final kelondroRow rowdef) throws FileNotFoundException {
assert rowdef.primaryKeyIndex == 0;
return new kelondroEcoFS.ChunkIterator(file, rowdef.objectsize, rowdef.primaryKeyLength);
}
- public static long tableSize(File tablefile, int recordsize) {
+ public static long tableSize(final File tablefile, final int recordsize) {
// returns number of records in table
return kelondroEcoFS.tableSize(tablefile, recordsize);
}
@@ -234,18 +234,18 @@ public class kelondroEcoTable implements kelondroIndex {
return tableTracker.keySet().iterator();
}
- public static final Map<String, String> memoryStats(String filename) {
+ public static final Map<String, String> memoryStats(final String filename) {
// returns a map for each file in the tracker;
// the map represents properties for each record objects,
// i.e. for cache memory allocation
- kelondroEcoTable theEcoTable = tableTracker.get(filename);
+ final kelondroEcoTable theEcoTable = tableTracker.get(filename);
return theEcoTable.memoryStats();
}
private final Map<String, String> memoryStats() {
// returns statistical data about this object
assert ((table == null) || (table.size() == index.size()));
- HashMap<String, String> map = new HashMap<String, String>();
+ final HashMap<String, String> map = new HashMap<String, String>();
map.put("tableSize", Integer.toString(index.size()));
map.put("tableKeyChunkSize", Integer.toString(index.row().objectsize));
map.put("tableKeyMem", Integer.toString((int) (index.row().objectsize * index.size() * kelondroRowCollection.growfactor)));
@@ -258,15 +258,15 @@ public class kelondroEcoTable implements kelondroIndex {
return this.table != null;
}
- public static int staticRAMIndexNeed(File f, kelondroRow rowdef) {
+ public static int staticRAMIndexNeed(final File f, final kelondroRow rowdef) {
return (int) ((rowdef.primaryKeyLength + 4) * tableSize(f, rowdef.objectsize) * kelondroRowCollection.growfactor);
}
- public synchronized boolean addUnique(Entry row) throws IOException {
+ public synchronized boolean addUnique(final Entry row) throws IOException {
assert file.size() == index.size() + fail : "file.size() = " + file.size() + ", index.size() = " + index.size();
assert ((table == null) || (table.size() == index.size()));
- int i = (int) file.size();
- boolean added = index.addi(row.getPrimaryKeyBytes(), i);
+ final int i = (int) file.size();
+ final boolean added = index.addi(row.getPrimaryKeyBytes(), i);
if (!added) return false;
if (table != null) {
assert table.size() == i;
@@ -277,9 +277,9 @@ public class kelondroEcoTable implements kelondroIndex {
return true;
}
- public synchronized int addUniqueMultiple(List<Entry> rows) throws IOException {
+ public synchronized int addUniqueMultiple(final List<Entry> rows) throws IOException {
assert file.size() == index.size() + fail : "file.size() = " + file.size() + ", index.size() = " + index.size();
- Iterator<Entry> i = rows.iterator();
+ final Iterator<Entry> i = rows.iterator();
int c = 0;
while (i.hasNext()) {
if (addUnique(i.next())) c++;
@@ -295,14 +295,14 @@ public class kelondroEcoTable implements kelondroIndex {
*/
public synchronized ArrayList<kelondroRowCollection> removeDoubles() throws IOException {
assert file.size() == index.size() + fail : "file.size() = " + file.size() + ", index.size() = " + index.size();
- ArrayList<kelondroRowCollection> report = new ArrayList<kelondroRowCollection>();
+ final ArrayList<kelondroRowCollection> report = new ArrayList<kelondroRowCollection>();
kelondroRowSet rows;
- TreeSet<Integer> d = new TreeSet<Integer>();
- byte[] b = new byte[rowdef.objectsize];
+ final TreeSet<Integer> d = new TreeSet<Integer>();
+ final byte[] b = new byte[rowdef.objectsize];
Integer L;
kelondroRow.Entry inconsistentEntry;
// iterate over all entries that have inconsistent index references
- for (Integer[] is: index.removeDoubles()) {
+ for (final Integer[] is: index.removeDoubles()) {
// 'is' is the set of all indexes, that have the same reference
// we collect that entries now here
rows = new kelondroRowSet(this.rowdef, is.length);
@@ -340,19 +340,19 @@ public class kelondroEcoTable implements kelondroIndex {
return this.file.filename().toString();
}
- public synchronized Entry get(byte[] key) throws IOException {
+ public synchronized Entry get(final byte[] key) throws IOException {
if ((file == null) || (index == null)) return null;
assert file.size() == index.size() + fail : "file.size() = " + file.size() + ", index.size() = " + index.size() + ", fail = " + fail;
assert ((table == null) || (table.size() == index.size()));
- int i = index.geti(key);
+ final int i = index.geti(key);
if (i == -1) return null;
- byte[] b = new byte[rowdef.objectsize];
+ final byte[] b = new byte[rowdef.objectsize];
if (table == null) {
// read row from the file
file.get(i, b, 0);
} else {
// construct the row using the copy in RAM
- kelondroRow.Entry v = table.get(i, false);
+ final kelondroRow.Entry v = table.get(i, false);
assert v != null;
if (v == null) return null;
assert key.length == rowdef.primaryKeyLength;
@@ -364,10 +364,10 @@ public class kelondroEcoTable implements kelondroIndex {
return rowdef.newEntry(b);
}
- public synchronized boolean has(byte[] key) {
+ public synchronized boolean has(final byte[] key) {
try {
assert file.size() == index.size() + fail : "file.size() = " + file.size() + ", index.size() = " + index.size();
- } catch (IOException e) {
+ } catch (final IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
@@ -375,7 +375,7 @@ public class kelondroEcoTable implements kelondroIndex {
return index.has(key);
}
- public synchronized kelondroCloneableIterator<byte[]> keys(boolean up, byte[] firstKey) throws IOException {
+ public synchronized kelondroCloneableIterator<byte[]> keys(final boolean up, final byte[] firstKey) throws IOException {
return index.keys(up, firstKey);
}
@@ -383,19 +383,19 @@ public class kelondroEcoTable implements kelondroIndex {
return null;
}
- public synchronized Entry put(Entry row) throws IOException {
+ public synchronized Entry put(final Entry row) throws IOException {
assert file.size() == index.size() + fail : "file.size() = " + file.size() + ", index.size() = " + index.size();
assert ((table == null) || (table.size() == index.size()));
assert row != null;
assert row.bytes() != null;
if ((row == null) || (row.bytes() == null)) return null;
- int i = index.geti(row.getPrimaryKeyBytes());
+ final int i = index.geti(row.getPrimaryKeyBytes());
if (i == -1) {
addUnique(row);
return null;
}
- byte[] b = new byte[rowdef.objectsize];
+ final byte[] b = new byte[rowdef.objectsize];
if (table == null) {
// read old value
file.get(i, b, 0);
@@ -403,7 +403,7 @@ public class kelondroEcoTable implements kelondroIndex {
file.put(i, row.bytes(), 0);
} else {
// read old value
- kelondroRow.Entry v = table.get(i, false);
+ final kelondroRow.Entry v = table.get(i, false);
assert v != null;
System.arraycopy(row.getPrimaryKeyBytes(), 0, b, 0, rowdef.primaryKeyLength);
System.arraycopy(v.bytes(), 0, b, rowdef.primaryKeyLength, rowdef.objectsize - rowdef.primaryKeyLength);
@@ -417,30 +417,30 @@ public class kelondroEcoTable implements kelondroIndex {
return rowdef.newEntry(b);
}
- public synchronized Entry put(Entry row, Date entryDate) throws IOException {
+ public synchronized Entry put(final Entry row, final Date entryDate) throws IOException {
return put(row);
}
- public synchronized void putMultiple(List<Entry> rows) throws IOException {
+ public synchronized void putMultiple(final List<Entry> rows) throws IOException {
assert file.size() == index.size() + fail : "file.size() = " + file.size() + ", index.size() = " + index.size();
- Iterator<Entry> i = rows.iterator();
+ final Iterator<Entry> i = rows.iterator();
while (i.hasNext()) {
put(i.next());
}
assert file.size() == index.size() + fail : "file.size() = " + file.size() + ", index.size() = " + index.size();
}
- private void removeInFile(int i) throws IOException {
+ private void removeInFile(final int i) throws IOException {
assert i >= 0;
- byte[] p = new byte[rowdef.objectsize];
+ final byte[] p = new byte[rowdef.objectsize];
if (table == null) {
if (i == index.size() - 1) {
file.cleanLast();
} else {
file.cleanLast(p, 0);
file.put(i, p, 0);
- byte[] k = new byte[rowdef.primaryKeyLength];
+ final byte[] k = new byte[rowdef.primaryKeyLength];
System.arraycopy(p, 0, k, 0, rowdef.primaryKeyLength);
index.puti(k, i);
}
@@ -451,28 +451,28 @@ public class kelondroEcoTable implements kelondroIndex {
file.cleanLast();
} else {
// switch values
- kelondroRow.Entry te = table.removeOne();
+ final kelondroRow.Entry te = table.removeOne();
table.set(i, te);
file.cleanLast(p, 0);
file.put(i, p, 0);
- kelondroRow.Entry lr = rowdef.newEntry(p);
+ final kelondroRow.Entry lr = rowdef.newEntry(p);
index.puti(lr.getPrimaryKeyBytes(), i);
}
}
}
- public synchronized Entry remove(byte[] key) throws IOException {
+ public synchronized Entry remove(final byte[] key) throws IOException {
assert file.size() == index.size() + fail : "file.size() = " + file.size() + ", index.size() = " + index.size();
assert ((table == null) || (table.size() == index.size()));
assert key.length == rowdef.primaryKeyLength;
- int i = index.geti(key);
+ final int i = index.geti(key);
if (i == -1) return null; // nothing to do
// prepare result
- byte[] b = new byte[rowdef.objectsize];
- byte[] p = new byte[rowdef.objectsize];
- int sb = index.size();
+ final byte[] b = new byte[rowdef.objectsize];
+ final byte[] p = new byte[rowdef.objectsize];
+ final int sb = index.size();
int ix;
assert i < index.size();
if (table == null) {
@@ -487,14 +487,14 @@ public class kelondroEcoTable implements kelondroIndex {
file.get(i, b, 0);
file.cleanLast(p, 0);
file.put(i, p, 0);
- byte[] k = new byte[rowdef.primaryKeyLength];
+ final byte[] k = new byte[rowdef.primaryKeyLength];
System.arraycopy(p, 0, k, 0, rowdef.primaryKeyLength);
index.puti(k, i);
}
assert (file.size() == index.size() + fail);
} else {
// get result value from the table copy, so we don't need to read it from the file
- kelondroRow.Entry v = table.get(i, false);
+ final kelondroRow.Entry v = table.get(i, false);
System.arraycopy(key, 0, b, 0, key.length);
System.arraycopy(v.bytes(), 0, b, rowdef.primaryKeyLength, taildef.objectsize);
@@ -509,12 +509,12 @@ public class kelondroEcoTable implements kelondroIndex {
ix = index.removei(key);
assert ix == i;
- kelondroRow.Entry te = table.removeOne();
+ final kelondroRow.Entry te = table.removeOne();
table.set(i, te);
file.cleanLast(p, 0);
file.put(i, p, 0);
- kelondroRow.Entry lr = rowdef.newEntry(p);
+ final kelondroRow.Entry lr = rowdef.newEntry(p);
index.puti(lr.getPrimaryKeyBytes(), i);
}
assert (file.size() == index.size() + fail);
@@ -529,10 +529,10 @@ public class kelondroEcoTable implements kelondroIndex {
public synchronized Entry removeOne() throws IOException {
assert file.size() == index.size() + fail : "file.size() = " + file.size() + ", index.size() = " + index.size();
assert ((table == null) || (table.size() == index.size()));
- byte[] le = new byte[rowdef.objectsize];
+ final byte[] le = new byte[rowdef.objectsize];
file.cleanLast(le, 0);
- kelondroRow.Entry lr = rowdef.newEntry(le);
- int i = index.removei(lr.getPrimaryKeyBytes());
+ final kelondroRow.Entry lr = rowdef.newEntry(le);
+ final int i = index.removei(lr.getPrimaryKeyBytes());
assert i >= 0;
if (table != null) table.removeOne();
assert file.size() == index.size() + fail : "file.size() = " + file.size() + ", index.size() = " + index.size();
@@ -540,7 +540,7 @@ public class kelondroEcoTable implements kelondroIndex {
}
public void clear() throws IOException {
- File f = file.filename();
+ final File f = file.filename();
file.close();
f.delete();
@@ -548,17 +548,17 @@ public class kelondroEcoTable implements kelondroIndex {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(f);
- } catch (FileNotFoundException e) {
+ } catch (final FileNotFoundException e) {
// should not happen
e.printStackTrace();
}
- if (fos != null) try { fos.close(); } catch (IOException e) {}
+ if (fos != null) try { fos.close(); } catch (final IOException e) {}
// open an existing table file
try {
this.file = new kelondroBufferedEcoFS(new kelondroEcoFS(f, rowdef.objectsize), this.buffersize);
- } catch (FileNotFoundException e) {
+ } catch (final FileNotFoundException e) {
// should never happen
e.printStackTrace();
}
@@ -577,7 +577,7 @@ public class kelondroEcoTable implements kelondroIndex {
}
- public synchronized kelondroCloneableIterator<Entry> rows(boolean up, byte[] firstKey) throws IOException {
+ public synchronized kelondroCloneableIterator<Entry> rows(final boolean up, final byte[] firstKey) throws IOException {
return new rowIterator(up, firstKey);
}
@@ -587,17 +587,17 @@ public class kelondroEcoTable implements kelondroIndex {
byte[] fk;
int c;
- public rowIterator(boolean up, byte[] firstKey) throws IOException {
+ public rowIterator(final boolean up, final byte[] firstKey) throws IOException {
this.up = up;
this.fk = firstKey;
this.i = index.keys(up, firstKey);
this.c = -1;
}
- public kelondroCloneableIterator<Entry> clone(Object modifier) {
+ public kelondroCloneableIterator<Entry> clone(final Object modifier) {
try {
return new rowIterator(up, fk);
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
return null;
}
@@ -608,29 +608,29 @@ public class kelondroEcoTable implements kelondroIndex {
}
public Entry next() {
- byte[] k = i.next();
+ final byte[] k = i.next();
assert k != null;
if (k == null) return null;
try {
this.c = index.geti(k);
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
return null;
}
assert this.c >= 0;
if (this.c < 0) return null;
- byte[] b = new byte[rowdef.objectsize];
+ final byte[] b = new byte[rowdef.objectsize];
if (table == null) {
// read from file
try {
file.get(this.c, b, 0);
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
return null;
}
} else {
// compose from table and key
- kelondroRow.Entry v = table.get(this.c, false);
+ final kelondroRow.Entry v = table.get(this.c, false);
assert v != null;
if (v == null) return null;
System.arraycopy(k, 0, b, 0, rowdef.primaryKeyLength);
@@ -645,12 +645,12 @@ public class kelondroEcoTable implements kelondroIndex {
}
- public static kelondroIndex testTable(File f, String testentities, int testcase) throws IOException {
+ public static kelondroIndex testTable(final File f, final String testentities, final int testcase) throws IOException {
if (f.exists()) f.delete();
- kelondroRow rowdef = new kelondroRow("byte[] a-4, byte[] b-4", kelondroNaturalOrder.naturalOrder, 0);
- kelondroIndex tt = new kelondroEcoTable(f, rowdef, testcase, 100, 0);
+ final kelondroRow rowdef = new kelondroRow("byte[] a-4, byte[] b-4", kelondroNaturalOrder.naturalOrder, 0);
+ final kelondroIndex tt = new kelondroEcoTable(f, rowdef, testcase, 100, 0);
byte[] b;
- kelondroRow.Entry row = rowdef.newEntry();
+ final kelondroRow.Entry row = rowdef.newEntry();
for (int i = 0; i < testentities.length(); i++) {
b = kelondroTree.testWord(testentities.charAt(i));
row.setCol(0, b);
@@ -660,10 +660,10 @@ public class kelondroEcoTable implements kelondroIndex {
return tt;
}
- public static void bigtest(int elements, File testFile, int testcase) {
+ public static void bigtest(final int elements, final File testFile, final int testcase) {
System.out.println("starting big test with " + elements + " elements:");
- long start = System.currentTimeMillis();
- String[] s = kelondroTree.permutations(elements);
+ final long start = System.currentTimeMillis();
+ final String[] s = kelondroTree.permutations(elements);
kelondroIndex tt;
try {
for (int i = 0; i < s.length; i++) {
@@ -687,15 +687,15 @@ public class kelondroEcoTable implements kelondroIndex {
}
}
System.out.println("FINISHED test after " + ((System.currentTimeMillis() - start) / 1000) + " seconds.");
- } catch (Exception e) {
+ } catch (final Exception e) {
e.printStackTrace();
System.out.println("TERMINATED");
}
}
- public static void main(String[] args) {
+ public static void main(final String[] args) {
// open a file, add one entry and exit
- File f = new File(args[0]);
+ final File f = new File(args[0]);
System.out.println("========= Testcase: no tail cache:");
bigtest(5, f, tailCacheDenyUsage);
System.out.println("========= Testcase: with tail cache:");
diff --git a/source/de/anomic/kelondro/kelondroException.java b/source/de/anomic/kelondro/kelondroException.java
index 44d93bd17..8d6ec5ae5 100644
--- a/source/de/anomic/kelondro/kelondroException.java
+++ b/source/de/anomic/kelondro/kelondroException.java
@@ -36,11 +36,11 @@ public class kelondroException extends java.lang.RuntimeException {
super("unspecific-error");
}
- public kelondroException(String message) {
+ public kelondroException(final String message) {
super(message);
}
- public kelondroException(String database, String message) {
+ public kelondroException(final String database, final String message) {
super(message + " in db '" + database + "'");
}
diff --git a/source/de/anomic/kelondro/kelondroFileRA.java b/source/de/anomic/kelondro/kelondroFileRA.java
index c8966b46d..e1e6a87b5 100644
--- a/source/de/anomic/kelondro/kelondroFileRA.java
+++ b/source/de/anomic/kelondro/kelondroFileRA.java
@@ -32,11 +32,11 @@ public final class kelondroFileRA extends kelondroAbstractRA implements kelondro
protected RandomAccessFile RAFile;
- public kelondroFileRA(String file) throws IOException, FileNotFoundException {
+ public kelondroFileRA(final String file) throws IOException, FileNotFoundException {
this(new File(file));
}
- public kelondroFileRA(File file) throws IOException, FileNotFoundException {
+ public kelondroFileRA(final File file) throws IOException, FileNotFoundException {
this.name = file.getName();
this.file = file;
RAFile = new RandomAccessFile(file, "rw");
@@ -56,20 +56,20 @@ public final class kelondroFileRA extends kelondroAbstractRA implements kelondro
}
// pseudo-native method write
- public void write(int b) throws IOException {
+ public void write(final int b) throws IOException {
RAFile.write(b);
}
- public int read(byte[] b, int off, int len) throws IOException {
+ public int read(final byte[] b, final int off, final int len) throws IOException {
return RAFile.read(b, off, len);
}
- public void write(byte[] b, int off, int len) throws IOException {
+ public void write(final byte[] b, final int off, final int len) throws IOException {
// write to file
RAFile.write(b, off, len);
}
- public void seek(long pos) throws IOException {
+ public void seek(final long pos) throws IOException {
RAFile.seek(pos);
}
@@ -86,8 +86,8 @@ public final class kelondroFileRA extends kelondroAbstractRA implements kelondro
}
// some static tools
- public static void writeMap(File f, Map<String, String> map, String comment) throws IOException {
- File fp = f.getParentFile();
+ public static void writeMap(final File f, final Map<String, String> map, final String comment) throws IOException {
+ final File fp = f.getParentFile();
if (fp != null) fp.mkdirs();
kelondroRA kra = null;
try {
@@ -95,19 +95,19 @@ public final class kelondroFileRA extends kelondroAbstractRA implements kelondro
kra.writeMap(map, comment);
kra.close();
} finally {
- if (kra != null) try {kra.close();}catch(Exception e){}
+ if (kra != null) try {kra.close();}catch(final Exception e){}
}
}
- public static Map<String, String> readMap(File f) throws IOException {
+ public static Map<String, String> readMap(final File f) throws IOException {
kelondroRA kra = null;
try {
kra = new kelondroFileRA(f);
- Map<String, String> map = kra.readMap();
+ final Map<String, String> map = kra.readMap();
kra.close();
return map;
} finally {
- if (kra != null) try {kra.close();}catch(Exception e){}
+ if (kra != null) try {kra.close();}catch(final Exception e){}
}
}
diff --git a/source/de/anomic/kelondro/kelondroFixedWidthArray.java b/source/de/anomic/kelondro/kelondroFixedWidthArray.java
index 21111b851..15d06b3bf 100644
--- a/source/de/anomic/kelondro/kelondroFixedWidthArray.java
+++ b/source/de/anomic/kelondro/kelondroFixedWidthArray.java
@@ -39,7 +39,7 @@ public class kelondroFixedWidthArray extends kelondroFullRecords implements kelo
private static short thisOHBytes = 0; // our record definition does not need extra bytes
private static short thisOHHandles = 0; // and no handles
- public kelondroFixedWidthArray(File file, kelondroRow rowdef, int intprops) throws IOException {
+ public kelondroFixedWidthArray(final File file, final kelondroRow rowdef, final int intprops) throws IOException {
// this creates a new array
//super(file, true, -1, thisOHBytes, thisOHHandles, rowdef, intprops, rowdef.columns() /* txtProps */, 80 /* txtPropWidth */);
super(file, thisOHBytes, thisOHHandles, rowdef, intprops, rowdef.columns() /* txtProps */, 80 /* txtPropWidth */);
@@ -49,12 +49,12 @@ public class kelondroFixedWidthArray extends kelondroFullRecords implements kelo
}
// store column description
for (int i = 0; i < rowdef.columns(); i++) {
- try {super.setText(i, rowdef.column(i).toString().getBytes());} catch (IOException e) {}
+ try {super.setText(i, rowdef.column(i).toString().getBytes());} catch (final IOException e) {}
}
}
}
- public kelondroFixedWidthArray(kelondroRA ra, String filename, kelondroRow rowdef, int intprops) throws IOException {
+ public kelondroFixedWidthArray(final kelondroRA ra, final String filename, final kelondroRow rowdef, final int intprops) throws IOException {
// this creates a new array
//super(ra, filename, true, -1, thisOHBytes, thisOHHandles, rowdef, intprops, rowdef.columns() /* txtProps */, 80 /* txtPropWidth */, false);
super(ra, filename, thisOHBytes, thisOHHandles, rowdef, intprops, rowdef.columns() /* txtProps */, 80 /* txtPropWidth */, false);
@@ -63,18 +63,18 @@ public class kelondroFixedWidthArray extends kelondroFullRecords implements kelo
}
// store column description
for (int i = 0; i < rowdef.columns(); i++) {
- try {super.setText(i, rowdef.column(i).toString().getBytes());} catch (IOException e) {}
+ try {super.setText(i, rowdef.column(i).toString().getBytes());} catch (final IOException e) {}
}
}
- public static kelondroFixedWidthArray open(File file, kelondroRow rowdef, int intprops) {
+ public static kelondroFixedWidthArray open(final File file, final kelondroRow rowdef, final int intprops) {
try {
return new kelondroFixedWidthArray(file, rowdef, intprops);
- } catch (IOException e) {
+ } catch (final IOException e) {
file.delete();
try {
return new kelondroFixedWidthArray(file, rowdef, intprops);
- } catch (IOException ee) {
+ } catch (final IOException ee) {
e.printStackTrace();
ee.printStackTrace();
System.exit(-1);
@@ -83,19 +83,19 @@ public class kelondroFixedWidthArray extends kelondroFullRecords implements kelo
}
}
- public synchronized void set(int index, kelondroRow.Entry rowentry) throws IOException {
+ public synchronized void set(final int index, final kelondroRow.Entry rowentry) throws IOException {
// this writes a row without reading the row from the file system first
// create a node at position index with rowentry
- kelondroHandle h = new kelondroHandle(index);
+ final kelondroHandle h = new kelondroHandle(index);
(new EcoNode(h, (rowentry == null) ? null : rowentry.bytes(), 0)).commit();
// attention! this newNode call wants that the OH bytes are passed within the bulkchunk
// field. Here, only the rowentry.bytes() raw payload is passed. This is valid, because
// the OHbytes and OHhandles are zero.
}
- public synchronized void setMultiple(TreeMap<Integer, kelondroRow.Entry> rows) throws IOException {
- Iterator<Map.Entry<Integer, kelondroRow.Entry>> i = rows.entrySet().iterator();
+ public synchronized void setMultiple(final TreeMap<Integer, kelondroRow.Entry> rows) throws IOException {
+ final Iterator<Map.Entry<Integer, kelondroRow.Entry>> i = rows.entrySet().iterator();
Map.Entry<Integer, kelondroRow.Entry> entry;
int k;
while (i.hasNext()) {
@@ -105,40 +105,40 @@ public class kelondroFixedWidthArray extends kelondroFullRecords implements kelo
}
}
- public synchronized kelondroRow.Entry getIfValid(int index) throws IOException {
- byte[] b = (new EcoNode(new kelondroHandle(index))).getValueRow();
+ public synchronized kelondroRow.Entry getIfValid(final int index) throws IOException {
+ final byte[] b = (new EcoNode(new kelondroHandle(index))).getValueRow();
if (b[0] == 0) return null;
if ((b[0] == -128) && (b[1] == 0)) return null;
return row().newEntry(b);
}
- public synchronized kelondroRow.Entry get(int index) throws IOException {
+ public synchronized kelondroRow.Entry get(final int index) throws IOException {
return row().newEntry(new EcoNode(new kelondroHandle(index)).getValueRow());
}
- protected synchronized int seti(int index, int value) throws IOException {
- int before = getHandle(index).hashCode();
+ protected synchronized int seti(final int index, final int value) throws IOException {
+ final int before = getHandle(index).hashCode();
setHandle(index, new kelondroHandle(value));
return before;
}
- protected synchronized int geti(int index) {
+ protected synchronized int geti(final int index) {
return getHandle(index).hashCode();
}
- public synchronized int add(kelondroRow.Entry rowentry) throws IOException {
+ public synchronized int add(final kelondroRow.Entry rowentry) throws IOException {
// adds a new rowentry, but re-uses a previously as-deleted marked entry
- kelondroNode n = new EcoNode(rowentry.bytes());
+ final kelondroNode n = new EcoNode(rowentry.bytes());
n.commit();
return n.handle().hashCode();
}
- public synchronized void remove(int index) throws IOException {
+ public synchronized void remove(final int index) throws IOException {
assert (index < (super.free() + super.size())) : "remove: index " + index + " out of bounds " + (super.free() + super.size());
// get the node at position index
- kelondroHandle h = new kelondroHandle(index);
- kelondroNode n = new EcoNode(h);
+ final kelondroHandle h = new kelondroHandle(index);
+ final kelondroNode n = new EcoNode(h);
// erase the row
n.setValueRow(null);
@@ -160,10 +160,10 @@ public class kelondroFixedWidthArray extends kelondroFullRecords implements kelo
System.out.println("EndOfTable");
}
- public static void main(String[] args) {
+ public static void main(final String[] args) {
//File f = new File("d:\\\\mc\\privat\\fixtest.db");
- File f = new File("/Users/admin/fixtest.db");
- kelondroRow rowdef = new kelondroRow("byte[] a-12, byte[] b-4", kelondroNaturalOrder.naturalOrder, 0);
+ final File f = new File("/Users/admin/fixtest.db");
+ final kelondroRow rowdef = new kelondroRow("byte[] a-12, byte[] b-4", kelondroNaturalOrder.naturalOrder, 0);
try {
System.out.println("erster Test");
f.delete();
@@ -213,7 +213,7 @@ public class kelondroFixedWidthArray extends kelondroFullRecords implements kelo
k.print();
k.close();
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
}
diff --git a/source/de/anomic/kelondro/kelondroFlexTable.java b/source/de/anomic/kelondro/kelondroFlexTable.java
index 30a3bfe38..26ba9a4af 100644
--- a/source/de/anomic/kelondro/kelondroFlexTable.java
+++ b/source/de/anomic/kelondro/kelondroFlexTable.java
@@ -47,7 +47,7 @@ public class kelondroFlexTable extends kelondroFlexWidthArray implements kelondr
protected kelondroBytesIntMap index;
private boolean RAMIndex;
- public kelondroFlexTable(File path, String tablename, kelondroRow rowdef, int minimumSpace, boolean resetOnFail) {
+ public kelondroFlexTable(final File path, final String tablename, final kelondroRow rowdef, int minimumSpace, final boolean resetOnFail) {
// the buffersize applies to a possible load of the ram-index
// the minimumSpace is a initial allocation space for the index; names the number of index slots
// if the ram is not sufficient, a tree file is generated
@@ -55,22 +55,22 @@ public class kelondroFlexTable extends kelondroFlexWidthArray implements kelondr
super(path, tablename, rowdef, resetOnFail);
if ((super.col[0].size() < 0) && (resetOnFail)) try {
super.reset();
- } catch (IOException e2) {
+ } catch (final IOException e2) {
e2.printStackTrace();
throw new kelondroException(e2.getMessage());
}
minimumSpace = Math.max(minimumSpace, super.size());
try {
- long neededRAM = 10 * 1024 * 104 + (long) ((super.row().column(0).cellwidth + 4) * minimumSpace * kelondroRowCollection.growfactor);
+ final long neededRAM = 10 * 1024 * 104 + (long) ((super.row().column(0).cellwidth + 4) * minimumSpace * kelondroRowCollection.growfactor);
- File newpath = new File(path, tablename);
- File indexfile = new File(newpath, "col.000.index");
+ final File newpath = new File(path, tablename);
+ final File indexfile = new File(newpath, "col.000.index");
String description = "";
description = new String(this.col[0].getDescription());
- int p = description.indexOf(';', 4);
- long stt = (p > 0) ? Long.parseLong(description.substring(4, p)) : 0;
+ final int p = description.indexOf(';', 4);
+ final long stt = (p > 0) ? Long.parseLong(description.substring(4, p)) : 0;
System.out.println("*** Last Startup time: " + stt + " milliseconds");
- long start = System.currentTimeMillis();
+ final long start = System.currentTimeMillis();
if (serverMemory.request(neededRAM, false)) {
// we can use a RAM index
@@ -111,7 +111,7 @@ public class kelondroFlexTable extends kelondroFlexWidthArray implements kelondr
}
// check consistency
- ArrayList<Integer[]> doubles = index.removeDoubles();
+ final ArrayList<Integer[]> doubles = index.removeDoubles();
if (doubles.size() > 0) {
System.out.println("DEBUG: WARNING - FlexTable " + newpath.toString() + " has " + doubles.size() + " doubles");
}
@@ -119,7 +119,7 @@ public class kelondroFlexTable extends kelondroFlexWidthArray implements kelondr
// assign index to wrapper
description = "stt=" + Long.toString(System.currentTimeMillis() - start) + ";";
super.col[0].setDescription(description.getBytes());
- } catch (IOException e) {
+ } catch (final IOException e) {
if (resetOnFail) {
RAMIndex = true;
index = new kelondroBytesIntMap(super.row().column(0).cellwidth, super.rowdef.objectOrder, 0);
@@ -135,11 +135,11 @@ public class kelondroFlexTable extends kelondroFlexWidthArray implements kelondr
index = new kelondroBytesIntMap(super.row().column(0).cellwidth, super.rowdef.objectOrder, 0);
}
- public static int staticSize(File path, String tablename) {
+ public static int staticSize(final File path, final String tablename) {
return kelondroFlexWidthArray.staticsize(path, tablename);
}
- public static int staticRAMIndexNeed(File path, String tablename, kelondroRow rowdef) {
+ public static int staticRAMIndexNeed(final File path, final String tablename, final kelondroRow rowdef) {
return (int) ((rowdef.column(0).cellwidth + 4) * staticSize(path, tablename) * kelondroRowCollection.growfactor);
}
@@ -147,7 +147,7 @@ public class kelondroFlexTable extends kelondroFlexWidthArray implements kelondr
return RAMIndex;
}
- public synchronized boolean has(byte[] key) {
+ public synchronized boolean has(final byte[] key) {
// it is not recommended to implement or use a has predicate unless
// it can be ensured that it causes no IO
if ((kelondroAbstractRecords.debugmode) && (RAMIndex != true)) serverLog.logWarning("kelondroFlexTable", "RAM index warning in file " + super.tablename);
@@ -155,11 +155,11 @@ public class kelondroFlexTable extends kelondroFlexWidthArray implements kelondr
return index.has(key);
}
- private kelondroBytesIntMap initializeRamIndex(int initialSpace) {
- int space = Math.max(super.col[0].size(), initialSpace) + 1;
+ private kelondroBytesIntMap initializeRamIndex(final int initialSpace) {
+ final int space = Math.max(super.col[0].size(), initialSpace) + 1;
if (space < 0) throw new kelondroException("wrong space: " + space);
- kelondroBytesIntMap ri = new kelondroBytesIntMap(super.row().column(0).cellwidth, super.rowdef.objectOrder, space);
- Iterator<kelondroNode> content = super.col[0].contentNodes(-1);
+ final kelondroBytesIntMap ri = new kelondroBytesIntMap(super.row().column(0).cellwidth, super.rowdef.objectOrder, space);
+ final Iterator<kelondroNode> content = super.col[0].contentNodes(-1);
kelondroNode node;
int i;
byte[] key;
@@ -169,7 +169,7 @@ public class kelondroFlexTable extends kelondroFlexWidthArray implements kelondr
key = node.getKey();
assert (key != null) : "DEBUG: empty key in initializeRamIndex"; // should not happen; if it does, it is an error of the condentNodes iterator
//System.out.println("ENTRY: " + serverLog.arrayList(indexentry.bytes(), 0, indexentry.objectsize()));
- try { ri.addi(key, i); } catch (IOException e) {} // no IOException can happen here
+ try { ri.addi(key, i); } catch (final IOException e) {} // no IOException can happen here
if ((i % 10000) == 0) {
System.out.print('.');
System.out.flush();
@@ -180,13 +180,14 @@ public class kelondroFlexTable extends kelondroFlexWidthArray implements kelondr
return ri;
}
- private kelondroIndex initializeTreeIndex(File indexfile, long preloadTime, kelondroByteOrder objectOrder) throws IOException {
- kelondroIndex treeindex = new kelondroCache(new kelondroTree(indexfile, true, preloadTime, treeIndexRow(rowdef.primaryKeyLength, objectOrder), 2, 80));
- Iterator<kelondroNode> content = super.col[0].contentNodes(-1);
+ private kelondroIndex initializeTreeIndex(final File indexfile, final long preloadTime, final kelondroByteOrder objectOrder) throws IOException {
+ final kelondroIndex treeindex = new kelondroCache(new kelondroTree(indexfile, true, preloadTime, treeIndexRow(rowdef.primaryKeyLength, objectOrder), 2, 80));
+ final Iterator<kelondroNode> content = super.col[0].contentNodes(-1);
kelondroNode node;
kelondroRow.Entry indexentry;
- int i, c = 0, all = super.col[0].size();
- long start = System.currentTimeMillis();
+ int i, c = 0;
+ final int all = super.col[0].size();
+ final long start = System.currentTimeMillis();
long last = start;
while (content.hasNext()) {
node = content.next();
@@ -205,13 +206,13 @@ public class kelondroFlexTable extends kelondroFlexWidthArray implements kelondr
return treeindex;
}
- private static final kelondroRow treeIndexRow(int keywidth, kelondroByteOrder objectOrder) {
+ private static final kelondroRow treeIndexRow(final int keywidth, final kelondroByteOrder objectOrder) {
return new kelondroRow("byte[] key-" + keywidth + ", int reference-4 {b256}", objectOrder, 0);
}
- public synchronized kelondroRow.Entry get(byte[] key) throws IOException {
+ public synchronized kelondroRow.Entry get(final byte[] key) throws IOException {
if (index == null) return null; // case may happen during shutdown
- int pos = index.geti(key);
+ final int pos = index.geti(key);
assert this.size() == index.size() : "content.size() = " + this.size() + ", index.size() = " + index.size();
if (pos < 0) return null;
// pos may be greater than this.size(), because this table may have deleted entries
@@ -226,21 +227,21 @@ public class kelondroFlexTable extends kelondroFlexWidthArray implements kelondr
// assume that the column for the primary key is 0,
// and the column 0 is stored in a file only for that column
// then we don't need to lookup from that file, because we already know the value (it's the key)
- kelondroRow.Entry result = super.getOmitCol0(pos, key);
+ final kelondroRow.Entry result = super.getOmitCol0(pos, key);
assert result != null;
return result;
//}
}
- public synchronized void putMultiple(List<kelondroRow.Entry> rows) throws IOException {
+ public synchronized void putMultiple(final List<kelondroRow.Entry> rows) throws IOException {
// put a list of entries in a ordered way.
// this should save R/W head positioning time
- Iterator<kelondroRow.Entry> i = rows.iterator();
+ final Iterator<kelondroRow.Entry> i = rows.iterator();
kelondroRow.Entry row;
int pos;
byte[] key;
- TreeMap<Integer, kelondroRow.Entry> old_rows_ordered = new TreeMap<Integer, kelondroRow.Entry>();
- ArrayList<kelondroRow.Entry> new_rows_sequential = new ArrayList<kelondroRow.Entry>();
+ final TreeMap<Integer, kelondroRow.Entry> old_rows_ordered = new TreeMap<Integer, kelondroRow.Entry>();
+ final ArrayList<kelondroRow.Entry> new_rows_sequential = new ArrayList<kelondroRow.Entry>();
assert this.size() == index.size() : "content.size() = " + this.size() + ", index.size() = " + index.size();
while (i.hasNext()) {
row = i.next();
@@ -260,16 +261,16 @@ public class kelondroFlexTable extends kelondroFlexWidthArray implements kelondr
assert this.size() == index.size() : "content.size() = " + this.size() + ", index.size() = " + index.size();
}
- public synchronized kelondroRow.Entry put(kelondroRow.Entry row, Date entryDate) throws IOException {
+ public synchronized kelondroRow.Entry put(final kelondroRow.Entry row, final Date entryDate) throws IOException {
assert this.size() == index.size() : "content.size() = " + this.size() + ", index.size() = " + index.size();
return put(row);
}
- public synchronized kelondroRow.Entry put(kelondroRow.Entry row) throws IOException {
+ public synchronized kelondroRow.Entry put(final kelondroRow.Entry row) throws IOException {
assert (row != null);
assert (!(serverLog.allZero(row.getColBytes(0))));
assert row.objectsize() <= this.rowdef.objectsize;
- byte[] key = row.getColBytes(0);
+ final byte[] key = row.getColBytes(0);
if (index == null) return null; // case may appear during shutdown
int pos = index.geti(key);
if (pos < 0) {
@@ -279,12 +280,12 @@ public class kelondroFlexTable extends kelondroFlexWidthArray implements kelondr
return null;
}
//System.out.println("row.key=" + serverLog.arrayList(row.bytes(), 0, row.objectsize()));
- kelondroRow.Entry oldentry = super.get(pos);
+ final kelondroRow.Entry oldentry = super.get(pos);
assert this.size() == index.size() : "content.size() = " + this.size() + ", index.size() = " + index.size();
if (oldentry == null) {
serverLog.logSevere("kelondroFlexTable", "put(): index failure; the index pointed to a cell which is empty. content.size() = " + this.size() + ", index.size() = " + ((index == null) ? 0 : index.size()));
// patch bug ***** FIND CAUSE! (see also: remove)
- int oldindex = index.removei(key);
+ final int oldindex = index.removei(key);
assert oldindex >= 0;
assert index.geti(key) == -1;
// here is this.size() > index.size() because of remove operation above
@@ -299,19 +300,19 @@ public class kelondroFlexTable extends kelondroFlexWidthArray implements kelondr
return oldentry;
}
- public synchronized boolean addUnique(kelondroRow.Entry row) throws IOException {
+ public synchronized boolean addUnique(final kelondroRow.Entry row) throws IOException {
assert row.objectsize() == this.rowdef.objectsize;
assert this.size() == index.size() : "content.size() = " + this.size() + ", index.size() = " + index.size();
return index.addi(row.getColBytes(0), super.add(row));
}
- public synchronized int addUniqueMultiple(List<kelondroRow.Entry> rows) throws IOException {
+ public synchronized int addUniqueMultiple(final List<kelondroRow.Entry> rows) throws IOException {
// add a list of entries in a ordered way.
// this should save R/W head positioning time
- TreeMap<Integer, byte[]> indexed_result = super.addMultiple(rows);
+ final TreeMap<Integer, byte[]> indexed_result = super.addMultiple(rows);
// indexed_result is a Integer/byte[] relation
// that is used here to store the index
- Iterator<Map.Entry<Integer, byte[]>> i = indexed_result.entrySet().iterator();
+ final Iterator<Map.Entry<Integer, byte[]>> i = indexed_result.entrySet().iterator();
Map.Entry<Integer, byte[]> entry;
while (i.hasNext()) {
entry = i.next();
@@ -322,10 +323,10 @@ public class kelondroFlexTable extends kelondroFlexWidthArray implements kelondr
}
public synchronized ArrayList<kelondroRowCollection> removeDoubles() throws IOException {
- ArrayList<kelondroRowCollection> report = new ArrayList<kelondroRowCollection>();
+ final ArrayList<kelondroRowCollection> report = new ArrayList<kelondroRowCollection>();
kelondroRowSet rows;
- TreeSet<Integer> d = new TreeSet<Integer>();
- for (Integer[] is: index.removeDoubles()) {
+ final TreeSet<Integer> d = new TreeSet<Integer>();
+ for (final Integer[] is: index.removeDoubles()) {
rows = new kelondroRowSet(this.rowdef, is.length);
for (int j = 0; j < is.length; j++) {
d.add(is[j]);
@@ -343,15 +344,15 @@ public class kelondroFlexTable extends kelondroFlexWidthArray implements kelondr
return report;
}
- public synchronized kelondroRow.Entry remove(byte[] key) throws IOException {
+ public synchronized kelondroRow.Entry remove(final byte[] key) throws IOException {
// the underlying data structure is a file, where the order cannot be maintained. Gaps are filled with new values.
- int i = index.removei(key);
+ final int i = index.removei(key);
assert (index.geti(key) < 0); // must be deleted
if (i < 0) {
assert this.size() == index.size() : "content.size() = " + this.size() + ", index.size() = " + index.size();
return null;
}
- kelondroRow.Entry r = super.getOmitCol0(i, key);
+ final kelondroRow.Entry r = super.getOmitCol0(i, key);
if (r == null) {
serverLog.logSevere("kelondroFlexTable", "remove(): index failure; the index pointed to a cell which is empty. content.size() = " + this.size() + ", index.size() = " + ((index == null) ? 0 : index.size()));
// patch bug ***** FIND CAUSE! (see also: put)
@@ -367,7 +368,7 @@ public class kelondroFlexTable extends kelondroFlexWidthArray implements kelondr
}
public synchronized kelondroRow.Entry removeOne() throws IOException {
- int i = index.removeonei();
+ final int i = index.removeonei();
if (i < 0) return null;
kelondroRow.Entry r;
r = super.get(i);
@@ -376,11 +377,11 @@ public class kelondroFlexTable extends kelondroFlexWidthArray implements kelondr
return r;
}
- public synchronized kelondroCloneableIterator<byte[]> keys(boolean up, byte[] firstKey) throws IOException {
+ public synchronized kelondroCloneableIterator<byte[]> keys(final boolean up, final byte[] firstKey) throws IOException {
return index.keys(up, firstKey);
}
- public synchronized kelondroCloneableIterator<kelondroRow.Entry> rows(boolean up, byte[] firstKey) throws IOException {
+ public synchronized kelondroCloneableIterator<kelondroRow.Entry> rows(final boolean up, final byte[] firstKey) throws IOException {
if (index == null) return new rowIterator(up, firstKey);
assert this.size() == index.size() : "content.size() = " + this.size() + ", index.size() = " + index.size();
return new rowIterator(up, firstKey);
@@ -391,15 +392,15 @@ public class kelondroFlexTable extends kelondroFlexWidthArray implements kelondr
kelondroCloneableIterator<kelondroRow.Entry> indexIterator;
boolean up;
- public rowIterator(boolean up, byte[] firstKey) throws IOException {
+ public rowIterator(final boolean up, final byte[] firstKey) throws IOException {
this.up = up;
indexIterator = index.rows(up, firstKey);
}
- public rowIterator clone(Object modifier) {
+ public rowIterator clone(final Object modifier) {
try {
return new rowIterator(up, (byte[]) modifier);
- } catch (IOException e) {
+ } catch (final IOException e) {
return null;
}
}
@@ -417,10 +418,10 @@ public class kelondroFlexTable extends kelondroFlexWidthArray implements kelondr
serverLog.logSevere("kelondroFlexTable.rowIterator: " + tablename, "indexIterator returned null");
return null;
}
- int idx = (int) idxEntry.getColLong(1);
+ final int idx = (int) idxEntry.getColLong(1);
try {
return get(idx);
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
return null;
}
@@ -441,25 +442,25 @@ public class kelondroFlexTable extends kelondroFlexWidthArray implements kelondr
return tableTracker.keySet().iterator();
}
- public static final kelondroProfile profileStats(String filename) {
+ public static final kelondroProfile profileStats(final String filename) {
// returns a map for each file in the tracker;
// the map represents properties for each record oobjects,
// i.e. for cache memory allocation
- kelondroFlexTable theFlexTable = tableTracker.get(filename);
+ final kelondroFlexTable theFlexTable = tableTracker.get(filename);
return theFlexTable.profile();
}
- public static final Map<String, String> memoryStats(String filename) {
+ public static final Map<String, String> memoryStats(final String filename) {
// returns a map for each file in the tracker;
// the map represents properties for each record objects,
// i.e. for cache memory allocation
- kelondroFlexTable theFlexTable = tableTracker.get(filename);
+ final kelondroFlexTable theFlexTable = tableTracker.get(filename);
return theFlexTable.memoryStats();
}
private final Map<String, String> memoryStats() {
// returns statistical data about this object
- HashMap<String, String> map = new HashMap<String, String>();
+ final HashMap<String, String> map = new HashMap<String, String>();
map.put("tableIndexChunkSize", (!RAMIndex) ? "0" : Integer.toString(index.row().objectsize));
map.put("tableIndexCount", (!RAMIndex) ? "0" : Integer.toString(index.size()));
map.put("tableIndexMem", (!RAMIndex) ? "0" : Integer.toString((int) (index.row().objectsize * index.size() * kelondroRowCollection.growfactor)));
@@ -478,19 +479,19 @@ public class kelondroFlexTable extends kelondroFlexWidthArray implements kelondr
super.close();
}
- public static void main(String[] args) {
+ public static void main(final String[] args) {
// open a file, add one entry and exit
- File f = new File(args[0]);
- String name = args[1];
- kelondroRow row = new kelondroRow("Cardinal key-4 {b256}, byte[] x-64", kelondroNaturalOrder.naturalOrder, 0);
+ final File f = new File(args[0]);
+ final String name = args[1];
+ final kelondroRow row = new kelondroRow("Cardinal key-4 {b256}, byte[] x-64", kelondroNaturalOrder.naturalOrder, 0);
try {
- kelondroFlexTable t = new kelondroFlexTable(f, name, row, 0, true);
- kelondroRow.Entry entry = row.newEntry();
+ final kelondroFlexTable t = new kelondroFlexTable(f, name, row, 0, true);
+ final kelondroRow.Entry entry = row.newEntry();
entry.setCol(0, System.currentTimeMillis());
entry.setCol(1, "dummy".getBytes());
t.put(entry);
t.close();
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
}
diff --git a/source/de/anomic/kelondro/kelondroFlexWidthArray.java b/source/de/anomic/kelondro/kelondroFlexWidthArray.java
index 17c30654b..16d8196fb 100644
--- a/source/de/anomic/kelondro/kelondroFlexWidthArray.java
+++ b/source/de/anomic/kelondro/kelondroFlexWidthArray.java
@@ -44,32 +44,32 @@ public class kelondroFlexWidthArray implements kelondroArray {
protected String tablename;
protected String filename;
- public kelondroFlexWidthArray(File path, String tablename, kelondroRow rowdef, boolean resetOnFail) {
+ public kelondroFlexWidthArray(final File path, final String tablename, final kelondroRow rowdef, final boolean resetOnFail) {
this.path = path;
this.rowdef = rowdef;
this.tablename = tablename;
try {
init();
- } catch (IOException e) {
+ } catch (final IOException e) {
if (resetOnFail) {
serverLog.logSevere("kelondroFlexWidthArray", "IOException during initialization of " + new File(path, tablename).toString() + ": reset");
delete(path, tablename);
try {
init();
- } catch (IOException e1) {
+ } catch (final IOException e1) {
e1.printStackTrace();
throw new kelondroException("IOException during initialization of " + new File(path, tablename).toString() + ": cannot reset: " + e1.getMessage());
}
} else {
throw new kelondroException("IOException during initialization of " + new File(path, tablename).toString() + ": not allowed to reset: " + e.getMessage());
}
- } catch (kelondroException e) {
+ } catch (final kelondroException e) {
if (resetOnFail) {
serverLog.logSevere("kelondroFlexWidthArray", "kelondroException during initialization of " + new File(path, tablename).toString() + ": reset");
delete(path, tablename);
try {
init();
- } catch (IOException e1) {
+ } catch (final IOException e1) {
e1.printStackTrace();
throw new kelondroException("kelondroException during initialization of " + new File(path, tablename).toString() + ": cannot reset: " + e1.getMessage());
}
@@ -90,7 +90,7 @@ public class kelondroFlexWidthArray implements kelondroArray {
}
// check if table directory exists
- File tabledir = new File(path, tablename);
+ final File tabledir = new File(path, tablename);
if (tabledir.exists()) {
if (!(tabledir.isDirectory())) throw new IOException("path " + tabledir.toString() + " must be a directory");
} else {
@@ -100,11 +100,11 @@ public class kelondroFlexWidthArray implements kelondroArray {
this.filename = tabledir.getCanonicalPath();
// save/check property file for this array
- File propfile = new File(tabledir, "properties");
+ final File propfile = new File(tabledir, "properties");
Map<String, String> props = new HashMap<String, String>();
if (propfile.exists()) {
props = serverFileUtils.loadHashMap(propfile);
- String stored_rowdef = props.get("rowdef");
+ final String stored_rowdef = props.get("rowdef");
if ((stored_rowdef == null) || (!(rowdef.subsumes(new kelondroRow(stored_rowdef, rowdef.objectOrder, 0))))) {
System.out.println("FATAL ERROR: stored rowdef '" + stored_rowdef + "' does not match with new rowdef '" +
rowdef + "' for flex table '" + path + "', table " + tablename);
@@ -115,13 +115,13 @@ public class kelondroFlexWidthArray implements kelondroArray {
serverFileUtils.saveMap(propfile, props, "FlexWidthArray properties");
// open existing files
- String[] files = tabledir.list();
+ final String[] files = tabledir.list();
for (int i = 0; i < files.length; i++) {
if ((files[i].startsWith("col.") && (files[i].endsWith(".list")))) {
- int colstart = Integer.parseInt(files[i].substring(4, 7));
- int colend = (files[i].charAt(7) == '-') ? Integer.parseInt(files[i].substring(8, 11)) : colstart;
+ final int colstart = Integer.parseInt(files[i].substring(4, 7));
+ final int colend = (files[i].charAt(7) == '-') ? Integer.parseInt(files[i].substring(8, 11)) : colstart;
- kelondroColumn columns[] = new kelondroColumn[colend - colstart + 1];
+ final kelondroColumn columns[] = new kelondroColumn[colend - colstart + 1];
for (int j = colstart; j <= colend; j++) columns[j-colstart] = rowdef.column(j);
col[colstart] = new kelondroFixedWidthArray(new File(tabledir, files[i]), new kelondroRow(columns, (colstart == 0) ? rowdef.objectOrder : kelondroNaturalOrder.naturalOrder, 0), 16);
for (int j = colstart; j <= colend; j++) check = check.substring(0, j) + "X" + check.substring(j + 1);
@@ -137,7 +137,7 @@ public class kelondroFlexWidthArray implements kelondroArray {
q--;
}
// create new array file
- kelondroColumn[] columns = new kelondroColumn[q - p + 1];
+ final kelondroColumn[] columns = new kelondroColumn[q - p + 1];
for (int j = p; j <= q; j++) {
columns[j - p] = rowdef.column(j);
check = check.substring(0, j) + "X" + check.substring(j + 1);
@@ -150,10 +150,10 @@ public class kelondroFlexWidthArray implements kelondroArray {
return this.filename;
}
- public static int staticsize(File path, String tablename) {
+ public static int staticsize(final File path, final String tablename) {
// check if table directory exists
- File tabledir = new File(path, tablename);
+ final File tabledir = new File(path, tablename);
if (tabledir.exists()) {
if (!(tabledir.isDirectory())) return 0;
} else {
@@ -161,19 +161,19 @@ public class kelondroFlexWidthArray implements kelondroArray {
}
// open existing files
- File file = new File(tabledir, "col.000.list");
+ final File file = new File(tabledir, "col.000.list");
return kelondroAbstractRecords.staticsize(file);
}
- public static void delete(File path, String tablename) {
- File tabledir = new File(path, tablename);
+ public static void delete(final File path, final String tablename) {
+ final File tabledir = new File(path, tablename);
if (!(tabledir.exists())) return;
if ((!(tabledir.isDirectory()))) {
tabledir.delete();
return;
}
- String[] files = tabledir.list();
+ final String[] files = tabledir.list();
for (int i = 0; i < files.length; i++) {
new File(tabledir, files[i]).delete();
}
@@ -199,7 +199,7 @@ public class kelondroFlexWidthArray implements kelondroArray {
}
}
- protected static final String colfilename(int start, int end) {
+ protected static final String colfilename(final int start, final int end) {
String f = Integer.toString(end);
while (f.length() < 3) f = "0" + f;
if (start == end) return "col." + f + ".list";
@@ -218,7 +218,7 @@ public class kelondroFlexWidthArray implements kelondroArray {
return col[0].size();
}
- public synchronized void setMultiple(TreeMap<Integer, kelondroRow.Entry> entries) throws IOException {
+ public synchronized void setMultiple(final TreeMap<Integer, kelondroRow.Entry> entries) throws IOException {
// a R/W head path-optimized option to write a set of entries
Iterator<Map.Entry<Integer, kelondroRow.Entry>> i;
Map.Entry<Integer, kelondroRow.Entry> entry;
@@ -240,11 +240,11 @@ public class kelondroFlexWidthArray implements kelondroArray {
}
}
- public synchronized void set(int index, kelondroRow.Entry rowentry) throws IOException {
+ public synchronized void set(final int index, final kelondroRow.Entry rowentry) throws IOException {
assert rowentry.objectsize() == this.rowdef.objectsize;
int c = 0;
kelondroRow.Entry e;
- byte[] reb = rowentry.bytes();
+ final byte[] reb = rowentry.bytes();
while (c < rowdef.columns()) {
e = col[c].row().newEntry(reb, rowdef.colstart[c], false);
col[c].set(index, e);
@@ -252,10 +252,10 @@ public class kelondroFlexWidthArray implements kelondroArray {
}
}
- public synchronized int add(kelondroRow.Entry rowentry) throws IOException {
+ public synchronized int add(final kelondroRow.Entry rowentry) throws IOException {
assert rowentry.objectsize() == this.rowdef.objectsize;
int index = -1;
- byte[] reb = rowentry.bytes();
+ final byte[] reb = rowentry.bytes();
index = col[0].add(col[0].row().newEntry(reb, 0, false));
int c = col[0].row().columns();
@@ -267,14 +267,14 @@ public class kelondroFlexWidthArray implements kelondroArray {
}
@SuppressWarnings("unchecked")
- protected synchronized TreeMap<Integer, byte[]> addMultiple(List<kelondroRow.Entry> rows) throws IOException {
+ protected synchronized TreeMap<Integer, byte[]> addMultiple(final List<kelondroRow.Entry> rows) throws IOException {
// result is a Integer/byte[] relation
// of newly added rows (index, key)
- TreeMap<Integer, byte[]> indexref = new TreeMap<Integer, byte[]>();
+ final TreeMap<Integer, byte[]> indexref = new TreeMap<Integer, byte[]>();
Iterator<kelondroRow.Entry> i;
kelondroRow.Entry rowentry;
// prepare storage for other columns
- TreeMap<Integer, kelondroRow.Entry>[] colm = new TreeMap[col.length];
+ final TreeMap<Integer, kelondroRow.Entry>[] colm = new TreeMap[col.length];
for (int j = 0; j < col.length; j++) {
if (col[j] == null) colm[j] = null; else colm[j] = new TreeMap<Integer, kelondroRow.Entry>();
}
@@ -285,7 +285,7 @@ public class kelondroFlexWidthArray implements kelondroArray {
kelondroRow.Entry e;
int index = -1;
- byte[] reb = rowentry.bytes();
+ final byte[] reb = rowentry.bytes();
e = col[0].row().newEntry(reb, 0, false);
index = col[0].add(e);
int c = col[0].row().columns();
@@ -306,11 +306,11 @@ public class kelondroFlexWidthArray implements kelondroArray {
return indexref;
}
- public synchronized kelondroRow.Entry get(int index) throws IOException {
+ public synchronized kelondroRow.Entry get(final int index) throws IOException {
kelondroRow.Entry e = col[0].getIfValid(index);
//assert e != null;
if (e == null) return null; // probably a deleted entry
- kelondroRow.Entry p = rowdef.newEntry();
+ final kelondroRow.Entry p = rowdef.newEntry();
p.setCol(0, e.getColBytes(0));
int r = col[0].row().columns();
while (r < rowdef.columns()) {
@@ -323,9 +323,9 @@ public class kelondroFlexWidthArray implements kelondroArray {
return p;
}
- public synchronized kelondroRow.Entry getOmitCol0(int index, byte[] col0) throws IOException {
+ public synchronized kelondroRow.Entry getOmitCol0(final int index, final byte[] col0) throws IOException {
assert col[0].row().columns() == 1;
- kelondroRow.Entry p = rowdef.newEntry();
+ final kelondroRow.Entry p = rowdef.newEntry();
kelondroRow.Entry e;
p.setCol(0, col0);
int r = 1;
@@ -339,7 +339,7 @@ public class kelondroFlexWidthArray implements kelondroArray {
return p;
}
- public synchronized void remove(int index) throws IOException {
+ public synchronized void remove(final int index) throws IOException {
int r = 0;
// remove only from the first column
@@ -366,11 +366,11 @@ public class kelondroFlexWidthArray implements kelondroArray {
System.out.println("EndOfTable");
}
- public static void main(String[] args) {
+ public static void main(final String[] args) {
//File f = new File("d:\\\\mc\\privat\\fixtest.db");
- File f = new File("/Users/admin/");
- kelondroRow rowdef = new kelondroRow("byte[] a-12, byte[] b-4", kelondroNaturalOrder.naturalOrder, 0);
- String testname = "flextest";
+ final File f = new File("/Users/admin/");
+ final kelondroRow rowdef = new kelondroRow("byte[] a-12, byte[] b-4", kelondroNaturalOrder.naturalOrder, 0);
+ final String testname = "flextest";
try {
System.out.println("erster Test");
kelondroFlexWidthArray.delete(f, testname);
@@ -413,7 +413,7 @@ public class kelondroFlexWidthArray implements kelondroArray {
k.col[0].print();
k.close();
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
}
diff --git a/source/de/anomic/kelondro/kelondroFullRecords.java b/source/de/anomic/kelondro/kelondroFullRecords.java
index 8c359fa78..192dcd5fc 100644
--- a/source/de/anomic/kelondro/kelondroFullRecords.java
+++ b/source/de/anomic/kelondro/kelondroFullRecords.java
@@ -37,24 +37,24 @@ public class kelondroFullRecords extends kelondroAbstractRecords {
private static TreeMap<String, kelondroFullRecords> recordTracker = new TreeMap<String, kelondroFullRecords>();
public kelondroFullRecords(
- File file,
- short ohbytec, short ohhandlec,
- kelondroRow rowdef, int FHandles, int txtProps, int txtPropWidth) throws IOException {
+ final File file,
+ final short ohbytec, final short ohhandlec,
+ final kelondroRow rowdef, final int FHandles, final int txtProps, final int txtPropWidth) throws IOException {
super(file, true, ohbytec, ohhandlec, rowdef, FHandles, txtProps, txtPropWidth);
recordTracker.put(this.filename, this);
}
public kelondroFullRecords(
- kelondroRA ra, String filename,
- short ohbytec, short ohhandlec,
- kelondroRow rowdef, int FHandles, int txtProps, int txtPropWidth,
- boolean exitOnFail) {
+ final kelondroRA ra, final String filename,
+ final short ohbytec, final short ohhandlec,
+ final kelondroRow rowdef, final int FHandles, final int txtProps, final int txtPropWidth,
+ final boolean exitOnFail) {
super(ra, filename, true, ohbytec, ohhandlec, rowdef, FHandles, txtProps, txtPropWidth, exitOnFail);
recordTracker.put(this.filename, this);
}
public kelondroFullRecords(
- kelondroRA ra, String filename) throws IOException{
+ final kelondroRA ra, final String filename) throws IOException{
super(ra, filename, true);
recordTracker.put(this.filename, this);
}
@@ -64,7 +64,7 @@ public class kelondroFullRecords extends kelondroAbstractRecords {
return recordTracker.keySet().iterator();
}
- protected synchronized void deleteNode(kelondroHandle handle) throws IOException {
+ protected synchronized void deleteNode(final kelondroHandle handle) throws IOException {
super.deleteNode(handle);
}
@@ -73,7 +73,7 @@ public class kelondroFullRecords extends kelondroAbstractRecords {
super.close();
}
- public kelondroNode newNode(kelondroHandle handle, byte[] bulk, int offset) throws IOException {
+ public kelondroNode newNode(final kelondroHandle handle, final byte[] bulk, final int offset) throws IOException {
return new EcoNode(handle, bulk, offset);
}
@@ -84,7 +84,7 @@ public class kelondroFullRecords extends kelondroAbstractRecords {
private boolean ohChanged = false;
private boolean bodyChanged = false;
- public EcoNode(byte[] rowinstance) throws IOException {
+ public EcoNode(final byte[] rowinstance) throws IOException {
// this initializer is used to create nodes from bulk-read byte arrays
assert ((rowinstance == null) || (rowinstance.length == ROW.objectsize)) : "bulkchunk.length = " + (rowinstance == null ? "null" : rowinstance.length) + ", ROW.width(0) = " + ROW.width(0);
this.handle = new kelondroHandle(USAGE.allocatePayload(rowinstance));
@@ -104,7 +104,7 @@ public class kelondroFullRecords extends kelondroAbstractRecords {
this.bodyChanged = false;
}
- public EcoNode(kelondroHandle handle, byte[] bulkchunk, int offset) throws IOException {
+ public EcoNode(final kelondroHandle handle, final byte[] bulkchunk, final int offset) throws IOException {
// this initializer is used to create nodes from bulk-read byte arrays
// if write is true, then the chunk in bulkchunk is written to the file
// othervise it is considered equal to what is stored in the file
@@ -144,7 +144,7 @@ public class kelondroFullRecords extends kelondroAbstractRecords {
this.bodyChanged = changed;
}
- public EcoNode(kelondroHandle handle) throws IOException {
+ public EcoNode(final kelondroHandle handle) throws IOException {
// this creates an entry with an pre-reserved entry position.
// values can be written using the setValues() method,
// but we expect that values are already there in the file.
@@ -176,14 +176,14 @@ public class kelondroFullRecords extends kelondroAbstractRecords {
return this.handle;
}
- public void setOHByte(int i, byte b) {
+ public void setOHByte(final int i, final byte b) {
if (i >= OHBYTEC) throw new IllegalArgumentException("setOHByte: wrong index " + i);
if (this.handle.index == kelondroHandle.NUL) throw new kelondroException(filename, "setOHByte: no handle assigned");
this.ohChunk[i] = b;
this.ohChanged = true;
}
- public void setOHHandle(int i, kelondroHandle otherhandle) {
+ public void setOHHandle(final int i, final kelondroHandle otherhandle) {
assert (i < OHHANDLEC): "setOHHandle: wrong array size " + i;
assert (this.handle.index != kelondroHandle.NUL): "setOHHandle: no handle assigned ind file" + filename;
if (otherhandle == null) {
@@ -195,20 +195,20 @@ public class kelondroFullRecords extends kelondroAbstractRecords {
this.ohChanged = true;
}
- public byte getOHByte(int i) {
+ public byte getOHByte(final int i) {
if (i >= OHBYTEC) throw new IllegalArgumentException("getOHByte: wrong index " + i);
if (this.handle.index == kelondroHandle.NUL) throw new kelondroException(filename, "Cannot load OH values");
return this.ohChunk[i];
}
- public kelondroHandle getOHHandle(int i) {
+ public kelondroHandle getOHHandle(final int i) {
if (this.handle.index == kelondroHandle.NUL) throw new kelondroException(filename, "Cannot load OH values");
assert (i < OHHANDLEC): "handle index out of bounds: " + i + " in file " + filename;
- int h = bytes2int(this.ohChunk, OHBYTEC + 4 * i);
+ final int h = bytes2int(this.ohChunk, OHBYTEC + 4 * i);
return (h == kelondroHandle.NUL) ? null : new kelondroHandle(h);
}
- public synchronized void setValueRow(byte[] row) throws IOException {
+ public synchronized void setValueRow(final byte[] row) throws IOException {
// if the index is defined, then write values directly to the file, else only to the object
if ((row != null) && (row.length != ROW.objectsize)) throw new IOException("setValueRow with wrong (" + row.length + ") row length instead correct: " + ROW.objectsize);
@@ -247,7 +247,7 @@ public class kelondroFullRecords extends kelondroAbstractRecords {
// place the data to the file
- boolean doCommit = this.ohChanged || this.bodyChanged;
+ final boolean doCommit = this.ohChanged || this.bodyChanged;
// save head
synchronized (entryFile) {
diff --git a/source/de/anomic/kelondro/kelondroHandle.java b/source/de/anomic/kelondro/kelondroHandle.java
index e3b0a9c55..f5bd87d45 100644
--- a/source/de/anomic/kelondro/kelondroHandle.java
+++ b/source/de/anomic/kelondro/kelondroHandle.java
@@ -32,7 +32,7 @@ public class kelondroHandle implements Comparable<kelondroHandle> {
protected int index;
- protected kelondroHandle(int i) {
+ protected kelondroHandle(final int i) {
assert (i == NUL) || (i >= 0) : "node handle index too low: " + i;
//assert (i == NUL) || (i < USAGE.allCount()) : "node handle index too high: " + i + ", USEDC=" + USAGE.USEDC + ", FREEC=" + USAGE.FREEC;
this.index = i;
@@ -50,19 +50,19 @@ public class kelondroHandle implements Comparable<kelondroHandle> {
return s;
}
- public boolean equals(kelondroHandle h) {
+ public boolean equals(final kelondroHandle h) {
assert (index != NUL);
assert (h.index != NUL);
return (this.index == h.index);
}
- public boolean equals(Object h) {
+ public boolean equals(final Object h) {
assert (index != NUL);
assert (((kelondroHandle) h).index != NUL);
return (h instanceof kelondroHandle && this.index == ((kelondroHandle) h).index);
}
- public int compare(kelondroHandle h0, kelondroHandle h1) {
+ public int compare(final kelondroHandle h0, final kelondroHandle h1) {
assert ((h0).index != NUL);
assert ((h1).index != NUL);
if ((h0).index < (h1).index) return -1;
@@ -70,7 +70,7 @@ public class kelondroHandle implements Comparable<kelondroHandle> {
return 0;
}
- public int compareTo(kelondroHandle h) {
+ public int compareTo(final kelondroHandle h) {
// this is needed for a TreeMap
assert (index != NUL) : "this.index is NUL in compareTo";
assert ((h).index != NUL) : "handle.index is NUL in compareTo";
diff --git a/source/de/anomic/kelondro/kelondroHashtable.java b/source/de/anomic/kelondro/kelondroHashtable.java
index 0de114a99..285830182 100644
--- a/source/de/anomic/kelondro/kelondroHashtable.java
+++ b/source/de/anomic/kelondro/kelondroHashtable.java
@@ -115,7 +115,7 @@ import java.io.IOException;
public class kelondroHashtable {
- private kelondroFixedWidthArray hashArray;
+ private final kelondroFixedWidthArray hashArray;
protected int offset;
protected int maxk;
private int maxrehash;
@@ -123,7 +123,7 @@ public class kelondroHashtable {
private static final byte[] dummyKey = kelondroBase64Order.enhancedCoder.encodeLong(0, 5).getBytes();
- public kelondroHashtable(File file, kelondroRow rowdef, int offset, int maxsize, int maxrehash) throws IOException {
+ public kelondroHashtable(final File file, final kelondroRow rowdef, final int offset, final int maxsize, final int maxrehash) throws IOException {
// this creates a new hashtable
// the key element is not part of the columns array
// this is unlike the kelondroTree, where the key is part of a row
@@ -133,7 +133,7 @@ public class kelondroHashtable {
// this number is needed to omit grow of the table in case of re-hashing
// the maxsize is re-computed to a virtual folding height and will result in a tablesize
// less than the given maxsize. The actual maxsize can be retrieved by maxsize()
- boolean fileExisted = file.exists();
+ final boolean fileExisted = file.exists();
this.hashArray = new kelondroFixedWidthArray(file, extCol(rowdef), 6);
if (fileExisted) {
this.offset = hashArray.geti(0);
@@ -153,8 +153,8 @@ public class kelondroHashtable {
}
}
- private kelondroRow extCol(kelondroRow rowdef) {
- kelondroColumn[] newCol = new kelondroColumn[rowdef.columns() + 1];
+ private kelondroRow extCol(final kelondroRow rowdef) {
+ final kelondroColumn[] newCol = new kelondroColumn[rowdef.columns() + 1];
newCol[0] = new kelondroColumn("Cardinal key-4 {b256}");
for (int i = 0; i < rowdef.columns(); i++) newCol[i + 1] = rowdef.column(i);
return new kelondroRow(newCol, rowdef.objectOrder, rowdef.primaryKeyIndex);
@@ -166,22 +166,22 @@ public class kelondroHashtable {
return p;
}
- public synchronized byte[][] get(int key) throws IOException {
- Object[] search = search(new Hash(key));
+ public synchronized byte[][] get(final int key) throws IOException {
+ final Object[] search = search(new Hash(key));
if (search[1] == null) return null;
- byte[][] row = (byte[][]) search[1];
- byte[][] result = new byte[row.length - 1][];
+ final byte[][] row = (byte[][]) search[1];
+ final byte[][] result = new byte[row.length - 1][];
System.arraycopy(row, 1, result, 0, row.length - 1);
return result;
}
- public synchronized kelondroRow.Entry put(int key, kelondroRow.Entry rowentry) throws IOException {
- Hash hash = new Hash(key);
+ public synchronized kelondroRow.Entry put(final int key, final kelondroRow.Entry rowentry) throws IOException {
+ final Hash hash = new Hash(key);
// find row
- Object[] search = search(hash);
+ final Object[] search = search(hash);
kelondroRow.Entry oldhkrow;
- int rowNumber = ((Integer) search[0]).intValue();
+ final int rowNumber = ((Integer) search[0]).intValue();
if (search[1] == null) {
oldhkrow = null;
} else {
@@ -192,14 +192,14 @@ public class kelondroHashtable {
while (rowNumber >= hashArray.size()) hashArray.set(hashArray.size(), dummyRow);
// write row
- kelondroRow.Entry newhkrow = hashArray.row().newEntry();
+ final kelondroRow.Entry newhkrow = hashArray.row().newEntry();
newhkrow.setCol(0, hash.key());
newhkrow.setCol(1, rowentry.bytes());
hashArray.set(rowNumber, newhkrow);
return (oldhkrow == null ? null : hashArray.row().newEntry(oldhkrow.getColBytes(1)));
}
- private Object[] search(Hash hash) throws IOException {
+ private Object[] search(final Hash hash) throws IOException {
kelondroRow.Entry hkrow;
int rowKey;
int rowNumber;
@@ -219,7 +219,7 @@ public class kelondroHashtable {
int key;
int hash;
int depth;
- public Hash(int key) {
+ public Hash(final int key) {
this.key = key;
this.hash = key;
this.depth = offset + 1;
diff --git a/source/de/anomic/kelondro/kelondroIntBytesMap.java b/source/de/anomic/kelondro/kelondroIntBytesMap.java
index 6ccdb15db..c5ae1d6dc 100644
--- a/source/de/anomic/kelondro/kelondroIntBytesMap.java
+++ b/source/de/anomic/kelondro/kelondroIntBytesMap.java
@@ -38,11 +38,12 @@ public class kelondroIntBytesMap {
// to index0 with addb, and a runtime-phase where data can only be written
// to index1 with putb.
- private kelondroRow rowdef;
- private kelondroRowSet index0, index1;
- private kelondroOrder<kelondroRow.Entry> entryOrder;
+ private final kelondroRow rowdef;
+ private final kelondroRowSet index0;
+ private kelondroRowSet index1;
+ private final kelondroOrder<kelondroRow.Entry> entryOrder;
- public kelondroIntBytesMap(int payloadSize, int initSize) {
+ public kelondroIntBytesMap(final int payloadSize, final int initSize) {
this.rowdef = new kelondroRow("Cardinal key-4 {b256}, byte[] payload-" + payloadSize, kelondroNaturalOrder.naturalOrder, 0);
this.index0 = new kelondroRowSet(rowdef, initSize);
this.index1 = null;
@@ -60,9 +61,9 @@ public class kelondroIntBytesMap {
return index0.row();
}
- public byte[] getb(int ii) {
+ public byte[] getb(final int ii) {
assert ii >= 0 : "i = " + ii;
- byte[] key = kelondroNaturalOrder.encodeLong(ii, 4);
+ final byte[] key = kelondroNaturalOrder.encodeLong(ii, 4);
if (index0 != null) {
if (index1 == null) {
// finish initialization phase
@@ -70,19 +71,19 @@ public class kelondroIntBytesMap {
index0.uniq();
index1 = new kelondroRowSet(rowdef, 0);
}
- kelondroRow.Entry indexentry = index0.get(key);
+ final kelondroRow.Entry indexentry = index0.get(key);
if (indexentry != null) return indexentry.getColBytes(1);
}
assert (index1 != null);
- kelondroRow.Entry indexentry = index1.get(key);
+ final kelondroRow.Entry indexentry = index1.get(key);
if (indexentry == null) return null;
return indexentry.getColBytes(1);
}
- public byte[] putb(int ii, byte[] value) {
+ public byte[] putb(final int ii, final byte[] value) {
assert ii >= 0 : "i = " + ii;
assert value != null;
- byte[] key = kelondroNaturalOrder.encodeLong(ii, 4);
+ final byte[] key = kelondroNaturalOrder.encodeLong(ii, 4);
if (index0 != null) {
if (index1 == null) {
// finish initialization phase
@@ -90,9 +91,9 @@ public class kelondroIntBytesMap {
index0.uniq();
index1 = new kelondroRowSet(rowdef, 0);
}
- kelondroRow.Entry indexentry = index0.get(key);
+ final kelondroRow.Entry indexentry = index0.get(key);
if (indexentry != null) {
- byte[] oldv = indexentry.getColBytes(1);
+ final byte[] oldv = indexentry.getColBytes(1);
indexentry.setCol(0, key);
indexentry.setCol(1, value);
index0.put(indexentry);
@@ -103,28 +104,28 @@ public class kelondroIntBytesMap {
// at this point index1 cannot be null
assert (index1 != null);
- kelondroRow.Entry newentry = rowdef.newEntry();
+ final kelondroRow.Entry newentry = rowdef.newEntry();
newentry.setCol(0, ii);
newentry.setCol(1, value);
- kelondroRow.Entry oldentry = index1.put(newentry);
+ final kelondroRow.Entry oldentry = index1.put(newentry);
if (oldentry == null) return null;
return oldentry.getColBytes(1);
}
- public void addb(int ii, byte[] value) {
+ public void addb(final int ii, final byte[] value) {
assert index1 == null; // valid only in init-phase
assert ii >= 0 : "i = " + ii;
assert value != null;
- kelondroRow.Entry newentry = index0.row().newEntry();
+ final kelondroRow.Entry newentry = index0.row().newEntry();
newentry.setCol(0, ii);
newentry.setCol(1, value);
index0.addUnique(newentry);
}
- public byte[] removeb(int ii) {
+ public byte[] removeb(final int ii) {
assert ii >= 0 : "i = " + ii;
- byte[] key = kelondroNaturalOrder.encodeLong(ii, 4);
+ final byte[] key = kelondroNaturalOrder.encodeLong(ii, 4);
if (index0 != null) {
if (index1 == null) {
// finish initialization phase
@@ -132,7 +133,7 @@ public class kelondroIntBytesMap {
index0.uniq();
index1 = new kelondroRowSet(rowdef, 0);
}
- kelondroRow.Entry indexentry = index0.remove(key);
+ final kelondroRow.Entry indexentry = index0.remove(key);
if (indexentry != null) {
return indexentry.getColBytes(1);
}
@@ -141,21 +142,21 @@ public class kelondroIntBytesMap {
// at this point index1 cannot be null
assert (index1 != null);
if (index1.size() == 0) return null;
- kelondroRow.Entry indexentry = index1.remove(key);
+ final kelondroRow.Entry indexentry = index1.remove(key);
if (indexentry == null) return null;
return indexentry.getColBytes(1);
}
public byte[] removeoneb() {
if ((index1 != null) && (index1.size() != 0)) {
- kelondroRow.Entry indexentry = index1.removeOne();
+ final kelondroRow.Entry indexentry = index1.removeOne();
assert (indexentry != null);
if (indexentry == null) return null;
//assert consistencyAnalysis0() : "consistency problem: " + consistencyAnalysis();
return indexentry.getColBytes(1);
}
if ((index0 != null) && (index0.size() != 0)) {
- kelondroRow.Entry indexentry = index0.removeOne();
+ final kelondroRow.Entry indexentry = index0.removeOne();
assert (indexentry != null);
if (indexentry == null) return null;
//assert consistencyAnalysis0() : "consistency problem: " + consistencyAnalysis();
@@ -217,19 +218,19 @@ public class kelondroIntBytesMap {
return kelondroProfile.consolidate(index0.profile(), index1.profile());
}
- public static void main(String[] args) {
+ public static void main(final String[] args) {
boolean assertEnabled = false;
assert assertEnabled = true;
System.out.println((assertEnabled) ? "asserts are enabled" : "enable asserts with 'java -ea'; not enabled yet");
- long start = System.currentTimeMillis();
- long randomstart = 0;
- Random random = new Random(randomstart);
+ final long start = System.currentTimeMillis();
+ final long randomstart = 0;
+ final Random random = new Random(randomstart);
long r;
Long R;
int p, rc = 0;
- ArrayList<Long> ra = new ArrayList<Long>();
- HashSet<Long> jcontrol = new HashSet<Long>();
- kelondroIntBytesMap kcontrol = new kelondroIntBytesMap(1, 0);
+ final ArrayList<Long> ra = new ArrayList<Long>();
+ final HashSet<Long> jcontrol = new HashSet<Long>();
+ final kelondroIntBytesMap kcontrol = new kelondroIntBytesMap(1, 0);
for (int i = 0; i < 1000000; i++) {
r = Math.abs(random.nextLong() % 10000);
//System.out.println("add " + r);
diff --git a/source/de/anomic/kelondro/kelondroLock.java b/source/de/anomic/kelondro/kelondroLock.java
index 00b715a8e..a9c13815a 100644
--- a/source/de/anomic/kelondro/kelondroLock.java
+++ b/source/de/anomic/kelondro/kelondroLock.java
@@ -40,29 +40,29 @@ public class kelondroLock {
apply(-1);
}
- public synchronized void apply(long millis) {
+ public synchronized void apply(final long millis) {
// sets a lock that is valid for a specific time
// if the time is over, the lock is released automatically
if (locked()) {
do {
try { wait(100); }
- catch (InterruptedException e) { }
- catch (Exception e) { e.printStackTrace(); }
+ catch (final InterruptedException e) { }
+ catch (final Exception e) { e.printStackTrace(); }
} while (locked());
}
lock = true;
releaseTime = (millis < 0) ? Long.MAX_VALUE : System.currentTimeMillis() + millis;
}
- public synchronized boolean stay(long waitMillis, long lockMillis) {
+ public synchronized boolean stay(final long waitMillis, final long lockMillis) {
// this tries to apply a lock, but does not block infinitely until
// the lock is released. If after the given time the lock is not released
// the method returns with false and no more lock is applied
// if the lock was applied successfully, it returns with true
if (locked()) {
try { wait(waitMillis); }
- catch (InterruptedException e) { }
- catch (Exception e) { e.printStackTrace(); }
+ catch (final InterruptedException e) { }
+ catch (final Exception e) { e.printStackTrace(); }
if (locked()) return false;
}
lock = true;
diff --git a/source/de/anomic/kelondro/kelondroMHashMap.java b/source/de/anomic/kelondro/kelondroMHashMap.java
index c3d1aa0bc..fb141f2b3 100644
--- a/source/de/anomic/kelondro/kelondroMHashMap.java
+++ b/source/de/anomic/kelondro/kelondroMHashMap.java
@@ -30,14 +30,14 @@ public class kelondroMHashMap {
int valuelen;
int reclen, count;
byte[] mem;
- private byte[] emptykey;
+ private final byte[] emptykey;
- public kelondroMHashMap(int valuelen) {
+ public kelondroMHashMap(final int valuelen) {
// initializes a hash map with integer access key
this(4, valuelen);
}
- public kelondroMHashMap(int keylen, int valuelen) {
+ public kelondroMHashMap(final int keylen, final int valuelen) {
this.keylen = keylen;
this.valuelen = valuelen;
this.reclen = keylen + valuelen;
@@ -48,7 +48,7 @@ public class kelondroMHashMap {
for (int i = 0; i < (mem.length / reclen); i++) System.arraycopy(emptykey, 0, mem, i * reclen, keylen);
}
- private boolean equals(int posKeyInMem, byte[] otherkey) {
+ private boolean equals(final int posKeyInMem, final byte[] otherkey) {
assert (otherkey.length == keylen);
int pos = posKeyInMem * reclen;
int i = 0;
@@ -64,14 +64,14 @@ public class kelondroMHashMap {
return mem.length / reclen;
}
- private static int hashkey(byte[] key, int capacity) {
+ private static int hashkey(final byte[] key, final int capacity) {
int h = 0;
for (int i = 0; i < key.length; i++) h = h * 15 + (0xff & key[i]);
//System.out.println("hash code of key " + new String(key) + " is " + h);
return h % capacity;
}
- private static int rehash(int previousKey, int capacity) {
+ private static int rehash(int previousKey, final int capacity) {
if (previousKey == 0) previousKey = capacity;
return previousKey - 1;
}
@@ -80,7 +80,7 @@ public class kelondroMHashMap {
return count;
}
- private int findExisting(byte[] key) {
+ private int findExisting(final byte[] key) {
// returns an index position if found; -1 otherwise
int hash = hashkey(key, capacity());
//System.out.println("first guess for key " + new String(key) + ": " + hash + "( capacity is " + capacity() + " )");
@@ -93,7 +93,7 @@ public class kelondroMHashMap {
return -1;
}
- private int findSpace(byte[] key) {
+ private int findSpace(final byte[] key) {
// returns an new index position which is empty
// if there is no space left -1 is returned
int hash = hashkey(key, capacity());
@@ -105,7 +105,7 @@ public class kelondroMHashMap {
return -1;
}
- private static int findSpace(byte[] m, byte[] key, int rl, int trycount, int capacity) {
+ private static int findSpace(final byte[] m, final byte[] key, final int rl, final int trycount, final int capacity) {
// returns an new index position which is empty
// if there is no space left -1 is returned
int hash = hashkey(key, capacity);
@@ -124,11 +124,11 @@ public class kelondroMHashMap {
(byte) ((v >>> 8) & 0xFF), (byte) ((v >>> 0) & 0xFF)};
}
- public void put(int key, byte[] value) {
+ public void put(final int key, final byte[] value) {
put(toByteKey(key), value);
}
- public void put(byte[] key, byte[] value) {
+ public void put(final byte[] key, final byte[] value) {
// inserts a new value or overwrites existing
// if the hash is full, a RuntimeException is thrown
// this method does not return the old value to avoid generation of objects
@@ -144,10 +144,10 @@ public class kelondroMHashMap {
// create temporary bigger hashtable and insert all
synchronized (mem) {
System.out.println("increasing space to " + mem.length * 2);
- int newspace = mem.length * 2;
- int newcapacity = capacity() * 2;
+ final int newspace = mem.length * 2;
+ final int newcapacity = capacity() * 2;
byte[] newmem = new byte[newspace];
- Iterator<entry> i = entries();
+ final Iterator<entry> i = entries();
kelondroMHashMap.entry e;
int mempos;
while (i.hasNext()) {
@@ -169,46 +169,46 @@ public class kelondroMHashMap {
} else {
// there is enough space
//System.out.println("put " + new String(key) + " into cell " + hash);
- int mempos = hash * reclen;
+ final int mempos = hash * reclen;
System.arraycopy(key, 0, mem, mempos, keylen);
System.arraycopy(value, 0, mem, mempos + keylen, valuelen);
}
count++;
} else {
// overwrite old entry
- int mempos = hash * reclen;
+ final int mempos = hash * reclen;
System.arraycopy(key, 0, mem, mempos, keylen);
System.arraycopy(value, 0, mem, mempos + keylen, valuelen);
}
}
- public byte[] get(int key) {
+ public byte[] get(final int key) {
return get(toByteKey(key));
}
- public byte[] get(byte[] key) {
+ public byte[] get(final byte[] key) {
assert (key.length == keylen);
- int hash = findExisting(key);
+ final int hash = findExisting(key);
//System.out.println("get " + new String(key) + " from cell " + hash);
if (hash < 0) {
return null;
}
// read old entry
- byte[] value = new byte[valuelen];
+ final byte[] value = new byte[valuelen];
System.arraycopy(mem, hash * reclen + keylen, value, 0, valuelen);
return value;
}
- public void remove(int key) {
+ public void remove(final int key) {
remove(toByteKey(key));
}
- public void remove(byte[] key) {
+ public void remove(final byte[] key) {
assert (key.length == keylen);
System.out.println("REMOVE!");
- int hash = findExisting(key);
+ final int hash = findExisting(key);
if (hash >= 0) {
// overwrite old key
System.arraycopy(emptykey, 0, mem, hash * reclen, keylen);
@@ -233,7 +233,7 @@ public class kelondroMHashMap {
}
public entry next() {
- int i = hashkey;
+ final int i = hashkey;
hashkey = anyhashpos(hashkey + 1);
return new entry(i);
}
@@ -272,7 +272,7 @@ public class kelondroMHashMap {
while (hash < capacity()) {
mempos = hash * reclen;
if (mem[mempos] != 0) {
- byte[] key = new byte[keylen];
+ final byte[] key = new byte[keylen];
System.arraycopy(mem, mempos, key, 0, keylen);
return key;
}
@@ -284,26 +284,26 @@ public class kelondroMHashMap {
public class entry {
public byte[] key, value;
- public entry(int index) {
+ public entry(final int index) {
this.key = new byte[keylen];
this.value = new byte[valuelen];
- int mempos = index * (reclen);
+ final int mempos = index * (reclen);
System.arraycopy(mem, mempos, key, 0, keylen);
System.arraycopy(mem, mempos + keylen, value, 0, valuelen);
}
- public entry(byte[] key, byte[] value) {
+ public entry(final byte[] key, final byte[] value) {
this.key = key;
this.value = value;
}
}
- public static void main(String[] args) {
- long start = System.currentTimeMillis();
- kelondroMHashMap map = new kelondroMHashMap(4);
+ public static void main(final String[] args) {
+ final long start = System.currentTimeMillis();
+ final kelondroMHashMap map = new kelondroMHashMap(4);
for (int i = 0; i < 100; i++) map.put(3333 + i, ("" + (1000 + i)).getBytes());
- Iterator<entry> i = map.entries();
+ final Iterator<entry> i = map.entries();
kelondroMHashMap.entry e;
System.out.println("Enumeration of elements: count=" + map.size());
int c = 0;
diff --git a/source/de/anomic/kelondro/kelondroMScoreCluster.java b/source/de/anomic/kelondro/kelondroMScoreCluster.java
index e9cabb8ac..2ace44a3a 100644
--- a/source/de/anomic/kelondro/kelondroMScoreCluster.java
+++ b/source/de/anomic/kelondro/kelondroMScoreCluster.java
@@ -58,18 +58,18 @@ public final class kelondroMScoreCluster<E> {
static {
try {
date2000 = shortFormatter.parse("20000101000000").getTime();
- } catch (ParseException e) {}
+ } catch (final ParseException e) {}
}
public static int object2score(Object o) {
if (o instanceof Integer) return ((Integer) o).intValue();
if (o instanceof Long) {
- long l = ((Long) o).longValue();
+ final long l = ((Long) o).longValue();
if (l < Integer.MAX_VALUE) return (int) l;
o = ((Long) o).toString();
}
if (o instanceof Double) {
- double d = 1000d * ((Double) o).doubleValue();
+ final double d = 1000d * ((Double) o).doubleValue();
return (int) Math.round(d);
}
String s = null;
@@ -95,7 +95,7 @@ public final class kelondroMScoreCluster<E> {
return 0;
}
return (int) l;
- } catch (Exception e) {
+ } catch (final Exception e) {
// try it lex
int len = s.length();
if (len > 5) len = 5;
@@ -122,7 +122,7 @@ public final class kelondroMScoreCluster<E> {
for (int i = 128; i < 256; i++) plainByteArray[i] = (byte) (i & 0X20);
}
- private long scoreKey(int elementNr, int elementCount) {
+ private long scoreKey(final int elementNr, final int elementCount) {
return (((elementCount & 0xFFFFFFFFL)) << 32) | ((elementNr & 0xFFFFFFFFL));
}
@@ -134,23 +134,23 @@ public final class kelondroMScoreCluster<E> {
return refkeyDB.size();
}
- public synchronized void incScore(E[] objs) {
+ public synchronized void incScore(final E[] objs) {
for (int i = 0; i < objs.length; i++) addScore(objs[i], 1);
}
- public synchronized void decScore(E[] objs) {
+ public synchronized void decScore(final E[] objs) {
for (int i = 0; i < objs.length; i++) addScore(objs[i], -1);
}
- public synchronized void incScore(E obj) {
+ public synchronized void incScore(final E obj) {
addScore(obj, 1);
}
- public synchronized void decScore(E obj) {
+ public synchronized void decScore(final E obj) {
addScore(obj, -1);
}
- public synchronized void setScore(E obj, int newScore) {
+ public synchronized void setScore(final E obj, final int newScore) {
if (obj == null) return;
//System.out.println("setScore " + obj.getClass().getName());
Long usk = refkeyDB.remove(obj); // get unique score key, old entry is not needed any more
@@ -169,9 +169,9 @@ public final class kelondroMScoreCluster<E> {
keyrefDB.remove(usk);
// get previous handle and score
- long c = usk.longValue();
- int oldScore = (int) ((c & 0xFFFFFFFF00000000L) >> 32);
- int oldHandle = (int) (c & 0xFFFFFFFFL);
+ final long c = usk.longValue();
+ final int oldScore = (int) ((c & 0xFFFFFFFF00000000L) >> 32);
+ final int oldHandle = (int) (c & 0xFFFFFFFFL);
gcount -= oldScore;
// set new value
@@ -184,7 +184,7 @@ public final class kelondroMScoreCluster<E> {
gcount += newScore;
}
- public synchronized void addScore(E obj, int incrementScore) {
+ public synchronized void addScore(final E obj, final int incrementScore) {
if (obj == null) return;
//System.out.println("setScore " + obj.getClass().getName());
Long usk = refkeyDB.remove(obj); // get unique score key, old entry is not needed any more
@@ -203,12 +203,12 @@ public final class kelondroMScoreCluster<E> {
keyrefDB.remove(usk);
// get previous handle and score
- long c = usk.longValue();
- int oldScore = (int) ((c & 0xFFFFFFFF00000000L) >> 32);
- int oldHandle = (int) (c & 0xFFFFFFFFL);
+ final long c = usk.longValue();
+ final int oldScore = (int) ((c & 0xFFFFFFFF00000000L) >> 32);
+ final int oldHandle = (int) (c & 0xFFFFFFFFL);
// set new value
- int newValue = oldScore + incrementScore;
+ final int newValue = oldScore + incrementScore;
if (newValue < 0) throw new kelondroOutOfLimitsException(newValue);
usk = new Long(scoreKey(oldHandle, newValue)); // generates an unique key for a specific score
refkeyDB.put(obj, usk);
@@ -220,18 +220,18 @@ public final class kelondroMScoreCluster<E> {
gcount += incrementScore;
}
- public synchronized int deleteScore(E obj) {
+ public synchronized int deleteScore(final E obj) {
// deletes entry and returns previous score
if (obj == null) return 0;
//System.out.println("setScore " + obj.getClass().getName());
- Long usk = refkeyDB.remove(obj); // get unique score key, old entry is not needed any more
+ final Long usk = refkeyDB.remove(obj); // get unique score key, old entry is not needed any more
if (usk == null) return 0;
// delete old entry
keyrefDB.remove(usk);
// get previous handle and score
- int oldScore = (int) ((usk.longValue() & 0xFFFFFFFF00000000L) >> 32);
+ final int oldScore = (int) ((usk.longValue() & 0xFFFFFFFF00000000L) >> 32);
// decrease overall counter
gcount -= oldScore;
@@ -239,13 +239,13 @@ public final class kelondroMScoreCluster<E> {
return oldScore;
}
- public synchronized boolean existsScore(E obj) {
+ public synchronized boolean existsScore(final E obj) {
return (refkeyDB.get(obj) != null);
}
- public synchronized int getScore(E obj) {
+ public synchronized int getScore(final E obj) {
if (obj == null) return 0;
- Long cs = refkeyDB.get(obj);
+ final Long cs = refkeyDB.get(obj);
if (cs == null) return 0;
return (int) ((cs.longValue() & 0xFFFFFFFF00000000L) >> 32);
}
@@ -272,15 +272,15 @@ public final class kelondroMScoreCluster<E> {
return keyrefDB.get(keyrefDB.firstKey());
}
- public synchronized E[] getScores(int maxCount, boolean up) {
+ public synchronized E[] getScores(final int maxCount, final boolean up) {
return getScores(maxCount, up, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
@SuppressWarnings("unchecked")
- public synchronized E[] getScores(int maxCount, boolean up, int minScore, int maxScore) {
+ public synchronized E[] getScores(int maxCount, final boolean up, final int minScore, final int maxScore) {
if (maxCount > refkeyDB.size()) maxCount = refkeyDB.size();
E[] s = (E[]) new Object[maxCount];
- Iterator<E> it = scores(up, minScore, maxScore);
+ final Iterator<E> it = scores(up, minScore, maxScore);
int i = 0;
while ((i < maxCount) && (it.hasNext())) s[i++] = it.next();
if (i < maxCount) {
@@ -297,12 +297,12 @@ public final class kelondroMScoreCluster<E> {
return refkeyDB + " / " + keyrefDB;
}
- public synchronized Iterator<E> scores(boolean up) {
+ public synchronized Iterator<E> scores(final boolean up) {
if (up) return new simpleScoreIterator<E>();
return new reverseScoreIterator<E>();
}
- public synchronized Iterator<E> scores(boolean up, int minScore, int maxScore) {
+ public synchronized Iterator<E> scores(final boolean up, final int minScore, final int maxScore) {
return new komplexScoreIterator<E>(up, minScore, maxScore);
}
@@ -314,7 +314,7 @@ public final class kelondroMScoreCluster<E> {
int min, max;
@SuppressWarnings("unchecked")
- public komplexScoreIterator(boolean up, int minScore, int maxScore) {
+ public komplexScoreIterator(final boolean up, final int minScore, final int maxScore) {
this.up = up;
this.min = minScore;
this.max = maxScore;
@@ -344,7 +344,7 @@ public final class kelondroMScoreCluster<E> {
}
public E next() {
- E o = n;
+ final E o = n;
internalNext();
return o;
}
@@ -371,13 +371,13 @@ public final class kelondroMScoreCluster<E> {
public E next() {
key = view.lastKey();
view = view.headMap(key);
- E value = keyrefDB.get(key);
+ final E value = keyrefDB.get(key);
//System.out.println("cluster reverse iterator: score = " + ((((Long) key).longValue() & 0xFFFFFFFF00000000L) >> 32) + ", handle = " + (((Long) key).longValue() & 0xFFFFFFFFL) + ", value = " + value);
return value;
}
public void remove() {
- Object val = keyrefDB.remove(key);
+ final Object val = keyrefDB.remove(key);
if (val != null) refkeyDB.remove(val);
}
@@ -409,9 +409,9 @@ public final class kelondroMScoreCluster<E> {
}
- public static void main(String[] args) {
+ public static void main(final String[] args) {
- String t = "ZZZZZZZZZZ";
+ final String t = "ZZZZZZZZZZ";
System.out.println("score of " + t + ": " + object2score(t));
if (args.length > 0) {
System.out.println("score of " + args[0] + ": " + object2score(args[0]));
@@ -419,15 +419,15 @@ public final class kelondroMScoreCluster<E> {
}
System.out.println("Test for Score: start");
- kelondroMScoreCluster<String> s = new kelondroMScoreCluster<String>();
+ final kelondroMScoreCluster<String> s = new kelondroMScoreCluster<String>();
long c = 0;
// create cluster
- long time = System.currentTimeMillis();
- Random random = new Random(1234);
+ final long time = System.currentTimeMillis();
+ final Random random = new Random(1234);
int r;
- int count = 20;
- int[] mem = new int[count];
+ final int count = 20;
+ final int[] mem = new int[count];
for (int x = 0; x < 100; x++) {
for (int i = 0; i < count; i++) {
diff --git a/source/de/anomic/kelondro/kelondroMSetTools.java b/source/de/anomic/kelondro/kelondroMSetTools.java
index fd9790414..c70ec11b2 100644
--- a/source/de/anomic/kelondro/kelondroMSetTools.java
+++ b/source/de/anomic/kelondro/kelondroMSetTools.java
@@ -61,13 +61,13 @@ public class kelondroMSetTools {
// - join by iterative tests (where we distinguish left-right and right-left tests)
- public static <A, B> TreeMap<A, B> joinConstructive(Collection<TreeMap<A, B>> maps, boolean concatStrings) {
+ public static <A, B> TreeMap<A, B> joinConstructive(final Collection<TreeMap<A, B>> maps, final boolean concatStrings) {
// this joins all TreeMap(s) contained in maps
// first order entities by their size
- TreeMap<Long, TreeMap<A, B>> orderMap = new TreeMap<Long, TreeMap<A, B>>();
+ final TreeMap<Long, TreeMap<A, B>> orderMap = new TreeMap<Long, TreeMap<A, B>>();
TreeMap<A, B> singleMap;
- Iterator<TreeMap<A, B>> i = maps.iterator();
+ final Iterator<TreeMap<A, B>> i = maps.iterator();
int count = 0;
while (i.hasNext()) {
// get next entity:
@@ -103,17 +103,17 @@ public class kelondroMSetTools {
return joinResult;
}
- public static <A, B> TreeMap<A, B> joinConstructive(TreeMap<A, B> map1, TreeMap<A, B> map2, boolean concatStrings) {
+ public static <A, B> TreeMap<A, B> joinConstructive(final TreeMap<A, B> map1, final TreeMap<A, B> map2, final boolean concatStrings) {
// comparators must be equal
if ((map1 == null) || (map2 == null)) return null;
if (map1.comparator() != map2.comparator()) return null;
if ((map1.size() == 0) || (map2.size() == 0)) return new TreeMap<A, B>(map1.comparator());
// decide which method to use
- int high = ((map1.size() > map2.size()) ? map1.size() : map2.size());
- int low = ((map1.size() > map2.size()) ? map2.size() : map1.size());
- int stepsEnum = 10 * (high + low - 1);
- int stepsTest = 12 * log2a(high) * low;
+ final int high = ((map1.size() > map2.size()) ? map1.size() : map2.size());
+ final int low = ((map1.size() > map2.size()) ? map2.size() : map1.size());
+ final int stepsEnum = 10 * (high + low - 1);
+ final int stepsTest = 12 * log2a(high) * low;
// start most efficient method
if (stepsEnum > stepsTest) {
@@ -124,9 +124,9 @@ public class kelondroMSetTools {
}
@SuppressWarnings("unchecked")
- private static <A, B> TreeMap<A, B> joinConstructiveByTest(TreeMap<A, B> small, TreeMap<A, B> large, boolean concatStrings) {
- Iterator<Map.Entry<A, B>> mi = small.entrySet().iterator();
- TreeMap<A, B> result = new TreeMap<A, B>(large.comparator());
+ private static <A, B> TreeMap<A, B> joinConstructiveByTest(final TreeMap<A, B> small, final TreeMap<A, B> large, final boolean concatStrings) {
+ final Iterator<Map.Entry<A, B>> mi = small.entrySet().iterator();
+ final TreeMap<A, B> result = new TreeMap<A, B>(large.comparator());
Map.Entry<A, B> mentry1;
B mobj2;
while (mi.hasNext()) {
@@ -144,12 +144,12 @@ public class kelondroMSetTools {
}
@SuppressWarnings("unchecked")
- private static <A, B> TreeMap<A, B> joinConstructiveByEnumeration(TreeMap<A, B> map1, TreeMap<A, B> map2, boolean concatStrings) {
+ private static <A, B> TreeMap<A, B> joinConstructiveByEnumeration(final TreeMap<A, B> map1, final TreeMap<A, B> map2, final boolean concatStrings) {
// implement pairwise enumeration
- Comparator<? super A> comp = map1.comparator();
- Iterator<Map.Entry<A, B>> mi1 = map1.entrySet().iterator();
- Iterator<Map.Entry<A, B>> mi2 = map2.entrySet().iterator();
- TreeMap<A, B> result = new TreeMap<A, B>(map1.comparator());
+ final Comparator<? super A> comp = map1.comparator();
+ final Iterator<Map.Entry<A, B>> mi1 = map1.entrySet().iterator();
+ final Iterator<Map.Entry<A, B>> mi2 = map2.entrySet().iterator();
+ final TreeMap<A, B> result = new TreeMap<A, B>(map1.comparator());
int c;
if ((mi1.hasNext()) && (mi2.hasNext())) {
Map.Entry<A, B> mentry1 = mi1.next();
@@ -175,17 +175,17 @@ public class kelondroMSetTools {
}
// now the same for set-set
- public static <A> TreeSet<A> joinConstructive(TreeSet<A> set1, TreeSet<A> set2) {
+ public static <A> TreeSet<A> joinConstructive(final TreeSet<A> set1, final TreeSet<A> set2) {
// comparators must be equal
if ((set1 == null) || (set2 == null)) return null;
if (set1.comparator() != set2.comparator()) return null;
if ((set1.size() == 0) || (set2.size() == 0)) return new TreeSet<A>(set1.comparator());
// decide which method to use
- int high = ((set1.size() > set2.size()) ? set1.size() : set2.size());
- int low = ((set1.size() > set2.size()) ? set2.size() : set1.size());
- int stepsEnum = 10 * (high + low - 1);
- int stepsTest = 12 * log2a(high) * low;
+ final int high = ((set1.size() > set2.size()) ? set1.size() : set2.size());
+ final int low = ((set1.size() > set2.size()) ? set2.size() : set1.size());
+ final int stepsEnum = 10 * (high + low - 1);
+ final int stepsTest = 12 * log2a(high) * low;
// start most efficient method
if (stepsEnum > stepsTest) {
@@ -195,9 +195,9 @@ public class kelondroMSetTools {
return joinConstructiveByEnumeration(set1, set2);
}
- private static <A> TreeSet<A> joinConstructiveByTest(TreeSet<A> small, TreeSet<A> large) {
- Iterator<A> mi = small.iterator();
- TreeSet<A> result = new TreeSet<A>(small.comparator());
+ private static <A> TreeSet<A> joinConstructiveByTest(final TreeSet<A> small, final TreeSet<A> large) {
+ final Iterator<A> mi = small.iterator();
+ final TreeSet<A> result = new TreeSet<A>(small.comparator());
A o;
while (mi.hasNext()) {
o = mi.next();
@@ -206,12 +206,12 @@ public class kelondroMSetTools {
return result;
}
- private static <A> TreeSet<A> joinConstructiveByEnumeration(TreeSet<A> set1, TreeSet<A> set2) {
+ private static <A> TreeSet<A> joinConstructiveByEnumeration(final TreeSet<A> set1, final TreeSet<A> set2) {
// implement pairvise enumeration
- Comparator<? super A> comp = set1.comparator();
- Iterator<A> mi = set1.iterator();
- Iterator<A> si = set2.iterator();
- TreeSet<A> result = new TreeSet<A>(set1.comparator());
+ final Comparator<? super A> comp = set1.comparator();
+ final Iterator<A> mi = set1.iterator();
+ final Iterator<A> si = set2.iterator();
+ final TreeSet<A> result = new TreeSet<A>(set1.comparator());
int c;
if ((mi.hasNext()) && (si.hasNext())) {
A mobj = mi.next();
@@ -233,17 +233,17 @@ public class kelondroMSetTools {
}
// now the same for set-set
- public static <A> boolean anymatch(TreeSet<A> set1, TreeSet<A> set2) {
+ public static <A> boolean anymatch(final TreeSet<A> set1, final TreeSet<A> set2) {
// comparators must be equal
if ((set1 == null) || (set2 == null)) return false;
if (set1.comparator() != set2.comparator()) return false;
if ((set1.size() == 0) || (set2.size() == 0)) return false;
// decide which method to use
- int high = ((set1.size() > set2.size()) ? set1.size() : set2.size());
- int low = ((set1.size() > set2.size()) ? set2.size() : set1.size());
- int stepsEnum = 10 * (high + low - 1);
- int stepsTest = 12 * log2a(high) * low;
+ final int high = ((set1.size() > set2.size()) ? set1.size() : set2.size());
+ final int low = ((set1.size() > set2.size()) ? set2.size() : set1.size());
+ final int stepsEnum = 10 * (high + low - 1);
+ final int stepsTest = 12 * log2a(high) * low;
// start most efficient method
if (stepsEnum > stepsTest) {
@@ -253,8 +253,8 @@ public class kelondroMSetTools {
return anymatchByEnumeration(set1, set2);
}
- private static <A> boolean anymatchByTest(TreeSet<A> small, TreeSet<A> large) {
- Iterator<A> mi = small.iterator();
+ private static <A> boolean anymatchByTest(final TreeSet<A> small, final TreeSet<A> large) {
+ final Iterator<A> mi = small.iterator();
A o;
while (mi.hasNext()) {
o = mi.next();
@@ -263,11 +263,11 @@ public class kelondroMSetTools {
return false;
}
- private static <A> boolean anymatchByEnumeration(TreeSet<A> set1, TreeSet<A> set2) {
+ private static <A> boolean anymatchByEnumeration(final TreeSet<A> set1, final TreeSet<A> set2) {
// implement pairvise enumeration
- Comparator<? super A> comp = set1.comparator();
- Iterator<A> mi = set1.iterator();
- Iterator<A> si = set2.iterator();
+ final Comparator<? super A> comp = set1.comparator();
+ final Iterator<A> mi = set1.iterator();
+ final Iterator<A> si = set2.iterator();
int c;
if ((mi.hasNext()) && (si.hasNext())) {
A mobj = mi.next();
@@ -289,7 +289,7 @@ public class kelondroMSetTools {
// ------------------------------------------------------------------------------------------------
// exclude
- public static <A, B> TreeMap<A, B> excludeConstructive(TreeMap<A, B> map, TreeSet<A> set) {
+ public static <A, B> TreeMap<A, B> excludeConstructive(final TreeMap<A, B> map, final TreeSet<A> set) {
// comparators must be equal
if (map == null) return null;
if (set == null) return map;
@@ -299,9 +299,9 @@ public class kelondroMSetTools {
// return excludeConstructiveByEnumeration(map, set);
}
- private static <A, B> TreeMap<A, B> excludeConstructiveByTestMapInSet(TreeMap<A, B> map, TreeSet<A> set) {
- Iterator<A> mi = map.keySet().iterator();
- TreeMap<A, B> result = new TreeMap<A, B>(map.comparator());
+ private static <A, B> TreeMap<A, B> excludeConstructiveByTestMapInSet(final TreeMap<A, B> map, final TreeSet<A> set) {
+ final Iterator<A> mi = map.keySet().iterator();
+ final TreeMap<A, B> result = new TreeMap<A, B>(map.comparator());
A o;
while (mi.hasNext()) {
o = mi.next();
@@ -310,7 +310,7 @@ public class kelondroMSetTools {
return result;
}
- public static <A, B> void excludeDestructive(TreeMap<A, B> map, TreeSet<A> set) {
+ public static <A, B> void excludeDestructive(final TreeMap<A, B> map, final TreeSet<A> set) {
// comparators must be equal
if (map == null) return;
if (set == null) return;
@@ -323,18 +323,18 @@ public class kelondroMSetTools {
excludeDestructiveByTestSetInMap(map, set);
}
- private static <A, B> void excludeDestructiveByTestMapInSet(TreeMap<A, B> map, TreeSet<A> set) {
- Iterator<A> mi = map.keySet().iterator();
+ private static <A, B> void excludeDestructiveByTestMapInSet(final TreeMap<A, B> map, final TreeSet<A> set) {
+ final Iterator<A> mi = map.keySet().iterator();
while (mi.hasNext()) if (set.contains(mi.next())) mi.remove();
}
- private static <A, B> void excludeDestructiveByTestSetInMap(TreeMap<A, B> map, TreeSet<A> set) {
- Iterator<A> si = set.iterator();
+ private static <A, B> void excludeDestructiveByTestSetInMap(final TreeMap<A, B> map, final TreeSet<A> set) {
+ final Iterator<A> si = set.iterator();
while (si.hasNext()) map.remove(si.next());
}
// and the same again with set-set
- public static <A> void excludeDestructive(TreeSet<A> set1, TreeSet<A> set2) {
+ public static <A> void excludeDestructive(final TreeSet<A> set1, final TreeSet<A> set2) {
// comparators must be equal
if (set1 == null) return;
if (set2 == null) return;
@@ -347,20 +347,20 @@ public class kelondroMSetTools {
excludeDestructiveByTestLargeInSmall(set1, set2);
}
- private static <A> void excludeDestructiveByTestSmallInLarge(TreeSet<A> small, TreeSet<A> large) {
- Iterator<A> mi = small.iterator();
+ private static <A> void excludeDestructiveByTestSmallInLarge(final TreeSet<A> small, final TreeSet<A> large) {
+ final Iterator<A> mi = small.iterator();
while (mi.hasNext()) if (large.contains(mi.next())) mi.remove();
}
- private static <A> void excludeDestructiveByTestLargeInSmall(TreeSet<A> large, TreeSet<A> small) {
- Iterator<A> si = small.iterator();
+ private static <A> void excludeDestructiveByTestLargeInSmall(final TreeSet<A> large, final TreeSet<A> small) {
+ final Iterator<A> si = small.iterator();
while (si.hasNext()) large.remove(si.next());
}
// ------------------------------------------------------------------------------------------------
- public static TreeMap<String, String> loadMap(String filename, String sep) {
- TreeMap<String, String> map = new TreeMap<String, String>();
+ public static TreeMap<String, String> loadMap(final String filename, final String sep) {
+ final TreeMap<String, String> map = new TreeMap<String, String>();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(filename)));
@@ -371,15 +371,15 @@ public class kelondroMSetTools {
if ((line.length() > 0) && (!(line.startsWith("#"))) && ((pos = line.indexOf(sep)) > 0))
map.put(line.substring(0, pos).trim().toLowerCase(), line.substring(pos + sep.length()).trim());
}
- } catch (IOException e) {
+ } catch (final IOException e) {
} finally {
- if (br != null) try { br.close(); } catch (Exception e) {}
+ if (br != null) try { br.close(); } catch (final Exception e) {}
}
return map;
}
- public static TreeMap<String, ArrayList<String>> loadMapMultiValsPerKey(String filename, String sep) {
- TreeMap<String, ArrayList<String>> map = new TreeMap<String, ArrayList<String>>();
+ public static TreeMap<String, ArrayList<String>> loadMapMultiValsPerKey(final String filename, final String sep) {
+ final TreeMap<String, ArrayList<String>> map = new TreeMap<String, ArrayList<String>>();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(filename)));
@@ -394,15 +394,15 @@ public class kelondroMSetTools {
map.get(key).add(value);
}
}
- } catch (IOException e) {
+ } catch (final IOException e) {
} finally {
- if (br != null) try { br.close(); } catch (Exception e) {}
+ if (br != null) try { br.close(); } catch (final Exception e) {}
}
return map;
}
- public static TreeSet<String> loadList(File file, Comparator<String> c) {
- TreeSet<String> list = new TreeSet<String>(c);
+ public static TreeSet<String> loadList(final File file, final Comparator<String> c) {
+ final TreeSet<String> list = new TreeSet<String>(c);
if (!(file.exists())) return list;
BufferedReader br = null;
@@ -414,16 +414,16 @@ public class kelondroMSetTools {
if ((line.length() > 0) && (!(line.startsWith("#")))) list.add(line.trim().toLowerCase());
}
br.close();
- } catch (IOException e) {
+ } catch (final IOException e) {
} finally {
- if (br != null) try{br.close();}catch(Exception e){}
+ if (br != null) try{br.close();}catch(final Exception e){}
}
return list;
}
- public static String setToString(Set<String> set, char separator) {
- Iterator<String> i = set.iterator();
- StringBuffer sb = new StringBuffer(set.size() * 7);
+ public static String setToString(final Set<String> set, final char separator) {
+ final Iterator<String> i = set.iterator();
+ final StringBuffer sb = new StringBuffer(set.size() * 7);
if (i.hasNext()) sb.append(i.next());
while (i.hasNext()) {
sb.append(separator).append(i.next());
@@ -434,9 +434,9 @@ public class kelondroMSetTools {
// ------------------------------------------------------------------------------------------------
- public static void main(String[] args) {
- TreeMap<String, String> m = new TreeMap<String, String>();
- TreeMap<String, String> s = new TreeMap<String, String>();
+ public static void main(final String[] args) {
+ final TreeMap<String, String> m = new TreeMap<String, String>();
+ final TreeMap<String, String> s = new TreeMap<String, String>();
m.put("a", "a");
m.put("x", "x");
m.put("f", "f");
diff --git a/source/de/anomic/kelondro/kelondroMap.java b/source/de/anomic/kelondro/kelondroMap.java
index 9caf8a0e8..47ee01a3d 100644
--- a/source/de/anomic/kelondro/kelondroMap.java
+++ b/source/de/anomic/kelondro/kelondroMap.java
@@ -39,13 +39,13 @@ import de.anomic.server.serverDate;
public class kelondroMap {
- private kelondroBLOB blob;
+ private final kelondroBLOB blob;
private kelondroMScoreCluster<String> cacheScore;
private HashMap<String, HashMap<String, String>> cache;
- private long startup;
- private int cachesize;
+ private final long startup;
+ private final int cachesize;
- public kelondroMap(kelondroBLOB blob, int cachesize) {
+ public kelondroMap(final kelondroBLOB blob, final int cachesize) {
this.blob = blob;
this.cache = new HashMap<String, HashMap<String, String>>();
this.cacheScore = new kelondroMScoreCluster<String>();
@@ -86,8 +86,8 @@ public class kelondroMap {
return bb.toString();
}
- private static HashMap<String, String> string2map(String s) throws IOException {
- BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(s.getBytes())));
+ private static HashMap<String, String> string2map(final String s) throws IOException {
+ final BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(s.getBytes())));
final HashMap<String, String> map = new HashMap<String, String>();
String line;
int pos;
@@ -108,7 +108,7 @@ public class kelondroMap {
* @param newMap
* @throws IOException
*/
- public synchronized void put(String key, HashMap<String, String> newMap) throws IOException {
+ public synchronized void put(String key, final HashMap<String, String> newMap) throws IOException {
assert (key != null);
assert (key.length() > 0);
assert (newMap != null);
@@ -181,7 +181,7 @@ public class kelondroMap {
if (!(blob.has(key.getBytes()))) return null;
// read object
- byte[] b = blob.get(key.getBytes());
+ final byte[] b = blob.get(key.getBytes());
if (b == null) return null;
map = string2map(new String(b));
@@ -227,13 +227,13 @@ public class kelondroMap {
* @return
* @throws IOException
*/
- public kelondroCloneableIterator<byte[]> keys(boolean up, byte[] firstKey) throws IOException {
+ public kelondroCloneableIterator<byte[]> keys(final boolean up, final byte[] firstKey) throws IOException {
return keys(up, false, firstKey, null);
}
public synchronized kelondroCloneableIterator<byte[]> keys(final boolean up, final boolean rotating, final byte[] firstKey, final byte[] secondKey) throws IOException {
// simple enumeration of key names without special ordering
- kelondroCloneableIterator<byte[]> i = blob.keys(up, firstKey);
+ final kelondroCloneableIterator<byte[]> i = blob.keys(up, firstKey);
if (rotating) return new kelondroRotateIterator<byte[]>(i, secondKey, blob.size()); else return i;
}
@@ -275,7 +275,7 @@ public class kelondroMap {
Iterator<byte[]> keyIterator;
boolean finish;
- public objectIterator(Iterator<byte[]> keyIterator) {
+ public objectIterator(final Iterator<byte[]> keyIterator) {
this.keyIterator = keyIterator;
this.finish = false;
}
@@ -294,7 +294,7 @@ public class kelondroMap {
final HashMap<String, String> obj = get(new String(nextKey));
if (obj == null) throw new kelondroException("no more elements available");
return obj;
- } catch (IOException e) {
+ } catch (final IOException e) {
finish = true;
return null;
}
diff --git a/source/de/anomic/kelondro/kelondroMapDataMining.java b/source/de/anomic/kelondro/kelondroMapDataMining.java
index b6f035c2c..fbfc6dcd8 100644
--- a/source/de/anomic/kelondro/kelondroMapDataMining.java
+++ b/source/de/anomic/kelondro/kelondroMapDataMining.java
@@ -36,13 +36,13 @@ import java.util.Map;
public class kelondroMapDataMining extends kelondroMap {
- private String[] sortfields, longaccfields, doubleaccfields;
+ private final String[] sortfields, longaccfields, doubleaccfields;
private HashMap<String, kelondroMScoreCluster<String>> sortClusterMap; // a String-kelondroMScoreCluster - relation
private HashMap<String, Object> accMap; // to store accumulations of specific fields
private int elementCount;
@SuppressWarnings({ "unchecked", "null" })
- public kelondroMapDataMining(kelondroBLOB dyn, int cachesize, String[] sortfields, String[] longaccfields, String[] doubleaccfields, Method externalInitializer, Object externalHandler) {
+ public kelondroMapDataMining(final kelondroBLOB dyn, final int cachesize, final String[] sortfields, final String[] longaccfields, final String[] doubleaccfields, final Method externalInitializer, final Object externalHandler) {
super(dyn, cachesize);
// create fast ordering clusters and acc fields
@@ -81,7 +81,7 @@ public class kelondroMapDataMining extends kelondroMap {
// fill cluster and accumulator with values
if ((sortfields != null) || (longaccfields != null) || (doubleaccfields != null)) try {
- kelondroCloneableIterator<byte[]> it = dyn.keys(true, false);
+ final kelondroCloneableIterator<byte[]> it = dyn.keys(true, false);
String mapname;
Object cell;
long valuel;
@@ -105,7 +105,7 @@ public class kelondroMapDataMining extends kelondroMap {
if (cell instanceof Long) valuel = ((Long) cell).longValue();
if (cell instanceof String) valuel = Long.parseLong((String) cell);
longaccumulator[i] = new Long(longaccumulator[i].longValue() + valuel);
- } catch (NumberFormatException e) {}
+ } catch (final NumberFormatException e) {}
}
if (doubleaccfields != null) for (int i = 0; i < doubleaccfields.length; i++) {
@@ -115,23 +115,23 @@ public class kelondroMapDataMining extends kelondroMap {
if (cell instanceof Double) valued = ((Double) cell).doubleValue();
if (cell instanceof String) valued = Double.parseDouble((String) cell);
doubleaccumulator[i] = new Double(doubleaccumulator[i].doubleValue() + valued);
- } catch (NumberFormatException e) {}
+ } catch (final NumberFormatException e) {}
}
if ((externalHandler != null) && (externalInitializer != null)) {
try {
externalInitializer.invoke(externalHandler, new Object[]{mapname, map});
- } catch (IllegalArgumentException e) {
+ } catch (final IllegalArgumentException e) {
e.printStackTrace();
- } catch (IllegalAccessException e) {
+ } catch (final IllegalAccessException e) {
e.printStackTrace();
- } catch (InvocationTargetException e) {
+ } catch (final InvocationTargetException e) {
e.printStackTrace();
}
}
elementCount++;
}
- } catch (IOException e) {}
+ } catch (final IOException e) {}
// fill cluster
if (sortfields != null) for (int i = 0; i < sortfields.length; i++) sortClusterMap.put(sortfields[i], cluster[i]);
@@ -168,7 +168,7 @@ public class kelondroMapDataMining extends kelondroMap {
this.elementCount = 0;
}
- public synchronized void put(String key, HashMap<String, String> newMap) throws IOException {
+ public synchronized void put(final String key, final HashMap<String, String> newMap) throws IOException {
assert (key != null);
assert (key.length() > 0);
assert (newMap != null);
@@ -194,7 +194,7 @@ public class kelondroMapDataMining extends kelondroMap {
if ((longaccfields != null) || (doubleaccfields != null)) updateAcc(newMap, true);
}
- private void updateAcc(Map<String, String> map, boolean add) {
+ private void updateAcc(final Map<String, String> map, final boolean add) {
String value;
long valuel;
double valued;
@@ -211,7 +211,7 @@ public class kelondroMapDataMining extends kelondroMap {
} else {
accMap.put(longaccfields[i], new Long(longaccumulator.longValue() - valuel));
}
- } catch (NumberFormatException e) {}
+ } catch (final NumberFormatException e) {}
}
}
if (doubleaccfields != null) for (int i = 0; i < doubleaccfields.length; i++) {
@@ -225,7 +225,7 @@ public class kelondroMapDataMining extends kelondroMap {
} else {
accMap.put(doubleaccfields[i], new Double(doubleaccumulator.doubleValue() - valued));
}
- } catch (NumberFormatException e) {}
+ } catch (final NumberFormatException e) {}
}
}
}
@@ -243,7 +243,7 @@ public class kelondroMapDataMining extends kelondroMap {
}
}
- public synchronized void remove(String key) throws IOException {
+ public synchronized void remove(final String key) throws IOException {
if (key == null) return;
// update elementCount
@@ -273,7 +273,7 @@ public class kelondroMapDataMining extends kelondroMap {
}
}
- public synchronized Iterator<byte[]> keys(final boolean up, /* sorted by */ String field) {
+ public synchronized Iterator<byte[]> keys(final boolean up, /* sorted by */ final String field) {
// sorted iteration using the sortClusters
if (sortClusterMap == null) return null;
final kelondroMScoreCluster<String> cluster = sortClusterMap.get(field);
@@ -286,7 +286,7 @@ public class kelondroMapDataMining extends kelondroMap {
Iterator<String> s;
- public string2bytearrayIterator(Iterator<String> s) {
+ public string2bytearrayIterator(final Iterator<String> s) {
this.s = s;
}
@@ -295,7 +295,7 @@ public class kelondroMapDataMining extends kelondroMap {
}
public byte[] next() {
- String r = s.next();
+ final String r = s.next();
if (r == null) return null;
return r.getBytes();
}
@@ -353,7 +353,7 @@ public class kelondroMapDataMining extends kelondroMap {
boolean finish;
HashMap<String, String> n;
- public mapIterator(Iterator<byte[]> keyIterator) {
+ public mapIterator(final Iterator<byte[]> keyIterator) {
this.keyIterator = keyIterator;
this.finish = false;
this.n = next0();
@@ -364,7 +364,7 @@ public class kelondroMapDataMining extends kelondroMap {
}
public HashMap<String, String> next() {
- HashMap<String, String> n1 = n;
+ final HashMap<String, String> n1 = n;
n = next0();
return n1;
}
@@ -382,7 +382,7 @@ public class kelondroMapDataMining extends kelondroMap {
}
try {
map = get(nextKey);
- } catch (IOException e) {
+ } catch (final IOException e) {
break;
}
if (map == null) continue; // circumvention of a modified exception
diff --git a/source/de/anomic/kelondro/kelondroMergeIterator.java b/source/de/anomic/kelondro/kelondroMergeIterator.java
index 7c0393fc1..4b6513bf2 100644
--- a/source/de/anomic/kelondro/kelondroMergeIterator.java
+++ b/source/de/anomic/kelondro/kelondroMergeIterator.java
@@ -37,7 +37,7 @@ public class kelondroMergeIterator<E> implements kelondroCloneableIterator<E> {
private final Method merger;
private final boolean up;
- public kelondroMergeIterator(kelondroCloneableIterator<E> a, kelondroCloneableIterator<E> b, Comparator<E> c, Method m, boolean up) {
+ public kelondroMergeIterator(final kelondroCloneableIterator<E> a, final kelondroCloneableIterator<E> b, final Comparator<E> c, final Method m, final boolean up) {
// this works currently only for String-type key iterations
this.a = a;
this.b = b;
@@ -48,7 +48,7 @@ public class kelondroMergeIterator<E> implements kelondroCloneableIterator<E> {
nextb();
}
- public kelondroMergeIterator<E> clone(Object modifier) {
+ public kelondroMergeIterator<E> clone(final Object modifier) {
return new kelondroMergeIterator<E>(a.clone(modifier), b.clone(modifier), comp, merger, up);
}
@@ -64,14 +64,14 @@ public class kelondroMergeIterator<E> implements kelondroCloneableIterator<E> {
private void nexta() {
try {
if ((a != null) && (a.hasNext())) na = a.next(); else na = null;
- } catch (ConcurrentModificationException e) {
+ } catch (final ConcurrentModificationException e) {
na = null;
}
}
private void nextb() {
try {
if ((b != null) && (b.hasNext())) nb = b.next(); else nb = null;
- } catch (ConcurrentModificationException e) {
+ } catch (final ConcurrentModificationException e) {
nb = null;
}
}
@@ -94,19 +94,19 @@ public class kelondroMergeIterator<E> implements kelondroCloneableIterator<E> {
return s;
}
// compare the Objects
- int c = comp.compare(na, nb);
+ final int c = comp.compare(na, nb);
if (c == 0) {
try {
//System.out.print("MERGE OF " + na.toString() + " AND " + nb.toString() + ": ");
s = (E) this.merger.invoke(null, new Object[]{na, nb});
//System.out.println("RESULT IS " + s.toString());
- } catch (IllegalArgumentException e) {
+ } catch (final IllegalArgumentException e) {
e.printStackTrace();
s = null;
- } catch (IllegalAccessException e) {
+ } catch (final IllegalAccessException e) {
e.printStackTrace();
s = null;
- } catch (InvocationTargetException e) {
+ } catch (final InvocationTargetException e) {
e.printStackTrace();
s = null;
}
@@ -128,7 +128,7 @@ public class kelondroMergeIterator<E> implements kelondroCloneableIterator<E> {
throw new java.lang.UnsupportedOperationException("merge does not support remove");
}
- public static <A> kelondroCloneableIterator<A> cascade(Set<kelondroCloneableIterator<A>> iterators, kelondroOrder<A> c, Method merger, boolean up) {
+ public static <A> kelondroCloneableIterator<A> cascade(final Set<kelondroCloneableIterator<A>> iterators, final kelondroOrder<A> c, final Method merger, final boolean up) {
// this extends the ability to combine two iterators
// to the ability of combining a set of iterators
if (iterators == null) return null;
@@ -136,10 +136,10 @@ public class kelondroMergeIterator<E> implements kelondroCloneableIterator<E> {
return cascade(iterators.iterator(), c, merger, up);
}
- private static <A> kelondroCloneableIterator<A> cascade(Iterator<kelondroCloneableIterator<A>> iiterators, kelondroOrder<A> c, Method merger, boolean up) {
+ private static <A> kelondroCloneableIterator<A> cascade(final Iterator<kelondroCloneableIterator<A>> iiterators, final kelondroOrder<A> c, final Method merger, final boolean up) {
if (iiterators == null) return null;
if (!(iiterators.hasNext())) return null;
- kelondroCloneableIterator<A> one = iiterators.next();
+ final kelondroCloneableIterator<A> one = iiterators.next();
if (!(iiterators.hasNext())) return one;
return new kelondroMergeIterator<A>(one, cascade(iiterators, c, merger, up), c, merger, up);
}
@@ -147,21 +147,21 @@ public class kelondroMergeIterator<E> implements kelondroCloneableIterator<E> {
public static Method simpleMerge = null;
static {
try {
- Class<?> c = Class.forName("de.anomic.kelondro.kelondroMergeIterator");
+ final Class<?> c = Class.forName("de.anomic.kelondro.kelondroMergeIterator");
simpleMerge = c.getMethod("mergeEqualByReplace", new Class[]{Object.class, Object.class});
- } catch (SecurityException e) {
+ } catch (final SecurityException e) {
System.out.println("Error while initializing simpleMerge: " + e.getMessage());
simpleMerge = null;
- } catch (ClassNotFoundException e) {
+ } catch (final ClassNotFoundException e) {
System.out.println("Error while initializing simpleMerge: " + e.getMessage());
simpleMerge = null;
- } catch (NoSuchMethodException e) {
+ } catch (final NoSuchMethodException e) {
System.out.println("Error while initializing simpleMerge: " + e.getMessage());
simpleMerge = null;
}
}
- public static Object mergeEqualByReplace(Object a, Object b) {
+ public static Object mergeEqualByReplace(final Object a, final Object b) {
return a;
}
diff --git a/source/de/anomic/kelondro/kelondroMicroDate.java b/source/de/anomic/kelondro/kelondroMicroDate.java
index 245cf50da..8e40b4442 100755
--- a/source/de/anomic/kelondro/kelondroMicroDate.java
+++ b/source/de/anomic/kelondro/kelondroMicroDate.java
@@ -33,11 +33,11 @@ public class kelondroMicroDate {
private static final long hour = 3600000L; // milliseconds of a hour
private static final long day = 86400000L; // milliseconds of a day
- public static int microDateDays(Date modified) {
+ public static int microDateDays(final Date modified) {
return microDateDays(modified.getTime());
}
- public static int microDateDays(long modified) {
+ public static int microDateDays(final long modified) {
// this calculates a virtual age from a given date
// the purpose is to have an age in days of a given modified date
// from a fixed standpoint in the past
@@ -46,23 +46,23 @@ public class kelondroMicroDate {
return (int) ((modified / day) % 262144L);
}
- public static String microDateHoursStr(long time) {
+ public static String microDateHoursStr(final long time) {
return kelondroBase64Order.enhancedCoder.encodeLong(microDateHoursInt(time), 3);
}
- public static int microDateHoursInt(long time) {
+ public static int microDateHoursInt(final long time) {
return (int) ((time / hour) % 262144L);
}
- public static int microDateHoursAge(String mdhs) {
+ public static int microDateHoursAge(final String mdhs) {
return microDateHoursInt(System.currentTimeMillis()) - (int) kelondroBase64Order.enhancedCoder.decodeLong(mdhs);
}
- public static long reverseMicroDateDays(long microDateDays) {
+ public static long reverseMicroDateDays(final long microDateDays) {
return Math.min(System.currentTimeMillis(), microDateDays * day);
}
- public static void main(String[] args) {
+ public static void main(final String[] args) {
}
}
diff --git a/source/de/anomic/kelondro/kelondroNIOFileRA.java b/source/de/anomic/kelondro/kelondroNIOFileRA.java
index 7ce68bb79..235249352 100644
--- a/source/de/anomic/kelondro/kelondroNIOFileRA.java
+++ b/source/de/anomic/kelondro/kelondroNIOFileRA.java
@@ -40,11 +40,11 @@ public class kelondroNIOFileRA extends kelondroAbstractRA implements kelondroRA
protected boolean mapBody;
protected boolean wroteHead, wroteBody, wroteTail;
- public kelondroNIOFileRA(String file, boolean mapBody, long tailMaxSize) throws IOException {
+ public kelondroNIOFileRA(final String file, final boolean mapBody, final long tailMaxSize) throws IOException {
this(new File(file), mapBody, tailMaxSize);
}
- public kelondroNIOFileRA(File file, boolean mapBody, long tailMaxSize) throws IOException {
+ public kelondroNIOFileRA(final File file, boolean mapBody, final long tailMaxSize) throws IOException {
this.name = file.getName();
this.file = file;
this.seekPos = 0;
@@ -72,7 +72,7 @@ public class kelondroNIOFileRA extends kelondroAbstractRA implements kelondroRA
", bodyOffset = " + bodyOffset + ", tailOffset = " + tailOffset);
}
- private boolean growTail(long newPos) throws IOException {
+ private boolean growTail(final long newPos) throws IOException {
if (newPos >= tailMaxSize) {
System.out.println("cannot grow " + name);
return false;
@@ -135,7 +135,7 @@ public class kelondroNIOFileRA extends kelondroAbstractRA implements kelondroRA
}
// pseudo-native method write
- public void write(int b) throws IOException {
+ public void write(final int b) throws IOException {
if (seekPos < bodyOffset) {
bufferHead.put((int) seekPos, (byte) (b & 0xff));
wroteHead = true;
@@ -166,20 +166,20 @@ public class kelondroNIOFileRA extends kelondroAbstractRA implements kelondroRA
seekPos++;
}
- public int read(byte[] b, int off, int len) throws IOException {
+ public int read(final byte[] b, final int off, final int len) throws IOException {
for (int i = 0; i < len; i++) {
b[off + i] = (byte) read();
}
return len;
}
- public void write(byte[] b, int off, int len) throws IOException {
+ public void write(final byte[] b, final int off, final int len) throws IOException {
for (int i = 0; i < len; i++) {
write(b[off + i]);
}
}
- public void seek(long pos) throws IOException {
+ public void seek(final long pos) throws IOException {
seekPos = pos;
}
@@ -204,53 +204,53 @@ public class kelondroNIOFileRA extends kelondroAbstractRA implements kelondroRA
protected void finalize() throws Throwable {
if (RAChannel != null) {
- try {RAChannel.close();}catch(Exception e){}
+ try {RAChannel.close();}catch(final Exception e){}
}
if (RAFile != null) {
- try {RAFile.close();}catch(Exception e){}
+ try {RAFile.close();}catch(final Exception e){}
}
}
- public static void test1(kelondroRA ra) throws IOException {
+ public static void test1(final kelondroRA ra) throws IOException {
for (int i = 0; i < 2048; i++) {
ra.seek(i);
ra.write(32);
}
}
- public static void main(String[] args) {
+ public static void main(final String[] args) {
// tests...
- File f = new File("/yacy/nio.test.txt");
+ final File f = new File("/yacy/nio.test.txt");
if (f.exists()) f.delete();
System.out.println("* fill with blanks");
- try { kelondroRA ra = new kelondroNIOFileRA(f, true, 2046); test1(ra); ra.close();
- } catch (IOException e) { e.printStackTrace(); }
+ try { final kelondroRA ra = new kelondroNIOFileRA(f, true, 2046); test1(ra); ra.close();
+ } catch (final IOException e) { e.printStackTrace(); }
System.out.println("* write in at head");
- try { kelondroRA ra = new kelondroNIOFileRA(f, true, 10);
+ try { final kelondroRA ra = new kelondroNIOFileRA(f, true, 10);
ra.seek(8); ra.write((byte) 'h');
ra.close();
- } catch (IOException e) { e.printStackTrace(); }
+ } catch (final IOException e) { e.printStackTrace(); }
System.out.println("* write in at body");
- try { kelondroRA ra = new kelondroNIOFileRA(f, true, 10);
+ try { final kelondroRA ra = new kelondroNIOFileRA(f, true, 10);
ra.seek(1024); ra.write((byte) 'b');
ra.close();
- } catch (IOException e) { e.printStackTrace(); }
+ } catch (final IOException e) { e.printStackTrace(); }
System.out.println("* write in at tail");
- try { kelondroRA ra = new kelondroNIOFileRA(f, true, 10);
+ try { final kelondroRA ra = new kelondroNIOFileRA(f, true, 10);
ra.seek(2048); ra.write((byte) 't');
ra.close();
- } catch (IOException e) { e.printStackTrace(); }
+ } catch (final IOException e) { e.printStackTrace(); }
System.out.println("* write in behind tail");
- try { kelondroRA ra = new kelondroNIOFileRA(f, true, 10);
+ try { final kelondroRA ra = new kelondroNIOFileRA(f, true, 10);
ra.seek(2059); ra.write((byte) 'x');
ra.close();
- } catch (IOException e) { e.printStackTrace(); }
+ } catch (final IOException e) { e.printStackTrace(); }
}
}
diff --git a/source/de/anomic/kelondro/kelondroNaturalOrder.java b/source/de/anomic/kelondro/kelondroNaturalOrder.java
index 025fcd0ed..a024c7b52 100644
--- a/source/de/anomic/kelondro/kelondroNaturalOrder.java
+++ b/source/de/anomic/kelondro/kelondroNaturalOrder.java
@@ -32,26 +32,26 @@ public final class kelondroNaturalOrder extends kelondroAbstractOrder<byte[]> im
public static final kelondroByteOrder naturalOrder = new kelondroNaturalOrder(true);
public static final Comparator<String> naturalComparator = new kelondroByteOrder.StringOrder(naturalOrder);
- public kelondroNaturalOrder(boolean ascending) {
+ public kelondroNaturalOrder(final boolean ascending) {
this.asc = ascending;
this.zero = null;
}
- public boolean wellformed(byte[] a) {
+ public boolean wellformed(final byte[] a) {
return true;
}
- public boolean wellformed(byte[] a, int astart, int alength) {
+ public boolean wellformed(final byte[] a, final int astart, final int alength) {
return true;
}
public final kelondroOrder<byte[]> clone() {
- kelondroNaturalOrder o = new kelondroNaturalOrder(this.asc);
+ final kelondroNaturalOrder o = new kelondroNaturalOrder(this.asc);
o.rotate(this.zero);
return o;
}
- public static kelondroByteOrder orderBySignature(String signature) {
+ public static kelondroByteOrder orderBySignature(final String signature) {
kelondroByteOrder oo = null;
if (oo == null) oo = kelondroNaturalOrder.bySignature(signature);
if (oo == null) oo = kelondroBase64Order.bySignature(signature);
@@ -59,7 +59,7 @@ public final class kelondroNaturalOrder extends kelondroAbstractOrder<byte[]> im
return oo;
}
- public final static kelondroByteOrder bySignature(String signature) {
+ public final static kelondroByteOrder bySignature(final String signature) {
if (signature.equals("nd")) return new kelondroNaturalOrder(false);
if (signature.equals("nu")) return new kelondroNaturalOrder(true);
return null;
@@ -71,7 +71,7 @@ public final class kelondroNaturalOrder extends kelondroAbstractOrder<byte[]> im
return null;
}
- private final static long cardinalI(byte[] key) {
+ private final static long cardinalI(final byte[] key) {
// returns a cardinal number in the range of 0 .. Long.MAX_VALUE
long c = 0;
int p = 0;
@@ -81,16 +81,16 @@ public final class kelondroNaturalOrder extends kelondroAbstractOrder<byte[]> im
return c;
}
- public final long cardinal(byte[] key) {
+ public final long cardinal(final byte[] key) {
if (this.zero == null) return cardinalI(key);
- long zeroCardinal = cardinalI(this.zero);
- long keyCardinal = cardinalI(key);
+ final long zeroCardinal = cardinalI(this.zero);
+ final long keyCardinal = cardinalI(key);
if (keyCardinal > zeroCardinal) return keyCardinal - zeroCardinal;
return Long.MAX_VALUE - keyCardinal + zeroCardinal;
}
public final static byte[] encodeLong(long c, int length) {
- byte[] b = new byte[length];
+ final byte[] b = new byte[length];
while (length > 0) {
b[--length] = (byte) (c & 0xFF);
c >>= 8;
@@ -98,7 +98,7 @@ public final class kelondroNaturalOrder extends kelondroAbstractOrder<byte[]> im
return b;
}
- public final static void encodeLong(long c, byte[] b, int offset, int length) {
+ public final static void encodeLong(long c, final byte[] b, final int offset, int length) {
assert offset + length <= b.length;
while (length > 0) {
b[--length + offset] = (byte) (c & 0xFF);
@@ -106,7 +106,7 @@ public final class kelondroNaturalOrder extends kelondroAbstractOrder<byte[]> im
}
}
- public final static long decodeLong(byte[] s) {
+ public final static long decodeLong(final byte[] s) {
if (s == null) return 0;
long c = 0;
int p = 0;
@@ -114,7 +114,7 @@ public final class kelondroNaturalOrder extends kelondroAbstractOrder<byte[]> im
return c;
}
- public final static long decodeLong(byte[] s, int offset, int length) {
+ public final static long decodeLong(final byte[] s, int offset, final int length) {
if (s == null) return 0;
long c = 0;
final int m = Math.min(s.length, offset + length);
@@ -122,7 +122,7 @@ public final class kelondroNaturalOrder extends kelondroAbstractOrder<byte[]> im
return c;
}
- private static final int sig(int x) {
+ private static final int sig(final int x) {
return (x > 0) ? 1 : (x < 0) ? -1 : 0;
}
@@ -131,15 +131,15 @@ public final class kelondroNaturalOrder extends kelondroAbstractOrder<byte[]> im
// is less than, equal to, or greater than the second.
// two arrays are also equal if one array is a subset of the other's array
// with filled-up char(0)-values
- public final int compare(byte[] a, byte[] b) {
+ public final int compare(final byte[] a, final byte[] b) {
return (asc) ? compare0(a, 0, a.length, b, 0, b.length) : compare0(b, 0, b.length, a, 0, a.length);
}
- public final int compare(byte[] a, int aoffset, int alength, byte[] b, int boffset, int blength) {
+ public final int compare(final byte[] a, final int aoffset, final int alength, final byte[] b, final int boffset, final int blength) {
return (asc) ? compare0(a, aoffset, alength, b, boffset, blength) : compare0(b, boffset, blength, a, aoffset, alength);
}
- public final int compare0(byte[] a, int aoffset, int alength, byte[] b, int boffset, int blength) {
+ public final int compare0(final byte[] a, final int aoffset, final int alength, final byte[] b, final int boffset, final int blength) {
if (zero == null) return compares(a, aoffset, alength, b, boffset, blength);
// we have an artificial start point. check all combinations
final int az = compares(a, aoffset, alength, zero, 0, zero.length); // -1 if a < z; 0 if a == z; 1 if a > z
@@ -148,13 +148,13 @@ public final class kelondroNaturalOrder extends kelondroAbstractOrder<byte[]> im
return sig(az - bz);
}
- public static final boolean equal(byte[] a, byte[] b) {
+ public static final boolean equal(final byte[] a, final byte[] b) {
if ((a == null) && (b == null)) return true;
if ((a == null) || (b == null)) return false;
return compares(a, 0, a.length, b, 0, b.length) == 0;
}
- public static final int compares(byte[] a, int aoffset, int alength, byte[] b, int boffset, int blength) {
+ public static final int compares(final byte[] a, final int aoffset, final int alength, final byte[] b, final int boffset, final int blength) {
int i = 0;
final int al = Math.min(alength, a.length - aoffset);
final int bl = Math.min(blength, b.length - boffset);
@@ -174,11 +174,11 @@ public final class kelondroNaturalOrder extends kelondroAbstractOrder<byte[]> im
return 0;
}
- public static void main(String[] args) {
- byte[] t = new byte[12];
+ public static void main(final String[] args) {
+ final byte[] t = new byte[12];
for (int i = 0; i < 12; i++) t[i] = (byte) 255;
t[0] = (byte) 127;
- kelondroOrder<byte[]> o = new kelondroNaturalOrder(true);
+ final kelondroOrder<byte[]> o = new kelondroNaturalOrder(true);
System.out.println(o.partition(t, 16));
}
diff --git a/source/de/anomic/kelondro/kelondroObjectBuffer.java b/source/de/anomic/kelondro/kelondroObjectBuffer.java
index 0df662921..0fe1156c8 100644
--- a/source/de/anomic/kelondro/kelondroObjectBuffer.java
+++ b/source/de/anomic/kelondro/kelondroObjectBuffer.java
@@ -62,11 +62,11 @@ public class kelondroObjectBuffer {
// without an index-backend
private int readHit, readMiss, writeUnique, writeDouble;
- private String name;
+ private final String name;
private byte[] key;
private Object value;
- public kelondroObjectBuffer(String name) {
+ public kelondroObjectBuffer(final String name) {
this.name = name;
this.readHit = 0;
this.readMiss = 0;
@@ -89,7 +89,7 @@ public class kelondroObjectBuffer {
};
}
- private static String[] combinedStatus(String[] a, String[] b) {
+ private static String[] combinedStatus(final String[] a, final String[] b) {
return new String[]{
Integer.toString(Integer.parseInt(a[0]) + Integer.parseInt(b[0])),
Integer.toString(Integer.parseInt(a[1]) + Integer.parseInt(b[1])),
@@ -98,14 +98,14 @@ public class kelondroObjectBuffer {
};
}
- public static String[] combinedStatus(String[][] a, int l) {
+ public static String[] combinedStatus(final String[][] a, final int l) {
if ((a == null) || (a.length == 0) || (l == 0)) return null;
if ((a.length >= 1) && (l == 1)) return a[0];
if ((a.length >= 2) && (l == 2)) return combinedStatus(a[0], a[1]);
return combinedStatus(combinedStatus(a, l - 1), a[l - 1]);
}
- public void put(byte[] key, Object value) {
+ public void put(final byte[] key, final Object value) {
if ((key == null) || (value == null)) return;
synchronized(this) {
if (kelondroNaturalOrder.equal(this.key, key)){
@@ -118,7 +118,7 @@ public class kelondroObjectBuffer {
}
}
- public void put(String key, Object value) {
+ public void put(final String key, final Object value) {
if ((key == null) || (value == null)) return;
synchronized(this) {
if (kelondroNaturalOrder.equal(this.key, key.getBytes())){
@@ -131,7 +131,7 @@ public class kelondroObjectBuffer {
}
}
- public Object get(byte[] key) {
+ public Object get(final byte[] key) {
if (key == null) return null;
synchronized(this) {
if (kelondroNaturalOrder.equal(this.key, key)){
@@ -144,7 +144,7 @@ public class kelondroObjectBuffer {
}
}
- public Object get(String key) {
+ public Object get(final String key) {
if (key == null) return null;
synchronized(this) {
if (kelondroNaturalOrder.equal(this.key, key.getBytes())){
@@ -157,7 +157,7 @@ public class kelondroObjectBuffer {
}
}
- public void remove(byte[] key) {
+ public void remove(final byte[] key) {
if (key == null) return;
synchronized(this) {
if (kelondroNaturalOrder.equal(this.key, key)){
@@ -167,7 +167,7 @@ public class kelondroObjectBuffer {
}
}
- public void remove(String key) {
+ public void remove(final String key) {
if (key == null) return;
synchronized(this) {
if (kelondroNaturalOrder.equal(this.key, key.getBytes())){
diff --git a/source/de/anomic/kelondro/kelondroObjectSpace.java b/source/de/anomic/kelondro/kelondroObjectSpace.java
index 188388cbb..c21cb9380 100644
--- a/source/de/anomic/kelondro/kelondroObjectSpace.java
+++ b/source/de/anomic/kelondro/kelondroObjectSpace.java
@@ -37,7 +37,7 @@ public class kelondroObjectSpace {
private static TreeMap<Integer, Integer> aliveNow = new TreeMap<Integer, Integer>();
//private static TreeMap aliveMax = new TreeMap();
- private static void incAlive(int size) {
+ private static void incAlive(final int size) {
final Integer s = new Integer(size);
synchronized (aliveNow) {
final Integer x = aliveNow.get(s);
@@ -45,7 +45,7 @@ public class kelondroObjectSpace {
}
}
- private static void decAlive(int size) {
+ private static void decAlive(final int size) {
final Integer s = new Integer(size);
synchronized (aliveNow) {
final Integer x = aliveNow.get(s);
@@ -53,11 +53,11 @@ public class kelondroObjectSpace {
}
}
- public static byte[] alloc(int len) {
+ public static byte[] alloc(final int len) {
if ((len < minSize) || (len > maxSize)) return new byte[len];
incAlive(len);
synchronized (objHeap) {
- ArrayList<byte[]> buf = objHeap.get(new Integer(len));
+ final ArrayList<byte[]> buf = objHeap.get(new Integer(len));
if ((buf == null) || (buf.size() == 0)) return new byte[len];
return buf.remove(buf.size() - 1);
}
@@ -91,9 +91,9 @@ public class kelondroObjectSpace {
// creates a statistic output of this object space
// the result is a mapping from Integer (chunk size) to Integer (number of counts)
// and shows how many Objects are held in this space for usage
- TreeMap<Integer, Integer> result = new TreeMap<Integer, Integer>();
+ final TreeMap<Integer, Integer> result = new TreeMap<Integer, Integer>();
synchronized (objHeap) {
- Iterator<Map.Entry<Integer, ArrayList<byte[]>>> i = objHeap.entrySet().iterator();
+ final Iterator<Map.Entry<Integer, ArrayList<byte[]>>> i = objHeap.entrySet().iterator();
Map.Entry<Integer, ArrayList<byte[]>> entry;
while (i.hasNext()) {
entry = i.next();
diff --git a/source/de/anomic/kelondro/kelondroOutOfLimitsException.java b/source/de/anomic/kelondro/kelondroOutOfLimitsException.java
index 553445e9f..2038a011e 100644
--- a/source/de/anomic/kelondro/kelondroOutOfLimitsException.java
+++ b/source/de/anomic/kelondro/kelondroOutOfLimitsException.java
@@ -30,11 +30,11 @@ public class kelondroOutOfLimitsException extends java.lang.RuntimeException {
super("unspecific-error");
}
- public kelondroOutOfLimitsException(int expectedLimit, int actualSize) {
+ public kelondroOutOfLimitsException(final int expectedLimit, final int actualSize) {
super("Object size is " + actualSize + "; it exceeds the size limit " + expectedLimit);
}
- public kelondroOutOfLimitsException(int actualSize) {
+ public kelondroOutOfLimitsException(final int actualSize) {
super("Object size is " + actualSize + "; must not be negative");
}
diff --git a/source/de/anomic/kelondro/kelondroProfile.java b/source/de/anomic/kelondro/kelondroProfile.java
index 98054f992..dbd0c1661 100644
--- a/source/de/anomic/kelondro/kelondroProfile.java
+++ b/source/de/anomic/kelondro/kelondroProfile.java
@@ -61,7 +61,7 @@ public class kelondroProfile implements Cloneable {
return System.currentTimeMillis();
}
- protected void stopRead(long handle) {
+ protected void stopRead(final long handle) {
accRead += System.currentTimeMillis() - handle;
}
@@ -69,7 +69,7 @@ public class kelondroProfile implements Cloneable {
return System.currentTimeMillis();
}
- protected void stopWrite(long handle) {
+ protected void stopWrite(final long handle) {
accWrite += System.currentTimeMillis() - handle;
}
@@ -77,12 +77,12 @@ public class kelondroProfile implements Cloneable {
return System.currentTimeMillis();
}
- protected void stopDelete(long handle) {
+ protected void stopDelete(final long handle) {
accDelete += System.currentTimeMillis() - handle;
}
public kelondroProfile clone() {
- kelondroProfile clone = new kelondroProfile();
+ final kelondroProfile clone = new kelondroProfile();
clone.accRead = this.accRead;
clone.accWrite = this.accWrite;
clone.accDelete = this.accDelete;
@@ -93,20 +93,20 @@ public class kelondroProfile implements Cloneable {
return "read=" + accRead + ", write=" + accWrite + ", delete=" + accDelete;
}
- public static kelondroProfile consolidate(kelondroProfile[] profiles) {
+ public static kelondroProfile consolidate(final kelondroProfile[] profiles) {
for (int i = 1; i < profiles.length; i++) consolidate(profiles[0], profiles[i]);
return profiles[0];
}
- public static kelondroProfile consolidate(kelondroProfile profile1, kelondroProfile profile2) {
+ public static kelondroProfile consolidate(final kelondroProfile profile1, final kelondroProfile profile2) {
profile1.accRead += profile2.accRead;
profile1.accWrite += profile2.accWrite;
profile1.accDelete += profile2.accDelete;
return profile1;
}
- public static kelondroProfile delta(kelondroProfile newer, kelondroProfile older) {
- kelondroProfile result = new kelondroProfile();
+ public static kelondroProfile delta(final kelondroProfile newer, final kelondroProfile older) {
+ final kelondroProfile result = new kelondroProfile();
result.accRead = newer.accRead - older.accRead;
result.accWrite = newer.accWrite - older.accWrite;
result.accDelete = newer.accDelete - older.accDelete;
diff --git a/source/de/anomic/kelondro/kelondroRAIOChunks.java b/source/de/anomic/kelondro/kelondroRAIOChunks.java
index 236b3d495..798b545ce 100644
--- a/source/de/anomic/kelondro/kelondroRAIOChunks.java
+++ b/source/de/anomic/kelondro/kelondroRAIOChunks.java
@@ -28,7 +28,7 @@ public final class kelondroRAIOChunks extends kelondroAbstractIOChunks implement
protected kelondroRA ra;
- public kelondroRAIOChunks(kelondroRA ra, String name) {
+ public kelondroRAIOChunks(final kelondroRA ra, final String name) {
this.name = name;
this.ra = ra;
}
@@ -41,10 +41,10 @@ public final class kelondroRAIOChunks extends kelondroAbstractIOChunks implement
return ra.length();
}
- public synchronized int read(long pos, byte[] b, int off, int len) throws IOException {
+ public synchronized int read(final long pos, final byte[] b, final int off, final int len) throws IOException {
if (len == 0) return 0;
this.ra.seek(pos);
- long available = ra.available();
+ final long available = ra.available();
if (available >= len) {
return ra.read(b, off, len);
} else if (available == 0) {
@@ -54,7 +54,7 @@ public final class kelondroRAIOChunks extends kelondroAbstractIOChunks implement
}
}
- public synchronized void write(long pos, byte[] b, int off, int len) throws IOException {
+ public synchronized void write(final long pos, final byte[] b, final int off, final int len) throws IOException {
this.ra.seek(pos);
this.ra.write(b, off, len);
}
diff --git a/source/de/anomic/kelondro/kelondroRAMIndex.java b/source/de/anomic/kelondro/kelondroRAMIndex.java
index d5c0741ee..d6ecdd2df 100644
--- a/source/de/anomic/kelondro/kelondroRAMIndex.java
+++ b/source/de/anomic/kelondro/kelondroRAMIndex.java
@@ -33,11 +33,11 @@ import de.anomic.kelondro.kelondroRow.Entry;
public class kelondroRAMIndex implements kelondroIndex {
- private kelondroRow rowdef;
+ private final kelondroRow rowdef;
private kelondroRowSet index0, index1;
- private kelondroRow.EntryComparator entryComparator;
+ private final kelondroRow.EntryComparator entryComparator;
- public kelondroRAMIndex(kelondroRow rowdef, int initialspace) {
+ public kelondroRAMIndex(final kelondroRow rowdef, final int initialspace) {
this.rowdef = rowdef;
this.entryComparator = new kelondroRow.EntryComparator(rowdef.objectOrder);
reset(initialspace);
@@ -47,7 +47,7 @@ public class kelondroRAMIndex implements kelondroIndex {
reset(0);
}
- public void reset(int initialspace) {
+ public void reset(final int initialspace) {
this.index0 = null; // first flush RAM to make room
this.index0 = new kelondroRowSet(rowdef, initialspace);
this.index1 = null; // to show that this is the initialization phase
@@ -66,26 +66,26 @@ public class kelondroRAMIndex implements kelondroIndex {
}
}
- public synchronized kelondroRow.Entry get(byte[] key) {
+ public synchronized kelondroRow.Entry get(final byte[] key) {
assert (key != null);
finishInitialization();
- kelondroRow.Entry indexentry = index0.get(key);
+ final kelondroRow.Entry indexentry = index0.get(key);
if (indexentry != null) return indexentry;
return index1.get(key);
}
- public boolean has(byte[] key) {
+ public boolean has(final byte[] key) {
assert (key != null);
finishInitialization();
if (index0.has(key)) return true;
return index1.has(key);
}
- public synchronized kelondroRow.Entry put(kelondroRow.Entry entry) {
+ public synchronized kelondroRow.Entry put(final kelondroRow.Entry entry) {
assert (entry != null);
finishInitialization();
// if the new entry is within the initialization part, just overwrite it
- kelondroRow.Entry indexentry = index0.get(entry.getPrimaryKeyBytes());
+ final kelondroRow.Entry indexentry = index0.get(entry.getPrimaryKeyBytes());
if (indexentry != null) {
index0.put(entry);
return indexentry;
@@ -94,18 +94,18 @@ public class kelondroRAMIndex implements kelondroIndex {
return index1.put(entry);
}
- public Entry put(Entry row, Date entryDate) {
+ public Entry put(final Entry row, final Date entryDate) {
return put(row);
}
- public void putMultiple(List<Entry> rows) {
- Iterator<Entry> i = rows.iterator();
+ public void putMultiple(final List<Entry> rows) {
+ final Iterator<Entry> i = rows.iterator();
while (i.hasNext()) {
put(i.next());
}
}
- public synchronized boolean addUnique(kelondroRow.Entry entry) {
+ public synchronized boolean addUnique(final kelondroRow.Entry entry) {
assert (entry != null);
if (index1 == null) {
// we are in the initialization phase
@@ -116,8 +116,8 @@ public class kelondroRAMIndex implements kelondroIndex {
}
}
- public int addUniqueMultiple(List<Entry> rows) {
- Iterator<Entry> i = rows.iterator();
+ public int addUniqueMultiple(final List<Entry> rows) {
+ final Iterator<Entry> i = rows.iterator();
int c = 0;
while (i.hasNext()) {
if (addUnique(i.next())) c++;
@@ -131,16 +131,16 @@ public class kelondroRAMIndex implements kelondroIndex {
return index0.removeDoubles();
}
- public synchronized kelondroRow.Entry remove(byte[] key) {
+ public synchronized kelondroRow.Entry remove(final byte[] key) {
finishInitialization();
// if the new entry is within the initialization part, just delete it
- kelondroRow.Entry indexentry = index0.remove(key);
+ final kelondroRow.Entry indexentry = index0.remove(key);
if (indexentry != null) {
assert index0.get(key) == null; // check if remove worked
return indexentry;
}
// else remove it from the index1
- kelondroRow.Entry removed = index1.remove(key);
+ final kelondroRow.Entry removed = index1.remove(key);
assert index1.get(key) == null : "removed " + ((removed == null) ? " is null" : " is not null") + ", and index entry still exists"; // check if remove worked
return removed;
}
@@ -166,7 +166,7 @@ public class kelondroRAMIndex implements kelondroIndex {
return index0.size() + index1.size();
}
- public synchronized kelondroCloneableIterator<byte[]> keys(boolean up, byte[] firstKey) {
+ public synchronized kelondroCloneableIterator<byte[]> keys(final boolean up, final byte[] firstKey) {
// returns the key-iterator of the underlying kelondroIndex
if (index1 == null) {
// finish initialization phase
@@ -192,7 +192,7 @@ public class kelondroRAMIndex implements kelondroIndex {
true);
}
- public synchronized kelondroCloneableIterator<kelondroRow.Entry> rows(boolean up, byte[] firstKey) {
+ public synchronized kelondroCloneableIterator<kelondroRow.Entry> rows(final boolean up, final byte[] firstKey) {
// returns the row-iterator of the underlying kelondroIndex
if (index1 == null) {
// finish initialization phase
diff --git a/source/de/anomic/kelondro/kelondroRelations.java b/source/de/anomic/kelondro/kelondroRelations.java
index afe8edc81..9fccf4184 100755
--- a/source/de/anomic/kelondro/kelondroRelations.java
+++ b/source/de/anomic/kelondro/kelondroRelations.java
@@ -32,10 +32,10 @@ import java.util.HashMap;
public class kelondroRelations {
- private File baseDir;
+ private final File baseDir;
private HashMap<String, kelondroIndex> relations;
- public kelondroRelations(File location) {
+ public kelondroRelations(final File location) {
this.baseDir = location;
}
@@ -44,15 +44,15 @@ public class kelondroRelations {
if (p >= 0) filename = filename.substring(0, p);
p = filename.lastIndexOf('-');
assert p >= 0;
- int payloadsize = Integer.parseInt(filename.substring(p + 1));
+ final int payloadsize = Integer.parseInt(filename.substring(p + 1));
filename = filename.substring(0, p);
p = filename.lastIndexOf('-');
assert p >= 0;
- int keysize = Integer.parseInt(filename.substring(p + 1));
+ final int keysize = Integer.parseInt(filename.substring(p + 1));
return rowdef(keysize, payloadsize);
}
- private static kelondroRow rowdef(int keysize, int payloadsize) {
+ private static kelondroRow rowdef(final int keysize, final int payloadsize) {
return new kelondroRow(
"byte[] key-" + keysize + ", " +
"long time-8" + keysize + ", " +
@@ -61,43 +61,43 @@ public class kelondroRelations {
kelondroNaturalOrder.naturalOrder, 0);
}
- private static String filename(String tablename, int keysize, int payloadsize) {
+ private static String filename(final String tablename, final int keysize, final int payloadsize) {
return tablename + "-" + keysize + "-" + payloadsize + ".eco";
}
- public void declareRelation(String name, int keysize, int payloadsize) {
+ public void declareRelation(final String name, final int keysize, final int payloadsize) {
// try to get the relation from the relation-cache
- kelondroIndex relation = relations.get(name);
+ final kelondroIndex relation = relations.get(name);
if (relation != null) return;
// try to find the relation as stored on file
- String[] list = baseDir.list();
- String targetfilename = filename(name, keysize, payloadsize);
+ final String[] list = baseDir.list();
+ final String targetfilename = filename(name, keysize, payloadsize);
for (int i = 0; i < list.length; i++) {
if (list[i].startsWith(name)) {
if (!list[i].equals(targetfilename)) continue;
- kelondroRow row = rowdef(list[i]);
+ final kelondroRow row = rowdef(list[i]);
if (row.primaryKeyLength != keysize || row.column(1).cellwidth != payloadsize) continue; // a wrong table
- kelondroIndex table = new kelondroEcoTable(new File(baseDir, list[i]), row, kelondroEcoTable.tailCacheUsageAuto, 1024*1024, 0);
+ final kelondroIndex table = new kelondroEcoTable(new File(baseDir, list[i]), row, kelondroEcoTable.tailCacheUsageAuto, 1024*1024, 0);
relations.put(name, table);
return;
}
}
// the relation does not exist, create it
- kelondroRow row = rowdef(keysize, payloadsize);
- kelondroIndex table = new kelondroEcoTable(new File(baseDir, targetfilename), row, kelondroEcoTable.tailCacheUsageAuto, 1024*1024, 0);
+ final kelondroRow row = rowdef(keysize, payloadsize);
+ final kelondroIndex table = new kelondroEcoTable(new File(baseDir, targetfilename), row, kelondroEcoTable.tailCacheUsageAuto, 1024*1024, 0);
relations.put(name, table);
}
- public kelondroIndex getRelation(String name) {
+ public kelondroIndex getRelation(final String name) {
// try to get the relation from the relation-cache
- kelondroIndex relation = relations.get(name);
+ final kelondroIndex relation = relations.get(name);
if (relation != null) return relation;
// try to find the relation as stored on file
- String[] list = baseDir.list();
+ final String[] list = baseDir.list();
for (int i = 0; i < list.length; i++) {
if (list[i].startsWith(name)) {
- kelondroRow row = rowdef(list[i]);
- kelondroIndex table = new kelondroEcoTable(new File(baseDir, list[i]), row, kelondroEcoTable.tailCacheUsageAuto, 1024*1024, 0);
+ final kelondroRow row = rowdef(list[i]);
+ final kelondroIndex table = new kelondroEcoTable(new File(baseDir, list[i]), row, kelondroEcoTable.tailCacheUsageAuto, 1024*1024, 0);
relations.put(name, table);
return table;
}
@@ -106,61 +106,61 @@ public class kelondroRelations {
return null;
}
- public String putRelation(String name, String key, String value) throws IOException {
- byte[] r = putRelation(name, key.getBytes(), value.getBytes());
+ public String putRelation(final String name, final String key, final String value) throws IOException {
+ final byte[] r = putRelation(name, key.getBytes(), value.getBytes());
if (r == null) return null;
return new String(r);
}
- public byte[] putRelation(String name, byte[] key, byte[] value) throws IOException {
- kelondroIndex table = getRelation(name);
+ public byte[] putRelation(final String name, final byte[] key, final byte[] value) throws IOException {
+ final kelondroIndex table = getRelation(name);
if (table == null) return null;
- kelondroRow.Entry entry = table.row().newEntry();
+ final kelondroRow.Entry entry = table.row().newEntry();
entry.setCol(0, key);
entry.setCol(1, System.currentTimeMillis());
entry.setCol(2, 1000000);
entry.setCol(3, value);
- kelondroRow.Entry oldentry = table.put(entry);
+ final kelondroRow.Entry oldentry = table.put(entry);
if (oldentry == null) return null;
return oldentry.getColBytes(3);
}
- public String getRelation(String name, String key) throws IOException {
- byte[] r = getRelation(name, key.getBytes());
+ public String getRelation(final String name, final String key) throws IOException {
+ final byte[] r = getRelation(name, key.getBytes());
if (r == null) return null;
return new String(r);
}
- public byte[] getRelation(String name, byte[] key) throws IOException {
- kelondroIndex table = getRelation(name);
+ public byte[] getRelation(final String name, final byte[] key) throws IOException {
+ final kelondroIndex table = getRelation(name);
if (table == null) return null;
- kelondroRow.Entry entry = table.get(key);
+ final kelondroRow.Entry entry = table.get(key);
if (entry == null) return null;
return entry.getColBytes(3);
}
- public boolean hasRelation(String name, byte[] key) throws IOException {
- kelondroIndex table = getRelation(name);
+ public boolean hasRelation(final String name, final byte[] key) throws IOException {
+ final kelondroIndex table = getRelation(name);
if (table == null) return false;
return table.has(key);
}
- public byte[] removeRelation(String name, byte[] key) throws IOException {
- kelondroIndex table = getRelation(name);
+ public byte[] removeRelation(final String name, final byte[] key) throws IOException {
+ final kelondroIndex table = getRelation(name);
if (table == null) return null;
- kelondroRow.Entry entry = table.remove(key);
+ final kelondroRow.Entry entry = table.remove(key);
if (entry == null) return null;
return entry.getColBytes(3);
}
- public static void main(String args[]) {
- kelondroRelations r = new kelondroRelations(new File("/Users/admin/"));
+ public static void main(final String args[]) {
+ final kelondroRelations r = new kelondroRelations(new File("/Users/admin/"));
try {
- String table1 = "test1";
+ final String table1 = "test1";
r.declareRelation(table1, 12, 30);
r.putRelation(table1, "abcdefg", "eineintrag");
r.putRelation(table1, "abcdefg", "eineintrag");
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
}
diff --git a/source/de/anomic/kelondro/kelondroRotateIterator.java b/source/de/anomic/kelondro/kelondroRotateIterator.java
index 04da8c9d7..8ccb779b2 100644
--- a/source/de/anomic/kelondro/kelondroRotateIterator.java
+++ b/source/de/anomic/kelondro/kelondroRotateIterator.java
@@ -33,7 +33,7 @@ public class kelondroRotateIterator<E> implements kelondroCloneableIterator<E> {
boolean nempty;
int terminationCount;
- public kelondroRotateIterator(kelondroCloneableIterator<E> a, Object modifier, int terminationCount) {
+ public kelondroRotateIterator(final kelondroCloneableIterator<E> a, final Object modifier, final int terminationCount) {
// this works currently only for String-type key iterations
this.a = a;
this.modifier = modifier;
@@ -42,7 +42,7 @@ public class kelondroRotateIterator<E> implements kelondroCloneableIterator<E> {
this.nempty = this.clone.hasNext();
}
- public kelondroRotateIterator<E> clone(Object modifier) {
+ public kelondroRotateIterator<E> clone(final Object modifier) {
return new kelondroRotateIterator<E>(a, modifier, terminationCount - 1);
}
diff --git a/source/de/anomic/kelondro/kelondroRow.java b/source/de/anomic/kelondro/kelondroRow.java
index aaa877a94..c1531c746 100644
--- a/source/de/anomic/kelondro/kelondroRow.java
+++ b/source/de/anomic/kelondro/kelondroRow.java
@@ -46,7 +46,7 @@ public final class kelondroRow {
public int primaryKeyIndex, primaryKeyLength;
protected Map<String, Object[]> nickref = null; // a mapping from nicknames to Object[2]{kelondroColumn, Integer(colstart)}
- public kelondroRow(kelondroColumn[] row, kelondroByteOrder objectOrder, int primaryKey) {
+ public kelondroRow(final kelondroColumn[] row, final kelondroByteOrder objectOrder, final int primaryKey) {
assert objectOrder != null;
this.objectOrder = objectOrder;
this.row = row;
@@ -61,7 +61,7 @@ public final class kelondroRow {
this.primaryKeyLength = (primaryKey < 0) ? this.objectsize : row[primaryKeyIndex].cellwidth;
}
- public kelondroRow(String structure, kelondroByteOrder objectOrder, int primaryKey) {
+ public kelondroRow(final String structure, final kelondroByteOrder objectOrder, final int primaryKey) {
assert (objectOrder != null);
this.objectOrder = objectOrder;
// define row with row syntax
@@ -74,9 +74,9 @@ public final class kelondroRow {
// parse property part definition:
int p = structure.indexOf('|');
if (p < 0) p = structure.length();
- ArrayList<kelondroColumn> l = new ArrayList<kelondroColumn>();
- String attr = structure.substring(0, p);
- StringTokenizer st = new StringTokenizer(attr, ",");
+ final ArrayList<kelondroColumn> l = new ArrayList<kelondroColumn>();
+ final String attr = structure.substring(0, p);
+ final StringTokenizer st = new StringTokenizer(attr, ",");
while (st.hasMoreTokens()) {
l.add(new kelondroColumn(st.nextToken()));
}
@@ -94,7 +94,7 @@ public final class kelondroRow {
this.primaryKeyLength = (primaryKey < 0) ? this.objectsize : row[primaryKeyIndex].cellwidth;
}
- public final void setOrdering(kelondroByteOrder objectOrder, int primaryKey) {
+ public final void setOrdering(final kelondroByteOrder objectOrder, final int primaryKey) {
assert (objectOrder != null);
this.objectOrder = objectOrder;
this.primaryKeyIndex = primaryKey;
@@ -119,22 +119,22 @@ public final class kelondroRow {
return this.objectsize;
}
*/
- public final kelondroColumn column(int col) {
+ public final kelondroColumn column(final int col) {
return row[col];
}
- public final int width(int column) {
+ public final int width(final int column) {
return this.row[column].cellwidth;
}
public final int[] widths() {
- int[] w = new int[this.row.length];
+ final int[] w = new int[this.row.length];
for (int i = 0; i < this.row.length; i++) w[i] = row[i].cellwidth;
return w;
}
public final String toString() {
- StringBuffer s = new StringBuffer();
+ final StringBuffer s = new StringBuffer();
s.append(row[0].toString());
for (int i = 1; i < row.length; i++) {
s.append(", ");
@@ -147,7 +147,7 @@ public final class kelondroRow {
return new Entry();
}
- public final Entry newEntry(byte[] rowinstance) {
+ public final Entry newEntry(final byte[] rowinstance) {
if (rowinstance == null) return null;
//assert (rowinstance[0] != 0);
assert (this.objectOrder.wellformed(rowinstance, 0, row[0].cellwidth)) : "rowinstance[0] = " + new String(rowinstance, 0, row[0].cellwidth) + " / " + serverLog.arrayList(rowinstance, 0, row[0].cellwidth);
@@ -155,14 +155,14 @@ public final class kelondroRow {
return new Entry(rowinstance, false);
}
- public final Entry newEntry(Entry oldrow, int fromColumn) {
+ public final Entry newEntry(final Entry oldrow, final int fromColumn) {
if (oldrow == null) return null;
assert (oldrow.getColBytes(0)[0] != 0);
assert (this.objectOrder.wellformed(oldrow.getColBytes(0), 0, row[0].cellwidth));
return new Entry(oldrow, fromColumn, false);
}
- public final Entry newEntry(byte[] rowinstance, int start, boolean clone) {
+ public final Entry newEntry(final byte[] rowinstance, final int start, final boolean clone) {
if (rowinstance == null) return null;
//assert (rowinstance[0] != 0);
assert (this.objectOrder.wellformed(rowinstance, start, row[0].cellwidth)) : "rowinstance = " + new String(rowinstance);
@@ -172,19 +172,19 @@ public final class kelondroRow {
return new Entry(rowinstance, start, clone);
}
- public final Entry newEntry(byte[][] cells) {
+ public final Entry newEntry(final byte[][] cells) {
if (cells == null) return null;
assert (cells[0][0] != 0);
assert (this.objectOrder.wellformed(cells[0], 0, row[0].cellwidth));
return new Entry(cells);
}
- public final Entry newEntry(String external, boolean decimalCardinal) {
+ public final Entry newEntry(final String external, final boolean decimalCardinal) {
if (external == null) return null;
return new Entry(external, decimalCardinal);
}
- public final EntryIndex newEntryIndex(byte[] rowinstance, int index) {
+ public final EntryIndex newEntryIndex(final byte[] rowinstance, final int index) {
if (rowinstance == null) return null;
assert (rowinstance[0] != 0);
assert (this.objectOrder.wellformed(rowinstance, 0, row[0].cellwidth));
@@ -194,11 +194,11 @@ public final class kelondroRow {
public static class EntryComparator extends kelondroAbstractOrder<Entry> implements kelondroOrder<Entry>, Comparator<Entry> {
kelondroByteOrder base;
- public EntryComparator(kelondroByteOrder baseOrder) {
+ public EntryComparator(final kelondroByteOrder baseOrder) {
this.base = baseOrder;
}
- public int compare(Entry a, Entry b) {
+ public int compare(final Entry a, final Entry b) {
return a.compareTo(b);
}
@@ -206,7 +206,7 @@ public final class kelondroRow {
return new EntryComparator(base);
}
- public long cardinal(Entry key) {
+ public long cardinal(final Entry key) {
return base.cardinal(key.getPrimaryKeyBytes());
}
@@ -214,7 +214,7 @@ public final class kelondroRow {
return base.signature();
}
- public boolean wellformed(Entry a) {
+ public boolean wellformed(final Entry a) {
return base.wellformed(a.getPrimaryKeyBytes());
}
@@ -231,15 +231,15 @@ public final class kelondroRow {
offset = 0;
}
- public Entry(byte[] newrow, boolean forceclone) {
+ public Entry(final byte[] newrow, final boolean forceclone) {
this(newrow, 0, forceclone);
}
- public Entry(Entry oldrow, int fromColumn, boolean forceclone) {
+ public Entry(final Entry oldrow, final int fromColumn, final boolean forceclone) {
this(oldrow.rowinstance, oldrow.offset + oldrow.colstart(fromColumn), forceclone);
}
- public Entry(byte[] newrow, int start, boolean forceclone) {
+ public Entry(final byte[] newrow, final int start, final boolean forceclone) {
if ((!forceclone) && (newrow.length - start >= objectsize)) {
this.rowinstance = newrow;
this.offset = start;
@@ -251,7 +251,7 @@ public final class kelondroRow {
//for (int i = ll; i < objectsize; i++) this.rowinstance[i] = 0;
}
- public Entry(byte[][] cols) {
+ public Entry(final byte[][] cols) {
assert row.length == cols.length : "cols.length = " + cols.length + ", row.length = " + row.length;
this.rowinstance = new byte[objectsize];
this.offset = 0;
@@ -271,10 +271,10 @@ public final class kelondroRow {
}
}
- public Entry(String external, boolean decimalCardinal) {
+ public Entry(String external, final boolean decimalCardinal) {
// parse external form
if (external.charAt(0) == '{') external = external.substring(1, external.length() - 1);
- String[] elts = external.split(",");
+ final String[] elts = external.split(",");
if (nickref == null) genNickRef();
String nick;
int p;
@@ -290,7 +290,7 @@ public final class kelondroRow {
if ((decimalCardinal) && (row[i].celltype == kelondroColumn.celltype_cardinal)) {
try {
setCol(nick, Long.parseLong(elts[i].substring(p + 1).trim()));
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
serverLog.logSevere("kelondroRow", "NumberFormatException for celltype_cardinal; row = " + i + ", celltype = " + row[i].celltype + ", encoder = " + row[i].encoder + ", value = '" + elts[i].substring(p + 1).trim() + "'");
setCol(nick, 0);
}
@@ -298,7 +298,7 @@ public final class kelondroRow {
assert row[i].cellwidth == 1;
try {
setCol(nick, new byte[]{(byte) Integer.parseInt(elts[i].substring(p + 1).trim())});
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
serverLog.logSevere("kelondroRow", "NumberFormatException for celltype_binary; row = " + i + ", celltype = " + row[i].celltype + ", encoder = " + row[i].encoder + ", value = '" + elts[i].substring(p + 1).trim() + "'");
setCol(nick, new byte[]{0});
}
@@ -312,24 +312,24 @@ public final class kelondroRow {
}
}
- protected final int colstart(int column) {
+ protected final int colstart(final int column) {
return colstart[column];
}
- protected final int cellwidth(int column) {
+ protected final int cellwidth(final int column) {
return row[column].cellwidth;
}
- public final int compareTo(Entry o) {
+ public final int compareTo(final Entry o) {
// compares only the content of the primary key
if (objectOrder == null) throw new kelondroException("objects cannot be compared, no order given");
return objectOrder.compare(this.getPrimaryKeyBytes(), (o).getPrimaryKeyBytes());
}
- public final boolean equals(Entry otherEntry) {
+ public final boolean equals(final Entry otherEntry) {
// compares the content of the complete entry
- byte[] t = this.bytes();
- byte[] o = otherEntry.bytes();
+ final byte[] t = this.bytes();
+ final byte[] o = otherEntry.bytes();
if (o.length != t.length) return false;
for (int i = 0; i < t.length; i++) {
if (t[i] != o[i]) return false;
@@ -341,13 +341,13 @@ public final class kelondroRow {
if ((offset == 0) && (rowinstance.length == objectsize)) {
return rowinstance;
} else {
- byte[] tmp = new byte[objectsize];
+ final byte[] tmp = new byte[objectsize];
System.arraycopy(rowinstance, offset, tmp, 0, objectsize);
return tmp;
}
}
- public final void writeToArray(byte[] target, int targetOffset) {
+ public final void writeToArray(final byte[] target, final int targetOffset) {
// this method shall replace the byte()s where possible, bacause it may reduce the number of new byte[] allocations
assert (targetOffset + objectsize <= target.length) : "targetOffset = " + targetOffset + ", target.length = " + target.length + ", objectsize = " + objectsize;
System.arraycopy(rowinstance, offset, target, targetOffset, objectsize);
@@ -361,36 +361,36 @@ public final class kelondroRow {
return objectsize;
}
- public final boolean empty(int column) {
+ public final boolean empty(final int column) {
return rowinstance[offset + colstart[column]] == 0;
}
- public final void setCol(String nickname, char c) {
+ public final void setCol(final String nickname, final char c) {
if (nickref == null) genNickRef();
- Object[] ref = nickref.get(nickname);
+ final Object[] ref = nickref.get(nickname);
if (ref == null) return;
rowinstance[offset + ((Integer) ref[1]).intValue()] = (byte) c;
}
- public final void setCol(String nickname, byte[] cell) {
+ public final void setCol(final String nickname, final byte[] cell) {
if (nickref == null) genNickRef();
- Object[] ref = nickref.get(nickname);
+ final Object[] ref = nickref.get(nickname);
if (ref == null) return;
- kelondroColumn col = (kelondroColumn) ref[0];
+ final kelondroColumn col = (kelondroColumn) ref[0];
setCol(col.encoder, ((Integer) ref[1]).intValue(), col.cellwidth, cell);
}
- public final void setCol(int column, byte[] cell) {
+ public final void setCol(final int column, final byte[] cell) {
setCol(row[column].encoder, colstart[column], row[column].cellwidth, cell);
}
- public final void setCol(int column, char[] cell) {
- int clstrt = colstart[column];
+ public final void setCol(final int column, final char[] cell) {
+ final int clstrt = colstart[column];
for (int i = 0; i < cell.length; i++) rowinstance[offset + clstrt + i] = (byte) cell[i];
for (int i = cell.length; i < row[column].cellwidth; i++) rowinstance[offset + clstrt + i] = 0;
}
- private final void setCol(int encoding, int clstrt, int length, byte[] cell) {
+ private final void setCol(final int encoding, final int clstrt, int length, final byte[] cell) {
if (cell == null) {
while (length-- > 0) rowinstance[offset + clstrt + length] = 0;
} else {
@@ -404,46 +404,46 @@ public final class kelondroRow {
}
}
- public final void setCol(int column, byte c) {
+ public final void setCol(final int column, final byte c) {
rowinstance[offset + colstart[column]] = c;
}
- public final void setCol(int column, String cell, String encoding) {
+ public final void setCol(final int column, final String cell, final String encoding) {
if (encoding == null)
setCol(column, cell.getBytes());
else
try {
setCol(column, (cell == null) ? null : cell.getBytes(encoding));
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
e.printStackTrace();
}
}
- public final void setCol(String nick, String cell, String encoding) {
+ public final void setCol(final String nick, final String cell, final String encoding) {
if (encoding == null)
setCol(nick, cell.getBytes());
else
try {
setCol(nick, cell.getBytes(encoding));
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
e.printStackTrace();
}
}
- public final void setCol(String nickname, long cell) {
+ public final void setCol(final String nickname, final long cell) {
if (nickref == null) genNickRef();
- Object[] ref = nickref.get(nickname);
+ final Object[] ref = nickref.get(nickname);
if (ref == null) return;
- kelondroColumn col = (kelondroColumn) ref[0];
+ final kelondroColumn col = (kelondroColumn) ref[0];
setCol(col.encoder, offset + ((Integer) ref[1]).intValue(), col.cellwidth, cell);
}
- public final void setCol(int column, long cell) {
+ public final void setCol(final int column, final long cell) {
// uses the column definition to choose the right encoding
setCol(row[column].encoder, offset + colstart[column], row[column].cellwidth, cell);
}
- private final void setCol(int encoder, int offset, int length, long cell) {
+ private final void setCol(final int encoder, final int offset, final int length, final long cell) {
switch (encoder) {
case kelondroColumn.encoder_none:
throw new kelondroException("ROW", "setColLong has celltype none, no encoder given");
@@ -458,29 +458,29 @@ public final class kelondroRow {
}
}
- public final byte[] getCol(String nickname, byte[] dflt) {
+ public final byte[] getCol(final String nickname, final byte[] dflt) {
if (nickref == null) genNickRef();
- Object[] ref = nickref.get(nickname);
+ final Object[] ref = nickref.get(nickname);
if (ref == null) return dflt;
- kelondroColumn col = (kelondroColumn) ref[0];
- byte[] cell = new byte[col.cellwidth];
+ final kelondroColumn col = (kelondroColumn) ref[0];
+ final byte[] cell = new byte[col.cellwidth];
System.arraycopy(rowinstance, offset + ((Integer) ref[1]).intValue(), cell, 0, cell.length);
return cell;
}
- public final String getColString(String nickname, String dflt, String encoding) {
+ public final String getColString(final String nickname, final String dflt, final String encoding) {
if (nickref == null) genNickRef();
- Object[] ref = nickref.get(nickname);
+ final Object[] ref = nickref.get(nickname);
if (ref == null) return dflt;
- kelondroColumn col = (kelondroColumn) ref[0];
+ final kelondroColumn col = (kelondroColumn) ref[0];
return getColString(col.encoder, ((Integer) ref[1]).intValue(), col.cellwidth, encoding);
}
- public final String getColString(int column, String encoding) {
+ public final String getColString(final int column, final String encoding) {
return getColString(row[column].encoder, colstart[column], row[column].cellwidth, encoding);
}
- private final String getColString(int encoder, int clstrt, int length, String encoding) {
+ private final String getColString(final int encoder, final int clstrt, int length, final String encoding) {
if (rowinstance[offset + clstrt] == 0) return null;
if (length > rowinstance.length - offset - clstrt) length = rowinstance.length - offset - clstrt;
while ((length > 0) && (rowinstance[offset + clstrt + length - 1] == 0)) length--;
@@ -490,26 +490,26 @@ public final class kelondroRow {
return new String(rowinstance, offset + clstrt, length);
else
return new String(rowinstance, offset + clstrt, length, encoding);
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
return "";
}
}
- public final long getColLong(String nickname, long dflt) {
+ public final long getColLong(final String nickname, final long dflt) {
if (nickref == null) genNickRef();
- Object[] ref = nickref.get(nickname);
+ final Object[] ref = nickref.get(nickname);
if (ref == null) return dflt;
- kelondroColumn col = (kelondroColumn) ref[0];
- int clstrt = ((Integer) ref[1]).intValue();
+ final kelondroColumn col = (kelondroColumn) ref[0];
+ final int clstrt = ((Integer) ref[1]).intValue();
return getColLong(col.encoder, clstrt, col.cellwidth);
}
- public final long getColLong(int column) {
+ public final long getColLong(final int column) {
// uses the column definition to choose the right encoding
return getColLong(row[column].encoder, colstart[column], row[column].cellwidth);
}
- protected final long getColLong(int encoder, int clstrt, int length) {
+ protected final long getColLong(final int encoder, final int clstrt, final int length) {
switch (encoder) {
case kelondroColumn.encoder_none:
throw new kelondroException("ROW", "getColLong has celltype none, no encoder given");
@@ -531,47 +531,47 @@ public final class kelondroRow {
throw new kelondroException("ROW", "getColLong did not find appropriate encoding");
}
- public final byte getColByte(String nickname, byte dflt) {
+ public final byte getColByte(final String nickname, final byte dflt) {
if (nickref == null) genNickRef();
- Object[] ref = nickref.get(nickname);
+ final Object[] ref = nickref.get(nickname);
if (ref == null) return dflt;
return rowinstance[offset + ((Integer) ref[1]).intValue()];
}
- public final byte getColByte(int column) {
+ public final byte getColByte(final int column) {
return rowinstance[offset + colstart[column]];
}
public final byte[] getPrimaryKeyBytes() {
- byte[] c = new byte[primaryKeyLength];
+ final byte[] c = new byte[primaryKeyLength];
System.arraycopy(rowinstance, offset + ((primaryKeyIndex < 0) ? 0 : colstart[primaryKeyIndex]), c, 0, primaryKeyLength);
return c;
}
- public final byte[] getColBytes(int column) {
+ public final byte[] getColBytes(final int column) {
assert offset + colstart[column] + row[column].cellwidth <= rowinstance.length :
"column = " + column + ", offset = " + offset + ", colstart[column] = " + colstart[column] + ", row[column].cellwidth() = " + row[column].cellwidth + ", rowinstance.length = " + rowinstance.length;
- int w = row[column].cellwidth;
- byte[] c = new byte[w];
+ final int w = row[column].cellwidth;
+ final byte[] c = new byte[w];
System.arraycopy(rowinstance, offset + colstart[column], c, 0, w);
return c;
}
- public final char[] getColChars(int column) {
- int w = row[column].cellwidth;
- char[] c = new char[w];
+ public final char[] getColChars(final int column) {
+ final int w = row[column].cellwidth;
+ final char[] c = new char[w];
System.arraycopy(rowinstance, offset + colstart[column], c, 0, w);
return c;
}
- public final void writeToArray(int column, byte[] target, int targetOffset) {
+ public final void writeToArray(final int column, final byte[] target, final int targetOffset) {
// this method shall replace the getColBytes where possible, bacause it may reduce the number of new byte[] allocations
assert (targetOffset + row[column].cellwidth <= target.length) : "targetOffset = " + targetOffset + ", target.length = " + target.length + ", row[column].cellwidth() = " + row[column].cellwidth;
System.arraycopy(rowinstance, offset + colstart[column], target, targetOffset, row[column].cellwidth);
}
- public final String toPropertyForm(boolean includeBraces, boolean decimalCardinal, boolean longname) {
- serverByteBuffer bb = new serverByteBuffer();
+ public final String toPropertyForm(final boolean includeBraces, final boolean decimalCardinal, final boolean longname) {
+ final serverByteBuffer bb = new serverByteBuffer();
if (includeBraces) bb.append('{');
for (int i = 0; i < row.length; i++) {
bb.append((longname) ? row[i].description : row[i].nickname);
@@ -603,8 +603,8 @@ public final class kelondroRow {
}
public final class EntryIndex extends Entry {
- private int index;
- public EntryIndex(byte[] row, int i) {
+ private final int index;
+ public EntryIndex(final byte[] row, final int i) {
super(row, false);
this.index = i;
}
@@ -613,21 +613,21 @@ public final class kelondroRow {
}
}
- public final static void long2bytes(long x, byte[] b, int offset, int length) {
+ public final static void long2bytes(long x, final byte[] b, final int offset, final int length) {
for (int i = length - 1; i >= 0; i--) {
b[offset + i] = (byte) (x & 0XFF);
x >>= 8;
}
}
- public final static long bytes2long(byte[] b, int offset, int length) {
+ public final static long bytes2long(final byte[] b, final int offset, final int length) {
if (b == null) return 0;
long x = 0;
for (int i = 0; i < length; i++) x = (x << 8) | (0xff & b[offset + i]);
return x;
}
- public final boolean subsumes(kelondroRow otherRow) {
+ public final boolean subsumes(final kelondroRow otherRow) {
// returns true, if this row has at least all columns as the other row
// and possibly some more
if (this.objectsize < otherRow.objectsize) return false;
@@ -640,7 +640,7 @@ public final class kelondroRow {
return true;
}
- public final boolean equals(kelondroRow otherRow) {
+ public final boolean equals(final kelondroRow otherRow) {
if (this.objectsize != otherRow.objectsize) return false;
if (this.columns() != otherRow.columns()) return false;
for (int i = 0; i < otherRow.row.length; i++) {
diff --git a/source/de/anomic/kelondro/kelondroRowCollection.java b/source/de/anomic/kelondro/kelondroRowCollection.java
index cdb446e16..cc446c70e 100644
--- a/source/de/anomic/kelondro/kelondroRowCollection.java
+++ b/source/de/anomic/kelondro/kelondroRowCollection.java
@@ -78,7 +78,7 @@ public class kelondroRowCollection {
private static final int exp_order_bound = 5;
private static final int exp_collection = 6;
- public kelondroRowCollection(kelondroRowCollection rc) {
+ public kelondroRowCollection(final kelondroRowCollection rc) {
this.rowdef = rc.rowdef;
this.chunkcache = rc.chunkcache;
this.chunkcount = rc.chunkcount;
@@ -87,7 +87,7 @@ public class kelondroRowCollection {
this.lastTimeWrote = rc.lastTimeWrote;
}
- public kelondroRowCollection(kelondroRow rowdef, int objectCount) {
+ public kelondroRowCollection(final kelondroRow rowdef, final int objectCount) {
this.rowdef = rowdef;
this.chunkcache = new byte[objectCount * rowdef.objectsize];
this.chunkcount = 0;
@@ -96,7 +96,7 @@ public class kelondroRowCollection {
this.lastTimeWrote = System.currentTimeMillis();
}
- public kelondroRowCollection(kelondroRow rowdef, int objectCount, byte[] cache, int sortBound) {
+ public kelondroRowCollection(final kelondroRow rowdef, final int objectCount, final byte[] cache, final int sortBound) {
this.rowdef = rowdef;
this.chunkcache = cache;
this.chunkcount = objectCount;
@@ -105,10 +105,10 @@ public class kelondroRowCollection {
this.lastTimeWrote = System.currentTimeMillis();
}
- public kelondroRowCollection(kelondroRow rowdef, kelondroRow.Entry exportedCollectionRowEnvironment, int columnInEnvironment) {
+ public kelondroRowCollection(final kelondroRow rowdef, final kelondroRow.Entry exportedCollectionRowEnvironment, final int columnInEnvironment) {
this.rowdef = rowdef;
- int chunkcachelength = exportedCollectionRowEnvironment.cellwidth(columnInEnvironment) - exportOverheadSize;
- kelondroRow.Entry exportedCollection = exportRow(chunkcachelength).newEntry(exportedCollectionRowEnvironment, columnInEnvironment);
+ final int chunkcachelength = exportedCollectionRowEnvironment.cellwidth(columnInEnvironment) - exportOverheadSize;
+ final kelondroRow.Entry exportedCollection = exportRow(chunkcachelength).newEntry(exportedCollectionRowEnvironment, columnInEnvironment);
this.chunkcount = (int) exportedCollection.getColLong(exp_chunkcount);
//assert (this.chunkcount <= chunkcachelength / rowdef.objectsize) : "chunkcount = " + this.chunkcount + ", chunkcachelength = " + chunkcachelength + ", rowdef.objectsize = " + rowdef.objectsize;
if ((this.chunkcount > chunkcachelength / rowdef.objectsize)) {
@@ -117,7 +117,7 @@ public class kelondroRowCollection {
}
this.lastTimeRead = (exportedCollection.getColLong(exp_last_read) + 10957) * day;
this.lastTimeWrote = (exportedCollection.getColLong(exp_last_wrote) + 10957) * day;
- String sortOrderKey = exportedCollection.getColString(exp_order_type, null);
+ final String sortOrderKey = exportedCollection.getColString(exp_order_type, null);
kelondroByteOrder oldOrder = null;
if ((sortOrderKey == null) || (sortOrderKey.equals("__"))) {
oldOrder = null;
@@ -146,19 +146,19 @@ public class kelondroRowCollection {
private static final kelondroRow exportMeasureRow = exportRow(0 /* no relevance */);
- protected static final int sizeOfExportedCollectionRows(kelondroRow.Entry exportedCollectionRowEnvironment, int columnInEnvironment) {
- kelondroRow.Entry exportedCollectionEntry = exportMeasureRow.newEntry(exportedCollectionRowEnvironment, columnInEnvironment);
- int chunkcount = (int) exportedCollectionEntry.getColLong(exp_chunkcount);
+ protected static final int sizeOfExportedCollectionRows(final kelondroRow.Entry exportedCollectionRowEnvironment, final int columnInEnvironment) {
+ final kelondroRow.Entry exportedCollectionEntry = exportMeasureRow.newEntry(exportedCollectionRowEnvironment, columnInEnvironment);
+ final int chunkcount = (int) exportedCollectionEntry.getColLong(exp_chunkcount);
return chunkcount;
}
private static final long day = 1000 * 60 * 60 * 24;
- public static int daysSince2000(long time) {
+ public static int daysSince2000(final long time) {
return (int) (time / day) - 10957;
}
- private static kelondroRow exportRow(int chunkcachelength) {
+ private static kelondroRow exportRow(final int chunkcachelength) {
// find out the size of this collection
return new kelondroRow(
"int size-4 {b256}," +
@@ -178,8 +178,8 @@ public class kelondroRowCollection {
// returns null if the collection is empty
trim(false);
assert this.size() * this.rowdef.objectsize == this.chunkcache.length;
- kelondroRow row = exportRow(chunkcache.length);
- kelondroRow.Entry entry = row.newEntry();
+ final kelondroRow row = exportRow(chunkcache.length);
+ final kelondroRow.Entry entry = row.newEntry();
assert (sortBound <= chunkcount) : "sortBound = " + sortBound + ", chunkcount = " + chunkcount;
assert (this.chunkcount <= chunkcache.length / rowdef.objectsize) : "chunkcount = " + this.chunkcount + ", chunkcache.length = " + chunkcache.length + ", rowdef.objectsize = " + rowdef.objectsize;
entry.setCol(exp_chunkcount, this.chunkcount);
@@ -192,23 +192,23 @@ public class kelondroRowCollection {
return entry.bytes();
}
- public static kelondroRowCollection importCollection(InputStream is, kelondroRow rowdef) throws IOException {
- byte[] byte2 = new byte[2];
- byte[] byte4 = new byte[4];
- is.read(byte4); int size = (int) kelondroNaturalOrder.decodeLong(byte4);
+ public static kelondroRowCollection importCollection(final InputStream is, final kelondroRow rowdef) throws IOException {
+ final byte[] byte2 = new byte[2];
+ final byte[] byte4 = new byte[4];
+ is.read(byte4); final int size = (int) kelondroNaturalOrder.decodeLong(byte4);
is.read(byte2); //short lastread = (short) kelondroNaturalOrder.decodeLong(byte2);
is.read(byte2); //short lastwrote = (short) kelondroNaturalOrder.decodeLong(byte2);
is.read(byte2); //String orderkey = new String(byte2);
- is.read(byte2); short ordercol = (short) kelondroNaturalOrder.decodeLong(byte2);
- is.read(byte2); short orderbound = (short) kelondroNaturalOrder.decodeLong(byte2);
+ is.read(byte2); final short ordercol = (short) kelondroNaturalOrder.decodeLong(byte2);
+ is.read(byte2); final short orderbound = (short) kelondroNaturalOrder.decodeLong(byte2);
assert rowdef.primaryKeyIndex == ordercol;
- byte[] chunkcache = new byte[size * rowdef.objectsize];
- int c = is.read(chunkcache);
+ final byte[] chunkcache = new byte[size * rowdef.objectsize];
+ final int c = is.read(chunkcache);
assert c == chunkcache.length;
return new kelondroRowCollection(rowdef, size, chunkcache, orderbound);
}
- public void saveCollection(File file) throws IOException {
+ public void saveCollection(final File file) throws IOException {
serverFileUtils.copy(exportCollection(), file);
}
@@ -216,8 +216,8 @@ public class kelondroRowCollection {
return this.rowdef;
}
- private final void ensureSize(int elements) {
- int needed = elements * rowdef.objectsize;
+ private final void ensureSize(final int elements) {
+ final int needed = elements * rowdef.objectsize;
if (chunkcache.length >= needed) return;
byte[] newChunkcache = new byte[(int) (needed * growfactor)]; // increase space
System.arraycopy(chunkcache, 0, newChunkcache, 0, chunkcache.length);
@@ -229,7 +229,7 @@ public class kelondroRowCollection {
return (long) ((((long) (chunkcount + 1)) * ((long) rowdef.objectsize)) * growfactor);
}
- public synchronized void trim(boolean plusGrowFactor) {
+ public synchronized void trim(final boolean plusGrowFactor) {
if (chunkcache.length == 0) return;
int needed = chunkcount * rowdef.objectsize;
if (plusGrowFactor) needed = (int) (needed * growfactor);
@@ -255,7 +255,7 @@ public class kelondroRowCollection {
return lastTimeWrote;
}
- public synchronized final byte[] getKey(int index) {
+ public synchronized final byte[] getKey(final int index) {
assert (index >= 0) : "get: access with index " + index + " is below zero";
assert (index < chunkcount) : "get: access with index " + index + " is above chunkcount " + chunkcount + "; sortBound = " + sortBound;
assert (index * rowdef.objectsize < chunkcache.length);
@@ -263,19 +263,19 @@ public class kelondroRowCollection {
if (index >= chunkcount) return null;
if ((index + 1) * rowdef.objectsize > chunkcache.length) return null; // the whole chunk does not fit into the chunkcache
this.lastTimeRead = System.currentTimeMillis();
- byte[] b = new byte[this.rowdef.width(0)];
+ final byte[] b = new byte[this.rowdef.width(0)];
System.arraycopy(chunkcache, index * rowdef.objectsize, b, 0, b.length);
return b;
}
- public final kelondroRow.Entry get(int index, boolean clone) {
+ public final kelondroRow.Entry get(final int index, final boolean clone) {
assert (index >= 0) : "get: access with index " + index + " is below zero";
assert (index < chunkcount) : "get: access with index " + index + " is above chunkcount " + chunkcount + "; sortBound = " + sortBound;
assert (index * rowdef.objectsize < chunkcache.length);
assert sortBound <= chunkcount : "sortBound = " + sortBound + ", chunkcount = " + chunkcount;
if ((chunkcache == null) || (rowdef == null)) return null; // case may appear during shutdown
kelondroRow.Entry entry;
- int addr = index * rowdef.objectsize;
+ final int addr = index * rowdef.objectsize;
synchronized (this) {
if (index >= chunkcount) return null;
if (addr + rowdef.objectsize > chunkcache.length) return null; // the whole chunk does not fit into the chunkcache
@@ -285,7 +285,7 @@ public class kelondroRowCollection {
return entry;
}
- public synchronized final void set(int index, kelondroRow.Entry a) {
+ public synchronized final void set(final int index, final kelondroRow.Entry a) {
assert (index >= 0) : "set: access with index " + index + " is below zero";
ensureSize(index + 1);
a.writeToArray(chunkcache, index * rowdef.objectsize);
@@ -293,7 +293,7 @@ public class kelondroRowCollection {
this.lastTimeWrote = System.currentTimeMillis();
}
- public final void insertUnique(int index, kelondroRow.Entry a) {
+ public final void insertUnique(final int index, final kelondroRow.Entry a) {
assert (a != null);
if (index < chunkcount) {
@@ -306,14 +306,14 @@ public class kelondroRowCollection {
set(index, a);
}
- public synchronized boolean addUnique(kelondroRow.Entry row) {
- byte[] r = row.bytes();
+ public synchronized boolean addUnique(final kelondroRow.Entry row) {
+ final byte[] r = row.bytes();
return addUnique(r, 0, r.length);
}
- public synchronized int addUniqueMultiple(List<kelondroRow.Entry> rows) {
+ public synchronized int addUniqueMultiple(final List<kelondroRow.Entry> rows) {
assert this.sortBound == 0 : "sortBound = " + this.sortBound + ", chunkcount = " + this.chunkcount;
- Iterator<kelondroRow.Entry> i = rows.iterator();
+ final Iterator<kelondroRow.Entry> i = rows.iterator();
int c = 0;
while (i.hasNext()) {
if (addUnique(i.next())) c++;
@@ -321,11 +321,11 @@ public class kelondroRowCollection {
return c;
}
- public synchronized void add(byte[] a) {
+ public synchronized void add(final byte[] a) {
addUnique(a, 0, a.length);
}
- private final boolean addUnique(byte[] a, int astart, int alength) {
+ private final boolean addUnique(final byte[] a, final int astart, final int alength) {
assert (a != null);
assert (astart >= 0) && (astart < a.length) : " astart = " + a;
assert (!(serverLog.allZero(a, astart, alength))) : "a = " + serverLog.arrayList(a, astart, alength);
@@ -338,7 +338,7 @@ public class kelondroRowCollection {
}
*/
//assert (!(bugappearance(a, astart, alength))) : "a = " + serverLog.arrayList(a, astart, alength);
- int l = Math.min(rowdef.objectsize, Math.min(alength, a.length - astart));
+ final int l = Math.min(rowdef.objectsize, Math.min(alength, a.length - astart));
ensureSize(chunkcount + 1);
System.arraycopy(a, astart, chunkcache, rowdef.objectsize * chunkcount, l);
chunkcount++;
@@ -346,7 +346,7 @@ public class kelondroRowCollection {
return true;
}
- public synchronized final void addAllUnique(kelondroRowCollection c) {
+ public synchronized final void addAllUnique(final kelondroRowCollection c) {
if (c == null) return;
assert(rowdef.objectsize == c.rowdef.objectsize);
ensureSize(chunkcount + c.size());
@@ -364,14 +364,14 @@ public class kelondroRowCollection {
* @param p element at this position will be removed
* @param keepOrder keep the order of remaining entries
*/
- protected synchronized final void removeRow(int p, boolean keepOrder) {
+ protected synchronized final void removeRow(final int p, final boolean keepOrder) {
assert p >= 0 : "p = " + p;
assert p < chunkcount : "p = " + p + ", chunkcount = " + chunkcount;
assert chunkcount > 0 : "chunkcount = " + chunkcount;
assert sortBound <= chunkcount : "sortBound = " + sortBound + ", chunkcount = " + chunkcount;
if (keepOrder && (p < sortBound)) {
// remove by shift (quite expensive for big collections)
- int addr = p * this.rowdef.objectsize;
+ final int addr = p * this.rowdef.objectsize;
System.arraycopy(
chunkcache, addr + this.rowdef.objectsize,
chunkcache, addr,
@@ -396,7 +396,7 @@ public class kelondroRowCollection {
public synchronized kelondroRow.Entry removeOne() {
// removes the last entry from the collection
if (chunkcount == 0) return null;
- kelondroRow.Entry r = get(chunkcount - 1, true);
+ final kelondroRow.Entry r = get(chunkcount - 1, true);
if (chunkcount == sortBound) sortBound--;
chunkcount--;
this.lastTimeWrote = System.currentTimeMillis();
@@ -481,10 +481,10 @@ public class kelondroRowCollection {
}
}
- public synchronized void select(Set<String> keys) {
+ public synchronized void select(final Set<String> keys) {
// removes all entries but the ones given by urlselection
if ((keys == null) || (keys.isEmpty())) return;
- Iterator<kelondroRow.Entry> i = rows();
+ final Iterator<kelondroRow.Entry> i = rows();
kelondroRow.Entry row;
while (i.hasNext()) {
row = i.next();
@@ -501,29 +501,29 @@ public class kelondroRowCollection {
assert this.isSorted();
return;
}
- byte[] swapspace = new byte[this.rowdef.objectsize];
- int p = partition(0, this.chunkcount, this.sortBound, swapspace);
+ final byte[] swapspace = new byte[this.rowdef.objectsize];
+ final int p = partition(0, this.chunkcount, this.sortBound, swapspace);
if ((sortingthreadexecutor != null) &&
(!sortingthreadexecutor.isShutdown()) &&
(serverProcessor.useCPU > 1) &&
(this.chunkcount > 8000)) {
// sort this using multi-threading
- Future<Integer> part0 = partitionthreadexecutor.submit(new partitionthread(this, 0, p, 0));
- Future<Integer> part1 = partitionthreadexecutor.submit(new partitionthread(this, p, this.chunkcount, p));
+ final Future<Integer> part0 = partitionthreadexecutor.submit(new partitionthread(this, 0, p, 0));
+ final Future<Integer> part1 = partitionthreadexecutor.submit(new partitionthread(this, p, this.chunkcount, p));
try {
- int p0 = part0.get().intValue();
- Future<Object> sort0 = sortingthreadexecutor.submit(new qsortthread(this, 0, p0, 0));
- Future<Object> sort1 = sortingthreadexecutor.submit(new qsortthread(this, p0, p, p0));
- int p1 = part1.get().intValue();
- Future<Object> sort2 = sortingthreadexecutor.submit(new qsortthread(this, p, p1, p));
- Future<Object> sort3 = sortingthreadexecutor.submit(new qsortthread(this, p1, this.chunkcount, p1));
+ final int p0 = part0.get().intValue();
+ final Future<Object> sort0 = sortingthreadexecutor.submit(new qsortthread(this, 0, p0, 0));
+ final Future<Object> sort1 = sortingthreadexecutor.submit(new qsortthread(this, p0, p, p0));
+ final int p1 = part1.get().intValue();
+ final Future<Object> sort2 = sortingthreadexecutor.submit(new qsortthread(this, p, p1, p));
+ final Future<Object> sort3 = sortingthreadexecutor.submit(new qsortthread(this, p1, this.chunkcount, p1));
sort0.get();
sort1.get();
sort2.get();
sort3.get();
- } catch (InterruptedException e) {
+ } catch (final InterruptedException e) {
e.printStackTrace();
- } catch (ExecutionException e) {
+ } catch (final ExecutionException e) {
e.printStackTrace();
}
} else {
@@ -543,22 +543,22 @@ public class kelondroRowCollection {
assert this.isSorted();
return;
}
- byte[] swapspace = new byte[this.rowdef.objectsize];
- int p = partition(0, this.chunkcount, this.sortBound, swapspace);
+ final byte[] swapspace = new byte[this.rowdef.objectsize];
+ final int p = partition(0, this.chunkcount, this.sortBound, swapspace);
if ((sortingthreadexecutor != null) &&
(!sortingthreadexecutor.isShutdown()) &&
(serverProcessor.useCPU > 1) &&
(this.chunkcount > 4000)) {
// sort this using multi-threading
- Future<Object> part = sortingthreadexecutor.submit(new qsortthread(this, 0, p, 0));
+ final Future<Object> part = sortingthreadexecutor.submit(new qsortthread(this, 0, p, 0));
//CompletionService<Object> sortingthreadcompletion = new ExecutorCompletionService<Object>(sortingthreadexecutor);
//Future<Object> part = sortingthreadcompletion.submit(new qsortthread(this, 0, p, 0));
qsort(p + 1, this.chunkcount, 0, swapspace);
try {
part.get();
- } catch (InterruptedException e) {
+ } catch (final InterruptedException e) {
e.printStackTrace();
- } catch (ExecutionException e) {
+ } catch (final ExecutionException e) {
e.printStackTrace();
}
} else {
@@ -573,7 +573,7 @@ public class kelondroRowCollection {
kelondroRowCollection rc;
int L, R, S;
- public qsortthread(kelondroRowCollection rc, int L, int R, int S) {
+ public qsortthread(final kelondroRowCollection rc, final int L, final int R, final int S) {
this.rc = rc;
this.L = L;
this.R = R;
@@ -586,13 +586,13 @@ public class kelondroRowCollection {
}
}
- final void qsort(int L, int R, int S, byte[] swapspace) {
+ final void qsort(final int L, final int R, final int S, final byte[] swapspace) {
if (R - L < isortlimit) {
isort(L, R, swapspace);
return;
}
assert R > L: "L = " + L + ", R = " + R + ", S = " + S;
- int p = partition(L, R, S, swapspace);
+ final int p = partition(L, R, S, swapspace);
assert p >= L: "L = " + L + ", R = " + R + ", S = " + S + ", p = " + p;
assert p < R: "L = " + L + ", R = " + R + ", S = " + S + ", p = " + p;
qsort(L, p, 0, swapspace);
@@ -603,7 +603,7 @@ public class kelondroRowCollection {
kelondroRowCollection rc;
int L, R, S;
- public partitionthread(kelondroRowCollection rc, int L, int R, int S) {
+ public partitionthread(final kelondroRowCollection rc, final int L, final int R, final int S) {
this.rc = rc;
this.L = L;
this.R = R;
@@ -615,7 +615,7 @@ public class kelondroRowCollection {
}
}
- final int partition(int L, int R, int S, byte[] swapspace) {
+ final int partition(final int L, final int R, int S, final byte[] swapspace) {
// L is the first element in the sequence
// R is the right bound of the sequence, and outside of the sequence
// S is the bound of the sorted elements in the sequence
@@ -684,13 +684,13 @@ public class kelondroRowCollection {
return p;
}
- private final int pivot(int L, int R, int S, byte[] swapspace) {
+ private final int pivot(final int L, final int R, final int S, final byte[] swapspace) {
if ((S == 0) || (S < L)) {
// the collection has no ordering
// or
// the collection has an ordering, but this is not relevant for this pivot
// because the ordered zone is outside of ordering zone
- int m = picMiddle(new int[]{L, (3 * L + R - 1) / 4, (L + R - 1) / 2, (L + 3 * R - 3) / 4, R - 1}, 5);
+ final int m = picMiddle(new int[]{L, (3 * L + R - 1) / 4, (L + R - 1) / 2, (L + 3 * R - 3) / 4, R - 1}, 5);
assert L <= m;
assert m < R;
return m;
@@ -698,7 +698,7 @@ public class kelondroRowCollection {
if (S < R) {
// the collection has an ordering
// and part of the ordered zone is inside the to-be-ordered zone
- int m = picMiddle(new int[]{L, L + (S - L) / 3, (L + R - 1) / 2, S, R - 1}, 5);
+ final int m = picMiddle(new int[]{L, L + (S - L) / 3, (L + R - 1) / 2, S, R - 1}, 5);
assert L <= m;
assert m < R;
return m;
@@ -710,10 +710,10 @@ public class kelondroRowCollection {
return (L + R - 1) / 2;
}
- private final int picMiddle(int[] list, int len) {
+ private final int picMiddle(final int[] list, int len) {
assert len % 2 == 1;
assert len <= list.length;
- int cut = list.length / 2;
+ final int cut = list.length / 2;
for (int i = 0; i < cut; i++) {remove(list, len, min(list, len)); len--;}
for (int i = 0; i < cut; i++) {remove(list, len, max(list, len)); len--;}
// the remaining element must be the middle element
@@ -721,12 +721,12 @@ public class kelondroRowCollection {
return list[0];
}
- private final void remove(int[] list, int len, int idx) {
+ private final void remove(final int[] list, final int len, final int idx) {
if (idx == len - 1) return;
list[idx] = list[len - 1]; // shift last element to front
}
- private final int min(int[] list, int len) {
+ private final int min(final int[] list, int len) {
assert len > 0;
int f = 0;
while (len-- > 0) {
@@ -735,7 +735,7 @@ public class kelondroRowCollection {
return f;
}
- private final int max(int[] list, int len) {
+ private final int max(final int[] list, int len) {
assert len > 0;
int f = 0;
while (len-- > 0) {
@@ -744,13 +744,13 @@ public class kelondroRowCollection {
return f;
}
- private final void isort(int L, int R, byte[] swapspace) {
+ private final void isort(final int L, final int R, final byte[] swapspace) {
for (int i = L + 1; i < R; i++)
for (int j = i; j > L && compare(j - 1, j) > 0; j--)
swap(j, j - 1, 0, swapspace);
}
- private final int swap(int i, int j, int p, byte[] swapspace) {
+ private final int swap(final int i, final int j, final int p, final byte[] swapspace) {
if (i == j) return p;
System.arraycopy(chunkcache, this.rowdef.objectsize * i, swapspace, 0, this.rowdef.objectsize);
System.arraycopy(chunkcache, this.rowdef.objectsize * j, chunkcache, this.rowdef.objectsize * i, this.rowdef.objectsize);
@@ -767,7 +767,7 @@ public class kelondroRowCollection {
// by the large number of memory movements.
if (chunkcount < 2) return;
int i = chunkcount - 2;
- long t = System.currentTimeMillis(); // for time-out
+ final long t = System.currentTimeMillis(); // for time-out
int d = 0;
boolean u = true;
try {
@@ -782,7 +782,7 @@ public class kelondroRowCollection {
throw new RuntimeException("uniq() time-out at " + i + " (backwards) from " + chunkcount + " elements after " + (System.currentTimeMillis() - t) + " milliseconds; " + d + " deletions so far");
}
}
- } catch (RuntimeException e) {
+ } catch (final RuntimeException e) {
serverLog.logWarning("kelondroRowCollection", e.getMessage(), e);
} finally {
if (!u) this.sort();
@@ -795,7 +795,7 @@ public class kelondroRowCollection {
// in contrast to uniq() this removes also the remaining, non-double entry that had a double-occurrence to the others
// all removed chunks are returned in an array
this.sort();
- ArrayList<kelondroRowCollection> report = new ArrayList<kelondroRowCollection>();
+ final ArrayList<kelondroRowCollection> report = new ArrayList<kelondroRowCollection>();
if (chunkcount < 2) return report;
int i = chunkcount - 2;
int d = 0;
@@ -820,7 +820,7 @@ public class kelondroRowCollection {
}
i--;
}
- } catch (RuntimeException e) {
+ } catch (final RuntimeException e) {
serverLog.logWarning("kelondroRowCollection", e.getMessage(), e);
} finally {
if (!u) this.sort();
@@ -843,24 +843,24 @@ public class kelondroRowCollection {
}
public synchronized String toString() {
- StringBuffer s = new StringBuffer();
- Iterator<kelondroRow.Entry> i = rows();
+ final StringBuffer s = new StringBuffer();
+ final Iterator<kelondroRow.Entry> i = rows();
if (i.hasNext()) s.append(i.next().toString());
while (i.hasNext()) s.append(", " + (i.next()).toString());
return new String(s);
}
- private final int compare(int i, int j) {
+ private final int compare(final int i, final int j) {
assert (chunkcount * this.rowdef.objectsize <= chunkcache.length) : "chunkcount = " + chunkcount + ", objsize = " + this.rowdef.objectsize + ", chunkcache.length = " + chunkcache.length;
assert (i >= 0) && (i < chunkcount) : "i = " + i + ", chunkcount = " + chunkcount;
assert (j >= 0) && (j < chunkcount) : "j = " + j + ", chunkcount = " + chunkcount;
assert (this.rowdef.objectOrder != null);
if (i == j) return 0;
assert (this.rowdef.primaryKeyIndex == 0) : "this.sortColumn = " + this.rowdef.primaryKeyIndex;
- int colstart = (this.rowdef.primaryKeyIndex <= 0) ? 0 : this.rowdef.colstart[this.rowdef.primaryKeyIndex];
+ final int colstart = (this.rowdef.primaryKeyIndex <= 0) ? 0 : this.rowdef.colstart[this.rowdef.primaryKeyIndex];
//assert (!bugappearance(chunkcache, i * this.rowdef.objectsize + colstart, this.rowdef.primaryKeyLength));
//assert (!bugappearance(chunkcache, j * this.rowdef.objectsize + colstart, this.rowdef.primaryKeyLength));
- int c = this.rowdef.objectOrder.compare(
+ final int c = this.rowdef.objectOrder.compare(
chunkcache,
i * this.rowdef.objectsize + colstart,
this.rowdef.primaryKeyLength,
@@ -870,32 +870,32 @@ public class kelondroRowCollection {
return c;
}
- protected final byte[] compilePivot(int i) {
+ protected final byte[] compilePivot(final int i) {
assert (i >= 0) && (i < chunkcount) : "i = " + i + ", chunkcount = " + chunkcount;
assert (this.rowdef.objectOrder != null);
assert (this.rowdef.objectOrder instanceof kelondroBase64Order);
assert (this.rowdef.primaryKeyIndex == 0) : "this.sortColumn = " + this.rowdef.primaryKeyIndex;
- int colstart = (this.rowdef.primaryKeyIndex <= 0) ? 0 : this.rowdef.colstart[this.rowdef.primaryKeyIndex];
+ final int colstart = (this.rowdef.primaryKeyIndex <= 0) ? 0 : this.rowdef.colstart[this.rowdef.primaryKeyIndex];
//assert (!bugappearance(chunkcache, i * this.rowdef.objectsize + colstart, this.rowdef.primaryKeyLength));
return ((kelondroBase64Order) this.rowdef.objectOrder).compilePivot(chunkcache, i * this.rowdef.objectsize + colstart, this.rowdef.primaryKeyLength);
}
- protected final byte[] compilePivot(byte[] a, int astart, int alength) {
+ protected final byte[] compilePivot(final byte[] a, final int astart, final int alength) {
assert (this.rowdef.objectOrder != null);
assert (this.rowdef.objectOrder instanceof kelondroBase64Order);
assert (this.rowdef.primaryKeyIndex == 0) : "this.sortColumn = " + this.rowdef.primaryKeyIndex;
return ((kelondroBase64Order) this.rowdef.objectOrder).compilePivot(a, astart, alength);
}
- protected final int comparePivot(byte[] compiledPivot, int j) {
+ protected final int comparePivot(final byte[] compiledPivot, final int j) {
assert (chunkcount * this.rowdef.objectsize <= chunkcache.length) : "chunkcount = " + chunkcount + ", objsize = " + this.rowdef.objectsize + ", chunkcache.length = " + chunkcache.length;
assert (j >= 0) && (j < chunkcount) : "j = " + j + ", chunkcount = " + chunkcount;
assert (this.rowdef.objectOrder != null);
assert (this.rowdef.objectOrder instanceof kelondroBase64Order);
assert (this.rowdef.primaryKeyIndex == 0) : "this.sortColumn = " + this.rowdef.primaryKeyIndex;
- int colstart = (this.rowdef.primaryKeyIndex <= 0) ? 0 : this.rowdef.colstart[this.rowdef.primaryKeyIndex];
+ final int colstart = (this.rowdef.primaryKeyIndex <= 0) ? 0 : this.rowdef.colstart[this.rowdef.primaryKeyIndex];
//assert (!bugappearance(chunkcache, j * this.rowdef.objectsize + colstart, this.rowdef.primaryKeyLength));
- int c = ((kelondroBase64Order) this.rowdef.objectOrder).comparePivot(
+ final int c = ((kelondroBase64Order) this.rowdef.objectOrder).comparePivot(
compiledPivot,
chunkcache,
j * this.rowdef.objectsize + colstart,
@@ -903,13 +903,13 @@ public class kelondroRowCollection {
return c;
}
- protected synchronized int compare(byte[] a, int astart, int alength, int chunknumber) {
+ protected synchronized int compare(final byte[] a, final int astart, final int alength, final int chunknumber) {
assert (chunknumber < chunkcount);
- int l = Math.min(this.rowdef.primaryKeyLength, Math.min(a.length - astart, alength));
+ final int l = Math.min(this.rowdef.primaryKeyLength, Math.min(a.length - astart, alength));
return rowdef.objectOrder.compare(a, astart, l, chunkcache, chunknumber * this.rowdef.objectsize + ((rowdef.primaryKeyIndex <= 0) ? 0 : this.rowdef.colstart[rowdef.primaryKeyIndex]), this.rowdef.primaryKeyLength);
}
- protected synchronized boolean match(byte[] a, int astart, int alength, int chunknumber) {
+ protected synchronized boolean match(final byte[] a, final int astart, final int alength, final int chunknumber) {
if (chunknumber >= chunkcount) return false;
int i = 0;
int p = chunknumber * this.rowdef.objectsize + ((rowdef.primaryKeyIndex <= 0) ? 0 : this.rowdef.colstart[rowdef.primaryKeyIndex]);
@@ -922,7 +922,7 @@ public class kelondroRowCollection {
chunkcache = null;
}
- private static long d(long a, long b) {
+ private static long d(final long a, final long b) {
if (b == 0) return a; else return a / b;
}
@@ -934,8 +934,8 @@ public class kelondroRowCollection {
kelondroBase64Order.enhancedCoder.encodeLong(random.nextLong(), 4);
}
- public static void test(int testsize) {
- kelondroRow r = new kelondroRow(new kelondroColumn[]{
+ public static void test(final int testsize) {
+ final kelondroRow r = new kelondroRow(new kelondroColumn[]{
new kelondroColumn("hash", kelondroColumn.celltype_string, kelondroColumn.encoder_bytes, yacySeedDB.commonHashLength, "hash")},
kelondroBase64Order.enhancedCoder, 0);
@@ -945,9 +945,9 @@ public class kelondroRowCollection {
a.add("BBBBBBBBBBBB".getBytes());
a.add("BBBBBBBBBBBB".getBytes());
a.add("CCCCCCCCCCCC".getBytes());
- ArrayList<kelondroRowCollection> del = a.removeDoubles();
+ final ArrayList<kelondroRowCollection> del = a.removeDoubles();
System.out.println(del + "rows double");
- Iterator<kelondroRow.Entry> j = a.rows();
+ final Iterator<kelondroRow.Entry> j = a.rows();
while (j.hasNext()) System.out.println(new String(j.next().bytes()));
System.out.println("kelondroRowCollection test with size = " + testsize);
@@ -962,7 +962,7 @@ public class kelondroRowCollection {
long t1 = System.nanoTime();
System.out.println("create a : " + (t1 - t0) + " nanoseconds, " + d(testsize, (t1 - t0)) + " entries/nanoseconds; a.size() = " + a.size());
- kelondroRowCollection c = new kelondroRowCollection(r, testsize);
+ final kelondroRowCollection c = new kelondroRowCollection(r, testsize);
random = new Random(0);
t0 = System.nanoTime();
for (int i = 0; i < testsize; i++) {
@@ -970,59 +970,59 @@ public class kelondroRowCollection {
}
t1 = System.nanoTime();
System.out.println("create c : " + (t1 - t0) + " nanoseconds, " + d(testsize, (t1 - t0)) + " entries/nanoseconds");
- kelondroRowCollection d = new kelondroRowCollection(r, testsize);
+ final kelondroRowCollection d = new kelondroRowCollection(r, testsize);
for (int i = 0; i < testsize; i++) {
d.add(c.get(i, false).getColBytes(0));
}
- long t2 = System.nanoTime();
+ final long t2 = System.nanoTime();
System.out.println("copy c -> d: " + (t2 - t1) + " nanoseconds, " + d(testsize, (t2 - t1)) + " entries/nanoseconds");
serverProcessor.useCPU = 1;
c.sort();
- long t3 = System.nanoTime();
+ final long t3 = System.nanoTime();
System.out.println("sort c (1) : " + (t3 - t2) + " nanoseconds, " + d(testsize, (t3 - t2)) + " entries/nanoseconds");
serverProcessor.useCPU = 2;
d.sort();
- long t4 = System.nanoTime();
+ final long t4 = System.nanoTime();
System.out.println("sort d (2) : " + (t4 - t3) + " nanoseconds, " + d(testsize, (t4 - t3)) + " entries/nanoseconds");
c.uniq();
- long t5 = System.nanoTime();
+ final long t5 = System.nanoTime();
System.out.println("uniq c : " + (t5 - t4) + " nanoseconds, " + d(testsize, (t5 - t4)) + " entries/nanoseconds");
d.uniq();
- long t6 = System.nanoTime();
+ final long t6 = System.nanoTime();
System.out.println("uniq d : " + (t6 - t5) + " nanoseconds, " + d(testsize, (t6 - t5)) + " entries/nanoseconds");
random = new Random(0);
- kelondroRowSet e = new kelondroRowSet(r, testsize);
+ final kelondroRowSet e = new kelondroRowSet(r, testsize);
for (int i = 0; i < testsize; i++) {
e.put(r.newEntry(randomHash().getBytes()));
}
- long t7 = System.nanoTime();
+ final long t7 = System.nanoTime();
System.out.println("create e : " + (t7 - t6) + " nanoseconds, " + d(testsize, (t7 - t6)) + " entries/nanoseconds");
e.sort();
- long t8 = System.nanoTime();
+ final long t8 = System.nanoTime();
System.out.println("sort e (2) : " + (t8 - t7) + " nanoseconds, " + d(testsize, (t8 - t7)) + " entries/nanoseconds");
e.uniq();
- long t9 = System.nanoTime();
+ final long t9 = System.nanoTime();
System.out.println("uniq e : " + (t9 - t8) + " nanoseconds, " + d(testsize, (t9 - t8)) + " entries/nanoseconds");
- boolean cis = c.isSorted();
- long t10 = System.nanoTime();
+ final boolean cis = c.isSorted();
+ final long t10 = System.nanoTime();
System.out.println("c isSorted = " + ((cis) ? "true" : "false") + ": " + (t10 - t9) + " nanoseconds");
- boolean dis = d.isSorted();
- long t11 = System.nanoTime();
+ final boolean dis = d.isSorted();
+ final long t11 = System.nanoTime();
System.out.println("d isSorted = " + ((dis) ? "true" : "false") + ": " + (t11 - t10) + " nanoseconds");
- boolean eis = e.isSorted();
- long t12 = System.nanoTime();
+ final boolean eis = e.isSorted();
+ final long t12 = System.nanoTime();
System.out.println("e isSorted = " + ((eis) ? "true" : "false") + ": " + (t12 - t11) + " nanoseconds");
random = new Random(0);
boolean allfound = true;
for (int i = 0; i < testsize; i++) {
- String rh = randomHash();
+ final String rh = randomHash();
if (e.get(rh.getBytes()) == null) {
allfound = false;
System.out.println("not found hash " + rh + " at attempt " + i);
break;
}
}
- long t13 = System.nanoTime();
+ final long t13 = System.nanoTime();
System.out.println("e allfound = " + ((allfound) ? "true" : "false") + ": " + (t13 - t12) + " nanoseconds");
boolean noghosts = true;
for (int i = 0; i < testsize; i++) {
@@ -1031,14 +1031,14 @@ public class kelondroRowCollection {
break;
}
}
- long t14 = System.nanoTime();
+ final long t14 = System.nanoTime();
System.out.println("e noghosts = " + ((noghosts) ? "true" : "false") + ": " + (t14 - t13) + " nanoseconds");
System.out.println("Result size: c = " + c.size() + ", d = " + d.size() + ", e = " + e.size());
System.out.println();
if (sortingthreadexecutor != null) sortingthreadexecutor.shutdown();
}
- public static void main(String[] args) {
+ public static void main(final String[] args) {
//test(1000);
test(50000);
//test(100000);
diff --git a/source/de/anomic/kelondro/kelondroRowSet.java b/source/de/anomic/kelondro/kelondroRowSet.java
index e3d5b91f7..e4ea4b1b4 100644
--- a/source/de/anomic/kelondro/kelondroRowSet.java
+++ b/source/de/anomic/kelondro/kelondroRowSet.java
@@ -40,30 +40,30 @@ public class kelondroRowSet extends kelondroRowCollection implements kelondroInd
private kelondroProfile profile;
- public kelondroRowSet(kelondroRowSet rs) {
+ public kelondroRowSet(final kelondroRowSet rs) {
super(rs);
this.profile = rs.profile;
}
- public kelondroRowSet(kelondroRow rowdef, int objectCount, byte[] cache, int sortBound) {
+ public kelondroRowSet(final kelondroRow rowdef, final int objectCount, final byte[] cache, final int sortBound) {
super(rowdef, objectCount, cache, sortBound);
assert rowdef.objectOrder != null;
this.profile = new kelondroProfile();
}
- public kelondroRowSet(kelondroRow rowdef, int objectCount) {
+ public kelondroRowSet(final kelondroRow rowdef, final int objectCount) {
super(rowdef, objectCount);
assert rowdef.objectOrder != null;
this.profile = new kelondroProfile();
}
- public kelondroRowSet(kelondroRow rowdef, kelondroRow.Entry exportedCollectionRowEnvironment, int columnInEnvironment) {
+ public kelondroRowSet(final kelondroRow rowdef, final kelondroRow.Entry exportedCollectionRowEnvironment, final int columnInEnvironment) {
super(rowdef, exportedCollectionRowEnvironment, columnInEnvironment);
assert rowdef.objectOrder != null;
this.profile = new kelondroProfile();
}
- public void setOrdering(kelondroByteOrder newOrder, int newColumn) {
+ public void setOrdering(final kelondroByteOrder newOrder, final int newColumn) {
assert newOrder != null;
if ((rowdef.objectOrder == null) ||
(!(rowdef.objectOrder.signature().equals(newOrder.signature()))) ||
@@ -73,29 +73,29 @@ public class kelondroRowSet extends kelondroRowCollection implements kelondroInd
}
}
- public static kelondroRowSet importRowSet(DataInput is, kelondroRow rowdef) throws IOException {
- byte[] byte2 = new byte[2];
- byte[] byte4 = new byte[4];
- is.readFully(byte4); int size = (int) kelondroNaturalOrder.decodeLong(byte4);
+ public static kelondroRowSet importRowSet(final DataInput is, final kelondroRow rowdef) throws IOException {
+ final byte[] byte2 = new byte[2];
+ final byte[] byte4 = new byte[4];
+ is.readFully(byte4); final int size = (int) kelondroNaturalOrder.decodeLong(byte4);
is.readFully(byte2); //short lastread = (short) kelondroNaturalOrder.decodeLong(byte2);
is.readFully(byte2); //short lastwrote = (short) kelondroNaturalOrder.decodeLong(byte2);
is.readFully(byte2); //String orderkey = new String(byte2);
- is.readFully(byte2); short ordercol = (short) kelondroNaturalOrder.decodeLong(byte2);
- is.readFully(byte2); short orderbound = (short) kelondroNaturalOrder.decodeLong(byte2);
+ is.readFully(byte2); final short ordercol = (short) kelondroNaturalOrder.decodeLong(byte2);
+ is.readFully(byte2); final short orderbound = (short) kelondroNaturalOrder.decodeLong(byte2);
assert rowdef.primaryKeyIndex == ordercol;
- byte[] chunkcache = new byte[size * rowdef.objectsize];
+ final byte[] chunkcache = new byte[size * rowdef.objectsize];
is.readFully(chunkcache);
return new kelondroRowSet(rowdef, size, chunkcache, orderbound);
}
- public static int skipNextRowSet(DataInputStream is, kelondroRow rowdef) throws IOException {
- byte[] byte2 = new byte[2];
- byte[] byte4 = new byte[4];
- is.readFully(byte4); int size = (int) kelondroNaturalOrder.decodeLong(byte4);
+ public static int skipNextRowSet(final DataInputStream is, final kelondroRow rowdef) throws IOException {
+ final byte[] byte2 = new byte[2];
+ final byte[] byte4 = new byte[4];
+ is.readFully(byte4); final int size = (int) kelondroNaturalOrder.decodeLong(byte4);
is.readFully(byte2); //short lastread = (short) kelondroNaturalOrder.decodeLong(byte2);
is.readFully(byte2); //short lastwrote = (short) kelondroNaturalOrder.decodeLong(byte2);
is.readFully(byte2); //String orderkey = new String(byte2);
- is.readFully(byte2); short ordercol = (short) kelondroNaturalOrder.decodeLong(byte2);
+ is.readFully(byte2); final short ordercol = (short) kelondroNaturalOrder.decodeLong(byte2);
is.readFully(byte2);
assert rowdef.primaryKeyIndex == ordercol;
int skip = size * rowdef.objectsize;
@@ -108,39 +108,39 @@ public class kelondroRowSet extends kelondroRowCollection implements kelondroInd
this.profile = new kelondroProfile();
}
- public synchronized boolean has(byte[] key) {
- long handle = profile.startRead();
- int index = find(key, 0, key.length);
+ public synchronized boolean has(final byte[] key) {
+ final long handle = profile.startRead();
+ final int index = find(key, 0, key.length);
profile.stopRead(handle);
return index >= 0;
}
- public synchronized kelondroRow.Entry get(byte[] key) {
+ public synchronized kelondroRow.Entry get(final byte[] key) {
return get(key, 0, key.length);
}
- private kelondroRow.Entry get(byte[] key, int astart, int alength) {
- long handle = profile.startRead();
- int index = find(key, astart, alength);
- kelondroRow.Entry entry = (index >= 0) ? get(index, true) : null;
+ private kelondroRow.Entry get(final byte[] key, final int astart, final int alength) {
+ final long handle = profile.startRead();
+ final int index = find(key, astart, alength);
+ final kelondroRow.Entry entry = (index >= 0) ? get(index, true) : null;
profile.stopRead(handle);
return entry;
}
- public synchronized void putMultiple(List<kelondroRow.Entry> rows) {
- Iterator<kelondroRow.Entry> i = rows.iterator();
+ public synchronized void putMultiple(final List<kelondroRow.Entry> rows) {
+ final Iterator<kelondroRow.Entry> i = rows.iterator();
while (i.hasNext()) put(i.next());
}
- public kelondroRow.Entry put(kelondroRow.Entry row, Date entryDate) {
+ public kelondroRow.Entry put(final kelondroRow.Entry row, final Date entryDate) {
return put(row);
}
- public synchronized kelondroRow.Entry put(kelondroRow.Entry entry) {
+ public synchronized kelondroRow.Entry put(final kelondroRow.Entry entry) {
assert (entry != null);
assert (entry.getPrimaryKeyBytes() != null);
//assert (!(serverLog.allZero(entry.getColBytes(super.sortColumn))));
- long handle = profile.startWrite();
+ final long handle = profile.startWrite();
int index = -1;
kelondroRow.Entry oldentry = null;
// when reaching a specific amount of un-sorted entries, re-sort all
@@ -158,11 +158,11 @@ public class kelondroRowSet extends kelondroRowCollection implements kelondroInd
return oldentry;
}
- private synchronized kelondroRow.Entry remove(byte[] a, int start, int length) {
- int index = find(a, start, length);
+ private synchronized kelondroRow.Entry remove(final byte[] a, final int start, final int length) {
+ final int index = find(a, start, length);
if (index < 0) return null;
//System.out.println("remove: chunk found at index position (before remove) " + index + ", inset=" + serverLog.arrayList(super.chunkcache, super.rowdef.objectsize() * index, length + 10) + ", searchkey=" + serverLog.arrayList(a, start, length));
- kelondroRow.Entry entry = super.get(index, true);
+ final kelondroRow.Entry entry = super.get(index, true);
super.removeRow(index, true);
//System.out.println("remove: chunk found at index position (after remove) " + index + ", inset=" + serverLog.arrayList(super.chunkcache, super.rowdef.objectsize() * index, length) + ", searchkey=" + serverLog.arrayList(a, start, length));
int findagainindex = 0;
@@ -171,11 +171,11 @@ public class kelondroRowSet extends kelondroRowCollection implements kelondroInd
return entry;
}
- public kelondroRow.Entry remove(byte[] a) {
+ public kelondroRow.Entry remove(final byte[] a) {
return remove(a, 0, a.length);
}
- private int find(byte[] a, int astart, int alength) {
+ private int find(final byte[] a, final int astart, final int alength) {
// returns the chunknumber; -1 if not found
if (rowdef.objectOrder == null) return iterativeSearch(a, astart, alength, 0, this.chunkcount);
@@ -188,14 +188,14 @@ public class kelondroRowSet extends kelondroRowCollection implements kelondroInd
// first try to find in sorted area
assert this.rowdef.objectOrder.wellformed(a, astart, alength) : "not wellformed: " + new String(a, astart, alength);
final byte[] compiledPivot = compilePivot(a, astart, alength);
- int p = binarySearchCompiledPivot(compiledPivot);
+ final int p = binarySearchCompiledPivot(compiledPivot);
if (p >= 0) return p;
// then find in unsorted area
return iterativeSearchCompiledPivot(compiledPivot, this.sortBound, this.chunkcount);
} else {
// first try to find in sorted area
- int p = binarySearch(a, astart, alength);
+ final int p = binarySearch(a, astart, alength);
if (p >= 0) return p;
// then find in unsorted area
@@ -203,7 +203,7 @@ public class kelondroRowSet extends kelondroRowCollection implements kelondroInd
}
}
- private int iterativeSearch(byte[] key, int astart, int alength, int leftBorder, int rightBound) {
+ private int iterativeSearch(final byte[] key, final int astart, final int alength, final int leftBorder, final int rightBound) {
// returns the chunknumber
if (rowdef.objectOrder == null) {
for (int i = leftBorder; i < rightBound; i++) {
@@ -219,7 +219,7 @@ public class kelondroRowSet extends kelondroRowCollection implements kelondroInd
}
}
- private int iterativeSearchCompiledPivot(byte[] compiledPivot, int leftBorder, int rightBound) {
+ private int iterativeSearchCompiledPivot(final byte[] compiledPivot, final int leftBorder, final int rightBound) {
// returns the chunknumber
assert (rowdef.objectOrder != null);
assert (rowdef.objectOrder instanceof kelondroBase64Order);
@@ -229,7 +229,7 @@ public class kelondroRowSet extends kelondroRowCollection implements kelondroInd
return -1;
}
- private int binarySearch(byte[] key, int astart, int alength) {
+ private int binarySearch(final byte[] key, final int astart, final int alength) {
// returns the exact position of the key if the key exists,
// or -1 if the key does not exist
assert (rowdef.objectOrder != null);
@@ -246,7 +246,7 @@ public class kelondroRowSet extends kelondroRowCollection implements kelondroInd
return -1;
}
- private int binarySearchCompiledPivot(byte[] compiledPivot) {
+ private int binarySearchCompiledPivot(final byte[] compiledPivot) {
// returns the exact position of the key if the key exists,
// or -1 if the key does not exist
assert (rowdef.objectOrder != null);
@@ -264,7 +264,7 @@ public class kelondroRowSet extends kelondroRowCollection implements kelondroInd
return -1;
}
- public int binaryPosition(byte[] key, int astart, int alength) {
+ public int binaryPosition(final byte[] key, final int astart, final int alength) {
// returns the exact position of the key if the key exists,
// or a position of an entry that is greater than the key if the
// key does not exist
@@ -291,17 +291,18 @@ public class kelondroRowSet extends kelondroRowCollection implements kelondroInd
return super.keys();
}
- public synchronized kelondroCloneableIterator<byte[]> keys(boolean up, byte[] firstKey) {
+ public synchronized kelondroCloneableIterator<byte[]> keys(final boolean up, final byte[] firstKey) {
return new keyIterator(up, firstKey);
}
public class keyIterator implements kelondroCloneableIterator<byte[]> {
- private boolean up;
- private byte[] first;
- private int p, bound;
+ private final boolean up;
+ private final byte[] first;
+ private int p;
+ final int bound;
- public keyIterator(boolean up, byte[] firstKey) {
+ public keyIterator(final boolean up, final byte[] firstKey) {
// see that all elements are sorted
sort();
this.up = up;
@@ -315,7 +316,7 @@ public class kelondroRowSet extends kelondroRowCollection implements kelondroInd
}
}
- public keyIterator clone(Object second) {
+ public keyIterator clone(final Object second) {
return new keyIterator(up, (byte[]) second);
}
@@ -330,7 +331,7 @@ public class kelondroRowSet extends kelondroRowCollection implements kelondroInd
}
public byte[] next() {
- byte[] key = getKey(p);
+ final byte[] key = getKey(p);
if (up) p++; else p--;
return key;
}
@@ -346,17 +347,18 @@ public class kelondroRowSet extends kelondroRowCollection implements kelondroInd
return super.rows();
}
- public synchronized kelondroCloneableIterator<kelondroRow.Entry> rows(boolean up, byte[] firstKey) {
+ public synchronized kelondroCloneableIterator<kelondroRow.Entry> rows(final boolean up, final byte[] firstKey) {
return new rowIterator(up, firstKey);
}
public class rowIterator implements kelondroCloneableIterator<kelondroRow.Entry> {
- private boolean up;
- private byte[] first;
- private int p, bound;
+ private final boolean up;
+ private final byte[] first;
+ private int p;
+ final int bound;
- public rowIterator(boolean up, byte[] firstKey) {
+ public rowIterator(final boolean up, final byte[] firstKey) {
// see that all elements are sorted
sort();
this.up = up;
@@ -370,7 +372,7 @@ public class kelondroRowSet extends kelondroRowCollection implements kelondroInd
}
}
- public rowIterator clone(Object second) {
+ public rowIterator clone(final Object second) {
return new rowIterator(up, (byte[]) second);
}
@@ -385,7 +387,7 @@ public class kelondroRowSet extends kelondroRowCollection implements kelondroInd
}
public kelondroRow.Entry next() {
- kelondroRow.Entry entry = get(p, true);
+ final kelondroRow.Entry entry = get(p, true);
if (up) p++; else p--;
return entry;
}
@@ -395,7 +397,7 @@ public class kelondroRowSet extends kelondroRowCollection implements kelondroInd
}
}
- public static void main(String[] args) {
+ public static void main(final String[] args) {
// sort/uniq-test
/*
kelondroRow rowdef = new kelondroRow("Cardinal key-4 {b256}, byte[] payload-1", kelondroNaturalOrder.naturalOrder, 0);
@@ -415,14 +417,14 @@ public class kelondroRowSet extends kelondroRowCollection implements kelondroInd
System.out.println("after uniq, size = " + rs.size());
*/
- String[] test = { "eins", "zwei", "drei", "vier", "fuenf", "sechs", "sieben", "acht", "neun", "zehn" };
- kelondroRowSet d = new kelondroRowSet(new kelondroRow("byte[] key-10, Cardinal x-4 {b256}", kelondroNaturalOrder.naturalOrder, 0), 0);
+ final String[] test = { "eins", "zwei", "drei", "vier", "fuenf", "sechs", "sieben", "acht", "neun", "zehn" };
+ final kelondroRowSet d = new kelondroRowSet(new kelondroRow("byte[] key-10, Cardinal x-4 {b256}", kelondroNaturalOrder.naturalOrder, 0), 0);
d.setOrdering(kelondroNaturalOrder.naturalOrder, 0);
for (int ii = 0; ii < test.length; ii++) d.add(test[ii].getBytes());
for (int ii = 0; ii < test.length; ii++) d.add(test[ii].getBytes());
d.sort();
d.remove("fuenf".getBytes(), 0, 5);
- Iterator<kelondroRow.Entry> ii = d.rows();
+ final Iterator<kelondroRow.Entry> ii = d.rows();
String s;
System.out.print("INPUT-ITERATOR: ");
kelondroRow.Entry entry;
@@ -503,11 +505,11 @@ public class kelondroRowSet extends kelondroRowCollection implements kelondroInd
*/
// remove test
- long start = System.currentTimeMillis();
- kelondroRowSet c = new kelondroRowSet(new kelondroRow("byte[] a-12, byte[] b-12", kelondroBase64Order.enhancedCoder, 0), 0);
+ final long start = System.currentTimeMillis();
+ final kelondroRowSet c = new kelondroRowSet(new kelondroRow("byte[] a-12, byte[] b-12", kelondroBase64Order.enhancedCoder, 0), 0);
byte[] key;
- int testsize = 5000;
- byte[][] delkeys = new byte[testsize / 5][];
+ final int testsize = 5000;
+ final byte[][] delkeys = new byte[testsize / 5][];
Random random = new Random(0);
for (int i = 0; i < testsize; i++) {
key = randomHash(random);
@@ -542,7 +544,7 @@ public class kelondroRowSet extends kelondroRowCollection implements kelondroInd
return (kelondroBase64Order.enhancedCoder.encodeLong(Math.abs(r0), 11).substring(5) +
kelondroBase64Order.enhancedCoder.encodeLong(Math.abs(r1), 11).substring(5)).getBytes();
}
- public static byte[] randomHash(Random r) {
+ public static byte[] randomHash(final Random r) {
return randomHash(r.nextLong(), r.nextLong());
}
diff --git a/source/de/anomic/kelondro/kelondroSQLTable.java b/source/de/anomic/kelondro/kelondroSQLTable.java
index 4ac1506b3..48850bed7 100644
--- a/source/de/anomic/kelondro/kelondroSQLTable.java
+++ b/source/de/anomic/kelondro/kelondroSQLTable.java
@@ -61,14 +61,14 @@ public class kelondroSQLTable implements kelondroIndex {
private Connection theDBConnection = null;
private final kelondroByteOrder order = new kelondroNaturalOrder(true);
- private kelondroRow rowdef;
+ private final kelondroRow rowdef;
- public kelondroSQLTable(String dbType, kelondroRow rowdef) throws Exception {
+ public kelondroSQLTable(final String dbType, final kelondroRow rowdef) throws Exception {
this.rowdef = rowdef;
openDatabaseConnection(dbType);
}
- private void openDatabaseConnection(String dbType) throws Exception{
+ private void openDatabaseConnection(final String dbType) throws Exception{
if (dbType == null) throw new IllegalArgumentException();
@@ -82,12 +82,12 @@ public class kelondroSQLTable implements kelondroIndex {
}
try {
Class.forName(dbDriverStr).newInstance();
- } catch (Exception e) {
+ } catch (final Exception e) {
throw new Exception ("Unable to load the jdbc driver: " + e.getMessage(),e);
}
try {
this.theDBConnection = DriverManager.getConnection (dbConnStr,this.db_usr_str,this.db_pwd_str);
- } catch (Exception e) {
+ } catch (final Exception e) {
throw new Exception ("Unable to establish a database connection: " + e.getMessage(),e);
}
@@ -100,7 +100,7 @@ public class kelondroSQLTable implements kelondroIndex {
public void close() {
if (this.theDBConnection != null) try {
this.theDBConnection.close();
- } catch (SQLException e) {
+ } catch (final SQLException e) {
e.printStackTrace();
}
this.theDBConnection = null;
@@ -109,13 +109,13 @@ public class kelondroSQLTable implements kelondroIndex {
public int size() {
int size = -1;
try {
- String sqlQuery = new String
+ final String sqlQuery = new String
(
"SELECT count(value) from test"
);
- PreparedStatement sqlStatement = this.theDBConnection.prepareStatement(sqlQuery);
- ResultSet result = sqlStatement.executeQuery();
+ final PreparedStatement sqlStatement = this.theDBConnection.prepareStatement(sqlQuery);
+ final ResultSet result = sqlStatement.executeQuery();
while (result.next()) {
size = result.getInt(1);
@@ -125,7 +125,7 @@ public class kelondroSQLTable implements kelondroIndex {
sqlStatement.close();
return size;
- } catch (Exception e) {
+ } catch (final Exception e) {
e.printStackTrace();
return -1;
}
@@ -135,10 +135,10 @@ public class kelondroSQLTable implements kelondroIndex {
return this.rowdef;
}
- public boolean has(byte[] key) {
+ public boolean has(final byte[] key) {
try {
return (get(key) != null);
- } catch (IOException e) {
+ } catch (final IOException e) {
return false;
}
}
@@ -147,18 +147,18 @@ public class kelondroSQLTable implements kelondroIndex {
return new ArrayList<kelondroRowCollection>();
}
- public kelondroRow.Entry get(byte[] key) throws IOException {
+ public kelondroRow.Entry get(final byte[] key) throws IOException {
try {
- String sqlQuery = new String
+ final String sqlQuery = new String
(
"SELECT value from test where hash = ?"
);
- PreparedStatement sqlStatement = this.theDBConnection.prepareStatement(sqlQuery);
+ final PreparedStatement sqlStatement = this.theDBConnection.prepareStatement(sqlQuery);
sqlStatement.setString(1, new String(key));
byte[] value = null;
- ResultSet result = sqlStatement.executeQuery();
+ final ResultSet result = sqlStatement.executeQuery();
while (result.next()) {
value = result.getBytes("value");
}
@@ -167,28 +167,28 @@ public class kelondroSQLTable implements kelondroIndex {
sqlStatement.close();
if (value == null) return null;
- kelondroRow.Entry entry = this.rowdef.newEntry(value);
+ final kelondroRow.Entry entry = this.rowdef.newEntry(value);
return entry;
- } catch (Exception e) {
+ } catch (final Exception e) {
throw new IOException(e.getMessage());
}
}
- public synchronized void putMultiple(List<kelondroRow.Entry> rows) throws IOException {
- Iterator<kelondroRow.Entry> i = rows.iterator();
+ public synchronized void putMultiple(final List<kelondroRow.Entry> rows) throws IOException {
+ final Iterator<kelondroRow.Entry> i = rows.iterator();
while (i.hasNext()) put(i.next());
}
- public kelondroRow.Entry put(kelondroRow.Entry row, Date entryDate) throws IOException {
+ public kelondroRow.Entry put(final kelondroRow.Entry row, final Date entryDate) throws IOException {
return put(row);
}
- public kelondroRow.Entry put(kelondroRow.Entry row) throws IOException {
+ public kelondroRow.Entry put(final kelondroRow.Entry row) throws IOException {
try {
- kelondroRow.Entry oldEntry = remove(row.getColBytes(0));
+ final kelondroRow.Entry oldEntry = remove(row.getColBytes(0));
- String sqlQuery = new String
+ final String sqlQuery = new String
(
"INSERT INTO test (" +
"hash, " +
@@ -197,7 +197,7 @@ public class kelondroSQLTable implements kelondroIndex {
);
- PreparedStatement sqlStatement = this.theDBConnection.prepareStatement(sqlQuery);
+ final PreparedStatement sqlStatement = this.theDBConnection.prepareStatement(sqlQuery);
sqlStatement.setString(1, new String(row.getColString(0, null)));
sqlStatement.setBytes(2, row.bytes());
@@ -206,41 +206,41 @@ public class kelondroSQLTable implements kelondroIndex {
sqlStatement.close();
return oldEntry;
- } catch (Exception e) {
+ } catch (final Exception e) {
throw new IOException(e.getMessage());
}
}
- public synchronized boolean addUnique(kelondroRow.Entry row) throws IOException {
+ public synchronized boolean addUnique(final kelondroRow.Entry row) throws IOException {
throw new UnsupportedOperationException();
}
- public synchronized void addUnique(kelondroRow.Entry row, Date entryDate) {
+ public synchronized void addUnique(final kelondroRow.Entry row, final Date entryDate) {
throw new UnsupportedOperationException();
}
- public synchronized int addUniqueMultiple(List<kelondroRow.Entry> rows) throws IOException {
+ public synchronized int addUniqueMultiple(final List<kelondroRow.Entry> rows) throws IOException {
throw new UnsupportedOperationException();
}
- public kelondroRow.Entry remove(byte[] key) throws IOException {
+ public kelondroRow.Entry remove(final byte[] key) throws IOException {
try {
- kelondroRow.Entry entry = this.get(key);
+ final kelondroRow.Entry entry = this.get(key);
if (entry == null) return entry;
- String sqlQuery = new String
+ final String sqlQuery = new String
(
"DELETE FROM test WHERE hash = ?"
);
- PreparedStatement sqlStatement = this.theDBConnection.prepareStatement(sqlQuery);
+ final PreparedStatement sqlStatement = this.theDBConnection.prepareStatement(sqlQuery);
sqlStatement.setString(1, new String(key));
sqlStatement.execute();
return entry;
- } catch (Exception e) {
+ } catch (final Exception e) {
throw new IOException(e.getMessage());
}
}
@@ -249,12 +249,12 @@ public class kelondroSQLTable implements kelondroIndex {
return null;
}
- public kelondroCloneableIterator<kelondroRow.Entry> rows(boolean up, byte[] startKey) throws IOException {
+ public kelondroCloneableIterator<kelondroRow.Entry> rows(final boolean up, final byte[] startKey) throws IOException {
// Objects are of type kelondroRow.Entry
return null;
}
- public kelondroCloneableIterator<byte[]> keys(boolean up, byte[] startKey) {
+ public kelondroCloneableIterator<byte[]> keys(final boolean up, final byte[] startKey) {
// Objects are of type byte[]
return null;
}
@@ -264,7 +264,7 @@ public class kelondroSQLTable implements kelondroIndex {
return 0;
}
- public int columnSize(int column) {
+ public int columnSize(final int column) {
// TODO Auto-generated method stub
return 0;
}
diff --git a/source/de/anomic/kelondro/kelondroSortStack.java b/source/de/anomic/kelondro/kelondroSortStack.java
index 8cefffe0c..d8beec6bb 100644
--- a/source/de/anomic/kelondro/kelondroSortStack.java
+++ b/source/de/anomic/kelondro/kelondroSortStack.java
@@ -41,7 +41,7 @@ public class kelondroSortStack<E> {
protected HashSet<Integer> instack; // keeps track which element has been on the stack or is now in the offstack
protected int maxsize;
- public kelondroSortStack(int maxsize) {
+ public kelondroSortStack(final int maxsize) {
// the maxsize is the maximum number of entries in the stack
// if this is set to -1, the size is unlimited
this.onstack = new TreeMap<Long, E>();
@@ -53,11 +53,11 @@ public class kelondroSortStack<E> {
return this.onstack.size();
}
- public void push(stackElement se) {
+ public void push(final stackElement se) {
push(se.element, se.weight);
}
- public synchronized void push(E element, Long weight) {
+ public synchronized void push(final E element, Long weight) {
if (exists(element)) return;
// manipulate weight in such a way that it has no conflicts
@@ -79,8 +79,8 @@ public class kelondroSortStack<E> {
public synchronized stackElement top() {
// returns the element that is currently on top of the stack
if (this.onstack.isEmpty()) return null;
- Long w = this.onstack.firstKey();
- E element = this.onstack.get(w);
+ final Long w = this.onstack.firstKey();
+ final E element = this.onstack.get(w);
return new stackElement(element, w);
}
@@ -89,24 +89,24 @@ public class kelondroSortStack<E> {
// it is removed and added to the offstack list
// this is exactly the same as element(offstack.size())
if (this.onstack.isEmpty()) return null;
- Long w = this.onstack.firstKey();
- E element = this.onstack.remove(w);
- stackElement se = new stackElement(element, w);
+ final Long w = this.onstack.firstKey();
+ final E element = this.onstack.remove(w);
+ final stackElement se = new stackElement(element, w);
return se;
}
- public boolean exists(E element) {
+ public boolean exists(final E element) {
// uses the hashCode of the element to find out of the element had been on the list or the stack
return this.instack.contains(new Integer(element.hashCode()));
}
- public boolean exists(int hashcode) {
+ public boolean exists(final int hashcode) {
// uses the hashCode of the element to find out of the element had been on the list or the stack
return this.instack.contains(new Integer(hashcode));
}
- public stackElement get(int hashcode) {
- Iterator<Map.Entry<Long, E>> i = this.onstack.entrySet().iterator();
+ public stackElement get(final int hashcode) {
+ final Iterator<Map.Entry<Long, E>> i = this.onstack.entrySet().iterator();
Map.Entry<Long, E> entry;
while (i.hasNext()) {
entry = i.next();
@@ -115,8 +115,8 @@ public class kelondroSortStack<E> {
return null;
}
- public stackElement remove(int hashcode) {
- Iterator<Map.Entry<Long, E>> i = this.onstack.entrySet().iterator();
+ public stackElement remove(final int hashcode) {
+ final Iterator<Map.Entry<Long, E>> i = this.onstack.entrySet().iterator();
Map.Entry<Long, E> entry;
stackElement se;
while (i.hasNext()) {
@@ -130,7 +130,7 @@ public class kelondroSortStack<E> {
return null;
}
- public boolean bottom(long weight) {
+ public boolean bottom(final long weight) {
// returns true if the element with that weight would be on the bottom of the stack after inserting
return weight > this.onstack.lastKey().longValue();
}
@@ -138,7 +138,7 @@ public class kelondroSortStack<E> {
public class stackElement {
public Long weight;
public E element;
- public stackElement(E element, Long weight) {
+ public stackElement(final E element, final Long weight) {
this.element = element;
this.weight = weight;
}
diff --git a/source/de/anomic/kelondro/kelondroSortStore.java b/source/de/anomic/kelondro/kelondroSortStore.java
index d80461a58..cb06a1cf3 100644
--- a/source/de/anomic/kelondro/kelondroSortStore.java
+++ b/source/de/anomic/kelondro/kelondroSortStore.java
@@ -35,9 +35,9 @@ public class kelondroSortStore<E> extends kelondroSortStack<E> {
// been pulled from the stack with pop are listed. Provides access methods to address
// specific elements in the list.
- private ArrayList<stackElement> offstack; // objects that had been on the stack but had been removed
+ private final ArrayList<stackElement> offstack; // objects that had been on the stack but had been removed
- public kelondroSortStore(int maxsize) {
+ public kelondroSortStore(final int maxsize) {
super(maxsize);
this.offstack = new ArrayList<stackElement>();
}
@@ -50,7 +50,7 @@ public class kelondroSortStore<E> extends kelondroSortStack<E> {
return this.offstack.size();
}
- public synchronized void push(E element, Long weight) {
+ public synchronized void push(final E element, final Long weight) {
super.push(element, weight);
if (this.maxsize <= 0) return;
while ((this.onstack.size() > 0) && (super.onstack.size() + this.offstack.size() > this.maxsize)) {
@@ -62,13 +62,13 @@ public class kelondroSortStore<E> extends kelondroSortStack<E> {
// returns the element that is currently on top of the stack
// it is removed and added to the offstack list
// this is exactly the same as element(offstack.size())
- stackElement se = super.pop();
+ final stackElement se = super.pop();
if (se == null) return null;
this.offstack.add(se);
return se;
}
- public synchronized stackElement element(int position) {
+ public synchronized stackElement element(final int position) {
// returns an element from a specific position. It is either taken from the offstack,
// or removed from the onstack.
// The offstack will grow if elements are not from the offstack and present at the onstack.
@@ -77,42 +77,42 @@ public class kelondroSortStore<E> extends kelondroSortStack<E> {
}
if (position >= size()) return null; // we don't have that element
while (position >= this.offstack.size()) {
- Long w = this.onstack.firstKey();
- E element = this.onstack.remove(w);
- stackElement se = new stackElement(element, w);
+ final Long w = this.onstack.firstKey();
+ final E element = this.onstack.remove(w);
+ final stackElement se = new stackElement(element, w);
this.offstack.add(se);
}
return this.offstack.get(position);
}
- public ArrayList<stackElement> list(int count) {
+ public ArrayList<stackElement> list(final int count) {
// returns the specific amount of entries. If they are not yet present in the offstack, they are shifted there from the onstack
// if count is < 0 then all elements are taken
// the returned list is not cloned from the internal list and shall not be modified in any way (read-only)
if (count < 0) {
// shift all elements
while (this.onstack.size() > 0) {
- Long w = this.onstack.firstKey();
- E element = this.onstack.remove(w);
- stackElement se = new stackElement(element, w);
+ final Long w = this.onstack.firstKey();
+ final E element = this.onstack.remove(w);
+ final stackElement se = new stackElement(element, w);
this.offstack.add(se);
}
return this.offstack;
}
if (size() < count) throw new RuntimeException("list(" + count + ") exceeded avaiable number of elements (" + size() + ")");
while (this.offstack.size() < count) {
- Long w = this.onstack.firstKey();
- E element = this.onstack.remove(w);
- stackElement se = new stackElement(element, w);
+ final Long w = this.onstack.firstKey();
+ final E element = this.onstack.remove(w);
+ final stackElement se = new stackElement(element, w);
this.offstack.add(se);
}
return this.offstack;
}
- public stackElement get(int hashcode) {
+ public stackElement get(final int hashcode) {
stackElement se = super.get(hashcode);
if (se != null) return se;
- Iterator<stackElement> j = this.offstack.iterator();
+ final Iterator<stackElement> j = this.offstack.iterator();
while (j.hasNext()) {
se = j.next();
if (se.element.hashCode() == hashcode) return se;
@@ -120,7 +120,7 @@ public class kelondroSortStore<E> extends kelondroSortStack<E> {
return null;
}
- public stackElement remove(int hashcode) {
+ public stackElement remove(final int hashcode) {
stackElement se = super.remove(hashcode);
if (se != null) return se;
for (int j = 0; j < this.offstack.size(); j++) {
diff --git a/source/de/anomic/kelondro/kelondroSplitTable.java b/source/de/anomic/kelondro/kelondroSplitTable.java
index c56861eb5..bb009697e 100644
--- a/source/de/anomic/kelondro/kelondroSplitTable.java
+++ b/source/de/anomic/kelondro/kelondroSplitTable.java
@@ -66,12 +66,12 @@ public class kelondroSplitTable implements kelondroIndex {
private ExecutorService executor;
private HashMap<String, kelondroIndex> tables; // a map from a date string to a kelondroIndex object
- private kelondroRow rowdef;
- private File path;
- private String tablename;
- private kelondroOrder<kelondroRow.Entry> entryOrder;
+ private final kelondroRow rowdef;
+ private final File path;
+ private final String tablename;
+ private final kelondroOrder<kelondroRow.Entry> entryOrder;
- public kelondroSplitTable(File path, String tablename, kelondroRow rowdef, boolean resetOnFail) {
+ public kelondroSplitTable(final File path, final String tablename, final kelondroRow rowdef, final boolean resetOnFail) {
this.path = path;
this.tablename = tablename;
this.rowdef = rowdef;
@@ -79,7 +79,7 @@ public class kelondroSplitTable implements kelondroIndex {
init(resetOnFail);
}
- public void init(boolean resetOnFail) {
+ public void init(final boolean resetOnFail) {
// init the thread pool for the keeperOf executor service
this.executor = new ThreadPoolExecutor(serverProcessor.useCPU + 1, serverProcessor.useCPU + 1, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new NamePrefixThreadFactory(tablename));
@@ -87,11 +87,11 @@ public class kelondroSplitTable implements kelondroIndex {
// initialized tables map
this.tables = new HashMap<String, kelondroIndex>();
if (!(path.exists())) path.mkdirs();
- String[] tablefile = path.list();
+ final String[] tablefile = path.list();
String date;
// first pass: find tables
- HashMap<String, Long> t = new HashMap<String, Long>();
+ final HashMap<String, Long> t = new HashMap<String, Long>();
long ram, sum = 0;
File f;
for (int i = 0; i < tablefile.length; i++) {
@@ -151,10 +151,10 @@ public class kelondroSplitTable implements kelondroIndex {
public void clear() throws IOException {
this.close();
- String[] l = path.list();
+ final String[] l = path.list();
for (int i = 0; i < l.length; i++) {
if (l[i].startsWith(tablename)) {
- File f = new File(path, l[i]);
+ final File f = new File(path, l[i]);
if (f.isDirectory()) kelondroFlexWidthArray.delete(path, l[i]); else f.delete();
}
}
@@ -166,9 +166,9 @@ public class kelondroSplitTable implements kelondroIndex {
}
private static final Calendar thisCalendar = Calendar.getInstance();
- public static final String dateSuffix(Date date) {
+ public static final String dateSuffix(final Date date) {
int month, year;
- StringBuffer suffix = new StringBuffer(6);
+ final StringBuffer suffix = new StringBuffer(6);
synchronized (thisCalendar) {
thisCalendar.setTime(date);
month = thisCalendar.get(Calendar.MONTH) + 1;
@@ -183,15 +183,15 @@ public class kelondroSplitTable implements kelondroIndex {
}
public int size() {
- Iterator<kelondroIndex> i = tables.values().iterator();
+ final Iterator<kelondroIndex> i = tables.values().iterator();
int s = 0;
while (i.hasNext()) s += i.next().size();
return s;
}
public synchronized kelondroProfile profile() {
- kelondroProfile[] profiles = new kelondroProfile[tables.size()];
- Iterator<kelondroIndex> i = tables.values().iterator();
+ final kelondroProfile[] profiles = new kelondroProfile[tables.size()];
+ final Iterator<kelondroIndex> i = tables.values().iterator();
int c = 0;
while (i.hasNext()) profiles[c++] = (i.next()).profile();
return kelondroProfile.consolidate(profiles);
@@ -209,35 +209,35 @@ public class kelondroSplitTable implements kelondroIndex {
return this.rowdef;
}
- public boolean has(byte[] key) {
+ public boolean has(final byte[] key) {
return keeperOf(key) != null;
}
- public synchronized kelondroRow.Entry get(byte[] key) throws IOException {
- kelondroIndex keeper = keeperOf(key);
+ public synchronized kelondroRow.Entry get(final byte[] key) throws IOException {
+ final kelondroIndex keeper = keeperOf(key);
if (keeper == null) return null;
return keeper.get(key);
}
- public synchronized void putMultiple(List<kelondroRow.Entry> rows) throws IOException {
+ public synchronized void putMultiple(final List<kelondroRow.Entry> rows) throws IOException {
throw new UnsupportedOperationException("not yet implemented");
}
- public synchronized kelondroRow.Entry put(kelondroRow.Entry row) throws IOException {
+ public synchronized kelondroRow.Entry put(final kelondroRow.Entry row) throws IOException {
return put(row, null); // entry for current date
}
- public synchronized kelondroRow.Entry put(kelondroRow.Entry row, Date entryDate) throws IOException {
+ public synchronized kelondroRow.Entry put(final kelondroRow.Entry row, Date entryDate) throws IOException {
assert row.objectsize() <= this.rowdef.objectsize;
- kelondroIndex keeper = keeperOf(row.getColBytes(0));
+ final kelondroIndex keeper = keeperOf(row.getColBytes(0));
if (keeper != null) return keeper.put(row);
if ((entryDate == null) || (entryDate.after(new Date()))) entryDate = new Date(); // fix date
- String suffix = dateSuffix(entryDate);
+ final String suffix = dateSuffix(entryDate);
if (suffix == null) return null;
kelondroIndex table = tables.get(suffix);
if (table == null) {
// open table
- File f = new File(path, tablename + "." + suffix);
+ final File f = new File(path, tablename + "." + suffix);
if (f.exists()) {
if (f.isDirectory()) {
// open a flex table
@@ -269,8 +269,8 @@ public class kelondroSplitTable implements kelondroIndex {
//long start = System.currentTimeMillis();
// start a concurrent query to database tables
- CompletionService<kelondroIndex> cs = new ExecutorCompletionService<kelondroIndex>(executor);
- int s = tables.size();
+ final CompletionService<kelondroIndex> cs = new ExecutorCompletionService<kelondroIndex>(executor);
+ final int s = tables.size();
int rejected = 0;
for (final kelondroIndex table : tables.values()) {
try {
@@ -279,7 +279,7 @@ public class kelondroSplitTable implements kelondroIndex {
if (table.has(key)) return table; else return dummyIndex;
}
});
- } catch (RejectedExecutionException e) {
+ } catch (final RejectedExecutionException e) {
// the executor is either shutting down or the blocking queue is full
// execute the search direct here without concurrency
if (table.has(key)) return table;
@@ -290,8 +290,8 @@ public class kelondroSplitTable implements kelondroIndex {
// read the result
try {
for (int i = 0, n = s - rejected; i < n; i++) {
- Future<kelondroIndex> f = cs.take();
- kelondroIndex index = f.get();
+ final Future<kelondroIndex> f = cs.take();
+ final kelondroIndex index = f.get();
if (index != dummyIndex) {
//System.out.println("*DEBUG SplitTable success.time = " + (System.currentTimeMillis() - start) + " ms");
return index;
@@ -299,23 +299,23 @@ public class kelondroSplitTable implements kelondroIndex {
}
//System.out.println("*DEBUG SplitTable fail.time = " + (System.currentTimeMillis() - start) + " ms");
return null;
- } catch (InterruptedException e) {
+ } catch (final InterruptedException e) {
Thread.currentThread().interrupt();
- } catch (ExecutionException e) {
+ } catch (final ExecutionException e) {
throw new RuntimeException(e.getCause());
}
//System.out.println("*DEBUG SplitTable fail.time = " + (System.currentTimeMillis() - start) + " ms");
return null;
}
- public synchronized boolean addUnique(kelondroRow.Entry row) throws IOException {
+ public synchronized boolean addUnique(final kelondroRow.Entry row) throws IOException {
return addUnique(row, null);
}
- public synchronized boolean addUnique(kelondroRow.Entry row, Date entryDate) throws IOException {
+ public synchronized boolean addUnique(final kelondroRow.Entry row, Date entryDate) throws IOException {
assert row.objectsize() <= this.rowdef.objectsize;
if ((entryDate == null) || (entryDate.after(new Date()))) entryDate = new Date(); // fix date
- String suffix = dateSuffix(entryDate);
+ final String suffix = dateSuffix(entryDate);
if (suffix == null) return false;
kelondroIndex table = tables.get(suffix);
if (table == null) {
@@ -332,8 +332,8 @@ public class kelondroSplitTable implements kelondroIndex {
return table.addUnique(row);
}
- public synchronized int addUniqueMultiple(List<kelondroRow.Entry> rows) throws IOException {
- Iterator<kelondroRow.Entry> i = rows.iterator();
+ public synchronized int addUniqueMultiple(final List<kelondroRow.Entry> rows) throws IOException {
+ final Iterator<kelondroRow.Entry> i = rows.iterator();
int c = 0;
while (i.hasNext()) {
if (addUnique(i.next())) c++;
@@ -341,28 +341,28 @@ public class kelondroSplitTable implements kelondroIndex {
return c;
}
- public synchronized void addUniqueMultiple(List<kelondroRow.Entry> rows, Date entryDate) throws IOException {
- Iterator<kelondroRow.Entry> i = rows.iterator();
+ public synchronized void addUniqueMultiple(final List<kelondroRow.Entry> rows, final Date entryDate) throws IOException {
+ final Iterator<kelondroRow.Entry> i = rows.iterator();
while (i.hasNext()) addUnique(i.next(), entryDate);
}
public ArrayList<kelondroRowCollection> removeDoubles() throws IOException {
- Iterator<kelondroIndex> i = tables.values().iterator();
- ArrayList<kelondroRowCollection> report = new ArrayList<kelondroRowCollection>();
+ final Iterator<kelondroIndex> i = tables.values().iterator();
+ final ArrayList<kelondroRowCollection> report = new ArrayList<kelondroRowCollection>();
while (i.hasNext()) {
report.addAll(i.next().removeDoubles());
}
return report;
}
- public synchronized kelondroRow.Entry remove(byte[] key) throws IOException {
- kelondroIndex table = keeperOf(key);
+ public synchronized kelondroRow.Entry remove(final byte[] key) throws IOException {
+ final kelondroIndex table = keeperOf(key);
if (table == null) return null;
return table.remove(key);
}
public synchronized kelondroRow.Entry removeOne() throws IOException {
- Iterator<kelondroIndex> i = tables.values().iterator();
+ final Iterator<kelondroIndex> i = tables.values().iterator();
kelondroIndex table, maxtable = null;
int maxcount = -1;
while (i.hasNext()) {
@@ -379,18 +379,18 @@ public class kelondroSplitTable implements kelondroIndex {
}
}
- public synchronized kelondroCloneableIterator<byte[]> keys(boolean up, byte[] firstKey) throws IOException {
- HashSet<kelondroCloneableIterator<byte[]>> set = new HashSet<kelondroCloneableIterator<byte[]>>();
- Iterator<kelondroIndex> i = tables.values().iterator();
+ public synchronized kelondroCloneableIterator<byte[]> keys(final boolean up, final byte[] firstKey) throws IOException {
+ final HashSet<kelondroCloneableIterator<byte[]>> set = new HashSet<kelondroCloneableIterator<byte[]>>();
+ final Iterator<kelondroIndex> i = tables.values().iterator();
while (i.hasNext()) {
set.add(i.next().keys(up, firstKey));
}
return kelondroMergeIterator.cascade(set, rowdef.objectOrder, kelondroMergeIterator.simpleMerge, up);
}
- public synchronized kelondroCloneableIterator<kelondroRow.Entry> rows(boolean up, byte[] firstKey) throws IOException {
- HashSet<kelondroCloneableIterator<kelondroRow.Entry>> set = new HashSet<kelondroCloneableIterator<kelondroRow.Entry>>();
- Iterator<kelondroIndex> i = tables.values().iterator();
+ public synchronized kelondroCloneableIterator<kelondroRow.Entry> rows(final boolean up, final byte[] firstKey) throws IOException {
+ final HashSet<kelondroCloneableIterator<kelondroRow.Entry>> set = new HashSet<kelondroCloneableIterator<kelondroRow.Entry>>();
+ final Iterator<kelondroIndex> i = tables.values().iterator();
while (i.hasNext()) {
set.add(i.next().rows(up, firstKey));
}
@@ -422,17 +422,17 @@ public class kelondroSplitTable implements kelondroIndex {
this.executor.shutdown();
try {
this.executor.awaitTermination(3, TimeUnit.SECONDS);
- } catch (InterruptedException e) {
+ } catch (final InterruptedException e) {
}
this.executor = null;
- Iterator<kelondroIndex> i = tables.values().iterator();
+ final Iterator<kelondroIndex> i = tables.values().iterator();
while (i.hasNext()) {
i.next().close();
}
this.tables = null;
}
- public static void main(String[] args) {
+ public static void main(final String[] args) {
System.out.println(dateSuffix(new Date()));
}
diff --git a/source/de/anomic/kelondro/kelondroStack.java b/source/de/anomic/kelondro/kelondroStack.java
index c1ddbfc93..34875933f 100644
--- a/source/de/anomic/kelondro/kelondroStack.java
+++ b/source/de/anomic/kelondro/kelondroStack.java
@@ -47,7 +47,7 @@ public final class kelondroStack extends kelondroFullRecords {
protected static final int root = 0; // pointer for FHandles-array: pointer to root node
protected static final int toor = 1; // pointer for FHandles-array: pointer to root node
- public kelondroStack(File file, kelondroRow rowdef) throws IOException {
+ public kelondroStack(final File file, final kelondroRow rowdef) throws IOException {
// this creates a new stack
super(file, thisOHBytes, thisOHHandles, rowdef, thisFHandles, rowdef.columns() /* txtProps */, 80 /* txtPropWidth */);
if (super.fileExisted) {
@@ -58,14 +58,14 @@ public final class kelondroStack extends kelondroFullRecords {
}
}
- public static final kelondroStack open(File file, kelondroRow rowdef) {
+ public static final kelondroStack open(final File file, final kelondroRow rowdef) {
try {
return new kelondroStack(file, rowdef);
- } catch (IOException e) {
+ } catch (final IOException e) {
file.delete();
try {
return new kelondroStack(file, rowdef);
- } catch (IOException ee) {
+ } catch (final IOException ee) {
System.out.println("kelondroStack: cannot open or create file " + file.toString());
e.printStackTrace();
ee.printStackTrace();
@@ -74,20 +74,20 @@ public final class kelondroStack extends kelondroFullRecords {
}
}
- public static kelondroStack reset(kelondroStack stack) {
+ public static kelondroStack reset(final kelondroStack stack) {
// memorize settings to this file
- File f = new File(stack.filename);
- kelondroRow row = stack.row();
+ final File f = new File(stack.filename);
+ final kelondroRow row = stack.row();
// close and delete the file
- try {stack.close();} catch (Exception e) {}
+ try {stack.close();} catch (final Exception e) {}
if (f.exists()) f.delete();
// re-open a database with same settings as before
return open(f, row);
}
- public Iterator<kelondroRow.Entry> stackIterator(boolean up) {
+ public Iterator<kelondroRow.Entry> stackIterator(final boolean up) {
// iterates the elements in an ordered way.
// returns kelondroRow.Entry - type Objects
return new stackIterator(up);
@@ -98,7 +98,7 @@ public final class kelondroStack extends kelondroFullRecords {
kelondroHandle lastHandle = null;
boolean up;
- public stackIterator(boolean up) {
+ public stackIterator(final boolean up) {
this.up = up;
nextHandle = getHandle((up) ? root : toor);
}
@@ -112,7 +112,7 @@ public final class kelondroStack extends kelondroFullRecords {
try {
nextHandle = new EcoNode(nextHandle).getOHHandle((up) ? right : left);
return row().newEntry(new EcoNode(lastHandle).getValueRow());
- } catch (IOException e) {
+ } catch (final IOException e) {
throw new kelondroException(filename, "IO error at Counter:next()");
}
}
@@ -120,7 +120,7 @@ public final class kelondroStack extends kelondroFullRecords {
public void remove() {
try {
unlinkNode(new EcoNode(lastHandle));
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
}
@@ -130,12 +130,12 @@ public final class kelondroStack extends kelondroFullRecords {
return super.size();
}
- public synchronized void push(kelondroRow.Entry row) throws IOException {
+ public synchronized void push(final kelondroRow.Entry row) throws IOException {
// check if there is already a stack
if (getHandle(toor) == null) {
if (getHandle(root) != null) throw new RuntimeException("push: internal organisation of root and toor");
// create node
- kelondroNode n = new EcoNode(row.bytes());
+ final kelondroNode n = new EcoNode(row.bytes());
n.setOHHandle(left, null);
n.setOHHandle(right, null);
n.commit();
@@ -145,10 +145,10 @@ public final class kelondroStack extends kelondroFullRecords {
// thats it
} else {
// expand the list at the end
- kelondroNode n = new EcoNode(row.bytes());
+ final kelondroNode n = new EcoNode(row.bytes());
n.setOHHandle(left, getHandle(toor));
n.setOHHandle(right, null);
- kelondroNode n1 = new EcoNode(getHandle(toor));
+ final kelondroNode n1 = new EcoNode(getHandle(toor));
n1.setOHHandle(right, n.handle());
n.commit();
n1.commit();
@@ -160,9 +160,9 @@ public final class kelondroStack extends kelondroFullRecords {
public synchronized kelondroRow.Entry pop() throws IOException {
// return row ontop of the stack and shrink stack by one
- kelondroNode n = topNode();
+ final kelondroNode n = topNode();
if (n == null) return null;
- kelondroRow.Entry ret = row().newEntry(n.getValueRow());
+ final kelondroRow.Entry ret = row().newEntry(n.getValueRow());
// remove node
unlinkNode(n);
@@ -173,16 +173,16 @@ public final class kelondroStack extends kelondroFullRecords {
public synchronized kelondroRow.Entry top() throws IOException {
// return row ontop of the stack
- kelondroNode n = topNode();
+ final kelondroNode n = topNode();
if (n == null) return null;
return row().newEntry(n.getValueRow());
}
public synchronized kelondroRow.Entry pot() throws IOException {
// return row on the bottom of the stack and remove record
- kelondroNode n = botNode();
+ final kelondroNode n = botNode();
if (n == null) return null;
- kelondroRow.Entry ret = row().newEntry(n.getValueRow());
+ final kelondroRow.Entry ret = row().newEntry(n.getValueRow());
// remove node
unlinkNode(n);
@@ -193,22 +193,22 @@ public final class kelondroStack extends kelondroFullRecords {
public synchronized kelondroRow.Entry bot() throws IOException {
// return row on the bottom of the stack
- kelondroNode n = botNode();
+ final kelondroNode n = botNode();
if (n == null) return null;
return row().newEntry(n.getValueRow());
}
- void unlinkNode(kelondroNode n) throws IOException {
+ void unlinkNode(final kelondroNode n) throws IOException {
// join chaines over node
- kelondroHandle l = n.getOHHandle(left);
- kelondroHandle r = n.getOHHandle(right);
+ final kelondroHandle l = n.getOHHandle(left);
+ final kelondroHandle r = n.getOHHandle(right);
// look left
if (l == null) {
// reached the root on left side
setHandle(root, r);
} else {
// un-link the previous record
- kelondroNode k = new EcoNode(l);
+ final kelondroNode k = new EcoNode(l);
k.setOHHandle(left, k.getOHHandle(left));
k.setOHHandle(right, r);
k.commit();
@@ -219,7 +219,7 @@ public final class kelondroStack extends kelondroFullRecords {
setHandle(toor, l);
} else {
// un-link the following record
- kelondroNode k = new EcoNode(r);
+ final kelondroNode k = new EcoNode(r);
k.setOHHandle(left, l);
k.setOHHandle(right, k.getOHHandle(right));
k.commit();
@@ -229,7 +229,7 @@ public final class kelondroStack extends kelondroFullRecords {
private kelondroNode topNode() throws IOException {
// return node ontop of the stack
if (size() == 0) return null;
- kelondroHandle h = getHandle(toor);
+ final kelondroHandle h = getHandle(toor);
if (h == null) return null;
return new EcoNode(h);
}
@@ -237,12 +237,12 @@ public final class kelondroStack extends kelondroFullRecords {
private kelondroNode botNode() throws IOException {
// return node on bottom of the stack
if (size() == 0) return null;
- kelondroHandle h = getHandle(root);
+ final kelondroHandle h = getHandle(root);
if (h == null) return null;
return new EcoNode(h);
}
- public int imp(File file, String separator) throws IOException {
+ public int imp(final File file, final String separator) throws IOException {
// imports a value-separated file, returns number of records that have been read
RandomAccessFile f = null;
try {
@@ -250,7 +250,7 @@ public final class kelondroStack extends kelondroFullRecords {
String s;
StringTokenizer st;
int recs = 0;
- kelondroRow.Entry buffer = row().newEntry();
+ final kelondroRow.Entry buffer = row().newEntry();
int c;
int line = 0;
while ((s = f.readLine()) != null) {
@@ -274,11 +274,11 @@ public final class kelondroStack extends kelondroFullRecords {
}
return recs;
} finally {
- if (f!=null) try{f.close();}catch(Exception e){}
+ if (f!=null) try{f.close();}catch(final Exception e){}
}
}
- public String hp(kelondroHandle h) {
+ public String hp(final kelondroHandle h) {
if (h == null)
return "NULL";
else
@@ -287,7 +287,7 @@ public final class kelondroStack extends kelondroFullRecords {
public void print() throws IOException {
super.print();
- Iterator<kelondroRow.Entry> it = stackIterator(true);
+ final Iterator<kelondroRow.Entry> it = stackIterator(true);
kelondroRow.Entry r;
while (it.hasNext()) {
r = it.next();
@@ -299,12 +299,12 @@ public final class kelondroStack extends kelondroFullRecords {
System.out.println();
}
- private static void cmd(String[] args) {
+ private static void cmd(final String[] args) {
System.out.print("kelondroStack ");
for (int i = 0; i < args.length; i++) System.out.print(args[i] + " ");
System.out.println("");
byte[] ret = null;
- kelondroRow lens = new kelondroRow("byte[] key-" + Integer.parseInt(args[1]) + ", byte[] value-" + Integer.parseInt(args[2]), kelondroNaturalOrder.naturalOrder, 0);
+ final kelondroRow lens = new kelondroRow("byte[] key-" + Integer.parseInt(args[1]) + ", byte[] value-" + Integer.parseInt(args[2]), kelondroNaturalOrder.naturalOrder, 0);
try {
if ((args.length > 4) || (args.length < 2)) {
System.err.println("usage: kelondroStack -c|-p|-v|-g|-i|-s [file]|[key [value]] <db-file>");
@@ -317,19 +317,19 @@ public final class kelondroStack extends kelondroFullRecords {
ret = null;
} else if (args[0].equals("-g")) {
fm = new kelondroStack(new File(args[1]), lens);
- kelondroRow.Entry ret2 = fm.pop();
+ final kelondroRow.Entry ret2 = fm.pop();
ret = ((ret2 == null) ? null : ret2.getColBytes(1));
fm.close();
}
fm.close();
} else if (args.length == 3) {
if (args[0].equals("-i")) {
- kelondroStack fm = new kelondroStack(new File(args[2]), lens);
- int i = fm.imp(new File(args[1]),";");
+ final kelondroStack fm = new kelondroStack(new File(args[2]), lens);
+ final int i = fm.imp(new File(args[1]),";");
fm.close();
ret = (i + " records imported").getBytes();
} else if (args[0].equals("-s")) {
- String db = args[2];
+ final String db = args[2];
BufferedReader f = null;
try {
f = new BufferedReader(new FileReader(args[1]));
@@ -345,23 +345,23 @@ public final class kelondroStack extends kelondroFullRecords {
}
ret = null;
} finally {
- if (f != null) try {f.close();}catch(Exception e) {}
+ if (f != null) try {f.close();}catch(final Exception e) {}
}
} else if (args[0].equals("-g")) {
- kelondroStack fm = new kelondroStack(new File(args[2]), lens);
- kelondroRow.Entry ret2 = fm.pop();
+ final kelondroStack fm = new kelondroStack(new File(args[2]), lens);
+ final kelondroRow.Entry ret2 = fm.pop();
ret = ((ret2 == null) ? null : ret2.getColBytes(1));
fm.close();
}
} else if (args.length == 4) {
if (args[0].equals("-c")) {
// create <keylen> <valuelen> <filename>
- File f = new File(args[3]);
+ final File f = new File(args[3]);
if (f.exists()) f.delete();
- kelondroStack fm = new kelondroStack(f, lens);
+ final kelondroStack fm = new kelondroStack(f, lens);
fm.close();
} else if (args[0].equals("-p")) {
- kelondroStack fm = new kelondroStack(new File(args[3]), lens);
+ final kelondroStack fm = new kelondroStack(new File(args[3]), lens);
fm.push(fm.row().newEntry(new byte[][] {args[1].getBytes(), args[2].getBytes()}));
fm.close();
}
@@ -370,12 +370,12 @@ public final class kelondroStack extends kelondroFullRecords {
System.out.println("NULL");
else
System.out.println(new String(ret));
- } catch (Exception e) {
+ } catch (final Exception e) {
e.printStackTrace();
}
}
- public static void main(String[] args) {
+ public static void main(final String[] args) {
// -c 10 20 test.stack
// -p a a1 test.stack
// -p b b1 test.stack
diff --git a/source/de/anomic/kelondro/kelondroTree.java b/source/de/anomic/kelondro/kelondroTree.java
index d01e9050e..f34407029 100644
--- a/source/de/anomic/kelondro/kelondroTree.java
+++ b/source/de/anomic/kelondro/kelondroTree.java
@@ -74,11 +74,11 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
protected int readAheadChunkSize = 100;
protected long lastIteratorCount = readAheadChunkSize;
- public kelondroTree(File file, boolean useNodeCache, long preloadTime, kelondroRow rowdef) throws IOException {
+ public kelondroTree(final File file, final boolean useNodeCache, final long preloadTime, final kelondroRow rowdef) throws IOException {
this(file, useNodeCache, preloadTime, rowdef, rowdef.columns() /* txtProps */, 80 /* txtPropWidth */);
}
- public kelondroTree(File file, boolean useNodeCache, long preloadTime, kelondroRow rowdef, int txtProps, int txtPropsWidth) throws IOException {
+ public kelondroTree(final File file, final boolean useNodeCache, final long preloadTime, final kelondroRow rowdef, final int txtProps, final int txtPropsWidth) throws IOException {
// opens an existing tree file or creates a new tree file
super(file, useNodeCache, preloadTime,
thisOHBytes, thisOHHandles, rowdef,
@@ -91,20 +91,20 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
this.loopDetectionOrder = new kelondroByteOrder.StringOrder(rowdef.objectOrder);
}
- public static final kelondroTree open(File file, boolean useNodeCache, long preloadTime, kelondroRow rowdef) {
+ public static final kelondroTree open(final File file, final boolean useNodeCache, final long preloadTime, final kelondroRow rowdef) {
return open(file, useNodeCache, preloadTime, rowdef, rowdef.columns() /* txtProps */, 80 /* txtPropWidth */);
}
- public static final kelondroTree open(File file, boolean useNodeCache, long preloadTime, kelondroRow rowdef, int txtProps, int txtPropsWidth) {
+ public static final kelondroTree open(final File file, final boolean useNodeCache, final long preloadTime, final kelondroRow rowdef, final int txtProps, final int txtPropsWidth) {
// opens new or existing file; in case that any error occur the file is deleted again and it is tried to create the file again
// if that fails, the method returns null
try {
return new kelondroTree(file, useNodeCache, preloadTime, rowdef, txtProps, txtPropsWidth);
- } catch (IOException e) {
+ } catch (final IOException e) {
file.delete();
try {
return new kelondroTree(file, useNodeCache, preloadTime, rowdef, txtProps, txtPropsWidth);
- } catch (IOException ee) {
+ } catch (final IOException ee) {
log.severe("cannot open or create file " + file.toString());
e.printStackTrace();
ee.printStackTrace();
@@ -113,19 +113,19 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
}
}
- public kelondroTree(kelondroRA ra, String filename, boolean useNodeCache, long preloadTime, kelondroRow rowdef, boolean exitOnFail) {
+ public kelondroTree(final kelondroRA ra, final String filename, final boolean useNodeCache, final long preloadTime, final kelondroRow rowdef, final boolean exitOnFail) {
// this creates a new tree within a kelondroRA
this(ra, filename, useNodeCache, preloadTime, rowdef, new kelondroNaturalOrder(true), rowdef.columns() /* txtProps */, 80 /* txtPropWidth */, exitOnFail);
}
- public kelondroTree(kelondroRA ra, String filename, boolean useNodeCache, long preloadTime, kelondroRow rowdef, kelondroByteOrder objectOrder, int txtProps, int txtPropsWidth, boolean exitOnFail) {
+ public kelondroTree(final kelondroRA ra, final String filename, final boolean useNodeCache, final long preloadTime, final kelondroRow rowdef, final kelondroByteOrder objectOrder, final int txtProps, final int txtPropsWidth, final boolean exitOnFail) {
// this creates a new tree within a kelondroRA
super(ra, filename, useNodeCache, preloadTime,
thisOHBytes, thisOHHandles, rowdef,
thisFHandles, txtProps, txtPropsWidth, exitOnFail);
try {
setHandle(root, null); // define the root value
- } catch (IOException e) {
+ } catch (final IOException e) {
super.logFailure("cannot set root handle / " + e.getMessage());
if (exitOnFail) System.exit(-1);
throw new RuntimeException("cannot set root handle / " + e.getMessage());
@@ -134,7 +134,7 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
this.loopDetectionOrder = new kelondroByteOrder.StringOrder(rowdef.objectOrder);
}
- public kelondroTree(kelondroRA ra, String filename, boolean useNodeCache, long preloadTime) throws IOException {
+ public kelondroTree(final kelondroRA ra, final String filename, final boolean useNodeCache, final long preloadTime) throws IOException {
// this opens a file with an existing tree in a kelondroRA
super(ra, filename, useNodeCache, preloadTime);
super.setLogger(log);
@@ -145,18 +145,18 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
setHandle(root, null);
}
- private void commitNode(kelondroNode n) throws IOException {
+ private void commitNode(final kelondroNode n) throws IOException {
//kelondroHandle left = n.getOHHandle(leftchild);
//kelondroHandle right = n.getOHHandle(rightchild);
n.commit();
}
- public boolean has(byte[] key) {
+ public boolean has(final byte[] key) {
throw new UnsupportedOperationException("has should not be used with kelondroTree.");
}
// Returns the value to which this map maps the specified key.
- public kelondroRow.Entry get(byte[] key) throws IOException {
+ public kelondroRow.Entry get(final byte[] key) throws IOException {
kelondroRow.Entry result;
synchronized (writeSearchObj) {
writeSearchObj.process(key);
@@ -193,7 +193,7 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
protected Search() {
}
- protected void process(byte[] key) throws IOException {
+ protected void process(final byte[] key) throws IOException {
// searchs the database for the key and stores the result in the thisHandle
// if the key was found, then found=true, thisHandle and leftchild is set;
// else found=false and thisHandle and leftchild is undefined
@@ -218,13 +218,13 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
found = false;
int c;
- TreeSet<String> visitedNodeKeys = new TreeSet<String>(loopDetectionOrder); // to detect loops
+ final TreeSet<String> visitedNodeKeys = new TreeSet<String>(loopDetectionOrder); // to detect loops
// System.out.println("Starting Compare Loop in Database " + filename); // debug
while (thisHandle != null) {
try {
parentnode = thenode;
thenode = new CacheNode(thisHandle, thenode, (child == -1) ? leftchild : rightchild, true);
- } catch (IllegalArgumentException e) {
+ } catch (final IllegalArgumentException e) {
logWarning("kelondroTree.Search.process: fixed a broken handle");
found = false;
return;
@@ -312,23 +312,23 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
}
}
- public synchronized boolean isChild(kelondroNode childn, kelondroNode parentn, int child) {
+ public synchronized boolean isChild(final kelondroNode childn, final kelondroNode parentn, final int child) {
if (childn == null) throw new IllegalArgumentException("isLeftChild: Node parameter is NULL");
- kelondroHandle lc = parentn.getOHHandle(child);
+ final kelondroHandle lc = parentn.getOHHandle(child);
if (lc == null) return false;
return (lc.equals(childn.handle()));
}
- public synchronized void putMultiple(List<Entry> rows) throws IOException {
- Iterator<Entry> i = rows.iterator();
+ public synchronized void putMultiple(final List<Entry> rows) throws IOException {
+ final Iterator<Entry> i = rows.iterator();
while (i.hasNext()) put(i.next());
}
- public kelondroRow.Entry put(kelondroRow.Entry row, Date entryDate) throws IOException {
+ public kelondroRow.Entry put(final kelondroRow.Entry row, final Date entryDate) throws IOException {
return put(row);
}
- public kelondroRow.Entry put(kelondroRow.Entry newrow) throws IOException {
+ public kelondroRow.Entry put(final kelondroRow.Entry newrow) throws IOException {
assert (newrow != null);
assert (newrow.columns() == row().columns());
assert (!(serverLog.allZero(newrow.getPrimaryKeyBytes())));
@@ -341,7 +341,7 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
writeSearchObj.process(newrow.getColBytes(0));
if (writeSearchObj.found()) {
// a node with this key exist. simply overwrite the content and return old content
- kelondroNode e = writeSearchObj.getMatcher();
+ final kelondroNode e = writeSearchObj.getMatcher();
result = row().newEntry(e.getValueRow());
e.setValueRow(newrow.bytes());
commitNode(e);
@@ -351,7 +351,7 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
if (getHandle(root) != null)
throw new kelondroException(filename, "tried to create root node twice");
// we dont have any Nodes in the file, so start here to create one
- kelondroNode e = new CacheNode(newrow.bytes());
+ final kelondroNode e = new CacheNode(newrow.bytes());
// write the propetries
e.setOHByte(magic, (byte) 1);
e.setOHByte(balance, (byte) 0);
@@ -442,14 +442,14 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
break;
}
if (path.startsWith("RL")) {
- kelondroHandle parentHandle = parentNode.handle();
+ final kelondroHandle parentHandle = parentNode.handle();
LL_RightRotation(theNode, new CacheNode(theNode.getOHHandle(leftchild), theNode, leftchild, false));
parentNode = new CacheNode(parentHandle, null, 0, false); // reload the parent node
RR_LeftRotation(parentNode, new CacheNode(parentNode.getOHHandle(rightchild), parentNode, rightchild, false));
break;
}
if (path.startsWith("LR")) {
- kelondroHandle parentHandle = parentNode.handle();
+ final kelondroHandle parentHandle = parentNode.handle();
RR_LeftRotation(theNode, new CacheNode(theNode.getOHHandle(rightchild), theNode, rightchild, false));
parentNode = new CacheNode(parentHandle, null, 0, false); // reload the parent node
LL_RightRotation(parentNode, new CacheNode(parentNode.getOHHandle(leftchild), parentNode, leftchild, false));
@@ -470,18 +470,18 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
return result;
}
- public synchronized boolean addUnique(kelondroRow.Entry row) throws IOException {
- int s = this.size();
+ public synchronized boolean addUnique(final kelondroRow.Entry row) throws IOException {
+ final int s = this.size();
this.put(row);
return this.size() > s;
}
- public synchronized void addUnique(kelondroRow.Entry row, Date entryDate) throws IOException {
+ public synchronized void addUnique(final kelondroRow.Entry row, final Date entryDate) throws IOException {
this.put(row, entryDate);
}
- public synchronized int addUniqueMultiple(List<kelondroRow.Entry> rows) throws IOException {
- Iterator<kelondroRow.Entry> i = rows.iterator();
+ public synchronized int addUniqueMultiple(final List<kelondroRow.Entry> rows) throws IOException {
+ final Iterator<kelondroRow.Entry> i = rows.iterator();
int c = 0;
while (i.hasNext()) {
if (addUnique(i.next())) c++;
@@ -489,14 +489,14 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
return c;
}
- private void assignChild(kelondroNode parentNode, kelondroNode childNode, int childType) throws IOException {
+ private void assignChild(final kelondroNode parentNode, final kelondroNode childNode, final int childType) throws IOException {
parentNode.setOHHandle(childType, childNode.handle());
childNode.setOHHandle(parent, parentNode.handle());
commitNode(parentNode);
commitNode(childNode);
}
- private void replace(kelondroNode oldNode, kelondroNode oldNodeParent, kelondroNode newNode) throws IOException {
+ private void replace(final kelondroNode oldNode, final kelondroNode oldNodeParent, final kelondroNode newNode) throws IOException {
// this routine looks where the oldNode is connected to, and replaces
// the anchor's link to the oldNode by the newNode-link
// the new link gets the anchor as parent link assigned
@@ -533,24 +533,24 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
// if the oldNode is not needed any more, it can be disposed (check childs first).
}
- private static byte max0(byte b) {
+ private static byte max0(final byte b) {
if (b > 0) return b;
return 0;
}
- private static byte min0(byte b) {
+ private static byte min0(final byte b) {
if (b < 0) return b;
return 0;
}
- private void LL_RightRotation(kelondroNode parentNode, CacheNode childNode) throws IOException {
+ private void LL_RightRotation(final kelondroNode parentNode, final CacheNode childNode) throws IOException {
// replace the parent node; the parent is afterwards unlinked
- kelondroHandle p2Handle = parentNode.getOHHandle(parent);
- kelondroNode p2Node = (p2Handle == null) ? null : new CacheNode(p2Handle, null, 0, false);
+ final kelondroHandle p2Handle = parentNode.getOHHandle(parent);
+ final kelondroNode p2Node = (p2Handle == null) ? null : new CacheNode(p2Handle, null, 0, false);
replace(parentNode, p2Node, childNode);
// set the left son of the parent to the right son of the childNode
- kelondroHandle childOfChild = childNode.getOHHandle(rightchild);
+ final kelondroHandle childOfChild = childNode.getOHHandle(rightchild);
if (childOfChild == null) {
parentNode.setOHHandle(leftchild, null);
} else {
@@ -564,8 +564,8 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
// - newBal(leftChild) = oldBal(leftChild) - 1 + min(newBal(parent), 0)
byte parentBalance = parentNode.getOHByte(balance);
byte childBalance = childNode.getOHByte(balance);
- byte oldBalParent = parentBalance;
- byte oldBalChild = childBalance;
+ final byte oldBalParent = parentBalance;
+ final byte oldBalChild = childBalance;
parentBalance = (byte) (oldBalParent - 1 - max0(oldBalChild));
childBalance = (byte) (oldBalChild - 1 + min0(parentBalance));
parentNode.setOHByte(balance, parentBalance);
@@ -574,14 +574,14 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
commitNode(childNode);
}
- private void RR_LeftRotation(kelondroNode parentNode, CacheNode childNode) throws IOException {
+ private void RR_LeftRotation(final kelondroNode parentNode, final CacheNode childNode) throws IOException {
// replace the parent node; the parent is afterwards unlinked
- kelondroHandle p2Handle = parentNode.getOHHandle(parent);
- kelondroNode p2Node = (p2Handle == null) ? null : new CacheNode(p2Handle, null, 0, false);
+ final kelondroHandle p2Handle = parentNode.getOHHandle(parent);
+ final kelondroNode p2Node = (p2Handle == null) ? null : new CacheNode(p2Handle, null, 0, false);
replace(parentNode, p2Node, childNode);
// set the left son of the parent to the right son of the childNode
- kelondroHandle childOfChild = childNode.getOHHandle(leftchild);
+ final kelondroHandle childOfChild = childNode.getOHHandle(leftchild);
if (childOfChild == null) {
parentNode.setOHHandle(rightchild, null);
} else {
@@ -595,8 +595,8 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
// - newBal(rightChild) = oldBal(rightChild) + 1 + max(newBal(parent), 0)
byte parentBalance = parentNode.getOHByte(balance);
byte childBalance = childNode.getOHByte(balance);
- byte oldBalParent = parentBalance;
- byte oldBalChild = childBalance;
+ final byte oldBalParent = parentBalance;
+ final byte oldBalChild = childBalance;
parentBalance = (byte) (oldBalParent + 1 - min0(oldBalChild));
childBalance = (byte) (oldBalChild + 1 + max0(parentBalance));
parentNode.setOHByte(balance, parentBalance);
@@ -606,22 +606,22 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
}
// Associates the specified value with the specified key in this map
- public byte[] put(byte[] key, byte[] value) throws IOException {
- kelondroRow.Entry row = row().newEntry(new byte[][]{key, value});
- kelondroRow.Entry ret = put(row);
+ public byte[] put(final byte[] key, final byte[] value) throws IOException {
+ final kelondroRow.Entry row = row().newEntry(new byte[][]{key, value});
+ final kelondroRow.Entry ret = put(row);
if (ret == null) return null; else return ret.getColBytes(0);
}
// Removes the mapping for this key from this map if present (optional operation).
- public kelondroRow.Entry remove(byte[] key) throws IOException {
+ public kelondroRow.Entry remove(final byte[] key) throws IOException {
// the order inside the database file cannot be maintained, but iteration over objects will always maintain the object order
// therefore keepOrder should be true, because the effect is always given, while the data structure does not maintain order
// delete from database
synchronized(writeSearchObj) {
writeSearchObj.process(key);
if (writeSearchObj.found()) {
- CacheNode result = writeSearchObj.getMatcher();
- kelondroRow.Entry values = row().newEntry(result.getValueRow());
+ final CacheNode result = writeSearchObj.getMatcher();
+ final kelondroRow.Entry values = row().newEntry(result.getValueRow());
remove(result, writeSearchObj.getParent());
return values;
} else {
@@ -633,8 +633,8 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
public kelondroRow.Entry removeOne() throws IOException {
// removes just any entry and removes that entry
synchronized(writeSearchObj) {
- CacheNode theOne = lastNode();
- kelondroRow.Entry values = row().newEntry(theOne.getValueRow());
+ final CacheNode theOne = lastNode();
+ final kelondroRow.Entry values = row().newEntry(theOne.getValueRow());
remove(theOne, null);
return values;
}
@@ -644,7 +644,7 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
while (size() > 0) remove(lastNode(), null);
}
- private void remove(CacheNode node, kelondroNode parentOfNode) throws IOException {
+ private void remove(CacheNode node, final kelondroNode parentOfNode) throws IOException {
// there are three cases when removing a node
// - the node is a leaf - it can be removed easily
// - the node has one child - the child replaces the node
@@ -671,7 +671,7 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
replace(node, parentOfNode, new CacheNode(node.getOHHandle(rightchild), node, rightchild, false));
} else {
// difficult case: node has two children
- CacheNode repl = lastNode(new CacheNode(node.getOHHandle(leftchild), node, leftchild, false));
+ final CacheNode repl = lastNode(new CacheNode(node.getOHHandle(leftchild), node, leftchild, false));
//System.out.println("last node is " + repl.toString());
// we remove that replacement node and put it where the node was
// this seems to be recursive, but is not since the replacement
@@ -691,7 +691,7 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
try {
childnode = new CacheNode(repl.getOHHandle(leftchild), repl, leftchild, false);
replace(repl, new CacheNode(repl.getOHHandle(parent), null, 0, false), childnode);
- } catch (IllegalArgumentException e) {
+ } catch (final IllegalArgumentException e) {
// now treat the situation as if that link had been null before
n = new CacheNode(repl.getOHHandle(parent), null, 0, false); // parent node of replacement node
h = n.getOHHandle(leftchild);
@@ -704,7 +704,7 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
try {
childnode = new CacheNode(repl.getOHHandle(rightchild), repl, rightchild, false);
replace(repl, new CacheNode(repl.getOHHandle(parent), null, 0, false), childnode);
- } catch (IllegalArgumentException e) {
+ } catch (final IllegalArgumentException e) {
// now treat the situation as if that link had been null before
n = new CacheNode(repl.getOHHandle(parent), null, 0, false); // parent node of replacement node
h = n.getOHHandle(leftchild);
@@ -719,10 +719,10 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
//System.out.println("node after reload is " + node.toString());
// now plant in the replha node
- byte b = node.getOHByte(balance); // save balance of disappearing node
- kelondroHandle parentHandle = node.getOHHandle(parent);
- kelondroHandle leftchildHandle = node.getOHHandle(leftchild);
- kelondroHandle rightchildHandle = node.getOHHandle(rightchild);
+ final byte b = node.getOHByte(balance); // save balance of disappearing node
+ final kelondroHandle parentHandle = node.getOHHandle(parent);
+ final kelondroHandle leftchildHandle = node.getOHHandle(leftchild);
+ final kelondroHandle rightchildHandle = node.getOHHandle(rightchild);
replace(node, parentOfNode, repl);
repl.setOHByte(balance, b); // restore balance
repl.setOHHandle(parent, parentHandle); // restore handles
@@ -748,7 +748,7 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
}
protected CacheNode firstNode() throws IOException {
- kelondroHandle h = getHandle(root);
+ final kelondroHandle h = getHandle(root);
if (h == null) return null;
return firstNode(new CacheNode(h, null, 0, true));
}
@@ -756,7 +756,7 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
protected CacheNode firstNode(CacheNode node) throws IOException {
if (node == null) throw new IllegalArgumentException("firstNode: node=null");
kelondroHandle h = node.getOHHandle(leftchild);
- HashSet<String> visitedNodeKeys = new HashSet<String>(); // to detect loops
+ final HashSet<String> visitedNodeKeys = new HashSet<String>(); // to detect loops
String nodeKey;
while (h != null) {
try {
@@ -764,7 +764,7 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
nodeKey = new String(node.getKey());
if (visitedNodeKeys.contains(nodeKey)) throw new kelondroException(this.filename, "firstNode: database contains loops: '" + nodeKey + "' appears twice.");
visitedNodeKeys.add(nodeKey);
- } catch (IllegalArgumentException e) {
+ } catch (final IllegalArgumentException e) {
// return what we have
return node;
}
@@ -774,7 +774,7 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
}
protected CacheNode lastNode() throws IOException {
- kelondroHandle h = getHandle(root);
+ final kelondroHandle h = getHandle(root);
if (h == null) return null;
return lastNode(new CacheNode(h, null, 0, true));
}
@@ -782,7 +782,7 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
protected CacheNode lastNode(CacheNode node) throws IOException {
if (node == null) throw new IllegalArgumentException("lastNode: node=null");
kelondroHandle h = node.getOHHandle(rightchild);
- HashSet<String> visitedNodeKeys = new HashSet<String>(); // to detect loops
+ final HashSet<String> visitedNodeKeys = new HashSet<String>(); // to detect loops
String nodeKey;
while (h != null) {
try {
@@ -790,7 +790,7 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
nodeKey = new String(node.getKey());
if (visitedNodeKeys.contains(nodeKey)) throw new kelondroException(this.filename, "lastNode: database contains loops: '" + nodeKey + "' appears twice.");
visitedNodeKeys.add(nodeKey);
- } catch (IllegalArgumentException e) {
+ } catch (final IllegalArgumentException e) {
// return what we have
return node;
}
@@ -807,7 +807,7 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
LinkedList<Object[]> nodeStack;
int count;
- public nodeIterator(boolean up, boolean rotating) throws IOException {
+ public nodeIterator(final boolean up, final boolean rotating) throws IOException {
this.count = 0;
this.up = up;
this.rot = rotating;
@@ -816,17 +816,17 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
init((up) ? firstNode() : lastNode());
}
- public nodeIterator(boolean up, boolean rotating, byte[] firstKey, boolean including) throws IOException {
+ public nodeIterator(final boolean up, final boolean rotating, final byte[] firstKey, final boolean including) throws IOException {
this.count = 0;
this.up = up;
this.rot = rotating;
- Search search = new Search();
+ final Search search = new Search();
search.process(firstKey);
if (search.found()) {
init(search.getMatcher());
} else {
- CacheNode nn = search.getParent();
+ final CacheNode nn = search.getParent();
if (nn == null) {
this.nextNode = null;
} else {
@@ -841,7 +841,7 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
// correct nextNode upon start
// this happens, if the start node was not proper, or could not be found
while ((nextNode != null) && (nextNode.getKey() != null)) {
- int c = row().objectOrder.compare(firstKey, nextNode.getKey());
+ final int c = row().objectOrder.compare(firstKey, nextNode.getKey());
if (c == 0) {
if (including) {
break; // correct + finished
@@ -867,7 +867,7 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
}
}
- private void init(CacheNode start) throws IOException {
+ private void init(final CacheNode start) throws IOException {
this.nextNode = start;
// fill node stack for start node
@@ -877,7 +877,7 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
if (searchHandle == null) {nextNode = null; return;}
CacheNode searchNode = new CacheNode(searchHandle, null, 0, false);
- byte[] startKey = start.getKey();
+ final byte[] startKey = start.getKey();
int c, ct;
while ((c = row().objectOrder.compare(startKey, searchNode.getKey())) != 0) {
// the current 'thisNode' is not the start node, put it on the stack
@@ -906,12 +906,12 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
count++;
if ((rot) && (nextNode == null)) try {
init((up) ? firstNode() : lastNode());
- } catch (IOException e) {
+ } catch (final IOException e) {
throw new kelondroException(filename, "io-error while rot");
}
if (nextNode == null) throw new kelondroException(filename, "nodeIterator.next: no more entries available");
if ((count > size()) && (!(rot))) throw new kelondroException(filename, "nodeIterator.next: internal loopback; database corrupted");
- CacheNode ret = nextNode;
+ final CacheNode ret = nextNode;
// middle-case
try {
@@ -920,7 +920,7 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
if (childHandle != null) {
//System.out.println("go to other leg, stack size=" + nodeStack.size());
// we have walked one leg of the tree; now go to the other one: step down to next child
- HashSet<kelondroHandle> visitedNodeHandles = new HashSet<kelondroHandle>(); // to detect loops
+ final HashSet<kelondroHandle> visitedNodeHandles = new HashSet<kelondroHandle>(); // to detect loops
nodeStack.addLast(new Object[]{nextNode, new Integer(childtype)});
nextNode = new CacheNode(childHandle, nextNode, childtype, false);
childtype = (up) ? leftchild : rightchild;
@@ -936,7 +936,7 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
try {
nodeStack.addLast(new Object[]{nextNode, new Integer(childtype)});
nextNode = new CacheNode(childHandle, nextNode, childtype, false);
- } catch (IllegalArgumentException e) {
+ } catch (final IllegalArgumentException e) {
// return what we have
nodeStack.removeLast();
return ret;
@@ -969,7 +969,7 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
}
}
}
- } catch (IOException e) {
+ } catch (final IOException e) {
nextNode = null;
}
@@ -981,16 +981,16 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
}
}
- public TreeMap<String, kelondroRow.Entry> rowMap(boolean up, byte[] firstKey, boolean including, int count) throws IOException {
+ public TreeMap<String, kelondroRow.Entry> rowMap(final boolean up, final byte[] firstKey, final boolean including, final int count) throws IOException {
// returns an ordered map of keys/row relations; key objects are of type String, value objects are of type byte[][]
- kelondroByteOrder setOrder = (kelondroByteOrder) row().objectOrder.clone();
+ final kelondroByteOrder setOrder = (kelondroByteOrder) row().objectOrder.clone();
setOrder.direction(up);
setOrder.rotate(firstKey);
- TreeMap<String, kelondroRow.Entry> rows = new TreeMap<String, kelondroRow.Entry>(this.loopDetectionOrder);
+ final TreeMap<String, kelondroRow.Entry> rows = new TreeMap<String, kelondroRow.Entry>(this.loopDetectionOrder);
CacheNode n;
String key;
synchronized (this) {
- Iterator<CacheNode> i = (firstKey == null) ? new nodeIterator(up, false) : new nodeIterator(up, false, firstKey, including);
+ final Iterator<CacheNode> i = (firstKey == null) ? new nodeIterator(up, false) : new nodeIterator(up, false, firstKey, including);
while ((rows.size() < count) && (i.hasNext())) {
n = i.next();
if (n == null) return rows;
@@ -1001,15 +1001,15 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
return rows;
}
- public TreeSet<String> keySet(boolean up, boolean rotating, byte[] firstKey, boolean including, int count) throws IOException {
+ public TreeSet<String> keySet(final boolean up, final boolean rotating, final byte[] firstKey, final boolean including, final int count) throws IOException {
// returns an ordered set of keys; objects are of type String
- kelondroByteOrder setOrder = (kelondroByteOrder) row().objectOrder.clone();
+ final kelondroByteOrder setOrder = (kelondroByteOrder) row().objectOrder.clone();
setOrder.direction(up);
setOrder.rotate(firstKey);
- TreeSet<String> set = new TreeSet<String>(this.loopDetectionOrder);
+ final TreeSet<String> set = new TreeSet<String>(this.loopDetectionOrder);
kelondroNode n;
synchronized (this) {
- Iterator<CacheNode> i = (firstKey == null) ? new nodeIterator(up, rotating) : new nodeIterator(up, rotating, firstKey, including);
+ final Iterator<CacheNode> i = (firstKey == null) ? new nodeIterator(up, rotating) : new nodeIterator(up, rotating, firstKey, including);
while ((set.size() < count) && (i.hasNext())) {
n = i.next();
if ((n != null) && (n.getKey() != null)) set.add(new String(n.getKey()));
@@ -1018,7 +1018,7 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
return set;
}
- public kelondroCloneableIterator<kelondroRow.Entry> rows(boolean up, byte[] firstKey) throws IOException {
+ public kelondroCloneableIterator<kelondroRow.Entry> rows(final boolean up, final byte[] firstKey) throws IOException {
// iterates the rows of the Nodes
// enumerated objects are of type byte[][]
// iterates the elements in a sorted way.
@@ -1036,7 +1036,7 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
Iterator<Map.Entry<String, kelondroRow.Entry>> bufferIterator;
long guessedCountLimit;
- public rowIterator(boolean up, byte[] firstKey, long guessedCountLimit) throws IOException {
+ public rowIterator(final boolean up, final byte[] firstKey, final long guessedCountLimit) throws IOException {
this.guessedCountLimit = guessedCountLimit;
inc = up;
count = 0;
@@ -1049,10 +1049,10 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
lastIteratorCount = 0;
}
- public rowIterator clone(Object secondStart) {
+ public rowIterator clone(final Object secondStart) {
try {
return new rowIterator(inc, (byte[]) secondStart, guessedCountLimit);
- } catch (IOException e) {
+ } catch (final IOException e) {
return null;
}
}
@@ -1063,7 +1063,7 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
public kelondroRow.Entry next() {
if (!(bufferIterator.hasNext())) return null;
- Map.Entry<String, kelondroRow.Entry> entry = bufferIterator.next();
+ final Map.Entry<String, kelondroRow.Entry> entry = bufferIterator.next();
lastKey = entry.getKey().getBytes();
// check if this was the last entry in the rowBuffer
@@ -1073,7 +1073,7 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
lastKey[lastKey.length - 1]++; // ***BUG??? FIXME
rowBuffer = rowMap(inc, lastKey, false, chunkSize);
bufferIterator = rowBuffer.entrySet().iterator();
- } catch (IOException e) {
+ } catch (final IOException e) {
rowBuffer = null;
bufferIterator = null;
}
@@ -1088,14 +1088,14 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
public void remove() {
if (lastKey != null) try {
kelondroTree.this.remove(lastKey);
- } catch (IOException e) {
+ } catch (final IOException e) {
// do nothing
}
}
}
- public kelondroCloneableIterator<byte[]> keys(boolean up, byte[] firstKey) throws IOException {
+ public kelondroCloneableIterator<byte[]> keys(final boolean up, final byte[] firstKey) throws IOException {
return new keyIterator(up, firstKey, this.size());
}
@@ -1109,7 +1109,7 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
Iterator<String> bufferIterator;
long guessedCountLimit;
- public keyIterator(boolean up, byte[] firstKey, long guessedCountLimit) throws IOException {
+ public keyIterator(final boolean up, final byte[] firstKey, final long guessedCountLimit) throws IOException {
this.guessedCountLimit = guessedCountLimit;
inc = up;
count = 0;
@@ -1122,10 +1122,10 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
lastIteratorCount = 0;
}
- public keyIterator clone(Object secondStart) {
+ public keyIterator clone(final Object secondStart) {
try {
return new keyIterator(inc, (byte[]) secondStart, guessedCountLimit);
- } catch (IOException e) {
+ } catch (final IOException e) {
return null;
}
}
@@ -1145,7 +1145,7 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
lastKey[lastKey.length - 1]++; // ***BUG??? FIXME
keyBuffer = keySet(inc, false, lastKey, false, chunkSize);
bufferIterator = keyBuffer.iterator();
- } catch (IOException e) {
+ } catch (final IOException e) {
keyBuffer = null;
bufferIterator = null;
}
@@ -1160,21 +1160,21 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
public void remove() {
if (lastKey != null) try {
kelondroTree.this.remove(lastKey);
- } catch (IOException e) {
+ } catch (final IOException e) {
// do nothing
}
}
}
- public int imp(File file, String separator) throws IOException {
+ public int imp(final File file, final String separator) throws IOException {
// imports a value-separated file, returns number of records that have been read
- RandomAccessFile f = new RandomAccessFile(file,"r");
+ final RandomAccessFile f = new RandomAccessFile(file,"r");
String s;
StringTokenizer st;
int recs = 0;
- kelondroRow.Entry buffer = row().newEntry();
+ final kelondroRow.Entry buffer = row().newEntry();
int c;
int line = 0;
while ((s = f.readLine()) != null) {
@@ -1201,34 +1201,35 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
public synchronized int height() {
try {
- kelondroHandle h = getHandle(root);
+ final kelondroHandle h = getHandle(root);
if (h == null) return 0;
return height(new CacheNode(h, null, 0, false));
- } catch (IOException e) {
+ } catch (final IOException e) {
return 0;
}
}
- private int height(CacheNode node) throws IOException {
+ private int height(final CacheNode node) throws IOException {
if (node == null) return 0;
kelondroHandle h = node.getOHHandle(leftchild);
- int hl = (h == null) ? 0 : height(new CacheNode(h, node, leftchild, false));
+ final int hl = (h == null) ? 0 : height(new CacheNode(h, node, leftchild, false));
h = node.getOHHandle(rightchild);
- int hr = (h == null) ? 0 : height(new CacheNode(h, node, rightchild, false));
+ final int hr = (h == null) ? 0 : height(new CacheNode(h, node, rightchild, false));
if (hl > hr) return hl + 1;
return hr + 1;
}
public void print() throws IOException {
super.print();
- int height = height();
+ final int height = height();
System.out.println("HEIGHT = " + height);
Vector<kelondroHandle> thisline = new Vector<kelondroHandle>();
thisline.add(getHandle(root));
Vector<kelondroHandle> nextline;
kelondroHandle handle;
kelondroNode node;
- int linelength, width = (1 << (height - 1)) * (row().width(0) + 1);
+ int linelength;
+ final int width = (1 << (height - 1)) * (row().width(0) + 1);
String key;
for (int h = 1; h < height; h++) {
linelength = width / (thisline.size() * 2);
@@ -1284,7 +1285,7 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
System.out.println();
}
- public static void cmd(String[] args) {
+ public static void cmd(final String[] args) {
System.out.print("kelondroTree ");
for (int i = 0; i < args.length; i++) System.out.print(args[i] + " ");
System.out.println("");
@@ -1297,10 +1298,10 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
} else if (args.length == 1) {
if (args[0].equals("-t")) {
// test script
- File testFile = new File("test.db");
+ final File testFile = new File("test.db");
while (testFile.exists()) testFile.delete();
- kelondroTree fm = new kelondroTree(testFile, true, 10, new kelondroRow("byte[] a-4, byte[] b-4", kelondroNaturalOrder.naturalOrder, 0));
- byte[] dummy = "".getBytes();
+ final kelondroTree fm = new kelondroTree(testFile, true, 10, new kelondroRow("byte[] a-4, byte[] b-4", kelondroNaturalOrder.naturalOrder, 0));
+ final byte[] dummy = "".getBytes();
fm.put("abc0".getBytes(), dummy); fm.put("bcd0".getBytes(), dummy);
fm.put("def0".getBytes(), dummy); fm.put("bab0".getBytes(), dummy);
fm.put("abc1".getBytes(), dummy); fm.put("bcd1".getBytes(), dummy);
@@ -1321,7 +1322,7 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
ret = null;
}
} else if (args.length == 2) {
- kelondroTree fm = new kelondroTree(new File(args[1]), true, 10, new kelondroRow("byte[] a-4, byte[] b-4", kelondroNaturalOrder.naturalOrder, 0));
+ final kelondroTree fm = new kelondroTree(new File(args[1]), true, 10, new kelondroRow("byte[] a-4, byte[] b-4", kelondroNaturalOrder.naturalOrder, 0));
if (args[0].equals("-v")) {
fm.print();
ret = null;
@@ -1329,16 +1330,16 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
fm.close();
} else if (args.length == 3) {
if (args[0].equals("-d")) {
- kelondroTree fm = new kelondroTree(new File(args[1]), true, 10, new kelondroRow("byte[] a-4, byte[] b-4", kelondroNaturalOrder.naturalOrder, 0));
+ final kelondroTree fm = new kelondroTree(new File(args[1]), true, 10, new kelondroRow("byte[] a-4, byte[] b-4", kelondroNaturalOrder.naturalOrder, 0));
fm.remove(args[2].getBytes());
fm.close();
} else if (args[0].equals("-i")) {
- kelondroTree fm = new kelondroTree(new File(args[1]), true, 10, new kelondroRow("byte[] a-4, byte[] b-4", kelondroNaturalOrder.naturalOrder, 0));
- int i = fm.imp(new File(args[1]),";");
+ final kelondroTree fm = new kelondroTree(new File(args[1]), true, 10, new kelondroRow("byte[] a-4, byte[] b-4", kelondroNaturalOrder.naturalOrder, 0));
+ final int i = fm.imp(new File(args[1]),";");
fm.close();
ret = (i + " records imported").getBytes();
} else if (args[0].equals("-s")) {
- String db = args[2];
+ final String db = args[2];
BufferedReader f = null;
try {
f = new BufferedReader(new FileReader(args[1]));
@@ -1353,18 +1354,18 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
}
ret = null;
} finally {
- if (f != null) try {f.close();}catch(Exception e){}
+ if (f != null) try {f.close();}catch(final Exception e){}
}
} else if (args[0].equals("-g")) {
- kelondroTree fm = new kelondroTree(new File(args[1]), true, 10, new kelondroRow("byte[] a-4, byte[] b-4", kelondroNaturalOrder.naturalOrder, 0));
- kelondroRow.Entry ret2 = fm.get(args[2].getBytes());
+ final kelondroTree fm = new kelondroTree(new File(args[1]), true, 10, new kelondroRow("byte[] a-4, byte[] b-4", kelondroNaturalOrder.naturalOrder, 0));
+ final kelondroRow.Entry ret2 = fm.get(args[2].getBytes());
ret = ((ret2 == null) ? null : ret2.getColBytes(1));
fm.close();
} else if (args[0].equals("-n")) {
- kelondroTree fm = new kelondroTree(new File(args[1]), true, 10, new kelondroRow("byte[] a-4, byte[] b-4", kelondroNaturalOrder.naturalOrder, 0));
+ final kelondroTree fm = new kelondroTree(new File(args[1]), true, 10, new kelondroRow("byte[] a-4, byte[] b-4", kelondroNaturalOrder.naturalOrder, 0));
//byte[][] keys = fm.getSequentialKeys(args[2].getBytes(), 500, true);
- Iterator<kelondroRow.Entry> rowIt = fm.rows(true, (args[2].length() == 0) ? null : args[2].getBytes());
- Vector<String> v = new Vector<String>();
+ final Iterator<kelondroRow.Entry> rowIt = fm.rows(true, (args[2].length() == 0) ? null : args[2].getBytes());
+ final Vector<String> v = new Vector<String>();
while (rowIt.hasNext()) v.add(rowIt.next().getColString(0, null));
ret = v.toString().getBytes();
fm.close();
@@ -1372,13 +1373,13 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
} else if (args.length == 4) {
if (args[0].equals("-c")) {
// create <keylen> <valuelen> <filename>
- File f = new File(args[3]);
+ final File f = new File(args[3]);
if (f.exists()) f.delete();
- kelondroRow lens = new kelondroRow("byte[] key-" + Integer.parseInt(args[1]) + ", byte[] value-" + Integer.parseInt(args[2]), kelondroNaturalOrder.naturalOrder, 0);
- kelondroTree fm = new kelondroTree(f, true, 10, lens);
+ final kelondroRow lens = new kelondroRow("byte[] key-" + Integer.parseInt(args[1]) + ", byte[] value-" + Integer.parseInt(args[2]), kelondroNaturalOrder.naturalOrder, 0);
+ final kelondroTree fm = new kelondroTree(f, true, 10, lens);
fm.close();
} else if (args[0].equals("-u")) {
- kelondroTree fm = new kelondroTree(new File(args[1]), true, 10, new kelondroRow("byte[] a-4, byte[] b-4", kelondroNaturalOrder.naturalOrder, 0));
+ final kelondroTree fm = new kelondroTree(new File(args[1]), true, 10, new kelondroRow("byte[] a-4, byte[] b-4", kelondroNaturalOrder.naturalOrder, 0));
ret = fm.put(args[1].getBytes(), args[2].getBytes());
fm.close();
}
@@ -1387,12 +1388,12 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
System.out.println("NULL");
else
System.out.println(new String(ret));
- } catch (Exception e) {
+ } catch (final Exception e) {
e.printStackTrace();
}
}
- public static void main(String[] args) {
+ public static void main(final String[] args) {
//cmd(args);
//iterationtest();
//bigtest(Integer.parseInt(args[0]));
@@ -1400,17 +1401,17 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
//smalltest();
}
- public static String[] permutations(int letters) {
+ public static String[] permutations(final int letters) {
String p = "";
for (int i = 0; i < letters; i++) p = p + ((char) (('A') + i));
return permutations(p);
}
- public static String[] permutations(String source) {
+ public static String[] permutations(final String source) {
if (source.length() == 0) return new String[0];
if (source.length() == 1) return new String[]{source};
- char c = source.charAt(0);
- String[] recres = permutations(source.substring(1));
- String[] result = new String[source.length() * recres.length];
+ final char c = source.charAt(0);
+ final String[] recres = permutations(source.substring(1));
+ final String[] result = new String[source.length() * recres.length];
for (int perm = 0; perm < recres.length; perm++) {
result[perm * source.length()] = c + recres[perm];
for (int pos = 1; pos < source.length() - 1; pos++) {
@@ -1421,17 +1422,17 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
return result;
}
- public static byte[] testWord(char c) {
+ public static byte[] testWord(final char c) {
return new byte[]{(byte) c, 32, 32, 32};
}
- public static void randomtest(int elements) {
+ public static void randomtest(final int elements) {
System.out.println("random " + elements + ":");
- String s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".substring(0, elements);
+ final String s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".substring(0, elements);
String t, d;
char c;
kelondroTree tt = null;
- File testFile = new File("test.db");
+ final File testFile = new File("test.db");
byte[] b;
try {
int steps = 0;
@@ -1492,18 +1493,18 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
tt.close();
}
- } catch (Exception e) {
+ } catch (final Exception e) {
e.printStackTrace();
- if (tt != null) try {tt.print();} catch (IOException ee) {}
+ if (tt != null) try {tt.print();} catch (final IOException ee) {}
System.out.println("TERMINATED");
}
}
public static void smalltest() {
- File f = new File("test.db");
+ final File f = new File("test.db");
if (f.exists()) f.delete();
try {
- kelondroTree tt = new kelondroTree(f, true, 10, new kelondroRow("byte[] a-4, byte[] b-4", kelondroNaturalOrder.naturalOrder, 0));
+ final kelondroTree tt = new kelondroTree(f, true, 10, new kelondroRow("byte[] a-4, byte[] b-4", kelondroNaturalOrder.naturalOrder, 0));
byte[] b;
b = testWord('B'); tt.put(b, b); //tt.print();
b = testWord('C'); tt.put(b, b); //tt.print();
@@ -1521,14 +1522,14 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
b = testWord('J'); tt.put(b, b);
b = testWord('K'); tt.put(b, b);
b = testWord('L'); tt.put(b, b);
- int c = countElements(tt);
+ final int c = countElements(tt);
System.out.println("elements: " + c);
- Iterator<kelondroRow.Entry> i = tt.rows(true, testWord('G'));
+ final Iterator<kelondroRow.Entry> i = tt.rows(true, testWord('G'));
for (int j = 0; j < c; j++) {
System.out.println("Row " + j + ": " + new String((i.next()).getColBytes(0)));
}
System.out.println("TERMINATED");
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
}
@@ -1566,9 +1567,9 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
}
*/
- public static kelondroTree testTree(File f, String testentities) throws IOException {
+ public static kelondroTree testTree(final File f, final String testentities) throws IOException {
if (f.exists()) f.delete();
- kelondroTree tt = new kelondroTree(f, false, 10, new kelondroRow("byte[] a-4, byte[] b-4", kelondroNaturalOrder.naturalOrder, 0));
+ final kelondroTree tt = new kelondroTree(f, false, 10, new kelondroRow("byte[] a-4, byte[] b-4", kelondroNaturalOrder.naturalOrder, 0));
byte[] b;
for (int i = 0; i < testentities.length(); i++) {
b = testWord(testentities.charAt(i));
@@ -1577,12 +1578,12 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
return tt;
}
- public static void bigtest(int elements) {
+ public static void bigtest(final int elements) {
System.out.println("starting big test with " + elements + " elements:");
- long start = System.currentTimeMillis();
- String[] s = permutations(elements);
+ final long start = System.currentTimeMillis();
+ final String[] s = permutations(elements);
kelondroTree tt;
- File testFile = new File("test.db");
+ final File testFile = new File("test.db");
try {
for (int i = 0; i < s.length; i++) {
System.out.println("*** probing tree " + i + " for permutation " + s[i]);
@@ -1624,16 +1625,16 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
}
}
System.out.println("FINISHED test after " + ((System.currentTimeMillis() - start) / 1000) + " seconds.");
- } catch (Exception e) {
+ } catch (final Exception e) {
e.printStackTrace();
System.out.println("TERMINATED");
}
}
- public static int countElements(kelondroIndex t) {
+ public static int countElements(final kelondroIndex t) {
int count = 0;
try {
- Iterator<kelondroRow.Entry> iter = t.rows(true, null);
+ final Iterator<kelondroRow.Entry> iter = t.rows(true, null);
kelondroRow.Entry row;
while (iter.hasNext()) {
count++;
@@ -1642,7 +1643,7 @@ public class kelondroTree extends kelondroCachedRecords implements kelondroIndex
// else System.out.println("counted element: " + new
// String(n.getKey()));
}
- } catch (IOException e) {
+ } catch (final IOException e) {
}
return count;
}
diff --git a/source/de/anomic/kelondro/kelondroXMLTables.java b/source/de/anomic/kelondro/kelondroXMLTables.java
index 7cc27195c..e46c128d9 100644
--- a/source/de/anomic/kelondro/kelondroXMLTables.java
+++ b/source/de/anomic/kelondro/kelondroXMLTables.java
@@ -50,11 +50,11 @@ public class kelondroXMLTables {
}
@SuppressWarnings("unchecked")
- public kelondroXMLTables(File file) throws IOException {
+ public kelondroXMLTables(final File file) throws IOException {
this.propFile = file;
this.timestamp = System.currentTimeMillis();
if (propFile.exists()) {
- XMLDecoder xmldec = new XMLDecoder(new FileInputStream(propFile));
+ final XMLDecoder xmldec = new XMLDecoder(new FileInputStream(propFile));
tables = (Hashtable<String, Hashtable<String, String>>) xmldec.readObject();
xmldec.close();
} else {
@@ -62,7 +62,7 @@ public class kelondroXMLTables {
}
}
- public void commit(File target) throws IOException {
+ public void commit(final File target) throws IOException {
// this method is used if the Mircrotable was created without assigning
// a file to it as an empty table the table then becomes file-based,
// and write operation will be committed to the file
@@ -70,7 +70,7 @@ public class kelondroXMLTables {
commit(true);
}
- private void commit(boolean force) throws IOException {
+ private void commit(final boolean force) throws IOException {
// this function commits the data to a file
// it does not save the data until a specific waiting-time has been lasted
if ((force) || (System.currentTimeMillis() - timestamp > 10000)) {
@@ -80,10 +80,10 @@ public class kelondroXMLTables {
throw new RuntimeException("Microtables.commit: no file specified");
// write first to a temporary file
- File tmpFile = new File(this.propFile.toString() + ".tmp");
+ final File tmpFile = new File(this.propFile.toString() + ".tmp");
// write file
- XMLEncoder xmlenc = new XMLEncoder(new FileOutputStream(tmpFile));
+ final XMLEncoder xmlenc = new XMLEncoder(new FileOutputStream(tmpFile));
xmlenc.writeObject(tables);
xmlenc.close();
@@ -96,29 +96,29 @@ public class kelondroXMLTables {
}
}
- public boolean hasTable(String table) {
+ public boolean hasTable(final String table) {
return (tables.get(table) != null);
}
- public int sizeTable(String table) {
+ public int sizeTable(final String table) {
// returns number of entries in table; if table does not exist -1
- Hashtable<String, String> l = tables.get(table);
+ final Hashtable<String, String> l = tables.get(table);
if (l == null) return -1;
return l.size();
}
- public void createTable(String table) throws IOException {
+ public void createTable(final String table) throws IOException {
// creates a new table
- Hashtable<String, String> l = tables.get(table);
+ final Hashtable<String, String> l = tables.get(table);
if (l != null)
return; // we do not overwite
tables.put(table, new Hashtable<String, String>());
if (this.propFile != null) commit(false);
}
- public void set(String table, String key, String value) throws IOException {
+ public void set(final String table, final String key, String value) throws IOException {
if (table != null) {
- Hashtable<String, String> l = tables.get(table);
+ final Hashtable<String, String> l = tables.get(table);
if (l == null) throw new RuntimeException("Microtables.set: table does not exist");
if (value == null) value = "";
l.put(key, value);
@@ -127,9 +127,9 @@ public class kelondroXMLTables {
commit(false);
}
- public String get(String table, String key, String deflt) {
+ public String get(final String table, final String key, final String deflt) {
if (table != null) {
- Hashtable<String, String> l = tables.get(table);
+ final Hashtable<String, String> l = tables.get(table);
if (l == null)
throw new RuntimeException("Microtables.get: table does not exist");
if (l.containsKey(key))
@@ -140,9 +140,9 @@ public class kelondroXMLTables {
return null;
}
- public boolean has(String table, String key) {
+ public boolean has(final String table, final String key) {
if (table != null) {
- Hashtable<String, String> l = tables.get(table);
+ final Hashtable<String, String> l = tables.get(table);
if (l == null)
throw new RuntimeException("Microtables.has: table does not exist");
return (l.containsKey(key));
@@ -150,9 +150,9 @@ public class kelondroXMLTables {
return false;
}
- public Enumeration<String> keys(String table) {
+ public Enumeration<String> keys(final String table) {
if (table != null) {
- Hashtable<String, String> l = tables.get(table);
+ final Hashtable<String, String> l = tables.get(table);
if (l == null)
throw new RuntimeException("Microtables.keys: table does not exist");
return l.keys();
diff --git a/source/de/anomic/language/identification/Identificator.java b/source/de/anomic/language/identification/Identificator.java
index 4a7ec678e..95612efb8 100644
--- a/source/de/anomic/language/identification/Identificator.java
+++ b/source/de/anomic/language/identification/Identificator.java
@@ -33,7 +33,7 @@ import java.util.Vector;
*/
public final class Identificator {
- private LanguageStatisticsHolder languages;
+ private final LanguageStatisticsHolder languages;
public Identificator() {
languages = LanguageStatisticsHolder.getInstance();
@@ -46,7 +46,7 @@ public final class Identificator {
* @param text the text that is to be analyzed
* @return the language or "unknown" if the method was not able to find out the language
*/
- public String getLanguage(String text) {
+ public String getLanguage(final String text) {
// only test the first 100000 characters of a text
return getLanguage(text, 100000);
}
@@ -58,12 +58,12 @@ public final class Identificator {
* @param limit the number of characters that are supposed to be considered
* @return the language or "unknown" if the method was not able to find out the language
*/
- public String getLanguage(String text, int limit) {
+ public String getLanguage(final String text, final int limit) {
String ret = null;
- LanguageStatistics testStat = new LanguageStatistics("text");
- char[] letter = new char[1];
+ final LanguageStatistics testStat = new LanguageStatistics("text");
+ final char[] letter = new char[1];
float letters = 0;
int upperLimit = text.length();
if (upperLimit > limit) {
@@ -98,7 +98,7 @@ public final class Identificator {
}
// create list with relevant languages
- List<Integer> relevantLanguages = new Vector <Integer>();
+ final List<Integer> relevantLanguages = new Vector <Integer>();
for (int i = 0; i < languages.size(); i++) {
// only languages that contain the most common character in the text will be tested
@@ -110,8 +110,8 @@ public final class Identificator {
if (relevantLanguages.size() > 0) {
// compare characters in text with characters in statistics
- float[] offsetList = new float[relevantLanguages.size()];
- int[] votesList = new int[relevantLanguages.size()];
+ final float[] offsetList = new float[relevantLanguages.size()];
+ final int[] votesList = new int[relevantLanguages.size()];
iter = testStat.keySet().iterator();
float minimum;
diff --git a/source/de/anomic/language/identification/LanguageFilenameFilter.java b/source/de/anomic/language/identification/LanguageFilenameFilter.java
index dce89fcd6..431c2a635 100644
--- a/source/de/anomic/language/identification/LanguageFilenameFilter.java
+++ b/source/de/anomic/language/identification/LanguageFilenameFilter.java
@@ -29,9 +29,9 @@ import java.io.FilenameFilter;
class LanguageFilenameFilter implements FilenameFilter {
- private String fileExtension = "lng";
+ private final String fileExtension = "lng";
- public boolean accept(File dir, String name) {
+ public boolean accept(final File dir, final String name) {
if (name.matches(".+\\."+fileExtension)) {
return true;
} else {
diff --git a/source/de/anomic/language/identification/LanguageStatistics.java b/source/de/anomic/language/identification/LanguageStatistics.java
index 548b30298..1f709646c 100644
--- a/source/de/anomic/language/identification/LanguageStatistics.java
+++ b/source/de/anomic/language/identification/LanguageStatistics.java
@@ -48,7 +48,7 @@ public class LanguageStatistics {
/** This map holds the character statistics of the language. */
private Map<Character, Float> stats = new HashMap<Character, Float>();
- LanguageStatistics(File file) {
+ LanguageStatistics(final File file) {
loadStatisticsFromFile(file);
}
@@ -105,7 +105,7 @@ public class LanguageStatistics {
this.stats = statistics;
}
- public final boolean loadStatisticsFromFile(File file) {
+ public final boolean loadStatisticsFromFile(final File file) {
boolean ret = true;
BufferedReader reader = null;
String line;
@@ -125,16 +125,16 @@ public class LanguageStatistics {
langName = langName.substring(0, langName.lastIndexOf("."));
}
- } catch (FileNotFoundException ex) {
+ } catch (final FileNotFoundException ex) {
ret = false;
logger.logWarning("ERROR: file '" + file.getName() + "' not found", ex);
- } catch (IOException ex) {
+ } catch (final IOException ex) {
logger.logWarning("ERROR: problems reading file '" + file.getName() + "'", ex);
} finally {
try { if(reader != null) {
reader.close();
}
- } catch (IOException ex) {
+ } catch (final IOException ex) {
logger.logWarning("ERROR: IO trouble ", ex);
}
}
@@ -146,7 +146,7 @@ public class LanguageStatistics {
* @param character the character in question
* @return true if language contains character, else false
*/
- public boolean contains(Character character) {
+ public boolean contains(final Character character) {
if (stats.containsKey(character)) {
return true;
} else {
diff --git a/source/de/anomic/language/identification/LanguageStatisticsHolder.java b/source/de/anomic/language/identification/LanguageStatisticsHolder.java
index a81d06dd1..073982c8c 100644
--- a/source/de/anomic/language/identification/LanguageStatisticsHolder.java
+++ b/source/de/anomic/language/identification/LanguageStatisticsHolder.java
@@ -37,7 +37,7 @@ public class LanguageStatisticsHolder extends Vector<LanguageStatistics> {
private static final long serialVersionUID = -887517724227204705L;
- private String languageDir = "langstats"; // directory that contains language files
+ private final String languageDir = "langstats"; // directory that contains language files
private static LanguageStatisticsHolder instance;
@@ -61,11 +61,11 @@ public class LanguageStatisticsHolder extends Vector<LanguageStatistics> {
* Reads all language files from a directory.
* @param directory the directory that contains the language files
*/
- private void addAllLanguagesInDirectory(String directory) {
+ private void addAllLanguagesInDirectory(final String directory) {
- File folder = new File(directory);
- FilenameFilter filter = new LanguageFilenameFilter();
- File[] allLanguageFiles = folder.listFiles(filter);
+ final File folder = new File(directory);
+ final FilenameFilter filter = new LanguageFilenameFilter();
+ final File[] allLanguageFiles = folder.listFiles(filter);
if (allLanguageFiles != null) {
for (int i = 0; i < allLanguageFiles.length; i++) {
diff --git a/source/de/anomic/net/ftpc.java b/source/de/anomic/net/ftpc.java
index 3d619eaab..11a299fb0 100644
--- a/source/de/anomic/net/ftpc.java
+++ b/source/de/anomic/net/ftpc.java
@@ -2358,7 +2358,7 @@ public class ftpc {
// after stream is empty we should get control completion echo
reply = receive();
- boolean success = (getStatus(reply) == 2);
+ final boolean success = (getStatus(reply) == 2);
// shutdown remote client connection
data.close();
diff --git a/source/de/anomic/net/natLib.java b/source/de/anomic/net/natLib.java
index 4a08ce89b..accd55d13 100644
--- a/source/de/anomic/net/natLib.java
+++ b/source/de/anomic/net/natLib.java
@@ -37,7 +37,7 @@ import de.anomic.tools.nxTools;
public class natLib {
- public static String getDI604(String password) {
+ public static String getDI604(final String password) {
// this pulls off the ip number from the DI-604 router/nat
/*
wget --quiet --ignore-length http://admin:<pw>@192.168.0.1:80/status.htm > /dev/null
@@ -48,9 +48,9 @@ public class natLib {
ArrayList<String> x = nxTools.strings(HttpClient.wget("http://admin:"+password+"@192.168.0.1:80/status.htm", null, 10000));
x = nxTools.grep(x, 1, "IP Address");
if ((x == null) || (x.size() == 0)) return null;
- String line = nxTools.tail1(x);
+ final String line = nxTools.tail1(x);
return nxTools.awk(nxTools.awk(line, " ", 1), ">", 2);
- } catch (Exception e) {
+ } catch (final Exception e) {
return null;
}
}
@@ -59,9 +59,9 @@ public class natLib {
try {
ArrayList<String> x = nxTools.strings(HttpClient.wget("http://www.whatismyip.com/", null, 10000));
x = nxTools.grep(x, 0, "Your IP is");
- String line = nxTools.tail1(x);
+ final String line = nxTools.tail1(x);
return nxTools.awk(line, " ", 4);
- } catch (Exception e) {
+ } catch (final Exception e) {
return null;
}
}
@@ -70,9 +70,9 @@ public class natLib {
try {
ArrayList<String> x = nxTools.strings(HttpClient.wget("http://www.slac.stanford.edu/cgi-bin/nph-traceroute.pl", null, 10000));
x = nxTools.grep(x, 0, "firewall protecting your browser");
- String line = nxTools.tail1(x);
+ final String line = nxTools.tail1(x);
return nxTools.awk(line, " ", 7);
- } catch (Exception e) {
+ } catch (final Exception e) {
return null;
}
}
@@ -81,14 +81,14 @@ public class natLib {
try {
ArrayList<String> x = nxTools.strings(HttpClient.wget("http://ipid.shat.net/", null, 10000), "UTF-8");
x = nxTools.grep(x, 2, "Your IP address");
- String line = nxTools.tail1(x);
+ final String line = nxTools.tail1(x);
return nxTools.awk(nxTools.awk(nxTools.awk(line, " ", 5), ">", 2), "<", 1);
- } catch (Exception e) {
+ } catch (final Exception e) {
return null;
}
}
- private static boolean isNotLocal(String ip) {
+ private static boolean isNotLocal(final String ip) {
if ((ip.equals("localhost")) ||
(ip.startsWith("127")) ||
(ip.startsWith("192.168")) ||
@@ -98,22 +98,22 @@ public class natLib {
return true;
}
- private static boolean isIP(String ip) {
+ private static boolean isIP(final String ip) {
if (ip == null) return false;
try {
/*InetAddress dummy =*/ InetAddress.getByName(ip);
return true;
- } catch (Exception e) {
+ } catch (final Exception e) {
return false;
}
}
//TODO: This is not IPv6 compatible
- public static boolean isProper(String ip) {
- plasmaSwitchboard sb=plasmaSwitchboard.getSwitchboard();
+ public static boolean isProper(final String ip) {
+ final plasmaSwitchboard sb=plasmaSwitchboard.getSwitchboard();
if (sb != null) {
if (sb.isRobinsonMode()) return true;
- String yacyDebugMode = sb.getConfig("yacyDebugMode", "false");
+ final String yacyDebugMode = sb.getConfig("yacyDebugMode", "false");
if (yacyDebugMode.equals("true")) {
return true;
}
@@ -127,23 +127,23 @@ public class natLib {
return (isNotLocal(ip)) && (isIP(ip));
}
- public static final InetAddress getInetAddress(String ip) {
+ public static final InetAddress getInetAddress(final String ip) {
if (ip == null) return null;
if (ip.length() < 8) return null;
- String[] ips = ip.split("\\.");
+ final String[] ips = ip.split("\\.");
if (ips.length != 4) return null;
- byte[] ipb = new byte[4];
+ final byte[] ipb = new byte[4];
try {
ipb[0] = (byte) Integer.parseInt(ips[0]);
ipb[1] = (byte) Integer.parseInt(ips[1]);
ipb[2] = (byte) Integer.parseInt(ips[2]);
ipb[3] = (byte) Integer.parseInt(ips[3]);
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
return null;
}
try {
return InetAddress.getByAddress(ipb);
- } catch (UnknownHostException e) {
+ } catch (final UnknownHostException e) {
return null;
}
}
@@ -152,7 +152,7 @@ public class natLib {
return 3;
}
- private static String retrieveFrom(int option) {
+ private static String retrieveFrom(final int option) {
if ((option < 0) || (option >= retrieveOptions())) return null;
if (option == 0) return getWhatIsMyIP();
if (option == 1) return getStanford();
@@ -160,7 +160,7 @@ public class natLib {
return null;
}
- public static String retrieveIP(boolean DI604, String password) {
+ public static String retrieveIP(final boolean DI604, final String password) {
String ip;
if (DI604) {
// first try the simple way...
@@ -181,7 +181,7 @@ public class natLib {
if (isProper(ip)) return ip;
// now go the uneasy way and ask some web responder
- disorderHeap random = new disorderHeap(retrieveOptions());
+ final disorderHeap random = new disorderHeap(retrieveOptions());
for (int i = 0; i < retrieveOptions(); i++) {
ip = retrieveFrom(random.number());
if (isProper(ip)) return ip;
@@ -199,7 +199,7 @@ public class natLib {
// listlist: http://www.aspnetimap.com/help/welcome/dnsbl.html
- public static void main(String[] args) {
+ public static void main(final String[] args) {
//System.out.println("PROBE DI604 : " + getDI604(""));
//System.out.println("PROBE whatismyip: " + getWhatIsMyIP());
//System.out.println("PROBE stanford : " + getStanford());
diff --git a/source/de/anomic/net/whois.java b/source/de/anomic/net/whois.java
index b456526aa..5928c56d6 100644
--- a/source/de/anomic/net/whois.java
+++ b/source/de/anomic/net/whois.java
@@ -28,13 +28,13 @@ import java.util.Properties;
public class whois {
- public static Properties Whois(String dom) {
+ public static Properties Whois(final String dom) {
try {
- Process p = Runtime.getRuntime().exec("whois " + dom);
- BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
+ final Process p = Runtime.getRuntime().exec("whois " + dom);
+ final BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line, key, value, oldValue;
int pos;
- Properties result = new Properties();
+ final Properties result = new Properties();
while ((line = br.readLine()) != null) {
pos = line.indexOf(":");
if (pos > 0) {
@@ -46,13 +46,13 @@ public class whois {
}
}
return result;
- } catch (IOException e) {
+ } catch (final IOException e) {
//e.printStackTrace();
return null;
}
}
- public static String evaluateWhois(Properties p) {
+ public static String evaluateWhois(final Properties p) {
String info1, info2;
info1 = p.getProperty("netname");
info2 = p.getProperty("descr");
diff --git a/source/de/anomic/plasma/cache/ResourceInfoFactory.java b/source/de/anomic/plasma/cache/ResourceInfoFactory.java
index 0188aa6e6..8bf640b4f 100644
--- a/source/de/anomic/plasma/cache/ResourceInfoFactory.java
+++ b/source/de/anomic/plasma/cache/ResourceInfoFactory.java
@@ -35,8 +35,8 @@ import de.anomic.yacy.yacyURL;
public class ResourceInfoFactory {
public IResourceInfo buildResourceInfoObj(
- yacyURL resourceURL,
- Map<String, String> resourceMetadata
+ final yacyURL resourceURL,
+ final Map<String, String> resourceMetadata
) throws UnsupportedProtocolException, IllegalAccessException {
String protocString = resourceURL.getProtocol();
@@ -65,7 +65,7 @@ public class ResourceInfoFactory {
// return the newly created object
return infoObject;
- } catch (Exception e) {
+ } catch (final Exception e) {
if (e instanceof RuntimeException) {
throw (RuntimeException)e;
} else if (e instanceof ClassNotFoundException) {
diff --git a/source/de/anomic/plasma/cache/UnsupportedProtocolException.java b/source/de/anomic/plasma/cache/UnsupportedProtocolException.java
index 3f65470a8..89f32b076 100644
--- a/source/de/anomic/plasma/cache/UnsupportedProtocolException.java
+++ b/source/de/anomic/plasma/cache/UnsupportedProtocolException.java
@@ -11,11 +11,11 @@ public class UnsupportedProtocolException extends Exception {
public static final String MESSAGE = "Unsupported protocol error: ";
- public UnsupportedProtocolException(String protocol) {
+ public UnsupportedProtocolException(final String protocol) {
super(MESSAGE + protocol);
}
- public UnsupportedProtocolException(String protocol, Throwable cause) {
+ public UnsupportedProtocolException(final String protocol, final Throwable cause) {
super(MESSAGE + protocol, cause);
}
}
diff --git a/source/de/anomic/plasma/cache/ftp/ResourceInfo.java b/source/de/anomic/plasma/cache/ftp/ResourceInfo.java
index 23ae9a517..56679e068 100644
--- a/source/de/anomic/plasma/cache/ftp/ResourceInfo.java
+++ b/source/de/anomic/plasma/cache/ftp/ResourceInfo.java
@@ -32,6 +32,7 @@ import java.util.Map;
import java.util.TreeMap;
import de.anomic.plasma.cache.IResourceInfo;
+import de.anomic.plasma.cache.ResourceInfoFactory;
import de.anomic.yacy.yacyURL;
public class ResourceInfo implements IResourceInfo {
@@ -39,15 +40,16 @@ public class ResourceInfo implements IResourceInfo {
public static final String MIMETYPE = "mimetype";
public static final String MODIFICATION_DATE = "modificationDate";
- private yacyURL objectURL, refererURL;
- private TreeMap<String, String> propertyMap;
+ private final yacyURL objectURL;
+ private yacyURL refererURL;
+ private final TreeMap<String, String> propertyMap;
/**
* Constructor used by the {@link ResourceInfoFactory}
* @param objectURL
* @param objectInfo
*/
- public ResourceInfo(yacyURL objectURL, Map<String, String> objectInfo) {
+ public ResourceInfo(final yacyURL objectURL, final Map<String, String> objectInfo) {
if (objectURL == null) throw new NullPointerException();
if (objectInfo == null) throw new NullPointerException();
@@ -59,7 +61,7 @@ public class ResourceInfo implements IResourceInfo {
this.propertyMap = new TreeMap<String, String>(objectInfo);
}
- public ResourceInfo(yacyURL objectURL, yacyURL refererUrl, String mimeType, Date fileDate) {
+ public ResourceInfo(final yacyURL objectURL, final yacyURL refererUrl, final String mimeType, final Date fileDate) {
if (objectURL == null) throw new NullPointerException();
// generating the url hash
@@ -124,7 +126,7 @@ public class ResourceInfo implements IResourceInfo {
return false;
}
- public boolean validResponseStatus(String responseStatus) {
+ public boolean validResponseStatus(final String responseStatus) {
return responseStatus != null && responseStatus.equalsIgnoreCase("OK");
}
diff --git a/source/de/anomic/plasma/cache/http/ResourceInfo.java b/source/de/anomic/plasma/cache/http/ResourceInfo.java
index 10a658a4c..0c4ec24be 100644
--- a/source/de/anomic/plasma/cache/http/ResourceInfo.java
+++ b/source/de/anomic/plasma/cache/http/ResourceInfo.java
@@ -34,12 +34,13 @@ import java.util.TreeMap;
import de.anomic.http.httpHeader;
import de.anomic.plasma.plasmaHTCache;
import de.anomic.plasma.cache.IResourceInfo;
+import de.anomic.plasma.cache.ResourceInfoFactory;
import de.anomic.server.serverDate;
import de.anomic.yacy.yacyURL;
public class ResourceInfo implements IResourceInfo {
- private yacyURL url;
- private httpHeader responseHeader;
+ private final yacyURL url;
+ private final httpHeader responseHeader;
private httpHeader requestHeader;
/**
@@ -47,7 +48,7 @@ public class ResourceInfo implements IResourceInfo {
* @param objectURL
* @param objectInfo
*/
- public ResourceInfo(yacyURL objectURL, Map<String, String> objectInfo) {
+ public ResourceInfo(final yacyURL objectURL, final Map<String, String> objectInfo) {
if (objectURL == null) throw new NullPointerException();
if (objectInfo == null) throw new NullPointerException();
@@ -58,7 +59,7 @@ public class ResourceInfo implements IResourceInfo {
this.responseHeader = new httpHeader(null, objectInfo);
}
- public ResourceInfo(yacyURL objectURL, httpHeader requestHeaders, httpHeader responseHeaders) {
+ public ResourceInfo(final yacyURL objectURL, final httpHeader requestHeaders, final httpHeader responseHeaders) {
if (objectURL == null) throw new NullPointerException();
if (responseHeaders == null) throw new NullPointerException();
@@ -82,7 +83,7 @@ public class ResourceInfo implements IResourceInfo {
String mimeType = this.responseHeader.mime();
mimeType = mimeType.trim().toLowerCase();
- int pos = mimeType.indexOf(';');
+ final int pos = mimeType.indexOf(';');
return ((pos < 0) ? mimeType : mimeType.substring(0, pos));
}
@@ -110,7 +111,7 @@ public class ResourceInfo implements IResourceInfo {
if (this.requestHeader == null) return null;
try {
return new yacyURL((String) this.requestHeader.get(httpHeader.REFERER, ""), null);
- } catch (Exception e) {
+ } catch (final Exception e) {
return null;
}
}
@@ -129,7 +130,7 @@ public class ResourceInfo implements IResourceInfo {
return this.url.hash();
}
- public void setRequestHeader(httpHeader reqestHeader) {
+ public void setRequestHeader(final httpHeader reqestHeader) {
this.requestHeader = reqestHeader;
}
@@ -137,7 +138,7 @@ public class ResourceInfo implements IResourceInfo {
* @see de.anomic.plasma.cache.IResourceInfo#shallIndexCacheForCrawler()
*/
public String shallIndexCacheForCrawler() {
- String mimeType = this.getMimeType();
+ final String mimeType = this.getMimeType();
if (plasmaHTCache.isPicture(mimeType)) { return "Media_Content_(Picture)"; }
if (!plasmaHTCache.isText(mimeType)) { return "Media_Content_(not_text)"; }
return null;
@@ -152,7 +153,7 @@ public class ResourceInfo implements IResourceInfo {
// thus we do not care about it here for indexing
// a picture cannot be indexed
- String mimeType = this.getMimeType();
+ final String mimeType = this.getMimeType();
if (plasmaHTCache.isPicture(mimeType)) {
return "Media_Content_(Picture)";
}
@@ -162,7 +163,7 @@ public class ResourceInfo implements IResourceInfo {
// -if-modified-since in request
// if the page is fresh at the very moment we can index it
- Date ifModifiedSince = getModificationDate();
+ final Date ifModifiedSince = getModificationDate();
if ((ifModifiedSince != null) && (this.responseHeader.containsKey(httpHeader.LAST_MODIFIED))) {
// parse date
Date d = this.responseHeader.lastModified();
@@ -229,7 +230,7 @@ public class ResourceInfo implements IResourceInfo {
//System.out.println("***not indexed because cache-control");
return "Stale_(expired_by_cache-control)";
}
- } catch (Exception e) {
+ } catch (final Exception e) {
return "Error_(" + e.getMessage() + ")";
}
}
@@ -283,15 +284,15 @@ public class ResourceInfo implements IResourceInfo {
cacheControl = cacheControl.trim().toUpperCase();
if (cacheControl.startsWith("MAX-AGE=")) {
// we need also the load date
- Date date = this.responseHeader.date();
+ final Date date = this.responseHeader.date();
if (date == null) return "stale_no_date_given_in_response";
try {
- long ttl = 1000 * Long.parseLong(cacheControl.substring(8)); // milliseconds to live
+ final long ttl = 1000 * Long.parseLong(cacheControl.substring(8)); // milliseconds to live
if (serverDate.correctedUTCTime() - date.getTime() > ttl) {
//System.out.println("***not indexed because cache-control");
return "stale_expired";
}
- } catch (Exception e) {
+ } catch (final Exception e) {
return "stale_error_" + e.getMessage() + ")";
}
}
@@ -336,7 +337,7 @@ public class ResourceInfo implements IResourceInfo {
if (d2.after(d1)) { return false; }
}
- String mimeType = this.getMimeType();
+ final String mimeType = this.getMimeType();
if (!plasmaHTCache.isPicture(mimeType)) {
// -cookies in request
// unfortunately, we should reload in case of a cookie
@@ -368,12 +369,12 @@ public class ResourceInfo implements IResourceInfo {
// -expires in cached response
// the expires value gives us a very easy hint when the cache is stale
- Date expires = this.responseHeader.expires();
+ final Date expires = this.responseHeader.expires();
if (expires != null) {
// System.out.println("EXPIRES-TEST: expires=" + expires + ", NOW=" + serverDate.correctedGMTDate() + ", url=" + url);
if (expires.before(new Date(serverDate.correctedUTCTime()))) { return false; }
}
- Date lastModified = this.responseHeader.lastModified();
+ final Date lastModified = this.responseHeader.lastModified();
cacheControl = this.responseHeader.get(httpHeader.CACHE_CONTROL);
if (cacheControl == null && lastModified == null && expires == null) { return false; }
@@ -386,7 +387,7 @@ public class ResourceInfo implements IResourceInfo {
Date date = this.responseHeader.date();
if (lastModified != null) {
if (date == null) { date = new Date(serverDate.correctedUTCTime()); }
- long age = date.getTime() - lastModified.getTime();
+ final long age = date.getTime() - lastModified.getTime();
if (age < 0) { return false; }
// TTL (Time-To-Live) is age/10 = (d2.getTime() - d1.getTime()) / 10
// the actual living-time is serverDate.correctedGMTDate().getTime() - d2.getTime()
@@ -413,7 +414,7 @@ public class ResourceInfo implements IResourceInfo {
if (serverDate.correctedUTCTime() - date.getTime() > ttl) {
return false;
}
- } catch (Exception e) {
+ } catch (final Exception e) {
return false;
}
}
@@ -421,7 +422,7 @@ public class ResourceInfo implements IResourceInfo {
return true;
}
- public boolean validResponseStatus(String responseStatus) {
+ public boolean validResponseStatus(final String responseStatus) {
return responseStatus.startsWith("200") ||
responseStatus.startsWith("203");
}
diff --git a/source/de/anomic/plasma/parser/AbstractParser.java b/source/de/anomic/plasma/parser/AbstractParser.java
index c595f0faf..ec7df67a5 100644
--- a/source/de/anomic/plasma/parser/AbstractParser.java
+++ b/source/de/anomic/plasma/parser/AbstractParser.java
@@ -77,7 +77,7 @@ public abstract class AbstractParser implements Parser{
/**
* The Constructor of this class.
*/
- public AbstractParser(String[] libxDependencies) {
+ public AbstractParser(final String[] libxDependencies) {
super();
this.libxDependencies = libxDependencies;
}
@@ -87,7 +87,7 @@ public abstract class AbstractParser implements Parser{
* This value is needed by some parsers to decide
* if the parsed text could be hold in memory
*/
- public void setContentLength(long length) {
+ public void setContentLength(final long length) {
this.contentLength = length;
}
@@ -96,12 +96,12 @@ public abstract class AbstractParser implements Parser{
* @throws InterruptedException if the parser was interrupted
*/
public static final void checkInterruption() throws InterruptedException {
- Thread currentThread = Thread.currentThread();
+ final Thread currentThread = Thread.currentThread();
if ((currentThread instanceof serverThread) && ((serverThread)currentThread).shutdownInProgress()) throw new InterruptedException("Shutdown in progress ...");
if (currentThread.isInterrupted()) throw new InterruptedException("Shutdown in progress ...");
}
- public final File createTempFile(String name) throws IOException {
+ public final File createTempFile(final String name) throws IOException {
String parserClassName = this.getClass().getName();
int idx = parserClassName.lastIndexOf(".");
if (idx != -1) {
@@ -110,35 +110,35 @@ public abstract class AbstractParser implements Parser{
// getting the file extension
idx = name.lastIndexOf("/");
- String fileName = (idx != -1) ? name.substring(idx+1) : name;
+ final String fileName = (idx != -1) ? name.substring(idx+1) : name;
idx = fileName.lastIndexOf(".");
- String fileExt = (idx > -1) ? fileName.substring(idx+1) : "";
+ final String fileExt = (idx > -1) ? fileName.substring(idx+1) : "";
// creates the temp file
- File tempFile = File.createTempFile(parserClassName + "_" + ((idx>-1)?fileName.substring(0,idx):fileName), (fileExt.length()>0)?"."+fileExt:fileExt);
+ final File tempFile = File.createTempFile(parserClassName + "_" + ((idx>-1)?fileName.substring(0,idx):fileName), (fileExt.length()>0)?"."+fileExt:fileExt);
return tempFile;
}
- public int parseDir(yacyURL location, String prefix, File dir, plasmaParserDocument doc)
+ public int parseDir(final yacyURL location, final String prefix, final File dir, final plasmaParserDocument doc)
throws ParserException, InterruptedException, IOException {
if (!dir.isDirectory())
throw new ParserException("tried to parse ordinary file " + dir + " as directory", location);
- String[] files = dir.list();
+ final String[] files = dir.list();
int result = 0;
for (int i=0; i<files.length; i++) {
checkInterruption();
- File file = new File(dir, files[i]);
+ 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 {
- yacyURL url = yacyURL.newURL(location, "/" + prefix + "/"
+ final yacyURL url = yacyURL.newURL(location, "/" + prefix + "/"
// XXX: workaround for relative paths within document
+ file.getPath().substring(file.getPath().indexOf(File.separatorChar) + 1)
+ "/" + file.getName());
- plasmaParserDocument subdoc = new plasmaParser().parseSource(
+ final plasmaParserDocument subdoc = new plasmaParser().parseSource(
url,
plasmaParser.getMimeTypeByFileExt(files[i].substring(files[i].indexOf('.') + 1)),
null, file);
@@ -146,7 +146,7 @@ public abstract class AbstractParser implements Parser{
doc.addSubDocument(subdoc);
subdoc.close();
result++;
- } catch (ParserException e) {
+ } catch (final ParserException e) {
this.theLogger.logInfo("unable to parse file " + file + " in " + location + ", skipping");
}
}
@@ -166,10 +166,10 @@ public abstract class AbstractParser implements Parser{
* @see de.anomic.plasma.parser.Parser#parse(de.anomic.net.URL, java.lang.String, byte[])
*/
public plasmaParserDocument parse(
- yacyURL location,
- String mimeType,
- String charset,
- byte[] source
+ final yacyURL location,
+ final String mimeType,
+ final String charset,
+ final byte[] source
) throws ParserException, InterruptedException {
ByteArrayInputStream contentInputStream = null;
try {
@@ -183,7 +183,7 @@ public abstract class AbstractParser implements Parser{
try {
contentInputStream.close();
contentInputStream = null;
- } catch (Exception e){ /* ignore this */}
+ } catch (final Exception e){ /* ignore this */}
}
}
}
@@ -201,10 +201,10 @@ public abstract class AbstractParser implements Parser{
* @see de.anomic.plasma.parser.Parser#parse(de.anomic.net.URL, java.lang.String, java.io.File)
*/
public plasmaParserDocument parse(
- yacyURL location,
- String mimeType,
- String charset,
- File sourceFile
+ final yacyURL location,
+ final String mimeType,
+ final String charset,
+ final File sourceFile
) throws ParserException, InterruptedException {
BufferedInputStream contentInputStream = null;
try {
@@ -216,10 +216,10 @@ public abstract class AbstractParser implements Parser{
// parse the stream
return this.parse(location, mimeType, charset, contentInputStream);
- } catch (FileNotFoundException e) {
+ } catch (final FileNotFoundException e) {
throw new ParserException("Unexpected error while parsing file. " + e.getMessage(),location);
} finally {
- if (contentInputStream != null) try{contentInputStream.close();}catch(Exception e){/* ignore this */}
+ if (contentInputStream != null) try{contentInputStream.close();}catch(final Exception e){/* ignore this */}
}
}
@@ -248,7 +248,7 @@ public abstract class AbstractParser implements Parser{
/**
* Setting the logger that should be used by this parser class ...
*/
- public void setLogger(serverLog log) {
+ public void setLogger(final serverLog log) {
this.theLogger = log;
}
diff --git a/source/de/anomic/plasma/parser/ParserException.java b/source/de/anomic/plasma/parser/ParserException.java
index 940bae023..c2ed6e4ef 100644
--- a/source/de/anomic/plasma/parser/ParserException.java
+++ b/source/de/anomic/plasma/parser/ParserException.java
@@ -38,21 +38,21 @@ public class ParserException extends Exception
super();
}
- public ParserException(String message, yacyURL url) {
+ public ParserException(final String message, final yacyURL url) {
this(message,url,ErrorURL.DENIED_PARSER_ERROR);
}
- public ParserException(String message, yacyURL url, String errorCode) {
+ public ParserException(final String message, final yacyURL url, final String errorCode) {
super(message);
this.errorCode = errorCode;
this.url = url;
}
- public ParserException(String message, yacyURL url, Throwable cause) {
+ public ParserException(final String message, final yacyURL url, final Throwable cause) {
this(message,url,cause,ErrorURL.DENIED_PARSER_ERROR);
}
- public ParserException(String message, yacyURL url, Throwable cause, String errorCode) {
+ public ParserException(final String message, final yacyURL url, final Throwable cause, final String errorCode) {
super(message, cause);
this.errorCode = errorCode;
this.url = url;
diff --git a/source/de/anomic/plasma/parser/ParserInfo.java b/source/de/anomic/plasma/parser/ParserInfo.java
index 13143e074..2a51c5d38 100644
--- a/source/de/anomic/plasma/parser/ParserInfo.java
+++ b/source/de/anomic/plasma/parser/ParserInfo.java
@@ -18,7 +18,7 @@ public class ParserInfo {
public int usageCount = 0;
public String toString() {
- StringBuffer toStr = new StringBuffer();
+ final StringBuffer toStr = new StringBuffer();
toStr.append(this.parserName).append(" V")
.append((this.parserVersionNr==null)?"0.0":this.parserVersionNr).append(" | ")
diff --git a/source/de/anomic/plasma/parser/bzip/bzipParser.java b/source/de/anomic/plasma/parser/bzip/bzipParser.java
index d40390365..88d657cdf 100644
--- a/source/de/anomic/plasma/parser/bzip/bzipParser.java
+++ b/source/de/anomic/plasma/parser/bzip/bzipParser.java
@@ -69,7 +69,7 @@ public class bzipParser extends AbstractParser implements Parser {
return SUPPORTED_MIME_TYPES;
}
- public plasmaParserDocument parse(yacyURL location, String mimeType, String charset, InputStream source) throws ParserException, InterruptedException {
+ public plasmaParserDocument parse(final yacyURL location, final String mimeType, final String charset, final InputStream source) throws ParserException, InterruptedException {
File tempFile = null;
try {
@@ -87,14 +87,14 @@ public class bzipParser extends AbstractParser implements Parser {
}
int read = 0;
- byte[] data = new byte[1024];
- CBZip2InputStream zippedContent = new CBZip2InputStream(source);
+ final byte[] data = new byte[1024];
+ final CBZip2InputStream zippedContent = new CBZip2InputStream(source);
tempFile = File.createTempFile("bunzip","tmp");
tempFile.deleteOnExit();
// creating a temp file to store the uncompressed data
- FileOutputStream out = new FileOutputStream(tempFile);
+ final FileOutputStream out = new FileOutputStream(tempFile);
// reading gzip file and store it uncompressed
while((read = zippedContent.read(data, 0, 1024)) != -1) {
@@ -107,9 +107,9 @@ public class bzipParser extends AbstractParser implements Parser {
checkInterruption();
// creating a new parser class to parse the unzipped content
- plasmaParser theParser = new plasmaParser();
+ final plasmaParser theParser = new plasmaParser();
return theParser.parseSource(location,null,null,tempFile);
- } catch (Exception e) {
+ } catch (final Exception e) {
if (e instanceof InterruptedException) throw (InterruptedException) e;
if (e instanceof ParserException) throw (ParserException) e;
diff --git a/source/de/anomic/plasma/parser/doc/docParser.java b/source/de/anomic/plasma/parser/doc/docParser.java
index 0c27bcd4f..ef1590977 100644
--- a/source/de/anomic/plasma/parser/doc/docParser.java
+++ b/source/de/anomic/plasma/parser/doc/docParser.java
@@ -57,15 +57,15 @@ public class docParser extends AbstractParser implements Parser {
this.parserName = "Word Document Parser";
}
- public plasmaParserDocument parse(yacyURL location, String mimeType, String charset,
- InputStream source) throws ParserException, InterruptedException {
+ public plasmaParserDocument parse(final yacyURL location, final String mimeType, final String charset,
+ final InputStream source) throws ParserException, InterruptedException {
try {
- WordExtractor extractor = new WordExtractor();
- String contents = extractor.extractText(source);
+ final WordExtractor extractor = new WordExtractor();
+ final String contents = extractor.extractText(source);
- plasmaParserDocument theDoc = new plasmaParserDocument(
+ final plasmaParserDocument theDoc = new plasmaParserDocument(
location,
mimeType,
"UTF-8",
@@ -83,7 +83,7 @@ public class docParser extends AbstractParser implements Parser {
null);
return theDoc;
- } catch (Exception e) {
+ } catch (final Exception e) {
if (e instanceof InterruptedException) throw (InterruptedException) e;
if (e instanceof ParserException) throw (ParserException) e;
diff --git a/source/de/anomic/plasma/parser/gzip/gzipParser.java b/source/de/anomic/plasma/parser/gzip/gzipParser.java
index 8bbcd368d..9fe2fef6d 100644
--- a/source/de/anomic/plasma/parser/gzip/gzipParser.java
+++ b/source/de/anomic/plasma/parser/gzip/gzipParser.java
@@ -64,20 +64,20 @@ public class gzipParser extends AbstractParser implements Parser {
return SUPPORTED_MIME_TYPES;
}
- public plasmaParserDocument parse(yacyURL location, String mimeType, String charset, InputStream source) throws ParserException, InterruptedException {
+ public plasmaParserDocument parse(final yacyURL location, final String mimeType, final String charset, final InputStream source) throws ParserException, InterruptedException {
File tempFile = null;
try {
int read = 0;
- byte[] data = new byte[1024];
+ final byte[] data = new byte[1024];
- GZIPInputStream zippedContent = new GZIPInputStream(source);
+ final GZIPInputStream zippedContent = new GZIPInputStream(source);
tempFile = File.createTempFile("gunzip","tmp");
tempFile.deleteOnExit();
// creating a temp file to store the uncompressed data
- FileOutputStream out = new FileOutputStream(tempFile);
+ final FileOutputStream out = new FileOutputStream(tempFile);
// reading gzip file and store it uncompressed
while((read = zippedContent.read(data, 0, 1024)) != -1) {
@@ -90,9 +90,9 @@ public class gzipParser extends AbstractParser implements Parser {
checkInterruption();
// creating a new parser class to parse the unzipped content
- plasmaParser theParser = new plasmaParser();
+ final plasmaParser theParser = new plasmaParser();
return theParser.parseSource(location,null,null,tempFile);
- } catch (Exception e) {
+ } catch (final Exception e) {
if (e instanceof InterruptedException) throw (InterruptedException) e;
if (e instanceof ParserException) throw (ParserException) e;
diff --git a/source/de/anomic/plasma/parser/mimeType/mimeTypeParser.java b/source/de/anomic/plasma/parser/mimeType/mimeTypeParser.java
index fe3de0df3..18843c41b 100644
--- a/source/de/anomic/plasma/parser/mimeType/mimeTypeParser.java
+++ b/source/de/anomic/plasma/parser/mimeType/mimeTypeParser.java
@@ -85,15 +85,15 @@ public class mimeTypeParser extends AbstractParser implements Parser {
}
@SuppressWarnings("unchecked")
- public String getMimeType (File sourceFile) {
+ public String getMimeType (final File sourceFile) {
String mimeType = null;
try {
- MagicMatch match = Magic.getMagicMatch(sourceFile,true);
+ final MagicMatch match = Magic.getMagicMatch(sourceFile,true);
// if a match was found we can return the new mimeType
if (match!=null) {
- Collection<MagicMatch> subMatches = match.getSubMatches();
+ final Collection<MagicMatch> subMatches = match.getSubMatches();
if ((subMatches != null) && (!subMatches.isEmpty())) {
mimeType = subMatches.iterator().next().getMimeType();
} else {
@@ -101,16 +101,16 @@ public class mimeTypeParser extends AbstractParser implements Parser {
}
return mimeType;
}
- } catch (Exception e) {
+ } catch (final Exception e) {
/* ignore this */
}
return null;
}
@SuppressWarnings("unchecked")
- public plasmaParserDocument parse(yacyURL location, String mimeType, String charset, File sourceFile) throws ParserException, InterruptedException {
+ public plasmaParserDocument parse(final yacyURL location, String mimeType, final String charset, final File sourceFile) throws ParserException, InterruptedException {
- String orgMimeType = mimeType;
+ final String orgMimeType = mimeType;
// determining the mime type of the file ...
try {
@@ -125,14 +125,14 @@ public class mimeTypeParser extends AbstractParser implements Parser {
threadLoopDetection.put(Thread.currentThread(),new Integer(loopDepth.intValue()+1));
// deactivating the logging for jMimeMagic
- Logger jmimeMagicLogger = Logger.getLogger("net.sf.jmimemagic");
+ final Logger jmimeMagicLogger = Logger.getLogger("net.sf.jmimemagic");
jmimeMagicLogger.setLevel(Level.OFF);
- MagicMatch match = Magic.getMagicMatch(sourceFile,true,false);
+ final MagicMatch match = Magic.getMagicMatch(sourceFile,true,false);
// if a match was found we can return the new mimeType
if (match!=null) {
- Collection<MagicMatch> subMatches = match.getSubMatches();
+ final Collection<MagicMatch> subMatches = match.getSubMatches();
if ((subMatches != null) && (!subMatches.isEmpty())) {
mimeType = subMatches.iterator().next().getMimeType();
if ((mimeType == null)||(mimeType.length() == 0)) mimeType = match.getMimeType();
@@ -148,19 +148,19 @@ public class mimeTypeParser extends AbstractParser implements Parser {
checkInterruption();
// parsing the content using the determined mimetype
- plasmaParser theParser = new plasmaParser();
+ final plasmaParser theParser = new plasmaParser();
return theParser.parseSource(location,mimeType,charset,sourceFile);
}
throw new ParserException("Unable to detect mimetype of resource (3).",location);
- } catch (MagicMatchNotFoundException e) {
+ } catch (final MagicMatchNotFoundException e) {
throw new ParserException("Unable to detect mimetype of resource (4).",location);
- } catch (Exception e) {
+ } catch (final Exception e) {
if (e instanceof InterruptedException) throw (InterruptedException) e;
if (e instanceof ParserException) throw (ParserException) e;
throw new ParserException("Unexpected error while detect mimetype of resource. " + e.getMessage(),location);
} finally {
- Integer loopDepth = threadLoopDetection.get(Thread.currentThread());
+ final Integer loopDepth = threadLoopDetection.get(Thread.currentThread());
if (loopDepth.intValue() <= 1) {
threadLoopDetection.remove(Thread.currentThread());
} else {
@@ -169,13 +169,13 @@ public class mimeTypeParser extends AbstractParser implements Parser {
}
}
- public plasmaParserDocument parse(yacyURL location, String mimeType,String charset, InputStream source) throws ParserException, InterruptedException {
+ public plasmaParserDocument parse(final yacyURL location, final String mimeType,final String charset, final InputStream source) throws ParserException, InterruptedException {
File dstFile = null;
try {
dstFile = File.createTempFile("mimeTypeParser",".tmp");
serverFileUtils.copy(source,dstFile);
return parse(location,mimeType,charset,dstFile);
- } catch (IOException e) {
+ } catch (final IOException e) {
throw new ParserException("Unexpected error while detect mimetype of resource. " + e.getMessage(),location);
} finally {
if (dstFile != null) {dstFile.delete();}
diff --git a/source/de/anomic/plasma/parser/mimeType/odtDetector.java b/source/de/anomic/plasma/parser/mimeType/odtDetector.java
index cf5bf3fc5..01c23e806 100644
--- a/source/de/anomic/plasma/parser/mimeType/odtDetector.java
+++ b/source/de/anomic/plasma/parser/mimeType/odtDetector.java
@@ -57,13 +57,13 @@ public class odtDetector implements MagicDetector {
}
@SuppressWarnings("unchecked")
- public String[] process(byte[] data, int offset, int length, long bitmask, char comparator, String mimeType, Map params) {
+ public String[] process(final byte[] data, final int offset, final int length, final long bitmask, final char comparator, final String mimeType, final Map params) {
File dstFile = null;
try {
dstFile = File.createTempFile("mimeTypeParser",".tmp");
serverFileUtils.copy(data,dstFile);
return process(dstFile, offset, length, bitmask, comparator, mimeType, params);
- } catch (IOException e) {
+ } catch (final IOException e) {
return null;
} finally {
if (dstFile != null) {dstFile.delete();}
@@ -71,21 +71,21 @@ public class odtDetector implements MagicDetector {
}
@SuppressWarnings("unchecked")
- public String[] process(File file, int offset, int length, long bitmask, char comparator, String mimeType, Map params) {
+ public String[] process(final File file, final int offset, final int length, final long bitmask, final char comparator, final String mimeType, final Map params) {
try {
// opening the zip file
- ZipFile zipFile = new ZipFile(file);
+ final ZipFile zipFile = new ZipFile(file);
// searching for a file named mimetype
- ZipEntry mimeTypeInfo = zipFile.getEntry("mimetype");
+ final ZipEntry mimeTypeInfo = zipFile.getEntry("mimetype");
if (mimeTypeInfo == null) return null;
// read in the content of the file
- InputStream zippedContent = zipFile.getInputStream(mimeTypeInfo);
- String realMimeType = new String(serverFileUtils.read(zippedContent, mimeTypeInfo.getSize()));
+ final InputStream zippedContent = zipFile.getInputStream(mimeTypeInfo);
+ final String realMimeType = new String(serverFileUtils.read(zippedContent, mimeTypeInfo.getSize()));
return new String[]{realMimeType};
- } catch (Exception e) {
+ } catch (final Exception e) {
return null;
}
diff --git a/source/de/anomic/plasma/parser/mimeType/rssDetector.java b/source/de/anomic/plasma/parser/mimeType/rssDetector.java
index ce22f9dba..1806cb99c 100644
--- a/source/de/anomic/plasma/parser/mimeType/rssDetector.java
+++ b/source/de/anomic/plasma/parser/mimeType/rssDetector.java
@@ -55,25 +55,25 @@ public class rssDetector implements MagicDetector {
}
@SuppressWarnings("unchecked")
- public String[] process(File file, int offset, int length, long bitmask, char comparator, String mimeType, Map params) {
+ public String[] process(final File file, final int offset, final int length, final long bitmask, final char comparator, final String mimeType, final Map params) {
FileInputStream fileInput = null;
try {
fileInput = new FileInputStream(file);
return detect(fileInput);
- } catch (Exception e) {
+ } catch (final Exception e) {
return null;
} finally {
- if (fileInput != null) try { fileInput.close(); } catch (Exception e) { /* ignore this */ }
+ if (fileInput != null) try { fileInput.close(); } catch (final Exception e) { /* ignore this */ }
}
}
@SuppressWarnings("unchecked")
- public String[] process(byte[] data, int offset, int length, long bitmask, char comparator, String mimeType, Map params) {
- ByteArrayInputStream input = new ByteArrayInputStream(data);
+ public String[] process(final byte[] data, final int offset, final int length, final long bitmask, final char comparator, final String mimeType, final Map params) {
+ final ByteArrayInputStream input = new ByteArrayInputStream(data);
return detect(input);
}
- private String[] detect(InputStream input) {
+ private String[] detect(final InputStream input) {
return new String[]{"application/rss+xml"};
}
diff --git a/source/de/anomic/plasma/parser/odt/odtParser.java b/source/de/anomic/plasma/parser/odt/odtParser.java
index 77454e51e..fe2603c32 100644
--- a/source/de/anomic/plasma/parser/odt/odtParser.java
+++ b/source/de/anomic/plasma/parser/odt/odtParser.java
@@ -78,7 +78,7 @@ public class odtParser extends AbstractParser implements Parser {
return SUPPORTED_MIME_TYPES;
}
- public plasmaParserDocument parse(yacyURL location, String mimeType, String charset, File dest) throws ParserException, InterruptedException {
+ public plasmaParserDocument parse(final yacyURL location, final String mimeType, final String charset, final File dest) throws ParserException, InterruptedException {
Writer writer = null;
File writerFile = null;
@@ -90,8 +90,8 @@ public class odtParser extends AbstractParser implements Parser {
String docAuthor = null;
// opening the file as zip file
- ZipFile zipFile= new ZipFile(dest);
- Enumeration<? extends ZipEntry> zipEnum = zipFile.entries();
+ final ZipFile zipFile= new ZipFile(dest);
+ final Enumeration<? extends ZipEntry> zipEnum = zipFile.entries();
// looping through all containing files
while (zipEnum.hasMoreElements()) {
@@ -99,12 +99,12 @@ public class odtParser extends AbstractParser implements Parser {
checkInterruption();
// getting the next zip file entry
- ZipEntry zipEntry= zipEnum.nextElement();
- String entryName = zipEntry.getName();
+ final ZipEntry zipEntry= zipEnum.nextElement();
+ final String entryName = zipEntry.getName();
// content.xml contains the document content in xml format
if (entryName.equals("content.xml")) {
- long contentSize = zipEntry.getSize();
+ final long contentSize = zipEntry.getSize();
// creating a writer for output
if ((contentSize == -1) || (contentSize > Parser.MAX_KEEP_IN_MEMORY_SIZE)) {
@@ -115,8 +115,8 @@ public class odtParser extends AbstractParser implements Parser {
}
// extract data
- InputStream zipFileEntryStream = zipFile.getInputStream(zipEntry);
- OpenDocumentTextInputStream odStream = new OpenDocumentTextInputStream(zipFileEntryStream);
+ final InputStream zipFileEntryStream = zipFile.getInputStream(zipEntry);
+ final OpenDocumentTextInputStream odStream = new OpenDocumentTextInputStream(zipFileEntryStream);
serverFileUtils.copy(odStream, writer, "UTF-8");
// close readers and writers
@@ -125,9 +125,9 @@ public class odtParser extends AbstractParser implements Parser {
} else if (entryName.equals("meta.xml")) {
// meta.xml contains metadata about the document
- InputStream zipFileEntryStream = zipFile.getInputStream(zipEntry);
- ODFMetaFileAnalyzer metaAnalyzer = new ODFMetaFileAnalyzer();
- OpenDocumentMetadata metaData = metaAnalyzer.analyzeMetaData(zipFileEntryStream);
+ final InputStream zipFileEntryStream = zipFile.getInputStream(zipEntry);
+ final ODFMetaFileAnalyzer metaAnalyzer = new ODFMetaFileAnalyzer();
+ final OpenDocumentMetadata metaData = metaAnalyzer.analyzeMetaData(zipFileEntryStream);
docDescription = metaData.getDescription();
docKeywordStr = metaData.getKeyword();
docShortTitle = metaData.getTitle();
@@ -150,7 +150,7 @@ public class odtParser extends AbstractParser implements Parser {
// create the parser document
plasmaParserDocument theDoc = null;
if (writer instanceof serverCharBuffer) {
- byte[] contentBytes = ((serverCharBuffer)writer).toString().getBytes("UTF-8");
+ final byte[] contentBytes = ((serverCharBuffer)writer).toString().getBytes("UTF-8");
theDoc = new plasmaParserDocument(
location,
mimeType,
@@ -178,21 +178,21 @@ public class odtParser extends AbstractParser implements Parser {
null);
}
return theDoc;
- } catch (Exception e) {
+ } catch (final Exception e) {
if (e instanceof InterruptedException) throw (InterruptedException) e;
if (e instanceof ParserException) throw (ParserException) e;
// close the writer
- if (writer != null) try { writer.close(); } catch (Exception ex) {/* ignore this */}
+ if (writer != null) try { writer.close(); } catch (final Exception ex) {/* ignore this */}
// delete the file
- if (writerFile != null) try { writerFile.delete(); } catch (Exception ex) {/* ignore this */}
+ if (writerFile != null) try { writerFile.delete(); } catch (final Exception ex) {/* ignore this */}
throw new ParserException("Unexpected error while parsing odt file. " + e.getMessage(),location);
}
}
- public plasmaParserDocument parse(yacyURL location, String mimeType, String charset, InputStream source) throws ParserException, InterruptedException {
+ public plasmaParserDocument parse(final yacyURL location, final String mimeType, final String charset, final InputStream source) throws ParserException, InterruptedException {
File dest = null;
try {
// creating a tempfile
@@ -204,13 +204,13 @@ public class odtParser extends AbstractParser implements Parser {
// parsing the content
return parse(location, mimeType, charset, dest);
- } catch (Exception e) {
+ } catch (final Exception e) {
if (e instanceof InterruptedException) throw (InterruptedException) e;
if (e instanceof ParserException) throw (ParserException) e;
throw new ParserException("Unexpected error while parsing odt file. " + e.getMessage(),location);
} finally {
- if (dest != null) try { dest.delete(); } catch (Exception e){/* ignore this */}
+ if (dest != null) try { dest.delete(); } catch (final Exception e){/* ignore this */}
}
}
@@ -219,28 +219,28 @@ public class odtParser extends AbstractParser implements Parser {
super.reset();
}
- public static void main(String[] args) {
+ public static void main(final String[] args) {
try {
if (args.length != 1) return;
// getting the content URL
- yacyURL contentUrl = new yacyURL(args[0], null);
+ final yacyURL contentUrl = new yacyURL(args[0], null);
// creating a new parser
- odtParser testParser = new odtParser();
+ final odtParser testParser = new odtParser();
// setting the parser logger
testParser.setLogger(new serverLog("PARSER.ODT"));
// downloading the document content
- httpHeader reqHeader = new httpHeader();
+ final httpHeader reqHeader = new httpHeader();
reqHeader.put(httpHeader.USER_AGENT, HTTPLoader.crawlerUserAgent);
- byte[] content = HttpClient.wget(contentUrl.toString(), reqHeader, 10000);
- ByteArrayInputStream input = new ByteArrayInputStream(content);
+ final byte[] content = HttpClient.wget(contentUrl.toString(), reqHeader, 10000);
+ final ByteArrayInputStream input = new ByteArrayInputStream(content);
// parsing the document
testParser.parse(contentUrl, "application/vnd.oasis.opendocument.text", null, input);
- } catch (Exception e) {
+ } catch (final Exception e) {
e.printStackTrace();
}
}
diff --git a/source/de/anomic/plasma/parser/pdf/pdfParser.java b/source/de/anomic/plasma/parser/pdf/pdfParser.java
index 7f5827cef..822522b1d 100644
--- a/source/de/anomic/plasma/parser/pdf/pdfParser.java
+++ b/source/de/anomic/plasma/parser/pdf/pdfParser.java
@@ -74,7 +74,7 @@ public class pdfParser extends AbstractParser implements Parser {
return SUPPORTED_MIME_TYPES;
}
- public plasmaParserDocument parse(yacyURL location, String mimeType, String charset, InputStream source) throws ParserException, InterruptedException {
+ public plasmaParserDocument parse(final yacyURL location, final String mimeType, final String charset, final InputStream source) throws ParserException, InterruptedException {
PDDocument theDocument = null;
Writer writer = null;
@@ -93,14 +93,14 @@ public class pdfParser extends AbstractParser implements Parser {
checkInterruption();
// creating a pdf parser
- PDFParser parser = new PDFParser(source);
+ final PDFParser parser = new PDFParser(source);
parser.parse();
// check for interruption
checkInterruption();
// creating a text stripper
- PDFTextStripper stripper = new PDFTextStripper();
+ final PDFTextStripper stripper = new PDFTextStripper();
theDocument = parser.getPDDocument();
if (theDocument.isEncrypted()) {
@@ -111,7 +111,7 @@ public class pdfParser extends AbstractParser implements Parser {
}
// extracting some metadata
- PDDocumentInformation theDocInfo = theDocument.getDocumentInformation();
+ final PDDocumentInformation theDocInfo = theDocument.getDocumentInformation();
if (theDocInfo != null) {
docTitle = theDocInfo.getTitle();
docSubject = theDocInfo.getSubject();
@@ -138,7 +138,7 @@ public class pdfParser extends AbstractParser implements Parser {
plasmaParserDocument theDoc = null;
if (writer instanceof serverCharBuffer) {
- byte[] contentBytes = ((serverCharBuffer)writer).toString().getBytes("UTF-8");
+ final byte[] contentBytes = ((serverCharBuffer)writer).toString().getBytes("UTF-8");
theDoc = new plasmaParserDocument(
location,
mimeType,
@@ -168,21 +168,21 @@ public class pdfParser extends AbstractParser implements Parser {
return theDoc;
}
- catch (Exception e) {
+ catch (final Exception e) {
if (e instanceof InterruptedException) throw (InterruptedException) e;
if (e instanceof ParserException) throw (ParserException) e;
// close the writer
- if (writer != null) try { writer.close(); } catch (Exception ex) {/* ignore this */}
+ if (writer != null) try { writer.close(); } catch (final Exception ex) {/* ignore this */}
// delete the file
- if (writerFile != null) try { writerFile.delete(); } catch (Exception ex) {/* ignore this */}
+ if (writerFile != null) try { writerFile.delete(); } catch (final Exception ex) {/* ignore this */}
e.printStackTrace();
throw new ParserException("Unexpected error while parsing pdf file. " + e.getMessage(),location);
} finally {
- if (theDocument != null) try { theDocument.close(); } catch (Exception e) {/* ignore this */}
- if (writer != null) try { writer.close(); } catch (Exception e) {/* ignore this */}
+ if (theDocument != null) try { theDocument.close(); } catch (final Exception e) {/* ignore this */}
+ if (writer != null) try { writer.close(); } catch (final Exception e) {/* ignore this */}
Thread.currentThread().setPriority(Thread.NORM_PRIORITY);
}
}
@@ -196,7 +196,7 @@ public class pdfParser extends AbstractParser implements Parser {
* test
* @param args
*/
- public static void main(String[] args) {
+ public static void main(final String[] args) {
if(args.length > 0 && args[0].length() > 0) {
// file
final File pdfFile = new File(args[0]);
@@ -211,13 +211,13 @@ public class pdfParser extends AbstractParser implements Parser {
try {
document = parser.parse(null, "application/pdf", null, pdfFile);
- } catch (ParserException e) {
+ } catch (final ParserException e) {
System.err.println("Cannot parse file "+ pdfFile.getAbsolutePath());
e.printStackTrace();
- } catch (InterruptedException e) {
+ } catch (final InterruptedException e) {
System.err.println("Interrupted while parsing!");
e.printStackTrace();
- } catch (NoClassDefFoundError e) {
+ } catch (final NoClassDefFoundError e) {
System.err.println("class not found: " + e.getMessage());
}
@@ -232,7 +232,7 @@ public class pdfParser extends AbstractParser implements Parser {
try {
// write file
serverFileUtils.copy(document.getText(), new File("parsedPdf.txt"));
- } catch (IOException e) {
+ } catch (final IOException e) {
System.err.println("error saving parsed document");
e.printStackTrace();
}
diff --git a/source/de/anomic/plasma/parser/ppt/pptParser.java b/source/de/anomic/plasma/parser/ppt/pptParser.java
index 5e65a40c6..95a2baf7d 100644
--- a/source/de/anomic/plasma/parser/ppt/pptParser.java
+++ b/source/de/anomic/plasma/parser/ppt/pptParser.java
@@ -68,22 +68,22 @@ public class pptParser extends AbstractParser implements Parser {
* parses the source documents and returns a plasmaParserDocument containing
* all extracted information about the parsed document
*/
- public plasmaParserDocument parse(yacyURL location, String mimeType,
- String charset, InputStream source) throws ParserException,
+ public plasmaParserDocument parse(final yacyURL location, final String mimeType,
+ final String charset, final InputStream source) throws ParserException,
InterruptedException {
try {
/*
* create new PowerPointExtractor and extract text and notes
* of the document
*/
- PowerPointExtractor pptExtractor = new PowerPointExtractor(new BufferedInputStream(source));
- String contents = pptExtractor.getText(true, true);
+ final PowerPointExtractor pptExtractor = new PowerPointExtractor(new BufferedInputStream(source));
+ final String contents = pptExtractor.getText(true, true);
/*
* create the plasmaParserDocument for the database
* and set shortText and bodyText properly
*/
- plasmaParserDocument theDoc = new plasmaParserDocument(
+ final plasmaParserDocument theDoc = new plasmaParserDocument(
location,
mimeType,
"UTF-8",
@@ -100,13 +100,13 @@ public class pptParser extends AbstractParser implements Parser {
null,
null);
return theDoc;
- } catch (Exception e) {
+ } catch (final Exception e) {
if (e instanceof InterruptedException) throw (InterruptedException) e;
/*
* an unexpected error occurred, log it and throw a ParserException
*/
- String errorMsg = "Unable to parse the ppt document '" + location + "':" + e.getMessage();
+ final String errorMsg = "Unable to parse the ppt document '" + location + "':" + e.getMessage();
this.theLogger.logSevere(errorMsg);
throw new ParserException(errorMsg, location);
}
diff --git a/source/de/anomic/plasma/parser/ps/psParser.java b/source/de/anomic/plasma/parser/ps/psParser.java
index 877e85269..a8c9d6fef 100644
--- a/source/de/anomic/plasma/parser/ps/psParser.java
+++ b/source/de/anomic/plasma/parser/ps/psParser.java
@@ -79,23 +79,23 @@ public class psParser extends AbstractParser implements Parser {
public boolean testForPs2Ascii() {
try {
String procOutputLine = null;
- StringBuffer procOutput = new StringBuffer();
+ final StringBuffer procOutput = new StringBuffer();
- Process ps2asciiProc = Runtime.getRuntime().exec(new String[]{"ps2ascii", "--version"});
- BufferedReader stdOut = new BufferedReader(new InputStreamReader(ps2asciiProc.getInputStream()));
+ final Process ps2asciiProc = Runtime.getRuntime().exec(new String[]{"ps2ascii", "--version"});
+ final BufferedReader stdOut = new BufferedReader(new InputStreamReader(ps2asciiProc.getInputStream()));
while ((procOutputLine = stdOut.readLine()) != null) {
procOutput.append(procOutputLine).append(", ");
}
- int returnCode = ps2asciiProc.waitFor();
+ final int returnCode = ps2asciiProc.waitFor();
return (returnCode == 0);
- } catch (Exception e) {
+ } catch (final Exception e) {
if (this.theLogger != null) this.theLogger.logInfo("ps2ascii not found. Switching to java parser mode.");
return false;
}
}
- public plasmaParserDocument parse(yacyURL location, String mimeType, String charset, File sourceFile) throws ParserException, InterruptedException {
+ public plasmaParserDocument parse(final yacyURL location, final String mimeType, final String charset, final File sourceFile) throws ParserException, InterruptedException {
File outputFile = null;
try {
@@ -110,7 +110,7 @@ public class psParser extends AbstractParser implements Parser {
}
// return result
- plasmaParserDocument theDoc = new plasmaParserDocument(
+ final plasmaParserDocument theDoc = new plasmaParserDocument(
location,
mimeType,
"UTF-8",
@@ -124,7 +124,7 @@ public class psParser extends AbstractParser implements Parser {
null);
return theDoc;
- } catch (Exception e) {
+ } catch (final Exception e) {
if (e instanceof InterruptedException) throw (InterruptedException) e;
if (e instanceof ParserException) throw (ParserException) e;
@@ -136,7 +136,7 @@ public class psParser extends AbstractParser implements Parser {
}
}
- public void parseUsingJava (File inputFile, File outputFile) throws Exception {
+ public void parseUsingJava (final File inputFile, final File outputFile) throws Exception {
BufferedReader reader = null;
BufferedWriter writer = null;
@@ -144,8 +144,8 @@ public class psParser extends AbstractParser implements Parser {
reader = new BufferedReader(new FileReader(inputFile));
writer = new BufferedWriter(new FileWriter(outputFile));
- String versionInfoLine = reader.readLine();
- String version = versionInfoLine.substring(versionInfoLine.length()-3);
+ final String versionInfoLine = reader.readLine();
+ final String version = versionInfoLine.substring(versionInfoLine.length()-3);
int ichar = 0;
boolean isComment = false;
@@ -175,7 +175,7 @@ public class psParser extends AbstractParser implements Parser {
}
} else if (version.startsWith("3")) {
- StringBuffer stmt = new StringBuffer();
+ final StringBuffer stmt = new StringBuffer();
boolean isBMP = false;
boolean isStore = false;
int store = 0;
@@ -217,8 +217,8 @@ public class psParser extends AbstractParser implements Parser {
throw new Exception("Unsupported Postscript version '" + version + "'.");
}
} finally {
- if (reader != null) try { reader.close(); } catch (Exception e) {/* */}
- if (writer != null) try { writer.close(); } catch (Exception e) {/* */}
+ if (reader != null) try { reader.close(); } catch (final Exception e) {/* */}
+ if (writer != null) try { writer.close(); } catch (final Exception e) {/* */}
}
@@ -230,17 +230,17 @@ public class psParser extends AbstractParser implements Parser {
* @param outputFile
* @throws Exception
*/
- private void parseUsingPS2ascii(File inputFile, File outputFile) throws Exception {
+ private void parseUsingPS2ascii(final File inputFile, final File outputFile) throws Exception {
int execCode = 0;
StringBuffer procErr = null;
try {
String procOutputLine = null;
- StringBuffer procOut = new StringBuffer();
+ final StringBuffer procOut = new StringBuffer();
procErr = new StringBuffer();
- Process ps2asciiProc = Runtime.getRuntime().exec(new String[]{"ps2ascii", inputFile.getAbsolutePath(),outputFile.getAbsolutePath()});
- BufferedReader stdOut = new BufferedReader(new InputStreamReader(ps2asciiProc.getInputStream()));
- BufferedReader stdErr = new BufferedReader(new InputStreamReader(ps2asciiProc.getErrorStream()));
+ final Process ps2asciiProc = Runtime.getRuntime().exec(new String[]{"ps2ascii", inputFile.getAbsolutePath(),outputFile.getAbsolutePath()});
+ final BufferedReader stdOut = new BufferedReader(new InputStreamReader(ps2asciiProc.getInputStream()));
+ final BufferedReader stdErr = new BufferedReader(new InputStreamReader(ps2asciiProc.getErrorStream()));
while ((procOutputLine = stdOut.readLine()) != null) {
procOut.append(procOutputLine);
}
@@ -248,8 +248,8 @@ public class psParser extends AbstractParser implements Parser {
procErr.append(procOutputLine);
}
execCode = ps2asciiProc.waitFor();
- } catch (Exception e) {
- String errorMsg = "Unable to convert ps to ascii. " + e.getMessage();
+ } catch (final Exception e) {
+ final String errorMsg = "Unable to convert ps to ascii. " + e.getMessage();
this.theLogger.logSevere(errorMsg);
throw new Exception(errorMsg);
}
@@ -262,7 +262,7 @@ public class psParser extends AbstractParser implements Parser {
super.reset();
}
- public plasmaParserDocument parse(yacyURL location, String mimeType, String charset, InputStream source) throws ParserException, InterruptedException {
+ public plasmaParserDocument parse(final yacyURL location, final String mimeType, final String charset, final InputStream source) throws ParserException, InterruptedException {
File tempFile = null;
try {
@@ -275,13 +275,13 @@ public class psParser extends AbstractParser implements Parser {
// parsing the file
return parse(location,mimeType,charset,tempFile);
- } catch (Exception e) {
+ } catch (final Exception e) {
if (e instanceof InterruptedException) throw (InterruptedException) e;
if (e instanceof ParserException) throw (ParserException) e;
throw new ParserException("Unable to parse the ps file. " + e.getMessage(),location, e);
} finally {
- if (tempFile != null) try{ tempFile.delete(); }catch(Exception e) {/* */}
+ if (tempFile != null) try{ tempFile.delete(); }catch(final Exception e) {/* */}
}
}
diff --git a/source/de/anomic/plasma/parser/rpm/rpmParser.java b/source/de/anomic/plasma/parser/rpm/rpmParser.java
index 2bb201abc..742289e24 100644
--- a/source/de/anomic/plasma/parser/rpm/rpmParser.java
+++ b/source/de/anomic/plasma/parser/rpm/rpmParser.java
@@ -75,26 +75,26 @@ public class rpmParser extends AbstractParser implements Parser {
return SUPPORTED_MIME_TYPES;
}
- public plasmaParserDocument parse(yacyURL location, String mimeType, String charset,
- InputStream source) throws ParserException {
+ public plasmaParserDocument parse(final yacyURL location, final String mimeType, final String charset,
+ final InputStream source) throws ParserException {
File dstFile = null;
try {
dstFile = File.createTempFile("rpmParser",".tmp");
serverFileUtils.copy(source,dstFile);
return parse(location,mimeType,charset,dstFile);
- } catch (Exception e) {
+ } catch (final Exception e) {
return null;
} finally {
if (dstFile != null) {dstFile.delete();}
}
}
- public plasmaParserDocument parse(yacyURL location, String mimeType, String charset, File sourceFile) throws ParserException, InterruptedException {
+ public plasmaParserDocument parse(final yacyURL location, final String mimeType, final String charset, final File sourceFile) throws ParserException, InterruptedException {
RPMFile rpmFile = null;
try {
String summary = null, description = null, packager = null, name = sourceFile.getName();
- HashMap<yacyURL, String> anchors = new HashMap<yacyURL, String>();
- StringBuffer content = new StringBuffer();
+ final HashMap<yacyURL, String> anchors = new HashMap<yacyURL, String>();
+ final StringBuffer content = new StringBuffer();
// opening the rpm file
rpmFile = new RPMFile(sourceFile);
@@ -103,13 +103,13 @@ public class rpmParser extends AbstractParser implements Parser {
rpmFile.parse();
// getting all header names
- String[] headerNames = rpmFile.getTagNames();
+ final String[] headerNames = rpmFile.getTagNames();
for (int i=0; i<headerNames.length; i++) {
// check for interruption
checkInterruption();
// getting the next tag
- DataTypeIf tag = rpmFile.getTag(headerNames[i]);
+ final DataTypeIf tag = rpmFile.getTag(headerNames[i]);
if (tag == null) continue;
content.append(headerNames[i])
@@ -129,7 +129,7 @@ public class rpmParser extends AbstractParser implements Parser {
rpmFile = null;
if (summary == null) summary = name;
- plasmaParserDocument theDoc = new plasmaParserDocument(
+ final plasmaParserDocument theDoc = new plasmaParserDocument(
location,
mimeType,
"UTF-8",
@@ -143,13 +143,13 @@ public class rpmParser extends AbstractParser implements Parser {
null);
return theDoc;
- } catch (Exception e) {
+ } catch (final Exception e) {
if (e instanceof InterruptedException) throw (InterruptedException) e;
if (e instanceof ParserException) throw (ParserException) e;
throw new ParserException("Unexpected error while parsing rpm file. " + e.getMessage(),location);
} finally {
- if (rpmFile != null) try { rpmFile.close(); } catch (Exception e) {/* ignore this */}
+ if (rpmFile != null) try { rpmFile.close(); } catch (final Exception e) {/* ignore this */}
}
}
@@ -158,17 +158,17 @@ public class rpmParser extends AbstractParser implements Parser {
super.reset();
}
- public static void main(String[] args) {
+ public static void main(final String[] args) {
try {
- yacyURL contentUrl = new yacyURL(args[0], null);
+ final yacyURL contentUrl = new yacyURL(args[0], null);
- rpmParser testParser = new rpmParser();
- httpHeader reqHeader = new httpHeader();
+ final rpmParser testParser = new rpmParser();
+ final httpHeader reqHeader = new httpHeader();
reqHeader.put(httpHeader.USER_AGENT, HTTPLoader.crawlerUserAgent);
- byte[] content = HttpClient.wget(contentUrl.toString(), reqHeader, 10000);
- ByteArrayInputStream input = new ByteArrayInputStream(content);
+ final byte[] content = HttpClient.wget(contentUrl.toString(), reqHeader, 10000);
+ final ByteArrayInputStream input = new ByteArrayInputStream(content);
testParser.parse(contentUrl, "application/x-rpm", null, input);
- } catch (Exception e) {
+ } catch (final Exception e) {
e.printStackTrace();
}
}
diff --git a/source/de/anomic/plasma/parser/rss/rssParser.java b/source/de/anomic/plasma/parser/rss/rssParser.java
index 1618175ac..a32ac8ef1 100644
--- a/source/de/anomic/plasma/parser/rss/rssParser.java
+++ b/source/de/anomic/plasma/parser/rss/rssParser.java
@@ -73,41 +73,41 @@ public class rssParser extends AbstractParser implements Parser {
this.parserName = "Rich Site Summary/Atom Feed Parser";
}
- public plasmaParserDocument parse(yacyURL location, String mimeType, String charset, InputStream source) throws ParserException, InterruptedException {
+ public plasmaParserDocument parse(final yacyURL location, final String mimeType, final String charset, final InputStream source) throws ParserException, InterruptedException {
try {
- LinkedList<String> feedSections = new LinkedList<String>();
- HashMap<yacyURL, String> anchors = new HashMap<yacyURL, String>();
- HashMap<String, htmlFilterImageEntry> images = new HashMap<String, htmlFilterImageEntry>();
- serverByteBuffer text = new serverByteBuffer();
- serverCharBuffer authors = new serverCharBuffer();
+ final LinkedList<String> feedSections = new LinkedList<String>();
+ final HashMap<yacyURL, String> anchors = new HashMap<yacyURL, String>();
+ final HashMap<String, htmlFilterImageEntry> images = new HashMap<String, htmlFilterImageEntry>();
+ final serverByteBuffer text = new serverByteBuffer();
+ final serverCharBuffer authors = new serverCharBuffer();
- RSSFeed feed = new RSSReader(source).getFeed();
+ final RSSFeed feed = new RSSReader(source).getFeed();
// getting the rss feed title and description
- String feedTitle = feed.getChannel().getTitle();
+ final String feedTitle = feed.getChannel().getTitle();
// getting feed creator
- String feedCreator = feed.getChannel().getAuthor();
+ final String feedCreator = feed.getChannel().getAuthor();
if (feedCreator != null && feedCreator.length() > 0) authors.append(",").append(feedCreator);
// getting the feed description
- String feedDescription = feed.getChannel().getDescription();
+ final String feedDescription = feed.getChannel().getDescription();
if (feed.getImage() != null) {
- yacyURL imgURL = new yacyURL(feed.getImage(), null);
+ final yacyURL imgURL = new yacyURL(feed.getImage(), null);
images.put(imgURL.hash(), new htmlFilterImageEntry(imgURL, feedTitle, -1, -1));
}
// loop through the feed items
- for (RSSMessage item: feed) {
+ for (final RSSMessage item: feed) {
// check for interruption
checkInterruption();
- String itemTitle = item.getTitle();
- yacyURL itemURL = new yacyURL(item.getLink(), null);
- String itemDescr = item.getDescription();
- String itemCreator = item.getCreator();
+ final String itemTitle = item.getTitle();
+ final yacyURL itemURL = new yacyURL(item.getLink(), null);
+ final String itemDescr = item.getDescription();
+ final String itemCreator = item.getCreator();
if (itemCreator != null && itemCreator.length() > 0) authors.append(",").append(itemCreator);
feedSections.add(itemTitle);
@@ -116,29 +116,29 @@ public class rssParser extends AbstractParser implements Parser {
if ((text.length() != 0) && (text.byteAt(text.length() - 1) != 32)) text.append((byte) 32);
text.append(new serverCharBuffer(htmlFilterAbstractScraper.stripAll(new serverCharBuffer(itemDescr.toCharArray()))).trim().toString()).append(' ');
- String itemContent = item.getDescription();
+ final String itemContent = item.getDescription();
if ((itemContent != null) && (itemContent.length() > 0)) {
- htmlFilterContentScraper scraper = new htmlFilterContentScraper(itemURL);
- Writer writer = new htmlFilterWriter(null, null, scraper, null, false);
+ final htmlFilterContentScraper scraper = new htmlFilterContentScraper(itemURL);
+ final Writer writer = new htmlFilterWriter(null, null, scraper, null, false);
serverFileUtils.copy(new ByteArrayInputStream(itemContent.getBytes("UTF-8")), writer, "UTF-8");
- String itemHeadline = scraper.getTitle();
+ final String itemHeadline = scraper.getTitle();
if ((itemHeadline != null) && (itemHeadline.length() > 0)) {
feedSections.add(itemHeadline);
}
- Map<yacyURL, String> itemLinks = scraper.getAnchors();
+ final Map<yacyURL, String> itemLinks = scraper.getAnchors();
if ((itemLinks != null) && (itemLinks.size() > 0)) {
anchors.putAll(itemLinks);
}
- HashMap<String, htmlFilterImageEntry> itemImages = scraper.getImages();
+ final HashMap<String, htmlFilterImageEntry> itemImages = scraper.getImages();
if ((itemImages != null) && (itemImages.size() > 0)) {
htmlFilterContentScraper.addAllImages(images, itemImages);
}
- byte[] extractedText = scraper.getText();
+ final byte[] extractedText = scraper.getText();
if ((extractedText != null) && (extractedText.length > 0)) {
if ((text.length() != 0) && (text.byteAt(text.length() - 1) != 32)) text.append((byte) 32);
text.append(scraper.getText());
@@ -147,7 +147,7 @@ public class rssParser extends AbstractParser implements Parser {
}
}
- plasmaParserDocument theDoc = new plasmaParserDocument(
+ final plasmaParserDocument theDoc = new plasmaParserDocument(
location,
mimeType,
"UTF-8",
@@ -162,7 +162,7 @@ public class rssParser extends AbstractParser implements Parser {
return theDoc;
- } catch (Exception e) {
+ } catch (final Exception e) {
if (e instanceof InterruptedException) throw (InterruptedException) e;
if (e instanceof ParserException) throw (ParserException) e;
diff --git a/source/de/anomic/plasma/parser/rtf/rtfParser.java b/source/de/anomic/plasma/parser/rtf/rtfParser.java
index 1d69cc970..6a2f800e8 100644
--- a/source/de/anomic/plasma/parser/rtf/rtfParser.java
+++ b/source/de/anomic/plasma/parser/rtf/rtfParser.java
@@ -59,18 +59,18 @@ public class rtfParser extends AbstractParser implements Parser {
this.parserName = "Rich Text Format Parser";
}
- public plasmaParserDocument parse(yacyURL location, String mimeType, String charset, InputStream source) throws ParserException, InterruptedException {
+ public plasmaParserDocument parse(final yacyURL location, final String mimeType, final String charset, final InputStream source) throws ParserException, InterruptedException {
try {
- DefaultStyledDocument doc = new DefaultStyledDocument();
+ final DefaultStyledDocument doc = new DefaultStyledDocument();
- RTFEditorKit theRtfEditorKit = new RTFEditorKit();
+ final RTFEditorKit theRtfEditorKit = new RTFEditorKit();
theRtfEditorKit.read(source, doc, 0);
- String bodyText = doc.getText(0, doc.getLength());
+ final String bodyText = doc.getText(0, doc.getLength());
- plasmaParserDocument theDoc = new plasmaParserDocument(
+ final plasmaParserDocument theDoc = new plasmaParserDocument(
location,
mimeType,
"UTF-8",
@@ -89,7 +89,7 @@ public class rtfParser extends AbstractParser implements Parser {
return theDoc;
}
- catch (Exception e) {
+ catch (final Exception e) {
if (e instanceof InterruptedException) throw (InterruptedException) e;
if (e instanceof ParserException) throw (ParserException) e;
diff --git a/source/de/anomic/plasma/parser/sevenzip/ByteArrayIInStream.java b/source/de/anomic/plasma/parser/sevenzip/ByteArrayIInStream.java
index 39c01c53f..21502c98b 100644
--- a/source/de/anomic/plasma/parser/sevenzip/ByteArrayIInStream.java
+++ b/source/de/anomic/plasma/parser/sevenzip/ByteArrayIInStream.java
@@ -31,12 +31,12 @@ import SevenZip.IInStream;
public class ByteArrayIInStream extends IInStream {
private class SeekableByteArrayInputStream extends ByteArrayInputStream {
- public SeekableByteArrayInputStream(byte[] buf) { super(buf); }
- public SeekableByteArrayInputStream(byte[] buf, int off, int len) { super(buf, off, len); }
+ 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(int offset) { seekAbsolute(super.pos + offset); }
- public void seekAbsolute(int offset) {
+ 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;
@@ -45,11 +45,11 @@ public class ByteArrayIInStream extends IInStream {
private final SeekableByteArrayInputStream sbais;
- public ByteArrayIInStream(byte[] buffer) {
+ public ByteArrayIInStream(final byte[] buffer) {
this.sbais = new SeekableByteArrayInputStream(buffer);
}
- public long Seek(long offset, int origin) {
+ 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;
@@ -61,7 +61,7 @@ public class ByteArrayIInStream extends IInStream {
return this.sbais.read();
}
- public int read(byte[] b, int off, int len) throws IOException {
+ public int read(final byte[] b, final int off, final int len) throws IOException {
return this.sbais.read(b, off, len);
}
}
\ No newline at end of file
diff --git a/source/de/anomic/plasma/parser/sevenzip/SZParserExtractCallback.java b/source/de/anomic/plasma/parser/sevenzip/SZParserExtractCallback.java
index 4074c0086..283d6ecca 100644
--- a/source/de/anomic/plasma/parser/sevenzip/SZParserExtractCallback.java
+++ b/source/de/anomic/plasma/parser/sevenzip/SZParserExtractCallback.java
@@ -51,8 +51,8 @@ public class SZParserExtractCallback extends ArchiveExtractCallback {
private final plasmaParserDocument doc;
private final String prefix;
- public SZParserExtractCallback(serverLog logger, IInArchive handler,
- long maxRamSize, plasmaParserDocument doc, String prefix) {
+ public SZParserExtractCallback(final serverLog logger, final IInArchive handler,
+ final long maxRamSize, final plasmaParserDocument doc, final String prefix) {
super.Init(handler);
this.log = logger;
this.maxRamSize = maxRamSize;
@@ -61,7 +61,7 @@ public class SZParserExtractCallback extends ArchiveExtractCallback {
this.prefix = prefix;
}
- public void PrepareOperation(int arg0) {
+ public void PrepareOperation(final int arg0) {
this.extractMode = (arg0 == IInArchive.NExtract_NAskMode_kExtract);
switch (arg0) {
case IInArchive.NExtract_NAskMode_kExtract:
@@ -76,7 +76,7 @@ public class SZParserExtractCallback extends ArchiveExtractCallback {
}
}
- public void SetOperationResult(int arg0) throws IOException {
+ public void SetOperationResult(final int arg0) throws IOException {
if (arg0 != IInArchive.NExtract_NOperationResult_kOK) {
this.NumErrors++;
switch(arg0) {
@@ -97,8 +97,8 @@ public class SZParserExtractCallback extends ArchiveExtractCallback {
plasmaParserDocument theDoc;
// workaround for relative links in file, normally '#' shall be used behind the location, see
// below for reversion of the effects
- yacyURL url = yacyURL.newURL(doc.dc_source(), this.prefix + "/" + super.filePath);
- String mime = plasmaParser.getMimeTypeByFileExt(super.filePath.substring(super.filePath.lastIndexOf('.') + 1));
+ final yacyURL url = yacyURL.newURL(doc.dc_source(), this.prefix + "/" + super.filePath);
+ final String mime = plasmaParser.getMimeTypeByFileExt(super.filePath.substring(super.filePath.lastIndexOf('.') + 1));
if (this.cfos.isFallback()) {
theDoc = this.parser.parseSource(url, mime, null, this.cfos.getContentFile());
} else {
@@ -106,16 +106,16 @@ public class SZParserExtractCallback extends ArchiveExtractCallback {
}
// revert the above workaround
- Map<yacyURL, String> nanchors = new HashMap<yacyURL, String>(theDoc.getAnchors().size(), 1f);
- Iterator<Map.Entry<yacyURL, String>> it = theDoc.getAnchors().entrySet().iterator();
+ final Map<yacyURL, String> nanchors = new HashMap<yacyURL, String>(theDoc.getAnchors().size(), 1f);
+ final Iterator<Map.Entry<yacyURL, String>> it = theDoc.getAnchors().entrySet().iterator();
Map.Entry<yacyURL, String> entry;
- String base = doc.dc_source().toNormalform(false, true);
+ final String base = doc.dc_source().toNormalform(false, true);
String u;
while (it.hasNext()) {
entry = it.next();
u = entry.getKey().toNormalform(true, true);
if (u.startsWith(base + "/")) {
- String ref = "#" + u.substring(base.length() + 1);
+ final String ref = "#" + u.substring(base.length() + 1);
this.log.logFinest("changing " + entry.getKey() + " to use reference " + ref);
nanchors.put(new yacyURL(base + ref, null), entry.getValue());
} else {
@@ -126,24 +126,24 @@ public class SZParserExtractCallback extends ArchiveExtractCallback {
theDoc.getAnchors().putAll(nanchors);
this.doc.addSubDocument(theDoc);
}
- } catch (ParserException e) {
- IOException ex = new IOException("error parsing extracted content of " + super.filePath + ": " + e.getMessage());
+ } catch (final ParserException e) {
+ final IOException ex = new IOException("error parsing extracted content of " + super.filePath + ": " + e.getMessage());
ex.initCause(e);
throw ex;
- } catch (InterruptedException e) {
- IOException ex = new IOException("interrupted");
+ } catch (final InterruptedException e) {
+ final IOException ex = new IOException("interrupted");
ex.initCause(e);
throw ex;
}
}
- public OutputStream GetStream(int index, int askExtractMode) throws IOException {
- SevenZipEntry item = super.archiveHandler.getEntry(index);
+ 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 (InterruptedException e) {
- IOException ex = new IOException("interrupted");
+ } catch (final InterruptedException e) {
+ final IOException ex = new IOException("interrupted");
ex.initCause(e);
throw ex;
}
diff --git a/source/de/anomic/plasma/parser/sevenzip/sevenzipParser.java b/source/de/anomic/plasma/parser/sevenzip/sevenzipParser.java
index 07eccadfd..e814c8181 100644
--- a/source/de/anomic/plasma/parser/sevenzip/sevenzipParser.java
+++ b/source/de/anomic/plasma/parser/sevenzip/sevenzipParser.java
@@ -61,24 +61,24 @@ public class sevenzipParser extends AbstractParser implements Parser {
super.parserName = "7zip Archive Parser";
}
- public plasmaParserDocument parse(yacyURL location, String mimeType, String charset,
- IInStream source, long maxRamSize) throws ParserException, InterruptedException {
- plasmaParserDocument doc = new plasmaParserDocument(location, mimeType, charset);
+ public plasmaParserDocument parse(final yacyURL location, final String mimeType, final String charset,
+ final IInStream source, final long maxRamSize) throws ParserException, InterruptedException {
+ final plasmaParserDocument doc = new plasmaParserDocument(location, mimeType, charset);
Handler archive;
super.theLogger.logFine("opening 7zip archive...");
try {
archive = new Handler(source);
- } catch (IOException e) {
+ } catch (final IOException e) {
throw new ParserException("error opening 7zip archive", location, e);
}
checkInterruption();
- SZParserExtractCallback aec = new SZParserExtractCallback(super.theLogger, archive,
+ final SZParserExtractCallback aec = new SZParserExtractCallback(super.theLogger, archive,
maxRamSize, doc, location.getFile());
super.theLogger.logFine("processing archive contents...");
try {
archive.Extract(null, -1, 0, aec);
return doc;
- } catch (IOException e) {
+ } catch (final IOException e) {
if (e.getCause() instanceof InterruptedException)
throw (InterruptedException)e.getCause();
if (e.getCause() instanceof ParserException)
@@ -87,35 +87,35 @@ public class sevenzipParser extends AbstractParser implements Parser {
"error processing 7zip archive at internal file: " + aec.getCurrentFilePath(),
location, e);
} finally {
- try { archive.close(); } catch (IOException e) { }
+ try { archive.close(); } catch (final IOException e) { }
}
}
- public plasmaParserDocument parse(yacyURL location, String mimeType, String charset,
- byte[] source) throws ParserException, InterruptedException {
+ public plasmaParserDocument parse(final yacyURL location, final String mimeType, final String charset,
+ final byte[] source) throws ParserException, InterruptedException {
return parse(location, mimeType, charset, new ByteArrayIInStream(source), Parser.MAX_KEEP_IN_MEMORY_SIZE - source.length);
}
- public plasmaParserDocument parse(yacyURL location, String mimeType, String charset,
- File sourceFile) throws ParserException, InterruptedException {
+ public plasmaParserDocument parse(final yacyURL location, final String mimeType, final String charset,
+ final File sourceFile) throws ParserException, InterruptedException {
try {
return parse(location, mimeType, charset, new MyRandomAccessFile(sourceFile, "r"), Parser.MAX_KEEP_IN_MEMORY_SIZE);
- } catch (IOException e) {
+ } catch (final IOException e) {
throw new ParserException("error processing 7zip archive", location, e);
}
}
- public plasmaParserDocument parse(yacyURL location, String mimeType, String charset,
- InputStream source) throws ParserException, InterruptedException {
+ public plasmaParserDocument parse(final yacyURL location, final String mimeType, final String charset,
+ final InputStream source) throws ParserException, InterruptedException {
try {
- serverCachedFileOutputStream cfos = new serverCachedFileOutputStream(Parser.MAX_KEEP_IN_MEMORY_SIZE);
+ final serverCachedFileOutputStream cfos = new serverCachedFileOutputStream(Parser.MAX_KEEP_IN_MEMORY_SIZE);
serverFileUtils.copy(source, cfos);
if (cfos.isFallback()) {
return parse(location, mimeType, charset, cfos.getContentFile());
} else {
return parse(location, mimeType, charset, cfos.getContentBAOS());
}
- } catch (IOException e) {
+ } catch (final IOException e) {
throw new ParserException("error processing 7zip archive", location, e);
}
}
diff --git a/source/de/anomic/plasma/parser/swf/swfParser.java b/source/de/anomic/plasma/parser/swf/swfParser.java
index 107dd96ee..dbce2f4f0 100644
--- a/source/de/anomic/plasma/parser/swf/swfParser.java
+++ b/source/de/anomic/plasma/parser/swf/swfParser.java
@@ -70,18 +70,18 @@ public class swfParser extends AbstractParser implements Parser {
* parses the source documents and returns a plasmaParserDocument containing
* all extracted information about the parsed document
*/
- public plasmaParserDocument parse(yacyURL location, String mimeType, String charset, InputStream source) throws ParserException, InterruptedException {
+ public plasmaParserDocument parse(final yacyURL location, final String mimeType, final String charset, final InputStream source) throws ParserException, InterruptedException {
try {
- SWF2HTML swf2html = new SWF2HTML();
+ final SWF2HTML swf2html = new SWF2HTML();
String contents = swf2html.convertSWFToHTML(source);
String url = null;
String urlnr = null;
- String linebreak = System.getProperty("line.separator");
- String[] sections = null;
- String abstrct = null;
+ final String linebreak = System.getProperty("line.separator");
+ final String[] sections = null;
+ final String abstrct = null;
//TreeSet images = null;
- HashMap<yacyURL, String> anchors = new HashMap<yacyURL, String>();
+ final HashMap<yacyURL, String> anchors = new HashMap<yacyURL, String>();
int urls = 0;
int urlStart = -1;
int urlEnd = 0;
@@ -103,7 +103,7 @@ public class swfParser extends AbstractParser implements Parser {
}
// As the result of parsing this function must return a plasmaParserDocument object
- plasmaParserDocument theDoc = new plasmaParserDocument(
+ final plasmaParserDocument theDoc = new plasmaParserDocument(
location, // url of the source document
mimeType, // the documents mime type
"UTF-8", // charset of the document text
@@ -120,11 +120,11 @@ public class swfParser extends AbstractParser implements Parser {
anchors, // a map of extracted anchors
null); // a treeset of image URLs
return theDoc;
- } catch (Exception e) {
+ } 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
- String errorMsg = "Unable to parse the swf document '" + location + "':" + e.getMessage();
+ final String errorMsg = "Unable to parse the swf document '" + location + "':" + e.getMessage();
this.theLogger.logSevere(errorMsg);
throw new ParserException(errorMsg, location);
}
diff --git a/source/de/anomic/plasma/parser/tar/tarParser.java b/source/de/anomic/plasma/parser/tar/tarParser.java
index 5c8ea891b..b2dc48cb1 100644
--- a/source/de/anomic/plasma/parser/tar/tarParser.java
+++ b/source/de/anomic/plasma/parser/tar/tarParser.java
@@ -79,7 +79,7 @@ public class tarParser extends AbstractParser implements Parser {
return SUPPORTED_MIME_TYPES;
}
- public plasmaParserDocument parse(yacyURL location, String mimeType, String charset, InputStream source) throws ParserException, InterruptedException {
+ public plasmaParserDocument parse(final yacyURL location, final String mimeType, final String charset, InputStream source) throws ParserException, InterruptedException {
long docTextLength = 0;
OutputStream docText = null;
@@ -94,30 +94,30 @@ public class tarParser extends AbstractParser implements Parser {
}
// creating a new parser class to parse the unzipped content
- plasmaParser theParser = new plasmaParser();
+ final plasmaParser theParser = new plasmaParser();
/*
* If the mimeType was not reported correcly by the webserve we
* have to decompress it first
*/
- String ext = plasmaParser.getFileExt(location).toLowerCase();
+ final String ext = plasmaParser.getFileExt(location).toLowerCase();
if (ext.equals("gz") || ext.equals("tgz")) {
source = new GZIPInputStream(source);
}
// TODO: what about bzip ....
- StringBuffer docKeywords = new StringBuffer();
- StringBuffer docLongTitle = new StringBuffer();
- LinkedList<String> docSections = new LinkedList<String>();
- StringBuffer docAbstrct = new StringBuffer();
+ final StringBuffer docKeywords = new StringBuffer();
+ final StringBuffer docLongTitle = new StringBuffer();
+ final LinkedList<String> docSections = new LinkedList<String>();
+ final StringBuffer docAbstrct = new StringBuffer();
- Map<yacyURL, String> docAnchors = new HashMap<yacyURL, String>();
- HashMap<String, htmlFilterImageEntry> docImages = new HashMap<String, htmlFilterImageEntry>();
+ final Map<yacyURL, String> docAnchors = new HashMap<yacyURL, String>();
+ final HashMap<String, htmlFilterImageEntry> docImages = new HashMap<String, htmlFilterImageEntry>();
// looping through the contained files
TarEntry entry;
- TarInputStream tin = new TarInputStream(source);
+ final TarInputStream tin = new TarInputStream(source);
while ((entry = tin.getNextEntry()) !=null) {
// check for interruption
checkInterruption();
@@ -126,14 +126,14 @@ public class tarParser extends AbstractParser implements Parser {
if (entry.isDirectory()) continue;
// Get the short entry name
- String entryName = entry.getName();
+ final String entryName = entry.getName();
// getting the entry file extension
- int idx = entryName.lastIndexOf(".");
- String entryExt = (idx > -1) ? entryName.substring(idx+1) : "";
+ final int idx = entryName.lastIndexOf(".");
+ final String entryExt = (idx > -1) ? entryName.substring(idx+1) : "";
// trying to determine the mimeType per file extension
- String entryMime = plasmaParser.getMimeTypeByFileExt(entryExt);
+ final String entryMime = plasmaParser.getMimeTypeByFileExt(entryExt);
// getting the entry content
File subDocTempFile = null;
@@ -149,10 +149,10 @@ public class tarParser extends AbstractParser implements Parser {
// parsing the content
subDoc = theParser.parseSource(yacyURL.newURL(location,"#" + entryName),entryMime,null,subDocTempFile);
- } catch (ParserException e) {
+ } catch (final ParserException e) {
this.theLogger.logInfo("Unable to parse tar file entry '" + entryName + "'. " + e.getMessage());
} finally {
- if (subDocTempFile != null) try {subDocTempFile.delete(); } catch(Exception ex){/* ignore this */}
+ if (subDocTempFile != null) try {subDocTempFile.delete(); } catch(final Exception ex){/* ignore this */}
}
if (subDoc == null) continue;
@@ -212,17 +212,17 @@ public class tarParser extends AbstractParser implements Parser {
}
return result;
- } catch (Exception e) {
+ } 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 (Exception ex) {/* ignore this */}
+ if (docText != null) try { docText.close(); } catch (final Exception ex) {/* ignore this */}
// delete the file
- if (outputFile != null) try { outputFile.delete(); } catch (Exception ex) {/* ignore this */}
+ if (outputFile != null) try { outputFile.delete(); } catch (final Exception ex) {/* ignore this */}
throw new ParserException("Unexpected error while parsing tar resource. " + e.getMessage(),location);
}
diff --git a/source/de/anomic/plasma/parser/vcf/vcfParser.java b/source/de/anomic/plasma/parser/vcf/vcfParser.java
index 367f2a659..cb8c3e92c 100644
--- a/source/de/anomic/plasma/parser/vcf/vcfParser.java
+++ b/source/de/anomic/plasma/parser/vcf/vcfParser.java
@@ -78,19 +78,19 @@ public class vcfParser extends AbstractParser implements Parser {
return SUPPORTED_MIME_TYPES;
}
- public plasmaParserDocument parse(yacyURL location, String mimeType, String charset, InputStream source) throws ParserException, InterruptedException {
+ public plasmaParserDocument parse(final yacyURL location, final String mimeType, final String charset, final InputStream source) throws ParserException, InterruptedException {
try {
- StringBuffer parsedTitle = new StringBuffer();
- StringBuffer parsedDataText = new StringBuffer();
- HashMap<String, String> parsedData = new HashMap<String, String>();
- HashMap<yacyURL, String> anchors = new HashMap<yacyURL, String>();
- LinkedList<String> parsedNames = new LinkedList<String>();
+ final StringBuffer parsedTitle = new StringBuffer();
+ final StringBuffer parsedDataText = new StringBuffer();
+ final HashMap<String, String> parsedData = new HashMap<String, String>();
+ final HashMap<yacyURL, String> anchors = new HashMap<yacyURL, String>();
+ final LinkedList<String> parsedNames = new LinkedList<String>();
boolean useLastLine = false;
int lineNr = 0;
String line = null;
- BufferedReader inputReader = (charset!=null)
+ final BufferedReader inputReader = (charset!=null)
? new BufferedReader(new InputStreamReader(source,charset))
: new BufferedReader(new InputStreamReader(source));
while (true) {
@@ -108,13 +108,13 @@ public class vcfParser extends AbstractParser implements Parser {
else if (line.length() == 0) continue;
lineNr++;
- int pos = line.indexOf(":");
+ final int pos = line.indexOf(":");
if (pos != -1) {
- String key = line.substring(0,pos).trim().toUpperCase();
+ final String key = line.substring(0,pos).trim().toUpperCase();
String value = line.substring(pos+1).trim();
String encoding = null;
- String[] keyParts = key.split(";");
+ final String[] keyParts = key.split(";");
if (keyParts.length > 1) {
for (int i=0; i < keyParts.length; i++) {
if (keyParts[i].toUpperCase().startsWith("ENCODING")) {
@@ -152,7 +152,7 @@ public class vcfParser extends AbstractParser implements Parser {
} while (line.length()!=0);
value = kelondroBase64Order.standardCoder.decodeString(value, "de.anomic.plasma.parser.vcf.vcfParser.parse(...)");
}
- } catch (Exception ey) {
+ } catch (final Exception ey) {
// Encoding error: This could occure e.g. if the base64 doesn't
// end with an empty newline
//
@@ -184,7 +184,7 @@ public class vcfParser extends AbstractParser implements Parser {
// looping through the properties and add there values to
// the text representation of the vCard
- Iterator<String> iter = parsedData.values().iterator();
+ final Iterator<String> iter = parsedData.values().iterator();
while (iter.hasNext()) {
value = iter.next();
parsedDataText.append(value).append("\r\n");
@@ -193,10 +193,10 @@ public class vcfParser extends AbstractParser implements Parser {
parsedData.clear();
} else if (key.toUpperCase().startsWith("URL")) {
try {
- yacyURL newURL = new yacyURL(value, null);
+ final yacyURL newURL = new yacyURL(value, null);
anchors.put(newURL, newURL.toString());
//parsedData.put(key,value);
- } catch (MalformedURLException ex) {/* ignore this */}
+ } catch (final MalformedURLException ex) {/* ignore this */}
} else if (
!key.equalsIgnoreCase("BEGIN") &&
!key.equalsIgnoreCase("END") &&
@@ -219,9 +219,9 @@ public class vcfParser extends AbstractParser implements Parser {
}
}
- String[] sections = parsedNames.toArray(new String[parsedNames.size()]);
- byte[] text = parsedDataText.toString().getBytes();
- plasmaParserDocument theDoc = new plasmaParserDocument(
+ final String[] sections = parsedNames.toArray(new String[parsedNames.size()]);
+ final byte[] text = parsedDataText.toString().getBytes();
+ final plasmaParserDocument theDoc = new plasmaParserDocument(
location, // url of the source document
mimeType, // the documents mime type
null,
@@ -234,7 +234,7 @@ public class vcfParser extends AbstractParser implements Parser {
anchors, // a map of extracted anchors
null); // a treeset of image URLs
return theDoc;
- } catch (Exception e) {
+ } catch (final Exception e) {
if (e instanceof InterruptedException) throw (InterruptedException) e;
if (e instanceof ParserException) throw (ParserException) e;
@@ -247,19 +247,19 @@ public class vcfParser extends AbstractParser implements Parser {
super.reset();
}
- public static final String decodeQuotedPrintable(String s) {
+ public static final String decodeQuotedPrintable(final String s) {
if (s == null) return null;
- byte[] b = s.getBytes();
- StringBuffer sb = new StringBuffer();
+ final byte[] b = s.getBytes();
+ final StringBuffer sb = new StringBuffer();
for (int i = 0; i < b.length; i++) {
- int c = b[i];
+ final int c = b[i];
if (c == '=') {
try {
- int u = Character.digit((char) b[++i], 16);
- int l = Character.digit((char) b[++i], 16);
+ final int u = Character.digit((char) b[++i], 16);
+ final int l = Character.digit((char) b[++i], 16);
if (u == -1 || l == -1) throw new RuntimeException("bad quoted-printable encoding");
sb.append((char) ((u << 4) + l));
- } catch (ArrayIndexOutOfBoundsException e) {
+ } catch (final ArrayIndexOutOfBoundsException e) {
throw new RuntimeException("bad quoted-printable encoding");
}
} else {
@@ -269,17 +269,17 @@ public class vcfParser extends AbstractParser implements Parser {
return sb.toString();
}
- public static void main(String[] args) {
+ public static void main(final String[] args) {
try {
- yacyURL contentUrl = new yacyURL(args[0], null);
+ final yacyURL contentUrl = new yacyURL(args[0], null);
- vcfParser testParser = new vcfParser();
- httpHeader reqHeader = new httpHeader();
+ final vcfParser testParser = new vcfParser();
+ final httpHeader reqHeader = new httpHeader();
reqHeader.put(httpHeader.USER_AGENT, HTTPLoader.crawlerUserAgent);
- byte[] content = HttpClient.wget(contentUrl.toString(), reqHeader, 10000);
- ByteArrayInputStream input = new ByteArrayInputStream(content);
+ final byte[] content = HttpClient.wget(contentUrl.toString(), reqHeader, 10000);
+ final ByteArrayInputStream input = new ByteArrayInputStream(content);
testParser.parse(contentUrl, "text/x-vcard", "UTF-8",input);
- } catch (Exception e) {
+ } catch (final Exception e) {
e.printStackTrace();
}
}
diff --git a/source/de/anomic/plasma/parser/xls/xlsParser.java b/source/de/anomic/plasma/parser/xls/xlsParser.java
index e2bba8443..411425aff 100644
--- a/source/de/anomic/plasma/parser/xls/xlsParser.java
+++ b/source/de/anomic/plasma/parser/xls/xlsParser.java
@@ -82,36 +82,36 @@ public class xlsParser extends AbstractParser implements Parser, HSSFListener {
* parses the source documents and returns a plasmaParserDocument containing
* all extracted information about the parsed document
*/
- public plasmaParserDocument parse(yacyURL location, String mimeType,
- String charset, InputStream source) throws ParserException,
+ public plasmaParserDocument parse(final yacyURL location, final String mimeType,
+ final String charset, final InputStream source) throws ParserException,
InterruptedException {
try {
//generate new StringBuffer for parsing
sbFoundStrings = new StringBuffer();
//create a new org.apache.poi.poifs.filesystem.Filesystem
- POIFSFileSystem poifs = new POIFSFileSystem(source);
+ final POIFSFileSystem poifs = new POIFSFileSystem(source);
//get the Workbook (excel part) stream in a InputStream
- InputStream din = poifs.createDocumentInputStream("Workbook");
+ final InputStream din = poifs.createDocumentInputStream("Workbook");
//construct out HSSFRequest object
- HSSFRequest req = new HSSFRequest();
+ final HSSFRequest req = new HSSFRequest();
//lazy listen for ALL records with the listener shown above
req.addListenerForAllRecords(this);
//create our event factory
- HSSFEventFactory factory = new HSSFEventFactory();
+ final HSSFEventFactory factory = new HSSFEventFactory();
//process our events based on the document input stream
factory.processEvents(req, din);
//close our document input stream (don't want to leak these!)
din.close();
//now the parsed strings are in the StringBuffer, now convert them to a String
- String contents = sbFoundStrings.toString();
+ final String contents = sbFoundStrings.toString();
/*
* create the plasmaParserDocument for the database
* and set shortText and bodyText properly
*/
- plasmaParserDocument theDoc = new plasmaParserDocument(
+ final plasmaParserDocument theDoc = new plasmaParserDocument(
location,
mimeType,
"UTF-8",
@@ -128,13 +128,13 @@ public class xlsParser extends AbstractParser implements Parser, HSSFListener {
null,
null);
return theDoc;
- } catch (Exception e) {
+ } catch (final Exception e) {
if (e instanceof InterruptedException) throw (InterruptedException) e;
/*
* an unexpected error occurred, log it and throw a ParserException
*/
- String errorMsg = "Unable to parse the xls document '" + location + "':" + e.getMessage();
+ final String errorMsg = "Unable to parse the xls document '" + location + "':" + e.getMessage();
this.theLogger.logSevere(errorMsg);
throw new ParserException(errorMsg, location);
} finally {
@@ -151,10 +151,10 @@ public class xlsParser extends AbstractParser implements Parser, HSSFListener {
super.reset();
}
- public void processRecord(Record record) {
+ public void processRecord(final Record record) {
switch (record.getSid()){
case NumberRecord.sid: {
- NumberRecord numrec = (NumberRecord) record;
+ final NumberRecord numrec = (NumberRecord) record;
sbFoundStrings.append(numrec.getValue());
break;
}
@@ -171,7 +171,7 @@ public class xlsParser extends AbstractParser implements Parser, HSSFListener {
}
case LabelSSTRecord.sid: {
- LabelSSTRecord lsrec = (LabelSSTRecord)record;
+ final LabelSSTRecord lsrec = (LabelSSTRecord)record;
sbFoundStrings.append( sstrec.getString(lsrec.getSSTIndex()) );
break;
}
diff --git a/source/de/anomic/plasma/parser/zip/zipParser.java b/source/de/anomic/plasma/parser/zip/zipParser.java
index 4afc8946d..34108b1f9 100644
--- a/source/de/anomic/plasma/parser/zip/zipParser.java
+++ b/source/de/anomic/plasma/parser/zip/zipParser.java
@@ -77,7 +77,7 @@ public class zipParser extends AbstractParser implements Parser {
return SUPPORTED_MIME_TYPES;
}
- public plasmaParserDocument parse(yacyURL location, String mimeType, String charset, InputStream source) throws ParserException, InterruptedException {
+ public plasmaParserDocument parse(final yacyURL location, final String mimeType, final String charset, final InputStream source) throws ParserException, InterruptedException {
long docTextLength = 0;
OutputStream docText = null;
@@ -91,19 +91,19 @@ public class zipParser extends AbstractParser implements Parser {
docText = new serverByteBuffer();
}
- StringBuffer docKeywords = new StringBuffer();
- StringBuffer docLongTitle = new StringBuffer();
- LinkedList<String> docSections = new LinkedList<String>();
- StringBuffer docAbstrct = new StringBuffer();
- Map<yacyURL, String> docAnchors = new HashMap<yacyURL, String>();
- HashMap<String, htmlFilterImageEntry> docImages = new HashMap<String, htmlFilterImageEntry>();
+ final StringBuffer docKeywords = new StringBuffer();
+ final StringBuffer docLongTitle = new StringBuffer();
+ final LinkedList<String> docSections = new LinkedList<String>();
+ final StringBuffer docAbstrct = new StringBuffer();
+ final Map<yacyURL, String> docAnchors = new HashMap<yacyURL, String>();
+ final HashMap<String, htmlFilterImageEntry> docImages = new HashMap<String, htmlFilterImageEntry>();
// creating a new parser class to parse the unzipped content
- plasmaParser theParser = new plasmaParser();
+ final plasmaParser theParser = new plasmaParser();
// looping through the contained files
ZipEntry entry;
- ZipInputStream zippedContent = new ZipInputStream(source);
+ final ZipInputStream zippedContent = new ZipInputStream(source);
while ((entry = zippedContent.getNextEntry()) !=null) {
// check for interruption
checkInterruption();
@@ -112,14 +112,14 @@ public class zipParser extends AbstractParser implements Parser {
if (entry.isDirectory()) continue;
// Get the entry name
- String entryName = entry.getName();
- int idx = entryName.lastIndexOf(".");
+ final String entryName = entry.getName();
+ final int idx = entryName.lastIndexOf(".");
// getting the file extension
- String entryExt = (idx > -1) ? entryName.substring(idx+1) : "";
+ final String entryExt = (idx > -1) ? entryName.substring(idx+1) : "";
// trying to determine the mimeType per file extension
- String entryMime = plasmaParser.getMimeTypeByFileExt(entryExt);
+ final String entryMime = plasmaParser.getMimeTypeByFileExt(entryExt);
// parsing the content
File subDocTempFile = null;
@@ -132,10 +132,10 @@ public class zipParser extends AbstractParser implements Parser {
// parsing the zip file entry
subDoc = theParser.parseSource(yacyURL.newURL(location,"#" + entryName),entryMime,null, subDocTempFile);
- } catch (ParserException e) {
+ } catch (final ParserException e) {
this.theLogger.logInfo("Unable to parse zip file entry '" + entryName + "'. " + e.getMessage());
} finally {
- if (subDocTempFile != null) try {subDocTempFile.delete(); } catch(Exception ex){/* ignore this */}
+ if (subDocTempFile != null) try {subDocTempFile.delete(); } catch(final Exception ex){/* ignore this */}
}
if (subDoc == null) continue;
@@ -196,17 +196,17 @@ public class zipParser extends AbstractParser implements Parser {
}
return result;
- } catch (Exception e) {
+ } 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 (Exception ex) {/* ignore this */}
+ if (docText != null) try { docText.close(); } catch (final Exception ex) {/* ignore this */}
// delete the file
- if (outputFile != null) try { outputFile.delete(); } catch (Exception ex) {/* ignore this */}
+ if (outputFile != null) try { outputFile.delete(); } catch (final Exception ex) {/* ignore this */}
throw new ParserException("Unexpected error while parsing zip resource. " + e.getClass().getName() + ": "+ e.getMessage(),location);
}
diff --git a/source/de/anomic/plasma/plasmaCondenser.java b/source/de/anomic/plasma/plasmaCondenser.java
index 8478034bc..8a15b7e2a 100644
--- a/source/de/anomic/plasma/plasmaCondenser.java
+++ b/source/de/anomic/plasma/plasmaCondenser.java
@@ -90,7 +90,7 @@ public final class plasmaCondenser {
private static boolean[] invisibleChar = new boolean['z' - ' ' + 1];
static {
// initialize array of invisible charachters
- String invisibleString = "\"$%&/()=`^+*#'-_:;,<>[]\\";
+ final String invisibleString = "\"$%&/()=`^+*#'-_:;,<>[]\\";
for (int i = ' '; i <= 'z'; i++) {
invisibleChar[i - ' '] = false;
}
@@ -101,8 +101,8 @@ public final class plasmaCondenser {
//private Properties analysis;
private TreeMap<String, indexWord> words; // a string (the words) to (indexWord) - relation
- private int wordminsize;
- private int wordcut;
+ private final int wordminsize;
+ private final int wordcut;
//public int RESULT_NUMB_TEXT_BYTES = -1;
public int RESULT_NUMB_WORDS = -1;
@@ -111,7 +111,7 @@ public final class plasmaCondenser {
public int RESULT_DIFF_SENTENCES = -1;
public kelondroBitfield RESULT_FLAGS = new kelondroBitfield(4);
- public plasmaCondenser(plasmaParserDocument document, boolean indexText, boolean indexMedia) throws UnsupportedEncodingException {
+ public plasmaCondenser(final plasmaParserDocument document, final boolean indexText, final boolean indexMedia) throws UnsupportedEncodingException {
// if addMedia == true, then all the media links are also parsed and added to the words
// added media words are flagged with the appropriate media flag
this.wordminsize = 3;
@@ -142,13 +142,13 @@ public final class plasmaCondenser {
insertTextToWords(document.dc_description(), 3, indexRWIEntry.flag_app_dc_description, RESULT_FLAGS);
insertTextToWords(document.dc_creator(), 4, indexRWIEntry.flag_app_dc_creator, RESULT_FLAGS);
// missing: tags!
- String[] titles = document.getSectionTitles();
+ final String[] titles = document.getSectionTitles();
for (int i = 0; i < titles.length; i++) {
insertTextToWords(titles[i], i + 10, indexRWIEntry.flag_app_emphasized, RESULT_FLAGS);
}
// anchors
- Iterator<Map.Entry<yacyURL, String>> i = document.getAnchors().entrySet().iterator();
+ final Iterator<Map.Entry<yacyURL, String>> i = document.getAnchors().entrySet().iterator();
while (i.hasNext()) {
entry = i.next();
if ((entry == null) || (entry.getKey() == null)) continue;
@@ -188,7 +188,7 @@ public final class plasmaCondenser {
}
// images
- Iterator<htmlFilterImageEntry> j = document.getImages().values().iterator();
+ final Iterator<htmlFilterImageEntry> j = document.getImages().values().iterator();
htmlFilterImageEntry ientry;
while (j.hasNext()) {
ientry = j.next();
@@ -197,7 +197,7 @@ public final class plasmaCondenser {
}
// finally check all words for missing flag entry
- Iterator<Map.Entry<String, indexWord>> k = words.entrySet().iterator();
+ final Iterator<Map.Entry<String, indexWord>> k = words.entrySet().iterator();
indexWord wprop;
Map.Entry<String, indexWord> we;
while (k.hasNext()) {
@@ -217,13 +217,13 @@ public final class plasmaCondenser {
if (document.getApplinks().size() > 0) RESULT_FLAGS.set(flag_cat_hasapp, true);
}
- private void insertTextToWords(String text, int phrase, int flagpos, kelondroBitfield flagstemplate) {
+ private void insertTextToWords(final String text, final int phrase, final int flagpos, final kelondroBitfield flagstemplate) {
String word;
indexWord wprop;
sievedWordsEnum wordenum;
try {
wordenum = new sievedWordsEnum(new ByteArrayInputStream(text.getBytes()), "UTF-8", 3);
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
return;
}
int pip = 0;
@@ -240,11 +240,11 @@ public final class plasmaCondenser {
}
}
- public plasmaCondenser(InputStream text, String charset) throws UnsupportedEncodingException {
+ public plasmaCondenser(final InputStream text, final String charset) throws UnsupportedEncodingException {
this(text, charset, 3, 2);
}
- public plasmaCondenser(InputStream text, String charset, int wordminsize, int wordcut) throws UnsupportedEncodingException {
+ public plasmaCondenser(final InputStream text, final String charset, final int wordminsize, final int wordcut) throws UnsupportedEncodingException {
this.wordminsize = wordminsize;
this.wordcut = wordcut;
// analysis = new Properties();
@@ -252,10 +252,10 @@ public final class plasmaCondenser {
createCondensement(text, charset);
}
- public int excludeWords(TreeSet<String> stopwords) {
+ public int excludeWords(final TreeSet<String> stopwords) {
// subtracts the given stopwords from the word list
// the word list shrinkes. This returns the number of shrinked words
- int oldsize = words.size();
+ final int oldsize = words.size();
words = kelondroMSetTools.excludeConstructive(words, stopwords);
return oldsize - words.size();
}
@@ -265,14 +265,14 @@ public final class plasmaCondenser {
return words;
}
- public String intString(int number, int length) {
+ public String intString(final int number, final int length) {
String s = Integer.toString(number);
while (s.length() < length) s = "0" + s;
return s;
}
- private void createCondensement(InputStream is, String charset) throws UnsupportedEncodingException {
- HashSet<String> currsentwords = new HashSet<String>();
+ private void createCondensement(final InputStream is, final String charset) throws UnsupportedEncodingException {
+ final HashSet<String> currsentwords = new HashSet<String>();
StringBuffer sentence = new StringBuffer(100);
String word = "";
String k;
@@ -289,18 +289,18 @@ public final class plasmaCondenser {
boolean comb_indexof = false, last_last = false, last_index = false;
RandomAccessFile fa;
final boolean dumpWords = false;
- HashMap<StringBuffer, indexPhrase> sentences = new HashMap<StringBuffer, indexPhrase>();
+ final HashMap<StringBuffer, indexPhrase> sentences = new HashMap<StringBuffer, indexPhrase>();
if (dumpWords) try {
fa = new RandomAccessFile(new File("dump.txt"), "rw");
fa.seek(fa.length());
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
fa = null;
}
// read source
- sievedWordsEnum wordenum = new sievedWordsEnum(is, charset, wordminsize);
+ final sievedWordsEnum wordenum = new sievedWordsEnum(is, charset, wordminsize);
while (wordenum.hasMoreElements()) {
word = (new String(wordenum.nextElement())).toLowerCase(); // TODO: does toLowerCase work for non ISO-8859-1 chars?
//System.out.println("PARSED-WORD " + word);
@@ -309,7 +309,7 @@ public final class plasmaCondenser {
if (dumpWords && fa != null) try {
fa.writeBytes(word);
fa.write(160);
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
@@ -391,7 +391,7 @@ public final class plasmaCondenser {
if (dumpWords && fa != null) try {
fa.write('\n');
fa.close();
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
@@ -400,11 +400,11 @@ public final class plasmaCondenser {
// we reconstruct the sentence hashtable
// and order the entries by the number of the sentence
// this structure is needed to replace double occurring words in sentences
- Object[] orderedSentences = new Object[sentenceHandleCount];
+ final Object[] orderedSentences = new Object[sentenceHandleCount];
String[] s;
int wc;
Object o;
- Iterator<StringBuffer> sit = sentences.keySet().iterator();
+ final Iterator<StringBuffer> sit = sentences.keySet().iterator();
while (sit.hasNext()) {
o = sit.next();
if (o != null) {
@@ -425,7 +425,7 @@ public final class plasmaCondenser {
Map.Entry<String, indexWord> entry;
// we search for similar words and reorganize the corresponding sentences
// a word is similar, if a shortened version is equal
- Iterator<Map.Entry<String, indexWord>> wi = words.entrySet().iterator(); // enumerates the keys in descending order
+ final Iterator<Map.Entry<String, indexWord>> wi = words.entrySet().iterator(); // enumerates the keys in descending order
wordsearch: while (wi.hasNext()) {
entry = wi.next();
word = entry.getKey();
@@ -439,7 +439,7 @@ public final class plasmaCondenser {
// corresponding links
// in sentences that use this word
wsp1 = words.get(k);
- Iterator<Integer> it1 = wsp.phrases(); // we iterate over all sentences that refer to this word
+ final Iterator<Integer> it1 = wsp.phrases(); // we iterate over all sentences that refer to this word
while (it1.hasNext()) {
idx = it1.next().intValue(); // number of a sentence
s = (String[]) orderedSentences[idx];
@@ -468,16 +468,16 @@ public final class plasmaCondenser {
this.RESULT_DIFF_SENTENCES = sentenceHandleCount;
}
- public final static boolean invisible(char c) {
+ public final static boolean invisible(final char c) {
// TODO: Bugfix for UTF-8: does this work for non ISO-8859-1 chars?
if ((c < ' ') || (c > 'z')) return true;
return invisibleChar[c - ' '];
}
- public static Enumeration<StringBuffer> wordTokenizer(String s, String charset, int minLength) {
+ public static Enumeration<StringBuffer> wordTokenizer(final String s, final String charset, final int minLength) {
try {
return new sievedWordsEnum(new ByteArrayInputStream(s.getBytes()), charset, minLength);
- } catch (Exception e) {
+ } catch (final Exception e) {
return null;
}
}
@@ -489,13 +489,13 @@ public final class plasmaCondenser {
unsievedWordsEnum e;
int ml;
- public sievedWordsEnum(InputStream is, String charset, int minLength) throws UnsupportedEncodingException {
+ public sievedWordsEnum(final InputStream is, final String charset, final int minLength) throws UnsupportedEncodingException {
e = new unsievedWordsEnum(is, charset);
buffer = nextElement0();
ml = minLength;
}
- public void pre(boolean x) {
+ public void pre(final boolean x) {
e.pre(x);
}
@@ -524,7 +524,7 @@ public final class plasmaCondenser {
}
public StringBuffer nextElement() {
- StringBuffer r = buffer;
+ final StringBuffer r = buffer;
buffer = nextElement0();
return r;
}
@@ -537,13 +537,13 @@ public final class plasmaCondenser {
sentencesFromInputStreamEnum e;
StringBuffer s;
- public unsievedWordsEnum(InputStream is, String charset) throws UnsupportedEncodingException {
+ public unsievedWordsEnum(final InputStream is, final String charset) throws UnsupportedEncodingException {
e = new sentencesFromInputStreamEnum(is, charset);
s = new StringBuffer(20);
buffer = nextElement0();
}
- public void pre(boolean x) {
+ public void pre(final boolean x) {
e.pre(x);
}
@@ -569,7 +569,7 @@ public final class plasmaCondenser {
return null;
}
}
- int p = s.indexOf(" ");
+ final int p = s.indexOf(" ");
if (p < 0) {
r = s;
s = new StringBuffer();
@@ -585,7 +585,7 @@ public final class plasmaCondenser {
}
public StringBuffer nextElement() {
- StringBuffer r = buffer;
+ final StringBuffer r = buffer;
buffer = nextElement0();
return r;
}
@@ -598,10 +598,10 @@ public final class plasmaCondenser {
return sb;
}
- public static sentencesFromInputStreamEnum sentencesFromInputStream(InputStream is, String charset) {
+ public static sentencesFromInputStreamEnum sentencesFromInputStream(final InputStream is, final String charset) {
try {
return new sentencesFromInputStreamEnum(is, charset);
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
return null;
}
}
@@ -615,30 +615,30 @@ public final class plasmaCondenser {
int counter = 0;
boolean pre = false;
- public sentencesFromInputStreamEnum(InputStream is, String charset) throws UnsupportedEncodingException {
+ public sentencesFromInputStreamEnum(final InputStream is, final String charset) throws UnsupportedEncodingException {
raf = new BufferedReader((charset == null) ? new InputStreamReader(is) : new InputStreamReader(is, charset));
buffer = nextElement0();
counter = 0;
pre = false;
}
- public void pre(boolean x) {
+ public void pre(final boolean x) {
this.pre = x;
}
private StringBuffer nextElement0() {
try {
- StringBuffer s = readSentence(raf, pre);
+ final StringBuffer s = readSentence(raf, pre);
//System.out.println(" SENTENCE='" + s + "'"); // DEBUG
if (s == null) {
raf.close();
return null;
}
return s;
- } catch (IOException e) {
+ } catch (final IOException e) {
try {
raf.close();
- } catch (Exception ee) {
+ } catch (final Exception ee) {
}
return null;
}
@@ -653,7 +653,7 @@ public final class plasmaCondenser {
return null;
} else {
counter = counter + buffer.length() + 1;
- StringBuffer r = buffer;
+ final StringBuffer r = buffer;
buffer = nextElement0();
return r;
}
@@ -668,8 +668,8 @@ public final class plasmaCondenser {
}
}
- static StringBuffer readSentence(Reader reader, boolean pre) throws IOException {
- StringBuffer s = new StringBuffer(40);
+ static StringBuffer readSentence(final Reader reader, final boolean pre) throws IOException {
+ final StringBuffer s = new StringBuffer(40);
int nextChar;
char c, lc = ' '; // starting with ' ' as last character prevents that the result string starts with a ' '
@@ -697,36 +697,36 @@ public final class plasmaCondenser {
return s;
}
- public static Map<String, indexWord> getWords(byte[] text, String charset) throws UnsupportedEncodingException {
+ public static Map<String, indexWord> getWords(final byte[] text, final String charset) throws UnsupportedEncodingException {
// returns a word/indexWord relation map
if (text == null) return null;
- ByteArrayInputStream buffer = new ByteArrayInputStream(text);
+ final ByteArrayInputStream buffer = new ByteArrayInputStream(text);
return new plasmaCondenser(buffer, charset, 2, 1).words();
}
- public static Map<String, indexWord> getWords(String text) {
+ public static Map<String, indexWord> getWords(final String text) {
// returns a word/indexWord relation map
if (text == null) return null;
- ByteArrayInputStream buffer = new ByteArrayInputStream(text.getBytes());
+ final ByteArrayInputStream buffer = new ByteArrayInputStream(text.getBytes());
try {
return new plasmaCondenser(buffer, "UTF-8", 2, 1).words();
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
return null;
}
}
- public static void main(String[] args) {
+ public static void main(final String[] args) {
// read a property file and convert them into configuration lines
try {
- File f = new File(args[0]);
- Properties p = new Properties();
+ final File f = new File(args[0]);
+ final Properties p = new Properties();
p.load(new FileInputStream(f));
- StringBuffer sb = new StringBuffer();
+ final StringBuffer sb = new StringBuffer();
sb.append("{\n");
for (int i = 0; i <= 15; i++) {
sb.append('"');
- String s = p.getProperty("keywords" + i);
- String[] l = s.split(",");
+ final String s = p.getProperty("keywords" + i);
+ final String[] l = s.split(",");
for (int j = 0; j < l.length; j++) {
sb.append(indexWord.word2hash(l[j]));
}
@@ -734,9 +734,9 @@ public final class plasmaCondenser {
}
sb.append("}\n");
System.out.println(new String(sb));
- } catch (FileNotFoundException e) {
+ } catch (final FileNotFoundException e) {
e.printStackTrace();
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
diff --git a/source/de/anomic/plasma/plasmaDHTChunk.java b/source/de/anomic/plasma/plasmaDHTChunk.java
index e6188f7d6..bb6122e63 100644
--- a/source/de/anomic/plasma/plasmaDHTChunk.java
+++ b/source/de/anomic/plasma/plasmaDHTChunk.java
@@ -99,7 +99,7 @@ public class plasmaDHTChunk {
return urlCache;
}
- public void setStatus(int newStatus) {
+ public void setStatus(final int newStatus) {
this.status = newStatus;
}
@@ -107,7 +107,7 @@ public class plasmaDHTChunk {
return this.status;
}
- public plasmaDHTChunk(serverLog log, plasmaWordIndex wordIndex, int minCount, int maxCount, int maxtime) {
+ public plasmaDHTChunk(final serverLog log, final plasmaWordIndex wordIndex, final int minCount, final int maxCount, final int maxtime) {
try {
this.log = log;
this.wordIndex = wordIndex;
@@ -121,12 +121,12 @@ public class plasmaDHTChunk {
if (this.log.isFine()) log.logFine("Too few (" + this.idxCount + ") indexes selected for transfer.");
this.status = chunkStatus_FAILED;
}
- } catch (InterruptedException e) {
+ } catch (final InterruptedException e) {
this.status = chunkStatus_INTERRUPTED;
}
}
- public plasmaDHTChunk(serverLog log, plasmaWordIndex wordIndex, int minCount, int maxCount, int maxtime, String startHash) {
+ public plasmaDHTChunk(final serverLog log, final plasmaWordIndex wordIndex, final int minCount, final int maxCount, final int maxtime, final String startHash) {
try {
this.log = log;
this.wordIndex = wordIndex;
@@ -139,7 +139,7 @@ public class plasmaDHTChunk {
if (this.log.isFine()) log.logFine("Too few (" + this.idxCount + ") indexes selected for transfer.");
this.status = chunkStatus_FAILED;
}
- } catch (InterruptedException e) {
+ } catch (final InterruptedException e) {
this.status = chunkStatus_INTERRUPTED;
}
}
@@ -147,7 +147,7 @@ public class plasmaDHTChunk {
private String selectTransferStart() {
String startPointHash;
// first try to select with increasing probality a good start point
- double minimumDistance = ((double) peerRedundancy) / ((double) wordIndex.seedDB.sizeConnected());
+ final double minimumDistance = ((double) peerRedundancy) / ((double) wordIndex.seedDB.sizeConnected());
double d, bestDistance = 0.0;
String bestHash = null;
for (int i = wordIndex.seedDB.sizeConnected() / 8; i > 0; i--) {
@@ -169,15 +169,15 @@ public class plasmaDHTChunk {
}
}
- private void selectTransferContainers(String hash, int mincount, int maxcount, int maxtime) throws InterruptedException {
+ private void selectTransferContainers(final String hash, final int mincount, final int maxcount, final int maxtime) throws InterruptedException {
try {
this.selectionStartTime = System.currentTimeMillis();
- int refcountRAM = selectTransferContainersResource(hash, true, maxcount, maxtime);
+ final int refcountRAM = selectTransferContainersResource(hash, true, maxcount, maxtime);
if (refcountRAM >= mincount) {
if (this.log.isFine()) log.logFine("DHT selection from RAM: " + refcountRAM + " entries");
return;
}
- int refcountFile = selectTransferContainersResource(hash, false, maxcount, maxtime);
+ final int refcountFile = selectTransferContainersResource(hash, false, maxcount, maxtime);
if (this.log.isFine()) log.logFine("DHT selection from FILE: " + refcountFile + " entries, RAM provided only " + refcountRAM + " entries");
return;
} finally {
@@ -185,7 +185,7 @@ public class plasmaDHTChunk {
}
}
- private int selectTransferContainersResource(String hash, boolean ram, int maxcount, int maxtime) throws InterruptedException {
+ private int selectTransferContainersResource(final String hash, final boolean ram, final int maxcount, final int maxtime) throws InterruptedException {
// if (maxcount > 500) { maxcount = 500; } // flooding & OOM reduce
// the hash is a start hash from where the indexes are picked
final ArrayList<indexContainer> tmpContainers = new ArrayList<indexContainer>(maxcount);
@@ -250,7 +250,7 @@ public class plasmaDHTChunk {
// use whats left
if (this.log.isFine()) log.logFine("Selected partial index (" + container.size() + " from " + wholesize + " URLs, " + notBoundCounter + " not bound) for word " + container.getWordHash());
tmpContainers.add(container);
- } catch (kelondroException e) {
+ } catch (final kelondroException e) {
log.logSevere("plasmaWordIndexDistribution/2: deleted DB for word " + container.getWordHash(), e);
wordIndex.deleteContainer(container.getWordHash());
}
@@ -266,7 +266,7 @@ public class plasmaDHTChunk {
this.status = chunkStatus_FILLED;
return refcount;
- } catch (kelondroException e) {
+ } catch (final kelondroException e) {
log.logSevere("selectTransferIndexes database corrupted: " + e.getMessage(), e);
indexContainers = new indexContainer[0];
urlCache = new HashMap<String, indexURLReference>();
@@ -287,14 +287,14 @@ public class plasmaDHTChunk {
if (this.log.isFine()) log.logFine("Deletion of partial index #" + i + " not possible, entry is null");
continue;
}
- int c = this.indexContainers[i].size();
+ final int c = this.indexContainers[i].size();
urlHashes = new HashSet<String>(this.indexContainers[i].size());
urlIter = this.indexContainers[i].entries();
while (urlIter.hasNext()) {
iEntry = urlIter.next();
urlHashes.add(iEntry.urlHash());
}
- String wordHash = indexContainers[i].getWordHash();
+ final String wordHash = indexContainers[i].getWordHash();
count = wordIndex.removeEntriesExpl(this.indexContainers[i].getWordHash(), urlHashes);
if (log.isFine())
if (this.log.isFine()) log.logFine("Deleted partial index (" + c + " URLs) for word " + wordHash + "; " + this.wordIndex.indexSize(wordHash) + " entries left");
diff --git a/source/de/anomic/plasma/plasmaDHTFlush.java b/source/de/anomic/plasma/plasmaDHTFlush.java
index 641d35a11..ac0608cde 100644
--- a/source/de/anomic/plasma/plasmaDHTFlush.java
+++ b/source/de/anomic/plasma/plasmaDHTFlush.java
@@ -45,10 +45,10 @@ public class plasmaDHTFlush extends Thread {
private final long startingTime = System.currentTimeMillis();
private final plasmaSwitchboard sb;
private plasmaDHTTransfer worker = null;
- private serverLog log;
- private plasmaWordIndex wordIndex;
+ private final serverLog log;
+ private final plasmaWordIndex wordIndex;
- public plasmaDHTFlush(serverLog log, plasmaWordIndex wordIndex, yacySeed seed, boolean delete, boolean gzipBody, int timeout) {
+ public plasmaDHTFlush(final serverLog log, final plasmaWordIndex wordIndex, final yacySeed seed, final boolean delete, final boolean gzipBody, final int timeout) {
super(new ThreadGroup("TransferIndexThreadGroup"),"TransferIndex_" + seed.getName());
this.log = log;
this.wordIndex = wordIndex;
@@ -65,7 +65,7 @@ public class plasmaDHTFlush extends Thread {
this.performTransferWholeIndex();
}
- public void stopIt(boolean wait) throws InterruptedException {
+ public void stopIt(final boolean wait) throws InterruptedException {
this.finished = true;
if (this.worker != null) this.worker.stopIt();
if (wait) this.join();
@@ -80,7 +80,7 @@ public class plasmaDHTFlush extends Thread {
}
public int[] getIndexCount() {
- plasmaDHTTransfer workerThread = this.worker;
+ final plasmaDHTTransfer workerThread = this.worker;
if (workerThread != null) {
return new int[]{this.chunkSize, workerThread.dhtChunk.indexCount()};
}
@@ -100,7 +100,7 @@ public class plasmaDHTFlush extends Thread {
}
public float getTransferedContainerPercent() {
- long currentWordsDBSize = this.sb.webIndex.size();
+ final long currentWordsDBSize = this.sb.webIndex.size();
if (this.initialWordsDBSize == 0) return 100;
else if (currentWordsDBSize >= this.initialWordsDBSize) return 0;
//else return (float) ((initialWordsDBSize-currentWordsDBSize)/(initialWordsDBSize/100));
@@ -118,7 +118,7 @@ public class plasmaDHTFlush extends Thread {
}
public String[] getStatus() {
- plasmaDHTTransfer workerThread = this.worker;
+ final plasmaDHTTransfer workerThread = this.worker;
if (workerThread != null) {
return new String[]{this.status,workerThread.getStatusMessage()};
}
@@ -126,7 +126,7 @@ public class plasmaDHTFlush extends Thread {
}
public String[] getRange() {
- plasmaDHTTransfer workerThread = this.worker;
+ final plasmaDHTTransfer workerThread = this.worker;
if (workerThread != null) {
return new String[]{"[" + this.oldStartingPointHash + ".." + this.startPointHash + "]",
"[" + workerThread.dhtChunk.firstContainer().getWordHash() + ".." + workerThread.dhtChunk.lastContainer().getWordHash() + "]"};
@@ -210,7 +210,7 @@ public class plasmaDHTFlush extends Thread {
// deleting transfered words from index
if (this.delete) {
this.status = "Running: Deleting chunk " + iteration;
- String urlReferences = oldDHTChunk.deleteTransferIndexes();
+ final String urlReferences = oldDHTChunk.deleteTransferIndexes();
if (this.log.isFine()) this.log.logFine("Deleted from " + oldDHTChunk.containerSize() + " transferred RWIs locally " + urlReferences + " URL references");
}
oldDHTChunk = null;
@@ -226,14 +226,14 @@ public class plasmaDHTFlush extends Thread {
// if we reach this point we were aborted by the user or by server shutdown
if (this.sb.webIndex.size() > 0) this.status = "aborted";
- } catch (Exception e) {
+ } catch (final Exception e) {
this.status = "Error: " + e.getMessage();
this.log.logWarning("Index transfer to peer " + this.seed.getName() + ":" + this.seed.hash + " failed:'" + e.getMessage() + "'",e);
} finally {
if (this.worker != null) {
this.worker.stopIt();
- try {this.worker.join();}catch(Exception e){}
+ try {this.worker.join();}catch(final Exception e){}
}
}
}
@@ -243,10 +243,10 @@ public class plasmaDHTFlush extends Thread {
this.chunkSize = this.worker.dhtChunk.indexCount();
// getting the chunk selection time
- long selectionTime = this.worker.dhtChunk.getSelectionTime();
+ final long selectionTime = this.worker.dhtChunk.getSelectionTime();
// getting the chunk transfer time
- long transferTime = this.worker.getTransferTime();
+ final long transferTime = this.worker.getTransferTime();
// calculationg the new chunk size
if (transferTime > 60*1000 && this.chunkSize>200) {
@@ -260,7 +260,7 @@ public class plasmaDHTFlush extends Thread {
}
}
- private static boolean nothingSelected(plasmaDHTChunk newDHTChunk) {
+ private static boolean nothingSelected(final plasmaDHTChunk newDHTChunk) {
return (newDHTChunk == null) ||
(newDHTChunk.containerSize() == 0) ||
(newDHTChunk.getStatus() == plasmaDHTChunk.chunkStatus_FAILED);
diff --git a/source/de/anomic/plasma/plasmaDHTTransfer.java b/source/de/anomic/plasma/plasmaDHTTransfer.java
index bf1c58330..87df13f8e 100644
--- a/source/de/anomic/plasma/plasmaDHTTransfer.java
+++ b/source/de/anomic/plasma/plasmaDHTTransfer.java
@@ -54,21 +54,21 @@ public class plasmaDHTTransfer extends Thread {
plasmaDHTChunk dhtChunk;
// other fields
- private yacySeedDB seedDB;
- private yacyPeerActions peerActions;
- private int maxRetry;
+ private final yacySeedDB seedDB;
+ private final yacyPeerActions peerActions;
+ private final int maxRetry;
private int transferMode = TRANSFER_MODE_DISTRIBUTION;
serverLog log;
public plasmaDHTTransfer(
- serverLog log,
- yacySeedDB seedDB,
- yacyPeerActions peerActions,
- yacySeed destSeed,
- plasmaDHTChunk dhtChunk,
- boolean gzipBody,
- int timeout,
- int retries
+ final serverLog log,
+ final yacySeedDB seedDB,
+ final yacyPeerActions peerActions,
+ final yacySeed destSeed,
+ final plasmaDHTChunk dhtChunk,
+ final boolean gzipBody,
+ final int timeout,
+ final int retries
) {
super(new ThreadGroup("TransferIndexThreadGroup"), "TransferIndexWorker_" + destSeed.getName());
this.log = log;
@@ -81,14 +81,14 @@ public class plasmaDHTTransfer extends Thread {
this.seed = destSeed;
}
- public void setTransferMode(int mode) {
+ public void setTransferMode(final int mode) {
this.transferMode = mode;
}
public void run() {
try {
this.uploadIndex();
- } catch (InterruptedException e) {
+ } catch (final InterruptedException e) {
e.printStackTrace();
}
}
@@ -133,15 +133,16 @@ public class plasmaDHTTransfer extends Thread {
* - the retry counter limit was exceeded
*/
this.transferStatus = plasmaDHTChunk.chunkStatus_RUNNING;
- long retryCount = 0, start = System.currentTimeMillis();
+ long retryCount = 0;
+ final long start = System.currentTimeMillis();
while (true) {
// testing if we were aborted
if (this.isAborted()) return;
// transfering seleted words to remote peer
this.transferStatusMessage = "Running: Transfering chunk to target " + this.seed.hash + "/" + this.seed.getName();
- HashMap<String, Object> result = yacyClient.transferIndex(this.seedDB, this.seed, this.dhtChunk.containers(), this.dhtChunk.urlCacheMap(), this.gzipBody4Transfer, this.timeout4Transfer);
- String error = (String) result.get("result");
+ final HashMap<String, Object> result = yacyClient.transferIndex(this.seedDB, this.seed, this.dhtChunk.containers(), this.dhtChunk.urlCacheMap(), this.gzipBody4Transfer, this.timeout4Transfer);
+ final String error = (String) result.get("result");
if (error == null) {
// words successfully transfered
this.transferTime = System.currentTimeMillis() - start;
@@ -159,7 +160,7 @@ public class plasmaDHTTransfer extends Thread {
// if the peer has set a pause time and we are in flush mode (index transfer)
// then we pause for a while now
if (this.transferMode == TRANSFER_MODE_FLUSH) {
- long pause = getBusyTime(result);
+ final long pause = getBusyTime(result);
if (pause != -1) {
this.transferStatusMessage = "Finished: Transfer of chunk to target " + this.seed.hash + "/" + this.seed.getName() + ". Pausing " + pause + " ms.";
this.pause(pause);
@@ -224,7 +225,7 @@ public class plasmaDHTTransfer extends Thread {
return;
// doing a peer ping to the remote seed
- int added = yacyClient.publishMySeed(this.seedDB.mySeed(), this.peerActions, this.seed.getPublicAddress(), this.seed.hash);
+ final int added = yacyClient.publishMySeed(this.seedDB.mySeed(), this.peerActions, this.seed.getPublicAddress(), this.seed.hash);
if (added < 0) {
// inc. retry counter
retryCount++;
@@ -243,23 +244,23 @@ public class plasmaDHTTransfer extends Thread {
}
@SuppressWarnings("unchecked")
- private long getBusyTime(HashMap<String, Object> result) {
+ private long getBusyTime(final HashMap<String, Object> result) {
int pause = -1;
- Object transferRWIResult = result.get("resultTransferRWI");
+ final Object transferRWIResult = result.get("resultTransferRWI");
assert transferRWIResult instanceof HashMap;
if (transferRWIResult != null && ((HashMap<String, String>) transferRWIResult).containsKey("pause")) {
- String pauseStr = ((HashMap<String, String>) transferRWIResult).get("pause");
- try { pause = Integer.valueOf(pauseStr).intValue(); } catch (NumberFormatException numEx){}
+ final String pauseStr = ((HashMap<String, String>) transferRWIResult).get("pause");
+ try { pause = Integer.valueOf(pauseStr).intValue(); } catch (final NumberFormatException numEx){}
if (pause < 0) pause = 5000;
else if (pause > 30000) pause = 30000;
}
return pause;
}
- private void pause(long sleepTime) throws InterruptedException {
+ private void pause(final long sleepTime) throws InterruptedException {
if (sleepTime == 0) return;
long sleepCounter = sleepTime / 1000;
- long sleepRest = sleepTime % 1000;
+ final long sleepRest = sleepTime % 1000;
while (!this.isAborted() && sleepCounter > 0) {
sleepCounter--;
Thread.sleep(1000);
diff --git a/source/de/anomic/plasma/plasmaDbImporter.java b/source/de/anomic/plasma/plasmaDbImporter.java
index 12587f673..4fcc557a5 100644
--- a/source/de/anomic/plasma/plasmaDbImporter.java
+++ b/source/de/anomic/plasma/plasmaDbImporter.java
@@ -17,13 +17,13 @@ public class plasmaDbImporter extends AbstractImporter implements Importer {
/**
* the source word index (the DB to import)
*/
- private plasmaWordIndex importWordIndex;
+ private final plasmaWordIndex importWordIndex;
/**
* the destination word index (the home DB)
*/
protected plasmaWordIndex homeWordIndex;
- private int importStartSize;
+ private final int importStartSize;
private String wordHash = "------------";
@@ -32,7 +32,7 @@ public class plasmaDbImporter extends AbstractImporter implements Importer {
private long urlCounter = 0, wordCounter = 0, entryCounter = 0, notBoundEntryCounter = 0;
- public plasmaDbImporter(plasmaWordIndex homeWI, plasmaWordIndex importWI) {
+ public plasmaDbImporter(final plasmaWordIndex homeWI, final plasmaWordIndex importWI) {
super("PLASMADB");
this.homeWordIndex = homeWI;
this.importWordIndex = importWI;
@@ -50,7 +50,7 @@ public class plasmaDbImporter extends AbstractImporter implements Importer {
* @see Importer#getStatus()
*/
public String getStatus() {
- StringBuffer theStatus = new StringBuffer();
+ final StringBuffer theStatus = new StringBuffer();
theStatus.append("Hash=").append(this.wordHash).append("\n");
theStatus.append("#URL=").append(this.urlCounter).append("\n");
@@ -96,15 +96,15 @@ public class plasmaDbImporter extends AbstractImporter implements Importer {
this.log.logInfo("Home word index contains " + homeWordIndex.size() + " words and " + homeWordIndex.countURL() + " URLs.");
this.log.logInfo("Import word index contains " + this.importWordIndex.size() + " words and " + this.importWordIndex.countURL() + " URLs.");
- HashSet<String> unknownUrlBuffer = new HashSet<String>();
- HashSet<String> importedUrlBuffer = new HashSet<String>();
+ final HashSet<String> unknownUrlBuffer = new HashSet<String>();
+ final HashSet<String> importedUrlBuffer = new HashSet<String>();
// iterate over all words from import db
//Iterator importWordHashIterator = this.importWordIndex.wordHashes(this.wordChunkStartHash, plasmaWordIndex.RL_WORDFILES, false);
Iterator<indexContainer> indexContainerIterator = this.importWordIndex.indexContainerSet(this.wordChunkStartHash, false, false, 100).iterator();
while (!isAborted() && indexContainerIterator.hasNext()) {
- TreeSet<String> entityUrls = new TreeSet<String>();
+ final TreeSet<String> entityUrls = new TreeSet<String>();
indexContainer newContainer = null;
try {
this.wordCounter++;
@@ -113,7 +113,7 @@ public class plasmaDbImporter extends AbstractImporter implements Importer {
// loop throug the entities of the container and get the
// urlhash
- Iterator<indexRWIRowEntry> importWordIdxEntries = newContainer.entries();
+ final Iterator<indexRWIRowEntry> importWordIdxEntries = newContainer.entries();
indexRWIEntry importWordIdxEntry;
while (importWordIdxEntries.hasNext()) {
// testing if import process was aborted
@@ -121,14 +121,14 @@ public class plasmaDbImporter extends AbstractImporter implements Importer {
// getting next word index entry
importWordIdxEntry = importWordIdxEntries.next();
- String urlHash = importWordIdxEntry.urlHash();
+ final String urlHash = importWordIdxEntry.urlHash();
entityUrls.add(urlHash);
}
- Iterator<String> urlIter = entityUrls.iterator();
+ final Iterator<String> urlIter = entityUrls.iterator();
while (urlIter.hasNext()) {
if (isAborted()) break;
- String urlHash = urlIter.next();
+ final String urlHash = urlIter.next();
if (!importedUrlBuffer.contains(urlHash)) {
if (unknownUrlBuffer.contains(urlHash)) {
@@ -141,7 +141,7 @@ public class plasmaDbImporter extends AbstractImporter implements Importer {
// we need to import the url
// getting the url entry
- indexURLReference urlEntry = this.importWordIndex.getURL(urlHash, null, 0);
+ final indexURLReference urlEntry = this.importWordIndex.getURL(urlHash, null, 0);
if (urlEntry != null) {
/* write it into the home url db */
@@ -183,7 +183,7 @@ public class plasmaDbImporter extends AbstractImporter implements Importer {
if (this.wordCounter%500 == 0) {
this.wordChunkEndHash = this.wordHash;
this.wordChunkEnd = System.currentTimeMillis();
- long duration = this.wordChunkEnd - this.wordChunkStart;
+ final long duration = this.wordChunkEnd - this.wordChunkStart;
this.log.logInfo(this.wordCounter + " word entities imported " +
"[" + this.wordChunkStartHash + " .. " + this.wordChunkEndHash + "] " +
this.getProcessingStatusPercent() + "%\n" +
@@ -196,7 +196,7 @@ public class plasmaDbImporter extends AbstractImporter implements Importer {
this.wordChunkStartHash = this.wordChunkEndHash;
}
- } catch (Exception e) {
+ } catch (final Exception e) {
this.log.logSevere("Import of word entity '" + this.wordHash + "' failed.",e);
} finally {
if (newContainer != null) newContainer.clear();
@@ -204,7 +204,7 @@ public class plasmaDbImporter extends AbstractImporter implements Importer {
if (!indexContainerIterator.hasNext()) {
// We may not be finished yet, try to get the next chunk of wordHashes
- TreeSet<indexContainer> containers = this.importWordIndex.indexContainerSet(this.wordHash, false, false, 100);
+ final TreeSet<indexContainer> containers = this.importWordIndex.indexContainerSet(this.wordHash, false, false, 100);
indexContainerIterator = containers.iterator();
// Make sure we don't get the same wordhash twice, but don't skip a word
if ((indexContainerIterator.hasNext())&&(!this.wordHash.equals((indexContainerIterator.next()).getWordHash()))) {
@@ -215,13 +215,13 @@ public class plasmaDbImporter extends AbstractImporter implements Importer {
this.log.logInfo("Home word index contains " + homeWordIndex.size() + " words and " + homeWordIndex.countURL() + " URLs.");
this.log.logInfo("Import word index contains " + this.importWordIndex.size() + " words and " + this.importWordIndex.countURL() + " URLs.");
- } catch (Exception e) {
+ } catch (final Exception e) {
this.log.logSevere("Database import failed.",e);
e.printStackTrace();
this.error = e.toString();
} finally {
this.log.logInfo("Import process finished.");
- if (this.importWordIndex != null) try { this.importWordIndex.close(); } catch (Exception e){}
+ if (this.importWordIndex != null) try { this.importWordIndex.close(); } catch (final Exception e){}
}
}
diff --git a/source/de/anomic/plasma/plasmaGrafics.java b/source/de/anomic/plasma/plasmaGrafics.java
index 349eed705..cb09288db 100644
--- a/source/de/anomic/plasma/plasmaGrafics.java
+++ b/source/de/anomic/plasma/plasmaGrafics.java
@@ -72,7 +72,7 @@ public class plasmaGrafics {
private long execTime = 0;
private float fraction = 0;
- public CircleThreadPiece(String pieceName, Color color) {
+ public CircleThreadPiece(final String pieceName, final Color color) {
this.pieceName = pieceName;
this.color = color;
}
@@ -83,13 +83,13 @@ public class plasmaGrafics {
public long getExecTime() { return this.execTime; }
public String getPieceName() { return this.pieceName; }
- public void addExecTime(long execTime) { this.execTime += execTime; }
+ public void addExecTime(final long execTime) { this.execTime += execTime; }
public void reset() {
this.execTime = 0;
this.fraction = 0;
}
- public void setExecTime(long execTime) { this.execTime = execTime; }
- public void setFraction(long totalBusyTime) {
+ public void setExecTime(final long execTime) { this.execTime = execTime; }
+ public void setFraction(final long totalBusyTime) {
this.fraction = (float)this.execTime / (float)totalBusyTime;
}
}
@@ -106,22 +106,22 @@ public class plasmaGrafics {
private static BufferedImage logo = null; // [MN]
private static long bannerPictureDate = 0; // [MN]
- public static ymageMatrix getSearchEventPicture(yacySeedDB seedDB, String eventID) {
- plasmaSearchEvent event = plasmaSearchEvent.getEvent(eventID);
+ public static ymageMatrix getSearchEventPicture(final yacySeedDB seedDB, final String eventID) {
+ final plasmaSearchEvent event = plasmaSearchEvent.getEvent(eventID);
if (event == null) return null;
- yacySearch[] primarySearches = event.getPrimarySearchThreads();
- yacySearch[] secondarySearches = event.getSecondarySearchThreads();
+ final yacySearch[] primarySearches = event.getPrimarySearchThreads();
+ final yacySearch[] secondarySearches = event.getSecondarySearchThreads();
if (primarySearches == null) return null; // this was a local search and there are no threads
// get a copy of a recent network picture
- ymageMatrix eventPicture = getNetworkPicture(seedDB, 120000, plasmaSwitchboard.getSwitchboard().getConfig("network.unit.name", "unspecified"), plasmaSwitchboard.getSwitchboard().getConfig("network.unit.description", "unspecified"), COL_BACKGROUND);
+ final ymageMatrix eventPicture = getNetworkPicture(seedDB, 120000, plasmaSwitchboard.getSwitchboard().getConfig("network.unit.name", "unspecified"), plasmaSwitchboard.getSwitchboard().getConfig("network.unit.description", "unspecified"), COL_BACKGROUND);
//if (eventPicture instanceof ymageMatrix) eventPicture = (ymageMatrix) eventPicture; //new ymageMatrix((ymageMatrix) eventPicture);
// TODO: fix cloning of ymageMatrix pictures
// get dimensions
- int cr = Math.min(eventPicture.getWidth(), eventPicture.getHeight()) / 5 - 20;
- int cx = eventPicture.getWidth() / 2;
- int cy = eventPicture.getHeight() / 2;
+ final int cr = Math.min(eventPicture.getWidth(), eventPicture.getHeight()) / 5 - 20;
+ final int cx = eventPicture.getWidth() / 2;
+ final int cy = eventPicture.getHeight() / 2;
String hash;
int angle;
@@ -146,8 +146,8 @@ public class plasmaGrafics {
}
// draw in the search target
- plasmaSearchQuery query = event.getQuery();
- Iterator<String> i = query.queryHashes.iterator();
+ final plasmaSearchQuery query = event.getQuery();
+ final Iterator<String> i = query.queryHashes.iterator();
eventPicture.setColor(ymageMatrix.GREY);
while (i.hasNext()) {
hash = i.next();
@@ -158,20 +158,20 @@ public class plasmaGrafics {
return eventPicture;
}
- public static ymageMatrix getNetworkPicture(yacySeedDB seedDB, long maxAge, String networkName, String networkTitle, String bgcolor) {
+ public static ymageMatrix getNetworkPicture(final yacySeedDB seedDB, final long maxAge, final String networkName, final String networkTitle, final String bgcolor) {
return getNetworkPicture(seedDB, maxAge, 640, 480, 300, 300, 1000, true, networkName, networkTitle, bgcolor);
}
- public static ymageMatrix getNetworkPicture(yacySeedDB seedDB, long maxAge, int width, int height, int passiveLimit, int potentialLimit, int maxCount, boolean corona, String networkName, String networkTitle, String bgcolor) {
+ public static ymageMatrix getNetworkPicture(final yacySeedDB seedDB, final long maxAge, final int width, final int height, final int passiveLimit, final int potentialLimit, final int maxCount, final boolean corona, final String networkName, final String networkTitle, final String bgcolor) {
if ((networkPicture == null) || ((System.currentTimeMillis() - networkPictureDate) > maxAge)) {
drawNetworkPicture(seedDB, width, height, passiveLimit, potentialLimit, maxCount, corona, networkName, networkTitle, bgcolor);
}
return networkPicture;
}
- private static void drawNetworkPicture(yacySeedDB seedDB, int width, int height, int passiveLimit, int potentialLimit, int maxCount, boolean corona, String networkName, String networkTitle, String bgcolor) {
+ private static void drawNetworkPicture(final yacySeedDB seedDB, final int width, final int height, final int passiveLimit, final int potentialLimit, final int maxCount, final boolean corona, final String networkName, final String networkTitle, final String bgcolor) {
- int innerradius = Math.min(width, height) / 5;
+ final int innerradius = Math.min(width, height) / 5;
int outerradius = innerradius + innerradius * seedDB.sizeConnected() / 100;
if (outerradius > innerradius * 2) outerradius = innerradius * 2;
@@ -245,11 +245,11 @@ public class plasmaGrafics {
networkPictureDate = System.currentTimeMillis();
}
- private static void drawNetworkPicturePeer(ymageMatrix img, int x, int y, int innerradius, int outerradius, yacySeed seed, String colorDot, String colorLine, String colorText, boolean corona) {
- String name = seed.getName().toUpperCase() /*+ ":" + seed.hash + ":" + (((double) ((int) (100 * (((double) yacySeed.dhtPosition(seed.hash)) / ((double) yacySeed.maxDHTDistance))))) / 100.0)*/;
+ private static void drawNetworkPicturePeer(final ymageMatrix img, final int x, final int y, final int innerradius, final int outerradius, final yacySeed seed, final String colorDot, final String colorLine, final String colorText, final boolean corona) {
+ final String name = seed.getName().toUpperCase() /*+ ":" + seed.hash + ":" + (((double) ((int) (100 * (((double) yacySeed.dhtPosition(seed.hash)) / ((double) yacySeed.maxDHTDistance))))) / 100.0)*/;
if (name.length() < shortestName) shortestName = name.length();
if (name.length() > longestName) longestName = name.length();
- int angle = (int) (360 * seed.dhtPosition());
+ final int angle = (int) (360 * seed.dhtPosition());
//System.out.println("Seed " + seed.hash + " has distance " + seed.dhtDistance() + ", angle = " + angle);
int linelength = 20 + outerradius * (20 * (name.length() - shortestName) / (longestName - shortestName) + (Math.abs(seed.hash.hashCode()) % 20)) / 60;
if (linelength > outerradius) linelength = outerradius;
@@ -273,7 +273,7 @@ public class plasmaGrafics {
long strength;
img.setColor("303030");
img.arcArc(x, y, innerradius, angle, dotsize + 1, dotsize + 1, 0, 360);
- int waveradius = innerradius / 2;
+ final int waveradius = innerradius / 2;
for (int r = 0; r < waveradius; r++) {
strength = (waveradius - r) * (long) (0x08 * ppm10 * (1.0 + Math.sin(Math.PI * 16 * r / waveradius))) / waveradius;
//System.out.println("r = " + r + ", Strength = " + strength);
@@ -283,24 +283,24 @@ public class plasmaGrafics {
}
}
- public static BufferedImage getPeerLoadPicture(long maxAge, int width, int height, CircleThreadPiece[] pieces, CircleThreadPiece fillRest) {
+ public static BufferedImage getPeerLoadPicture(final long maxAge, final int width, final int height, final CircleThreadPiece[] pieces, final CircleThreadPiece fillRest) {
if ((peerloadPicture == null) || ((System.currentTimeMillis() - peerloadPictureDate) > maxAge)) {
drawPeerLoadPicture(width, height, pieces, fillRest);
}
return peerloadPicture;
}
- private static void drawPeerLoadPicture(int width, int height, CircleThreadPiece[] pieces, CircleThreadPiece fillRest) {
+ private static void drawPeerLoadPicture(final int width, final int height, final CircleThreadPiece[] pieces, final CircleThreadPiece fillRest) {
//prepare image
peerloadPicture = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
- Graphics2D g = peerloadPicture.createGraphics();
+ final Graphics2D g = peerloadPicture.createGraphics();
g.setBackground(COL_LOAD_BG);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.clearRect(0,0,width,height);
- int circ_w = Math.min(width,height)-20; //width of the circle (r*2)
- int circ_x = width-circ_w-10; //x-coordinate of circle-left
- int circ_y = 10; //y-coordinate of circle-top
+ final int circ_w = Math.min(width,height)-20; //width of the circle (r*2)
+ final int circ_x = width-circ_w-10; //x-coordinate of circle-left
+ final int circ_y = 10; //y-coordinate of circle-top
int curr_angle = 0; //remember current angle
int i;
@@ -327,7 +327,7 @@ public class plasmaGrafics {
peerloadPictureDate = System.currentTimeMillis();
}
- private static void drawLegendLine(Graphics2D g, int x, int y, String caption, Color item_color) {
+ private static void drawLegendLine(final Graphics2D g, final int x, final int y, final String caption, final Color item_color) {
g.setColor(item_color);
g.fillRect(x, y-LEGEND_BOX_SIZE, LEGEND_BOX_SIZE, LEGEND_BOX_SIZE);
g.setColor(COL_BORDER);
@@ -338,7 +338,7 @@ public class plasmaGrafics {
}
//[MN]
- public static ymageMatrix getBannerPicture(long maxAge, int width, int height, String bgcolor, String textcolor, String bordercolor, String name, long links, long words, String type, int ppm, String network, int peers, long nlinks, long nwords, double nqph, long nppm) {
+ public static ymageMatrix getBannerPicture(final long maxAge, final int width, final int height, final String bgcolor, final String textcolor, final String bordercolor, final String name, final long links, final long words, final String type, final int ppm, final String network, final int peers, final long nlinks, final long nwords, final double nqph, final long nppm) {
if ((bannerPicture == null) || ((System.currentTimeMillis() - bannerPictureDate) > maxAge)) {
drawBannerPicture(width, height, bgcolor, textcolor, bordercolor, name, links, words, type, ppm, network, peers, nlinks, nwords, nqph, nppm, logo);
}
@@ -346,7 +346,7 @@ public class plasmaGrafics {
}
//[MN]
- public static ymageMatrix getBannerPicture(long maxAge, int width, int height, String bgcolor, String textcolor, String bordercolor, String name, long links, long words, String type, int ppm, String network, int peers, long nlinks, long nwords, double nqph, long nppm, BufferedImage newLogo) {
+ public static ymageMatrix getBannerPicture(final long maxAge, final int width, final int height, final String bgcolor, final String textcolor, final String bordercolor, final String name, final long links, final long words, final String type, final int ppm, final String network, final int peers, final long nlinks, final long nwords, final double nqph, final long nppm, final BufferedImage newLogo) {
if ((bannerPicture == null) || ((System.currentTimeMillis() - bannerPictureDate) > maxAge)) {
drawBannerPicture(width, height, bgcolor, textcolor, bordercolor, name, links, words, type, ppm, network, peers, nlinks, nwords, nqph, nppm, newLogo);
}
@@ -354,9 +354,9 @@ public class plasmaGrafics {
}
//[MN]
- private static void drawBannerPicture(int width, int height, String bgcolor, String textcolor, String bordercolor, String name, long links, long words, String type, int ppm, String network, int peers, long nlinks, long nwords, double nqph, long nppm, BufferedImage newLogo) {
+ private static void drawBannerPicture(final int width, final int height, final String bgcolor, final String textcolor, final String bordercolor, final String name, final long links, final long words, final String type, final int ppm, final String network, final int peers, final long nlinks, final long nwords, final double nqph, final long nppm, final BufferedImage newLogo) {
- int exprlength = 19;
+ final int exprlength = 19;
logo = newLogo;
bannerPicture = new ymageMatrix(width, height, ymageMatrix.MODE_REPLACE, bgcolor);
@@ -375,8 +375,8 @@ public class plasmaGrafics {
ymageToolPrint.print(bannerPicture, 285, 52, 0, "SPEED: " + addTrailingBlanks(nppm + " PAGES/MINUTE", exprlength), -1);
if (logo != null) {
- int x = (100/2 - logo.getWidth()/2);
- int y = (height/2 - logo.getHeight()/2);
+ final int x = (100/2 - logo.getWidth()/2);
+ final int y = (height/2 - logo.getHeight()/2);
bannerPicture.insertBitmap(logo, x, y, 0, 0, ymageMatrix.FILTER_ANTIALIASING);
}
@@ -400,12 +400,12 @@ public class plasmaGrafics {
}
//[MN]
- private static String addBlanksAndDots(long input, int length) {
+ private static String addBlanksAndDots(final long input, final int length) {
return addBlanksAndDots(input + "", length);
}
//[MN]
- private static String addBlanksAndDots(String input, int length) {
+ private static String addBlanksAndDots(String input, final int length) {
input = addDots(input);
input = addTrailingBlanks(input,length);
return input;
diff --git a/source/de/anomic/plasma/plasmaHTCache.java b/source/de/anomic/plasma/plasmaHTCache.java
index 60bb17e7b..cff631cd1 100644
--- a/source/de/anomic/plasma/plasmaHTCache.java
+++ b/source/de/anomic/plasma/plasmaHTCache.java
@@ -115,8 +115,8 @@ public final class plasmaHTCache {
public static final char LT_GLOBAL = 'G';
// doctype calculation
- public static char docType(yacyURL url) {
- String path = url.getPath().toLowerCase();
+ public static char docType(final yacyURL url) {
+ final String path = url.getPath().toLowerCase();
// serverLog.logFinest("PLASMA", "docType URL=" + path);
char doctype = DT_UNKNOWN;
if (path.endsWith(".gif")) { doctype = DT_IMAGE; }
@@ -141,7 +141,7 @@ public final class plasmaHTCache {
return doctype;
}
- public static char docType(String mime) {
+ public static char docType(final String mime) {
// serverLog.logFinest("PLASMA", "docType mime=" + mime);
char doctype = DT_UNKNOWN;
if (mime == null) doctype = DT_UNKNOWN;
@@ -185,7 +185,7 @@ public final class plasmaHTCache {
return doctype;
}
- public static void init(File htCachePath, long CacheSizeMax) {
+ public static void init(final File htCachePath, final long CacheSizeMax) {
cachePath = htCachePath;
maxCacheSize = CacheSizeMax;
@@ -247,26 +247,26 @@ public final class plasmaHTCache {
// 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 (ClassNotFoundException e) {
+ } catch (final ClassNotFoundException e) {
e.printStackTrace();
}
}
static void resetResponseHeaderDB() {
if (responseHeaderDB != null) responseHeaderDB.close();
- File dbfile = new File(cachePath, DB_NAME);
+ final File dbfile = new File(cachePath, DB_NAME);
if (dbfile.exists()) dbfile.delete();
openResponseHeaderDB();
}
private static void openResponseHeaderDB() {
// open the response header database
- File dbfile = new File(cachePath, DB_NAME);
+ final File dbfile = new File(cachePath, DB_NAME);
kelondroBLOB blob = null;
if (DB_NAME.endsWith("heap")) {
try {
blob = new kelondroBLOBHeap(dbfile, yacySeedDB.commonHashLength, kelondroBase64Order.enhancedCoder);
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
} else {
@@ -275,8 +275,8 @@ public final class plasmaHTCache {
responseHeaderDB = new kelondroMap(blob, 500);
}
- private static void deleteOldHTCache(File directory) {
- String[] list = directory.list();
+ private static void deleteOldHTCache(final File directory) {
+ final String[] list = directory.list();
if (list != null) {
File object;
for (int i = list.length - 1; i >= 0; i--) {
@@ -299,7 +299,7 @@ public final class plasmaHTCache {
return responseHeaderDB.size();
}
- public static void push(Entry entry) {
+ public static void push(final Entry entry) {
cacheStack.add(entry);
}
@@ -311,7 +311,7 @@ public final class plasmaHTCache {
* This method changes the HTCache size.<br>
* @param the new cache size in bytes
*/
- public static void setCacheSize(long newCacheSize) {
+ public static void setCacheSize(final long newCacheSize) {
maxCacheSize = newCacheSize;
}
@@ -323,20 +323,20 @@ public final class plasmaHTCache {
return (curCacheSize >= maxCacheSize) ? 0 : maxCacheSize - curCacheSize;
}
- public static boolean writeResourceContent(yacyURL url, byte[] array) {
+ public static boolean writeResourceContent(final yacyURL url, final byte[] array) {
if (array == null) return false;
- File file = getCachePath(url);
+ final File file = getCachePath(url);
try {
deleteFile(file);
file.getParentFile().mkdirs();
serverFileUtils.copy(array, file);
- } catch (FileNotFoundException e) {
+ } 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 (IOException e) {
+ } catch (final IOException e) {
log.logSevere("File storage failed (IO error): " + e.getMessage());
return false;
}
@@ -344,7 +344,7 @@ public final class plasmaHTCache {
return true;
}
- public static void writeFileAnnouncement(File file) {
+ public static void writeFileAnnouncement(final File file) {
if (file.exists()) {
curCacheSize += file.length();
if (System.currentTimeMillis() - lastcleanup > 300000) {
@@ -356,13 +356,13 @@ public final class plasmaHTCache {
}
}
- public static boolean deleteURLfromCache(yacyURL url) {
+ public static boolean deleteURLfromCache(final yacyURL url) {
if (deleteFileandDirs(getCachePath(url), "FROM")) {
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 (IOException e) {
+ } catch (final IOException e) {
resetResponseHeaderDB();
log.logInfo("IOExeption removing response header from DB: " + e.getMessage(), e);
}
@@ -371,9 +371,9 @@ public final class plasmaHTCache {
return false;
}
- private static boolean deleteFile(File obj) {
+ private static boolean deleteFile(final File obj) {
if (obj.exists()) {
- long size = obj.length();
+ final long size = obj.length();
if (obj.delete()) {
curCacheSize -= size;
return true;
@@ -382,7 +382,7 @@ public final class plasmaHTCache {
return false;
}
- private static boolean deleteFileandDirs(File path, String msg) {
+ 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
@@ -397,21 +397,21 @@ public final class plasmaHTCache {
return false;
}
- private static void cleanupDoIt(long newCacheSize) {
+ private static void cleanupDoIt(final long newCacheSize) {
File file;
- Iterator<Map.Entry<String, File>> iter = cacheAge.entrySet().iterator();
+ final Iterator<Map.Entry<String, File>> iter = cacheAge.entrySet().iterator();
Map.Entry<String, File> entry;
while (iter.hasNext() && curCacheSize >= newCacheSize) {
if (Thread.currentThread().isInterrupted()) return;
entry = iter.next();
- String key = entry.getKey();
+ final String key = entry.getKey();
file = entry.getValue();
- long t = Long.parseLong(key.substring(0, 16), 16);
+ final long t = Long.parseLong(key.substring(0, 16), 16);
if (System.currentTimeMillis() - t < 300000) break; // 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
- String urlHash = getHash(file);
+ final String urlHash = getHash(file);
if (deleteFileandDirs(file, "OLD")) {
try {
// As the file is gone, the entry in responseHeader.db is not needed anymore
@@ -419,13 +419,13 @@ public final class plasmaHTCache {
if (log.isFinest()) log.logFinest("Trying to remove responseHeader for URLhash: " + urlHash);
responseHeaderDB.remove(urlHash);
} else {
- yacyURL url = getURL(file);
+ 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 (IOException e) {
+ } catch (final IOException e) {
log.logInfo("IOExeption removing response header from DB: " + e.getMessage(), e);
}
}
@@ -453,8 +453,8 @@ public final class plasmaHTCache {
responseHeaderDB.close();
}
- private static String ageString(long date, File f) {
- StringBuffer sb = new StringBuffer(32);
+ 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);
@@ -466,32 +466,32 @@ public final class plasmaHTCache {
public static void cacheScan() {
log.logConfig("STARTING HTCACHE SCANNING");
- kelondroMScoreCluster<String> doms = new kelondroMScoreCluster<String>();
+ final kelondroMScoreCluster<String> doms = new kelondroMScoreCluster<String>();
int fileCount = 0;
- enumerateFiles fileEnum = new enumerateFiles(cachePath, true, false, true, true);
- File dbfile = new File(cachePath, "responseHeader.db");
+ final enumerateFiles fileEnum = new enumerateFiles(cachePath, true, false, true, true);
+ final File dbfile = new File(cachePath, "responseHeader.db");
while (fileEnum.hasMoreElements()) {
if (Thread.currentThread().isInterrupted()) return;
fileCount++;
- File nextFile = fileEnum.nextElement();
- long nextFileModDate = nextFile.lastModified();
+ 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 (InterruptedException e) {
+ } catch (final InterruptedException e) {
return;
}
}
//System.out.println("%" + (String) cacheAge.firstKey() + "=" + cacheAge.get(cacheAge.firstKey()));
long ageHours = 0;
if (!cacheAge.isEmpty()) {
- Iterator<String> i = cacheAge.keySet().iterator();
+ final Iterator<String> i = cacheAge.keySet().iterator();
if (i.hasNext()) try {
ageHours = (System.currentTimeMillis() - Long.parseLong(i.next().substring(0, 16), 16)) / 3600000;
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
ageHours = 0;
} else {
ageHours = 0;
@@ -505,13 +505,13 @@ public final class plasmaHTCache {
log.logConfig("STARTING DNS PREFETCH");
// start to prefetch IPs from DNS
String dom;
- long start = System.currentTimeMillis();
+ 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();
- InetAddress ip = serverDomains.dnsResolve(dom);
+ final InetAddress ip = serverDomains.dnsResolve(dom);
if (ip == null) continue;
result += ", " + dom + "=" + ip.getHostAddress();
log.logConfig("PRE-FILLED " + dom + "=" + ip.getHostAddress());
@@ -520,7 +520,7 @@ public final class plasmaHTCache {
// wait a short while to prevent that this looks like a DoS
try {
Thread.sleep(100);
- } catch (InterruptedException e) {
+ } catch (final InterruptedException e) {
return;
}
}
@@ -528,7 +528,7 @@ public final class plasmaHTCache {
" ADDRESSES: " + result.substring(2));
}
- private static String dom(File f) {
+ 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("\\");
@@ -545,7 +545,7 @@ public final class plasmaHTCache {
p = s.indexOf("/");
if (p < 0) p = s.indexOf("\\");
if (p < 0) return null;
- int e = s.indexOf("!");
+ final int e = s.indexOf("!");
if ((e > 0) && (e < p)) p = e; // strip port
return prefix + s.substring(0, p);
}
@@ -559,19 +559,19 @@ public final class plasmaHTCache {
* @throws <b>UnsupportedProtocolException</b> if the protocol is not supported and therefore the
* info object couldn't be created
*/
- public static IResourceInfo loadResourceInfo(yacyURL url) throws UnsupportedProtocolException, IllegalAccessException {
+ public static IResourceInfo loadResourceInfo(final yacyURL url) throws UnsupportedProtocolException, IllegalAccessException {
// loading data from database
Map<String, String> hdb;
try {
hdb = responseHeaderDB.get(url.hash());
- } catch (IOException e) {
+ } catch (final IOException e) {
return null;
}
if (hdb == null) return null;
// generate the cached object
- IResourceInfo cachedObj = objFactory.buildResourceInfoObj(url, hdb);
+ final IResourceInfo cachedObj = objFactory.buildResourceInfoObj(url, hdb);
return cachedObj;
}
@@ -587,12 +587,12 @@ public final class plasmaHTCache {
return (cacheStack.size() == 0);
}
- public static boolean isPicture(String mimeType) {
+ public static boolean isPicture(final String mimeType) {
if (mimeType == null) return false;
return mimeType.toUpperCase().startsWith("IMAGE");
}
- public static boolean isText(String mimeType) {
+ public static boolean isText(final String mimeType) {
// Object ct = response.get(httpHeader.CONTENT_TYPE);
// if (ct == null) return false;
// String t = ((String)ct).toLowerCase();
@@ -600,7 +600,7 @@ public final class plasmaHTCache {
return plasmaParser.supportedMimeTypesContains(mimeType);
}
- public static boolean noIndexingURL(yacyURL url) {
+ public static boolean noIndexingURL(final yacyURL url) {
if (url == null) return false;
String urlString = url.toString().toLowerCase();
@@ -619,7 +619,7 @@ public final class plasmaHTCache {
return plasmaParser.mediaExtContains(urlString);
}
- private static String replaceRegex(String input, String regex, String replacement) {
+ 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);
@@ -661,8 +661,8 @@ public final class plasmaHTCache {
path = replaceRegex(path, "/\\.\\./", "/!!/");
path = replaceRegex(path, "(\"|\\\\|\\*|\\?|:|<|>|\\|+)", "_"); // hier wird kein '/' gefiltert
String extention = null;
- int d = path.lastIndexOf(".");
- int s = path.lastIndexOf("/");
+ final int d = path.lastIndexOf(".");
+ final int s = path.lastIndexOf("/");
if ((d >= 0) && (d > s)) {
extention = path.substring(d);
} else if (path.endsWith("/ndx")) {
@@ -693,20 +693,20 @@ public final class plasmaHTCache {
} else {
host = "other/" + host;
}
- StringBuffer fileName = new StringBuffer();
+ final StringBuffer fileName = new StringBuffer();
fileName.append(protocol).append('/').append(host);
if (port >= 0) {
fileName.append('!').append(port);
}
// generate cache path
- File FileFlat = hashFile(fileName, "hash", extention, url.hash());
+ final File FileFlat = hashFile(fileName, "hash", extention, url.hash());
return FileFlat;
}
- private static File hashFile(StringBuffer fileName, String prefix, String extention, String urlhash) {
- String hexHash = yacySeed.b64Hash2hexHash(urlhash);
- StringBuffer f = new StringBuffer(fileName.length() + 30);
+ 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);
@@ -719,15 +719,15 @@ public final class plasmaHTCache {
*/
public static String getHash(final File f) {
if ((!f.isFile()) || (f.getPath().indexOf("hash") < 0)) return null;
- String name = f.getName();
+ final String name = f.getName();
if (name.length() < 18) return null; // not a hash file name
- String hexHash = name.substring(0,18);
+ final String hexHash = name.substring(0,18);
if (hexHash.indexOf('.') >= 0) return null;
try {
- String hash = kelondroBase64Order.enhancedCoder.encode(serverCodings.decodeHex(hexHash));
+ final String hash = kelondroBase64Order.enhancedCoder.encode(serverCodings.decodeHex(hexHash));
if (hash.length() == yacySeedDB.commonHashLength) return hash;
return null;
- } catch (Exception e) {
+ } catch (final Exception e) {
//log.logWarning("getHash: " + e.getMessage(), e);
return null;
}
@@ -745,7 +745,7 @@ public final class plasmaHTCache {
// try the urlPool
try {
url = plasmaSwitchboard.getSwitchboard().getURL(urlHash);
- } catch (Exception e) {
+ } catch (final Exception e) {
log.logWarning("getURL(" + urlHash + "): " /*+ e.getMessage()*/, e);
url = null;
}
@@ -754,15 +754,15 @@ public final class plasmaHTCache {
Map<String, String> hdb;
try {
hdb = responseHeaderDB.get(urlHash);
- } catch (IOException e1) {
+ } catch (final IOException e1) {
hdb = null;
}
if (hdb != null) {
- Object origRequestLine = hdb.get(httpHeader.X_YACY_ORIGINAL_REQUEST_LINE);
+ final Object origRequestLine = hdb.get(httpHeader.X_YACY_ORIGINAL_REQUEST_LINE);
if ((origRequestLine != null)&&(origRequestLine instanceof String)) {
int i = ((String)origRequestLine).indexOf(" ");
if (i >= 0) {
- String s = ((String)origRequestLine).substring(i).trim();
+ final String s = ((String)origRequestLine).substring(i).trim();
i = s.indexOf(" ");
try {
url = new yacyURL((i<0) ? s : s.substring(0,i), urlHash);
@@ -775,7 +775,7 @@ public final class plasmaHTCache {
if (url != null) return url;
}
// If we can't get the correct URL, it seems to be a treeed file
- String c = cachePath.toString().replace('\\', '/');
+ 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);
@@ -867,21 +867,21 @@ public final class plasmaHTCache {
* is available or the cached file is not readable, <code>null</code>
* is returned.
*/
- public static InputStream getResourceContentStream(yacyURL url) {
+ public static InputStream getResourceContentStream(final yacyURL url) {
// load the url as resource from the cache
- File f = getCachePath(url);
+ final File f = getCachePath(url);
if (f.exists() && f.canRead()) try {
return new BufferedInputStream(new FileInputStream(f));
- } catch (IOException e) {
+ } catch (final IOException e) {
log.logSevere("Unable to create a BufferedInputStream from file " + f,e);
return null;
}
return null;
}
- public static long getResourceContentLength(yacyURL url) {
+ public static long getResourceContentLength(final yacyURL url) {
// load the url as resource from the cache
- File f = getCachePath(url);
+ final File f = getCachePath(url);
if (f.exists() && f.canRead()) {
return f.length();
}
@@ -889,16 +889,16 @@ public final class plasmaHTCache {
}
public static Entry newEntry(
- Date initDate,
- int depth,
- yacyURL url,
- String name,
- String responseStatus,
- IResourceInfo docInfo,
- String initiator,
- CrawlProfile.entry profile
+ final Date initDate,
+ final int depth,
+ final yacyURL url,
+ final String name,
+ final String responseStatus,
+ final IResourceInfo docInfo,
+ final String initiator,
+ final CrawlProfile.entry profile
) {
- Entry entry = new Entry(
+ final Entry entry = new Entry(
initDate,
depth,
url,
@@ -915,23 +915,23 @@ public final class plasmaHTCache {
public final static class Entry {
// the class objects
- private Date initDate; // the date when the request happened; will be used as a key
- private int depth; // the depth of prefetching
- private String responseStatus;
- private File cacheFile; // the cache file
+ private final Date initDate; // the date when the request happened; will be used as a key
+ private final int depth; // the depth of prefetching
+ private final String responseStatus;
+ private final File cacheFile; // the cache file
private byte[] cacheArray; // or the cache as byte-array
- private yacyURL url;
- private String name; // the name of the link, read as anchor from an <a>-tag
- private Date lastModified;
+ private final yacyURL url;
+ private final String name; // the name of the link, read as anchor from an <a>-tag
+ private final Date lastModified;
private char doctype;
- private String language;
- private CrawlProfile.entry profile;
- private String initiator;
+ private final String language;
+ private final CrawlProfile.entry profile;
+ private final String initiator;
/**
* protocolspecific information about the resource
*/
- private IResourceInfo resInfo;
+ private final IResourceInfo resInfo;
protected Entry clone() throws CloneNotSupportedException {
return new Entry(
@@ -947,14 +947,14 @@ public final class plasmaHTCache {
}
@SuppressWarnings("null")
- public Entry(Date initDate,
- int depth,
- yacyURL url,
- String name,
- String responseStatus,
- IResourceInfo resourceInfo,
- String initiator,
- CrawlProfile.entry profile
+ public Entry(final Date initDate,
+ final int depth,
+ final yacyURL url,
+ final String name,
+ final String responseStatus,
+ final IResourceInfo resourceInfo,
+ final String initiator,
+ final CrawlProfile.entry profile
) {
if (resourceInfo == null){
System.out.println("Content information object is null. " + url);
@@ -1032,7 +1032,7 @@ public final class plasmaHTCache {
return this.cacheFile;
}
- public void setCacheArray(byte[] data) {
+ public void setCacheArray(final byte[] data) {
this.cacheArray = data;
}
@@ -1047,13 +1047,13 @@ public final class plasmaHTCache {
private boolean writeResourceInfo() {
if (this.resInfo == null) return false;
try {
- HashMap<String, String> hm = new HashMap<String, String>();
+ final HashMap<String, String> hm = new HashMap<String, String>();
hm.putAll(this.resInfo.getMap());
hm.put("@@URL", this.url.toNormalform(false, false));
hm.put("@@DEPTH", Integer.toString(this.depth));
if (this.initiator != null) hm.put("@@INITIATOR", this.initiator);
responseHeaderDB.put(this.url.hash(), hm);
- } catch (Exception e) {
+ } catch (final Exception e) {
resetResponseHeaderDB();
return false;
}
diff --git a/source/de/anomic/plasma/plasmaParser.java b/source/de/anomic/plasma/plasmaParser.java
index 1818d9af4..7ed80f11e 100644
--- a/source/de/anomic/plasma/plasmaParser.java
+++ b/source/de/anomic/plasma/plasmaParser.java
@@ -47,8 +47,8 @@ import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
-import java.util.regex.Pattern;
import java.util.regex.Matcher;
+import java.util.regex.Pattern;
import de.anomic.crawler.ErrorURL;
import de.anomic.htmlFilter.htmlFilterContentScraper;
@@ -62,8 +62,8 @@ import de.anomic.plasma.parser.ParserException;
import de.anomic.plasma.parser.ParserInfo;
import de.anomic.server.serverFileUtils;
import de.anomic.server.logging.serverLog;
-import de.anomic.yacy.yacyURL;
import de.anomic.tools.ListDirs;
+import de.anomic.yacy.yacyURL;
public final class plasmaParser {
public static final String PARSER_MODE_PROXY = "PROXY";
@@ -99,10 +99,10 @@ public final class plasmaParser {
BufferedInputStream bufferedIn = null;
try {
mimeTypeLookupByFileExt.load(bufferedIn = new BufferedInputStream(new FileInputStream(new File("httpd.mime"))));
- } catch (IOException e) {
+ } catch (final IOException e) {
System.err.println("ERROR: httpd.mime not found in settings path");
} finally {
- if (bufferedIn != null) try{bufferedIn.close();}catch(Exception e){}
+ if (bufferedIn != null) try{bufferedIn.close();}catch(final Exception e){}
}
}
@@ -149,10 +149,10 @@ public final class plasmaParser {
* @see #initMediaExt(String)
*/
static {
- String apps = "sit,hqx,img,dmg,exe,com,bat,sh,vbs,zip,jar";
- String audio = "mp2,mp3,ogg,aac,aif,aiff,wav";
- String video = "swf,avi,wmv,rm,mov,mpg,mpeg,ram,m4v";
- String image = "jpg,jpeg,jpe,gif,png,ico,bmp";
+ final String apps = "sit,hqx,img,dmg,exe,com,bat,sh,vbs,zip,jar";
+ final String audio = "mp2,mp3,ogg,aac,aif,aiff,wav";
+ final String video = "swf,avi,wmv,rm,mov,mpg,mpeg,ram,m4v";
+ final String image = "jpg,jpeg,jpe,gif,png,ico,bmp";
initMediaExt(extString2extList(
apps + "," + // application container
"tar,gz,bz2,arj,zip,rar," + // archive formats
@@ -172,7 +172,7 @@ public final class plasmaParser {
loadAvailableParserList();
}
- private serverLog theLogger = new serverLog("PARSER");
+ private final serverLog theLogger = new serverLog("PARSER");
public serverLog getLogger() {
return this.theLogger;
@@ -189,12 +189,12 @@ public final class plasmaParser {
* @param htmlParsableMimeTypes a list of mimetypes that can be parsed by the
* yacy html parser
*/
- public static void initHTMLParsableMimeTypes(String htmlParsableMimeTypes) {
- LinkedList<String> mimeTypes = new LinkedList<String>();
+ public static void initHTMLParsableMimeTypes(final String htmlParsableMimeTypes) {
+ final LinkedList<String> mimeTypes = new LinkedList<String>();
if ((htmlParsableMimeTypes == null) || (htmlParsableMimeTypes.length() == 0)) {
return;
}
- String[] realtimeParsableMimeTypeList = htmlParsableMimeTypes.split(",");
+ final String[] realtimeParsableMimeTypeList = htmlParsableMimeTypes.split(",");
for (int i = 0; i < realtimeParsableMimeTypeList.length; i++) {
mimeTypes.add(realtimeParsableMimeTypeList[i].toLowerCase().trim());
}
@@ -204,46 +204,46 @@ public final class plasmaParser {
}
}
- public static List<String> extString2extList(String extString) {
- LinkedList<String> extensions = new LinkedList<String>();
+ public static List<String> extString2extList(final String extString) {
+ final LinkedList<String> extensions = new LinkedList<String>();
if ((extString == null) || (extString.length() == 0)) {
return extensions;
} else {
- String[] xs = extString.split(",");
+ final String[] xs = extString.split(",");
for (int i = 0; i < xs.length; i++) extensions.add(xs[i].toLowerCase().trim());
}
return extensions;
}
- public static void initMediaExt(List<String> mediaExtList) {
+ public static void initMediaExt(final List<String> mediaExtList) {
synchronized (mediaExtSet) {
mediaExtSet.clear();
mediaExtSet.addAll(mediaExtList);
}
}
- public static void initImageExt(List<String> imageExtList) {
+ public static void initImageExt(final List<String> imageExtList) {
synchronized (imageExtSet) {
imageExtSet.clear();
imageExtSet.addAll(imageExtList);
}
}
- public static void initAudioExt(List<String> audioExtList) {
+ public static void initAudioExt(final List<String> audioExtList) {
synchronized (audioExtSet) {
audioExtSet.clear();
audioExtSet.addAll(audioExtList);
}
}
- public static void initVideoExt(List<String> videoExtList) {
+ public static void initVideoExt(final List<String> videoExtList) {
synchronized (videoExtSet) {
videoExtSet.clear();
videoExtSet.addAll(videoExtList);
}
}
- public static void initAppsExt(List<String> appsExtList) {
+ public static void initAppsExt(final List<String> appsExtList) {
synchronized (appsExtSet) {
appsExtSet.clear();
appsExtSet.addAll(appsExtList);
@@ -256,7 +256,7 @@ public final class plasmaParser {
}
}
- public static void initSupportedHTMLFileExt(List<String> supportedRealtimeFileExtList) {
+ public static void initSupportedHTMLFileExt(final List<String> supportedRealtimeFileExtList) {
synchronized (supportedHTMLFileExt) {
supportedHTMLFileExt.clear();
supportedHTMLFileExt.addAll(supportedRealtimeFileExtList);
@@ -270,18 +270,18 @@ public final class plasmaParser {
}
}
- public static boolean supportedHTMLContent(yacyURL url, String mimeType) {
+ public static boolean supportedHTMLContent(final yacyURL url, final String mimeType) {
return HTMLParsableMimeTypesContains(mimeType) && supportedHTMLFileExtContains(url);
}
- public static boolean supportedHTMLFileExtContains(yacyURL url) {
- String fileExt = getFileExt(url);
+ public static boolean supportedHTMLFileExtContains(final yacyURL url) {
+ final String fileExt = getFileExt(url);
synchronized (supportedHTMLFileExt) {
return supportedHTMLFileExt.contains(fileExt);
}
}
- public static String getFileExt(yacyURL url) {
+ public static String getFileExt(final yacyURL url) {
// getting the file path
String name = url.getPath();
@@ -312,28 +312,28 @@ public final class plasmaParser {
}
}
- public static boolean imageExtContains(String imageExt) {
+ public static boolean imageExtContains(final String imageExt) {
if (imageExt == null) return false;
synchronized (imageExtSet) {
return imageExtSet.contains(imageExt.trim().toLowerCase());
}
}
- public static boolean audioExtContains(String audioExt) {
+ public static boolean audioExtContains(final String audioExt) {
if (audioExt == null) return false;
synchronized (audioExtSet) {
return audioExtSet.contains(audioExt.trim().toLowerCase());
}
}
- public static boolean videoExtContains(String videoExt) {
+ public static boolean videoExtContains(final String videoExt) {
if (videoExt == null) return false;
synchronized (videoExtSet) {
return videoExtSet.contains(videoExt.trim().toLowerCase());
}
}
- public static boolean appsExtContains(String appsExt) {
+ public static boolean appsExtContains(final String appsExt) {
if (appsExt == null) return false;
synchronized (appsExtSet) {
return appsExtSet.contains(appsExt.trim().toLowerCase());
@@ -373,7 +373,7 @@ public final class plasmaParser {
// patch missing '-'
if (encoding.startsWith("windows") && encoding.length() > 7) {
- char c = encoding.charAt(7);
+ final char c = encoding.charAt(7);
if ((c >= '0') && (c <= '9')) {
encoding = "windows-" + encoding.substring(7);
}
@@ -382,13 +382,13 @@ public final class plasmaParser {
if (encoding.startsWith("ISO")) {
// patch typos
if (encoding.length() > 3) {
- char c = encoding.charAt(3);
+ final char c = encoding.charAt(3);
if ((c >= '0') && (c <= '9')) {
encoding = "ISO-" + encoding.substring(3);
}
}
if (encoding.length() > 8) {
- char c = encoding.charAt(8);
+ final char c = encoding.charAt(8);
if ((c >= '0') && (c <= '9')) {
encoding = encoding.substring(0, 8) + "-" + encoding.substring(8);
}
@@ -403,7 +403,7 @@ public final class plasmaParser {
// converting cp\d{4} -> windows-\d{4}
if (encoding.matches("CP([_-])?125[0-8]")) {
- char c = encoding.charAt(2);
+ final char c = encoding.charAt(2);
if ((c >= '0') && (c <= '9')) {
encoding = "windows-" + encoding.substring(2);
} else {
@@ -419,11 +419,11 @@ public final class plasmaParser {
if (mimeType == null) mimeType = "application/octet-stream";
mimeType = mimeType.trim().toLowerCase();
- int pos = mimeType.indexOf(';');
+ final int pos = mimeType.indexOf(';');
return ((pos < 0) ? mimeType : mimeType.substring(0, pos));
}
- public static String getMimeTypeByFileExt(String fileExt) {
+ public static String getMimeTypeByFileExt(final String fileExt) {
return mimeTypeLookupByFileExt.getProperty(fileExt,"application/octet-stream");
}
@@ -436,45 +436,45 @@ public final class plasmaParser {
plasmaParser.availableParserList.clear();
// getting the current java classpath
- String javaClassPath = System.getProperty("java.class.path");
+ final String javaClassPath = System.getProperty("java.class.path");
// getting the current package name
- String plasmaParserPkgName = plasmaParser.class.getPackage().getName() + ".parser";
+ final String plasmaParserPkgName = plasmaParser.class.getPackage().getName() + ".parser";
serverLog.logInfo("PARSER","Searching for additional content parsers in package " + plasmaParserPkgName);
// getting an uri to the parser subpackage
- String packageURI = plasmaParser.class.getResource("/"+plasmaParserPkgName.replace('.','/')).toString() + "/";
+ final String packageURI = plasmaParser.class.getResource("/"+plasmaParserPkgName.replace('.','/')).toString() + "/";
serverLog.logFine("PARSER", "Parser directory is " + packageURI);
/*
* loop through all subdirectories and test if we can
* find an additional parser class
*/
- ListDirs parserDir = new ListDirs(packageURI);
- ArrayList<String> parserClasses = parserDir.listFiles(".*/parser/[^/]+/[^/]+Parser\\.class");
+ final ListDirs parserDir = new ListDirs(packageURI);
+ final ArrayList<String> parserClasses = parserDir.listFiles(".*/parser/[^/]+/[^/]+Parser\\.class");
if (parserClasses == null) return;
final Pattern patternGetClassName = Pattern.compile(".*/([^/]+)\\.class");
final Pattern patternGetFullClassName = Pattern.compile(".*(/[^/]+/[^/]+)\\.class");
- for (String parserClassFile: parserClasses) {
+ for (final String parserClassFile: parserClasses) {
serverLog.logFine("PARSER", "Testing parser class " + parserClassFile);
- Matcher matcherClassName = patternGetClassName.matcher(parserClassFile);
+ final Matcher matcherClassName = patternGetClassName.matcher(parserClassFile);
matcherClassName.find();
- String className = matcherClassName.group(1);
- Matcher matcherFullClassName = patternGetFullClassName.matcher(parserClassFile);
+ final String className = matcherClassName.group(1);
+ final Matcher matcherFullClassName = patternGetFullClassName.matcher(parserClassFile);
matcherFullClassName.find();
- String fullClassName = plasmaParserPkgName + matcherFullClassName.group(1).replace("/", ".");
+ final String fullClassName = plasmaParserPkgName + matcherFullClassName.group(1).replace("/", ".");
try {
// trying to load the parser class by its name
- Class<?> parserClass = Class.forName(fullClassName);
- Object theParser0 = parserClass.newInstance();
+ final Class<?> parserClass = Class.forName(fullClassName);
+ final Object theParser0 = parserClass.newInstance();
if (!(theParser0 instanceof Parser)) continue;
- Parser theParser = (Parser) theParser0;
+ final Parser theParser = (Parser) theParser0;
// testing if all needed libx libraries are available
- String[] neededLibx = theParser.getLibxDependences();
- StringBuffer neededLibxBuf = new StringBuffer();
+ final String[] neededLibx = theParser.getLibxDependences();
+ final StringBuffer neededLibxBuf = new StringBuffer();
if (neededLibx != null) {
for (int libxId=0; libxId < neededLibx.length; libxId++) {
if (javaClassPath.indexOf(neededLibx[libxId]) == -1) {
@@ -487,10 +487,10 @@ public final class plasmaParser {
}
// loading the list of mime-types that are supported by this parser class
- Hashtable<String, String> supportedMimeTypes = theParser.getSupportedMimeTypes();
+ final Hashtable<String, String> supportedMimeTypes = theParser.getSupportedMimeTypes();
// creating a parser info object
- ParserInfo parserInfo = new ParserInfo();
+ final ParserInfo parserInfo = new ParserInfo();
parserInfo.parserClass = parserClass;
parserInfo.parserClassName = fullClassName;
parserInfo.libxDependencies = neededLibx;
@@ -498,9 +498,9 @@ public final class plasmaParser {
parserInfo.parserVersionNr = (theParser).getVersion();
parserInfo.parserName = (theParser).getName();
- Iterator<String> mimeTypeIterator = supportedMimeTypes.keySet().iterator();
+ final Iterator<String> mimeTypeIterator = supportedMimeTypes.keySet().iterator();
while (mimeTypeIterator.hasNext()) {
- String mimeType = mimeTypeIterator.next();
+ final String mimeType = mimeTypeIterator.next();
availableParserList.put(mimeType, parserInfo);
serverLog.logInfo("PARSER", "Found functional parser for mimeType '" + mimeType + "'." +
"\n\tName: " + parserInfo.parserName +
@@ -509,32 +509,32 @@ public final class plasmaParser {
((neededLibxBuf.length()>0)?"\n\tDependencies: " + neededLibxBuf.toString():""));
}
- } catch (Exception e) { /* we can ignore this for the moment */
+ } catch (final Exception e) { /* we can ignore this for the moment */
serverLog.logWarning("PARSER", "Parser '" + className + "' doesn't work correctly and will be ignored.\n [" + e.getClass().getName() + "]: " + e.getMessage());
e.printStackTrace();
- } catch (Error e) { /* we can ignore this for the moment */
+ } catch (final Error e) { /* we can ignore this for the moment */
serverLog.logWarning("PARSER", "Parser '" + className + "' doesn't work correctly and will be ignored.\n [" + e.getClass().getName() + "]: " + e.getMessage());
e.printStackTrace();
}
}
- } catch (Exception e) {
+ } catch (final Exception e) {
serverLog.logSevere("PARSER", "Unable to determine all installed parsers. " + e.toString());
}
}
public void close() {
// clearing the parser list
- Iterator<plasmaParserConfig> configs = parserConfigList.values().iterator();
+ final Iterator<plasmaParserConfig> configs = parserConfigList.values().iterator();
while (configs.hasNext()) {
- plasmaParserConfig currentConfig = configs.next();
+ final plasmaParserConfig currentConfig = configs.next();
synchronized (currentConfig.enabledParserList) {
currentConfig.enabledParserList.clear();
}
}
}
- public plasmaParserDocument parseSource(yacyURL location, String mimeType, String charset, byte[] sourceArray)
+ public plasmaParserDocument parseSource(final yacyURL location, final String mimeType, final String charset, final byte[] sourceArray)
throws InterruptedException, ParserException {
ByteArrayInputStream byteIn = null;
try {
@@ -543,7 +543,7 @@ public final class plasmaParser {
// testing if the resource is not empty
if (sourceArray == null || sourceArray.length == 0) {
- String errorMsg = "No resource content available (1).";
+ final String errorMsg = "No resource content available (1).";
this.theLogger.logInfo("Unable to parse '" + location + "'. " + errorMsg);
throw new ParserException(errorMsg,location,ErrorURL.DENIED_NOT_PARSEABLE_NO_CONTENT);
}
@@ -554,7 +554,7 @@ public final class plasmaParser {
// parsing the temp file
return parseSource(location, mimeType, charset, sourceArray.length, byteIn);
- } catch (Exception e) {
+ } catch (final Exception e) {
// Interrupted- and Parser-Exceptions should pass through
if (e instanceof InterruptedException) throw (InterruptedException) e;
if (e instanceof ParserException) throw (ParserException) e;
@@ -563,12 +563,12 @@ public final class plasmaParser {
this.theLogger.logSevere("Unexpected exception in parseSource from byte-array: " + e.getMessage(), e);
throw new ParserException("Unexpected exception while parsing " + location,location, e);
} finally {
- if (byteIn != null) try { byteIn.close(); } catch (Exception ex){/* ignore this */}
+ if (byteIn != null) try { byteIn.close(); } catch (final Exception ex){/* ignore this */}
}
}
- public plasmaParserDocument parseSource(yacyURL location, String theMimeType, String theDocumentCharset, File sourceFile) throws InterruptedException, ParserException {
+ public plasmaParserDocument parseSource(final yacyURL location, final String theMimeType, final String theDocumentCharset, final File sourceFile) throws InterruptedException, ParserException {
BufferedInputStream sourceStream = null;
try {
@@ -577,7 +577,7 @@ public final class plasmaParser {
// testing if the resource is not empty
if (!(sourceFile.exists() && sourceFile.canRead() && sourceFile.length() > 0)) {
- String errorMsg = sourceFile.exists() ? "Empty resource file." : "No resource content available (2).";
+ final String errorMsg = sourceFile.exists() ? "Empty resource file." : "No resource content available (2).";
this.theLogger.logInfo("Unable to parse '" + location + "'. " + errorMsg);
throw new ParserException(errorMsg,location,ErrorURL.DENIED_NOT_PARSEABLE_NO_CONTENT);
}
@@ -588,7 +588,7 @@ public final class plasmaParser {
// parsing the data
return this.parseSource(location, theMimeType, theDocumentCharset, sourceFile.length(), sourceStream);
- } catch (Exception e) {
+ } catch (final Exception e) {
// Interrupted- and Parser-Exceptions should pass through
if (e instanceof InterruptedException) throw (InterruptedException) e;
if (e instanceof ParserException) throw (ParserException) e;
@@ -597,7 +597,7 @@ public final class plasmaParser {
this.theLogger.logSevere("Unexpected exception in parseSource from File: " + e.getMessage(), e);
throw new ParserException("Unexpected exception while parsing " + location,location, e);
} finally {
- if (sourceStream != null) try { sourceStream.close(); } catch (Exception ex){/* ignore this */}
+ if (sourceStream != null) try { sourceStream.close(); } catch (final Exception ex){/* ignore this */}
}
}
@@ -612,7 +612,7 @@ public final class plasmaParser {
* @throws InterruptedException
* @throws ParserException
*/
- public plasmaParserDocument parseSource(yacyURL location, String theMimeType, String theDocumentCharset, long contentLength, InputStream sourceStream) throws InterruptedException, ParserException {
+ public plasmaParserDocument parseSource(final yacyURL location, final String theMimeType, final String theDocumentCharset, final long contentLength, final InputStream sourceStream) throws InterruptedException, ParserException {
Parser theParser = null;
String mimeType = null;
try {
@@ -623,15 +623,15 @@ public final class plasmaParser {
mimeType = normalizeMimeType(theMimeType);
// getting the file extension of the document
- String fileExt = getFileExt(location);
+ final String fileExt = getFileExt(location);
// getting the charset of the document
// TODO: do a charset detection here ....
- String documentCharset = patchCharsetEncoding(theDocumentCharset);
+ final String documentCharset = patchCharsetEncoding(theDocumentCharset);
// testing if parsing is supported for this resource
if (!plasmaParser.supportedContent(location,mimeType)) {
- String errorMsg = "No parser available to parse mimetype '" + mimeType + "'";
+ final String errorMsg = "No parser available to parse mimetype '" + mimeType + "'";
this.theLogger.logInfo("Unable to parse '" + location + "'. " + errorMsg);
throw new ParserException(errorMsg,location,ErrorURL.DENIED_WRONG_MIMETYPE_OR_EXT);
}
@@ -653,30 +653,30 @@ public final class plasmaParser {
} else if (HTMLParsableMimeTypesContains(mimeType)) {
doc = parseHtml(location, mimeType, documentCharset, sourceStream);
} else {
- String errorMsg = "No parser available to parse mimetype '" + mimeType + "'";
+ final String errorMsg = "No parser available to parse mimetype '" + mimeType + "'";
this.theLogger.logInfo("Unable to parse '" + location + "'. " + errorMsg);
throw new ParserException(errorMsg,location,ErrorURL.DENIED_WRONG_MIMETYPE_OR_EXT);
}
// check result
if (doc == null) {
- String errorMsg = "Unexpected error. Parser returned null.";
+ final String errorMsg = "Unexpected error. Parser returned null.";
this.theLogger.logInfo("Unable to parse '" + location + "'. " + errorMsg);
throw new ParserException(errorMsg,location);
}
return doc;
- } catch (UnsupportedEncodingException e) {
- String errorMsg = "Unsupported charset encoding: " + e.getMessage();
+ } catch (final UnsupportedEncodingException e) {
+ final String errorMsg = "Unsupported charset encoding: " + e.getMessage();
this.theLogger.logSevere("Unable to parse '" + location + "'. " + errorMsg, e);
throw new ParserException(errorMsg,location,ErrorURL.DENIED_UNSUPPORTED_CHARSET);
- } catch (Exception e) {
+ } catch (final Exception e) {
// Interrupted- and Parser-Exceptions should pass through
if (e instanceof InterruptedException) throw (InterruptedException) e;
if (e instanceof ParserException) throw (ParserException) e;
// log unexpected error
- String errorMsg = "Unexpected exception. " + e.getMessage();
+ final String errorMsg = "Unexpected exception. " + e.getMessage();
this.theLogger.logSevere("Unable to parse '" + location + "'. " + errorMsg, e);
throw new ParserException(errorMsg,location,e);
@@ -687,10 +687,10 @@ public final class plasmaParser {
}
}
- private plasmaParserDocument parseHtml(yacyURL location, String mimeType, String documentCharset, InputStream sourceStream) throws IOException, ParserException {
+ private plasmaParserDocument parseHtml(final yacyURL location, final String mimeType, final String documentCharset, final InputStream sourceStream) throws IOException, ParserException {
// make a scraper and transformer
- htmlFilterInputStream htmlFilter = new htmlFilterInputStream(sourceStream,documentCharset,location,null,false);
+ final htmlFilterInputStream htmlFilter = new htmlFilterInputStream(sourceStream,documentCharset,location,null,false);
String charset = htmlFilter.detectCharset();
if (charset == null) {
charset = documentCharset;
@@ -703,26 +703,26 @@ public final class plasmaParser {
}
// parsing the content
- htmlFilterContentScraper scraper = new htmlFilterContentScraper(location);
- htmlFilterWriter writer = new htmlFilterWriter(null,null,scraper,null,false);
+ final htmlFilterContentScraper scraper = new htmlFilterContentScraper(location);
+ final htmlFilterWriter writer = new htmlFilterWriter(null,null,scraper,null,false);
serverFileUtils.copy(htmlFilter, writer, charset);
writer.close();
//OutputStream hfos = new htmlFilterOutputStream(null, scraper, null, false);
//serverFileUtils.copy(sourceFile, hfos);
//hfos.close();
if (writer.binarySuspect()) {
- String errorMsg = "Binary data found in resource";
+ final String errorMsg = "Binary data found in resource";
this.theLogger.logSevere("Unable to parse '" + location + "'. " + errorMsg);
throw new ParserException(errorMsg,location);
}
return transformScraper(location, mimeType, documentCharset, scraper);
}
- public plasmaParserDocument transformScraper(yacyURL location, String mimeType, String charSet, htmlFilterContentScraper scraper) {
- String[] sections = new String[scraper.getHeadlines(1).length + scraper.getHeadlines(2).length + scraper.getHeadlines(3).length + scraper.getHeadlines(4).length];
+ public plasmaParserDocument transformScraper(final yacyURL location, final String mimeType, final String charSet, final htmlFilterContentScraper 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];
- plasmaParserDocument ppd = new plasmaParserDocument(
+ final plasmaParserDocument ppd = new plasmaParserDocument(
location,
mimeType,
charSet,
@@ -764,16 +764,16 @@ public final class plasmaParser {
}
// fetching a new parser object from pool
- Parser theParser = makeParser(parserClassName);
+ final Parser theParser = makeParser(parserClassName);
// checking if the created parser really supports the given mimetype
- Hashtable<String, String> supportedMimeTypes = theParser.getSupportedMimeTypes();
+ final Hashtable<String, String> supportedMimeTypes = theParser.getSupportedMimeTypes();
if ((supportedMimeTypes != null) && (supportedMimeTypes.containsKey(mimeType))) {
parserInfo.incUsageCounter();
return theParser;
}
- } catch (Exception e) {
+ } catch (final Exception e) {
System.err.println("ERROR: Unable to load the correct parser for type " + mimeType);
}
@@ -781,11 +781,11 @@ public final class plasmaParser {
}
- static Map<yacyURL, String> allReflinks(Collection<?> links) {
+ static Map<yacyURL, String> allReflinks(final Collection<?> links) {
// links is either a Set of Strings (with urls) or htmlFilterImageEntries
// we find all links that are part of a reference inside a url
- HashMap<yacyURL, String> v = new HashMap<yacyURL, String>();
- Iterator<?> i = links.iterator();
+ final HashMap<yacyURL, String> v = new HashMap<yacyURL, String>();
+ final Iterator<?> i = links.iterator();
Object o;
yacyURL url;
String u;
@@ -816,13 +816,13 @@ public final class plasmaParser {
if (!(v.containsKey(url))) v.put(url, "ref");
continue loop;
}
- } catch (MalformedURLException e) {}
+ } catch (final MalformedURLException e) {}
return v;
}
- static Map<yacyURL, String> allSubpaths(Collection<?> links) {
+ static Map<yacyURL, String> allSubpaths(final Collection<?> links) {
// links is either a Set of Strings (urls) or a Set of htmlFilterImageEntries
- HashSet<String> h = new HashSet<String>();
+ final HashSet<String> h = new HashSet<String>();
Iterator<?> i = links.iterator();
Object o;
yacyURL url;
@@ -849,21 +849,21 @@ public final class plasmaParser {
assert (u.length() < l) : "u = " + u;
pos = u.lastIndexOf('/');
}
- } catch (MalformedURLException e) {}
+ } catch (final MalformedURLException e) {}
// now convert the strings to yacyURLs
i = h.iterator();
- HashMap<yacyURL, String> v = new HashMap<yacyURL, String>();
+ final HashMap<yacyURL, String> v = new HashMap<yacyURL, String>();
while (i.hasNext()) {
u = (String) i.next();
try {
url = new yacyURL(u, null);
v.put(url, "sub");
- } catch (MalformedURLException e) {}
+ } catch (final MalformedURLException e) {}
}
return v;
}
- public static void main(String[] args) {
+ public static void main(final String[] args) {
//javac -sourcepath source source/de/anomic/plasma/plasmaParser.java
//java -cp source de.anomic.plasma.plasmaParser bug.html bug.out
try {
@@ -877,7 +877,7 @@ public final class plasmaParser {
System.err.println("Usage: java de.anomic.plasma.plasmaParser (-f filename|-u URL) [-m mimeType]");
}
- String mode = args[0];
+ final String mode = args[0];
JakartaCommonsHttpResponse res = null;
plasmaParserDocument document = null;
try { // close InputStream when done
@@ -888,7 +888,7 @@ public final class plasmaParser {
contentURL = new yacyURL(args[1], null);
// downloading the document content
- JakartaCommonsHttpClient client = new JakartaCommonsHttpClient(5000, null, null);
+ final JakartaCommonsHttpClient client = new JakartaCommonsHttpClient(5000, null, null);
res = client.GET(args[1]);
if (res.getStatusCode() != 200) {
@@ -910,7 +910,7 @@ public final class plasmaParser {
}
// creating a plasma parser
- plasmaParser theParser = new plasmaParser();
+ final plasmaParser theParser = new plasmaParser();
// configuring the html parsable mimeTypes
plasmaParser.initHTMLParsableMimeTypes("application/xhtml+xml,text/html,text/plain,text/sgml");
@@ -945,26 +945,26 @@ public final class plasmaParser {
// found links
int anchorNr = 0;
- Map<yacyURL, String> anchors = document.getAnchors();
- Iterator<yacyURL> anchorIter = anchors.keySet().iterator();
+ final Map<yacyURL, String> anchors = document.getAnchors();
+ final Iterator<yacyURL> anchorIter = anchors.keySet().iterator();
while (anchorIter.hasNext()) {
- yacyURL key = anchorIter.next();
+ final yacyURL key = anchorIter.next();
System.out.println("URL " + anchorNr + ":\t" + key.toString() + " | " + anchors.get(key));
anchorNr++;
}
document.close();
}
- } catch (Exception e) {
+ } catch (final Exception e) {
e.printStackTrace();
}
}
- public static boolean supportedContent(yacyURL url, String mimeType) {
+ public static boolean supportedContent(final yacyURL url, final String mimeType) {
if (url == null) throw new NullPointerException();
- Iterator<plasmaParserConfig> configs = parserConfigList.values().iterator();
+ final Iterator<plasmaParserConfig> configs = parserConfigList.values().iterator();
while (configs.hasNext()) {
- plasmaParserConfig currentConfig = configs.next();
+ final plasmaParserConfig currentConfig = configs.next();
synchronized (currentConfig.enabledParserList) {
if (currentConfig.supportedContent(url, mimeType)) return true;
}
@@ -973,16 +973,16 @@ public final class plasmaParser {
return false;
}
- public static boolean supportedContent(String parserMode, yacyURL url, String mimeType) {
+ public static boolean supportedContent(final String parserMode, final yacyURL url, final String mimeType) {
if (!PARSER_MODE.contains(parserMode)) throw new IllegalArgumentException();
if (url == null) throw new NullPointerException();
if (parserMode.equals(PARSER_MODE_IMAGE)) return true;
- plasmaParserConfig config = parserConfigList.get(parserMode);
+ final plasmaParserConfig config = parserConfigList.get(parserMode);
return (config == null)?false:config.supportedContent(url, mimeType);
}
- public static void initParseableMimeTypes(String parserMode, String configStr) {
+ public static void initParseableMimeTypes(final String parserMode, final String configStr) {
if (!PARSER_MODE.contains(parserMode)) throw new IllegalArgumentException();
plasmaParserConfig config = parserConfigList.get(parserMode);
@@ -993,7 +993,7 @@ public final class plasmaParser {
config.initParseableMimeTypes(configStr);
}
- public static String[] setEnabledParserList(String parserMode, Set<String> mimeTypeSet) {
+ public static String[] setEnabledParserList(final String parserMode, final Set<String> mimeTypeSet) {
if (!PARSER_MODE.contains(parserMode)) throw new IllegalArgumentException();
plasmaParserConfig config = parserConfigList.get(parserMode);
@@ -1004,10 +1004,10 @@ public final class plasmaParser {
return config.setEnabledParserList(mimeTypeSet);
}
- public static boolean supportedFileExtContains(String fileExt) {
- Iterator<plasmaParserConfig> configs = parserConfigList.values().iterator();
+ public static boolean supportedFileExtContains(final String fileExt) {
+ final Iterator<plasmaParserConfig> configs = parserConfigList.values().iterator();
while (configs.hasNext()) {
- plasmaParserConfig currentConfig = configs.next();
+ final plasmaParserConfig currentConfig = configs.next();
synchronized (currentConfig.enabledParserList) {
if (currentConfig.supportedFileExtContains(fileExt)) return true;
}
@@ -1016,10 +1016,10 @@ public final class plasmaParser {
return false;
}
- public static boolean supportedMimeTypesContains(String mimeType) {
- Iterator<plasmaParserConfig> configs = parserConfigList.values().iterator();
+ public static boolean supportedMimeTypesContains(final String mimeType) {
+ final Iterator<plasmaParserConfig> configs = parserConfigList.values().iterator();
while (configs.hasNext()) {
- plasmaParserConfig currentConfig = configs.next();
+ final plasmaParserConfig currentConfig = configs.next();
synchronized (currentConfig.enabledParserList) {
if (currentConfig.supportedMimeTypesContains(mimeType)) return true;
}
@@ -1028,21 +1028,21 @@ public final class plasmaParser {
return false;
}
- public static Parser makeParser(Object name) throws Exception {
+ public static Parser makeParser(final Object name) throws Exception {
if (!(name instanceof String))
throw new IllegalArgumentException("The object key must be of type string.");
// loading class by name
- Class<?> moduleClass = Class.forName((String)name);
+ final Class<?> moduleClass = Class.forName((String)name);
// instantiating class
- Parser theParser = (Parser) moduleClass.newInstance();
+ final Parser theParser = (Parser) moduleClass.newInstance();
// setting logger that should by used
- String parserShortName = ((String)name).substring("de.anomic.plasma.parser.".length(),((String)name).lastIndexOf("."));
+ final String parserShortName = ((String)name).substring("de.anomic.plasma.parser.".length(),((String)name).lastIndexOf("."));
- serverLog theLogger = new serverLog("PARSER." + parserShortName.toUpperCase());
+ final serverLog theLogger = new serverLog("PARSER." + parserShortName.toUpperCase());
theParser.setLogger(theLogger);
return theParser;
diff --git a/source/de/anomic/plasma/plasmaParserConfig.java b/source/de/anomic/plasma/plasmaParserConfig.java
index 1bd2bdd14..db99dd1be 100644
--- a/source/de/anomic/plasma/plasmaParserConfig.java
+++ b/source/de/anomic/plasma/plasmaParserConfig.java
@@ -28,6 +28,7 @@
package de.anomic.plasma;
import java.util.Arrays;
+import java.util.Enumeration;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
@@ -55,7 +56,7 @@ public class plasmaParserConfig {
*/
public String parserMode = null;
- public plasmaParserConfig(String theParserMode) {
+ public plasmaParserConfig(final String theParserMode) {
if (!plasmaParser.PARSER_MODE.contains(theParserMode)) {
throw new IllegalArgumentException("Unknown parser mode " + theParserMode);
}
@@ -63,7 +64,7 @@ public class plasmaParserConfig {
this.parserMode = theParserMode;
}
- public boolean supportedContent(yacyURL url, String mimeType) {
+ public boolean supportedContent(final yacyURL url, String mimeType) {
// TODO: we need some exceptions here to index URLs like this
// http://www.musicabona.com/respighi/12668/cd/index.html.fr
mimeType = plasmaParser.normalizeMimeType(mimeType);
@@ -90,11 +91,11 @@ public class plasmaParserConfig {
}
- public boolean supportedFileExt(yacyURL url) {
+ public boolean supportedFileExt(final yacyURL url) {
if (url == null) throw new NullPointerException();
// getting the file path
- String name = plasmaParser.getFileExt(url);
+ final String name = plasmaParser.getFileExt(url);
return supportedFileExtContains(name);
}
@@ -111,12 +112,12 @@ public class plasmaParserConfig {
}
}
- public void initParseableMimeTypes(String enabledMimeTypes) {
+ public void initParseableMimeTypes(final String enabledMimeTypes) {
HashSet<String> mimeTypes = null;
if ((enabledMimeTypes == null) || (enabledMimeTypes.length() == 0)) {
mimeTypes = new HashSet<String>();
} else {
- String[] enabledMimeTypeList = enabledMimeTypes.split(",");
+ final String[] enabledMimeTypeList = enabledMimeTypes.split(",");
mimeTypes = new HashSet<String>(enabledMimeTypeList.length);
for (int i = 0; i < enabledMimeTypeList.length; i++) mimeTypes.add(enabledMimeTypeList[i].toLowerCase().trim());
}
@@ -124,19 +125,19 @@ public class plasmaParserConfig {
}
public void enableAllParsers() {
- Set<String> availableMimeTypes = plasmaParser.availableParserList.keySet();
+ final Set<String> availableMimeTypes = plasmaParser.availableParserList.keySet();
setEnabledParserList(availableMimeTypes);
}
- public String[] setEnabledParserList(Set<String> mimeTypeSet) {
+ public String[] setEnabledParserList(final Set<String> mimeTypeSet) {
- HashSet<String> newEnabledParsers = new HashSet<String>();
- HashSet<String> newSupportedFileExt = new HashSet<String>();
+ final HashSet<String> newEnabledParsers = new HashSet<String>();
+ final HashSet<String> newSupportedFileExt = new HashSet<String>();
if (mimeTypeSet != null) {
- Iterator<String> mimeTypes = mimeTypeSet.iterator();
+ final Iterator<String> mimeTypes = mimeTypeSet.iterator();
while (mimeTypes.hasNext()) {
- String mimeType = mimeTypes.next();
+ final String mimeType = mimeTypes.next();
if (plasmaParser.availableParserList.containsKey(mimeType)) {
Parser theParser = null;
try {
@@ -144,19 +145,19 @@ public class plasmaParserConfig {
theParser = plasmaParser.makeParser((plasmaParser.availableParserList.get(mimeType)).parserClassName);
// getting a list of mimeTypes that the parser supports
- Hashtable<String, String> parserSupportsMimeTypes = theParser.getSupportedMimeTypes();
+ final Hashtable<String, String> parserSupportsMimeTypes = theParser.getSupportedMimeTypes();
if (parserSupportsMimeTypes != null) {
- Object supportedExtensions = parserSupportsMimeTypes.get(mimeType);
+ final Object supportedExtensions = parserSupportsMimeTypes.get(mimeType);
if ((supportedExtensions != null) &&
(supportedExtensions instanceof String) &&
(((String)supportedExtensions).length() > 0)) {
- String[] extArray = ((String)supportedExtensions).split(",");
+ final String[] extArray = ((String)supportedExtensions).split(",");
newSupportedFileExt.addAll(Arrays.asList(extArray));
}
}
newEnabledParsers.add(mimeType);
- } catch (Exception e) {
+ } catch (final Exception e) {
serverLog.logSevere("PARSER", "error in setEnabledParserList", e);
} finally {
if (theParser != null)
diff --git a/source/de/anomic/plasma/plasmaParserDocument.java b/source/de/anomic/plasma/plasmaParserDocument.java
index 8829236c4..81d616015 100644
--- a/source/de/anomic/plasma/plasmaParserDocument.java
+++ b/source/de/anomic/plasma/plasmaParserDocument.java
@@ -47,17 +47,17 @@ import de.anomic.yacy.yacyURL;
public class plasmaParserDocument {
- private yacyURL source; // the source url
- private String mimeType; // mimeType as taken from http header
- private String charset; // the charset of the document
- private List<String> keywords; // most resources provide a keyword field
- private StringBuffer title; // a document title, taken from title or h1 tag; shall appear as headline of search result
- private StringBuffer creator; // author or copyright
- private List<String> sections; // if present: more titles/headlines appearing in the document
- private StringBuffer description; // an abstract, if present: short content description
+ private final yacyURL 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
+ private final StringBuffer title; // a document title, taken from title or h1 tag; shall appear as headline of search result
+ private final StringBuffer creator; // author or copyright
+ private final List<String> sections; // if present: more titles/headlines appearing in the document
+ private final StringBuffer description; // an abstract, if present: short content description
private Object text; // the clear text, all that is visible
- private Map<yacyURL, String> anchors; // all links embedded as clickeable entities (anchor tags)
- private HashMap<String, htmlFilterImageEntry> images; // all visible pictures in document
+ private final Map<yacyURL, String> anchors; // all links embedded as clickeable entities (anchor tags)
+ private final HashMap<String, htmlFilterImageEntry> images; // all visible pictures in document
// the anchors and images - Maps are URL-to-EntityDescription mappings.
// The EntityDescription appear either as visible text in anchors or as alternative
// text in image tags.
@@ -68,10 +68,10 @@ public class plasmaParserDocument {
private InputStream textStream;
private int inboundLinks, outboundLinks; // counters for inbound and outbound links, are counted after calling notifyWebStructure
- protected plasmaParserDocument(yacyURL location, String mimeType, String charset,
- String[] keywords, String title, String author,
- String[] sections, String abstrct,
- Object text, Map<yacyURL, String> anchors, HashMap<String, htmlFilterImageEntry> images) {
+ protected plasmaParserDocument(final yacyURL location, final String mimeType, final String charset,
+ final String[] keywords, final String title, final String author,
+ final String[] sections, final String abstrct,
+ final Object text, final Map<yacyURL, String> anchors, final HashMap<String, htmlFilterImageEntry> images) {
this.source = location;
this.mimeType = (mimeType == null) ? "application/octet-stream" : mimeType;
this.charset = charset;
@@ -93,7 +93,7 @@ public class plasmaParserDocument {
if (text == null) try {
this.text = new serverCachedFileOutputStream(Parser.MAX_KEEP_IN_MEMORY_SIZE);
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
this.text = new StringBuffer();
} else {
@@ -101,28 +101,28 @@ public class plasmaParserDocument {
}
}
- public plasmaParserDocument(yacyURL location, String mimeType, String charset) {
+ public plasmaParserDocument(final yacyURL location, final String mimeType, final String charset) {
this(location, mimeType, charset, null, null, null, null, null, (Object)null, null, null);
}
- public plasmaParserDocument(yacyURL location, String mimeType, String charset,
- String[] keywords, String title, String author,
- String[] sections, String abstrct,
- byte[] text, Map<yacyURL, String> anchors, HashMap<String, htmlFilterImageEntry> images) {
+ public plasmaParserDocument(final yacyURL location, final String mimeType, final String charset,
+ final String[] keywords, final String title, final String author,
+ final String[] sections, final String abstrct,
+ final byte[] text, final Map<yacyURL, String> anchors, final HashMap<String, htmlFilterImageEntry> images) {
this(location, mimeType, charset, keywords, title, author, sections, abstrct, (Object)text, anchors, images);
}
- public plasmaParserDocument(yacyURL location, String mimeType, String charset,
- String[] keywords, String title, String author,
- String[] sections, String abstrct,
- File text, Map<yacyURL, String> anchors, HashMap<String, htmlFilterImageEntry> images) {
+ public plasmaParserDocument(final yacyURL location, final String mimeType, final String charset,
+ final String[] keywords, final String title, final String author,
+ final String[] sections, final String abstrct,
+ final File text, final Map<yacyURL, String> anchors, final HashMap<String, htmlFilterImageEntry> images) {
this(location, mimeType, charset, keywords, title, author, sections, abstrct, (Object)text, anchors, images);
}
- public plasmaParserDocument(yacyURL location, String mimeType, String charset,
- String[] keywords, String title, String author,
- String[] sections, String abstrct,
- serverCachedFileOutputStream text, Map<yacyURL, String> anchors, HashMap<String, htmlFilterImageEntry> images) {
+ public plasmaParserDocument(final yacyURL location, final String mimeType, final String charset,
+ final String[] keywords, final String title, final String author,
+ final String[] sections, final String abstrct,
+ final serverCachedFileOutputStream text, final Map<yacyURL, String> anchors, final HashMap<String, htmlFilterImageEntry> images) {
this(location, mimeType, charset, keywords, title, author, sections, abstrct, (Object)text, anchors, images);
}
@@ -154,9 +154,9 @@ dc_rights
if (creator != null) return creator.toString(); else return new String();
}
- public String dc_subject(char separator) {
+ public String dc_subject(final char separator) {
// sort out doubles and empty words
- TreeSet<String> hs = new TreeSet<String>();
+ final TreeSet<String> hs = new TreeSet<String>();
String s;
for (int i = 0; i < this.keywords.size(); i++) {
if (this.keywords.get(i) == null) continue;
@@ -165,8 +165,8 @@ dc_rights
}
if (hs.size() == 0) return "";
// generate a new list
- StringBuffer sb = new StringBuffer(this.keywords.size() * 6);
- Iterator<String> i = hs.iterator();
+ final StringBuffer sb = new StringBuffer(this.keywords.size() * 6);
+ final Iterator<String> i = hs.iterator();
while (i.hasNext()) sb.append(i.next()).append(separator);
return sb.substring(0, sb.length() - 1);
}
@@ -219,7 +219,7 @@ dc_rights
return ((serverCachedFileOutputStream)this.text).getContent();
}
return this.textStream;
- } catch (Exception e) {
+ } catch (final Exception e) {
e.printStackTrace();
}
return null;
@@ -234,14 +234,14 @@ dc_rights
} else if (this.text instanceof byte[]) {
return (byte[])this.text;
} else if (this.text instanceof serverCachedFileOutputStream) {
- serverCachedFileOutputStream ffbaos = (serverCachedFileOutputStream)this.text;
+ final serverCachedFileOutputStream ffbaos = (serverCachedFileOutputStream)this.text;
if (ffbaos.isFallback()) {
return serverFileUtils.read(ffbaos.getContent());
} else {
return ffbaos.getContentBAOS();
}
}
- } catch (Exception e) {
+ } catch (final Exception e) {
e.printStackTrace();
}
return new byte[0];
@@ -258,9 +258,9 @@ dc_rights
return -1;
}
- public Iterator<StringBuffer> getSentences(boolean pre) {
+ public Iterator<StringBuffer> getSentences(final boolean pre) {
if (this.text == null) return null;
- plasmaCondenser.sentencesFromInputStreamEnum e = plasmaCondenser.sentencesFromInputStream(getText(), this.charset);
+ final plasmaCondenser.sentencesFromInputStreamEnum e = plasmaCondenser.sentencesFromInputStream(getText(), this.charset);
e.pre(pre);
return e;
}
@@ -319,13 +319,13 @@ dc_rights
String u;
int extpos, qpos;
String ext = null;
- Iterator<Map.Entry<yacyURL, String>> i = anchors.entrySet().iterator();
+ final Iterator<Map.Entry<yacyURL, String>> i = anchors.entrySet().iterator();
hyperlinks = new HashMap<yacyURL, String>();
videolinks = new HashMap<yacyURL, String>();
audiolinks = new HashMap<yacyURL, String>();
applinks = new HashMap<yacyURL, String>();
emaillinks = new HashMap<String, String>();
- HashMap<String, htmlFilterImageEntry> collectedImages = new HashMap<String, htmlFilterImageEntry>(); // this is a set that is collected now and joined later to the imagelinks
+ final HashMap<String, htmlFilterImageEntry> collectedImages = new HashMap<String, htmlFilterImageEntry>(); // this is a set that is collected now and joined later to the imagelinks
Map.Entry<yacyURL, String> entry;
while (i.hasNext()) {
entry = i.next();
@@ -381,7 +381,7 @@ dc_rights
this.resorted = true;
}
- public void addSubDocument(plasmaParserDocument doc) throws IOException {
+ public void addSubDocument(final plasmaParserDocument doc) throws IOException {
this.sections.addAll(Arrays.asList(doc.getSectionTitles()));
if (this.title.length() > 0) this.title.append('\n');
@@ -412,12 +412,12 @@ dc_rights
/**
* @param faviconURL the {@link URL} to the favicon that belongs to the document
*/
- public void setFavicon(yacyURL faviconURL) {
+ public void setFavicon(final yacyURL faviconURL) {
this.favicon = faviconURL;
}
- public void notifyWebStructure(plasmaWebStructure webStructure, plasmaCondenser condenser, Date docDate) {
- Integer[] ioLinks = webStructure.generateCitationReference(this, condenser, docDate); // [outlinksSame, outlinksOther]
+ public void notifyWebStructure(final plasmaWebStructure webStructure, final plasmaCondenser condenser, final Date docDate) {
+ final Integer[] ioLinks = webStructure.generateCitationReference(this, condenser, docDate); // [outlinksSame, outlinksOther]
this.inboundLinks = ioLinks[0].intValue();
this.outboundLinks = ioLinks[1].intValue();
}
@@ -437,7 +437,7 @@ dc_rights
if (this.textStream != null) {
try {
this.textStream.close();
- } catch (Exception e) {
+ } catch (final Exception e) {
/* ignore this */
} finally {
this.textStream = null;
@@ -448,7 +448,7 @@ dc_rights
if ((this.text != null) && (this.text instanceof File)) {
try {
((File)this.text).delete();
- } catch (Exception e) {
+ } catch (final Exception e) {
/* ignore this */
} finally {
this.text = null;
diff --git a/source/de/anomic/plasma/plasmaProfiling.java b/source/de/anomic/plasma/plasmaProfiling.java
index c59cc338a..8089226c0 100644
--- a/source/de/anomic/plasma/plasmaProfiling.java
+++ b/source/de/anomic/plasma/plasmaProfiling.java
@@ -38,8 +38,8 @@ public class plasmaProfiling {
private static ymageChart bufferChart = null;
- public static long maxPayload(String eventname, long min) {
- Iterator<Event> i = serverProfiling.history(eventname);
+ public static long maxPayload(final String eventname, final long min) {
+ final Iterator<Event> i = serverProfiling.history(eventname);
serverProfiling.Event event;
long max = min, l;
while (i.hasNext()) {
@@ -50,22 +50,22 @@ public class plasmaProfiling {
return max;
}
- public static ymageMatrix performanceGraph(int width, int height, String subline) {
+ public static ymageMatrix performanceGraph(final int width, final int height, final String subline) {
// find maximum values for automatic graph dimension adoption
- int maxppm = (int) maxPayload("ppm", 25);
- long maxbytes = maxPayload("memory", 110 * 1024 * 1024);
+ final int maxppm = (int) maxPayload("ppm", 25);
+ final long maxbytes = maxPayload("memory", 110 * 1024 * 1024);
// declare graph and set dimensions
- int leftborder = 30;
- int rightborder = 30;
- int topborder = 20;
- int bottomborder = 20;
- int leftscale = 50;
- int rightscale = 100;
- int bottomscale = 60;
- int vspace = height - topborder - bottomborder;
- int hspace = width - leftborder - rightborder;
- int maxtime = 600;
+ final int leftborder = 30;
+ final int rightborder = 30;
+ final int topborder = 20;
+ final int bottomborder = 20;
+ final int leftscale = 50;
+ final int rightscale = 100;
+ final int bottomscale = 60;
+ final int vspace = height - topborder - bottomborder;
+ final int hspace = width - leftborder - rightborder;
+ final int maxtime = 600;
ymageChart chart = new ymageChart(width, height, "FFFFFF", "000000", "AAAAAA", leftborder, rightborder, topborder, bottomborder, "PEER PERFORMANCE GRAPH: PAGES/MINUTE and USED MEMORY", subline);
chart.declareDimension(ymageChart.DIMENSION_BOTTOM, bottomscale, hspace / (maxtime / bottomscale), -maxtime, "000000", "CCCCCC", "TIME/SECONDS");
chart.declareDimension(ymageChart.DIMENSION_LEFT, leftscale, vspace * leftscale / maxppm, 0, "008800", null , "PPM [PAGES/MINUTE]");
@@ -73,7 +73,9 @@ public class plasmaProfiling {
// draw ppm
Iterator<Event> i = serverProfiling.history("ppm");
- long time, now = System.currentTimeMillis(), bytes;
+ long time;
+ final long now = System.currentTimeMillis();
+ long bytes;
int x0 = 1, x1, y0 = 0, y1, ppm;
serverProfiling.Event event;
try {
@@ -106,7 +108,7 @@ public class plasmaProfiling {
x0 = x1; y0 = y1;
}
bufferChart = chart;
- } catch (ConcurrentModificationException cme) {
+ } catch (final ConcurrentModificationException cme) {
chart = bufferChart;
}
@@ -118,7 +120,7 @@ public class plasmaProfiling {
public long duration;
public int resultCount;
- public searchEvent(String queryID, String processName, int resultCount, long duration) {
+ public searchEvent(final String queryID, final String processName, final int resultCount, final long duration) {
this.queryID = queryID;
this.processName = processName;
this.resultCount = resultCount;
diff --git a/source/de/anomic/plasma/plasmaRankingCRProcess.java b/source/de/anomic/plasma/plasmaRankingCRProcess.java
index fe9820227..3fab22925 100644
--- a/source/de/anomic/plasma/plasmaRankingCRProcess.java
+++ b/source/de/anomic/plasma/plasmaRankingCRProcess.java
@@ -66,17 +66,17 @@ public class plasmaRankingCRProcess {
public static final kelondroRow RCI_coli = new kelondroRow("byte[] RefereeDom-6", kelondroBase64Order.enhancedCoder, 0);
public static final String RCI_colname = "RCI-a-coli";
- private static boolean accumulate_upd(File f, kelondroAttrSeq acc) {
+ private static boolean accumulate_upd(final File f, final kelondroAttrSeq acc) {
// open file
kelondroAttrSeq source_cr = null;
try {
source_cr = new kelondroAttrSeq(f, false);
- } catch (IOException e) {
+ } catch (final IOException e) {
return false;
}
// put elements in accumulator file
- Iterator<String> el = source_cr.keys();
+ final Iterator<String> el = source_cr.keys();
String key;
kelondroAttrSeq.Entry new_entry, acc_entry;
int FUDate, FDDate, LUDate, UCount, PCount, ACount, VCount, Vita;
@@ -139,17 +139,17 @@ public class plasmaRankingCRProcess {
return true;
}
- private static boolean accumulate_upd(File f, kelondroIndex acc, kelondroCollectionIndex seq) throws IOException {
+ private static boolean accumulate_upd(final File f, final kelondroIndex acc, final kelondroCollectionIndex seq) throws IOException {
// open file
kelondroAttrSeq source_cr = null;
try {
source_cr = new kelondroAttrSeq(f, false);
- } catch (IOException e) {
+ } catch (final IOException e) {
return false;
}
// put elements in accumulator file
- Iterator<String> el = source_cr.keys();
+ final Iterator<String> el = source_cr.keys();
String key;
kelondroAttrSeq.Entry new_entry;
kelondroRow.Entry acc_entry;
@@ -219,7 +219,7 @@ public class plasmaRankingCRProcess {
}
@SuppressWarnings("null")
- public static void accumulate(File from_dir, File tmp_dir, File err_dir, File bkp_dir, File to_file, int max_files, boolean newdb) throws IOException {
+ public static void accumulate(final File from_dir, final File tmp_dir, final File err_dir, final File bkp_dir, final File to_file, int max_files, final boolean newdb) throws IOException {
if (!(from_dir.isDirectory())) {
System.out.println("source path " + from_dir + " is not a directory.");
return;
@@ -242,7 +242,7 @@ public class plasmaRankingCRProcess {
kelondroIndex newacc = null;
kelondroCollectionIndex newseq = null;
if (newdb) {
- File path = to_file.getParentFile(); // path to storage place
+ final File path = to_file.getParentFile(); // path to storage place
newacc = new kelondroFlexTable(path, CRG_accname, CRG_accrow, 0, false);
newseq = new kelondroCollectionIndex(path, CRG_seqname, 12, kelondroBase64Order.enhancedCoder, 2, 9, CRG_colrow);
} else {
@@ -258,7 +258,7 @@ public class plasmaRankingCRProcess {
}
// collect source files
File source_file = null;
- String[] files = from_dir.list();
+ final String[] files = from_dir.list();
if (files.length < max_files) max_files = files.length;
for (int i = 0; i < max_files; i++) {
// open file
@@ -301,7 +301,7 @@ public class plasmaRankingCRProcess {
tmp_file.renameTo(to_file);
}
serverFileUtils.moveAll(tmp_dir, bkp_dir);
- } catch (IOException e) {
+ } catch (final IOException e) {
// move previously processed files back
e.printStackTrace();
serverFileUtils.moveAll(tmp_dir, from_dir);
@@ -309,12 +309,12 @@ public class plasmaRankingCRProcess {
}
- public static int genrci(File cr_in, File rci_out) throws IOException {
+ public static int genrci(File cr_in, final File rci_out) throws IOException {
if (!(cr_in.exists())) return 0;
kelondroAttrSeq cr = new kelondroAttrSeq(cr_in, false);
//if (rci_out.exists()) rci_out.delete(); // we want only fresh rci here (during testing)
if (!(rci_out.exists())) {
- kelondroAttrSeq rcix = new kelondroAttrSeq("Global Ranking Reverse Citation Index",
+ final kelondroAttrSeq rcix = new kelondroAttrSeq("Global Ranking Reverse Citation Index",
"<AnchorDom-6>,'='," +
"<UDate-3>," +
"'|',*<Referee-12>", false);
@@ -324,8 +324,8 @@ public class plasmaRankingCRProcess {
// loop over all referees
int count = 0;
- int size = cr.size();
- long start = System.currentTimeMillis();
+ final int size = cr.size();
+ final long start = System.currentTimeMillis();
long l;
final Iterator<String> i = cr.keys();
String referee, anchor, anchorDom;
@@ -337,7 +337,7 @@ public class plasmaRankingCRProcess {
cr_UDate = cr_entry.getAttr("UDate", 0);
// loop over all anchors
- Iterator<String> j = cr_entry.getSeqSet().iterator();
+ final Iterator<String> j = cr_entry.getSeqSet().iterator();
while (j.hasNext()) {
// get domain of anchors
anchor = j.next();
@@ -371,15 +371,15 @@ public class plasmaRankingCRProcess {
return count;
}
- public static int genrcix(File cr_path_in, File rci_path_out) throws IOException {
+ public static int genrcix(final File cr_path_in, final File rci_path_out) throws IOException {
//kelondroFlexTable acc = new kelondroFlexTable(cr_path_in, CRG_accname, kelondroBase64Order.enhancedCoder, 128 * 1024 * 1024, -1, CRG_accrow, true);
- kelondroCollectionIndex seq = new kelondroCollectionIndex(cr_path_in, CRG_seqname, 12, kelondroBase64Order.enhancedCoder, 2, 9, CRG_colrow);
- kelondroCollectionIndex rci = new kelondroCollectionIndex(rci_path_out, RCI_colname, 6, kelondroBase64Order.enhancedCoder, 2, 9, RCI_coli);
+ final kelondroCollectionIndex seq = new kelondroCollectionIndex(cr_path_in, CRG_seqname, 12, kelondroBase64Order.enhancedCoder, 2, 9, CRG_colrow);
+ final kelondroCollectionIndex rci = new kelondroCollectionIndex(rci_path_out, RCI_colname, 6, kelondroBase64Order.enhancedCoder, 2, 9, RCI_coli);
// loop over all referees
int count = 0;
- int size = seq.size();
- long start = System.currentTimeMillis();
+ final int size = seq.size();
+ final long start = System.currentTimeMillis();
long l;
final Iterator<Object[]> i = seq.keycollections(null, null, false);
Object[] keycollection;
@@ -392,7 +392,7 @@ public class plasmaRankingCRProcess {
cr_entry = (kelondroRowSet) keycollection[1];
// loop over all anchors
- Iterator<kelondroRow.Entry> j = cr_entry.rows();
+ final Iterator<kelondroRow.Entry> j = cr_entry.rows();
kelondroRow.Entry entry;
while (j.hasNext()) {
// get domain of anchors
@@ -421,45 +421,45 @@ public class plasmaRankingCRProcess {
return count;
}
- public static void main(String[] args) {
+ public static void main(final String[] args) {
// java -classpath source de.anomic.plasma.kelondroPropFile -transcode DATA/RANKING/GLOBAL/CRG-test-unsorted-original.cr DATA/RANKING/GLOBAL/CRG-test-generated.cr
try {
if ((args.length == 5) && (args[0].equals("-accumulate"))) {
accumulate(new File(args[1]), new File(args[2]), new File(args[3]), new File(args[4]), new File(args[5]), Integer.parseInt(args[6]), true);
}
if ((args.length == 2) && (args[0].equals("-accumulate"))) {
- File root_path = new File(args[1]);
- File from_dir = new File(root_path, "DATA/RANKING/GLOBAL/014_othercr");
- File ready_dir = new File(root_path, "DATA/RANKING/GLOBAL/015_ready");
- File tmp_dir = new File(root_path, "DATA/RANKING/GLOBAL/016_tmp");
- File err_dir = new File(root_path, "DATA/RANKING/GLOBAL/017_err");
- File acc_dir = new File(root_path, "DATA/RANKING/GLOBAL/018_acc");
- String filename = "CRG-a-" + new serverDate().toShortString(true) + ".cr.gz";
- File to_file = new File(root_path, "DATA/RANKING/GLOBAL/020_con0/" + filename);
+ final File root_path = new File(args[1]);
+ final File from_dir = new File(root_path, "DATA/RANKING/GLOBAL/014_othercr");
+ final File ready_dir = new File(root_path, "DATA/RANKING/GLOBAL/015_ready");
+ final File tmp_dir = new File(root_path, "DATA/RANKING/GLOBAL/016_tmp");
+ final File err_dir = new File(root_path, "DATA/RANKING/GLOBAL/017_err");
+ final File acc_dir = new File(root_path, "DATA/RANKING/GLOBAL/018_acc");
+ final String filename = "CRG-a-" + new serverDate().toShortString(true) + ".cr.gz";
+ final File to_file = new File(root_path, "DATA/RANKING/GLOBAL/020_con0/" + filename);
if (!(ready_dir.exists())) ready_dir.mkdirs();
if (!(tmp_dir.exists())) tmp_dir.mkdirs();
if (!(err_dir.exists())) err_dir.mkdirs();
if (!(acc_dir.exists())) acc_dir.mkdirs();
if (!(to_file.getParentFile().exists())) to_file.getParentFile().mkdirs();
serverFileUtils.moveAll(from_dir, ready_dir);
- long start = System.currentTimeMillis();
- int files = ready_dir.list().length;
+ final long start = System.currentTimeMillis();
+ final int files = ready_dir.list().length;
accumulate(ready_dir, tmp_dir, err_dir, acc_dir, to_file, 1000, true);
- long seconds = java.lang.Math.max(1, (System.currentTimeMillis() - start) / 1000);
+ final long seconds = java.lang.Math.max(1, (System.currentTimeMillis() - start) / 1000);
System.out.println("Finished accumulate for " + files + " files in " + seconds + " seconds (" + (files / seconds) + " files/second)");
}
if ((args.length == 3) && (args[0].equals("-recycle"))) {
- File root_path = new File(args[1]);
- int max_age_hours = Integer.parseInt(args[2]);
- File own_dir = new File(root_path, "DATA/RANKING/GLOBAL/010_owncr");
- File acc_dir = new File(root_path, "DATA/RANKING/GLOBAL/018_acc");
- File bkp_dir = new File(root_path, "DATA/RANKING/GLOBAL/019_bkp");
+ final File root_path = new File(args[1]);
+ final int max_age_hours = Integer.parseInt(args[2]);
+ final File own_dir = new File(root_path, "DATA/RANKING/GLOBAL/010_owncr");
+ final File acc_dir = new File(root_path, "DATA/RANKING/GLOBAL/018_acc");
+ final File bkp_dir = new File(root_path, "DATA/RANKING/GLOBAL/019_bkp");
if (!(own_dir.exists())) return;
if (!(acc_dir.exists())) return;
if (!(bkp_dir.exists())) bkp_dir.mkdirs();
- String[] list = acc_dir.list();
- long start = System.currentTimeMillis();
- int files = list.length;
+ final String[] list = acc_dir.list();
+ final long start = System.currentTimeMillis();
+ final int files = list.length;
long d;
File f;
for (int i = 0; i < list.length; i++) {
@@ -476,23 +476,23 @@ public class plasmaRankingCRProcess {
serverFileUtils.copy(f, new File(own_dir, list[i]));
f.renameTo(new File(bkp_dir, list[i]));
}
- } catch (IOException e) {
+ } catch (final IOException e) {
// there is something wrong with this file; delete it
System.out.println("file " + f.getName() + " is corrupted and deleted");
f.delete();
}
}
- long seconds = java.lang.Math.max(1, (System.currentTimeMillis() - start) / 1000);
+ final long seconds = java.lang.Math.max(1, (System.currentTimeMillis() - start) / 1000);
System.out.println("Finished recycling of " + files + " files in " + seconds + " seconds (" + (files / seconds) + " files/second)");
}
if ((args.length == 2) && (args[0].equals("-genrci"))) {
- File root_path = new File(args[1]);
- File cr_filedir = new File(root_path, "DATA/RANKING/GLOBAL/020_con0");
- File rci_filedir = new File(root_path, "DATA/RANKING/GLOBAL/030_rci0");
+ final File root_path = new File(args[1]);
+ final File cr_filedir = new File(root_path, "DATA/RANKING/GLOBAL/020_con0");
+ final File rci_filedir = new File(root_path, "DATA/RANKING/GLOBAL/030_rci0");
rci_filedir.mkdirs();
- long start = System.currentTimeMillis();
- int count = genrcix(cr_filedir, rci_filedir);
- long seconds = java.lang.Math.max(1, (System.currentTimeMillis() - start) / 1000);
+ final long start = System.currentTimeMillis();
+ final int count = genrcix(cr_filedir, rci_filedir);
+ final long seconds = java.lang.Math.max(1, (System.currentTimeMillis() - start) / 1000);
System.out.println("Completed RCI generation: " + count + " citation references in " + seconds + " seconds (" + (count / seconds) + " CR-records/second)");
}
/*
@@ -510,7 +510,7 @@ public class plasmaRankingCRProcess {
}
}
*/
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
}
diff --git a/source/de/anomic/plasma/plasmaRankingDistribution.java b/source/de/anomic/plasma/plasmaRankingDistribution.java
index 8632bcb52..11e4a73ac 100644
--- a/source/de/anomic/plasma/plasmaRankingDistribution.java
+++ b/source/de/anomic/plasma/plasmaRankingDistribution.java
@@ -50,14 +50,14 @@ public final class plasmaRankingDistribution {
public static final int METHOD_FIXEDADDRESS = 99;
private final serverLog log;
- private File sourcePath; // where to load CR-files
+ private final File sourcePath; // where to load CR-files
private int method; // of peer selection
private int percentage; // to select any other peer
private String address[]; // of fixed other peer
- private yacySeedDB seedDB;
+ private final yacySeedDB seedDB;
private static Random random = new Random(System.currentTimeMillis());
- public plasmaRankingDistribution(serverLog log, yacySeedDB seedDB, File sourcePath, int method, int percentage, String addresses) {
+ public plasmaRankingDistribution(final serverLog log, final yacySeedDB seedDB, final File sourcePath, final int method, final int percentage, final String addresses) {
this.log = log;
this.seedDB = seedDB;
this.sourcePath = sourcePath;
@@ -71,7 +71,7 @@ public final class plasmaRankingDistribution {
while (st.hasMoreTokens()) {this.address[c++] = st.nextToken();}
}
- public void setMethod(int method, int percentage, String address[]) {
+ public void setMethod(final int method, final int percentage, final String address[]) {
this.method = method;
this.percentage = percentage;
this.address = address;
@@ -100,7 +100,7 @@ public final class plasmaRankingDistribution {
return false;
}
- String[] outfiles = sourcePath.list();
+ final String[] outfiles = sourcePath.list();
if (outfiles == null) {
log.logFine("no ranking distribution: source path does not exist");
@@ -140,7 +140,7 @@ public final class plasmaRankingDistribution {
return false;
}
- private boolean transferRankingAnySeed(File crfile, int trycount) throws InterruptedException {
+ private boolean transferRankingAnySeed(final File crfile, final int trycount) throws InterruptedException {
yacySeed target = null;
for (int j = 0; j < trycount; j++) {
// check for interruption
@@ -150,13 +150,13 @@ public final class plasmaRankingDistribution {
target = seedDB.anySeedVersion(yacyVersion.YACY_ACCEPTS_RANKING_TRANSMISSION);
if (target == null) continue;
- String targetaddress = target.getPublicAddress();
+ final String targetaddress = target.getPublicAddress();
if (transferRankingAddress(crfile, targetaddress)) return true;
}
return false;
}
- private boolean transferRankingAddress(File crfile) throws InterruptedException {
+ private boolean transferRankingAddress(final File crfile) throws InterruptedException {
// try all addresses
for (int i = 0; i < this.address.length; i++) {
// check for interruption
@@ -168,12 +168,12 @@ public final class plasmaRankingDistribution {
return false;
}
- private boolean transferRankingAddress(File crfile, String address) {
+ private boolean transferRankingAddress(final File crfile, final String address) {
// do the transfer
- long starttime = System.currentTimeMillis();
+ final long starttime = System.currentTimeMillis();
String result = "unknown";
try {
- byte[] b = serverFileUtils.read(crfile);
+ final byte[] b = serverFileUtils.read(crfile);
result = yacyClient.transfer(address, crfile.getName(), b);
if (result == null) {
log.logInfo("RankingDistribution - transmitted file " + crfile + " to " + address + " successfully in " + ((System.currentTimeMillis() - starttime) / 1000) + " seconds");
@@ -181,7 +181,7 @@ public final class plasmaRankingDistribution {
} else {
log.logInfo("RankingDistribution - error transmitting file " + crfile + " to " + address + ": " + result);
}
- } catch (IOException e) {
+ } catch (final IOException e) {
log.logInfo("RankingDistribution - could not read file " + crfile + ": " + e.getMessage());
result = "input file error: " + e.getMessage();
}
diff --git a/source/de/anomic/plasma/plasmaRankingRCIEvaluation.java b/source/de/anomic/plasma/plasmaRankingRCIEvaluation.java
index 0bc5fc5b9..30e8435af 100644
--- a/source/de/anomic/plasma/plasmaRankingRCIEvaluation.java
+++ b/source/de/anomic/plasma/plasmaRankingRCIEvaluation.java
@@ -42,11 +42,11 @@ import de.anomic.yacy.yacyURL;
public class plasmaRankingRCIEvaluation {
- public static int[] rcieval(kelondroAttrSeq rci) {
+ public static int[] rcieval(final kelondroAttrSeq rci) {
// collect information about which entry has how many references
// the output is a reference-count:occurrences relation
- HashMap<Integer, Integer> counts = new HashMap<Integer, Integer>();
- Iterator<String> i = rci.keys();
+ final HashMap<Integer, Integer> counts = new HashMap<Integer, Integer>();
+ final Iterator<String> i = rci.keys();
String key;
kelondroAttrSeq.Entry entry;
Integer count_key, count_count;
@@ -65,7 +65,7 @@ public class plasmaRankingRCIEvaluation {
}
counts.put(count_key, count_count);
}
- int[] ctable = new int[maxcount + 1];
+ final int[] ctable = new int[maxcount + 1];
for (int j = 0; j <= maxcount; j++) {
count_count = counts.get(new Integer(j));
if (count_count == null) {
@@ -77,15 +77,15 @@ public class plasmaRankingRCIEvaluation {
return ctable;
}
- public static long sum(int[] c) {
+ public static long sum(final int[] c) {
long s = 0;
for (int i = 0; i < c.length; i++) s += c[i];
return s;
}
- public static int[] interval(int[] counts, int parts) {
+ public static int[] interval(final int[] counts, final int parts) {
long limit = sum(counts) / 2;
- int[] partition = new int[parts];
+ final int[] partition = new int[parts];
int s = 0, p = parts - 1;
for (int i = 1; i < counts.length; i++) {
s += counts[i];
@@ -100,7 +100,7 @@ public class plasmaRankingRCIEvaluation {
return partition;
}
- public static void checkPartitionTable0(int[] counts, int[] partition) {
+ public static void checkPartitionTable0(final int[] counts, final int[] partition) {
int sumsum = 0;
int sum;
int j = 0;
@@ -115,9 +115,9 @@ public class plasmaRankingRCIEvaluation {
System.out.println("complete sum = " + sumsum);
}
- public static void checkPartitionTable1(int[] counts, int[] partition) {
+ public static void checkPartitionTable1(final int[] counts, final int[] partition) {
int sumsum = 0;
- int[] sum = new int[partition.length];
+ final int[] sum = new int[partition.length];
for (int i = 0; i < partition.length; i++) sum[i] = 0;
for (int i = 0; i < counts.length; i++) sum[orderIntoYBI(partition, i)] += counts[i];
for (int i = partition.length - 1; i >= 0; i--) {
@@ -127,7 +127,7 @@ public class plasmaRankingRCIEvaluation {
System.out.println("complete sum = " + sumsum);
}
- public static int orderIntoYBI(int[] partition, int count) {
+ public static int orderIntoYBI(final int[] partition, final int count) {
for (int i = 0; i < partition.length - 1; i++) {
if ((count >= (partition[i + 1] + 1)) && (count <= partition[i])) return i;
}
@@ -135,10 +135,10 @@ public class plasmaRankingRCIEvaluation {
}
@SuppressWarnings("unchecked")
- public static TreeSet<String>[] genRankingTable(kelondroAttrSeq rci, int[] partition) {
- TreeSet<String>[] ranked = new TreeSet[partition.length];
+ public static TreeSet<String>[] genRankingTable(final kelondroAttrSeq rci, final int[] partition) {
+ final TreeSet<String>[] ranked = new TreeSet[partition.length];
for (int i = 0; i < partition.length; i++) ranked[i] = new TreeSet<String>(kelondroBase64Order.enhancedComparator);
- Iterator<String> i = rci.keys();
+ final Iterator<String> i = rci.keys();
String key;
kelondroAttrSeq.Entry entry;
while (i.hasNext()) {
@@ -149,10 +149,10 @@ public class plasmaRankingRCIEvaluation {
return ranked;
}
- public static HashMap<String, String> genReverseDomHash(File domlist) {
- HashSet<String> domset = serverFileUtils.loadList(domlist);
- HashMap<String, String> dommap = new HashMap<String, String>();
- Iterator<String> i = domset.iterator();
+ public static HashMap<String, String> genReverseDomHash(final File domlist) {
+ final HashSet<String> domset = serverFileUtils.loadList(domlist);
+ final HashMap<String, String> dommap = new HashMap<String, String>();
+ final Iterator<String> i = domset.iterator();
String dom;
while (i.hasNext()) {
dom = i.next();
@@ -160,12 +160,12 @@ public class plasmaRankingRCIEvaluation {
try {
dommap.put((new yacyURL("http://" + dom, null)).hash().substring(6), dom);
dommap.put((new yacyURL("http://www." + dom, null)).hash().substring(6), "www." + dom);
- } catch (MalformedURLException e) {}
+ } catch (final MalformedURLException e) {}
}
return dommap;
}
- public static void storeRankingTable(TreeSet<String>[] ranking, File tablePath) throws IOException {
+ public static void storeRankingTable(final TreeSet<String>[] ranking, final File tablePath) throws IOException {
String filename;
if (!(tablePath.exists())) tablePath.mkdirs();
for (int i = 0; i < ranking.length - 1; i++) {
@@ -174,18 +174,18 @@ public class plasmaRankingRCIEvaluation {
}
}
- public static void main(String[] args) {
+ public static void main(final String[] args) {
try {
if ((args.length == 2) && (args[0].equals("-genybr"))) {
- File root_path = new File(args[1]);
- File rci_file = new File(root_path, "DATA/RANKING/GLOBAL/030_rci0/RCI-0.rci.gz");
- long start = System.currentTimeMillis();
+ final File root_path = new File(args[1]);
+ final File rci_file = new File(root_path, "DATA/RANKING/GLOBAL/030_rci0/RCI-0.rci.gz");
+ final long start = System.currentTimeMillis();
if (!(rci_file.exists())) return;
// create partition table
final kelondroAttrSeq rci = new kelondroAttrSeq(rci_file, false);
- int counts[] = rcieval(rci);
- int[] partition = interval(counts, 16);
+ final int counts[] = rcieval(rci);
+ final int[] partition = interval(counts, 16);
// check the table
System.out.println("partition position table:");
@@ -200,19 +200,19 @@ public class plasmaRankingRCIEvaluation {
System.out.println("sum of all references: " + sum);
// create ranking
- TreeSet<String>[] ranked = genRankingTable(rci, partition);
+ final TreeSet<String>[] ranked = genRankingTable(rci, partition);
storeRankingTable(ranked, new File(root_path, "ranking/YBR"));
- long seconds = java.lang.Math.max(1, (System.currentTimeMillis() - start) / 1000);
+ final long seconds = java.lang.Math.max(1, (System.currentTimeMillis() - start) / 1000);
System.out.println("Finished YBR generation in " + seconds + " seconds.");
}
if ((args.length == 2) && (args[0].equals("-rcieval"))) {
- File root_path = new File(args[1]);
+ final File root_path = new File(args[1]);
// load a partition table
plasmaSearchRankingProcess.loadYBR(new File(root_path, "ranking/YBR"), 16);
// load domain list and generate hash index for domains
- HashMap<String, String> dommap = genReverseDomHash(new File(root_path, "domlist.txt"));
+ final HashMap<String, String> dommap = genReverseDomHash(new File(root_path, "domlist.txt"));
// print out the table
String hash, dom;
@@ -227,7 +227,7 @@ public class plasmaRankingRCIEvaluation {
}
}
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
}
diff --git a/source/de/anomic/plasma/plasmaSearchAPI.java b/source/de/anomic/plasma/plasmaSearchAPI.java
index 8fcfd1a96..20ca82829 100644
--- a/source/de/anomic/plasma/plasmaSearchAPI.java
+++ b/source/de/anomic/plasma/plasmaSearchAPI.java
@@ -46,8 +46,8 @@ public class plasmaSearchAPI {
// collection of static methods for a search servlet. Exists only to prevent that the same processes are defined more than once.
- public static kelondroBitfield compileFlags(serverObjects post) {
- kelondroBitfield b = new kelondroBitfield(4);
+ public static kelondroBitfield compileFlags(final serverObjects post) {
+ final kelondroBitfield b = new kelondroBitfield(4);
if (post.get("allurl", "").equals("on")) return null;
if (post.get("flags") != null) {
if (post.get("flags","").length() == 0) return null;
@@ -67,12 +67,12 @@ public class plasmaSearchAPI {
return b;
}
- public static void listHosts(serverObjects prop, String startHash, yacyPeerActions peerActions) {
+ public static void listHosts(final serverObjects prop, final String startHash, final yacyPeerActions peerActions) {
// list known hosts
yacySeed seed;
int hc = 0;
prop.put("searchresult_keyhash", startHash);
- Iterator<yacySeed> e = peerActions.dhtAction.getAcceptRemoteIndexSeeds(startHash);
+ final Iterator<yacySeed> e = peerActions.dhtAction.getAcceptRemoteIndexSeeds(startHash);
while (e.hasNext()) {
seed = e.next();
if (seed != null) {
@@ -84,9 +84,9 @@ public class plasmaSearchAPI {
prop.put("searchresult_hosts", hc);
}
- public static plasmaSearchRankingProcess genSearchresult(serverObjects prop, plasmaSwitchboard sb, String keyhash, kelondroBitfield filter) {
- plasmaSearchQuery query = new plasmaSearchQuery(keyhash, -1, sb.getRanking(), filter);
- plasmaSearchRankingProcess ranked = new plasmaSearchRankingProcess(sb.webIndex, query, Integer.MAX_VALUE, 1);
+ public static plasmaSearchRankingProcess genSearchresult(final serverObjects prop, final plasmaSwitchboard sb, final String keyhash, final kelondroBitfield filter) {
+ final plasmaSearchQuery query = new plasmaSearchQuery(keyhash, -1, sb.getRanking(), filter);
+ final plasmaSearchRankingProcess ranked = new plasmaSearchRankingProcess(sb.webIndex, query, Integer.MAX_VALUE, 1);
ranked.execQuery();
if (ranked.filteredCount() == 0) {
@@ -110,7 +110,7 @@ public class plasmaSearchAPI {
return ranked;
}
- public static void genURLList(serverObjects prop, String keyhash, String keystring, plasmaSearchRankingProcess ranked, kelondroBitfield flags, int maxlines) {
+ public static void genURLList(final serverObjects prop, final String keyhash, final String keystring, final plasmaSearchRankingProcess ranked, final kelondroBitfield flags, final int maxlines) {
// search for a word hash and generate a list of url links
prop.put("genUrlList_keyHash", keyhash);
@@ -179,7 +179,7 @@ public class plasmaSearchAPI {
i++;
if ((maxlines >= 0) && (i >= maxlines)) break;
}
- Iterator<String> iter = ranked.miss(); // iterates url hash strings
+ final Iterator<String> iter = ranked.miss(); // iterates url hash strings
while (iter.hasNext()) {
us = iter.next();
prop.put("genUrlList_urlList_"+i+"_urlExists", "0");
@@ -194,7 +194,7 @@ public class plasmaSearchAPI {
}
}
- public static void putBlacklists(serverObjects prop, String[] lists) {
+ public static void putBlacklists(final serverObjects prop, final String[] lists) {
prop.put("genUrlList_blacklists", lists.length);
for (int i=0; i<lists.length; i++)
prop.put("genUrlList_blacklists_" + i + "_name", lists[i]);
diff --git a/source/de/anomic/plasma/plasmaSearchEvent.java b/source/de/anomic/plasma/plasmaSearchEvent.java
index f39192830..b7ddbd829 100644
--- a/source/de/anomic/plasma/plasmaSearchEvent.java
+++ b/source/de/anomic/plasma/plasmaSearchEvent.java
@@ -72,12 +72,12 @@ public final class plasmaSearchEvent {
private long eventTime;
plasmaSearchQuery query;
- private plasmaWordIndex wordIndex;
+ private final plasmaWordIndex wordIndex;
plasmaSearchRankingProcess rankedCache; // ordered search results, grows dynamically as all the query threads enrich this container
- private Map<String, TreeMap<String, String>> rcAbstracts; // cache for index abstracts; word:TreeMap mapping where the embedded TreeMap is a urlhash:peerlist relation
+ private final Map<String, TreeMap<String, String>> rcAbstracts; // cache for index abstracts; word:TreeMap mapping where the embedded TreeMap is a urlhash:peerlist relation
private yacySearch[] primarySearchThreads, secondarySearchThreads;
private Thread localSearchThread;
- private TreeMap<String, String> preselectedPeerHashes;
+ private final TreeMap<String, String> preselectedPeerHashes;
//private Object[] references;
public TreeMap<String, String> IAResults;
public TreeMap<String, Integer> IACount;
@@ -92,11 +92,11 @@ public final class plasmaSearchEvent {
ResultURLs crawlResults;
@SuppressWarnings("unchecked")
- private plasmaSearchEvent(plasmaSearchQuery query,
- plasmaWordIndex wordIndex,
- ResultURLs crawlResults,
- TreeMap<String, String> preselectedPeerHashes,
- boolean generateAbstracts) {
+ private plasmaSearchEvent(final plasmaSearchQuery query,
+ final plasmaWordIndex wordIndex,
+ final ResultURLs crawlResults,
+ final TreeMap<String, String> preselectedPeerHashes,
+ final boolean generateAbstracts) {
this.eventTime = System.currentTimeMillis(); // for lifetime check
this.wordIndex = wordIndex;
this.crawlResults = crawlResults;
@@ -125,16 +125,16 @@ public final class plasmaSearchEvent {
kelondroMSetTools.excludeDestructive(this.snippetFetchWordHashes, plasmaSwitchboard.stopwords);
}
- long start = System.currentTimeMillis();
+ final long start = System.currentTimeMillis();
if ((query.domType == plasmaSearchQuery.SEARCHDOM_GLOBALDHT) ||
(query.domType == plasmaSearchQuery.SEARCHDOM_CLUSTERALL)) {
// do a global search
this.rankedCache = new plasmaSearchRankingProcess(wordIndex, query, max_results_preparation, 16);
- int fetchpeers = 10;
+ final int fetchpeers = 10;
// the result of the fetch is then in the rcGlobal
- long timer = System.currentTimeMillis();
+ final long timer = System.currentTimeMillis();
serverLog.logFine("SEARCH_EVENT", "STARTING " + fetchpeers + " THREADS TO CATCH EACH " + query.displayResults() + " URLs");
this.primarySearchThreads = yacySearch.primaryRemoteSearches(
plasmaSearchQuery.hashSet2hashString(query.queryHashes),
@@ -169,8 +169,8 @@ public final class plasmaSearchEvent {
if (generateAbstracts) {
// compute index abstracts
- long timer = System.currentTimeMillis();
- Iterator<Map.Entry<String, indexContainer>> ci = this.rankedCache.searchContainerMaps()[0].entrySet().iterator();
+ final long timer = System.currentTimeMillis();
+ final Iterator<Map.Entry<String, indexContainer>> ci = this.rankedCache.searchContainerMaps()[0].entrySet().iterator();
Map.Entry<String, indexContainer> entry;
int maxcount = -1;
double mindhtdistance = 1.1, d;
@@ -178,7 +178,7 @@ public final class plasmaSearchEvent {
while (ci.hasNext()) {
entry = ci.next();
wordhash = entry.getKey();
- indexContainer container = entry.getValue();
+ final indexContainer container = entry.getValue();
assert (container.getWordHash().equals(wordhash));
if (container.size() > maxcount) {
IAmaxcounthash = wordhash;
@@ -208,7 +208,7 @@ public final class plasmaSearchEvent {
serverProfiling.update("SEARCH", new plasmaProfiling.searchEvent(query.id(true), "online snippet fetch threads started", 0, 0));
} else {
// prepare result vector directly without worker threads
- long timer = System.currentTimeMillis();
+ final long timer = System.currentTimeMillis();
indexURLReference uentry;
ResultEntry resultEntry;
yacyURL url;
@@ -258,15 +258,15 @@ public final class plasmaSearchEvent {
}
}
- public static void cleanupEvents(boolean all) {
+ public static void cleanupEvents(final boolean all) {
// remove old events in the event cache
- Iterator<plasmaSearchEvent> i = lastEvents.values().iterator();
+ final Iterator<plasmaSearchEvent> i = lastEvents.values().iterator();
plasmaSearchEvent cleanEvent;
while (i.hasNext()) {
cleanEvent = i.next();
if ((all) || (cleanEvent.eventTime + eventLifetime < System.currentTimeMillis())) {
// execute deletion of failed words
- Set<String> removeWords = cleanEvent.query.queryHashes;
+ final Set<String> removeWords = cleanEvent.query.queryHashes;
removeWords.addAll(cleanEvent.query.excludeHashes);
cleanEvent.wordIndex.removeEntriesMultiple(removeWords, cleanEvent.failedURLs.keySet());
serverLog.logInfo("SearchEvents", "cleaning up event " + cleanEvent.query.id(true) + ", removed " + cleanEvent.failedURLs.size() + " URL references on " + removeWords.size() + " words");
@@ -277,7 +277,7 @@ public final class plasmaSearchEvent {
}
}
- ResultEntry obtainResultEntry(indexURLReference page, int snippetFetchMode) {
+ ResultEntry obtainResultEntry(final indexURLReference page, final int snippetFetchMode) {
// a search result entry needs some work to produce a result Entry:
// - check if url entry exists in LURL-db
@@ -293,15 +293,15 @@ public final class plasmaSearchEvent {
// find the url entry
long startTime = System.currentTimeMillis();
- indexURLReference.Components comp = page.comp();
- String pagetitle = comp.dc_title().toLowerCase();
+ final indexURLReference.Components comp = page.comp();
+ final String pagetitle = comp.dc_title().toLowerCase();
if (comp.url() == null) {
registerFailure(page.hash(), "url corrupted (null)");
return null; // rare case where the url is corrupted
}
- String pageurl = comp.url().toString().toLowerCase();
- String pageauthor = comp.dc_creator().toLowerCase();
- long dbRetrievalTime = System.currentTimeMillis() - startTime;
+ final String pageurl = comp.url().toString().toLowerCase();
+ final String pageauthor = comp.dc_creator().toLowerCase();
+ final long dbRetrievalTime = System.currentTimeMillis() - startTime;
// check exclusion
if ((plasmaSearchQuery.matches(pagetitle, query.excludeHashes)) ||
@@ -350,8 +350,8 @@ public final class plasmaSearchEvent {
if (query.contentdom == plasmaSearchQuery.CONTENTDOM_TEXT) {
// attach text snippet
startTime = System.currentTimeMillis();
- plasmaSnippetCache.TextSnippet snippet = plasmaSnippetCache.retrieveTextSnippet(comp, snippetFetchWordHashes, (snippetFetchMode == 2), ((query.constraint != null) && (query.constraint.get(plasmaCondenser.flag_cat_indexof))), 180, 3000, (snippetFetchMode == 2) ? Integer.MAX_VALUE : 30000, query.isGlobal());
- long snippetComputationTime = System.currentTimeMillis() - startTime;
+ final plasmaSnippetCache.TextSnippet snippet = plasmaSnippetCache.retrieveTextSnippet(comp, snippetFetchWordHashes, (snippetFetchMode == 2), ((query.constraint != null) && (query.constraint.get(plasmaCondenser.flag_cat_indexof))), 180, 3000, (snippetFetchMode == 2) ? Integer.MAX_VALUE : 30000, query.isGlobal());
+ final long snippetComputationTime = System.currentTimeMillis() - startTime;
serverLog.logInfo("SEARCH_EVENT", "text snippet load time for " + comp.url() + ": " + snippetComputationTime + ", " + ((snippet.getErrorCode() < 11) ? "snippet found" : ("no snippet found (" + snippet.getError() + ")")));
if (snippet.getErrorCode() < 11) {
@@ -370,8 +370,8 @@ public final class plasmaSearchEvent {
} else {
// attach media information
startTime = System.currentTimeMillis();
- ArrayList<MediaSnippet> mediaSnippets = plasmaSnippetCache.retrieveMediaSnippets(comp.url(), snippetFetchWordHashes, query.contentdom, (snippetFetchMode == 2), 6000, query.isGlobal());
- long snippetComputationTime = System.currentTimeMillis() - startTime;
+ final ArrayList<MediaSnippet> mediaSnippets = plasmaSnippetCache.retrieveMediaSnippets(comp.url(), snippetFetchWordHashes, query.contentdom, (snippetFetchMode == 2), 6000, query.isGlobal());
+ final long snippetComputationTime = System.currentTimeMillis() - startTime;
serverLog.logInfo("SEARCH_EVENT", "media snippet load time for " + comp.url() + ": " + snippetComputationTime);
if ((mediaSnippets != null) && (mediaSnippets.size() > 0)) {
@@ -449,17 +449,17 @@ public final class plasmaSearchEvent {
return this.snippetComputationAllTime;
}
- public static plasmaSearchEvent getEvent(String eventID) {
+ public static plasmaSearchEvent getEvent(final String eventID) {
return lastEvents.get(eventID);
}
public static plasmaSearchEvent getEvent(
- plasmaSearchQuery query,
- plasmaSearchRankingProfile ranking,
- plasmaWordIndex wordIndex,
- ResultURLs crawlResults,
- TreeMap<String, String> preselectedPeerHashes,
- boolean generateAbstracts) {
+ final plasmaSearchQuery query,
+ final plasmaSearchRankingProfile ranking,
+ final plasmaWordIndex wordIndex,
+ final ResultURLs crawlResults,
+ final TreeMap<String, String> preselectedPeerHashes,
+ final boolean generateAbstracts) {
plasmaSearchEvent event = lastEvents.get(query.id(false));
if (event == null) {
event = new plasmaSearchEvent(query, wordIndex, crawlResults, preselectedPeerHashes, generateAbstracts);
@@ -501,11 +501,11 @@ public final class plasmaSearchEvent {
private class resultWorker extends Thread {
- private long timeout; // the date until this thread should try to work
+ private final long timeout; // the date until this thread should try to work
private long lastLifeSign; // when the last time the run()-loop was executed
- private int id;
+ private final int id;
- public resultWorker(int id, long maxlifetime) {
+ public resultWorker(final int id, final long maxlifetime) {
this.id = id;
this.lastLifeSign = System.currentTimeMillis();
this.timeout = System.currentTimeMillis() + Math.max(1000, maxlifetime);
@@ -528,7 +528,7 @@ public final class plasmaSearchEvent {
if (page == null) {
if (!anyRemoteSearchAlive()) break; // we cannot expect more results
// if we did not get another entry, sleep some time and try again
- try {Thread.sleep(100);} catch (InterruptedException e1) {}
+ try {Thread.sleep(100);} catch (final InterruptedException e1) {}
continue;
}
if (anyResultWith(page.hash())) continue;
@@ -537,7 +537,7 @@ public final class plasmaSearchEvent {
// try secondary search
prepareSecondarySearch(); // will be executed only once
- ResultEntry resultEntry = obtainResultEntry(page, 2);
+ final ResultEntry resultEntry = obtainResultEntry(page, 2);
if (resultEntry == null) continue; // the entry had some problems, cannot be used
urlRetrievalAllTime += resultEntry.dbRetrievalTime;
snippetComputationAllTime += resultEntry.snippetComputationTime;
@@ -553,11 +553,11 @@ public final class plasmaSearchEvent {
serverLog.logInfo("SEARCH", "resultWorker thread " + id + " terminated");
}
- private boolean anyResultWith(String urlhash) {
+ private boolean anyResultWith(final String urlhash) {
return result.exists(urlhash.hashCode());
}
- private boolean anyFailureWith(String urlhash) {
+ private boolean anyFailureWith(final String urlhash) {
return (failedURLs.get(urlhash) != null);
}
@@ -566,12 +566,12 @@ public final class plasmaSearchEvent {
}
}
- private void registerFailure(String urlhash, String reason) {
+ private void registerFailure(final String urlhash, final String reason) {
this.failedURLs.put(urlhash, reason);
serverLog.logInfo("search", "sorted out hash " + urlhash + " during search: " + reason);
}
- public ResultEntry oneResult(int item) {
+ public ResultEntry oneResult(final int item) {
// check if we already retrieved this item (happens if a search pages is accessed a second time)
serverProfiling.update("SEARCH", new plasmaProfiling.searchEvent(query.id(true), "obtain one result entry - start", 0, 0));
if (this.result.sizeStore() > item) {
@@ -585,18 +585,18 @@ public final class plasmaSearchEvent {
if ((localSearchThread != null) && (localSearchThread.isAlive())) {
// in case that the local search takes longer than some other remote search requests,
// do some sleeps to give the local process a chance to contribute
- try {Thread.sleep(item * 100);} catch (InterruptedException e) {}
+ try {Thread.sleep(item * 100);} catch (final InterruptedException e) {}
}
// now wait until as many remote worker threads have finished, as we want to display results
while ((this.primarySearchThreads != null) && (this.primarySearchThreads.length > item) && (anyWorkerAlive()) &&
((result.size() <= item) || (countFinishedRemoteSearch() <= item))) {
- try {Thread.sleep(100);} catch (InterruptedException e) {}
+ try {Thread.sleep(100);} catch (final InterruptedException e) {}
}
}
// finally wait until enough results are there produced from the snippet fetch process
while ((anyWorkerAlive()) && (result.size() <= item)) {
- try {Thread.sleep(100);} catch (InterruptedException e) {}
+ try {Thread.sleep(100);} catch (final InterruptedException e) {}
}
// finally, if there is something, return the result
@@ -606,12 +606,12 @@ public final class plasmaSearchEvent {
private int resultCounter = 0;
public ResultEntry nextResult() {
- ResultEntry re = oneResult(resultCounter);
+ final ResultEntry re = oneResult(resultCounter);
resultCounter++;
return re;
}
- public plasmaSnippetCache.MediaSnippet oneImage(int item) {
+ public plasmaSnippetCache.MediaSnippet oneImage(final int item) {
// check if we already retrieved this item (happens if a search pages is accessed a second time)
if (this.images.sizeStore() > item) {
// we have the wanted result already in the result array .. return that
@@ -619,14 +619,14 @@ public final class plasmaSearchEvent {
}
// feed some results from the result stack into the image stack
- int count = Math.min(5, Math.max(1, 10 * this.result.size() / (item + 1)));
+ final int count = Math.min(5, Math.max(1, 10 * this.result.size() / (item + 1)));
for (int i = 0; i < count; i++) {
// generate result object
- plasmaSearchEvent.ResultEntry result = nextResult();
+ final plasmaSearchEvent.ResultEntry result = nextResult();
plasmaSnippetCache.MediaSnippet ms;
if (result != null) {
// iterate over all images in the result
- ArrayList<plasmaSnippetCache.MediaSnippet> imagemedia = result.mediaSnippets();
+ final ArrayList<plasmaSnippetCache.MediaSnippet> imagemedia = result.mediaSnippets();
if (imagemedia != null) {
for (int j = 0; j < imagemedia.size(); j++) {
ms = imagemedia.get(j);
@@ -641,10 +641,10 @@ public final class plasmaSearchEvent {
return this.images.element(item).element;
}
- public ArrayList<kelondroSortStack<ResultEntry>.stackElement> completeResults(long waitingtime) {
- long timeout = System.currentTimeMillis() + waitingtime;
+ public ArrayList<kelondroSortStack<ResultEntry>.stackElement> completeResults(final long waitingtime) {
+ final long timeout = System.currentTimeMillis() + waitingtime;
while ((result.size() < query.neededResults()) && (anyWorkerAlive()) && (System.currentTimeMillis() < timeout)) {
- try {Thread.sleep(100);} catch (InterruptedException e) {}
+ try {Thread.sleep(100);} catch (final InterruptedException e) {}
//System.out.println("+++DEBUG-completeResults+++ sleeping " + 200);
}
return this.result.list(this.result.size());
@@ -669,15 +669,15 @@ public final class plasmaSearchEvent {
System.out.println("DEBUG-INDEXABSTRACT: hash " + (String) entry.getKey() + ": " + ((query.queryHashes.contains((String) entry.getKey())) ? "NEEDED" : "NOT NEEDED") + "; " + ((TreeMap) entry.getValue()).size() + " entries");
}
*/
- TreeMap<String, String> abstractJoin = (rcAbstracts.size() == query.queryHashes.size()) ? kelondroMSetTools.joinConstructive(rcAbstracts.values(), true) : new TreeMap<String, String>();
+ final TreeMap<String, String> abstractJoin = (rcAbstracts.size() == query.queryHashes.size()) ? kelondroMSetTools.joinConstructive(rcAbstracts.values(), true) : new TreeMap<String, String>();
if (abstractJoin.size() != 0) {
//System.out.println("DEBUG-INDEXABSTRACT: index abstracts delivered " + abstractJoin.size() + " additional results for secondary search");
// generate query for secondary search
- TreeMap<String, String> secondarySearchURLs = new TreeMap<String, String>(); // a (peerhash:urlhash-liststring) mapping
+ final TreeMap<String, String> secondarySearchURLs = new TreeMap<String, String>(); // a (peerhash:urlhash-liststring) mapping
Iterator<Map.Entry<String, String>> i1 = abstractJoin.entrySet().iterator();
Map.Entry<String, String> entry1;
String url, urls, peer, peers;
- String mypeerhash = wordIndex.seedDB.mySeed().hash;
+ final String mypeerhash = wordIndex.seedDB.mySeed().hash;
boolean mypeerinvolved = false;
int mypeercount;
while (i1.hasNext()) {
@@ -720,14 +720,14 @@ public final class plasmaSearchEvent {
}
}
- private String wordsFromPeer(String peerhash, String urls) {
+ private String wordsFromPeer(final String peerhash, final String urls) {
Map.Entry<String, TreeMap<String, String>> entry;
String word, peerlist, url, wordlist = "";
TreeMap<String, String> urlPeerlist;
int p;
boolean hasURL;
synchronized (rcAbstracts) {
- Iterator<Map.Entry <String, TreeMap<String, String>>> i = rcAbstracts.entrySet().iterator();
+ final Iterator<Map.Entry <String, TreeMap<String, String>>> i = rcAbstracts.entrySet().iterator();
while (i.hasNext()) {
entry = i.next();
word = entry.getKey();
@@ -748,33 +748,33 @@ public final class plasmaSearchEvent {
return wordlist;
}
- public void remove(String urlhash) {
+ public void remove(final String urlhash) {
// removes the url hash reference from last search result
/*indexRWIEntry e =*/ this.rankedCache.remove(urlhash);
//assert e != null;
}
- public Set<String> references(int count) {
+ public Set<String> references(final int count) {
// returns a set of words that are computed as toplist
return this.rankedCache.getReferences(count);
}
public static class ResultEntry {
// payload objects
- private indexURLReference urlentry;
- private indexURLReference.Components urlcomps; // buffer for components
+ private final indexURLReference urlentry;
+ private final indexURLReference.Components urlcomps; // buffer for components
private String alternative_urlstring;
private String alternative_urlname;
- private plasmaSnippetCache.TextSnippet textSnippet;
- private ArrayList<plasmaSnippetCache.MediaSnippet> mediaSnippets;
+ private final plasmaSnippetCache.TextSnippet textSnippet;
+ private final ArrayList<plasmaSnippetCache.MediaSnippet> mediaSnippets;
// statistic objects
public long dbRetrievalTime, snippetComputationTime;
- public ResultEntry(indexURLReference urlentry, plasmaWordIndex wordIndex,
- plasmaSnippetCache.TextSnippet textSnippet,
- ArrayList<plasmaSnippetCache.MediaSnippet> mediaSnippets,
- long dbRetrievalTime, long snippetComputationTime) {
+ public ResultEntry(final indexURLReference urlentry, final plasmaWordIndex wordIndex,
+ final plasmaSnippetCache.TextSnippet textSnippet,
+ final ArrayList<plasmaSnippetCache.MediaSnippet> mediaSnippets,
+ final long dbRetrievalTime, final long snippetComputationTime) {
this.urlentry = urlentry;
this.urlcomps = urlentry.comp();
this.alternative_urlstring = null;
@@ -783,13 +783,13 @@ public final class plasmaSearchEvent {
this.mediaSnippets = mediaSnippets;
this.dbRetrievalTime = dbRetrievalTime;
this.snippetComputationTime = snippetComputationTime;
- String host = urlcomps.url().getHost();
+ final String host = urlcomps.url().getHost();
if (host.endsWith(".yacyh")) {
// translate host into current IP
int p = host.indexOf(".");
- String hash = yacySeed.hexHash2b64Hash(host.substring(p + 1, host.length() - 6));
- yacySeed seed = wordIndex.seedDB.getConnected(hash);
- String filename = urlcomps.url().getFile();
+ final String hash = yacySeed.hexHash2b64Hash(host.substring(p + 1, host.length() - 6));
+ final yacySeed seed = wordIndex.seedDB.getConnected(hash);
+ final String filename = urlcomps.url().getFile();
String address = null;
if ((seed == null) || ((address = seed.getPublicAddress()) == null)) {
// seed is not known from here
@@ -803,7 +803,7 @@ public final class plasmaSearchEvent {
urlentry.hash());
wordIndex.removeURL(urlentry.hash()); // clean up
throw new RuntimeException("index void");
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
throw new RuntimeException("parser failed: " + e.getMessage());
}
}
@@ -858,7 +858,7 @@ public final class plasmaSearchEvent {
return urlentry.lapp();
}
public indexRWIVarEntry word() {
- indexRWIEntry word = urlentry.word();
+ final indexRWIEntry word = urlentry.word();
assert word instanceof indexRWIVarEntry;
return (indexRWIVarEntry) word;
}
diff --git a/source/de/anomic/plasma/plasmaSearchImages.java b/source/de/anomic/plasma/plasmaSearchImages.java
index 360c5da3a..5fbe55b64 100644
--- a/source/de/anomic/plasma/plasmaSearchImages.java
+++ b/source/de/anomic/plasma/plasmaSearchImages.java
@@ -35,24 +35,24 @@ import de.anomic.yacy.yacyURL;
public final class plasmaSearchImages {
- private HashMap<String, htmlFilterImageEntry> images;
+ private final HashMap<String, htmlFilterImageEntry> images;
- public plasmaSearchImages(long maxTime, yacyURL url, int depth, boolean indexing) {
- long start = System.currentTimeMillis();
+ public plasmaSearchImages(final long maxTime, final yacyURL url, final int depth, final boolean indexing) {
+ final long start = System.currentTimeMillis();
this.images = new HashMap<String, htmlFilterImageEntry>();
if (maxTime > 10) {
- Object[] resource = plasmaSnippetCache.getResource(url, true, (int) maxTime, false, indexing);
- InputStream res = (InputStream) resource[0];
- Long resLength = (Long) resource[1];
+ final Object[] resource = plasmaSnippetCache.getResource(url, true, (int) maxTime, false, indexing);
+ final InputStream res = (InputStream) resource[0];
+ final Long resLength = (Long) resource[1];
if (res != null) {
plasmaParserDocument document = null;
try {
// parse the document
document = plasmaSnippetCache.parseDocument(url, resLength.longValue(), res);
- } catch (ParserException e) {
+ } catch (final ParserException e) {
// parsing failed
} finally {
- try { res.close(); } catch (Exception e) {/* ignore this */}
+ try { res.close(); } catch (final Exception e) {/* ignore this */}
}
if (document == null) return;
@@ -61,13 +61,13 @@ public final class plasmaSearchImages {
// add also links from pages one step deeper, if depth > 0
if (depth > 0) {
- Iterator<yacyURL> i = document.getHyperlinks().keySet().iterator();
+ final Iterator<yacyURL> i = document.getHyperlinks().keySet().iterator();
String nexturlstring;
while (i.hasNext()) {
try {
nexturlstring = i.next().toNormalform(true, true);
addAll(new plasmaSearchImages(serverDate.remainingTime(start, maxTime, 10), new yacyURL(nexturlstring, null), depth - 1, indexing));
- } catch (MalformedURLException e1) {
+ } catch (final MalformedURLException e1) {
e1.printStackTrace();
}
}
@@ -77,7 +77,7 @@ public final class plasmaSearchImages {
}
}
- public void addAll(plasmaSearchImages m) {
+ public void addAll(final plasmaSearchImages m) {
synchronized (m.images) {
htmlFilterContentScraper.addAllImages(this.images, m.images);
}
diff --git a/source/de/anomic/plasma/plasmaSearchQuery.java b/source/de/anomic/plasma/plasmaSearchQuery.java
index 017ab361c..7ed8f181d 100644
--- a/source/de/anomic/plasma/plasmaSearchQuery.java
+++ b/source/de/anomic/plasma/plasmaSearchQuery.java
@@ -78,10 +78,10 @@ public final class plasmaSearchQuery {
public long searchtime, urlretrievaltime, snippetcomputationtime; // time to perform the search, to get all the urls, and to compute the snippets
public boolean specialRights; // is true if the user has a special authorization and my use more database-extensive options
- public plasmaSearchQuery(String queryString,
- int lines,
- plasmaSearchRankingProfile ranking,
- kelondroBitfield constraint) {
+ public plasmaSearchQuery(final String queryString,
+ final int lines,
+ final plasmaSearchRankingProfile ranking,
+ final kelondroBitfield constraint) {
if ((queryString.length() == 12) && (kelondroBase64Order.enhancedCoder.wellformed(queryString.getBytes()))) {
this.queryString = null;
this.queryHashes = new TreeSet<String>();
@@ -89,7 +89,7 @@ public final class plasmaSearchQuery {
this.queryHashes.add(queryString);
} else {
this.queryString = queryString;
- TreeSet<String>[] cq = cleanQuery(queryString);
+ final TreeSet<String>[] cq = cleanQuery(queryString);
this.queryHashes = indexWord.words2hashes(cq[0]);
this.excludeHashes = indexWord.words2hashes(cq[1]);
}
@@ -113,17 +113,17 @@ public final class plasmaSearchQuery {
}
public plasmaSearchQuery(
- String queryString, TreeSet<String> queryHashes,
- TreeSet<String> excludeHashes,
- plasmaSearchRankingProfile ranking,
- int maxDistance, String prefer, int contentdom,
- boolean onlineSnippetFetch,
- int lines, int offset, String urlMask,
- int domType, String domGroupName, int domMaxTargets,
- kelondroBitfield constraint, boolean allofconstraint,
- int domainzone,
- String host,
- boolean specialRights) {
+ final String queryString, final TreeSet<String> queryHashes,
+ final TreeSet<String> excludeHashes,
+ final plasmaSearchRankingProfile ranking,
+ final int maxDistance, final String prefer, final int contentdom,
+ final boolean onlineSnippetFetch,
+ final int lines, final int offset, final String urlMask,
+ final int domType, final String domGroupName, final int domMaxTargets,
+ final kelondroBitfield constraint, final boolean allofconstraint,
+ final int domainzone,
+ final String host,
+ final boolean specialRights) {
this.queryString = queryString;
this.queryHashes = queryHashes;
this.excludeHashes = excludeHashes;
@@ -156,11 +156,11 @@ public final class plasmaSearchQuery {
return this.linesPerPage;
}
- public void setOffset(int newOffset) {
+ public void setOffset(final int newOffset) {
this.offset = newOffset;
}
- public static int contentdomParser(String dom) {
+ public static int contentdomParser(final String dom) {
if (dom.equals("text")) return CONTENTDOM_TEXT;
else if (dom.equals("image")) return CONTENTDOM_IMAGE;
else if (dom.equals("audio")) return CONTENTDOM_AUDIO;
@@ -186,7 +186,7 @@ public final class plasmaSearchQuery {
return this.domType == SEARCHDOM_LOCAL;
}
- public static TreeSet<String> hashes2Set(String query) {
+ public static TreeSet<String> hashes2Set(final String query) {
if (query == null) return new TreeSet<String>(kelondroBase64Order.enhancedComparator);
final TreeSet<String> keyhashes = new TreeSet<String>(kelondroBase64Order.enhancedComparator);
for (int i = 0; i < (query.length() / yacySeedDB.commonHashLength); i++) {
@@ -195,17 +195,17 @@ public final class plasmaSearchQuery {
return keyhashes;
}
- public static String hashSet2hashString(Set<String> hashes) {
- Iterator<String> i = hashes.iterator();
- StringBuffer sb = new StringBuffer(hashes.size() * yacySeedDB.commonHashLength);
+ public static String hashSet2hashString(final Set<String> hashes) {
+ final Iterator<String> i = hashes.iterator();
+ final StringBuffer sb = new StringBuffer(hashes.size() * yacySeedDB.commonHashLength);
while (i.hasNext()) sb.append(i.next());
return new String(sb);
}
- public static String anonymizedQueryHashes(Set<String> hashes) {
+ public static String anonymizedQueryHashes(final Set<String> hashes) {
// create a more anonymized representation of euqery hashes for logging
- Iterator<String> i = hashes.iterator();
- StringBuffer sb = new StringBuffer(hashes.size() * (yacySeedDB.commonHashLength + 2) + 2);
+ final Iterator<String> i = hashes.iterator();
+ final StringBuffer sb = new StringBuffer(hashes.size() * (yacySeedDB.commonHashLength + 2) + 2);
sb.append("[");
String hash;
if (i.hasNext()) {
@@ -220,10 +220,10 @@ public final class plasmaSearchQuery {
return new String(sb);
}
- public static final boolean matches(String text, TreeSet<String> keyhashes) {
+ public static final boolean matches(final String text, final TreeSet<String> keyhashes) {
// returns true if any of the word hashes in keyhashes appear in the String text
// to do this, all words in the string must be recognized and transcoded to word hashes
- TreeSet<String> wordhashes = indexWord.words2hashes(plasmaCondenser.getWords(text).keySet());
+ final TreeSet<String> wordhashes = indexWord.words2hashes(plasmaCondenser.getWords(text).keySet());
return kelondroMSetTools.anymatch(wordhashes, keyhashes);
}
@@ -261,7 +261,7 @@ public final class plasmaSearchQuery {
return new TreeSet[]{query, exclude};
}
- public String queryString(boolean encodeHTML) {
+ public String queryString(final boolean encodeHTML) {
if(encodeHTML){
return htmlTools.encodeUnicode2html(this.queryString, true);
} else {
@@ -273,14 +273,14 @@ public final class plasmaSearchQuery {
return cleanQuery(this.queryString);
}
- public void filterOut(Set<String> blueList) {
+ public void filterOut(final Set<String> blueList) {
// filter out words that appear in this set
// this is applied to the queryHashes
- TreeSet<String> blues = indexWord.words2hashes(blueList);
+ final TreeSet<String> blues = indexWord.words2hashes(blueList);
kelondroMSetTools.excludeDestructive(queryHashes, blues);
}
- public String id(boolean anonymized) {
+ public String id(final boolean anonymized) {
// generate a string that identifies a search so results can be re-used in a cache
if (anonymized) {
return anonymizedQueryHashes(this.queryHashes) + "-" + anonymizedQueryHashes(this.excludeHashes) + "*" + this.contentdom + "*" + this.zonecode + "*" + indexWord.word2hash(this.ranking.toExternalString());
diff --git a/source/de/anomic/plasma/plasmaSearchRankingProcess.java b/source/de/anomic/plasma/plasmaSearchRankingProcess.java
index 0a7550c17..3dd1581f6 100644
--- a/source/de/anomic/plasma/plasmaSearchRankingProcess.java
+++ b/source/de/anomic/plasma/plasmaSearchRankingProcess.java
@@ -58,22 +58,22 @@ public final class plasmaSearchRankingProcess {
private static boolean useYBR = true;
private static final int maxDoubleDomAll = 20, maxDoubleDomSpecial = 10000;
- private kelondroSortStack<indexRWIVarEntry> stack;
- private HashMap<String, kelondroSortStack<indexRWIVarEntry>> doubleDomCache; // key = domhash (6 bytes); value = like stack
- private HashMap<String, String> handover; // key = urlhash, value = urlstring; used for double-check of urls that had been handed over to search process
- private plasmaSearchQuery query;
- private int maxentries;
+ private final kelondroSortStack<indexRWIVarEntry> stack;
+ private final HashMap<String, kelondroSortStack<indexRWIVarEntry>> doubleDomCache; // key = domhash (6 bytes); value = like stack
+ private final HashMap<String, String> handover; // key = urlhash, value = urlstring; used for double-check of urls that had been handed over to search process
+ private final plasmaSearchQuery query;
+ private final int maxentries;
private int remote_peerCount, remote_indexCount, remote_resourceSize, local_resourceSize;
- private indexRWIEntryOrder order;
- private ConcurrentHashMap<String, Integer> urlhashes; // map for double-check; String/Long relation, addresses ranking number (backreference for deletion)
- private kelondroMScoreCluster<String> ref; // reference score computation for the commonSense heuristic
- private int[] flagcount; // flag counter
- private TreeSet<String> misses; // contains url-hashes that could not been found in the LURL-DB
- private plasmaWordIndex wordIndex;
+ private final indexRWIEntryOrder order;
+ private final ConcurrentHashMap<String, Integer> urlhashes; // map for double-check; String/Long relation, addresses ranking number (backreference for deletion)
+ private final kelondroMScoreCluster<String> ref; // reference score computation for the commonSense heuristic
+ private final int[] flagcount; // flag counter
+ private final TreeSet<String> misses; // contains url-hashes that could not been found in the LURL-DB
+ private final plasmaWordIndex wordIndex;
private HashMap<String, indexContainer>[] localSearchContainerMaps;
- private int[] domZones;
+ private final int[] domZones;
- public plasmaSearchRankingProcess(plasmaWordIndex wordIndex, plasmaSearchQuery query, int maxentries, int concurrency) {
+ public plasmaSearchRankingProcess(final plasmaWordIndex wordIndex, final plasmaSearchQuery query, final int maxentries, final int concurrency) {
// we collect the urlhashes and construct a list with urlEntry objects
// attention: if minEntries is too high, this method will not terminate within the maxTime
// sortorder: 0 = hash, 1 = url, 2 = ranking
@@ -98,7 +98,7 @@ public final class plasmaSearchRankingProcess {
for (int i = 0; i < 8; i++) {this.domZones[i] = 0;}
}
- public long ranking(indexRWIVarEntry word) {
+ public long ranking(final indexRWIVarEntry word) {
return order.cardinal(word);
}
@@ -114,7 +114,7 @@ public final class plasmaSearchRankingProcess {
// join and exclude the local result
timer = System.currentTimeMillis();
- indexContainer index =
+ final indexContainer index =
(this.localSearchContainerMaps == null) ?
plasmaWordIndex.emptyContainer(null, 0) :
indexContainer.joinExcludeContainers(
@@ -122,7 +122,7 @@ public final class plasmaSearchRankingProcess {
this.localSearchContainerMaps[1].values(),
query.maxDistance);
serverProfiling.update("SEARCH", new plasmaProfiling.searchEvent(query.id(true), plasmaSearchEvent.JOIN, index.size(), System.currentTimeMillis() - timer));
- int joincount = index.size();
+ final int joincount = index.size();
if ((index == null) || (joincount == 0)) {
return;
@@ -131,7 +131,7 @@ public final class plasmaSearchRankingProcess {
insertRanked(index, true, index.size());
}
- public void insertRanked(indexContainer index, boolean local, int fullResource) {
+ public void insertRanked(final indexContainer index, final boolean local, final int fullResource) {
// we collect the urlhashes and construct a list with urlEntry objects
// attention: if minEntries is too high, this method will not terminate within the maxTime
@@ -147,12 +147,12 @@ public final class plasmaSearchRankingProcess {
long timer = System.currentTimeMillis();
// normalize entries
- ArrayList<indexRWIVarEntry> decodedEntries = this.order.normalizeWith(index);
+ final ArrayList<indexRWIVarEntry> decodedEntries = this.order.normalizeWith(index);
serverProfiling.update("SEARCH", new plasmaProfiling.searchEvent(query.id(true), plasmaSearchEvent.NORMALIZING, index.size(), System.currentTimeMillis() - timer));
// iterate over normalized entries and select some that are better than currently stored
timer = System.currentTimeMillis();
- Iterator<indexRWIVarEntry> i = decodedEntries.iterator();
+ final Iterator<indexRWIVarEntry> i = decodedEntries.iterator();
indexRWIVarEntry iEntry;
Long r;
while (i.hasNext()) {
@@ -218,7 +218,7 @@ public final class plasmaSearchRankingProcess {
serverProfiling.update("SEARCH", new plasmaProfiling.searchEvent(query.id(true), plasmaSearchEvent.PRESORT, index.size(), System.currentTimeMillis() - timer));
}
- private boolean testFlags(indexRWIEntry ientry) {
+ private boolean testFlags(final indexRWIEntry ientry) {
if (query.constraint == null) return true;
// test if ientry matches with filter
// if all = true: let only entries pass that has all matching bits
@@ -247,7 +247,7 @@ public final class plasmaSearchRankingProcess {
// - root-domain guessing to prefer the root domain over other urls if search word appears in domain name
- private kelondroSortStack<indexRWIVarEntry>.stackElement bestRWI(boolean skipDoubleDom) {
+ private kelondroSortStack<indexRWIVarEntry>.stackElement bestRWI(final boolean skipDoubleDom) {
// returns from the current RWI list the best entry and removes this entry from the list
kelondroSortStack<indexRWIVarEntry> m;
kelondroSortStack<indexRWIVarEntry>.stackElement rwi;
@@ -256,7 +256,7 @@ public final class plasmaSearchRankingProcess {
if (rwi == null) continue; // in case that a synchronization problem occurred just go lazy over it
if (!skipDoubleDom) return rwi;
// check doubledom
- String domhash = rwi.element.urlHash().substring(6);
+ final String domhash = rwi.element.urlHash().substring(6);
m = this.doubleDomCache.get(domhash);
if (m == null) {
// first appearance of dom
@@ -269,7 +269,7 @@ public final class plasmaSearchRankingProcess {
}
// no more entries in sorted RWI entries. Now take Elements from the doubleDomCache
// find best entry from all caches
- Iterator<kelondroSortStack<indexRWIVarEntry>> i = this.doubleDomCache.values().iterator();
+ final Iterator<kelondroSortStack<indexRWIVarEntry>> i = this.doubleDomCache.values().iterator();
kelondroSortStack<indexRWIVarEntry>.stackElement bestEntry = null;
kelondroSortStack<indexRWIVarEntry>.stackElement o;
while (i.hasNext()) {
@@ -293,15 +293,15 @@ public final class plasmaSearchRankingProcess {
return bestEntry;
}
- public indexURLReference bestURL(boolean skipDoubleDom) {
+ public indexURLReference bestURL(final boolean skipDoubleDom) {
// returns from the current RWI list the best URL entry and removed this entry from the list
while ((stack.size() > 0) || (size() > 0)) {
if (((stack.size() == 0) && (size() == 0))) break;
- kelondroSortStack<indexRWIVarEntry>.stackElement obrwi = bestRWI(skipDoubleDom);
+ final kelondroSortStack<indexRWIVarEntry>.stackElement obrwi = bestRWI(skipDoubleDom);
if (obrwi == null) continue; // *** ? this happened and the thread was suspended silently. cause?
- indexURLReference u = wordIndex.getURL(obrwi.element.urlHash(), obrwi.element, obrwi.weight.longValue());
+ final indexURLReference u = wordIndex.getURL(obrwi.element.urlHash(), obrwi.element, obrwi.weight.longValue());
if (u != null) {
- indexURLReference.Components comp = u.comp();
+ final indexURLReference.Components comp = u.comp();
if (comp.url() != null) this.handover.put(u.hash(), comp.url().toNormalform(true, false)); // remember that we handed over this url
return u;
}
@@ -313,7 +313,7 @@ public final class plasmaSearchRankingProcess {
public int size() {
//assert sortedRWIEntries.size() == urlhashes.size() : "sortedRWIEntries.size() = " + sortedRWIEntries.size() + ", urlhashes.size() = " + urlhashes.size();
int c = stack.size();
- Iterator<kelondroSortStack<indexRWIVarEntry>> i = this.doubleDomCache.values().iterator();
+ final Iterator<kelondroSortStack<indexRWIVarEntry>> i = this.doubleDomCache.values().iterator();
while (i.hasNext()) c += i.next().size();
return c;
}
@@ -349,8 +349,8 @@ public final class plasmaSearchRankingProcess {
return this.local_resourceSize;
}
- public indexRWIEntry remove(String urlHash) {
- kelondroSortStack<indexRWIVarEntry>.stackElement se = stack.remove(urlHash.hashCode());
+ public indexRWIEntry remove(final String urlHash) {
+ final kelondroSortStack<indexRWIVarEntry>.stackElement se = stack.remove(urlHash.hashCode());
if (se == null) return null;
urlhashes.remove(urlHash);
return se.element;
@@ -360,18 +360,18 @@ public final class plasmaSearchRankingProcess {
return this.misses.iterator();
}
- public Set<String> getReferences(int count) {
+ public Set<String> getReferences(final int count) {
// create a list of words that had been computed by statistics over all
// words that appeared in the url or the description of all urls
- Object[] refs = ref.getScores(count, false, 2, Integer.MAX_VALUE);
- TreeSet<String> s = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
+ final Object[] refs = ref.getScores(count, false, 2, Integer.MAX_VALUE);
+ final TreeSet<String> s = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
for (int i = 0; i < refs.length; i++) {
s.add((String) refs[i]);
}
return s;
}
- public void addReferences(String[] words) {
+ public void addReferences(final String[] words) {
String word;
for (int i = 0; i < words.length; i++) {
word = words[i].toLowerCase();
@@ -382,11 +382,11 @@ public final class plasmaSearchRankingProcess {
}
}
- protected void addReferences(plasmaSearchEvent.ResultEntry resultEntry) {
+ protected void addReferences(final plasmaSearchEvent.ResultEntry resultEntry) {
// take out relevant information for reference computation
if ((resultEntry.url() == null) || (resultEntry.title() == null)) return;
- String[] urlcomps = htmlFilterContentScraper.urlComps(resultEntry.url().toNormalform(true, true)); // word components of the url
- String[] descrcomps = resultEntry.title().toLowerCase().split(htmlFilterContentScraper.splitrex); // words in the description
+ final String[] urlcomps = htmlFilterContentScraper.urlComps(resultEntry.url().toNormalform(true, true)); // word components of the url
+ final String[] descrcomps = resultEntry.title().toLowerCase().split(htmlFilterContentScraper.splitrex); // words in the description
// add references
addReferences(urlcomps);
@@ -397,7 +397,7 @@ public final class plasmaSearchRankingProcess {
return this.order;
}
- public static void loadYBR(File rankingPath, int count) {
+ public static void loadYBR(final File rankingPath, final int count) {
// load ranking tables
if (rankingPath.exists()) {
ybrTables = new kelondroBinSearch[count];
@@ -413,7 +413,7 @@ public final class plasmaSearchRankingProcess {
ybrTables[i] = null;
}
}
- } catch (IOException e) {
+ } catch (final IOException e) {
ybrTables = null;
}
} else {
@@ -429,16 +429,16 @@ public final class plasmaSearchRankingProcess {
return useYBR;
}
- public static void switchYBR(boolean usage) {
+ public static void switchYBR(final boolean usage) {
useYBR = usage;
}
- public static int ybr(String urlHash) {
+ public static int ybr(final String urlHash) {
// returns the YBR value in a range of 0..15, where 0 means best ranking and 15 means worst ranking
if (ybrTables == null) return 15;
if (!(useYBR)) return 15;
final String domHash = urlHash.substring(6);
- int m = Math.min(maxYBR, ybrTables.length);
+ final int m = Math.min(maxYBR, ybrTables.length);
for (int i = 0; i < m; i++) {
if ((ybrTables[i] != null) && (ybrTables[i].contains(domHash.getBytes()))) {
//System.out.println("YBR FOUND: " + urlHash + " (" + i + ")");
@@ -450,9 +450,9 @@ public final class plasmaSearchRankingProcess {
}
public long postRanking(
- Set<String> topwords,
- plasmaSearchEvent.ResultEntry rentry,
- int position) {
+ final Set<String> topwords,
+ final plasmaSearchEvent.ResultEntry rentry,
+ final int position) {
long r = (255 - position) << 8;
@@ -467,9 +467,9 @@ public final class plasmaSearchRankingProcess {
if (rentry.title().matches(query.prefer)) r += 256 << query.ranking.coeff_prefer;
// apply 'common-sense' heuristic using references
- String urlstring = rentry.url().toNormalform(true, true);
- String[] urlcomps = htmlFilterContentScraper.urlComps(urlstring);
- String[] descrcomps = rentry.title().toLowerCase().split(htmlFilterContentScraper.splitrex);
+ final String urlstring = rentry.url().toNormalform(true, true);
+ final String[] urlcomps = htmlFilterContentScraper.urlComps(urlstring);
+ final String[] descrcomps = rentry.title().toLowerCase().split(htmlFilterContentScraper.splitrex);
for (int j = 0; j < urlcomps.length; j++) {
if (topwords.contains(urlcomps[j])) r += Math.max(1, 256 - urlstring.length()) << query.ranking.coeff_urlcompintoplist;
}
@@ -478,9 +478,9 @@ public final class plasmaSearchRankingProcess {
}
// apply query-in-result matching
- Set<String> urlcomph = indexWord.words2hashSet(urlcomps);
- Set<String> descrcomph = indexWord.words2hashSet(descrcomps);
- Iterator<String> shi = query.queryHashes.iterator();
+ final Set<String> urlcomph = indexWord.words2hashSet(urlcomps);
+ final Set<String> descrcomph = indexWord.words2hashSet(descrcomps);
+ final Iterator<String> shi = query.queryHashes.iterator();
String queryhash;
while (shi.hasNext()) {
queryhash = shi.next();
diff --git a/source/de/anomic/plasma/plasmaSearchRankingProfile.java b/source/de/anomic/plasma/plasmaSearchRankingProfile.java
index 435c1cc16..7bf5b0721 100644
--- a/source/de/anomic/plasma/plasmaSearchRankingProfile.java
+++ b/source/de/anomic/plasma/plasmaSearchRankingProfile.java
@@ -76,7 +76,7 @@ public class plasmaSearchRankingProfile {
coeff_urlcompintoplist, coeff_descrcompintoplist, coeff_prefer,
coeff_termfrequency;
- public plasmaSearchRankingProfile(int mediatype) {
+ public plasmaSearchRankingProfile(final int mediatype) {
// set default-values
coeff_domlength = 11;
coeff_ybr = 9;
@@ -111,14 +111,14 @@ public class plasmaSearchRankingProfile {
coeff_prefer = 14;
}
- public plasmaSearchRankingProfile(String prefix, String profile) {
+ public plasmaSearchRankingProfile(final String prefix, final String profile) {
this(plasmaSearchQuery.CONTENTDOM_TEXT); // set defaults
if ((profile != null) && (profile.length() > 0)) {
//parse external form
- HashMap<String, Integer> coeff = new HashMap<String, Integer>();
- String[] elts = ((profile.startsWith("{") && (profile.endsWith("}"))) ? profile.substring(1, profile.length() - 1) : profile).split(",");
+ final HashMap<String, Integer> coeff = new HashMap<String, Integer>();
+ final String[] elts = ((profile.startsWith("{") && (profile.endsWith("}"))) ? profile.substring(1, profile.length() - 1) : profile).split(",");
int p;
- int s = (prefix == null) ? 0 : prefix.length();
+ final int s = (prefix == null) ? 0 : prefix.length();
String e;
for (int i = 0; i < elts.length; i++) {
@@ -163,10 +163,10 @@ public class plasmaSearchRankingProfile {
}
}
- private static int parseMap(HashMap<String, Integer> coeff, String attr, int dflt) {
+ private static int parseMap(final HashMap<String, Integer> coeff, final String attr, final int dflt) {
if (coeff.containsKey(attr)) try {
return (coeff.get(attr)).intValue();
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
return dflt;
} else {
return dflt;
@@ -177,14 +177,14 @@ public class plasmaSearchRankingProfile {
return toExternalMap("").toString();
}
- public Map<String, String> toExternalMap(String prefix) {
- Map<String, String> ext = preToExternalMap(prefix);
+ public Map<String, String> toExternalMap(final String prefix) {
+ final Map<String, String> ext = preToExternalMap(prefix);
ext.putAll(postToExternalMap(prefix));
return ext;
}
- public Map<String, String> preToExternalMap(String prefix) {
- Map<String, String> ext = new HashMap<String, String>();
+ public Map<String, String> preToExternalMap(final String prefix) {
+ final Map<String, String> ext = new HashMap<String, String>();
ext.put(prefix + DOMLENGTH, Integer.toString(coeff_domlength));
ext.put(prefix + YBR, Integer.toString(coeff_ybr));
ext.put(prefix + DATE, Integer.toString(coeff_date));
@@ -216,18 +216,18 @@ public class plasmaSearchRankingProfile {
return ext;
}
- public Map<String, String> postToExternalMap(String prefix) {
- Map<String, String> ext = new HashMap<String, String>();
+ public Map<String, String> postToExternalMap(final String prefix) {
+ final Map<String, String> ext = new HashMap<String, String>();
ext.put(prefix + URLCOMPINTOPLIST, Integer.toString(coeff_urlcompintoplist));
ext.put(prefix + DESCRCOMPINTOPLIST, Integer.toString(coeff_descrcompintoplist));
ext.put(prefix + PREFER, Integer.toString(coeff_prefer));
return ext;
}
- public String toExternalURLGet(String prefix) {
- Iterator<Map.Entry<String, String>> i = toExternalMap("").entrySet().iterator();
+ public String toExternalURLGet(final String prefix) {
+ final Iterator<Map.Entry<String, String>> i = toExternalMap("").entrySet().iterator();
Map.Entry<String, String> entry;
- StringBuffer ext = new StringBuffer();
+ final StringBuffer ext = new StringBuffer();
while (i.hasNext()) {
entry = i.next();
ext.append("&");
diff --git a/source/de/anomic/plasma/plasmaSnippetCache.java b/source/de/anomic/plasma/plasmaSnippetCache.java
index 8457c0181..2cf0e0265 100644
--- a/source/de/anomic/plasma/plasmaSnippetCache.java
+++ b/source/de/anomic/plasma/plasmaSnippetCache.java
@@ -80,8 +80,8 @@ public class plasmaSnippetCache {
private static serverLog log = null;
public static void init(
- plasmaParser parserx,
- serverLog logx
+ final plasmaParser parserx,
+ final serverLog logx
) {
parser = parserx;
log = logx;
@@ -92,18 +92,18 @@ public class plasmaSnippetCache {
}
public static class TextSnippet {
- private yacyURL url;
+ private final yacyURL url;
private String line;
- private String error;
- private int errorCode;
+ private final String error;
+ private final int errorCode;
Set<String> remaingHashes;
- private yacyURL favicon;
+ private final yacyURL favicon;
- public TextSnippet(yacyURL url, String line, int errorCode, Set<String> remaingHashes, String errortext) {
+ public TextSnippet(final yacyURL url, final String line, final int errorCode, final Set<String> remaingHashes, final String errortext) {
this(url,line,errorCode,remaingHashes,errortext,null);
}
- public TextSnippet(yacyURL url, String line, int errorCode, Set<String> remaingHashes, String errortext, yacyURL favicon) {
+ public TextSnippet(final yacyURL url, final String line, final int errorCode, final Set<String> remaingHashes, final String errortext, final yacyURL favicon) {
this.url = url;
this.line = line;
this.errorCode = errorCode;
@@ -132,13 +132,13 @@ public class plasmaSnippetCache {
public Set<String> getRemainingHashes() {
return this.remaingHashes;
}
- public String getLineMarked(Set<String> queryHashes) {
+ public String getLineMarked(final Set<String> queryHashes) {
if (line == null) return "";
if ((queryHashes == null) || (queryHashes.size() == 0)) return line.trim();
if (line.endsWith(".")) line = line.substring(0, line.length() - 1);
- Iterator<String> i = queryHashes.iterator();
+ final Iterator<String> i = queryHashes.iterator();
String h;
- String[] w = line.split(" ");
+ final String[] w = line.split(" ");
String prefix = "";
String postfix = "";
int len = 0;
@@ -195,7 +195,7 @@ public class plasmaSnippetCache {
w[j] = prefix + w[j] + postfix;
}
}
- StringBuffer l = new StringBuffer(line.length() + queryHashes.size() * 8);
+ final StringBuffer l = new StringBuffer(line.length() + queryHashes.size() * 8);
for (int j = 0; j < w.length; j++) {
l.append(w[j]);
l.append(' ');
@@ -213,7 +213,7 @@ public class plasmaSnippetCache {
public yacyURL href, source;
public String name, attr;
public int ranking;
- public MediaSnippet(int type, yacyURL href, String name, String attr, int ranking, yacyURL source) {
+ public MediaSnippet(final int type, final yacyURL href, final String name, final String attr, final int ranking, final yacyURL source) {
this.type = type;
this.href = href;
this.source = source; // the web page where the media resource appeared
@@ -228,15 +228,15 @@ public class plasmaSnippetCache {
}
}
- public static boolean existsInCache(yacyURL url, Set<String> queryhashes) {
- String hashes = yacySearch.set2string(queryhashes);
+ public static boolean existsInCache(final yacyURL url, final Set<String> queryhashes) {
+ final String hashes = yacySearch.set2string(queryhashes);
return retrieveFromCache(hashes, url.hash()) != null;
}
@SuppressWarnings("unchecked")
- public static TextSnippet retrieveTextSnippet(indexURLReference.Components comp, Set<String> queryhashes, boolean fetchOnline, boolean pre, int snippetMaxLength, int timeout, int maxDocLen, boolean reindexing) {
+ public static TextSnippet retrieveTextSnippet(final indexURLReference.Components comp, final Set<String> queryhashes, final boolean fetchOnline, final boolean pre, final int snippetMaxLength, final int timeout, final int maxDocLen, final boolean reindexing) {
// heise = "0OQUNU3JSs05"
- yacyURL url = comp.url();
+ final yacyURL url = comp.url();
if (queryhashes.size() == 0) {
//System.out.println("found no queryhashes for URL retrieve " + url);
return new TextSnippet(url, null, ERROR_NO_HASH_GIVEN, queryhashes, "no query hashes given");
@@ -244,7 +244,7 @@ public class plasmaSnippetCache {
// try to get snippet from snippetCache
int source = SOURCE_CACHE;
- String wordhashes = yacySearch.set2string(queryhashes);
+ final String wordhashes = yacySearch.set2string(queryhashes);
String line = retrieveFromCache(wordhashes, url.hash());
if (line != null) {
// found the snippet
@@ -284,7 +284,7 @@ public class plasmaSnippetCache {
// if not found try to download it
// download resource using the crawler and keep resource in memory if possible
- plasmaHTCache.Entry entry = plasmaSwitchboard.getSwitchboard().crawlQueues.loadResourceFromWeb(url, timeout, true, true, reindexing);
+ final plasmaHTCache.Entry entry = plasmaSwitchboard.getSwitchboard().crawlQueues.loadResourceFromWeb(url, timeout, true, true, reindexing);
// getting resource metadata (e.g. the http headers for http resources)
if (entry != null) {
@@ -293,7 +293,7 @@ public class plasmaSnippetCache {
resInfo = entry.getDocumentInfo();
// read resource body (if it is there)
- byte []resourceArray = entry.cacheArray();
+ final byte []resourceArray = entry.cacheArray();
if (resourceArray != null) {
resContent = new ByteArrayInputStream(resourceArray);
resContentLength = resourceArray.length;
@@ -310,7 +310,7 @@ public class plasmaSnippetCache {
} else {
return new TextSnippet(url, null, ERROR_SOURCE_LOADING, queryhashes, "no resource available");
}
- } catch (Exception e) {
+ } catch (final Exception e) {
e.printStackTrace();
return new TextSnippet(url, null, ERROR_SOURCE_LOADING, queryhashes, "error loading resource: " + e.getMessage());
}
@@ -321,10 +321,10 @@ public class plasmaSnippetCache {
plasmaParserDocument document = null;
try {
document = parseDocument(url, resContentLength, resContent, resInfo);
- } catch (ParserException e) {
+ } catch (final ParserException e) {
return new TextSnippet(url, null, ERROR_PARSER_FAILED, queryhashes, e.getMessage()); // cannot be parsed
} finally {
- try { resContent.close(); } catch (Exception e) {/* ignore this */}
+ try { resContent.close(); } catch (final Exception e) {/* ignore this */}
}
if (document == null) return new TextSnippet(url, null, ERROR_PARSER_FAILED, queryhashes, "parser error/failed"); // cannot be parsed
@@ -332,16 +332,16 @@ public class plasmaSnippetCache {
/* ===========================================================================
* COMPUTE SNIPPET
* =========================================================================== */
- yacyURL resFavicon = document.getFavicon();
+ final yacyURL resFavicon = document.getFavicon();
if (resFavicon != null) faviconCache.put(url.hash(), resFavicon);
// we have found a parseable non-empty file: use the lines
// compute snippet from text
final Iterator<StringBuffer> sentences = document.getSentences(pre);
if (sentences == null) return new TextSnippet(url, null, ERROR_PARSER_NO_LINES, queryhashes, "parser returned no sentences",resFavicon);
- Object[] tsr = computeTextSnippet(sentences, queryhashes, snippetMaxLength);
- String textline = (tsr == null) ? null : (String) tsr[0];
- Set<String> remainingHashes = (tsr == null) ? queryhashes : (Set<String>) tsr[1];
+ final Object[] tsr = computeTextSnippet(sentences, queryhashes, snippetMaxLength);
+ final String textline = (tsr == null) ? null : (String) tsr[0];
+ final Set<String> remainingHashes = (tsr == null) ? queryhashes : (Set<String>) tsr[1];
// compute snippet from media
//String audioline = computeMediaSnippet(document.getAudiolinks(), queryhashes);
@@ -379,7 +379,7 @@ public class plasmaSnippetCache {
* @param global the domain of the search. If global == true then the content is re-indexed
* @return the parsed document as {@link plasmaParserDocument}
*/
- public static plasmaParserDocument retrieveDocument(yacyURL url, boolean fetchOnline, int timeout, boolean forText, boolean global) {
+ public static plasmaParserDocument retrieveDocument(final yacyURL url, final boolean fetchOnline, final int timeout, final boolean forText, final boolean global) {
// load resource
long resContentLength = 0;
@@ -395,14 +395,14 @@ public class plasmaSnippetCache {
// if not found try to download it
// download resource using the crawler and keep resource in memory if possible
- plasmaHTCache.Entry entry = plasmaSwitchboard.getSwitchboard().crawlQueues.loadResourceFromWeb(url, timeout, true, forText, global);
+ final plasmaHTCache.Entry entry = plasmaSwitchboard.getSwitchboard().crawlQueues.loadResourceFromWeb(url, timeout, true, forText, global);
// getting resource metadata (e.g. the http headers for http resources)
if (entry != null) {
resInfo = entry.getDocumentInfo();
// read resource body (if it is there)
- byte[] resourceArray = entry.cacheArray();
+ final byte[] resourceArray = entry.cacheArray();
if (resourceArray != null) {
resContent = new ByteArrayInputStream(resourceArray);
resContentLength = resourceArray.length;
@@ -421,7 +421,7 @@ public class plasmaSnippetCache {
serverLog.logFine("snippet fetch", "no resource available for url " + url);
return null;
}
- } catch (Exception e) {
+ } catch (final Exception e) {
serverLog.logFine("snippet fetch", "error loading resource: " + e.getMessage() + " for url " + url);
return null;
}
@@ -430,17 +430,17 @@ public class plasmaSnippetCache {
plasmaParserDocument document = null;
try {
document = parseDocument(url, resContentLength, resContent, resInfo);
- } catch (ParserException e) {
+ } catch (final ParserException e) {
serverLog.logFine("snippet fetch", "parser error " + e.getMessage() + " for url " + url);
return null;
} finally {
- try { resContent.close(); } catch (Exception e) {}
+ try { resContent.close(); } catch (final Exception e) {}
}
return document;
}
- public static void storeToCache(String wordhashes, String urlhash, String snippet) {
+ public static void storeToCache(final String wordhashes, final String urlhash, final String snippet) {
// generate key
String key = urlhash + wordhashes;
@@ -466,9 +466,9 @@ public class plasmaSnippetCache {
}
}
- private static String retrieveFromCache(String wordhashes, String urlhash) {
+ private static String retrieveFromCache(final String wordhashes, final String urlhash) {
// generate key
- String key = urlhash + wordhashes;
+ final String key = urlhash + wordhashes;
return snippetsCache.get(key);
}
@@ -502,14 +502,14 @@ public class plasmaSnippetCache {
@SuppressWarnings("unchecked")
private static Object[] /*{String - the snippet, Set - remaining hashes}*/
- computeTextSnippet(Iterator<StringBuffer> sentences, Set<String> queryhashes, int maxLength) {
+ computeTextSnippet(final Iterator<StringBuffer> sentences, final Set<String> queryhashes, int maxLength) {
try {
if (sentences == null) return null;
if ((queryhashes == null) || (queryhashes.size() == 0)) return null;
Iterator<String> j;
HashMap<String, Integer> hs;
StringBuffer sentence;
- TreeMap<Integer, StringBuffer> os = new TreeMap<Integer, StringBuffer>();
+ final TreeMap<Integer, StringBuffer> os = new TreeMap<Integer, StringBuffer>();
int uniqCounter = 9999;
int score;
while (sentences.hasNext()) {
@@ -543,7 +543,7 @@ public class plasmaSnippetCache {
if (maxLength < 20) maxLength = 20;
tsr = computeTextSnippet(os.values().iterator(), remaininghashes, maxLength);
if (tsr == null) return null;
- String nextSnippet = (String) tsr[0];
+ final String nextSnippet = (String) tsr[0];
if (nextSnippet == null) return tsr;
return new Object[]{result + (" / " + nextSnippet), tsr[1]};
} else {
@@ -554,25 +554,25 @@ public class plasmaSnippetCache {
}
}
return null;
- } catch (IndexOutOfBoundsException e) {
+ } catch (final IndexOutOfBoundsException e) {
log.logSevere("computeSnippet: error with string generation", e);
return new Object[]{null, queryhashes};
}
}
private static Object[] /*{String - the snippet, Set - remaining hashes}*/
- computeTextSnippet(String sentence, Set<String> queryhashes, int maxLength) {
+ computeTextSnippet(String sentence, final Set<String> queryhashes, final int maxLength) {
try {
if (sentence == null) return null;
if ((queryhashes == null) || (queryhashes.size() == 0)) return null;
String hash;
// find all hashes that appear in the sentence
- HashMap<String, Integer> hs = hashSentence(sentence);
- Iterator<String> j = queryhashes.iterator();
+ final HashMap<String, Integer> hs = hashSentence(sentence);
+ final Iterator<String> j = queryhashes.iterator();
Integer pos;
int p, minpos = sentence.length(), maxpos = -1;
- HashSet<String> remainingHashes = new HashSet<String>();
+ final HashSet<String> remainingHashes = new HashSet<String>();
while (j.hasNext()) {
hash = j.next();
pos = hs.get(hash);
@@ -592,7 +592,7 @@ public class plasmaSnippetCache {
if (maxpos - minpos + 10 > maxLength) {
// the string is too long, even if we cut at both ends
// so cut here in the middle of the string
- int lenb = sentence.length();
+ final int lenb = sentence.length();
sentence = sentence.substring(0, (minpos + 20 > sentence.length()) ? sentence.length() : minpos + 20).trim() +
" [..] " +
sentence.substring((maxpos + 26 > sentence.length()) ? sentence.length() : maxpos + 26).trim();
@@ -602,8 +602,8 @@ public class plasmaSnippetCache {
// the string is too long, even if we cut it at the end
// so cut it here at both ends at once
assert maxpos >= minpos;
- int newlen = Math.max(10, maxpos - minpos + 10);
- int around = (maxLength - newlen) / 2;
+ final int newlen = Math.max(10, maxpos - minpos + 10);
+ final int around = (maxLength - newlen) / 2;
assert minpos - around < sentence.length() : "maxpos = " + maxpos + ", minpos = " + minpos + ", around = " + around + ", sentence.length() = " + sentence.length();
assert ((maxpos + around) <= sentence.length()) && ((maxpos + around) <= sentence.length()) : "maxpos = " + maxpos + ", minpos = " + minpos + ", around = " + around + ", sentence.length() = " + sentence.length();
sentence = "[..] " + sentence.substring(minpos - around, ((maxpos + around) > sentence.length()) ? sentence.length() : (maxpos + around)).trim() + " [..]";
@@ -623,20 +623,20 @@ public class plasmaSnippetCache {
sentence = sentence.substring(6, 20).trim() + " [..] " + sentence.substring(sentence.length() - 26, sentence.length() - 6).trim();
}
return new Object[] {sentence, remainingHashes};
- } catch (IndexOutOfBoundsException e) {
+ } catch (final IndexOutOfBoundsException e) {
log.logSevere("computeSnippet: error with string generation", e);
return null;
}
}
- public static ArrayList<MediaSnippet> retrieveMediaSnippets(yacyURL url, Set<String> queryhashes, int mediatype, boolean fetchOnline, int timeout, boolean reindexing) {
+ public static ArrayList<MediaSnippet> retrieveMediaSnippets(final yacyURL url, final Set<String> queryhashes, final int mediatype, final boolean fetchOnline, final int timeout, final boolean reindexing) {
if (queryhashes.size() == 0) {
serverLog.logFine("snippet fetch", "no query hashes given for url " + url);
return new ArrayList<MediaSnippet>();
}
- plasmaParserDocument document = retrieveDocument(url, fetchOnline, timeout, false, reindexing);
- ArrayList<MediaSnippet> a = new ArrayList<MediaSnippet>();
+ final plasmaParserDocument document = retrieveDocument(url, fetchOnline, timeout, false, reindexing);
+ final ArrayList<MediaSnippet> a = new ArrayList<MediaSnippet>();
if (document != null) {
if ((mediatype == plasmaSearchQuery.CONTENTDOM_ALL) || (mediatype == plasmaSearchQuery.CONTENTDOM_AUDIO)) a.addAll(computeMediaSnippets(document, queryhashes, plasmaSearchQuery.CONTENTDOM_AUDIO));
if ((mediatype == plasmaSearchQuery.CONTENTDOM_ALL) || (mediatype == plasmaSearchQuery.CONTENTDOM_VIDEO)) a.addAll(computeMediaSnippets(document, queryhashes, plasmaSearchQuery.CONTENTDOM_VIDEO));
@@ -646,7 +646,7 @@ public class plasmaSnippetCache {
return a;
}
- public static ArrayList<MediaSnippet> computeMediaSnippets(plasmaParserDocument document, Set<String> queryhashes, int mediatype) {
+ public static ArrayList<MediaSnippet> computeMediaSnippets(final plasmaParserDocument document, final Set<String> queryhashes, final int mediatype) {
if (document == null) return new ArrayList<MediaSnippet>();
Map<yacyURL, String> media = null;
@@ -655,12 +655,12 @@ public class plasmaSnippetCache {
else if (mediatype == plasmaSearchQuery.CONTENTDOM_APP) media = document.getApplinks();
if (media == null) return null;
- Iterator<Map.Entry<yacyURL, String>> i = media.entrySet().iterator();
+ final Iterator<Map.Entry<yacyURL, String>> i = media.entrySet().iterator();
Map.Entry<yacyURL, String> entry;
yacyURL url;
String desc;
Set<String> s;
- ArrayList<MediaSnippet> result = new ArrayList<MediaSnippet>();
+ final ArrayList<MediaSnippet> result = new ArrayList<MediaSnippet>();
while (i.hasNext()) {
entry = i.next();
url = entry.getKey();
@@ -679,31 +679,31 @@ public class plasmaSnippetCache {
return result;
}
- public static ArrayList<MediaSnippet> computeImageSnippets(plasmaParserDocument document, Set<String> queryhashes) {
+ public static ArrayList<MediaSnippet> computeImageSnippets(final plasmaParserDocument document, final Set<String> queryhashes) {
- TreeSet<htmlFilterImageEntry> images = new TreeSet<htmlFilterImageEntry>();
+ final TreeSet<htmlFilterImageEntry> images = new TreeSet<htmlFilterImageEntry>();
images.addAll(document.getImages().values()); // iterates images in descending size order!
// a measurement for the size of the images can be retrieved using the htmlFilterImageEntry.hashCode()
- Iterator<htmlFilterImageEntry> i = images.iterator();
+ final Iterator<htmlFilterImageEntry> i = images.iterator();
htmlFilterImageEntry ientry;
yacyURL url;
String desc;
Set<String> s;
- ArrayList<MediaSnippet> result = new ArrayList<MediaSnippet>();
+ final ArrayList<MediaSnippet> result = new ArrayList<MediaSnippet>();
while (i.hasNext()) {
ientry = i.next();
url = ientry.url();
desc = ientry.alt();
s = removeAppearanceHashes(url.toNormalform(false, false), queryhashes);
if (s.size() == 0) {
- int ranking = ientry.hashCode();
+ final int ranking = ientry.hashCode();
result.add(new MediaSnippet(plasmaSearchQuery.CONTENTDOM_IMAGE, url, desc, ientry.width() + " x " + ientry.height(), ranking, document.dc_source()));
continue;
}
s = removeAppearanceHashes(desc, s);
if (s.size() == 0) {
- int ranking = ientry.hashCode();
+ final int ranking = ientry.hashCode();
result.add(new MediaSnippet(plasmaSearchQuery.CONTENTDOM_IMAGE, url, desc, ientry.width() + " x " + ientry.height(), ranking, document.dc_source()));
continue;
}
@@ -711,14 +711,14 @@ public class plasmaSnippetCache {
return result;
}
- private static Set<String> removeAppearanceHashes(String sentence, Set<String> queryhashes) {
+ private static Set<String> removeAppearanceHashes(final String sentence, final Set<String> queryhashes) {
// remove all hashes that appear in the sentence
if (sentence == null) return queryhashes;
- HashMap<String, Integer> hs = hashSentence(sentence);
- Iterator<String> j = queryhashes.iterator();
+ final HashMap<String, Integer> hs = hashSentence(sentence);
+ final Iterator<String> j = queryhashes.iterator();
String hash;
Integer pos;
- Set<String> remaininghashes = new HashSet<String>();
+ final Set<String> remaininghashes = new HashSet<String>();
while (j.hasNext()) {
hash = j.next();
pos = hs.get(hash);
@@ -729,10 +729,10 @@ public class plasmaSnippetCache {
return remaininghashes;
}
- private static HashMap<String, Integer> hashSentence(String sentence) {
+ private static HashMap<String, Integer> hashSentence(final String sentence) {
// generates a word-wordPos mapping
- HashMap<String, Integer> map = new HashMap<String, Integer>();
- Enumeration<StringBuffer> words = plasmaCondenser.wordTokenizer(sentence, "UTF-8", 0);
+ final HashMap<String, Integer> map = new HashMap<String, Integer>();
+ final Enumeration<StringBuffer> words = plasmaCondenser.wordTokenizer(sentence, "UTF-8", 0);
int pos = 0;
StringBuffer word;
String hash;
@@ -745,16 +745,16 @@ public class plasmaSnippetCache {
return map;
}
- private static boolean containsAllHashes(String sentence, Set<String> queryhashes) {
- HashMap<String, Integer> m = hashSentence(sentence);
- Iterator<String> i = queryhashes.iterator();
+ private static boolean containsAllHashes(final String sentence, final Set<String> queryhashes) {
+ final HashMap<String, Integer> m = hashSentence(sentence);
+ final Iterator<String> i = queryhashes.iterator();
while (i.hasNext()) {
if (!(m.containsKey(i.next()))) return false;
}
return true;
}
- public static plasmaParserDocument parseDocument(yacyURL url, long contentLength, InputStream resourceStream) throws ParserException {
+ public static plasmaParserDocument parseDocument(final yacyURL url, final long contentLength, final InputStream resourceStream) throws ParserException {
return parseDocument(url, contentLength, resourceStream, null);
}
@@ -767,7 +767,7 @@ public class plasmaSnippetCache {
* @return the extracted data
* @throws ParserException
*/
- public static plasmaParserDocument parseDocument(yacyURL url, long contentLength, InputStream resourceStream, IResourceInfo docInfo) throws ParserException {
+ public static plasmaParserDocument parseDocument(final yacyURL url, final long contentLength, final InputStream resourceStream, IResourceInfo docInfo) throws ParserException {
try {
if (resourceStream == null) return null;
@@ -776,7 +776,7 @@ public class plasmaSnippetCache {
// try to get the header from the htcache directory
try {
docInfo = plasmaHTCache.loadResourceInfo(url);
- } catch (Exception e) {
+ } catch (final Exception e) {
// ignore this. resource info loading failed
}
}
@@ -788,17 +788,17 @@ public class plasmaSnippetCache {
// getting URL mimeType
try {
- httpHeader header = HttpClient.whead(url.toString());
+ final httpHeader header = HttpClient.whead(url.toString());
docInfo = plasmaHTCache.getResourceInfoFactory().buildResourceInfoObj(url, header);
- } catch (Exception e) {
+ } catch (final Exception e) {
// ingore this. http header download failed
}
}
// STEP 3: if the metadata is still null try to guess the mimeType of the resource
if (docInfo == null) {
- String filename = plasmaHTCache.getCachePath(url).getName();
- int p = filename.lastIndexOf('.');
+ final String filename = plasmaHTCache.getCachePath(url).getName();
+ final int p = filename.lastIndexOf('.');
if ( // if no extension is available
(p < 0) ||
// or the extension is supported by one of the parsers
@@ -823,7 +823,7 @@ public class plasmaSnippetCache {
return parser.parseSource(url, docInfo.getMimeType(), docInfo.getCharacterEncoding(), contentLength, resourceStream);
}
return null;
- } catch (InterruptedException e) {
+ } catch (final InterruptedException e) {
// interruption of thread detected
return null;
}
@@ -841,7 +841,7 @@ public class plasmaSnippetCache {
* <tr><td>[1]</td><td>the content-length as {@link Integer}</td></tr>
* </table>
*/
- public static Object[] getResource(yacyURL url, boolean fetchOnline, int socketTimeout, boolean forText, boolean reindexing) {
+ public static Object[] getResource(final yacyURL url, final boolean fetchOnline, final int socketTimeout, final boolean forText, final boolean reindexing) {
// load the url as resource from the web
long contentLength = -1;
@@ -853,11 +853,11 @@ public class plasmaSnippetCache {
// if the content is not available in cache try to download it from web
// try to download the resource using a crawler
- plasmaHTCache.Entry entry = plasmaSwitchboard.getSwitchboard().crawlQueues.loadResourceFromWeb(url, (socketTimeout < 0) ? -1 : socketTimeout, true, forText, reindexing);
+ final plasmaHTCache.Entry entry = plasmaSwitchboard.getSwitchboard().crawlQueues.loadResourceFromWeb(url, (socketTimeout < 0) ? -1 : socketTimeout, true, forText, reindexing);
if (entry == null) return null; // not found in web
// read resource body (if it is there)
- byte[] resourceArray = entry.cacheArray();
+ final byte[] resourceArray = entry.cacheArray();
// in case that the resource was not in ram, read it from disk
if (resourceArray == null) {
@@ -873,17 +873,17 @@ public class plasmaSnippetCache {
return new Object[]{resource,new Long(contentLength)};
}
- public static String failConsequences(TextSnippet snippet, String eventID) {
+ public static String failConsequences(final TextSnippet snippet, final String eventID) {
// problems with snippet fetch
- String urlHash = snippet.getUrl().hash();
- String querystring = kelondroMSetTools.setToString(snippet.getRemainingHashes(), ' ');
+ final String urlHash = snippet.getUrl().hash();
+ final String querystring = kelondroMSetTools.setToString(snippet.getRemainingHashes(), ' ');
if ((snippet.getErrorCode() == ERROR_SOURCE_LOADING) ||
(snippet.getErrorCode() == ERROR_RESOURCE_LOADING) ||
(snippet.getErrorCode() == ERROR_PARSER_FAILED) ||
(snippet.getErrorCode() == ERROR_PARSER_NO_LINES)) {
log.logInfo("error: '" + snippet.getError() + "', remove url = " + snippet.getUrl().toNormalform(false, true) + ", cause: " + snippet.getError());
plasmaSwitchboard.getSwitchboard().webIndex.removeURL(urlHash);
- plasmaSearchEvent event = plasmaSearchEvent.getEvent(eventID);
+ final plasmaSearchEvent event = plasmaSearchEvent.getEvent(eventID);
assert plasmaSwitchboard.getSwitchboard() != null;
assert plasmaSwitchboard.getSwitchboard().webIndex != null;
assert event != null : "eventID = " + eventID;
diff --git a/source/de/anomic/plasma/plasmaStore.java b/source/de/anomic/plasma/plasmaStore.java
index 3b7019099..d1384d842 100644
--- a/source/de/anomic/plasma/plasmaStore.java
+++ b/source/de/anomic/plasma/plasmaStore.java
@@ -43,23 +43,23 @@ public class plasmaStore {
// some static helper methods
- public static void saveGzip(File f, byte[] content) throws IOException {
+ public static void saveGzip(final File f, final byte[] content) throws IOException {
java.util.zip.GZIPOutputStream gzipout = null;
try {
f.getParentFile().mkdirs();
gzipout = new java.util.zip.GZIPOutputStream(new FileOutputStream(f));
gzipout.write(content, 0, content.length);
} finally {
- if (gzipout!=null)try{gzipout.close();}catch(Exception e){}
+ if (gzipout!=null)try{gzipout.close();}catch(final Exception e){}
}
}
- public static byte[] loadGzip(File f) throws IOException {
+ public static byte[] loadGzip(final File f) throws IOException {
java.util.zip.GZIPInputStream gzipin = null;
try {
gzipin = new java.util.zip.GZIPInputStream(new FileInputStream(f));
byte[] result = new byte[1024];
- byte[] buffer = new byte[512];
+ final byte[] buffer = new byte[512];
byte[] b;
int len = 0;
int last;
@@ -82,7 +82,7 @@ public class plasmaStore {
result = null;
return b;
} finally {
- if (gzipin != null) try{gzipin.close();}catch(Exception e){}
+ if (gzipin != null) try{gzipin.close();}catch(final Exception e){}
}
}
diff --git a/source/de/anomic/plasma/plasmaSwitchboard.java b/source/de/anomic/plasma/plasmaSwitchboard.java
index 7e94fca34..7736864f9 100644
--- a/source/de/anomic/plasma/plasmaSwitchboard.java
+++ b/source/de/anomic/plasma/plasmaSwitchboard.java
@@ -117,6 +117,7 @@ import de.anomic.crawler.HTTPLoader;
import de.anomic.crawler.ImporterManager;
import de.anomic.crawler.IndexingStack;
import de.anomic.crawler.NoticedURL;
+import de.anomic.crawler.ProtocolLoader;
import de.anomic.crawler.ResourceObserver;
import de.anomic.crawler.ResultImages;
import de.anomic.crawler.ResultURLs;
@@ -138,6 +139,7 @@ import de.anomic.http.httpRemoteProxyConfig;
import de.anomic.http.httpd;
import de.anomic.http.httpdProxyHandler;
import de.anomic.http.httpdRobotsTxtConfig;
+import de.anomic.index.indexDefaultReferenceBlacklist;
import de.anomic.index.indexReferenceBlacklist;
import de.anomic.index.indexURLReference;
import de.anomic.kelondro.kelondroBitfield;
@@ -265,7 +267,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
*/
public static final String STR_REMOTECRAWLTRIGGER = "REMOTECRAWLTRIGGER: REMOTE CRAWL TO PEER ";
- private serverSemaphore shutdownSync = new serverSemaphore(0);
+ private final serverSemaphore shutdownSync = new serverSemaphore(0);
private boolean terminate = false;
//private Object crawlingPausedSync = new Object();
@@ -826,7 +828,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
private static plasmaSwitchboard sb = null;
- public plasmaSwitchboard(File rootPath, String initPath, String configPath, boolean applyPro) {
+ public plasmaSwitchboard(final File rootPath, final String initPath, final String configPath, final boolean applyPro) {
super(rootPath, initPath, configPath, applyPro);
serverProfiling.startSystemProfiling();
sb=this;
@@ -843,7 +845,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
System.setProperty("java.awt.headless", "false");
yacytray = new yacyTray(this, false);
}
- } catch (Exception e) {
+ } catch (final Exception e) {
System.setProperty("java.awt.headless", "true");
}
@@ -857,9 +859,9 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
// load values from configs
this.plasmaPath = getConfigPath(PLASMA_PATH, PLASMA_PATH_DEFAULT);
this.log.logConfig("Plasma DB Path: " + this.plasmaPath.toString());
- File indexPrimaryPath = getConfigPath(INDEX_PRIMARY_PATH, INDEX_PATH_DEFAULT);
+ final File indexPrimaryPath = getConfigPath(INDEX_PRIMARY_PATH, INDEX_PATH_DEFAULT);
this.log.logConfig("Index Primary Path: " + indexPrimaryPath.toString());
- File indexSecondaryPath = (getConfig(INDEX_SECONDARY_PATH, "").length() == 0) ? indexPrimaryPath : new File(getConfig(INDEX_SECONDARY_PATH, ""));
+ final File indexSecondaryPath = (getConfig(INDEX_SECONDARY_PATH, "").length() == 0) ? indexPrimaryPath : new File(getConfig(INDEX_SECONDARY_PATH, ""));
this.log.logConfig("Index Secondary Path: " + indexSecondaryPath.toString());
this.listsPath = getConfigPath(LISTS_PATH, LISTS_PATH_DEFAULT);
this.log.logConfig("Lists Path: " + this.listsPath.toString());
@@ -872,13 +874,13 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
this.log.logConfig("Work Path: " + this.workPath.toString());
// set a high maximum cache size to current size; this is adopted later automatically
- int wordCacheMaxCount = Math.max((int) getConfigLong(WORDCACHE_INIT_COUNT, 30000),
+ final int wordCacheMaxCount = Math.max((int) getConfigLong(WORDCACHE_INIT_COUNT, 30000),
(int) getConfigLong(WORDCACHE_MAX_COUNT, 20000));
setConfig(WORDCACHE_MAX_COUNT, Integer.toString(wordCacheMaxCount));
// start indexing management
log.logConfig("Starting Indexing Management");
- String networkName = getConfig("network.unit.name", "");
+ final String networkName = getConfig("network.unit.name", "");
webIndex = new plasmaWordIndex(networkName, log, indexPrimaryPath, indexSecondaryPath, wordCacheMaxCount);
crawlResults = new ResultURLs();
@@ -886,7 +888,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
log.logConfig("Starting YaCy Protocol Core");
this.yc = new yacyCore(this);
serverInstantBusyThread.oneTimeJob(this, "loadSeedLists", yacyCore.log, 0);
- long startedSeedListAquisition = System.currentTimeMillis();
+ final long startedSeedListAquisition = System.currentTimeMillis();
// set up local robots.txt
this.robotstxtConfig = httpdRobotsTxtConfig.init(this);
@@ -903,8 +905,8 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
// load coloured lists
if (blueList == null) {
// read only once upon first instantiation of this class
- String f = getConfig(LIST_BLUE, LIST_BLUE_DEFAULT);
- File plasmaBlueListFile = new File(f);
+ final String f = getConfig(LIST_BLUE, LIST_BLUE_DEFAULT);
+ final File plasmaBlueListFile = new File(f);
if (f != null) blueList = kelondroMSetTools.loadList(plasmaBlueListFile, kelondroNaturalOrder.naturalComparator); else blueList= new TreeSet<String>();
this.log.logConfig("loaded blue-list from file " + plasmaBlueListFile.getName() + ", " +
blueList.size() + " entries, " +
@@ -912,7 +914,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
}
// load the black-list / inspired by [AS]
- File blacklistsPath = getConfigPath(LISTS_PATH, LISTS_PATH_DEFAULT);
+ final File blacklistsPath = getConfigPath(LISTS_PATH, LISTS_PATH_DEFAULT);
String blacklistClassName = getConfig(BLACKLIST_CLASS, BLACKLIST_CLASS_DEFAULT);
if (blacklistClassName.equals("de.anomic.plasma.urlPattern.defaultURLPattern")) {
// patch old class location
@@ -922,15 +924,15 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
this.log.logConfig("Starting blacklist engine ...");
try {
- Class<?> blacklistClass = Class.forName(blacklistClassName);
- Constructor<?> blacklistClassConstr = blacklistClass.getConstructor( new Class[] { File.class } );
+ final Class<?> blacklistClass = Class.forName(blacklistClassName);
+ final Constructor<?> blacklistClassConstr = blacklistClass.getConstructor( new Class[] { File.class } );
urlBlacklist = (indexReferenceBlacklist) blacklistClassConstr.newInstance(new Object[] { blacklistsPath });
this.log.logFine("Used blacklist engine class: " + blacklistClassName);
this.log.logConfig("Using blacklist engine: " + urlBlacklist.getEngineInfo());
- } catch (Exception e) {
+ } catch (final Exception e) {
this.log.logSevere("Unable to load the blacklist engine",e);
System.exit(-1);
- } catch (Error e) {
+ } catch (final Error e) {
this.log.logSevere("Unable to load the blacklist engine",e);
System.exit(-1);
}
@@ -942,7 +944,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
// load badwords (to filter the topwords)
if (badwords == null) {
- File badwordsFile = new File(rootPath, LIST_BADWORDS_DEFAULT);
+ final File badwordsFile = new File(rootPath, LIST_BADWORDS_DEFAULT);
badwords = kelondroMSetTools.loadList(badwordsFile, kelondroNaturalOrder.naturalComparator);
this.log.logConfig("loaded badwords from file " + badwordsFile.getName() +
", " + badwords.size() + " entries, " +
@@ -951,7 +953,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
// load stopwords
if (stopwords == null) {
- File stopwordsFile = new File(rootPath, LIST_STOPWORDS_DEFAULT);
+ final File stopwordsFile = new File(rootPath, LIST_STOPWORDS_DEFAULT);
stopwords = kelondroMSetTools.loadList(stopwordsFile, kelondroNaturalOrder.naturalComparator);
this.log.logConfig("loaded stopwords from file " + stopwordsFile.getName() + ", " +
stopwords.size() + " entries, " +
@@ -959,14 +961,14 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
}
// load ranking tables
- File YBRPath = new File(rootPath, "ranking/YBR");
+ final File YBRPath = new File(rootPath, "ranking/YBR");
if (YBRPath.exists()) {
plasmaSearchRankingProcess.loadYBR(YBRPath, 15);
}
// loading the robots.txt db
this.log.logConfig("Initializing robots.txt DB");
- File robotsDBFile = new File(this.plasmaPath, DBFILE_CRAWL_ROBOTS);
+ final File robotsDBFile = new File(this.plasmaPath, DBFILE_CRAWL_ROBOTS);
robots = new RobotsTxt(robotsDBFile);
this.log.logConfig("Loaded robots.txt DB from file " + robotsDBFile.getName() +
", " + robots.size() + " entries" +
@@ -978,7 +980,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
// create the cache directory
htCachePath = getConfigPath(HTCACHE_PATH, HTCACHE_PATH_DEFAULT);
this.log.logInfo("HTCACHE Path = " + htCachePath.getAbsolutePath());
- long maxCacheSize = 1024 * 1024 * Long.parseLong(getConfig(PROXY_CACHE_SIZE, "2")); // this is megabyte
+ final long maxCacheSize = 1024 * 1024 * Long.parseLong(getConfig(PROXY_CACHE_SIZE, "2")); // this is megabyte
plasmaHTCache.init(htCachePath, maxCacheSize);
// create the release download directory
@@ -997,7 +999,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
// Init User DB
this.log.logConfig("Loading User DB");
- File userDbFile = new File(getRootPath(), DBFILE_USER);
+ final File userDbFile = new File(getRootPath(), DBFILE_USER);
this.userDB = new userDB(userDbFile);
this.log.logConfig("Loaded User DB from file " + userDbFile.getName() +
", " + this.userDB.size() + " entries" +
@@ -1065,16 +1067,16 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
this.remoteSearches = new ArrayList<plasmaSearchQuery>();
// init messages: clean up message symbol
- File notifierSource = new File(getRootPath(), getConfig(HTROOT_PATH, HTROOT_PATH_DEFAULT) + "/env/grafics/empty.gif");
- File notifierDest = new File(getConfigPath(HTDOCS_PATH, HTDOCS_PATH_DEFAULT), "notifier.gif");
+ final File notifierSource = new File(getRootPath(), getConfig(HTROOT_PATH, HTROOT_PATH_DEFAULT) + "/env/grafics/empty.gif");
+ final File notifierDest = new File(getConfigPath(HTDOCS_PATH, HTDOCS_PATH_DEFAULT), "notifier.gif");
try {
serverFileUtils.copy(notifierSource, notifierDest);
- } catch (IOException e) {
+ } catch (final IOException e) {
}
// clean up profiles
this.log.logConfig("Cleaning Profiles");
- try { cleanProfiles(); } catch (InterruptedException e) { /* Ignore this here */ }
+ try { cleanProfiles(); } catch (final InterruptedException e) { /* Ignore this here */ }
// init ranking transmission
/*
@@ -1109,10 +1111,10 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
*/
// init nameCacheNoCachingList
- String noCachingList = getConfig(HTTPC_NAME_CACHE_CACHING_PATTERNS_NO,"");
- String[] noCachingEntries = noCachingList.split(",");
+ final String noCachingList = getConfig(HTTPC_NAME_CACHE_CACHING_PATTERNS_NO,"");
+ final String[] noCachingEntries = noCachingList.split(",");
for (int i = 0; i < noCachingEntries.length; i++) {
- String entry = noCachingEntries[i].trim();
+ final String entry = noCachingEntries[i].trim();
serverDomains.nameCacheNoCachingPatterns.add(entry);
}
@@ -1120,13 +1122,13 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
log.logConfig("Initializing Snippet Cache");
plasmaSnippetCache.init(parser, log);
- String wikiParserClassName = getConfig(WIKIPARSER_CLASS, WIKIPARSER_CLASS_DEFAULT);
+ final String wikiParserClassName = getConfig(WIKIPARSER_CLASS, WIKIPARSER_CLASS_DEFAULT);
this.log.logConfig("Loading wiki parser " + wikiParserClassName + " ...");
try {
- Class<?> wikiParserClass = Class.forName(wikiParserClassName);
- Constructor<?> wikiParserClassConstr = wikiParserClass.getConstructor(new Class[] { plasmaSwitchboard.class });
+ final Class<?> wikiParserClass = Class.forName(wikiParserClassName);
+ final Constructor<?> wikiParserClassConstr = wikiParserClass.getConstructor(new Class[] { plasmaSwitchboard.class });
wikiParser = (wikiParser)wikiParserClassConstr.newInstance(new Object[] { this });
- } catch (Exception e) {
+ } catch (final Exception e) {
this.log.logSevere("Unable to load wiki parser, the wiki won't work", e);
}
@@ -1146,8 +1148,8 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
// init robinson cluster
// before we do that, we wait some time until the seed list is loaded.
- while (((System.currentTimeMillis() - startedSeedListAquisition) < 8000) && (this.webIndex.seedDB.sizeConnected() == 0)) try {Thread.sleep(1000);} catch (InterruptedException e) {}
- try {Thread.sleep(1000);} catch (InterruptedException e) {}
+ while (((System.currentTimeMillis() - startedSeedListAquisition) < 8000) && (this.webIndex.seedDB.sizeConnected() == 0)) try {Thread.sleep(1000);} catch (final InterruptedException e) {}
+ try {Thread.sleep(1000);} catch (final InterruptedException e) {}
this.clusterhashes = this.webIndex.seedDB.clusterHashes(getConfig("cluster.peers.yacydomain", ""));
// deploy blocking threads
@@ -1202,11 +1204,11 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
}
- public static void overwriteNetworkDefinition(plasmaSwitchboard sb) {
+ public static void overwriteNetworkDefinition(final plasmaSwitchboard sb) {
// load network configuration into settings
String networkUnitDefinition = sb.getConfig("network.unit.definition", "defaults/yacy.network.freeworld.unit");
- String networkGroupDefinition = sb.getConfig("network.group.definition", "yacy.network.group");
+ final String networkGroupDefinition = sb.getConfig("network.group.definition", "yacy.network.group");
// patch old values
if (networkUnitDefinition.equals("yacy.network.unit")) {
@@ -1233,9 +1235,9 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
if (networkUnitDefinition.startsWith("http://")) {
try {
sb.setConfig(plasmaSwitchboard.loadHashMap(new yacyURL(networkUnitDefinition, null)));
- } catch (MalformedURLException e) { }
+ } catch (final MalformedURLException e) { }
} else {
- File networkUnitDefinitionFile = (networkUnitDefinition.startsWith("/")) ? new File(networkUnitDefinition) : new File(sb.getRootPath(), networkUnitDefinition);
+ final File networkUnitDefinitionFile = (networkUnitDefinition.startsWith("/")) ? new File(networkUnitDefinition) : new File(sb.getRootPath(), networkUnitDefinition);
if (networkUnitDefinitionFile.exists()) {
initProps = serverFileUtils.loadHashMap(networkUnitDefinitionFile);
sb.setConfig(initProps);
@@ -1244,9 +1246,9 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
if (networkGroupDefinition.startsWith("http://")) {
try {
sb.setConfig(plasmaSwitchboard.loadHashMap(new yacyURL(networkGroupDefinition, null)));
- } catch (MalformedURLException e) { }
+ } catch (final MalformedURLException e) { }
} else {
- File networkGroupDefinitionFile = new File(sb.getRootPath(), networkGroupDefinition);
+ final File networkGroupDefinitionFile = new File(sb.getRootPath(), networkGroupDefinition);
if (networkGroupDefinitionFile.exists()) {
initProps = serverFileUtils.loadHashMap(networkGroupDefinitionFile);
sb.setConfig(initProps);
@@ -1259,7 +1261,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
if (location.length() == 0) break;
try {
yacyVersion.latestReleaseLocations.add(new yacyURL(location, null));
- } catch (MalformedURLException e) {
+ } catch (final MalformedURLException e) {
break;
}
i++;
@@ -1274,11 +1276,11 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
}
- public void switchNetwork(String networkDefinition) {
+ public void switchNetwork(final String networkDefinition) {
// pause crawls
- boolean lcp = crawlJobIsPaused(CRAWLJOB_LOCAL_CRAWL);
+ final boolean lcp = crawlJobIsPaused(CRAWLJOB_LOCAL_CRAWL);
if (!lcp) pauseCrawlJob(CRAWLJOB_LOCAL_CRAWL);
- boolean rcp = crawlJobIsPaused(CRAWLJOB_REMOTE_TRIGGERED_CRAWL);
+ final boolean rcp = crawlJobIsPaused(CRAWLJOB_REMOTE_TRIGGERED_CRAWL);
if (!rcp) pauseCrawlJob(CRAWLJOB_REMOTE_TRIGGERED_CRAWL);
// trigger online caution
proxyLastAccess = System.currentTimeMillis() + 10000; // at least 10 seconds online caution to prevent unnecessary action on database meanwhile
@@ -1289,9 +1291,9 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
this.webIndex.close();
setConfig("network.unit.definition", networkDefinition);
overwriteNetworkDefinition(this);
- File indexPrimaryPath = getConfigPath(INDEX_PRIMARY_PATH, INDEX_PATH_DEFAULT);
- File indexSecondaryPath = (getConfig(INDEX_SECONDARY_PATH, "").length() == 0) ? indexPrimaryPath : new File(getConfig(INDEX_SECONDARY_PATH, ""));
- int wordCacheMaxCount = (int) getConfigLong(WORDCACHE_MAX_COUNT, 20000);
+ final File indexPrimaryPath = getConfigPath(INDEX_PRIMARY_PATH, INDEX_PATH_DEFAULT);
+ final File indexSecondaryPath = (getConfig(INDEX_SECONDARY_PATH, "").length() == 0) ? indexPrimaryPath : new File(getConfig(INDEX_SECONDARY_PATH, ""));
+ final int wordCacheMaxCount = (int) getConfigLong(WORDCACHE_MAX_COUNT, 20000);
this.webIndex = new plasmaWordIndex(getConfig("network.unit.name", ""), getLog(), indexPrimaryPath, indexSecondaryPath, wordCacheMaxCount);
}
// start up crawl jobs
@@ -1316,7 +1318,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
public void initMessages() {
this.log.logConfig("Starting Message Board");
- File messageDbFile = new File(workPath, DBFILE_MESSAGE);
+ final File messageDbFile = new File(workPath, DBFILE_MESSAGE);
this.messageDB = new messageBoard(messageDbFile);
this.log.logConfig("Loaded Message Board DB from file " + messageDbFile.getName() +
", " + this.messageDB.size() + " entries" +
@@ -1325,7 +1327,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
public void initWiki() {
this.log.logConfig("Starting Wiki Board");
- File wikiDbFile = new File(workPath, DBFILE_WIKI);
+ final File wikiDbFile = new File(workPath, DBFILE_WIKI);
this.wikiDB = new wikiBoard(wikiDbFile, new File(workPath, DBFILE_WIKI_BKP));
this.log.logConfig("Loaded Wiki Board DB from file " + wikiDbFile.getName() +
", " + this.wikiDB.size() + " entries" +
@@ -1334,13 +1336,13 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
public void initBlog() {
this.log.logConfig("Starting Blog");
- File blogDbFile = new File(workPath, DBFILE_BLOG);
+ final File blogDbFile = new File(workPath, DBFILE_BLOG);
this.blogDB = new blogBoard(blogDbFile);
this.log.logConfig("Loaded Blog DB from file " + blogDbFile.getName() +
", " + this.blogDB.size() + " entries" +
", " + ppRamString(blogDbFile.length()/1024));
- File blogCommentDbFile = new File(workPath, DBFILE_BLOGCOMMENTS);
+ final File blogCommentDbFile = new File(workPath, DBFILE_BLOGCOMMENTS);
this.blogCommentDB = new blogBoardComments(blogCommentDbFile);
this.log.logConfig("Loaded Blog-Comment DB from file " + blogCommentDbFile.getName() +
", " + this.blogCommentDB.size() + " entries" +
@@ -1349,9 +1351,9 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
public void initBookmarks(){
this.log.logConfig("Loading Bookmarks DB");
- File bookmarksFile = new File(workPath, DBFILE_BOOKMARKS);
- File tagsFile = new File(workPath, DBFILE_BOOKMARKS_TAGS);
- File datesFile = new File(workPath, DBFILE_BOOKMARKS_DATES);
+ final File bookmarksFile = new File(workPath, DBFILE_BOOKMARKS);
+ final File tagsFile = new File(workPath, DBFILE_BOOKMARKS_TAGS);
+ final File datesFile = new File(workPath, DBFILE_BOOKMARKS_DATES);
this.bookmarksDB = new bookmarksDB(bookmarksFile, tagsFile, datesFile);
this.log.logConfig("Loaded Bookmarks DB from files "+ bookmarksFile.getName()+ ", "+tagsFile.getName());
this.log.logConfig(this.bookmarksDB.tagsSize()+" Tag, "+this.bookmarksDB.bookmarksSize()+" Bookmarks");
@@ -1371,21 +1373,21 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
public boolean isPublicRobinson() {
// robinson peers may be member of robinson clusters, which can be public or private
// this does not check the robinson attribute, only the specific subtype of the cluster
- String clustermode = getConfig(CLUSTER_MODE, CLUSTER_MODE_PUBLIC_PEER);
+ final String clustermode = getConfig(CLUSTER_MODE, CLUSTER_MODE_PUBLIC_PEER);
return (clustermode.equals(CLUSTER_MODE_PUBLIC_CLUSTER)) || (clustermode.equals(CLUSTER_MODE_PUBLIC_PEER));
}
- public boolean isInMyCluster(String peer) {
+ public boolean isInMyCluster(final String peer) {
// check if the given peer is in the own network, if this is a robinson cluster
// depending on the robinson cluster type, the peer String may be a peerhash (b64-hash)
// or a ip:port String or simply a ip String
// if this robinson mode does not define a cluster membership, false is returned
if (peer == null) return false;
if (!isRobinsonMode()) return false;
- String clustermode = getConfig(CLUSTER_MODE, CLUSTER_MODE_PUBLIC_PEER);
+ final String clustermode = getConfig(CLUSTER_MODE, CLUSTER_MODE_PUBLIC_PEER);
if (clustermode.equals(CLUSTER_MODE_PRIVATE_CLUSTER)) {
// check if we got the request from a peer in the private cluster
- String network = getConfig(CLUSTER_PEERS_IPPORT, "");
+ final String network = getConfig(CLUSTER_PEERS_IPPORT, "");
return network.indexOf(peer) >= 0;
} else if (clustermode.equals(CLUSTER_MODE_PUBLIC_CLUSTER)) {
// check if we got the request from a peer in the public cluster
@@ -1395,15 +1397,15 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
}
}
- public boolean isInMyCluster(yacySeed seed) {
+ public boolean isInMyCluster(final yacySeed seed) {
// check if the given peer is in the own network, if this is a robinson cluster
// if this robinson mode does not define a cluster membership, false is returned
if (seed == null) return false;
if (!isRobinsonMode()) return false;
- String clustermode = getConfig(CLUSTER_MODE, CLUSTER_MODE_PUBLIC_PEER);
+ final String clustermode = getConfig(CLUSTER_MODE, CLUSTER_MODE_PUBLIC_PEER);
if (clustermode.equals(CLUSTER_MODE_PRIVATE_CLUSTER)) {
// check if we got the request from a peer in the private cluster
- String network = getConfig(CLUSTER_PEERS_IPPORT, "");
+ final String network = getConfig(CLUSTER_PEERS_IPPORT, "");
return network.indexOf(seed.getPublicAddress()) >= 0;
} else if (clustermode.equals(CLUSTER_MODE_PUBLIC_CLUSTER)) {
// check if we got the request from a peer in the public cluster
@@ -1419,10 +1421,10 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
* @param url
* @return null if the url can be accepted, a string containing a rejection reason if the url cannot be accepted
*/
- public String acceptURL(yacyURL url) {
+ public String acceptURL(final yacyURL url) {
// returns true if the url can be accepted accoring to network.unit.domain
if (url == null) return "url is null";
- String host = url.getHost();
+ final String host = url.getHost();
if (host == null) return "url.host is null";
if (this.acceptGlobalURLs && this.acceptLocalURLs) return null; // fast shortcut to avoid dnsResolve
/*
@@ -1436,7 +1438,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
*/
// check if this is a local address and we are allowed to index local pages:
//boolean local = hostAddress.isSiteLocalAddress() || hostAddress.isLoopbackAddress();
- boolean local = url.isLocal();
+ final boolean local = url.isLocal();
//assert local == yacyURL.isLocalDomain(url.hash()); // TODO: remove the dnsResolve above!
if ((this.acceptGlobalURLs && !local) || (this.acceptLocalURLs && local)) return null;
return (local) ?
@@ -1444,7 +1446,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
("the host '" + host + "' is global, but global addresses are not accepted");
}
- public String urlExists(String hash) {
+ public String urlExists(final String hash) {
// tests if hash occurrs in any database
// if it exists, the name of the database is returned,
// if it not exists, null is returned
@@ -1452,18 +1454,18 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
return this.crawlQueues.urlExists(hash);
}
- public void urlRemove(String hash) {
+ public void urlRemove(final String hash) {
webIndex.removeURL(hash);
crawlResults.remove(hash);
crawlQueues.urlRemove(hash);
}
- public yacyURL getURL(String urlhash) {
+ public yacyURL getURL(final String urlhash) {
if (urlhash == null) return null;
if (urlhash.length() == 0) return null;
- yacyURL ne = crawlQueues.getURL(urlhash);
+ final yacyURL ne = crawlQueues.getURL(urlhash);
if (ne != null) return ne;
- indexURLReference le = webIndex.getURL(urlhash, null, 0);
+ final indexURLReference le = webIndex.getURL(urlhash, null, 0);
if (le != null) return le.comp().url();
return null;
}
@@ -1478,7 +1480,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
* This method changes the HTCache size.<br>
* @param newCacheSize in MB
*/
- public final void setCacheSize(long newCacheSize) {
+ public final void setCacheSize(final long newCacheSize) {
plasmaHTCache.setCacheSize(1048576 * newCacheSize);
}
@@ -1528,7 +1530,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
return this.webIndex.cleanProfiles();
}
- public boolean htEntryStoreProcess(plasmaHTCache.Entry entry) {
+ public boolean htEntryStoreProcess(final plasmaHTCache.Entry entry) {
if (entry == null) return false;
@@ -1537,7 +1539,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
*
* Testing if the content type is supported by the available parsers
* ========================================================================= */
- boolean isSupportedContent = plasmaParser.supportedContent(entry.url(),entry.getMimeType());
+ final boolean isSupportedContent = plasmaParser.supportedContent(entry.url(),entry.getMimeType());
/* =========================================================================
* INDEX CONTROL HEADER
@@ -1557,7 +1559,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
*
* check if ip is local ip address // TODO: remove this procotol specific code here
* ========================================================================= */
- String urlRejectReason = acceptURL(entry.url());
+ final String urlRejectReason = acceptURL(entry.url());
if (urlRejectReason != null) {
if (this.log.isFine()) this.log.logFine("Rejected URL '" + entry.url() + "': " + urlRejectReason);
doIndexing = false;
@@ -1581,7 +1583,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
// work off unwritten files
if (entry.cacheArray() != null) {
- String error = entry.shallStoreCacheForProxy();
+ 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());
@@ -1665,11 +1667,11 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
return webIndex.queuePreStack.size();
}
- public void enQueue(IndexingStack.QueueEntry job) {
+ public void enQueue(final IndexingStack.QueueEntry job) {
assert job != null;
try {
webIndex.queuePreStack.push(job);
- } catch (IOException e) {
+ } catch (final IOException e) {
log.logSevere("IOError in plasmaSwitchboard.enQueue: " + e.getMessage(), e);
}
}
@@ -1697,7 +1699,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
", overhangStackSize=" + crawlQueues.noticeURL.stackSize(NoticedURL.STACK_TYPE_OVERHANG) +
", remoteStackSize=" + crawlQueues.noticeURL.stackSize(NoticedURL.STACK_TYPE_REMOTE));
try {
- int sizeBefore = webIndex.queuePreStack.size();
+ final int sizeBefore = webIndex.queuePreStack.size();
nextentry = webIndex.queuePreStack.pop();
if (nextentry == null) {
log.logWarning("deQueue: null entry on queue stack.");
@@ -1709,7 +1711,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
}
return null;
}
- } catch (IOException e) {
+ } catch (final IOException e) {
log.logSevere("IOError in plasmaSwitchboard.deQueue: " + e.getMessage(), e);
return null;
}
@@ -1734,7 +1736,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
// possibly delete entries from last chunk
if ((this.dhtTransferChunk != null) && (this.dhtTransferChunk.getStatus() == plasmaDHTChunk.chunkStatus_COMPLETE)) {
- String deletedURLs = this.dhtTransferChunk.deleteTransferIndexes();
+ final String deletedURLs = this.dhtTransferChunk.deleteTransferIndexes();
if (this.log.isFine()) this.log.logFine("Deleted from " + this.dhtTransferChunk.containers().length + " transferred RWIs locally, removed " + deletedURLs + " URL references");
this.dhtTransferChunk = null;
}
@@ -1747,7 +1749,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
(this.dhtTransferChunk.getStatus() == plasmaDHTChunk.chunkStatus_FAILED)
)) {
// generate new chunk
- int minChunkSize = (int) getConfigLong(INDEX_DIST_CHUNK_SIZE_MIN, 30);
+ final int minChunkSize = (int) getConfigLong(INDEX_DIST_CHUNK_SIZE_MIN, 30);
dhtTransferChunk = new plasmaDHTChunk(this.log, webIndex, minChunkSize, dhtTransferIndexCount, 5000);
doneSomething = true;
}
@@ -1773,7 +1775,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
}
// get next queue entry and start a queue processing
- IndexingStack.QueueEntry queueEntry = deQueue();
+ final IndexingStack.QueueEntry queueEntry = deQueue();
assert queueEntry != null;
if (queueEntry == null) return true;
if (queueEntry.profile() == null) {
@@ -1805,7 +1807,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
storeDocumentIndex(analysis);
*/
return true;
- } catch (InterruptedException e) {
+ } catch (final InterruptedException e) {
log.logInfo("DEQUEUE: Shutdown detected.");
return false;
}
@@ -1816,9 +1818,9 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
public plasmaParserDocument document;
public plasmaCondenser condenser;
public indexingQueueEntry(
- IndexingStack.QueueEntry queueEntry,
- plasmaParserDocument document,
- plasmaCondenser condenser) {
+ final IndexingStack.QueueEntry queueEntry,
+ final plasmaParserDocument document,
+ final plasmaCondenser condenser) {
super();
this.queueEntry = queueEntry;
this.document = document;
@@ -1906,7 +1908,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
try {
if (this.log.isFine()) log.logFine("Cleaning Incoming News, " + this.webIndex.newsPool.size(yacyNewsPool.INCOMING_DB) + " entries on stack");
if (this.webIndex.newsPool.automaticProcess(webIndex.seedDB) > 0) hasDoneSomething = true;
- } catch (IOException e) {}
+ } catch (final IOException e) {}
if (getConfigBool("cleanup.deletionProcessedNews", true)) {
this.webIndex.newsPool.clear(yacyNewsPool.PROCESSED_DB);
}
@@ -1919,7 +1921,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
final long deleteOldSeedsTime = getConfigLong("routing.deleteOldSeeds.time",7)*24*3600000;
Iterator<yacySeed> e = this.webIndex.seedDB.seedsSortedDisconnected(true,yacySeed.LASTSEEN);
yacySeed seed = null;
- ArrayList<String> deleteQueue = new ArrayList<String>();
+ final ArrayList<String> deleteQueue = new ArrayList<String>();
checkInterruption();
//clean passive seeds
while(e.hasNext()) {
@@ -1950,12 +1952,12 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
// check if update is available and
// if auto-update is activated perform an automatic installation and restart
- yacyVersion updateVersion = yacyVersion.rulebasedUpdateInfo(false);
+ final yacyVersion updateVersion = yacyVersion.rulebasedUpdateInfo(false);
if (updateVersion != null) {
// there is a version that is more recent. Load it and re-start with it
log.logInfo("AUTO-UPDATE: downloading more recent release " + updateVersion.url);
- File downloaded = yacyVersion.downloadRelease(updateVersion);
- boolean devenvironment = yacyVersion.combined2prettyVersion(sb.getConfig("version","0.1")).startsWith("dev");
+ final File downloaded = yacyVersion.downloadRelease(updateVersion);
+ final boolean devenvironment = yacyVersion.combined2prettyVersion(sb.getConfig("version","0.1")).startsWith("dev");
if (devenvironment) {
log.logInfo("AUTO-UPDATE: omiting update because this is a development environment");
} else if ((downloaded == null) || (!downloaded.exists()) || (downloaded.length() == 0)) {
@@ -1975,13 +1977,13 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
try {
fileIn = new FileInputStream(new File("DATA/SETTINGS/profile.txt"));
profile.load(fileIn);
- } catch(IOException e) {
+ } catch(final IOException e) {
} finally {
- if (fileIn != null) try { fileIn.close(); } catch (Exception e) {}
+ if (fileIn != null) try { fileIn.close(); } catch (final Exception e) {}
}
- String homepage = (String) profile.get("homepage");
+ final String homepage = (String) profile.get("homepage");
if ((homepage != null) && (homepage.length() > 10)) {
- Properties news = new Properties();
+ final Properties news = new Properties();
news.put("homepage", profile.get("homepage"));
this.webIndex.newsPool.publishMyNews(yacyNewsRecord.newRecord(webIndex.seedDB.mySeed(), yacyNewsPool.CATEGORY_PROFILE_BROADCAST, news));
}
@@ -2002,7 +2004,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
observer.resourceObserverJob();
return hasDoneSomething;
- } catch (InterruptedException e) {
+ } catch (final InterruptedException e) {
this.log.logInfo("cleanupJob: Shutdown detected");
return false;
}
@@ -2012,8 +2014,8 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
* With this function the crawling process can be paused
* @param jobType
*/
- public void pauseCrawlJob(String jobType) {
- Object[] status = this.crawlJobsStatus.get(jobType);
+ public void pauseCrawlJob(final String jobType) {
+ final Object[] status = this.crawlJobsStatus.get(jobType);
synchronized(status[CRAWLJOB_SYNC]) {
status[CRAWLJOB_STATUS] = Boolean.TRUE;
}
@@ -2024,8 +2026,8 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
* Continue the previously paused crawling
* @param jobType
*/
- public void continueCrawlJob(String jobType) {
- Object[] status = this.crawlJobsStatus.get(jobType);
+ public void continueCrawlJob(final String jobType) {
+ final Object[] status = this.crawlJobsStatus.get(jobType);
synchronized(status[CRAWLJOB_SYNC]) {
if (((Boolean)status[CRAWLJOB_STATUS]).booleanValue()) {
status[CRAWLJOB_STATUS] = Boolean.FALSE;
@@ -2039,19 +2041,19 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
* @param jobType
* @return <code>true</code> if crawling was paused or <code>false</code> otherwise
*/
- public boolean crawlJobIsPaused(String jobType) {
- Object[] status = this.crawlJobsStatus.get(jobType);
+ public boolean crawlJobIsPaused(final String jobType) {
+ final Object[] status = this.crawlJobsStatus.get(jobType);
synchronized(status[CRAWLJOB_SYNC]) {
return ((Boolean)status[CRAWLJOB_STATUS]).booleanValue();
}
}
- public indexingQueueEntry parseDocument(indexingQueueEntry in) {
+ public indexingQueueEntry parseDocument(final indexingQueueEntry in) {
in.queueEntry.updateStatus(IndexingStack.QUEUE_STATE_PARSING);
plasmaParserDocument document = null;
try {
document = parseDocument(in.queueEntry);
- } catch (InterruptedException e) {
+ } catch (final InterruptedException e) {
document = null;
}
if (document == null) {
@@ -2061,9 +2063,9 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
return new indexingQueueEntry(in.queueEntry, document, null);
}
- private plasmaParserDocument parseDocument(IndexingStack.QueueEntry entry) throws InterruptedException {
+ private plasmaParserDocument parseDocument(final IndexingStack.QueueEntry entry) throws InterruptedException {
plasmaParserDocument document = null;
- int processCase = entry.processCase();
+ final int processCase = entry.processCase();
if (this.log.isFine()) log.logFine("processResourceStack processCase=" + processCase +
", depth=" + entry.depth() +
@@ -2074,14 +2076,14 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
", url=" + entry.url()); // DEBUG
// PARSE CONTENT
- long parsingStartTime = System.currentTimeMillis();
+ final long parsingStartTime = System.currentTimeMillis();
try {
// parse the document
document = parser.parseSource(entry.url(), entry.getMimeType(), entry.getCharacterEncoding(), entry.cacheFile());
assert(document != null) : "Unexpected error. Parser returned null.";
if (document == null) return null;
- } catch (ParserException e) {
+ } catch (final ParserException e) {
this.log.logInfo("Unable to parse the resource '" + entry.url() + "'. " + e.getMessage());
addURLtoErrorDB(entry.url(), entry.referrerHash(), entry.initiator(), entry.anchorName(), e.getErrorCode(), new kelondroBitfield());
if (document != null) {
@@ -2091,19 +2093,19 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
return null;
}
- long parsingEndTime = System.currentTimeMillis();
+ final long parsingEndTime = System.currentTimeMillis();
// get the document date
- Date docDate = entry.getModificationDate();
+ final Date docDate = entry.getModificationDate();
// put anchors on crawl stack
- long stackStartTime = System.currentTimeMillis();
+ final long stackStartTime = System.currentTimeMillis();
if (
((processCase == PROCESSCASE_4_PROXY_LOAD) || (processCase == PROCESSCASE_5_LOCAL_CRAWLING)) &&
((entry.profile() == null) || (entry.depth() < entry.profile().generalDepth()))
) {
- Map<yacyURL, String> hl = document.getHyperlinks();
- Iterator<Map.Entry<yacyURL, String>> i = hl.entrySet().iterator();
+ final Map<yacyURL, String> hl = document.getHyperlinks();
+ final Iterator<Map.Entry<yacyURL, String>> i = hl.entrySet().iterator();
yacyURL nextUrl;
Map.Entry<yacyURL, String> nextEntry;
while (i.hasNext()) {
@@ -2116,7 +2118,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
// enqueue the hyperlink into the pre-notice-url db
crawlStacker.enqueueEntry(nextUrl, entry.urlHash(), entry.initiator(), nextEntry.getValue(), docDate, entry.depth() + 1, entry.profile());
}
- long stackEndTime = System.currentTimeMillis();
+ final long stackEndTime = System.currentTimeMillis();
if (log.isInfo()) log.logInfo("CRAWL: ADDED " + hl.size() + " LINKS FROM " + entry.url().toNormalform(false, true) +
", NEW CRAWL STACK SIZE IS " + crawlQueues.noticeURL.stackSize(NoticedURL.STACK_TYPE_CORE) +
", STACKING TIME = " + (stackEndTime-stackStartTime) +
@@ -2125,12 +2127,12 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
return document;
}
- public indexingQueueEntry condenseDocument(indexingQueueEntry in) {
+ public indexingQueueEntry condenseDocument(final indexingQueueEntry in) {
in.queueEntry.updateStatus(IndexingStack.QUEUE_STATE_CONDENSING);
plasmaCondenser condenser = null;
try {
condenser = condenseDocument(in.queueEntry, in.document);
- } catch (InterruptedException e) {
+ } catch (final InterruptedException e) {
condenser = null;
}
if (condenser == null) {
@@ -2141,17 +2143,17 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
// 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
- CrawlProfile.entry profile = in.queueEntry.profile();
+ final CrawlProfile.entry profile = in.queueEntry.profile();
ResultImages.registerImages(in.document, (profile == null) ? true : !profile.remoteIndexing());
return new indexingQueueEntry(in.queueEntry, in.document, condenser);
}
- private plasmaCondenser condenseDocument(IndexingStack.QueueEntry entry, plasmaParserDocument document) throws InterruptedException {
+ private plasmaCondenser condenseDocument(final IndexingStack.QueueEntry entry, plasmaParserDocument document) throws InterruptedException {
// CREATE INDEX
- String dc_title = document.dc_title();
- yacyURL referrerURL = entry.referrerURL();
- int processCase = entry.processCase();
+ final String dc_title = document.dc_title();
+ final yacyURL referrerURL = entry.referrerURL();
+ final int processCase = entry.processCase();
String noIndexReason = ErrorURL.DENIED_UNSPECIFIED_INDEXING_ERROR;
if (processCase == PROCESSCASE_4_PROXY_LOAD) {
@@ -2185,31 +2187,31 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
plasmaCondenser condenser;
try {
condenser = new plasmaCondenser(document, entry.profile().indexText(), entry.profile().indexMedia());
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
return null;
}
return condenser;
}
- public indexingQueueEntry webStructureAnalysis(indexingQueueEntry in) {
+ public indexingQueueEntry webStructureAnalysis(final indexingQueueEntry in) {
in.queueEntry.updateStatus(IndexingStack.QUEUE_STATE_STRUCTUREANALYSIS);
in.document.notifyWebStructure(webStructure, in.condenser, in.queueEntry.getModificationDate());
return in;
}
- public void storeDocumentIndex(indexingQueueEntry in) {
+ public void storeDocumentIndex(final indexingQueueEntry in) {
in.queueEntry.updateStatus(IndexingStack.QUEUE_STATE_INDEXSTORAGE);
storeDocumentIndex(in.queueEntry, in.document, in.condenser);
in.queueEntry.updateStatus(IndexingStack.QUEUE_STATE_FINISHED);
in.queueEntry.close();
}
- private void storeDocumentIndex(IndexingStack.QueueEntry queueEntry, plasmaParserDocument document, plasmaCondenser condenser) {
+ private void storeDocumentIndex(final IndexingStack.QueueEntry queueEntry, final plasmaParserDocument document, final plasmaCondenser condenser) {
// CREATE INDEX
- String dc_title = document.dc_title();
- yacyURL referrerURL = queueEntry.referrerURL();
- int processCase = queueEntry.processCase();
+ final String dc_title = document.dc_title();
+ final yacyURL referrerURL = queueEntry.referrerURL();
+ final int processCase = queueEntry.processCase();
// remove stopwords
log.logInfo("Excluded " + condenser.excludeWords(stopwords) + " words in URL " + queueEntry.url());
@@ -2218,7 +2220,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
indexURLReference newEntry = null;
try {
newEntry = webIndex.storeDocument(queueEntry, document, condenser);
- } catch (IOException e) {
+ } 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.hash(), queueEntry.initiator(), dc_title, "error storing url: " + e.getMessage(), new kelondroBitfield());
return;
@@ -2252,7 +2254,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
serverProfiling.update("indexed", queueEntry.url().toNormalform(true, false));
// if this was performed for a remote crawl request, notify requester
- yacySeed initiatorPeer = queueEntry.initiatorPeer();
+ final yacySeed initiatorPeer = queueEntry.initiatorPeer();
if ((processCase == PROCESSCASE_6_GLOBAL_CRAWLING) && (initiatorPeer != null)) {
log.logInfo("Sending crawl receipt for '" + queueEntry.url().toNormalform(false, true) + "' to " + initiatorPeer.getName());
if (clusterhashes != null) initiatorPeer.setAlternativeAddress(clusterhashes.get(initiatorPeer.hash));
@@ -2265,7 +2267,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
yacySeed initiatorPeer;
indexURLReference reference;
- public receiptSending(yacySeed initiatorPeer, indexURLReference reference) {
+ public receiptSending(final yacySeed initiatorPeer, final indexURLReference reference) {
this.initiatorPeer = initiatorPeer;
this.reference = reference;
}
@@ -2275,18 +2277,18 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
}
private static SimpleDateFormat DateFormatter = new SimpleDateFormat("EEE, dd MMM yyyy");
- public static String dateString(Date date) {
+ public static String dateString(final Date date) {
if (date == null) return ""; else return DateFormatter.format(date);
}
// we need locale independent RFC-822 dates at some places
private static SimpleDateFormat DateFormatter822 = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US);
- public static String dateString822(Date date) {
+ public static String dateString822(final Date date) {
if (date == null) return ""; else return DateFormatter822.format(date);
}
- public serverObjects action(String actionName, serverObjects actionInput) {
+ public serverObjects action(final String actionName, final serverObjects actionInput) {
// perform an action. (not used)
return null;
}
@@ -2298,35 +2300,35 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
}
// method for index deletion
- public int removeAllUrlReferences(yacyURL url, boolean fetchOnline) {
+ public int removeAllUrlReferences(final yacyURL url, final boolean fetchOnline) {
return removeAllUrlReferences(url.hash(), fetchOnline);
}
- public int removeAllUrlReferences(String urlhash, boolean fetchOnline) {
+ public int removeAllUrlReferences(final String urlhash, final boolean fetchOnline) {
// find all the words in a specific resource and remove the url reference from every word index
// finally, delete the url entry
// determine the url string
- indexURLReference entry = webIndex.getURL(urlhash, null, 0);
+ final indexURLReference entry = webIndex.getURL(urlhash, null, 0);
if (entry == null) return 0;
- indexURLReference.Components comp = entry.comp();
+ final indexURLReference.Components comp = entry.comp();
if (comp.url() == null) return 0;
InputStream resourceContent = null;
try {
// get the resource content
- Object[] resource = plasmaSnippetCache.getResource(comp.url(), fetchOnline, 10000, true, false);
+ final Object[] resource = plasmaSnippetCache.getResource(comp.url(), fetchOnline, 10000, true, false);
resourceContent = (InputStream) resource[0];
- Long resourceContentLength = (Long) resource[1];
+ final Long resourceContentLength = (Long) resource[1];
// parse the resource
- plasmaParserDocument document = plasmaSnippetCache.parseDocument(comp.url(), resourceContentLength.longValue(), resourceContent);
+ final plasmaParserDocument document = plasmaSnippetCache.parseDocument(comp.url(), resourceContentLength.longValue(), resourceContent);
// get the word set
Set<String> words = null;
try {
words = new plasmaCondenser(document, true, true).words().keySet();
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
e.printStackTrace();
}
@@ -2337,29 +2339,29 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
// finally delete the url entry itself
webIndex.removeURL(urlhash);
return count;
- } catch (ParserException e) {
+ } catch (final ParserException e) {
return 0;
} finally {
- if (resourceContent != null) try { resourceContent.close(); } catch (Exception e) {/* ignore this */}
+ if (resourceContent != null) try { resourceContent.close(); } catch (final Exception e) {/* ignore this */}
}
}
- public int adminAuthenticated(httpHeader header) {
+ public int adminAuthenticated(final httpHeader header) {
// authorization for localhost, only if flag is set to grant localhost access as admin
- String clientIP = (String) header.get(httpHeader.CONNECTION_PROP_CLIENTIP, "");
- String refererHost = header.refererHost();
- boolean accessFromLocalhost = serverCore.isLocalhost(clientIP) && (refererHost.length() == 0 || serverCore.isLocalhost(refererHost));
+ final String clientIP = (String) header.get(httpHeader.CONNECTION_PROP_CLIENTIP, "");
+ final String refererHost = header.refererHost();
+ final boolean accessFromLocalhost = serverCore.isLocalhost(clientIP) && (refererHost.length() == 0 || serverCore.isLocalhost(refererHost));
if (getConfigBool("adminAccountForLocalhost", false) && accessFromLocalhost) return 3; // soft-authenticated for localhost
// get the authorization string from the header
- String authorization = ((String) header.get(httpHeader.AUTHORIZATION, "xxxxxx")).trim().substring(6);
+ final String authorization = ((String) header.get(httpHeader.AUTHORIZATION, "xxxxxx")).trim().substring(6);
// security check against too long authorization strings
if (authorization.length() > 256) return 0;
// authorization by encoded password, only for localhost access
- String adminAccountBase64MD5 = getConfig(httpd.ADMIN_ACCOUNT_B64MD5, "");
+ final String adminAccountBase64MD5 = getConfig(httpd.ADMIN_ACCOUNT_B64MD5, "");
if (accessFromLocalhost && (adminAccountBase64MD5.equals(authorization))) return 3; // soft-authenticated for localhost
// authorization by hit in userDB
@@ -2369,11 +2371,11 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
return httpd.staticAdminAuthenticated(authorization, this);
}
- public boolean verifyAuthentication(httpHeader header, boolean strict) {
+ public boolean verifyAuthentication(final httpHeader header, final boolean strict) {
// handle access rights
switch (adminAuthenticated(header)) {
case 0: // wrong password given
- try { Thread.sleep(3000); } catch (InterruptedException e) { } // prevent brute-force
+ try { Thread.sleep(3000); } catch (final InterruptedException e) { } // prevent brute-force
return false;
case 1: // no password given
return false;
@@ -2394,7 +2396,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
// 1000 <= wantedPPM : maximum performance
if (wantedPPM <= 10) wantedPPM = 10;
if (wantedPPM >= 6000) wantedPPM = 6000;
- int newBusySleep = 60000 / wantedPPM; // for wantedPPM = 10: 6000; for wantedPPM = 1000: 60
+ final int newBusySleep = 60000 / wantedPPM; // for wantedPPM = 10: 6000; for wantedPPM = 1000: 60
serverBusyThread thread;
@@ -2424,15 +2426,15 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
}
- public static int accessFrequency(HashMap<String, TreeSet<Long>> tracker, String host) {
+ public static int accessFrequency(final HashMap<String, TreeSet<Long>> tracker, final String host) {
// returns the access frequency in queries per hour for a given host and a specific tracker
- long timeInterval = 1000 * 60 * 60;
- TreeSet<Long> accessSet = tracker.get(host);
+ final long timeInterval = 1000 * 60 * 60;
+ final TreeSet<Long> accessSet = tracker.get(host);
if (accessSet == null) return 0;
return accessSet.tailSet(new Long(System.currentTimeMillis() - timeInterval)).size();
}
- public void startTransferWholeIndex(yacySeed seed, boolean delete) {
+ public void startTransferWholeIndex(final yacySeed seed, final boolean delete) {
if (transferIdxThread == null) {
this.transferIdxThread = new plasmaDHTFlush(this.log, this.webIndex, seed, delete,
"true".equalsIgnoreCase(getConfig(INDEX_TRANSFER_GZIP_BODY, "false")),
@@ -2441,20 +2443,20 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
}
}
- public void stopTransferWholeIndex(boolean wait) {
+ public void stopTransferWholeIndex(final boolean wait) {
if ((transferIdxThread != null) && (transferIdxThread.isAlive()) && (!transferIdxThread.isFinished())) {
try {
this.transferIdxThread.stopIt(wait);
- } catch (InterruptedException e) { }
+ } catch (final InterruptedException e) { }
}
}
- public void abortTransferWholeIndex(boolean wait) {
+ public void abortTransferWholeIndex(final boolean wait) {
if (transferIdxThread != null) {
if (!transferIdxThread.isFinished())
try {
this.transferIdxThread.stopIt(wait);
- } catch (InterruptedException e) { }
+ } catch (final InterruptedException e) { }
transferIdxThread = null;
}
}
@@ -2494,7 +2496,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
}
public boolean dhtTransferJob() {
- String rejectReason = dhtShallTransfer();
+ final String rejectReason = dhtShallTransfer();
if (rejectReason != null) {
if (this.log.isFine()) log.logFine(rejectReason);
return false;
@@ -2509,12 +2511,12 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
}
// do the transfer
- int peerCount = Math.max(1, (this.webIndex.seedDB.mySeed().isJunior()) ?
+ final int peerCount = Math.max(1, (this.webIndex.seedDB.mySeed().isJunior()) ?
(int) getConfigLong("network.unit.dhtredundancy.junior", 1) :
(int) getConfigLong("network.unit.dhtredundancy.senior", 1)); // set redundancy factor
- long starttime = System.currentTimeMillis();
+ final long starttime = System.currentTimeMillis();
- boolean ok = dhtTransferProcess(dhtTransferChunk, peerCount);
+ final boolean ok = dhtTransferProcess(dhtTransferChunk, peerCount);
if (ok) {
dhtTransferChunk.setStatus(plasmaDHTChunk.chunkStatus_COMPLETE);
@@ -2525,8 +2527,8 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
} else {
if (dhtTransferChunk.indexCount() >= dhtTransferIndexCount) dhtTransferIndexCount++;
}
- int minChunkSize = (int) getConfigLong(INDEX_DIST_CHUNK_SIZE_MIN, 30);
- int maxChunkSize = (int) getConfigLong(INDEX_DIST_CHUNK_SIZE_MAX, 3000);
+ final int minChunkSize = (int) getConfigLong(INDEX_DIST_CHUNK_SIZE_MIN, 30);
+ final int maxChunkSize = (int) getConfigLong(INDEX_DIST_CHUNK_SIZE_MAX, 3000);
if (dhtTransferIndexCount < minChunkSize) dhtTransferIndexCount = minChunkSize;
if (dhtTransferIndexCount > maxChunkSize) dhtTransferIndexCount = maxChunkSize;
@@ -2534,7 +2536,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
return true;
} else {
dhtTransferChunk.incTransferFailedCounter();
- int maxChunkFails = (int) getConfigLong(INDEX_DIST_CHUNK_FAILS_MAX, 1);
+ final int maxChunkFails = (int) getConfigLong(INDEX_DIST_CHUNK_FAILS_MAX, 1);
if (dhtTransferChunk.getTransferFailedCounter() >= maxChunkFails) {
//System.out.println("DEBUG: " + dhtTransferChunk.getTransferFailedCounter() + " of " + maxChunkFails + " sendings failed for this chunk, aborting!");
dhtTransferChunk.setStatus(plasmaDHTChunk.chunkStatus_FAILED);
@@ -2548,13 +2550,13 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
}
}
- public boolean dhtTransferProcess(plasmaDHTChunk dhtChunk, int peerCount) {
+ public boolean dhtTransferProcess(final plasmaDHTChunk dhtChunk, final int peerCount) {
if ((this.webIndex.seedDB == null) || (this.webIndex.seedDB.sizeConnected() == 0)) return false;
try {
// find a list of DHT-peers
- double maxDist = 0.2;
- ArrayList<yacySeed> seeds = webIndex.peerActions.dhtAction.getDHTTargets(webIndex.seedDB, log, peerCount, Math.min(8, (int) (this.webIndex.seedDB.sizeConnected() * maxDist)), dhtChunk.firstContainer().getWordHash(), dhtChunk.lastContainer().getWordHash(), maxDist);
+ final double maxDist = 0.2;
+ final ArrayList<yacySeed> seeds = webIndex.peerActions.dhtAction.getDHTTargets(webIndex.seedDB, log, peerCount, Math.min(8, (int) (this.webIndex.seedDB.sizeConnected() * maxDist)), dhtChunk.firstContainer().getWordHash(), dhtChunk.lastContainer().getWordHash(), maxDist);
if (seeds.size() < peerCount) {
log.logWarning("found not enough (" + seeds.size() + ") peers for distribution for dhtchunk [" + dhtChunk.firstContainer().getWordHash() + " .. " + dhtChunk.lastContainer().getWordHash() + "]");
return false;
@@ -2564,23 +2566,23 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
int hc1 = 0;
// getting distribution configuration values
- boolean gzipBody = getConfig(INDEX_DIST_GZIP_BODY, "false").equalsIgnoreCase("true");
- int timeout = (int)getConfigLong(INDEX_DIST_TIMEOUT, 60000);
- int retries = 0;
+ final boolean gzipBody = getConfig(INDEX_DIST_GZIP_BODY, "false").equalsIgnoreCase("true");
+ final int timeout = (int)getConfigLong(INDEX_DIST_TIMEOUT, 60000);
+ final int retries = 0;
// starting up multiple DHT transfer threads
- Iterator<yacySeed> seedIter = seeds.iterator();
- ArrayList<plasmaDHTTransfer> transfer = new ArrayList<plasmaDHTTransfer>(peerCount);
+ final Iterator<yacySeed> seedIter = seeds.iterator();
+ final ArrayList<plasmaDHTTransfer> transfer = new ArrayList<plasmaDHTTransfer>(peerCount);
while (hc1 < peerCount && (transfer.size() > 0 || seedIter.hasNext())) {
// starting up some transfer threads
- int transferThreadCount = transfer.size();
+ final int transferThreadCount = transfer.size();
for (int i=0; i < peerCount-hc1-transferThreadCount; i++) {
// check for interruption
checkInterruption();
if (seedIter.hasNext()) {
- plasmaDHTTransfer t = new plasmaDHTTransfer(log, webIndex.seedDB, webIndex.peerActions, seedIter.next(), dhtChunk,gzipBody,timeout,retries);
+ final plasmaDHTTransfer t = new plasmaDHTTransfer(log, webIndex.seedDB, webIndex.peerActions, seedIter.next(), dhtChunk,gzipBody,timeout,retries);
t.start();
transfer.add(t);
} else {
@@ -2589,12 +2591,12 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
}
// waiting for the transfer threads to finish
- Iterator<plasmaDHTTransfer> transferIter = transfer.iterator();
+ final Iterator<plasmaDHTTransfer> transferIter = transfer.iterator();
while (transferIter.hasNext()) {
// check for interruption
checkInterruption();
- plasmaDHTTransfer t = transferIter.next();
+ final plasmaDHTTransfer t = transferIter.next();
if (!t.isAlive()) {
// remove finished thread from the list
transferIter.remove();
@@ -2618,22 +2620,22 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
}
this.log.logSevere("Index distribution failed. Too few peers (" + hc1 + ") received the index, not deleted locally.");
return false;
- } catch (InterruptedException e) {
+ } catch (final InterruptedException e) {
return false;
}
}
private void addURLtoErrorDB(
- yacyURL url,
- String referrerHash,
- String initiator,
- String name,
- String failreason,
- kelondroBitfield flags
+ final yacyURL url,
+ final String referrerHash,
+ final String initiator,
+ final String name,
+ final String failreason,
+ final kelondroBitfield flags
) {
assert initiator != null;
// create a new errorURL DB entry
- CrawlEntry bentry = new CrawlEntry(
+ final CrawlEntry bentry = new CrawlEntry(
initiator,
url,
referrerHash,
@@ -2643,7 +2645,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
0,
0,
0);
- ZURL.Entry ee = crawlQueues.errorURL.newEntry(
+ final ZURL.Entry ee = crawlQueues.errorURL.newEntry(
bentry, initiator, new Date(),
0, failreason);
// store the entry
@@ -2660,9 +2662,9 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
webIndex.seedDB.mySeed().put(yacySeed.NAME, getConfig("peerName", "nameless"));
webIndex.seedDB.mySeed().put(yacySeed.PORT, Integer.toString(serverCore.getPortNr(getConfig("port", "8080"))));
- long uptime = (System.currentTimeMillis() - serverCore.startupTime) / 1000;
- long uptimediff = uptime - lastseedcheckuptime;
- long indexedcdiff = indexedPages - lastindexedPages;
+ final long uptime = (System.currentTimeMillis() - serverCore.startupTime) / 1000;
+ final long uptimediff = uptime - lastseedcheckuptime;
+ final long indexedcdiff = indexedPages - lastindexedPages;
//double requestcdiff = requestedQueries - lastrequestedQueries;
if (uptimediff > 300 || uptimediff <= 0 || lastseedcheckuptime == -1 ) {
lastseedcheckuptime = uptime;
@@ -2701,7 +2703,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
ArrayList<String> seedList;
Iterator<String> enu;
int lc;
- int sc = webIndex.seedDB.sizeConnected();
+ final int sc = webIndex.seedDB.sizeConnected();
httpHeader header;
yacyCore.log.logInfo("BOOTSTRAP: " + sc + " seeds known from previous run");
@@ -2719,15 +2721,15 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
) {
// load the seed list
try {
- httpHeader reqHeader = new httpHeader();
+ final httpHeader reqHeader = new httpHeader();
reqHeader.put(httpHeader.PRAGMA, "no-cache");
reqHeader.put(httpHeader.CACHE_CONTROL, "no-cache");
reqHeader.put(httpHeader.USER_AGENT, HTTPLoader.yacyUserAgent);
url = new yacyURL(seedListFileURL, null);
- long start = System.currentTimeMillis();
+ final long start = System.currentTimeMillis();
header = HttpClient.whead(url.toString(), reqHeader);
- long loadtime = System.currentTimeMillis() - start;
+ final long loadtime = System.currentTimeMillis() - start;
if (header == null) {
if (loadtime > getConfigLong("bootstrapLoadTimeout", 6000)) {
yacyCore.log.logWarning("BOOTSTRAP: seed-list URL " + seedListFileURL + " not available, time-out after " + loadtime + " milliseconds");
@@ -2757,10 +2759,10 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
yacyCore.log.logInfo("BOOTSTRAP: " + lc + " seeds from seed-list URL " + seedListFileURL + ", AGE=" + (header.age() / 3600000) + "h");
}
- } catch (IOException e) {
+ } catch (final IOException e) {
// this is when wget fails, commonly because of timeout
yacyCore.log.logWarning("BOOTSTRAP: failed (1) to load seeds from seed-list URL " + seedListFileURL + ": " + e.getMessage());
- } catch (Exception e) {
+ } catch (final Exception e) {
// this is when wget fails; may be because of missing internet connection
yacyCore.log.logSevere("BOOTSTRAP: failed (2) to load seeds from seed-list URL " + seedListFileURL + ": " + e.getMessage(), e);
}
@@ -2770,12 +2772,12 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
}
public void checkInterruption() throws InterruptedException {
- Thread curThread = Thread.currentThread();
+ final Thread curThread = Thread.currentThread();
if ((curThread instanceof serverThread) && ((serverThread)curThread).shutdownInProgress()) throw new InterruptedException("Shutdown in progress ...");
else if (this.terminate || curThread.isInterrupted()) throw new InterruptedException("Shutdown in progress ...");
}
- public void terminate(long delay) {
+ public void terminate(final long delay) {
if (delay <= 0) throw new IllegalArgumentException("The shutdown delay must be greater than 0.");
(new delayedShutdown(this,delay)).start();
}
@@ -2802,15 +2804,15 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.
* @param url
* @return
*/
- public static Map<String, String> loadHashMap(yacyURL url) {
+ public static Map<String, String> loadHashMap(final yacyURL url) {
try {
// sending request
- httpHeader reqHeader = new httpHeader();
+ final httpHeader reqHeader = new httpHeader();
reqHeader.put(httpHeader.USER_AGENT, HTTPLoader.yacyUserAgent);
final HashMap<String, String> result = nxTools.table(HttpClient.wget(url.toString(), reqHeader, 10000), "UTF-8");
if (result == null) return new HashMap<String, String>();
return result;
- } catch (Exception e) {
+ } catch (final Exception e) {
return new HashMap<String, String>();
}
}
@@ -2823,9 +2825,9 @@ class MoreMemory extends TimerTask {
}
class delayedShutdown extends Thread {
- private plasmaSwitchboard sb;
- private long delay;
- public delayedShutdown(plasmaSwitchboard sb, long delay) {
+ private final plasmaSwitchboard sb;
+ private final long delay;
+ public delayedShutdown(final plasmaSwitchboard sb, final long delay) {
this.sb = sb;
this.delay = delay;
}
@@ -2833,7 +2835,7 @@ class delayedShutdown extends Thread {
public void run() {
try {
Thread.sleep(delay);
- } catch (InterruptedException e) {
+ } catch (final InterruptedException e) {
sb.getLog().logInfo("interrupted delayed shutdown");
}
this.sb.terminate();
diff --git a/source/de/anomic/plasma/plasmaWebStructure.java b/source/de/anomic/plasma/plasmaWebStructure.java
index 45670b887..ece343ba3 100644
--- a/source/de/anomic/plasma/plasmaWebStructure.java
+++ b/source/de/anomic/plasma/plasmaWebStructure.java
@@ -52,12 +52,12 @@ public class plasmaWebStructure {
public static int maxhosts = 8000; // maximum number of hosts in web structure map
private StringBuffer crg; // global citation references
- private serverLog log;
- private File rankingPath, structureFile;
- private String crlFile, crgFile;
+ private final serverLog log;
+ private final File rankingPath, structureFile;
+ private final String crlFile, crgFile;
TreeMap<String, String> structure_old, structure_new; // <b64hash(6)>','<host> to <date-yyyymmdd(8)>{<target-b64hash(6)><target-count-hex(4)>}*
- public plasmaWebStructure(serverLog log, File rankingPath, String crlFile, String crgFile, File structureFile) {
+ public plasmaWebStructure(final serverLog log, final File rankingPath, final String crlFile, final String crgFile, final File structureFile) {
this.log = log;
this.rankingPath = rankingPath;
this.crlFile = crlFile;
@@ -68,21 +68,21 @@ public class plasmaWebStructure {
this.structureFile = structureFile;
// load web structure
- Map<String, String> loadedStructure = (this.structureFile.exists()) ? serverFileUtils.loadHashMap(this.structureFile) : new TreeMap<String, String>();
+ final Map<String, String> loadedStructure = (this.structureFile.exists()) ? serverFileUtils.loadHashMap(this.structureFile) : new TreeMap<String, String>();
if (loadedStructure != null) this.structure_old.putAll(loadedStructure);
// delete out-dated entries in case the structure is too big
if (this.structure_old.size() > maxhosts) {
// fill a set with last-modified - dates of the structure
- TreeSet<String> delset = new TreeSet<String>();
+ final TreeSet<String> delset = new TreeSet<String>();
String key, value;
- for (Map.Entry<String, String> entry : this.structure_old.entrySet()) {
+ for (final Map.Entry<String, String> entry : this.structure_old.entrySet()) {
key = entry.getKey();
value = entry.getValue();
delset.add(value.substring(0, 8) + key);
}
int delcount = this.structure_old.size() - (maxhosts * 9 / 10);
- Iterator<String> j = delset.iterator();
+ final Iterator<String> j = delset.iterator();
while ((delcount > 0) && (j.hasNext())) {
this.structure_old.remove(j.next().substring(8));
delcount--;
@@ -90,16 +90,16 @@ public class plasmaWebStructure {
}
}
- public Integer[] /*(outlinksSame, outlinksOther)*/ generateCitationReference(plasmaParserDocument document, plasmaCondenser condenser, Date docDate) {
- yacyURL url = document.dc_source();
+ public Integer[] /*(outlinksSame, outlinksOther)*/ generateCitationReference(final plasmaParserDocument document, final plasmaCondenser condenser, final Date docDate) {
+ final yacyURL url = document.dc_source();
// generate citation reference
- Map<yacyURL, String> hl = document.getHyperlinks();
- Iterator<yacyURL> it = hl.keySet().iterator();
+ final Map<yacyURL, String> hl = document.getHyperlinks();
+ final Iterator<yacyURL> it = hl.keySet().iterator();
String nexturlhash;
- StringBuffer cpg = new StringBuffer(12 * (hl.size() + 1) + 1);
- StringBuffer cpl = new StringBuffer(12 * (hl.size() + 1) + 1);
- String lhp = url.hash().substring(6); // local hash part
+ final StringBuffer cpg = new StringBuffer(12 * (hl.size() + 1) + 1);
+ final StringBuffer cpl = new StringBuffer(12 * (hl.size() + 1) + 1);
+ final String lhp = url.hash().substring(6); // local hash part
int GCount = 0;
int LCount = 0;
while (it.hasNext()) {
@@ -119,7 +119,7 @@ public class plasmaWebStructure {
// append this reference to buffer
// generate header info
- String head = url.hash() + "=" +
+ final String head = url.hash() + "=" +
kelondroMicroDate.microDateHoursStr(docDate.getTime()) + // latest update timestamp of the URL
kelondroMicroDate.microDateHoursStr(System.currentTimeMillis()) + // last visit timestamp of the URL
kelondroBase64Order.enhancedCoder.encodeLongSmart(LCount, 2) + // count of links to local resources
@@ -151,15 +151,15 @@ public class plasmaWebStructure {
return new Integer[] {new Integer(LCount), new Integer(GCount)};
}
- public void flushCitationReference(String type) {
+ public void flushCitationReference(final String type) {
if (crg.length() < 12) return;
- String filename = type.toUpperCase() + "-A-" + new serverDate().toShortString(true) + "." + crg.substring(0, 12) + ".cr.gz";
- File path = new File(rankingPath, (type.equals("crl")) ? crlFile : crgFile);
+ final String filename = type.toUpperCase() + "-A-" + new serverDate().toShortString(true) + "." + crg.substring(0, 12) + ".cr.gz";
+ final File path = new File(rankingPath, (type.equals("crl")) ? crlFile : crgFile);
path.mkdirs();
- File file = new File(path, filename);
+ final File file = new File(path, filename);
// generate header
- StringBuffer header = new StringBuffer(200);
+ final StringBuffer header = new StringBuffer(200);
header.append("# Name=YaCy " + ((type.equals("crl")) ? "Local" : "Global") + " Citation Reference Ticket"); header.append((char) 13); header.append((char) 10);
header.append("# Created=" + System.currentTimeMillis()); header.append((char) 13); header.append((char) 10);
header.append("# Structure=<Referee-12>,'=',<UDate-3>,<VDate-3>,<LCount-2>,<GCount-2>,<ICount-2>,<DCount-2>,<TLength-3>,<WACount-3>,<WUCount-3>,<Flags-1>,'|',*<Anchor-" + ((type.equals("crl")) ? "6" : "12") + ">"); header.append((char) 13); header.append((char) 10);
@@ -168,22 +168,22 @@ public class plasmaWebStructure {
try {
serverFileUtils.writeAndGZip(crg.toString().getBytes(), file);
if (this.log.isFine()) log.logFine("wrote citation reference dump " + file.toString());
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
}
- private static int refstr2count(String refs) {
+ private static int refstr2count(final String refs) {
if ((refs == null) || (refs.length() <= 8)) return 0;
assert (refs.length() - 8) % 10 == 0;
return (refs.length() - 8) / 10;
}
- static Map<String, Integer> refstr2map(String refs) {
+ static Map<String, Integer> refstr2map(final String refs) {
if ((refs == null) || (refs.length() <= 8)) return new HashMap<String, Integer>();
- Map<String, Integer> map = new HashMap<String, Integer>();
+ final Map<String, Integer> map = new HashMap<String, Integer>();
String c;
- int refsc = refstr2count(refs);
+ final int refsc = refstr2count(refs);
for (int i = 0; i < refsc; i++) {
c = refs.substring(8 + i * 10, 8 + (i + 1) * 10);
map.put(c.substring(0, 6), new Integer(Integer.parseInt(c.substring(6), 16)));
@@ -191,11 +191,11 @@ public class plasmaWebStructure {
return map;
}
- private static String map2refstr(Map<String, Integer> map) {
- StringBuffer s = new StringBuffer(map.size() * 10);
+ private static String map2refstr(final Map<String, Integer> map) {
+ final StringBuffer s = new StringBuffer(map.size() * 10);
s.append(serverDate.formatShortDay(new Date()));
String h;
- for (Map.Entry<String, Integer> entry : map.entrySet()) {
+ for (final Map.Entry<String, Integer> entry : map.entrySet()) {
s.append(entry.getKey());
h = Integer.toHexString(entry.getValue().intValue());
if (h.length() == 0) {
@@ -215,7 +215,7 @@ public class plasmaWebStructure {
return s.toString();
}
- public Map<String, Integer> references(String domhash) {
+ public Map<String, Integer> references(final String domhash) {
// returns a map with a domhash(String):refcount(Integer) relation
assert domhash.length() == 6;
SortedMap<String, String> tailMap;
@@ -223,7 +223,7 @@ public class plasmaWebStructure {
synchronized (structure_old) {
tailMap = structure_old.tailMap(domhash);
if (!tailMap.isEmpty()) {
- String key = tailMap.firstKey();
+ final String key = tailMap.firstKey();
if (key.startsWith(domhash)) {
h = refstr2map(tailMap.get(key));
}
@@ -232,7 +232,7 @@ public class plasmaWebStructure {
synchronized (structure_new) {
tailMap = structure_new.tailMap(domhash);
if (!tailMap.isEmpty()) {
- String key = tailMap.firstKey();
+ final String key = tailMap.firstKey();
if (key.startsWith(domhash)) {
h.putAll(refstr2map(tailMap.get(key)));
}
@@ -241,7 +241,7 @@ public class plasmaWebStructure {
return h;
}
- public int referencesCount(String domhash) {
+ public int referencesCount(final String domhash) {
// returns the number of domains that are referenced by this domhash
assert domhash.length() == 6 : "domhash = " + domhash;
SortedMap<String, String> tailMap;
@@ -249,7 +249,7 @@ public class plasmaWebStructure {
synchronized (structure_old) {
tailMap = structure_old.tailMap(domhash);
if (!tailMap.isEmpty()) {
- String key = tailMap.firstKey();
+ final String key = tailMap.firstKey();
if (key.startsWith(domhash)) {
c = refstr2count(tailMap.get(key));
}
@@ -258,7 +258,7 @@ public class plasmaWebStructure {
synchronized (structure_new) {
tailMap = structure_new.tailMap(domhash);
if (!tailMap.isEmpty()) {
- String key = tailMap.firstKey();
+ final String key = tailMap.firstKey();
if (key.startsWith(domhash)) {
c += refstr2count(tailMap.get(key));
}
@@ -267,14 +267,14 @@ public class plasmaWebStructure {
return c;
}
- public String resolveDomHash2DomString(String domhash) {
+ public String resolveDomHash2DomString(final String domhash) {
// returns the domain as string, null if unknown
assert domhash.length() == 6;
SortedMap<String, String> tailMap;
synchronized(structure_old) {
tailMap = structure_old.tailMap(domhash);
if (!tailMap.isEmpty()) {
- String key = tailMap.firstKey();
+ final String key = tailMap.firstKey();
if (key.startsWith(domhash)) {
return key.substring(7);
}
@@ -283,7 +283,7 @@ public class plasmaWebStructure {
synchronized(structure_new) {
tailMap = structure_new.tailMap(domhash);
if (!tailMap.isEmpty()) {
- String key = tailMap.firstKey();
+ final String key = tailMap.firstKey();
if (key.startsWith(domhash)) {
return key.substring(7);
}
@@ -292,11 +292,11 @@ public class plasmaWebStructure {
return null;
}
- private void learn(yacyURL url, StringBuffer reference /*string of b64(12digits)-hashes*/) {
- String domhash = url.hash().substring(6);
+ private void learn(final yacyURL url, final StringBuffer reference /*string of b64(12digits)-hashes*/) {
+ final String domhash = url.hash().substring(6);
// parse the new reference string and join it with the stored references
- Map<String, Integer> refs = references(domhash);
+ final Map<String, Integer> refs = references(domhash);
assert reference.length() % 12 == 0;
String dom;
int c;
@@ -316,7 +316,7 @@ public class plasmaWebStructure {
// shrink the references: the entry with the smallest number of references is removed
int minrefcount = Integer.MAX_VALUE;
String minrefkey = null;
- findloop: for (Map.Entry<String, Integer> entry : refs.entrySet()) {
+ findloop: for (final Map.Entry<String, Integer> entry : refs.entrySet()) {
if (entry.getValue().intValue() < minrefcount) {
minrefcount = entry.getValue().intValue();
minrefkey = entry.getKey();
@@ -336,12 +336,12 @@ public class plasmaWebStructure {
}
}
- private static final void joinStructure(TreeMap<String, String> into, TreeMap<String, String> from) {
- for (Map.Entry<String, String> e: from.entrySet()) {
+ private static final void joinStructure(final TreeMap<String, String> into, final TreeMap<String, String> from) {
+ for (final Map.Entry<String, String> e: from.entrySet()) {
if (into.containsKey(e.getKey())) {
- Map<String, Integer> s0 = refstr2map(into.get(e.getKey()));
- Map<String, Integer> s1 = refstr2map(e.getValue());
- for (Map.Entry<String, Integer> r: s1.entrySet()) {
+ final Map<String, Integer> s0 = refstr2map(into.get(e.getKey()));
+ final Map<String, Integer> s1 = refstr2map(e.getValue());
+ for (final Map.Entry<String, Integer> r: s1.entrySet()) {
if (s0.containsKey(r.getKey())) {
s0.put(r.getKey(), s0.get(r.getKey()).intValue() + r.getValue().intValue());
} else {
@@ -368,7 +368,7 @@ public class plasmaWebStructure {
synchronized(structure_old) {
serverFileUtils.saveMap(this.structureFile, this.structure_old, "Web Structure Syntax: <b64hash(6)>','<host> to <date-yyyymmdd(8)>{<target-b64hash(6)><target-count-hex(4)>}*");
}
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
}
@@ -379,7 +379,7 @@ public class plasmaWebStructure {
int refsize, maxref = 0;
joinOldNew();
synchronized(structure_new) {
- for (Map.Entry<String, String> entry : structure_old.entrySet()) {
+ for (final Map.Entry<String, String> entry : structure_old.entrySet()) {
refsize = entry.getValue().length();
if (refsize > maxref) {
maxref = refsize;
@@ -390,17 +390,17 @@ public class plasmaWebStructure {
return maxhost;
}
- public Iterator<structureEntry> structureEntryIterator(boolean latest) {
+ public Iterator<structureEntry> structureEntryIterator(final boolean latest) {
// iterates objects of type structureEntry
return new structureIterator(latest);
}
public class structureIterator implements Iterator<structureEntry> {
- private Iterator<Map.Entry<String, String>> i;
+ private final Iterator<Map.Entry<String, String>> i;
private structureEntry nextentry;
- public structureIterator(boolean latest) {
+ public structureIterator(final boolean latest) {
i = ((latest) ? structure_new : structure_old).entrySet().iterator();
next0();
}
@@ -430,7 +430,7 @@ public class plasmaWebStructure {
}
public structureEntry next() {
- structureEntry r = nextentry;
+ final structureEntry r = nextentry;
next0();
return r;
}
@@ -444,7 +444,7 @@ public class plasmaWebStructure {
public class structureEntry {
public String domhash, domain, date;
public Map<String, Integer> references;
- public structureEntry(String domhash, String domain, String date, Map<String, Integer> references) {
+ public structureEntry(final String domhash, final String domain, final String date, final Map<String, Integer> references) {
this.domhash = domhash;
this.domain = domain;
this.date = date;
diff --git a/source/de/anomic/plasma/plasmaWordIndex.java b/source/de/anomic/plasma/plasmaWordIndex.java
index c9081771a..517f4ac89 100644
--- a/source/de/anomic/plasma/plasmaWordIndex.java
+++ b/source/de/anomic/plasma/plasmaWordIndex.java
@@ -92,29 +92,29 @@ public final class plasmaWordIndex implements indexRI {
private final kelondroByteOrder indexOrder = kelondroBase64Order.enhancedCoder;
private final indexRAMRI dhtOutCache, dhtInCache;
private final indexCollectionRI collections; // new database structure to replace AssortmentCluster and FileCluster
- private serverLog log;
+ private final serverLog log;
indexRepositoryReference referenceURL;
public yacySeedDB seedDB;
public yacyNewsPool newsPool;
- private File primaryRoot, secondaryRoot;
+ private final File primaryRoot, secondaryRoot;
public IndexingStack queuePreStack;
public CrawlProfile profilesActiveCrawls, profilesPassiveCrawls;
public CrawlProfile.entry defaultProxyProfile;
public CrawlProfile.entry defaultRemoteProfile;
public CrawlProfile.entry defaultTextSnippetLocalProfile, defaultTextSnippetGlobalProfile;
public CrawlProfile.entry defaultMediaSnippetLocalProfile, defaultMediaSnippetGlobalProfile;
- private File queuesRoot;
+ private final File queuesRoot;
public yacyPeerActions peerActions;
- public plasmaWordIndex(String networkName, serverLog log, File indexPrimaryRoot, File indexSecondaryRoot, int entityCacheMaxSize) {
+ public plasmaWordIndex(final String networkName, final serverLog log, final File indexPrimaryRoot, final File indexSecondaryRoot, final int entityCacheMaxSize) {
this.log = log;
this.primaryRoot = new File(indexPrimaryRoot, networkName);
this.secondaryRoot = new File(indexSecondaryRoot, networkName);
File indexPrimaryTextLocation = new File(this.primaryRoot, "TEXT");
if (!indexPrimaryTextLocation.exists()) {
// patch old index locations; the secondary path is patched in plasmaCrawlLURL
- File oldPrimaryPath = new File(new File(indexPrimaryRoot, "PUBLIC"), "TEXT");
- File oldPrimaryTextLocation = new File(new File(indexPrimaryRoot, "PUBLIC"), "TEXT");
+ final File oldPrimaryPath = new File(new File(indexPrimaryRoot, "PUBLIC"), "TEXT");
+ final File oldPrimaryTextLocation = new File(new File(indexPrimaryRoot, "PUBLIC"), "TEXT");
if (oldPrimaryPath.exists() && oldPrimaryTextLocation.exists()) {
// move the text folder from the old location to the new location
assert !indexPrimaryTextLocation.exists();
@@ -127,13 +127,13 @@ public final class plasmaWordIndex implements indexRI {
}
}
- File textindexcache = new File(indexPrimaryTextLocation, "RICACHE");
+ final File textindexcache = new File(indexPrimaryTextLocation, "RICACHE");
if (!(textindexcache.exists())) textindexcache.mkdirs();
this.dhtOutCache = new indexRAMRI(textindexcache, indexRWIRowEntry.urlEntryRow, entityCacheMaxSize, wCacheMaxChunk, wCacheMaxAge, "dump1.array", "index.dhtout.heap", log);
this.dhtInCache = new indexRAMRI(textindexcache, indexRWIRowEntry.urlEntryRow, entityCacheMaxSize, wCacheMaxChunk, wCacheMaxAge, "dump2.array", "index.dhtin.heap", log);
// create collections storage path
- File textindexcollections = new File(indexPrimaryTextLocation, "RICOLLECTION");
+ final File textindexcollections = new File(indexPrimaryTextLocation, "RICOLLECTION");
if (!(textindexcollections.exists())) textindexcollections.mkdirs();
this.collections = new indexCollectionRI(textindexcollections, "collection", maxCollectionPartition, indexRWIRowEntry.urlEntryRow);
@@ -144,10 +144,10 @@ public final class plasmaWordIndex implements indexRI {
this.queuesRoot = new File(this.primaryRoot, "QUEUES");
this.queuesRoot.mkdirs();
this.log.logConfig("Initializing Crawl Profiles");
- File profilesActiveFile = new File(queuesRoot, DBFILE_ACTIVE_CRAWL_PROFILES);
+ final File profilesActiveFile = new File(queuesRoot, DBFILE_ACTIVE_CRAWL_PROFILES);
if (!profilesActiveFile.exists()) {
// migrate old file
- File oldFile = new File(new File(queuesRoot.getParentFile().getParentFile().getParentFile(), "PLASMADB"), "crawlProfilesActive1.db");
+ final File oldFile = new File(new File(queuesRoot.getParentFile().getParentFile().getParentFile(), "PLASMADB"), "crawlProfilesActive1.db");
if (oldFile.exists()) oldFile.renameTo(profilesActiveFile);
}
this.profilesActiveCrawls = new CrawlProfile(profilesActiveFile);
@@ -155,10 +155,10 @@ public final class plasmaWordIndex implements indexRI {
log.logConfig("Loaded active crawl profiles from file " + profilesActiveFile.getName() +
", " + this.profilesActiveCrawls.size() + " entries" +
", " + profilesActiveFile.length()/1024);
- File profilesPassiveFile = new File(queuesRoot, DBFILE_PASSIVE_CRAWL_PROFILES);
+ final File profilesPassiveFile = new File(queuesRoot, DBFILE_PASSIVE_CRAWL_PROFILES);
if (!profilesPassiveFile.exists()) {
// migrate old file
- File oldFile = new File(new File(queuesRoot.getParentFile().getParentFile().getParentFile(), "PLASMADB"), "crawlProfilesPassive1.db");
+ final File oldFile = new File(new File(queuesRoot.getParentFile().getParentFile().getParentFile(), "PLASMADB"), "crawlProfilesPassive1.db");
if (oldFile.exists()) oldFile.renameTo(profilesPassiveFile);
}
this.profilesPassiveCrawls = new CrawlProfile(profilesPassiveFile);
@@ -167,19 +167,19 @@ public final class plasmaWordIndex implements indexRI {
", " + profilesPassiveFile.length()/1024);
// init queues
- File preStackFile = new File(queuesRoot, "urlNoticePreStack");
+ final File preStackFile = new File(queuesRoot, "urlNoticePreStack");
if (!preStackFile.exists()) {
// migrate old file
- File oldFile = new File(new File(queuesRoot.getParentFile().getParentFile().getParentFile(), "PLASMADB"), "switchboardQueue.stack");
+ final File oldFile = new File(new File(queuesRoot.getParentFile().getParentFile().getParentFile(), "PLASMADB"), "switchboardQueue.stack");
if (oldFile.exists()) oldFile.renameTo(preStackFile);
}
this.queuePreStack = new IndexingStack(this, preStackFile, this.profilesActiveCrawls);
// create or init seed cache
- File networkRoot = new File(this.primaryRoot, "NETWORK");
+ final File networkRoot = new File(this.primaryRoot, "NETWORK");
networkRoot.mkdirs();
- File mySeedFile = new File(networkRoot, yacySeedDB.DBFILE_OWN_SEED);
- File oldSeedFile = new File(new File(indexPrimaryRoot.getParentFile(), "YACYDB"), "mySeed.txt");
+ final File mySeedFile = new File(networkRoot, yacySeedDB.DBFILE_OWN_SEED);
+ final File oldSeedFile = new File(new File(indexPrimaryRoot.getParentFile(), "YACYDB"), "mySeed.txt");
if (oldSeedFile.exists()) oldSeedFile.renameTo(mySeedFile);
seedDB = new yacySeedDB(
new File(networkRoot, "seed.new.db"),
@@ -205,7 +205,7 @@ public final class plasmaWordIndex implements indexRI {
collections.clear();
try {
referenceURL.clear();
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
queuePreStack.clear();
@@ -218,7 +218,7 @@ public final class plasmaWordIndex implements indexRI {
this.defaultTextSnippetGlobalProfile = null;
this.defaultMediaSnippetLocalProfile = null;
this.defaultMediaSnippetGlobalProfile = null;
- Iterator<CrawlProfile.entry> i = this.profilesActiveCrawls.profiles(true);
+ final Iterator<CrawlProfile.entry> i = this.profilesActiveCrawls.profiles(true);
CrawlProfile.entry profile;
String name;
try {
@@ -232,7 +232,7 @@ public final class plasmaWordIndex implements indexRI {
if (name.equals(CRAWL_PROFILE_SNIPPET_LOCAL_MEDIA)) this.defaultMediaSnippetLocalProfile = profile;
if (name.equals(CRAWL_PROFILE_SNIPPET_GLOBAL_MEDIA)) this.defaultMediaSnippetGlobalProfile = profile;
}
- } catch (Exception e) {
+ } catch (final Exception e) {
this.profilesActiveCrawls.clear();
this.defaultProxyProfile = null;
this.defaultRemoteProfile = null;
@@ -281,7 +281,7 @@ public final class plasmaWordIndex implements indexRI {
}
private void resetProfiles() {
- File pdb = new File(this.queuesRoot, DBFILE_ACTIVE_CRAWL_PROFILES);
+ final File pdb = new File(this.queuesRoot, DBFILE_ACTIVE_CRAWL_PROFILES);
if (pdb.exists()) pdb.delete();
profilesActiveCrawls = new CrawlProfile(pdb);
initActiveCrawlProfiles();
@@ -311,30 +311,30 @@ public final class plasmaWordIndex implements indexRI {
hasDoneSomething = true;
}
}
- } catch (kelondroException e) {
+ } catch (final kelondroException e) {
resetProfiles();
hasDoneSomething = true;
}
return hasDoneSomething;
}
- public File getLocation(boolean primary) {
+ public File getLocation(final boolean primary) {
return (primary) ? this.primaryRoot : this.secondaryRoot;
}
- public void putURL(indexURLReference entry) throws IOException {
+ public void putURL(final indexURLReference entry) throws IOException {
this.referenceURL.store(entry);
}
- public indexURLReference getURL(String urlHash, indexRWIEntry searchedWord, long ranking) {
+ public indexURLReference getURL(final String urlHash, final indexRWIEntry searchedWord, final long ranking) {
return this.referenceURL.load(urlHash, searchedWord, ranking);
}
- public boolean removeURL(String urlHash) {
+ public boolean removeURL(final String urlHash) {
return this.referenceURL.remove(urlHash);
}
- public boolean existsURL(String urlHash) {
+ public boolean existsURL(final String urlHash) {
return this.referenceURL.exists(urlHash);
}
@@ -342,7 +342,7 @@ public final class plasmaWordIndex implements indexRI {
return this.referenceURL.size();
}
- public Export exportURL(File f, String filter, int format, boolean dom) {
+ public Export exportURL(final File f, final String filter, final int format, final boolean dom) {
return this.referenceURL.export(f, filter, format, dom);
}
@@ -350,11 +350,11 @@ public final class plasmaWordIndex implements indexRI {
return this.referenceURL.export();
}
- public kelondroCloneableIterator<indexURLReference> entriesURL(boolean up, String firstHash) throws IOException {
+ public kelondroCloneableIterator<indexURLReference> entriesURL(final boolean up, final String firstHash) throws IOException {
return this.referenceURL.entries(up, firstHash);
}
- public indexRepositoryReference.BlacklistCleaner getURLCleaner(indexReferenceBlacklist blacklist) {
+ public indexRepositoryReference.BlacklistCleaner getURLCleaner(final indexReferenceBlacklist blacklist) {
return this.referenceURL.getBlacklistCleaner(blacklist); // thread is not already started after this is called!
}
@@ -398,24 +398,24 @@ public final class plasmaWordIndex implements indexRI {
return dhtInCache.size();
}
- public long dhtCacheSizeBytes(boolean in) {
+ public long dhtCacheSizeBytes(final boolean in) {
// calculate the real size in bytes of DHT-In/Out-Cache
long cacheBytes = 0;
- long entryBytes = indexRWIRowEntry.urlEntryRow.objectsize;
- indexRAMRI cache = (in ? dhtInCache : dhtOutCache);
+ final long entryBytes = indexRWIRowEntry.urlEntryRow.objectsize;
+ final indexRAMRI cache = (in ? dhtInCache : dhtOutCache);
synchronized (cache) {
- Iterator<indexContainer> it = cache.wordContainers(null, false);
+ final Iterator<indexContainer> it = cache.wordContainers(null, false);
while (it.hasNext()) cacheBytes += it.next().size() * entryBytes;
}
return cacheBytes;
}
- public void setMaxWordCount(int maxWords) {
+ public void setMaxWordCount(final int maxWords) {
dhtOutCache.setMaxWordCount(maxWords);
dhtInCache.setMaxWordCount(maxWords);
}
- public void dhtFlushControl(indexRAMRI theCache) {
+ public void dhtFlushControl(final indexRAMRI theCache) {
// check for forced flush
int l = 0;
// flush elements that are too big. This flushing depends on the fact that the flush rule
@@ -431,17 +431,17 @@ public final class plasmaWordIndex implements indexRI {
}
}
- public long getUpdateTime(String wordHash) {
- indexContainer entries = getContainer(wordHash, null);
+ public long getUpdateTime(final String wordHash) {
+ final indexContainer entries = getContainer(wordHash, null);
if (entries == null) return 0;
return entries.updated();
}
- public static indexContainer emptyContainer(String wordHash, int elementCount) {
+ public static indexContainer emptyContainer(final String wordHash, final int elementCount) {
return new indexContainer(wordHash, indexRWIRowEntry.urlEntryRow, elementCount);
}
- public void addEntry(String wordHash, indexRWIRowEntry entry, long updateTime, boolean dhtInCase) {
+ public void addEntry(final String wordHash, final indexRWIRowEntry entry, final long updateTime, boolean dhtInCase) {
// set dhtInCase depending on wordHash
if ((!dhtInCase) && (yacyDHTAction.shallBeOwnWord(seedDB, wordHash))) dhtInCase = true;
@@ -455,11 +455,11 @@ public final class plasmaWordIndex implements indexRI {
}
}
- public void addEntries(indexContainer entries) {
+ public void addEntries(final indexContainer entries) {
addEntries(entries, false);
}
- public void addEntries(indexContainer entries, boolean dhtInCase) {
+ public void addEntries(final indexContainer entries, boolean dhtInCase) {
assert (entries.row().objectsize == indexRWIRowEntry.urlEntryRow.objectsize);
// set dhtInCase depending on wordHash
@@ -476,16 +476,16 @@ public final class plasmaWordIndex implements indexRI {
}
public int flushCacheSome() {
- int fo = flushCache(dhtOutCache, Math.max(1, dhtOutCache.size() / lowcachedivisor));
- int fi = flushCache(dhtInCache, Math.max(1, dhtInCache.size() / lowcachedivisor));
+ final int fo = flushCache(dhtOutCache, Math.max(1, dhtOutCache.size() / lowcachedivisor));
+ final int fi = flushCache(dhtInCache, Math.max(1, dhtInCache.size() / lowcachedivisor));
return fo + fi;
}
- private int flushCache(indexRAMRI ram, int count) {
+ private int flushCache(final indexRAMRI ram, int count) {
if (count <= 0) return 0;
String wordHash;
- ArrayList<indexContainer> containerList = new ArrayList<indexContainer>();
+ final ArrayList<indexContainer> containerList = new ArrayList<indexContainer>();
count = Math.min(5000, Math.min(count, ram.size()));
boolean collectMax = true;
indexContainer c;
@@ -505,22 +505,22 @@ public final class plasmaWordIndex implements indexRI {
containerList.addAll(ram.bestFlushContainers(count));
// flush the containers
- for (indexContainer container : containerList) collections.addEntries(container);
+ for (final indexContainer container : containerList) collections.addEntries(container);
//System.out.println("DEBUG-Finished flush of " + count + " entries from RAM to DB in " + (System.currentTimeMillis() - start) + " milliseconds");
return containerList.size();
}
- public int addPageIndex(yacyURL url, Date urlModified, int size, plasmaParserDocument document, plasmaCondenser condenser, String language, char doctype, int outlinksSame, int outlinksOther) {
+ public int addPageIndex(final yacyURL url, final Date urlModified, final int size, final plasmaParserDocument document, final plasmaCondenser condenser, final String language, final char doctype, final int outlinksSame, final int outlinksOther) {
// this is called by the switchboard to put in a new page into the index
// use all the words in one condenser object to simultanous create index entries
int wordCount = 0;
- int urlLength = url.toNormalform(true, true).length();
- int urlComps = htmlFilterContentScraper.urlComps(url.toString()).length;
+ final int urlLength = url.toNormalform(true, true).length();
+ final int urlComps = htmlFilterContentScraper.urlComps(url.toString()).length;
// iterate over all words of context text
- Iterator<Map.Entry<String, indexWord>> i = condenser.words().entrySet().iterator();
+ final Iterator<Map.Entry<String, indexWord>> i = condenser.words().entrySet().iterator();
Map.Entry<String, indexWord> wentry;
String word;
indexRWIRowEntry ientry;
@@ -551,14 +551,14 @@ public final class plasmaWordIndex implements indexRI {
return wordCount;
}
- public boolean hasContainer(String wordHash) {
+ public boolean hasContainer(final String wordHash) {
if (dhtOutCache.hasContainer(wordHash)) return true;
if (dhtInCache.hasContainer(wordHash)) return true;
if (collections.hasContainer(wordHash)) return true;
return false;
}
- public indexContainer getContainer(String wordHash, Set<String> urlselection) {
+ public indexContainer getContainer(final String wordHash, final Set<String> urlselection) {
if ((wordHash == null) || (wordHash.length() != yacySeedDB.commonHashLength)) {
// wrong input
return null;
@@ -583,8 +583,8 @@ public final class plasmaWordIndex implements indexRI {
if (container == null) return null;
// check doubles
- int beforeDouble = container.size();
- ArrayList<kelondroRowCollection> d = container.removeDoubles();
+ final int beforeDouble = container.size();
+ final ArrayList<kelondroRowCollection> d = container.removeDoubles();
kelondroRowCollection set;
for (int i = 0; i < d.size(); i++) {
// for each element in the double-set, take that one that is the most recent one
@@ -607,14 +607,14 @@ public final class plasmaWordIndex implements indexRI {
return container;
}
- public HashMap<String, indexContainer> getContainers(Set<String> wordHashes, Set<String> urlselection, boolean deleteIfEmpty, boolean interruptIfEmpty) {
+ public HashMap<String, indexContainer> getContainers(final Set<String> wordHashes, final Set<String> urlselection, final boolean deleteIfEmpty, final boolean interruptIfEmpty) {
// return map of wordhash:indexContainer
// retrieve entities that belong to the hashes
- HashMap<String, indexContainer> containers = new HashMap<String, indexContainer>(wordHashes.size());
+ final HashMap<String, indexContainer> containers = new HashMap<String, indexContainer>(wordHashes.size());
String singleHash;
indexContainer singleContainer;
- Iterator<String> i = wordHashes.iterator();
+ final Iterator<String> i = wordHashes.iterator();
while (i.hasNext()) {
// get next word hash:
@@ -632,7 +632,7 @@ public final class plasmaWordIndex implements indexRI {
}
@SuppressWarnings("unchecked")
- public HashMap<String, indexContainer>[] localSearchContainers(plasmaSearchQuery query, Set<String> urlselection) {
+ public HashMap<String, indexContainer>[] localSearchContainers(final plasmaSearchQuery query, final Set<String> urlselection) {
// search for the set of hashes and return a map of of wordhash:indexContainer containing the seach result
// retrieve entities that belong to the hashes
@@ -642,7 +642,7 @@ public final class plasmaWordIndex implements indexRI {
true,
true);
if ((inclusionContainers.size() != 0) && (inclusionContainers.size() < query.queryHashes.size())) inclusionContainers = new HashMap<String, indexContainer>(0); // prevent that only a subset is returned
- HashMap<String, indexContainer> exclusionContainers = (inclusionContainers.size() == 0) ? new HashMap<String, indexContainer>(0) : getContainers(
+ final HashMap<String, indexContainer> exclusionContainers = (inclusionContainers.size() == 0) ? new HashMap<String, indexContainer>(0) : getContainers(
query.excludeHashes,
urlselection,
true,
@@ -662,7 +662,7 @@ public final class plasmaWordIndex implements indexRI {
return dhtInCache.size() + dhtOutCache.size();
}
- public int indexSize(String wordHash) {
+ public int indexSize(final String wordHash) {
int size = 0;
size += dhtInCache.indexSize(wordHash);
size += dhtOutCache.indexSize(wordHash);
@@ -682,8 +682,8 @@ public final class plasmaWordIndex implements indexRI {
peerActions.close();
}
- public indexContainer deleteContainer(String wordHash) {
- indexContainer c = new indexContainer(
+ public indexContainer deleteContainer(final String wordHash) {
+ final indexContainer c = new indexContainer(
wordHash,
indexRWIRowEntry.urlEntryRow,
dhtInCache.sizeContainer(wordHash) + dhtOutCache.sizeContainer(wordHash) + collections.indexSize(wordHash)
@@ -694,7 +694,7 @@ public final class plasmaWordIndex implements indexRI {
return c;
}
- public boolean removeEntry(String wordHash, String urlHash) {
+ public boolean removeEntry(final String wordHash, final String urlHash) {
boolean removed = false;
removed = removed | (dhtInCache.removeEntry(wordHash, urlHash));
removed = removed | (dhtOutCache.removeEntry(wordHash, urlHash));
@@ -702,10 +702,10 @@ public final class plasmaWordIndex implements indexRI {
return removed;
}
- public int removeEntryMultiple(Set<String> wordHashes, String urlHash) {
+ public int removeEntryMultiple(final Set<String> wordHashes, final String urlHash) {
// remove the same url hashes for multiple words
// this is mainly used when correcting a index after a search
- Iterator<String> i = wordHashes.iterator();
+ final Iterator<String> i = wordHashes.iterator();
int count = 0;
while (i.hasNext()) {
if (removeEntry(i.next(), urlHash)) count++;
@@ -713,7 +713,7 @@ public final class plasmaWordIndex implements indexRI {
return count;
}
- public int removeEntries(String wordHash, Set<String> urlHashes) {
+ public int removeEntries(final String wordHash, final Set<String> urlHashes) {
int removed = 0;
removed += dhtInCache.removeEntries(wordHash, urlHashes);
removed += dhtOutCache.removeEntries(wordHash, urlHashes);
@@ -721,7 +721,7 @@ public final class plasmaWordIndex implements indexRI {
return removed;
}
- public String removeEntriesExpl(String wordHash, Set<String> urlHashes) {
+ public String removeEntriesExpl(final String wordHash, final Set<String> urlHashes) {
String removed = "";
removed += dhtInCache.removeEntries(wordHash, urlHashes) + ", ";
removed += dhtOutCache.removeEntries(wordHash, urlHashes) + ", ";
@@ -729,19 +729,19 @@ public final class plasmaWordIndex implements indexRI {
return removed;
}
- public void removeEntriesMultiple(Set<String> wordHashes, Set<String> urlHashes) {
+ public void removeEntriesMultiple(final Set<String> wordHashes, final Set<String> urlHashes) {
// remove the same url hashes for multiple words
// this is mainly used when correcting a index after a search
- Iterator<String> i = wordHashes.iterator();
+ final Iterator<String> i = wordHashes.iterator();
while (i.hasNext()) {
removeEntries(i.next(), urlHashes);
}
}
- public int removeWordReferences(Set<String> words, String urlhash) {
+ public int removeWordReferences(final Set<String> words, final String urlhash) {
// sequentially delete all word references
// returns number of deletions
- Iterator<String> iter = words.iterator();
+ final Iterator<String> iter = words.iterator();
int count = 0;
while (iter.hasNext()) {
// delete the URL reference in this word index
@@ -750,13 +750,13 @@ public final class plasmaWordIndex implements indexRI {
return count;
}
- public synchronized TreeSet<indexContainer> indexContainerSet(String startHash, boolean ram, boolean rot, int count) {
+ public synchronized TreeSet<indexContainer> indexContainerSet(final String startHash, final boolean ram, final boolean rot, int count) {
// creates a set of indexContainers
// this does not use the dhtInCache
- kelondroOrder<indexContainer> containerOrder = new indexContainerOrder(indexOrder.clone());
+ final kelondroOrder<indexContainer> containerOrder = new indexContainerOrder(indexOrder.clone());
containerOrder.rotate(emptyContainer(startHash, 0));
- TreeSet<indexContainer> containers = new TreeSet<indexContainer>(containerOrder);
- Iterator<indexContainer> i = wordContainers(startHash, ram, rot);
+ final TreeSet<indexContainer> containers = new TreeSet<indexContainer>(containerOrder);
+ final Iterator<indexContainer> i = wordContainers(startHash, ram, rot);
if (ram) count = Math.min(dhtOutCache.size(), count);
indexContainer container;
// this loop does not terminate using the i.hasNex() predicate when rot == true
@@ -773,17 +773,17 @@ public final class plasmaWordIndex implements indexRI {
return containers; // this may return less containers as demanded
}
- public indexURLReference storeDocument(IndexingStack.QueueEntry entry, plasmaParserDocument document, plasmaCondenser condenser) throws IOException {
- long startTime = System.currentTimeMillis();
+ public indexURLReference storeDocument(final IndexingStack.QueueEntry entry, final plasmaParserDocument document, final plasmaCondenser condenser) throws IOException {
+ final long startTime = System.currentTimeMillis();
// CREATE INDEX
- String dc_title = document.dc_title();
- yacyURL referrerURL = entry.referrerURL();
- Date docDate = entry.getModificationDate();
+ final String dc_title = document.dc_title();
+ final yacyURL referrerURL = entry.referrerURL();
+ final Date docDate = entry.getModificationDate();
// create a new loaded URL db entry
- long ldate = System.currentTimeMillis();
- indexURLReference newEntry = new indexURLReference(
+ final long ldate = System.currentTimeMillis();
+ final indexURLReference newEntry = new indexURLReference(
entry.url(), // URL
dc_title, // document description
document.dc_creator(), // author
@@ -810,10 +810,10 @@ public final class plasmaWordIndex implements indexRI {
// STORE URL TO LOADED-URL-DB
putURL(newEntry);
- long storageEndTime = System.currentTimeMillis();
+ final long storageEndTime = System.currentTimeMillis();
// STORE PAGE INDEX INTO WORD INDEX DB
- int words = addPageIndex(
+ final int words = addPageIndex(
entry.url(), // document url
docDate, // document mod date
(int) entry.size(), // document size
@@ -825,7 +825,7 @@ public final class plasmaWordIndex implements indexRI {
document.outboundLinks() // outbound links
);
- long indexingEndTime = System.currentTimeMillis();
+ final long indexingEndTime = System.currentTimeMillis();
if (log.isInfo()) {
// TODO: UTF-8 docDescription seems not to be displayed correctly because
@@ -845,8 +845,8 @@ public final class plasmaWordIndex implements indexRI {
return newEntry;
}
- public synchronized kelondroCloneableIterator<indexContainer> wordContainers(String startHash, boolean ram, boolean rot) {
- kelondroCloneableIterator<indexContainer> i = wordContainers(startHash, ram);
+ public synchronized kelondroCloneableIterator<indexContainer> wordContainers(final String startHash, final boolean ram, final boolean rot) {
+ final kelondroCloneableIterator<indexContainer> i = wordContainers(startHash, ram);
if (rot) {
return new kelondroRotateIterator<indexContainer>(i, new String(kelondroBase64Order.zero(startHash.length())), dhtOutCache.size() + ((ram) ? 0 : collections.size()));
} else {
@@ -854,8 +854,8 @@ public final class plasmaWordIndex implements indexRI {
}
}
- public synchronized kelondroCloneableIterator<indexContainer> wordContainers(String startWordHash, boolean ram) {
- kelondroOrder<indexContainer> containerOrder = new indexContainerOrder(indexOrder.clone());
+ public synchronized kelondroCloneableIterator<indexContainer> wordContainers(final String startWordHash, final boolean ram) {
+ final kelondroOrder<indexContainer> containerOrder = new indexContainerOrder(indexOrder.clone());
containerOrder.rotate(emptyContainer(startWordHash, 0));
if (ram) {
return dhtOutCache.wordContainers(startWordHash, false);
@@ -871,13 +871,13 @@ public final class plasmaWordIndex implements indexRI {
// The Cleaner class was provided as "UrldbCleaner" by Hydrox
- public synchronized ReferenceCleaner getReferenceCleaner(String startHash) {
+ public synchronized ReferenceCleaner getReferenceCleaner(final String startHash) {
return new ReferenceCleaner(startHash);
}
public class ReferenceCleaner extends Thread {
- private String startHash;
+ private final String startHash;
private boolean run = true;
private boolean pause = false;
public int rwiCountAtStart = 0;
@@ -885,7 +885,7 @@ public final class plasmaWordIndex implements indexRI {
public String lastWordHash = "";
public int lastDeletionCounter = 0;
- public ReferenceCleaner(String startHash) {
+ public ReferenceCleaner(final String startHash) {
this.startHash = startHash;
this.rwiCountAtStart = size();
}
@@ -895,19 +895,19 @@ public final class plasmaWordIndex implements indexRI {
indexContainer container = null;
indexRWIRowEntry entry = null;
yacyURL url = null;
- HashSet<String> urlHashs = new HashSet<String>();
+ final HashSet<String> urlHashs = new HashSet<String>();
Iterator<indexContainer> indexContainerIterator = indexContainerSet(startHash, false, false, 100).iterator();
while (indexContainerIterator.hasNext() && run) {
waiter();
container = indexContainerIterator.next();
- Iterator<indexRWIRowEntry> containerIterator = container.entries();
+ final Iterator<indexRWIRowEntry> containerIterator = container.entries();
wordHashNow = container.getWordHash();
while (containerIterator.hasNext() && run) {
waiter();
entry = containerIterator.next();
// System.out.println("Wordhash: "+wordHash+" UrlHash:
// "+entry.getUrlHash());
- indexURLReference ue = referenceURL.load(entry.urlHash(), entry, 0);
+ final indexURLReference ue = referenceURL.load(entry.urlHash(), entry, 0);
if (ue == null) {
urlHashs.add(entry.urlHash());
} else {
@@ -918,7 +918,7 @@ public final class plasmaWordIndex implements indexRI {
}
}
if (urlHashs.size() > 0) {
- int removed = removeEntries(container.getWordHash(), urlHashs);
+ final int removed = removeEntries(container.getWordHash(), urlHashs);
serverLog.logFine("INDEXCLEANER", container.getWordHash() + ": " + removed + " of " + container.size() + " URL-entries deleted");
lastWordHash = container.getWordHash();
lastDeletionCounter = urlHashs.size();
@@ -926,7 +926,7 @@ public final class plasmaWordIndex implements indexRI {
}
if (!containerIterator.hasNext()) {
// We may not be finished yet, try to get the next chunk of wordHashes
- TreeSet<indexContainer> containers = indexContainerSet(container.getWordHash(), false, false, 100);
+ final TreeSet<indexContainer> containers = indexContainerSet(container.getWordHash(), false, false, 100);
indexContainerIterator = containers.iterator();
// Make sure we don't get the same wordhash twice, but don't skip a word
if ((indexContainerIterator.hasNext()) && (!container.getWordHash().equals(indexContainerIterator.next().getWordHash()))) {
@@ -968,7 +968,7 @@ public final class plasmaWordIndex implements indexRI {
if (this.pause) {
try {
this.wait();
- } catch (InterruptedException e) {
+ } catch (final InterruptedException e) {
this.run = false;
return;
}
diff --git a/source/de/anomic/server/logging/ConsoleOutErrHandler.java b/source/de/anomic/server/logging/ConsoleOutErrHandler.java
index f2ad35198..d799f16d0 100644
--- a/source/de/anomic/server/logging/ConsoleOutErrHandler.java
+++ b/source/de/anomic/server/logging/ConsoleOutErrHandler.java
@@ -52,52 +52,52 @@ public final class ConsoleOutErrHandler extends Handler{
* Get any configuration properties set
*/
private void configure() {
- LogManager manager = LogManager.getLogManager();
- String className = getClass().getName();
+ final LogManager manager = LogManager.getLogManager();
+ final String className = getClass().getName();
- String level = manager.getProperty(className + ".level");
+ final String level = manager.getProperty(className + ".level");
setLevel((level == null) ? Level.INFO : Level.parse(level));
- Level levelStdOut = parseLevel(manager.getProperty(className + ".levelStdOut"));
- Level levelSplit = parseLevel(manager.getProperty(className + ".levelSplit"));
- Level levelStdErr = parseLevel(manager.getProperty(className + ".levelStdErr"));
+ final Level levelStdOut = parseLevel(manager.getProperty(className + ".levelStdOut"));
+ final Level levelSplit = parseLevel(manager.getProperty(className + ".levelSplit"));
+ final Level levelStdErr = parseLevel(manager.getProperty(className + ".levelStdErr"));
setLevels(levelStdOut,levelSplit,levelStdErr);
- String filter = manager.getProperty(className + ".filter");
+ final String filter = manager.getProperty(className + ".filter");
setFilter(makeFilter(filter));
- String formatter = manager.getProperty(className + ".formatter");
+ final String formatter = manager.getProperty(className + ".formatter");
setFormatter(makeFormatter(formatter));
- String encoding = manager.getProperty(className + ".encoding");
+ final String encoding = manager.getProperty(className + ".encoding");
try {
this.stdOutHandler.setEncoding(encoding);
this.stdErrHandler.setEncoding(encoding);
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
e.printStackTrace();
}
- String ignoreCtrlChrStr = manager.getProperty(className + ".ignoreCtrlChr");
+ final String ignoreCtrlChrStr = manager.getProperty(className + ".ignoreCtrlChr");
this.ignoreCtrlChr = (ignoreCtrlChrStr==null)?false:ignoreCtrlChrStr.equalsIgnoreCase("true");
}
- private Level parseLevel(String levelName) {
+ private Level parseLevel(final String levelName) {
try {
return (levelName == null) ? Level.INFO : Level.parse(levelName);
- } catch (Exception e) {
+ } catch (final Exception e) {
return Level.ALL;
}
}
- private Filter makeFilter(String name) {
+ private Filter makeFilter(final String name) {
if (name == null) return null;
Filter f = null;
try {
- Class<?> c = Class.forName(name);
+ final Class<?> c = Class.forName(name);
f = (Filter)c.newInstance();
- } catch (Exception e) {
+ } catch (final Exception e) {
if (name != null) {
System.err.println("Unable to load filter: " + name);
}
@@ -105,21 +105,21 @@ public final class ConsoleOutErrHandler extends Handler{
return f;
}
- private Formatter makeFormatter(String name) {
+ private Formatter makeFormatter(final String name) {
if (name == null) return null;
Formatter f = null;
try {
- Class<?> c = Class.forName(name);
+ final Class<?> c = Class.forName(name);
f = (Formatter)c.newInstance();
- } catch (Exception e) {
+ } catch (final Exception e) {
f = new SimpleFormatter();
}
return f;
}
- public void publish(LogRecord record) {
+ public void publish(final LogRecord record) {
if (!isLoggable(record)) return;
if (this.ignoreCtrlChr) {
@@ -147,34 +147,34 @@ public final class ConsoleOutErrHandler extends Handler{
this.stdErrHandler.close();
}
- public synchronized void setLevel(Level newLevel) throws SecurityException {
+ public synchronized void setLevel(final Level newLevel) throws SecurityException {
super.setLevel(newLevel);
}
- public void setLevels(Level stdOutLevel, Level splitLevel, Level stdErrLevel) throws SecurityException {
+ public void setLevels(final Level stdOutLevel, final Level splitLevel, final Level stdErrLevel) throws SecurityException {
this.stdOutHandler.setLevel(stdOutLevel);
this.splitLevel = splitLevel;
this.stdErrHandler.setLevel(stdErrLevel);
}
- public void setFormatter(Formatter newFormatter) throws SecurityException {
+ public void setFormatter(final Formatter newFormatter) throws SecurityException {
super.setFormatter(newFormatter);
if (newFormatter == null) return;
try {
this.stdOutHandler.setFormatter(newFormatter.getClass().newInstance());
this.stdErrHandler.setFormatter(newFormatter.getClass().newInstance());
- } catch (Exception e) {
+ } catch (final Exception e) {
throw new SecurityException(e.getMessage());
}
}
- public void setFilter(Filter newFilter) throws SecurityException {
+ public void setFilter(final Filter newFilter) throws SecurityException {
super.setFilter(newFilter);
if (newFilter == null) return;
try {
this.stdOutHandler.setFilter(newFilter.getClass().newInstance());
this.stdErrHandler.setFilter(newFilter.getClass().newInstance());
- } catch (Exception e) {
+ } catch (final Exception e) {
throw new SecurityException(e.getMessage());
}
}
diff --git a/source/de/anomic/server/logging/ConsoleOutHandler.java b/source/de/anomic/server/logging/ConsoleOutHandler.java
index 21b136e00..926a55bcc 100644
--- a/source/de/anomic/server/logging/ConsoleOutHandler.java
+++ b/source/de/anomic/server/logging/ConsoleOutHandler.java
@@ -38,7 +38,7 @@ public final class ConsoleOutHandler extends StreamHandler{
setOutputStream(System.out);
}
- public synchronized void publish(LogRecord record) {
+ public synchronized void publish(final LogRecord record) {
super.publish(record);
flush();
}
diff --git a/source/de/anomic/server/logging/GuiHandler.java b/source/de/anomic/server/logging/GuiHandler.java
index e2d54943d..ec00e7fd3 100644
--- a/source/de/anomic/server/logging/GuiHandler.java
+++ b/source/de/anomic/server/logging/GuiHandler.java
@@ -53,53 +53,53 @@ public class GuiHandler extends Handler{
* Get any configuration properties set
*/
private void configure() {
- LogManager manager = LogManager.getLogManager();
- String className = getClass().getName();
+ final LogManager manager = LogManager.getLogManager();
+ final String className = getClass().getName();
- String level = manager.getProperty(className + ".level");
+ final String level = manager.getProperty(className + ".level");
setLevel((level == null) ? Level.INFO : Level.parse(level));
- String filter = manager.getProperty(className + ".filter");
+ final String filter = manager.getProperty(className + ".filter");
setFilter(makeFilter(filter));
- String formatter = manager.getProperty(className + ".formatter");
+ final String formatter = manager.getProperty(className + ".formatter");
setFormatter(makeFormatter(formatter));
- String sizeString = manager.getProperty(className + ".size");
+ final String sizeString = manager.getProperty(className + ".size");
this.size = parseSize(sizeString);
}
- private int parseSize(String sizeString) {
+ private int parseSize(final String sizeString) {
int newSize = DEFAULT_SIZE;
try {
newSize = Integer.parseInt(sizeString);
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
newSize = DEFAULT_SIZE;
}
return newSize;
}
- private Filter makeFilter(String name) {
+ private Filter makeFilter(final String name) {
if (name == null) return null;
Filter f = null;
try {
- Class<?> c = Class.forName(name);
+ final Class<?> c = Class.forName(name);
f = (Filter)c.newInstance();
- } catch (Exception e) {
+ } catch (final Exception e) {
System.err.println("Unable to load filter: " + name);
}
return f;
}
- private Formatter makeFormatter(String name) {
+ private Formatter makeFormatter(final String name) {
if (name == null) return null;
Formatter f = null;
try {
- Class<?> c = Class.forName(name);
+ final Class<?> c = Class.forName(name);
f = (Formatter)c.newInstance();
- } catch (Exception e) {
+ } catch (final Exception e) {
f = new SimpleFormatter();
}
return f;
@@ -116,11 +116,11 @@ public class GuiHandler extends Handler{
return this.size;
}
- public synchronized void publish(LogRecord record) {
+ public synchronized void publish(final LogRecord record) {
if (!isLoggable(record)) return;
// write it to the buffer
- int ix = (this.start+this.count)%this.buffer.length;
+ final int ix = (this.start+this.count)%this.buffer.length;
this.buffer[ix] = record;
if (this.count < this.buffer.length) {
this.count++;
@@ -134,12 +134,12 @@ public class GuiHandler extends Handler{
}
- public synchronized LogRecord[] getLogArray(Long sequenceNumberStart) {
- ArrayList<LogRecord> tempBuffer = new ArrayList<LogRecord>(this.count);
+ public synchronized LogRecord[] getLogArray(final Long sequenceNumberStart) {
+ final ArrayList<LogRecord> tempBuffer = new ArrayList<LogRecord>(this.count);
for (int i = 0; i < this.count; i++) {
- int ix = (this.start+i)%this.buffer.length;
- LogRecord record = this.buffer[ix];
+ final int ix = (this.start+i)%this.buffer.length;
+ final LogRecord record = this.buffer[ix];
if ((sequenceNumberStart == null) || (record.getSequenceNumber() >= sequenceNumberStart.longValue())) {
tempBuffer.add(record);
}
@@ -148,25 +148,25 @@ public class GuiHandler extends Handler{
return tempBuffer.toArray(new LogRecord[tempBuffer.size()]);
}
- public synchronized String getLog(boolean reversed, int lineCount) {
+ public synchronized String getLog(final boolean reversed, int lineCount) {
if ((lineCount > this.count)||(lineCount < 0)) lineCount = this.count;
- StringBuffer logMessages = new StringBuffer(this.count*40);
- Formatter logFormatter = getFormatter();
+ final StringBuffer logMessages = new StringBuffer(this.count*40);
+ final Formatter logFormatter = getFormatter();
try {
- int start = (reversed)?this.start+this.count-1:this.start;
+ final int start = (reversed)?this.start+this.count-1:this.start;
LogRecord record=null;
for (int i = 0; i < lineCount; i++) {
- int ix = (reversed) ?
+ final int ix = (reversed) ?
Math.abs((start-i)%this.buffer.length) :
(start+i)%this.buffer.length;
record = this.buffer[ix];
logMessages.append(logFormatter.format(record));
}
return logMessages.toString();
- } catch (Exception ex) {
+ } catch (final Exception ex) {
// We don't want to throw an exception here, but we
// report the exception to any registered ErrorManager.
reportError(null, ex, ErrorManager.FORMAT_FAILURE);
@@ -174,25 +174,25 @@ public class GuiHandler extends Handler{
}
}
- public synchronized String[] getLogLines(boolean reversed, int lineCount) {
+ public synchronized String[] getLogLines(final boolean reversed, int lineCount) {
if ((lineCount > this.count)||(lineCount < 0)) lineCount = this.count;
- ArrayList<String> logMessages = new ArrayList<String>(this.count);
- Formatter logFormatter = getFormatter();
+ final ArrayList<String> logMessages = new ArrayList<String>(this.count);
+ final Formatter logFormatter = getFormatter();
try {
- int theStart = (reversed)?this.start+this.count-1:this.start+this.count-lineCount;
+ final int theStart = (reversed)?this.start+this.count-1:this.start+this.count-lineCount;
LogRecord record=null;
for (int i = 0; i < lineCount; i++) {
- int ix = (reversed) ?
+ final int ix = (reversed) ?
Math.abs((theStart-i)%this.buffer.length) :
(theStart + i) % this.buffer.length;
record = this.buffer[ix];
logMessages.add(logFormatter.format(record));
}
return logMessages.toArray(new String[logMessages.size()]);
- } catch (Exception ex) {
+ } catch (final Exception ex) {
// We don't want to throw an exception here, but we
// report the exception to any registered ErrorManager.
reportError(null, ex, ErrorManager.FORMAT_FAILURE);
diff --git a/source/de/anomic/server/logging/LogalizerHandler.java b/source/de/anomic/server/logging/LogalizerHandler.java
index d5c850586..a4d175415 100644
--- a/source/de/anomic/server/logging/LogalizerHandler.java
+++ b/source/de/anomic/server/logging/LogalizerHandler.java
@@ -27,16 +27,16 @@ package de.anomic.server.logging;
import java.io.IOException;
import java.net.URISyntaxException;
+import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;
-import java.util.ArrayList;
import java.util.logging.Handler;
import java.util.logging.LogManager;
import java.util.logging.LogRecord;
-import java.util.regex.Pattern;
import java.util.regex.Matcher;
+import java.util.regex.Pattern;
import de.anomic.plasma.plasmaParser;
import de.anomic.server.logging.logParsers.LogParser;
@@ -56,30 +56,30 @@ public class LogalizerHandler extends Handler {
@SuppressWarnings("null")
private HashMap<String, Object> loadParsers() {
- HashMap<String, Object> logParsers = new HashMap<String, Object>();
+ final HashMap<String, Object> logParsers = new HashMap<String, Object>();
try {
if (debug) System.out.println("Searching for additional content parsers in package " + logParserPackage);
// getting an uri to the parser subpackage
- String packageURI = plasmaParser.class.getResource("/"+logParserPackage.replace('.','/')).toString();
+ final String packageURI = plasmaParser.class.getResource("/"+logParserPackage.replace('.','/')).toString();
if (debug) System.out.println("LogParser directory is " + packageURI);
- ListDirs parserDir = new ListDirs(packageURI);
- ArrayList<String> parserDirFiles = parserDir.listFiles(".*\\.class");
+ final ListDirs parserDir = new ListDirs(packageURI);
+ final ArrayList<String> parserDirFiles = parserDir.listFiles(".*\\.class");
if(parserDirFiles.size() == 0 && debug) {
System.out.println("Can't find any parsers in "+parserDir.toString());
}
- for(String filename: parserDirFiles) {
+ for(final String filename: parserDirFiles) {
final Pattern patternGetClassName = Pattern.compile(".*/([^/]+)\\.class");
- Matcher matcherClassName = patternGetClassName.matcher(filename);
+ final Matcher matcherClassName = patternGetClassName.matcher(filename);
matcherClassName.find();
- String className = matcherClassName.group(1);
- Class<?> tempClass = Class.forName(logParserPackage+"."+className);
+ final String className = matcherClassName.group(1);
+ final Class<?> tempClass = Class.forName(logParserPackage+"."+className);
if (tempClass.isInterface()) {
if (debug) System.out.println(tempClass.getName() + " is an Interface");
} else {
- Object theParser = tempClass.newInstance();
+ final Object theParser = tempClass.newInstance();
if (theParser instanceof LogParser) {
- LogParser theLogParser = (LogParser) theParser;
+ final LogParser theLogParser = (LogParser) theParser;
//System.out.println(bla.getName() + " is a logParser");
logParsers.put(theLogParser.getParserType(), theParser);
@@ -92,15 +92,15 @@ public class LogalizerHandler extends Handler {
}
}
}
- } catch (ClassNotFoundException e) {
+ } catch (final ClassNotFoundException e) {
e.printStackTrace();
- } catch (InstantiationException e) {
+ } catch (final InstantiationException e) {
e.printStackTrace();
- } catch (IllegalAccessException e) {
+ } catch (final IllegalAccessException e) {
e.printStackTrace();
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
- } catch (URISyntaxException e) {
+ } catch (final URISyntaxException e) {
e.printStackTrace();
}
return logParsers;
@@ -110,8 +110,8 @@ public class LogalizerHandler extends Handler {
* Get any configuration properties set
*/
private void configure() {
- LogManager manager = LogManager.getLogManager();
- String className = getClass().getName();
+ final LogManager manager = LogManager.getLogManager();
+ final String className = getClass().getName();
if(manager.getProperty(className + ".enabled").equalsIgnoreCase("true")) enabled = true;
if(manager.getProperty(className + ".debug").equalsIgnoreCase("true")) debug = true;
@@ -121,11 +121,11 @@ public class LogalizerHandler extends Handler {
parsers = loadParsers();
}
- public void publish(LogRecord record) {
+ public void publish(final LogRecord record) {
if (enabled) {
- LogParser temp = (LogParser) parsers.get(record.getLoggerName());
+ final LogParser temp = (LogParser) parsers.get(record.getLoggerName());
if (temp != null) {
- int returnV = temp.parse(record.getLevel().toString(), record.getMessage());
+ final int returnV = temp.parse(record.getLevel().toString(), record.getMessage());
//if (debug) System.out.println("Logalizertest: " + returnV + " --- " + record.getLevel() + " --- " + record.getMessage());
if (debug) System.out.println("Logalizertest: " + returnV + " --- " + record.getLevel());
}
@@ -136,9 +136,9 @@ public class LogalizerHandler extends Handler {
return parsers.keySet();
}
- public LogParser getParser(int number) {
+ public LogParser getParser(final int number) {
String o;
- Iterator<String> it = parsers.keySet().iterator();
+ final Iterator<String> it = parsers.keySet().iterator();
int i = 0;
while (it.hasNext()) {
o = it.next();
@@ -148,7 +148,7 @@ public class LogalizerHandler extends Handler {
return null;
}
- public Hashtable<String, Object> getParserResults(LogParser parsername) {
+ public Hashtable<String, Object> getParserResults(final LogParser parsername) {
return parsername.getResults();
}
diff --git a/source/de/anomic/server/logging/logParsers/LogParserPLASMA.java b/source/de/anomic/server/logging/logParsers/LogParserPLASMA.java
index cdd203663..511ccb239 100644
--- a/source/de/anomic/server/logging/logParsers/LogParserPLASMA.java
+++ b/source/de/anomic/server/logging/logParsers/LogParserPLASMA.java
@@ -208,10 +208,10 @@ public class LogParserPLASMA implements LogParser{
private long DHTSendTraffic=0;
private int DHTSendURLs=0;
private int RWIRejectCount=0;
- private HashSet<String> RWIRejectPeerNames = new HashSet<String>();
- private HashSet<String> RWIRejectPeerHashs = new HashSet<String>();
- private HashSet<String> DHTPeerNames = new HashSet<String>();
- private HashSet<String> DHTPeerHashs = new HashSet<String>();
+ private final HashSet<String> RWIRejectPeerNames = new HashSet<String>();
+ private final HashSet<String> RWIRejectPeerHashs = new HashSet<String>();
+ private final HashSet<String> DHTPeerNames = new HashSet<String>();
+ private final HashSet<String> DHTPeerHashs = new HashSet<String>();
private int DHTSelectionTargetCount = 0;
private int DHTSelectionWordsCount = 0;
private int DHTSelectionWordsTimeCount = 0;
@@ -240,8 +240,8 @@ public class LogParserPLASMA implements LogParser{
private long totalParserTime = 0;
private int totalParserRuns = 0;
- public int parse(String logLevel, String logLine) {
- long start = System.currentTimeMillis();
+ public int parse(final String logLevel, final String logLine) {
+ final long start = System.currentTimeMillis();
if (logLevel.equals("INFO")){
m = i1.matcher (logLine);
@@ -433,7 +433,7 @@ public class LogParserPLASMA implements LogParser{
}
public Hashtable<String, Object> getResults() {
- Hashtable<String, Object> results = new Hashtable<String, Object>();
+ final Hashtable<String, Object> results = new Hashtable<String, Object>();
results.put(PARSER_VERSION , new Double(parserVersion));
results.put(URLS_RECEIVED , new Integer(urlSum));
results.put(URLS_REQUESTED , new Integer(urlReqSum));
diff --git a/source/de/anomic/server/logging/serverLog.java b/source/de/anomic/server/logging/serverLog.java
index a441cf0cd..6017fade6 100644
--- a/source/de/anomic/server/logging/serverLog.java
+++ b/source/de/anomic/server/logging/serverLog.java
@@ -54,131 +54,131 @@ public final class serverLog {
private final Logger theLogger;
- public serverLog(String appName) {
+ public serverLog(final String appName) {
this.theLogger = Logger.getLogger(appName);
//this.theLogger.setLevel(Level.FINEST); // set a default level
}
- public void setLevel(Level newLevel) {
+ public void setLevel(final Level newLevel) {
this.theLogger.setLevel(newLevel);
}
- public void logSevere(String message) {this.theLogger.severe(message);}
- public void logSevere(String message, Throwable thrown) {this.theLogger.log(Level.SEVERE,message,thrown);}
+ public void logSevere(final String message) {this.theLogger.severe(message);}
+ public void logSevere(final String message, final Throwable thrown) {this.theLogger.log(Level.SEVERE,message,thrown);}
public boolean isSevere() { return this.theLogger.isLoggable(Level.SEVERE); }
- public void logWarning(String message) {this.theLogger.warning(message);}
- public void logWarning(String message, Throwable thrown) {this.theLogger.log(Level.WARNING,message,thrown);}
+ public void logWarning(final String message) {this.theLogger.warning(message);}
+ public void logWarning(final String message, final Throwable thrown) {this.theLogger.log(Level.WARNING,message,thrown);}
public boolean isWarning() { return this.theLogger.isLoggable(Level.WARNING); }
- public void logConfig(String message) {this.theLogger.config(message);}
- public void logConfig(String message, Throwable thrown) {this.theLogger.log(Level.CONFIG,message,thrown);}
+ public void logConfig(final String message) {this.theLogger.config(message);}
+ public void logConfig(final String message, final Throwable thrown) {this.theLogger.log(Level.CONFIG,message,thrown);}
public boolean isConfig() { return this.theLogger.isLoggable(Level.CONFIG); }
- public void logInfo(String message) {this.theLogger.info(message);}
- public void logInfo(String message, Throwable thrown) {this.theLogger.log(Level.INFO,message,thrown);}
+ public void logInfo(final String message) {this.theLogger.info(message);}
+ public void logInfo(final String message, final Throwable thrown) {this.theLogger.log(Level.INFO,message,thrown);}
public boolean isInfo() { return this.theLogger.isLoggable(Level.INFO); }
- public void logFine(String message) {this.theLogger.fine(message);}
- public void logFine(String message, Throwable thrown) {this.theLogger.log(Level.FINE,message,thrown);}
+ public void logFine(final String message) {this.theLogger.fine(message);}
+ public void logFine(final String message, final Throwable thrown) {this.theLogger.log(Level.FINE,message,thrown);}
public boolean isFine() { return this.theLogger.isLoggable(Level.FINE); }
- public void logFiner(String message) {this.theLogger.finer(message);}
- public void logFiner(String message, Throwable thrown) {this.theLogger.log(Level.FINER,message,thrown);}
+ public void logFiner(final String message) {this.theLogger.finer(message);}
+ public void logFiner(final String message, final Throwable thrown) {this.theLogger.log(Level.FINER,message,thrown);}
public boolean isFiner() { return this.theLogger.isLoggable(Level.FINER); }
- public void logFinest(String message) {this.theLogger.finest(message);}
- public void logFinest(String message, Throwable thrown) {this.theLogger.log(Level.FINEST,message,thrown);}
+ public void logFinest(final String message) {this.theLogger.finest(message);}
+ public void logFinest(final String message, final Throwable thrown) {this.theLogger.log(Level.FINEST,message,thrown);}
public boolean isFinest() { return this.theLogger.isLoggable(Level.FINEST); }
- public boolean isLoggable(Level level) {
+ public boolean isLoggable(final Level level) {
return this.theLogger.isLoggable(level);
}
// static log messages: log everything
- public static void logSevere(String appName, String message) {
+ public static void logSevere(final String appName, final String message) {
Logger.getLogger(appName).severe(message);
}
- public static void logSevere(String appName, String message, Throwable thrown) {
+ public static void logSevere(final String appName, final String message, final Throwable thrown) {
Logger.getLogger(appName).log(Level.SEVERE,message,thrown);
}
- public static void isSevere(String appName) {
+ public static void isSevere(final String appName) {
Logger.getLogger(appName).isLoggable(Level.SEVERE);
}
- public static void logWarning(String appName, String message) {
+ public static void logWarning(final String appName, final String message) {
Logger.getLogger(appName).warning(message);
}
- public static void logWarning(String appName, String message, Throwable thrown) {
+ public static void logWarning(final String appName, final String message, final Throwable thrown) {
Logger.getLogger(appName).log(Level.WARNING,message,thrown);
}
- public static void isWarning(String appName) {
+ public static void isWarning(final String appName) {
Logger.getLogger(appName).isLoggable(Level.WARNING);
}
- public static void logConfig(String appName, String message) {
+ public static void logConfig(final String appName, final String message) {
Logger.getLogger(appName).config(message);
}
- public static void logConfig(String appName, String message, Throwable thrown) {
+ public static void logConfig(final String appName, final String message, final Throwable thrown) {
Logger.getLogger(appName).log(Level.CONFIG,message,thrown);
}
- public static void isConfig(String appName) {
+ public static void isConfig(final String appName) {
Logger.getLogger(appName).isLoggable(Level.CONFIG);
}
- public static void logInfo(String appName, String message) {
+ public static void logInfo(final String appName, final String message) {
Logger.getLogger(appName).info(message);
}
- public static void logInfo(String appName, String message, Throwable thrown) {
+ public static void logInfo(final String appName, final String message, final Throwable thrown) {
Logger.getLogger(appName).log(Level.INFO,message,thrown);
}
- public static void isInfo(String appName) {
+ public static void isInfo(final String appName) {
Logger.getLogger(appName).isLoggable(Level.INFO);
}
- public static void logFine(String appName, String message) {
+ public static void logFine(final String appName, final String message) {
Logger.getLogger(appName).fine(message);
}
- public static void logFine(String appName, String message, Throwable thrown) {
+ public static void logFine(final String appName, final String message, final Throwable thrown) {
Logger.getLogger(appName).log(Level.FINE,message,thrown);
}
- public static void isFine(String appName) {
+ public static void isFine(final String appName) {
Logger.getLogger(appName).isLoggable(Level.FINE);
}
- public static void logFiner(String appName, String message) {
+ public static void logFiner(final String appName, final String message) {
Logger.getLogger(appName).finer(message);
}
- public static void logFiner(String appName, String message, Throwable thrown) {
+ public static void logFiner(final String appName, final String message, final Throwable thrown) {
Logger.getLogger(appName).log(Level.FINER,message,thrown);
}
- public static void isFiner(String appName) {
+ public static void isFiner(final String appName) {
Logger.getLogger(appName).isLoggable(Level.FINER);
}
- public static void logFinest(String appName, String message) {
+ public static void logFinest(final String appName, final String message) {
Logger.getLogger(appName).finest(message);
}
- public static void logFinest(String appName, String message, Throwable thrown) {
+ public static void logFinest(final String appName, final String message, final Throwable thrown) {
Logger.getLogger(appName).log(Level.FINEST,message,thrown);
}
- public static void isFinest(String appName) {
+ public static void isFinest(final String appName) {
Logger.getLogger(appName).isLoggable(Level.FINEST);
}
- public static final void configureLogging(File homePath, File loggingConfigFile) throws SecurityException, FileNotFoundException, IOException {
+ public static final void configureLogging(final File homePath, final File loggingConfigFile) throws SecurityException, FileNotFoundException, IOException {
FileInputStream fileIn = null;
try {
System.out.println("STARTUP: Trying to load logging configuration from file " + loggingConfigFile.toString());
fileIn = new FileInputStream(loggingConfigFile);
// loading the logger configuration from file
- LogManager logManager = LogManager.getLogManager();
+ final LogManager logManager = LogManager.getLogManager();
logManager.readConfiguration(fileIn);
// creating the logging directory
- String logPattern = logManager.getProperty("java.util.logging.FileHandler.pattern");
+ final String logPattern = logManager.getProperty("java.util.logging.FileHandler.pattern");
int stripPos = logPattern.lastIndexOf('/');
if (stripPos < 0) stripPos = logPattern.lastIndexOf(File.pathSeparatorChar);
File log = new File(logPattern.substring(0, stripPos));
@@ -193,33 +193,33 @@ public final class serverLog {
// System.setOut(new PrintStream(new LoggerOutputStream(Logger.getLogger("STDOUT"),Level.FINEST)));
// System.setErr(new PrintStream(new LoggerOutputStream(Logger.getLogger("STDERR"),Level.SEVERE)));
} finally {
- if (fileIn != null) try {fileIn.close();}catch(Exception e){}
+ if (fileIn != null) try {fileIn.close();}catch(final Exception e){}
}
}
- public static final String format(String s, int n, int fillChar) {
- int l = s.length();
+ public static final String format(final String s, int n, final int fillChar) {
+ final int l = s.length();
if (l >= n) return s;
- StringBuffer sb = new StringBuffer(l + n);
- for (int i = l + n; i > n; n--) sb.insert(0, fillChar);
+ final StringBuffer sb = new StringBuffer(l + n);
+ for (final int i = l + n; i > n; n--) sb.insert(0, fillChar);
return sb.toString();
}
- public static final String arrayList(byte[] b, int start, int length) {
+ public static final String arrayList(final byte[] b, final int start, int length) {
if (b == null) return "NULL";
if (b.length == 0) return "[]";
length = Math.min(length, b.length - start);
- StringBuffer sb = new StringBuffer(b.length * 4);
+ final StringBuffer sb = new StringBuffer(b.length * 4);
sb.append('[').append(Integer.toString(b[start])).append(',');
for (int i = 1; i < length; i++) sb.append(' ').append(Integer.toString(b[start + i])).append(',');
sb.append(']');
return sb.toString();
}
- public static final String table(byte[] b, int linewidth, int marker) {
+ public static final String table(final byte[] b, final int linewidth, final int marker) {
if (b == null) return "NULL";
if (b.length == 0) return "[]";
- StringBuffer sb = new StringBuffer(b.length * 4);
+ final StringBuffer sb = new StringBuffer(b.length * 4);
for (int i = 0; i < b.length; i++) {
if (i % linewidth == 0)
sb.append('\n').append("# ").append(Integer.toHexString(i)).append(": ");
@@ -232,11 +232,11 @@ public final class serverLog {
return sb.toString();
}
- public static final boolean allZero(byte[] a) {
+ public static final boolean allZero(final byte[] a) {
return allZero(a, 0, a.length);
}
- public static final boolean allZero(byte[] a, int astart, int alength) {
+ public static final boolean allZero(final byte[] a, final int astart, final int alength) {
for (int i = 0; i < alength; i++) if (a[astart + i] != 0) return false;
return true;
}
diff --git a/source/de/anomic/server/logging/serverMiniLogFormatter.java b/source/de/anomic/server/logging/serverMiniLogFormatter.java
index 93f8d36af..65a719ba5 100644
--- a/source/de/anomic/server/logging/serverMiniLogFormatter.java
+++ b/source/de/anomic/server/logging/serverMiniLogFormatter.java
@@ -36,9 +36,9 @@ public final class serverMiniLogFormatter extends SimpleFormatter {
super();
}
- public synchronized String format(LogRecord record) {
+ public synchronized String format(final LogRecord record) {
- StringBuffer buffer = this.buffer;
+ final StringBuffer buffer = this.buffer;
buffer.setLength(0);
buffer.append(formatMessage(record));
diff --git a/source/de/anomic/server/logging/serverSimpleLogFormatter.java b/source/de/anomic/server/logging/serverSimpleLogFormatter.java
index 56b4149e8..638ea5930 100644
--- a/source/de/anomic/server/logging/serverSimpleLogFormatter.java
+++ b/source/de/anomic/server/logging/serverSimpleLogFormatter.java
@@ -36,7 +36,7 @@ import java.util.logging.SimpleFormatter;
public class serverSimpleLogFormatter extends SimpleFormatter {
- private Date date = new Date();
+ private final Date date = new Date();
private final FieldPosition position = new FieldPosition(0);
// e.g. 2005/05/25 11:22:53
@@ -49,13 +49,13 @@ public class serverSimpleLogFormatter extends SimpleFormatter {
super();
}
- public synchronized String format(LogRecord record) {
+ public synchronized String format(final LogRecord record) {
- StringBuffer buffer = this.buffer;
+ final StringBuffer buffer = this.buffer;
buffer.setLength(0);
// adding the loglevel
- int logLevel = record.getLevel().intValue();
+ final int logLevel = record.getLevel().intValue();
if (logLevel == serverLog.LOGLEVEL_SEVERE)
this.buffer.append(serverLog.LOGTOKEN_SEVERE);
else if (logLevel == serverLog.LOGLEVEL_WARNING)
@@ -93,13 +93,13 @@ public class serverSimpleLogFormatter extends SimpleFormatter {
StringWriter writer = null;
try {
writer = new StringWriter();
- PrintWriter printer = new PrintWriter(writer);
+ final PrintWriter printer = new PrintWriter(writer);
record.getThrown().printStackTrace(printer);
buffer.append(writer.toString());
- } catch (Exception e) {
+ } catch (final Exception e) {
buffer.append("Failed to get stack trace: " + e.getMessage());
} finally {
- if (writer != null) try {writer.close();} catch (Exception ex) {}
+ if (writer != null) try {writer.close();} catch (final Exception ex) {}
}
}
return buffer.toString();
diff --git a/source/de/anomic/server/serverAbstractBlockingThread.java b/source/de/anomic/server/serverAbstractBlockingThread.java
index ddd4fdc97..37f98f130 100644
--- a/source/de/anomic/server/serverAbstractBlockingThread.java
+++ b/source/de/anomic/server/serverAbstractBlockingThread.java
@@ -33,10 +33,10 @@ public abstract class serverAbstractBlockingThread<J extends serverProcessorJob>
private BlockingQueue<J> input = null;
private serverProcessor<J> output = null;
- public void setInputQueue(BlockingQueue<J> queue) {
+ public void setInputQueue(final BlockingQueue<J> queue) {
this.input = queue;
}
- public void setOutputProcess(serverProcessor<J> processor) {
+ public void setOutputProcess(final serverProcessor<J> processor) {
this.output = processor;
}
public BlockingQueue<J> getInputQueue() {
@@ -60,7 +60,7 @@ public abstract class serverAbstractBlockingThread<J extends serverProcessorJob>
// do job
timestamp = System.currentTimeMillis();
memstamp0 = serverMemory.used();
- J in = this.input.take();
+ final J in = this.input.take();
if ((in == null) || (in.status == serverProcessorJob.STATUS_POISON)) {
// the poison pill: shutdown
// a null element is pushed to the queue on purpose to signal
@@ -68,7 +68,7 @@ public abstract class serverAbstractBlockingThread<J extends serverProcessorJob>
this.running = false;
break;
}
- J out = this.job(in);
+ final J out = this.job(in);
if ((out != null) && (this.output != null)) this.output.enQueue(out);
// do memory and busy/idle-count/time monitoring
memstamp1 = serverMemory.used();
@@ -80,11 +80,11 @@ public abstract class serverAbstractBlockingThread<J extends serverProcessorJob>
if (busyCycles > 0) memuse += memuse / busyCycles;
}
busytime += System.currentTimeMillis() - timestamp;
- } catch (InterruptedException e) {
+ } catch (final InterruptedException e) {
// don't ignore this: shut down
this.running = false;
break;
- } catch (Exception e) {
+ } catch (final Exception e) {
// handle exceptions: thread must not die on any unexpected exceptions
// if the exception is too bad it should call terminate()
this.jobExceptionHandler(e);
@@ -96,7 +96,7 @@ public abstract class serverAbstractBlockingThread<J extends serverProcessorJob>
logSystem("thread '" + this.getName() + "' terminated.");
}
- private void logSystem(String text) {
+ private void logSystem(final String text) {
if (log == null) serverLog.logConfig("THREAD-CONTROL", text);
else log.logConfig(text);
}
diff --git a/source/de/anomic/server/serverAbstractBusyThread.java b/source/de/anomic/server/serverAbstractBusyThread.java
index 0158c0c7c..f25f21660 100644
--- a/source/de/anomic/server/serverAbstractBusyThread.java
+++ b/source/de/anomic/server/serverAbstractBusyThread.java
@@ -34,35 +34,35 @@ public abstract class serverAbstractBusyThread extends serverAbstractThread impl
private long idletime = 0, memprereq = 0;
private long idleCycles = 0, busyCycles = 0, outofmemoryCycles = 0;
private boolean intermissionObedient = true;
- private Object syncObject = new Object();
+ private final Object syncObject = new Object();
- protected final void announceMoreSleepTime(long millis) {
+ protected final void announceMoreSleepTime(final long millis) {
this.idletime += millis;
}
- public final void setStartupSleep(long milliseconds) {
+ public final void setStartupSleep(final long milliseconds) {
// sets a sleep time before execution of the job-loop
startup = milliseconds;
}
- public final long setIdleSleep(long milliseconds) {
+ public final long setIdleSleep(final long milliseconds) {
// sets a sleep time for pauses between two jobs
idlePause = milliseconds;
return milliseconds;
}
- public final long setBusySleep(long milliseconds) {
+ public final long setBusySleep(final long milliseconds) {
// sets a sleep time for pauses between two jobs
busyPause = milliseconds;
return milliseconds;
}
- public void setMemPreReqisite(long freeBytes) {
+ public void setMemPreReqisite(final long freeBytes) {
// sets minimum required amount of memory for the job execution
memprereq = freeBytes;
}
- public void setObeyIntermission(boolean obey) {
+ public void setObeyIntermission(final boolean obey) {
// defines if the thread should obey the intermission command
intermissionObedient = obey;
}
@@ -88,7 +88,7 @@ public abstract class serverAbstractBusyThread extends serverAbstractThread impl
return this.idletime;
}
- public void intermission(long pause) {
+ public void intermission(final long pause) {
if (pause == Long.MAX_VALUE)
this.intermission = Long.MAX_VALUE;
else
@@ -162,10 +162,10 @@ public abstract class serverAbstractBusyThread extends serverAbstractThread impl
timestamp = System.currentTimeMillis();
ratz((isBusy) ? this.busyPause : this.idlePause);
idletime += System.currentTimeMillis() - timestamp;
- } catch (SocketException e) {
+ } catch (final SocketException e) {
// in case that a socket is interrupted, this method must die silently (shutdown)
this.log.logFine("socket-job interrupted: " + e.getMessage());
- } catch (Exception e) {
+ } catch (final Exception e) {
// handle exceptions: thread must not die on any unexpected exceptions
// if the exception is too bad it should call terminate()
this.jobExceptionHandler(e);
@@ -188,7 +188,7 @@ public abstract class serverAbstractBusyThread extends serverAbstractThread impl
logSystem("thread '" + this.getName() + "' terminated.");
}
- private void ratz(long millis) {
+ private void ratz(final long millis) {
try {/*
if (this.syncObject != null) {
synchronized (this.syncObject) {
@@ -197,7 +197,7 @@ public abstract class serverAbstractBusyThread extends serverAbstractThread impl
} else {*/
Thread.sleep(millis);
//}
- } catch (InterruptedException e) {
+ } catch (final InterruptedException e) {
if (this.log != null)
this.log.logConfig("thread '" + this.getName() + "' interrupted because of shutdown.");
}
@@ -215,7 +215,7 @@ public abstract class serverAbstractBusyThread extends serverAbstractThread impl
}
}
- private void logSystem(String text) {
+ private void logSystem(final String text) {
if (log == null) serverLog.logConfig("THREAD-CONTROL", text);
else log.logConfig(text);
}
diff --git a/source/de/anomic/server/serverAbstractSwitch.java b/source/de/anomic/server/serverAbstractSwitch.java
index 2e980cd9a..6f9f980ae 100644
--- a/source/de/anomic/server/serverAbstractSwitch.java
+++ b/source/de/anomic/server/serverAbstractSwitch.java
@@ -38,21 +38,21 @@ public abstract class serverAbstractSwitch<E> implements serverSwitch<E> {
private static final long maxTrackingTimeDefault = 1000 * 60 * 60; // store only access data from the last hour to save ram space
// configuration management
- private File configFile;
- private String configComment;
- private File rootPath;
+ private final File configFile;
+ private final String configComment;
+ private final File rootPath;
protected serverLog log;
protected int serverJobs;
protected long maxTrackingTime;
private Map<String, String> configProps;
- private Map<String, String> configRemoved;
- private HashMap<InetAddress, String> authorization;
- private TreeMap<String, serverBusyThread> workerThreads;
- private TreeMap<String, serverSwitchAction> switchActions;
+ private final Map<String, String> configRemoved;
+ private final HashMap<InetAddress, String> authorization;
+ private final TreeMap<String, serverBusyThread> workerThreads;
+ private final TreeMap<String, serverSwitchAction> switchActions;
protected ConcurrentHashMap<String, TreeMap<Long, String>> accessTracker; // mappings from requesting host to an ArrayList of serverTrack-entries
- private LinkedBlockingQueue<E> cacheStack;
+ private final LinkedBlockingQueue<E> cacheStack;
- public serverAbstractSwitch(File rootPath, String initPath, String configPath, boolean applyPro) {
+ public serverAbstractSwitch(final File rootPath, final String initPath, final String configPath, final boolean applyPro) {
// we initialize the switchboard with a property file,
// but maintain these properties then later in a new 'config' file
// to reset all changed configs, the config file must
@@ -62,7 +62,7 @@ public abstract class serverAbstractSwitch<E> implements serverSwitch<E> {
this.cacheStack = new LinkedBlockingQueue<E>();
this.rootPath = rootPath;
this.configComment = "This is an automatically generated file, updated by serverAbstractSwitch and initialized by " + initPath;
- File initFile = new File(rootPath, initPath);
+ final File initFile = new File(rootPath, initPath);
this.configFile = new File(rootPath, configPath); // propertiesFile(config);
new File(configFile.getParent()).mkdir();
@@ -145,7 +145,7 @@ public abstract class serverAbstractSwitch<E> implements serverSwitch<E> {
}
// a logger for this switchboard
- public void setLog(serverLog log) {
+ public void setLog(final serverLog log) {
this.log = log;
}
@@ -156,14 +156,14 @@ public abstract class serverAbstractSwitch<E> implements serverSwitch<E> {
/*
* remove all entries from the access tracker where the age of the last access is greater than the given timeout
*/
- public void cleanupAccessTracker(long timeout) {
- Iterator<Map.Entry<String, TreeMap<Long, String>>> i = accessTracker.entrySet().iterator();
+ public void cleanupAccessTracker(final long timeout) {
+ final Iterator<Map.Entry<String, TreeMap<Long, String>>> i = accessTracker.entrySet().iterator();
while (i.hasNext()) {
if (i.next().getValue().tailMap(new Long(System.currentTimeMillis() - timeout)).size() == 0) i.remove();
}
}
- public void track(String host, String accessPath) {
+ public void track(final String host, String accessPath) {
// learn that a specific host has accessed a specific path
if (accessPath == null) accessPath="NULL";
TreeMap<Long, String> access = accessTracker.get(host);
@@ -176,7 +176,7 @@ public abstract class serverAbstractSwitch<E> implements serverSwitch<E> {
}
}
- public TreeMap<Long, String> accessTrack(String host) {
+ public TreeMap<Long, String> accessTrack(final String host) {
// returns mapping from Long(accesstime) to path
TreeMap<Long, String> access = accessTracker.get(host);
@@ -195,19 +195,19 @@ public abstract class serverAbstractSwitch<E> implements serverSwitch<E> {
return access;
}
- private TreeMap<Long, String> clearTooOldAccess(TreeMap<Long, String> access) {
+ private TreeMap<Long, String> clearTooOldAccess(final TreeMap<Long, String> access) {
return new TreeMap<Long, String>(access.tailMap(new Long(System.currentTimeMillis() - maxTrackingTime)));
}
public Iterator<String> accessHosts() {
// returns an iterator of hosts in tracker (String)
- HashMap<String, TreeMap<Long, String>> accessTrackerClone = new HashMap<String, TreeMap<Long, String>>();
+ final HashMap<String, TreeMap<Long, String>> accessTrackerClone = new HashMap<String, TreeMap<Long, String>>();
accessTrackerClone.putAll(accessTracker);
return accessTrackerClone.keySet().iterator();
}
- public void setConfig(Map<String, String> otherConfigs) {
- Iterator<Map.Entry<String, String>> i = otherConfigs.entrySet().iterator();
+ public void setConfig(final Map<String, String> otherConfigs) {
+ final Iterator<Map.Entry<String, String>> i = otherConfigs.entrySet().iterator();
Map.Entry<String, String> entry;
while (i.hasNext()) {
entry = i.next();
@@ -215,22 +215,22 @@ public abstract class serverAbstractSwitch<E> implements serverSwitch<E> {
}
}
- public void setConfig(String key, boolean value) {
+ public void setConfig(final String key, final boolean value) {
setConfig(key, (value) ? "true" : "false");
}
- public void setConfig(String key, long value) {
+ public void setConfig(final String key, final long value) {
setConfig(key, Long.toString(value));
}
- public void setConfig(String key, double value) {
+ public void setConfig(final String key, final double value) {
setConfig(key, Double.toString(value));
}
- public void setConfig(String key, String value) {
+ public void setConfig(final String key, final String value) {
// perform action before setting new value
- Iterator<serverSwitchAction> bevore = switchActions.values().iterator();
- Iterator<serverSwitchAction> after = switchActions.values().iterator();
+ final Iterator<serverSwitchAction> bevore = switchActions.values().iterator();
+ final Iterator<serverSwitchAction> after = switchActions.values().iterator();
synchronized (configProps) {
serverSwitchAction action;
@@ -238,13 +238,13 @@ public abstract class serverAbstractSwitch<E> implements serverSwitch<E> {
action = bevore.next();
try {
action.doBevoreSetConfig(key, value);
- } catch (Exception e) {
+ } catch (final Exception e) {
log.logSevere("serverAction bevoreSetConfig '" + action.getShortDescription() + "' failed with exception: " + e.getMessage());
}
}
// set the value
- Object oldValue = configProps.put(key, value);
+ final Object oldValue = configProps.put(key, value);
saveConfig();
// perform actions afterwards
@@ -252,25 +252,25 @@ public abstract class serverAbstractSwitch<E> implements serverSwitch<E> {
action = after.next();
try {
action.doAfterSetConfig(key, value, (oldValue == null) ? null : (String) oldValue);
- } catch (Exception e) {
+ } catch (final Exception e) {
log.logSevere("serverAction afterSetConfig '" + action.getShortDescription() + "' failed with exception: " + e.getMessage());
}
}
}
}
- public void removeConfig(String key) {
+ public void removeConfig(final String key) {
configProps.remove(key);
}
/* (non-Javadoc)
* @see de.anomic.server.serverSwitch#getConfig(java.lang.String, java.lang.String)
*/
- public String getConfig(String key, String dflt) {
- Iterator<serverSwitchAction> i = switchActions.values().iterator();
+ public String getConfig(final String key, final String dflt) {
+ final Iterator<serverSwitchAction> i = switchActions.values().iterator();
synchronized (configProps) {
// get the value
- Object s = configProps.get(key);
+ final Object s = configProps.get(key);
// do action
serverSwitchAction action;
@@ -278,7 +278,7 @@ public abstract class serverAbstractSwitch<E> implements serverSwitch<E> {
action = i.next();
try {
action.doWhenGetConfig(key, (s == null) ? null : (String) s, dflt);
- } catch (Exception e) {
+ } catch (final Exception e) {
log.logSevere("serverAction whenGetConfig '" + action.getShortDescription() + "' failed with exception: " + e.getMessage());
}
}
@@ -289,23 +289,23 @@ public abstract class serverAbstractSwitch<E> implements serverSwitch<E> {
}
}
- public long getConfigLong(String key, long dflt) {
+ public long getConfigLong(final String key, final long dflt) {
try {
return Long.parseLong(getConfig(key, Long.toString(dflt)));
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
return dflt;
}
}
- public double getConfigDouble(String key, double dflt) {
+ public double getConfigDouble(final String key, final double dflt) {
try {
return Double.parseDouble(getConfig(key, Double.toString(dflt)));
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
return dflt;
}
}
- public boolean getConfigBool(String key, boolean dflt) {
+ public boolean getConfigBool(final String key, final boolean dflt) {
return Boolean.valueOf(getConfig(key, Boolean.toString(dflt))).booleanValue();
}
@@ -318,10 +318,10 @@ public abstract class serverAbstractSwitch<E> implements serverSwitch<E> {
* returned File is derived from this setting only. Otherwise the path's file
* is constructed from the applications root path + the relative path setting.
*/
- public File getConfigPath(String key, String dflt) {
+ public File getConfigPath(final String key, final String dflt) {
File ret;
- String path = getConfig(key, dflt).replace('\\', '/');
- File f = new File(path);
+ final String path = getConfig(key, dflt).replace('\\', '/');
+ final File f = new File(path);
if (f == null) {
ret = null;
} else {
@@ -340,7 +340,7 @@ public abstract class serverAbstractSwitch<E> implements serverSwitch<E> {
synchronized (configProps) {
serverFileUtils.saveMap(configFile, configProps, configComment);
}
- } catch (IOException e) {
+ } catch (final IOException e) {
System.out.println("ERROR: cannot write config file " + configFile.toString() + ": " + e.getMessage());
}
}
@@ -351,28 +351,28 @@ public abstract class serverAbstractSwitch<E> implements serverSwitch<E> {
}
// add/remove action listener
- public void deployAction(String actionName, String actionShortDescription, String actionLongDescription,
- serverSwitchAction newAction) {
+ public void deployAction(final String actionName, final String actionShortDescription, final String actionLongDescription,
+ final serverSwitchAction newAction) {
newAction.setLog(log);
newAction.setDescription(actionShortDescription, actionLongDescription);
switchActions.put(actionName, newAction);
log.logInfo("Deployed Action '" + actionShortDescription + "', (" + switchActions.size() + " actions registered)");
}
- public void undeployAction(String actionName) {
- serverSwitchAction action = switchActions.get(actionName);
+ public void undeployAction(final String actionName) {
+ final serverSwitchAction action = switchActions.get(actionName);
action.close();
switchActions.remove(actionName);
log.logInfo("Undeployed Action '" + action.getShortDescription() + "', (" + switchActions.size() + " actions registered)");
}
public void deployThread(
- String threadName,
- String threadShortDescription,
- String threadLongDescription,
- String threadMonitorURL,
- serverBusyThread newThread,
- long startupDelay) {
+ final String threadName,
+ final String threadShortDescription,
+ final String threadLongDescription,
+ final String threadMonitorURL,
+ final serverBusyThread newThread,
+ final long startupDelay) {
deployThread(threadName, threadShortDescription, threadLongDescription, threadMonitorURL,
newThread, startupDelay,
Long.parseLong(getConfig(threadName + "_idlesleep" , "100")),
@@ -381,36 +381,36 @@ public abstract class serverAbstractSwitch<E> implements serverSwitch<E> {
}
public void deployThread(
- String threadName,
- String threadShortDescription,
- String threadLongDescription,
- String threadMonitorURL,
- serverBusyThread newThread,
- long startupDelay,
- long initialIdleSleep,
- long initialBusySleep,
- long initialMemoryPreRequisite) {
+ final String threadName,
+ final String threadShortDescription,
+ final String threadLongDescription,
+ final String threadMonitorURL,
+ final serverBusyThread newThread,
+ final long startupDelay,
+ final long initialIdleSleep,
+ final long initialBusySleep,
+ final long initialMemoryPreRequisite) {
if (newThread.isAlive()) throw new RuntimeException("undeployed threads must not live; they are started as part of the deployment");
newThread.setStartupSleep(startupDelay);
long x;
try {
x = Long.parseLong(getConfig(threadName + "_idlesleep" , "novalue"));
newThread.setIdleSleep(x);
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
newThread.setIdleSleep(initialIdleSleep);
setConfig(threadName + "_idlesleep", initialIdleSleep);
}
try {
x = Long.parseLong(getConfig(threadName + "_busysleep" , "novalue"));
newThread.setBusySleep(x);
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
newThread.setBusySleep(initialBusySleep);
setConfig(threadName + "_busysleep", initialBusySleep);
}
try {
x = Long.parseLong(getConfig(threadName + "_memprereq" , "novalue"));
newThread.setMemPreReqisite(x);
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
newThread.setMemPreReqisite(initialMemoryPreRequisite);
setConfig(threadName + "_memprereq", initialMemoryPreRequisite);
}
@@ -421,12 +421,12 @@ public abstract class serverAbstractSwitch<E> implements serverSwitch<E> {
if (workerThreads.containsKey(threadName)) newThread.start();
}
- public serverBusyThread getThread(String threadName) {
+ public serverBusyThread getThread(final String threadName) {
return workerThreads.get(threadName);
}
- public void setThreadPerformance(String threadName, long idleMillis, long busyMillis, long memprereqBytes) {
- serverBusyThread thread = workerThreads.get(threadName);
+ public void setThreadPerformance(final String threadName, final long idleMillis, final long busyMillis, final long memprereqBytes) {
+ final serverBusyThread thread = workerThreads.get(threadName);
if (thread != null) {
thread.setIdleSleep(idleMillis);
thread.setBusySleep(busyMillis);
@@ -434,21 +434,21 @@ public abstract class serverAbstractSwitch<E> implements serverSwitch<E> {
}
}
- public synchronized void terminateThread(String threadName, boolean waitFor) {
+ public synchronized void terminateThread(final String threadName, final boolean waitFor) {
if (workerThreads.containsKey(threadName)) {
((serverThread) workerThreads.get(threadName)).terminate(waitFor);
workerThreads.remove(threadName);
}
}
- public void intermissionAllThreads(long pause) {
- Iterator<String> e = workerThreads.keySet().iterator();
+ public void intermissionAllThreads(final long pause) {
+ final Iterator<String> e = workerThreads.keySet().iterator();
while (e.hasNext()) {
workerThreads.get(e.next()).intermission(pause);
}
}
- public synchronized void terminateAllThreads(boolean waitFor) {
+ public synchronized void terminateAllThreads(final boolean waitFor) {
Iterator<String> e = workerThreads.keySet().iterator();
while (e.hasNext()) {
((serverThread) workerThreads.get(e.next())).terminate(false);
@@ -474,7 +474,7 @@ public abstract class serverAbstractSwitch<E> implements serverSwitch<E> {
return cacheStack.peek();
}
- public void enQueue(E job) {
+ public void enQueue(final E job) {
cacheStack.add(job);
}
@@ -484,48 +484,48 @@ public abstract class serverAbstractSwitch<E> implements serverSwitch<E> {
// authentification routines:
- public void setAuthentify(InetAddress host, String user, String rights) {
+ public void setAuthentify(final InetAddress host, final String user, final String rights) {
// sets access attributes according to host addresses
authorization.put(host, user + "@" + rights);
}
- public void removeAuthentify(InetAddress host) {
+ public void removeAuthentify(final InetAddress host) {
// remove access attributes according to host addresses
authorization.remove(host);
}
- public String getAuthentifyUser(InetAddress host) {
+ public String getAuthentifyUser(final InetAddress host) {
// read user name according to host addresses
- String a = authorization.get(host);
+ final String a = authorization.get(host);
if (a == null) return null;
- int p = a.indexOf("@");
+ final int p = a.indexOf("@");
if (p < 0) return null;
return a.substring(0, p);
}
- public String getAuthentifyRights(InetAddress host) {
+ public String getAuthentifyRights(final InetAddress host) {
// read access rigths according to host addresses
- String a = authorization.get(host);
+ final String a = authorization.get(host);
if (a == null) return null;
- int p = a.indexOf("@");
+ final int p = a.indexOf("@");
if (p < 0) return null;
return a.substring(p + 1);
}
- public void addAuthentifyRight(InetAddress host, String right) {
- String rights = getAuthentifyRights(host);
+ public void addAuthentifyRight(final InetAddress host, final String right) {
+ final String rights = getAuthentifyRights(host);
if (rights == null) {
// create new authentification
setAuthentify(host, "unknown", right);
} else {
// add more authentification
- String user = getAuthentifyUser(host);
+ final String user = getAuthentifyUser(host);
setAuthentify(host, user, rights + right);
}
}
- public boolean hasAuthentifyRight(InetAddress host, String right) {
- String rights = getAuthentifyRights(host);
+ public boolean hasAuthentifyRight(final InetAddress host, final String right) {
+ final String rights = getAuthentifyRights(host);
if (rights == null) return false;
return rights.indexOf(right) >= 0;
}
@@ -540,7 +540,7 @@ public abstract class serverAbstractSwitch<E> implements serverSwitch<E> {
return configProps.toString();
}
- public void handleBusyState(int jobs) {
+ public void handleBusyState(final int jobs) {
serverJobs = jobs;
}
}
diff --git a/source/de/anomic/server/serverAbstractThread.java b/source/de/anomic/server/serverAbstractThread.java
index ede4f4540..75c83cabb 100644
--- a/source/de/anomic/server/serverAbstractThread.java
+++ b/source/de/anomic/server/serverAbstractThread.java
@@ -57,16 +57,16 @@ public abstract class serverAbstractThread extends Thread implements serverThrea
// shall only be used, if a thread blocks for an important reason
// like a socket connect and must renew the timestamp to correct
// statistics
- long thisBlockTime = (System.currentTimeMillis() - this.threadBlockTimestamp);
+ final long thisBlockTime = (System.currentTimeMillis() - this.threadBlockTimestamp);
this.blockPause += thisBlockTime;
this.busytime -= thisBlockTime;
}
- protected final void announceMoreExecTime(long millis) {
+ protected final void announceMoreExecTime(final long millis) {
this.busytime += millis;
}
- public final void setDescription(String shortText, String longText, String monitorURL) {
+ public final void setDescription(final String shortText, final String longText, final String monitorURL) {
// sets a visible description string
this.shortDescr = shortText;
this.longDescr = longText;
@@ -100,7 +100,7 @@ public abstract class serverAbstractThread extends Thread implements serverThrea
return memuse;
}
- public final void setLog(serverLog log) {
+ public final void setLog(final serverLog log) {
// defines a log where process states can be written to
this.log = log;
}
@@ -110,7 +110,7 @@ public abstract class serverAbstractThread extends Thread implements serverThrea
return !this.running || Thread.currentThread().isInterrupted();
}
- public void terminate(boolean waitFor) {
+ public void terminate(final boolean waitFor) {
// after calling this method, the thread shall terminate
this.running = false;
@@ -120,18 +120,18 @@ public abstract class serverAbstractThread extends Thread implements serverThrea
// wait for termination
if (waitFor) {
// Busy waiting removed: while (this.isAlive()) try {this.sleep(100);} catch (InterruptedException e) {break;}
- try { this.join(3000); } catch (InterruptedException e) {return;}
+ try { this.join(3000); } catch (final InterruptedException e) {return;}
}
// If we reach this point, the process is closed
}
- private final void logError(String text,Throwable thrown) {
+ private final void logError(final String text,final Throwable thrown) {
if (log == null) serverLog.logSevere("THREAD-CONTROL", text, thrown);
else log.logSevere(text,thrown);
}
- public void jobExceptionHandler(Exception e) {
+ public void jobExceptionHandler(final Exception e) {
if (!(e instanceof ClosedByInterruptException)) {
// default handler for job exceptions. shall be overridden for own handler
logError("thread '" + this.getName() + "': " + e.toString(),e);
diff --git a/source/de/anomic/server/serverByteBuffer.java b/source/de/anomic/server/serverByteBuffer.java
index 0b46d1c80..013a81eea 100644
--- a/source/de/anomic/server/serverByteBuffer.java
+++ b/source/de/anomic/server/serverByteBuffer.java
@@ -46,26 +46,26 @@ public final class serverByteBuffer extends OutputStream {
offset = 0;
}
- public serverByteBuffer(int initLength) {
+ public serverByteBuffer(final int initLength) {
this.buffer = new byte[initLength];
this.length = 0;
this.offset = 0;
}
- public serverByteBuffer(byte[] bb) {
+ public serverByteBuffer(final byte[] bb) {
buffer = bb;
length = bb.length;
offset = 0;
}
- public serverByteBuffer(byte[] bb, int initLength) {
+ public serverByteBuffer(final byte[] bb, final int initLength) {
this.buffer = new byte[initLength];
System.arraycopy(bb, 0, buffer, 0, bb.length);
length = bb.length;
offset = 0;
}
- public serverByteBuffer(byte[] bb, int of, int le) {
+ public serverByteBuffer(final byte[] bb, final int of, final int le) {
if (of * 2 > bb.length) {
buffer = new byte[le];
System.arraycopy(bb, of, buffer, 0, le);
@@ -78,13 +78,13 @@ public final class serverByteBuffer extends OutputStream {
}
}
- public serverByteBuffer(serverByteBuffer bb) {
+ public serverByteBuffer(final serverByteBuffer bb) {
buffer = bb.buffer;
length = bb.length;
offset = bb.offset;
}
- public serverByteBuffer(File f) throws IOException {
+ public serverByteBuffer(final File f) throws IOException {
// initially fill the byte buffer with the content of a file
if (f.length() > Integer.MAX_VALUE) throw new IOException("file is too large for buffering");
@@ -93,7 +93,7 @@ public final class serverByteBuffer extends OutputStream {
offset = 0;
try {
- FileInputStream fis = new FileInputStream(f);
+ final FileInputStream fis = new FileInputStream(f);
// byte[] buf = new byte[512];
// int p = 0;
// while ((l = fis.read(buf)) > 0) {
@@ -102,7 +102,7 @@ public final class serverByteBuffer extends OutputStream {
/*int l =*/ fis.read(buffer);
// }
fis.close();
- } catch (FileNotFoundException e) {
+ } catch (final FileNotFoundException e) {
throw new IOException("File not found: " + f.toString() + "; " + e.getMessage());
}
}
@@ -127,20 +127,20 @@ public final class serverByteBuffer extends OutputStream {
offset = 0;
}
- public void write(int b) {
+ public void write(final int b) {
write((byte) (b & 0xff));
}
- public void write(byte b) {
+ public void write(final byte b) {
if (offset + length + 1 > buffer.length) grow();
buffer[offset + length++] = b;
}
- public void write(byte[] bb) {
+ public void write(final byte[] bb) {
write(bb, 0, bb.length);
}
- public void write(byte[] bb, int of, int le) {
+ public void write(final byte[] bb, final int of, final int le) {
while (offset + length + le > buffer.length) grow();
System.arraycopy(bb, of, buffer, offset + length, le);
length += le;
@@ -148,70 +148,70 @@ public final class serverByteBuffer extends OutputStream {
// overwrite does not increase the 'length' write position pointer!
- public void overwrite(int pos, int b) {
+ public void overwrite(final int pos, final int b) {
overwrite(pos, (byte) (b & 0xff));
}
- public void overwrite(int pos, byte b) {
+ public void overwrite(final int pos, final byte b) {
if (offset + pos + 1 > buffer.length) grow();
buffer[offset + pos] = b;
if (pos >= length) length = pos + 1;
}
- public void overwrite(int pos, byte[] bb) {
+ public void overwrite(final int pos, final byte[] bb) {
overwrite(pos, bb, 0, bb.length);
}
- public void overwrite(int pos, byte[] bb, int of, int le) {
+ public void overwrite(final int pos, final byte[] bb, final int of, final int le) {
while (offset + pos + le > buffer.length) grow();
System.arraycopy(bb, of, buffer, offset + pos, le);
if (pos + le > length) length = pos + le;
}
- public serverByteBuffer append(byte b) {
+ public serverByteBuffer append(final byte b) {
write(b);
return this;
}
- public serverByteBuffer append(int i) {
+ public serverByteBuffer append(final int i) {
write((byte) (i & 0xFF));
return this;
}
- public serverByteBuffer append(byte[] bb) {
+ public serverByteBuffer append(final byte[] bb) {
write(bb);
return this;
}
- public serverByteBuffer append(byte[] bb, int of, int le) {
+ public serverByteBuffer append(final byte[] bb, final int of, final int le) {
write(bb, of, le);
return this;
}
- public serverByteBuffer append(String s) {
+ public serverByteBuffer append(final String s) {
return append(s.getBytes());
}
- public serverByteBuffer append(String s, String charset) throws UnsupportedEncodingException {
+ public serverByteBuffer append(final String s, final String charset) throws UnsupportedEncodingException {
return append(s.getBytes(charset));
}
- public serverByteBuffer append(serverByteBuffer bb) {
+ public serverByteBuffer append(final serverByteBuffer bb) {
return append(bb.buffer, bb.offset, bb.length);
}
- public serverByteBuffer append(Object o) {
+ public serverByteBuffer append(final Object o) {
if (o instanceof String) return append((String) o);
if (o instanceof byte[]) return append((byte[]) o);
return null;
}
- public byte byteAt(int pos) {
+ public byte byteAt(final int pos) {
if (pos > length) return -1;
return buffer[offset + pos];
}
- public void deleteByteAt(int pos) {
+ public void deleteByteAt(final int pos) {
if (pos < 0) return;
if (pos >= length) return;
if (pos == length - 1) {
@@ -221,21 +221,21 @@ public final class serverByteBuffer extends OutputStream {
}
}
- public int indexOf(byte b) {
+ public int indexOf(final byte b) {
return indexOf(b, 0);
}
- public int indexOf(byte[] bs) {
+ public int indexOf(final byte[] bs) {
return indexOf(bs, 0);
}
- public int indexOf(byte b, int start) {
+ public int indexOf(final byte b, final int start) {
if (start >= length) return -1;
for (int i = start; i < length; i++) if (buffer[offset + i] == b) return i;
return -1;
}
- public int indexOf(byte[] bs, int start) {
+ public int indexOf(final byte[] bs, final int start) {
if (start + bs.length > length) return -1;
loop: for (int i = start; i <= length - bs.length; i++) {
// first test only first byte
@@ -252,16 +252,16 @@ public final class serverByteBuffer extends OutputStream {
return -1;
}
- public int lastIndexOf(byte b) {
+ public int lastIndexOf(final byte b) {
for (int i = length - 1; i >= 0; i--) if (buffer[offset + i] == b) return i;
return -1;
}
- public boolean startsWith(byte[] bs) {
+ public boolean startsWith(final byte[] bs) {
return startsWith(bs, 0);
}
- public boolean startsWith(byte[] bs, int start) {
+ public boolean startsWith(final byte[] bs, final int start) {
if (length - start < bs.length) return false;
for (int i = 0; i < bs.length; i++) {
if (buffer[offset + i + start] != bs[i]) return false;
@@ -273,26 +273,26 @@ public final class serverByteBuffer extends OutputStream {
return getBytes(0);
}
- public byte[] getBytes(int start) {
+ public byte[] getBytes(final int start) {
return getBytes(start, this.length);
}
- public byte[] getBytes(int start, int len) {
+ public byte[] getBytes(final int start, final int len) {
// start is inclusive, end is exclusive
if (len > length) throw new IndexOutOfBoundsException("getBytes: len > length");
if (start > length) throw new IndexOutOfBoundsException("getBytes: start > length");
if ((start == 0) && (len == length) && (len == buffer.length)) return buffer;
- byte[] tmp = new byte[len];
+ final byte[] tmp = new byte[len];
System.arraycopy(buffer, offset + start, tmp, 0, len);
return tmp;
}
- public serverByteBuffer trim(int start) {
+ public serverByteBuffer trim(final int start) {
trim(start, this.length - start);
return this;
}
- public serverByteBuffer trim(int start, int len) {
+ public serverByteBuffer trim(final int start, final int len) {
if (start + len > this.length) throw new IndexOutOfBoundsException("trim: start + len > length; this.offset = " + this.offset + ", this.length = " + this.length + ", start = " + start + ", len = " + len);
this.offset = this.offset + start;
this.length = len;
@@ -309,7 +309,7 @@ public final class serverByteBuffer extends OutputStream {
return trim(l, r - l + 1);
}
- public int isUTF8char(int start) {
+ public int isUTF8char(final int start) {
// a sequence of bytes is a utf-8 character, if one of the following 4 conditions is true:
// - ASCII equivalence range; (first) byte begins with zero
// - first byte begins with 110, the following byte begins with 10
@@ -333,7 +333,7 @@ public final class serverByteBuffer extends OutputStream {
return -1;
}
- public boolean isWhitespace(boolean includeNonLetterBytes) {
+ public boolean isWhitespace(final boolean includeNonLetterBytes) {
// returns true, if trim() would result in an empty serverByteBuffer
if (includeNonLetterBytes) {
byte b;
@@ -347,7 +347,7 @@ public final class serverByteBuffer extends OutputStream {
return true;
}
- public int whitespaceStart(boolean includeNonLetterBytes) {
+ public int whitespaceStart(final boolean includeNonLetterBytes) {
// returns number of whitespace bytes at the beginning of text
if (includeNonLetterBytes) {
byte b;
@@ -361,7 +361,7 @@ public final class serverByteBuffer extends OutputStream {
return length;
}
- public int whitespaceEnd(boolean includeNonLetterBytes) {
+ public int whitespaceEnd(final boolean includeNonLetterBytes) {
// returns position of whitespace at the end of text
if (includeNonLetterBytes) {
byte b;
@@ -380,24 +380,24 @@ public final class serverByteBuffer extends OutputStream {
return new String(buffer, offset, length);
}
- public String toString(String charsetName) {
+ public String toString(final String charsetName) {
try {
return new String(this.getBytes(),charsetName);
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
return new String(this.getBytes());
}
}
- public String toString(int left, int rightbound) {
+ public String toString(final int left, final int rightbound) {
return new String(buffer, offset + left, rightbound - left);
}
- public Properties propParser(String charset) {
+ public Properties propParser(final String charset) {
// extract a=b or a="b" - relations from the buffer
int pos = offset;
int start;
String key;
- Properties p = new Properties();
+ final Properties p = new Properties();
// eat up spaces at beginning
while ((pos < length) && (buffer[pos] <= 32)) pos++;
while (pos < length) {
@@ -407,7 +407,7 @@ public final class serverByteBuffer extends OutputStream {
if (pos >= length) break; // this is the case if we found no equal
try {
key = new String(buffer, start, pos - start,charset).trim().toLowerCase();
- } catch (UnsupportedEncodingException e1) {
+ } catch (final UnsupportedEncodingException e1) {
key = new String(buffer, start, pos - start).trim().toLowerCase();
}
// we have a key
@@ -427,7 +427,7 @@ public final class serverByteBuffer extends OutputStream {
if (pos >= length) break; // this is the case if we found no parent doublequote
try {
p.setProperty(key, new String(buffer, start, pos - start,charset).trim());
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
p.setProperty(key, new String(buffer, start, pos - start).trim());
}
pos++;
@@ -439,7 +439,7 @@ public final class serverByteBuffer extends OutputStream {
if (pos >= length) break; // this is the case if we found no parent singlequote
try {
p.setProperty(key, new String(buffer, start, pos - start,charset).trim());
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
p.setProperty(key, new String(buffer, start, pos - start).trim());
}
pos++;
@@ -449,7 +449,7 @@ public final class serverByteBuffer extends OutputStream {
while ((pos < length) && (buffer[pos] > 32)) pos++;
try {
p.setProperty(key, new String(buffer, start, pos - start,charset).trim());
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
p.setProperty(key, new String(buffer, start, pos - start).trim());
}
}
@@ -460,11 +460,11 @@ public final class serverByteBuffer extends OutputStream {
return p;
}
- public static boolean equals(byte[] buffer, byte[] pattern) {
+ public static boolean equals(final byte[] buffer, final byte[] pattern) {
return equals(buffer, 0, pattern);
}
- public static boolean equals(byte[] buffer, int offset, byte[] pattern) {
+ public static boolean equals(final byte[] buffer, final int offset, final byte[] pattern) {
// compares two byte arrays: true, if pattern appears completely at offset position
if (buffer.length < offset + pattern.length) return false;
for (int i = 0; i < pattern.length; i++) if (buffer[offset + i] != pattern[i]) return false;
@@ -476,19 +476,19 @@ public final class serverByteBuffer extends OutputStream {
this.offset = 0;
}
- public void reset(int newSize) {
+ public void reset(final int newSize) {
this.resize(newSize);
this.reset();
}
- public void resize(int newSize) {
+ public void resize(final int newSize) {
if(newSize < 0) throw new IllegalArgumentException("Illegal array size: " + newSize);
- byte[] v = new byte[newSize];
+ final byte[] v = new byte[newSize];
System.arraycopy(this.buffer,0,v,0,newSize > this.buffer.length ? this.buffer.length : newSize);
this.buffer = v;
}
- public void writeTo(OutputStream dest) throws IOException {
+ public void writeTo(final OutputStream dest) throws IOException {
dest.write(this.buffer, this.offset, this.length);
dest.flush();
}
diff --git a/source/de/anomic/server/serverCachedFileOutputStream.java b/source/de/anomic/server/serverCachedFileOutputStream.java
index c999e7e7b..c43e15e08 100644
--- a/source/de/anomic/server/serverCachedFileOutputStream.java
+++ b/source/de/anomic/server/serverCachedFileOutputStream.java
@@ -44,17 +44,17 @@ public class serverCachedFileOutputStream extends ByteArrayOutputStream {
protected boolean isFallback = false;
protected OutputStream fallback = null;
- public serverCachedFileOutputStream(long fallbackSize) throws IOException {
+ public serverCachedFileOutputStream(final long fallbackSize) throws IOException {
this(fallbackSize, null, true, 32);
}
- public serverCachedFileOutputStream(long fallbackSize, File fallback, boolean buffered)
+ public serverCachedFileOutputStream(final long fallbackSize, final File fallback, final boolean buffered)
throws IOException {
this(fallbackSize, fallback, buffered, 32);
}
- public serverCachedFileOutputStream(long fallbackSize, File fallback, boolean buffered,
- long size) throws IOException {
+ public serverCachedFileOutputStream(final long fallbackSize, final File fallback, final boolean buffered,
+ final long size) throws IOException {
this.fallbackSize = fallbackSize;
this.fallbackFile = (fallback == null) ? File.createTempFile(
serverCachedFileOutputStream.class.getName(),
@@ -63,19 +63,19 @@ public class serverCachedFileOutputStream extends ByteArrayOutputStream {
checkFallback(size);
}
- public serverCachedFileOutputStream(long fallbackSize, File fallback, boolean buffered,
- byte[] data) throws IOException {
+ public serverCachedFileOutputStream(final long fallbackSize, final File fallback, final boolean buffered,
+ final byte[] data) throws IOException {
this(fallbackSize, fallback, buffered, 0);
super.buf = data;
super.count = data.length;
checkFallback(this.size = data.length);
}
- protected boolean checkFallback(long size) {
+ protected boolean checkFallback(final long size) {
if (size > this.fallbackSize) try {
fallback();
return true;
- } catch (IOException e) {
+ } catch (final IOException e) {
throw new RuntimeException("error falling back to file", e);
} else {
return false;
@@ -90,7 +90,7 @@ public class serverCachedFileOutputStream extends ByteArrayOutputStream {
} else if (this.fallbackFile.isDirectory()) {
throw new IOException("cannot write on a directory");
}
- OutputStream os = new FileOutputStream(this.fallbackFile);
+ final OutputStream os = new FileOutputStream(this.fallbackFile);
this.fallback = (this.buffered) ? new BufferedOutputStream(os) : os;
serverFileUtils.copy(new ByteArrayInputStream(super.buf), this.fallback);
super.buf = new byte[0];
@@ -102,20 +102,20 @@ public class serverCachedFileOutputStream extends ByteArrayOutputStream {
return this.isFallback;
}
- public synchronized void write(int b) {
+ public synchronized void write(final int b) {
if (checkFallback(++this.size)) try {
this.fallback.write(b);
- } catch (IOException e) {
+ } catch (final IOException e) {
throw new RuntimeException("error writing to fallback", e);
} else {
super.write(b);
}
}
- public synchronized void write(byte[] b, int off, int len) {
+ public synchronized void write(final byte[] b, final int off, final int len) {
if (checkFallback(this.size += len)) try {
this.fallback.write(b, off, len);
- } catch (IOException e) {
+ } catch (final IOException e) {
throw new RuntimeException("error writing to fallback", e);
} else {
super.write(b, off, len);
@@ -131,7 +131,7 @@ public class serverCachedFileOutputStream extends ByteArrayOutputStream {
public InputStream getContent() throws IOException {
close();
if (this.isFallback) {
- InputStream is = new FileInputStream(this.fallbackFile);
+ final InputStream is = new FileInputStream(this.fallbackFile);
return (this.buffered) ? new BufferedInputStream(is) : is;
} else {
return new ByteArrayInputStream(this.buf);
diff --git a/source/de/anomic/server/serverCharBuffer.java b/source/de/anomic/server/serverCharBuffer.java
index a544e5055..ca6ec22df 100644
--- a/source/de/anomic/server/serverCharBuffer.java
+++ b/source/de/anomic/server/serverCharBuffer.java
@@ -48,26 +48,26 @@ public final class serverCharBuffer extends Writer {
offset = 0;
}
- public serverCharBuffer(int initLength) {
+ public serverCharBuffer(final int initLength) {
this.buffer = new char[initLength];
this.length = 0;
this.offset = 0;
}
- public serverCharBuffer(char[] bb) {
+ public serverCharBuffer(final char[] bb) {
buffer = bb;
length = bb.length;
offset = 0;
}
- public serverCharBuffer(char[] bb, int initLength) {
+ public serverCharBuffer(final char[] bb, final int initLength) {
this.buffer = new char[initLength];
System.arraycopy(bb, 0, buffer, 0, bb.length);
length = bb.length;
offset = 0;
}
- public serverCharBuffer(char[] bb, int of, int le) {
+ public serverCharBuffer(final char[] bb, final int of, final int le) {
if (of * 2 > bb.length) {
buffer = new char[le];
System.arraycopy(bb, of, buffer, 0, le);
@@ -80,13 +80,13 @@ public final class serverCharBuffer extends Writer {
}
}
- public serverCharBuffer(serverCharBuffer bb) {
+ public serverCharBuffer(final serverCharBuffer bb) {
buffer = bb.buffer;
length = bb.length;
offset = bb.offset;
}
- public serverCharBuffer(File f) throws IOException {
+ public serverCharBuffer(final File f) throws IOException {
// initially fill the buffer with the content of a file
if (f.length() > Integer.MAX_VALUE) throw new IOException("file is too large for buffering");
@@ -95,13 +95,13 @@ public final class serverCharBuffer extends Writer {
offset = 0;
try {
- FileReader fr = new FileReader(f);
- char[] temp = new char[256];
+ final FileReader fr = new FileReader(f);
+ final char[] temp = new char[256];
int c;
while ((c = fr.read(temp)) > 0) {
this.append(temp,0,c);
}
- } catch (FileNotFoundException e) {
+ } catch (final FileNotFoundException e) {
throw new IOException("File not found: " + f.toString() + "; " + e.getMessage());
}
}
@@ -126,20 +126,20 @@ public final class serverCharBuffer extends Writer {
offset = 0;
}
- public void write(int b) {
+ public void write(final int b) {
write((char)b);
}
- public void write(char b) {
+ public void write(final char b) {
if (offset + length + 1 > buffer.length) grow();
buffer[offset + length++] = b;
}
- public void write(char[] bb) {
+ public void write(final char[] bb) {
write(bb, 0, bb.length);
}
- public void write(char[] bb, int of, int le) {
+ public void write(final char[] bb, final int of, final int le) {
while (offset + length + le > buffer.length) grow();
System.arraycopy(bb, of, buffer, offset + length, le);
length += le;
@@ -153,32 +153,32 @@ public final class serverCharBuffer extends Writer {
// return this;
// }
- public serverCharBuffer append(int i) {
+ public serverCharBuffer append(final int i) {
write((char) (i));
return this;
}
- public serverCharBuffer append(char[] bb) {
+ public serverCharBuffer append(final char[] bb) {
write(bb);
return this;
}
- public serverCharBuffer append(char[] bb, int of, int le) {
+ public serverCharBuffer append(final char[] bb, final int of, final int le) {
write(bb, of, le);
return this;
}
- public serverCharBuffer append(String s) {
+ public serverCharBuffer append(final String s) {
return append(s,0,s.length());
}
- public serverCharBuffer append(String s, int off, int len) {
- char[] temp = new char[len];
+ public serverCharBuffer append(final String s, final int off, final int len) {
+ final char[] temp = new char[len];
s.getChars(off, (off + len), temp, 0);
return append(temp);
}
- public serverCharBuffer append(serverCharBuffer bb) {
+ public serverCharBuffer append(final serverCharBuffer bb) {
return append(bb.buffer, bb.offset, bb.length);
}
@@ -188,13 +188,13 @@ public final class serverCharBuffer extends Writer {
// return null;
// }
- public char charAt(int pos) {
+ public char charAt(final int pos) {
if (pos < 0) throw new IndexOutOfBoundsException();
if (pos > length) throw new IndexOutOfBoundsException();
return buffer[offset + pos];
}
- public void deleteCharAt(int pos) {
+ public void deleteCharAt(final int pos) {
if (pos < 0) return;
if (pos >= length) return;
if (pos == length - 1) {
@@ -204,21 +204,21 @@ public final class serverCharBuffer extends Writer {
}
}
- public int indexOf(char b) {
+ public int indexOf(final char b) {
return indexOf(b, 0);
}
- public int indexOf(char[] bs) {
+ public int indexOf(final char[] bs) {
return indexOf(bs, 0);
}
- public int indexOf(char b, int start) {
+ public int indexOf(final char b, final int start) {
if (start >= length) return -1;
for (int i = start; i < length; i++) if (buffer[offset + i] == b) return i;
return -1;
}
- public int indexOf(char[] bs, int start) {
+ public int indexOf(final char[] bs, final int start) {
if (start + bs.length > length) return -1;
loop: for (int i = start; i <= length - bs.length; i++) {
// first test only first char
@@ -235,12 +235,12 @@ public final class serverCharBuffer extends Writer {
return -1;
}
- public int lastIndexOf(char b) {
+ public int lastIndexOf(final char b) {
for (int i = length - 1; i >= 0; i--) if (buffer[offset + i] == b) return i;
return -1;
}
- public boolean startsWith(char[] bs) {
+ public boolean startsWith(final char[] bs) {
if (length < bs.length) return false;
for (int i = 0; i < bs.length; i++) {
if (buffer[offset + i] != bs[i]) return false;
@@ -252,20 +252,20 @@ public final class serverCharBuffer extends Writer {
return getChars(0);
}
- public char[] getChars(int start) {
+ public char[] getChars(final int start) {
return getChars(start, length);
}
- public char[] getChars(int start, int end) {
+ public char[] getChars(final int start, final int end) {
// start is inclusive, end is exclusive
if (end > length) throw new IndexOutOfBoundsException("getBytes: end > length");
if (start > length) throw new IndexOutOfBoundsException("getBytes: start > length");
- char[] tmp = new char[end - start];
+ final char[] tmp = new char[end - start];
System.arraycopy(buffer, offset + start, tmp, 0, end - start);
return tmp;
}
- public serverCharBuffer trim(int start) {
+ public serverCharBuffer trim(final int start) {
// the end value is outside (+1) of the wanted target array
if (start > length) throw new IndexOutOfBoundsException("trim: start > length");
offset = offset + start;
@@ -273,7 +273,7 @@ public final class serverCharBuffer extends Writer {
return this;
}
- public serverCharBuffer trim(int start, int end) {
+ public serverCharBuffer trim(final int start, final int end) {
// the end value is outside (+1) of the wanted target array
if (start > length) throw new IndexOutOfBoundsException("trim: start > length");
if (end > length) throw new IndexOutOfBoundsException("trim: end > length");
@@ -292,7 +292,7 @@ public final class serverCharBuffer extends Writer {
return trim(l, r);
}
- public boolean isWhitespace(boolean includeNonLetterBytes) {
+ public boolean isWhitespace(final boolean includeNonLetterBytes) {
// returns true, if trim() would result in an empty serverByteBuffer
if (includeNonLetterBytes) {
char b;
@@ -306,7 +306,7 @@ public final class serverCharBuffer extends Writer {
return true;
}
- public int whitespaceStart(boolean includeNonLetterBytes) {
+ public int whitespaceStart(final boolean includeNonLetterBytes) {
// returns number of whitespace char at the beginning of text
if (includeNonLetterBytes) {
char b;
@@ -320,7 +320,7 @@ public final class serverCharBuffer extends Writer {
return length;
}
- public int whitespaceEnd(boolean includeNonLetterBytes) {
+ public int whitespaceEnd(final boolean includeNonLetterBytes) {
// returns position of whitespace at the end of text
if (includeNonLetterBytes) {
char b;
@@ -339,7 +339,7 @@ public final class serverCharBuffer extends Writer {
return new String(buffer, offset, length);
}
- public String toString(int left, int rightbound) {
+ public String toString(final int left, final int rightbound) {
return new String(buffer, offset + left, rightbound - left);
}
@@ -348,7 +348,7 @@ public final class serverCharBuffer extends Writer {
int pos = offset;
int start;
String key;
- Properties p = new Properties();
+ final Properties p = new Properties();
// eat up spaces at beginning
while ((pos < length) && (buffer[pos] <= 32)) pos++;
while (pos < length) {
@@ -395,11 +395,11 @@ public final class serverCharBuffer extends Writer {
return p;
}
- public static boolean equals(char[] buffer, char[] pattern) {
+ public static boolean equals(final char[] buffer, final char[] pattern) {
return equals(buffer, 0, pattern);
}
- public static boolean equals(char[] buffer, int offset, char[] pattern) {
+ public static boolean equals(final char[] buffer, final int offset, final char[] pattern) {
// compares two char arrays: true, if pattern appears completely at offset position
if (buffer.length < offset + pattern.length) return false;
for (int i = 0; i < pattern.length; i++) if (buffer[offset + i] != pattern[i]) return false;
@@ -411,20 +411,20 @@ public final class serverCharBuffer extends Writer {
this.offset = 0;
}
- public void reset(int newSize) {
+ public void reset(final int newSize) {
this.resize(newSize);
this.reset();
}
- public void resize(int newSize) {
+ public void resize(final int newSize) {
if(newSize < 0) throw new IllegalArgumentException("Illegal array size: " + newSize);
- char[] v = new char[newSize];
+ final char[] v = new char[newSize];
System.arraycopy(this.buffer,0,v,0,newSize > this.buffer.length ? this.buffer.length : newSize);
this.buffer = v;
}
public char toCharArray()[] {
- char[] newbuf = new char[this.length];
+ final char[] newbuf = new char[this.length];
System.arraycopy(this.buffer, 0, newbuf, 0, this.length);
return newbuf;
}
diff --git a/source/de/anomic/server/serverClassLoader.java b/source/de/anomic/server/serverClassLoader.java
index 13875d786..af314b695 100644
--- a/source/de/anomic/server/serverClassLoader.java
+++ b/source/de/anomic/server/serverClassLoader.java
@@ -41,7 +41,7 @@ public final class serverClassLoader extends ClassLoader {
this.classes = new HashMap<File, Class<?>>();
}
- public serverClassLoader(ClassLoader parent) {
+ public serverClassLoader(final ClassLoader parent) {
super(parent);
classes = new HashMap<File, Class<?>>();
}
@@ -50,7 +50,7 @@ public final class serverClassLoader extends ClassLoader {
return super.getPackages();
}
- public Class<?> loadClass(File classfile) throws ClassNotFoundException {
+ public Class<?> loadClass(final File classfile) throws ClassNotFoundException {
// we consider that the classkey can either be only the name of a class, or a partial or
// complete path to a class file
@@ -60,7 +60,7 @@ public final class serverClassLoader extends ClassLoader {
String classFileName = null;
try {
classFileName = classfile.getCanonicalPath();
- } catch (IOException e) {
+ } catch (final IOException e) {
throw new ClassNotFoundException("Unable to resolve the classfile path");
}
// try to load the class
@@ -95,8 +95,8 @@ public final class serverClassLoader extends ClassLoader {
packge += ".";
}
}
- int p = classFileName.indexOf(".", endPackage);
- String classname = packge + classFileName.substring(endPackage + 1, p);
+ final int p = classFileName.indexOf(".", endPackage);
+ final String classname = packge + classFileName.substring(endPackage + 1, p);
// now that we have the name, we can create the real class file
//classfile = new File(classkey + ".class");
@@ -127,11 +127,11 @@ public final class serverClassLoader extends ClassLoader {
c = this.defineClass(null, b, 0, b.length);
resolveClass(c);
this.classes.put(classfile, c);
- } catch (LinkageError ee) {
+ } catch (final LinkageError ee) {
c = findLoadedClass(classname);
if (c!=null) return c;
serverLog.logSevere("ClassLoader", "class "+ classname +" not defined: "+ ee);
- } catch (IOException ee) {
+ } catch (final IOException ee) {
//System.out.println("INTERNAL ERROR2 in cachedClassLoader: " + ee.getMessage());
throw new ClassNotFoundException(classfile.toString());
}
diff --git a/source/de/anomic/server/serverCodings.java b/source/de/anomic/server/serverCodings.java
index 0ce84dad5..3e318cc62 100644
--- a/source/de/anomic/server/serverCodings.java
+++ b/source/de/anomic/server/serverCodings.java
@@ -44,15 +44,15 @@ import java.util.Map.Entry;
public final class serverCodings {
- public static String encodeHex(long in, int length) {
+ public static String encodeHex(final long in, final int length) {
String s = Long.toHexString(in);
while (s.length() < length) s = "0" + s;
return s;
}
- public static String encodeOctal(byte[] in) {
+ public static String encodeOctal(final byte[] in) {
if (in == null) return "";
- StringBuffer result = new StringBuffer(in.length * 8 / 3);
+ final StringBuffer result = new StringBuffer(in.length * 8 / 3);
for (int i = 0; i < in.length; i++) {
if ((0Xff & in[i]) < 8) result.append('0');
result.append(Integer.toOctalString(0Xff & in[i]));
@@ -60,9 +60,9 @@ public final class serverCodings {
return new String(result);
}
- public static String encodeHex(byte[] in) {
+ public static String encodeHex(final byte[] in) {
if (in == null) return "";
- StringBuffer result = new StringBuffer(in.length * 2);
+ final StringBuffer result = new StringBuffer(in.length * 2);
for (int i = 0; i < in.length; i++) {
if ((0Xff & in[i]) < 16) result.append('0');
result.append(Integer.toHexString(0Xff & in[i]));
@@ -70,86 +70,86 @@ public final class serverCodings {
return new String(result);
}
- public static byte[] decodeHex(String hex) {
- byte[] result = new byte[hex.length() / 2];
+ public static byte[] decodeHex(final String hex) {
+ final byte[] result = new byte[hex.length() / 2];
for (int i = 0; i < result.length; i++) {
result[i] = (byte) (16 * Integer.parseInt(hex.charAt(i * 2) + "", 16) + Integer.parseInt(hex.charAt(i * 2 + 1) + "", 16));
}
return result;
}
- public static String encodeMD5Hex(String key) {
+ public static String encodeMD5Hex(final String key) {
// generate a hex representation from the md5 of a string
return encodeHex(encodeMD5Raw(key));
}
- public static String encodeMD5Hex(File file) {
+ public static String encodeMD5Hex(final File file) {
// generate a hex representation from the md5 of a file
return encodeHex(encodeMD5Raw(file));
}
- public static String encodeMD5Hex(byte[] b) {
+ public static String encodeMD5Hex(final byte[] b) {
// generate a hex representation from the md5 of a byte-array
return encodeHex(encodeMD5Raw(b));
}
- public static byte[] encodeMD5Raw(String key) {
+ public static byte[] encodeMD5Raw(final String key) {
try {
- MessageDigest digest = MessageDigest.getInstance("MD5");
+ final MessageDigest digest = MessageDigest.getInstance("MD5");
digest.reset();
digest.update(key.getBytes());
return digest.digest();
- } catch (java.security.NoSuchAlgorithmException e) {
+ } catch (final java.security.NoSuchAlgorithmException e) {
System.out.println("Internal Error at md5:" + e.getMessage());
}
return null;
}
- public static byte[] encodeMD5Raw(File file) {
+ public static byte[] encodeMD5Raw(final File file) {
try {
- MessageDigest digest = MessageDigest.getInstance("MD5");
+ final MessageDigest digest = MessageDigest.getInstance("MD5");
digest.reset();
- InputStream in = new BufferedInputStream(new FileInputStream(file), 2048);
- byte[] buf = new byte[2048];
+ final InputStream in = new BufferedInputStream(new FileInputStream(file), 2048);
+ final byte[] buf = new byte[2048];
int n;
while ((n = in.read(buf)) > 0) digest.update(buf, 0, n);
in.close();
// now compute the hex-representation of the md5 digest
return digest.digest();
- } catch (java.security.NoSuchAlgorithmException e) {
+ } catch (final java.security.NoSuchAlgorithmException e) {
System.out.println("Internal Error at md5:" + e.getMessage());
- } catch (java.io.FileNotFoundException e) {
+ } catch (final java.io.FileNotFoundException e) {
System.out.println("file not found:" + file.toString());
e.printStackTrace();
- } catch (java.io.IOException e) {
+ } catch (final java.io.IOException e) {
System.out.println("file error with " + file.toString() + ": " + e.getMessage());
}
return null;
}
- private static byte[] encodeMD5Raw(byte[] b) {
+ private static byte[] encodeMD5Raw(final byte[] b) {
try {
- MessageDigest digest = MessageDigest.getInstance("MD5");
+ final MessageDigest digest = MessageDigest.getInstance("MD5");
digest.reset();
- InputStream in = new ByteArrayInputStream(b);
- byte[] buf = new byte[2048];
+ final InputStream in = new ByteArrayInputStream(b);
+ final byte[] buf = new byte[2048];
int n;
while ((n = in.read(buf)) > 0) digest.update(buf, 0, n);
in.close();
// now compute the hex-representation of the md5 digest
return digest.digest();
- } catch (java.security.NoSuchAlgorithmException e) {
+ } catch (final java.security.NoSuchAlgorithmException e) {
System.out.println("Internal Error at md5:" + e.getMessage());
- } catch (java.io.IOException e) {
+ } catch (final java.io.IOException e) {
System.out.println("byte[] error: " + e.getMessage());
}
return null;
}
- public static Properties s2p(String s) {
- Properties p = new Properties();
+ public static Properties s2p(final String s) {
+ final Properties p = new Properties();
int pos;
- StringTokenizer st = new StringTokenizer(s, ",");
+ final StringTokenizer st = new StringTokenizer(s, ",");
String token;
while (st.hasMoreTokens()) {
token = st.nextToken().trim();
@@ -159,14 +159,14 @@ public final class serverCodings {
return p;
}
- public static HashMap<String, String> string2map(String string, String separator) {
+ public static HashMap<String, String> string2map(String string, final String separator) {
// this can be used to parse a Map.toString() into a Map again
if (string == null) return null;
- HashMap<String, String> map = new HashMap<String, String>();
+ final HashMap<String, String> map = new HashMap<String, String>();
int pos;
if ((pos = string.indexOf("{")) >= 0) string = string.substring(pos + 1).trim();
if ((pos = string.lastIndexOf("}")) >= 0) string = string.substring(0, pos).trim();
- StringTokenizer st = new StringTokenizer(string, separator);
+ final StringTokenizer st = new StringTokenizer(string, separator);
String token;
while (st.hasMoreTokens()) {
token = st.nextToken().trim();
@@ -176,7 +176,7 @@ public final class serverCodings {
return map;
}
- public static String map2string(Map<String, String> m, String separator, boolean braces) {
+ public static String map2string(final Map<String, String> m, final String separator, final boolean braces) {
// m must be synchronized to prevent that a ConcurrentModificationException occurs
synchronized (m) {
final StringBuffer buf = new StringBuffer(20 * m.size());
@@ -184,13 +184,13 @@ public final class serverCodings {
int retry = 10;
critical: while (retry > 0) {
try {
- for (Entry<String, String> e: m.entrySet()) {
+ for (final Entry<String, String> e: m.entrySet()) {
buf.append(e.getKey()).append('=');
if (e.getValue() != null) { buf.append(e.getValue()); }
buf.append(separator);
}
break critical; // success
- } catch (ConcurrentModificationException e) {
+ } catch (final ConcurrentModificationException e) {
// retry
buf.setLength(1);
retry--;
@@ -203,24 +203,24 @@ public final class serverCodings {
}
}
- public static Set<String> string2set(String string, String separator) {
+ public static Set<String> string2set(String string, final String separator) {
// this can be used to parse a Map.toString() into a Map again
if (string == null) return null;
- Set<String> set = Collections.synchronizedSet(new HashSet<String>());
+ final Set<String> set = Collections.synchronizedSet(new HashSet<String>());
int pos;
if ((pos = string.indexOf("{")) >= 0) string = string.substring(pos + 1).trim();
if ((pos = string.lastIndexOf("}")) >= 0) string = string.substring(0, pos).trim();
- StringTokenizer st = new StringTokenizer(string, separator);
+ final StringTokenizer st = new StringTokenizer(string, separator);
while (st.hasMoreTokens()) {
set.add(st.nextToken().trim());
}
return set;
}
- public static String set2string(Set<String> s, String separator, boolean braces) {
- StringBuffer buf = new StringBuffer();
+ public static String set2string(final Set<String> s, final String separator, final boolean braces) {
+ final StringBuffer buf = new StringBuffer();
if (braces) buf.append("{");
- Iterator<String> i = s.iterator();
+ final Iterator<String> i = s.iterator();
boolean hasNext = i.hasNext();
while (hasNext) {
buf.append(i.next().toString());
@@ -231,7 +231,7 @@ public final class serverCodings {
return new String(buf);
}
- public static void main(String[] s) {
+ public static void main(final String[] s) {
if (s.length == 0) {
System.out.println("usage: -[ec|dc|es|ds|s2m] <arg>");
System.exit(0);
diff --git a/source/de/anomic/server/serverCore.java b/source/de/anomic/server/serverCore.java
index a37c85d52..8a1bd47a5 100644
--- a/source/de/anomic/server/serverCore.java
+++ b/source/de/anomic/server/serverCore.java
@@ -124,10 +124,10 @@ public final class serverCore extends serverAbstractBusyThread implements server
private SSLSocketFactory sslSocketFactory = null;
private ServerSocket socket; // listener
- private int timeout; // connection time-out of the socket
+ private final int timeout; // connection time-out of the socket
serverHandler handlerPrototype; // the command class (a serverHandler)
- private serverSwitch<?> switchboard; // the command class switchboard
+ private final serverSwitch<?> switchboard; // the command class switchboard
HashMap<String, String> denyHost;
int commandMaxLength;
private int maxBusySessions;
@@ -173,25 +173,25 @@ public final class serverCore extends serverAbstractBusyThread implements server
}
*/
- public static String clientAddress(Socket s) {
- InetAddress uAddr = s.getInetAddress();
+ public static String clientAddress(final Socket s) {
+ final InetAddress uAddr = s.getInetAddress();
if (uAddr.isAnyLocalAddress()) return "localhost";
String cIP = uAddr.getHostAddress();
if (isLocalhost(cIP)) cIP = "localhost";
return cIP;
}
- public static final boolean isLocalhost(String hostname) {
+ public static final boolean isLocalhost(final String hostname) {
return hostname.equals("localhost") || hostname.startsWith("127.") || hostname.startsWith("0:0:0:0:0:0:0:1");
}
// class initializer
public serverCore(
- int timeout,
- boolean blockAttack,
- serverHandler handlerPrototype,
- serverSwitch<?> switchboard,
- int commandMaxLength
+ final int timeout,
+ final boolean blockAttack,
+ final serverHandler handlerPrototype,
+ final serverSwitch<?> switchboard,
+ final int commandMaxLength
) {
this.timeout = timeout;
@@ -241,8 +241,8 @@ public final class serverCore extends serverAbstractBusyThread implements server
// updating the port information
//yacyCore.seedDB.mySeed.put(yacySeed.PORT,Integer.toString(bindAddress.getPort()));
//yacyCore.seedDB.mySeed().put(yacySeed.PORT, extendedPort);
- } catch (Exception e) {
- String errorMsg = "FATAL ERROR: " + e.getMessage() + " - probably root access rights needed. check port number";
+ } catch (final Exception e) {
+ final String errorMsg = "FATAL ERROR: " + e.getMessage() + " - probably root access rights needed. check port number";
this.log.logSevere(errorMsg);
System.out.println(errorMsg);
System.exit(0);
@@ -269,19 +269,19 @@ public final class serverCore extends serverAbstractBusyThread implements server
extendedPortString = extendedPortString.substring(pos+1);
if (bindIP.startsWith("#")) {
- String interfaceName = bindIP.substring(1);
+ final String interfaceName = bindIP.substring(1);
String hostName = null;
this.log.logFine("Trying to determine IP address of interface '" + interfaceName + "'.");
- Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
+ final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
if (interfaces != null) {
while (interfaces.hasMoreElements()) {
- NetworkInterface interf = interfaces.nextElement();
+ final NetworkInterface interf = interfaces.nextElement();
if (interf.getName().equalsIgnoreCase(interfaceName)) {
- Enumeration<InetAddress> addresses = interf.getInetAddresses();
+ final Enumeration<InetAddress> addresses = interf.getInetAddresses();
if (addresses != null) {
while (addresses.hasMoreElements()) {
- InetAddress address = addresses.nextElement();
+ final InetAddress address = addresses.nextElement();
if (address instanceof Inet4Address) {
hostName = address.getHostAddress();
break;
@@ -331,7 +331,7 @@ public final class serverCore extends serverAbstractBusyThread implements server
announceThreadBlockRelease();
- String cIP = clientAddress(controlSocket);
+ final String cIP = clientAddress(controlSocket);
//System.out.println("server bfHosts=" + bfHost.toString());
if (bfHost.get(cIP) != null) {
Integer attempts = bfHost.get(cIP);
@@ -340,7 +340,7 @@ public final class serverCore extends serverAbstractBusyThread implements server
this.log.logWarning("SLOWING DOWN ACCESS FOR BRUTE-FORCE PREVENTION FROM " + cIP + ", ATTEMPT " + attempts.intValue());
// add a delay to make brute-force harder
announceThreadBlockApply();
- try {Thread.sleep(attempts.intValue() /*BFPATCH*/);} catch (InterruptedException e) {}
+ try {Thread.sleep(attempts.intValue() /*BFPATCH*/);} catch (final InterruptedException e) {}
announceThreadBlockRelease();
if ((attempts.intValue() >= 10) && (this.denyHost != null)) {
this.denyHost.put(cIP, "deny");
@@ -377,14 +377,14 @@ public final class serverCore extends serverAbstractBusyThread implements server
//controlSocket.setReceiveBufferSize(1440);
// create session
- Session connection = new Session(sessionThreadGroup, controlSocket, this.timeout);
+ final Session connection = new Session(sessionThreadGroup, controlSocket, this.timeout);
this.busySessions.put(connection, PRESENT);
} else {
this.log.logWarning("ACCESS FROM " + cIP + " DENIED");
}
return true;
- } catch (SocketException e) {
+ } catch (final SocketException e) {
if (this.forceRestart) {
// reinitialize serverCore
init();
@@ -400,12 +400,12 @@ public final class serverCore extends serverAbstractBusyThread implements server
Thread.interrupted();
// shut down all busySessions
- if (this.busySessions != null) for (Session session: this.busySessions.keySet()) {
+ if (this.busySessions != null) for (final Session session: this.busySessions.keySet()) {
try {
session.interrupt();
- } catch (SecurityException e ) {
+ } catch (final SecurityException e ) {
e.printStackTrace();
- } catch (ConcurrentModificationException e) {
+ } catch (final ConcurrentModificationException e) {
e.printStackTrace();
}
}
@@ -414,13 +414,13 @@ public final class serverCore extends serverAbstractBusyThread implements server
try {
this.log.logInfo("Closing server socket ...");
this.socket.close();
- } catch (Exception e) {
+ } catch (final Exception e) {
this.log.logWarning("Unable to close the server socket.");
}
// close all sessions
this.log.logInfo("Closing server sessions ...");
- if (this.busySessions != null) for (Session s: this.busySessions.keySet()) {
+ if (this.busySessions != null) for (final Session s: this.busySessions.keySet()) {
s.interrupt();
s.close();
}
@@ -437,7 +437,7 @@ public final class serverCore extends serverAbstractBusyThread implements server
return this.maxBusySessions;
}
- public void setMaxSessionCount(int count) {
+ public void setMaxSessionCount(final int count) {
this.maxBusySessions = count;
}
@@ -455,7 +455,7 @@ public final class serverCore extends serverAbstractBusyThread implements server
private long start; // startup time
private serverHandler commandObj;
- private HashMap<String, Object> commandObjMethodCache = new HashMap<String, Object>(5);
+ private final HashMap<String, Object> commandObjMethodCache = new HashMap<String, Object>(5);
private String request; // current command line
private int commandCounter; // for logging: number of commands in this session
@@ -470,7 +470,7 @@ public final class serverCore extends serverAbstractBusyThread implements server
public int socketTimeout;
public int hashIndex;
- public Session(ThreadGroup theThreadGroup, Socket controlSocket, int socketTimeout) {
+ public Session(final ThreadGroup theThreadGroup, final Socket controlSocket, final int socketTimeout) {
super(theThreadGroup, controlSocket.getInetAddress().toString() + "@" + Long.toString(System.currentTimeMillis()));
this.socketTimeout = socketTimeout;
this.controlSocket = controlSocket;
@@ -510,7 +510,7 @@ public final class serverCore extends serverAbstractBusyThread implements server
return this.userPort;
}
- public void setStopped(boolean stopped) {
+ public void setStopped(final boolean stopped) {
this.stopped = stopped;
}
@@ -526,7 +526,7 @@ public final class serverCore extends serverAbstractBusyThread implements server
this.controlSocket.close();
serverCore.this.log.logInfo("Closing main socket of thread '" + this.getName() + "'");
}
- } catch (Exception e) {}
+ } catch (final Exception e) {}
}
}
@@ -538,7 +538,7 @@ public final class serverCore extends serverAbstractBusyThread implements server
return System.currentTimeMillis() - this.start;
}
- public void setIdentity(String id) {
+ public void setIdentity(final String id) {
this.identity = id;
}
@@ -548,14 +548,14 @@ public final class serverCore extends serverAbstractBusyThread implements server
}
*/
- public void log(boolean outgoing, String request) {
+ public void log(final boolean outgoing, final String request) {
serverCore.this.log.logFine(this.userAddress.getHostAddress() + "/" + this.identity + " " +
"[" + ((busySessions == null)? -1 : busySessions.size()) + ", " + this.commandCounter +
((outgoing) ? "] > " : "] < ") +
request);
}
- public void writeLine(String messg) throws IOException {
+ public void writeLine(final String messg) throws IOException {
send(this.out, messg + CRLF_STRING);
log(true, messg);
}
@@ -570,7 +570,7 @@ public final class serverCore extends serverAbstractBusyThread implements server
* @return the next requestline as string
*/
public String readLineAsString() {
- byte[] l = readLine();
+ final byte[] l = readLine();
return (l == null) ? null: new String(l);
}
@@ -616,7 +616,7 @@ public final class serverCore extends serverAbstractBusyThread implements server
// listen for commands
listen();
- } catch (Exception e) {
+ } catch (final Exception e) {
System.err.println("ERROR: (internal) " + e);
} finally {
try {
@@ -636,13 +636,13 @@ public final class serverCore extends serverAbstractBusyThread implements server
this.out.close();
// sleep for a while
- try {Thread.sleep(1000);} catch (InterruptedException e) {}
+ try {Thread.sleep(1000);} catch (final InterruptedException e) {}
// close everything
this.controlSocket.close();
this.controlSocket = null;
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
if (busySessions != null) busySessions.remove(this);
@@ -665,7 +665,7 @@ public final class serverCore extends serverAbstractBusyThread implements server
boolean terminate = false;
String reqCmd;
String reqProtocol = "HTTP";
- Object[] stringParameter = new String[1];
+ final Object[] stringParameter = new String[1];
while ((this.in != null) && ((requestBytes = readLine()) != null)) {
this.setName("Session_" + this.userAddress.getHostAddress() +
":" + this.controlSocket.getPort() +
@@ -680,7 +680,7 @@ public final class serverCore extends serverAbstractBusyThread implements server
if (this.request.trim().length() == 0) this.request = "EMPTY";
// getting the rest of the request parameters
- int pos = this.request.indexOf(' ');
+ final int pos = this.request.indexOf(' ');
if (pos < 0) {
reqCmd = this.request.trim().toUpperCase();
stringParameter[0] = "";
@@ -728,7 +728,7 @@ public final class serverCore extends serverAbstractBusyThread implements server
try {
commandMethod = this.commandObj.getClass().getMethod(reqCmd, stringType);
this.commandObjMethodCache.put(reqProtocol + "_" + reqCmd, commandMethod);
- } catch (NoSuchMethodException noMethod) {
+ } catch (final NoSuchMethodException noMethod) {
commandMethod = this.commandObj.getClass().getMethod("UNKNOWN", stringType);
stringParameter[0] = this.request.trim();
}
@@ -766,11 +766,11 @@ public final class serverCore extends serverAbstractBusyThread implements server
}
if (terminate) break;
- } catch (InvocationTargetException ite) {
+ } catch (final InvocationTargetException ite) {
System.out.println("ERROR A " + this.userAddress.getHostAddress());
// we extract a target exception and let the thread survive
writeLine(this.commandObj.error(ite.getTargetException()));
- } catch (NoSuchMethodException nsme) {
+ } catch (final NoSuchMethodException nsme) {
System.out.println("ERROR B " + this.userAddress.getHostAddress());
if (!this.userAddress.isSiteLocalAddress()) {
if (serverCore.this.denyHost != null) {
@@ -781,15 +781,15 @@ public final class serverCore extends serverAbstractBusyThread implements server
// the client requested a command that does not exist
//Object[] errorParameter = { nsme };
//writeLine((String) error.invoke(this.cmdObject, errorParameter));
- } catch (IllegalAccessException iae) {
+ } catch (final IllegalAccessException iae) {
System.out.println("ERROR C " + this.userAddress.getHostAddress());
// wrong parameters: this an only be an internal problem
writeLine(this.commandObj.error(iae));
- } catch (java.lang.ClassCastException e) {
+ } catch (final java.lang.ClassCastException e) {
System.out.println("ERROR D " + this.userAddress.getHostAddress());
// ??
writeLine(this.commandObj.error(e));
- } catch (Exception e) {
+ } catch (final Exception e) {
System.out.println("ERROR E " + this.userAddress.getHostAddress());
// whatever happens: the thread has to survive!
writeLine("UNKNOWN REASON:" + this.commandObj.error(e));
@@ -798,7 +798,7 @@ public final class serverCore extends serverAbstractBusyThread implements server
} /* catch (java.lang.ClassNotFoundException e) {
System.out.println("Internal error: Wrapper class not found: " + e.getMessage());
System.exit(0);
- } */ catch (java.io.IOException e) {
+ } */ catch (final java.io.IOException e) {
// connection interruption: more or less normal
}
//announceMoreExecTime(System.currentTimeMillis() - this.start);
@@ -825,10 +825,10 @@ public final class serverCore extends serverAbstractBusyThread implements server
* @return A byte array representing one line of the input or
* <code>null</null> if EOS reached.
*/
- public static byte[] receive(PushbackInputStream pbis, int maxSize, boolean logerr) {
+ public static byte[] receive(final PushbackInputStream pbis, final int maxSize, final boolean logerr) {
// reuse an existing linebuffer
- serverByteBuffer readLineBuffer = new serverByteBuffer(80);
+ final serverByteBuffer readLineBuffer = new serverByteBuffer(80);
int bufferSize = 0, b = 0;
try {
@@ -861,31 +861,31 @@ public final class serverCore extends serverAbstractBusyThread implements server
// EOS
if (bufferSize == 0 && b == -1) return null;
return readLineBuffer.getBytes();
- } catch (ClosedByInterruptException e) {
+ } catch (final ClosedByInterruptException e) {
if (logerr) serverLog.logSevere("SERVER", "receive interrupted - timeout");
return null;
- } catch (IOException e) {
+ } catch (final IOException e) {
if (logerr) serverLog.logSevere("SERVER", "receive interrupted - exception 2 = " + e.getMessage());
return null;
}
}
- public static void send(OutputStream os, String buf) throws IOException {
+ public static void send(final OutputStream os, final String buf) throws IOException {
os.write(buf.getBytes());
// TODO make sure there was no reason to add this additional newline
//os.write(CRLF);
os.flush();
}
- public static void send(OutputStream os, byte[] buf) throws IOException {
+ public static void send(final OutputStream os, final byte[] buf) throws IOException {
os.write(buf);
os.write(CRLF);
os.flush();
}
- public static String send(OutputStream os, InputStream is) throws IOException {
- int bufferSize = is.available();
- byte[] buffer = new byte[((bufferSize < 1) || (bufferSize > 4096)) ? 4096 : bufferSize];
+ public static String send(final OutputStream os, final InputStream is) throws IOException {
+ final int bufferSize = is.available();
+ final byte[] buffer = new byte[((bufferSize < 1) || (bufferSize > 4096)) ? 4096 : bufferSize];
int l;
while ((l = is.read(buffer)) > 0) {os.write(buffer, 0, l);}
os.write(CRLF);
@@ -898,13 +898,13 @@ public final class serverCore extends serverAbstractBusyThread implements server
}
public static final void checkInterruption() throws InterruptedException {
- Thread currentThread = Thread.currentThread();
+ final Thread currentThread = Thread.currentThread();
if (currentThread.isInterrupted()) throw new InterruptedException();
if ((currentThread instanceof serverCore.Session) && ((serverCore.Session)currentThread).isStopped()) throw new InterruptedException();
}
- public void reconnect(int delay) {
- Thread restart = new Restarter(delay);
+ public void reconnect(final int delay) {
+ final Thread restart = new Restarter(delay);
restart.start();
}
@@ -912,14 +912,14 @@ public final class serverCore extends serverAbstractBusyThread implements server
public class Restarter extends Thread {
public serverCore theServerCore = null;
public int delay = 5000;
- public Restarter(int delay) {
+ public Restarter(final int delay) {
this.delay = delay;
}
public void run() {
// waiting for a while
try {
Thread.sleep(delay);
- } catch (InterruptedException e) {
+ } catch (final InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
@@ -938,19 +938,19 @@ public final class serverCore extends serverAbstractBusyThread implements server
String keyStoreFileName = this.switchboard.getConfig("keyStore", "").trim();
// getting the keystore pwd
- String keyStorePwd = this.switchboard.getConfig("keyStorePassword", "").trim();
+ final String keyStorePwd = this.switchboard.getConfig("keyStorePassword", "").trim();
// take a look if we have something to import
- String pkcs12ImportFile = this.switchboard.getConfig("pkcs12ImportFile", "").trim();
+ final String pkcs12ImportFile = this.switchboard.getConfig("pkcs12ImportFile", "").trim();
if (pkcs12ImportFile.length() > 0) {
this.log.logInfo("Import certificates from import file '" + pkcs12ImportFile + "'.");
try {
// getting the password
- String pkcs12ImportPwd = this.switchboard.getConfig("pkcs12ImportPwd", "").trim();
+ final String pkcs12ImportPwd = this.switchboard.getConfig("pkcs12ImportPwd", "").trim();
// creating tool to import cert
- PKCS12Tool pkcsTool = new PKCS12Tool(pkcs12ImportFile,pkcs12ImportPwd);
+ final PKCS12Tool pkcsTool = new PKCS12Tool(pkcs12ImportFile,pkcs12ImportPwd);
// creating a new keystore file
if (keyStoreFileName.length() == 0) {
@@ -958,9 +958,9 @@ public final class serverCore extends serverAbstractBusyThread implements server
keyStoreFileName = "DATA/SETTINGS/myPeerKeystore";
// creating an empty java keystore
- KeyStore ks = KeyStore.getInstance("JKS");
+ final KeyStore ks = KeyStore.getInstance("JKS");
ks.load(null,keyStorePwd.toCharArray());
- FileOutputStream ksOut = new FileOutputStream(keyStoreFileName);
+ final FileOutputStream ksOut = new FileOutputStream(keyStoreFileName);
ks.store(ksOut, keyStorePwd.toCharArray());
ksOut.close();
@@ -978,7 +978,7 @@ public final class serverCore extends serverAbstractBusyThread implements server
// deleting original import file
// TODO: should we do this
- } catch (Exception e) {
+ } catch (final Exception e) {
this.log.logSevere("Unable to import certificate from import file '" + pkcs12ImportFile + "'.",e);
}
} else if (keyStoreFileName.length() == 0) return null;
@@ -990,28 +990,28 @@ public final class serverCore extends serverAbstractBusyThread implements server
// creating a new keystore instance of type (java key store)
this.log.logFine("Initializing keystore ...");
- KeyStore ks = KeyStore.getInstance("JKS");
+ final KeyStore ks = KeyStore.getInstance("JKS");
// loading keystore data from file
this.log.logFine("Loading keystore file " + keyStoreFileName);
- FileInputStream stream = new FileInputStream(keyStoreFileName);
+ final FileInputStream stream = new FileInputStream(keyStoreFileName);
ks.load(stream, keyStorePwd.toCharArray());
// creating a keystore factory
this.log.logFine("Initializing key manager factory ...");
- KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
+ final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks,keyStorePwd.toCharArray());
// initializing the ssl context
this.log.logFine("Initializing SSL context ...");
- SSLContext sslcontext = SSLContext.getInstance("TLS");
+ final SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(kmf.getKeyManagers(), null, null);
- SSLSocketFactory factory = sslcontext.getSocketFactory();
+ final SSLSocketFactory factory = sslcontext.getSocketFactory();
this.log.logInfo("SSL support initialized successfully");
return factory;
- } catch (Exception e) {
- String errorMsg = "FATAL ERROR: Unable to initialize the SSL Socket factory. " + e.getMessage();
+ } catch (final Exception e) {
+ final String errorMsg = "FATAL ERROR: Unable to initialize the SSL Socket factory. " + e.getMessage();
this.log.logSevere(errorMsg);
System.out.println(errorMsg);
System.exit(0);
@@ -1019,7 +1019,7 @@ public final class serverCore extends serverAbstractBusyThread implements server
}
}
- public Socket negotiateSSL(Socket sock) throws Exception {
+ public Socket negotiateSSL(final Socket sock) throws Exception {
SSLSocket sslsock;
@@ -1033,7 +1033,7 @@ public final class serverCore extends serverAbstractBusyThread implements server
sslsock.addHandshakeCompletedListener(
new HandshakeCompletedListener() {
public void handshakeCompleted(
- HandshakeCompletedEvent event) {
+ final HandshakeCompletedEvent event) {
System.out.println("Handshake finished!");
System.out.println(
"\t CipherSuite:" + event.getCipherSuite());
@@ -1046,7 +1046,7 @@ public final class serverCore extends serverAbstractBusyThread implements server
);
sslsock.setUseClientMode(false);
- String[] suites = sslsock.getSupportedCipherSuites();
+ final String[] suites = sslsock.getSupportedCipherSuites();
sslsock.setEnabledCipherSuites(suites);
// start handshake
sslsock.startHandshake();
@@ -1054,7 +1054,7 @@ public final class serverCore extends serverAbstractBusyThread implements server
//String cipherSuite = sslsock.getSession().getCipherSuite();
return sslsock;
- } catch (Exception e) {
+ } catch (final Exception e) {
throw e;
}
}
diff --git a/source/de/anomic/server/serverCoreSocket.java b/source/de/anomic/server/serverCoreSocket.java
index 900fdf1af..60302edac 100644
--- a/source/de/anomic/server/serverCoreSocket.java
+++ b/source/de/anomic/server/serverCoreSocket.java
@@ -40,7 +40,7 @@ public class serverCoreSocket extends Socket {
private boolean isSSL = false;
private String sslType = null;
- public serverCoreSocket(Socket sock) throws IOException {
+ public serverCoreSocket(final Socket sock) throws IOException {
this.sock = sock;
// determine the socket type
@@ -56,10 +56,10 @@ public class serverCoreSocket extends Socket {
}
private void detectSSL() throws IOException {
- InputStream in = getInputStream();
+ final InputStream in = getInputStream();
// read the first 5 bytes to determine the protocol type
- byte[] preRead = new byte[5];
+ final byte[] preRead = new byte[5];
int read, count = 0;
while ((count < preRead.length) && ((read = in.read()) != -1)) {
preRead[count] = (byte) read;
@@ -79,7 +79,7 @@ public class serverCoreSocket extends Socket {
// SSL messages have two preceding bytes
// byte nr 3 specifies the handshake type
// 3 means "ClientHello"
- int handshakeType = preRead[2] & 0x00FF;
+ final int handshakeType = preRead[2] & 0x00FF;
if (handshakeType == 1) this.isSSL = true;
idx = 3;
}
@@ -183,7 +183,7 @@ public class serverCoreSocket extends Socket {
return this.sock.isOutputShutdown();
}
- public synchronized void setSoTimeout(int timeout) throws SocketException {
+ public synchronized void setSoTimeout(final int timeout) throws SocketException {
this.sock.setSoTimeout(timeout);
}
diff --git a/source/de/anomic/server/serverDate.java b/source/de/anomic/server/serverDate.java
index 93d685fc9..7e3b49e29 100644
--- a/source/de/anomic/server/serverDate.java
+++ b/source/de/anomic/server/serverDate.java
@@ -95,7 +95,7 @@ public final class serverDate {
CAL_GMT.setTimeInMillis(0);
for (int i = 0; i < serverDate.FORMATS_HTTP.length; i++) {
- SimpleDateFormat f = serverDate.FORMATS_HTTP[i];
+ final SimpleDateFormat f = serverDate.FORMATS_HTTP[i];
f.setTimeZone(TZ_GMT);
f.set2DigitYearStart(CAL_GMT.getTime());
}
@@ -119,7 +119,7 @@ public final class serverDate {
for(int i = 0; i < FORMATS_HTTP.length; i++) {
try {
return parse(FORMATS_HTTP[i], s);
- } catch (ParseException e) {
+ } catch (final ParseException e) {
// on ParseException try again with next parser
}
}
@@ -137,7 +137,7 @@ public final class serverDate {
* @param date The Date instance to transform.
* @return A fixed width (20 chars) ISO8601 date String.
*/
- public static String formatISO8601(Date date){
+ public static String formatISO8601(final Date date){
return format(FORMAT_ISO8601, date);
}
@@ -161,13 +161,13 @@ public final class serverDate {
* @return
* @throws ParseException
*/
- public static Date parseISO8601(String s) throws ParseException {
- Calendar cal = Calendar.getInstance(TZ_GMT, Locale.US);
+ public static Date parseISO8601(final String s) throws ParseException {
+ final Calendar cal = Calendar.getInstance(TZ_GMT, Locale.US);
cal.clear();
// split 2007-12-19T10:20:30.789+0500 into its parts
// correct: yyyy['-'MM['-'dd['T'HH':'MM[':'ss['.'SSS]]('Z'|ZZZZZ)]]]
- StringTokenizer t = new StringTokenizer(s, "-T:.Z+", true);
+ final StringTokenizer t = new StringTokenizer(s, "-T:.Z+", true);
if (s == null || t.countTokens() == 0)
throw new ParseException("parseISO8601: Cannot parse '" + s + "'", 0);
@@ -190,7 +190,7 @@ public final class serverDate {
// timezone token, too.
// hour
if (t.nextToken().equals("T")) {
- int hour = Integer.parseInt(t.nextToken());
+ final int hour = Integer.parseInt(t.nextToken());
// no error, got hours
int min = 0;
int sec = 0;
@@ -234,9 +234,9 @@ public final class serverDate {
cal.set(Calendar.SECOND, sec);
cal.set(Calendar.MILLISECOND, msec);
}
- } catch (NoSuchElementException e) {
+ } catch (final NoSuchElementException e) {
// ignore this as it is perfectly fine to have non-complete date in this format
- } catch (Exception e) {
+ } catch (final Exception e) {
// catch all Exceptions and return what we parsed so far
serverLog.logInfo("SERVER", "parseISO8601: DATE ERROR with: '" + s + "' got so far: '" + cal.toString());
}
@@ -264,7 +264,7 @@ public final class serverDate {
* @see #formatShortDay()
* @param date the Date to transform
*/
- public static String formatShortDay(Date date) {
+ public static String formatShortDay(final Date date) {
return format(FORMAT_SHORT_DAY, date);
}
@@ -276,7 +276,7 @@ public final class serverDate {
* @param date the Date to transform
* @param tz a TimeZone the resulting date String should be aligned to.
*/
- public static String formatShortDay(Date date, TimeZone tz) {
+ public static String formatShortDay(final Date date, final TimeZone tz) {
return format(FORMAT_SHORT_DAY, date, tz);
}
@@ -287,7 +287,7 @@ public final class serverDate {
* @throws ParseException The exception is thrown if an error occured during while parsing
* the String.
*/
- public static Date parseShortDay(String timeString) throws ParseException {
+ public static Date parseShortDay(final String timeString) throws ParseException {
return parse(FORMAT_SHORT_DAY, timeString);
}
@@ -303,14 +303,14 @@ public final class serverDate {
/**
* Identical to {@link #formatShortDay(Date)}, but for short second format.
*/
- public static String formatShortSecond(Date date) {
+ public static String formatShortSecond(final Date date) {
return format(FORMAT_SHORT_SECOND, date);
}
/**
* Identical to {@link #formatShortDay(Date, TimeZone)}, but for short second format.
*/
- public static String formatShortSecond(Date date, TimeZone tz) {
+ public static String formatShortSecond(final Date date, final TimeZone tz) {
return format(FORMAT_SHORT_SECOND, date, tz);
}
@@ -320,7 +320,7 @@ public final class serverDate {
* plus a 6 digit day time value, like "20071218233510". The String should be in GMT/UTC to
* get a correct Date.
*/
- public static Date parseShortSecond(String timeString) throws ParseException {
+ public static Date parseShortSecond(final String timeString) throws ParseException {
return parse(FORMAT_SHORT_SECOND, timeString);
}
@@ -328,7 +328,7 @@ public final class serverDate {
* Like {@link #parseShortSecond(String)} using additional timezone information provided in an
* offset String, like "+0100" for CET.
*/
- public static Date parseShortSecond(String remoteTimeString, String remoteUTCOffset) {
+ public static Date parseShortSecond(final String remoteTimeString, final String remoteUTCOffset) {
// FIXME: This method returns an incorrect date, check callers!
// ex: de.anomic.server.serverDate.parseShortSecond("20070101120000", "+0200").toGMTString()
// => 1 Jan 2007 13:00:00 GMT
@@ -336,10 +336,10 @@ public final class serverDate {
if (remoteUTCOffset == null || remoteUTCOffset.length() == 0) { return new Date(); }
try {
return new Date(parse(FORMAT_SHORT_SECOND, remoteTimeString).getTime() - serverDate.UTCDiff() + serverDate.UTCDiff(remoteUTCOffset));
- } catch (java.text.ParseException e) {
+ } catch (final java.text.ParseException e) {
serverLog.logFinest("parseUniversalDate", e.getMessage() + ", remoteTimeString=[" + remoteTimeString + "]");
return new Date();
- } catch (java.lang.NumberFormatException e) {
+ } catch (final java.lang.NumberFormatException e) {
serverLog.logFinest("parseUniversalDate", e.getMessage() + ", remoteTimeString=[" + remoteTimeString + "]");
return new Date();
}
@@ -350,15 +350,15 @@ public final class serverDate {
* Format a time inteval in milliseconds into a String of the form
* X 'day'['s'] HH':'mm
*/
- public static String formatInterval(long millis) {
+ public static String formatInterval(final long millis) {
try {
- long mins = millis / 60000;
+ final long mins = millis / 60000;
- StringBuffer uptime = new StringBuffer();
+ final StringBuffer uptime = new StringBuffer();
- int uptimeDays = (int) (Math.floor(mins/1440));
- int uptimeHours = (int) (Math.floor(mins/60)%24);
- int uptimeMins = (int) mins%60;
+ final int uptimeDays = (int) (Math.floor(mins/1440));
+ final int uptimeHours = (int) (Math.floor(mins/60)%24);
+ final int uptimeMins = (int) mins%60;
uptime.append(uptimeDays)
.append(((uptimeDays == 1)?" day ":" days "))
@@ -369,14 +369,14 @@ public final class serverDate {
.append(uptimeMins);
return uptime.toString();
- } catch (Exception e) {
+ } catch (final Exception e) {
return "unknown";
}
}
/** called by all public format...(..., TimeZone) methods */
- private static String format(SimpleDateFormat format, Date date, TimeZone tz) {
- TimeZone bakTZ = format.getTimeZone();
+ private static String format(final SimpleDateFormat format, final Date date, final TimeZone tz) {
+ final TimeZone bakTZ = format.getTimeZone();
String result;
synchronized (format) {
@@ -389,14 +389,14 @@ public final class serverDate {
}
/** called by all public format...(...) methods */
- private static String format(SimpleDateFormat format, Date date) {
+ private static String format(final SimpleDateFormat format, final Date date) {
synchronized (format) {
return format.format(date);
}
}
/** calles by all public parse...(...) methods */
- private static Date parse(SimpleDateFormat format, String dateString) throws ParseException {
+ private static Date parse(final SimpleDateFormat format, final String dateString) throws ParseException {
synchronized (format) {
return format.parse(dateString);
}
@@ -455,9 +455,9 @@ public final class serverDate {
// since there are some places on earth where there is a time shift of half an hour
// we need too show also the minutes of the time shift
// Examples: http://www.timeanddate.com/library/abbreviations/timezones/
- long offsetHours = UTCDiff();
- int om = Math.abs((int) (offsetHours / minuteMillis)) % 60;
- int oh = Math.abs((int) (offsetHours / hourMillis));
+ final long offsetHours = UTCDiff();
+ final int om = Math.abs((int) (offsetHours / minuteMillis)) % 60;
+ final int oh = Math.abs((int) (offsetHours / hourMillis));
String diff = Integer.toString(om);
if (diff.length() < 2) diff = "0" + diff;
diff = Integer.toString(oh) + diff;
@@ -473,19 +473,19 @@ public final class serverDate {
// DST_OFFSET is dependent on the time of the Calendar, so it has to be updated
// to get the correct current offset
thisCalendar.setTimeInMillis(System.currentTimeMillis());
- long zoneOffsetHours = thisCalendar.get(Calendar.ZONE_OFFSET);
- long DSTOffsetHours = thisCalendar.get(Calendar.DST_OFFSET);
+ final long zoneOffsetHours = thisCalendar.get(Calendar.ZONE_OFFSET);
+ final long DSTOffsetHours = thisCalendar.get(Calendar.DST_OFFSET);
return zoneOffsetHours + DSTOffsetHours;
}
- public static long UTCDiff(String diffString) {
+ public static long UTCDiff(final String diffString) {
if (diffString.length() != 5) throw new IllegalArgumentException("UTC String malformed (wrong size):" + diffString);
boolean ahead = true;
if (diffString.charAt(0) == '+') ahead = true;
else if (diffString.charAt(0) == '-') ahead = false;
else throw new IllegalArgumentException("UTC String malformed (wrong sign):" + diffString);
- long oh = Long.parseLong(diffString.substring(1, 3));
- long om = Long.parseLong(diffString.substring(3));
+ final long oh = Long.parseLong(diffString.substring(1, 3));
+ final long om = Long.parseLong(diffString.substring(3));
return ((ahead) ? (long) 1 : (long) -1) * (oh * hourMillis + om * minuteMillis);
}
@@ -498,7 +498,7 @@ public final class serverDate {
this(System.currentTimeMillis());
}
- public serverDate(long utime) {
+ public serverDate(final long utime) {
// set the time as the difference, measured in milliseconds,
// between the current time and midnight, January 1, 1970 UTC/GMT
this.utime = utime;
@@ -528,36 +528,36 @@ public final class serverDate {
this.dow = (int) (((utime / dayMillis) + 3) % 7);
}
- public serverDate(String datestring) throws java.text.ParseException {
+ public serverDate(final String datestring) throws java.text.ParseException {
// parse a date string; othervise throw a java.text.ParseException
if ((datestring.length() == 14) || (datestring.length() == 17)) {
// parse a ShortString
- try {years = Integer.parseInt(datestring.substring(0, 4)) - 1970;} catch (NumberFormatException e) {
+ try {years = Integer.parseInt(datestring.substring(0, 4)) - 1970;} catch (final NumberFormatException e) {
throw new java.text.ParseException("serverDate '" + datestring + "' wrong year", 0);
}
if (years < 0) throw new java.text.ParseException("serverDate '" + datestring + "' wrong year", 0);
- try {months = Integer.parseInt(datestring.substring(4, 6)) - 1;} catch (NumberFormatException e) {
+ try {months = Integer.parseInt(datestring.substring(4, 6)) - 1;} catch (final NumberFormatException e) {
throw new java.text.ParseException("serverDate '" + datestring + "' wrong month", 4);
}
if ((months < 0) || (months > 11)) throw new java.text.ParseException("serverDate '" + datestring + "' wrong month", 4);
- try {days = Integer.parseInt(datestring.substring(6, 8)) - 1;} catch (NumberFormatException e) {
+ try {days = Integer.parseInt(datestring.substring(6, 8)) - 1;} catch (final NumberFormatException e) {
throw new java.text.ParseException("serverDate '" + datestring + "' wrong day", 6);
}
if ((days < 0) || (days > 30)) throw new java.text.ParseException("serverDate '" + datestring + "' wrong day", 6);
- try {hours = Integer.parseInt(datestring.substring(8, 10));} catch (NumberFormatException e) {
+ try {hours = Integer.parseInt(datestring.substring(8, 10));} catch (final NumberFormatException e) {
throw new java.text.ParseException("serverDate '" + datestring + "' wrong hour", 8);
}
if ((hours < 0) || (hours > 23)) throw new java.text.ParseException("serverDate '" + datestring + "' wrong hour", 8);
- try {minutes = Integer.parseInt(datestring.substring(10, 12));} catch (NumberFormatException e) {
+ try {minutes = Integer.parseInt(datestring.substring(10, 12));} catch (final NumberFormatException e) {
throw new java.text.ParseException("serverDate '" + datestring + "' wrong minute", 10);
}
if ((minutes < 0) || (minutes > 59)) throw new java.text.ParseException("serverDate '" + datestring + "' wrong minute", 10);
- try {seconds = Integer.parseInt(datestring.substring(12, 14));} catch (NumberFormatException e) {
+ try {seconds = Integer.parseInt(datestring.substring(12, 14));} catch (final NumberFormatException e) {
throw new java.text.ParseException("serverDate '" + datestring + "' wrong second", 12);
}
if ((seconds < 0) || (seconds > 59)) throw new java.text.ParseException("serverDate '" + datestring + "' wrong second", 12);
if (datestring.length() == 17) {
- try {milliseconds = Integer.parseInt(datestring.substring(14, 17));} catch (NumberFormatException e) {
+ try {milliseconds = Integer.parseInt(datestring.substring(14, 17));} catch (final NumberFormatException e) {
throw new java.text.ParseException("serverDate '" + datestring + "' wrong millisecond", 14);
}
} else {
@@ -578,9 +578,9 @@ public final class serverDate {
", day-of-week=" + wkday[dow];
}
- public String toShortString(boolean millis) {
+ public String toShortString(final boolean millis) {
// returns a "yyyyMMddHHmmssSSS"
- byte[] result = new byte[(millis) ? 17 : 14];
+ final byte[] result = new byte[(millis) ? 17 : 14];
int x = 1970 + years;
result[ 0] = (byte) (48 + (x / 1000)); x = x % 1000;
result[ 1] = (byte) (48 + (x / 100)); x = x % 100;
@@ -607,13 +607,13 @@ public final class serverDate {
return new String(result);
}
- public static long remainingTime(long start, long due, long minimum) {
+ public static long remainingTime(final long start, final long due, final long minimum) {
if (due < 0) return -1;
- long r = due + start - System.currentTimeMillis();
+ final long r = due + start - System.currentTimeMillis();
if (r <= 0) return minimum; else return r;
}
- public static void main(String[] args) {
+ public static void main(final String[] args) {
//System.out.println("kelondroDate is (" + new kelondroDate().toString() + ")");
System.out.println("offset is " + (UTCDiff()/1000/60/60) + " hours, javaDate is " + new Date() + ", correctedDate is " + new Date(correctedUTCTime()));
System.out.println("serverDate : " + new serverDate().toShortString(false));
@@ -628,14 +628,14 @@ public final class serverDate {
try {
System.out.println("serverDate re-parse short: " + new serverDate(new serverDate().toShortString(false)).toShortString(true));
System.out.println("serverDate re-parse long : " + new serverDate(new serverDate().toShortString(true)).toShortString(true));
- } catch (java.text.ParseException e) {
+ } catch (final java.text.ParseException e) {
System.out.println("Parse Exception: " + e.getMessage() + ", pos " + e.getErrorOffset());
}
//String testresult;
- int cycles = 10000;
+ final int cycles = 10000;
long start;
- String[] testresult = new String[10000];
+ final String[] testresult = new String[10000];
start = System.currentTimeMillis();
for (int i = 0; i < cycles; i++) testresult[i] = new serverDate().toShortString(false);
System.out.println("time for " + cycles + " calls to serverDate:" + (System.currentTimeMillis() - start) + " milliseconds");
diff --git a/source/de/anomic/server/serverDomains.java b/source/de/anomic/server/serverDomains.java
index 4f6ba0d96..70f05d9f2 100644
--- a/source/de/anomic/server/serverDomains.java
+++ b/source/de/anomic/server/serverDomains.java
@@ -363,11 +363,11 @@ public class serverDomains {
private static HashMap<String, Integer> TLDID = new HashMap<String, Integer>();
//private static HashMap<String, String> TLDName = new HashMap<String, String>();
- private static void insertTLDProps(String[] TLDList, int id) {
+ private static void insertTLDProps(final String[] TLDList, final int id) {
int p;
String tld;
//String name;
- Integer ID = new Integer(id);
+ final Integer ID = new Integer(id);
for (int i = 0; i < TLDList.length; i++) {
p = TLDList[i].indexOf('=');
if (p > 0) {
@@ -408,7 +408,7 @@ public class serverDomains {
* @param longTime Time in miliseconds since 01/01/1970 00:00 GMT
* @return int seconds since startTime
*/
- private static int intTime(long longTime) {
+ private static int intTime(final long longTime) {
return (int) Math.max(0, ((longTime - startTime) / 1000));
}
@@ -423,7 +423,7 @@ public class serverDomains {
host = host.toLowerCase().trim();
// trying to resolve host by doing a name cache lookup
- InetAddress ip = nameCacheHit.get(host);
+ final InetAddress ip = nameCacheHit.get(host);
if (ip != null) return ip;
if (nameCacheMiss.contains(host)) return null;
@@ -449,7 +449,7 @@ public class serverDomains {
) {
doCaching = false;
} else {
- Iterator<String> noCachingPatternIter = nameCacheNoCachingPatterns.iterator();
+ final Iterator<String> noCachingPatternIter = nameCacheNoCachingPatterns.iterator();
String nextPattern;
while (noCachingPatternIter.hasNext()) {
nextPattern = noCachingPatternIter.next();
@@ -473,7 +473,7 @@ public class serverDomains {
}
}
return ip;
- } catch (UnknownHostException e) {
+ } catch (final UnknownHostException e) {
// remove old entries
flushMissNameCache();
@@ -511,7 +511,7 @@ public class serverDomains {
* Removes old entries from the dns hit cache
*/
public static void flushHitNameCache() {
- int cutofftime = intTime(System.currentTimeMillis()) - maxNameCacheHitAge;
+ final int cutofftime = intTime(System.currentTimeMillis()) - maxNameCacheHitAge;
String k;
while ((nameCacheHitAges.size() > maxNameCacheHitSize) || (nameCacheHitAges.getMinScore() < cutofftime)) {
k = nameCacheHitAges.getMinObject();
@@ -525,7 +525,7 @@ public class serverDomains {
* Removes old entries from the dns miss cache
*/
public static void flushMissNameCache() {
- int cutofftime = intTime(System.currentTimeMillis()) - maxNameCacheMissAge;
+ final int cutofftime = intTime(System.currentTimeMillis()) - maxNameCacheMissAge;
String k;
while ((nameCacheMissAges.size() > maxNameCacheMissSize) || (nameCacheMissAges.getMinScore() < cutofftime)) {
k = nameCacheMissAges.getMinObject();
@@ -539,18 +539,18 @@ public class serverDomains {
static {
try {
localAddresses = InetAddress.getAllByName(InetAddress.getLocalHost().getHostName());
- } catch (UnknownHostException e) {
+ } catch (final UnknownHostException e) {
localAddresses = new InetAddress[0];
}
}
- public static int getDomainID(String host) {
- int p = host.lastIndexOf('.');
+ public static int getDomainID(final String host) {
+ final int p = host.lastIndexOf('.');
String tld = "";
if (p > 0) {
tld = host.substring(p + 1);
}
- Integer i = TLDID.get(tld);
+ final Integer i = TLDID.get(tld);
if (i == null) {
return (isLocal(host)) ? 7 : TLD_Generic_ID;
} else {
@@ -591,7 +591,7 @@ public class serverDomains {
return true;
// check the tld list
- int p = host.lastIndexOf('.');
+ final int p = host.lastIndexOf('.');
String tld = "";
if (p > 0) {
tld = host.substring(p + 1);
@@ -617,16 +617,16 @@ public class serverDomains {
public static String myPublicIP() {
// if a static IP was configured, we have to return it here ...
- plasmaSwitchboard sb = plasmaSwitchboard.getSwitchboard();
+ final plasmaSwitchboard sb = plasmaSwitchboard.getSwitchboard();
if (sb != null) {
- String staticIP = sb.getConfig("staticIP", "");
+ final String staticIP = sb.getConfig("staticIP", "");
if ((!staticIP.equals(""))) {
return staticIP;
}
}
// otherwise we return the real IP address of this host
- InetAddress pLIP = myPublicLocalIP();
+ final InetAddress pLIP = myPublicLocalIP();
if (pLIP != null) return pLIP.getHostAddress();
return null;
}
@@ -636,21 +636,21 @@ public class serverDomains {
String hostName;
try {
hostName = InetAddress.getLocalHost().getHostName();
- } catch (java.net.UnknownHostException e) {
+ } catch (final java.net.UnknownHostException e) {
hostName = "localhost"; // hopin' nothing serious happened only the hostname changed while running yacy
System.err.println("ERROR: (internal) " + e.getMessage());
}
// list all addresses
- InetAddress[] ia = InetAddress.getAllByName(hostName);
+ final InetAddress[] ia = InetAddress.getAllByName(hostName);
// for (int i = 0; i < ia.length; i++) System.out.println("IP: " +
// ia[i].getHostAddress()); // DEBUG
if (ia.length == 0) {
try {
return InetAddress.getLocalHost();
- } catch (UnknownHostException e) {
+ } catch (final UnknownHostException e) {
try {
return InetAddress.getByName("127.0.0.1");
- } catch (UnknownHostException ee) {
+ } catch (final UnknownHostException ee) {
return null;
}
}
@@ -681,7 +681,7 @@ public class serverDomains {
if (ia[i].getHostAddress().indexOf(":") < 0) return ia[i];
}
return ia[0];
- } catch (java.net.UnknownHostException e) {
+ } catch (final java.net.UnknownHostException e) {
System.err.println("ERROR: (internal) " + e.getMessage());
return null;
}
diff --git a/source/de/anomic/server/serverFileUtils.java b/source/de/anomic/server/serverFileUtils.java
index 564f0d42e..42cb32c88 100644
--- a/source/de/anomic/server/serverFileUtils.java
+++ b/source/de/anomic/server/serverFileUtils.java
@@ -57,7 +57,7 @@ public final class serverFileUtils {
private static final int DEFAULT_BUFFER_SIZE = 1024; // this is also the maximum chunk size
- public static long copy(InputStream source, OutputStream dest) throws IOException {
+ public static long copy(final InputStream source, final OutputStream dest) throws IOException {
return copy(source, dest, -1);
}
@@ -75,8 +75,8 @@ public final class serverFileUtils {
* @see #copy(File source, OutputStream dest)
* @see #copy(File source, File dest)
*/
- public static long copy(InputStream source, OutputStream dest, long count) throws IOException {
- byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
+ public static long copy(final InputStream source, final OutputStream dest, final long count) throws IOException {
+ final byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int chunkSize = (int) ((count > 0) ? Math.min(count, DEFAULT_BUFFER_SIZE) : DEFAULT_BUFFER_SIZE);
int c; long total = 0;
@@ -96,29 +96,29 @@ public final class serverFileUtils {
return total;
}
- public static int copy(File source, String inputCharset, Writer dest) throws IOException {
+ public static int copy(final File source, final String inputCharset, final Writer dest) throws IOException {
InputStream fis = null;
try {
fis = new FileInputStream(source);
return copy(fis, dest, inputCharset);
} finally {
- if (fis != null) try { fis.close(); } catch (Exception e) {}
+ if (fis != null) try { fis.close(); } catch (final Exception e) {}
}
}
- public static int copy(InputStream source, Writer dest, String inputCharset) throws IOException {
- InputStreamReader reader = new InputStreamReader(source,inputCharset);
+ public static int copy(final InputStream source, final Writer dest, final String inputCharset) throws IOException {
+ final InputStreamReader reader = new InputStreamReader(source,inputCharset);
return copy(reader,dest);
}
- public static int copy(String source, Writer dest) throws IOException {
+ public static int copy(final String source, final Writer dest) throws IOException {
dest.write(source);
dest.flush();
return source.length();
}
- public static int copy(Reader source, Writer dest) throws IOException {
- char[] buffer = new char[DEFAULT_BUFFER_SIZE];
+ public static int copy(final Reader source, final Writer dest) throws IOException {
+ final char[] buffer = new char[DEFAULT_BUFFER_SIZE];
int count = 0;
int n = 0;
try {
@@ -126,14 +126,14 @@ public final class serverFileUtils {
dest.write(buffer, 0, n);
count += n;
}
- } catch (Exception e) {
+ } catch (final Exception e) {
// an "sun.io.MalformedInputException: Missing byte-order mark" - exception may occur here
throw new IOException(e.getMessage());
}
return count;
}
- public static void copy(InputStream source, File dest) throws IOException {
+ public static void copy(final InputStream source, final File dest) throws IOException {
copy(source,dest,-1);
}
@@ -149,13 +149,13 @@ public final class serverFileUtils {
* @see #copy(File source, OutputStream dest)
* @see #copy(File source, File dest)
*/
- public static void copy(InputStream source, File dest, long count) throws IOException {
+ public static void copy(final InputStream source, final File dest, final long count) throws IOException {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(dest);
copy(source, fos, count);
} finally {
- if (fos != null) try {fos.close();} catch (Exception e) {}
+ if (fos != null) try {fos.close();} catch (final Exception e) {}
}
}
@@ -170,15 +170,15 @@ public final class serverFileUtils {
* @see #copy(File source, OutputStream dest)
* @see #copy(File source, File dest)
*/
- public static void copyRange(File source, OutputStream dest, int start) throws IOException {
+ public static void copyRange(final File source, final OutputStream dest, final int start) throws IOException {
InputStream fis = null;
try {
fis = new FileInputStream(source);
- long skipped = fis.skip(start);
+ final long skipped = fis.skip(start);
if (skipped != start) throw new IllegalStateException("Unable to skip '" + start + "' bytes. Only '" + skipped + "' bytes skipped.");
copy(fis, dest, -1);
} finally {
- if (fis != null) try { fis.close(); } catch (Exception e) {}
+ if (fis != null) try { fis.close(); } catch (final Exception e) {}
}
}
@@ -192,13 +192,13 @@ public final class serverFileUtils {
* @see #copyRange(File source, OutputStream dest, int start)
* @see #copy(File source, File dest)
*/
- public static void copy(File source, OutputStream dest) throws IOException {
+ public static void copy(final File source, final OutputStream dest) throws IOException {
InputStream fis = null;
try {
fis = new FileInputStream(source);
copy(fis, dest, -1);
} finally {
- if (fis != null) try { fis.close(); } catch (Exception e) {}
+ if (fis != null) try { fis.close(); } catch (final Exception e) {}
}
}
@@ -213,7 +213,7 @@ public final class serverFileUtils {
* @see #copyRange(File source, OutputStream dest, int start)
* @see #copy(File source, OutputStream dest)
*/
- public static void copy(File source, File dest) throws IOException {
+ public static void copy(final File source, final File dest) throws IOException {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
@@ -221,26 +221,26 @@ public final class serverFileUtils {
fos = new FileOutputStream(dest);
copy(fis, fos, -1);
} finally {
- if (fis != null) try {fis.close();} catch (Exception e) {}
- if (fos != null) try {fos.close();} catch (Exception e) {}
+ if (fis != null) try {fis.close();} catch (final Exception e) {}
+ if (fos != null) try {fos.close();} catch (final Exception e) {}
}
}
- public static void copy(byte[] source, OutputStream dest) throws IOException {
+ public static void copy(final byte[] source, final OutputStream dest) throws IOException {
dest.write(source, 0, source.length);
dest.flush();
}
- public static void copy(byte[] source, File dest) throws IOException {
+ public static void copy(final byte[] source, final File dest) throws IOException {
copy(new ByteArrayInputStream(source), dest);
}
- public static byte[] read(InputStream source) throws IOException {
+ public static byte[] read(final InputStream source) throws IOException {
return read(source,-1);
}
- public static byte[] read(InputStream source, long count) throws IOException {
- ByteArrayOutputStream baos = (count > 0)
+ public static byte[] read(final InputStream source, final long count) throws IOException {
+ final ByteArrayOutputStream baos = (count > 0)
? new ByteArrayOutputStream((int)count)
: new ByteArrayOutputStream();
copy(source, baos, count);
@@ -250,20 +250,20 @@ public final class serverFileUtils {
return baos.toByteArray();
}
- public static byte[] read(File source) throws IOException {
- byte[] buffer = new byte[(int) source.length()];
+ public static byte[] read(final File source) throws IOException {
+ final byte[] buffer = new byte[(int) source.length()];
InputStream fis = null;
try {
fis = new FileInputStream(source);
int p = 0, c;
while ((c = fis.read(buffer, p, buffer.length - p)) > 0) p += c;
} finally {
- if (fis != null) try { fis.close(); } catch (Exception e) {}
+ if (fis != null) try { fis.close(); } catch (final Exception e) {}
}
return buffer;
}
- public static byte[] readAndZip(File source) throws IOException {
+ public static byte[] readAndZip(final File source) throws IOException {
ByteArrayOutputStream byteOut = null;
GZIPOutputStream zipOut = null;
try {
@@ -273,29 +273,29 @@ public final class serverFileUtils {
zipOut.close();
return byteOut.toByteArray();
} finally {
- if (zipOut != null) try { zipOut.close(); } catch (Exception e) {}
- if (byteOut != null) try { byteOut.close(); } catch (Exception e) {}
+ if (zipOut != null) try { zipOut.close(); } catch (final Exception e) {}
+ if (byteOut != null) try { byteOut.close(); } catch (final Exception e) {}
}
}
- public static void writeAndGZip(byte[] source, File dest) throws IOException {
+ public static void writeAndGZip(final byte[] source, final File dest) throws IOException {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(dest);
writeAndGZip(source, fos);
} finally {
- if (fos != null) try {fos.close();} catch (Exception e) {}
+ if (fos != null) try {fos.close();} catch (final Exception e) {}
}
}
- public static void writeAndGZip(byte[] source, OutputStream dest) throws IOException {
+ public static void writeAndGZip(final byte[] source, final OutputStream dest) throws IOException {
GZIPOutputStream zipOut = null;
try {
zipOut = new GZIPOutputStream(dest);
copy(source, zipOut);
zipOut.close();
} finally {
- if (zipOut != null) try { zipOut.close(); } catch (Exception e) {}
+ if (zipOut != null) try { zipOut.close(); } catch (final Exception e) {}
}
}
@@ -312,10 +312,10 @@ public final class serverFileUtils {
if ((source.length > 1) && (((source[1] << 8) | source[0]) == GZIPInputStream.GZIP_MAGIC)) {
System.out.println("DEBUG: uncompressGZipArray - uncompressing source");
try {
- ByteArrayInputStream byteInput = new ByteArrayInputStream(source);
- ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
- GZIPInputStream zippedContent = new GZIPInputStream(byteInput);
- byte[] data = new byte[1024];
+ final ByteArrayInputStream byteInput = new ByteArrayInputStream(source);
+ final ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
+ final GZIPInputStream zippedContent = new GZIPInputStream(byteInput);
+ final byte[] data = new byte[1024];
int read = 0;
// reading gzip file and store it uncompressed
@@ -326,7 +326,7 @@ public final class serverFileUtils {
byteOutput.close();
source = byteOutput.toByteArray();
- } catch (Exception e) {
+ } catch (final Exception e) {
if (!e.getMessage().equals("Not in GZIP format")) {
throw new IOException(e.getMessage());
}
@@ -336,8 +336,8 @@ public final class serverFileUtils {
return source;
}
- public static HashSet<String> loadList(File file) {
- HashSet<String> set = new HashSet<String>();
+ public static HashSet<String> loadList(final File file) {
+ final HashSet<String> set = new HashSet<String>();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
@@ -347,31 +347,31 @@ public final class serverFileUtils {
if ((line.length() > 0) && (!(line.startsWith("#")))) set.add(line.trim().toLowerCase());
}
br.close();
- } catch (IOException e) {
+ } catch (final IOException e) {
} finally {
- if (br != null) try { br.close(); } catch (Exception e) {}
+ if (br != null) try { br.close(); } catch (final Exception e) {}
}
return set;
}
- public static Map<String, String> loadHashMap(File f) {
+ public static Map<String, String> loadHashMap(final File f) {
// load props
try {
- byte[] b = read(f);
+ final byte[] b = read(f);
return nxTools.table(nxTools.strings(b));
- } catch (IOException e2) {
+ } catch (final IOException e2) {
System.err.println("ERROR: " + f.toString() + " not found in settings path");
return null;
}
}
- public static void saveMap(File file, Map<String, String> props, String comment) throws IOException {
+ public static void saveMap(final File file, final Map<String, String> props, final String comment) throws IOException {
PrintWriter pw = null;
- File tf = new File(file.toString() + "." + (System.currentTimeMillis() % 1000));
+ final File tf = new File(file.toString() + "." + (System.currentTimeMillis() % 1000));
pw = new PrintWriter(new BufferedOutputStream(new FileOutputStream(tf)));
pw.println("# " + comment);
String key, value;
- for (Map.Entry<String, String> entry: props.entrySet()) {
+ for (final Map.Entry<String, String> entry: props.entrySet()) {
key = entry.getKey();
if (entry.getValue() == null) {
value = "";
@@ -386,41 +386,41 @@ public final class serverFileUtils {
tf.renameTo(file);
}
- public static Set<String> loadSet(File file, int chunksize, boolean tree) throws IOException {
- Set<String> set = (tree) ? (Set<String>) new TreeSet<String>() : (Set<String>) new HashSet<String>();
- byte[] b = read(file);
+ public static Set<String> loadSet(final File file, final int chunksize, final boolean tree) throws IOException {
+ final Set<String> set = (tree) ? (Set<String>) new TreeSet<String>() : (Set<String>) new HashSet<String>();
+ final byte[] b = read(file);
for (int i = 0; (i + chunksize) <= b.length; i++) {
set.add(new String(b, i, chunksize));
}
return set;
}
- public static Set<String> loadSet(File file, String sep, boolean tree) throws IOException {
- Set<String> set = (tree) ? (Set<String>) new TreeSet<String>() : (Set<String>) new HashSet<String>();
- byte[] b = read(file);
- StringTokenizer st = new StringTokenizer(new String(b, "UTF-8"), sep);
+ public static Set<String> loadSet(final File file, final String sep, final boolean tree) throws IOException {
+ final Set<String> set = (tree) ? (Set<String>) new TreeSet<String>() : (Set<String>) new HashSet<String>();
+ final byte[] b = read(file);
+ final StringTokenizer st = new StringTokenizer(new String(b, "UTF-8"), sep);
while (st.hasMoreTokens()) {
set.add(st.nextToken());
}
return set;
}
- public static void saveSet(File file, String format, Set<String> set, String sep) throws IOException {
- File tf = new File(file.toString() + ".tmp" + (System.currentTimeMillis() % 1000));
+ public static void saveSet(final File file, final String format, final Set<String> set, final String sep) throws IOException {
+ final File tf = new File(file.toString() + ".tmp" + (System.currentTimeMillis() % 1000));
OutputStream os = null;
if ((format == null) || (format.equals("plain"))) {
os = new BufferedOutputStream(new FileOutputStream(tf));
} else if (format.equals("gzip")) {
os = new GZIPOutputStream(new FileOutputStream(tf));
} else if (format.equals("zip")) {
- ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file));
+ final ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file));
String name = file.getName();
if (name.endsWith(".zip")) name = name.substring(0, name.length() - 4);
zos.putNextEntry(new ZipEntry(name + ".txt"));
os = zos;
}
if(os != null) {
- for (Iterator<String> i = set.iterator(); i.hasNext(); ) {
+ for (final Iterator<String> i = set.iterator(); i.hasNext(); ) {
os.write((i.next().toString()).getBytes());
if (sep != null) os.write(sep.getBytes());
}
@@ -430,22 +430,22 @@ public final class serverFileUtils {
tf.renameTo(file);
}
- public static void saveSet(File file, String format, kelondroRowSet set, String sep) throws IOException {
- File tf = new File(file.toString() + ".tmp" + (System.currentTimeMillis() % 1000));
+ public static void saveSet(final File file, final String format, final kelondroRowSet set, final String sep) throws IOException {
+ final File tf = new File(file.toString() + ".tmp" + (System.currentTimeMillis() % 1000));
OutputStream os = null;
if ((format == null) || (format.equals("plain"))) {
os = new BufferedOutputStream(new FileOutputStream(tf));
} else if (format.equals("gzip")) {
os = new GZIPOutputStream(new FileOutputStream(tf));
} else if (format.equals("zip")) {
- ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file));
+ final ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file));
String name = file.getName();
if (name.endsWith(".zip")) name = name.substring(0, name.length() - 4);
zos.putNextEntry(new ZipEntry(name + ".txt"));
os = zos;
}
if(os != null) {
- Iterator<kelondroRow.Entry> i = set.rows();
+ final Iterator<kelondroRow.Entry> i = set.rows();
String key;
if (i.hasNext()) {
key = new String(i.next().getColBytes(0));
@@ -467,17 +467,17 @@ public final class serverFileUtils {
* @param from_dir Directory which contents will be moved.
* @param to_dir Directory to move into. It must exist already.
*/
- public static void moveAll(File from_dir, File to_dir) {
+ public static void moveAll(final File from_dir, final File to_dir) {
if (!(from_dir.isDirectory())) return;
if (!(to_dir.isDirectory())) return;
- String[] list = from_dir.list();
+ final String[] list = from_dir.list();
for (int i = 0; i < list.length; i++) (new File(from_dir, list[i])).renameTo(new File(to_dir, list[i]));
}
public static class dirlistComparator implements Comparator<File> {
- public int compare(File file1, File file2) {
+ public int compare(final File file1, final File file2) {
if (file1.isDirectory() && !file2.isDirectory()) {
return -1;
} else if (!file1.isDirectory() && file2.isDirectory()) {
@@ -488,10 +488,10 @@ public final class serverFileUtils {
}
}
- public static void main(String[] args) {
+ public static void main(final String[] args) {
try {
writeAndGZip("ein zwei drei, Zauberei".getBytes(), new File("zauberei.txt.gz"));
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
}
@@ -503,7 +503,7 @@ public final class serverFileUtils {
* @return number of copies bytes
* @throws IOException
*/
- public static int copyToStream(BufferedInputStream in, final BufferedOutputStream out) throws IOException {
+ public static int copyToStream(final BufferedInputStream in, final BufferedOutputStream out) throws IOException {
int count = 0;
// copy bytes
int b;
@@ -523,7 +523,7 @@ public final class serverFileUtils {
* @return number of copies bytes
* @throws IOException
*/
- public static int copyToStreams(BufferedInputStream in, final BufferedOutputStream out0, final BufferedOutputStream out1) throws IOException {
+ public static int copyToStreams(final BufferedInputStream in, final BufferedOutputStream out0, final BufferedOutputStream out1) throws IOException {
assert out0 != null;
assert out1 != null;
diff --git a/source/de/anomic/server/serverInstantBlockingThread.java b/source/de/anomic/server/serverInstantBlockingThread.java
index 5de2c2d1a..91d550c09 100644
--- a/source/de/anomic/server/serverInstantBlockingThread.java
+++ b/source/de/anomic/server/serverInstantBlockingThread.java
@@ -33,14 +33,14 @@ import de.anomic.server.logging.serverLog;
public class serverInstantBlockingThread<J extends serverProcessorJob> extends serverAbstractBlockingThread<J> implements serverBlockingThread<J> {
- private Method jobExecMethod;
- private Object environment;
- private Long handle;
+ private final Method jobExecMethod;
+ private final Object environment;
+ private final Long handle;
private static int handleCounter = 0;
public static int instantThreadCounter = 0;
public static ConcurrentHashMap<Long, String> jobs = new ConcurrentHashMap<Long, String>();
- public serverInstantBlockingThread(Object env, String jobExec, BlockingQueue<J> input, serverProcessor<J> output) {
+ public serverInstantBlockingThread(final Object env, final String jobExec, final BlockingQueue<J> input, final serverProcessor<J> output) {
// jobExec is the name of a method of the object 'env' that executes the one-step-run
// jobCount is the name of a method that returns the size of the job
@@ -55,17 +55,17 @@ public class serverInstantBlockingThread<J extends serverProcessorJob> extends s
this.handle = new Long(System.currentTimeMillis() + this.getName().hashCode());
}
- protected static Method execMethod(Object env, String jobExec) {
- Class<?> theClass = (env instanceof Class) ? (Class<?>) env : env.getClass();
+ protected static Method execMethod(final Object env, final String jobExec) {
+ final Class<?> theClass = (env instanceof Class) ? (Class<?>) env : env.getClass();
try {
- Method[] methods = theClass.getMethods();
+ final Method[] methods = theClass.getMethods();
for (int i = 0; i < methods.length; i++) {
if ((methods[i].getParameterTypes().length == 1) && (methods[i].getName().equals(jobExec))) {
return methods[i];
}
}
throw new NoSuchMethodException(jobExec + " does not exist in " + env.getClass().getName());
- } catch (NoSuchMethodException e) {
+ } catch (final NoSuchMethodException e) {
throw new RuntimeException("serverInstantThread, wrong declaration of jobExec: " + e.getMessage());
}
}
@@ -75,7 +75,7 @@ public class serverInstantBlockingThread<J extends serverProcessorJob> extends s
}
@SuppressWarnings("unchecked")
- public J job(J next) throws Exception {
+ public J job(final J next) throws Exception {
if (next == null) return null; // poison pill: shutdown
instantThreadCounter++;
//System.out.println("started job " + this.handle + ": " + this.getName());
@@ -83,22 +83,22 @@ public class serverInstantBlockingThread<J extends serverProcessorJob> extends s
J out = null;
try {
out = (J) jobExecMethod.invoke(environment, new Object[]{next});
- } catch (IllegalAccessException e) {
+ } catch (final IllegalAccessException e) {
serverLog.logSevere("BLOCKINGTHREAD", "Internal Error in serverInstantThread.job: " + e.getMessage());
serverLog.logSevere("BLOCKINGTHREAD", "shutting down thread '" + this.getName() + "'");
this.terminate(false);
- } catch (IllegalArgumentException e) {
+ } catch (final IllegalArgumentException e) {
serverLog.logSevere("BLOCKINGTHREAD", "Internal Error in serverInstantThread.job: " + e.getMessage());
serverLog.logSevere("BLOCKINGTHREAD", "shutting down thread '" + this.getName() + "'");
this.terminate(false);
- } catch (InvocationTargetException e) {
- String targetException = e.getTargetException().getMessage();
+ } catch (final InvocationTargetException e) {
+ final String targetException = e.getTargetException().getMessage();
e.getTargetException().printStackTrace();
e.printStackTrace();
if ((targetException != null) && ((targetException.indexOf("heap space") > 0) || (targetException.indexOf("NullPointerException") > 0))) e.getTargetException().printStackTrace();
serverLog.logSevere("BLOCKINGTHREAD", "Runtime Error in serverInstantThread.job, thread '" + this.getName() + "': " + e.getMessage() + "; target exception: " + targetException, e.getTargetException());
e.getTargetException().printStackTrace();
- } catch (OutOfMemoryError e) {
+ } catch (final OutOfMemoryError e) {
serverLog.logSevere("BLOCKINGTHREAD", "OutOfMemory Error in serverInstantThread.job, thread '" + this.getName() + "': " + e.getMessage());
e.printStackTrace();
}
diff --git a/source/de/anomic/server/serverInstantBusyThread.java b/source/de/anomic/server/serverInstantBusyThread.java
index c5b1609ce..6d3b32b23 100644
--- a/source/de/anomic/server/serverInstantBusyThread.java
+++ b/source/de/anomic/server/serverInstantBusyThread.java
@@ -30,20 +30,20 @@ import de.anomic.server.logging.serverLog;
public final class serverInstantBusyThread extends serverAbstractBusyThread implements serverBusyThread {
private Method jobExecMethod, jobCountMethod, freememExecMethod;
- private Object environment;
- private Long handle;
+ private final Object environment;
+ private final Long handle;
public static int instantThreadCounter = 0;
public static TreeMap<Long, String> jobs = new TreeMap<Long, String>();
- public serverInstantBusyThread(Object env, String jobExec, String jobCount, String freemem) {
+ public serverInstantBusyThread(final Object env, final String jobExec, final String jobCount, final String freemem) {
// jobExec is the name of a method of the object 'env' that executes the one-step-run
// jobCount is the name of a method that returns the size of the job
// freemem is the name of a method that tries to free memory and returns void
- Class<?> theClass = (env instanceof Class) ? (Class<?>) env : env.getClass();
+ final Class<?> theClass = (env instanceof Class) ? (Class<?>) env : env.getClass();
try {
this.jobExecMethod = theClass.getMethod(jobExec, new Class[0]);
- } catch (NoSuchMethodException e) {
+ } catch (final NoSuchMethodException e) {
throw new RuntimeException("serverInstantThread, wrong declaration of jobExec: " + e.getMessage());
}
try {
@@ -52,7 +52,7 @@ public final class serverInstantBusyThread extends serverAbstractBusyThread impl
else
this.jobCountMethod = theClass.getMethod(jobCount, new Class[0]);
- } catch (NoSuchMethodException e) {
+ } catch (final NoSuchMethodException e) {
throw new RuntimeException("serverInstantThread, wrong declaration of jobCount: " + e.getMessage());
}
try {
@@ -61,7 +61,7 @@ public final class serverInstantBusyThread extends serverAbstractBusyThread impl
else
this.freememExecMethod = theClass.getMethod(freemem, new Class[0]);
- } catch (NoSuchMethodException e) {
+ } catch (final NoSuchMethodException e) {
throw new RuntimeException("serverInstantThread, wrong declaration of freemem: " + e.getMessage());
}
this.environment = (env instanceof Class) ? null : env;
@@ -72,16 +72,16 @@ public final class serverInstantBusyThread extends serverAbstractBusyThread impl
public int getJobCount() {
if (this.jobCountMethod == null) return Integer.MAX_VALUE;
try {
- Object result = jobCountMethod.invoke(environment, new Object[0]);
+ final Object result = jobCountMethod.invoke(environment, new Object[0]);
if (result instanceof Integer)
return ((Integer) result).intValue();
else
return -1;
- } catch (IllegalAccessException e) {
+ } catch (final IllegalAccessException e) {
return -1;
- } catch (IllegalArgumentException e) {
+ } catch (final IllegalArgumentException e) {
return -1;
- } catch (InvocationTargetException e) {
+ } catch (final InvocationTargetException e) {
serverLog.logSevere("BUSYTHREAD", "invocation serverInstantThread of thread '" + this.getName() + "': " + e.getMessage(), e);
return -1;
}
@@ -93,22 +93,22 @@ public final class serverInstantBusyThread extends serverAbstractBusyThread impl
synchronized(jobs) {jobs.put(this.handle, this.getName());}
boolean jobHasDoneSomething = false;
try {
- Object result = jobExecMethod.invoke(environment, new Object[0]);
+ final Object result = jobExecMethod.invoke(environment, new Object[0]);
if (result == null) jobHasDoneSomething = true;
else if (result instanceof Boolean) jobHasDoneSomething = ((Boolean) result).booleanValue();
- } catch (IllegalAccessException e) {
+ } catch (final IllegalAccessException e) {
serverLog.logSevere("BUSYTHREAD", "Internal Error in serverInstantThread.job: " + e.getMessage());
serverLog.logSevere("BUSYTHREAD", "shutting down thread '" + this.getName() + "'");
this.terminate(false);
- } catch (IllegalArgumentException e) {
+ } catch (final IllegalArgumentException e) {
serverLog.logSevere("BUSYTHREAD", "Internal Error in serverInstantThread.job: " + e.getMessage());
serverLog.logSevere("BUSYTHREAD", "shutting down thread '" + this.getName() + "'");
this.terminate(false);
- } catch (InvocationTargetException e) {
- String targetException = e.getTargetException().getMessage();
+ } catch (final InvocationTargetException e) {
+ final String targetException = e.getTargetException().getMessage();
e.printStackTrace();
serverLog.logSevere("BUSYTHREAD", "Runtime Error in serverInstantThread.job, thread '" + this.getName() + "': " + e.getMessage() + "; target exception: " + targetException, e.getTargetException());
- } catch (OutOfMemoryError e) {
+ } catch (final OutOfMemoryError e) {
serverLog.logSevere("BUSYTHREAD", "OutOfMemory Error in serverInstantThread.job, thread '" + this.getName() + "': " + e.getMessage());
e.printStackTrace();
freemem();
@@ -122,28 +122,28 @@ public final class serverInstantBusyThread extends serverAbstractBusyThread impl
if (freememExecMethod == null) return;
try {
freememExecMethod.invoke(environment, new Object[0]);
- } catch (IllegalAccessException e) {
+ } catch (final IllegalAccessException e) {
serverLog.logSevere("BUSYTHREAD", "Internal Error in serverInstantThread.freemem: " + e.getMessage());
serverLog.logSevere("BUSYTHREAD", "shutting down thread '" + this.getName() + "'");
this.terminate(false);
- } catch (IllegalArgumentException e) {
+ } catch (final IllegalArgumentException e) {
serverLog.logSevere("BUSYTHREAD", "Internal Error in serverInstantThread.freemem: " + e.getMessage());
serverLog.logSevere("BUSYTHREAD", "shutting down thread '" + this.getName() + "'");
this.terminate(false);
- } catch (InvocationTargetException e) {
- String targetException = e.getTargetException().getMessage();
+ } catch (final InvocationTargetException e) {
+ final String targetException = e.getTargetException().getMessage();
if (targetException.indexOf("heap space") > 0) e.getTargetException().printStackTrace();
serverLog.logSevere("BUSYTHREAD", "Runtime Error in serverInstantThread.freemem, thread '" + this.getName() + "': " + e.getMessage() + "; target exception: " + targetException, e.getTargetException());
e.getTargetException().printStackTrace();
- } catch (OutOfMemoryError e) {
+ } catch (final OutOfMemoryError e) {
serverLog.logSevere("BUSYTHREAD", "OutOfMemory Error in serverInstantThread.freemem, thread '" + this.getName() + "': " + e.getMessage());
e.printStackTrace();
}
}
- public static serverBusyThread oneTimeJob(Object env, String jobExec, serverLog log, long startupDelay) {
+ public static serverBusyThread oneTimeJob(final Object env, final String jobExec, final serverLog log, final long startupDelay) {
// start the job and execute it once as background process
- serverBusyThread thread = new serverInstantBusyThread(env, jobExec, null, null);
+ final serverBusyThread thread = new serverInstantBusyThread(env, jobExec, null, null);
thread.setStartupSleep(startupDelay);
thread.setIdleSleep(-1);
thread.setBusySleep(-1);
@@ -153,14 +153,14 @@ public final class serverInstantBusyThread extends serverAbstractBusyThread impl
return thread;
}
- public static serverThread oneTimeJob(Runnable thread, long startupDelay) {
- serverLog log = new serverLog(thread.getClass().getName() + "/run");
+ public static serverThread oneTimeJob(final Runnable thread, final long startupDelay) {
+ final serverLog log = new serverLog(thread.getClass().getName() + "/run");
log.setLevel(java.util.logging.Level.INFO);
return oneTimeJob(thread, "run", log, startupDelay);
}
- public static serverThread oneTimeJob(Runnable thread, long startupDelay, int maxJobs) {
- while (instantThreadCounter >= maxJobs) try {Thread.sleep(100);} catch (InterruptedException e) {break;}
+ public static serverThread oneTimeJob(final Runnable thread, final long startupDelay, final int maxJobs) {
+ while (instantThreadCounter >= maxJobs) try {Thread.sleep(100);} catch (final InterruptedException e) {break;}
return oneTimeJob( thread, startupDelay);
}
diff --git a/source/de/anomic/server/serverMemory.java b/source/de/anomic/server/serverMemory.java
index 06c45adaf..ba3726e23 100644
--- a/source/de/anomic/server/serverMemory.java
+++ b/source/de/anomic/server/serverMemory.java
@@ -46,10 +46,10 @@ public class serverMemory {
* @param last time which must be passed since lased gc
* @param info additional info for log
*/
- public final synchronized static void gc(int last, String info) { // thq
- long elapsed = System.currentTimeMillis() - lastGC;
+ public final synchronized static void gc(final int last, final String info) { // thq
+ final long elapsed = System.currentTimeMillis() - lastGC;
if (elapsed > last) {
- long free = free();
+ final long free = free();
System.gc();
lastGC = System.currentTimeMillis();
if (log.isFine()) log.logInfo("[gc] before: " + bytesToString(free) + ", after: " + bytesToString(free()) + ", call: " + info);
@@ -147,7 +147,7 @@ public class serverMemory {
long avail = available();
if (avail >= size) return true;
if (log.isFine()) {
- String t = new Throwable("Stack trace").getStackTrace()[1].toString();
+ final String t = new Throwable("Stack trace").getStackTrace()[1].toString();
log.logFine(t + " requested " + (size >> 10) + " KB, got " + (avail >> 10) + " KB");
}
final long avg = getAverageGCFree();
@@ -179,7 +179,7 @@ public class serverMemory {
* @param byteCount
* @return formatted String with unit
*/
- public static String bytesToString(long byteCount) {
+ public static String bytesToString(final long byteCount) {
try {
final StringBuffer byteString = new StringBuffer();
@@ -198,7 +198,7 @@ public class serverMemory {
}
return byteString.toString();
- } catch (Exception e) {
+ } catch (final Exception e) {
return "unknown";
}
}
@@ -207,13 +207,13 @@ public class serverMemory {
* main
* @param args
*/
- public static void main(String[] args) {
+ public static void main(final String[] args) {
// try this with a jvm 1.4.2 and with a jvm 1.5 and compare results
- int mb = 1024 * 1024;
+ final int mb = 1024 * 1024;
System.out.println("vm: " + System.getProperty("java.vm.version"));
System.out.println("computed max = " + (max() / mb) + " mb");
- int alloc = 10000;
- byte[][] x = new byte[100000][];
+ final int alloc = 10000;
+ final byte[][] x = new byte[100000][];
for (int i = 0; i < 100000; i++) {
x[i] = new byte[alloc];
if (i % 100 == 0) System.out.println("used = " + (i * alloc / mb) +
diff --git a/source/de/anomic/server/serverObjects.java b/source/de/anomic/server/serverObjects.java
index c1dbc3278..e33f91f0c 100644
--- a/source/de/anomic/server/serverObjects.java
+++ b/source/de/anomic/server/serverObjects.java
@@ -66,11 +66,11 @@ public class serverObjects extends HashMap<String, String> implements Cloneable
super();
}
- public serverObjects(int initialCapacity) {
+ public serverObjects(final int initialCapacity) {
super(initialCapacity);
}
- public serverObjects(Map<String, String> input) {
+ public serverObjects(final Map<String, String> input) {
super(input);
}
@@ -83,7 +83,7 @@ public class serverObjects extends HashMap<String, String> implements Cloneable
* @return The value that was added to the map.
* @see java.util.Hashtable#put(K, V)
*/
- public String put(String key, String value) {
+ public String put(final String key, final String value) {
if (key == null) {
// this does nothing
return null;
@@ -101,7 +101,7 @@ public class serverObjects extends HashMap<String, String> implements Cloneable
* @param value mapped value as a byte array.
* @return the previous value as String.
*/
- public String put(String key, byte[] value) {
+ public String put(final String key, final byte[] value) {
return this.put(key, new String(value)); //TODO: do we need an encoding method for byte[]?
}
@@ -112,7 +112,7 @@ public class serverObjects extends HashMap<String, String> implements Cloneable
* @param value value as double/float.
* @return value as it was added to the map or <code>NaN</code> if an error occured.
*/
- public double put(String key, double value) {
+ public double put(final String key, final double value) {
if (null == this.put(key, Double.toString(value))) {
return Double.NaN;
} else {
@@ -124,7 +124,7 @@ public class serverObjects extends HashMap<String, String> implements Cloneable
* same as {@link #put(String, double)} but for integer types
* @return Returns 0 for the error case.
*/
- public long put(String key, long value) {
+ public long put(final String key, final long value) {
if (null == this.put(key, Long.toString(value))) {
return 0;
} else {
@@ -132,15 +132,15 @@ public class serverObjects extends HashMap<String, String> implements Cloneable
}
}
- public String put(String key, java.util.Date value) {
+ public String put(final String key, final java.util.Date value) {
return this.put(key, value.toString());
}
- public String put(String key, serverDate value) {
+ public String put(final String key, final serverDate value) {
return this.put(key, value.toString());
}
- public String put(String key, InetAddress value) {
+ public String put(final String key, final InetAddress value) {
return this.put(key, value.toString());
}
@@ -151,7 +151,7 @@ public class serverObjects extends HashMap<String, String> implements Cloneable
* @return the modified String that was added to the map.
* @see htmlTools#encodeUnicode2html(String, boolean)
*/
- public String putHTML(String key, String value) {
+ public String putHTML(final String key, final String value) {
return putHTML(key, value, false);
}
@@ -161,7 +161,7 @@ public class serverObjects extends HashMap<String, String> implements Cloneable
* If forXML is <code>true</code>, then only the characters <b>&amp; &quot; &lt; &gt;</b> will be
* replaced in the returned String.
*/
- public String putHTML(String key, String value, boolean forXML) {
+ public String putHTML(final String key, final String value, final boolean forXML) {
return put(key, htmlTools.encodeUnicode2html(value, true, forXML));
}
@@ -173,7 +173,7 @@ public class serverObjects extends HashMap<String, String> implements Cloneable
* representation.
* @return the String value added to the map.
*/
- public String putNum(String key, long value) {
+ public String putNum(final String key, final long value) {
return this.put(key, yFormatter.number(value, this.localized));
}
@@ -181,7 +181,7 @@ public class serverObjects extends HashMap<String, String> implements Cloneable
* Variant for double/float types.
* @see #putNum(String, long)
*/
- public String putNum(String key, double value) {
+ public String putNum(final String key, final double value) {
return this.put(key, yFormatter.number(value, this.localized));
}
@@ -189,103 +189,103 @@ public class serverObjects extends HashMap<String, String> implements Cloneable
* Variant for string encoded numbers.
* @see #putNum(String, long)
*/
- public String putNum(String key, String value) {
+ public String putNum(final String key, final String value) {
return this.put(key, yFormatter.number(value));
}
- public String putWiki(String key, String wikiCode){
+ public String putWiki(final String key, final String wikiCode){
return this.put(key, plasmaSwitchboard.wikiParser.transform(wikiCode));
}
- public String putWiki(String key, byte[] wikiCode) {
+ public String putWiki(final String key, final byte[] wikiCode) {
try {
return this.put(key, plasmaSwitchboard.wikiParser.transform(wikiCode));
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
return this.put(key, "Internal error pasting wiki-code: " + e.getMessage());
}
}
- public String putWiki(String key, String wikiCode, String publicAddress) {
+ public String putWiki(final String key, final String wikiCode, final String publicAddress) {
return this.put(key, plasmaSwitchboard.wikiParser.transform(wikiCode, publicAddress));
}
- public String putWiki(String key, byte[] wikiCode, String publicAddress) {
+ public String putWiki(final String key, final byte[] wikiCode, final String publicAddress) {
try {
return this.put(key, plasmaSwitchboard.wikiParser.transform(wikiCode, "UTF-8", publicAddress));
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
return this.put(key, "Internal error pasting wiki-code: " + e.getMessage());
}
}
// inc variant: for counters
- public long inc(String key) {
+ public long inc(final String key) {
String c = super.get(key);
if (c == null) c = "0";
- long l = Long.parseLong(c) + 1;
+ final long l = Long.parseLong(c) + 1;
super.put(key, Long.toString(l));
return l;
}
// new get with default objects
- public Object get(String key, Object dflt) {
- Object result = super.get(key);
+ public Object get(final String key, final Object dflt) {
+ final Object result = super.get(key);
if (result == null) return dflt; else return result;
}
// string variant
- public String get(String key, String dflt) {
- Object result = super.get(key);
+ public String get(final String key, final String dflt) {
+ final Object result = super.get(key);
if (result == null) return dflt; else return (String) result;
}
- public int getInt(String key, int dflt) {
- String s = super.get(key);
+ public int getInt(final String key, final int dflt) {
+ final String s = super.get(key);
if (s == null) return dflt;
try {
return Integer.parseInt(s);
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
return dflt;
}
}
- public long getLong(String key, long dflt) {
- String s = super.get(key);
+ public long getLong(final String key, final long dflt) {
+ final String s = super.get(key);
if (s == null) return dflt;
try {
return Long.parseLong(s);
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
return dflt;
}
}
- public double getDouble(String key, double dflt) {
- String s = super.get(key);
+ public double getDouble(final String key, final double dflt) {
+ final String s = super.get(key);
if (s == null) return dflt;
try {
return Double.parseDouble(s);
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
return dflt;
}
}
// returns a set of all values where their key mappes the keyMapper
- public String[] getAll(String keyMapper) {
+ public String[] getAll(final String keyMapper) {
// the keyMapper may contain regular expressions as defined in String.matches
// this method is particulary useful when parsing the result of checkbox forms
- ArrayList<String> v = new ArrayList<String>();
- Iterator<String> e = keySet().iterator();
+ final ArrayList<String> v = new ArrayList<String>();
+ final Iterator<String> e = keySet().iterator();
String key;
while (e.hasNext()) {
key = e.next();
if (key.matches(keyMapper)) v.add(get(key));
}
// make a String[]
- String[] result = new String[v.size()];
+ final String[] result = new String[v.size()];
for (int i = 0; i < v.size(); i++) result[i] = v.get(i);
return result;
}
// put all elements of another hashtable into the own table
- public void putAll(serverObjects add) {
- Iterator<String> e = add.keySet().iterator();
+ public void putAll(final serverObjects add) {
+ final Iterator<String> e = add.keySet().iterator();
String k;
while (e.hasNext()) {
k = e.next();
@@ -294,11 +294,11 @@ public class serverObjects extends HashMap<String, String> implements Cloneable
}
// convenience methods for storing and loading to a file system
- public void store(File f) throws IOException {
+ public void store(final File f) throws IOException {
BufferedOutputStream fos = null;
try {
fos = new BufferedOutputStream(new FileOutputStream(f));
- Iterator<String> e = keySet().iterator();
+ final Iterator<String> e = keySet().iterator();
String key, value;
while (e.hasNext()) {
key = e.next();
@@ -310,7 +310,7 @@ public class serverObjects extends HashMap<String, String> implements Cloneable
try {
fos.flush();
fos.close();
- } catch (Exception e){}
+ } catch (final Exception e){}
}
}
}
@@ -322,7 +322,7 @@ public class serverObjects extends HashMap<String, String> implements Cloneable
* use a default english locale without grouping.
* @see yFormatter#setLocale(String)
*/
- public void setLocalized(boolean loc) {
+ public void setLocalized(final boolean loc) {
this.localized = loc;
}
diff --git a/source/de/anomic/server/serverPlainSwitch.java b/source/de/anomic/server/serverPlainSwitch.java
index 0cfc544ed..b57eef285 100644
--- a/source/de/anomic/server/serverPlainSwitch.java
+++ b/source/de/anomic/server/serverPlainSwitch.java
@@ -30,11 +30,11 @@ import java.io.File;
public class serverPlainSwitch<E> extends serverAbstractSwitch<E> implements serverSwitch<E> {
- public serverPlainSwitch(File rootPath, String initPath, String configPath, boolean applyPro) {
+ public serverPlainSwitch(final File rootPath, final String initPath, final String configPath, final boolean applyPro) {
super(rootPath, initPath, configPath, applyPro);
}
- public serverObjects action(String actionName, serverObjects actionInput) {
+ public serverObjects action(final String actionName, final serverObjects actionInput) {
// no actions
return null;
}
diff --git a/source/de/anomic/server/serverProcessor.java b/source/de/anomic/server/serverProcessor.java
index 85bf07e18..04a971012 100644
--- a/source/de/anomic/server/serverProcessor.java
+++ b/source/de/anomic/server/serverProcessor.java
@@ -45,11 +45,11 @@ public class serverProcessor<J extends serverProcessorJob> {
private Object environment;
private String methodName;
- public serverProcessor(Object env, String jobExec, int inputQueueSize, serverProcessor<J> output) {
+ public serverProcessor(final Object env, final String jobExec, final int inputQueueSize, final serverProcessor<J> output) {
this(env, jobExec, inputQueueSize, output, useCPU + 1);
}
- public serverProcessor(Object env, String jobExec, int inputQueueSize, serverProcessor<J> output, int poolsize) {
+ public serverProcessor(final Object env, final String jobExec, final int inputQueueSize, final serverProcessor<J> output, final int poolsize) {
// start a fixed number of executors that handle entries in the process queue
this.environment = env;
this.methodName = jobExec;
@@ -67,19 +67,19 @@ public class serverProcessor<J extends serverProcessorJob> {
}
@SuppressWarnings("unchecked")
- public void enQueue(J in) throws InterruptedException {
+ public void enQueue(final J in) throws InterruptedException {
// ensure that enough job executors are running
if ((this.input == null) || (executor == null) || (executor.isShutdown()) || (executor.isTerminated())) {
// execute serialized without extra thread
serverLog.logWarning("PROCESSOR", "executing job " + environment.getClass().getName() + "." + methodName + " serialized");
try {
- J out = (J) serverInstantBlockingThread.execMethod(this.environment, this.methodName).invoke(environment, new Object[]{in});
+ final J out = (J) serverInstantBlockingThread.execMethod(this.environment, this.methodName).invoke(environment, new Object[]{in});
if ((out != null) && (output != null)) output.enQueue(out);
- } catch (IllegalArgumentException e) {
+ } catch (final IllegalArgumentException e) {
e.printStackTrace();
- } catch (IllegalAccessException e) {
+ } catch (final IllegalAccessException e) {
e.printStackTrace();
- } catch (InvocationTargetException e) {
+ } catch (final InvocationTargetException e) {
e.printStackTrace();
}
return;
@@ -89,19 +89,19 @@ public class serverProcessor<J extends serverProcessorJob> {
}
@SuppressWarnings("unchecked")
- public void shutdown(long millisTimeout) {
+ public void shutdown(final long millisTimeout) {
if (executor == null) return;
if (executor.isShutdown()) return;
// put poison pills into the queue
for (int i = 0; i < poolsize; i++) {
try {
input.put((J) serverProcessorJob.poisonPill); // put a poison pill into the queue which will kill the job
- } catch (InterruptedException e) { }
+ } catch (final InterruptedException e) { }
}
// wait for shutdown
try {
executor.awaitTermination(millisTimeout, TimeUnit.MILLISECONDS);
- } catch (InterruptedException e) {}
+ } catch (final InterruptedException e) {}
executor.shutdown();
this.executor = null;
this.input = null;
diff --git a/source/de/anomic/server/serverProcessorJob.java b/source/de/anomic/server/serverProcessorJob.java
index c5da15d49..b8bd9ae0f 100644
--- a/source/de/anomic/server/serverProcessorJob.java
+++ b/source/de/anomic/server/serverProcessorJob.java
@@ -38,7 +38,7 @@ public class serverProcessorJob {
this.status = STATUS_INITIATED;
}
- public serverProcessorJob(int status) {
+ public serverProcessorJob(final int status) {
this.status = status;
}
diff --git a/source/de/anomic/server/serverProfiling.java b/source/de/anomic/server/serverProfiling.java
index 5df2ce1d1..7294cf9f3 100644
--- a/source/de/anomic/server/serverProfiling.java
+++ b/source/de/anomic/server/serverProfiling.java
@@ -52,10 +52,10 @@ public class serverProfiling extends Thread {
systemProfiler.running = false;
}
- private long delaytime;
+ private final long delaytime;
private boolean running;
- public serverProfiling(long time) {
+ public serverProfiling(final long time) {
this.delaytime = time;
running = true;
}
@@ -65,17 +65,17 @@ public class serverProfiling extends Thread {
update("memory", new Long(serverMemory.used()));
try {
Thread.sleep(this.delaytime);
- } catch (InterruptedException e) {
+ } catch (final InterruptedException e) {
this.running = false;
}
}
}
- public static void update(String eventName, Object eventPayload) {
+ public static void update(final String eventName, final Object eventPayload) {
// get event history container
int counter = eventCounter.containsKey(eventName) ? (eventCounter.get(eventName)).intValue() : 0;
if (historyMaps.containsKey(eventName)) {
- ConcurrentLinkedQueue<Event> history = historyMaps.get(eventName);
+ final ConcurrentLinkedQueue<Event> history = historyMaps.get(eventName);
// update entry
history.add(new Event(counter, eventPayload));
@@ -84,14 +84,14 @@ public class serverProfiling extends Thread {
// clean up too old entries
Event e;
- long now = System.currentTimeMillis();
+ final long now = System.currentTimeMillis();
while (history.size() > 0) {
e = history.peek();
if (now - e.time < 600000) break;
history.poll();
}
} else {
- ConcurrentLinkedQueue<Event> history = new ConcurrentLinkedQueue<Event>();
+ final ConcurrentLinkedQueue<Event> history = new ConcurrentLinkedQueue<Event>();
// update entry
history.add(new Event(counter, eventPayload));
@@ -103,7 +103,7 @@ public class serverProfiling extends Thread {
}
}
- public static Iterator<Event> history(String eventName) {
+ public static Iterator<Event> history(final String eventName) {
return (historyMaps.containsKey(eventName) ? (historyMaps.get(eventName)) : new ConcurrentLinkedQueue<Event>()).iterator();
}
@@ -112,7 +112,7 @@ public class serverProfiling extends Thread {
public Object payload;
public long time;
- public Event(int count, Object payload) {
+ public Event(final int count, final Object payload) {
this.count = count;
this.payload = payload;
this.time = System.currentTimeMillis();
diff --git a/source/de/anomic/server/serverSemaphore.java b/source/de/anomic/server/serverSemaphore.java
index 0d5c7414b..d4eabfe2f 100644
--- a/source/de/anomic/server/serverSemaphore.java
+++ b/source/de/anomic/server/serverSemaphore.java
@@ -29,11 +29,11 @@ public final class serverSemaphore {
private long currentValue = 0;
private long maximumValue = Long.MAX_VALUE;
- public serverSemaphore(long initialValue) {
+ public serverSemaphore(final long initialValue) {
this(initialValue,Long.MAX_VALUE);
}
- protected serverSemaphore(long initialValue, long maxValue) {
+ protected serverSemaphore(final long initialValue, final long maxValue) {
/* some errorhandling */
if (maxValue < initialValue) {
throw new IllegalArgumentException("The semaphore maximum value must not be " +
@@ -61,7 +61,7 @@ public final class serverSemaphore {
if (this.currentValue < 0) {
try {
wait();
- } catch(InterruptedException e) {
+ } catch(final InterruptedException e) {
this.currentValue++;
throw e;
}
diff --git a/source/de/anomic/server/serverSwitchAbstractAction.java b/source/de/anomic/server/serverSwitchAbstractAction.java
index 56c745485..06bb00eff 100644
--- a/source/de/anomic/server/serverSwitchAbstractAction.java
+++ b/source/de/anomic/server/serverSwitchAbstractAction.java
@@ -28,7 +28,7 @@ public abstract class serverSwitchAbstractAction {
protected serverLog log = null;
private String shortDescr = "", longDescr = "";
- public void setDescription(String shortText, String longText) {
+ public void setDescription(final String shortText, final String longText) {
// sets a visible description string
this.shortDescr = shortText;
this.longDescr = longText;
@@ -44,7 +44,7 @@ public abstract class serverSwitchAbstractAction {
return this.longDescr;
}
- public void setLog(serverLog log) {
+ public void setLog(final serverLog log) {
// defines a log where process states can be written to
this.log = log;
}
diff --git a/source/de/anomic/server/serverSystem.java b/source/de/anomic/server/serverSystem.java
index afac6c399..53019d2b1 100644
--- a/source/de/anomic/server/serverSystem.java
+++ b/source/de/anomic/server/serverSystem.java
@@ -71,8 +71,8 @@ public final class serverSystem {
// static initialization
static {
// check operation system type
- Properties sysprop = System.getProperties();
- String sysname = sysprop.getProperty("os.name","").toLowerCase();
+ final Properties sysprop = System.getProperties();
+ final String sysname = sysprop.getProperty("os.name","").toLowerCase();
if (sysname.startsWith("mac os x")) systemOS = systemMacOSX;
else if (sysname.startsWith("mac os")) systemOS = systemMacOSC;
else if (sysname.startsWith("windows")) systemOS = systemWindows;
@@ -94,12 +94,12 @@ public final class serverSystem {
macSetFileCreator = macMRJFileUtils.getMethod("setFileCreator", new Class[] {Class.forName("java.io.File"), macMRJOSType});
macMRJOSTypeConstructor = macMRJOSType.getConstructor(new Class[] {Class.forName("java.lang.String")});
macOpenURL = macMRJFileUtils.getMethod("openURL", new Class[] {Class.forName("java.lang.String")});
- byte[] nullb = new byte[4];
+ final byte[] nullb = new byte[4];
for (int i = 0; i < 4; i++) nullb[i] = 0;
macMRJOSNullObj = macMRJOSTypeConstructor.newInstance(new Object[] {new String(nullb)});
macFSTypeCache = new Hashtable<String, String>();
macFSCreatorCache = new Hashtable<String, String>();
- } catch (Exception e) {
+ } catch (final Exception e) {
//e.printStackTrace();
macMRJFileUtils = null; macMRJOSType = null;
}
@@ -112,97 +112,97 @@ public final class serverSystem {
return systemOS == systemWindows;
}*/
- public static Object getMacOSTS(String s) {
+ public static Object getMacOSTS(final String s) {
if ((isMacArchitecture) && (macMRJFileUtils != null)) try {
if ((s == null) || (s.equals(blankTypeString))) return macMRJOSNullObj;
else return macMRJOSTypeConstructor.newInstance(new Object[] {s});
- } catch (Exception e) {
+ } catch (final Exception e) {
return macMRJOSNullObj;
} else return null;
}
- public static String getMacFSType(File f) {
+ public static String getMacFSType(final File f) {
if ((isMacArchitecture) && (macMRJFileUtils != null)) try {
- String s = macGetFileType.invoke(null, new Object[] {f}).toString();
+ final String s = macGetFileType.invoke(null, new Object[] {f}).toString();
if ((s == null) || (s.charAt(0) == 0)) return blankTypeString; else return s;
- } catch (Exception e) {
+ } catch (final Exception e) {
return null;
} else return null;
}
- public static String getMacFSCreator(File f) {
+ public static String getMacFSCreator(final File f) {
if ((isMacArchitecture) && (macMRJFileUtils != null)) try {
- String s = macGetFileCreator.invoke(null, new Object[] {f}).toString();
+ final String s = macGetFileCreator.invoke(null, new Object[] {f}).toString();
if ((s == null) || (s.charAt(0) == 0)) return blankTypeString; else return s;
- } catch (Exception e) {
+ } catch (final Exception e) {
return null;
} else return null;
}
- public static void setMacFSType(File f, String t) {
+ public static void setMacFSType(final File f, final String t) {
if ((isMacArchitecture) && (macMRJFileUtils != null)) try {
macSetFileType.invoke(null, new Object[] {f, getMacOSTS(t)});
- } catch (Exception e) {/*System.out.println(e.getMessage()); e.printStackTrace();*/}
+ } catch (final Exception e) {/*System.out.println(e.getMessage()); e.printStackTrace();*/}
}
- public static void setMacFSCreator(File f, String t) {
+ public static void setMacFSCreator(final File f, final String t) {
if ((isMacArchitecture) && (macMRJFileUtils != null)) try {
macSetFileCreator.invoke(null, new Object[] {f, getMacOSTS(t)});
- } catch (Exception e) {/*System.out.println(e.getMessage()); e.printStackTrace();*/}
+ } catch (final Exception e) {/*System.out.println(e.getMessage()); e.printStackTrace();*/}
}
- public static boolean aquireMacFSType(File f) {
+ public static boolean aquireMacFSType(final File f) {
if ((!(isMacArchitecture)) || (macMRJFileUtils == null)) return false;
- String name = f.toString();
+ final String name = f.toString();
// check file type
- int dot = name.lastIndexOf(".");
+ final int dot = name.lastIndexOf(".");
if ((dot < 0) || (dot + 1 >= name.length())) return false;
- String type = getMacFSType(f);
+ final String type = getMacFSType(f);
if ((type == null) || (type.equals(blankTypeString))) return false;
- String ext = name.substring(dot + 1).toLowerCase();
- String oldType = macFSTypeCache.get(ext);
+ final String ext = name.substring(dot + 1).toLowerCase();
+ final String oldType = macFSTypeCache.get(ext);
if ((oldType != null) && (oldType.equals(type))) return false;
macFSTypeCache.put(ext, type);
return true;
}
- public static boolean aquireMacFSCreator(File f) {
+ public static boolean aquireMacFSCreator(final File f) {
if ((!(isMacArchitecture)) || (macMRJFileUtils == null)) return false;
- String name = f.toString();
+ final String name = f.toString();
// check creator
- String creator = getMacFSCreator(f);
+ final String creator = getMacFSCreator(f);
if ((creator == null) || (creator.equals(blankTypeString))) return false;
- String oldCreator = macFSCreatorCache.get(name);
+ final String oldCreator = macFSCreatorCache.get(name);
if ((oldCreator != null) && (oldCreator.equals(creator))) return false;
macFSCreatorCache.put(name, creator);
return true;
}
- public static boolean applyMacFSType(File f) {
+ public static boolean applyMacFSType(final File f) {
if ((!(isMacArchitecture)) || (macMRJFileUtils == null)) return false;
- String name = f.toString();
+ final String name = f.toString();
// reconstruct file type
- int dot = name.lastIndexOf(".");
+ final int dot = name.lastIndexOf(".");
if ((dot < 0) || (dot + 1 >= name.length())) return false;
- String type = macFSTypeCache.get(name.substring(dot + 1).toLowerCase());
+ final String type = macFSTypeCache.get(name.substring(dot + 1).toLowerCase());
if (type == null) return false;
- String oldType = getMacFSType(f);
+ final String oldType = getMacFSType(f);
if ((oldType != null) && (oldType.equals(type))) return false;
setMacFSType(f, type);
return getMacFSType(f).equals(type);
}
- public static boolean applyMacFSCreator(File f) {
+ public static boolean applyMacFSCreator(final File f) {
if ((!(isMacArchitecture)) || (macMRJFileUtils == null)) return false;
- String name = f.toString();
+ final String name = f.toString();
// reconstruct file creator
- String creator = macFSCreatorCache.get(name);
+ final String creator = macFSCreatorCache.get(name);
if (creator == null) return false;
- String oldCreator = getMacFSCreator(f);
+ final String oldCreator = getMacFSCreator(f);
if ((oldCreator != null) && (oldCreator.equals(creator))) return false;
//System.out.println("***Setting creator for " + f.toString() + " to " + creator);
setMacFSCreator(f, creator);
@@ -238,15 +238,15 @@ public final class serverSystem {
return s;
}
- private static String errorResponse(Process p) {
- BufferedReader err = new BufferedReader(new InputStreamReader(p.getErrorStream()));
+ private static String errorResponse(final Process p) {
+ final BufferedReader err = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String line, error = "";
try {
while ((line = err.readLine()) != null) {
error = line + "\n";
}
return error;
- } catch (IOException e) {
+ } catch (final IOException e) {
return null;
}
}
@@ -270,11 +270,11 @@ public final class serverSystem {
}
*/
- public static void openBrowser(String url) {
+ public static void openBrowser(final String url) {
openBrowser(url, "firefox");
}
- public static void openBrowser(String url, String app) {
+ public static void openBrowser(final String url, final String app) {
try {
String cmd;
Process p;
@@ -307,24 +307,24 @@ public final class serverSystem {
if (p.exitValue() != 0) throw new RuntimeException("EXEC ERROR: " + errorResponse(p));
}
}
- } catch (Exception e) {
+ } catch (final Exception e) {
System.out.println("please start your browser and open the following location: " + url);
}
}
- public static void deployScript(File scriptFile, String theScript) throws IOException {
+ public static void deployScript(final File scriptFile, final String theScript) throws IOException {
serverFileUtils.copy(theScript.getBytes(), scriptFile);
if(!isWindows){ // set executable
try {
Runtime.getRuntime().exec("chmod 755 " + scriptFile.getAbsolutePath().replaceAll(" ", "\\ ")).waitFor();
- } catch (InterruptedException e) {
+ } catch (final InterruptedException e) {
serverLog.logSevere("DEPLOY", "deploy of script file failed. file = " + scriptFile.getAbsolutePath(), e);
throw new IOException(e.getMessage());
}
}
}
- public static void execAsynchronous(File scriptFile) throws IOException {
+ public static void execAsynchronous(final File scriptFile) throws IOException {
// runs a script as separate thread
String starterFileExtension = null;
String script = null;
@@ -336,34 +336,34 @@ public final class serverSystem {
starterFileExtension = ".starter.sh";
script = "#!/bin/sh" + serverCore.LF_STRING + scriptFile.getAbsolutePath().replaceAll(" ", "\\ ") + " &" + serverCore.LF_STRING;
}
- File starterFile = new File(scriptFile.getAbsolutePath().replaceAll(" ", "\\ ") + starterFileExtension);
+ final File starterFile = new File(scriptFile.getAbsolutePath().replaceAll(" ", "\\ ") + starterFileExtension);
deployScript(starterFile, script);
try {
Runtime.getRuntime().exec(starterFile.getAbsolutePath().replaceAll(" ", "\\ ")).waitFor();
- } catch (InterruptedException e) {
+ } catch (final InterruptedException e) {
throw new IOException(e.getMessage());
}
starterFile.delete();
}
- public static Vector<String> execSynchronous(String command) throws IOException {
+ public static Vector<String> execSynchronous(final String command) throws IOException {
// runs a unix/linux command and returns output as Vector of Strings
// this method blocks until the command is executed
- Process p = Runtime.getRuntime().exec(command);
- BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
+ final Process p = Runtime.getRuntime().exec(command);
+ final BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String text;
- Vector<String> output = new Vector<String>();
+ final Vector<String> output = new Vector<String>();
while ((text = in.readLine()) != null) {
output.add(text);
}
return output;
}
- public static void main(String[] args) {
+ public static void main(final String[] args) {
//try{System.getProperties().list(new PrintStream(new FileOutputStream(new File("system.properties.txt"))));} catch (FileNotFoundException e) {}
//System.out.println("nullstr=" + macMRJOSNullObj.toString());
if (args[0].equals("-f")) {
- File f = new File(args[1]);
+ final File f = new File(args[1]);
System.out.println("File " + f.toString() + ": creator = " + getMacFSCreator(f) + "; type = " + getMacFSType(f));
}
if (args[0].equals("-u")) {
diff --git a/source/de/anomic/server/servletProperties.java b/source/de/anomic/server/servletProperties.java
index 850b9520f..21e419a8d 100644
--- a/source/de/anomic/server/servletProperties.java
+++ b/source/de/anomic/server/servletProperties.java
@@ -43,11 +43,11 @@ public class servletProperties extends serverObjects {
super();
}
- public servletProperties(serverObjects so) {
+ public servletProperties(final serverObjects so) {
super(so);
}
- public void setOutgoingHeader(httpHeader outgoingHeader) {
+ public void setOutgoingHeader(final httpHeader outgoingHeader) {
this.outgoingHeader = outgoingHeader;
}
@@ -58,35 +58,35 @@ public class servletProperties extends serverObjects {
return new httpHeader();
}
- public void setPrefix(String myprefix) {
+ public void setPrefix(final String myprefix) {
prefix=myprefix;
}
- public String put(String key, byte[] value) {
+ public String put(final String key, final byte[] value) {
return super.put(prefix + key, value);
}
- public long put(String key, long value) {
+ public long put(final String key, final long value) {
return super.put(prefix + key, value);
}
- public long inc(String key) {
+ public long inc(final String key) {
return super.inc(prefix+key);
}
- public Object get(String key, Object dflt) {
+ public Object get(final String key, final Object dflt) {
return super.get(prefix+key, dflt);
}
- public String get(String key, String dflt) {
+ public String get(final String key, final String dflt) {
return super.get(prefix+key, dflt);
}
- public int getInt(String key, int dflt) {
+ public int getInt(final String key, final int dflt) {
return super.getInt(prefix+key, dflt);
}
- public long getLong(String key, long dflt) {
+ public long getLong(final String key, final long dflt) {
return super.getLong(prefix+key, dflt);
}
}
diff --git a/source/de/anomic/tools/ListDirs.java b/source/de/anomic/tools/ListDirs.java
index 9bbccc655..5db3cad4f 100644
--- a/source/de/anomic/tools/ListDirs.java
+++ b/source/de/anomic/tools/ListDirs.java
@@ -27,23 +27,23 @@
package de.anomic.tools;
import java.io.File;
-import java.util.jar.JarFile;
-import java.util.jar.JarEntry;
-import java.util.Enumeration;
-import java.util.ArrayList;
+import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
-import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.jar.JarEntry;
+import java.util.jar.JarFile;
public class ListDirs {
private boolean isJar = false;
private File FileObject = null;
private JarFile JarFileObject = null;
- private String uri;
+ private final String uri;
private String pathInJar;
- public ListDirs(String uri) throws IOException, URISyntaxException {
+ public ListDirs(final String uri) throws IOException, URISyntaxException {
this.uri = uri;
if(uri.startsWith("jar:")) {
isJar = true;
@@ -54,10 +54,10 @@ public class ListDirs {
}
}
- public ArrayList<String> listFiles(String regex) {
- ArrayList<String> files = getAllFiles();
- ArrayList<String> classes = new ArrayList<String>();
- for(String file: files) {
+ public ArrayList<String> listFiles(final String regex) {
+ final ArrayList<String> files = getAllFiles();
+ final ArrayList<String> classes = new ArrayList<String>();
+ for(final String file: files) {
if(file.matches(regex)) {
classes.add(file);
}
@@ -66,28 +66,28 @@ public class ListDirs {
}
private ArrayList<String> getAllFiles() {
- ArrayList<String> files = new ArrayList<String>(50);
+ final ArrayList<String> files = new ArrayList<String>(50);
if(isJar) {
- Enumeration<JarEntry> entries = JarFileObject.entries();
+ final Enumeration<JarEntry> entries = JarFileObject.entries();
while(entries.hasMoreElements()) {
- JarEntry entry = entries.nextElement();
- String entryname = entry.getName();
+ final JarEntry entry = entries.nextElement();
+ final String entryname = entry.getName();
if(entryname.startsWith(pathInJar) && entryname.charAt(entryname.length()-1)!='/') {
files.add(entryname);
}
}
} else {
- for(File file: getFilesRecursive(FileObject)) {
+ for(final File file: getFilesRecursive(FileObject)) {
files.add(file.toString());
}
}
return files;
}
- private ArrayList<File> getFilesRecursive(File start) {
- File[] fileList = start.listFiles();
- ArrayList<File> completeList = new ArrayList<File>();
- for(File file: fileList) {
+ private ArrayList<File> getFilesRecursive(final File start) {
+ final File[] fileList = start.listFiles();
+ final ArrayList<File> completeList = new ArrayList<File>();
+ for(final File file: fileList) {
if(file.isDirectory()) {
completeList.addAll(getFilesRecursive(file));
} else {
diff --git a/source/de/anomic/tools/PKCS12Tool.java b/source/de/anomic/tools/PKCS12Tool.java
index 1b144e066..18536b25d 100644
--- a/source/de/anomic/tools/PKCS12Tool.java
+++ b/source/de/anomic/tools/PKCS12Tool.java
@@ -42,10 +42,10 @@ import java.util.Enumeration;
public class PKCS12Tool {
- private KeyStore kspkcs12;
- private String kspkcs12Pass;
+ private final KeyStore kspkcs12;
+ private final String kspkcs12Pass;
- public PKCS12Tool(String pkcs12FileName, String pkcs12Pwd) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException {
+ public PKCS12Tool(final String pkcs12FileName, final String pkcs12Pwd) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException {
if (pkcs12FileName == null) throw new NullPointerException();
this.kspkcs12Pass = pkcs12Pwd;
@@ -53,7 +53,7 @@ public class PKCS12Tool {
this.kspkcs12 = KeyStore.getInstance("PKCS12");
// load pkcs12 file into keystore object
- FileInputStream fileIn = new FileInputStream(pkcs12FileName);
+ final FileInputStream fileIn = new FileInputStream(pkcs12FileName);
this.kspkcs12.load(fileIn,(pkcs12Pwd!=null)?pkcs12Pwd.toCharArray():null);
// close stream
@@ -65,19 +65,19 @@ public class PKCS12Tool {
}
public void printAliases() throws KeyStoreException {
- Enumeration<String> aliases = aliases();
+ final Enumeration<String> aliases = aliases();
while (aliases.hasMoreElements()) {
System.out.println(aliases.nextElement());
}
}
- public void importToJKS(String jksName, String jksPassword) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException {
+ public void importToJKS(final String jksName, final String jksPassword) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException {
// creating java keystore
- KeyStore jks=KeyStore.getInstance("JKS");
+ final KeyStore jks=KeyStore.getInstance("JKS");
// loading keystore from file
FileInputStream jksFileIn = null;
- File jksFile = new File(jksName);
+ final File jksFile = new File(jksName);
if (jksFile.exists()) {
System.err.println("Loading java keystore from file '" + jksFile + "'");
@@ -88,17 +88,17 @@ public class PKCS12Tool {
jks.load(jksFileIn,(jksPassword!=null)?jksPassword.toCharArray():null);
if (jksFileIn != null) jksFileIn.close();
- Enumeration<String> pkcs12Aliases = aliases();
+ final Enumeration<String> pkcs12Aliases = aliases();
while (pkcs12Aliases.hasMoreElements()) {
- String strAlias = pkcs12Aliases.nextElement();
+ final String strAlias = pkcs12Aliases.nextElement();
System.err.println("Importing Alias '" + strAlias + "'");
if (this.kspkcs12.isKeyEntry(strAlias)) {
System.err.println("- Alias has key");
- Key key = this.kspkcs12.getKey(strAlias, (this.kspkcs12Pass!=null)?this.kspkcs12Pass.toCharArray():null);
+ final Key key = this.kspkcs12.getKey(strAlias, (this.kspkcs12Pass!=null)?this.kspkcs12Pass.toCharArray():null);
System.err.println("- Alias key imported");
- Certificate[] chain = this.kspkcs12.getCertificateChain(strAlias);
+ final Certificate[] chain = this.kspkcs12.getCertificateChain(strAlias);
System.err.println("- Alias certificate chain size: " + chain.length);
jks.setKeyEntry(strAlias, key, (jksPassword!=null)?jksPassword.toCharArray():null, chain);
@@ -107,7 +107,7 @@ public class PKCS12Tool {
// storing jdk into file
System.err.print("Storing java keystore");
- FileOutputStream jksFileOut = new FileOutputStream(jksName);
+ final FileOutputStream jksFileOut = new FileOutputStream(jksName);
jks.store(jksFileOut,(jksPassword!=null)?jksPassword.toCharArray():null);
jksFileOut.close();
System.err.print("Import finished.");
@@ -116,8 +116,8 @@ public class PKCS12Tool {
/**
* @param args
*/
- public static void main(String[] args) throws Exception {
- PKCS12Tool pkcs12 = new PKCS12Tool("c:/temp/keystore.pkcs12","test");
+ public static void main(final String[] args) throws Exception {
+ final PKCS12Tool pkcs12 = new PKCS12Tool("c:/temp/keystore.pkcs12","test");
//pkcs12.printAliases();
pkcs12.importToJKS("c:/temp/jks.ks", "test");
}
diff --git a/source/de/anomic/tools/Punycode.java b/source/de/anomic/tools/Punycode.java
index eeea62f54..54cfec1af 100644
--- a/source/de/anomic/tools/Punycode.java
+++ b/source/de/anomic/tools/Punycode.java
@@ -42,18 +42,18 @@ public class Punycode
* @param input Unicode string.
* @return Punycoded string.
*/
- public static String encode(String input)
+ public static String encode(final String input)
throws PunycodeException
{
int n = INITIAL_N;
int delta = 0;
int bias = INITIAL_BIAS;
- StringBuffer output = new StringBuffer();
+ final StringBuffer output = new StringBuffer();
// Copy all basic code points to the output
int b = 0;
for (int i = 0; i < input.length(); i++) {
- char c = input.charAt(i);
+ final char c = input.charAt(i);
if (isBasic(c)) {
output.append(c);
b++;
@@ -71,7 +71,7 @@ public class Punycode
// Find the minimum code point >= n
for (int i = 0; i < input.length(); i++) {
- int c = input.charAt(i);
+ final int c = input.charAt(i);
if (c >= n && c < m) {
m = c;
}
@@ -84,7 +84,7 @@ public class Punycode
n = m;
for (int j = 0; j < input.length(); j++) {
- int c = input.charAt(j);
+ final int c = input.charAt(j);
if (c < n) {
delta++;
if (0 == delta) {
@@ -130,18 +130,18 @@ public class Punycode
* @param input Punycode string
* @return Unicode string.
*/
- public static String decode(String input)
+ public static String decode(final String input)
throws PunycodeException
{
int n = INITIAL_N;
int i = 0;
int bias = INITIAL_BIAS;
- StringBuffer output = new StringBuffer();
+ final StringBuffer output = new StringBuffer();
int d = input.lastIndexOf(DELIMITER);
if (d > 0) {
for (int j = 0; j < d; j++) {
- char c = input.charAt(j);
+ final char c = input.charAt(j);
if (!isBasic(c)) {
throw new PunycodeException(PunycodeException.BAD_INPUT);
}
@@ -153,15 +153,15 @@ public class Punycode
}
while (d < input.length()) {
- int oldi = i;
+ final int oldi = i;
int w = 1;
for (int k = BASE; ; k += BASE) {
if (d == input.length()) {
throw new PunycodeException(PunycodeException.BAD_INPUT);
}
- int c = input.charAt(d++);
- int digit = codepoint2digit(c);
+ final int c = input.charAt(d++);
+ final int digit = codepoint2digit(c);
if (digit > (Integer.MAX_VALUE - i) / w) {
throw new PunycodeException(PunycodeException.OVERFLOW);
}
@@ -197,7 +197,7 @@ public class Punycode
return output.toString();
}
- public final static int adapt(int delta, int numpoints, boolean first)
+ public final static int adapt(int delta, final int numpoints, final boolean first)
{
if (first) {
delta = delta / DAMP;
@@ -216,20 +216,20 @@ public class Punycode
return k + ((BASE - TMIN + 1) * delta) / (delta + SKEW);
}
- public final static boolean isBasic(char c)
+ public final static boolean isBasic(final char c)
{
return c < 0x80;
}
// the following method has been added by Michael Christen
- public static boolean isBasic(String input) {
+ public static boolean isBasic(final String input) {
for (int j = 0; j < input.length(); j++) {
if (!isBasic(input.charAt(j))) return false;
}
return true;
}
- public final static int digit2codepoint(int d)
+ public final static int digit2codepoint(final int d)
throws PunycodeException
{
if (d < 26) {
@@ -243,7 +243,7 @@ public class Punycode
}
}
- public final static int codepoint2digit(int c)
+ public final static int codepoint2digit(final int c)
throws PunycodeException
{
if (c - '0' < 10) {
@@ -272,7 +272,7 @@ public class Punycode
*
* @param m message.
*/
- public PunycodeException(String m)
+ public PunycodeException(final String m)
{
super(m);
}
diff --git a/source/de/anomic/tools/bbCode.java b/source/de/anomic/tools/bbCode.java
index e932f72ee..40605bde1 100644
--- a/source/de/anomic/tools/bbCode.java
+++ b/source/de/anomic/tools/bbCode.java
@@ -39,7 +39,7 @@ public class bbCode {
*@author Marc Nause
*@return String
*/
- public String escapeHtml(String input){
+ public String escapeHtml(final String input){
String output = "";
int iter = 0;
@@ -59,7 +59,7 @@ public class bbCode {
*@author Roland Ramthun
*@return String
*/
- public String bb(String input){
+ public String bb(final String input){
String output = escapeHtml(input);
//Parse bold
output = output.replaceAll("\\[b\\]", "<b>");
diff --git a/source/de/anomic/tools/bitfield.java b/source/de/anomic/tools/bitfield.java
index b502f7a59..8a366a0c2 100644
--- a/source/de/anomic/tools/bitfield.java
+++ b/source/de/anomic/tools/bitfield.java
@@ -29,27 +29,27 @@ public class bitfield {
this(0);
}
- public bitfield(int bytelength) {
+ public bitfield(final int bytelength) {
this.bb= new byte[bytelength];
for (int i = 0 ; i < bytelength; i++) bb[i] = 0;
}
- public bitfield(byte[] field) {
+ public bitfield(final byte[] field) {
bb = field;
}
- private static byte setAtom(byte a, int pos) {
+ private static byte setAtom(final byte a, final int pos) {
if ((pos > 5) || (pos < 0)) throw new RuntimeException("atom position out of bounds: " + pos);
return (byte) ((64 | ((a + 16) | (1<<pos))) - 16);
}
- private static byte unsetAtom(byte a, int pos) {
+ private static byte unsetAtom(final byte a, final int pos) {
if ((pos > 5) || (pos < 0)) throw new RuntimeException("atom position out of bounds: " + pos);
return (byte) (((a + 16) & (0xff ^ (1<<pos))) - 16);
}
- public void set(int pos, boolean value) {
- int slot = pos / 6;
+ public void set(final int pos, final boolean value) {
+ final int slot = pos / 6;
if (pos < 0) throw new RuntimeException("position out of bounds: " + pos);
if (slot > bb.length) {
// extend capacity
@@ -62,8 +62,8 @@ public class bitfield {
bb[slot] = (value) ? setAtom(bb[slot], pos % 6) : unsetAtom(bb[slot], pos % 6);
}
- public boolean get(int pos) {
- int slot = pos / 6;
+ public boolean get(final int pos) {
+ final int slot = pos / 6;
if (pos < 0) throw new RuntimeException("position out of bounds: " + pos);
if (slot > bb.length) return false;
return (bb[slot] & (1<<(pos%6))) > 0;
@@ -86,9 +86,9 @@ public class bitfield {
*/
}
- public static void main(String[] args) {
- bitfield test = new bitfield(4);
- int l = test.length();
+ public static void main(final String[] args) {
+ final bitfield test = new bitfield(4);
+ final int l = test.length();
System.out.println("available: " + l);
System.out.println("before: " + test.toString());
for (int i = 0; i < l/2; i++) {
diff --git a/source/de/anomic/tools/consoleInterface.java b/source/de/anomic/tools/consoleInterface.java
index 4695ac521..16bdd1b1a 100755
--- a/source/de/anomic/tools/consoleInterface.java
+++ b/source/de/anomic/tools/consoleInterface.java
@@ -39,10 +39,10 @@ public class consoleInterface extends Thread
* FIXME just for debugging
*/
//private final String name;
- private serverLog log;
+ private final serverLog log;
- public consoleInterface(final InputStream stream, String name, serverLog log)
+ public consoleInterface(final InputStream stream, final String name, final serverLog log)
{
this.log = log;
this.stream = stream;
@@ -50,7 +50,7 @@ public class consoleInterface extends Thread
// block reading {@see getOutput()}
try {
dataIsRead.acquire();
- } catch (InterruptedException e) {
+ } catch (final InterruptedException e) {
// this should never happen because this is a constructor
e.printStackTrace();
}
@@ -68,7 +68,7 @@ public class consoleInterface extends Thread
try {
// may block!
Thread.sleep(1);
- } catch (InterruptedException e) {
+ } catch (final InterruptedException e) {
// just stop sleeping
}
if (buffer.ready())
@@ -94,7 +94,7 @@ public class consoleInterface extends Thread
//final long start = System.currentTimeMillis();
dataIsRead.acquire();
//log.logInfo("logpoint 5 data ready for '"+ name +"' after "+ (System.currentTimeMillis() - start) +" ms");
- } catch (InterruptedException e) {
+ } catch (final InterruptedException e) {
// after interrupt just return what is available (maybe nothing)
}
// is just for checking availability, so release it immediatly
diff --git a/source/de/anomic/tools/crypt.java b/source/de/anomic/tools/crypt.java
index 47cda7213..6d047300c 100644
--- a/source/de/anomic/tools/crypt.java
+++ b/source/de/anomic/tools/crypt.java
@@ -60,15 +60,15 @@ public class crypt {
String cryptMethod; // one of ["TripleDES", "Blowfish", "DESede", "DES"]
private static final String defaultMethod = "PBEWithMD5AndDES"; //"DES";
- public crypt(String pbe) {
+ public crypt(final String pbe) {
// this is possible, but not recommended
this(pbe, (pbe + "XXXXXXXX").substring(0, 8));
}
- public crypt(String pbe, String salt) {
+ public crypt(final String pbe, final String salt) {
this(pbe, salt, defaultMethod);
}
- private crypt(String pbe, String salt, String method) {
+ private crypt(final String pbe, String salt, final String method) {
// a Password-Based Encryption. The SecretKey is created on the fly
if (salt.length() > 8) salt = salt.substring(0,8);
if (salt.length() < 8) salt = (salt + "XXXXXXXX").substring(0,8);
@@ -81,15 +81,15 @@ public class crypt {
// Section: simple Codings
// --------------------------------------------------------
- public static String simpleEncode(String content) {
+ public static String simpleEncode(final String content) {
return simpleEncode(content, null, 'b');
}
- public static String simpleEncode(String content, String key) {
+ public static String simpleEncode(final String content, final String key) {
return simpleEncode(content, key, 'b');
}
- public static String simpleEncode(String content, String key, char method) {
+ public static String simpleEncode(final String content, String key, final char method) {
if (key == null) { key = "NULL"; }
switch (method) {
case 'b' : return "b|" + kelondroBase64Order.enhancedCoder.encodeString(content);
@@ -99,7 +99,7 @@ public class crypt {
}
}
- public static String simpleDecode(String encoded, String key) {
+ public static String simpleDecode(final String encoded, final String key) {
if (encoded == null || encoded.length() < 3) {
return null;
}
@@ -113,7 +113,7 @@ public class crypt {
case 'z':
try {
return gzip.gunzipString(kelondroBase64Order.enhancedCoder.decode(encoded.substring(2), "de.anomic.tools.crypt.simpleDecode()"));
- } catch (Exception e) {
+ } catch (final Exception e) {
e.printStackTrace();
return null;
}
@@ -126,8 +126,8 @@ public class crypt {
}
}
- public static void main(String[] args) {
- String teststring="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
+ public static void main(final String[] args) {
+ final String teststring="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println("Teststring = " + teststring);
System.out.println("enc-b result = " + simpleDecode(simpleEncode(teststring, null, 'b'), null));
System.out.println("enc-z result = " + simpleDecode(simpleEncode(teststring, null, 'z'), null));
diff --git a/source/de/anomic/tools/cryptbig.java b/source/de/anomic/tools/cryptbig.java
index c95cf1cad..0b4d1d628 100644
--- a/source/de/anomic/tools/cryptbig.java
+++ b/source/de/anomic/tools/cryptbig.java
@@ -66,7 +66,7 @@ public class cryptbig {
public static String randomSalt() {
// generate robust 48-bit random number
- long salt = (saltrandom.nextLong() & 0XffffffffffffL) + (System.currentTimeMillis() & 0XffffffffffffL) + ((1001 * saltcounter) & 0XffffffffffffL);
+ final long salt = (saltrandom.nextLong() & 0XffffffffffffL) + (System.currentTimeMillis() & 0XffffffffffffL) + ((1001 * saltcounter) & 0XffffffffffffL);
saltcounter++;
// we generate 48-bit salt values, that are represented as 8-character
// b64-encoded strings
@@ -88,29 +88,29 @@ public class cryptbig {
Cipher ecipher;
Cipher dcipher;
- public cryptbig(String pbe) {
+ public cryptbig(final String pbe) {
// this is possible, but not recommended
this(pbe, (pbe + "XXXXXXXX").substring(0, 8));
}
- public cryptbig(String pbe, String salt) {
+ public cryptbig(final String pbe, final String salt) {
this(pbe, salt, defaultMethod);
}
- private cryptbig(String pbe, String salt, String method) {
+ private cryptbig(final String pbe, String salt, final String method) {
// a Password-Based Encryption. The SecretKey is created on the fly
- PBEKeySpec keySpec = new PBEKeySpec(pbe.toCharArray());
+ final PBEKeySpec keySpec = new PBEKeySpec(pbe.toCharArray());
try {
if (salt.length() > 8) salt = salt.substring(0,8);
if (salt.length() < 8) salt = (salt + "XXXXXXXX").substring(0,8);
// create the PBE key
- SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(method);
- SecretKey key = keyFactory.generateSecret(keySpec);
+ final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(method);
+ final SecretKey key = keyFactory.generateSecret(keySpec);
// create parameter spec for PBE
- PBEParameterSpec paramSpec = new PBEParameterSpec(salt.getBytes(), 1000 /*ITERATIONS*/);
+ final PBEParameterSpec paramSpec = new PBEParameterSpec(salt.getBytes(), 1000 /*ITERATIONS*/);
// Create a cipher and initialize it for encrypting end decrypting
cryptMethod = method;
@@ -118,72 +118,72 @@ public class cryptbig {
dcipher = Cipher.getInstance(cryptMethod);
ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec); // paramSpec only for PBE!
dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
- } catch (javax.crypto.NoSuchPaddingException e) {
- } catch (java.security.InvalidKeyException e) {
- } catch (java.security.NoSuchAlgorithmException e) {
- } catch (java.security.spec.InvalidKeySpecException e) {
- } catch (java.security.InvalidAlgorithmParameterException e) {
+ } catch (final javax.crypto.NoSuchPaddingException e) {
+ } catch (final java.security.InvalidKeyException e) {
+ } catch (final java.security.NoSuchAlgorithmException e) {
+ } catch (final java.security.spec.InvalidKeySpecException e) {
+ } catch (final java.security.InvalidAlgorithmParameterException e) {
}
}
// Encode a string into a new string using utf-8, crypt and b64
- public String encryptString(String str) {
+ public String encryptString(final String str) {
try {
- byte[] utf = str.getBytes("UTF8");
- byte[] enc = encryptArray(utf);
+ final byte[] utf = str.getBytes("UTF8");
+ final byte[] enc = encryptArray(utf);
if (enc == null) return null;
return kelondroBase64Order.standardCoder.encode(enc);
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
}
return null;
}
// Decode a string into a new string using b64, crypt and utf-8
- public String decryptString(String str) {
+ public String decryptString(final String str) {
try {
- byte[] b64dec = kelondroBase64Order.standardCoder.decode(str, "de.anomic.tools.cryptbig.decryptString()");
+ final byte[] b64dec = kelondroBase64Order.standardCoder.decode(str, "de.anomic.tools.cryptbig.decryptString()");
if (b64dec == null) return null; // error in input string (inconsistency)
- byte[] dec = decryptArray(b64dec);
+ final byte[] dec = decryptArray(b64dec);
if (dec == null) return null;
return new String(dec, "UTF-8");
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
}
return null;
}
// Encode a byte array into a new byte array
- public byte[] encryptArray(byte[] b) {
+ public byte[] encryptArray(final byte[] b) {
if (b == null) return null;
try {
return ecipher.doFinal(b);
- } catch (javax.crypto.BadPaddingException e) {
- } catch (IllegalBlockSizeException e) {
+ } catch (final javax.crypto.BadPaddingException e) {
+ } catch (final IllegalBlockSizeException e) {
}
return null;
}
// Decode a string into a new string using b64, crypt and utf-8
- public byte[] decryptArray(byte[] b) {
+ public byte[] decryptArray(final byte[] b) {
if (b == null) return null;
try {
return dcipher.doFinal(b);
- } catch (javax.crypto.BadPaddingException e) {
- } catch (IllegalBlockSizeException e) {
+ } catch (final javax.crypto.BadPaddingException e) {
+ } catch (final IllegalBlockSizeException e) {
}
return null;
}
// This method returns the available implementations for a service type
- public static Set<String> listCryptoMethods(String serviceType) {
- Set<String> result = new HashSet<String>();
+ public static Set<String> listCryptoMethods(final String serviceType) {
+ final Set<String> result = new HashSet<String>();
// All providers
- Provider[] providers = Security.getProviders();
+ final Provider[] providers = Security.getProviders();
for (int i = 0; i < providers.length; i++) {
// Get services provided by each provider
- Set<?> keys = providers[i].keySet();
- for (Iterator<?> it = keys.iterator(); it.hasNext(); ) {
+ final Set<?> keys = providers[i].keySet();
+ for (final Iterator<?> it = keys.iterator(); it.hasNext(); ) {
String key = (String) it.next();
key = key.split(" ")[0];
if (key.startsWith(serviceType + ".")) {
@@ -197,26 +197,26 @@ public class cryptbig {
return result;
}
- public static void testCryptMethods(Set<String> methods) {
+ public static void testCryptMethods(final Set<String> methods) {
String method;
- Iterator<String> i = methods.iterator();
+ final Iterator<String> i = methods.iterator();
while (i.hasNext()) {
method = i.next();
System.out.print(method + " : ");
try {
- cryptbig crypter = new cryptbig("abrakadabra", method);
- String encrypted = crypter.encryptString("nicht verraten abc 1234567890");
+ final cryptbig crypter = new cryptbig("abrakadabra", method);
+ final String encrypted = crypter.encryptString("nicht verraten abc 1234567890");
System.out.print(encrypted + "/");
- String decrypted = crypter.decryptString(encrypted);
+ final String decrypted = crypter.decryptString(encrypted);
System.out.println(decrypted);
- } catch (Exception e) {
+ } catch (final Exception e) {
System.out.println("Exception: " + e.getMessage());
e.printStackTrace();
}
}
}
- public void encryptFile(String inFileName, String outFileName, boolean compress) {
+ public void encryptFile(final String inFileName, final String outFileName, final boolean compress) {
/*
File-Format of encrypted file:
Filename: b64-of-encryption-of-<encryption-date: YYYYMMddHHmmSSsss> plus extension ".crypt"
@@ -229,13 +229,13 @@ public class cryptbig {
<binary>
*/
try {
- File inFile = new File(inFileName);
- String inFileDate = dateFormatter.format(new Date(inFile.lastModified())); // 17 byte
- String encryptionDate = dateFormatter.format(new Date()); // 17 byte
- String inFileSize = kelondroBase64Order.standardCoder.encodeLong(inFile.length(), 11); // 64 / 6 = 11; 11 byte
- String flag = "1"; // 1 byte
+ final File inFile = new File(inFileName);
+ final String inFileDate = dateFormatter.format(new Date(inFile.lastModified())); // 17 byte
+ final String encryptionDate = dateFormatter.format(new Date()); // 17 byte
+ final String inFileSize = kelondroBase64Order.standardCoder.encodeLong(inFile.length(), 11); // 64 / 6 = 11; 11 byte
+ final String flag = "1"; // 1 byte
//int inFileNameLength = inFileName.length(); // 256
- String X = inFileDate + encryptionDate + inFileSize + flag + inFileName;
+ final String X = inFileDate + encryptionDate + inFileSize + flag + inFileName;
System.out.println("TEST: preserving inFileDate : " + dateFormatter.parse(inFileDate, new ParsePosition(0)));
System.out.println("TEST: preserving encryptionDate: " + dateFormatter.parse(encryptionDate, new ParsePosition(0)));
@@ -245,8 +245,8 @@ public class cryptbig {
System.out.println("TEST: preserving X-String : " + X);
// start encryption
- InputStream fin = new CipherInputStream(new FileInputStream(inFile), ecipher);
- OutputStream fout = new FileOutputStream(outFileName);
+ final InputStream fin = new CipherInputStream(new FileInputStream(inFile), ecipher);
+ final OutputStream fout = new FileOutputStream(outFileName);
// write magic and properties of original file
// - we encrypt the original date, the encryption date, the file size, the flag
@@ -256,9 +256,9 @@ public class cryptbig {
// - the length of B is BL; BL is then b64-ed to a string C of fixed length 1
// - after the magic String we write C, B and A
try {
- String A = new String(ecipher.doFinal(X.getBytes("UTF8")));
- String B = new String(ecipher.doFinal(kelondroBase64Order.standardCoder.encodeLong(A.length(), 2).getBytes("UTF8"))); // most probable not longer than 4
- String C = kelondroBase64Order.standardCoder.encodeLong(B.length(), 1); // fixed length 1 (6 bits, that should be enough)
+ final String A = new String(ecipher.doFinal(X.getBytes("UTF8")));
+ final String B = new String(ecipher.doFinal(kelondroBase64Order.standardCoder.encodeLong(A.length(), 2).getBytes("UTF8"))); // most probable not longer than 4
+ final String C = kelondroBase64Order.standardCoder.encodeLong(B.length(), 1); // fixed length 1 (6 bits, that should be enough)
fout.write(magicString.getBytes()); // the magic string, used to identify a 'crypt'-file
fout.write(C.getBytes());
fout.write(B.getBytes());
@@ -267,19 +267,19 @@ public class cryptbig {
// write content of file
copy(fout, fin, 512);
}
- catch (javax.crypto.IllegalBlockSizeException e) {System.err.println("ERROR:" + e.getMessage());}
- catch (javax.crypto.BadPaddingException e) {System.err.println("ERROR:" + e.getMessage());}
+ catch (final javax.crypto.IllegalBlockSizeException e) {System.err.println("ERROR:" + e.getMessage());}
+ catch (final javax.crypto.BadPaddingException e) {System.err.println("ERROR:" + e.getMessage());}
// finished files
fin.close();
fout.close();
- } catch (FileNotFoundException e) {
+ } catch (final FileNotFoundException e) {
System.err.println("ERROR: file '" + inFileName + "' not found");
- } catch (IOException e) {
+ } catch (final IOException e) {
System.err.println("ERROR: IO trouble");
}
}
- public void decryptFile(String inFileName, String outFileName) {
+ public void decryptFile(final String inFileName, final String outFileName) {
InputStream fin = null;
OutputStream fout = null;
try {
@@ -287,26 +287,26 @@ public class cryptbig {
fin = new BufferedInputStream(new FileInputStream(inFileName), 4096);
// read the file properties
- byte[] thisMagic = new byte[magicString.length()]; fin.read(thisMagic);
+ final byte[] thisMagic = new byte[magicString.length()]; fin.read(thisMagic);
if (!((new String(thisMagic)).equals(magicString))) {
// this is not an crypt file, so dont do anything
fin.close();
return;
}
- byte[] C = new byte[1]; fin.read(C); // the length of the following String, encoded as b64
- byte[] B = new byte[(int) kelondroBase64Order.standardCoder.decodeLong(new String(C))]; fin.read(B); // this is again the length of the following string, as encrypted b64-ed integer
- byte[] A = new byte[(int) kelondroBase64Order.standardCoder.decodeLong(new String(dcipher.doFinal(B), "UTF8"))]; fin.read(A);
- String X = new String(dcipher.doFinal(A), "UTF8");
+ final byte[] C = new byte[1]; fin.read(C); // the length of the following String, encoded as b64
+ final byte[] B = new byte[(int) kelondroBase64Order.standardCoder.decodeLong(new String(C))]; fin.read(B); // this is again the length of the following string, as encrypted b64-ed integer
+ final byte[] A = new byte[(int) kelondroBase64Order.standardCoder.decodeLong(new String(dcipher.doFinal(B), "UTF8"))]; fin.read(A);
+ final String X = new String(dcipher.doFinal(A), "UTF8");
System.out.println("TEST: detecting X-String : " + X);
// reconstruct the properties
- Date inFileDate = dateFormatter.parse(X.substring(0, 17), new ParsePosition(0));
- Date encryptionDate = dateFormatter.parse(X.substring(17, 34), new ParsePosition(0));
- long inFileSize = kelondroBase64Order.standardCoder.decodeLong(X.substring(34, 45));
- String flag = X.substring(45, 46);
- String origFileName = X.substring(46);
+ final Date inFileDate = dateFormatter.parse(X.substring(0, 17), new ParsePosition(0));
+ final Date encryptionDate = dateFormatter.parse(X.substring(17, 34), new ParsePosition(0));
+ final long inFileSize = kelondroBase64Order.standardCoder.decodeLong(X.substring(34, 45));
+ final String flag = X.substring(45, 46);
+ final String origFileName = X.substring(46);
System.out.println("TEST: detecting inFileDate : " + inFileDate);
System.out.println("TEST: detecting encryptionDate: " + encryptionDate);
@@ -325,27 +325,27 @@ public class cryptbig {
fout.close();
// do postprocessing
- } catch (BadPaddingException e) {
+ } catch (final BadPaddingException e) {
System.err.println("ERROR: decryption of '" + inFileName + "' not possible: " + e.getMessage());
- } catch (IllegalBlockSizeException e) {
+ } catch (final IllegalBlockSizeException e) {
System.err.println("ERROR: decryption of '" + inFileName + "' not possible: " + e.getMessage());
- } catch (FileNotFoundException e) {
+ } catch (final FileNotFoundException e) {
System.err.println("ERROR: file '" + inFileName + "' not found");
- } catch (IOException e) {
+ } catch (final IOException e) {
System.err.println("ERROR: IO trouble");
try { if(fin != null) {
fin.close();
- }} catch (Exception ee) {}
+ }} catch (final Exception ee) {}
try { if(fout != null) {
fout.close();
- }} catch (Exception ee) {}
+ }} catch (final Exception ee) {}
}
}
- private static void copy(OutputStream out, InputStream in, int bufferSize) throws IOException {
- InputStream bIn = new BufferedInputStream(in, bufferSize);
- OutputStream bOut = new BufferedOutputStream(out, bufferSize);
- byte[] buf = new byte[bufferSize];
+ private static void copy(final OutputStream out, final InputStream in, final int bufferSize) throws IOException {
+ final InputStream bIn = new BufferedInputStream(in, bufferSize);
+ final OutputStream bOut = new BufferedOutputStream(out, bufferSize);
+ final byte[] buf = new byte[bufferSize];
int n;
while ((n = bIn.read(buf)) > 0) bOut.write(buf, 0, n);
bIn.close();
@@ -353,16 +353,16 @@ public class cryptbig {
}
- public static String scrambleString(String key, String s) {
+ public static String scrambleString(final String key, final String s) {
// we perform several operations
// - generate salt
// - gzip string
// - crypt string with key and salt
// - base64-encode result
// - attach salt and return
- String salt = randomSalt();
+ final String salt = randomSalt();
//System.out.println("Salt=" + salt);
- cryptbig c = new cryptbig(key, salt);
+ final cryptbig c = new cryptbig(key, salt);
boolean gzFlag = true;
byte[] gz = gzip.gzipString(s);
if (gz.length > s.length()) {
@@ -370,30 +370,30 @@ public class cryptbig {
try {
gz = s.getBytes("UTF8");
gzFlag = false;
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
return null;
}
}
//System.out.println("GZIP length=" + gz.length);
if (gz == null) return null;
- byte[] enc = c.encryptArray(gz);
+ final byte[] enc = c.encryptArray(gz);
if (enc == null) return null;
return salt + ((gzFlag) ? "1" : "0") + kelondroBase64Order.enhancedCoder.encode(enc);
}
- public static String descrambleString(String key, String s) throws IOException {
- String salt = s.substring(0, 8);
- boolean gzFlag = (s.charAt(8) == '1');
+ public static String descrambleString(final String key, String s) throws IOException {
+ final String salt = s.substring(0, 8);
+ final boolean gzFlag = (s.charAt(8) == '1');
s = s.substring(9);
- cryptbig c = new cryptbig(key, salt);
- byte[] b64dec = kelondroBase64Order.enhancedCoder.decode(s, "de.anomic.tools.cryptbig.descrambleString()");
+ final cryptbig c = new cryptbig(key, salt);
+ final byte[] b64dec = kelondroBase64Order.enhancedCoder.decode(s, "de.anomic.tools.cryptbig.descrambleString()");
if (b64dec == null) return null; // error in input string (inconsistency)
- byte[] dec = c.decryptArray(b64dec);
+ final byte[] dec = c.decryptArray(b64dec);
if (dec == null) return null;
if (gzFlag)
return gzip.gunzipString(dec);
else
- try {return new String(dec,"UTF8");} catch (UnsupportedEncodingException e) {return null;}
+ try {return new String(dec,"UTF8");} catch (final UnsupportedEncodingException e) {return null;}
}
@@ -403,15 +403,15 @@ public class cryptbig {
// --------------------------------------------------------
- public static String simpleEncode(String content) {
+ public static String simpleEncode(final String content) {
return simpleEncode(content, null, 'b');
}
- public static String simpleEncode(String content, String key) {
+ public static String simpleEncode(final String content, final String key) {
return simpleEncode(content, key, 'b');
}
- public static String simpleEncode(String content, String key, char method) {
+ public static String simpleEncode(final String content, String key, final char method) {
if (key == null) key = "NULL";
if (method == 'p') return "p|" + content;
if (method == 'b') return "b|" + kelondroBase64Order.enhancedCoder.encodeString(content);
@@ -420,10 +420,10 @@ public class cryptbig {
return null;
}
- public static String simpleDecode(String encoded, String key) throws IOException {
+ public static String simpleDecode(String encoded, final String key) throws IOException {
if ((encoded == null) || (encoded.length() < 3)) return null;
if (encoded.charAt(1) != '|') return encoded; // not encoded
- char method = encoded.charAt(0);
+ final char method = encoded.charAt(0);
encoded = encoded.substring(2);
if (method == 'p') return encoded;
if (method == 'b') return kelondroBase64Order.enhancedCoder.decodeString(encoded, "de.anomic.tools.cryptbig.simpleDecode()");
@@ -437,13 +437,13 @@ public class cryptbig {
// Section: one-way encryption
// --------------------------------------------------------
- public static String oneWayEncryption(String key) {
- cryptbig crypter = new cryptbig(key);
+ public static String oneWayEncryption(final String key) {
+ final cryptbig crypter = new cryptbig(key);
String e = crypter.encryptString(key);
if (e.length() == 0) e = "0XXXX";
if (e.length() % 2 == 1) e += "X";
while (e.length() < 32) e = e + e;
- char[] r = new char[16];
+ final char[] r = new char[16];
for (int i = 0; i < 16; i++) r[i] = e.charAt(2 * i + 1);
return new String(r);
}
@@ -544,7 +544,7 @@ public class cryptbig {
System.out.println("");
}
- public static void main(String[] s) {
+ public static void main(final String[] s) {
if (s.length == 0) {
help();
System.exit(0);
@@ -555,13 +555,13 @@ public class cryptbig {
}
if (s[0].equals("-tc")) {
// list all available crypt mehtods:
- Set<String> methods = listCryptoMethods("Cipher");
+ final Set<String> methods = listCryptoMethods("Cipher");
System.out.println(methods.size() + " crypt methods:" + methods.toString());
testCryptMethods(methods);
System.exit(0);
}
if (s[0].equals("-random")) {
- int count = ((s.length == 2) ? (Integer.parseInt(s[1])) : 1);
+ final int count = ((s.length == 2) ? (Integer.parseInt(s[1])) : 1);
for (int i = 0; i < count; i++) System.out.println(randomSalt());
System.exit(0);
}
@@ -597,7 +597,7 @@ public class cryptbig {
if (s[0].equals("-ess")) {
// 'scramble' string
if (s.length != 3) {help(); System.exit(-1);}
- long t = System.currentTimeMillis();
+ final long t = System.currentTimeMillis();
System.out.println(scrambleString(s[1], s[2]));
System.out.println("Calculation time: " + (System.currentTimeMillis() - t) + " milliseconds");
System.exit(0);
@@ -605,10 +605,10 @@ public class cryptbig {
if (s[0].equals("-dss")) {
// 'descramble' string
if (s.length != 3) {help(); System.exit(-1);}
- long t = System.currentTimeMillis();
+ final long t = System.currentTimeMillis();
try {
System.out.println(descrambleString(s[1], s[2]));
- } catch (IOException e) {
+ } catch (final IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
@@ -628,7 +628,7 @@ public class cryptbig {
if (s[0].equals("-md5")) {
// generate a public key from a password that can be used for encryption
if (s.length != 2) {help(); System.exit(-1);}
- String md5s = serverCodings.encodeMD5Hex(new File(s[1]));
+ final String md5s = serverCodings.encodeMD5Hex(new File(s[1]));
System.out.println(md5s);
System.exit(0);
}
diff --git a/source/de/anomic/tools/diskUsage.java b/source/de/anomic/tools/diskUsage.java
index 7555a934c..36ed70493 100644
--- a/source/de/anomic/tools/diskUsage.java
+++ b/source/de/anomic/tools/diskUsage.java
@@ -93,7 +93,7 @@ public class diskUsage {
// public API //
//////////////////
- public static void init(ArrayList<String> pathsToCheck) {
+ public static void init(final ArrayList<String> pathsToCheck) {
if (usedOS >= 0) return; // prevent double initialization
usedOS = getOS();
if (usedOS == -1) {
@@ -152,7 +152,7 @@ public class diskUsage {
////////////
private static HashMap<String, long[]> dfUnix() {
- HashMap<String, long[]> diskUsages = new HashMap<String, long[]>();
+ final HashMap<String, long[]> diskUsages = new HashMap<String, long[]>();
try {
final List<String> lines = dfUnixExec();
nextLine: for (final String line: lines){
@@ -171,7 +171,7 @@ public class diskUsage {
}
}
return diskUsages;
- } catch (IOException e) {
+ } catch (final IOException e) {
usageError = "dfUnix: " + e.getMessage();
return diskUsages;
}
@@ -195,7 +195,7 @@ public class diskUsage {
allMountPoints.add(allMountPoints.size(), tokens[5]);
allVolumes.add(allVolumes.size(), tokens[0]);
}
- } catch (IOException e) {
+ } catch (final IOException e) {
usageError = "error during dfUnixGetVolumes: " + e.getMessage();
}
}
@@ -302,7 +302,7 @@ public class diskUsage {
}
public static HashMap<String, long[]> dfWindows() {
- HashMap<String, long[]> diskUsages = new HashMap<String, long[]>();
+ final HashMap<String, long[]> diskUsages = new HashMap<String, long[]>();
for (int i = 0; i < yacyUsedVolumes.size(); i++){
final List<String> processArgs = new ArrayList<String>();
processArgs.add(windowsCommand);
@@ -323,12 +323,12 @@ public class diskUsage {
return diskUsages;
}
- String[] tokens = line.trim().split(" ++");
- long[] vals = new long[2];
+ final String[] tokens = line.trim().split(" ++");
+ final long[] vals = new long[2];
vals[0] = -1;
try { vals[1] = new Long(tokens[2].replaceAll("[.,]", "")); } catch (final NumberFormatException e) {continue;}
diskUsages.put (yacyUsedVolumes.get(i), vals);
- } catch (IOException e) {
+ } catch (final IOException e) {
usageError = "dfWindows: " + e.getMessage();
return diskUsages;
}
@@ -352,7 +352,7 @@ public class diskUsage {
return -1;
}
- private static void checkMappedSubDirs (ArrayList<String> pathsToCheck) {
+ private static void checkMappedSubDirs (final ArrayList<String> pathsToCheck) {
for (final String path : pathsToCheck) {
if (usedOS <= UNIX_END)
checkPathUsageUnix (path);
@@ -372,10 +372,10 @@ public class diskUsage {
private static void checkPathUsageWindows(final String path) {
int index = -1;
- String sub = path.substring(0, 1); // ?? nur ein character?
+ final String sub = path.substring(0, 1); // ?? nur ein character?
try {
index = yacyUsedVolumes.indexOf(sub);
- } catch (IndexOutOfBoundsException e) {
+ } catch (final IndexOutOfBoundsException e) {
usageError = "internal error while checking used windows volumes";
return;
}
@@ -407,9 +407,9 @@ public class diskUsage {
log.logWarning("logpoint 1 " + ix.getMessage());
throw new IOException(ix.getMessage());
}
- List<String> list = inputStream.getOutput();
+ final List<String> list = inputStream.getOutput();
if (list.isEmpty()) {
- String error = errorStream.getOutput().toString();
+ final String error = errorStream.getOutput().toString();
log.logWarning("logpoint 2: "+ error);
throw new IOException("empty list: " + error);
} else
diff --git a/source/de/anomic/tools/disorderHeap.java b/source/de/anomic/tools/disorderHeap.java
index 340bc2927..8f5c386c2 100644
--- a/source/de/anomic/tools/disorderHeap.java
+++ b/source/de/anomic/tools/disorderHeap.java
@@ -36,31 +36,31 @@ public class disorderHeap implements Serializable {
list = new LinkedList<String>();
}
- public disorderHeap(int numbers) {
+ public disorderHeap(final int numbers) {
// create a disorder heap with numbers in it
// the numbers are 0..numbers-1
this();
for (int i = 0; i < numbers; i++) add(Integer.toString(i));
}
- public synchronized void add(String element) {
+ public synchronized void add(final String element) {
// add one element into the list at an arbitrary position
- int pos = (int) ((System.currentTimeMillis() / 7) % (list.size() + 1));
+ final int pos = (int) ((System.currentTimeMillis() / 7) % (list.size() + 1));
list.add(pos, element);
}
public synchronized String remove() {
if (list.size() == 0) return null;
- int pos = (int) ((System.currentTimeMillis() / 13) % list.size());
+ final int pos = (int) ((System.currentTimeMillis() / 13) % list.size());
return list.remove(pos);
}
public synchronized int number() {
- String n = this.remove();
+ final String n = this.remove();
if (n == null) return -1;
try {
return Integer.parseInt(n);
- } catch (Exception e) {
+ } catch (final Exception e) {
return -1;
}
}
@@ -70,8 +70,8 @@ public class disorderHeap implements Serializable {
}
- public static void main(String[] args) {
- disorderHeap ul = new disorderHeap();
+ public static void main(final String[] args) {
+ final disorderHeap ul = new disorderHeap();
for (int i = 0; i < args.length; i++) ul.add(args[i]);
for (int i = 0; i < args.length; i++) System.out.print(ul.remove() + " ");
System.out.println();
diff --git a/source/de/anomic/tools/disorderSet.java b/source/de/anomic/tools/disorderSet.java
index 5128072b4..8af16cb79 100644
--- a/source/de/anomic/tools/disorderSet.java
+++ b/source/de/anomic/tools/disorderSet.java
@@ -45,14 +45,14 @@ public class disorderSet extends HashSet<String> implements Set<String> {
if (this.size() == 0) return null;
// fill up the queue
dh = new disorderHeap();
- Iterator<String> elements = this.iterator();
+ final Iterator<String> elements = this.iterator();
while (elements.hasNext()) dh.add(elements.next());
}
return dh.remove();
}
- public static void main(String[] args) {
- disorderSet ds = new disorderSet();
+ public static void main(final String[] args) {
+ final disorderSet ds = new disorderSet();
for (int i = 0; i < args.length; i++) ds.add(args[i]);
for (int i = 0; i < args.length * 3; i++) System.out.print(ds.any() + " ");
System.out.println();
diff --git a/source/de/anomic/tools/enumerateFiles.java b/source/de/anomic/tools/enumerateFiles.java
index 75816afb1..08251b907 100644
--- a/source/de/anomic/tools/enumerateFiles.java
+++ b/source/de/anomic/tools/enumerateFiles.java
@@ -31,14 +31,14 @@ public class enumerateFiles implements Enumeration<File> {
// implements iterative search through recursively defined subdirectories
// and return all paths to the files
- private ArrayList<TreeSet<File>> hierarchy; // contains TreeSet elements, each TreeSet contains File Entries
- private boolean incOrder; // if true, the smallest value is returned first
+ private final ArrayList<TreeSet<File>> hierarchy; // contains TreeSet elements, each TreeSet contains File Entries
+ private final boolean incOrder; // if true, the smallest value is returned first
private File buffer; // the prefetch-buffer
- private boolean return_files;
- private boolean return_folders;
- private boolean delete_emptyFolders;
+ private final boolean return_files;
+ private final boolean return_folders;
+ private final boolean delete_emptyFolders;
- public enumerateFiles(File root, boolean files, boolean folders, boolean increasing, boolean deleteEmptyFolders) {
+ public enumerateFiles(final File root, final boolean files, final boolean folders, final boolean increasing, final boolean deleteEmptyFolders) {
// we define our data structures first
this.return_files = files;
this.return_folders = folders;
@@ -46,8 +46,8 @@ public class enumerateFiles implements Enumeration<File> {
this.hierarchy = new ArrayList<TreeSet<File>>();
this.incOrder = increasing;
// the we initially fill the hierarchy with the content of the root folder
- TreeSet<File> t = new TreeSet<File>();
- String[] l = root.list();
+ final TreeSet<File> t = new TreeSet<File>();
+ final String[] l = root.list();
// System.out.println("D " + l.toString());
if (l != null) for (int i = 0; i < l.length; i++) t.add(new File(root, l[i]));
this.hierarchy.add(t);
@@ -76,7 +76,7 @@ public class enumerateFiles implements Enumeration<File> {
// if the value represents another folder, we step into the next hierarchy
if (f.isDirectory()) {
t = new TreeSet<File>();
- String[] l = f.list();
+ final String[] l = f.list();
if (l == null) {
// f has disappeared
f = null;
@@ -107,7 +107,7 @@ public class enumerateFiles implements Enumeration<File> {
}
public File nextElement() {
- File r = buffer;
+ final File r = buffer;
buffer = nextElement0();
return r;
}
diff --git a/source/de/anomic/tools/gzip.java b/source/de/anomic/tools/gzip.java
index 9d9e95871..565d03886 100644
--- a/source/de/anomic/tools/gzip.java
+++ b/source/de/anomic/tools/gzip.java
@@ -40,67 +40,67 @@ public class gzip {
private static serverLog logger = new serverLog("GZIP");
- public static void gzipFile(String inFile, String outFile) {
+ public static void gzipFile(final String inFile, final String outFile) {
try {
- InputStream fin = new FileInputStream(inFile);
- OutputStream fout = new GZIPOutputStream(new FileOutputStream(outFile), 128);
+ final InputStream fin = new FileInputStream(inFile);
+ final OutputStream fout = new GZIPOutputStream(new FileOutputStream(outFile), 128);
copy(fout, fin, 128);
fin.close();
fout.close();
- } catch (FileNotFoundException e) {
+ } catch (final FileNotFoundException e) {
//System.err.println("ERROR: file '" + inFile + "' not found");
logger.logWarning("ERROR: file '" + inFile + "' not found", e);
- } catch (IOException e) {
+ } catch (final IOException e) {
//System.err.println("ERROR: IO trouble ");
logger.logWarning("ERROR: IO trouble ",e);
}
}
- public static void gunzipFile(String inFile, String outFile) {
+ public static void gunzipFile(final String inFile, final String outFile) {
try {
- InputStream fin = new GZIPInputStream(new FileInputStream(inFile));
- OutputStream fout = new FileOutputStream(outFile);
+ final InputStream fin = new GZIPInputStream(new FileInputStream(inFile));
+ final OutputStream fout = new FileOutputStream(outFile);
copy(fout, fin, 128);
fin.close();
fout.close();
- } catch (FileNotFoundException e) {
+ } catch (final FileNotFoundException e) {
//System.err.println("ERROR: file '" + inFile + "' not found");
logger.logWarning("ERROR: file '" + inFile + "' not found", e);
- } catch (IOException e) {
+ } catch (final IOException e) {
//System.err.println("ERROR: IO trouble ");
logger.logWarning("ERROR: IO trouble ",e);
}
}
- public static byte[] gzipString(String in) {
+ public static byte[] gzipString(final String in) {
try {
- InputStream fin = new ByteArrayInputStream(in.getBytes("UTF8"));
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- OutputStream fout = new GZIPOutputStream(baos, 128);
+ final InputStream fin = new ByteArrayInputStream(in.getBytes("UTF8"));
+ final ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ final OutputStream fout = new GZIPOutputStream(baos, 128);
copy(fout, fin, 128);
fin.close();
fout.close();
return baos.toByteArray();
- } catch (IOException e) {
+ } catch (final IOException e) {
//System.err.println("ERROR: IO trouble ");
logger.logWarning("ERROR: IO trouble ",e);
return null;
}
}
- public static String gunzipString(byte[] in) throws IOException {
- InputStream fin = new GZIPInputStream(new ByteArrayInputStream(in));
- ByteArrayOutputStream fout = new ByteArrayOutputStream();
+ public static String gunzipString(final byte[] in) throws IOException {
+ final InputStream fin = new GZIPInputStream(new ByteArrayInputStream(in));
+ final ByteArrayOutputStream fout = new ByteArrayOutputStream();
copy(fout, fin, 128);
fin.close();
fout.close();
return new String(fout.toByteArray(), "UTF-8");
}
- private static void copy(OutputStream out, InputStream in, int bufferSize) throws IOException {
- InputStream bIn = new BufferedInputStream(in, bufferSize);
- OutputStream bOut = new BufferedOutputStream(out, bufferSize);
- byte[] buf = new byte[bufferSize];
+ private static void copy(final OutputStream out, final InputStream in, final int bufferSize) throws IOException {
+ final InputStream bIn = new BufferedInputStream(in, bufferSize);
+ final OutputStream bOut = new BufferedOutputStream(out, bufferSize);
+ final byte[] buf = new byte[bufferSize];
int n;
while ((n = bIn.read(buf)) > 0) bOut.write(buf, 0, n);
bIn.close();
@@ -113,7 +113,7 @@ public class gzip {
}
- public static void main(String[] s) {
+ public static void main(final String[] s) {
if (s.length == 0) {
help();
System.exit(0);
diff --git a/source/de/anomic/tools/loaderThreads.java b/source/de/anomic/tools/loaderThreads.java
index e24f1ed0d..4c25d146e 100644
--- a/source/de/anomic/tools/loaderThreads.java
+++ b/source/de/anomic/tools/loaderThreads.java
@@ -47,9 +47,9 @@ public class loaderThreads {
}
public loaderThreads(
- int timeout,
- String user,
- String password
+ final int timeout,
+ final String user,
+ final String password
) {
this.timeout = timeout;
this.user = user;
@@ -59,30 +59,30 @@ public class loaderThreads {
this.failed = 0;
}
- public void newPropLoaderThread(String name, yacyURL url) {
+ public void newPropLoaderThread(final String name, final yacyURL url) {
newThread(name, url, new propLoader());
}
- public void newThread(String name, yacyURL url, loaderProcess process) {
- Thread t = new loaderThread(url, process);
+ public void newThread(final String name, final yacyURL url, final loaderProcess process) {
+ final Thread t = new loaderThread(url, process);
threads.put(name, t);
t.start();
}
- public void terminateThread(String name) {
- loaderThread t = (loaderThread) threads.get(name);
+ public void terminateThread(final String name) {
+ final loaderThread t = (loaderThread) threads.get(name);
if (t == null) throw new RuntimeException("no such thread: " + name);
else t.terminate();
}
- public int threadCompleted(String name) {
- loaderThread t = (loaderThread) threads.get(name);
+ public int threadCompleted(final String name) {
+ final loaderThread t = (loaderThread) threads.get(name);
if (t == null) throw new RuntimeException("no such thread: " + name);
else return t.completed();
}
- public int threadStatus(String name) {
- loaderThread t = (loaderThread) threads.get(name);
+ public int threadStatus(final String name) {
+ final loaderThread t = (loaderThread) threads.get(name);
if (t == null) throw new RuntimeException("no such thread: " + name);
else return t.status();
}
@@ -99,20 +99,20 @@ public class loaderThreads {
return threads.size();
}
- public Exception threadError(String name) {
- loaderThread t = (loaderThread) threads.get(name);
+ public Exception threadError(final String name) {
+ final loaderThread t = (loaderThread) threads.get(name);
if (t == null) throw new RuntimeException("no such thread: " + name);
else return t.error();
}
protected class loaderThread extends Thread {
- private yacyURL url;
+ private final yacyURL url;
private Exception error;
- private loaderProcess process;
+ private final loaderProcess process;
private byte[] page;
private boolean loaded;
- public loaderThread(yacyURL url, loaderProcess process) {
+ public loaderThread(final yacyURL url, final loaderProcess process) {
this.url = url;
this.process = process;
this.error = null;
@@ -122,7 +122,7 @@ public class loaderThreads {
public void run() {
try {
- httpHeader reqHeader = new httpHeader();
+ final httpHeader reqHeader = new httpHeader();
reqHeader.put(httpHeader.USER_AGENT, HTTPLoader.crawlerUserAgent);
page = HttpClient.wget(url.toString(), reqHeader, timeout);
loaded = true;
@@ -134,7 +134,7 @@ public class loaderThreads {
(process.status() == loaderCore.STATUS_FINALIZED)) completed++;
if ((process.status() == loaderCore.STATUS_ABORTED) ||
(process.status() == loaderCore.STATUS_FAILED)) failed++;
- } catch (Exception e) {
+ } catch (final Exception e) {
error = e;
failed++;
}
@@ -171,13 +171,13 @@ public class loaderThreads {
this.status = STATUS_READY;
}
- public synchronized void feed(byte[] v) {
+ public synchronized void feed(final byte[] v) {
this.status = STATUS_RUNNING;
this.completion = 1;
int line = 0;
String s, key, value;
int p;
- ArrayList<String> lines = nxTools.strings(v);
+ final ArrayList<String> lines = nxTools.strings(v);
try {
while ((this.run) && (line < lines.size())) {
// parse line and construct a property
@@ -198,7 +198,7 @@ public class loaderThreads {
this.status = STATUS_ABORTED;
return;
}
- } catch (Exception e) {
+ } catch (final Exception e) {
this.status = STATUS_FAILED;
this.error = e;
return;
diff --git a/source/de/anomic/tools/md5DirFileFilter.java b/source/de/anomic/tools/md5DirFileFilter.java
index dfad5c4dc..2ed189415 100644
--- a/source/de/anomic/tools/md5DirFileFilter.java
+++ b/source/de/anomic/tools/md5DirFileFilter.java
@@ -31,7 +31,7 @@ import java.io.FilenameFilter;
public class md5DirFileFilter implements FilenameFilter {
- public boolean accept(File dir, String name) {
+ public boolean accept(final File dir, final String name) {
return !(name.startsWith("dir.") || name.endsWith(".md5"));
}
diff --git a/source/de/anomic/tools/nxTools.java b/source/de/anomic/tools/nxTools.java
index 57c307c3b..fbc28f4df 100644
--- a/source/de/anomic/tools/nxTools.java
+++ b/source/de/anomic/tools/nxTools.java
@@ -57,11 +57,11 @@ import java.util.Vector;
public class nxTools {
- public static HashMap<String, String> table(Vector<String> list) {
- Enumeration<String> i = list.elements();
+ public static HashMap<String, String> table(final Vector<String> list) {
+ final Enumeration<String> i = list.elements();
int pos;
String line;
- HashMap<String, String> props = new HashMap<String, String>(list.size());
+ final HashMap<String, String> props = new HashMap<String, String>(list.size());
while (i.hasMoreElements()) {
line = (i.nextElement()).trim();
pos = line.indexOf("=");
@@ -70,7 +70,7 @@ public class nxTools {
return props;
}
- public static HashMap<String, String> table(byte[] a, String encoding) {
+ public static HashMap<String, String> table(final byte[] a, final String encoding) {
return table(strings(a, encoding));
}
@@ -86,12 +86,12 @@ public class nxTools {
* @param list
* @return
*/
- public static HashMap<String, String> table(ArrayList<String> list) {
+ public static HashMap<String, String> table(final ArrayList<String> list) {
if (list == null) return new HashMap<String, String>();
- Iterator<String> i = list.iterator();
+ final Iterator<String> i = list.iterator();
int pos;
String line;
- HashMap<String, String> props = new HashMap<String, String>(list.size());
+ final HashMap<String, String> props = new HashMap<String, String>(list.size());
while (i.hasNext()) {
line = (i.next()).trim();
if (line.startsWith("#")) continue; // exclude comments
@@ -102,11 +102,11 @@ public class nxTools {
return props;
}
- public static Vector<String> grep(Vector<String> list, int afterContext, String pattern) {
- Enumeration<String> i = list.elements();
+ public static Vector<String> grep(final Vector<String> list, final int afterContext, final String pattern) {
+ final Enumeration<String> i = list.elements();
int ac = 0;
String line;
- Vector<String> result = new Vector<String>();
+ final Vector<String> result = new Vector<String>();
while (i.hasMoreElements()) {
line = i.nextElement();
if (line.indexOf(pattern) >= 0) {
@@ -120,11 +120,11 @@ public class nxTools {
return result;
}
- public static ArrayList<String> grep(ArrayList<String> list, int afterContext, String pattern) {
- Iterator<String> i = list.iterator();
+ public static ArrayList<String> grep(final ArrayList<String> list, final int afterContext, final String pattern) {
+ final Iterator<String> i = list.iterator();
int ac = 0;
String line;
- ArrayList<String> result = new ArrayList<String>();
+ final ArrayList<String> result = new ArrayList<String>();
while (i.hasNext()) {
line = i.next();
if (line.indexOf(pattern) >= 0) {
@@ -138,17 +138,17 @@ public class nxTools {
return result;
}
- public static String tail1(Vector<String> list) {
+ public static String tail1(final Vector<String> list) {
if ((list == null) || (list.size() == 0)) return "";
return list.lastElement();
}
- public static String tail1(ArrayList<String> list) {
+ public static String tail1(final ArrayList<String> list) {
if ((list == null) || (list.size() == 0)) return "";
return list.get(list.size()-1);
}
- public static String awk(String sentence, String separator, int count) {
+ public static String awk(String sentence, final String separator, int count) {
// returns the nth word of sentence, where count is the counter and the first word has the number 1
// the words are separated by the separator
if ((sentence == null) || (separator == null) || (count < 1)) return null;
@@ -166,15 +166,15 @@ public class nxTools {
return null;
}
- public static ArrayList<String> strings(byte[] a) {
+ public static ArrayList<String> strings(final byte[] a) {
return strings(a, null);
}
- public static ArrayList<String> strings(byte[] a, String encoding) {
+ public static ArrayList<String> strings(final byte[] a, final String encoding) {
if (a == null) return new ArrayList<String>();
int s = 0;
int e;
- ArrayList<String> v = new ArrayList<String>();
+ final ArrayList<String> v = new ArrayList<String>();
byte b;
while (s < a.length) {
// find eol
@@ -190,7 +190,7 @@ public class nxTools {
v.add(new String(a, s, e - s));
} else try {
v.add(new String(a, s, e - s, encoding));
- } catch (UnsupportedEncodingException xcptn) {
+ } catch (final UnsupportedEncodingException xcptn) {
return v;
}
@@ -205,14 +205,14 @@ public class nxTools {
return v;
}
- public static String line(byte[] a, int lineNr) {
- InputStreamReader r = new InputStreamReader(new ByteArrayInputStream(a));
- LineNumberReader lnr = new LineNumberReader(r);
+ public static String line(final byte[] a, final int lineNr) {
+ final InputStreamReader r = new InputStreamReader(new ByteArrayInputStream(a));
+ final LineNumberReader lnr = new LineNumberReader(r);
String theLine = null;
while (lnr.getLineNumber() < lineNr) {
try {
theLine = lnr.readLine();
- } catch (IOException e) {
+ } catch (final IOException e) {
return null;
}
if (theLine == null) return null;
@@ -230,7 +230,7 @@ public class nxTools {
* @param len
* @return the shorten or the old String
*/
- public static String shortenURLString(String url, int len) {
+ public static String shortenURLString(final String url, final int len) {
// This is contributed by Thomas Quella (borg-0300)
if (url == null) { return null; }
int la = url.length();
diff --git a/source/de/anomic/tools/tarTools.java b/source/de/anomic/tools/tarTools.java
index 642ba3b29..cbc857372 100644
--- a/source/de/anomic/tools/tarTools.java
+++ b/source/de/anomic/tools/tarTools.java
@@ -39,7 +39,7 @@ import de.anomic.server.logging.serverLog;
public class tarTools {
- public static InputStream getInputStream(String tarFileName) throws Exception{
+ public static InputStream getInputStream(final String tarFileName) throws Exception{
if(tarFileName.endsWith(".gz")){
return new GZIPInputStream(new FileInputStream(new File(tarFileName)));
} else {
@@ -47,7 +47,7 @@ public class tarTools {
}
}
- public static InputStream getInputStream(File tarFileName) throws Exception{
+ public static InputStream getInputStream(final File tarFileName) throws Exception{
return getInputStream(tarFileName.toString());
}
@@ -57,16 +57,16 @@ public class tarTools {
* @param untarDir destination path
* @throws Exception (IOException or FileNotFoundException)
*/
- public static void unTar(InputStream in, String untarDir) throws Exception{
+ public static void unTar(final InputStream in, final String untarDir) throws Exception{
serverLog.logInfo("UNTAR", "starting");
if(new File(untarDir).exists()){
- TarInputStream tin = new TarInputStream(in);
+ final TarInputStream tin = new TarInputStream(in);
TarEntry tarEntry = tin.getNextEntry();
while(tarEntry != null){
- File destPath = new File(untarDir + File.separator + tarEntry.getName());
+ final File destPath = new File(untarDir + File.separator + tarEntry.getName());
if (!tarEntry.isDirectory()) {
new File(destPath.getParent()).mkdirs(); // create missing subdirectories
- FileOutputStream fout = new FileOutputStream(destPath);
+ final FileOutputStream fout = new FileOutputStream(destPath);
tin.copyEntryContents(fout);
fout.close();
} else {
@@ -81,13 +81,13 @@ public class tarTools {
serverLog.logInfo("UNTAR", "finished");
}
- public static void main(String args[]){
+ public static void main(final String args[]){
// @arg0 source
// @arg1 destination
if(args.length == 2){
try {
unTar(getInputStream(args[0]), args[1]);
- } catch (Exception e) {
+ } catch (final Exception e) {
System.out.println(e);
}
} else {
diff --git a/source/de/anomic/tools/yFormatter.java b/source/de/anomic/tools/yFormatter.java
index 57f1c5f19..246eac1f2 100644
--- a/source/de/anomic/tools/yFormatter.java
+++ b/source/de/anomic/tools/yFormatter.java
@@ -53,7 +53,7 @@ public final class yFormatter {
* @param locale the {@link Locale} to set or <code>null</code> to set the special
* empty locale to create unformatted numbers
*/
- public static void setLocale(Locale locale) {
+ public static void setLocale(final Locale locale) {
numForm = (locale == null ? cleanNumForm : NumberFormat.getInstance(locale));
initDefaults();
}
@@ -61,8 +61,8 @@ public final class yFormatter {
/**
* @param lang an ISO 639 language code which is used to generate a {@link Locale}
*/
- public static void setLocale(String lang) {
- String l = (lang.equalsIgnoreCase("default") ? "en" : lang.toLowerCase());
+ public static void setLocale(final String lang) {
+ final String l = (lang.equalsIgnoreCase("default") ? "en" : lang.toLowerCase());
setLocale(l.equals("none") ? null : new Locale(l));
}
@@ -73,17 +73,17 @@ public final class yFormatter {
numForm.setMaximumFractionDigits(2); // 2 decimal digits for float/double
}
- public static String number(double d, boolean localized) {
+ public static String number(final double d, final boolean localized) {
return (localized ? number(d) : cleanNumForm.format(d));
}
- public static String number(double d) {
+ public static String number(final double d) {
return numForm.format(d);
}
- public static String number(long l, boolean localized) {
+ public static String number(final long l, final boolean localized) {
return (localized ? number(l) : cleanNumForm.format(l));
}
- public static String number(long l) {
+ public static String number(final long l) {
return numForm.format(l);
}
@@ -94,7 +94,7 @@ public final class yFormatter {
* @param s string to parse into a number and reformat
* @return the formatted number as a String or "-" in case of a parsing error
*/
- public static String number(String s) {
+ public static String number(final String s) {
String ret = null;
try {
if (s.indexOf('.') == -1) {
@@ -102,7 +102,7 @@ public final class yFormatter {
} else {
ret = number(Double.parseDouble(s));
}
- } catch (NumberFormatException e) { /* empty */ }
+ } catch (final NumberFormatException e) { /* empty */ }
return (ret == null ? "-" : ret);
}
diff --git a/source/de/anomic/urlRedirector/urlRedirectord.java b/source/de/anomic/urlRedirector/urlRedirectord.java
index bfad3e025..7cfebee94 100644
--- a/source/de/anomic/urlRedirector/urlRedirectord.java
+++ b/source/de/anomic/urlRedirector/urlRedirectord.java
@@ -23,7 +23,7 @@ public class urlRedirectord implements serverHandler {
private serverCore.Session session;
private static plasmaSwitchboard sb = null;
- private serverLog theLogger = new serverLog("URL-REDIRECTOR");
+ private final serverLog theLogger = new serverLog("URL-REDIRECTOR");
private static CrawlProfile.entry profile = null;
private String nextURL;
@@ -76,7 +76,7 @@ public class urlRedirectord implements serverHandler {
return this.nextURL;
}
- public void initSession(Session theSession){
+ public void initSession(final Session theSession){
// getting current session
this.session = theSession;
}
@@ -85,7 +85,7 @@ public class urlRedirectord implements serverHandler {
return null;
}
- public String error(Throwable e) {
+ public String error(final Throwable e) {
return null;
}
@@ -97,15 +97,15 @@ public class urlRedirectord implements serverHandler {
this.session = null;
}
- public Boolean EMPTY(String arg) throws IOException {
+ public Boolean EMPTY(final String arg) throws IOException {
return null;
}
- public Boolean UNKNOWN(String requestLine) throws IOException {
+ public Boolean UNKNOWN(final String requestLine) throws IOException {
return null;
}
- public Boolean REDIRECTOR(String requestLine) {
+ public Boolean REDIRECTOR(final String requestLine) {
try {
boolean authenticated = false;
@@ -116,8 +116,8 @@ public class urlRedirectord implements serverHandler {
this.session.controlSocket.setSoTimeout(0);
String line = null;
- BufferedReader inputReader = new BufferedReader(new InputStreamReader(this.session.in));
- PrintWriter outputWriter = new PrintWriter(this.session.out);
+ final BufferedReader inputReader = new BufferedReader(new InputStreamReader(this.session.in));
+ final PrintWriter outputWriter = new PrintWriter(this.session.out);
while ((line = inputReader.readLine()) != null) {
if (line.equals("EXIT")) {
@@ -130,7 +130,7 @@ public class urlRedirectord implements serverHandler {
userName = line.substring(line.indexOf(" ")).trim();
} else if (line.startsWith("PWD")) {
if (userName != null) {
- userDB.Entry userEntry = sb.userDB.getEntry(userName);
+ final userDB.Entry userEntry = sb.userDB.getEntry(userName);
if (userEntry != null) {
md5Pwd = line.substring(line.indexOf(" ")).trim();
if (userEntry.getMD5EncodedUserPwd().equals(md5Pwd)) {
@@ -146,18 +146,18 @@ public class urlRedirectord implements serverHandler {
outputWriter.print("\r\n");
outputWriter.flush();
} else if (line.startsWith("DEPTH")) {
- int pos = line.indexOf(" ");
+ final int pos = line.indexOf(" ");
if (pos != -1) {
- String newDepth = line.substring(pos).trim();
+ final String newDepth = line.substring(pos).trim();
this.theLogger.logFine("Changing crawling depth to '" + newDepth + "'.");
sb.webIndex.profilesActiveCrawls.changeEntry(profile, "generalDepth",newDepth);
}
outputWriter.print("\r\n");
outputWriter.flush();
} else if (line.startsWith("CRAWLDYNAMIC")) {
- int pos = line.indexOf(" ");
+ final int pos = line.indexOf(" ");
if (pos != -1) {
- String newValue = line.substring(pos).trim();
+ final String newValue = line.substring(pos).trim();
this.theLogger.logFine("Changing crawl dynamic setting to '" + newValue + "'");
sb.webIndex.profilesActiveCrawls.changeEntry(profile, "crawlingQ",newValue);
}
@@ -168,7 +168,7 @@ public class urlRedirectord implements serverHandler {
return Boolean.FALSE;
}
- int pos = line.indexOf(" ");
+ final int pos = line.indexOf(" ");
this.nextURL = (pos != -1) ? line.substring(0,pos):line;
this.theLogger.logFine("Receiving request " + line);
@@ -178,10 +178,10 @@ public class urlRedirectord implements serverHandler {
String reasonString = null;
try {
// generating URL Object
- yacyURL reqURL = new yacyURL(this.nextURL, null);
+ final yacyURL reqURL = new yacyURL(this.nextURL, null);
// getting URL mimeType
- httpHeader header = HttpClient.whead(reqURL.toString());
+ final httpHeader header = HttpClient.whead(reqURL.toString());
if (plasmaParser.supportedContent(
plasmaParser.PARSER_MODE_URLREDIRECTOR,
@@ -189,7 +189,7 @@ public class urlRedirectord implements serverHandler {
header.mime())
) {
// first delete old entry, if exists
- String urlhash = reqURL.hash();
+ final String urlhash = reqURL.hash();
sb.webIndex.removeURL(urlhash);
sb.crawlQueues.noticeURL.removeByURLHash(urlhash);
sb.crawlQueues.errorURL.remove(urlhash);
@@ -207,7 +207,7 @@ public class urlRedirectord implements serverHandler {
} else {
reasonString = "Unsupporte file extension";
}
- } catch (MalformedURLException badUrlEx) {
+ } catch (final MalformedURLException badUrlEx) {
reasonString = "Malformed URL";
}
@@ -222,7 +222,7 @@ public class urlRedirectord implements serverHandler {
// Terminating connection
return serverCore.TERMINATE_CONNECTION;
- } catch (Exception e) {
+ } catch (final Exception e) {
this.theLogger.logSevere("Unexpected Error: " + e.getMessage(),e);
return serverCore.TERMINATE_CONNECTION;
}
diff --git a/source/de/anomic/xml/RSSFeed.java b/source/de/anomic/xml/RSSFeed.java
index df0395159..11216c602 100644
--- a/source/de/anomic/xml/RSSFeed.java
+++ b/source/de/anomic/xml/RSSFeed.java
@@ -69,17 +69,17 @@ public class RSSFeed implements Iterable<RSSMessage> {
maxsize = Integer.MAX_VALUE;
}
- public RSSFeed(int maxsize) {
+ public RSSFeed(final int maxsize) {
this();
this.maxsize = maxsize;
}
- public void setMaxsize(int maxsize) {
+ public void setMaxsize(final int maxsize) {
this.maxsize = maxsize;
while (messageQueue.size() > this.maxsize) pollMessage();
}
- public void setChannel(RSSMessage channelItem) {
+ public void setChannel(final RSSMessage channelItem) {
this.channel = channelItem;
}
@@ -87,7 +87,7 @@ public class RSSFeed implements Iterable<RSSMessage> {
return channel;
}
- public void setImage(String imageURL) {
+ public void setImage(final String imageURL) {
this.imageURL = imageURL;
}
@@ -95,14 +95,14 @@ public class RSSFeed implements Iterable<RSSMessage> {
return this.imageURL;
}
- public void addMessage(RSSMessage item) {
- String guid = item.getGuid();
+ public void addMessage(final RSSMessage item) {
+ final String guid = item.getGuid();
messageQueue.add(guid);
messages.put(guid, item);
while (messageQueue.size() > this.maxsize) pollMessage();
}
- public RSSMessage getMessage(String guid) {
+ public RSSMessage getMessage(final String guid) {
// retrieve item by guid
return messages.get(guid);
}
@@ -118,7 +118,7 @@ public class RSSFeed implements Iterable<RSSMessage> {
public RSSMessage pollMessage() {
// retrieve and delete item
if (messageQueue.size() == 0) return null;
- String nextGUID = messageQueue.poll();
+ final String nextGUID = messageQueue.poll();
if (nextGUID == null) return null;
return messages.remove(nextGUID);
}
@@ -155,8 +155,8 @@ public class RSSFeed implements Iterable<RSSMessage> {
*/
private static final ConcurrentHashMap<String, RSSFeed> channels = new ConcurrentHashMap<String, RSSFeed>();
- public static RSSFeed channels(String channelName) {
- ConcurrentHashMap<String, RSSFeed> channelss = channels;
+ public static RSSFeed channels(final String channelName) {
+ final ConcurrentHashMap<String, RSSFeed> channelss = channels;
RSSFeed feed = channelss.get(channelName);
if (feed != null) return feed;
feed = new RSSFeed();
diff --git a/source/de/anomic/xml/RSSMessage.java b/source/de/anomic/xml/RSSMessage.java
index 0223540b0..5caea1400 100644
--- a/source/de/anomic/xml/RSSMessage.java
+++ b/source/de/anomic/xml/RSSMessage.java
@@ -57,9 +57,9 @@ public class RSSMessage {
}
}
- private HashMap<String, String> map;
+ private final HashMap<String, String> map;
- public RSSMessage(String title, String description, String link) {
+ public RSSMessage(final String title, final String description, final String link) {
this();
setValue("title", title);
setValue("description", description);
@@ -73,67 +73,67 @@ public class RSSMessage {
this.map.put("guid", Long.toHexString(System.currentTimeMillis()) + ":" + guidcount++);
}
- public void setValue(String name, String value) {
+ public void setValue(final String name, final String value) {
map.put(name, value);
}
public String getAuthor() {
- String s = map.get("author");
+ final String s = map.get("author");
if (s == null) return ""; else return s;
}
public String getCopyright() {
- String s = map.get("copyright");
+ final String s = map.get("copyright");
if (s == null) return ""; else return s;
}
public String getCategory() {
- String s = map.get("category");
+ final String s = map.get("category");
if (s == null) return ""; else return s;
}
public String getTitle() {
- String s = map.get("title");
+ final String s = map.get("title");
if (s == null) return ""; else return s;
}
public String getLink() {
- String s = map.get("link");
+ final String s = map.get("link");
if (s == null) return ""; else return s;
}
public String getReferrer() {
- String s = map.get("referrer");
+ final String s = map.get("referrer");
if (s == null) return ""; else return s;
}
public String getLanguage() {
- String s = map.get("language");
+ final String s = map.get("language");
if (s == null) return ""; else return s;
}
public String getDescription() {
- String s = map.get("description");
+ final String s = map.get("description");
if (s == null) return ""; else return s;
}
public String getCreator() {
- String s = map.get("creator");
+ final String s = map.get("creator");
if (s == null) return ""; else return s;
}
public String getPubDate() {
- String s = map.get("pubDate");
+ final String s = map.get("pubDate");
if (s == null) return ""; else return s;
}
public String getGuid() {
- String s = map.get("guid");
+ final String s = map.get("guid");
if (s == null) return ""; else return s;
}
public String getDocs() {
- String s = map.get("docs");
+ final String s = map.get("docs");
if (s == null) return ""; else return s;
}
}
diff --git a/source/de/anomic/xml/RSSReader.java b/source/de/anomic/xml/RSSReader.java
index 806f8f062..133f91b5d 100644
--- a/source/de/anomic/xml/RSSReader.java
+++ b/source/de/anomic/xml/RSSReader.java
@@ -44,9 +44,9 @@ public class RSSReader extends DefaultHandler {
// class variables
private RSSMessage item;
- private StringBuffer buffer;
+ private final StringBuffer buffer;
private boolean parsingChannel, parsingImage, parsingItem;
- private RSSFeed theChannel;
+ private final RSSFeed theChannel;
public RSSReader() {
theChannel = new RSSFeed();
@@ -57,29 +57,29 @@ public class RSSReader extends DefaultHandler {
parsingItem = false;
}
- public RSSReader(String path) {
+ public RSSReader(final String path) {
this();
try {
- SAXParserFactory factory = SAXParserFactory.newInstance();
- SAXParser saxParser = factory.newSAXParser();
+ final SAXParserFactory factory = SAXParserFactory.newInstance();
+ final SAXParser saxParser = factory.newSAXParser();
saxParser.parse(path, this);
- } catch (Exception e) {
+ } catch (final Exception e) {
e.printStackTrace();
}
}
- public RSSReader(InputStream stream) {
+ public RSSReader(final InputStream stream) {
this();
try {
- SAXParserFactory factory = SAXParserFactory.newInstance();
- SAXParser saxParser = factory.newSAXParser();
+ final SAXParserFactory factory = SAXParserFactory.newInstance();
+ final SAXParser saxParser = factory.newSAXParser();
saxParser.parse(stream, this);
- } catch (Exception e) {
+ } catch (final Exception e) {
e.printStackTrace();
}
}
- public static RSSReader parse(byte[] a) {
+ public static RSSReader parse(final byte[] a) {
// check integrity of array
if ((a == null) || (a.length == 0)) {
@@ -94,28 +94,28 @@ public class RSSReader extends DefaultHandler {
serverLog.logWarning("rssReader", "response does not contain valid xml");
return null;
}
- String end = new String(a, a.length - 10, 10);
+ final String end = new String(a, a.length - 10, 10);
if (end.indexOf("rss") < 0) {
serverLog.logWarning("rssReader", "response incomplete");
return null;
}
// make input stream
- ByteArrayInputStream bais = new ByteArrayInputStream(a);
+ final ByteArrayInputStream bais = new ByteArrayInputStream(a);
// parse stream
RSSReader reader = null;
try {
reader = new RSSReader(bais);
- } catch (Exception e) {
+ } catch (final Exception e) {
serverLog.logWarning("rssReader", "parse exception: " + e);
return null;
}
- try { bais.close(); } catch (IOException e) {}
+ try { bais.close(); } catch (final IOException e) {}
return reader;
}
- public void startElement(String uri, String name, String tag, Attributes atts) throws SAXException {
+ public void startElement(final String uri, final String name, final String tag, final Attributes atts) throws SAXException {
if ("channel".equals(tag)) {
item = new RSSMessage();
parsingChannel = true;
@@ -127,7 +127,7 @@ public class RSSReader extends DefaultHandler {
}
}
- public void endElement(String uri, String name, String tag) {
+ public void endElement(final String uri, final String name, final String tag) {
if (tag == null) return;
if ("channel".equals(tag)) {
parsingChannel = false;
@@ -138,21 +138,21 @@ public class RSSReader extends DefaultHandler {
} else if ("image".equals(tag)) {
parsingImage = false;
} else if ((parsingImage) && (parsingChannel)) {
- String value = buffer.toString().trim();
+ final String value = buffer.toString().trim();
buffer.setLength(0);
if ("url".equals(tag)) theChannel.setImage(value);
} else if (parsingItem) {
- String value = buffer.toString().trim();
+ final String value = buffer.toString().trim();
buffer.setLength(0);
if (RSSMessage.tags.contains(tag)) item.setValue(tag, value);
} else if (parsingChannel) {
- String value = buffer.toString().trim();
+ final String value = buffer.toString().trim();
buffer.setLength(0);
if (RSSMessage.tags.contains(tag)) item.setValue(tag, value);
}
}
- public void characters(char ch[], int start, int length) {
+ public void characters(final char ch[], final int start, final int length) {
if (parsingItem || parsingChannel) {
buffer.append(ch, start, length);
}
diff --git a/source/de/anomic/xml/crawlHandler.java b/source/de/anomic/xml/crawlHandler.java
index 5b96c96b7..a28d8f04a 100644
--- a/source/de/anomic/xml/crawlHandler.java
+++ b/source/de/anomic/xml/crawlHandler.java
@@ -69,12 +69,12 @@ public class crawlHandler extends DefaultHandler {
private HashMap<String, Startpoint> startpoints; // a guid:Item map
- public crawlHandler(String path) {
+ public crawlHandler(final String path) {
init();
parse(path);
}
- public crawlHandler(InputStream stream) {
+ public crawlHandler(final InputStream stream) {
init();
parse(stream);
}
@@ -89,27 +89,27 @@ public class crawlHandler extends DefaultHandler {
parsingStartpoint = false;
}
- private void parse(String path) {
+ private void parse(final String path) {
try {
- SAXParserFactory factory = SAXParserFactory.newInstance();
- SAXParser saxParser = factory.newSAXParser();
+ final SAXParserFactory factory = SAXParserFactory.newInstance();
+ final SAXParser saxParser = factory.newSAXParser();
saxParser.parse(path, this);
- } catch (Exception e) {
+ } catch (final Exception e) {
e.printStackTrace();
}
}
- private void parse(InputStream stream) {
+ private void parse(final InputStream stream) {
try {
- SAXParserFactory factory = SAXParserFactory.newInstance();
- SAXParser saxParser = factory.newSAXParser();
+ final SAXParserFactory factory = SAXParserFactory.newInstance();
+ final SAXParser saxParser = factory.newSAXParser();
saxParser.parse(stream, this);
- } catch (Exception e) {
+ } catch (final Exception e) {
e.printStackTrace();
}
}
- public void startElement(String uri, String name, String tag, Attributes atts) {
+ public void startElement(final String uri, final String name, final String tag, final Attributes atts) {
if ("channel".equals(tag)) {
channel = new Startpoint();
parsingAttributes = true;
@@ -119,27 +119,27 @@ public class crawlHandler extends DefaultHandler {
}
}
- public void endElement(String uri, String name, String tag) {
+ public void endElement(final String uri, final String name, final String tag) {
if (tag == null) return;
if ("channel".equals(tag)) {
parsingAttributes = false;
} else if ("item".equals(tag)) {
- String guid = startpoint.getGuid();
+ final String guid = startpoint.getGuid();
startpointsGUID.add(guid);
startpoints.put(guid, startpoint);
parsingStartpoint = false;
} else if (parsingStartpoint) {
- String value = buffer.toString().trim();
+ final String value = buffer.toString().trim();
buffer.setLength(0);
if (startpointTagsSet.contains(tag)) startpoint.setValue(tag, value);
} else if (parsingAttributes) {
- String value = buffer.toString().trim();
+ final String value = buffer.toString().trim();
buffer.setLength(0);
if (startpointTagsSet.contains(tag)) channel.setValue(tag, value);
}
}
- public void characters(char ch[], int start, int length) {
+ public void characters(final char ch[], final int start, final int length) {
if (parsingStartpoint || parsingAttributes) {
buffer.append(ch, start, length);
}
@@ -149,12 +149,12 @@ public class crawlHandler extends DefaultHandler {
return channel;
}
- public Startpoint getStartpoint(int i) {
+ public Startpoint getStartpoint(final int i) {
// retrieve item by order number
return getStartpoint(startpointsGUID.get(i));
}
- public Startpoint getStartpoint(String guid) {
+ public Startpoint getStartpoint(final String guid) {
// retrieve item by guid
return startpoints.get(guid);
}
@@ -165,13 +165,13 @@ public class crawlHandler extends DefaultHandler {
public static class Attributes {
- private HashMap<String, String> map;
+ private final HashMap<String, String> map;
public Attributes() {
this.map = new HashMap<String, String>();
}
- public void setValue(String name, String value) {
+ public void setValue(final String name, final String value) {
map.put(name, value);
}
@@ -222,14 +222,14 @@ public class crawlHandler extends DefaultHandler {
public static class Startpoint {
- private HashMap<String, String> map;
+ private final HashMap<String, String> map;
public Startpoint() {
this.map = new HashMap<String, String>();
this.map.put("guid", Long.toHexString(System.currentTimeMillis()) + ":" + guidcount++);
}
- public void setValue(String name, String value) {
+ public void setValue(final String name, final String value) {
map.put(name, value);
}
diff --git a/source/de/anomic/xml/opensearchdescriptionReader.java b/source/de/anomic/xml/opensearchdescriptionReader.java
index fa9648ec4..a07b9ca93 100644
--- a/source/de/anomic/xml/opensearchdescriptionReader.java
+++ b/source/de/anomic/xml/opensearchdescriptionReader.java
@@ -95,11 +95,11 @@ public class opensearchdescriptionReader extends DefaultHandler {
// class variables
private Item channel;
- private StringBuffer buffer;
+ private final StringBuffer buffer;
private boolean parsingChannel;
private String imageURL;
- private ArrayList<String> itemsGUID; // a list of GUIDs, so the items can be retrieved by a specific order
- private HashMap<String, Item> items; // a guid:Item map
+ private final ArrayList<String> itemsGUID; // a list of GUIDs, so the items can be retrieved by a specific order
+ private final HashMap<String, Item> items; // a guid:Item map
public opensearchdescriptionReader() {
@@ -110,29 +110,29 @@ public class opensearchdescriptionReader extends DefaultHandler {
parsingChannel = false;
}
- public opensearchdescriptionReader(String path) {
+ public opensearchdescriptionReader(final String path) {
this();
try {
- SAXParserFactory factory = SAXParserFactory.newInstance();
- SAXParser saxParser = factory.newSAXParser();
+ final SAXParserFactory factory = SAXParserFactory.newInstance();
+ final SAXParser saxParser = factory.newSAXParser();
saxParser.parse(path, this);
- } catch (Exception e) {
+ } catch (final Exception e) {
e.printStackTrace();
}
}
- public opensearchdescriptionReader(InputStream stream) {
+ public opensearchdescriptionReader(final InputStream stream) {
this();
try {
- SAXParserFactory factory = SAXParserFactory.newInstance();
- SAXParser saxParser = factory.newSAXParser();
+ final SAXParserFactory factory = SAXParserFactory.newInstance();
+ final SAXParser saxParser = factory.newSAXParser();
saxParser.parse(stream, this);
- } catch (Exception e) {
+ } catch (final Exception e) {
e.printStackTrace();
}
}
- public static opensearchdescriptionReader parse(byte[] a) {
+ public static opensearchdescriptionReader parse(final byte[] a) {
// check integrity of array
if ((a == null) || (a.length == 0)) {
@@ -147,46 +147,46 @@ public class opensearchdescriptionReader extends DefaultHandler {
serverLog.logWarning("opensearchdescriptionReader", "response does not contain valid xml");
return null;
}
- String end = new String(a, a.length - 10, 10);
+ final String end = new String(a, a.length - 10, 10);
if (end.indexOf("rss") < 0) {
serverLog.logWarning("opensearchdescriptionReader", "response incomplete");
return null;
}
// make input stream
- ByteArrayInputStream bais = new ByteArrayInputStream(a);
+ final ByteArrayInputStream bais = new ByteArrayInputStream(a);
// parse stream
opensearchdescriptionReader reader = null;
try {
reader = new opensearchdescriptionReader(bais);
- } catch (Exception e) {
+ } catch (final Exception e) {
serverLog.logWarning("opensearchdescriptionReader", "parse exception: " + e);
return null;
}
- try { bais.close(); } catch (IOException e) {}
+ try { bais.close(); } catch (final IOException e) {}
return reader;
}
- public void startElement(String uri, String name, String tag, Attributes atts) throws SAXException {
+ public void startElement(final String uri, final String name, final String tag, final Attributes atts) throws SAXException {
if ("channel".equals(tag)) {
channel = new Item();
parsingChannel = true;
}
}
- public void endElement(String uri, String name, String tag) {
+ public void endElement(final String uri, final String name, final String tag) {
if (tag == null) return;
if ("channel".equals(tag)) {
parsingChannel = false;
} else if (parsingChannel) {
- String value = buffer.toString().trim();
+ final String value = buffer.toString().trim();
buffer.setLength(0);
if (tags.contains(tag)) channel.setValue(tag, value);
}
}
- public void characters(char ch[], int start, int length) {
+ public void characters(final char ch[], final int start, final int length) {
if (parsingChannel) {
buffer.append(ch, start, length);
}
@@ -196,12 +196,12 @@ public class opensearchdescriptionReader extends DefaultHandler {
return channel;
}
- public Item getItem(int i) {
+ public Item getItem(final int i) {
// retrieve item by order number
return getItem(itemsGUID.get(i));
}
- public Item getItem(String guid) {
+ public Item getItem(final String guid) {
// retrieve item by guid
return items.get(guid);
}
@@ -216,14 +216,14 @@ public class opensearchdescriptionReader extends DefaultHandler {
public static class Item {
- private HashMap<String, String> map;
+ private final HashMap<String, String> map;
public Item() {
this.map = new HashMap<String, String>();
this.map.put("guid", Long.toHexString(System.currentTimeMillis()) + ":" + guidcount++);
}
- public void setValue(String name, String value) {
+ public void setValue(final String name, final String value) {
map.put(name, value);
}
}
diff --git a/source/de/anomic/yacy/seedUpload/yacySeedUploadFile.java b/source/de/anomic/yacy/seedUpload/yacySeedUploadFile.java
index d3f90fc0d..4374ad481 100644
--- a/source/de/anomic/yacy/seedUpload/yacySeedUploadFile.java
+++ b/source/de/anomic/yacy/seedUpload/yacySeedUploadFile.java
@@ -36,18 +36,18 @@ public class yacySeedUploadFile implements yacySeedUploader {
public static final String CONFIG_FILE_PATH = "seedFilePath";
- public String uploadSeedFile(serverSwitch<?> sb, yacySeedDB seedDB, File seedFile) throws Exception {
+ public String uploadSeedFile(final serverSwitch<?> sb, final yacySeedDB seedDB, final File seedFile) throws Exception {
String seedFilePath = "";
try {
seedFilePath = sb.getConfig(CONFIG_FILE_PATH,"");
if (seedFilePath.length() == 0) throw new Exception("Path to seed file is not configured properly");
- File publicSeedFile = new File(seedFilePath);
+ final File publicSeedFile = new File(seedFilePath);
serverFileUtils.copy(seedFile,publicSeedFile);
return "Seed-List file stored successfully";
- } catch (Exception e) {
+ } catch (final Exception e) {
throw new Exception("Unable to store the seed-list file into the filesystem using path '" + seedFilePath + "'. " + e.getMessage());
}
}
diff --git a/source/de/anomic/yacy/seedUpload/yacySeedUploadFtp.java b/source/de/anomic/yacy/seedUpload/yacySeedUploadFtp.java
index 21ada8b9b..ddf15b206 100644
--- a/source/de/anomic/yacy/seedUpload/yacySeedUploadFtp.java
+++ b/source/de/anomic/yacy/seedUpload/yacySeedUploadFtp.java
@@ -39,7 +39,7 @@ public class yacySeedUploadFtp implements yacySeedUploader {
public static final String CONFIG_FTP_PASSWORD = "seedFTPPassword";
public static final String CONFIG_FTP_PATH = "seedFTPPath";
- public String uploadSeedFile (serverSwitch<?> sb, yacySeedDB seedDB, File seedFile) throws Exception {
+ public String uploadSeedFile (final serverSwitch<?> sb, final yacySeedDB seedDB, final File seedFile) throws Exception {
try {
if (sb == null) throw new NullPointerException("Reference to serverSwitch must not be null.");
if (seedDB == null) throw new NullPointerException("Reference to seedDB must not be null.");
@@ -47,19 +47,19 @@ public class yacySeedUploadFtp implements yacySeedUploader {
if (!seedFile.isFile()) throw new Exception("Seed file is not a file.");
if (!seedFile.canRead()) throw new Exception("Seed file is not readable.");
- String seedFTPServer = sb.getConfig(CONFIG_FTP_SERVER,null);
- String seedFTPAccount = sb.getConfig(CONFIG_FTP_ACCOUNT,null);
- String seedFTPPassword = sb.getConfig(CONFIG_FTP_PASSWORD,null);
- File seedFTPPath = new File(sb.getConfig(CONFIG_FTP_PATH,null));
+ final String seedFTPServer = sb.getConfig(CONFIG_FTP_SERVER,null);
+ final String seedFTPAccount = sb.getConfig(CONFIG_FTP_ACCOUNT,null);
+ final String seedFTPPassword = sb.getConfig(CONFIG_FTP_PASSWORD,null);
+ final File seedFTPPath = new File(sb.getConfig(CONFIG_FTP_PATH,null));
if ((seedFTPServer != null) && (seedFTPAccount != null) && (seedFTPPassword != null) && (seedFTPPath != null)) {
- String log = ftpc.put(seedFTPServer, seedFile, seedFTPPath.getParent(), seedFTPPath.getName(), seedFTPAccount, seedFTPPassword);
+ final String log = ftpc.put(seedFTPServer, seedFile, seedFTPPath.getParent(), seedFTPPath.getName(), seedFTPAccount, seedFTPPassword);
return log;
}
throw new Exception ("Seed upload settings not configured properly. password-len=" +
(seedFTPPassword == null ? "null" : seedFTPPassword.length()) + ", filePath=" +
seedFTPPath);
- } catch (Exception e) {
+ } catch (final Exception e) {
throw e;
}
}
diff --git a/source/de/anomic/yacy/seedUpload/yacySeedUploadScp.java b/source/de/anomic/yacy/seedUpload/yacySeedUploadScp.java
index 6de2c2ea1..fadad9681 100644
--- a/source/de/anomic/yacy/seedUpload/yacySeedUploadScp.java
+++ b/source/de/anomic/yacy/seedUpload/yacySeedUploadScp.java
@@ -51,17 +51,17 @@ public class yacySeedUploadScp implements yacySeedUploader {
public static final String CONFIG_SCP_PASSWORD = "seedScpPassword";
public static final String CONFIG_SCP_PATH = "seedScpPath";
- public String uploadSeedFile(serverSwitch<?> sb, yacySeedDB seedDB, File seedFile) throws Exception {
+ public String uploadSeedFile(final serverSwitch<?> sb, final yacySeedDB seedDB, final File seedFile) throws Exception {
try {
if (sb == null) throw new NullPointerException("Reference to serverSwitch nut not be null.");
if (seedDB == null) throw new NullPointerException("Reference to seedDB must not be null.");
if ((seedFile == null)||(!seedFile.exists())) throw new Exception("Seed file does not exist.");
- String seedScpServer = sb.getConfig(CONFIG_SCP_SERVER,null);
- String seedScpServerPort = sb.getConfig(CONFIG_SCP_SERVER_PORT,"22");
- String seedScpAccount = sb.getConfig(CONFIG_SCP_ACCOUNT,null);
- String seedScpPassword = sb.getConfig(CONFIG_SCP_PASSWORD,null);
- String seedScpPath = sb.getConfig(CONFIG_SCP_PATH,null);
+ final String seedScpServer = sb.getConfig(CONFIG_SCP_SERVER,null);
+ final String seedScpServerPort = sb.getConfig(CONFIG_SCP_SERVER_PORT,"22");
+ final String seedScpAccount = sb.getConfig(CONFIG_SCP_ACCOUNT,null);
+ final String seedScpPassword = sb.getConfig(CONFIG_SCP_PASSWORD,null);
+ final String seedScpPath = sb.getConfig(CONFIG_SCP_PATH,null);
if (seedScpServer == null || seedScpServer.length() == 0)
throw new Exception("Seed SCP upload settings not configured properly. Servername must not be null or empty.");
@@ -76,12 +76,12 @@ public class yacySeedUploadScp implements yacySeedUploader {
int port = 22;
try {
port = Integer.valueOf(seedScpServerPort).intValue();
- } catch (NumberFormatException ex) {
+ } catch (final NumberFormatException ex) {
throw new Exception("Seed SCP upload settings not configured properly. Server port is not a vaild integer.");
}
return sshc.put(seedScpServer, port, seedFile, seedScpPath, seedScpAccount, seedScpPassword);
- } catch (Exception e) {
+ } catch (final Exception e) {
throw e;
}
}
@@ -98,18 +98,18 @@ public class yacySeedUploadScp implements yacySeedUploader {
class sshc {
public static String put(
- String host,
- int port,
- File localFile,
- String remoteName,
- String account,
- String password
+ final String host,
+ final int port,
+ final File localFile,
+ final String remoteName,
+ final String account,
+ final String password
) throws Exception {
Session session = null;
try {
// Creating a new secure channel object
- JSch jsch=new JSch();
+ final JSch jsch=new JSch();
// setting hostname, username, userpassword
session = jsch.getSession(account, host, port);
@@ -119,7 +119,7 @@ class sshc {
* Setting the StrictHostKeyChecking to ignore unknown
* hosts because of a missing known_hosts file ...
*/
- java.util.Properties config = new java.util.Properties();
+ final java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking","no");
session.setConfig(config);
@@ -127,26 +127,26 @@ class sshc {
* we need this user interaction interface to support
* the interactive-keyboard mode
*/
- UserInfo ui=new SchUserInfo(password);
+ final UserInfo ui=new SchUserInfo(password);
session.setUserInfo(ui);
// trying to connect ...
session.connect();
String command="scp -p -t " + remoteName;
- Channel channel = session.openChannel("exec");
+ final Channel channel = session.openChannel("exec");
((ChannelExec)channel).setCommand(command);
// get I/O streams for remote scp
- OutputStream out=channel.getOutputStream();
- InputStream in=channel.getInputStream();
+ final OutputStream out=channel.getOutputStream();
+ final InputStream in=channel.getInputStream();
channel.connect();
checkAck(in);
// send "C0644 filesize filename", where filename should not include '/'
- int filesize=(int)(localFile).length();
+ final int filesize=(int)(localFile).length();
command="C0644 "+filesize+" ";
if(localFile.toString().lastIndexOf('/')>0){
command+=localFile.toString().substring(localFile.toString().lastIndexOf('/')+1);
@@ -160,17 +160,17 @@ class sshc {
checkAck(in);
// send a content of lfile
- byte[] buf=new byte[1024];
+ final byte[] buf=new byte[1024];
BufferedInputStream bufferedIn = null;
try {
bufferedIn=new BufferedInputStream(new FileInputStream(localFile));
while(true){
- int len=bufferedIn.read(buf, 0, buf.length);
+ final int len=bufferedIn.read(buf, 0, buf.length);
if(len<=0) break;
out.write(buf, 0, len); out.flush();
}
} finally {
- if (bufferedIn != null) try{bufferedIn.close();}catch(Exception e){}
+ if (bufferedIn != null) try{bufferedIn.close();}catch(final Exception e){}
}
// send '\0'
@@ -179,15 +179,15 @@ class sshc {
checkAck(in);
return "SCP: File uploaded successfully.";
- } catch (Exception e) {
+ } catch (final Exception e) {
throw new Exception("SCP: File uploading failed: " + e.getMessage());
} finally {
if ((session != null) && (session.isConnected())) session.disconnect();
}
}
- static int checkAck(InputStream in) throws IOException{
- int b=in.read();
+ static int checkAck(final InputStream in) throws IOException{
+ final int b=in.read();
// b may be 0 for success,
// 1 for error,
// 2 for fatal error,
@@ -196,7 +196,7 @@ class sshc {
if(b==-1) return b;
if(b==1 || b==2){
- StringBuffer sb=new StringBuffer();
+ final StringBuffer sb=new StringBuffer();
int c;
do {
c=in.read();
@@ -220,7 +220,7 @@ class SchUserInfo
implements UserInfo, UIKeyboardInteractive {
String passwd;
- public SchUserInfo(String password) {
+ public SchUserInfo(final String password) {
this.passwd = password;
}
@@ -228,7 +228,7 @@ implements UserInfo, UIKeyboardInteractive {
return this.passwd;
}
- public boolean promptYesNo(String str){
+ public boolean promptYesNo(final String str){
System.err.println("User was prompted from: " + str);
return true;
}
@@ -237,12 +237,12 @@ implements UserInfo, UIKeyboardInteractive {
return null;
}
- public boolean promptPassphrase(String message) {
+ public boolean promptPassphrase(final String message) {
System.out.println("promptPassphrase : " + message);
return false;
}
- public boolean promptPassword(String message) {
+ public boolean promptPassword(final String message) {
System.out.println("promptPassword : " + message);
return true;
}
@@ -250,15 +250,15 @@ implements UserInfo, UIKeyboardInteractive {
/**
* @see com.jcraft.jsch.UserInfo#showMessage(java.lang.String)
*/
- public void showMessage(String message) {
+ public void showMessage(final String message) {
System.out.println("Sch has tried to show the following message to the user: " + message);
}
- public String[] promptKeyboardInteractive(String destination,
- String name,
- String instruction,
- String[] prompt,
- boolean[] echo) {
+ public String[] promptKeyboardInteractive(final String destination,
+ final String name,
+ final String instruction,
+ final String[] prompt,
+ final boolean[] echo) {
System.out.println("User was prompted using interactive-keyboard: " +
"\n\tDestination: " + destination +
"\n\tName: " + name +
@@ -271,8 +271,8 @@ implements UserInfo, UIKeyboardInteractive {
return new String[]{};
}
- String arrayToString2(String[] a, String separator) {
- StringBuffer result = new StringBuffer();// start with first element
+ String arrayToString2(final String[] a, final String separator) {
+ final StringBuffer result = new StringBuffer();// start with first element
if (a.length > 0) {
result.append(a[0]);
for (int i=1; i<a.length; i++) {
@@ -283,8 +283,8 @@ implements UserInfo, UIKeyboardInteractive {
return result.toString();
}
- String arrayToString2(boolean[] a, String separator) {
- StringBuffer result = new StringBuffer();// start with first element
+ String arrayToString2(final boolean[] a, final String separator) {
+ final StringBuffer result = new StringBuffer();// start with first element
if (a.length > 0) {
result.append(a[0]);
for (int i=1; i<a.length; i++) {
diff --git a/source/de/anomic/yacy/yacyAccessible.java b/source/de/anomic/yacy/yacyAccessible.java
index 0c93221f0..4572c9345 100644
--- a/source/de/anomic/yacy/yacyAccessible.java
+++ b/source/de/anomic/yacy/yacyAccessible.java
@@ -41,13 +41,13 @@ public class yacyAccessible {
* updates Shortcut /addon/YaCy-Search.html
* @param newPort
*/
- public static void setNewPortLink(int newPort){
+ public static void setNewPortLink(final int newPort){
try {
- plasmaSwitchboard sb = plasmaSwitchboard.getSwitchboard();
- File shortcut = new File(sb.getRootPath() + "/addon/YaCy-Search.html".replace("/", File.separator));
- String content = "<meta http-equiv=\"refresh\" content=\"0;url=http://localhost:" + newPort + "/\">";
+ final plasmaSwitchboard sb = plasmaSwitchboard.getSwitchboard();
+ final File shortcut = new File(sb.getRootPath() + "/addon/YaCy-Search.html".replace("/", File.separator));
+ final String content = "<meta http-equiv=\"refresh\" content=\"0;url=http://localhost:" + newPort + "/\">";
serverFileUtils.copy(content.getBytes(), shortcut);
- } catch (Exception e) {
+ } catch (final Exception e) {
return;
}
}
@@ -56,13 +56,13 @@ public class yacyAccessible {
* updates Shortcut /addon/YaCy-Search.bat
* @param newPort
*/
- public static void setNewPortBat(int newPort){
+ public static void setNewPortBat(final int newPort){
try {
- plasmaSwitchboard sb = plasmaSwitchboard.getSwitchboard();
- File shortcut = new File(sb.getRootPath() + "/addon/YaCy-Search.bat".replace("/", File.separator));
- String content = "rundll32 url.dll,FileProtocolHandler \"http://localhost:" + newPort + "\"";
+ final plasmaSwitchboard sb = plasmaSwitchboard.getSwitchboard();
+ final File shortcut = new File(sb.getRootPath() + "/addon/YaCy-Search.bat".replace("/", File.separator));
+ final String content = "rundll32 url.dll,FileProtocolHandler \"http://localhost:" + newPort + "\"";
serverFileUtils.copy(content.getBytes(), shortcut);
- } catch (Exception e) {
+ } catch (final Exception e) {
return;
}
}
diff --git a/source/de/anomic/yacy/yacyClient.java b/source/de/anomic/yacy/yacyClient.java
index 31b95b89f..c2001fcef 100644
--- a/source/de/anomic/yacy/yacyClient.java
+++ b/source/de/anomic/yacy/yacyClient.java
@@ -92,7 +92,7 @@ import de.anomic.xml.RSSReader;
public final class yacyClient {
- public static int publishMySeed(yacySeed mySeed, yacyPeerActions peerActions, String address, String otherHash) {
+ public static int publishMySeed(final yacySeed mySeed, final yacyPeerActions peerActions, final String address, final String otherHash) {
// this is called to enrich the seed information by
// - own address (if peer is behind a nat/router)
// - check peer type (virgin/junior/senior/principal)
@@ -119,12 +119,12 @@ public final class yacyClient {
post.add(new StringPart("count", "20"));
post.add(new StringPart("seed", mySeed.genSeedStr(salt)));
// send request
- long start = System.currentTimeMillis();
- byte[] content = wput("http://" + address + "/yacy/hello.html", yacySeed.b64Hash2hexHash(otherHash) + ".yacyh", post, 15000, false);
+ final long start = System.currentTimeMillis();
+ final byte[] content = wput("http://" + address + "/yacy/hello.html", yacySeed.b64Hash2hexHash(otherHash) + ".yacyh", post, 15000, false);
yacyCore.log.logInfo("yacyClient.publishMySeed thread '" + Thread.currentThread().getName() + "' contacted peer at " + address + ", received " + ((content == null) ? "null" : content.length) + " bytes, time = " + (System.currentTimeMillis() - start) + " milliseconds");
result = nxTools.table(content, "UTF-8");
break;
- } catch (Exception e) {
+ } catch (final Exception e) {
if (Thread.currentThread().isInterrupted()) {
yacyCore.log.logWarning("yacyClient.publishMySeed thread '" + Thread.currentThread().getName() + "' interrupted.");
return -1;
@@ -163,15 +163,15 @@ public final class yacyClient {
if (serverCore.useStaticIP) {
mySeed.setIP(serverDomains.myPublicIP());
} else {
- String myIP = result.get("yourip");
- String properIP = yacySeed.isProperIP(myIP);
+ final String myIP = result.get("yourip");
+ final String properIP = yacySeed.isProperIP(myIP);
if (properIP == null) mySeed.setIP(myIP);
}
// change our seed-type
String mytype = result.get(yacySeed.YOURTYPE);
if (mytype == null) { mytype = ""; }
- yacyAccessible accessible = new yacyAccessible();
+ final yacyAccessible accessible = new yacyAccessible();
if (mytype.equals(yacySeed.PEERTYPE_SENIOR)||mytype.equals(yacySeed.PEERTYPE_PRINCIPAL)) {
accessible.IWasAccessed = true;
if (mySeed.isPrincipal()) {
@@ -249,7 +249,7 @@ public final class yacyClient {
* @return response body
* @throws IOException
*/
- private static byte[] wput(final String url, String vhost, final List<Part> post, final int timeout) throws IOException {
+ private static byte[] wput(final String url, final String vhost, final List<Part> post, final int timeout) throws IOException {
return wput(url, vhost, post, timeout, false);
}
/**
@@ -263,11 +263,11 @@ public final class yacyClient {
* @return response body
* @throws IOException
*/
- private static byte[] wput(final String url, String vhost, final List<Part> post, final int timeout, boolean gzipBody) throws IOException {
- httpHeader header = new httpHeader();
+ private static byte[] wput(final String url, final String vhost, final List<Part> post, final int timeout, final boolean gzipBody) throws IOException {
+ final httpHeader header = new httpHeader();
header.put(httpHeader.USER_AGENT, HTTPLoader.yacyUserAgent);
header.put(httpHeader.HOST, vhost);
- JakartaCommonsHttpClient client = new JakartaCommonsHttpClient(timeout, header, null);
+ final JakartaCommonsHttpClient client = new JakartaCommonsHttpClient(timeout, header, null);
client.setProxy(proxyConfig());
JakartaCommonsHttpResponse res = null;
@@ -293,14 +293,14 @@ public final class yacyClient {
* @return
* @throws IOException
*/
- private static byte[] postToFile(final yacySeed target, final String filename, final List<Part> post, int timeout) throws IOException {
+ private static byte[] postToFile(final yacySeed target, final String filename, final List<Part> post, final int timeout) throws IOException {
return wput("http://" + target.getClusterAddress() + "/yacy/" + filename, target.getHexHash() + ".yacyh", post, timeout, false);
}
- private static byte[] postToFile(yacySeedDB seedDB, final String targetHash, final String filename, final List<Part> post, int timeout) throws IOException {
+ private static byte[] postToFile(final yacySeedDB seedDB, final String targetHash, final String filename, final List<Part> post, final int timeout) throws IOException {
return wput("http://" + targetAddress(seedDB, targetHash) + "/yacy/" + filename, yacySeed.b64Hash2hexHash(targetHash)+ ".yacyh", post, timeout, false);
}
- public static yacySeed querySeed(yacySeed target, String seedHash) {
+ public static yacySeed querySeed(final yacySeed target, final String seedHash) {
// prepare request
final String salt = crypt.randomSalt();
final List<Part> post = yacyNetwork.basicRequestPost(plasmaSwitchboard.getSwitchboard(), target.hash, salt);
@@ -309,19 +309,19 @@ public final class yacyClient {
// send request
try {
- byte[] content = postToFile(target, "query.html", post, 10000);
+ final byte[] content = postToFile(target, "query.html", post, 10000);
final HashMap<String, String> result = nxTools.table(content, "UTF-8");
if (result == null || result.size() == 0) { return null; }
//final Date remoteTime = yacyCore.parseUniversalDate((String) result.get(yacySeed.MYTIME)); // read remote time
return yacySeed.genRemoteSeed(result.get("response"), salt, false);
- } catch (Exception e) {
+ } catch (final Exception e) {
yacyCore.log.logSevere("yacyClient.querySeed error:" + e.getMessage());
return null;
}
}
- public static int queryRWICount(yacySeed target, String wordHash) {
+ public static int queryRWICount(final yacySeed target, final String wordHash) {
// prepare request
final String salt = crypt.randomSalt();
final List<Part> post = yacyNetwork.basicRequestPost(plasmaSwitchboard.getSwitchboard(), target.hash, salt);
@@ -331,18 +331,18 @@ public final class yacyClient {
// send request
try {
- byte[] content = postToFile(target, "query.html", post, 5000);
+ final byte[] content = postToFile(target, "query.html", post, 5000);
final HashMap<String, String> result = nxTools.table(content, "UTF-8");
if (result == null || result.size() == 0) { return -1; }
return Integer.parseInt(result.get("response"));
- } catch (Exception e) {
+ } catch (final Exception e) {
yacyCore.log.logSevere("yacyClient.queryRWICount error:" + e.getMessage());
return -1;
}
}
- public static int queryUrlCount(yacySeed target) {
+ public static int queryUrlCount(final yacySeed target) {
if (target == null) { return -1; }
// prepare request
@@ -354,7 +354,7 @@ public final class yacyClient {
// send request
try {
- byte[] content = postToFile(target, "query.html", post, 5000);
+ final byte[] content = postToFile(target, "query.html", post, 5000);
final HashMap<String, String> result = nxTools.table(content, "UTF-8");
if ((result == null) || (result.size() == 0)) return -1;
@@ -363,16 +363,16 @@ public final class yacyClient {
return -1;
} else try {
return Integer.parseInt(resp);
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
return -1;
}
- } catch (IOException e) {
+ } catch (final IOException e) {
yacyCore.log.logSevere("yacyClient.queryUrlCount error asking peer '" + target.getName() + "':" + e.toString());
return -1;
}
}
- public static RSSFeed queryRemoteCrawlURLs(yacySeedDB seedDB, yacySeed target, int count) {
+ public static RSSFeed queryRemoteCrawlURLs(final yacySeedDB seedDB, final yacySeed target, final int count) {
// returns a list of
if (target == null) { return null; }
@@ -386,7 +386,7 @@ public final class yacyClient {
try {
/* a long time-out is needed */
final byte[] result = wput("http://" + target.getClusterAddress() + "/yacy/urls.xml", target.getHexHash() + ".yacyh", post, 60000);
- RSSReader reader = RSSReader.parse(result);
+ final RSSReader reader = RSSReader.parse(result);
if (reader == null) {
yacyCore.log.logWarning("yacyClient.queryRemoteCrawlURLs failed asking peer '" + target.getName() + "': probably bad response from remote peer (1), reader == null");
target.put(yacySeed.RCOUNT, "0");
@@ -394,7 +394,7 @@ public final class yacyClient {
//e.printStackTrace();
return null;
}
- RSSFeed feed = reader.getFeed();
+ final RSSFeed feed = reader.getFeed();
if (feed == null) {
// case where the rss reader does not understand the content
yacyCore.log.logWarning("yacyClient.queryRemoteCrawlURLs failed asking peer '" + target.getName() + "': probably bad response from remote peer (2)");
@@ -405,31 +405,31 @@ public final class yacyClient {
return null;
}
return feed;
- } catch (IOException e) {
+ } catch (final IOException e) {
yacyCore.log.logSevere("yacyClient.queryRemoteCrawlURLs error asking peer '" + target.getName() + "':" + e.toString());
return null;
}
}
public static String[] search(
- yacySeed mySeed,
- String wordhashes,
- String excludehashes,
- String urlhashes,
- String prefer,
- String filter,
- int count,
- int maxDistance,
- boolean global,
- int partitions,
- yacySeed target,
- plasmaWordIndex wordIndex,
- ResultURLs crawlResults,
- plasmaSearchRankingProcess containerCache,
- Map<String, TreeMap<String, String>> abstractCache,
- indexReferenceBlacklist blacklist,
- plasmaSearchRankingProfile rankingProfile,
- kelondroBitfield constraint
+ final yacySeed mySeed,
+ final String wordhashes,
+ final String excludehashes,
+ final String urlhashes,
+ final String prefer,
+ final String filter,
+ final int count,
+ final int maxDistance,
+ final boolean global,
+ final int partitions,
+ final yacySeed target,
+ final plasmaWordIndex wordIndex,
+ final ResultURLs crawlResults,
+ final plasmaSearchRankingProcess containerCache,
+ final Map<String, TreeMap<String, String>> abstractCache,
+ final indexReferenceBlacklist blacklist,
+ final plasmaSearchRankingProfile rankingProfile,
+ final kelondroBitfield constraint
) {
// send a search request to peer with remote Hash
// this mainly converts the words into word hashes
@@ -471,7 +471,7 @@ public final class yacyClient {
HashMap<String, String> result = null;
try {
result = nxTools.table(wput("http://" + target.getClusterAddress() + "/yacy/search.html", target.getHexHash() + ".yacyh", post, 60000), "UTF-8");
- } catch (IOException e) {
+ } catch (final IOException e) {
yacyCore.log.logInfo("SEARCH failed, Peer: " + target.hash + ":" + target.getName() + " (" + e.getMessage() + "), score=" + target.selectscore + ", DHTdist=" + yacyDHTAction.dhtDistance(target.hash, wordhashes.substring(0, 12)));
//yacyCore.peerActions.peerDeparture(target, "search request to peer created io exception: " + e.getMessage());
return null;
@@ -512,7 +512,7 @@ public final class yacyClient {
try {
results = Integer.parseInt(result.get("count"));
joincount = Integer.parseInt(result.get("joincount"));
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
yacyCore.log.logInfo("SEARCH failed FROM " + target.hash + ":" + target.getName() + ", wrong output format: " + e.getMessage());
//yacyCore.peerActions.peerDeparture(target, "search request to peer created number format exception");
return null;
@@ -521,27 +521,27 @@ public final class yacyClient {
// create containers
final int words = wordhashes.length() / yacySeedDB.commonHashLength;
- indexContainer[] container = new indexContainer[words];
+ final indexContainer[] container = new indexContainer[words];
for (int i = 0; i < words; i++) {
container[i] = plasmaWordIndex.emptyContainer(wordhashes.substring(i * yacySeedDB.commonHashLength, (i + 1) * yacySeedDB.commonHashLength), count);
}
// insert results to containers
indexURLReference urlEntry;
- String[] urls = new String[results];
+ final String[] urls = new String[results];
for (int n = 0; n < results; n++) {
// get one single search result
urlEntry = indexURLReference.importEntry(result.get("resource" + n));
if (urlEntry == null) continue;
assert (urlEntry.hash().length() == 12) : "urlEntry.hash() = " + urlEntry.hash();
if (urlEntry.hash().length() != 12) continue; // bad url hash
- indexURLReference.Components comp = urlEntry.comp();
+ final indexURLReference.Components comp = urlEntry.comp();
if (blacklist.isListed(indexReferenceBlacklist.BLACKLIST_SEARCH, comp.url())) {
yacyCore.log.logInfo("remote search (client): filtered blacklisted url " + comp.url() + " from peer " + target.getName());
continue; // block with backlist
}
- String urlRejectReason = plasmaSwitchboard.getSwitchboard().acceptURL(comp.url());
+ final String urlRejectReason = plasmaSwitchboard.getSwitchboard().acceptURL(comp.url());
if (urlRejectReason != null) {
yacyCore.log.logInfo("remote search (client): rejected url '" + comp.url() + "' (" + urlRejectReason + ") from peer " + target.getName());
continue; // reject url outside of our domain
@@ -565,7 +565,7 @@ public final class yacyClient {
try {
wordIndex.putURL(urlEntry);
crawlResults.stack(urlEntry, mySeed.hash, target.hash, 2);
- } catch (IOException e) {
+ } catch (final IOException e) {
yacyCore.log.logSevere("could not store search result", e);
continue; // db-error
}
@@ -593,7 +593,7 @@ public final class yacyClient {
containerCache.insertRanked(container[0], false, joincount); // one is enough
// integrate remote topwords
- String references = result.get("references");
+ final String references = result.get("references");
yacyCore.log.logInfo("remote search (client): peer " + target.getName() + " sent references " + references);
if (references != null) {
// add references twice, so they can be countet (must have at least 2 entries)
@@ -604,7 +604,7 @@ public final class yacyClient {
// read index abstract
if (abstractCache != null) {
- Iterator<Map.Entry<String, String>> i = result.entrySet().iterator();
+ final Iterator<Map.Entry<String, String>> i = result.entrySet().iterator();
Map.Entry<String, String> entry;
TreeMap<String, String> singleAbstract;
String wordhash;
@@ -634,7 +634,7 @@ public final class yacyClient {
long searchtime;
try {
searchtime = Integer.parseInt(result.get("searchtime"));
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
searchtime = totalrequesttime;
}
yacyCore.log.logFine("SEARCH "
@@ -655,7 +655,7 @@ public final class yacyClient {
return urls;
}
- public static HashMap<String, String> permissionMessage(yacySeedDB seedDB, String targetHash) {
+ public static HashMap<String, String> permissionMessage(final yacySeedDB seedDB, final String targetHash) {
// ask for allowed message size and attachement size
// if this replies null, the peer does not answer
@@ -669,14 +669,14 @@ public final class yacyClient {
final byte[] content = postToFile(seedDB, targetHash, "message.html", post, 5000);
final HashMap<String, String> result = nxTools.table(content, "UTF-8");
return result;
- } catch (Exception e) {
+ } catch (final Exception e) {
// most probably a network time-out exception
yacyCore.log.logSevere("yacyClient.permissionMessage error:" + e.getMessage());
return null;
}
}
- public static HashMap<String, String> postMessage(yacySeedDB seedDB, String targetHash, String subject, byte[] message) {
+ public static HashMap<String, String> postMessage(final yacySeedDB seedDB, final String targetHash, final String subject, final byte[] message) {
// this post a message to the remote message board
// prepare request
@@ -687,7 +687,7 @@ public final class yacyClient {
post.add(new StringPart("subject", subject));
try {
post.add(new StringPart("message", new String(message, "UTF-8")));
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
post.add(new StringPart("message", new String(message)));
}
@@ -696,13 +696,13 @@ public final class yacyClient {
final byte[] content = postToFile(seedDB, targetHash, "message.html", post, 20000);
final HashMap<String, String> result = nxTools.table(content, "UTF-8");
return result;
- } catch (Exception e) {
+ } catch (final Exception e) {
yacyCore.log.logSevere("yacyClient.postMessage error:" + e.getMessage());
return null;
}
}
- public static String targetAddress(yacySeedDB seedDB, String targetHash) {
+ public static String targetAddress(final yacySeedDB seedDB, final String targetHash) {
// find target address
String address;
if (targetHash.equals(seedDB.mySeed().hash)) {
@@ -716,7 +716,7 @@ public final class yacyClient {
return address;
}
- public static HashMap<String, String> transferPermission(String targetAddress, long filesize, String filename) {
+ public static HashMap<String, String> transferPermission(final String targetAddress, final long filesize, final String filename) {
// prepare request
final String salt = crypt.randomSalt();
@@ -732,14 +732,14 @@ public final class yacyClient {
final byte[] content = wput("http://" + targetAddress + "/yacy/transfer.html", targetAddress, post, 10000);
final HashMap<String, String> result = nxTools.table(content, "UTF-8");
return result;
- } catch (Exception e) {
+ } catch (final Exception e) {
// most probably a network time-out exception
yacyCore.log.logSevere("yacyClient.permissionTransfer error:" + e.getMessage());
return null;
}
}
- public static HashMap<String, String> transferStore(String targetAddress, String access, String filename, byte[] file) {
+ public static HashMap<String, String> transferStore(final String targetAddress, final String access, final String filename, final byte[] file) {
// prepare request
final String salt = crypt.randomSalt();
@@ -756,26 +756,26 @@ public final class yacyClient {
final byte[] content = wput("http://" + targetAddress + "/yacy/transfer.html", targetAddress, post, 20000);
final HashMap<String, String> result = nxTools.table(content, "UTF-8");
return result;
- } catch (Exception e) {
+ } catch (final Exception e) {
yacyCore.log.logSevere("yacyClient.postMessage error:" + e.getMessage());
return null;
}
}
- public static String transfer(String targetAddress, String filename, byte[] file) {
- HashMap<String, String> phase1 = transferPermission(targetAddress, file.length, filename);
+ public static String transfer(final String targetAddress, final String filename, final byte[] file) {
+ final HashMap<String, String> phase1 = transferPermission(targetAddress, file.length, filename);
if (phase1 == null) return "no connection to remote address " + targetAddress + "; phase 1";
- String access = phase1.get("access");
- String nextaddress = phase1.get("address");
- String protocol = phase1.get("protocol");
+ final String access = phase1.get("access");
+ final String nextaddress = phase1.get("address");
+ final String protocol = phase1.get("protocol");
//String path = (String) phase1.get("path");
//String maxsize = (String) phase1.get("maxsize");
String response = phase1.get("response");
if ((response == null) || (protocol == null) || (access == null)) return "wrong return values from other peer; phase 1";
if (!(response.equals("ok"))) return "remote peer rejected transfer: " + response;
- String accesscode = serverCodings.encodeMD5Hex(kelondroBase64Order.standardCoder.encodeString(access));
+ final String accesscode = serverCodings.encodeMD5Hex(kelondroBase64Order.standardCoder.encodeString(access));
if (protocol.equals("http")) {
- HashMap<String, String> phase2 = transferStore(nextaddress, accesscode, filename, file);
+ final HashMap<String, String> phase2 = transferStore(nextaddress, accesscode, filename, file);
if (phase2 == null) return "no connection to remote address " + targetAddress + "; phase 2";
response = phase2.get("response");
if (response == null) return "wrong return values from other peer; phase 2";
@@ -787,7 +787,7 @@ public final class yacyClient {
return "wrong protocol: " + protocol;
}
- public static HashMap<String, String> crawlReceipt(yacySeed mySeed, yacySeed target, String process, String result, String reason, indexURLReference entry, String wordhashes) {
+ public static HashMap<String, String> crawlReceipt(final yacySeed mySeed, final yacySeed target, final String process, final String result, final String reason, final indexURLReference entry, final String wordhashes) {
assert (target != null);
assert (mySeed != null);
assert (mySeed != target);
@@ -828,18 +828,18 @@ public final class yacyClient {
// send request
try {
- byte[] content = wput("http://" + address + "/yacy/crawlReceipt.html", target.getHexHash() + ".yacyh", post, 10000);
+ final byte[] content = wput("http://" + address + "/yacy/crawlReceipt.html", target.getHexHash() + ".yacyh", post, 10000);
return nxTools.table(content, "UTF-8");
- } catch (Exception e) {
+ } catch (final Exception e) {
// most probably a network time-out exception
yacyCore.log.logSevere("yacyClient.crawlReceipt error:" + e.getMessage());
return null;
}
}
- public static HashMap<String, Object> transferIndex(yacySeedDB seedDB, yacySeed targetSeed, indexContainer[] indexes, HashMap<String, indexURLReference> urlCache, boolean gzipBody, int timeout) {
+ public static HashMap<String, Object> transferIndex(final yacySeedDB seedDB, final yacySeed targetSeed, final indexContainer[] indexes, final HashMap<String, indexURLReference> urlCache, final boolean gzipBody, final int timeout) {
- HashMap<String, Object> resultObj = new HashMap<String, Object>();
+ final HashMap<String, Object> resultObj = new HashMap<String, Object>();
int payloadSize = 0;
try {
@@ -890,7 +890,7 @@ public final class yacyClient {
if (uhs.length == 0) { return resultObj; } // all url's known
// extract the urlCache from the result
- indexURLReference[] urls = new indexURLReference[uhs.length];
+ final indexURLReference[] urls = new indexURLReference[uhs.length];
for (int i = 0; i < uhs.length; i++) {
urls[i] = urlCache.get(uhs[i]);
if (urls[i] == null) {
@@ -927,7 +927,7 @@ public final class yacyClient {
}
}
- private static HashMap<String, String> transferRWI(yacySeedDB seedDB, yacySeed targetSeed, indexContainer[] indexes, boolean gzipBody, int timeout) {
+ private static HashMap<String, String> transferRWI(final yacySeedDB seedDB, final yacySeed targetSeed, final indexContainer[] indexes, boolean gzipBody, final int timeout) {
final String address = targetSeed.getPublicAddress();
if (address == null) { return null; }
@@ -978,13 +978,13 @@ public final class yacyClient {
// return the transfered index data in bytes (for debugging only)
result.put("indexPayloadSize", Integer.toString(entrypost.length()));
return result;
- } catch (Exception e) {
+ } catch (final Exception e) {
yacyCore.log.logSevere("yacyClient.transferRWI error:" + e.getMessage());
return null;
}
}
- private static HashMap<String, String> transferURL(yacySeedDB seedDB, yacySeed targetSeed, indexURLReference[] urls, boolean gzipBody, int timeout) {
+ private static HashMap<String, String> transferURL(final yacySeedDB seedDB, final yacySeed targetSeed, final indexURLReference[] urls, boolean gzipBody, final int timeout) {
// this post a message to the remote message board
final String address = targetSeed.getPublicAddress();
if (address == null) { return null; }
@@ -1020,17 +1020,17 @@ public final class yacyClient {
seedDB.mySeed().incSU(urlc);
}
- HashMap<String, String> result = nxTools.table(v);
+ final HashMap<String, String> result = nxTools.table(v);
// return the transfered url data in bytes (for debugging only)
result.put("urlPayloadSize", Integer.toString(urlPayloadSize));
return result;
- } catch (Exception e) {
+ } catch (final Exception e) {
yacyCore.log.logSevere("yacyClient.transferURL error:" + e.getMessage());
return null;
}
}
- public static HashMap<String, String> getProfile(yacySeed targetSeed) {
+ public static HashMap<String, String> getProfile(final yacySeed targetSeed) {
// this post a message to the remote message board
final String salt = crypt.randomSalt();
@@ -1041,7 +1041,7 @@ public final class yacyClient {
try {
final byte[] content = wput("http://" + address + "/yacy/profile.html", targetSeed.getHexHash() + ".yacyh", post, 5000);
return nxTools.table(content, "UTF-8");
- } catch (Exception e) {
+ } catch (final Exception e) {
yacyCore.log.logSevere("yacyClient.getProfile error:" + e.getMessage());
return null;
}
@@ -1052,11 +1052,11 @@ public final class yacyClient {
* @return
*/
private static final httpRemoteProxyConfig proxyConfig() {
- httpRemoteProxyConfig p = httpdProxyHandler.getRemoteProxyConfig();
+ final httpRemoteProxyConfig p = httpdProxyHandler.getRemoteProxyConfig();
return ((p != null) && (p.useProxy()) && (p.useProxy4Yacy())) ? p : null;
}
- public static void main(String[] args) {
+ public static void main(final String[] args) {
if(args.length > 1) {
System.out.println("yacyClient Test");
try {
@@ -1067,7 +1067,7 @@ public final class yacyClient {
final String wordhashe = indexWord.word2hash("test");
//System.out.println("permission=" + permissionMessage(args[1]));
- httpHeader reqHeader = new httpHeader();
+ final httpHeader reqHeader = new httpHeader();
reqHeader.put(httpHeader.USER_AGENT, HTTPLoader.crawlerUserAgent);
final byte[] content = HttpClient.wget(
"http://" + target.getPublicAddress() + "/yacy/search.html" +
@@ -1081,7 +1081,7 @@ public final class yacyClient {
reqHeader, 10000, target.getHexHash() + ".yacyh");
final HashMap<String, String> result = nxTools.table(content, "UTF-8");
System.out.println("Result=" + result.toString());
- } catch (Exception e) {
+ } catch (final Exception e) {
e.printStackTrace();
}
System.exit(0);
@@ -1091,7 +1091,7 @@ public final class yacyClient {
URL url = null;
try {
url = new URL(args[0]);
- } catch (MalformedURLException e) {
+ } catch (final MalformedURLException e) {
e.printStackTrace();
}
if(url == null) {
@@ -1110,7 +1110,7 @@ public final class yacyClient {
try {
final byte[] response = wput(url.toString(), vhost, post, timeout, gzipBody);
System.out.println(new String(response));
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
}
diff --git a/source/de/anomic/yacy/yacyCore.java b/source/de/anomic/yacy/yacyCore.java
index a690c2ba2..08ec291d4 100644
--- a/source/de/anomic/yacy/yacyCore.java
+++ b/source/de/anomic/yacy/yacyCore.java
@@ -89,14 +89,14 @@ public class yacyCore {
return Math.max(0, (int) ((System.currentTimeMillis() - serverCore.startupTime) / 1000));
}
- public yacyCore(plasmaSwitchboard sb) {
- long time = System.currentTimeMillis();
+ public yacyCore(final plasmaSwitchboard sb) {
+ final long time = System.currentTimeMillis();
this.sb = sb;
sb.setConfig("yacyStatus", "");
// create a peer news channel
- RSSFeed peernews = RSSFeed.channels(RSSFeed.PEERNEWS);
+ final RSSFeed peernews = RSSFeed.channels(RSSFeed.PEERNEWS);
peernews.addMessage(new RSSMessage("YaCy started", "", ""));
// ensure that correct IP is used
@@ -146,7 +146,7 @@ public class yacyCore {
return onlineMode;
}
- public static void setOnlineMode(int newOnlineMode) {
+ public static void setOnlineMode(final int newOnlineMode) {
onlineMode = newOnlineMode;
return;
}
@@ -242,12 +242,12 @@ public class yacyCore {
protected class publishThread extends Thread {
int added;
- private yacySeed seed;
+ private final yacySeed seed;
private final serverSemaphore sync;
private final List<Thread> syncList;
- public publishThread(ThreadGroup tg, yacySeed seed,
- serverSemaphore sync, List<Thread> syncList) throws InterruptedException {
+ public publishThread(final ThreadGroup tg, final yacySeed seed,
+ final serverSemaphore sync, final List<Thread> syncList) throws InterruptedException {
super(tg, "PublishSeed_" + seed.getName());
this.sync = sync;
@@ -263,7 +263,7 @@ public class yacyCore {
this.added = yacyClient.publishMySeed(sb.webIndex.seedDB.mySeed(), sb.webIndex.peerActions, seed.getClusterAddress(), seed.hash);
if (this.added < 0) {
// no or wrong response, delete that address
- String cause = "peer ping to peer resulted in error response (added < 0)";
+ final String cause = "peer ping to peer resulted in error response (added < 0)";
log.logInfo("publish: disconnected " + this.seed.get(yacySeed.PEERTYPE, yacySeed.PEERTYPE_SENIOR) + " peer '" + this.seed.getName() + "' from " + this.seed.getPublicAddress() + ": " + cause);
sb.webIndex.peerActions.peerDeparture(this.seed, cause);
} else {
@@ -271,7 +271,7 @@ public class yacyCore {
// update latest news from the other peer
log.logInfo("publish: handshaked " + this.seed.get(yacySeed.PEERTYPE, yacySeed.PEERTYPE_SENIOR) + " peer '" + this.seed.getName() + "' at " + this.seed.getPublicAddress());
// check if seed's lastSeen has been updated
- yacySeed newSeed = sb.webIndex.seedDB.getConnected(this.seed.hash);
+ final yacySeed newSeed = sb.webIndex.seedDB.getConnected(this.seed.hash);
if (newSeed != null) {
if (newSeed.getLastSeenUTC() < (System.currentTimeMillis() - 10000)) {
// update last seed date
@@ -294,7 +294,7 @@ public class yacyCore {
log.logFine("publish: recently handshaked " + this.seed.get(yacySeed.PEERTYPE, yacySeed.PEERTYPE_SENIOR) + " peer '" + this.seed.getName() + "' at " + this.seed.getPublicAddress() + " not in connectedDB");
}
}
- } catch (Exception e) {
+ } catch (final Exception e) {
log.logSevere("publishThread: error with target seed " + seed.toString() + ": " + e.getMessage(), e);
} finally {
this.syncList.add(this);
@@ -303,7 +303,7 @@ public class yacyCore {
}
}
- private int publishMySeed(boolean force) {
+ private int publishMySeed(final boolean force) {
try {
// call this after the httpd was started up
@@ -329,11 +329,11 @@ public class yacyCore {
// getting a list of peers to contact
if (sb.webIndex.seedDB.mySeed().get(yacySeed.PEERTYPE, yacySeed.PEERTYPE_VIRGIN).equals(yacySeed.PEERTYPE_VIRGIN)) {
if (attempts > PING_INITIAL) { attempts = PING_INITIAL; }
- Map<String, String> ch = plasmaSwitchboard.getSwitchboard().clusterhashes;
+ final Map<String, String> ch = plasmaSwitchboard.getSwitchboard().clusterhashes;
seeds = sb.webIndex.seedDB.seedsByAge(true, attempts - ((ch == null) ? 0 : ch.size())); // best for fast connection
// add also all peers from cluster if this is a public robinson cluster
if (ch != null) {
- Iterator<Map.Entry<String, String>> i = ch.entrySet().iterator();
+ final Iterator<Map.Entry<String, String>> i = ch.entrySet().iterator();
String hash;
Map.Entry<String, String> entry;
yacySeed seed;
@@ -364,7 +364,7 @@ public class yacyCore {
if (seeds.size() < attempts) { attempts = seeds.size(); }
// This will try to get Peers that are not currently in amIAccessibleDB
- Iterator<yacySeed> si = seeds.values().iterator();
+ final Iterator<yacySeed> si = seeds.values().iterator();
yacySeed seed;
// include a YaCyNews record to my seed
@@ -375,7 +375,7 @@ public class yacyCore {
} else {
sb.webIndex.seedDB.mySeed().put("news", de.anomic.tools.crypt.simpleEncode(record.toString()));
}
- } catch (IOException e) {
+ } catch (final IOException e) {
log.logSevere("publishMySeed: problem with news encoding", e);
}
sb.webIndex.seedDB.mySeed().setUnusedFlags();
@@ -402,7 +402,7 @@ public class yacyCore {
final String address = seed.getClusterAddress();
log.logFine("HELLO #" + i + " to peer '" + seed.get(yacySeed.NAME, "") + "' at " + address); // debug
- String seederror = seed.isProper(false);
+ final String seederror = seed.isProper(false);
if ((address == null) || (seederror != null)) {
// we don't like that address, delete it
sb.webIndex.peerActions.peerDeparture(seed, "peer ping to peer resulted in address = " + address + "; seederror = " + seederror);
@@ -446,9 +446,9 @@ public class yacyCore {
final int dbSize;
synchronized (amIAccessibleDB) {
dbSize = amIAccessibleDB.size();
- Iterator<String> ai = amIAccessibleDB.keySet().iterator();
+ final Iterator<String> ai = amIAccessibleDB.keySet().iterator();
while (ai.hasNext()) {
- yacyAccessible ya = amIAccessibleDB.get(ai.next());
+ final yacyAccessible ya = amIAccessibleDB.get(ai.next());
if (ya.lastUpdated < cutofftime) {
ai.remove();
} else {
@@ -501,7 +501,7 @@ public class yacyCore {
// still no success: ask own NAT or internet responder
//final boolean DI604use = switchboard.getConfig("DI604use", "false").equals("true");
//final String DI604pw = switchboard.getConfig("DI604pw", "");
- String ip = sb.getConfig("staticIP", "");
+ final String ip = sb.getConfig("staticIP", "");
//if (ip.equals("")) ip = natLib.retrieveIP(DI604use, DI604pw);
// yacyCore.log.logDebug("DEBUG: new IP=" + ip);
@@ -512,7 +512,7 @@ public class yacyCore {
((sb.webIndex.seedDB.mySeed().getPublicAddress() == null) ? "unknown" : sb.webIndex.seedDB.mySeed().getPublicAddress()));
sb.webIndex.seedDB.saveMySeed();
return 0;
- } catch (InterruptedException e) {
+ } catch (final InterruptedException e) {
try {
log.logInfo("publish: Interruption detected while publishing my seed.");
@@ -524,7 +524,7 @@ public class yacyCore {
yacyCore.publishThreadGroup.interrupt();
// waiting some time for the publishThreads to finish execution
- try { Thread.sleep(500); } catch (InterruptedException ex) {}
+ try { Thread.sleep(500); } catch (final InterruptedException ex) {}
// getting the amount of remaining publishing threads
int threadCount = yacyCore.publishThreadGroup.activeCount();
@@ -538,13 +538,13 @@ public class yacyCore {
if (currentThread.isAlive()) {
log.logFine("publish: Waiting for remaining publishing thread '" + currentThread.getName() + "' to finish shutdown");
- try { currentThread.join(500); } catch (InterruptedException ex) {}
+ try { currentThread.join(500); } catch (final InterruptedException ex) {}
}
}
log.logInfo("publish: Shutdown off all remaining publishing thread finished.");
- } catch (Exception ee) {
+ } catch (final Exception ee) {
log.logWarning("publish: Unexpected error while trying to shutdown all remaining publishing threads.", e);
}
@@ -559,7 +559,7 @@ public class yacyCore {
}
}
- public static yacySeedUploader getSeedUploader(String methodname) {
+ public static yacySeedUploader getSeedUploader(final String methodname) {
String className = null;
synchronized (yacyCore.seedUploadMethods) {
if (yacyCore.seedUploadMethods.containsKey(methodname)) {
@@ -572,7 +572,7 @@ public class yacyCore {
final Class<?> uploaderClass = Class.forName(className);
final Object uploader = uploaderClass.newInstance();
return (yacySeedUploader) uploader;
- } catch (Exception e) {
+ } catch (final Exception e) {
return null;
}
}
@@ -591,7 +591,7 @@ public class yacyCore {
}
final String[] uploaderClasses = uploadersDir.list(new FilenameFilter() {
- public boolean accept(File dir, String name) {
+ public boolean accept(final File dir, final String name) {
return name.startsWith("yacySeedUpload") && name.endsWith(".class");
}
});
@@ -615,11 +615,11 @@ public class yacyCore {
}
}
availableUploaders.put(className.substring("yacySeedUpload".length()), fullClassName);
- } catch (Exception e) { /* we can ignore this for the moment */
- } catch (Error e) { /* we can ignore this for the moment */
+ } catch (final Exception e) { /* we can ignore this for the moment */
+ } catch (final Error e) { /* we can ignore this for the moment */
}
}
- } catch (Exception e) {
+ } catch (final Exception e) {
} finally {
synchronized (yacyCore.seedUploadMethods) {
yacyCore.seedUploadMethods.clear();
@@ -628,7 +628,7 @@ public class yacyCore {
}
}
- public static boolean changeSeedUploadMethod(String method) {
+ public static boolean changeSeedUploadMethod(final String method) {
if (method == null || method.length() == 0) { return false; }
if (method.equalsIgnoreCase("none")) { return true; }
@@ -638,7 +638,7 @@ public class yacyCore {
}
}
- public static final String saveSeedList(plasmaSwitchboard sb) {
+ public static final String saveSeedList(final plasmaSwitchboard sb) {
try {
// return an error if this is not successful, and NULL if everything is fine
String logt;
@@ -672,7 +672,7 @@ public class yacyCore {
// determine the seed uploader that should be used ...
if (seedUploadMethod.equalsIgnoreCase("none")) { return "no uploader specified"; }
- yacySeedUploader uploader = getSeedUploader(seedUploadMethod);
+ final yacySeedUploader uploader = getSeedUploader(seedUploadMethod);
if (uploader == null) {
final String errorMsg = "Unable to get the proper uploader-class for seed uploading method '" + seedUploadMethod + "'.";
log.logWarning("SaveSeedList: " + errorMsg);
@@ -691,7 +691,7 @@ public class yacyCore {
throw new MalformedURLException("Unsupported protocol.");
}
seedURL = new yacyURL(seedURLStr, null);
- } catch (MalformedURLException e) {
+ } catch (final MalformedURLException e) {
final String errorMsg = "Malformed seed file URL '" + sb.webIndex.seedDB.mySeed().get(yacySeed.SEEDLIST, "") + "'. " + e.getMessage();
log.logWarning("SaveSeedList: " + errorMsg);
return errorMsg;
@@ -722,7 +722,7 @@ public class yacyCore {
// finally, set the principal status
sb.setConfig("yacyStatus", yacySeed.PEERTYPE_PRINCIPAL);
return null;
- } catch (Exception e) {
+ } catch (final Exception e) {
sb.webIndex.seedDB.mySeed().put(yacySeed.PEERTYPE, prevStatus);
sb.setConfig("yacyStatus", prevStatus);
final String errorMsg = "SaveSeedList: Seed upload failed (IO error): " + e.getMessage();
diff --git a/source/de/anomic/yacy/yacyDHTAction.java b/source/de/anomic/yacy/yacyDHTAction.java
index 4c85de019..6109ce27e 100644
--- a/source/de/anomic/yacy/yacyDHTAction.java
+++ b/source/de/anomic/yacy/yacyDHTAction.java
@@ -42,18 +42,18 @@ public class yacyDHTAction {
protected yacySeedDB seedDB;
protected kelondroMScoreCluster<String> seedCrawlReady;
- public yacyDHTAction(yacySeedDB seedDB) {
+ public yacyDHTAction(final yacySeedDB seedDB) {
this.seedDB = seedDB;
this.seedCrawlReady = new kelondroMScoreCluster<String>();
// init crawl-ready table
try {
- Iterator<yacySeed> en = seedDB.seedsConnected(true, false, null, (float) 0.0);
+ final Iterator<yacySeed> en = seedDB.seedsConnected(true, false, null, (float) 0.0);
yacySeed ys;
while (en.hasNext()) {
ys = en.next();
if ((ys != null) && (ys.getVersion() >= ((float) 0.3))) seedCrawlReady.setScore(ys.hash, yacyCore.yacyTime());
}
- } catch (IllegalArgumentException e) {
+ } catch (final IllegalArgumentException e) {
}
}
@@ -62,7 +62,7 @@ public class yacyDHTAction {
seedCrawlReady = null;
}
- public Iterator<yacySeed> getDHTSeeds(boolean up, String firstHash, float minVersion) {
+ public Iterator<yacySeed> getDHTSeeds(final boolean up, final String firstHash, final float minVersion) {
// enumerates seed-type objects: all seeds with starting point in the middle, rotating at the end/beginning
return new seedDHTEnum(up, firstHash, minVersion);
}
@@ -74,7 +74,7 @@ public class yacyDHTAction {
int steps;
float minVersion;
- public seedDHTEnum(boolean up, String firstHash, float minVersion) {
+ public seedDHTEnum(final boolean up, final String firstHash, final float minVersion) {
this.steps = seedDB.sizeConnected();
this.up = up;
this.minVersion = minVersion;
@@ -90,7 +90,7 @@ public class yacyDHTAction {
if (steps == 0) return null;
steps--;
if ((e1 != null) && (e1.hasNext())) {
- yacySeed n = e1.next();
+ final yacySeed n = e1.next();
if (!(e1.hasNext())) {
e1 = null;
e2 = seedDB.seedsConnected(up, false, null, minVersion);
@@ -136,7 +136,7 @@ public class yacyDHTAction {
if (s == null) return null;
if (s.getLong(yacySeed.RCOUNT, 0) > 0) return s;
}
- } catch (kelondroException e) {
+ } catch (final kelondroException e) {
System.out.println("DEBUG providesRemoteCrawlURLsEnum:" + e.getMessage());
yacyCore.log.logSevere("database inconsistency (" + e.getMessage() + "), re-set of db.");
seedDB.resetActiveTable();
@@ -146,7 +146,7 @@ public class yacyDHTAction {
}
public yacySeed next() {
- yacySeed next = nextSeed;
+ final yacySeed next = nextSeed;
nextSeed = nextInternal();
return next;
}
@@ -157,7 +157,7 @@ public class yacyDHTAction {
}
- public Iterator<yacySeed> getAcceptRemoteIndexSeeds(String starthash) {
+ public Iterator<yacySeed> getAcceptRemoteIndexSeeds(final String starthash) {
// returns an enumeration of yacySeed-Objects
// that have the AcceptRemoteIndex-Flag set
// the seeds are enumerated in the right order according DHT
@@ -169,7 +169,7 @@ public class yacyDHTAction {
Iterator<yacySeed> se;
yacySeed nextSeed;
- public acceptRemoteIndexSeedEnum(String starthash) {
+ public acceptRemoteIndexSeedEnum(final String starthash) {
se = getDHTSeeds(true, starthash, yacyVersion.YACY_HANDLES_COLLECTION_INDEX);
nextSeed = nextInternal();
}
@@ -186,7 +186,7 @@ public class yacyDHTAction {
if (s == null) return null;
if (s.getFlagAcceptRemoteIndex()) return s;
}
- } catch (kelondroException e) {
+ } catch (final kelondroException e) {
System.out.println("DEBUG acceptRemoteIndexSeedEnum:" + e.getMessage());
yacyCore.log.logSevere("database inconsistency (" + e.getMessage() + "), re-set of db.");
seedDB.resetActiveTable();
@@ -196,7 +196,7 @@ public class yacyDHTAction {
}
public yacySeed next() {
- yacySeed next = nextSeed;
+ final yacySeed next = nextSeed;
nextSeed = nextInternal();
return next;
}
@@ -207,7 +207,7 @@ public class yacyDHTAction {
}
- public Iterator<yacySeed> getAcceptRemoteCrawlSeeds(String starthash, boolean available) {
+ public Iterator<yacySeed> getAcceptRemoteCrawlSeeds(final String starthash, final boolean available) {
return new acceptRemoteCrawlSeedEnum(starthash, available);
}
@@ -217,7 +217,7 @@ public class yacyDHTAction {
yacySeed nextSeed;
boolean available;
- public acceptRemoteCrawlSeedEnum(String starthash, boolean available) {
+ public acceptRemoteCrawlSeedEnum(final String starthash, final boolean available) {
this.se = getDHTSeeds(true, starthash, (float) 0.0);
this.available = available;
nextSeed = nextInternal();
@@ -243,7 +243,7 @@ public class yacyDHTAction {
}
public yacySeed next() {
- yacySeed next = nextSeed;
+ final yacySeed next = nextSeed;
nextSeed = nextInternal();
return next;
}
@@ -254,7 +254,7 @@ public class yacyDHTAction {
}
- public synchronized yacySeed getGlobalCrawlSeed(String urlHash) {
+ public synchronized yacySeed getGlobalCrawlSeed(final String urlHash) {
Iterator<yacySeed> e = getAcceptRemoteCrawlSeeds(urlHash, true);
yacySeed seed;
if (e.hasNext()) seed = e.next(); else seed = null;
@@ -262,14 +262,14 @@ public class yacyDHTAction {
return seed;
}
- public synchronized yacySeed getPublicClusterCrawlSeed(String urlHash, TreeMap<String, String> clusterhashes) {
+ public synchronized yacySeed getPublicClusterCrawlSeed(final String urlHash, final TreeMap<String, String> clusterhashes) {
// clusterhashes is a String(hash)/String(IP) - mapping
- kelondroCloneableIterator<String> i = new kelondroRotateIterator<String>(new kelondroCloneableMapIterator<String>(clusterhashes, urlHash), null, clusterhashes.size());
+ final kelondroCloneableIterator<String> i = new kelondroRotateIterator<String>(new kelondroCloneableMapIterator<String>(clusterhashes, urlHash), null, clusterhashes.size());
String hash;
int count = clusterhashes.size(); // counter to ensure termination
while ((i.hasNext()) && (count-- > 0)) {
hash = i.next();
- yacySeed seed = seedDB.getConnected(hash);
+ final yacySeed seed = seedDB.getConnected(hash);
if (seed == null) continue;
seed.setAlternativeAddress(clusterhashes.get(hash));
return seed;
@@ -277,16 +277,16 @@ public class yacyDHTAction {
return null;
}
- public void setCrawlTime(String seedHash, int newYacyTime) {
+ public void setCrawlTime(final String seedHash, int newYacyTime) {
if (newYacyTime < yacyCore.yacyTime()) newYacyTime = yacyCore.yacyTime();
seedCrawlReady.setScore(seedHash, newYacyTime);
}
- public void setCrawlDelay(String seedHash, int newDelay) {
+ public void setCrawlDelay(final String seedHash, final int newDelay) {
seedCrawlReady.setScore(seedHash, yacyCore.yacyTime() + newDelay);
}
- public void processPeerArrival(yacySeed peer, boolean direct) {
+ public void processPeerArrival(final yacySeed peer, final boolean direct) {
if (peer.getVersion() >= ((float) 0.3)) {
if (!(seedCrawlReady.existsScore(peer.hash))) seedCrawlReady.setScore(peer.hash, yacyCore.yacyTime());
} else {
@@ -294,11 +294,11 @@ public class yacyDHTAction {
}
}
- public void processPeerDeparture(yacySeed peer) {
+ public void processPeerDeparture(final yacySeed peer) {
seedCrawlReady.deleteScore(peer.hash);
}
- public static boolean shallBeOwnWord(yacySeedDB seedDB, String wordhash) {
+ public static boolean shallBeOwnWord(final yacySeedDB seedDB, final String wordhash) {
if (seedDB == null) return false;
if (seedDB.mySeed().isPotential()) return false;
final double distance = dhtDistance(seedDB.mySeed().hash, wordhash);
@@ -307,10 +307,10 @@ public class yacyDHTAction {
return (distance > 0) && (distance <= max);
}
- public static double dhtDistance(String peer, String word) {
+ public static double dhtDistance(final String peer, final String word) {
// the dht distance is a positive value between 0 and 1
// if the distance is small, the word more probably belongs to the peer
- double d = hashDistance(peer, word);
+ final double d = hashDistance(peer, word);
if (d > 0) {
return d; // case where the word is 'before' the peer
} else {
@@ -318,7 +318,7 @@ public class yacyDHTAction {
}
}
- private static double hashDistance(String from, String to) {
+ private static double hashDistance(final String from, final String to) {
// computes the distance between two hashes.
// the maximum distance between two hashes is 1, the minimum -1
// this can be used like "from - to"
@@ -330,7 +330,7 @@ public class yacyDHTAction {
return ((double) (kelondroBase64Order.enhancedCoder.cardinal(from.getBytes()) - kelondroBase64Order.enhancedCoder.cardinal(to.getBytes()))) / ((double) Long.MAX_VALUE);
}
- public synchronized ArrayList<yacySeed> getDHTTargets(yacySeedDB seedDB, serverLog log, int primaryPeerCount, int reservePeerCount, String firstKey, String lastKey, double maxDist) {
+ public synchronized ArrayList<yacySeed> getDHTTargets(final yacySeedDB seedDB, final serverLog log, final int primaryPeerCount, final int reservePeerCount, final String firstKey, final String lastKey, final double maxDist) {
// find a list of DHT-peers
assert firstKey != null;
assert lastKey != null;
@@ -342,14 +342,14 @@ public class yacyDHTAction {
!(kelondroBase64Order.enhancedCoder.cardinal(firstKey.getBytes()) < kelondroBase64Order.enhancedCoder.cardinal(yacyCore.seedDB.mySeed.hash.getBytes()) &&
kelondroBase64Order.enhancedCoder.cardinal(lastKey.getBytes()) > kelondroBase64Order.enhancedCoder.cardinal(yacyCore.seedDB.mySeed.hash.getBytes()));
*/
- ArrayList<yacySeed> seeds = new ArrayList<yacySeed>();
+ final ArrayList<yacySeed> seeds = new ArrayList<yacySeed>();
yacySeed seed;
//double ownDistance = Math.min(yacyDHTAction.dhtDistance(yacyCore.seedDB.mySeed.hash, firstKey), yacyDHTAction.dhtDistance(yacyCore.seedDB.mySeed.hash, lastKey));
//double maxDistance = Math.min(ownDistance, maxDist);
double firstdist, lastdist;
Iterator<yacySeed> e = this.getAcceptRemoteIndexSeeds(lastKey);
- TreeSet<String> doublecheck = new TreeSet<String>(kelondroBase64Order.enhancedComparator);
+ final TreeSet<String> doublecheck = new TreeSet<String>(kelondroBase64Order.enhancedComparator);
int maxloop = Math.min(100, seedDB.sizeConnected()); // to ensure termination
if (log != null) log.logInfo("Collecting DHT target peers for first_hash = " + firstKey + ", last_hash = " + lastKey);
while ((e.hasNext()) && (seeds.size() < (primaryPeerCount + reservePeerCount)) && (maxloop-- > 0)) {
diff --git a/source/de/anomic/yacy/yacyNetwork.java b/source/de/anomic/yacy/yacyNetwork.java
index 353cd603e..2f3fab19f 100644
--- a/source/de/anomic/yacy/yacyNetwork.java
+++ b/source/de/anomic/yacy/yacyNetwork.java
@@ -42,28 +42,28 @@ import de.anomic.server.serverSwitch;
public class yacyNetwork {
- public static final boolean authentifyRequest(serverObjects post, serverSwitch<?> env) {
+ public static final boolean authentifyRequest(final serverObjects post, final serverSwitch<?> env) {
if ((post == null) || (env == null)) return false;
// identify network
- String unitName = post.get("network.unit.name", yacySeed.DFLT_NETWORK_UNIT); // the network unit
+ final String unitName = post.get("network.unit.name", yacySeed.DFLT_NETWORK_UNIT); // the network unit
if (!unitName.equals(env.getConfig("network.unit.name", yacySeed.DFLT_NETWORK_UNIT))) {
return false;
}
// check authentification method
- String authentificationControl = env.getConfig("network.unit.protocol.control", "uncontrolled");
+ final String authentificationControl = env.getConfig("network.unit.protocol.control", "uncontrolled");
if (authentificationControl.equals("uncontrolled")) return true;
- String authentificationMethod = env.getConfig("network.unit.protocol.request.authentification.method", "");
+ final String authentificationMethod = env.getConfig("network.unit.protocol.request.authentification.method", "");
if (authentificationMethod.length() == 0) {
return false;
}
if (authentificationMethod.equals("salted-magic-sim")) {
// authentify the peer using the md5-magic
- String salt = post.get("key", "");
- String iam = post.get("iam", "");
- String magic = env.getConfig("network.unit.protocol.request.authentification.essentials", "");
- String md5 = serverCodings.encodeMD5Hex(salt + iam + magic);
+ final String salt = post.get("key", "");
+ final String iam = post.get("iam", "");
+ final String magic = env.getConfig("network.unit.protocol.request.authentification.essentials", "");
+ final String md5 = serverCodings.encodeMD5Hex(salt + iam + magic);
return post.get("magicmd5", "").equals(md5);
}
@@ -71,10 +71,10 @@ public class yacyNetwork {
return false;
}
- public static final List<Part> basicRequestPost(plasmaSwitchboard sb, String targetHash, String salt) {
+ public static final List<Part> basicRequestPost(final plasmaSwitchboard sb, final String targetHash, final String salt) {
// put in all the essentials for routing and network authentification
// generate a session key
- ArrayList<Part> post = new ArrayList<Part>();
+ final ArrayList<Part> post = new ArrayList<Part>();
post.add(new StringPart("key", salt));
// just standard identification essentials
@@ -89,13 +89,13 @@ public class yacyNetwork {
post.add(new StringPart("network.unit.name", plasmaSwitchboard.getSwitchboard().getConfig("network.unit.name", yacySeed.DFLT_NETWORK_UNIT)));
// authentification essentials
- String authentificationControl = sb.getConfig("network.unit.protocol.control", "uncontrolled");
- String authentificationMethod = sb.getConfig("network.unit.protocol.request.authentification.method", "");
+ final String authentificationControl = sb.getConfig("network.unit.protocol.control", "uncontrolled");
+ final String authentificationMethod = sb.getConfig("network.unit.protocol.request.authentification.method", "");
if ((authentificationControl.equals("controlled")) && (authentificationMethod.length() > 0)) {
if (authentificationMethod.equals("salted-magic-sim")) {
// generate an authentification essential using the salt, the iam-hash and the network magic
- String magic = sb.getConfig("network.unit.protocol.request.authentification.essentials", "");
- String md5 = serverCodings.encodeMD5Hex(salt + sb.webIndex.seedDB.mySeed().hash + magic);
+ final String magic = sb.getConfig("network.unit.protocol.request.authentification.essentials", "");
+ final String md5 = serverCodings.encodeMD5Hex(salt + sb.webIndex.seedDB.mySeed().hash + magic);
post.add(new StringPart("magicmd5", md5));
}
}
diff --git a/source/de/anomic/yacy/yacyNewsDB.java b/source/de/anomic/yacy/yacyNewsDB.java
index 90d891d16..e8db559af 100644
--- a/source/de/anomic/yacy/yacyNewsDB.java
+++ b/source/de/anomic/yacy/yacyNewsDB.java
@@ -59,17 +59,17 @@ import de.anomic.server.serverDate;
public class yacyNewsDB {
- private File path;
+ private final File path;
protected kelondroIndex news;
- public yacyNewsDB(File path) {
+ public yacyNewsDB(final File path) {
this.path = path;
this.news = new kelondroEcoTable(path, yacyNewsRecord.rowdef, kelondroEcoTable.tailCacheUsageAuto, 10, 0);
//this.news = new kelondroCache(kelondroTree.open(path, true, preloadTime, yacyNewsRecord.rowdef));
}
private void resetDB() {
- try {close();} catch (Exception e) {}
+ try {close();} catch (final Exception e) {}
if (path.exists()) path.delete();
this.news = new kelondroEcoTable(path, yacyNewsRecord.rowdef, kelondroEcoTable.tailCacheUsageAuto, 10, 0);
}
@@ -87,14 +87,14 @@ public class yacyNewsDB {
return news.size();
}
- public void remove(String id) throws IOException {
+ public void remove(final String id) throws IOException {
news.remove(id.getBytes());
}
- public synchronized yacyNewsRecord put(yacyNewsRecord record) throws IOException {
+ public synchronized yacyNewsRecord put(final yacyNewsRecord record) throws IOException {
try {
return b2r(news.put(r2b(record)));
- } catch (kelondroException e) {
+ } catch (final kelondroException e) {
resetDB();
return b2r(news.put(r2b(record)));
}
@@ -126,16 +126,16 @@ public class yacyNewsDB {
}
- public synchronized yacyNewsRecord get(String id) throws IOException {
+ public synchronized yacyNewsRecord get(final String id) throws IOException {
try {
return b2r(news.get(id.getBytes()));
- } catch (kelondroException e) {
+ } catch (final kelondroException e) {
resetDB();
return null;
}
}
- protected final static yacyNewsRecord b2r(kelondroRow.Entry b) {
+ protected final static yacyNewsRecord b2r(final kelondroRow.Entry b) {
if (b == null) return null;
return yacyNewsRecord.newRecord(
b.getColString(0, null),
@@ -146,19 +146,19 @@ public class yacyNewsDB {
);
}
- protected final kelondroRow.Entry r2b(yacyNewsRecord r) {
+ protected final kelondroRow.Entry r2b(final yacyNewsRecord r) {
if (r == null) return null;
try {
- String attributes = r.attributes().toString();
+ final String attributes = r.attributes().toString();
if (attributes.length() > yacyNewsRecord.attributesMaxLength) throw new IllegalArgumentException("attribute length=" + attributes.length() + " exceeds maximum size=" + yacyNewsRecord.attributesMaxLength);
- kelondroRow.Entry entry = this.news.row().newEntry();
+ final kelondroRow.Entry entry = this.news.row().newEntry();
entry.setCol(0, r.id().getBytes());
entry.setCol(1, r.category().getBytes("UTF-8"));
entry.setCol(2, (r.received() == null) ? null : serverDate.formatShortSecond(r.received()).getBytes());
entry.setCol(3, kelondroBase64Order.enhancedCoder.encodeLong(r.distributed(), 2).getBytes());
entry.setCol(4, attributes.getBytes("UTF-8"));
return entry;
- } catch(UnsupportedEncodingException e) {
+ } catch(final UnsupportedEncodingException e) {
// ignore this. this should never occure
return null;
}
diff --git a/source/de/anomic/yacy/yacyNewsPool.java b/source/de/anomic/yacy/yacyNewsPool.java
index 642c75082..12ddcd56b 100644
--- a/source/de/anomic/yacy/yacyNewsPool.java
+++ b/source/de/anomic/yacy/yacyNewsPool.java
@@ -259,11 +259,11 @@ public class yacyNewsPool {
for (int i = 0; i < category.length; i++) categories.add(category[i]);
}
- private yacyNewsDB newsDB;
- private yacyNewsQueue outgoingNews, publishedNews, incomingNews, processedNews;
- private int maxDistribution;
+ private final yacyNewsDB newsDB;
+ private final yacyNewsQueue outgoingNews, publishedNews, incomingNews, processedNews;
+ private final int maxDistribution;
- public yacyNewsPool(File yacyDBPath) {
+ public yacyNewsPool(final File yacyDBPath) {
newsDB = new yacyNewsDB(new File(yacyDBPath, "news.db"));
outgoingNews = new yacyNewsQueue(new File(yacyDBPath, "newsOut.stack"), newsDB);
publishedNews = new yacyNewsQueue(new File(yacyDBPath, "newsPublished.stack"), newsDB);
@@ -284,13 +284,13 @@ public class yacyNewsPool {
return newsDB.size();
}
- public Iterator<yacyNewsRecord> recordIterator(int dbKey, boolean up) {
+ public Iterator<yacyNewsRecord> recordIterator(final int dbKey, final boolean up) {
// returns an iterator of yacyNewsRecord-type objects
- yacyNewsQueue queue = switchQueue(dbKey);
+ final yacyNewsQueue queue = switchQueue(dbKey);
return queue.records(up);
}
- public void publishMyNews(yacyNewsRecord record) {
+ public void publishMyNews(final yacyNewsRecord record) {
// this shall be called if our peer generated a new news record and wants to publish it
if (record == null) return;
try {
@@ -298,13 +298,13 @@ public class yacyNewsPool {
incomingNews.push(record); // we want to see our own news..
outgoingNews.push(record); // .. and put it on the publishing list
}
- } catch (IOException e) {}
+ } catch (final IOException e) {}
}
public yacyNewsRecord myPublication() throws IOException {
// generate a record for next peer-ping
if (outgoingNews.size() == 0) return null;
- yacyNewsRecord record = outgoingNews.topInc();
+ final yacyNewsRecord record = outgoingNews.topInc();
if ((record != null) && (record.distributed() >= maxDistribution)) {
// move record to its final position. This is only for history
publishedNews.push(outgoingNews.pop());
@@ -312,7 +312,7 @@ public class yacyNewsPool {
return record;
}
- public void enqueueIncomingNews(yacyNewsRecord record) throws IOException {
+ public void enqueueIncomingNews(final yacyNewsRecord record) throws IOException {
// called if a news is attached to a seed
// check consistency
@@ -321,7 +321,7 @@ public class yacyNewsPool {
if (record.category() == null) return;
if (!(categories.contains(record.category()))) return;
if (record.created().getTime() == 0) return;
- Map<String, String> attributes = record.attributes();
+ final Map<String, String> attributes = record.attributes();
if (attributes.containsKey("url")){
if (plasmaSwitchboard.urlBlacklist.isListed(indexReferenceBlacklist.BLACKLIST_NEWS, new yacyURL(attributes.get("url"), null))){
System.out.println("DEBUG: ignored news-entry url blacklisted: " + attributes.get("url"));
@@ -343,17 +343,17 @@ public class yacyNewsPool {
//RSSFeed.channels(yacyCore.channelName).addMessage(new RSSMessage("Incoming News: " + record.category() + " from " + record.originator(), record.attributes().toString()));
}
- public int size(int dbKey) {
+ public int size(final int dbKey) {
return switchQueue(dbKey).size();
}
- public int automaticProcess(yacySeedDB seedDB) throws IOException, InterruptedException {
+ public int automaticProcess(final yacySeedDB seedDB) throws IOException, InterruptedException {
// processes news in the incoming-db
// returns number of processes
yacyNewsRecord record;
int pc = 0;
synchronized (this.incomingNews) {
- Iterator<yacyNewsRecord> i = incomingNews.records(true);
+ final Iterator<yacyNewsRecord> i = incomingNews.records(true);
while (i.hasNext()) {
// check for interruption
if (Thread.currentThread().isInterrupted()) throw new InterruptedException("Shutdown in progress");
@@ -371,7 +371,7 @@ public class yacyNewsPool {
}
long day = 1000 * 60 * 60 * 24;
- private boolean automaticProcessP(yacySeedDB seedDB, yacyNewsRecord record) {
+ private boolean automaticProcessP(final yacySeedDB seedDB, final yacyNewsRecord record) {
if (record == null) return false;
if (record.category() == null) return true;
if ((System.currentTimeMillis() - record.created().getTime()) > (14 * day)) {
@@ -392,22 +392,22 @@ public class yacyNewsPool {
}
if ((record.category().equals(CATEGORY_CRAWL_START)) &&
((System.currentTimeMillis() - record.created().getTime()) > (2 * day))) {
- yacySeed seed = seedDB.get(record.originator());
+ final yacySeed seed = seedDB.get(record.originator());
if (seed == null) return false;
try {
return (Integer.parseInt(seed.get(yacySeed.ISPEED, "-")) < 10);
- } catch (NumberFormatException ee) {
+ } catch (final NumberFormatException ee) {
return true;
}
}
return false;
}
- public synchronized yacyNewsRecord getSpecific(int dbKey, String category, String key, String value) {
- yacyNewsQueue queue = switchQueue(dbKey);
+ public synchronized yacyNewsRecord getSpecific(final int dbKey, final String category, final String key, final String value) {
+ final yacyNewsQueue queue = switchQueue(dbKey);
yacyNewsRecord record;
String s;
- Iterator<yacyNewsRecord> i = queue.records(true);
+ final Iterator<yacyNewsRecord> i = queue.records(true);
while (i.hasNext()) {
record = i.next();
if ((record != null) && (record.category().equals(category))) {
@@ -418,10 +418,10 @@ public class yacyNewsPool {
return null;
}
- public synchronized yacyNewsRecord getByOriginator(int dbKey, String category, String originatorHash) {
- yacyNewsQueue queue = switchQueue(dbKey);
+ public synchronized yacyNewsRecord getByOriginator(final int dbKey, final String category, final String originatorHash) {
+ final yacyNewsQueue queue = switchQueue(dbKey);
yacyNewsRecord record;
- Iterator<yacyNewsRecord> i = queue.records(true);
+ final Iterator<yacyNewsRecord> i = queue.records(true);
while (i.hasNext()) {
record = i.next();
if ((record != null) &&
@@ -433,7 +433,7 @@ public class yacyNewsPool {
return null;
}
- public synchronized yacyNewsRecord getByID(int dbKey, String id) {
+ public synchronized yacyNewsRecord getByID(final int dbKey, final String id) {
switch (dbKey) {
case INCOMING_DB: return incomingNews.get(id);
case PROCESSED_DB: return processedNews.get(id);
@@ -443,7 +443,7 @@ public class yacyNewsPool {
return null;
}
- private yacyNewsQueue switchQueue(int dbKey) {
+ private yacyNewsQueue switchQueue(final int dbKey) {
switch (dbKey) {
case INCOMING_DB: return incomingNews;
case PROCESSED_DB: return processedNews;
@@ -453,7 +453,7 @@ public class yacyNewsPool {
return null;
}
- public void clear(int dbKey) {
+ public void clear(final int dbKey) {
// clear a table
switch (dbKey) {
case INCOMING_DB: incomingNews.clear(); break;
@@ -463,7 +463,7 @@ public class yacyNewsPool {
}
}
- public void moveOff(int dbKey, String id) throws IOException {
+ public void moveOff(final int dbKey, final String id) throws IOException {
// this is called if a queue element shall be moved to another queue or off the queue
// it depends on the dbKey how the record is handled
switch (dbKey) {
@@ -474,9 +474,9 @@ public class yacyNewsPool {
}
}
- private boolean moveOff(yacyNewsQueue fromqueue, yacyNewsQueue toqueue, String id) throws IOException {
+ private boolean moveOff(final yacyNewsQueue fromqueue, final yacyNewsQueue toqueue, final String id) throws IOException {
// called if a published news shall be removed
- yacyNewsRecord record = fromqueue.remove(id);
+ final yacyNewsRecord record = fromqueue.remove(id);
if (record == null) {
return false;
}
@@ -488,7 +488,7 @@ public class yacyNewsPool {
return true;
}
- public void moveOffAll(int dbKey) throws IOException {
+ public void moveOffAll(final int dbKey) throws IOException {
// this is called if a queue element shall be moved to another queue or off the queue
// it depends on the dbKey how the record is handled
switch (dbKey) {
@@ -499,9 +499,9 @@ public class yacyNewsPool {
}
}
- private int moveOffAll(yacyNewsQueue fromqueue, yacyNewsQueue toqueue) throws IOException {
+ private int moveOffAll(final yacyNewsQueue fromqueue, final yacyNewsQueue toqueue) throws IOException {
// move off all news from a specific queue to another queue
- Iterator<yacyNewsRecord> i = fromqueue.records(true);
+ final Iterator<yacyNewsRecord> i = fromqueue.records(true);
yacyNewsRecord record;
if (toqueue == null) return 0;
int c = 0;
diff --git a/source/de/anomic/yacy/yacyNewsQueue.java b/source/de/anomic/yacy/yacyNewsQueue.java
index 55b94be90..917b4ccc0 100644
--- a/source/de/anomic/yacy/yacyNewsQueue.java
+++ b/source/de/anomic/yacy/yacyNewsQueue.java
@@ -58,9 +58,9 @@ import de.anomic.server.serverDate;
public class yacyNewsQueue {
- private File path;
+ private final File path;
kelondroStack queueStack;
- private yacyNewsDB newsDB;
+ private final yacyNewsDB newsDB;
public static final kelondroRow rowdef = new kelondroRow(new kelondroColumn[]{
new kelondroColumn("newsid", kelondroColumn.celltype_string, kelondroColumn.encoder_bytes, yacyNewsRecord.idLength, "id = created + originator"),
@@ -69,14 +69,14 @@ public class yacyNewsQueue {
kelondroNaturalOrder.naturalOrder, 0
);
- public yacyNewsQueue(File path, yacyNewsDB newsDB) {
+ public yacyNewsQueue(final File path, final yacyNewsDB newsDB) {
this.path = path;
this.newsDB = newsDB;
this.queueStack = kelondroStack.open(path, rowdef);
}
private void resetDB() {
- try {close();} catch (Exception e) {}
+ try {close();} catch (final Exception e) {}
if (path.exists()) path.delete();
queueStack = kelondroStack.open(path, rowdef);
}
@@ -98,7 +98,7 @@ public class yacyNewsQueue {
return queueStack.size();
}
- public synchronized void push(yacyNewsRecord entry) throws IOException {
+ public synchronized void push(final yacyNewsRecord entry) throws IOException {
queueStack.push(r2b(entry, true));
}
@@ -114,7 +114,7 @@ public class yacyNewsQueue {
public synchronized yacyNewsRecord topInc() throws IOException {
if (queueStack.size() == 0) return null;
- yacyNewsRecord entry = pop();
+ final yacyNewsRecord entry = pop();
if (entry != null) {
entry.incDistribution();
push(entry);
@@ -122,9 +122,9 @@ public class yacyNewsQueue {
return entry;
}
- public synchronized yacyNewsRecord get(String id) {
+ public synchronized yacyNewsRecord get(final String id) {
yacyNewsRecord record;
- Iterator<yacyNewsRecord> i = records(true);
+ final Iterator<yacyNewsRecord> i = records(true);
while (i.hasNext()) {
record = i.next();
if ((record != null) && (record.id().equals(id))) return record;
@@ -132,9 +132,9 @@ public class yacyNewsQueue {
return null;
}
- public synchronized yacyNewsRecord remove(String id) {
+ public synchronized yacyNewsRecord remove(final String id) {
yacyNewsRecord record;
- Iterator<yacyNewsRecord> i = records(true);
+ final Iterator<yacyNewsRecord> i = records(true);
while (i.hasNext()) {
record = i.next();
if ((record != null) && (record.id().equals(id))) {
@@ -145,28 +145,28 @@ public class yacyNewsQueue {
return null;
}
- yacyNewsRecord b2r(kelondroRow.Entry b) throws IOException {
+ yacyNewsRecord b2r(final kelondroRow.Entry b) throws IOException {
if (b == null) return null;
- String id = b.getColString(0, null);
+ final String id = b.getColString(0, null);
//Date touched = yacyCore.parseUniversalDate(new String(b[1]));
return newsDB.get(id);
}
- private kelondroRow.Entry r2b(yacyNewsRecord r, boolean updateDB) throws IOException {
+ private kelondroRow.Entry r2b(final yacyNewsRecord r, final boolean updateDB) throws IOException {
if (r == null) return null;
if (updateDB) {
newsDB.put(r);
} else {
- yacyNewsRecord r1 = newsDB.get(r.id());
+ final yacyNewsRecord r1 = newsDB.get(r.id());
if (r1 == null) newsDB.put(r);
}
- kelondroRow.Entry b = queueStack.row().newEntry(new byte[][]{
+ final kelondroRow.Entry b = queueStack.row().newEntry(new byte[][]{
r.id().getBytes(),
serverDate.formatShortSecond(new Date()).getBytes()});
return b;
}
- public Iterator<yacyNewsRecord> records(boolean up) {
+ public Iterator<yacyNewsRecord> records(final boolean up) {
// iterates yacyNewsRecord-type objects
if (queueStack == null) return new HashSet<yacyNewsRecord>().iterator();
return new newsIterator(up);
@@ -177,7 +177,7 @@ public class yacyNewsQueue {
Iterator<kelondroRow.Entry> stackNodeIterator;
- public newsIterator(boolean up) {
+ public newsIterator(final boolean up) {
stackNodeIterator = queueStack.stackIterator(up);
}
@@ -186,10 +186,10 @@ public class yacyNewsQueue {
}
public yacyNewsRecord next() {
- kelondroRow.Entry row = stackNodeIterator.next();
+ final kelondroRow.Entry row = stackNodeIterator.next();
try {
return b2r(row);
- } catch (IOException e) {
+ } catch (final IOException e) {
return null;
}
}
diff --git a/source/de/anomic/yacy/yacyNewsRecord.java b/source/de/anomic/yacy/yacyNewsRecord.java
index ba4d23e3a..736e249db 100644
--- a/source/de/anomic/yacy/yacyNewsRecord.java
+++ b/source/de/anomic/yacy/yacyNewsRecord.java
@@ -62,12 +62,12 @@ public class yacyNewsRecord {
public static final int categoryStringLength = 8;
public static final int idLength = serverDate.PATTERN_SHORT_SECOND.length() + yacySeedDB.commonHashLength;
- private String originator; // hash of originating peer
- private Date created; // Date when news was created by originator
- private Date received; // Date when news was received here at this peer
- private String category; // keyword that adresses possible actions
+ private final String originator; // hash of originating peer
+ private final Date created; // Date when news was created by originator
+ private final Date received; // Date when news was received here at this peer
+ private final String category; // keyword that adresses possible actions
private int distributed; // counter that counts number of distributions of this news record
- private Map<String, String> attributes; // elemets of the news for a special category
+ private final Map<String, String> attributes; // elemets of the news for a special category
public static final int attributesMaxLength = maxNewsRecordLength
- idLength
@@ -84,50 +84,50 @@ public class yacyNewsRecord {
kelondroNaturalOrder.naturalOrder, 0
);
- public static yacyNewsRecord newRecord(String newsString) {
+ public static yacyNewsRecord newRecord(final String newsString) {
try {
return new yacyNewsRecord(newsString);
- } catch (IllegalArgumentException e) {
+ } catch (final IllegalArgumentException e) {
yacyCore.log.logWarning("rejected bad yacy news record: " + e.getMessage());
return null;
}
}
- public static yacyNewsRecord newRecord(yacySeed mySeed, String category, Properties attributes) {
+ public static yacyNewsRecord newRecord(final yacySeed mySeed, final String category, final Properties attributes) {
try {
- HashMap<String, String> m = new HashMap<String, String>();
- Iterator<Entry<Object, Object>> e = attributes.entrySet().iterator();
+ final HashMap<String, String> m = new HashMap<String, String>();
+ final Iterator<Entry<Object, Object>> e = attributes.entrySet().iterator();
Map.Entry<Object, Object> entry;
while (e.hasNext()) {
entry = e.next();
m.put((String) entry.getKey(), (String) entry.getValue());
}
return new yacyNewsRecord(mySeed, category, m);
- } catch (IllegalArgumentException e) {
+ } catch (final IllegalArgumentException e) {
yacyCore.log.logWarning("rejected bad yacy news record: " + e.getMessage());
return null;
}
}
- public static yacyNewsRecord newRecord(yacySeed mySeed, String category, Map<String, String> attributes) {
+ public static yacyNewsRecord newRecord(final yacySeed mySeed, final String category, final Map<String, String> attributes) {
try {
return new yacyNewsRecord(mySeed, category, attributes);
- } catch (IllegalArgumentException e) {
+ } catch (final IllegalArgumentException e) {
yacyCore.log.logWarning("rejected bad yacy news record: " + e.getMessage());
return null;
}
}
- public static yacyNewsRecord newRecord(String id, String category, Date received, int distributed, Map<String, String> attributes) {
+ public static yacyNewsRecord newRecord(final String id, final String category, final Date received, final int distributed, final Map<String, String> attributes) {
try {
return new yacyNewsRecord(id, category, received, distributed, attributes);
- } catch (IllegalArgumentException e) {
+ } catch (final IllegalArgumentException e) {
yacyCore.log.logWarning("rejected bad yacy news record: " + e.getMessage());
return null;
}
}
- public yacyNewsRecord(String newsString) {
+ public yacyNewsRecord(final String newsString) {
this.attributes = serverCodings.string2map(newsString, ",");
if (attributes.toString().length() > attributesMaxLength) throw new IllegalArgumentException("attributes length (" + attributes.toString().length() + ") exceeds maximum (" + attributesMaxLength + ")");
this.category = (attributes.containsKey("cat")) ? (String) attributes.get("cat") : "";
@@ -139,7 +139,7 @@ public class yacyNewsRecord {
removeStandards();
}
- public yacyNewsRecord(yacySeed mySeed, String category, Map<String, String> attributes) {
+ public yacyNewsRecord(final yacySeed mySeed, final String category, final Map<String, String> attributes) {
if (category.length() > categoryStringLength) throw new IllegalArgumentException("category length (" + category.length() + ") exceeds maximum (" + categoryStringLength + ")");
if (attributes.toString().length() > attributesMaxLength) throw new IllegalArgumentException("attributes length (" + attributes.toString().length() + ") exceeds maximum (" + attributesMaxLength + ")");
this.attributes = attributes;
@@ -151,7 +151,7 @@ public class yacyNewsRecord {
removeStandards();
}
- protected yacyNewsRecord(String id, String category, Date received, int distributed, Map<String, String> attributes) {
+ protected yacyNewsRecord(final String id, final String category, final Date received, final int distributed, final Map<String, String> attributes) {
if (category.length() > categoryStringLength) throw new IllegalArgumentException("category length (" + category.length() + ") exceeds maximum (" + categoryStringLength + ")");
if (attributes.toString().length() > attributesMaxLength) throw new IllegalArgumentException("attributes length (" + attributes.toString().length() + ") exceeds maximum (" + attributesMaxLength + ")");
this.attributes = attributes;
@@ -179,7 +179,7 @@ public class yacyNewsRecord {
if (this.created != null) attributes.put("cre", serverDate.formatShortSecond(this.created));
if (this.received != null) attributes.put("rec", serverDate.formatShortSecond(this.received));
attributes.put("dis", Integer.toString(this.distributed));
- String theString = attributes.toString();
+ final String theString = attributes.toString();
removeStandards();
return theString;
}
@@ -216,13 +216,13 @@ public class yacyNewsRecord {
return attributes;
}
- public String attribute(String key, String dflt) {
- String s = attributes.get(key);
+ public String attribute(final String key, final String dflt) {
+ final String s = attributes.get(key);
if ((s == null) || (s.length() == 0)) return dflt;
return s;
}
- public static void main(String[] args) {
+ public static void main(final String[] args) {
System.out.println((newRecord(args[0])).toString());
}
}
\ No newline at end of file
diff --git a/source/de/anomic/yacy/yacyPeerActions.java b/source/de/anomic/yacy/yacyPeerActions.java
index 36a902463..e4d4a91ae 100644
--- a/source/de/anomic/yacy/yacyPeerActions.java
+++ b/source/de/anomic/yacy/yacyPeerActions.java
@@ -35,13 +35,13 @@ import de.anomic.xml.RSSMessage;
public class yacyPeerActions {
- private yacySeedDB seedDB;
+ private final yacySeedDB seedDB;
private HashMap<String, String> userAgents;
public long disconnects;
public yacyDHTAction dhtAction;
- private yacyNewsPool newsPool;
+ private final yacyNewsPool newsPool;
- public yacyPeerActions(yacySeedDB seedDB, yacyNewsPool newsPool) {
+ public yacyPeerActions(final yacySeedDB seedDB, final yacyNewsPool newsPool) {
this.seedDB = seedDB;
this.newsPool = newsPool;
this.userAgents = new HashMap<String, String>();
@@ -57,7 +57,7 @@ public class yacyPeerActions {
dhtAction.close();
}
- public synchronized boolean connectPeer(yacySeed seed, boolean direct) {
+ public synchronized boolean connectPeer(final yacySeed seed, final boolean direct) {
// store a remote peer's seed
// returns true if the peer is new and previously unknown
if (seed == null) {
@@ -167,7 +167,7 @@ public class yacyPeerActions {
/*if (connectedSeed.getName() != seed.getName()) {
// TODO: update seed name lookup cache
}*/
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
yacyCore.log.logFine("connect: rejecting wrong peer '" + seed.getName() + "' from " + seed.getPublicAddress() + ". Cause: " + e.getMessage());
return false;
}
@@ -190,9 +190,9 @@ public class yacyPeerActions {
}
}
- public boolean peerArrival(yacySeed peer, boolean direct) {
+ public boolean peerArrival(final yacySeed peer, final boolean direct) {
if (peer == null) return false;
- boolean res = connectPeer(peer, direct);
+ final boolean res = connectPeer(peer, direct);
if (res) {
// perform all actions if peer is effective new
dhtAction.processPeerArrival(peer, direct);
@@ -202,7 +202,7 @@ public class yacyPeerActions {
return res;
}
- public void peerDeparture(yacySeed peer, String cause) {
+ public void peerDeparture(final yacySeed peer, final String cause) {
if (peer == null) return;
// we do this if we did not get contact with the other peer
yacyCore.log.logFine("connect: no contact to a " + peer.get(yacySeed.PEERTYPE, yacySeed.PEERTYPE_VIRGIN) + " peer '" + peer.getName() + "' at " + peer.getPublicAddress() + ". Cause: " + cause);
@@ -216,7 +216,7 @@ public class yacyPeerActions {
RSSFeed.channels(RSSFeed.PEERNEWS).addMessage(new RSSMessage(peer.getName() + " left the network", "", ""));
}
- public void peerPing(yacySeed peer) {
+ public void peerPing(final yacySeed peer) {
if (peer == null) return;
// this is called only if the peer has junior status
seedDB.addPotential(peer);
@@ -225,35 +225,35 @@ public class yacyPeerActions {
RSSFeed.channels(RSSFeed.PEERNEWS).addMessage(new RSSMessage(peer.getName() + " sent me a ping", "", ""));
}
- private void processPeerArrival(yacySeed peer, boolean direct) {
- String recordString = peer.get("news", null);
+ private void processPeerArrival(final yacySeed peer, final boolean direct) {
+ final String recordString = peer.get("news", null);
//System.out.println("### triggered news arrival from peer " + peer.getName() + ", news " + ((recordString == null) ? "empty" : "attached"));
if ((recordString == null) || (recordString.length() == 0)) return;
- String decodedString = de.anomic.tools.crypt.simpleDecode(recordString, "");
- yacyNewsRecord record = yacyNewsRecord.newRecord(decodedString);
+ final String decodedString = de.anomic.tools.crypt.simpleDecode(recordString, "");
+ final yacyNewsRecord record = yacyNewsRecord.newRecord(decodedString);
if (record != null) {
//System.out.println("### news arrival from peer " + peer.getName() + ", decoded=" + decodedString + ", record=" + recordString + ", news=" + record.toString());
- String cre1 = serverCodings.string2map(decodedString, ",").get("cre");
- String cre2 = serverCodings.string2map(record.toString(), ",").get("cre");
+ final String cre1 = serverCodings.string2map(decodedString, ",").get("cre");
+ final String cre2 = serverCodings.string2map(record.toString(), ",").get("cre");
if ((cre1 == null) || (cre2 == null) || (!(cre1.equals(cre2)))) {
System.out.println("### ERROR - cre are not equal: cre1=" + cre1 + ", cre2=" + cre2);
return;
}
try {
synchronized (this.newsPool) {this.newsPool.enqueueIncomingNews(record);}
- } catch (IOException e) {
+ } catch (final IOException e) {
serverLog.logSevere("YACY", "processPeerArrival", e);
}
}
}
- public void setUserAgent(String IP, String userAgent) {
+ public void setUserAgent(final String IP, final String userAgent) {
if (userAgents == null) return; // case can happen during shutdown
userAgents.put(IP, userAgent);
}
- public String getUserAgent(String IP) {
- String userAgent = userAgents.get(IP);
+ public String getUserAgent(final String IP) {
+ final String userAgent = userAgents.get(IP);
return (userAgent == null) ? "" : userAgent;
}
}
diff --git a/source/de/anomic/yacy/yacySearch.java b/source/de/anomic/yacy/yacySearch.java
index ebe58d6a2..10b0ceee6 100644
--- a/source/de/anomic/yacy/yacySearch.java
+++ b/source/de/anomic/yacy/yacySearch.java
@@ -71,20 +71,20 @@ public class yacySearch extends Thread {
final private indexReferenceBlacklist blacklist;
final private yacySeed targetPeer;
private String[] urls;
- private int count, maxDistance;
+ private final int count, maxDistance;
final private plasmaSearchRankingProfile rankingProfile;
final private String prefer, filter;
final private kelondroBitfield constraint;
ResultURLs crawlResults;
- public yacySearch(String wordhashes, String excludehashes, String urlhashes, String prefer, String filter, int count, int maxDistance,
- boolean global, int partitions, yacySeed targetPeer, plasmaWordIndex wordIndex,
- ResultURLs crawlResults,
- plasmaSearchRankingProcess containerCache,
- Map<String, TreeMap<String, String>> abstractCache,
- indexReferenceBlacklist blacklist,
- plasmaSearchRankingProfile rankingProfile,
- kelondroBitfield constraint) {
+ public yacySearch(final String wordhashes, final String excludehashes, final String urlhashes, final String prefer, final String filter, final int count, final int maxDistance,
+ final boolean global, final int partitions, final yacySeed targetPeer, final plasmaWordIndex wordIndex,
+ final ResultURLs crawlResults,
+ final plasmaSearchRankingProcess containerCache,
+ final Map<String, TreeMap<String, String>> abstractCache,
+ final indexReferenceBlacklist blacklist,
+ final plasmaSearchRankingProfile rankingProfile,
+ final kelondroBitfield constraint) {
super("yacySearch_" + targetPeer.getName());
//System.out.println("DEBUG - yacySearch thread " + this.getName() + " initialized " + ((urlhashes.length() == 0) ? "(primary)" : "(secondary)"));
this.wordhashes = wordhashes;
@@ -115,7 +115,7 @@ public class yacySearch extends Thread {
blacklist, rankingProfile, constraint);
if (urls != null) {
// urls is an array of url hashes. this is only used for log output
- StringBuffer urllist = new StringBuffer(this.urls.length * 13);
+ final StringBuffer urllist = new StringBuffer(this.urls.length * 13);
for (int i = 0; i < this.urls.length; i++) urllist.append(this.urls[i]).append(' ');
yacyCore.log.logInfo("REMOTE SEARCH - remote peer " + targetPeer.hash + ":" + targetPeer.getName() + " contributed " + urls.length + " links for word hash " + wordhashes + ": " + new String(urllist));
wordIndex.seedDB.mySeed().incRI(urls.length);
@@ -125,7 +125,7 @@ public class yacySearch extends Thread {
}
}
- public static String set2string(Set<String> hashes) {
+ public static String set2string(final Set<String> hashes) {
String wh = "";
final Iterator<String> iter = hashes.iterator();
while (iter.hasNext()) { wh = wh + iter.next(); }
@@ -144,9 +144,9 @@ public class yacySearch extends Thread {
return targetPeer;
}
- private static yacySeed[] selectClusterPeers(yacySeedDB seedDB, TreeMap<String, String> peerhashes) {
- Iterator<Map.Entry<String, String>> i = peerhashes.entrySet().iterator();
- ArrayList<yacySeed> l = new ArrayList<yacySeed>();
+ private static yacySeed[] selectClusterPeers(final yacySeedDB seedDB, final TreeMap<String, String> peerhashes) {
+ final Iterator<Map.Entry<String, String>> i = peerhashes.entrySet().iterator();
+ final ArrayList<yacySeed> l = new ArrayList<yacySeed>();
Map.Entry<String, String> entry;
yacySeed s;
while (i.hasNext()) {
@@ -157,7 +157,7 @@ public class yacySearch extends Thread {
l.add(s);
}
}
- yacySeed[] result = new yacySeed[l.size()];
+ final yacySeed[] result = new yacySeed[l.size()];
for (int j = 0; j < l.size(); j++) {
result[j] = l.get(j);
}
@@ -165,7 +165,7 @@ public class yacySearch extends Thread {
//return (yacySeed[]) l.toArray();
}
- private static yacySeed[] selectSearchTargets(yacySeedDB seedDB, yacyPeerActions peerActions, Set<String> wordhashes, int seedcount) {
+ private static yacySeed[] selectSearchTargets(final yacySeedDB seedDB, final yacyPeerActions peerActions, final Set<String> wordhashes, int seedcount) {
// find out a specific number of seeds, that would be relevant for the given word hash(es)
// the result is ordered by relevance: [0] is most relevant
// the seedcount is the maximum number of wanted results
@@ -252,7 +252,7 @@ public class yacySearch extends Thread {
// evaluate the ranking score and select seeds
seedcount = Math.min(ranking.size(), seedcount);
- yacySeed[] result = new yacySeed[seedcount + robinsonSeeds.size() + matchingSeeds.size()];
+ final yacySeed[] result = new yacySeed[seedcount + robinsonSeeds.size() + matchingSeeds.size()];
c = 0;
iter = ranking.scores(false); // higher are better
while (iter.hasNext() && c < seedcount) {
@@ -261,11 +261,11 @@ public class yacySearch extends Thread {
serverLog.logInfo("PLASMA", "selectPeers/_dht_: " + seed.hash + ":" + seed.getName() + " is choice " + c);
result[c++] = seed;
}
- for (yacySeed s: robinsonSeeds.values()) {
+ for (final yacySeed s: robinsonSeeds.values()) {
serverLog.logInfo("PLASMA", "selectPeers/_robinson_: " + s.hash + ":" + s.getName() + " is choice " + c);
result[c++] = s;
}
- for (yacySeed s: matchingSeeds.values()) {
+ for (final yacySeed s: matchingSeeds.values()) {
serverLog.logInfo("PLASMA", "selectPeers/_match_: " + s.hash + ":" + s.getName() + " is choice " + c);
result[c++] = s;
}
@@ -275,17 +275,17 @@ public class yacySearch extends Thread {
}
public static yacySearch[] primaryRemoteSearches(
- String wordhashes, String excludehashes, String urlhashes,
- String prefer, String filter, int count, int maxDist,
- plasmaWordIndex wordIndex,
- ResultURLs crawlResults,
- plasmaSearchRankingProcess containerCache,
- Map<String, TreeMap<String, String>> abstractCache,
+ final String wordhashes, final String excludehashes, final String urlhashes,
+ final String prefer, final String filter, final int count, final int maxDist,
+ final plasmaWordIndex wordIndex,
+ final ResultURLs crawlResults,
+ final plasmaSearchRankingProcess containerCache,
+ final Map<String, TreeMap<String, String>> abstractCache,
int targets,
- indexReferenceBlacklist blacklist,
- plasmaSearchRankingProfile rankingProfile,
- kelondroBitfield constraint,
- TreeMap<String, String> clusterselection) {
+ final indexReferenceBlacklist blacklist,
+ final plasmaSearchRankingProfile rankingProfile,
+ final kelondroBitfield constraint,
+ final TreeMap<String, String> clusterselection) {
// check own peer status
//if (wordIndex.seedDB.mySeed() == null || wordIndex.seedDB.mySeed().getPublicAddress() == null) { return null; }
@@ -294,7 +294,7 @@ public class yacySearch extends Thread {
if (targetPeers == null) return new yacySearch[0];
targets = targetPeers.length;
if (targets == 0) return new yacySearch[0];
- yacySearch[] searchThreads = new yacySearch[targets];
+ final yacySearch[] searchThreads = new yacySearch[targets];
for (int i = 0; i < targets; i++) {
searchThreads[i] = new yacySearch(wordhashes, excludehashes, urlhashes, prefer, filter, count, maxDist, true, targets, targetPeers[i],
wordIndex, crawlResults, containerCache, abstractCache, blacklist, rankingProfile, constraint);
@@ -304,13 +304,13 @@ public class yacySearch extends Thread {
return searchThreads;
}
- public static yacySearch secondaryRemoteSearch(String wordhashes, String excludehashes, String urlhashes,
- plasmaWordIndex wordIndex,
- ResultURLs crawlResults,
- plasmaSearchRankingProcess containerCache,
- String targethash, indexReferenceBlacklist blacklist,
- plasmaSearchRankingProfile rankingProfile,
- kelondroBitfield constraint, TreeMap<String, String> clusterselection) {
+ public static yacySearch secondaryRemoteSearch(final String wordhashes, final String excludehashes, final String urlhashes,
+ final plasmaWordIndex wordIndex,
+ final ResultURLs crawlResults,
+ final plasmaSearchRankingProcess containerCache,
+ final String targethash, final indexReferenceBlacklist blacklist,
+ final plasmaSearchRankingProfile rankingProfile,
+ final kelondroBitfield constraint, final TreeMap<String, String> clusterselection) {
// check own peer status
if (wordIndex.seedDB.mySeed() == null || wordIndex.seedDB.mySeed().getPublicAddress() == null) { return null; }
@@ -318,13 +318,13 @@ public class yacySearch extends Thread {
final yacySeed targetPeer = wordIndex.seedDB.getConnected(targethash);
if (targetPeer == null) return null;
if (clusterselection != null) targetPeer.setAlternativeAddress(clusterselection.get(targetPeer.hash));
- yacySearch searchThread = new yacySearch(wordhashes, excludehashes, urlhashes, "", "", 0, 9999, true, 0, targetPeer,
+ final yacySearch searchThread = new yacySearch(wordhashes, excludehashes, urlhashes, "", "", 0, 9999, true, 0, targetPeer,
wordIndex, crawlResults, containerCache, new TreeMap<String, TreeMap<String, String>>(), blacklist, rankingProfile, constraint);
searchThread.start();
return searchThread;
}
- public static int remainingWaiting(yacySearch[] searchThreads) {
+ public static int remainingWaiting(final yacySearch[] searchThreads) {
if (searchThreads == null) return 0;
int alive = 0;
for (int i = 0; i < searchThreads.length; i++) {
@@ -334,7 +334,7 @@ public class yacySearch extends Thread {
return alive;
}
- public static int collectedLinks(yacySearch[] searchThreads) {
+ public static int collectedLinks(final yacySearch[] searchThreads) {
int links = 0;
for (int i = 0; i < searchThreads.length; i++) {
if (!(searchThreads[i].isAlive())) links += searchThreads[i].urls.length;
@@ -342,7 +342,7 @@ public class yacySearch extends Thread {
return links;
}
- public static void interruptAlive(yacySearch[] searchThreads) {
+ public static void interruptAlive(final yacySearch[] searchThreads) {
for (int i = 0; i < searchThreads.length; i++) {
if (searchThreads[i].isAlive()) searchThreads[i].interrupt();
}
diff --git a/source/de/anomic/yacy/yacySeed.java b/source/de/anomic/yacy/yacySeed.java
index c42b0bbc2..6a4e71529 100644
--- a/source/de/anomic/yacy/yacySeed.java
+++ b/source/de/anomic/yacy/yacySeed.java
@@ -58,6 +58,7 @@ import de.anomic.index.indexWord;
import de.anomic.kelondro.kelondroBase64Order;
import de.anomic.net.natLib;
import de.anomic.server.serverCodings;
+import de.anomic.server.serverCore;
import de.anomic.server.serverDate;
import de.anomic.server.serverDomains;
import de.anomic.server.serverSystem;
@@ -166,7 +167,7 @@ public class yacySeed {
public int selectscore = -1; // only for debugging
public String alternativeIP = null;
- public yacySeed(String theHash, HashMap<String, String> theDna) {
+ public yacySeed(final String theHash, final HashMap<String, String> theDna) {
// create a seed with a pre-defined hash map
this.hash = theHash;
this.dna = theDna;
@@ -176,7 +177,7 @@ public class yacySeed {
this.dna.put(yacySeed.NAME, checkPeerName(get(yacySeed.NAME, "&empty;")));
}
- public yacySeed(String theHash) {
+ public yacySeed(final String theHash) {
this.dna = new HashMap<String, String>();
// settings that can only be computed by originating peer:
@@ -251,7 +252,7 @@ public class yacySeed {
* @param name
* @return a checked name without "<" and ">"
*/
- private static String checkPeerName(String name) {
+ private static String checkPeerName(final String name) {
name.replaceAll("<", "_");
name.replaceAll(">", "_");
return name;
@@ -263,7 +264,7 @@ public class yacySeed {
* @param name the peer name to check for default peer name compliance
* @return whether the given peer name may be a default generated peer name
*/
- public static boolean isDefaultPeerName(String name) {
+ public static boolean isDefaultPeerName(final String name) {
return (name != null &&
name.length() > 10 &&
name.charAt(0) <= '9' &&
@@ -275,9 +276,9 @@ public class yacySeed {
* used when doing routing within a cluster; this can assign a ip and a port
* that is used instead the address stored in the seed DNA
*/
- public void setAlternativeAddress(String ipport) {
+ public void setAlternativeAddress(final String ipport) {
if (ipport == null) return;
- int p = ipport.indexOf(':');
+ final int p = ipport.indexOf(':');
if (p < 0) this.alternativeIP = ipport; else this.alternativeIP = ipport.substring(0, p);
}
@@ -317,18 +318,18 @@ public class yacySeed {
* @param key the key for the value to fetch
* @param dflt the default value
*/
- public final String get(String key, String dflt) {
+ public final String get(final String key, final String dflt) {
final Object o = this.dna.get(key);
if (o == null) { return dflt; }
return (String) o;
}
- public final long getLong(String key, long dflt) {
+ public final long getLong(final String key, final long dflt) {
final Object o = this.dna.get(key);
if (o == null) { return dflt; }
if (o instanceof String) try {
return Long.parseLong((String) o);
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
return dflt;
} else if (o instanceof Long) {
return ((Long) o).longValue();
@@ -337,14 +338,14 @@ public class yacySeed {
} else return dflt;
}
- public final void setIP(String ip) { dna.put(yacySeed.IP, ip); }
- public final void setPort(String port) { dna.put(yacySeed.PORT, port); }
- public final void setType(String type) { dna.put(yacySeed.PEERTYPE, type); }
+ public final void setIP(final String ip) { dna.put(yacySeed.IP, ip); }
+ public final void setPort(final String port) { dna.put(yacySeed.PORT, port); }
+ public final void setType(final String type) { dna.put(yacySeed.PEERTYPE, type); }
public final void setJunior() { dna.put(yacySeed.PEERTYPE, yacySeed.PEERTYPE_JUNIOR); }
public final void setSenior() { dna.put(yacySeed.PEERTYPE, yacySeed.PEERTYPE_SENIOR); }
public final void setPrincipal() { dna.put(yacySeed.PEERTYPE, yacySeed.PEERTYPE_PRINCIPAL); }
- public final void put(String key, String value) {
+ public final void put(final String key, final String value) {
synchronized (this.dna) {
this.dna.put(key, value);
}
@@ -363,25 +364,25 @@ public class yacySeed {
return b64Hash2hexHash(this.hash);
}
- public final void incSI(int count) {
+ public final void incSI(final int count) {
String v = this.dna.get(yacySeed.INDEX_OUT);
if (v == null) { v = yacySeed.ZERO; }
dna.put(yacySeed.INDEX_OUT, Integer.toString(Integer.parseInt(v) + count));
}
- public final void incRI(int count) {
+ public final void incRI(final int count) {
String v = this.dna.get(yacySeed.INDEX_IN);
if (v == null) { v = yacySeed.ZERO; }
dna.put(yacySeed.INDEX_IN, Integer.toString(Integer.parseInt(v) + count));
}
- public final void incSU(int count) {
+ public final void incSU(final int count) {
String v = this.dna.get(yacySeed.URL_OUT);
if (v == null) { v = yacySeed.ZERO; }
dna.put(yacySeed.URL_OUT, Integer.toString(Integer.parseInt(v) + count));
}
- public final void incRU(int count) {
+ public final void incRU(final int count) {
String v = this.dna.get(yacySeed.URL_IN);
if (v == null) { v = yacySeed.ZERO; }
dna.put(yacySeed.URL_IN, Integer.toString(Integer.parseInt(v) + count));
@@ -397,7 +398,7 @@ public class yacySeed {
* @param b64Hash a base64 hash
* @return the octal representation of the given base64 hash
*/
- public static String b64Hash2octalHash(String b64Hash) {
+ public static String b64Hash2octalHash(final String b64Hash) {
return serverCodings.encodeOctal(kelondroBase64Order.enhancedCoder.decode(b64Hash, "de.anomic.yacy.yacySeed.b64Hash2octalHash()"));
}
@@ -406,7 +407,7 @@ public class yacySeed {
* @param b64Hash a base64 hash
* @return the hexadecimal representation of the given base64 hash
*/
- public static String b64Hash2hexHash(String b64Hash) {
+ public static String b64Hash2hexHash(final String b64Hash) {
// the hash string represents 12 * 6 bit = 72 bits. This is too much for a long integer.
return serverCodings.encodeHex(kelondroBase64Order.enhancedCoder.decode(b64Hash, "de.anomic.yacy.yacySeed.b64Hash2hexHash()"));
}
@@ -415,7 +416,7 @@ public class yacySeed {
* @param hexHash a hexadecimal hash
* @return the base64 representation of the given hex hash
*/
- public static String hexHash2b64Hash(String hexHash) {
+ public static String hexHash2b64Hash(final String hexHash) {
return kelondroBase64Order.enhancedCoder.encode(serverCodings.decodeHex(hexHash));
}
@@ -424,7 +425,7 @@ public class yacySeed {
* @param b64Hash a base64 hash
* @return returns a base256 - a byte - representation of the given base64 hash
*/
- public static byte[] b64Hash2b256Hash(String b64Hash) {
+ public static byte[] b64Hash2b256Hash(final String b64Hash) {
assert b64Hash.length() == 12;
return kelondroBase64Order.enhancedCoder.decode(b64Hash, "de.anomic.yacy.yacySeed.b64Hash2b256Hash()");
}
@@ -433,7 +434,7 @@ public class yacySeed {
* @param b256Hash a base256 hash - normal byte number system
* @return the base64 representation of the given base256 hash
*/
- public static String b256Hash2b64Hash(byte[] b256Hash) {
+ public static String b256Hash2b64Hash(final byte[] b256Hash) {
assert b256Hash.length == 9;
return kelondroBase64Order.enhancedCoder.encode(b256Hash);
}
@@ -446,7 +447,7 @@ public class yacySeed {
public final float getVersion() {
try {
return Float.parseFloat(get(yacySeed.VERSION, yacySeed.ZERO));
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
return 0;
}
}
@@ -456,7 +457,7 @@ public class yacySeed {
* either the IP or the port could be retrieved from this yacySeed object
*/
public final String getPublicAddress() {
- String ip = this.dna.get(yacySeed.IP);
+ final String ip = this.dna.get(yacySeed.IP);
if (ip == null) { return null; }
if (ip.length() < 8) { return null; } // 10.0.0.0
// if (ip.equals(yacyCore.seedDB.mySeed.dna.get(yacySeed.IP))) ip = "127.0.0.1";
@@ -509,7 +510,7 @@ public class yacySeed {
if (utc == null) { utc = "+0130"; }
try {
return serverDate.UTCDiff(utc);
- } catch (IllegalArgumentException e) {
+ } catch (final IllegalArgumentException e) {
return 0;
}
}
@@ -535,9 +536,9 @@ public class yacySeed {
// of the local UTC offset is wrong. We correct this here by adding the local UTC
// offset again.
return t + serverDate.UTCDiff();
- } catch (java.text.ParseException e) {
+ } catch (final java.text.ParseException e) {
return System.currentTimeMillis();
- } catch (java.lang.NumberFormatException e) {
+ } catch (final java.lang.NumberFormatException e) {
return System.currentTimeMillis();
}
}
@@ -556,14 +557,14 @@ public class yacySeed {
try {
final long t = serverDate.parseShortSecond(get(yacySeed.BDATE, "20040101000000")).getTime();
return (int) ((System.currentTimeMillis() - (t - getUTCDiff() + serverDate.UTCDiff())) / 1000 / 60 / 60 / 24);
- } catch (java.text.ParseException e) {
+ } catch (final java.text.ParseException e) {
return -1;
- } catch (java.lang.NumberFormatException e) {
+ } catch (final java.lang.NumberFormatException e) {
return -1;
}
}
- public void setPeerTags(Set<String> keys) {
+ public void setPeerTags(final Set<String> keys) {
dna.put(PEERTAGS, serverCodings.set2string(keys, "|", false));
}
@@ -571,11 +572,11 @@ public class yacySeed {
return serverCodings.string2set(get(PEERTAGS, ""), "|");
}
- public boolean matchPeerTags(Set<String> searchHashes) {
- String peertags = get(PEERTAGS, "");
+ public boolean matchPeerTags(final Set<String> searchHashes) {
+ final String peertags = get(PEERTAGS, "");
if (peertags.equals("*")) return true;
- Set<String> tags = serverCodings.string2set(peertags, "|");
- Iterator<String> i = tags.iterator();
+ final Set<String> tags = serverCodings.string2set(peertags, "|");
+ final Iterator<String> i = tags.iterator();
while (i.hasNext()) {
if (searchHashes.contains(indexWord.word2hash(i.next()))) return true;
}
@@ -585,7 +586,7 @@ public class yacySeed {
public int getPPM() {
try {
return Integer.parseInt(get(yacySeed.ISPEED, yacySeed.ZERO));
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
return 0;
}
}
@@ -593,7 +594,7 @@ public class yacySeed {
public double getQPM() {
try {
return Double.parseDouble(get(yacySeed.RSPEED, yacySeed.ZERO));
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
return 0d;
}
}
@@ -601,17 +602,17 @@ public class yacySeed {
public final long getLinkCount() {
try {
return getLong(yacySeed.LCOUNT, 0);
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
return 0;
}
}
- private boolean getFlag(int flag) {
+ private boolean getFlag(final int flag) {
final String flags = get(yacySeed.FLAGS, yacySeed.FLAGSZERO);
return (new bitfield(flags.getBytes())).get(flag);
}
- private void setFlag(int flag, boolean value) {
+ private void setFlag(final int flag, final boolean value) {
String flags = get(yacySeed.FLAGS, yacySeed.FLAGSZERO);
if (flags.length() != 4) { flags = yacySeed.FLAGSZERO; }
final bitfield f = new bitfield(flags.getBytes());
@@ -639,7 +640,7 @@ public class yacySeed {
public final void setUnusedFlags() {
for (int i = 4; i < 24; i++) { setFlag(i, true); }
}
- public final boolean isType(String type) {
+ public final boolean isType(final String type) {
return get(yacySeed.PEERTYPE, "").equals(type);
}
public final boolean isVirgin() {
@@ -675,12 +676,12 @@ public class yacySeed {
return dhtPosition(this.hash);
}
- public static double dhtPosition(String ahash) {
+ public static double dhtPosition(final String ahash) {
// normalized to 1.0
return ((double) kelondroBase64Order.enhancedCoder.cardinal(ahash.getBytes())) / ((double) maxDHTDistance);
}
- public final static double dhtDistance(String from, String to) {
+ public final static double dhtDistance(final String from, final String to) {
// computes a virtual distance, the result must be set in relation to maxDHTDistace
// if the distance is small, this peer is more responsible for that word hash
// if the distance is big, this peer is less responsible for that word hash
@@ -690,17 +691,17 @@ public class yacySeed {
return (fromPos <= toPos) ? (toPos - fromPos) : (1.0 - fromPos + toPos);
}
- private static String bestGap(yacySeedDB seedDB) {
+ private static String bestGap(final yacySeedDB seedDB) {
if ((seedDB == null) || (seedDB.sizeConnected() <= 2)) {
// use random hash
return randomHash();
}
// find gaps
- TreeMap<Double, String> gaps = hashGaps(seedDB);
+ final TreeMap<Double, String> gaps = hashGaps(seedDB);
// take one gap; prefer biggest but take also another smaller by chance
String interval = null;
- Random r = new Random();
+ final Random r = new Random();
while (gaps.size() > 0) {
interval = gaps.remove(gaps.lastKey());
if (r.nextBoolean()) break;
@@ -708,18 +709,18 @@ public class yacySeed {
if (interval == null) return randomHash();
// find dht position and size of gap
- double gapsize = dhtDistance(interval.substring(0, 12), interval.substring(12));
+ final double gapsize = dhtDistance(interval.substring(0, 12), interval.substring(12));
assert gapsize >= 0.0;
double gappos = dhtPosition(interval.substring(0, 12)) + (gapsize / 2);
if (gappos >= 1.0) gappos = gappos - 1.0; // fix overflow; can only occur for gap at end
return positionToHash(gappos);
}
- private static TreeMap<Double, String> hashGaps(yacySeedDB seedDB) {
- TreeMap<Double, String>gaps = new TreeMap<Double, String>();
+ private static TreeMap<Double, String> hashGaps(final yacySeedDB seedDB) {
+ final TreeMap<Double, String>gaps = new TreeMap<Double, String>();
if (seedDB == null) return gaps;
- Iterator<yacySeed> i = seedDB.seedsConnected(true, false, null, (float) 0.0);
+ final Iterator<yacySeed> i = seedDB.seedsConnected(true, false, null, (float) 0.0);
double d;
yacySeed s0 = null, s1, first = null;
while (i.hasNext()) {
@@ -746,14 +747,14 @@ public class yacySeed {
return gaps;
}
- private static String positionToHash(double t) {
+ private static String positionToHash(final double t) {
// transform the position of a peer position into a close peer hash
assert t >= 0.0 : "t = " + t;
assert t < 1.0 : "t = " + t;
// now calculate a hash that is closest to the best position
double d, bestD = Double.MAX_VALUE;
- int tries = 128;
+ final int tries = 128;
String hash, bestHash = null;
for (int v = 0; v < tries; v++) {
hash = randomHash();
@@ -766,11 +767,11 @@ public class yacySeed {
return bestHash;
}
- public static yacySeed genLocalSeed(yacySeedDB db) {
+ public static yacySeed genLocalSeed(final yacySeedDB db) {
return genLocalSeed(db, 0, null); // an anonymous peer
}
- public static yacySeed genLocalSeed(yacySeedDB db, int port, String name) {
+ public static yacySeed genLocalSeed(final yacySeedDB db, final int port, final String name) {
// generate a seed for the local peer
// this is the birthplace of a seed, that then will start to travel to other peers
@@ -799,7 +800,7 @@ public class yacySeed {
return hash;
}
- public static yacySeed genRemoteSeed(String seedStr, String key, boolean ownSeed) {
+ public static yacySeed genRemoteSeed(final String seedStr, final String key, final boolean ownSeed) {
// this method is used to convert the external representation of a seed into a seed object
// yacyCore.log.logFinest("genRemoteSeed: seedStr=" + seedStr + " key=" + key);
@@ -824,7 +825,7 @@ public class yacySeed {
return resultSeed;
}
- public final String isProper(boolean checkOwnIP) {
+ public final String isProper(final boolean checkOwnIP) {
// checks if everything is ok with that seed
// check hash
@@ -832,7 +833,7 @@ public class yacySeed {
if (this.hash.length() != yacySeedDB.commonHashLength) return "wrong hash length (" + this.hash.length() + ")";
// name
- String peerName = this.dna.get(yacySeed.NAME);
+ final String peerName = this.dna.get(yacySeed.NAME);
if (peerName == null) return "no peer name given";
dna.put(yacySeed.NAME, checkPeerName(peerName));
@@ -848,17 +849,17 @@ public class yacySeed {
if (seedURL != null && seedURL.length() > 0) {
if (!seedURL.startsWith("http://") && !seedURL.startsWith("https://")) return "wrong protocol for seedURL";
try {
- URL url = new URL(seedURL);
- String host = url.getHost();
+ final URL url = new URL(seedURL);
+ final String host = url.getHost();
if (host.equals("localhost") || host.startsWith("127.") || (host.startsWith("0:0:0:0:0:0:0:1"))) return "seedURL in localhost rejected";
- } catch (MalformedURLException e) {
+ } catch (final MalformedURLException e) {
return "seedURL malformed";
}
}
return null;
}
- public static final String isProperIP(String ipString) {
+ public static final String isProperIP(final String ipString) {
// returns null if ipString is proper, a string with the cause otervise
if (ipString == null) return "IP is null";
if (ipString.length() > 0 && ipString.length() < 8) return "IP is too short: " + ipString;
@@ -876,32 +877,32 @@ public class yacySeed {
}
}
- public final String genSeedStr(String key) {
+ public final String genSeedStr(final String key) {
// use a default encoding
- String z = this.genSeedStr('z', key);
- String b = this.genSeedStr('b', key);
+ final String z = this.genSeedStr('z', key);
+ final String b = this.genSeedStr('b', key);
// the compressed string may be longer that the uncompressed if there is too much overhead for compression meta-info
// take simply that string that is shorter
if (b.length() < z.length()) return b; else return z;
}
- public final synchronized String genSeedStr(char method, String key) {
+ public final synchronized String genSeedStr(final char method, final String key) {
return crypt.simpleEncode(this.toString(), key, method);
}
- public final void save(File f) throws IOException {
+ public final void save(final File f) throws IOException {
final String out = this.genSeedStr('p', null);
final FileWriter fw = new FileWriter(f);
fw.write(out, 0, out.length());
fw.close();
}
- public static yacySeed load(File f) throws IOException {
+ public static yacySeed load(final File f) throws IOException {
final FileReader fr = new FileReader(f);
final char[] b = new char[(int) f.length()];
fr.read(b, 0, b.length);
fr.close();
- yacySeed mySeed = genRemoteSeed(new String(b), null, true);
+ final yacySeed mySeed = genRemoteSeed(new String(b), null, true);
if (mySeed == null) return null;
mySeed.dna.put(yacySeed.IP, ""); // set own IP as unknown
return mySeed;
diff --git a/source/de/anomic/yacy/yacySeedDB.java b/source/de/anomic/yacy/yacySeedDB.java
index 195ae7039..f79d6855c 100644
--- a/source/de/anomic/yacy/yacySeedDB.java
+++ b/source/de/anomic/yacy/yacySeedDB.java
@@ -100,10 +100,10 @@ public final class yacySeedDB implements httpdAlternativeDomainNames {
private final Hashtable<InetAddress, SoftReference<yacySeed>> ipLookupCache;
public yacySeedDB(
- File seedActiveDBFile,
- File seedPassiveDBFile,
- File seedPotentialDBFile,
- File myOwnSeedFile) {
+ final File seedActiveDBFile,
+ final File seedPassiveDBFile,
+ final File seedPotentialDBFile,
+ final File myOwnSeedFile) {
this.seedActiveDBFile = seedActiveDBFile;
this.seedPassiveDBFile = seedPassiveDBFile;
this.seedPotentialDBFile = seedPotentialDBFile;
@@ -137,13 +137,13 @@ public final class yacySeedDB implements httpdAlternativeDomainNames {
if (myOwnSeedFile.length() > 0) try {
// load existing identity
mySeed = yacySeed.load(myOwnSeedFile);
- } catch (IOException e) {
+ } catch (final IOException e) {
// create new identity
serverLog.logSevere("SEEDDB", "could not load stored mySeed.txt from " + myOwnSeedFile.toString() + ": " + e.getMessage() + ". creating new seed.", e);
mySeed = yacySeed.genLocalSeed(this);
try {
mySeed.save(myOwnSeedFile);
- } catch (IOException ee) {
+ } catch (final IOException ee) {
serverLog.logSevere("SEEDDB", "error saving mySeed.txt (1) to " + myOwnSeedFile.toString() + ": " + ee.getMessage(), ee);
ee.printStackTrace();
System.exit(-1);
@@ -154,7 +154,7 @@ public final class yacySeedDB implements httpdAlternativeDomainNames {
mySeed = yacySeed.genLocalSeed(this);
try {
mySeed.save(myOwnSeedFile);
- } catch (IOException ee) {
+ } catch (final IOException ee) {
serverLog.logSevere("SEEDDB", "error saving mySeed.txt (2) to " + myOwnSeedFile.toString() + ": " + ee.getMessage(), ee);
ee.printStackTrace();
System.exit(-1);
@@ -171,7 +171,7 @@ public final class yacySeedDB implements httpdAlternativeDomainNames {
public yacySeed mySeed() {
if (this.mySeed == null) {
- if (this.sizeConnected() == 0) try {Thread.sleep(5000);} catch (InterruptedException e) {} // wait for init
+ if (this.sizeConnected() == 0) try {Thread.sleep(5000);} catch (final InterruptedException e) {} // wait for init
initMySeed();
}
return this.mySeed;
@@ -204,13 +204,13 @@ public final class yacySeedDB implements httpdAlternativeDomainNames {
seedActiveDB.remove(mySeed.hash);
seedPassiveDB.remove(mySeed.hash);
seedPotentialDB.remove(mySeed.hash);
- } catch (IOException e) {}
+ } catch (final IOException e) {}
}
public void saveMySeed() {
try {
this.mySeed().save(myOwnSeedFile);
- } catch (IOException e) {}
+ } catch (final IOException e) {}
}
public boolean noDHTActivity() {
@@ -219,36 +219,36 @@ public final class yacySeedDB implements httpdAlternativeDomainNames {
}
@SuppressWarnings("unchecked")
- private synchronized kelondroMapDataMining openSeedTable(File seedDBFile) {
+ private synchronized kelondroMapDataMining openSeedTable(final File seedDBFile) {
final boolean usetree = false;
new File(seedDBFile.getParent()).mkdirs();
Class[] args;
try {
args = new Class[]{"".getClass(), Class.forName("java.util.Map")};
- } catch (ClassNotFoundException e2){
+ } catch (final ClassNotFoundException e2){
e2.printStackTrace();
args = null;
}
Method initializeHandlerMethod;
try {
initializeHandlerMethod = this.getClass().getMethod("initializeHandler", args);
- } catch (SecurityException e1) {
+ } catch (final SecurityException e1) {
e1.printStackTrace();
initializeHandlerMethod = null;
- } catch (NoSuchMethodException e1) {
+ } catch (final NoSuchMethodException e1) {
e1.printStackTrace();
initializeHandlerMethod = null;
}
try {
return new kelondroMapDataMining(new kelondroBLOBTree(seedDBFile, true, true, commonHashLength, 480, '#', kelondroBase64Order.enhancedCoder, usetree, false, true), 500, sortFields, longaccFields, doubleaccFields, initializeHandlerMethod, this);
- } catch (Exception e) {
+ } catch (final Exception e) {
// try again
kelondroBLOBTree.delete(seedDBFile);
return new kelondroMapDataMining(new kelondroBLOBTree(seedDBFile, true, true, commonHashLength, 480, '#', kelondroBase64Order.enhancedCoder, usetree, false, true), 500, sortFields, longaccFields, doubleaccFields, initializeHandlerMethod, this);
}
}
- protected synchronized kelondroMapDataMining resetSeedTable(kelondroMapDataMining seedDB, File seedDBFile) {
+ protected synchronized kelondroMapDataMining resetSeedTable(kelondroMapDataMining seedDB, final File seedDBFile) {
// this is an emergency function that should only be used if any problem with the
// seed.db is detected
yacyCore.log.logFine("seed-db " + seedDBFile.toString() + " reset (on-the-fly)");
@@ -270,27 +270,27 @@ public final class yacySeedDB implements httpdAlternativeDomainNames {
}
@SuppressWarnings("unchecked")
- public void initializeHandler(String mapname, Map map) {
+ public void initializeHandler(final String mapname, final Map map) {
// this is used to set up a lastSeen lookup table
}
- public Iterator<yacySeed> seedsSortedConnected(boolean up, String field) {
+ public Iterator<yacySeed> seedsSortedConnected(final boolean up, final String field) {
// enumerates seed-type objects: all seeds sequentially ordered by field
return new seedEnum(up, field, seedActiveDB);
}
- public Iterator<yacySeed> seedsSortedDisconnected(boolean up, String field) {
+ public Iterator<yacySeed> seedsSortedDisconnected(final boolean up, final String field) {
// enumerates seed-type objects: all seeds sequentially ordered by field
return new seedEnum(up, field, seedPassiveDB);
}
- public Iterator<yacySeed> seedsSortedPotential(boolean up, String field) {
+ public Iterator<yacySeed> seedsSortedPotential(final boolean up, final String field) {
// enumerates seed-type objects: all seeds sequentially ordered by field
return new seedEnum(up, field, seedPotentialDB);
}
- public TreeMap<String, String> /* peer-b64-hashes/ipport */ clusterHashes(String clusterdefinition) {
+ public TreeMap<String, String> /* peer-b64-hashes/ipport */ clusterHashes(final String clusterdefinition) {
// collects seeds according to cluster definition string, which consists of
// comma-separated .yacy or .yacyh-domains
// the domain may be extended by an alternative address specification of the form
@@ -299,8 +299,8 @@ public final class yacySeedDB implements httpdAlternativeDomainNames {
// address has therefore the form
// address ::= (<peername>'.yacy'|<peerhexhash>'.yacyh'){'='<ip>{':'<port}}
// clusterdef ::= {address}{','address}*
- String[] addresses = (clusterdefinition.length() == 0) ? new String[0] : clusterdefinition.split(",");
- TreeMap<String, String> clustermap = new TreeMap<String, String>(kelondroBase64Order.enhancedComparator);
+ final String[] addresses = (clusterdefinition.length() == 0) ? new String[0] : clusterdefinition.split(",");
+ final TreeMap<String, String> clustermap = new TreeMap<String, String>(kelondroBase64Order.enhancedComparator);
yacySeed seed;
String hash, yacydom, ipport;
int p;
@@ -337,38 +337,38 @@ public final class yacySeedDB implements httpdAlternativeDomainNames {
return clustermap;
}
- public Iterator<yacySeed> seedsConnected(boolean up, boolean rot, String firstHash, float minVersion) {
+ public Iterator<yacySeed> seedsConnected(final boolean up, final boolean rot, final String firstHash, final float minVersion) {
// enumerates seed-type objects: all seeds sequentially without order
return new seedEnum(up, rot, (firstHash == null) ? null : firstHash.getBytes(), null, seedActiveDB, minVersion);
}
- public Iterator<yacySeed> seedsDisconnected(boolean up, boolean rot, String firstHash, float minVersion) {
+ public Iterator<yacySeed> seedsDisconnected(final boolean up, final boolean rot, final String firstHash, final float minVersion) {
// enumerates seed-type objects: all seeds sequentially without order
return new seedEnum(up, rot, (firstHash == null) ? null : firstHash.getBytes(), null, seedPassiveDB, minVersion);
}
- public Iterator<yacySeed> seedsPotential(boolean up, boolean rot, String firstHash, float minVersion) {
+ public Iterator<yacySeed> seedsPotential(final boolean up, final boolean rot, final String firstHash, final float minVersion) {
// enumerates seed-type objects: all seeds sequentially without order
return new seedEnum(up, rot, (firstHash == null) ? null : firstHash.getBytes(), null, seedPotentialDB, minVersion);
}
- public yacySeed anySeedVersion(float minVersion) {
+ public yacySeed anySeedVersion(final float minVersion) {
// return just any seed that has a specific minimum version number
- Iterator<yacySeed> e = seedsConnected(true, true, yacySeed.randomHash(), minVersion);
+ final Iterator<yacySeed> e = seedsConnected(true, true, yacySeed.randomHash(), minVersion);
return e.next();
}
- public HashMap<String, yacySeed> seedsByAge(boolean up, int count) {
+ public HashMap<String, yacySeed> seedsByAge(final boolean up, int count) {
// returns a peerhash/yacySeed relation
// to get most recent peers, set up = true; for oldest peers, set up = false
if (count > sizeConnected()) count = sizeConnected();
// fill a score object
- kelondroMScoreCluster<String> seedScore = new kelondroMScoreCluster<String>();
+ final kelondroMScoreCluster<String> seedScore = new kelondroMScoreCluster<String>();
yacySeed ys;
long absage;
- Iterator<yacySeed> s = seedsConnected(true, false, null, (float) 0.0);
+ final Iterator<yacySeed> s = seedsConnected(true, false, null, (float) 0.0);
int searchcount = 1000;
if (searchcount > sizeConnected()) searchcount = sizeConnected();
try {
@@ -377,12 +377,12 @@ public final class yacySeedDB implements httpdAlternativeDomainNames {
if ((ys != null) && (ys.get(yacySeed.LASTSEEN, "").length() > 10)) try {
absage = Math.abs(System.currentTimeMillis() + serverDate.dayMillis - ys.getLastSeenUTC());
seedScore.addScore(ys.hash, (int) absage); // the higher absage, the older is the peer
- } catch (Exception e) {}
+ } catch (final Exception e) {}
}
// result is now in the score object; create a result vector
- HashMap<String, yacySeed> result = new HashMap<String, yacySeed>();
- Iterator<String> it = seedScore.scores(up);
+ final HashMap<String, yacySeed> result = new HashMap<String, yacySeed>();
+ final Iterator<String> it = seedScore.scores(up);
int c = 0;
while ((c < count) && (it.hasNext())) {
c++;
@@ -390,7 +390,7 @@ public final class yacySeedDB implements httpdAlternativeDomainNames {
if ((ys != null) && (ys.hash != null)) result.put(ys.hash, ys);
}
return result;
- } catch (kelondroException e) {
+ } catch (final kelondroException e) {
seedActiveDB = resetSeedTable(seedActiveDB, seedActiveDBFile);
yacyCore.log.logFine("Internal Error at yacySeedDB.seedsByAge: " + e.getMessage(), e);
return null;
@@ -433,151 +433,151 @@ public final class yacySeedDB implements httpdAlternativeDomainNames {
public long countPotentialURL() { return seedPotentialDB.getLongAcc(yacySeed.LCOUNT); }
public long countPotentialRWI() { return seedPotentialDB.getLongAcc(yacySeed.ICOUNT); }
- public synchronized void addConnected(yacySeed seed) {
+ public synchronized void addConnected(final yacySeed seed) {
if ((seed == null) || (seed.isProper(false) != null)) return;
//seed.put(yacySeed.LASTSEEN, yacyCore.shortFormatter.format(new Date(yacyCore.universalTime())));
try {
nameLookupCache.put(seed.getName(), seed);
- HashMap<String, String> seedPropMap = seed.getMap();
+ final HashMap<String, String> seedPropMap = seed.getMap();
synchronized(seedPropMap) {
seedActiveDB.put(seed.hash, seedPropMap);
}
seedPassiveDB.remove(seed.hash);
seedPotentialDB.remove(seed.hash);
- } catch (IOException e){
+ } catch (final IOException e){
yacyCore.log.logSevere("ERROR add: seed.db corrupt (" + e.getMessage() + "); resetting seed.db", e);
resetActiveTable();
- } catch (kelondroException e){
+ } catch (final kelondroException e){
yacyCore.log.logSevere("ERROR add: seed.db corrupt (" + e.getMessage() + "); resetting seed.db", e);
resetActiveTable();
- } catch (IllegalArgumentException e) {
+ } catch (final IllegalArgumentException e) {
yacyCore.log.logSevere("ERROR add: seed.db corrupt (" + e.getMessage() + "); resetting seed.db", e);
resetActiveTable();
}
}
- public synchronized void addDisconnected(yacySeed seed) {
+ public synchronized void addDisconnected(final yacySeed seed) {
if (seed == null) return;
try {
nameLookupCache.remove(seed.getName());
seedActiveDB.remove(seed.hash);
seedPotentialDB.remove(seed.hash);
- } catch (Exception e) {}
+ } catch (final Exception e) {}
//seed.put(yacySeed.LASTSEEN, yacyCore.shortFormatter.format(new Date(yacyCore.universalTime())));
try {
- HashMap<String, String> seedPropMap = seed.getMap();
+ final HashMap<String, String> seedPropMap = seed.getMap();
synchronized(seedPropMap) {
seedPassiveDB.put(seed.hash, seedPropMap);
}
- } catch (IOException e) {
+ } catch (final IOException e) {
yacyCore.log.logSevere("ERROR add: seed.db corrupt (" + e.getMessage() + "); resetting seed.db", e);
resetPassiveTable();
- } catch (kelondroException e) {
+ } catch (final kelondroException e) {
yacyCore.log.logSevere("ERROR add: seed.db corrupt (" + e.getMessage() + "); resetting seed.db", e);
resetPassiveTable();
- } catch (IllegalArgumentException e) {
+ } catch (final IllegalArgumentException e) {
yacyCore.log.logSevere("ERROR add: seed.db corrupt (" + e.getMessage() + "); resetting seed.db", e);
resetPassiveTable();
}
}
- public synchronized void addPotential(yacySeed seed) {
+ public synchronized void addPotential(final yacySeed seed) {
if (seed == null) return;
try {
nameLookupCache.remove(seed.getName());
seedActiveDB.remove(seed.hash);
seedPassiveDB.remove(seed.hash);
- } catch (Exception e) {}
+ } catch (final Exception e) {}
if (seed.isProper(false) != null) return;
//seed.put(yacySeed.LASTSEEN, yacyCore.shortFormatter.format(new Date(yacyCore.universalTime())));
try {
- HashMap<String, String> seedPropMap = seed.getMap();
+ final HashMap<String, String> seedPropMap = seed.getMap();
synchronized(seedPropMap) {
seedPotentialDB.put(seed.hash, seedPropMap);
}
- } catch (IOException e) {
+ } catch (final IOException e) {
yacyCore.log.logSevere("ERROR add: seed.db corrupt (" + e.getMessage() + "); resetting seed.db", e);
resetPotentialTable();
- } catch (kelondroException e) {
+ } catch (final kelondroException e) {
yacyCore.log.logSevere("ERROR add: seed.db corrupt (" + e.getMessage() + "); resetting seed.db", e);
resetPotentialTable();
- } catch (IllegalArgumentException e) {
+ } catch (final IllegalArgumentException e) {
yacyCore.log.logSevere("ERROR add: seed.db corrupt (" + e.getMessage() + "); resetting seed.db", e);
resetPotentialTable();
}
}
- public synchronized void removeDisconnected(String peerHash) {
+ public synchronized void removeDisconnected(final String peerHash) {
if(peerHash == null) return;
try {
seedPassiveDB.remove(peerHash);
- } catch (IOException e) { }
+ } catch (final IOException e) { }
}
- public synchronized void removePotential(String peerHash) {
+ public synchronized void removePotential(final String peerHash) {
if(peerHash == null) return;
try {
seedPotentialDB.remove(peerHash);
- } catch (IOException e) { }
+ } catch (final IOException e) { }
}
- public boolean hasConnected(String hash) {
+ public boolean hasConnected(final String hash) {
try {
return seedActiveDB.has(hash);
- } catch (IOException e) {
+ } catch (final IOException e) {
return false;
}
}
- public boolean hasDisconnected(String hash) {
+ public boolean hasDisconnected(final String hash) {
try {
return seedPassiveDB.has(hash);
- } catch (IOException e) {
+ } catch (final IOException e) {
return false;
}
}
- public boolean hasPotential(String hash) {
+ public boolean hasPotential(final String hash) {
try {
return seedPotentialDB.has(hash);
- } catch (IOException e) {
+ } catch (final IOException e) {
return false;
}
}
- private yacySeed get(String hash, kelondroMapDataMining database) {
+ private yacySeed get(final String hash, final kelondroMapDataMining database) {
if (hash == null) return null;
if ((this.mySeed != null) && (hash.equals(mySeed.hash))) return mySeed;
HashMap<String, String> entry;
try {
entry = database.get(hash);
- } catch (IOException e) {
+ } catch (final IOException e) {
entry = null;
}
if (entry == null) return null;
return new yacySeed(hash, entry);
}
- public yacySeed getConnected(String hash) {
+ public yacySeed getConnected(final String hash) {
return get(hash, seedActiveDB);
}
- public yacySeed getDisconnected(String hash) {
+ public yacySeed getDisconnected(final String hash) {
return get(hash, seedPassiveDB);
}
- public yacySeed getPotential(String hash) {
+ public yacySeed getPotential(final String hash) {
return get(hash, seedPotentialDB);
}
- public yacySeed get(String hash) {
+ public yacySeed get(final String hash) {
yacySeed seed = getConnected(hash);
if (seed == null) seed = getDisconnected(hash);
if (seed == null) seed = getPotential(hash);
return seed;
}
- public void update(String hash, yacySeed seed) {
+ public void update(final String hash, final yacySeed seed) {
if (this.mySeed == null) initMySeed();
if (hash.equals(mySeed.hash)) {
mySeed = seed;
@@ -585,16 +585,16 @@ public final class yacySeedDB implements httpdAlternativeDomainNames {
}
yacySeed s = get(hash, seedActiveDB);
- if (s != null) try { seedActiveDB.put(hash, seed.getMap()); return;} catch (IOException e) {}
+ if (s != null) try { seedActiveDB.put(hash, seed.getMap()); return;} catch (final IOException e) {}
s = get(hash, seedPassiveDB);
- if (s != null) try { seedPassiveDB.put(hash, seed.getMap()); return;} catch (IOException e) {}
+ if (s != null) try { seedPassiveDB.put(hash, seed.getMap()); return;} catch (final IOException e) {}
s = get(hash, seedPotentialDB);
- if (s != null) try { seedPotentialDB.put(hash, seed.getMap()); return;} catch (IOException e) {}
+ if (s != null) try { seedPotentialDB.put(hash, seed.getMap()); return;} catch (final IOException e) {}
}
- public yacySeed lookupByName(String peerName) {
+ public yacySeed lookupByName(final String peerName) {
// reads a seed by searching by name
// local peer?
@@ -610,7 +610,7 @@ public final class yacySeedDB implements httpdAlternativeDomainNames {
// enumerate the cache and simultanous insert values
String name;
for (int table = 0; table < 2; table++) {
- Iterator<yacySeed> e = (table == 0) ? seedsConnected(true, false, null, (float) 0.0) : seedsDisconnected(true, false, null, (float) 0.0);
+ final Iterator<yacySeed> e = (table == 0) ? seedsConnected(true, false, null, (float) 0.0) : seedsDisconnected(true, false, null, (float) 0.0);
while (e.hasNext()) {
seed = e.next();
if (seed != null) {
@@ -630,10 +630,10 @@ public final class yacySeedDB implements httpdAlternativeDomainNames {
}
public yacySeed lookupByIP(
- InetAddress peerIP,
- boolean lookupConnected,
- boolean lookupDisconnected,
- boolean lookupPotential
+ final InetAddress peerIP,
+ final boolean lookupConnected,
+ final boolean lookupDisconnected,
+ final boolean lookupPotential
) {
if (peerIP == null) return null;
@@ -646,7 +646,7 @@ public final class yacySeedDB implements httpdAlternativeDomainNames {
}
// then try to use the cache
- SoftReference<yacySeed> ref = ipLookupCache.get(peerIP);
+ final SoftReference<yacySeed> ref = ipLookupCache.get(peerIP);
if (ref != null) {
seed = ref.get();
if (seed != null) return seed;
@@ -655,11 +655,11 @@ public final class yacySeedDB implements httpdAlternativeDomainNames {
int pos = -1;
String addressStr = null;
InetAddress seedIPAddress = null;
- HashSet<String> badPeerHashes = new HashSet<String>();
+ final HashSet<String> badPeerHashes = new HashSet<String>();
if (lookupConnected) {
// enumerate the cache and simultanous insert values
- Iterator<yacySeed> e = seedsConnected(true, false, null, (float) 0.0);
+ final Iterator<yacySeed> e = seedsConnected(true, false, null, (float) 0.0);
while (e.hasNext()) {
try {
seed = e.next();
@@ -677,17 +677,17 @@ public final class yacySeedDB implements httpdAlternativeDomainNames {
if (seed.isProper(false) == null) ipLookupCache.put(seedIPAddress, new SoftReference<yacySeed>(seed));
if (seedIPAddress.equals(peerIP)) return seed;
}
- } catch (UnknownHostException ex) {}
+ } catch (final UnknownHostException ex) {}
}
// delete bad peers
- Iterator<String> i = badPeerHashes.iterator();
- while (i.hasNext()) try {seedActiveDB.remove(i.next());} catch (IOException e1) {e1.printStackTrace();}
+ final Iterator<String> i = badPeerHashes.iterator();
+ while (i.hasNext()) try {seedActiveDB.remove(i.next());} catch (final IOException e1) {e1.printStackTrace();}
badPeerHashes.clear();
}
if (lookupDisconnected) {
// enumerate the cache and simultanous insert values
- Iterator<yacySeed>e = seedsDisconnected(true, false, null, (float) 0.0);
+ final Iterator<yacySeed>e = seedsDisconnected(true, false, null, (float) 0.0);
while (e.hasNext()) {
try {
@@ -706,17 +706,17 @@ public final class yacySeedDB implements httpdAlternativeDomainNames {
if (seed.isProper(false) == null) ipLookupCache.put(seedIPAddress, new SoftReference<yacySeed>(seed));
if (seedIPAddress.equals(peerIP)) return seed;
}
- } catch (UnknownHostException ex) {}
+ } catch (final UnknownHostException ex) {}
}
// delete bad peers
- Iterator<String> i = badPeerHashes.iterator();
- while (i.hasNext()) try {seedActiveDB.remove(i.next());} catch (IOException e1) {e1.printStackTrace();}
+ final Iterator<String> i = badPeerHashes.iterator();
+ while (i.hasNext()) try {seedActiveDB.remove(i.next());} catch (final IOException e1) {e1.printStackTrace();}
badPeerHashes.clear();
}
if (lookupPotential) {
// enumerate the cache and simultanous insert values
- Iterator<yacySeed> e = seedsPotential(true, false, null, (float) 0.0);
+ final Iterator<yacySeed> e = seedsPotential(true, false, null, (float) 0.0);
while (e.hasNext()) {
try {
@@ -729,7 +729,7 @@ public final class yacySeedDB implements httpdAlternativeDomainNames {
if (seed.isProper(false) == null) ipLookupCache.put(seedIPAddress, new SoftReference<yacySeed>(seed));
if (seedIPAddress.equals(peerIP)) return seed;
}
- } catch (UnknownHostException ex) {}
+ } catch (final UnknownHostException ex) {}
}
}
@@ -746,18 +746,18 @@ public final class yacySeedDB implements httpdAlternativeDomainNames {
if (seedIPAddress.equals(peerIP)) return mySeed;
// nothing found
return null;
- } catch (UnknownHostException e2) {
+ } catch (final UnknownHostException e2) {
return null;
}
}
- public ArrayList<String> storeCache(File seedFile) throws IOException {
+ public ArrayList<String> storeCache(final File seedFile) throws IOException {
return storeCache(seedFile, false);
}
- private ArrayList<String> storeCache(File seedFile, boolean addMySeed) throws IOException {
+ private ArrayList<String> storeCache(final File seedFile, final boolean addMySeed) throws IOException {
PrintWriter pw = null;
- ArrayList<String> v = new ArrayList<String>(seedActiveDB.size() + 1);
+ final ArrayList<String> v = new ArrayList<String>(seedActiveDB.size() + 1);
try {
pw = new PrintWriter(new BufferedWriter(new FileWriter(seedFile)));
@@ -773,7 +773,7 @@ public final class yacySeedDB implements httpdAlternativeDomainNames {
// store other seeds
yacySeed ys;
- Iterator<yacySeed> se = seedsConnected(true, false, null, (float) 0.0);
+ final Iterator<yacySeed> se = seedsConnected(true, false, null, (float) 0.0);
while (se.hasNext()) {
ys = se.next();
if (ys != null) {
@@ -784,19 +784,19 @@ public final class yacySeedDB implements httpdAlternativeDomainNames {
}
pw.flush();
} finally {
- if (pw != null) try { pw.close(); } catch (Exception e) {}
+ if (pw != null) try { pw.close(); } catch (final Exception e) {}
}
return v;
}
- public String uploadCache(yacySeedUploader uploader,
- serverSwitch<?> sb,
- yacySeedDB seedDB,
+ public String uploadCache(final yacySeedUploader uploader,
+ final serverSwitch<?> sb,
+ final yacySeedDB seedDB,
// String seedFTPServer,
// String seedFTPAccount,
// String seedFTPPassword,
// File seedFTPPath,
- yacyURL seedURL) throws Exception {
+ final yacyURL seedURL) throws Exception {
// upload a seed file, if possible
if (seedURL == null) throw new NullPointerException("UPLOAD - Error: URL not given");
@@ -808,7 +808,7 @@ public final class yacySeedDB implements httpdAlternativeDomainNames {
seedFile = File.createTempFile("seedFile",".txt", plasmaHTCache.cachePath);
seedFile.deleteOnExit();
serverLog.logFine("YACY","SaveSeedList: Storing seedlist into tempfile " + seedFile.toString());
- ArrayList<String> uv = storeCache(seedFile, true);
+ final ArrayList<String> uv = storeCache(seedFile, true);
// uploading the seed file
serverLog.logFine("YACY","SaveSeedList: Trying to upload seed-file, " + seedFile.length() + " bytes, " + uv.size() + " entries.");
@@ -816,31 +816,31 @@ public final class yacySeedDB implements httpdAlternativeDomainNames {
// test download
serverLog.logFine("YACY","SaveSeedList: Trying to download seed-file '" + seedURL + "'.");
- ArrayList<String> check = downloadSeedFile(seedURL);
+ final ArrayList<String> check = downloadSeedFile(seedURL);
// Comparing if local copy and uploaded copy are equal
- String errorMsg = checkCache(uv, check);
+ final String errorMsg = checkCache(uv, check);
if (errorMsg == null)
log = log + "UPLOAD CHECK - Success: the result vectors are equal" + serverCore.CRLF_STRING;
else {
throw new Exception("UPLOAD CHECK - Error: the result vector is different. " + errorMsg + serverCore.CRLF_STRING);
}
} finally {
- if (seedFile != null) try { seedFile.delete(); } catch (Exception e) {/* ignore this */}
+ if (seedFile != null) try { seedFile.delete(); } catch (final Exception e) {/* ignore this */}
}
return log;
}
- private ArrayList<String> downloadSeedFile(yacyURL seedURL) throws IOException {
+ private ArrayList<String> downloadSeedFile(final yacyURL seedURL) throws IOException {
// Configure http headers
- httpHeader reqHeader = new httpHeader();
+ final httpHeader reqHeader = new httpHeader();
reqHeader.put(httpHeader.PRAGMA, "no-cache");
reqHeader.put(httpHeader.CACHE_CONTROL, "no-cache"); // httpc uses HTTP/1.0 is this necessary?
reqHeader.put(httpHeader.USER_AGENT, HTTPLoader.yacyUserAgent);
// init http-client
- JakartaCommonsHttpClient client = new JakartaCommonsHttpClient(10000, reqHeader, null);
+ final JakartaCommonsHttpClient client = new JakartaCommonsHttpClient(10000, reqHeader, null);
byte[] content = null;
JakartaCommonsHttpResponse res = null;
try {
@@ -866,12 +866,12 @@ public final class yacySeedDB implements httpdAlternativeDomainNames {
// convert it into an array
return nxTools.strings(content,"UTF-8");
- } catch (Exception e) {
+ } catch (final Exception e) {
throw new IOException("Unable to download seed file '" + seedURL + "'. " + e.getMessage());
}
}
- private String checkCache(ArrayList<String> uv, ArrayList<String> check) {
+ private String checkCache(final ArrayList<String> uv, final ArrayList<String> check) {
if ((check == null) || (uv == null) || (uv.size() != check.size())) {
serverLog.logFine("YACY","SaveSeedList: Local and uploades seed-list " +
"contains varying numbers of entries." +
@@ -929,7 +929,7 @@ public final class yacySeedDB implements httpdAlternativeDomainNames {
host = host.substring(p + 1); // if ever, the double-dots are here but do not harm
}
// identify domain
- String domain = host.substring(0, host.length() - 5).toLowerCase();
+ final String domain = host.substring(0, host.length() - 5).toLowerCase();
seed = lookupByName(domain);
if (seed == null) return null;
if (this.mySeed == null) initMySeed();
@@ -950,7 +950,7 @@ public final class yacySeedDB implements httpdAlternativeDomainNames {
kelondroMapDataMining database;
float minVersion;
- public seedEnum(boolean up, boolean rot, byte[] firstKey, byte[] secondKey, kelondroMapDataMining database, float minVersion) {
+ public seedEnum(final boolean up, final boolean rot, final byte[] firstKey, final byte[] secondKey, final kelondroMapDataMining database, final float minVersion) {
this.database = database;
this.minVersion = minVersion;
try {
@@ -960,13 +960,13 @@ public final class yacySeedDB implements httpdAlternativeDomainNames {
if (nextSeed == null) break;
if (nextSeed.getVersion() >= this.minVersion) break;
}
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
yacyCore.log.logSevere("ERROR seedLinEnum: seed.db corrupt (" + e.getMessage() + "); resetting seed.db", e);
if (database == seedActiveDB) seedActiveDB = resetSeedTable(seedActiveDB, seedActiveDBFile);
if (database == seedPassiveDB) seedPassiveDB = resetSeedTable(seedPassiveDB, seedPassiveDBFile);
it = null;
- } catch (kelondroException e) {
+ } catch (final kelondroException e) {
e.printStackTrace();
yacyCore.log.logSevere("ERROR seedLinEnum: seed.db corrupt (" + e.getMessage() + "); resetting seed.db", e);
if (database == seedActiveDB) seedActiveDB = resetSeedTable(seedActiveDB, seedActiveDBFile);
@@ -975,12 +975,12 @@ public final class yacySeedDB implements httpdAlternativeDomainNames {
}
}
- public seedEnum(boolean up, String field, kelondroMapDataMining database) {
+ public seedEnum(final boolean up, final String field, final kelondroMapDataMining database) {
this.database = database;
try {
it = database.maps(up, field);
nextSeed = internalNext();
- } catch (kelondroException e) {
+ } catch (final kelondroException e) {
e.printStackTrace();
yacyCore.log.logSevere("ERROR seedLinEnum: seed.db corrupt (" + e.getMessage() + "); resetting seed.db", e);
if (database == seedActiveDB) seedActiveDB = resetSeedTable(seedActiveDB, seedActiveDBFile);
@@ -997,12 +997,12 @@ public final class yacySeedDB implements httpdAlternativeDomainNames {
public yacySeed internalNext() {
if ((it == null) || (!(it.hasNext()))) return null;
try {
- HashMap<String, String> dna = it.next();
+ final HashMap<String, String> dna = it.next();
if (dna == null) return null;
- String hash = dna.remove("key");
+ final String hash = dna.remove("key");
//while (hash.length() < commonHashLength) { hash = hash + "_"; }
return new yacySeed(hash, dna);
- } catch (Exception e) {
+ } catch (final Exception e) {
e.printStackTrace();
yacyCore.log.logSevere("ERROR internalNext: seed.db corrupt (" + e.getMessage() + "); resetting seed.db", e);
if (database == seedActiveDB) seedActiveDB = resetSeedTable(seedActiveDB, seedActiveDBFile);
@@ -1013,12 +1013,12 @@ public final class yacySeedDB implements httpdAlternativeDomainNames {
}
public yacySeed next() {
- yacySeed seed = nextSeed;
+ final yacySeed seed = nextSeed;
try {while (true) {
nextSeed = internalNext();
if (nextSeed == null) break;
if (nextSeed.getVersion() >= this.minVersion) break;
- }} catch (kelondroException e) {
+ }} catch (final kelondroException e) {
e.printStackTrace();
// eergency reset
yacyCore.log.logSevere("seed-db emergency reset", e);
@@ -1026,7 +1026,7 @@ public final class yacySeedDB implements httpdAlternativeDomainNames {
database.clear();
nextSeed = null;
return null;
- } catch (IOException e1) {
+ } catch (final IOException e1) {
// no recovery possible
e1.printStackTrace();
System.exit(-1);
diff --git a/source/de/anomic/yacy/yacyTray.java b/source/de/anomic/yacy/yacyTray.java
index c75ffd314..781bdb95c 100644
--- a/source/de/anomic/yacy/yacyTray.java
+++ b/source/de/anomic/yacy/yacyTray.java
@@ -45,7 +45,7 @@ import de.anomic.server.serverSystem;
public class yacyTray implements ActionListener, ItemListener {
- private boolean testing = false;
+ private final boolean testing = false;
plasmaSwitchboard sb;
@@ -57,13 +57,13 @@ public class yacyTray implements ActionListener, ItemListener {
private static SystemTray tray;
private static TrayIcon ti;
- public yacyTray(plasmaSwitchboard sb, boolean showmenu) {
+ public yacyTray(final plasmaSwitchboard sb, final boolean showmenu) {
this.sb = sb;
tray = SystemTray.getDefaultSystemTray();
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
- } catch (Exception e) {
+ } catch (final Exception e) {
e.printStackTrace();
}
if( Integer.parseInt(System.getProperty("java.version").substring(2,3)) >=5 )
@@ -84,7 +84,7 @@ public class yacyTray implements ActionListener, ItemListener {
// YaCy Search
menuItem = new JMenuItem("YaCy Search");
menuItem.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(final ActionEvent e) {
openBrowser("");
}
});
@@ -95,7 +95,7 @@ public class yacyTray implements ActionListener, ItemListener {
menu.addSeparator();
menuItem = new JMenuItem("Quit");
menuItem.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(final ActionEvent e) {
System.exit(0);
}
});
@@ -110,7 +110,7 @@ public class yacyTray implements ActionListener, ItemListener {
ti.setIconAutoSize(true);
ti.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(final ActionEvent e) {
trayClickAction();
}
});
@@ -129,7 +129,7 @@ public class yacyTray implements ActionListener, ItemListener {
} else { t1 = System.currentTimeMillis(); }
}
- private void openBrowser(String browserPopUpPage){
+ private void openBrowser(final String browserPopUpPage){
// no need for https, because we are on localhost
serverSystem.openBrowser("http://localhost:" + sb.getConfig("port", "8080") + "/" + browserPopUpPage);
}
@@ -139,12 +139,12 @@ public class yacyTray implements ActionListener, ItemListener {
isShown = false;
}
- public void displayBalloonMessage(String title, String message){
+ public void displayBalloonMessage(final String title, final String message){
ti.displayMessage(title, message, 0);
}
- public void actionPerformed(ActionEvent e) { }
+ public void actionPerformed(final ActionEvent e) { }
- public void itemStateChanged(ItemEvent e) { }
+ public void itemStateChanged(final ItemEvent e) { }
}
diff --git a/source/de/anomic/yacy/yacyURL.java b/source/de/anomic/yacy/yacyURL.java
index a22e1eb6b..016b5a176 100644
--- a/source/de/anomic/yacy/yacyURL.java
+++ b/source/de/anomic/yacy/yacyURL.java
@@ -52,7 +52,7 @@ public class yacyURL implements Serializable {
private String protocol, host, userInfo, path, quest, ref, hash;
private int port;
- public yacyURL(String url, String hash) throws MalformedURLException {
+ public yacyURL(final String url, final String hash) throws MalformedURLException {
if (url == null) throw new MalformedURLException("url string is null");
parseURLString(url);
@@ -76,7 +76,7 @@ public class yacyURL implements Serializable {
if (url.length() < p + 4) throw new MalformedURLException("URL not parseable: '" + url + "'");
if (url.substring(p + 1, p + 3).equals("//")) {
// identify host, userInfo and file for http and ftp protocol
- int q = url.indexOf('/', p + 3);
+ final int q = url.indexOf('/', p + 3);
int r;
if (q < 0) {
if ((r = url.indexOf('@', p + 3)) < 0) {
@@ -107,7 +107,7 @@ public class yacyURL implements Serializable {
// this is not a http or ftp url
if (protocol.equals("mailto")) {
// parse email url
- int q = url.indexOf('@', p + 3);
+ final int q = url.indexOf('@', p + 3);
if (q < 0) {
throw new MalformedURLException("wrong email address: " + url);
} else {
@@ -125,25 +125,25 @@ public class yacyURL implements Serializable {
// handle international domains
if (!Punycode.isBasic(host)) try {
- int d1 = host.lastIndexOf('.');
+ final int d1 = host.lastIndexOf('.');
if (d1 >= 0) {
- String tld = host.substring(d1 + 1);
- String dom = host.substring(0, d1);
- int d0 = dom.lastIndexOf('.');
+ final String tld = host.substring(d1 + 1);
+ final String dom = host.substring(0, d1);
+ final int d0 = dom.lastIndexOf('.');
if (d0 >= 0) {
host = dom.substring(0, d0) + ".xn--" + Punycode.encode(dom.substring(d0 + 1)) + "." + tld;
} else {
host = "xn--" + Punycode.encode(dom) + "." + tld;
}
}
- } catch (PunycodeException e) {}
+ } catch (final PunycodeException e) {}
}
- public yacyURL(File file) throws MalformedURLException {
+ public yacyURL(final File file) throws MalformedURLException {
this("file", "", -1, file.getAbsolutePath());
}
- public static yacyURL newURL(String baseURL, String relPath) throws MalformedURLException {
+ public static yacyURL newURL(final String baseURL, final String relPath) throws MalformedURLException {
if ((baseURL == null) ||
(relPath.startsWith("http://")) ||
(relPath.startsWith("https://")) ||
@@ -156,7 +156,7 @@ public class yacyURL implements Serializable {
}
}
- public static yacyURL newURL(yacyURL baseURL, String relPath) throws MalformedURLException {
+ public static yacyURL newURL(final yacyURL baseURL, final String relPath) throws MalformedURLException {
if ((baseURL == null) ||
(relPath.startsWith("http://")) ||
(relPath.startsWith("https://")) ||
@@ -169,7 +169,7 @@ public class yacyURL implements Serializable {
}
}
- private yacyURL(yacyURL baseURL, String relPath) throws MalformedURLException {
+ private yacyURL(final yacyURL baseURL, String relPath) throws MalformedURLException {
if (baseURL == null) throw new MalformedURLException("base URL is null");
if (relPath == null) throw new MalformedURLException("relPath is null");
@@ -204,7 +204,7 @@ public class yacyURL implements Serializable {
if (relPath.startsWith("#") || relPath.startsWith("?")) {
this.path = baseURL.path + relPath;
} else {
- int q = baseURL.path.lastIndexOf('/');
+ final int q = baseURL.path.lastIndexOf('/');
if (q < 0) {
this.path = relPath;
} else {
@@ -221,7 +221,7 @@ public class yacyURL implements Serializable {
escape();
}
- public yacyURL(String protocol, String host, int port, String path) throws MalformedURLException {
+ public yacyURL(final String protocol, final String host, final int port, final String path) throws MalformedURLException {
if (protocol == null) throw new MalformedURLException("protocol is null");
this.protocol = protocol;
this.host = host;
@@ -247,8 +247,8 @@ public class yacyURL implements Serializable {
/* by [MT] */
if (path.length() == 0 || path.charAt(0) != '/') { path = "/" + path; }
- Pattern pathPattern = Pattern.compile("(/[^/]+(?<!/\\.{1,2})/)[.]{2}(?=/|$)|/\\.(?=/)|/(?=/)");
- Matcher matcher = pathPattern.matcher(path);
+ final Pattern pathPattern = Pattern.compile("(/[^/]+(?<!/\\.{1,2})/)[.]{2}(?=/|$)|/\\.(?=/)|/(?=/)");
+ final Matcher matcher = pathPattern.matcher(path);
while (matcher.find()) {
path = matcher.replaceAll("");
matcher.reset(path);
@@ -272,7 +272,7 @@ public class yacyURL implements Serializable {
}
private void escapePath() {
- String[] pathp = path.split("/", -1);
+ final String[] pathp = path.split("/", -1);
String ptmp = "";
for (int i = 0; i < pathp.length; i++) {
ptmp += "/" + escape(pathp[i]);
@@ -285,7 +285,7 @@ public class yacyURL implements Serializable {
}
private void escapeQuest() {
- String[] questp = quest.split("&", -1);
+ final String[] questp = quest.split("&", -1);
String qtmp = "";
for (int i = 0; i < questp.length; i++) {
if (questp[i].indexOf('=') != -1) {
@@ -357,12 +357,12 @@ public class yacyURL implements Serializable {
* @return The encoded string
*/
// from: http://www.w3.org/International/URLUTF8Encoder.java
- public static String escape(String s)
+ public static String escape(final String s)
{
- StringBuffer sbuf = new StringBuffer();
- int len = s.length();
+ final StringBuffer sbuf = new StringBuffer();
+ final int len = s.length();
for (int i = 0; i < len; i++) {
- int ch = s.charAt(i);
+ final int ch = s.charAt(i);
if ('A' <= ch && ch <= 'Z') { // 'A'..'Z'
sbuf.append((char)ch);
} else if ('a' <= ch && ch <= 'z') { // 'a'..'z'
@@ -393,9 +393,9 @@ public class yacyURL implements Serializable {
}
// from: http://www.w3.org/International/unescape.java
- public static String unescape(String s) {
- StringBuffer sbuf = new StringBuffer();
- int l = s.length();
+ public static String unescape(final String s) {
+ final StringBuffer sbuf = new StringBuffer();
+ final int l = s.length();
int ch = -1;
int b, sumb = 0;
for (int i = 0, more = -1; i < l; i++) {
@@ -403,9 +403,9 @@ public class yacyURL implements Serializable {
switch (ch = s.charAt(i)) {
case '%':
ch = s.charAt(++i) ;
- int hb = (Character.isDigit ((char) ch) ? ch - '0' : 10 + Character.toLowerCase((char) ch) - 'a') & 0xF;
+ final int hb = (Character.isDigit ((char) ch) ? ch - '0' : 10 + Character.toLowerCase((char) ch) - 'a') & 0xF;
ch = s.charAt(++i) ;
- int lb = (Character.isDigit ((char) ch) ? ch - '0' : 10 + Character.toLowerCase ((char) ch) - 'a') & 0xF;
+ final int lb = (Character.isDigit ((char) ch) ? ch - '0' : 10 + Character.toLowerCase ((char) ch) - 'a') & 0xF;
b = (hb << 4) | lb;
break;
case '+':
@@ -441,18 +441,18 @@ public class yacyURL implements Serializable {
return sbuf.toString();
}
- private void identPort(String inputURL, int dflt) throws MalformedURLException {
+ private void identPort(final String inputURL, final int dflt) throws MalformedURLException {
// identify ref in file
- int r = this.host.indexOf(':');
+ final int r = this.host.indexOf(':');
if (r < 0) {
this.port = dflt;
} else {
try {
- String portStr = this.host.substring(r + 1);
+ final String portStr = this.host.substring(r + 1);
if (portStr.trim().length() > 0) this.port = Integer.parseInt(portStr);
else this.port = -1;
this.host = this.host.substring(0, r);
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
throw new MalformedURLException("wrong port in host fragment '" + this.host + "' of input url '" + inputURL + "'");
}
}
@@ -460,7 +460,7 @@ public class yacyURL implements Serializable {
private void identRef() {
// identify ref in file
- int r = path.indexOf('#');
+ final int r = path.indexOf('#');
if (r < 0) {
this.ref = null;
} else {
@@ -471,7 +471,7 @@ public class yacyURL implements Serializable {
private void identQuest() {
// identify quest in file
- int r = path.indexOf('?');
+ final int r = path.indexOf('?');
if (r < 0) {
this.quest = null;
} else {
@@ -484,7 +484,7 @@ public class yacyURL implements Serializable {
return getFile(true);
}
- public String getFile(boolean includeReference) {
+ public String getFile(final boolean includeReference) {
// this is the path plus quest plus ref
// if there is no quest and no ref the result is identical to getPath
// this is defined according to http://java.sun.com/j2se/1.4.2/docs/api/java/net/URL.html#getFile()
@@ -495,7 +495,7 @@ public class yacyURL implements Serializable {
public String getFileName() {
// this is a method not defined in any sun api
// it returns the last portion of a path without any reference
- int p = path.lastIndexOf('/');
+ final int p = path.lastIndexOf('/');
if (p < 0) return path;
if (p == path.length() - 1) return ""; // no file name, this is a path to a directory
return path.substring(p + 1); // the 'real' file name
@@ -537,14 +537,14 @@ public class yacyURL implements Serializable {
return toNormalform(false, true);
}
- public String toNormalform(boolean stripReference, boolean stripAmp) {
+ public String toNormalform(final boolean stripReference, final boolean stripAmp) {
if (stripAmp)
return toNormalform(!stripReference).replaceAll("&amp;", "&");
else
return toNormalform(!stripReference);
}
- private String toNormalform(boolean includeReference) {
+ private String toNormalform(final boolean includeReference) {
// generates a normal form of the URL
boolean defaultPort = false;
if (this.protocol.equals("mailto")) {
@@ -556,7 +556,7 @@ public class yacyURL implements Serializable {
} else if (this.protocol.equals("https")) {
if (this.port < 0 || this.port == 443) { defaultPort = true; }
}
- String path = resolveBackpath(this.getFile(includeReference));
+ final String path = resolveBackpath(this.getFile(includeReference));
if (defaultPort) {
return this.protocol + "://" +
@@ -568,7 +568,7 @@ public class yacyURL implements Serializable {
this.getHost().toLowerCase() + ((defaultPort) ? ("") : (":" + this.port)) + path;
}
- public boolean equals(yacyURL other) {
+ public boolean equals(final yacyURL other) {
return (((this.protocol == other.protocol) || (this.protocol.equals(other.protocol))) &&
((this.host == other.host ) || (this.host.equals(other.host))) &&
((this.userInfo == other.userInfo) || (this.userInfo.equals(other.userInfo))) &&
@@ -588,7 +588,7 @@ public class yacyURL implements Serializable {
return this.toNormalform(true, false).hashCode();
}
- public int compareTo(Object h) {
+ public int compareTo(final Object h) {
assert (h instanceof yacyURL);
return this.toString().compareTo(((yacyURL) h).toString());
}
@@ -598,7 +598,7 @@ public class yacyURL implements Serializable {
}
public boolean isCGI() {
- String ls = path.toLowerCase();
+ final String ls = path.toLowerCase();
return ((ls.indexOf(".cgi") >= 0) ||
(ls.indexOf(".exe") >= 0) ||
(ls.indexOf(";jsessionid=") >= 0) ||
@@ -610,15 +610,15 @@ public class yacyURL implements Serializable {
// static methods from plasmaURL
- public static final int flagTypeID(String hash) {
+ public static final int flagTypeID(final String hash) {
return (kelondroBase64Order.enhancedCoder.decodeByte(hash.charAt(11)) & 32) >> 5;
}
- public static final int flagTLDID(String hash) {
+ public static final int flagTLDID(final String hash) {
return (kelondroBase64Order.enhancedCoder.decodeByte(hash.charAt(11)) & 28) >> 2;
}
- public static final int flagLengthID(String hash) {
+ public static final int flagLengthID(final String hash) {
return (kelondroBase64Order.enhancedCoder.decodeByte(hash.charAt(11)) & 3);
}
@@ -634,8 +634,8 @@ public class yacyURL implements Serializable {
assert this.hash == null; // should only be called if the hash was not computed bevore
- int id = serverDomains.getDomainID(this.host); // id=7: tld is local
- boolean isHTTP = this.protocol.equals("http");
+ final int id = serverDomains.getDomainID(this.host); // id=7: tld is local
+ final boolean isHTTP = this.protocol.equals("http");
int p = this.host.lastIndexOf('.');
String dom = (p > 0) ? dom = host.substring(0, p) : "";
p = dom.lastIndexOf('.'); // locate subdomain
@@ -659,12 +659,12 @@ public class yacyURL implements Serializable {
// we collected enough information to compute the fragments that are
// basis for hashes
- int l = dom.length();
- int domlengthKey = (l <= 8) ? 0 : (l <= 12) ? 1 : (l <= 16) ? 2 : 3;
- byte flagbyte = (byte) (((isHTTP) ? 0 : 32) | (id << 2) | domlengthKey);
+ final int l = dom.length();
+ final int domlengthKey = (l <= 8) ? 0 : (l <= 12) ? 1 : (l <= 16) ? 2 : 3;
+ final byte flagbyte = (byte) (((isHTTP) ? 0 : 32) | (id << 2) | domlengthKey);
// combine the attributes
- StringBuffer hash = new StringBuffer(12);
+ final StringBuffer hash = new StringBuffer(12);
// form the 'local' part of the hash
hash.append(kelondroBase64Order.enhancedCoder.encode(serverCodings.encodeMD5Raw(toNormalform(true, true))).substring(0, 5)); // 5 chars
hash.append(subdomPortPath(subdom, port, rootpath)); // 1 char
@@ -676,35 +676,35 @@ public class yacyURL implements Serializable {
return new String(hash);
}
- private static char subdomPortPath(String subdom, int port, String rootpath) {
+ private static char subdomPortPath(final String subdom, final int port, final String rootpath) {
return kelondroBase64Order.enhancedCoder.encode(serverCodings.encodeMD5Raw(subdom + ":" + port + ":" + rootpath)).charAt(0);
}
private static final char rootURLFlag0 = subdomPortPath("", 80, "");
private static final char rootURLFlag1 = subdomPortPath("www", 80, "");
- public static final boolean probablyRootURL(String urlHash) {
+ public static final boolean probablyRootURL(final String urlHash) {
return (urlHash.charAt(5) == rootURLFlag0) || (urlHash.charAt(5) == rootURLFlag1);
}
- private static String protocolHostPort(String protocol, String host, int port) {
+ private static String protocolHostPort(final String protocol, final String host, final int port) {
return kelondroBase64Order.enhancedCoder.encode(serverCodings.encodeMD5Raw(protocol + ":" + host + ":" + port)).substring(0, 5);
}
private static String[] testTLDs = new String[] { "com", "net", "org", "uk", "fr", "de", "es", "it" };
- public static final yacyURL probablyWordURL(String urlHash, TreeSet<String> words) {
- Iterator<String> wi = words.iterator();
+ public static final yacyURL probablyWordURL(final String urlHash, final TreeSet<String> words) {
+ final Iterator<String> wi = words.iterator();
String word;
while (wi.hasNext()) {
word = wi.next();
if ((word == null) || (word.length() == 0)) continue;
- String pattern = urlHash.substring(6, 11);
+ final String pattern = urlHash.substring(6, 11);
for (int i = 0; i < testTLDs.length; i++) {
if (pattern.equals(protocolHostPort("http", "www." + word.toLowerCase() + "." + testTLDs[i], 80)))
try {
return new yacyURL("http://www." + word.toLowerCase() + "." + testTLDs[i], null);
- } catch (MalformedURLException e) {
+ } catch (final MalformedURLException e) {
return null;
}
}
@@ -712,20 +712,20 @@ public class yacyURL implements Serializable {
return null;
}
- public static final boolean isWordRootURL(String givenURLHash, TreeSet<String> words) {
+ public static final boolean isWordRootURL(final String givenURLHash, final TreeSet<String> words) {
if (!(probablyRootURL(givenURLHash))) return false;
- yacyURL wordURL = probablyWordURL(givenURLHash, words);
+ final yacyURL wordURL = probablyWordURL(givenURLHash, words);
if (wordURL == null) return false;
if (wordURL.hash().equals(givenURLHash)) return true;
return false;
}
- public static final int domLengthEstimation(String urlHash) {
+ public static final int domLengthEstimation(final String urlHash) {
// generates an estimation of the original domain length
assert (urlHash != null);
assert (urlHash.length() == 12) : "urlhash = " + urlHash;
- int flagbyte = kelondroBase64Order.enhancedCoder.decodeByte(urlHash.charAt(11));
- int domLengthKey = flagbyte & 3;
+ final int flagbyte = kelondroBase64Order.enhancedCoder.decodeByte(urlHash.charAt(11));
+ final int domLengthKey = flagbyte & 3;
switch (domLengthKey) {
case 0:
return 4;
@@ -739,22 +739,22 @@ public class yacyURL implements Serializable {
return 20;
}
- public static int domLengthNormalized(String urlHash) {
+ public static int domLengthNormalized(final String urlHash) {
return domLengthEstimation(urlHash) << 8 / 20;
}
- public static final int domDomain(String urlHash) {
+ public static final int domDomain(final String urlHash) {
// returns the ID of the domain of the domain
assert (urlHash != null);
assert (urlHash.length() == 12) : "urlhash = " + urlHash;
return (kelondroBase64Order.enhancedCoder.decodeByte(urlHash.charAt(11)) & 28) >> 2;
}
- public static boolean isDomDomain(String urlHash, int id) {
+ public static boolean isDomDomain(final String urlHash, final int id) {
return domDomain(urlHash) == id;
}
- public static boolean matchesAnyDomDomain(String urlHash, int idset) {
+ public static boolean matchesAnyDomDomain(final String urlHash, final int idset) {
// this is a boolean matching on a set of domDomains
return (domDomain(urlHash) | idset) != 0;
}
@@ -771,16 +771,16 @@ public class yacyURL implements Serializable {
}
// language calculation
- public static String language(yacyURL url) {
+ public static String language(final yacyURL url) {
String language = "uk";
- String host = url.getHost();
- int pos = host.lastIndexOf(".");
+ final String host = url.getHost();
+ final int pos = host.lastIndexOf(".");
if ((pos > 0) && (host.length() - pos == 3)) language = host.substring(pos + 1).toLowerCase();
return language;
}
- public static void main(String[] args) {
- String[][] test = new String[][]{
+ public static void main(final String[] args) {
+ final String[][] test = new String[][]{
new String[]{null, "http://www.anomic.de/home/test?x=1#home"},
new String[]{null, "http://www.anomic.de/home/test?x=1"},
new String[]{null, "http://www.anomic.de/home/test#home"},
@@ -813,11 +813,11 @@ public class yacyURL implements Serializable {
for (int i = 0; i < test.length; i++) {
environment = test[i][0];
url = test[i][1];
- try {aURL = yacyURL.newURL(environment, url);} catch (MalformedURLException e) {aURL = null;}
+ try {aURL = yacyURL.newURL(environment, url);} catch (final MalformedURLException e) {aURL = null;}
if (environment == null) {
- try {jURL = new java.net.URL(url);} catch (MalformedURLException e) {jURL = null;}
+ try {jURL = new java.net.URL(url);} catch (final MalformedURLException e) {jURL = null;}
} else {
- try {jURL = new java.net.URL(new java.net.URL(environment), url);} catch (MalformedURLException e) {jURL = null;}
+ try {jURL = new java.net.URL(new java.net.URL(environment), url);} catch (final MalformedURLException e) {jURL = null;}
}
// check equality to java.net.URL
@@ -837,7 +837,7 @@ public class yacyURL implements Serializable {
System.out.println("aURL0=" + aURL.toString());
System.out.println("aURL1=" + aURL1.toString());
}
- } catch (MalformedURLException e) {
+ } catch (final MalformedURLException e) {
System.out.println("no stability for url:");
System.out.println("aURL0=" + aURL.toString());
System.out.println("aURL1 cannot be computed:" + e.getMessage());
diff --git a/source/de/anomic/yacy/yacyVersion.java b/source/de/anomic/yacy/yacyVersion.java
index fee6e068a..d54d7729b 100644
--- a/source/de/anomic/yacy/yacyVersion.java
+++ b/source/de/anomic/yacy/yacyVersion.java
@@ -84,7 +84,7 @@ public final class yacyVersion implements Comparator<yacyVersion>, Comparable<ya
public yacyURL url;
public String name;
- public yacyVersion(yacyURL url) {
+ public yacyVersion(final yacyURL url) {
this(url.getFileName());
this.url = url;
}
@@ -113,13 +113,13 @@ public final class yacyVersion implements Comparator<yacyVersion>, Comparable<ya
}
// now all release names have the form
// ${releaseVersion}_${DSTAMP}_${releaseNr}
- String[] comp = release.split("_"); // should be 3 parts
+ final String[] comp = release.split("_"); // should be 3 parts
if (comp.length != 3) {
throw new RuntimeException("release file name '" + release + "' is not valid, 3 information parts expected");
}
try {
this.releaseNr = Float.parseFloat(comp[0]);
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
throw new RuntimeException("release file name '" + release + "' is not valid, '" + comp[0] + "' should be a float number");
}
this.mainRelease = ((int) (this.releaseNr * 1000)) % 10 == 0;
@@ -130,7 +130,7 @@ public final class yacyVersion implements Comparator<yacyVersion>, Comparable<ya
}
try {
this.svn = Integer.parseInt(comp[2]);
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
throw new RuntimeException("release file name '" + release + "' is not valid, '" + comp[2] + "' should be a integer number");
}
// finished! we parsed a relase string
@@ -138,27 +138,27 @@ public final class yacyVersion implements Comparator<yacyVersion>, Comparable<ya
public static final class DevMain {
public TreeSet<yacyVersion> dev, main;
- public DevMain(TreeSet<yacyVersion> dev, TreeSet<yacyVersion> main) {
+ public DevMain(final TreeSet<yacyVersion> dev, final TreeSet<yacyVersion> main) {
this.dev = dev;
this.main = main;
}
}
- public int compareTo(yacyVersion obj) {
+ public int compareTo(final yacyVersion obj) {
// returns 0 if this object is equal to the obj, -1 if this is smaller than obj and 1 if this is greater than obj
return compare(this, obj);
}
- public int compare(yacyVersion v0, yacyVersion v1) {
+ public int compare(final yacyVersion v0, final yacyVersion v1) {
// compare-operator for two yacyVersion objects
// must be implemented to make it possible to put this object into
// a ordered structure, like TreeSet or TreeMap
return (new Integer(v0.svn)).compareTo(new Integer(v1.svn));
}
- public boolean equals(Object obj) {
+ public boolean equals(final Object obj) {
if(obj instanceof yacyVersion) {
- yacyVersion v = (yacyVersion) obj;
+ final yacyVersion v = (yacyVersion) obj;
return (this.svn == v.svn) && (this.url.toNormalform(true, true).equals(v.url.toNormalform(true, true)));
} else {
return false;
@@ -179,9 +179,9 @@ public final class yacyVersion implements Comparator<yacyVersion>, Comparable<ya
public static final yacyVersion thisVersion() {
// construct a virtual release name for this release
if (thisVersion == null) {
- plasmaSwitchboard sb = plasmaSwitchboard.getSwitchboard();
+ final plasmaSwitchboard sb = plasmaSwitchboard.getSwitchboard();
if (sb == null) return null;
- boolean full = new File(sb.getRootPath(), "libx").exists();
+ final boolean full = new File(sb.getRootPath(), "libx").exists();
thisVersion = new yacyVersion(
"yacy" + ((full) ? "" : "_emb") +
"_v" + sb.getConfig("version", "0.1") + "_" +
@@ -191,33 +191,33 @@ public final class yacyVersion implements Comparator<yacyVersion>, Comparable<ya
return thisVersion;
}
- public static final yacyVersion rulebasedUpdateInfo(boolean manual) {
+ public static final yacyVersion rulebasedUpdateInfo(final boolean manual) {
// according to update properties, decide if we should retrieve update information
// if true, the release that can be obtained is returned.
// if false, null is returned
- plasmaSwitchboard sb = plasmaSwitchboard.getSwitchboard();
+ final plasmaSwitchboard sb = plasmaSwitchboard.getSwitchboard();
// check if update process allows update retrieve
- String process = sb.getConfig("update.process", "manual");
+ final String process = sb.getConfig("update.process", "manual");
if ((!manual) && (!process.equals("auto"))) {
yacyCore.log.logInfo("rulebasedUpdateInfo: not an automatic update selected");
return null; // no, its a manual or guided process
}
// check if the last retrieve time is a minimum time ago
- long cycle = Math.max(1, sb.getConfigLong("update.cycle", 168)) * 60 * 60 * 1000; // update.cycle is hours
- long timeLookup = sb.getConfigLong("update.time.lookup", System.currentTimeMillis());
+ final long cycle = Math.max(1, sb.getConfigLong("update.cycle", 168)) * 60 * 60 * 1000; // update.cycle is hours
+ final long timeLookup = sb.getConfigLong("update.time.lookup", System.currentTimeMillis());
if ((!manual) && (timeLookup + cycle > System.currentTimeMillis())) {
yacyCore.log.logInfo("rulebasedUpdateInfo: too early for a lookup for a new release (timeLookup = " + timeLookup + ", cycle = " + cycle + ", now = " + System.currentTimeMillis() + ")");
return null; // no we have recently made a lookup
}
// check if we know that there is a release that is more recent than that which we are using
- DevMain releasess = yacyVersion.allReleases(true);
- yacyVersion latestmain = (releasess.main.size() == 0) ? null : releasess.main.last();
- yacyVersion latestdev = (releasess.dev.size() == 0) ? null : releasess.dev.last();
- String concept = sb.getConfig("update.concept", "any");
- String blacklist = sb.getConfig("update.blacklist", ".\\...[123]");
+ final DevMain releasess = yacyVersion.allReleases(true);
+ final yacyVersion latestmain = (releasess.main.size() == 0) ? null : releasess.main.last();
+ final yacyVersion latestdev = (releasess.dev.size() == 0) ? null : releasess.dev.last();
+ final String concept = sb.getConfig("update.concept", "any");
+ final String blacklist = sb.getConfig("update.blacklist", ".\\...[123]");
if ((manual) || (concept.equals("any"))) {
// return a dev-release or a main-release
@@ -269,21 +269,21 @@ public final class yacyVersion implements Comparator<yacyVersion>, Comparable<ya
return null;
}
- public static DevMain allReleases(boolean force) {
+ public static DevMain allReleases(final boolean force) {
// join the release infos
- DevMain[] a = new DevMain[latestReleaseLocations.size()];
+ final DevMain[] a = new DevMain[latestReleaseLocations.size()];
for (int j = 0; j < latestReleaseLocations.size(); j++) {
a[j] = getReleases(latestReleaseLocations.get(j), force);
}
- TreeSet<yacyVersion> alldev = new TreeSet<yacyVersion>();
- TreeSet<yacyVersion> allmain = new TreeSet<yacyVersion>();
+ final TreeSet<yacyVersion> alldev = new TreeSet<yacyVersion>();
+ final TreeSet<yacyVersion> allmain = new TreeSet<yacyVersion>();
for (int j = 0; j < a.length; j++) if ((a[j] != null) && (a[j].dev != null)) alldev.addAll(a[j].dev);
for (int j = 0; j < a.length; j++) if ((a[j] != null) && (a[j].main != null)) allmain.addAll(a[j].main);
return new DevMain(alldev, allmain);
}
- private static DevMain getReleases(yacyURL location, boolean force) {
+ private static DevMain getReleases(final yacyURL location, final boolean force) {
// get release info from a internet resource
DevMain locLatestRelease = latestReleases.get(location);
if (force ||
@@ -306,15 +306,15 @@ public final class yacyVersion implements Comparator<yacyVersion>, Comparable<ya
htmlFilterContentScraper scraper;
try {
scraper = htmlFilterContentScraper.parseResource(url);
- } catch (IOException e) {
+ } catch (final IOException e) {
return null;
}
// analyse links in scraper resource, and find link to latest release in it
- Map<yacyURL, String> anchors = scraper.getAnchors(); // a url (String) / name (String) relation
- Iterator<yacyURL> i = anchors.keySet().iterator();
- TreeSet<yacyVersion> devreleases = new TreeSet<yacyVersion>();
- TreeSet<yacyVersion> mainreleases = new TreeSet<yacyVersion>();
+ final Map<yacyURL, String> anchors = scraper.getAnchors(); // a url (String) / name (String) relation
+ final Iterator<yacyURL> i = anchors.keySet().iterator();
+ final TreeSet<yacyVersion> devreleases = new TreeSet<yacyVersion>();
+ final TreeSet<yacyVersion> mainreleases = new TreeSet<yacyVersion>();
yacyVersion release;
while (i.hasNext()) {
url = i.next();
@@ -323,7 +323,7 @@ public final class yacyVersion implements Comparator<yacyVersion>, Comparable<ya
//System.out.println("r " + release.toAnchor());
if ( release.mainRelease) mainreleases.add(release);
if (!release.mainRelease) devreleases.add(release);
- } catch (RuntimeException e) {
+ } catch (final RuntimeException e) {
// the release string was not well-formed.
// that might have been another link
// just dont care
@@ -334,18 +334,18 @@ public final class yacyVersion implements Comparator<yacyVersion>, Comparable<ya
return new DevMain(devreleases, mainreleases);
}
- public static File downloadRelease(yacyVersion release) {
- File storagePath = plasmaSwitchboard.getSwitchboard().releasePath;
+ public static File downloadRelease(final yacyVersion release) {
+ final File storagePath = plasmaSwitchboard.getSwitchboard().releasePath;
// load file
File download = null;
- httpHeader header = new httpHeader();
+ final httpHeader header = new httpHeader();
header.put(httpHeader.USER_AGENT, HTTPLoader.yacyUserAgent);
- JakartaCommonsHttpClient client = new JakartaCommonsHttpClient(120000, header, null);
+ final JakartaCommonsHttpClient client = new JakartaCommonsHttpClient(120000, header, null);
JakartaCommonsHttpResponse res = null;
- String name = release.url.getFileName();
+ final String name = release.url.getFileName();
try {
res = client.GET(release.url.toString());
- boolean unzipped = res.getResponseHeader().gzip() && (res.getResponseHeader().mime().toLowerCase().equals("application/x-tar")); // if true, then the httpc has unzipped the file
+ final boolean unzipped = res.getResponseHeader().gzip() && (res.getResponseHeader().mime().toLowerCase().equals("application/x-tar")); // if true, then the httpc has unzipped the file
if ((unzipped) && (name.endsWith(".tar.gz"))) {
download = new File(storagePath, name.substring(0, name.length() - 3));
} else {
@@ -357,7 +357,7 @@ public final class yacyVersion implements Comparator<yacyVersion>, Comparable<ya
res.closeStream();
}
if ((!download.exists()) || (download.length() == 0)) throw new IOException("wget of url " + release.url + " failed");
- } catch (IOException e) {
+ } catch (final IOException e) {
serverLog.logSevere("yacyVersion", "download of " + release.name + " failed: " + e.getMessage());
if (download != null && download.exists()) download.delete();
download = null;
@@ -373,17 +373,17 @@ public final class yacyVersion implements Comparator<yacyVersion>, Comparable<ya
public static void restart() {
- plasmaSwitchboard sb = plasmaSwitchboard.getSwitchboard();
- String apphome = sb.getRootPath().toString();
+ final plasmaSwitchboard sb = plasmaSwitchboard.getSwitchboard();
+ final String apphome = sb.getRootPath().toString();
if (serverSystem.isWindows) {
- File startType = new File(sb.getRootPath(), "DATA/yacy.noconsole".replace("/", File.separator));
+ final File startType = new File(sb.getRootPath(), "DATA/yacy.noconsole".replace("/", File.separator));
String starterFile = "startYACY_debug.bat";
if (startType.exists()) starterFile = "startYACY.bat"; // startType noconsole
try{
serverLog.logInfo("RESTART", "INITIATED");
- String script =
+ final String script =
"@echo off" + serverCore.LF_STRING +
"title YaCy restarter" + serverCore.LF_STRING +
"echo YACY RESTARTER" + serverCore.LF_STRING +
@@ -394,13 +394,13 @@ public final class yacyVersion implements Comparator<yacyVersion>, Comparable<ya
"IF exist ..\\yacy.running goto WAIT" + serverCore.LF_STRING +
"cd " + apphome + serverCore.LF_STRING +
"start /MIN CMD /C " + starterFile + serverCore.LF_STRING;
- File scriptFile = new File(sb.getRootPath(), "DATA/RELEASE/restart.bat".replace("/", File.separator));
+ final File scriptFile = new File(sb.getRootPath(), "DATA/RELEASE/restart.bat".replace("/", File.separator));
serverSystem.deployScript(scriptFile, script);
serverLog.logInfo("RESTART", "wrote restart-script to " + scriptFile.getAbsolutePath());
serverSystem.execAsynchronous(scriptFile);
serverLog.logInfo("RESTART", "script is running");
sb.terminate(5000);
- } catch (IOException e) {
+ } catch (final IOException e) {
serverLog.logSevere("RESTART", "restart failed", e);
}
@@ -421,7 +421,7 @@ public final class yacyVersion implements Comparator<yacyVersion>, Comparable<ya
// start a re-start daemon
try {
serverLog.logInfo("RESTART", "INITIATED");
- String script =
+ final String script =
"#!/bin/sh" + serverCore.LF_STRING +
"cd " + sb.getRootPath() + "/DATA/RELEASE/" + serverCore.LF_STRING +
"while [ -f ../yacy.running ]; do" + serverCore.LF_STRING +
@@ -429,33 +429,33 @@ public final class yacyVersion implements Comparator<yacyVersion>, Comparable<ya
"done" + serverCore.LF_STRING +
"cd ../../" + serverCore.LF_STRING +
"nohup ./startYACY.sh > /dev/null" + serverCore.LF_STRING;
- File scriptFile = new File(sb.getRootPath(), "DATA/RELEASE/restart.sh");
+ final File scriptFile = new File(sb.getRootPath(), "DATA/RELEASE/restart.sh");
serverSystem.deployScript(scriptFile, script);
serverLog.logInfo("RESTART", "wrote restart-script to " + scriptFile.getAbsolutePath());
serverSystem.execAsynchronous(scriptFile);
serverLog.logInfo("RESTART", "script is running");
sb.terminate(5000);
- } catch (IOException e) {
+ } catch (final IOException e) {
serverLog.logSevere("RESTART", "restart failed", e);
}
}
}
- public static void deployRelease(File releaseFile) {
+ public static void deployRelease(final File releaseFile) {
//byte[] script = ("cd " + plasmaSwitchboard.getSwitchboard().getRootPath() + ";while [ -e ../yacy.running ]; do sleep 1;done;tar xfz " + release + ";cp -Rf yacy/* ../../;rm -Rf yacy;cd ../../;startYACY.sh").getBytes();
try {
- plasmaSwitchboard sb = plasmaSwitchboard.getSwitchboard();
- String apphome = sb.getRootPath().toString();
+ final plasmaSwitchboard sb = plasmaSwitchboard.getSwitchboard();
+ final String apphome = sb.getRootPath().toString();
serverLog.logInfo("UPDATE", "INITIATED");
try{
tarTools.unTar(tarTools.getInputStream(releaseFile), sb.getRootPath() + "/DATA/RELEASE/".replace("/", File.separator));
- } catch (Exception e){
+ } catch (final Exception e){
serverLog.logSevere("UNTAR", "failed", e);
}
String script = null;
String scriptFileName = null;
if(serverSystem.isWindows){
- File startType = new File(sb.getRootPath(), "DATA/yacy.noconsole".replace("/", File.separator));
+ final File startType = new File(sb.getRootPath(), "DATA/yacy.noconsole".replace("/", File.separator));
String starterFile = "startYACY_debug.bat";
if (startType.exists()) starterFile = "startYACY.bat"; // startType noconsole
script =
@@ -519,14 +519,14 @@ public final class yacyVersion implements Comparator<yacyVersion>, Comparable<ya
"nohup ./startYACY.sh > /dev/null" + serverCore.LF_STRING;
scriptFileName = "update.sh";
}
- File scriptFile = new File(sb.getRootPath(), "DATA/RELEASE/".replace("/", File.separator) + scriptFileName);
+ final File scriptFile = new File(sb.getRootPath(), "DATA/RELEASE/".replace("/", File.separator) + scriptFileName);
serverSystem.deployScript(scriptFile, script);
serverLog.logInfo("UPDATE", "wrote update-script to " + scriptFile.getAbsolutePath());
serverSystem.execAsynchronous(scriptFile);
serverLog.logInfo("UPDATE", "script is running");
sb.setConfig("update.time.deploy", System.currentTimeMillis());
sb.terminate(5000);
- } catch (IOException e) {
+ } catch (final IOException e) {
serverLog.logSevere("UPDATE", "update failed", e);
}
}
@@ -540,10 +540,10 @@ public final class yacyVersion implements Comparator<yacyVersion>, Comparable<ya
* If the major version is &gt;= 0.11 - major version is replaced by "dev" and separated SVN-version by '/', e.g."dev/01818" <br>
* "dev/00000" - If the input does not matcht the regular expression above
*/
- public static String combined2prettyVersion(String ver) {
+ public static String combined2prettyVersion(final String ver) {
return combined2prettyVersion(ver, "");
}
- public static String combined2prettyVersion(String ver, String computerName) {
+ public static String combined2prettyVersion(final String ver, final String computerName) {
final Matcher matcher = Pattern.compile("\\A(\\d+\\.\\d{1,3})(\\d{0,5})\\z").matcher(ver);
if (!matcher.find()) {
@@ -551,7 +551,7 @@ public final class yacyVersion implements Comparator<yacyVersion>, Comparable<ya
return "dev/00000";
}
- String mainversion = (Double.parseDouble(matcher.group(1)) < 0.11 ? "dev" : matcher.group(1));
+ final String mainversion = (Double.parseDouble(matcher.group(1)) < 0.11 ? "dev" : matcher.group(1));
String revision = matcher.group(2);
for(int i=revision.length();i<5;++i) revision += "0";
return mainversion+"/"+revision;
@@ -565,14 +565,14 @@ public final class yacyVersion implements Comparator<yacyVersion>, Comparable<ya
* @param svn Current version given from SVN.
* @return String with the combined version.
*/
- public static double versvn2combinedVersion(double version, int svn) {
+ public static double versvn2combinedVersion(final double version, final int svn) {
return (Math.rint((version*100000000.0) + (svn))/100000000);
}
- public static void main(String[] args) {
+ public static void main(final String[] args) {
System.out.println(thisVersion());
- float base = (float) 0.53;
- String blacklist = "....[123]";
+ final float base = (float) 0.53;
+ final String blacklist = "....[123]";
String test;
for (int i = 0; i < 20; i++) {
test = Float.toString(base + (((float) i) / 1000));
@@ -586,18 +586,18 @@ public final class yacyVersion implements Comparator<yacyVersion>, Comparable<ya
* @param filesPath where all downloaded files reside
* @param deleteAfterDays
*/
- public static void deleteOldDownloads(File filesPath, int deleteAfterDays) {
+ public static void deleteOldDownloads(final File filesPath, final int deleteAfterDays) {
// list downloaded releases
yacyVersion release;
- String[] downloaded = filesPath.list();
+ final String[] downloaded = filesPath.list();
// parse all filenames and put them in a sorted set
- SortedSet<yacyVersion> downloadedreleases = new TreeSet<yacyVersion>();
+ final SortedSet<yacyVersion> downloadedreleases = new TreeSet<yacyVersion>();
for (int j = 0; j < downloaded.length; j++) {
try {
release = new yacyVersion(downloaded[j]);
downloadedreleases.add(release);
- } catch (RuntimeException e) {
+ } catch (final RuntimeException e) {
// not a valid release
}
}
@@ -610,10 +610,10 @@ public final class yacyVersion implements Comparator<yacyVersion>, Comparable<ya
final yacyVersion latest = downloadedreleases.last();
downloadedreleases.remove(latest);
// if latest is a developer release, we also keep a main release
- boolean keepMain = !latest.mainRelease;
+ final boolean keepMain = !latest.mainRelease;
// remove old files
- long now = System.currentTimeMillis();
+ final long now = System.currentTimeMillis();
final long deleteAfterMillis = deleteAfterDays * 24 * 60 * 60000l;
String lastMain = null;
@@ -629,7 +629,7 @@ public final class yacyVersion implements Comparator<yacyVersion>, Comparable<ya
}
// check file age
- File downloadedFile = new File(filesPath + File.separator + filename);
+ final File downloadedFile = new File(filesPath + File.separator + filename);
if (now - downloadedFile.lastModified() > deleteAfterMillis) {
// delete file
if (!downloadedFile.delete()) {
diff --git a/source/de/anomic/ymage/AnimGifEncoder.java b/source/de/anomic/ymage/AnimGifEncoder.java
index b4b224457..8c9952940 100644
--- a/source/de/anomic/ymage/AnimGifEncoder.java
+++ b/source/de/anomic/ymage/AnimGifEncoder.java
@@ -75,13 +75,13 @@ public class AnimGifEncoder {
private boolean m_default_interlace = false;
/** The default delay time, */
- private int m_default_delay = 100;
+ private final int m_default_delay = 100;
/** Set when looping the set is requested. */
private boolean m_loop = true;
/** The outputstream to write the image to. */
- private OutputStream m_os;
+ private final OutputStream m_os;
/** The (current) list of images to embed in the GIF */
private ArrayList<AnIma> m_ima_ar;
@@ -107,14 +107,14 @@ public class AnimGifEncoder {
/**
* This constructor creates an empty default codec.
*/
- public AnimGifEncoder(OutputStream os) {
+ public AnimGifEncoder(final OutputStream os) {
m_os = os;
}
/**
* Creates a codec and specify interlace (not implemented yet).
*/
- public AnimGifEncoder(OutputStream os, boolean interlace) {
+ public AnimGifEncoder(final OutputStream os, final boolean interlace) {
m_os = os;
m_default_interlace = interlace;
}
@@ -130,7 +130,7 @@ public class AnimGifEncoder {
* specified.
* </p>
*/
- public void setLoop(boolean loop) {
+ public void setLoop(final boolean loop) {
m_loop = loop;
}
@@ -161,8 +161,8 @@ public class AnimGifEncoder {
* is released, and only the pixelset remains until the encode call is
* made. Calling encode will release the pixelset.
*/
- public void add(Image ima, int delaytime, boolean interlace, int px, int py) throws IOException {
- AnIma ai = new AnIma();
+ public void add(final Image ima, final int delaytime, final boolean interlace, final int px, final int py) throws IOException {
+ final AnIma ai = new AnIma();
ai.m_delay = delaytime;
ai.m_interlace = interlace;
ai.m_x = px;
@@ -188,14 +188,14 @@ public class AnimGifEncoder {
/**
* Adds the specified image to the list of images.
*/
- public void add(Image ima) throws IOException {
+ public void add(final Image ima) throws IOException {
add(ima, m_ima_ar == null ? 0 : m_default_delay, m_default_interlace, 0, 0);
}
/**
* Adds the specified image to the list of images.
*/
- public void add(Image ima, int delay) throws IOException {
+ public void add(final Image ima, final int delay) throws IOException {
add(ima, delay, m_default_interlace, 0, 0);
}
@@ -205,17 +205,17 @@ public class AnimGifEncoder {
/**
* Writes a string as a #of bytes to the output stream.
*/
- private void utStr(String str) throws IOException {
- byte[] buf = str.getBytes();
+ private void utStr(final String str) throws IOException {
+ final byte[] buf = str.getBytes();
m_os.write( buf );
}
- private void utWord(int val) throws IOException {
+ private void utWord(final int val) throws IOException {
utByte( (byte) ( val & 0xff));
utByte( (byte) (( val >> 8 ) & 0xff ));
}
- private void utByte(byte b) throws IOException {
+ private void utByte(final byte b) throws IOException {
m_os.write( b );
}
@@ -243,7 +243,7 @@ public class AnimGifEncoder {
* table and the complete output size.
*/
for (int i = 0; i < m_ima_ar.size(); i++) {
- AnIma ai = m_ima_ar.get(i);
+ final AnIma ai = m_ima_ar.get(i);
genImage(ai);
ai.m_rgb = null;
}
@@ -282,7 +282,7 @@ public class AnimGifEncoder {
* stored it throws a too many colors exception.
* The function returns the index code for the color.
*/
- private short findColorIndex(int color) throws IOException {
+ private short findColorIndex(final int color) throws IOException {
//-- 1. Primary hash..
int i = (color & 0x7fffffff) % CHSIZE;
@@ -293,7 +293,7 @@ public class AnimGifEncoder {
if(m_ccolor_ar[i] != 0) // Bucket is full?
{
//-- This was a clash. Locate a new bucket & look for another match!
- int disp = CHSIZE - i;
+ final int disp = CHSIZE - i;
do
{
i -= disp;
@@ -318,7 +318,7 @@ public class AnimGifEncoder {
* Checks if the image lies in the current complete image, else it extends
* the source image.
*/
- private void checkTotalSize(AnIma ai) {
+ private void checkTotalSize(final AnIma ai) {
int t;
t = ai.m_w + ai.m_x; // Get end-X of image,
@@ -343,7 +343,7 @@ public class AnimGifEncoder {
* the image, and an 8-bit "image" containing, for each pixel, the index
* into that color table. They also set the transparant color to use.
*/
- private void preCode(AnIma ai, Image ima) throws IOException {
+ private void preCode(final AnIma ai, final Image ima) throws IOException {
//-- Call the appropriate encoder depending on the image type.
if(ima instanceof BufferedImage)
precodeBuffered(ai, (BufferedImage) ima);
@@ -357,7 +357,7 @@ public class AnimGifEncoder {
* decoder. If the image is not implemented we fall back to the generic
* method.
*/
- private void precodeBuffered(AnIma ai, BufferedImage bi) throws IOException {
+ private void precodeBuffered(final AnIma ai, final BufferedImage bi) throws IOException {
//-- 1. Handle all shared tasks...
ai.m_w = bi.getWidth();
ai.m_h = bi.getHeight();
@@ -366,7 +366,7 @@ public class AnimGifEncoder {
//-- 2. Optimize for known types...
boolean done= false;
- int bt = bi.getType();
+ final int bt = bi.getType();
switch(bt)
{
case BufferedImage.TYPE_BYTE_INDEXED: done = precodeByteIndexed(ai, bi); break;
@@ -382,11 +382,11 @@ public class AnimGifEncoder {
precodeImage(ai, bi);
}
- private int getBiOffset(Raster ras, PixelInterleavedSampleModel sm, int x, int y) {
+ private int getBiOffset(final Raster ras, final PixelInterleavedSampleModel sm, final int x, final int y) {
return (y-ras.getSampleModelTranslateY()) * sm.getScanlineStride() + x-ras.getSampleModelTranslateX();
}
- private int getBiOffset(Raster ras, SinglePixelPackedSampleModel sm, int x, int y) {
+ private int getBiOffset(final Raster ras, final SinglePixelPackedSampleModel sm, final int x, final int y) {
return (y-ras.getSampleModelTranslateY()) * sm.getScanlineStride() + x-ras.getSampleModelTranslateX();
}
@@ -396,24 +396,24 @@ public class AnimGifEncoder {
/**
* Encodes TYPE_BYTE_INDEXED images.
*/
- private boolean precodeByteIndexed(AnIma ai, BufferedImage bi) throws IOException {
+ private boolean precodeByteIndexed(final AnIma ai, final BufferedImage bi) throws IOException {
//-- Get the colormodel, the raster, the databuffer and the samplemodel
- ColorModel tcm = bi.getColorModel();
+ final ColorModel tcm = bi.getColorModel();
if(! (tcm instanceof IndexColorModel)) return false;
- IndexColorModel cm = (IndexColorModel) tcm;
+ final IndexColorModel cm = (IndexColorModel) tcm;
- Raster ras = bi.getRaster();
- SampleModel tsm = ras.getSampleModel();
+ final Raster ras = bi.getRaster();
+ final SampleModel tsm = ras.getSampleModel();
if(! (tsm instanceof PixelInterleavedSampleModel)) return false;
- PixelInterleavedSampleModel sm = (PixelInterleavedSampleModel) tsm;
+ final PixelInterleavedSampleModel sm = (PixelInterleavedSampleModel) tsm;
- DataBuffer dbt = ras.getDataBuffer();
+ final DataBuffer dbt = ras.getDataBuffer();
if(dbt.getDataType() != DataBuffer.TYPE_BYTE) return false;
if(dbt.getNumBanks() != 1) return false;
- DataBufferByte db = (DataBufferByte) dbt;
+ final DataBufferByte db = (DataBufferByte) dbt;
//-- Prepare the color mapping
- short[] map = new short[256]; // Alternate lookup table
+ final short[] map = new short[256]; // Alternate lookup table
for(int i = 0; i < 256; i++) // Set all entries to unused,
map[i] = -1;
@@ -423,23 +423,23 @@ public class AnimGifEncoder {
* one. One fun thing: we only have to COPY all pixels, since we're
* already byte-packed.
*/
- int endoff = ai.m_w * ai.m_h; // Output image size,
- byte[] par = new byte[endoff]; // Byte-indexed output array,
+ final int endoff = ai.m_w * ai.m_h; // Output image size,
+ final byte[] par = new byte[endoff]; // Byte-indexed output array,
int doff = 0; // Destination offset,
//-- source
int soff = getBiOffset(ras, sm, 0, 0);
- byte[] px = db.getData(0); // Get the pixelset,
- int esoff = getBiOffset(ras, sm, ai.m_w-1, ai.m_h-1); // calc end offset,
- int iw = sm.getScanlineStride(); // Increment width = databuf's width
+ final byte[] px = db.getData(0); // Get the pixelset,
+ final int esoff = getBiOffset(ras, sm, ai.m_w-1, ai.m_h-1); // calc end offset,
+ final int iw = sm.getScanlineStride(); // Increment width = databuf's width
while(soff < esoff) { // For all scan lines,
- int xe = soff + ai.m_w; // End for this line
+ final int xe = soff + ai.m_w; // End for this line
while(soff < xe) { // While within this line
//-- (continue) collect a run,
- int rs = soff; // Save run start
- byte rcolor = px[soff++]; // First color
+ final int rs = soff; // Save run start
+ final byte rcolor = px[soff++]; // First color
while(soff < xe && px[soff] == rcolor) // Run till eoln or badclor
soff++;
@@ -447,7 +447,7 @@ public class AnimGifEncoder {
short ii = map[rcolor + 0x80];
if (ii == -1){ // Unknown map?
//-- New color. Get it's translated RGB value,
- int rix = rcolor & 0xff; // Translate to unsigned
+ final int rix = rcolor & 0xff; // Translate to unsigned
int rgb = cm.getRGB(rix); // Get RGB value for this input index,
if(rgb >= 0) { // Transparant color?
//-- If there is a transparant color index use it...
@@ -465,8 +465,8 @@ public class AnimGifEncoder {
}
//-- Always write this run.
- int dep = doff + (soff - rs); // End output pos
- byte idx = (byte) ii;
+ final int dep = doff + (soff - rs); // End output pos
+ final byte idx = (byte) ii;
while(doff < dep)
par[doff++] = idx; // Fill output.
}
@@ -485,18 +485,18 @@ public class AnimGifEncoder {
/**
* Encodes INT pixel-packed images.
*/
- private boolean precodeIntPacked(AnIma ai, BufferedImage bi) throws IOException {
+ private boolean precodeIntPacked(final AnIma ai, final BufferedImage bi) throws IOException {
//-- Get the colormodel, the raster, the databuffer and the samplemodel
- ColorModel cm = bi.getColorModel();
- Raster ras = bi.getRaster();
- SampleModel tsm = ras.getSampleModel();
+ final ColorModel cm = bi.getColorModel();
+ final Raster ras = bi.getRaster();
+ final SampleModel tsm = ras.getSampleModel();
if(! (tsm instanceof SinglePixelPackedSampleModel)) return false;
- SinglePixelPackedSampleModel sm = (SinglePixelPackedSampleModel) tsm;
+ final SinglePixelPackedSampleModel sm = (SinglePixelPackedSampleModel) tsm;
- DataBuffer dbt = ras.getDataBuffer();
+ final DataBuffer dbt = ras.getDataBuffer();
if(dbt.getDataType() != DataBuffer.TYPE_INT) return false;
if(dbt.getNumBanks() != 1) return false;
- DataBufferInt db = (DataBufferInt) dbt;
+ final DataBufferInt db = (DataBufferInt) dbt;
/*
* Prepare the run: get all constants e.a. The mechanism runs thru
@@ -504,24 +504,24 @@ public class AnimGifEncoder {
* one. One fun thing: we only have to COPY all pixels, since we're
* already byte-packed.
*/
- int endoff = ai.m_w * ai.m_h; // Output image size,
- byte[] par = new byte[endoff]; // Byte-indexed output array,
+ final int endoff = ai.m_w * ai.m_h; // Output image size,
+ final byte[] par = new byte[endoff]; // Byte-indexed output array,
int doff = 0; // Destination offset,
byte ii;
//-- source
int soff = getBiOffset(ras, sm, 0, 0);
- int[] px = db.getData(0); // Get the pixelset,
- int esoff = getBiOffset(ras, sm, ai.m_w-1, ai.m_h-1); // calc end offset,
- int iw = sm.getScanlineStride(); // Increment width = databuf's width
+ final int[] px = db.getData(0); // Get the pixelset,
+ final int esoff = getBiOffset(ras, sm, ai.m_w-1, ai.m_h-1); // calc end offset,
+ final int iw = sm.getScanlineStride(); // Increment width = databuf's width
while(soff < esoff) { // For all scan lines,
- int xe = soff + ai.m_w; // End for this line
+ final int xe = soff + ai.m_w; // End for this line
while (soff < xe) { // While within this line
//-- (continue) collect a run,
- int rs = soff; // Save run start
- int rcolor = px[soff++]; // First color
+ final int rs = soff; // Save run start
+ final int rcolor = px[soff++]; // First color
while(soff < xe && px[soff] == rcolor) // Run till eoln or badclor
soff++;
@@ -541,7 +541,7 @@ public class AnimGifEncoder {
}
//-- Always write this run.
- int dep = doff + (soff - rs); // End output pos
+ final int dep = doff + (soff - rs); // End output pos
while(doff < dep)
par[doff++] = ii; // Fill output.
}
@@ -561,18 +561,18 @@ public class AnimGifEncoder {
/**
* Encodes SHORT pixel-packed images.
*/
- private boolean precodeShortPacked(AnIma ai, BufferedImage bi) throws IOException {
+ private boolean precodeShortPacked(final AnIma ai, final BufferedImage bi) throws IOException {
//-- Get the colormodel, the raster, the databuffer and the samplemodel
- ColorModel cm = bi.getColorModel();
- Raster ras = bi.getRaster();
- SampleModel tsm = ras.getSampleModel();
+ final ColorModel cm = bi.getColorModel();
+ final Raster ras = bi.getRaster();
+ final SampleModel tsm = ras.getSampleModel();
if(! (tsm instanceof SinglePixelPackedSampleModel)) return false;
- SinglePixelPackedSampleModel sm = (SinglePixelPackedSampleModel) tsm;
+ final SinglePixelPackedSampleModel sm = (SinglePixelPackedSampleModel) tsm;
- DataBuffer dbt = ras.getDataBuffer();
+ final DataBuffer dbt = ras.getDataBuffer();
if(dbt.getDataType() != DataBuffer.TYPE_SHORT) return false;
if(dbt.getNumBanks() != 1) return false;
- DataBufferShort db = (DataBufferShort) dbt;
+ final DataBufferShort db = (DataBufferShort) dbt;
/*
* Prepare the run: get all constants e.a. The mechanism runs thru
@@ -580,25 +580,25 @@ public class AnimGifEncoder {
* one. One fun thing: we only have to COPY all pixels, since we're
* already byte-packed.
*/
- int endoff = ai.m_w * ai.m_h; // Output image size,
- byte[] par = new byte[endoff]; // Byte-indexed output array,
+ final int endoff = ai.m_w * ai.m_h; // Output image size,
+ final byte[] par = new byte[endoff]; // Byte-indexed output array,
int doff = 0; // Destination offset,
byte ii;
//-- source
int soff = getBiOffset(ras, sm, 0, 0);
- short[] px = db.getData(0); // Get the pixelset,
- int esoff = getBiOffset(ras, sm, ai.m_w-1, ai.m_h-1); // calc end offset,
- int iw = sm.getScanlineStride(); // Increment width = databuf's width
+ final short[] px = db.getData(0); // Get the pixelset,
+ final int esoff = getBiOffset(ras, sm, ai.m_w-1, ai.m_h-1); // calc end offset,
+ final int iw = sm.getScanlineStride(); // Increment width = databuf's width
while(soff < esoff) // For all scan lines,
{
- int xe = soff + ai.m_w; // End for this line
+ final int xe = soff + ai.m_w; // End for this line
while(soff < xe) // While within this line
{
//-- (continue) collect a run,
- int rs = soff; // Save run start
- short rcolor = px[soff++]; // First color
+ final int rs = soff; // Save run start
+ final short rcolor = px[soff++]; // First color
while(soff < xe && px[soff] == rcolor) // Run till eoln or badclor
soff++;
@@ -622,7 +622,7 @@ public class AnimGifEncoder {
}
//-- Always write this run.
- int dep = doff + (soff - rs); // End output pos
+ final int dep = doff + (soff - rs); // End output pos
while(doff < dep)
par[doff++] = ii; // Fill output.
}
@@ -644,7 +644,7 @@ public class AnimGifEncoder {
* Using a generic Image, this uses a PixelGrabber to get an integer
* pixel array.
*/
- private void precodeImage(AnIma ai, Image ima) throws IOException {
+ private void precodeImage(final AnIma ai, final Image ima) throws IOException {
int[] px;
//-- Wait for the image to arrive,
@@ -654,7 +654,7 @@ public class AnimGifEncoder {
{
mt.waitForAll(); // Be use all are loaded,
}
- catch(InterruptedException x)
+ catch(final InterruptedException x)
{
throw new IOException("Interrupted load of image");
}
@@ -668,10 +668,10 @@ public class AnimGifEncoder {
checkTotalSize(ai);
//-- Grab pixels & convert to 8-bit pixelset.
- PixelGrabber pg = new PixelGrabber(ima, 0, 0, ai.m_w, ai.m_h, true);
+ final PixelGrabber pg = new PixelGrabber(ima, 0, 0, ai.m_w, ai.m_h, true);
try {
pg.grabPixels();
- } catch(InterruptedException x) {
+ } catch(final InterruptedException x) {
throw new IOException("Interrupted load of image");
}
px = (int[]) pg.getPixels(); // Get the pixels,
@@ -685,10 +685,10 @@ public class AnimGifEncoder {
* for the combined GIF. The index of the color is then used in the 8-bit
* pixelset for this image.
*/
- private void translateColorsByArray(AnIma a, int[] px) throws IOException {
+ private void translateColorsByArray(final AnIma a, final int[] px) throws IOException {
int off;
byte[] par;
- int endoff = a.m_w * a.m_h; // Total #pixels in image
+ final int endoff = a.m_w * a.m_h; // Total #pixels in image
int rstart, rcolor; // Run data.
byte newc;
@@ -717,7 +717,7 @@ public class AnimGifEncoder {
else
{
//-- Not transparant- is an index known for this color?
- int i = (rcolor & 0x7fffffff) % CHSIZE;
+ final int i = (rcolor & 0x7fffffff) % CHSIZE;
if(m_ccolor_ar[i] == rcolor) // Bucket found?
newc = (byte)m_cindex_ar[i];
@@ -742,10 +742,10 @@ public class AnimGifEncoder {
*/
private void genColorTable() throws IOException {
// Turn colors into colormap entries.
- int nelem = 1 << m_color_bits;
- byte[] reds = new byte[nelem];
- byte[] grns = new byte[nelem];
- byte[] blus = new byte[nelem];
+ final int nelem = 1 << m_color_bits;
+ final byte[] reds = new byte[nelem];
+ final byte[] grns = new byte[nelem];
+ final byte[] blus = new byte[nelem];
//-- Now enumerate the color table.
for (int i = CHSIZE; --i >= 0;) { // Count backwards (faster)
@@ -787,7 +787,7 @@ public class AnimGifEncoder {
//-- Logical Screen Descriptor Block
utWord(m_w); // Collated width & height of all images
utWord(m_h);
- byte b = (byte)(0xF0 | (m_color_bits-1));// There IS a color map, 8 bits per color source resolution. not sorted,
+ final byte b = (byte)(0xF0 | (m_color_bits-1));// There IS a color map, 8 bits per color source resolution. not sorted,
utByte(b); // Packet fields,
utByte((byte)0); // Background Color Index assumed 0.
utByte((byte)0); // Pixel aspect ratio 1:1: zero always works...
@@ -819,7 +819,7 @@ public class AnimGifEncoder {
/**
* Writes a single image instance.
*/
- private void genImage(AnIma ai) throws IOException {
+ private void genImage(final AnIma ai) throws IOException {
//-- Write out a Graphic Control Extension for transparent colour & repeat, if necessary,
if(m_transparant_ix != -1 || m_ima_ar.size() > 1) {
byte transpar;
@@ -848,7 +848,7 @@ public class AnimGifEncoder {
utByte((byte) (ai.m_interlace ? 0x40 : 0)); // Packed fields: interlaced Y/N, no local table no sort,
//-- The table-based image data...
- int initcodesz = m_color_bits <= 1 ? 2 : m_color_bits;
+ final int initcodesz = m_color_bits <= 1 ? 2 : m_color_bits;
utByte((byte) initcodesz); // Output initial LZH code size, min. 2 bits,
genCompressed(ai, initcodesz+1); // Generate the compressed data,
utByte((byte) 0); // Zero-length packet (end series)
@@ -871,7 +871,7 @@ public class AnimGifEncoder {
/** End index within above index. */
private int m_px_endix;
- private void genCompressed(AnIma a, int initcodesz) throws IOException {
+ private void genCompressed(final AnIma a, final int initcodesz) throws IOException {
//-- Set all globals to retrieve pixel data quickly. $$TODO: Interlaced
m_curr_pixels = a.m_rgb;
m_px_ix = 0;
@@ -981,7 +981,7 @@ public class AnimGifEncoder {
int maxcode; // maximum code, given n_bits
int maxmaxcode = 1 << BITS; // should NEVER generate this code
- final int MAXCODE( int n_bits ) {
+ final int MAXCODE( final int n_bits ) {
return ( 1 << n_bits ) - 1;
}
@@ -1034,7 +1034,7 @@ public class AnimGifEncoder {
0x01FF, 0x03FF, 0x07FF, 0x0FFF,
0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF };
- void output(int code) throws IOException {
+ void output(final int code) throws IOException {
cur_accum |= ( code << cur_bits );
cur_bits += n_bits;
@@ -1097,7 +1097,7 @@ public class AnimGifEncoder {
}
// reset code table
- void cl_hash( int hsize ) {
+ void cl_hash( final int hsize ) {
for(int i = hsize; --i >= 0;)
htab[i] = -1;
}
@@ -1117,7 +1117,7 @@ public class AnimGifEncoder {
// Add a character to the end of the current packet, and if it is 254
// characters, flush the packet to disk.
- void char_out(byte c) throws IOException {
+ void char_out(final byte c) throws IOException {
accum[a_count++] = c;
if ( a_count >= 254 )
flush_char();
@@ -1133,24 +1133,24 @@ public class AnimGifEncoder {
}
// test method for ymage classes
- public static void main(String[] args) {
+ public static void main(final String[] args) {
System.setProperty("java.awt.headless", "true");
- ymageMatrix m = new ymageMatrix(200, 300, ymageMatrix.MODE_SUB, "FFFFFF");
+ final ymageMatrix m = new ymageMatrix(200, 300, ymageMatrix.MODE_SUB, "FFFFFF");
ymageMatrix.demoPaint(m);
- File file = new File("/Users/admin/Desktop/testimage.gif");
+ final File file = new File("/Users/admin/Desktop/testimage.gif");
OutputStream os;
try {
os = new FileOutputStream(file);
- AnimGifEncoder age = new AnimGifEncoder(os);
+ final AnimGifEncoder age = new AnimGifEncoder(os);
age.add(m.getImage());
age.add(m.getImage());
age.encode();
os.close();
- } catch (FileNotFoundException e) {
+ } catch (final FileNotFoundException e) {
e.printStackTrace();
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
}
@@ -1163,7 +1163,7 @@ class GifColorEntry {
/** The colortable [palette] entry number for this color */
public int m_index;
- public GifColorEntry(int col, int ix) {
+ public GifColorEntry(final int col, final int ix) {
m_color = col;
m_index = ix;
}
diff --git a/source/de/anomic/ymage/ymage8BitFontGenerator.java b/source/de/anomic/ymage/ymage8BitFontGenerator.java
index 249eda748..d5d9fab30 100644
--- a/source/de/anomic/ymage/ymage8BitFontGenerator.java
+++ b/source/de/anomic/ymage/ymage8BitFontGenerator.java
@@ -825,7 +825,7 @@ public class ymage8BitFontGenerator {
};
- public static void main(String[] args) {
+ public static void main(final String[] args) {
String[] letter;
int b;
int v;
diff --git a/source/de/anomic/ymage/ymageBMPParser.java b/source/de/anomic/ymage/ymageBMPParser.java
index 318b41044..002fbf580 100644
--- a/source/de/anomic/ymage/ymageBMPParser.java
+++ b/source/de/anomic/ymage/ymageBMPParser.java
@@ -47,21 +47,21 @@ public class ymageBMPParser {
//private static int BI_RLE4 = 2;
//private static int BI_BITFIELDS = 3;
- private IMAGEMAP imagemap;
+ private final IMAGEMAP imagemap;
//boolean debugmode = false;
- public static final boolean isBMP(byte[] source) {
+ public static final boolean isBMP(final byte[] source) {
// check the file magic
return (source != null) && (source.length >= 2) && (source[0] == 'B') && (source[1] == 'M');
}
- public ymageBMPParser(byte[] source) {
+ public ymageBMPParser(final byte[] source) {
// read info-header
- int bfOffBits = DWORD(source, FILEHEADER_offset + 10);
+ final int bfOffBits = DWORD(source, FILEHEADER_offset + 10);
- INFOHEADER infoheader = new INFOHEADER(source, INFOHEADER_offset);
- COLORTABLE colortable = new COLORTABLE(source, INFOHEADER_offset + INFOHEADER_size, infoheader);
+ final INFOHEADER infoheader = new INFOHEADER(source, INFOHEADER_offset);
+ final COLORTABLE colortable = new COLORTABLE(source, INFOHEADER_offset + INFOHEADER_size, infoheader);
// check consistency with bfOffBits
assert bfOffBits == INFOHEADER_offset + 40 + colortable.colorbytes : "bfOffBits = " + bfOffBits + ", colorbytes = " + colortable.colorbytes;
@@ -74,7 +74,7 @@ public class ymageBMPParser {
return imagemap.image;
}
- public static final int DWORD(byte[] b, int offset) {
+ public static final int DWORD(final byte[] b, final int offset) {
if (offset + 3 >= b.length) return 0;
int ret = (b[offset + 3] & 0xff);
ret = (ret << 8) | (b[offset + 2] & 0xff);
@@ -83,13 +83,13 @@ public class ymageBMPParser {
return ret;
}
- public static final int WORD(byte[] b, int offset) {
- int ret = ((b[offset + 1] & 0xff) << 8) | (b[offset] & 0xff);
+ public static final int WORD(final byte[] b, final int offset) {
+ final int ret = ((b[offset + 1] & 0xff) << 8) | (b[offset] & 0xff);
return ret;
}
- public static final int BYTE(byte[] b, int offset) {
- int ret = (b[offset] & 0xff);
+ public static final int BYTE(final byte[] b, final int offset) {
+ final int ret = (b[offset] & 0xff);
return ret;
}
@@ -98,7 +98,7 @@ public class ymageBMPParser {
public int biWidth, biHeight, biBitCount, biCompression, biSizeImage, biClrUsed;
- public INFOHEADER(byte[] s, int offset) {
+ public INFOHEADER(final byte[] s, final int offset) {
// read info-header
biWidth = DWORD(s, offset + 4);
biHeight = DWORD(s, offset + 8);
@@ -114,7 +114,7 @@ public class ymageBMPParser {
public int colorbytes;
public int[] colorindex;
- public COLORTABLE(byte[] s, int offset, INFOHEADER infoheader) {
+ public COLORTABLE(final byte[] s, final int offset, final INFOHEADER infoheader) {
// read colortable
colorbytes = 0; // for consistency check
if (infoheader.biClrUsed == 0) {
@@ -148,7 +148,7 @@ public class ymageBMPParser {
public BufferedImage image;
- public IMAGEMAP(byte[] s, int offset, int width, int height, int compression, int bitcount, COLORTABLE colortable) {
+ public IMAGEMAP(final byte[] s, final int offset, final int width, final int height, final int compression, final int bitcount, final COLORTABLE colortable) {
// parse picture content
if ((width != 0) && (height != 0)) {
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
@@ -167,7 +167,7 @@ public class ymageBMPParser {
}
- private void parseBMP1(byte[] s, int offset, int width, int height, COLORTABLE colortable) {
+ private void parseBMP1(final byte[] s, final int offset, final int width, final int height, final COLORTABLE colortable) {
int n = 0;
int b;
for (int rows = 0; rows < height; rows++) {
@@ -188,7 +188,7 @@ public class ymageBMPParser {
}
}
- private void parseBMP4(byte[] s, int offset, int width, int height, COLORTABLE colortable) {
+ private void parseBMP4(final byte[] s, final int offset, final int width, final int height, final COLORTABLE colortable) {
int n = 0;
int b;
for (int rows = 0; rows < height; rows++) {
@@ -203,7 +203,7 @@ public class ymageBMPParser {
}
}
- private void parseBMP8(byte[] s, int offset, int width, int height, COLORTABLE colortable) {
+ private void parseBMP8(final byte[] s, final int offset, final int width, final int height, final COLORTABLE colortable) {
int n = 0;
for (int rows = 0; rows < height; rows++) {
for (int columns = 0; columns < width; columns++) {
@@ -215,7 +215,7 @@ public class ymageBMPParser {
}
}
- private void parseBMP24(byte[] s, int offset, int width, int height) {
+ private void parseBMP24(final byte[] s, final int offset, final int width, final int height) {
int n = 0;
for (int rows = 0; rows < height; rows++) {
for (int columns = 0; columns < width; columns++) {
@@ -227,7 +227,7 @@ public class ymageBMPParser {
}
}
- private void parseBMP32(byte[] s, int offset, int width, int height) {
+ private void parseBMP32(final byte[] s, final int offset, final int width, final int height) {
int n = 0;
for (int rows = 0; rows < height; rows++) {
for (int columns = 0; columns < width; columns++) {
@@ -238,34 +238,34 @@ public class ymageBMPParser {
}
}
- private final int fill4(int x) {
- int r = x % 4;
+ private final int fill4(final int x) {
+ final int r = x % 4;
if (r == 0) return 0; else return 4 - r;
}
}
- public static void main(String[] args) {
+ public static void main(final String[] args) {
// read a bmp and write it as png
System.setProperty("java.awt.headless", "true");
- File in = new File(args[0]);
- File out = new File(args[1]);
+ final File in = new File(args[0]);
+ final File out = new File(args[1]);
- byte[] file = new byte[(int) in.length()];
+ final byte[] file = new byte[(int) in.length()];
FileInputStream fis = null;
try {
fis = new FileInputStream(in);
fis.read(file);
- } catch (FileNotFoundException e) {
+ } catch (final FileNotFoundException e) {
e.printStackTrace();
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
- ymageBMPParser parser = new ymageBMPParser(file);
+ final ymageBMPParser parser = new ymageBMPParser(file);
try {
ImageIO.write(parser.getImage(), "PNG", out);
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
}
diff --git a/source/de/anomic/ymage/ymageCaptcha.java b/source/de/anomic/ymage/ymageCaptcha.java
index 0c49b941b..103f4a4e1 100644
--- a/source/de/anomic/ymage/ymageCaptcha.java
+++ b/source/de/anomic/ymage/ymageCaptcha.java
@@ -29,24 +29,24 @@ import javax.imageio.ImageIO;
public class ymageCaptcha extends ymageMatrix {
- public ymageCaptcha(int width, int height, byte displayMode, String code) {
+ public ymageCaptcha(final int width, final int height, final byte displayMode, final String code) {
super(width, height, displayMode, "FFFFFF");
this.create(code);
}
- private void create(String code){
+ private void create(final String code){
- Random random = new Random();
+ final Random random = new Random();
- int width = this.getWidth();
- int height = this.getHeight();
- int chars = code.length();
+ final int width = this.getWidth();
+ final int height = this.getHeight();
+ final int chars = code.length();
int x;
int y;
int ub = 0;
- int widthPerChar = width/chars;
- int pixels = width * height;
+ final int widthPerChar = width/chars;
+ final int pixels = width * height;
//printing code
@@ -78,14 +78,14 @@ public class ymageCaptcha extends ymageMatrix {
}
- public static void main(String[] args) {
+ public static void main(final String[] args) {
// go into headless awt mode
System.setProperty("java.awt.headless", "true");
- ymageCaptcha m = new ymageCaptcha(200, 70, ymageMatrix.MODE_REPLACE, args[1]);
+ final ymageCaptcha m = new ymageCaptcha(200, 70, ymageMatrix.MODE_REPLACE, args[1]);
try {
ImageIO.write(m.getImage(), "png", new java.io.File(args[0]));
- } catch (java.io.IOException e) {
+ } catch (final java.io.IOException e) {
e.printStackTrace();
}
diff --git a/source/de/anomic/ymage/ymageChart.java b/source/de/anomic/ymage/ymageChart.java
index 3293315c0..cfe3d5000 100644
--- a/source/de/anomic/ymage/ymageChart.java
+++ b/source/de/anomic/ymage/ymageChart.java
@@ -47,9 +47,9 @@ public class ymageChart extends ymageMatrix {
String name;
String backgroundColor, foregroundColor;
- public ymageChart(int width, int height, String backgroundColor, String foregroundColor, String lightColor,
- int leftborder, int rightborder, int topborder, int bottomborder,
- String name, String subline) {
+ public ymageChart(final int width, final int height, final String backgroundColor, final String foregroundColor, final String lightColor,
+ final int leftborder, final int rightborder, final int topborder, final int bottomborder,
+ final String name, final String subline) {
super(width, height, ymageMatrix.MODE_REPLACE, backgroundColor);
this.leftborder = leftborder;
this.rightborder = rightborder;
@@ -68,7 +68,7 @@ public class ymageChart extends ymageMatrix {
}
}
- public void declareDimension(int dimensionType, int scale, int pixelperscale, int offset, String colorNaming, String colorScale, String name) {
+ public void declareDimension(final int dimensionType, final int scale, final int pixelperscale, final int offset, final String colorNaming, final String colorScale, final String name) {
if ((dimensionType == DIMENSION_LEFT) || (dimensionType == DIMENSION_RIGHT)) {
drawVerticalScale((dimensionType == DIMENSION_LEFT), scale, pixelperscale, offset, colorNaming, colorScale, name);
}
@@ -83,23 +83,23 @@ public class ymageChart extends ymageMatrix {
tablenames[dimensionType] = name;
}
- public void chartDot(int dimension_x, int dimension_y, int coord_x, int coord_y, int dotsize) {
- int x = (coord_x - offsets[dimension_x]) * pixels[dimension_x] / scales[dimension_x];
- int y = (coord_y - offsets[dimension_y]) * pixels[dimension_y] / scales[dimension_y];
+ public void chartDot(final int dimension_x, final int dimension_y, final int coord_x, final int coord_y, final int dotsize) {
+ final int x = (coord_x - offsets[dimension_x]) * pixels[dimension_x] / scales[dimension_x];
+ final int y = (coord_y - offsets[dimension_y]) * pixels[dimension_y] / scales[dimension_y];
if (dotsize == 1) plot(leftborder + x, height - bottomborder - y);
else dot(leftborder + x, height - bottomborder - y, dotsize, true);
}
- public void chartLine(int dimension_x, int dimension_y, int coord_x1, int coord_y1, int coord_x2, int coord_y2) {
- int x1 = (coord_x1 - offsets[dimension_x]) * pixels[dimension_x] / scales[dimension_x];
- int y1 = (coord_y1 - offsets[dimension_y]) * pixels[dimension_y] / scales[dimension_y];
- int x2 = (coord_x2 - offsets[dimension_x]) * pixels[dimension_x] / scales[dimension_x];
- int y2 = (coord_y2 - offsets[dimension_y]) * pixels[dimension_y] / scales[dimension_y];
+ public void chartLine(final int dimension_x, final int dimension_y, final int coord_x1, final int coord_y1, final int coord_x2, final int coord_y2) {
+ final int x1 = (coord_x1 - offsets[dimension_x]) * pixels[dimension_x] / scales[dimension_x];
+ final int y1 = (coord_y1 - offsets[dimension_y]) * pixels[dimension_y] / scales[dimension_y];
+ final int x2 = (coord_x2 - offsets[dimension_x]) * pixels[dimension_x] / scales[dimension_x];
+ final int y2 = (coord_y2 - offsets[dimension_y]) * pixels[dimension_y] / scales[dimension_y];
line(leftborder + x1, height - bottomborder - y1, leftborder + x2, height - bottomborder - y2);
}
- private void drawHorizontalScale(boolean top, int scale, int pixelperscale, int offset, String colorNaming, String colorScale, String name) {
- int y = (top) ? topborder : height - bottomborder;
+ private void drawHorizontalScale(final boolean top, final int scale, final int pixelperscale, final int offset, final String colorNaming, final String colorScale, final String name) {
+ final int y = (top) ? topborder : height - bottomborder;
int x = leftborder;
int s = offset;
while (x < width - rightborder) {
@@ -118,8 +118,8 @@ public class ymageChart extends ymageMatrix {
line(leftborder - 4, y, width - rightborder + 4, y);
}
- private void drawVerticalScale(boolean left, int scale, int pixelperscale, int offset, String colorNaming, String colorScale, String name) {
- int x = (left) ? leftborder : width - rightborder;
+ private void drawVerticalScale(final boolean left, final int scale, final int pixelperscale, final int offset, final String colorNaming, final String colorScale, final String name) {
+ final int x = (left) ? leftborder : width - rightborder;
int y = height - bottomborder;
int s = offset;
String s1;
@@ -142,15 +142,15 @@ public class ymageChart extends ymageMatrix {
line(x, topborder - 4, x, height - bottomborder + 4);
}
- public static void main(String[] args) {
+ public static void main(final String[] args) {
System.setProperty("java.awt.headless", "true");
- boolean invers = false;
- String bg = (invers) ? "000000" : "FFFFFF";
- String fg = (invers) ? "FFFFFF" : "000000";
- String scale = (invers) ? "333333" : "CCCCCC";
- String green = (invers) ? "008800" : "008800";
- String blue = (invers) ? "0000FF" : "0000FF";
- ymageChart ip = new ymageChart(660, 240, bg, fg, fg, 30, 30, 20, 20, "PEER PERFORMANCE GRAPH: PAGES/MINUTE and USED MEMORY", "");
+ final boolean invers = false;
+ final String bg = (invers) ? "000000" : "FFFFFF";
+ final String fg = (invers) ? "FFFFFF" : "000000";
+ final String scale = (invers) ? "333333" : "CCCCCC";
+ final String green = (invers) ? "008800" : "008800";
+ final String blue = (invers) ? "0000FF" : "0000FF";
+ final ymageChart ip = new ymageChart(660, 240, bg, fg, fg, 30, 30, 20, 20, "PEER PERFORMANCE GRAPH: PAGES/MINUTE and USED MEMORY", "");
ip.declareDimension(DIMENSION_BOTTOM, 60, 60, -600, fg, scale, "TIME/SECONDS");
//ip.declareDimension(DIMENSION_TOP, 10, 40, "000000", null, "count");
ip.declareDimension(DIMENSION_LEFT, 50, 40, 0, green, scale , "PPM [PAGES/MINUTE]");
@@ -165,12 +165,12 @@ public class ymageChart extends ymageMatrix {
//ip.print(100, 100, 0, "1234", false);
//ip.print(100, 100, 90, "TEXT", true);
//ip.print(100, 100, 90, "1234", false);
- File file = new File("/Users/admin/Desktop/testimage.png");
+ final File file = new File("/Users/admin/Desktop/testimage.png");
try {
- FileOutputStream fos = new FileOutputStream(file);
+ final FileOutputStream fos = new FileOutputStream(file);
ImageIO.write(ip.getImage(), "png", fos);
fos.close();
- } catch (IOException e) {}
+ } catch (final IOException e) {}
}
diff --git a/source/de/anomic/ymage/ymageDemoApplet.java b/source/de/anomic/ymage/ymageDemoApplet.java
index 298f9a24d..97282cd6b 100644
--- a/source/de/anomic/ymage/ymageDemoApplet.java
+++ b/source/de/anomic/ymage/ymageDemoApplet.java
@@ -19,8 +19,8 @@ public class ymageDemoApplet extends Applet implements Runnable {
ymageMatrix offGraphics;
public void init() {
- String str = getParameter("fps");
- int fps = (str != null) ? Integer.parseInt(str) : 10;
+ final String str = getParameter("fps");
+ final int fps = (str != null) ? Integer.parseInt(str) : 10;
delay = (fps > 0) ? (1000 / fps) : 100;
}
@@ -31,11 +31,11 @@ public class ymageDemoApplet extends Applet implements Runnable {
public void run() {
while (Thread.currentThread() == animator) {
- long time = System.currentTimeMillis();
+ final long time = System.currentTimeMillis();
repaint();
try {
Thread.sleep(delay - System.currentTimeMillis() + time);
- } catch (InterruptedException e) {
+ } catch (final InterruptedException e) {
break;
}
}
@@ -45,22 +45,22 @@ public class ymageDemoApplet extends Applet implements Runnable {
animator = null;
}
- public void update(Graphics g) {
- Dimension d = getSize();
+ public void update(final Graphics g) {
+ final Dimension d = getSize();
offGraphics = new ymageMatrix(d.width, d.height, ymageMatrix.MODE_REPLACE, "FFFFFF");
paintFrame(offGraphics);
g.drawImage(offGraphics.getImage(), 0, 0, null);
}
- public void paint(Graphics g) {
+ public void paint(final Graphics g) {
if (offGraphics != null) {
g.drawImage(offGraphics.getImage(), 0, 0, null);
}
}
- public void paintFrame(ymageMatrix m) {
+ public void paintFrame(final ymageMatrix m) {
ymageMatrix.demoPaint(m);
- int y = (int) (System.currentTimeMillis() / 10 % 300);
+ final int y = (int) (System.currentTimeMillis() / 10 % 300);
m.setColor(ymageMatrix.GREY);
ymageToolPrint.print(m, 0, y, 0, "Hello World", -1);
}
diff --git a/source/de/anomic/ymage/ymageFontGenerator.java b/source/de/anomic/ymage/ymageFontGenerator.java
index 5417fc994..70359b9a2 100644
--- a/source/de/anomic/ymage/ymageFontGenerator.java
+++ b/source/de/anomic/ymage/ymageFontGenerator.java
@@ -523,7 +523,7 @@ public class ymageFontGenerator {
};
- public static void main(String[] args) {
+ public static void main(final String[] args) {
String[] letter;
long b;
long v;
diff --git a/source/de/anomic/ymage/ymageGraph.java b/source/de/anomic/ymage/ymageGraph.java
index 78f4570f3..4409d8fee 100644
--- a/source/de/anomic/ymage/ymageGraph.java
+++ b/source/de/anomic/ymage/ymageGraph.java
@@ -56,22 +56,22 @@ public class ymageGraph {
bottommost = 1.0;
}
- public coordinate getPoint(String name) {
+ public coordinate getPoint(final String name) {
return points.get(name);
}
- public coordinate[] getBorder(String name) {
- int p = name.indexOf("$");
+ public coordinate[] getBorder(final String name) {
+ final int p = name.indexOf("$");
if (p < 0) return null;
- coordinate from = getPoint(name.substring(0, p));
- coordinate to = getPoint(name.substring(p + 1));
+ final coordinate from = getPoint(name.substring(0, p));
+ final coordinate to = getPoint(name.substring(p + 1));
if ((from == null) || (to == null)) return null;
return new coordinate[] {from, to};
}
- public coordinate addPoint(String name, double x, double y, int layer) {
- coordinate newc = new coordinate(x, y, layer);
- coordinate oldc = points.put(name, newc);
+ public coordinate addPoint(final String name, final double x, final double y, final int layer) {
+ final coordinate newc = new coordinate(x, y, layer);
+ final coordinate oldc = points.put(name, newc);
assert oldc == null; // all add shall be unique
if (x > rightmost) rightmost = x;
if (x < leftmost) leftmost = x;
@@ -80,13 +80,13 @@ public class ymageGraph {
return newc;
}
- public boolean hasBorder(String fromPoint, String toPoint) {
+ public boolean hasBorder(final String fromPoint, final String toPoint) {
return borders.contains(fromPoint + "-" + toPoint);
}
- public void setBorder(String fromPoint, String toPoint) {
- coordinate from = points.get(fromPoint);
- coordinate to = points.get(toPoint);
+ public void setBorder(final String fromPoint, final String toPoint) {
+ final coordinate from = points.get(fromPoint);
+ final coordinate to = points.get(toPoint);
assert from != null;
assert to != null;
borders.add(fromPoint + "$" + toPoint);
@@ -95,7 +95,7 @@ public class ymageGraph {
public class coordinate {
public double x, y;
public int layer;
- public coordinate(double x, double y, int layer) {
+ public coordinate(final double x, final double y, final int layer) {
assert x >= -1;
assert x <= 1;
assert y >= -1;
@@ -108,7 +108,7 @@ public class ymageGraph {
public void print() {
// for debug purpose: print out all coordinates
- Iterator<Map.Entry<String, coordinate>> i = points.entrySet().iterator();
+ final Iterator<Map.Entry<String, coordinate>> i = points.entrySet().iterator();
Map.Entry<String, coordinate> entry;
String name;
coordinate c;
@@ -118,7 +118,7 @@ public class ymageGraph {
c = entry.getValue();
System.out.println("point(" + c.x + ", " + c.y + ", " + c.layer + ") [" + name + "]");
}
- Iterator<String> j = borders.iterator();
+ final Iterator<String> j = borders.iterator();
while (j.hasNext()) {
System.out.println("border(" + j.next() + ")");
}
@@ -130,13 +130,13 @@ public class ymageGraph {
private static final long color_line = 0x333333;
private static final long color_lineend = 0x666666;
- public ymageMatrix draw(int width, int height, int leftborder, int rightborder, int topborder, int bottomborder) {
- ymageMatrix image = new ymageMatrix(width, height, ymageMatrix.MODE_SUB, color_back);
- double xfactor = ((rightmost - leftmost) == 0.0) ? 0.0 : (width - leftborder - rightborder) / (rightmost - leftmost);
- double yfactor = ((topmost - bottommost) == 0.0) ? 0.0 : (height - topborder - bottomborder) / (topmost - bottommost);
+ public ymageMatrix draw(final int width, final int height, final int leftborder, final int rightborder, final int topborder, final int bottomborder) {
+ final ymageMatrix image = new ymageMatrix(width, height, ymageMatrix.MODE_SUB, color_back);
+ final double xfactor = ((rightmost - leftmost) == 0.0) ? 0.0 : (width - leftborder - rightborder) / (rightmost - leftmost);
+ final double yfactor = ((topmost - bottommost) == 0.0) ? 0.0 : (height - topborder - bottomborder) / (topmost - bottommost);
// draw dots and names
- Iterator<Map.Entry<String, coordinate>> i = points.entrySet().iterator();
+ final Iterator<Map.Entry<String, coordinate>> i = points.entrySet().iterator();
Map.Entry<String, coordinate> entry;
String name;
coordinate c;
@@ -154,7 +154,7 @@ public class ymageGraph {
}
// draw lines
- Iterator<String> j = borders.iterator();
+ final Iterator<String> j = borders.iterator();
coordinate[] border;
image.setColor(color_line);
int x0, x1, y0, y1;
diff --git a/source/de/anomic/ymage/ymageICOParser.java b/source/de/anomic/ymage/ymageICOParser.java
index 621fceacb..a64623f5a 100644
--- a/source/de/anomic/ymage/ymageICOParser.java
+++ b/source/de/anomic/ymage/ymageICOParser.java
@@ -38,23 +38,23 @@ public class ymageICOParser {
public static int ICONDIRENTRY_size = 16;
- private int idCount;
+ private final int idCount;
ymageBMPParser.INFOHEADER[] infoheaders;
ymageBMPParser.IMAGEMAP[] imagemaps;
- public static final boolean isICO(byte[] source) {
+ public static final boolean isICO(final byte[] source) {
// check the file magic
return (source != null) && (source.length >= 4) && (source[0] == 0) && (source[1] == 0) && (source[2] == 1) && (source[3] == 0);
}
- public ymageICOParser(byte[] source) {
+ public ymageICOParser(final byte[] source) {
// read info-header
idCount = ymageBMPParser.WORD(source, 4);
// read the icon directory entry and the image entries
- ICONDIRENTRY[] icondirentries = new ICONDIRENTRY[idCount];
+ final ICONDIRENTRY[] icondirentries = new ICONDIRENTRY[idCount];
infoheaders = new ymageBMPParser.INFOHEADER[idCount];
- ymageBMPParser.COLORTABLE[] colortables = new ymageBMPParser.COLORTABLE[idCount];
+ final ymageBMPParser.COLORTABLE[] colortables = new ymageBMPParser.COLORTABLE[idCount];
imagemaps = new ymageBMPParser.IMAGEMAP[idCount];
for (int i = 0; i < idCount; i++) {
icondirentries[i] = new ICONDIRENTRY(source, 6 + i * ICONDIRENTRY_size);
@@ -69,7 +69,7 @@ public class ymageICOParser {
public int bWidth, bHeight, bColorCount, bReserved, wPlanes, wBitCount, dwBytesInRes, dwImageOffset;
- public ICONDIRENTRY(byte[] s, int offset) {
+ public ICONDIRENTRY(final byte[] s, final int offset) {
// read info-header
bWidth = ymageBMPParser.BYTE(s, offset + 0);
bHeight = ymageBMPParser.BYTE(s, offset + 1);
@@ -87,32 +87,32 @@ public class ymageICOParser {
return idCount;
}
- public BufferedImage getImage(int index) {
+ public BufferedImage getImage(final int index) {
return imagemaps[index].image;
}
- public static void main(String[] args) {
+ public static void main(final String[] args) {
// read a ICO and write it as png
System.setProperty("java.awt.headless", "true");
- File in = new File(args[0]);
- File out = new File(args[1]);
+ final File in = new File(args[0]);
+ final File out = new File(args[1]);
- byte[] file = new byte[(int) in.length()];
+ final byte[] file = new byte[(int) in.length()];
FileInputStream fis = null;
try {
fis = new FileInputStream(in);
fis.read(file);
- } catch (FileNotFoundException e) {
+ } catch (final FileNotFoundException e) {
e.printStackTrace();
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
- ymageICOParser parser = new ymageICOParser(file);
+ final ymageICOParser parser = new ymageICOParser(file);
try {
ImageIO.write(parser.getImage(0), "PNG", out);
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
}
}
diff --git a/source/de/anomic/ymage/ymageImageParser.java b/source/de/anomic/ymage/ymageImageParser.java
index 60c63b762..62fdb215f 100644
--- a/source/de/anomic/ymage/ymageImageParser.java
+++ b/source/de/anomic/ymage/ymageImageParser.java
@@ -8,8 +8,8 @@ import java.awt.Toolkit;
public class ymageImageParser {
- public static final Image parse(String filename, byte[] source) {
- MediaTracker mediaTracker = new MediaTracker(new Container());
+ public static final Image parse(final String filename, final byte[] source) {
+ final MediaTracker mediaTracker = new MediaTracker(new Container());
Image image;
if (((filename.endsWith(".ico")) || (filename.endsWith(".bmp"))) && (ymageBMPParser.isBMP(source))) {
// parse image with BMP parser
@@ -28,9 +28,9 @@ public class ymageImageParser {
image = Toolkit.getDefaultToolkit().createImage(source);
}
- int handle = image.hashCode();
+ final int handle = image.hashCode();
mediaTracker.addImage(image, handle);
- try {mediaTracker.waitForID(handle);} catch (InterruptedException e) {}
+ try {mediaTracker.waitForID(handle);} catch (final InterruptedException e) {}
return image;
}
diff --git a/source/de/anomic/ymage/ymageMatrix.java b/source/de/anomic/ymage/ymageMatrix.java
index c4ac70d18..df5db2a6a 100644
--- a/source/de/anomic/ymage/ymageMatrix.java
+++ b/source/de/anomic/ymage/ymageMatrix.java
@@ -64,17 +64,17 @@ public class ymageMatrix {
public static final byte FILTER_INVERT = 2;
protected int width, height;
- private BufferedImage image;
- private WritableRaster grid;
- private int[] defaultCol;
- private long backgroundCol;
- private byte defaultMode;
+ private final BufferedImage image;
+ private final WritableRaster grid;
+ private final int[] defaultCol;
+ private final long backgroundCol;
+ private final byte defaultMode;
- public ymageMatrix(int width, int height, byte drawMode, String backgroundColor) {
+ public ymageMatrix(final int width, final int height, final byte drawMode, final String backgroundColor) {
this(width, height, drawMode, Long.parseLong(backgroundColor, 16));
}
- public ymageMatrix(int width, int height, byte drawMode, long backgroundColor) {
+ public ymageMatrix(final int width, final int height, final byte drawMode, final long backgroundColor) {
if (!(serverMemory.request(1024 * 1024 + 3 * width * height, false))) throw new RuntimeException("ymage: not enough memory (" + serverMemory.available() + ") available");
this.width = width;
this.height = height;
@@ -100,7 +100,7 @@ public class ymageMatrix {
bgG = (int) ((this.backgroundCol >> 8) & 0xff);
bgB = (int) (this.backgroundCol & 0xff);
//}
- Graphics2D gr = image.createGraphics();
+ final Graphics2D gr = image.createGraphics();
gr.setBackground(new Color(bgR, bgG, bgB));
gr.clearRect(0, 0, width, height);
/*
@@ -125,11 +125,11 @@ public class ymageMatrix {
return height;
}
- public void setColor(long c) {
+ public void setColor(final long c) {
if (this.defaultMode == MODE_SUB) {
- int r = (int) (c >> 16);
- int g = (int) ((c >> 8) & 0xff);
- int b = (int) (c & 0xff);
+ final int r = (int) (c >> 16);
+ final int g = (int) ((c >> 8) & 0xff);
+ final int b = (int) (c & 0xff);
defaultCol[0] = (g + b) / 2;
defaultCol[1] = (r + b) / 2;
defaultCol[2] = (r + g) / 2;
@@ -141,17 +141,17 @@ public class ymageMatrix {
}
- public void setColor(String s) {
+ public void setColor(final String s) {
setColor(Long.parseLong(s, 16));
}
- public void plot(int x, int y) {
+ public void plot(final int x, final int y) {
plot (x, y, 100);
}
- private int[] cc = new int[3];
+ private final int[] cc = new int[3];
- public void plot(int x, int y, int intensity) {
+ public void plot(final int x, final int y, final int intensity) {
if ((x < 0) || (x >= width)) return;
if ((y < 0) || (y >= height)) return;
synchronized (cc) {
@@ -196,7 +196,7 @@ public class ymageMatrix {
}
}
- public void line(int Ax, int Ay, int Bx, int By) {
+ public void line(int Ax, int Ay, final int Bx, final int By) {
// Bresenham's line drawing algorithm
int dX = Math.abs(Bx-Ax);
int dY = Math.abs(By-Ay);
@@ -204,8 +204,8 @@ public class ymageMatrix {
if (Ax > Bx) Xincr=-1; else Xincr=1;
if (Ay > By) Yincr=-1; else Yincr=1;
if (dX >= dY) {
- int dPr = dY<<1;
- int dPru = dPr - (dX<<1);
+ final int dPr = dY<<1;
+ final int dPru = dPr - (dX<<1);
int P = dPr - dX;
for (; dX>=0; dX--) {
plot(Ax, Ay);
@@ -219,8 +219,8 @@ public class ymageMatrix {
}
}
} else {
- int dPr = dX<<1;
- int dPru = dPr - (dY<<1);
+ final int dPr = dX<<1;
+ final int dPru = dPr - (dY<<1);
int P = dPr - dY;
for (; dY>=0; dY--) {
plot(Ax, Ay);
@@ -236,38 +236,38 @@ public class ymageMatrix {
}
}
- public void lineDot(int x0, int y0, int x1, int y1, int radius, int distance, long lineColor, long dotColor) {
+ public void lineDot(final int x0, final int y0, final int x1, final int y1, final int radius, final int distance, final long lineColor, final long dotColor) {
// draw a line with a dot at the end.
// the radius value is the radius of the dot
// the distance value is the distance of the dot border to the endpoint
// compute first the angle of the line between the points
- double angle = (x1 - x0 > 0) ? Math.atan(((double) (y0 - y1)) / ((double) (x1 - x0))) : Math.PI - Math.atan(((double) (y0 - y1)) / ((double) (x0 - x1)));
+ final double angle = (x1 - x0 > 0) ? Math.atan(((double) (y0 - y1)) / ((double) (x1 - x0))) : Math.PI - Math.atan(((double) (y0 - y1)) / ((double) (x0 - x1)));
// now find two more points in between
// first calculate the radius' of the points
- double ra = Math.sqrt(((x0 - x1) * (x0 - x1) + (y0 - y1) * (y0 - y1))); // from a known point x1, y1
- double rb = ra - radius - distance;
- double rc = rb - radius;
+ final double ra = Math.sqrt(((x0 - x1) * (x0 - x1) + (y0 - y1) * (y0 - y1))); // from a known point x1, y1
+ final double rb = ra - radius - distance;
+ final double rc = rb - radius;
//System.out.println("CONTROL angle = " + angle);
//System.out.println("CONTROL x1 = " + x1 + ", x1calc = " + ((x0 + ((int) ra * Math.cos(angle)))));
//System.out.println("CONTROL y1 = " + y1 + ", y1calc = " + ((y0 - ((int) ra * Math.sin(angle)))));
// the points are on a circle with radius rb and rc
- int x2 = x0 + ((int) (rb * Math.cos(angle)));
- int y2 = y0 - ((int) (rb * Math.sin(angle)));
- int x3 = x0 + ((int) (rc * Math.cos(angle)));
- int y3 = y0 - ((int) (rc * Math.sin(angle)));
+ final int x2 = x0 + ((int) (rb * Math.cos(angle)));
+ final int y2 = y0 - ((int) (rb * Math.sin(angle)));
+ final int x3 = x0 + ((int) (rc * Math.cos(angle)));
+ final int y3 = y0 - ((int) (rc * Math.sin(angle)));
setColor(lineColor);
line(x0, y0, x3, y3);
setColor(dotColor);
dot(x2, y2, radius, true);
}
- public int[] getColor(int x, int y) {
- int[] c = new int[3];
+ public int[] getColor(final int x, final int y) {
+ final int[] c = new int[3];
return grid.getPixel(x, y, c);
}
- public void dot(int x, int y, int radius, boolean filled) {
+ public void dot(final int x, final int y, final int radius, final boolean filled) {
if (filled) {
for (int r = radius; r >= 0; r--) ymageToolCircle.circle(this, x, y, r);
} else {
@@ -275,27 +275,27 @@ public class ymageMatrix {
}
}
- public void arc(int x, int y, int innerRadius, int outerRadius, int fromArc, int toArc) {
+ public void arc(final int x, final int y, final int innerRadius, final int outerRadius, final int fromArc, final int toArc) {
for (int r = innerRadius; r <= outerRadius; r++) ymageToolCircle.circle(this, x, y, r, fromArc, toArc);
}
- public void arcLine(int cx, int cy, int innerRadius, int outerRadius, int angle) {
- int xi = cx + (int) (innerRadius * Math.cos(Math.PI * angle / 180));
- int yi = cy - (int) (innerRadius * Math.sin(Math.PI * angle / 180));
- int xo = cx + (int) (outerRadius * Math.cos(Math.PI * angle / 180));
- int yo = cy - (int) (outerRadius * Math.sin(Math.PI * angle / 180));
+ public void arcLine(final int cx, final int cy, final int innerRadius, final int outerRadius, final int angle) {
+ final int xi = cx + (int) (innerRadius * Math.cos(Math.PI * angle / 180));
+ final int yi = cy - (int) (innerRadius * Math.sin(Math.PI * angle / 180));
+ final int xo = cx + (int) (outerRadius * Math.cos(Math.PI * angle / 180));
+ final int yo = cy - (int) (outerRadius * Math.sin(Math.PI * angle / 180));
line(xi, yi, xo, yo);
}
- public void arcDot(int cx, int cy, int arcRadius, int angle, int dotRadius) {
- int x = cx + (int) (arcRadius * Math.cos(Math.PI * angle / 180));
- int y = cy - (int) (arcRadius * Math.sin(Math.PI * angle / 180));
+ public void arcDot(final int cx, final int cy, final int arcRadius, final int angle, final int dotRadius) {
+ final int x = cx + (int) (arcRadius * Math.cos(Math.PI * angle / 180));
+ final int y = cy - (int) (arcRadius * Math.sin(Math.PI * angle / 180));
dot(x, y, dotRadius, true);
}
- public void arcArc(int cx, int cy, int arcRadius, int angle, int innerRadius, int outerRadius, int fromArc, int toArc) {
- int x = cx + (int) (arcRadius * Math.cos(Math.PI * angle / 180));
- int y = cy - (int) (arcRadius * Math.sin(Math.PI * angle / 180));
+ public void arcArc(final int cx, final int cy, final int arcRadius, final int angle, final int innerRadius, final int outerRadius, final int fromArc, final int toArc) {
+ final int x = cx + (int) (arcRadius * Math.cos(Math.PI * angle / 180));
+ final int y = cy - (int) (arcRadius * Math.sin(Math.PI * angle / 180));
arc(x, y, innerRadius, outerRadius, fromArc, toArc);
}
@@ -306,7 +306,7 @@ public class ymageMatrix {
* @param y the y value of the upper left coordinate in the ymageMatrix where the bitmap will be placed
* @author Marc Nause
*/
- public void insertBitmap(BufferedImage bitmap, int x, int y) {
+ public void insertBitmap(final BufferedImage bitmap, final int x, final int y) {
insertBitmap(bitmap, x, y, -1);
}
@@ -318,7 +318,7 @@ public class ymageMatrix {
* @param filter chooses filter
* @author Marc Nause
*/
- public void insertBitmap(BufferedImage bitmap, int x, int y, byte filter) {
+ public void insertBitmap(final BufferedImage bitmap, final int x, final int y, final byte filter) {
insertBitmap(bitmap, x, y, -1, filter);
}
@@ -332,7 +332,7 @@ public class ymageMatrix {
* @param yy the y value of the pixel that determines which color is transparent
* @author Marc Nause
*/
- public void insertBitmap(BufferedImage bitmap, int x, int y, int xx, int yy) {
+ public void insertBitmap(final BufferedImage bitmap, final int x, final int y, final int xx, final int yy) {
insertBitmap(bitmap, x, y, bitmap.getRGB(xx, yy));
}
@@ -347,7 +347,7 @@ public class ymageMatrix {
* @param filter chooses filter
* @author Marc Nause
*/
- public void insertBitmap(BufferedImage bitmap, int x, int y, int xx, int yy, byte filter) {
+ public void insertBitmap(final BufferedImage bitmap, final int x, final int y, final int xx, final int yy, final byte filter) {
insertBitmap(bitmap, x, y, bitmap.getRGB(xx, yy), filter);
}
@@ -360,11 +360,11 @@ public class ymageMatrix {
* @param rgb the RGB value that will be transparent
* @author Marc Nause
*/
- public void insertBitmap(BufferedImage bitmap, int x, int y, int transRGB) {
- int heightSrc = bitmap.getHeight();
- int widthSrc = bitmap.getWidth();
- int heightTgt = height;
- int widthTgt = width;
+ public void insertBitmap(final BufferedImage bitmap, final int x, final int y, final int transRGB) {
+ final int heightSrc = bitmap.getHeight();
+ final int widthSrc = bitmap.getWidth();
+ final int heightTgt = height;
+ final int widthTgt = width;
int rgb;
for (int i = 0; i < heightSrc; i++) {
@@ -390,24 +390,24 @@ public class ymageMatrix {
* @param filter chooses filter
* @author Marc Nause
*/
- public void insertBitmap(BufferedImage bitmap, int x, int y, int transRGB, byte filter) {
+ public void insertBitmap(final BufferedImage bitmap, final int x, final int y, final int transRGB, final byte filter) {
insertBitmap(bitmap, x, y, transRGB);
- int bitmapWidth = bitmap.getWidth();
- int bitmapHeight = bitmap.getHeight();
+ final int bitmapWidth = bitmap.getWidth();
+ final int bitmapHeight = bitmap.getHeight();
if (filter == FILTER_ANTIALIASING) {
int transX = -1;
int transY = -1;
- int imageWidth = image.getWidth();
- int imageHeight = image.getHeight();
+ final int imageWidth = image.getWidth();
+ final int imageHeight = image.getHeight();
// find first pixel in bitmap that equals transRGB
// and also lies in area of image that will be covered by bitmap
int i = 0;
int j = 0;
- boolean found = false;
+ final boolean found = false;
while ((i < bitmapWidth) && (i + x < imageWidth) && !found) {
while ((j < bitmapHeight) && (j + y < imageHeight) && !found) {
if (bitmap.getRGB(i, j) == transRGB) {
@@ -443,7 +443,7 @@ public class ymageMatrix {
* @param rgb color of background
* @author Marc Nause
*/
- public void antialiasing(int lox, int loy, int rux, int ruy, int bgcolor) {
+ public void antialiasing(final int lox, final int loy, final int rux, final int ruy, final int bgcolor) {
filter(lox, loy, rux, ruy, FILTER_ANTIALIASING, bgcolor);
}
@@ -455,7 +455,7 @@ public class ymageMatrix {
* @param ruy y value for right lower coordinate
* @author Marc Nause
*/
- public void blur(int lox, int loy, int rux, int ruy) {
+ public void blur(final int lox, final int loy, final int rux, final int ruy) {
filter(lox, loy, rux, ruy, FILTER_BLUR, -1);
}
@@ -467,7 +467,7 @@ public class ymageMatrix {
* @param ruy y value for right lower coordinate
* @author Marc Nause
*/
- public void invert(int lox, int loy, int rux, int ruy) {
+ public void invert(final int lox, final int loy, final int rux, final int ruy) {
filter(lox, loy, rux, ruy, FILTER_INVERT, -1);
}
@@ -480,7 +480,7 @@ public class ymageMatrix {
* @param filter chooses filter
* @author Marc Nause
*/
- private void filter(int lox, int loy, int rux, int ruy, byte filter, int bgcolor) {
+ private void filter(int lox, int loy, int rux, int ruy, final byte filter, final int bgcolor) {
// taking care that all values are legal
if (lox < 0) { lox = 0; }
@@ -492,12 +492,12 @@ public class ymageMatrix {
if (rux > width) { rux = width - 1; }
if (ruy > height){ ruy = height - 1; }
if (lox > rux) {
- int tmp = lox;
+ final int tmp = lox;
lox = rux;
rux = tmp;
}
if (loy > ruy) {
- int tmp = loy;
+ final int tmp = loy;
loy = ruy;
ruy = tmp;
}
@@ -507,10 +507,10 @@ public class ymageMatrix {
int rgbG = 0;
int rgbB = 0;
int rgb = 0;
- int width2 = rux - lox + 1;
- int height2 = ruy - loy + 1;
+ final int width2 = rux - lox + 1;
+ final int height2 = ruy - loy + 1;
boolean border = false;
- BufferedImage image2 = new BufferedImage(width2, height2, BufferedImage.TYPE_INT_RGB);
+ final BufferedImage image2 = new BufferedImage(width2, height2, BufferedImage.TYPE_INT_RGB);
for (int i = lox; i < rux + 1; i++) {
for (int j = loy; j < ruy + 1; j++) {
@@ -609,7 +609,7 @@ public class ymageMatrix {
}
- public static void demoPaint(ymageMatrix m) {
+ public static void demoPaint(final ymageMatrix m) {
m.setColor(GREY);
m.line(0, 70, 100, 70); ymageToolPrint.print(m, 0, 65, 0, "Grey", -1);
m.line(65, 0, 65, 300);
@@ -664,20 +664,20 @@ public class ymageMatrix {
protected serverByteBuffer buffer;
protected int pixel;
protected long access;
- public sbbBuffer(int width, int height) {
+ public sbbBuffer(final int width, final int height) {
this.buffer = new serverByteBuffer();
this.access = System.currentTimeMillis();
this.pixel = width * height;
}
- public boolean enoughSize(int width, int height) {
+ public boolean enoughSize(final int width, final int height) {
return this.pixel >= width * height;
}
- public boolean olderThan(long timeout) {
+ public boolean olderThan(final long timeout) {
return System.currentTimeMillis() - this.access > timeout;
}
}
private static final ArrayList<sbbBuffer> sbbPool = new ArrayList<sbbBuffer>();
- private static serverByteBuffer sbbFromPool(int width, int height, long timeout) {
+ private static serverByteBuffer sbbFromPool(final int width, final int height, final long timeout) {
// returns an Image object from the image pool
// if the pooled Image was created recently (before timeout), it is not used
synchronized (sbbPool) {
@@ -698,32 +698,32 @@ public class ymageMatrix {
}
}
- public static serverByteBuffer exportImage(BufferedImage image, String targetExt) {
+ public static serverByteBuffer exportImage(final BufferedImage image, final String targetExt) {
// generate an byte array from the given image
//serverByteBuffer baos = new serverByteBuffer();
- serverByteBuffer baos = sbbFromPool(image.getWidth(), image.getHeight(), 1000);
+ final serverByteBuffer baos = sbbFromPool(image.getWidth(), image.getHeight(), 1000);
try {
ImageIO.write(image, targetExt, baos);
return baos;
- } catch (IOException e) {
+ } catch (final IOException e) {
// should not happen
e.printStackTrace();
return null;
}
}
- public static void main(String[] args) {
+ public static void main(final String[] args) {
// go into headless awt mode
System.setProperty("java.awt.headless", "true");
- ymageMatrix m = new ymageMatrix(200, 300, MODE_SUB, "FFFFFF");
+ final ymageMatrix m = new ymageMatrix(200, 300, MODE_SUB, "FFFFFF");
demoPaint(m);
- File file = new File("/Users/admin/Desktop/testimage.png");
+ final File file = new File("/Users/admin/Desktop/testimage.png");
try {
- FileOutputStream fos = new FileOutputStream(file);
+ final FileOutputStream fos = new FileOutputStream(file);
ImageIO.write(m.getImage(), "png", fos);
fos.close();
- } catch (IOException e) {}
+ } catch (final IOException e) {}
// open file automatically, works only on Mac OS X
/*
diff --git a/source/de/anomic/ymage/ymageOSM.java b/source/de/anomic/ymage/ymageOSM.java
index 05aad150a..e05375ceb 100644
--- a/source/de/anomic/ymage/ymageOSM.java
+++ b/source/de/anomic/ymage/ymageOSM.java
@@ -43,7 +43,7 @@ public class ymageOSM {
// helper methods to load map images from openstreetmap.org
- public static ymageMatrix getCombinedTiles(tileCoordinates t11) {
+ public static ymageMatrix getCombinedTiles(final tileCoordinates t11) {
tileCoordinates t00, t10, t20, t01, t21, t02, t12, t22;
t00 = new tileCoordinates(t11.xtile - 1, t11.ytile - 1, t11.zoom);
t10 = new tileCoordinates(t11.xtile , t11.ytile - 1, t11.zoom);
@@ -53,7 +53,7 @@ public class ymageOSM {
t02 = new tileCoordinates(t11.xtile - 1, t11.ytile + 1, t11.zoom);
t12 = new tileCoordinates(t11.xtile , t11.ytile + 1, t11.zoom);
t22 = new tileCoordinates(t11.xtile + 1, t11.ytile + 1, t11.zoom);
- ymageMatrix m = new ymageMatrix(768, 768, ymageMatrix.MODE_REPLACE, "FFFFFF");
+ final ymageMatrix m = new ymageMatrix(768, 768, ymageMatrix.MODE_REPLACE, "FFFFFF");
BufferedImage bi;
bi = getSingleTile(t00); if (bi != null) m.insertBitmap(getSingleTile(t00), 0, 0);
bi = getSingleTile(t10); if (bi != null) m.insertBitmap(getSingleTile(t10), 256, 0);
@@ -67,26 +67,26 @@ public class ymageOSM {
return m;
}
- public static BufferedImage getSingleTile(tileCoordinates tile) {
+ public static BufferedImage getSingleTile(final tileCoordinates tile) {
yacyURL tileURL;
try {
tileURL = new yacyURL(tile.url(), null);
- } catch (MalformedURLException e) {
+ } catch (final MalformedURLException e) {
return null;
}
System.out.println("*** DEBUG: fetching OSM tile: " + tileURL.toNormalform(true, true));
InputStream tileStream = plasmaHTCache.getResourceContentStream(tileURL);
if (tileStream == null) {
// download resource using the crawler and keep resource in memory if possible
- plasmaHTCache.Entry entry = plasmaSwitchboard.getSwitchboard().crawlQueues.loadResourceFromWeb(tileURL, 20000, true, false, false);
+ final plasmaHTCache.Entry entry = plasmaSwitchboard.getSwitchboard().crawlQueues.loadResourceFromWeb(tileURL, 20000, true, false, false);
if ((entry == null) || (entry.cacheArray() == null)) return null;
tileStream = new ByteArrayInputStream(entry.cacheArray());
}
try {
return ImageIO.read(tileStream);
- } catch (EOFException e) {
+ } catch (final EOFException e) {
return null;
- } catch (IOException e) {
+ } catch (final IOException e) {
return null;
}
}
@@ -101,7 +101,7 @@ public class ymageOSM {
this.ytile = (int) Math.floor((1 - Math.log(Math.tan(lat * Math.PI / 180) + 1 / Math.cos(lat * Math.PI / 180)) / Math.PI) / 2 * (1 << zoom));
}
- public tileCoordinates(int xtile, int ytile, int zoom) {
+ public tileCoordinates(final int xtile, final int ytile, final int zoom) {
this.zoom = zoom;
this.xtile = xtile;
this.ytile = ytile;
diff --git a/source/de/anomic/ymage/ymageToolCircle.java b/source/de/anomic/ymage/ymageToolCircle.java
index 8da25449c..ab7bc8b8c 100644
--- a/source/de/anomic/ymage/ymageToolCircle.java
+++ b/source/de/anomic/ymage/ymageToolCircle.java
@@ -34,7 +34,7 @@ public class ymageToolCircle {
private static int[][] circles = new int[0][];
- private static int[] getCircleCoords(int radius) {
+ private static int[] getCircleCoords(final int radius) {
if ((radius - 1) < circles.length) return circles[radius - 1];
// read some lines from known circles
@@ -96,11 +96,11 @@ public class ymageToolCircle {
return circles[radius - 1];
}
- public static void circle(ymageMatrix matrix, int xc, int yc, int radius) {
+ public static void circle(final ymageMatrix matrix, final int xc, final int yc, final int radius) {
if (radius == 0) {
matrix.plot(xc, yc);
} else {
- int[] c = getCircleCoords(radius);
+ final int[] c = getCircleCoords(radius);
int x, y;
for (int i = (c.length / 2) - 1; i >= 0; i--) {
x = c[2 * i ];
@@ -113,15 +113,15 @@ public class ymageToolCircle {
}
}
- public static void circle(ymageMatrix matrix, int xc, int yc, int radius, int fromArc, int toArc) {
+ public static void circle(final ymageMatrix matrix, final int xc, final int yc, final int radius, final int fromArc, final int toArc) {
// draws only a part of a circle
// arc is given in degree
if (radius == 0) {
matrix.plot(xc, yc);
} else {
- int[] c = getCircleCoords(radius);
- int q = c.length / 2;
- int[][] c4 = new int[q * 4][];
+ final int[] c = getCircleCoords(radius);
+ final int q = c.length / 2;
+ final int[][] c4 = new int[q * 4][];
for (int i = 0; i < q; i++) {
c4[i ] = new int[]{ c[2 * (i )], -c[2 * (i ) + 1] - 1}; // quadrant 1
c4[i + q] = new int[]{1 - c[2 * (q - 1 - i)], -c[2 * (q - 1 - i) + 1] - 1}; // quadrant 2
diff --git a/source/de/anomic/ymage/ymageToolPrint.java b/source/de/anomic/ymage/ymageToolPrint.java
index 720f8b4e5..2665258ef 100644
--- a/source/de/anomic/ymage/ymageToolPrint.java
+++ b/source/de/anomic/ymage/ymageToolPrint.java
@@ -44,8 +44,8 @@ public class ymageToolPrint {
0x0000000EC2E0ECL,0x0000000EC2E030L,0x0000000FF2E3FCL,0x000F0B8B80B80FL,0x00300C0300C030L,0x03C0B80B8B83C0L,0x0000B83BB0B800L,0x03FFC0F03C0FFFL
};
- private static void print(ymageMatrix matrix, int x, int y, int angle, char letter) {
- int index = letter - 0x20;
+ private static void print(final ymageMatrix matrix, int x, int y, final int angle, final char letter) {
+ final int index = letter - 0x20;
if (index >= font.length) return;
long character = font[index];
long row;
@@ -74,7 +74,7 @@ public class ymageToolPrint {
}
}
- public static void print(ymageMatrix matrix, int x, int y, int angle, String message, int align) {
+ public static void print(final ymageMatrix matrix, final int x, final int y, final int angle, final String message, final int align) {
// align = -1 : left
// align = 1 : right
// align = 0 : center
@@ -95,9 +95,9 @@ public class ymageToolPrint {
private static final int arcDist = 8;
- public static void arcPrint(ymageMatrix matrix, int cx, int cy, int radius, int angle, String message) {
- int x = cx + (int) ((radius + 1) * Math.cos(Math.PI * angle / 180));
- int y = cy - (int) ((radius + 1) * Math.sin(Math.PI * angle / 180));
+ public static void arcPrint(final ymageMatrix matrix, final int cx, final int cy, final int radius, final int angle, final String message) {
+ final int x = cx + (int) ((radius + 1) * Math.cos(Math.PI * angle / 180));
+ final int y = cy - (int) ((radius + 1) * Math.sin(Math.PI * angle / 180));
int yp = y + 3;
if ((angle > arcDist) && (angle < 180 - arcDist)) yp = y;
if ((angle > 180 + arcDist) && (angle < 360 - arcDist)) yp = y + 6;
diff --git a/source/genpw.java b/source/genpw.java
index 166528be6..591da05f0 100644
--- a/source/genpw.java
+++ b/source/genpw.java
@@ -26,7 +26,7 @@ import de.anomic.server.serverCodings;
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
public class genpw {
- public static void main(String[] args){
+ public static void main(final String[] args){
String username="";
String password="";
if(args.length==2){
@@ -39,11 +39,11 @@ public class genpw {
username="admin";
}
if(args.length<1){
- BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
+ final BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
username="admin";
try {
password=br.readLine();
- } catch (IOException e) {
+ } catch (final IOException e) {
System.err.println("IOException while reading from stdin");
System.exit(1);
}
diff --git a/source/migration.java b/source/migration.java
index 7e7cf5642..bd68fac6f 100644
--- a/source/migration.java
+++ b/source/migration.java
@@ -33,11 +33,11 @@ public class migration {
public static final int USE_WORK_DIR=1389; //wiki & messages in DATA/WORK
public static final int TAGDB_WITH_TAGHASH=1635; //tagDB keys are tagHashes instead of plain tagname.
public static final int NEW_OVERLAYS=4422;
- public static void main(String[] args) {
+ public static void main(final String[] args) {
}
- public static void migrate(plasmaSwitchboard sb, int fromRev, int toRev){
+ public static void migrate(final plasmaSwitchboard sb, final int fromRev, final int toRev){
if(fromRev < toRev){
if(fromRev < TAGDB_WITH_TAGHASH){
migrateBookmarkTagsDB(sb);
@@ -55,7 +55,7 @@ public class migration {
/*
* remove the static defaultfiles. We use them through a overlay now.
*/
- public static void migrateDefaultFiles(plasmaSwitchboard sb){
+ public static void migrateDefaultFiles(final plasmaSwitchboard sb){
File file=new File(sb.htDocsPath, "share/dir.html");
if(file.exists())
file.delete();
@@ -75,7 +75,7 @@ public class migration {
if(file.exists())
file.delete();
}
- public static void installSkins(plasmaSwitchboard sb){
+ public static void installSkins(final plasmaSwitchboard sb){
final File skinsPath = sb.getConfigPath("skinPath", "DATA/SKINS");
final File defaultSkinsPath = new File(sb.getRootPath(), "skins");
if(defaultSkinsPath.exists()){
@@ -85,7 +85,7 @@ public class migration {
if(skinFiles[i].endsWith(".css")){
try{
serverFileUtils.copy(new File(defaultSkinsPath, skinFiles[i]), new File(skinsPath, skinFiles[i]));
- }catch(IOException e){}
+ }catch(final IOException e){}
}
}
}
@@ -93,10 +93,10 @@ public class migration {
if(skin.equals("")){
skin="default";
}
- File skinsDir=sb.getConfigPath("skinPath", "DATA/SKINS");
- File skinFile=new File(skinsDir, skin+".css");
- File htdocsPath=new File(sb.getConfigPath(plasmaSwitchboard.HTDOCS_PATH, plasmaSwitchboard.HTROOT_PATH_DEFAULT), "env");
- File styleFile=new File(htdocsPath, "style.css");
+ final File skinsDir=sb.getConfigPath("skinPath", "DATA/SKINS");
+ final File skinFile=new File(skinsDir, skin+".css");
+ final File htdocsPath=new File(sb.getConfigPath(plasmaSwitchboard.HTDOCS_PATH, plasmaSwitchboard.HTROOT_PATH_DEFAULT), "env");
+ final File styleFile=new File(htdocsPath, "style.css");
if(!skinFile.exists()){
if(styleFile.exists()){
serverLog.logInfo("MIGRATION", "Skin "+skin+" not found. Keeping old skin.");
@@ -108,21 +108,21 @@ public class migration {
styleFile.getParentFile().mkdirs();
serverFileUtils.copy(skinFile, styleFile);
serverLog.logInfo("MIGRATION", "copied new Skinfile");
- } catch (IOException e) {
+ } catch (final IOException e) {
serverLog.logSevere("MIGRATION", "Cannot copy skinfile.");
}
}
}
- public static void migrateBookmarkTagsDB(plasmaSwitchboard sb){
+ public static void migrateBookmarkTagsDB(final plasmaSwitchboard sb){
sb.bookmarksDB.close();
- File tagsDBFile=new File(sb.workPath, "bookmarkTags.db");
+ final File tagsDBFile=new File(sb.workPath, "bookmarkTags.db");
if(tagsDBFile.exists()){
tagsDBFile.delete();
serverLog.logInfo("MIGRATION", "Migrating bookmarkTags.db to use wordhashs as keys.");
}
sb.initBookmarks();
}
- public static void migrateWorkFiles(plasmaSwitchboard sb){
+ public static void migrateWorkFiles(final plasmaSwitchboard sb){
File file=new File(sb.getRootPath(), "DATA/SETTINGS/wiki.db");
File file2;
if (file.exists()) {
@@ -132,7 +132,7 @@ public class migration {
try {
serverFileUtils.copy(file, file2);
file.delete();
- } catch (IOException e) {
+ } catch (final IOException e) {
}
file = new File(sb.getRootPath(), "DATA/SETTINGS/wiki-bkp.db");
@@ -142,7 +142,7 @@ public class migration {
try {
serverFileUtils.copy(file, file2);
file.delete();
- } catch (IOException e) {}
+ } catch (final IOException e) {}
}
sb.initWiki();
}
@@ -156,12 +156,12 @@ public class migration {
try {
serverFileUtils.copy(file, file2);
file.delete();
- } catch (IOException e) {}
+ } catch (final IOException e) {}
sb.initMessages();
}
}
- public static void presetPasswords(plasmaSwitchboard sb) {
+ public static void presetPasswords(final plasmaSwitchboard sb) {
// set preset accounts/passwords
String acc;
if ((acc = sb.getConfig("serverAccount", "")).length() > 0) {
@@ -196,7 +196,7 @@ public class migration {
}
}
- public static void migrateSwitchConfigSettings(plasmaSwitchboard sb) {
+ public static void migrateSwitchConfigSettings(final plasmaSwitchboard sb) {
// migration for additional parser settings
String value = "";
diff --git a/source/screenshot.java b/source/screenshot.java
index 6e666e5e0..2077df5ba 100755
--- a/source/screenshot.java
+++ b/source/screenshot.java
@@ -20,15 +20,15 @@ public class screenshot {
} catch (AWTException e) {
}
*/
- public static void main(String[] args) throws Exception {
+ public static void main(final String[] args) throws Exception {
- Toolkit toolkit = Toolkit.getDefaultToolkit();
- Dimension screenSize = toolkit.getScreenSize();
- Rectangle screenRect = new Rectangle(screenSize);
+ final Toolkit toolkit = Toolkit.getDefaultToolkit();
+ final Dimension screenSize = toolkit.getScreenSize();
+ final Rectangle screenRect = new Rectangle(screenSize);
// create screen shot
- Robot robot = new Robot();
- BufferedImage image = robot.createScreenCapture(screenRect);
- String outFileName = "test.png";
+ final Robot robot = new Robot();
+ final BufferedImage image = robot.createScreenCapture(screenRect);
+ final String outFileName = "test.png";
// save captured image to PNG file
ImageIO.write(image, "png", new File(outFileName));
// give feedback
diff --git a/source/yacy.java b/source/yacy.java
index 22c07863f..4ba4e39d7 100644
--- a/source/yacy.java
+++ b/source/yacy.java
@@ -153,7 +153,7 @@ public final class yacy {
* @param homePath Root-path where all information is to be found.
* @param startupFree free memory at startup time, to be used later for statistics
*/
- private static void startup(File homePath, long startupMemFree, long startupMemTotal) {
+ private static void startup(final File homePath, final long startupMemFree, final long startupMemTotal) {
int oldRev=0;
int newRev=0;
@@ -165,7 +165,7 @@ public final class yacy {
// check java version
try {
"a".codePointAt(0); // needs at least Java 1.5
- } catch (NoSuchMethodError e) {
+ } catch (final NoSuchMethodError e) {
System.err.println("STARTUP: Java Version too low. You need at least Java 1.5 to run YaCy");
Thread.sleep(3000);
System.exit(-1);
@@ -185,12 +185,12 @@ public final class yacy {
f = new File(homePath, "DATA/LOG/yacy.logging");
if (!f.exists()) try {
serverFileUtils.copy(new File(homePath, "yacy.logging"), f);
- } catch (IOException e){
+ } catch (final IOException e){
System.out.println("could not copy yacy.logging");
}
try{
serverLog.configureLogging(homePath, new File(homePath, "DATA/LOG/yacy.logging"));
- } catch (IOException e) {
+ } catch (final IOException e) {
System.out.println("could not find logging properties in homePath=" + homePath);
e.printStackTrace();
}
@@ -209,9 +209,9 @@ public final class yacy {
f.deleteOnExit();
pro = new File(homePath, "libx").exists();
- String oldconf = "DATA/SETTINGS/httpProxy.conf".replace("/", File.separator);
- String newconf = "DATA/SETTINGS/yacy.conf".replace("/", File.separator);
- File oldconffile = new File(homePath, oldconf);
+ final String oldconf = "DATA/SETTINGS/httpProxy.conf".replace("/", File.separator);
+ final String newconf = "DATA/SETTINGS/yacy.conf".replace("/", File.separator);
+ final File oldconffile = new File(homePath, oldconf);
if (oldconffile.exists()) {
oldconffile.renameTo(new File(homePath, newconf));
}
@@ -228,10 +228,10 @@ public final class yacy {
// if we are running an SVN version, we try to detect the used svn revision now ...
final Properties buildProp = new Properties();
- File buildPropFile = new File(homePath,"build.properties");
+ final File buildPropFile = new File(homePath,"build.properties");
try {
buildProp.load(new FileInputStream(buildPropFile));
- } catch (Exception e) {
+ } catch (final Exception e) {
serverLog.logWarning("STARTUP", buildPropFile.toString() + " not found in settings path");
}
@@ -245,14 +245,14 @@ public final class yacy {
if (matcher.find()) {
final String svrReleaseNr = matcher.group(1);
try {
- try {version = Double.parseDouble(vString);} catch (NumberFormatException e) {version = (float) 0.1;}
+ try {version = Double.parseDouble(vString);} catch (final NumberFormatException e) {version = (float) 0.1;}
version = yacyVersion.versvn2combinedVersion(version, Integer.parseInt(svrReleaseNr));
- } catch (NumberFormatException e) {}
+ } catch (final NumberFormatException e) {}
sb.setConfig("svnRevision", svrReleaseNr);
}
}
newRev=Integer.parseInt(sb.getConfig("svnRevision", "0"));
- } catch (Exception e) {
+ } catch (final Exception e) {
System.err.println("Unable to determine the currently used SVN revision number.");
}
@@ -264,7 +264,7 @@ public final class yacy {
yacyVersion.latestRelease = version;
// read environment
- int timeout = Math.max(20000, Integer.parseInt(sb.getConfig("httpdTimeout", "20000")));
+ final int timeout = Math.max(20000, Integer.parseInt(sb.getConfig("httpdTimeout", "20000")));
// create some directories
final File htRootPath = new File(homePath, sb.getConfig("htRootPath", "htroot"));
@@ -277,7 +277,7 @@ public final class yacy {
if (!((new File(htDocsPath, "notifier.gif")).exists())) try {
serverFileUtils.copy(new File(htRootPath, "env/grafics/empty.gif"),
new File(htDocsPath, "notifier.gif"));
- } catch (IOException e) {}
+ } catch (final IOException e) {}
final File htdocsReadme = new File(htDocsPath, "readme.txt");
if (!(htdocsReadme.exists())) try {serverFileUtils.copy((
@@ -292,7 +292,7 @@ public final class yacy {
"This directory shares it's content with the applications htroot path, so you\r\n" +
"may access your yacy search page with\r\n" +
"http://<your-peer-name>.yacy/\r\n" +
- "\r\n").getBytes(), htdocsReadme);} catch (IOException e) {
+ "\r\n").getBytes(), htdocsReadme);} catch (final IOException e) {
System.out.println("Error creating htdocs readme: " + e.getMessage());
}
@@ -306,7 +306,7 @@ public final class yacy {
migration.migrate(sb, oldRev, newRev);
// delete old release files
- int deleteOldDownloadsAfterDays = (int) sb.getConfigLong("update.deleteOld", 30);
+ final int deleteOldDownloadsAfterDays = (int) sb.getConfigLong("update.deleteOld", 30);
yacyVersion.deleteOldDownloads(sb.releasePath, deleteOldDownloadsAfterDays );
// set user-agent
@@ -337,7 +337,7 @@ public final class yacy {
// open the browser window
final boolean browserPopUpTrigger = sb.getConfig("browserPopUpTrigger", "true").equals("true");
if (browserPopUpTrigger) {
- String browserPopUpPage = sb.getConfig("browserPopUpPage", "ConfigBasic.html");
+ final String browserPopUpPage = sb.getConfig("browserPopUpPage", "ConfigBasic.html");
//boolean properPW = (sb.getConfig("adminAccount", "").length() == 0) && (sb.getConfig(httpd.ADMIN_ACCOUNT_B64MD5, "").length() > 0);
//if (!properPW) browserPopUpPage = "ConfigBasic.html";
final String browserPopUpApplication = sb.getConfig("browserPopUpApplication", "netscape");
@@ -362,7 +362,7 @@ public final class yacy {
}
}
serverLog.logInfo("STARTUP", "Copied the default locales to " + locale_work.toString());
- }catch(NullPointerException e){
+ }catch(final NullPointerException e){
serverLog.logSevere("STARTUP", "Nullpointer Exception while copying the default Locales");
}
@@ -374,7 +374,7 @@ public final class yacy {
final BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(sb.getConfigPath("locale.translated_html", "DATA/LOCALE/htroot"), lang+"/version" ))));
currentRev = br.readLine();
br.close();
- }catch(IOException e){
+ }catch(final IOException e){
//Error
}
@@ -387,7 +387,7 @@ public final class yacy {
bw.write(sb.getConfig("svnRevision", "Error getting Version"));
bw.close();
}
- } catch (IOException e) {}
+ } catch (final IOException e) {}
}
// initialize number formatter with this locale
yFormatter.setLocale(lang);
@@ -412,7 +412,7 @@ public final class yacy {
// wait for server shutdown
try {
sb.waitForShutdown();
- } catch (Exception e) {
+ } catch (final Exception e) {
serverLog.logSevere("MAIN CONTROL LOOP", "PANIC: " + e.getMessage(),e);
}
// shut down
@@ -423,10 +423,10 @@ public final class yacy {
server.close();
if (server.isAlive()) try {
// TODO only send request, don't read response (cause server is already down resulting in error)
- yacyURL u = new yacyURL((server.withSSL()?"https":"http")+"://localhost:" + serverCore.getPortNr(port), null);
+ final yacyURL u = new yacyURL((server.withSSL()?"https":"http")+"://localhost:" + serverCore.getPortNr(port), null);
HttpClient.wget(u.toString(), null, 10000); // kick server
serverLog.logConfig("SHUTDOWN", "sent termination signal to server socket");
- } catch (IOException ee) {
+ } catch (final IOException ee) {
serverLog.logConfig("SHUTDOWN", "termination signal to server socket missed (server shutdown, ok)");
}
JakartaCommonsHttpClient.closeAllConnections();
@@ -442,11 +442,11 @@ public final class yacy {
sb.close();
MultiThreadedHttpConnectionManager.shutdownAll();
}
- } catch (Exception e) {
+ } catch (final Exception e) {
serverLog.logSevere("STARTUP", "Unexpected Error: " + e.getClass().getName(),e);
//System.exit(1);
}
- } catch (Exception ee) {
+ } catch (final Exception ee) {
serverLog.logSevere("STARTUP", "FATAL ERROR: " + ee.getMessage(),ee);
} finally {
startupFinishedSync.V();
@@ -467,23 +467,23 @@ public final class yacy {
* @param homePath Root-path where all the information is to be found.
* @return Properties read from the configurationfile.
*/
- private static Properties configuration(String mes, File homePath) {
+ private static Properties configuration(final String mes, final File homePath) {
serverLog.logConfig(mes, "Application Root Path: " + homePath.toString());
// read data folder
- File dataFolder = new File(homePath, "DATA");
+ final File dataFolder = new File(homePath, "DATA");
if (!(dataFolder.exists())) {
serverLog.logSevere(mes, "Application was never started or root path wrong.");
System.exit(-1);
}
- Properties config = new Properties();
+ final Properties config = new Properties();
try {
config.load(new FileInputStream(new File(homePath, "DATA/SETTINGS/yacy.conf")));
- } catch (FileNotFoundException e) {
+ } catch (final FileNotFoundException e) {
serverLog.logSevere(mes, "could not find configuration file.");
System.exit(-1);
- } catch (IOException e) {
+ } catch (final IOException e) {
serverLog.logSevere(mes, "could not read configuration file.");
System.exit(-1);
}
@@ -496,7 +496,7 @@ public final class yacy {
// YaCy is running in the same runtime. we can shutdown via interrupt
sb.terminate();
} else {
- File applicationRoot = new File(System.getProperty("user.dir").replace('\\', '/'));
+ final File applicationRoot = new File(System.getProperty("user.dir").replace('\\', '/'));
shutdown(applicationRoot);
}
}
@@ -507,24 +507,24 @@ public final class yacy {
*
* @param homePath Root-path where all the information is to be found.
*/
- static void shutdown(File homePath) {
+ static void shutdown(final File homePath) {
// start up
System.out.println(copyright);
System.out.println(hline);
- Properties config = configuration("REMOTE-SHUTDOWN", homePath);
+ final Properties config = configuration("REMOTE-SHUTDOWN", homePath);
// read port
- int port = serverCore.getPortNr(config.getProperty("port", "8080"));
+ final int port = serverCore.getPortNr(config.getProperty("port", "8080"));
// read password
String encodedPassword = (String) config.get(httpd.ADMIN_ACCOUNT_B64MD5);
if (encodedPassword == null) encodedPassword = ""; // not defined
// send 'wget' to web interface
- httpHeader requestHeader = new httpHeader();
+ final httpHeader requestHeader = new httpHeader();
requestHeader.put(httpHeader.AUTHORIZATION, "realm=" + encodedPassword); // for http-authentify
- JakartaCommonsHttpClient con = new JakartaCommonsHttpClient(10000, requestHeader, null);
+ final JakartaCommonsHttpClient con = new JakartaCommonsHttpClient(10000, requestHeader, null);
JakartaCommonsHttpResponse res = null;
try {
res = con.GET("http://localhost:"+ port +"/Steering.html?shutdown=");
@@ -533,7 +533,7 @@ public final class yacy {
if (res.getStatusLine().startsWith("2")) {
serverLog.logConfig("REMOTE-SHUTDOWN", "YACY accepted shutdown command.");
serverLog.logConfig("REMOTE-SHUTDOWN", "Stand by for termination, which may last some seconds.");
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ final ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
serverFileUtils.copyToStream(new BufferedInputStream(res.getDataAsStream()), new BufferedOutputStream(bos));
} finally {
@@ -543,7 +543,7 @@ public final class yacy {
serverLog.logSevere("REMOTE-SHUTDOWN", "error response from YACY socket: " + res.getStatusLine());
System.exit(-1);
}
- } catch (IOException e) {
+ } catch (final IOException e) {
serverLog.logSevere("REMOTE-SHUTDOWN", "could not establish connection to YACY socket: " + e.getMessage());
System.exit(-1);
} finally {
@@ -568,24 +568,24 @@ public final class yacy {
*
* @param homePath Root-Path where all the information is to be found.
*/
- private static void genWordstat(File homePath) {
+ private static void genWordstat(final File homePath) {
// start up
System.out.println(copyright);
System.out.println(hline);
- Properties config = configuration("GEN-WORDSTAT", homePath);
+ final Properties config = configuration("GEN-WORDSTAT", homePath);
// load words
serverLog.logInfo("GEN-WORDSTAT", "loading words...");
- HashMap<String, String> words = loadWordMap(new File(homePath, "yacy.words"));
+ final HashMap<String, String> words = loadWordMap(new File(homePath, "yacy.words"));
// find all hashes
serverLog.logInfo("GEN-WORDSTAT", "searching all word-hash databases...");
- File dbRoot = new File(homePath, config.getProperty("dbPath"));
- enumerateFiles ef = new enumerateFiles(new File(dbRoot, "WORDS"), true, false, true, true);
+ final File dbRoot = new File(homePath, config.getProperty("dbPath"));
+ final enumerateFiles ef = new enumerateFiles(new File(dbRoot, "WORDS"), true, false, true, true);
File f;
String h;
- kelondroMScoreCluster<String> hs = new kelondroMScoreCluster<String>();
+ final kelondroMScoreCluster<String> hs = new kelondroMScoreCluster<String>();
while (ef.hasMoreElements()) {
f = ef.nextElement();
h = f.getName().substring(0, yacySeedDB.commonHashLength);
@@ -595,7 +595,7 @@ public final class yacy {
// list the hashes in reverse order
serverLog.logInfo("GEN-WORDSTAT", "listing words in reverse size order...");
String w;
- Iterator<String> i = hs.scores(false);
+ final Iterator<String> i = hs.scores(false);
while (i.hasNext()) {
h = i.next();
w = words.get(h);
@@ -611,27 +611,27 @@ public final class yacy {
* @param homePath path to the YaCy directory
* @param networkName
*/
- public static void minimizeUrlDB(File homePath, String networkName) {
+ public static void minimizeUrlDB(final File homePath, final String networkName) {
// run with "java -classpath classes yacy -minimizeUrlDB"
- try {serverLog.configureLogging(homePath, new File(homePath, "DATA/LOG/yacy.logging"));} catch (Exception e) {}
- File indexPrimaryRoot = new File(homePath, "DATA/INDEX");
- File indexSecondaryRoot = new File(homePath, "DATA/INDEX");
- File indexRoot2 = new File(homePath, "DATA/INDEX2");
- serverLog log = new serverLog("URL-CLEANUP");
+ try {serverLog.configureLogging(homePath, new File(homePath, "DATA/LOG/yacy.logging"));} catch (final Exception e) {}
+ final File indexPrimaryRoot = new File(homePath, "DATA/INDEX");
+ final File indexSecondaryRoot = new File(homePath, "DATA/INDEX");
+ final File indexRoot2 = new File(homePath, "DATA/INDEX2");
+ final serverLog log = new serverLog("URL-CLEANUP");
try {
log.logInfo("STARTING URL CLEANUP");
// db containing all currently loades urls
- indexRepositoryReference currentUrlDB = new indexRepositoryReference(new File(indexSecondaryRoot, networkName));
+ final indexRepositoryReference currentUrlDB = new indexRepositoryReference(new File(indexSecondaryRoot, networkName));
// db used to hold all neede urls
- indexRepositoryReference minimizedUrlDB = new indexRepositoryReference(new File(indexRoot2, networkName));
+ final indexRepositoryReference minimizedUrlDB = new indexRepositoryReference(new File(indexRoot2, networkName));
- int cacheMem = (int)(serverMemory.max() - serverMemory.total());
+ final int cacheMem = (int)(serverMemory.max() - serverMemory.total());
if (cacheMem < 2048000) throw new OutOfMemoryError("Not enough memory available to start clean up.");
- plasmaWordIndex wordIndex = new plasmaWordIndex(networkName, log, indexPrimaryRoot, indexSecondaryRoot, 10000);
- Iterator<indexContainer> indexContainerIterator = wordIndex.wordContainers("AAAAAAAAAAAA", false, false);
+ final plasmaWordIndex wordIndex = new plasmaWordIndex(networkName, log, indexPrimaryRoot, indexSecondaryRoot, 10000);
+ final Iterator<indexContainer> indexContainerIterator = wordIndex.wordContainers("AAAAAAAAAAAA", false, false);
long urlCounter = 0, wordCounter = 0;
long wordChunkStart = System.currentTimeMillis(), wordChunkEnd = 0;
@@ -644,25 +644,25 @@ public final class yacy {
wordIdxContainer = indexContainerIterator.next();
// the combined container will fit, read the container
- Iterator<indexRWIRowEntry> wordIdxEntries = wordIdxContainer.entries();
+ final Iterator<indexRWIRowEntry> wordIdxEntries = wordIdxContainer.entries();
indexRWIEntry iEntry;
while (wordIdxEntries.hasNext()) {
iEntry = wordIdxEntries.next();
- String urlHash = iEntry.urlHash();
+ final String urlHash = iEntry.urlHash();
if ((currentUrlDB.exists(urlHash)) && (!minimizedUrlDB.exists(urlHash))) try {
- indexURLReference urlEntry = currentUrlDB.load(urlHash, null, 0);
+ final indexURLReference urlEntry = currentUrlDB.load(urlHash, null, 0);
urlCounter++;
minimizedUrlDB.store(urlEntry);
if (urlCounter % 500 == 0) {
log.logInfo(urlCounter + " URLs found so far.");
}
- } catch (IOException e) {}
+ } catch (final IOException e) {}
}
if (wordCounter%500 == 0) {
wordChunkEndHash = wordIdxContainer.getWordHash();
wordChunkEnd = System.currentTimeMillis();
- long duration = wordChunkEnd - wordChunkStart;
+ final long duration = wordChunkEnd - wordChunkStart;
log.logInfo(wordCounter + " words scanned " +
"[" + wordChunkStartHash + " .. " + wordChunkEndHash + "]\n" +
"Duration: "+ 500*1000/duration + " words/s" +
@@ -675,10 +675,10 @@ public final class yacy {
// we have read all elements, now we can close it
wordIdxContainer = null;
- } catch (Exception e) {
+ } catch (final Exception e) {
log.logSevere("Exception", e);
} finally {
- if (wordIdxContainer != null) try { wordIdxContainer = null; } catch (Exception e) {}
+ if (wordIdxContainer != null) try { wordIdxContainer = null; } catch (final Exception e) {}
}
}
log.logInfo("current LURL DB contains " + currentUrlDB.size() + " entries.");
@@ -694,9 +694,9 @@ public final class yacy {
log.logInfo("You can now backup your old URL DB and rename minimized/urlHash.db to urlHash.db");
log.logInfo("TERMINATED URL CLEANUP");
- } catch (Exception e) {
+ } catch (final Exception e) {
log.logSevere("Exception: " + e.getMessage(), e);
- } catch (Error e) {
+ } catch (final Error e) {
log.logSevere("Error: " + e.getMessage(), e);
}
}
@@ -708,15 +708,15 @@ public final class yacy {
* @param wordlist File where the words are stored.
* @return HashMap with the hash-word - relation.
*/
- private static HashMap<String, String> loadWordMap(File wordlist) {
+ private static HashMap<String, String> loadWordMap(final File wordlist) {
// returns a hash-word - Relation
- HashMap<String, String> wordmap = new HashMap<String, String>();
+ final HashMap<String, String> wordmap = new HashMap<String, String>();
try {
String word;
- BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(wordlist)));
+ final BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(wordlist)));
while ((word = br.readLine()) != null) wordmap.put(indexWord.word2hash(word), word);
br.close();
- } catch (IOException e) {}
+ } catch (final IOException e) {}
return wordmap;
}
@@ -729,18 +729,18 @@ public final class yacy {
* @param minlength Minimal needed length for each word to be stored.
* @param maxlength Maximal allowed length for each word to be stored.
*/
- private static void cleanwordlist(String wordlist, int minlength, int maxlength) {
+ private static void cleanwordlist(final String wordlist, final int minlength, final int maxlength) {
// start up
System.out.println(copyright);
System.out.println(hline);
serverLog.logConfig("CLEAN-WORDLIST", "START");
String word;
- TreeSet<String> wordset = new TreeSet<String>();
+ final TreeSet<String> wordset = new TreeSet<String>();
int count = 0;
try {
- BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(wordlist)));
- String seps = "' .,:/-&";
+ final BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(wordlist)));
+ final String seps = "' .,:/-&";
while ((word = br.readLine()) != null) {
word = word.toLowerCase().trim();
for (int i = 0; i < seps.length(); i++) {
@@ -753,7 +753,7 @@ public final class yacy {
if (wordset.size() != count) {
count = count - wordset.size();
- BufferedWriter bw = new BufferedWriter(new PrintWriter(new FileWriter(wordlist)));
+ final BufferedWriter bw = new BufferedWriter(new PrintWriter(new FileWriter(wordlist)));
while (wordset.size() > 0) {
word = wordset.first();
bw.write(word + "\n");
@@ -764,7 +764,7 @@ public final class yacy {
} else {
serverLog.logInfo("CLEAN-WORDLIST", "not necessary to change wordlist");
}
- } catch (IOException e) {
+ } catch (final IOException e) {
serverLog.logSevere("CLEAN-WORDLIST", "ERROR: " + e.getMessage());
System.exit(-1);
}
@@ -773,22 +773,22 @@ public final class yacy {
serverLog.logConfig("CLEAN-WORDLIST", "FINISHED");
}
- private static void transferCR(String targetaddress, String crfile) {
- File f = new File(crfile);
+ private static void transferCR(final String targetaddress, final String crfile) {
+ final File f = new File(crfile);
try {
- byte[] b = serverFileUtils.read(f);
- String result = yacyClient.transfer(targetaddress, f.getName(), b);
+ final byte[] b = serverFileUtils.read(f);
+ final String result = yacyClient.transfer(targetaddress, f.getName(), b);
if (result == null)
serverLog.logInfo("TRANSFER-CR", "transmitted file " + crfile + " to " + targetaddress + " successfully");
else
serverLog.logInfo("TRANSFER-CR", "error transmitting file " + crfile + " to " + targetaddress + ": " + result);
- } catch (IOException e) {
+ } catch (final IOException e) {
serverLog.logInfo("TRANSFER-CR", "could not read file " + crfile);
}
}
- private static String[] shift(String[] args, int pos, int count) {
- String[] newargs = new String[args.length - count];
+ private static String[] shift(final String[] args, final int pos, final int count) {
+ final String[] newargs = new String[args.length - count];
System.arraycopy(args, 0, newargs, 0, pos);
System.arraycopy(args, pos + count, newargs, pos, args.length - pos - count);
return newargs;
@@ -800,24 +800,24 @@ public final class yacy {
*
* @param homePath Root-Path where all information is to be found.
*/
- private static void urldbcleanup(File homePath, String networkName) {
- File root = homePath;
- File indexroot = new File(root, "DATA/INDEX");
- try {serverLog.configureLogging(homePath, new File(homePath, "DATA/LOG/yacy.logging"));} catch (Exception e) {}
- indexRepositoryReference currentUrlDB = new indexRepositoryReference(new File(indexroot, networkName));
+ private static void urldbcleanup(final File homePath, final String networkName) {
+ final File root = homePath;
+ final File indexroot = new File(root, "DATA/INDEX");
+ try {serverLog.configureLogging(homePath, new File(homePath, "DATA/LOG/yacy.logging"));} catch (final Exception e) {}
+ final indexRepositoryReference currentUrlDB = new indexRepositoryReference(new File(indexroot, networkName));
currentUrlDB.deadlinkCleaner(null);
currentUrlDB.close();
}
- private static void RWIHashList(File homePath, String targetName, String resource, String format) {
+ private static void RWIHashList(final File homePath, final String targetName, final String resource, final String format) {
plasmaWordIndex WordIndex = null;
- serverLog log = new serverLog("HASHLIST");
- File indexPrimaryRoot = new File(homePath, "DATA/INDEX");
- File indexSecondaryRoot = new File(homePath, "DATA/INDEX");
- String wordChunkStartHash = "AAAAAAAAAAAA";
- try {serverLog.configureLogging(homePath, new File(homePath, "DATA/LOG/yacy.logging"));} catch (Exception e) {}
+ final serverLog log = new serverLog("HASHLIST");
+ final File indexPrimaryRoot = new File(homePath, "DATA/INDEX");
+ final File indexSecondaryRoot = new File(homePath, "DATA/INDEX");
+ final String wordChunkStartHash = "AAAAAAAAAAAA";
+ try {serverLog.configureLogging(homePath, new File(homePath, "DATA/LOG/yacy.logging"));} catch (final Exception e) {}
log.logInfo("STARTING CREATION OF RWI-HASHLIST");
- File root = homePath;
+ final File root = homePath;
try {
Iterator<indexContainer> indexContainerIterator = null;
if (resource.equals("all")) {
@@ -828,9 +828,9 @@ public final class yacy {
indexContainer container = null;
if (format.equals("zip")) {
log.logInfo("Writing Hashlist to ZIP-file: " + targetName + ".zip");
- ZipEntry zipEntry = new ZipEntry(targetName + ".txt");
- File file = new File(root, targetName + ".zip");
- ZipOutputStream bos = new ZipOutputStream(new FileOutputStream(file));
+ final ZipEntry zipEntry = new ZipEntry(targetName + ".txt");
+ final File file = new File(root, targetName + ".zip");
+ final ZipOutputStream bos = new ZipOutputStream(new FileOutputStream(file));
bos.putNextEntry(zipEntry);
if(indexContainerIterator != null) {
while (indexContainerIterator.hasNext()) {
@@ -847,8 +847,8 @@ public final class yacy {
bos.close();
} else {
log.logInfo("Writing Hashlist to TXT-file: " + targetName + ".txt");
- File file = new File(root, targetName + ".txt");
- BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
+ final File file = new File(root, targetName + ".txt");
+ final BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
if(indexContainerIterator != null) {
while (indexContainerIterator.hasNext()) {
counter++;
@@ -864,7 +864,7 @@ public final class yacy {
bos.close();
}
log.logInfo("Total number of Hashs: " + counter + ". Last found Hash: " + (container == null ? "null" : container.getWordHash()));
- } catch (IOException e) {
+ } catch (final IOException e) {
log.logSevere("IOException", e);
}
if (WordIndex != null) {
@@ -877,25 +877,25 @@ public final class yacy {
* Searching for peers affected by Bug
* @param homePath
*/
- public static void testPeerDB(File homePath) {
+ public static void testPeerDB(final File homePath) {
try {
- File yacyDBPath = new File(homePath, "DATA/INDEX/freeworld/NETWORK");
+ final File yacyDBPath = new File(homePath, "DATA/INDEX/freeworld/NETWORK");
- String[] dbFileNames = {"seed.new.db","seed.old.db","seed.pot.db"};
+ final String[] dbFileNames = {"seed.new.db","seed.old.db","seed.pot.db"};
for (int i=0; i < dbFileNames.length; i++) {
- File dbFile = new File(yacyDBPath,dbFileNames[i]);
- kelondroMapDataMining db = new kelondroMapDataMining(new kelondroBLOBTree(dbFile, true, true, yacySeedDB.commonHashLength, 480, '#', kelondroBase64Order.enhancedCoder, true, false, true), 500, yacySeedDB.sortFields, yacySeedDB.longaccFields, yacySeedDB.doubleaccFields, null, null);
+ final File dbFile = new File(yacyDBPath,dbFileNames[i]);
+ final kelondroMapDataMining db = new kelondroMapDataMining(new kelondroBLOBTree(dbFile, true, true, yacySeedDB.commonHashLength, 480, '#', kelondroBase64Order.enhancedCoder, true, false, true), 500, yacySeedDB.sortFields, yacySeedDB.longaccFields, yacySeedDB.doubleaccFields, null, null);
kelondroMapDataMining.mapIterator it;
it = db.maps(true, false);
while (it.hasNext()) {
- Map<String, String> dna = it.next();
+ final Map<String, String> dna = it.next();
String peerHash = dna.get("key");
if (peerHash.length() < yacySeedDB.commonHashLength) {
- String peerName = dna.get("Name");
- String peerIP = dna.get("IP");
- String peerPort = dna.get("Port");
+ final String peerName = dna.get("Name");
+ final String peerIP = dna.get("IP");
+ final String peerPort = dna.get("Port");
while (peerHash.length() < yacySeedDB.commonHashLength) { peerHash = peerHash + "_"; }
System.err.println("Invalid Peer-Hash found in '" + dbFileNames[i] + "': " + peerName + ":" + peerHash + ", http://" + peerIP + ":" + peerPort);
@@ -903,7 +903,7 @@ public final class yacy {
}
db.close();
}
- } catch (Exception e) {
+ } catch (final Exception e) {
e.printStackTrace();
}
}
@@ -926,8 +926,8 @@ public final class yacy {
// check memory amount
System.gc();
- long startupMemFree = serverMemory.free();
- long startupMemTotal = serverMemory.total();
+ final long startupMemFree = serverMemory.free();
+ final long startupMemTotal = serverMemory.total();
// go into headless awt mode
System.setProperty("java.awt.headless", "true");
@@ -967,13 +967,13 @@ public final class yacy {
} else if ((args.length == 4) && (args[0].toLowerCase().equals("-cleanwordlist"))) {
// this can be used to organize and clean a word-list
// start this with "java -classpath classes yacy -cleanwordlist <word-file> <minlength> <maxlength>"
- int minlength = Integer.parseInt(args[2]);
- int maxlength = Integer.parseInt(args[3]);
+ final int minlength = Integer.parseInt(args[2]);
+ final int maxlength = Integer.parseInt(args[3]);
cleanwordlist(args[1], minlength, maxlength);
} else if ((args.length >= 1) && (args[0].toLowerCase().equals("-transfercr"))) {
// transfer a single cr file to a remote peer
- String targetaddress = args[1];
- String crfile = args[2];
+ final String targetaddress = args[1];
+ final String crfile = args[2];
transferCR(targetaddress, crfile);
} else if ((args.length >= 1) && (args[0].toLowerCase().equals("-urldbcleanup"))) {
// generate a url list and save it in a file
@@ -986,7 +986,7 @@ public final class yacy {
if (args.length >= 2) domain= args[1];
if (args.length >= 3) format= args[2];
if (args.length == 4) applicationRoot= new File(args[3]);
- String outfile = "rwihashlist_" + System.currentTimeMillis();
+ final String outfile = "rwihashlist_" + System.currentTimeMillis();
RWIHashList(applicationRoot, outfile, domain, format);
} else {
if (args.length == 1) applicationRoot= new File(args[0]);
@@ -1003,7 +1003,7 @@ class shutdownHookThread extends Thread {
private plasmaSwitchboard sb = null;
private Thread mainThread = null;
- public shutdownHookThread(Thread mainThread, plasmaSwitchboard sb) {
+ public shutdownHookThread(final Thread mainThread, final plasmaSwitchboard sb) {
super();
this.sb = sb;
this.mainThread = mainThread;
@@ -1024,7 +1024,7 @@ class shutdownHookThread extends Thread {
this.mainThread.join();
}
}
- } catch (Exception e) {
+ } catch (final Exception e) {
serverLog.logSevere("SHUTDOWN","Unexpected error. " + e.getClass().getName(),e);
}
}