Changed the name of FileFinder to FileUtil

This commit is contained in:
Ziver Koc 2010-07-01 16:22:02 +00:00
parent a9bc9997ca
commit ce83415d1c
19 changed files with 315 additions and 59 deletions

View file

@ -7,8 +7,10 @@ import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
@ -18,7 +20,7 @@ import java.util.regex.Matcher;
*
* @author Ziver
*/
public class FileFinder {
public class FileUtil {
/**
* Returns a String with a relative path from the given path
@ -67,7 +69,7 @@ public class FileFinder {
* @throws URISyntaxException
*/
public static URL findURL(String path){
return FileFinder.class.getClassLoader().getResource(path);
return FileUtil.class.getClassLoader().getResource(path);
}
/**
@ -82,7 +84,7 @@ public class FileFinder {
if(file!=null && file.exists()){
return new BufferedInputStream( new FileInputStream( file ) );
}
return FileFinder.class.getClassLoader().getResourceAsStream(path);
return FileUtil.class.getClassLoader().getResourceAsStream(path);
} catch (Exception e) {
//e.printStackTrace(MultiPrintStream.out);
}
@ -98,7 +100,31 @@ public class FileFinder {
* @throws IOException
*/
public static String getFileContent(File file) throws IOException{
BufferedReader in = new BufferedReader(new FileReader(file));
return getContent( new FileInputStream(file) );
}
/**
* Reads and returns the content of a file as a String.
* Or use FileUtils.readFileToString(file);
*
* @param url is the url to read
* @return The file content
* @throws IOException
*/
public static String getContent(URL url) throws IOException{
return getContent( url.openStream() );
}
/**
* Reads and returns the content of a file as a String.
* Or use FileUtils.readFileToString(file);
*
* @param stream is the file stream to read
* @return The file content
* @throws IOException
*/
public static String getContent(InputStream stream) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(stream));
StringBuffer ret = new StringBuffer();
int tmp;
@ -110,6 +136,75 @@ public class FileFinder {
return ret.toString();
}
/**
* Cache for the search functions
*/
private static HashMap<SearchItem,List<File>> search_cache = new HashMap<SearchItem,List<File>>();
/**
* An Cache Item class to identify different cached items
* @author Ziver
*/
private static class SearchItem{
private File dir;
private boolean folders;
private int recurse;
protected SearchItem(File dir, boolean folders, int recurse){
this.dir = dir;
this.folders = folders;
this.recurse = recurse;
}
public boolean equals(Object o){
if(o!=null && o instanceof SearchItem){
SearchItem si = (SearchItem)o;
return dir.equals(si.dir) && folders == si.folders && recurse == si.recurse;
}
return false;
}
public int hashCode(){
int hash = 133;
hash = 23 * hash + dir.hashCode();
hash = 23 * hash + (folders ? 1 : 0);
hash = 23 * hash + recurse;
return 0;
}
}
/**
* Same as search(File dir)
* but is caches the result to be used next time this function is called
* with the same parameters.
*/
public static List<File> cachedSearch(File dir){
return cachedSearch(dir, new LinkedList<File>(), true);
}
/**
* Same as search(File dir, List<File> fileList, boolean recursive)
* but is caches the result to be used next time this function is called
* with the same parameters.
*/
public static List<File> cachedSearch(File dir, List<File> fileList, boolean recursive){
return cachedSearch(dir, new LinkedList<File>(), false, (recursive ? Integer.MAX_VALUE : 0));
}
/**
* Same as search(File dir, List<File> fileList, boolean folders, int recurse)
* but is caches the result to be used next time this function is called
* with the same parameters.
*/
public static List<File> cachedSearch(File dir, List<File> fileList, boolean folders, int recurse){
SearchItem si = new SearchItem(dir, folders, recurse);
if( search_cache.containsKey(si) ){
fileList.addAll( search_cache.get(si) );
return fileList;
}
search(dir, fileList, folders, recurse);
search_cache.put(si, fileList);
return fileList;
}
/**
* Returns a List with all the files in a folder and sub folders
*

View file

@ -10,6 +10,7 @@ import java.util.BitSet;
import zutil.struct.DynamicByteArrayStream;
public class Converter {
private Converter(){}
/**
* Converts an object to an array of bytes.
@ -248,4 +249,39 @@ public class Converter {
}
return ret;
}
/**
* Converts a given String to a specified class
*
* @param <T> is the resulting class
* @param data is the String data to be converted
* @param c is the class to convert to
* @return a instance of the class with the value in the string or null if there was an problem
*/
@SuppressWarnings("unchecked")
public static <T> T fromString(String data, Class<T> c){
if(data == null || data.isEmpty())
return null;
try{
if( c == String.class) return (T) data;
else if(c == Integer.class) return (T) new Integer(data);
else if(c == int.class) return (T) new Integer(data);
else if(c == Long.class) return (T) new Long(data);
else if(c == long.class) return (T) new Long(data);
else if(c == Float.class) return (T) new Float(data);
else if(c == float.class) return (T) new Float(data);
else if(c == Double.class) return (T) new Double(data);
else if(c == double.class) return (T) new Double(data);
else if(c == Boolean.class) return (T) new Boolean(data);
else if(c == boolean.class) return (T) new Boolean(data);
else if(c == Byte.class) return (T) new Byte(data);
else if(c == byte.class) return (T) new Byte(data);
else if(byte[].class.isAssignableFrom(c))
return (T) new sun.misc.BASE64Decoder().decodeBuffer(data);
}catch(Exception e){
e.printStackTrace();
}
return null;
}
}

