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
*/
public static Class<?>[] getGenericClasses(Class<?> c, Class<?> superClass){
// Search for the super class
while (c.getSuperclass() != Object.class && !superClass.isAssignableFrom(c.getSuperclass()))
c = c.getSuperclass();
// Did we find the super class?
if (superClass.isAssignableFrom(c.getSuperclass()))
return getGenericClasses(c.getGenericSuperclass());
if(superClass != null) {
// Search for the super class
while (c.getSuperclass() != null && c.getSuperclass() != Object.class) {
// Did we find the super class?
if (superClass.isAssignableFrom(c.getSuperclass()))
return getGenericClasses(c.getGenericSuperclass());
c = c.getSuperclass();
}
}
return new Class[0];
}
private static Class<?>[] getGenericClasses(Type genericType){
@ -118,7 +120,8 @@ public class ClassUtil {
Type[] argTypes = aType.getActualTypeArguments();
Class<?>[] classArray = new Class<?>[argTypes.length];
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;
}

View file

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

View file

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

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

@ -24,6 +24,7 @@
package zutil.net.ssdp;
import zutil.net.http.HttpHeaderParser;
import zutil.net.http.HttpPrintStream;
/**
@ -31,5 +32,7 @@ import zutil.net.http.HttpPrintStream;
*/
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("Cache-Control", "max-age = "+ cache_time );
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);
http.flush();
@ -265,7 +265,7 @@ public class SSDPServer extends ThreadedUDPNetwork implements ThreadedUDPNetwork
http.setHeader("Cache-Control", "max-age = "+cache_time );
http.setHeader("USN", service.getUSN() );
if(service instanceof SSDPCustomInfo)
((SSDPCustomInfo) service).setHeaders(http);
((SSDPCustomInfo) service).writeHeaders(http);
logger.log(Level.FINEST, "Sending Notification: " + http);
http.flush();

View file

@ -24,6 +24,7 @@
package zutil.net.ssdp;
import zutil.net.http.HttpHeaderParser;
import zutil.net.http.HttpPrintStream;
import java.io.IOException;
@ -44,7 +45,7 @@ public class StandardSSDPInfo implements SSDPServiceInfo, SSDPCustomInfo{
private String usn;
private long expiration_time;
// All header parameters
private HashMap<String, String> headers;
private HashMap<String, String> headers = new HashMap<>();
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);
}
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){
return headers.get(header.toUpperCase());
return headers.get(header);
}
@Override
public void setHeaders(HttpPrintStream http) {
public void writeHeaders(HttpPrintStream http) {
try {
if (headers != null) {
for (String key : headers.keySet()) {
http.setHeader(key, headers.get(key));
}
}
for (String key : headers.keySet())
http.setHeader(key, headers.get(key));
}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(){
return inetAddress;

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

@ -25,7 +25,7 @@
package zutil.plugin;
import zutil.io.IOUtil;
import zutil.io.file.FileSearch;
import zutil.io.file.FileSearcher;
import zutil.log.LogUtil;
import zutil.parser.DataNode;
import zutil.parser.json.JSONParser;
@ -61,14 +61,14 @@ public class PluginManager<T> implements Iterable<PluginData>{
public PluginManager(String path){
plugins = new HashMap<String, PluginData>();
FileSearch search = new FileSearch(new File(path));
FileSearcher search = new FileSearcher(new File(path));
search.setRecursive(true);
search.searchFolders(false);
search.searchCompressedFiles(true);
search.setFileName("plugin.json");
log.fine("Searching for plugins...");
for(FileSearch.FileSearchItem file : search){
for(FileSearcher.FileSearchItem file : search){
try {
DataNode node = JSONParser.read(IOUtil.getContentString(file.getInputStream()));
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();
service.setLocation("nowhere");
service.setST("zep:discover");
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Alias", "Desktop");
headers.put("PublicKey", "SuperDesktopKey");
service.setHeaders(headers);
service.setHeader("Alias", "Desktop");
service.setHeader("PublicKey", "SuperDesktopKey");
SSDPServer ssdp = new SSDPServer();
ssdp.addService(service);