Renamed FileSearch class and defined default values

This commit is contained in:
Ziver Koc 2015-11-11 18:07:48 +01:00
parent e2e6a40ce9
commit 997ec1c52b
8 changed files with 286 additions and 280 deletions

View file

@ -103,13 +103,15 @@ public class ClassUtil {
* there is no generics or the super class is not found * there is no generics or the super class is not found
*/ */
public static Class<?>[] getGenericClasses(Class<?> c, Class<?> superClass){ public static Class<?>[] getGenericClasses(Class<?> c, Class<?> superClass){
// Search for the super class if(superClass != null) {
while (c.getSuperclass() != Object.class && !superClass.isAssignableFrom(c.getSuperclass())) // Search for the super class
c = c.getSuperclass(); while (c.getSuperclass() != null && c.getSuperclass() != Object.class) {
// Did we find the super class? // Did we find the super class?
if (superClass.isAssignableFrom(c.getSuperclass())) if (superClass.isAssignableFrom(c.getSuperclass()))
return getGenericClasses(c.getGenericSuperclass()); return getGenericClasses(c.getGenericSuperclass());
c = c.getSuperclass();
}
}
return new Class[0]; return new Class[0];
} }
private static Class<?>[] getGenericClasses(Type genericType){ private static Class<?>[] getGenericClasses(Type genericType){
@ -118,7 +120,8 @@ public class ClassUtil {
Type[] argTypes = aType.getActualTypeArguments(); Type[] argTypes = aType.getActualTypeArguments();
Class<?>[] classArray = new Class<?>[argTypes.length]; Class<?>[] classArray = new Class<?>[argTypes.length];
for(int i=0; i<classArray.length; ++i) { for(int i=0; i<classArray.length; ++i) {
classArray[i] = (Class<?>) argTypes[i]; if(argTypes[i] instanceof Class)
classArray[i] = (Class<?>) argTypes[i];
} }
return classArray; return classArray;
} }

View file

@ -1,248 +1,247 @@
/* /*
* The MIT License (MIT) * The MIT License (MIT)
* *
* Copyright (c) 2015 Ziver Koc * Copyright (c) 2015 Ziver Koc
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE. * THE SOFTWARE.
*/ */
package zutil.io.file; package zutil.io.file;
import zutil.io.InputStreamCloser; import zutil.io.InputStreamCloser;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.util.*; import java.util.*;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import java.util.zip.ZipFile; import java.util.zip.ZipFile;
public class FileSearch implements Iterable<FileSearch.FileSearchItem>{ public class FileSearcher implements Iterable<FileSearcher.FileSearchItem>{
// Constants // Constants
private static final List<String> compressedFileExtensions = Arrays.asList(new String[]{ private static final List<String> compressedFileExtensions = Arrays.asList(new String[]{
"jar", "zip" "jar", "zip"
}); });
// Constructor params // Constructor params
private File root; private File root;
// Search parameters // Search parameters
private String fileName; private String fileName = null;
private String extension; private String extension = null;
private boolean recursive; private boolean recursive = false;
//private int depth; //private int depth;
private boolean searchFiles; private boolean searchFiles = true;
private boolean searchCompressedFiles; private boolean searchFolders = true;
private boolean searchFolders; private boolean searchCompressedFiles = false;
public FileSearch(File root){ public FileSearcher(File root){
this.root = root; this.root = root;
searchFiles = true; }
searchFolders = true;
}
/**
* @param file Sets the exact file name to search for (includes extension)
/** */
* @param file Sets the exact file name to search for (includes extension) public void setFileName(String file){
*/ fileName = file;
public void setFileName(String file){ }
fileName = file;
} /**
* Sets the file extensions to search for (should not include . at the beginning)
/** */
* Sets the file extensions to search for (should not include . at the beginning) public void setExtension(String ext){
*/ extension = ext;
public void setExtension(String ext){ }
} /**
* Defines if the search should go into sub-folders
/** */
* Sets if the search should go into sub-folders public void setRecursive(boolean recursive){
*/ this.recursive = recursive;
public void setRecursive(boolean recursive){ }
this.recursive = recursive;
} /**
* Sets how deep into folders the search should go
/** * (Recursion needs to be enabled for this attribute to be used)
* Sets how deep into folders the search should go */
* (Recursion needs to be enabled for this attribute to be used) //public void setDepth(int depth){
*/ // this.depth = depth;
//public void setDepth(int depth){ //}
// this.depth = depth;
//} public void searchFiles(boolean searchFiles){
this.searchFiles = searchFiles;
public void searchFiles(boolean searchFiles){ }
this.searchFiles = searchFiles; public void searchFolders(boolean searchFolders){
} this.searchFolders = searchFolders;
public void searchCompressedFiles(boolean searchCompressedFiles){ }
this.searchCompressedFiles = searchCompressedFiles; public void searchCompressedFiles(boolean searchCompressedFiles){
} this.searchCompressedFiles = searchCompressedFiles;
public void searchFolders(boolean searchFolders){ }
this.searchFolders = searchFolders;
}
@Override
public Iterator<FileSearchItem> iterator() {
@Override return new FileSearchIterator();
public Iterator<FileSearchItem> iterator() { }
return new FileSearchIterator();
}
protected class FileSearchIterator implements Iterator<FileSearchItem>{
private ArrayList<FileSearchItem> fileList;
protected class FileSearchIterator implements Iterator<FileSearchItem>{ private int currentIndex;
private ArrayList<FileSearchItem> fileList; private FileSearchItem nextItem;
private int currentIndex;
private FileSearchItem nextItem; public FileSearchIterator(){
fileList = new ArrayList<FileSearchItem>();
public FileSearchIterator(){ currentIndex = 0;
fileList = new ArrayList<FileSearchItem>();
currentIndex = 0; addFiles(new FileSearchFileItem(root), root.list());
next();
addFiles(new FileSearchFileItem(root), root.list()); }
next();
} @Override
public boolean hasNext() {
@Override return currentIndex < fileList.size();
public boolean hasNext() { }
return currentIndex < fileList.size();
} @Override
public void remove() {
@Override throw new UnsupportedOperationException();
public void remove() { }
throw new UnsupportedOperationException();
} @Override
public FileSearchItem next() {
@Override if(currentIndex < 0 || currentIndex >= fileList.size())
public FileSearchItem next() { return null;
if(currentIndex < 0 || currentIndex >= fileList.size()) // Temporarily save the current file
return null; FileSearchItem ret = fileList.get(currentIndex);
// Temporarily save the current file currentIndex++;
FileSearchItem ret = fileList.get(currentIndex);
currentIndex++; // Find the next file
for(; currentIndex<fileList.size(); currentIndex++){
// Find the next file FileSearchItem file = fileList.get(currentIndex);
for(; currentIndex<fileList.size(); currentIndex++){ if(recursive && file.isDirectory()){
FileSearchItem file = fileList.get(currentIndex); addFiles(file, file.listFiles());
if(recursive && file.isDirectory()){ if(searchFolders && file.getName().equalsIgnoreCase(fileName))
addFiles(file, file.listFiles()); break;
if(searchFolders && file.getName().equalsIgnoreCase(fileName)) }
break; else if(searchCompressedFiles && file.isFile() &&
} compressedFileExtensions.contains(
else if(searchCompressedFiles && file.isFile() && FileUtil.getFileExtension(file.getName()).toLowerCase())){
compressedFileExtensions.contains(FileUtil.getFileExtension(file.getName()).toLowerCase())){ try {
try { ZipFile zipFile = new ZipFile(file.getPath());
ZipFile zipFile = new ZipFile(file.getPath()); Enumeration<? extends ZipEntry> e = zipFile.entries();
Enumeration<? extends ZipEntry> e = zipFile.entries(); while(e.hasMoreElements()){
while(e.hasMoreElements()){ ZipEntry entry = e.nextElement();
ZipEntry entry = e.nextElement(); fileList.add(new FileSearchZipItem(file.getPath(), entry));
fileList.add(new FileSearchZipItem(file.getPath(), entry)); }
} zipFile.close();
zipFile.close(); } catch (IOException e) {
} catch (IOException e) { e.printStackTrace();
e.printStackTrace(); }
} }
} else if(searchFiles && file.isFile()){
else if(searchFiles && file.isFile()){ if(extension != null && FileUtil.getFileExtension(file.getName()).equalsIgnoreCase(extension))
if(extension != null && FileUtil.getFileExtension(file.getName()).equalsIgnoreCase(extension)) break;
break; else if(fileName != null && file.getName().equalsIgnoreCase(fileName))
else if(fileName != null && file.getName().equalsIgnoreCase(fileName)) break;
break; }
} }
}
return ret;
return ret; }
}
private void addFiles(FileSearchItem root, String[] list){
private void addFiles(FileSearchItem root, String[] list){ if(root instanceof FileSearchFileItem) {
if(root instanceof FileSearchFileItem) { for (String file : list) {
for (String file : list) { fileList.add(new FileSearchFileItem(
fileList.add(new FileSearchFileItem( new File(((FileSearchFileItem)root).file, file)));
new File(((FileSearchFileItem)root).file, file))); }
} }
} }
}
}
}
public interface FileSearchItem{
public interface FileSearchItem{ /** @return a file or folder name **/
/** @return a file or folder name **/ public String getName();
public String getName(); /** @return a path to the file or folder, in case of a compressed file the path to the package will be returned **/
/** @return a path to the file or folder, in case of a compressed file the path to the package will be returned **/ public String getPath();
public String getPath();
public boolean isCompressed();
public boolean isCompressed(); public boolean isFile();
public boolean isFile(); public boolean isDirectory();
public boolean isDirectory();
/** @return an InputStream if this is a file otherwise null **/
/** @return an InputStream if this is a file otherwise null **/ public InputStream getInputStream() throws IOException;
public InputStream getInputStream() throws IOException; /** @return an String array with all files if this is a folder otherwise null **/
/** @return an String array with all files if this is a folder otherwise null **/ public String[] listFiles();
public String[] listFiles(); }
}
protected static class FileSearchFileItem implements FileSearchItem{
public class FileSearchFileItem implements FileSearchItem{ private File file;
private File file;
protected FileSearchFileItem(File file){
protected FileSearchFileItem(File file){ this.file = file;
this.file = file; }
}
public String getName() { return file.getName(); }
public String getName() { return file.getName(); } public String getPath() { return file.getAbsolutePath(); }
public String getPath() { return file.getAbsolutePath(); }
public boolean isCompressed() { return false; }
public boolean isCompressed() { return false; } public boolean isFile() { return file.isFile(); }
public boolean isFile() { return file.isFile(); } public boolean isDirectory() { return file.isDirectory(); }
public boolean isDirectory() { return file.isDirectory(); }
public InputStream getInputStream() throws IOException { return new FileInputStream(file); }
public InputStream getInputStream() throws IOException { return new FileInputStream(file); } public String[] listFiles() { return file.list(); }
public String[] listFiles() { return file.list(); }
}
}
protected static class FileSearchZipItem implements FileSearchItem{
public class FileSearchZipItem implements FileSearchItem{ private String zipFile;
private String zipFile; private ZipEntry entry;
private ZipEntry entry; private String fileName;
private String fileName;
protected FileSearchZipItem(String file, ZipEntry entry){
protected FileSearchZipItem(String file, ZipEntry entry){ this.zipFile = file;
this.zipFile = file; this.entry = entry;
this.entry = entry; this.fileName = new File(entry.getName()).getName();
this.fileName = new File(entry.getName()).getName(); }
}
public String getName() { return fileName; }
public String getName() { return fileName; } public String getPath() { return "zip://"+zipFile+":"+entry.getName(); }
public String getPath() { return "zip://"+zipFile+":"+entry.getName(); }
public boolean isCompressed() { return true; }
public boolean isCompressed() { return true; } public boolean isFile() { return !entry.isDirectory(); }
public boolean isFile() { return !entry.isDirectory(); } public boolean isDirectory() { return entry.isDirectory(); }
public boolean isDirectory() { return entry.isDirectory(); }
public InputStream getInputStream() throws IOException {
public InputStream getInputStream() throws IOException { ZipFile zip = new ZipFile(zipFile);
ZipFile zip = new ZipFile(zipFile); return new InputStreamCloser(zip.getInputStream(entry), zip);
return new InputStreamCloser(zip.getInputStream(entry), zip); }
} public String[] listFiles() { return null; }
public String[] listFiles() { return null; }
}
}
} }

