Update of /cvsroot/metamorphosis/ruper2/src/java/core/org/krysalis/ruper2/util/io
In directory sc8-pr-cvs1:/tmp/cvs-serv30481/src/java/core/org/krysalis/ruper2/util/io
Added Files:
FileUtils.java VfsUtils.java ResolvedFile.java
Log Message:
Avoid clash with existing Ruper...
--- NEW FILE: FileUtils.java ---
package org.krysalis.ruper2.util.io;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
public class FileUtils {
// for toURI
private static boolean[] isSpecial = new boolean[256];
private static char[] escapedChar1 = new char[256];
private static char[] escapedChar2 = new char[256];
// stolen from FilePathToURI of the Xerces-J team
static {
for (int i = 0; i <= 0x20; i++) {
isSpecial[i] = true;
escapedChar1[i] = Character.forDigit(i >> 4, 16);
escapedChar2[i] = Character.forDigit(i & 0xf, 16);
}
isSpecial[0x7f] = true;
escapedChar1[0x7f] = '7';
escapedChar2[0x7f] = 'F';
char[] escChs = {'<', '>', '#', '%', '"', '{', '}',
'|', '\\', '^', '~', '[', ']', '`'};
int len = escChs.length;
char ch;
for (int i = 0; i < len; i++) {
ch = escChs[i];
isSpecial[ch] = true;
escapedChar1[ch] = Character.forDigit(ch >> 4, 16);
escapedChar2[ch] = Character.forDigit(ch & 0xf, 16);
}
}
/**
* Get the URL for a file taking into account # characters
*
* @param file the file whose URL representation is required.
* @return The FileURL value
* @throws MalformedURLException if the URL representation cannot be
* formed.
*/
public static URL getFileURL(File file) throws MalformedURLException {
return new URL(toURI(file.getAbsolutePath()));
}
public static String toURI(String path) {
boolean isDir = (new File(path)).isDirectory();
StringBuffer sb = new StringBuffer("file:");
sb.append("//");
// add an extra slash for filesystems with drive-specifiers
if (!path.startsWith(File.separator)) {
sb.append("/");
}
path = path.replace('\\', '/');
CharacterIterator iter = new StringCharacterIterator(path);
for (char c = iter.first(); c != CharacterIterator.DONE;
c = iter.next()) {
if (isSpecial[c]) {
sb.append('%');
sb.append(escapedChar1[c]);
sb.append(escapedChar2[c]);
} else {
sb.append(c);
}
}
if (isDir && !path.endsWith("/")) {
sb.append('/');
}
return sb.toString();
}
}
--- NEW FILE: VfsUtils.java ---
/*
The Krysalis Patchy Software License, Version 1.1_01
Copyright (c) 2002-2003 Nicola Ken Barozzi. All rights reserved.
This Licence is compatible with the BSD licence as described and
approved by http://www.opensource.org/, and is based on the
Apache Software Licence Version 1.1.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
3. The end-user documentation included with the redistribution,
if any, must include the following acknowledgment:
"This product includes software developed for project
Krysalis (http://www.krysalis.org/)."
Alternately, this acknowledgment may appear in the software itself,
if and wherever such third-party acknowledgments normally appear.
4. The names "Krysalis" and "Nicola Ken Barozzi" and
"Krysalis Centipede" must not be used to endorse or promote products
derived from this software without prior written permission. For
written permission, please contact [email protected].
5. Products derived from this software may not be called "Krysalis",
"Krysalis Centipede", nor may "Krysalis" appear in their name, without
prior written permission of Nicola Ken Barozzi.
6. This software may contain voluntary contributions made by many
individuals, who decided to donate the code to this project in respect
of this licence.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
====================================================================
*/
package org.krysalis.ruper2.util.io;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.vfs.AllFileSelector;
import org.apache.commons.vfs.Capability;
import org.apache.commons.vfs.FileObject;
import org.apache.commons.vfs.FileSelector;
import org.apache.commons.vfs.FileSystem;
import org.apache.commons.vfs.FileSystemException;
import org.apache.commons.vfs.FileSystemManager;
import org.apache.commons.vfs.FileType;
import org.apache.commons.vfs.impl.DefaultFileSystemManager;
import org.apache.commons.vfs.impl.StandardFileSystemManager;
/**
* @author ajack
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
/**
*
* @author $Author: arb_jack $
* @version $Revision: 1.1 $
*
*/
public class VfsUtils {
private static FileSystemManager l_defaultFsm = null;
private static FileSelector l_defaultAllFileSelector = null;
static {
l_defaultAllFileSelector = new AllFileSelector();
}
public static FileSystemManager createFSM(String name, String base)
throws FileSystemException {
DefaultFileSystemManager fsm = new StandardFileSystemManager();
fsm.setLogger(LogFactory.getLog(name));
fsm.init();
// Set Base Directory for Resolving Relative To...
fsm.setBaseFile(new java.io.File(base));
return fsm;
}
/**
* Create the Default FSM (if it does not exist)
* @return
* @throws FileSystemException
*/
private static FileSystemManager createDefaultFSM()
throws FileSystemException {
if (null == l_defaultFsm) {
l_defaultFsm = createFSM("Ruper::FileSystemManager", ".");
}
return l_defaultFsm;
}
/**
* Get (or create) the Default FSM
* @return
* @throws FileSystemException
*/
public static FileSystemManager getDefaultFSM()
throws FileSystemException {
if (l_defaultFsm == null) {
createDefaultFSM();
}
return l_defaultFsm;
}
/**
*
* Resolve a URL within the scope of this FSM
* @param url
* @return
* @throws Exception
*/
public static FileObject resolveUrl(String url) throws Exception {
return getDefaultFSM().resolveFile(url);
}
/**
*
* Convert a File to a FileObject within the scope of this FSM
* @param file
* @return
* @throws Exception
*/
public static FileObject toFileObject(File file) throws Exception {
return getDefaultFSM().toFileObject(file);
}
public static List getChildren(FileObject folder)
throws IOException, MalformedURLException, FileSystemException {
List result = new ArrayList();
if (folder.getFileSystem().hasCapability(Capability.LIST_CHILDREN)) {
if (folder.getType() == FileType.FILE) {
result.add(folder);
}
else {
FileObject array[] = folder.getChildren();
for (int i = 0; i < array.length; ++i)
result.add(array[i]);
}
}
else if ("http".equals(folder.getURL().getProtocol())) {
ArrayList list = new ArrayList();
InputStream urlStream = null;
// try opening the URL
urlStream = folder.getContent().getInputStream();
if (null != urlStream) {
String type =
URLConnection.guessContentTypeFromStream(urlStream);
if ((type == null) || (type.compareTo("text/html") != 0)) {
result.add(folder);
}
else {
// search the input stream for links
// first, read in the entire URL
byte b[] = new byte[1000];
int numRead = urlStream.read(b);
String content = new String(b, 0, numRead);
while (numRead != -1) {
numRead = urlStream.read(b);
if (numRead != -1) {
String newContent = new String(b, 0, numRead);
content += newContent;
}
}
urlStream.close();
String lowerCaseContent = content.toLowerCase();
int index = 0;
while ((index = lowerCaseContent.indexOf("<a", index))
!= -1) {
if ((index = lowerCaseContent.indexOf("href", index))
== -1) {
break;
}
if ((index = lowerCaseContent.indexOf("=", index))
== -1) {
break;
}
index++;
String remaining = content.substring(index);
StringTokenizer st =
new StringTokenizer(remaining, "\t\n\r\">#");
String strLink = st.nextToken();
if ((strLink.length() > 0)
&& (strLink.indexOf("?") == -1)) {
boolean added = false;
FileObject f = folder.resolveFile(strLink);
//
// Check not ".."
//
if (!f.equals(folder.getParent())) {
//
// Check that the parent of the child is this
//
if (f.getParent().equals(folder)) {
//
// Store another child, no dups...
//
if (!list.contains(f)) {
list.add(f);
added = true;
}
}
}
}
}
result = list;
}
}
}
return result;
}
/**
*
* Unarchive a file (if we can, i.e. JAR or ZIP)using default FSM
*
* @param input
* @return
* @throws FileSystemException
*/
public static FileObject unarchive(FileObject input)
throws FileSystemException {
return unarchive(getDefaultFSM(), input);
}
/**
*
* Unarchive a file (if we can, i.e. JAR or ZIP) using a specified FSM
*
* NOTE: This only returns a referece to the contents, one has to copy
* it to another location to get a real unarchive.
*
* @param input
* @return
* @throws FileSystemException
*/
public static FileObject unarchive(FileSystemManager fsm, FileObject input)
throws FileSystemException {
FileObject temp = null;
FileObject output = null;
String basename = input.getName().getBaseName();
if (FileType.FOLDER != input.getType()) {
if (basename.endsWith(".jar")) {
basename = basename.substring(0, basename.length() - 4);
temp = fsm.createFileSystem("jar", input);
output = temp.resolveFile(basename);
}
else if (basename.endsWith(".zip")) {
basename = basename.substring(0, basename.length() - 4);
temp = fsm.createFileSystem("zip", input);
output = temp.resolveFile(basename);
}
}
/*
* NOTE: This only returns a referece to the contents, one has to copy
* it to another location to get a real unarchive.
*/
if (null == output)
output = input;
return output;
}
/**
*
* Copy to destination from origin, and select all files.
*
* @param destination
* @param origin
* @throws FileSystemException
*/
public static void copyFrom(FileObject destination, FileObject origin)
throws FileSystemException {
VfsUtils.copyFrom(destination, origin, l_defaultAllFileSelector);
}
/**
*
* Copy to destination from origin, and select which files.
*
* @param destination
* @param origin
* @param selector
* @throws FileSystemException
*/
public static void copyFrom(
FileObject destination,
FileObject origin,
FileSelector selector)
throws FileSystemException {
destination.copyFrom(origin, selector);
}
public static void delete(FileObject deletee) throws FileSystemException {
deletee.delete(l_defaultAllFileSelector);
}
//
// :TODO: not working -- gies some odd file names when a file comes from a jar
//
public static File toFile(FileObject fileObject)
throws FileSystemException {
File resultFile = null;
if (null != fileObject) {
FileSystem fileSystem = fileObject.getFileSystem();
resultFile =
fileSystem.replicateFile(fileObject, l_defaultAllFileSelector);
//RuperLogger.g_log.warn("toFile: " + resultFile);
}
return resultFile;
}
public static void main(String args[]) throws Exception {
String url = "http://metamorphosis.krysalis.org/version/samples/";
if (0 < args.length)
url = args[0];
FileSystemManager fsm = VfsUtils.getDefaultFSM();
FileObject folder = fsm.resolveFile(url);
//if ( !folder.exists() )
// System.out.println("Bad Folder : " + folder);
List kids = VfsUtils.getChildren(folder);
for (Iterator i = kids.iterator(); i.hasNext();) {
FileObject kid = (FileObject) i.next();
System.out.println("Child [" + i + "] -> " + kid);
}
}
}
--- NEW FILE: ResolvedFile.java ---
/*
* Created on Sep 9, 2003
*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
package org.krysalis.ruper2.util.io;
import java.io.File;
import org.krysalis.version.util.SystemUtils;
/**
* @author ajack
*/
public class ResolvedFile extends File {
private Object m_originalInput = null;
private Object m_resolverContext = null;
private ResolvedFile(
Object resolveContext,
Object originalInput,
File file) {
super(file.getAbsolutePath());
}
public static File resolve(Object file) {
return resolve(SystemUtils.getCWD(), file);
}
public static File resolve(Object m_resolverContext, Object file) {
// Previously resolved within this context...
if ((file instanceof ResolvedFile)
&& (((ResolvedFile) file)
.m_resolverContext
.equals(m_resolverContext)))
return (File) file;
// Extract a 'path' (local or absolute) from this thing
String path = null;
if (file instanceof File)
path = ((File) file).getPath();
else if (file instanceof String)
path = (String) file;
else {
throw new IllegalArgumentException(
"Unable to resolve " + file.getClass().getName());
}
File pathFile = new File(path);
// Get a fully qualified file
File fullyQualified = null;
if (pathFile.isAbsolute()) {
fullyQualified = pathFile;
}
else {
if (m_resolverContext instanceof File)
fullyQualified = new File((File) m_resolverContext, path);
else if (m_resolverContext instanceof String)
fullyQualified =
new File(new File((String) m_resolverContext), path);
else {
throw new IllegalArgumentException(
"Unable to resolve using context "
+ m_resolverContext.getClass().getName());
}
}
return new ResolvedFile(m_resolverContext, file, fullyQualified);
}
public static void main(String args[]) {
String file = "lib/test.jar";
if (args.length > 0)
file = args[0];
File rf1 = ResolvedFile.resolve(file);
File rf2 =
ResolvedFile.resolve(SystemUtils.getCWD().getAbsolutePath(), file);
File rf3 = ResolvedFile.resolve(SystemUtils.getCWD().getAbsolutePath());
System.out.println("RF1:" + rf1.toString());
System.out.println("RF1:" + rf1.getAbsolutePath());
System.out.println("RF2:" + rf2.toString());
System.out.println("RF2:" + rf2.getAbsolutePath());
System.out.println("RF3:" + rf3.toString());
System.out.println("RF3:" + rf3.getAbsolutePath());
}
}
-------------------------------------------------------
This sf.net email is sponsored by:ThinkGeek
Welcome to geek heaven.
http://thinkgeek.com/sf
lmpx.com only provides a reader for public news (NNTP) servers. It is not
affiliated with the servers or forums shown here and is not responsible for
the content of articles, which is written by their respective authors.