Common.java
| Index Score | ||
|---|---|---|
![]() |
![]() |
org.furthurnet.datastructures.supporting |
![]() |
![]() |
Furthurnet |
View: Reasons, Metrics, Source Code
These are the metrics that contribute to the Enerjy Score for this file, ranked by impact. So the metrics listed at the top influence the score to a greater extent that the metrics listed at the bottom.
/*
* FURTHUR - A distributed peer-to-peer file sharing system.
* Copyright (C) 2001-2003 Jamie M. Addessi, Furthur Network
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.furthurnet.datastructures.supporting;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.furthurnet.furi.ServiceManager;
import org.furthurnet.servergui.ServerGuiConstants;
import org.furthurnet.xmlparser.QueryResultItem;
public class Common
{
public static String extractIp(String id)
{
if (id.charAt(0) == Constants.FIREWALL_TAG)
return id.substring(1, id.indexOf("_"));
else
return id.substring(0, id.indexOf("_"));
}
public static int extractInfoPort(String id)
{
int firstDel = id.indexOf("_");
int secondDel = id.indexOf("_", firstDel+1);
String portList = id.substring(firstDel+1, secondDel);
return Integer.parseInt(portList.substring(0, portList.indexOf("~")));
}
public static int extractOpenPort(String id)
{
int firstDel = id.indexOf("_");
int secondDel = id.indexOf("_", firstDel+1);
String portList = id.substring(firstDel+1, secondDel);
return Integer.parseInt(portList.substring(portList.indexOf("~")+1));
}
public static double extractSpeed(String id)
{
int firstDel = id.indexOf("_");
int secondDel = id.indexOf("_", firstDel+1);
int thirdDel = id.indexOf("_", secondDel+1);
return new Double(id.substring(secondDel+1, thirdDel)).doubleValue();
}
public static boolean equalStrings(String s1, String s2)
{
// compares strings even if one or both are null
if ((s1 == null) && (s2 == null))
return true;
else if ((s1 == null) && (s2 != null))
return false;
else if ((s1 != null) && (s2 == null))
return false;
else return (s1.equals(s2));
}
public static String[] extractValues(String s, int numValues)
{
return extractValues(s, numValues, "/");
}
public static String[] extractValues(String s, int numValues, String delim)
{
// Extracts the first 'numValues' strings from 's' where each string is delimited by "/"
// it puts these values in an array from [0] to [numvalues-1]
// it puts the remaining string in position [numvalues]
String[] list = new String[numValues + 1];
for (int i=0; i<numValues; i++)
{
int pos = s.indexOf(delim);
list[i] = s.substring(0, pos);
s = s.substring(pos+1);
}
list[numValues] = s;
return list;
}
public static int speedGroup(double speed)
{
// a set of speed groups must be defined as integers. a client with a specified
// speed is grouped in the speed group, and clients in the same speed group are positioned
// together in the heap.
// this method may be changed, but it truncates the speed and assigns the speed
// group the truncated integer value.
return new Double(Math.floor(speed)).intValue();
}
public static HeapItem decodeHeap(String changes)
{
return decodeHeap(changes, new IntegerPointer(0));
}
private static HeapItem decodeHeap(String changes, IntegerPointer pos)
{
// decode the string 'changes' into a binary tree, starting at character pos.
String sub = changes.substring(pos.value);
String[] list = extractValues(sub, 1);
String currentToken = list[0];
pos.value += currentToken.length() + 1;
if (currentToken.equals("0"))
return null;
else if (currentToken.charAt(0) == '*')
{
HeapItem temp = new HeapItem(Constants.UNCHANGED);
// The * signifies that the node's child connections have not changed.
if (currentToken.length() > 1)
if (currentToken.charAt(1) == Constants.FIREWALL_TAG)
{
//If it's a leftchild of a firewall node, the firewall tag is appended to the *.
// I don't think we need further action in this case.
}
else
{
//If it's a leftchild of a non-firewall node, the timestamp of the most recent change is appended to the *.
temp.timeStamp = new Long(currentToken.substring(1)).longValue();
}
return temp;
}
else
{
try
{
String currentId = currentToken.substring(0, currentToken.indexOf("!"));
double currentSpeed = new Double(currentToken.substring(currentToken.indexOf("!") + 1)).doubleValue();
HeapItem root = new HeapItem(currentSpeed, new ClientData(currentId));
root.child[Constants.LEFTCHILD] = decodeHeap(changes, pos);
root.child[Constants.RIGHTCHILD] = decodeHeap(changes, pos);
root.previousChild[Constants.LEFTCHILD] = extractFirewallInfo(changes, pos);
root.previousChild[Constants.RIGHTCHILD] = extractFirewallInfo(changes, pos);
return root;
}
catch (StringIndexOutOfBoundsException e)
{
System.out.println("currentToken is: :"+currentToken+":");
e.printStackTrace();
return null;
}
}
}
private static String extractFirewallInfo(String changes, IntegerPointer pos)
{
String sub = changes.substring(pos.value);
if (sub.charAt(0) != '{')
{
pos.value += sub.indexOf('|') + 1;
return Constants.NO_FIREWALL_INFO;
}
// return everything between { and }, including nested brackets
int numNests = 1;
for (int i=1; i<sub.length(); i++)
{
char c = sub.charAt(i);
if (c == '{')
numNests++;
else if (c == '}')
numNests--;
if (numNests == 0)
{
pos.value += i + 2; // skip the pipe at the end too
return sub.substring(0, i + 2);
}
}
// should never reach this line if the changes were encoded properly
return null;
}
public static String encodeHeap(HeapItem pos)
{
if (pos == null)
return "0/";
else if (pos.isUnchanged())
{
if (pos.timeStamp >= 0)
return new String("*" + new Long(pos.timeStamp).toString() + "/");
else
return "*/";
}
else
return new String(pos.getData().getId() + "!" + new Double(pos.getSpeed()).doubleValue() + "/") + encodeHeap(pos.child[Constants.LEFTCHILD]) + encodeHeap(pos.child[Constants.RIGHTCHILD]) + pos.previousChild[Constants.LEFTCHILD] + "|" + pos.previousChild[Constants.RIGHTCHILD] + "|";
}
public static double roundTo(double d, int p)
{
// rounds the double d to p decimal places
double temp = d * (Math.pow(10.0, (double)p));
return Math.floor(temp) / (Math.pow(10.0, (double)p));
}
public static String[] tokenize(String s)
{
return tokenize(s, countPipes(s));
}
public static String[] tokenize(String s, int maxSize)
{
String[] list = new String[maxSize]; // Make sure that no encoded string has more than 1000 values, or set this
int i = 0;
boolean done = false;
do
{
int pos = s.indexOf("|");
if (pos < 0)
done = true;
else
{
list[i] = s.substring(0, pos);
s = s.substring(pos+1);
i = i + 1;
}
} while (!done);
if (list.length > i)
list[i] = s;
return list;
}
public static void writeNullableStringToFile(PrintWriter out, String s)
{
if (s == null)
out.println();
else
out.println(s);
}
public static boolean isServing(String status)
{
if (status == null)
return false;
else
return ((status.equals(ServerGuiConstants.STATUS_SERVING)) ||
(status.equals(ServerGuiConstants.STATUS_STARTING)) ||
(status.equals(ServerGuiConstants.STATUS_FINISHING)));
}
public static boolean isFirewall(String _id)
{
if (_id == null)
return false;
else
return _id.charAt(0) == Constants.FIREWALL_TAG;
}
public static String appendDel(String s)
{
if ((s == null) || (s.length() == 0))
return null;
else
{
String temp = s;
if (temp.charAt(temp.length()-1) != File.separatorChar)
temp += File.separatorChar;
return temp;
}
}
public static String setFolderName(String _name)
{
String name = _name;
name = replaceAll(name, "/", "_");
name = replaceAll(name, "\\", "_");
name = replaceAll(name, "*", "_");
name = replaceAll(name, ":", "_");
name = replaceAll(name, "?", "_");
name = replaceAll(name, "\"", "_");
name = replaceAll(name, "<", "_");
name = replaceAll(name, ">", "_");
name = replaceAll(name, ",", "_");
name = replaceAll(name, "&", "_");
name = replaceAll(name, " ", "_");
// name = replaceAll(name, ".", "_");
return name.toLowerCase();
}
public static String replaceAll(String source, String oldText, String newText)
{
return replaceAll(source, oldText, newText, true);
}
public static String replaceAll(String source, String oldText, String newText, boolean caseSensitive)
{
String temp = source;
if (!caseSensitive)
{
while (temp.toUpperCase().indexOf(oldText.toUpperCase()) >= 0)
temp = replaceText(temp, oldText, newText, false);
}
else
{
while (temp.indexOf(oldText) >= 0)
temp = replaceText(temp, oldText, newText);
}
return temp;
}
public static String replaceText(String source, String oldText, String newText)
{
return replaceText(source, oldText, newText, true);
}
public static String replaceText(String source, String oldText, String newText, boolean caseSensitive)
{
try
{
if (!caseSensitive)
return source.substring(0, source.toUpperCase().indexOf(oldText.toUpperCase())) + newText + source.substring(source.toUpperCase().indexOf(oldText.toUpperCase()) + oldText.length());
else
return source.substring(0, source.indexOf(oldText)) + newText + source.substring(source.indexOf(oldText) + oldText.length());
}
catch (Exception e)
{
return source;
}
}
public static String generateFileSizeString(long totalBytes)
{
if (totalBytes < 1024000)
return roundTo((double)totalBytes / 1024, 1) + " KB";
else
return roundTo((double)totalBytes / 1024000, 1) + " MB";
}
public static String generateSpeedString(double speed) // speed passed in must be kb/sec
{
return generateSpeedString(speed, ServiceManager.getCfg().mSpeedDisplayType);
}
public static String generateSpeedString(double speed, int displayType) // speed passed in must be kb/sec
{
if (displayType == Constants.SPEED_DISPLAY_K_BYTES)
return new Double(Common.roundTo(speed / 8, 1)).toString() + " KB/sec";
else if (displayType == Constants.SPEED_DISPLAY_K_BITS)
return new Double(Common.roundTo(speed, 1)).toString() + " Kb/sec";
else return "";
}
public static long getPartialSize(QueryResultItem item, String tempFolder)
{
try
{
long total = 0;
String adjName = item.getSaveName();
try
{
File f = new File(appendDel(item.saveLoc) + adjName);
File[] files = f.listFiles();
for (int i=0; i<files.length; i++)
total += files[i].length();
}
catch (Exception e)
{}
File f = new File(appendDel(tempFolder) + adjName);
File[] files = f.listFiles();
for (int i=0; i<files.length; i++)
{
try
{
if (equalStrings(getExtension(files[i]), "tpm"))
total += files[i].length();
}
catch (Exception e)
{}
}
return total;
}
catch (Exception e)
{}
return -1;
}
public static void deleteTempDir(String folder, String path)
{
String adjName = setFolderName(folder);
try
{
File f = new File(appendDel(path) + adjName);
File[] files = f.listFiles();
for (int i=0; i<files.length; i++)
if ((files[i].getName().indexOf(".tpm") > 0) || (files[i].getName().indexOf(".cfg") > 0))
files[i].delete();
f.delete();
}
catch (Exception e)
{}
}
public static void deleteDownloadDir(String folder)
{
try
{
File f = new File(folder);
File[] files = f.listFiles();
for (int i=0; i<files.length; i++)
files[i].delete();
f.delete();
}
catch (Exception e)
{}
}
private static int countPipes(String s)
{
int total = 0;
for (int i=0; i<s.length(); i++)
{
if (s.charAt(i) == '|')
total++;
}
return total + 10; // 10 slot buffer
}
public static String getExtension(File f)
{
String s = f.getName();
return getExtension(s);
}
public static String getExtension(String s)
{
try
{
String ext = null;
int i = s.lastIndexOf('.');
if (i > 0 && i < s.length() - 1)
{
ext = s.substring(i+1).toLowerCase();
}
if (ext == null)
return "";
else
return ext;
}
catch (Exception e)
{
return "";
}
}
public static String removeExtension(File f)
{
String s = f.getName();
return removeExtension(s);
}
public static String removeExtension(String s)
{
try
{
String pre = null;
int i = s.lastIndexOf('.');
if (i > 0 && i < s.length() - 1)
{
pre = s.substring(0,i).toLowerCase();
}
if (pre == null)
return "";
else
return pre;
}
catch (Exception e)
{
return "";
}
}
public static String insertCRs(String x)
{
int maxChars = 80;
String line = "";
int numLines = 0;
while (x.length() > maxChars)
{
int pos = x.indexOf("\n");
if ((pos >= maxChars) || (pos <= 0))
pos = maxChars;
while ((x.charAt(pos) != ' ') && (x.charAt(pos) != '\n'))
pos--;
line += x.substring(0, pos) + "\n";
x = x.substring(pos);
while ((x.length() > 0) && (x.charAt(0) == '\n'))
x = x.substring(1);
}
return line + x;
}
public static String findSaveFolder(String name)
{
try
{
File f = new File(Common.appendDel(Common.appendDel(ServiceManager.getCfg().mDefaultTempLocation) + name) + "furthur_info.cfg");
if (f.exists())
{
FileReader reader = null;
BufferedReader in = null;
String saveLoc = null;
String saveName = null;
try
{
reader = new FileReader(f);
in = new BufferedReader(reader);
in.readLine();
in.readLine();
saveLoc = in.readLine();
saveName = name;
try
{
saveName = in.readLine();
}
catch (Exception e)
{}
}
catch (Exception e)
{
}
try
{
in.close();
reader.close();
}
catch (Exception e)
{}
return saveLoc + saveName;
}
}
catch (Exception e2)
{}
return ServiceManager.getCfg().mDefaultSaveLocation;
}
public static String validateNick(String nick)
{
try
{
if ((nick == null) || (nick.trim().length() == 0))
return "Unknown";
else
{
if (nick.endsWith(ServiceManager.getCfg().mIrcNickIdentifier))
return nick.substring(0, nick.length()-1);
return nick;
}
}
catch (Exception e)
{
return "Unknown";
}
}
public static String getTodaysDate() {
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
return sf.format(new Date());
}
}
The table below shows all metrics for Common.java.