View file

@ -219,7 +219,7 @@ public class SSDPClient extends ThreadedUDPNetwork implements ThreadedUDPNetwork
service.setExpirationTime( service.setExpirationTime(
System.currentTimeMillis() + 1000 * getCacheTime(header.getHeader("Cache-Control"))); System.currentTimeMillis() + 1000 * getCacheTime(header.getHeader("Cache-Control")));
} }
service.setHeaders(header.getHeaders()); service.readHeaders(header);
if(listener != null && newService) if(listener != null && newService)
listener.newService(service); listener.newService(service);

5
src/zutil/net/ssdp/SSDPCustomInfo.java Normal file → Executable file
View file

@ -24,6 +24,7 @@
package zutil.net.ssdp; package zutil.net.ssdp;
import zutil.net.http.HttpHeaderParser;
import zutil.net.http.HttpPrintStream; import zutil.net.http.HttpPrintStream;
/** /**
@ -31,5 +32,7 @@ import zutil.net.http.HttpPrintStream;
*/ */
public interface SSDPCustomInfo extends SSDPServiceInfo{ public interface SSDPCustomInfo extends SSDPServiceInfo{
public void setHeaders(HttpPrintStream http); public void readHeaders(HttpHeaderParser http);
public void writeHeaders(HttpPrintStream http);
} }