View file

@ -8,7 +8,7 @@ import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import zutil.FileFinder;
import zutil.FileUtil;
import zutil.MultiPrintStream;
import zutil.ProgressListener;
@ -60,7 +60,7 @@ public class UpdateClient{
// receive file updates
FileHash fileInfo = (FileHash)in.readObject();
File tmpPath = FileFinder.find(path);
File tmpPath = FileUtil.find(path);
while(!fileInfo.path.isEmpty()){
MultiPrintStream.out.println("Updating: "+path+fileInfo.path);
// reading new file data

View file

@ -13,7 +13,7 @@ import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import zutil.FileFinder;
import zutil.FileUtil;
import zutil.Hasher;
import zutil.MultiPrintStream;
@ -78,7 +78,7 @@ public class UpdateServer extends Thread{
try {
// receive the clients filelist
ArrayList<FileHash> clientFileList = (ArrayList<FileHash>)in.readObject();
File tmpPath = FileFinder.find(path);
File tmpPath = FileUtil.find(path);
for(FileHash file : fileList){
if(!clientFileList.contains(file)){
@ -124,10 +124,10 @@ public class UpdateServer extends Thread{
public static ArrayList<FileHash> getFileList(String path) throws Exception{
ArrayList<FileHash> fileHash = new ArrayList<FileHash>();
List<File> files = FileFinder.search(FileFinder.find(path));
List<File> files = FileUtil.search(FileUtil.find(path));
for(File file : files){
fileHash.add(new FileHash(
FileFinder.relativePath(file, path),
FileUtil.relativePath(file, path),
Hasher.hash(file, "MD5"),
file.length()));
}

View file

@ -7,7 +7,7 @@ import java.util.Scanner;
import java.util.regex.Pattern;
public class HTTPHeaderParser {
// Some Cached regexes
// Some Cached regex's
private static final Pattern colonPattern = Pattern.compile(":");
private static final Pattern equalPattern = Pattern.compile("=");
private static final Pattern andPattern = Pattern.compile("&");
@ -20,7 +20,7 @@ public class HTTPHeaderParser {
private float version;
private int httpCode;
// params
// Parameters
private HashMap<String, String> attributes;
private HashMap<String, String> cookies;

View file

@ -10,8 +10,10 @@ import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import zutil.MultiPrintStream;
import zutil.log.LogUtil;
import zutil.network.threaded.ThreadedTCPNetworkServer;
import zutil.network.threaded.ThreadedTCPNetworkServerThread;
@ -23,7 +25,7 @@ import zutil.network.threaded.ThreadedTCPNetworkServerThread;
* @author Ziver
*/
public class HttpServer extends ThreadedTCPNetworkServer{
public static final boolean DEBUG = true;
public static final Logger logger = LogUtil.getLogger();
public static final String SERVER_VERSION = "Ziver HttpServer 1.0";
public static final int COOKIE_TTL = 200;
public static final int SESSION_TTL = 10*60*1000; // in milliseconds
@ -67,7 +69,7 @@ public class HttpServer extends ThreadedTCPNetworkServer{
Timer timer = new Timer();
timer.schedule(new GarbageCollector(), 0, SESSION_TTL / 2);
MultiPrintStream.out.println("HTTP"+(keyStore==null?"":"S")+" Server ready!");
logger.info("HTTP"+(keyStore==null?"":"S")+" Server ready!");
}
/**
@ -85,7 +87,7 @@ public class HttpServer extends ThreadedTCPNetworkServer{
// Check if session is still valid
if((Long)client_session.get("ttl") < System.currentTimeMillis()){
sessions.remove(key);
if(DEBUG) MultiPrintStream.out.println("Removing Session: "+key);
logger.fine("Removing Session: "+key);
}
}
}
@ -115,7 +117,7 @@ public class HttpServer extends ThreadedTCPNetworkServer{
try {
return new HttpServerThread( s );
} catch (IOException e) {
e.printStackTrace( MultiPrintStream.out );
logger.log(Level.SEVERE, "Could not start new Thread", e);
}
return null;
}
@ -135,7 +137,7 @@ public class HttpServer extends ThreadedTCPNetworkServer{
out = new HttpPrintStream(socket.getOutputStream());
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
this.socket = socket;
if(DEBUG) MultiPrintStream.out.println("New Connection!!! "+socket.getInetAddress().getHostName());
logger.fine("New Connection!!! "+socket.getInetAddress().getHostName());
}
public void run(){
@ -147,10 +149,10 @@ public class HttpServer extends ThreadedTCPNetworkServer{
//**************************** REQUEST *********************************
try {
if(DEBUG) MultiPrintStream.out.println("Reciving Http Request!!!");
logger.finer("Reciving Http Request!!!");
HTTPHeaderParser parser = new HTTPHeaderParser(in);
if(DEBUG) MultiPrintStream.out.println(parser);
logger.finest(parser.toString());
client_info = parser.getAttributes();
request = parser.getURLAttributes();
cookie = parser.getCookies();
@ -209,15 +211,15 @@ public class HttpServer extends ThreadedTCPNetworkServer{
nextSessionId++;
}
// Debug
if(DEBUG){
MultiPrintStream.out.println( "# page_url: "+parser.getRequestURL() );
MultiPrintStream.out.println( "# cookie: "+cookie );
MultiPrintStream.out.println( "# client_session: "+client_session );
MultiPrintStream.out.println( "# client_info: "+client_info );
MultiPrintStream.out.println( "# request: "+request );
if(logger.isLoggable(Level.FINE)){
logger.finest( "# page_url: "+parser.getRequestURL() );
logger.finest( "# cookie: "+cookie );
logger.finest( "# client_session: "+client_session );
logger.finest( "# client_info: "+client_info );
logger.finest( "# request: "+request );
}
//**************************** RESPONSE ************************************
if(DEBUG) MultiPrintStream.out.println("Sending Http Response!!!");
logger.finer("Sending Http Response!!!");
out.setStatusCode(200);
out.setHeader( "Server", SERVER_VERSION );
out.setHeader( "Content-Type", "text/html" );
@ -231,13 +233,13 @@ public class HttpServer extends ThreadedTCPNetworkServer{
}
else{
out.setStatusCode( 404 );
out.println( "404 Page Not Found" );
if(DEBUG) MultiPrintStream.out.println("404 Page Not Found");
out.println( "404 Page Not Found: "+parser.getRequestURL() );
logger.fine( "404 Page Not Found: "+parser.getRequestURL() );
}
//********************************************************************************
} catch (Exception e) {
e.printStackTrace( MultiPrintStream.out );
logger.log(Level.WARNING, "500 Internal Server Error", e);
try {
out.setStatusCode( 500 );
} catch (Exception e1) {}
@ -249,12 +251,12 @@ public class HttpServer extends ThreadedTCPNetworkServer{
}
try{
if(DEBUG) MultiPrintStream.out.println("Conection Closed!!!");
logger.fine("Conection Closed!!!");
out.close();
in.close();
socket.close();
} catch( Exception e ) {
e.printStackTrace( MultiPrintStream.out );
logger.log(Level.WARNING, "Could not close connection", e);
}
}
}

View file

@ -18,6 +18,7 @@ public class BBCodeParser {
System.out.println(parser.parse("jshdkj [m"));
System.out.println(parser.parse("jshdkj [/m"));
System.out.println(parser.parse("jshdkj m]"));
System.out.println(parser.parse("jshdkj <br />"));
}
/**
@ -81,7 +82,7 @@ public class BBCodeParser {
if(c == '['){
bbcode = new StringBuilder();
}
else if(c == '/'){
else if(bbcode!=null && c == '/'){
closeTag = true;
}
else if(bbcode!=null){

View file

@ -155,7 +155,7 @@ public class JSONNode implements Iterable<JSONNode>{
* Sets the value of the node, but only if it is setup as an JSONType.Value
*/
public void set(int value){
if( !this.isValue() ) return;
if( !this.isValue() ) throw new NullPointerException("The node is not setup as a value");
type = JSONType.Number;
this.value = ""+value;
}
@ -163,7 +163,7 @@ public class JSONNode implements Iterable<JSONNode>{
* Sets the value of the node, but only if it is setup as an JSONType.Value
*/
public void set(double value){
if( !this.isValue() ) return;
if( !this.isValue() ) throw new NullPointerException("The node is not setup as a value");
type = JSONType.Number;
this.value = ""+value;
}
@ -171,7 +171,7 @@ public class JSONNode implements Iterable<JSONNode>{
* Sets the value of the node, but only if it is setup as an JSONType.Value
*/
public void set(boolean value){
if( !this.isValue() ) return;
if( !this.isValue() ) throw new NullPointerException("The node is not setup as a value");
type = JSONType.Boolean;
this.value = ""+value;
}
@ -179,7 +179,7 @@ public class JSONNode implements Iterable<JSONNode>{
* Sets the value of the node, but only if it is setup as an JSONType.Value
*/
public void set(String value){
if( !this.isValue() ) return;
if( !this.isValue() ) throw new NullPointerException("The node is not setup as a value");
type = JSONType.String;
this.value = value;
}

View file

@ -3,7 +3,7 @@ package zutil.parser.json;
import zutil.MultiPrintStream;
import zutil.parser.json.JSONNode.JSONType;
public class JSONParser {
public class JSONParser{
private String json;
private int index;
@ -159,4 +159,6 @@ public class JSONParser {
System.out.println("Return");
return root;
}
public void close() {}
}

View file

@ -2,7 +2,6 @@ package zutil.parser.json;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.Iterator;
import zutil.parser.json.JSONNode.JSONType;
@ -12,7 +11,7 @@ import zutil.parser.json.JSONNode.JSONType;
*
* @author Ziver
*/
public class JSONWriter {
public class JSONWriter{
private PrintStream out;
/**

View file

@ -5,12 +5,12 @@ import java.io.FileNotFoundException;
import java.net.URISyntaxException;
import zutil.FileChangeListener;
import zutil.FileFinder;
import zutil.FileUtil;
import zutil.FileWatcher;
public class FileChangedTest implements FileChangeListener{
public static void main(String[] args) throws URISyntaxException, FileNotFoundException{
FileWatcher watcher = new FileWatcher(FileFinder.find("test.txt"));
FileWatcher watcher = new FileWatcher(FileUtil.find("test.txt"));
watcher.setListener(new FileChangedTest());
while(true){

View file

@ -4,19 +4,19 @@ import java.io.File;
import java.net.URISyntaxException;
import java.util.List;
import zutil.FileFinder;
import zutil.FileUtil;
import zutil.Hasher;
public class FileFinderHasherTest {
public static void main(String[] args) throws URISyntaxException{
String relativePath = "zutil/test";
File path = FileFinder.find(relativePath);
List<File> files = FileFinder.search(path);
File path = FileUtil.find(relativePath);
List<File> files = FileUtil.search(path);
for(int i=0; i<files.size(); i++){
try {
System.out.println(
FileFinder.relativePath(files.get(i), relativePath)+
FileUtil.relativePath(files.get(i), relativePath)+
": "+Hasher.hash(files.get(i),"MD5"));
} catch (Exception e) {
e.printStackTrace();

View file

@ -0,0 +1,120 @@
package zutil.test;
import javax.wsdl.WSDLException;
import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import zutil.network.http.soap.SOAPHttpPage;
import zutil.network.ws.WSInterface;
import zutil.network.ws.WSObject;
import zutil.network.ws.WSReturnValueList;
public class SOAPTest {
//*******************************************************************************************
//**************************** TEST *********************************************************
public static void main(String[] args){
new SOAPTest();
}
public SOAPTest(){
try {
SOAPHttpPage soap = new SOAPHttpPage("http://test.se:8080/", new SOAPTestClass());
// Response
try {
Document document = soap.genSOAPResponse(
"<?xml version=\"1.0\"?>" +
"<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" +
" <soap:Body xmlns:m=\"http://www.example.org/stock\">\n" +
//" <m:pubA>\n" +
//" <m:Ztring>IBM</m:Ztring>\n" +
//" </m:pubA>\n" +
//" <m:pubZ>\n" +
//" <m:olle>66</m:olle>\n" +
//" </m:pubZ>\n" +
" <m:pubB>\n" +
" <m:byte>IBM</m:byte>\n" +
" </m:pubB>\n" +
" </soap:Body>\n" +
"</soap:Envelope>");
System.out.println( "****************** RESPONSE *********************" );
OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter writer = new XMLWriter( System.out, format );
writer.write( document );
System.out.println();
} catch (Exception e) {
e.printStackTrace();
}
} catch (WSDLException e) {
e.printStackTrace();
}
}
public class SOAPTestClass3 implements WSObject{
public String lol = "lol11";
public String lol2 = "lol22";
}
public class SOAPTestClass2 implements WSObject{
@WSFieldName(value="lolz", optional=true)
public String lol = "lol1";
@WSFieldName("lolx")
public String lol2 = "lol2";
public byte[] b = new byte[]{0x12, 0x23};
public SOAPTestClass3 l = new SOAPTestClass3();
}
public class SOAPTestRetClass extends WSReturnValueList{
@WSValueName("retTest")
public String lol = "lol1";
public String lol2 = "lol2";
}
public class SOAPTestClass implements WSInterface{
public SOAPTestClass(){}
@WSHeader()
@WSDocumentation("hello")
public void pubZ(
@WSParamName(value="olle", optional=true) int lol,
@WSParamName(value="olle2", optional=true) int lol2) throws Exception{
//System.out.println("Param: "+lol);
throw new Exception("Ziver is the fizle");
}
@WSReturnName("param")
@WSParamDocumentation("null is the shizzle")
public String[][] pubA (
@WSParamName("Ztring") String lol) throws Exception{
//System.out.println("ParamZ: "+lol);
return new String[][]{{"test","test2"},{"test3","test4"}};
}
@WSReturnName("zivarray")
@WSParamDocumentation("null is the bla")
public SOAPTestClass2[] pubX (
@WSParamName("Ztring") String lol) throws Exception{
return new SOAPTestClass2[]{new SOAPTestClass2(), new SOAPTestClass2()};
}
@WSReturnName("zivarray")
@WSParamDocumentation("null is the kala")
public SOAPTestRetClass pubB (
@WSParamName("byte") String lol) throws Exception{
SOAPTestRetClass tmp = new SOAPTestRetClass();
tmp.lol = "test";
tmp.lol2 = "test2";
return tmp;
}
@WSDisabled()
public void privaZ(){ }
protected void protZ(){ }
}
}

View file

@ -5,6 +5,7 @@ import zutil.algo.sort.SimpleSort;
import zutil.algo.sort.sortable.SortableIntArray;
import junit.framework.*;
@SuppressWarnings("unused")
public class SortTestSimple extends TestCase {
public static final int SIZE = 10000;
public static final int MAX_INT = 10000;

View file

@ -2,12 +2,10 @@ package zutil.test;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import javax.wsdl.WSDLException;
import zutil.MultiPrintStream;
import zutil.log.Logger;
import zutil.network.http.HttpServer;
import zutil.network.http.soap.SOAPHttpPage;
import zutil.network.ssdp.SSDPServer;
@ -16,9 +14,7 @@ import zutil.network.upnp.services.UPnPContentDirectory;
public class UPnPServerTest {
public static void main(String[] args) throws IOException, WSDLException{
//Logger.setGlobalLogLevel(Level.FINEST);
public static void main(String[] args) throws IOException, WSDLException{
UPnPMediaServer upnp = new UPnPMediaServer("http://192.168.0.60:8080/");
MultiPrintStream.out.println("UPNP Server running");

View file

@ -31,7 +31,7 @@ import javax.swing.text.Document;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import zutil.FileFinder;
import zutil.FileUtil;
/**
* Creates a Swing console window Thats takes System.in and
@ -60,7 +60,7 @@ public class Console{
public Console(String title, int width, int height, int buffer, boolean tray){
ConsoleInputStream in = new ConsoleInputStream();
DEFAULT_ICON = FileFinder.find(DEFAULT_ICON).getAbsolutePath();
DEFAULT_ICON = FileUtil.find(DEFAULT_ICON).getAbsolutePath();
initUI(title, in);
bufferSize = buffer;

View file

@ -7,7 +7,7 @@ import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
import zutil.FileFinder;
import zutil.FileUtil;
import zutil.image.ImageUtil;
/**
@ -35,7 +35,7 @@ public class JImagePanel extends JPanel {
* @param img is the path to the image
*/
public JImagePanel(String img) throws IOException {
this(ImageIO.read( FileFinder.find( img ) ));
this(ImageIO.read( FileUtil.find( img ) ));
}
/**

View file

@ -20,7 +20,7 @@ import javax.swing.WindowConstants;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import zutil.FileFinder;
import zutil.FileUtil;
import zutil.MultiPrintStream;
import zutil.struct.HistoryList;
import zutil.ui.JImagePanel;
@ -89,7 +89,7 @@ public class Wizard implements ActionListener{
finish.addActionListener( this );
// Set the image in the sidebar
sidebar.setImage(ImageIO.read( FileFinder.getInputStream( bg ) ));
sidebar.setImage(ImageIO.read( FileUtil.getInputStream( bg ) ));
// add the first page
pages.add( start );

View file

@ -10,13 +10,13 @@ import java.io.OutputStream;
*/
public class StringOutputStream extends OutputStream{
// The buffer
protected StringBuffer buffer;
protected StringBuilder buffer;
/**
* Creates an new instance of this class
*/
public StringOutputStream(){
buffer = new StringBuffer();
clear();
}
@Override
@ -34,6 +34,10 @@ public class StringOutputStream extends OutputStream{
buffer.append( new String(b, off, len) );
}
public void clear(){
buffer = new StringBuilder();
}
/**
* @return the String with the data
*/