View file

@ -194,7 +194,7 @@ public class SSDPServer extends ThreadedUDPNetwork implements ThreadedUDPNetwork
http.setHeader("EXT", "" ); http.setHeader("EXT", "" );
http.setHeader("Cache-Control", "max-age = "+ cache_time ); http.setHeader("Cache-Control", "max-age = "+ cache_time );
if(services.get(st) instanceof SSDPCustomInfo) if(services.get(st) instanceof SSDPCustomInfo)
((SSDPCustomInfo)services.get(st)).setHeaders(http); ((SSDPCustomInfo)services.get(st)).writeHeaders(http);
logger.log(Level.FINEST, "Sending Response: "+ http); logger.log(Level.FINEST, "Sending Response: "+ http);
http.flush(); http.flush();
@ -265,7 +265,7 @@ public class SSDPServer extends ThreadedUDPNetwork implements ThreadedUDPNetwork
http.setHeader("Cache-Control", "max-age = "+cache_time ); http.setHeader("Cache-Control", "max-age = "+cache_time );
http.setHeader("USN", service.getUSN() ); http.setHeader("USN", service.getUSN() );
if(service instanceof SSDPCustomInfo) if(service instanceof SSDPCustomInfo)
((SSDPCustomInfo) service).setHeaders(http); ((SSDPCustomInfo) service).writeHeaders(http);
logger.log(Level.FINEST, "Sending Notification: " + http); logger.log(Level.FINEST, "Sending Notification: " + http);
http.flush(); http.flush();

View file

@ -24,6 +24,7 @@
package zutil.net.ssdp; package zutil.net.ssdp;
import zutil.net.http.HttpHeaderParser;
import zutil.net.http.HttpPrintStream; import zutil.net.http.HttpPrintStream;
import java.io.IOException; import java.io.IOException;
@ -44,7 +45,7 @@ public class StandardSSDPInfo implements SSDPServiceInfo, SSDPCustomInfo{
private String usn; private String usn;
private long expiration_time; private long expiration_time;
// All header parameters // All header parameters
private HashMap<String, String> headers; private HashMap<String, String> headers = new HashMap<>();
private InetAddress inetAddress; private InetAddress inetAddress;
/** /**
@ -127,27 +128,28 @@ public class StandardSSDPInfo implements SSDPServiceInfo, SSDPCustomInfo{
return "USN: "+usn+"\nLocation: "+location+"\nST: "+st+"\nExpiration-Time: "+new Date(expiration_time); return "USN: "+usn+"\nLocation: "+location+"\nST: "+st+"\nExpiration-Time: "+new Date(expiration_time);
} }
public void setHeaders(HashMap<String, String> headers) {
this.headers = headers;
}
public void setHeader(String key, String value) {
headers.put(key, value);
}
public String getHeader(String header){ public String getHeader(String header){
return headers.get(header.toUpperCase()); return headers.get(header);
} }
@Override @Override
public void setHeaders(HttpPrintStream http) { public void writeHeaders(HttpPrintStream http) {
try { try {
if (headers != null) { for (String key : headers.keySet())
for (String key : headers.keySet()) { http.setHeader(key, headers.get(key));
http.setHeader(key, headers.get(key));
}
}
}catch(IOException e){ }catch(IOException e){
e.printStackTrace();
} }
} }
@Override
public void readHeaders(HttpHeaderParser http) {
HashMap<String,String> httpHeaders = http.getHeaders();
for (String key : httpHeaders.keySet())
headers.put(key, httpHeaders.get(key));
}
public InetAddress getInetAddress(){ public InetAddress getInetAddress(){
return inetAddress; return inetAddress;

6
src/zutil/plugin/PluginManager.java Normal file → Executable file
View file

@ -25,7 +25,7 @@
package zutil.plugin; package zutil.plugin;
import zutil.io.IOUtil; import zutil.io.IOUtil;
import zutil.io.file.FileSearch; import zutil.io.file.FileSearcher;
import zutil.log.LogUtil; import zutil.log.LogUtil;
import zutil.parser.DataNode; import zutil.parser.DataNode;
import zutil.parser.json.JSONParser; import zutil.parser.json.JSONParser;
@ -61,14 +61,14 @@ public class PluginManager<T> implements Iterable<PluginData>{
public PluginManager(String path){ public PluginManager(String path){
plugins = new HashMap<String, PluginData>(); plugins = new HashMap<String, PluginData>();
FileSearch search = new FileSearch(new File(path)); FileSearcher search = new FileSearcher(new File(path));
search.setRecursive(true); search.setRecursive(true);
search.searchFolders(false); search.searchFolders(false);
search.searchCompressedFiles(true); search.searchCompressedFiles(true);
search.setFileName("plugin.json"); search.setFileName("plugin.json");
log.fine("Searching for plugins..."); log.fine("Searching for plugins...");
for(FileSearch.FileSearchItem file : search){ for(FileSearcher.FileSearchItem file : search){
try { try {
DataNode node = JSONParser.read(IOUtil.getContentString(file.getInputStream())); DataNode node = JSONParser.read(IOUtil.getContentString(file.getInputStream()));
log.fine("Found plugin: "+file.getPath()); log.fine("Found plugin: "+file.getPath());

7
test/zutil/test/SSDPServerTest.java Normal file → Executable file
View file

@ -42,10 +42,9 @@ public class SSDPServerTest {
StandardSSDPInfo service = new StandardSSDPInfo(); StandardSSDPInfo service = new StandardSSDPInfo();
service.setLocation("nowhere"); service.setLocation("nowhere");
service.setST("zep:discover"); service.setST("zep:discover");
HashMap<String, String> headers = new HashMap<String, String>(); service.setHeader("Alias", "Desktop");
headers.put("Alias", "Desktop"); service.setHeader("PublicKey", "SuperDesktopKey");
headers.put("PublicKey", "SuperDesktopKey");
service.setHeaders(headers);
SSDPServer ssdp = new SSDPServer(); SSDPServer ssdp = new SSDPServer();
ssdp.addService(service); ssdp.addService(service);